etc/NEWS: clarify entry for proced-renice
[bpt/emacs.git] / lisp / textmodes / rst.el
... / ...
CommitLineData
1;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
2
3;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
4
5;; Maintainer: Stefan Merten <smerten@oekonux.de>
6;; Author: Stefan Merten <smerten@oekonux.de>,
7;; Martin Blais <blais@furius.ca>,
8;; David Goodger <goodger@python.org>,
9;; Wei-Wei Guo <wwguocn@gmail.com>
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software: you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
15;; the Free Software Foundation, either version 3 of the License, or
16;; (at your option) any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
24;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26;;; Commentary:
27
28;; This package provides major mode rst-mode, which supports documents marked
29;; up using the reStructuredText format. Support includes font locking as well
30;; as a lot of convenience functions for editing. It does this by defining a
31;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode.
32;; This package also contains:
33;;
34;; - Functions to automatically adjust and cycle the section underline
35;; adornments;
36;; - A mode that displays the table of contents and allows you to jump anywhere
37;; from it;
38;; - Functions to insert and automatically update a TOC in your source
39;; document;
40;; - Function to insert list, processing item bullets and enumerations
41;; automatically;
42;; - Font-lock highlighting of most reStructuredText structures;
43;; - Indentation and filling according to reStructuredText syntax;
44;; - Cursor movement according to reStructuredText syntax;
45;; - Some other convenience functions.
46;;
47;; See the accompanying document in the docutils documentation about
48;; the contents of this package and how to use it.
49;;
50;; For more information about reStructuredText, see
51;; http://docutils.sourceforge.net/rst.html
52;;
53;; For full details on how to use the contents of this file, see
54;; http://docutils.sourceforge.net/docs/user/emacs.html
55;;
56;;
57;; There are a number of convenient key bindings provided by rst-mode.
58;; For more on bindings, see rst-mode-map below. There are also many variables
59;; that can be customized, look for defcustom in this file.
60;;
61;; If you use the table-of-contents feature, you may want to add a hook to
62;; update the TOC automatically every time you adjust a section title::
63;;
64;; (add-hook 'rst-adjust-hook 'rst-toc-update)
65;;
66;; Syntax highlighting: font-lock is enabled by default. If you want to turn
67;; off syntax highlighting to rst-mode, you can use the following::
68;;
69;; (setq font-lock-global-modes '(not rst-mode ...))
70;;
71;;
72;;
73;; Customization is done by customizable variables contained in customization
74;; group "rst" and subgroups. Group "rst" is contained in the "wp" group.
75;;
76
77;;; DOWNLOAD
78
79;; The latest release of this file lies in the docutils source code repository:
80;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el
81
82;;; INSTALLATION
83
84;; Add the following lines to your init file:
85;;
86;; (require 'rst)
87;;
88;; If you are using `.txt' as a standard extension for reST files as
89;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
90;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
91;; provides to set the major mode automatically. For instance you may use::
92;;
93;; .. -*- mode: rst -*-
94;;
95;; in the very first line of your file. The following code is useful if you
96;; want automatically enter rst-mode from any file with compatible extensions:
97;;
98;; (setq auto-mode-alist
99;; (append '(("\\.txt\\'" . rst-mode)
100;; ("\\.rst\\'" . rst-mode)
101;; ("\\.rest\\'" . rst-mode)) auto-mode-alist))
102;;
103
104;;; Code:
105
106;; FIXME: Check through major mode conventions again.
107
108;; FIXME: Add proper ";;;###autoload" comments.
109
110;; FIXME: When 24.1 is common place remove use of `lexical-let' and put "-*-
111;; lexical-binding: t -*-" in the first line.
112
113;; FIXME: Use `testcover'.
114
115;; FIXME: The adornment classification often called `ado' should be a
116;; `defstruct'.
117
118;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
119;; Support for `testcover'
120
121(when (boundp 'testcover-1value-functions)
122 ;; Below `lambda' is used in a loop with varying parameters and is thus not
123 ;; 1valued.
124 (setq testcover-1value-functions
125 (delq 'lambda testcover-1value-functions))
126 (add-to-list 'testcover-compose-functions 'lambda))
127
128(defun rst-testcover-defcustom ()
129 "Remove all customized variables from `testcover-module-constants'.
130This seems to be a bug in `testcover': `defcustom' variables are
131considered constants. Revert it with this function after each `defcustom'."
132 (when (boundp 'testcover-module-constants)
133 (setq testcover-module-constants
134 (delq nil
135 (mapcar
136 (lambda (sym)
137 (if (not (plist-member (symbol-plist sym) 'standard-value))
138 sym))
139 testcover-module-constants)))))
140
141(defun rst-testcover-add-compose (fun)
142 "Add FUN to `testcover-compose-functions'."
143 (when (boundp 'testcover-compose-functions)
144 (add-to-list 'testcover-compose-functions fun)))
145
146(defun rst-testcover-add-1value (fun)
147 "Add FUN to `testcover-1value-functions'."
148 (when (boundp 'testcover-1value-functions)
149 (add-to-list 'testcover-1value-functions fun)))
150
151;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
152;; Common Lisp stuff
153
154;; Only use of macros is allowed - may be replaced by `cl-lib' some time.
155(eval-when-compile
156 (require 'cl))
157
158;; Redefine some functions from `cl.el' in a proper namespace until they may be
159;; used from there.
160
161(defun rst-signum (x)
162 "Return 1 if X is positive, -1 if negative, 0 if zero."
163 (cond
164 ((> x 0) 1)
165 ((< x 0) -1)
166 (t 0)))
167
168(defun rst-some (seq &optional pred)
169 "Return non-nil if any element of SEQ yields non-nil when PRED is applied.
170Apply PRED to each element of list SEQ until the first non-nil
171result is yielded and return this result. PRED defaults to
172`identity'."
173 (unless pred
174 (setq pred 'identity))
175 (catch 'rst-some
176 (dolist (elem seq)
177 (let ((r (funcall pred elem)))
178 (when r
179 (throw 'rst-some r))))))
180
181(defun rst-position-if (pred seq)
182 "Return position of first element satisfying PRED in list SEQ or nil."
183 (catch 'rst-position-if
184 (let ((i 0))
185 (dolist (elem seq)
186 (when (funcall pred elem)
187 (throw 'rst-position-if i))
188 (incf i)))))
189
190(defun rst-position (elem seq)
191 "Return position of ELEM in list SEQ or nil.
192Comparison done with `equal'."
193 ;; Create a closure containing `elem' so the `lambda' always sees our
194 ;; parameter instead of an `elem' which may be in dynamic scope at the time
195 ;; of execution of the `lambda'.
196 (lexical-let ((elem elem))
197 (rst-position-if (function (lambda (e)
198 (equal elem e)))
199 seq)))
200
201;; FIXME: Embed complicated `defconst's in `eval-when-compile'.
202
203;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
204;; Versions
205
206;; testcover: ok.
207(defun rst-extract-version (delim-re head-re re tail-re var &optional default)
208 "Extract the version from a variable according to the given regexes.
209Return the version after regex DELIM-RE and HEAD-RE matching RE
210and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match."
211 (if (string-match
212 (concat delim-re head-re "\\(" re "\\)" tail-re delim-re)
213 var)
214 (match-string 1 var)
215 default))
216
217;; Use CVSHeader to really get information from CVS and not other version
218;; control systems.
219(defconst rst-cvs-header
220 "$CVSHeader: sm/rst_el/rst.el,v 1.327.2.1 2012-09-22 09:06:56 stefan Exp $")
221(defconst rst-cvs-rev
222 (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
223 " .*" rst-cvs-header "0.0")
224 "The CVS revision of this file. CVS revision is the development revision.")
225(defconst rst-cvs-timestamp
226 (rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
227 "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
228 rst-cvs-header "1970-01-01 00:00:00")
229 "The CVS time stamp of this file.")
230
231;; Use LastChanged... to really get information from SVN.
232(defconst rst-svn-rev
233 (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
234 "$LastChangedRevision: 7515 $")
235 "The SVN revision of this file.
236SVN revision is the upstream (docutils) revision.")
237(defconst rst-svn-timestamp
238 (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " "
239 "$LastChangedDate: 2012-09-20 23:28:53 +0200 (Thu, 20 Sep 2012) $")
240 "The SVN time stamp of this file.")
241
242;; Maintained by the release process.
243(defconst rst-official-version
244 (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
245 "%OfficialVersion: 1.4.0 %")
246 "Official version of the package.")
247(defconst rst-official-cvs-rev
248 (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
249 "$Revision: 1.327.2.1 $")
250 "CVS revision of this file in the official version.")
251
252(defconst rst-version
253 (if (equal rst-official-cvs-rev rst-cvs-rev)
254 rst-official-version
255 (format "%s (development %s [%s])" rst-official-version
256 rst-cvs-rev rst-cvs-timestamp))
257 "The version string.
258Starts with the current official version. For developer versions
259in parentheses follows the development revision and the time stamp.")
260
261(defconst rst-package-emacs-version-alist
262 '(("1.0.0" . "24.3")
263 ("1.1.0" . "24.3")
264 ("1.2.0" . "24.3")
265 ("1.2.1" . "24.3")
266 ("1.3.0" . "24.3")
267 ("1.3.1" . "24.3")
268 ("1.4.0" . "24.3")
269 ))
270
271(unless (assoc rst-official-version rst-package-emacs-version-alist)
272 (error "Version %s not listed in `rst-package-emacs-version-alist'"
273 rst-version))
274
275(add-to-list 'customize-package-emacs-version-alist
276 (cons 'ReST rst-package-emacs-version-alist))
277
278;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
279;; Initialize customization
280
281\f
282(defgroup rst nil "Support for reStructuredText documents."
283 :group 'wp
284 :version "23.1"
285 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
286
287\f
288;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
289;; Facilities for regular expressions used everywhere
290
291;; The trailing numbers in the names give the number of referenceable regex
292;; groups contained in the regex.
293
294;; Used to be customizable but really is not customizable but fixed by the reST
295;; syntax.
296(defconst rst-bullets
297 ;; Sorted so they can form a character class when concatenated.
298 '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043)
299 "List of all possible bullet characters for bulleted lists.")
300
301(defconst rst-uri-schemes
302 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
303 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
304 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
305 "Supported URI schemes.")
306
307(defconst rst-adornment-chars
308 ;; Sorted so they can form a character class when concatenated.
309 '(?\]
310 ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
311 ?^ ?_ ?` ?{ ?| ?} ?~
312 ?-)
313 "Characters which may be used in adornments for sections and transitions.")
314
315(defconst rst-max-inline-length
316 1000
317 "Maximum length of inline markup to recognize.")
318
319(defconst rst-re-alist-def
320 ;; `*-beg' matches * at the beginning of a line.
321 ;; `*-end' matches * at the end of a line.
322 ;; `*-prt' matches a part of *.
323 ;; `*-tag' matches *.
324 ;; `*-sta' matches the start of * which may be followed by respective content.
325 ;; `*-pfx' matches the delimiter left of *.
326 ;; `*-sfx' matches the delimiter right of *.
327 ;; `*-hlp' helper for *.
328 ;;
329 ;; A trailing number says how many referenceable groups are contained.
330 `(
331
332 ;; Horizontal white space (`hws')
333 (hws-prt "[\t ]")
334 (hws-tag hws-prt "*") ; Optional sequence of horizontal white space.
335 (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space.
336
337 ;; Lines (`lin')
338 (lin-beg "^" hws-tag) ; Beginning of a possibly indented line.
339 (lin-end hws-tag "$") ; End of a line with optional trailing white space.
340 (linemp-tag "^" hws-tag "$") ; Empty line with optional white space.
341
342 ;; Various tags and parts
343 (ell-tag "\\.\\.\\.") ; Ellipsis
344 (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet.
345 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag.
346 (num-prt "[0-9]") ; A number enumerator part.
347 (num-tag num-prt "+") ; A number enumerator tag.
348 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part.
349 (rom-tag rom-prt "+") ; A roman enumerator tag.
350 (aut-tag "#") ; An automatic enumerator tag.
351 (dcl-tag "::") ; Double colon.
352
353 ;; Block lead in (`bli')
354 (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
355 ; immediate content.
356
357 ;; Various starts
358 (bul-sta bul-tag bli-sfx) ; Start of a bulleted item.
359
360 ;; Explicit markup tag (`exm')
361 (exm-tag "\\.\\.")
362 (exm-sta exm-tag hws-sta)
363 (exm-beg lin-beg exm-sta)
364
365 ;; Counters in enumerations (`cnt')
366 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter.
367 (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter.
368
369 ;; Enumerator (`enm')
370 (enmany-tag (:alt
371 (:seq cntany-tag "\\.")
372 (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator.
373 (enmexp-tag (:alt
374 (:seq cntexp-tag "\\.")
375 (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
376 ; enumerator.
377 (enmaut-tag (:alt
378 (:seq aut-tag "\\.")
379 (:seq "(?" aut-tag ")"))) ; An automatic enumerator.
380 (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start.
381 (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start.
382 (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
383 ; at the beginning of a line.
384
385 ;; Items may be enumerated or bulleted (`itm')
386 (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag.
387 (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
388 ; is the item tag.
389 (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
390 ; beginning of a line, group is the
391 ; item tag.
392
393 ;; Inline markup (`ilm')
394 (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
395 (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
396
397 ;; Inline markup content (`ilc')
398 (ilcsgl-tag "\\S ") ; A single non-white character.
399 (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content.
400 (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content.
401 (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
402 ; definition.
403 (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content.
404 (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
405 ; definition.
406 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content.
407 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content.
408 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content.
409 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count.
410 (ilcast-tag (:alt ilcsgl-tag
411 (:seq ilcsgl-tag
412 ilcast-prt ilcrep-hlp
413 ilcast-sfx))) ; Non-asterisk content.
414 (ilcbkq-tag (:alt ilcsgl-tag
415 (:seq ilcsgl-tag
416 ilcbkq-prt ilcrep-hlp
417 ilcbkq-sfx))) ; Non-backquote content.
418 (ilcbkqdef-tag (:alt ilcsgl-tag
419 (:seq ilcsgl-tag
420 ilcbkqdef-prt ilcrep-hlp
421 ilcbkq-sfx))) ; Non-backquote definition.
422 (ilcbar-tag (:alt ilcsgl-tag
423 (:seq ilcsgl-tag
424 ilcbar-prt ilcrep-hlp
425 ilcbar-sfx))) ; Non-vertical-bar content.
426 (ilcbardef-tag (:alt ilcsgl-tag
427 (:seq ilcsgl-tag
428 ilcbardef-prt ilcrep-hlp
429 ilcbar-sfx))) ; Non-vertical-bar definition.
430
431 ;; Fields (`fld')
432 (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name.
433 (fldnam-tag fldnam-prt "+") ; A field name.
434 (fld-tag ":" fldnam-tag ":") ; A field marker.
435
436 ;; Options (`opt')
437 (optsta-tag (:alt "[-+/]" "--")) ; Start of an option.
438 (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option.
439 (optarg-tag (:shy "[ =]\\S +")) ; Option argument.
440 (optsep-tag (:shy "," hws-prt)) ; Separator between options.
441 (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option.
442
443 ;; Footnotes and citations (`fnc')
444 (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name.
445 (fncnam-tag fncnam-prt "+") ; A footnote or citation name.
446 (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag.
447 (fncdef-tag-2 (:grp exm-sta)
448 (:grp fnc-tag)) ; A complete footnote or citation definition
449 ; tag. First group is the explicit markup
450 ; start, second group is the footnote /
451 ; citation tag.
452 (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation
453 ; definition. First group is the explicit
454 ; markup start, second group is the
455 ; footnote / citation tag.
456
457 ;; Substitutions (`sub')
458 (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag.
459 (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
460 ; tag.
461
462 ;; Symbol (`sym')
463 (sym-prt "[-+.:_]") ; Non-word part of a symbol.
464 (sym-tag (:shy "\\sw+" (:shy sym-prt "\\sw+") "*"))
465
466 ;; URIs (`uri')
467 (uri-tag (:alt ,@rst-uri-schemes))
468
469 ;; Adornment (`ado')
470 (ado-prt "[" ,(concat rst-adornment-chars) "]")
471 (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
472 ; otherwise explicit markup start would be
473 ; recognized.
474 (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
475 ; characters is matched differently.
476 (ado-tag-1-1 (:grp ado-prt)
477 "\\1" adorep2-hlp) ; A complete adornment, group is the first
478 ; adornment character and MUST be the FIRST
479 ; group in the whole expression.
480 (ado-tag-1-2 (:grp ado-prt)
481 "\\2" adorep2-hlp) ; A complete adornment, group is the first
482 ; adornment character and MUST be the
483 ; SECOND group in the whole expression.
484 (ado-beg-2-1 "^" (:grp ado-tag-1-2)
485 lin-end) ; A complete adornment line; first group is the whole
486 ; adornment and MUST be the FIRST group in the whole
487 ; expression; second group is the first adornment
488 ; character.
489
490 ;; Titles (`ttl')
491 (ttl-tag "\\S *\\w\\S *") ; A title text.
492 (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line.
493
494 ;; Directives and substitution definitions (`dir')
495 (dir-tag-3 (:grp exm-sta)
496 (:grp (:shy subdef-tag hws-sta) "?")
497 (:grp sym-tag dcl-tag)) ; A directive or substitution definition
498 ; tag. First group is explicit markup
499 ; start, second group is a possibly
500 ; empty substitution tag, third group is
501 ; the directive tag including the double
502 ; colon.
503 (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution
504 ; definition. Groups are as in dir-tag-3.
505
506 ;; Literal block (`lit')
507 (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
508 (:grp dcl-tag) "$") ; Start of a literal block. First group is
509 ; any text before the double colon tag which
510 ; may not exist, second group is the double
511 ; colon tag.
512
513 ;; Comments (`cmt')
514 (cmt-sta-1 (:grp exm-sta) "[^\[|_\n]"
515 (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$")))
516 "*$") ; Start of a comment block; first group is explicit markup
517 ; start.
518
519 ;; Paragraphs (`par')
520 (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag)
521 ) ; Tag at the beginning of a paragraph; there may be groups in
522 ; certain cases.
523 )
524 "Definition alist of relevant regexes.
525Each entry consists of the symbol naming the regex and an
526argument list for `rst-re'.")
527
528(defvar rst-re-alist) ; Forward declare to use it in `rst-re'.
529
530;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel.
531(rst-testcover-add-compose 'rst-re)
532;; testcover: ok.
533(defun rst-re (&rest args)
534 "Interpret ARGS as regular expressions and return a regex string.
535Each element of ARGS may be one of the following:
536
537A string which is inserted unchanged.
538
539A character which is resolved to a quoted regex.
540
541A symbol which is resolved to a string using `rst-re-alist-def'.
542
543A list with a keyword in the car. Each element of the cdr of such
544a list is recursively interpreted as ARGS. The results of this
545interpretation are concatenated according to the keyword.
546
547For the keyword `:seq' the results are simply concatenated.
548
549For the keyword `:shy' the results are concatenated and
550surrounded by a shy-group (\"\\(?:...\\)\").
551
552For the keyword `:alt' the results form an alternative (\"\\|\")
553which is shy-grouped (\"\\(?:...\\)\").
554
555For the keyword `:grp' the results are concatenated and form a
556referenceable group (\"\\(...\\)\").
557
558After interpretation of ARGS the results are concatenated as for
559`:seq'."
560 (apply 'concat
561 (mapcar
562 (lambda (re)
563 (cond
564 ((stringp re)
565 re)
566 ((symbolp re)
567 (cadr (assoc re rst-re-alist)))
568 ((characterp re)
569 (regexp-quote (char-to-string re)))
570 ((listp re)
571 (let ((nested
572 (mapcar (lambda (elt)
573 (rst-re elt))
574 (cdr re))))
575 (cond
576 ((eq (car re) :seq)
577 (mapconcat 'identity nested ""))
578 ((eq (car re) :shy)
579 (concat "\\(?:" (mapconcat 'identity nested "") "\\)"))
580 ((eq (car re) :grp)
581 (concat "\\(" (mapconcat 'identity nested "") "\\)"))
582 ((eq (car re) :alt)
583 (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)"))
584 (t
585 (error "Unknown list car: %s" (car re))))))
586 (t
587 (error "Unknown object type for building regex: %s" re))))
588 args)))
589
590;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'.
591(with-no-warnings ; Silence byte-compiler about this construction.
592 (defconst rst-re-alist
593 ;; Shadow global value we are just defining so we can construct it step by
594 ;; step.
595 (let (rst-re-alist)
596 (dolist (re rst-re-alist-def rst-re-alist)
597 (setq rst-re-alist
598 (nconc rst-re-alist
599 (list (list (car re) (apply 'rst-re (cdr re))))))))
600 "Alist mapping symbols from `rst-re-alist-def' to regex strings."))
601
602\f
603;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
604;; Mode definition
605
606;; testcover: ok.
607(defun rst-define-key (keymap key def &rest deprecated)
608 "Bind like `define-key' but add deprecated key definitions.
609KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key
610definitions should be in vector notation. These are defined as
611well but give an additional message."
612 (define-key keymap key def)
613 (dolist (dep-key deprecated)
614 (define-key keymap dep-key
615 `(lambda ()
616 ,(format "Deprecated binding for %s, use \\[%s] instead." def def)
617 (interactive)
618 (call-interactively ',def)
619 (message "[Deprecated use of key %s; use key %s instead]"
620 (key-description (this-command-keys))
621 (key-description ,key))))))
622
623;; Key bindings.
624(defvar rst-mode-map
625 (let ((map (make-sparse-keymap)))
626
627 ;; \C-c is the general keymap.
628 (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings)
629
630 ;;
631 ;; Section Adornments
632 ;;
633 ;; The adjustment function that adorns or rotates a section title.
634 (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t])
635 (rst-define-key map [?\C-=] 'rst-adjust) ; Does not work on the Mac OSX and
636 ; on consoles.
637
638 ;; \C-c \C-a is the keymap for adornments.
639 (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings)
640 ;; Another binding which works with all types of input.
641 (rst-define-key map [?\C-c ?\C-a ?\C-a] 'rst-adjust)
642 ;; Display the hierarchy of adornments implied by the current document
643 ;; contents.
644 (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy)
645 ;; Homogenize the adornments in the document.
646 (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments
647 [?\C-c ?\C-s])
648
649 ;;
650 ;; Section Movement and Selection
651 ;;
652 ;; Mark the subsection where the cursor is.
653 (rst-define-key map [?\C-\M-h] 'rst-mark-section
654 ;; Same as mark-defun sgml-mark-current-element.
655 [?\C-c ?\C-m])
656 ;; Move backward/forward between section titles.
657 ;; FIXME: Also bind similar to outline mode.
658 (rst-define-key map [?\C-\M-a] 'rst-backward-section
659 ;; Same as beginning-of-defun.
660 [?\C-c ?\C-n])
661 (rst-define-key map [?\C-\M-e] 'rst-forward-section
662 ;; Same as end-of-defun.
663 [?\C-c ?\C-p])
664
665 ;;
666 ;; Operating on regions
667 ;;
668 ;; \C-c \C-r is the keymap for regions.
669 (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings)
670 ;; Makes region a line-block.
671 (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region
672 [?\C-c ?\C-d])
673 ;; Shift region left or right according to tabs.
674 (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region
675 [?\C-c ?\C-r t] [?\C-c ?\C-l t])
676
677 ;;
678 ;; Operating on lists
679 ;;
680 ;; \C-c \C-l is the keymap for lists.
681 (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings)
682 ;; Makes paragraphs in region as a bullet list.
683 (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region
684 [?\C-c ?\C-b])
685 ;; Makes paragraphs in region as a enumeration.
686 (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region
687 [?\C-c ?\C-e])
688 ;; Converts bullets to an enumeration.
689 (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration
690 [?\C-c ?\C-v])
691 ;; Make sure that all the bullets in the region are consistent.
692 (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region
693 [?\C-c ?\C-w])
694 ;; Insert a list item.
695 (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list)
696
697 ;;
698 ;; Table-of-Contents Features
699 ;;
700 ;; \C-c \C-t is the keymap for table of contents.
701 (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings)
702 ;; Enter a TOC buffer to view and move to a specific section.
703 (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc)
704 ;; Insert a TOC here.
705 (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert
706 [?\C-c ?\C-i])
707 ;; Update the document's TOC (without changing the cursor position).
708 (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update
709 [?\C-c ?\C-u])
710 ;; Go to the section under the cursor (cursor must be in TOC).
711 (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section
712 [?\C-c ?\C-f])
713
714 ;;
715 ;; Converting Documents from Emacs
716 ;;
717 ;; \C-c \C-c is the keymap for compilation.
718 (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings)
719 ;; Run one of two pre-configured toolset commands on the document.
720 (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile
721 [?\C-c ?1])
722 (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset
723 [?\C-c ?2])
724 ;; Convert the active region to pseudo-xml using the docutils tools.
725 (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region
726 [?\C-c ?3])
727 ;; Convert the current document to PDF and launch a viewer on the results.
728 (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview
729 [?\C-c ?4])
730 ;; Convert the current document to S5 slides and view in a web browser.
731 (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview
732 [?\C-c ?5])
733
734 map)
735 "Keymap for reStructuredText mode commands.
736This inherits from Text mode.")
737
738
739;; Abbrevs.
740(define-abbrev-table 'rst-mode-abbrev-table
741 (mapcar (lambda (x) (append x '(nil 0 system)))
742 '(("contents" ".. contents::\n..\n ")
743 ("con" ".. contents::\n..\n ")
744 ("cont" "[...]")
745 ("skip" "\n\n[...]\n\n ")
746 ("seq" "\n\n[...]\n\n ")
747 ;; FIXME: Add footnotes, links, and more.
748 ))
749 "Abbrev table used while in `rst-mode'.")
750
751
752;; Syntax table.
753(defvar rst-mode-syntax-table
754 (let ((st (copy-syntax-table text-mode-syntax-table)))
755 (modify-syntax-entry ?$ "." st)
756 (modify-syntax-entry ?% "." st)
757 (modify-syntax-entry ?& "." st)
758 (modify-syntax-entry ?' "." st)
759 (modify-syntax-entry ?* "." st)
760 (modify-syntax-entry ?+ "." st)
761 (modify-syntax-entry ?- "." st)
762 (modify-syntax-entry ?/ "." st)
763 (modify-syntax-entry ?< "." st)
764 (modify-syntax-entry ?= "." st)
765 (modify-syntax-entry ?> "." st)
766 (modify-syntax-entry ?\\ "\\" st)
767 (modify-syntax-entry ?_ "." st)
768 (modify-syntax-entry ?| "." st)
769 (modify-syntax-entry ?\u00ab "." st)
770 (modify-syntax-entry ?\u00bb "." st)
771 (modify-syntax-entry ?\u2018 "." st)
772 (modify-syntax-entry ?\u2019 "." st)
773 (modify-syntax-entry ?\u201c "." st)
774 (modify-syntax-entry ?\u201d "." st)
775
776 st)
777 "Syntax table used while in `rst-mode'.")
778
779
780(defcustom rst-mode-hook nil
781 "Hook run when `rst-mode' is turned on.
782The hook for `text-mode' is run before this one."
783 :group 'rst
784 :type '(hook))
785(rst-testcover-defcustom)
786
787;; Pull in variable definitions silencing byte-compiler.
788(require 'newcomment)
789
790;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
791;; use *.txt, but this is too generic to be set as a default.
792;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
793;;;###autoload
794(define-derived-mode rst-mode text-mode "ReST"
795 "Major mode for editing reStructuredText documents.
796\\<rst-mode-map>
797
798Turning on `rst-mode' calls the normal hooks `text-mode-hook'
799and `rst-mode-hook'. This mode also supports font-lock
800highlighting.
801
802\\{rst-mode-map}"
803 :abbrev-table rst-mode-abbrev-table
804 :syntax-table rst-mode-syntax-table
805 :group 'rst
806
807 ;; Paragraph recognition.
808 (set (make-local-variable 'paragraph-separate)
809 (rst-re '(:alt
810 "\f"
811 lin-end)))
812 (set (make-local-variable 'paragraph-start)
813 (rst-re '(:alt
814 "\f"
815 lin-end
816 (:seq hws-tag par-tag- bli-sfx))))
817
818 ;; Indenting and filling.
819 (set (make-local-variable 'indent-line-function) 'rst-indent-line)
820 (set (make-local-variable 'adaptive-fill-mode) t)
821 (set (make-local-variable 'adaptive-fill-regexp)
822 (rst-re 'hws-tag 'par-tag- "?" 'hws-tag))
823 (set (make-local-variable 'adaptive-fill-function) 'rst-adaptive-fill)
824 (set (make-local-variable 'fill-paragraph-handle-comment) nil)
825
826 ;; Comments.
827 (set (make-local-variable 'comment-start) ".. ")
828 (set (make-local-variable 'comment-start-skip)
829 (rst-re 'lin-beg 'exm-tag 'bli-sfx))
830 (set (make-local-variable 'comment-continue) " ")
831 (set (make-local-variable 'comment-multi-line) t)
832 (set (make-local-variable 'comment-use-syntax) nil)
833 ;; reStructuredText has not really a comment ender but nil is not really a
834 ;; permissible value.
835 (set (make-local-variable 'comment-end) "")
836 (set (make-local-variable 'comment-end-skip) nil)
837
838 ;; Commenting in reStructuredText is very special so use our own set of
839 ;; functions.
840 (set (make-local-variable 'comment-line-break-function)
841 'rst-comment-line-break)
842 (set (make-local-variable 'comment-indent-function)
843 'rst-comment-indent)
844 (set (make-local-variable 'comment-insert-comment-function)
845 'rst-comment-insert-comment)
846 (set (make-local-variable 'comment-region-function)
847 'rst-comment-region)
848 (set (make-local-variable 'uncomment-region-function)
849 'rst-uncomment-region)
850
851 ;; Imenu and which function.
852 ;; FIXME: Check documentation of `which-function' for alternative ways to
853 ;; determine the current function name.
854 (set (make-local-variable 'imenu-create-index-function)
855 'rst-imenu-create-index)
856
857 ;; Font lock.
858 (set (make-local-variable 'font-lock-defaults)
859 '(rst-font-lock-keywords
860 t nil nil nil
861 (font-lock-multiline . t)
862 (font-lock-mark-block-function . mark-paragraph)))
863 (add-hook 'font-lock-extend-region-functions 'rst-font-lock-extend-region t)
864
865 ;; Text after a changed line may need new fontification.
866 (set (make-local-variable 'jit-lock-contextually) t))
867
868;;;###autoload
869(define-minor-mode rst-minor-mode
870 "Toggle ReST minor mode.
871With a prefix argument ARG, enable ReST minor mode if ARG is
872positive, and disable it otherwise. If called from Lisp, enable
873the mode if ARG is omitted or nil.
874
875When ReST minor mode is enabled, the ReST mode keybindings
876are installed on top of the major mode bindings. Use this
877for modes derived from Text mode, like Mail mode."
878 ;; The initial value.
879 nil
880 ;; The indicator for the mode line.
881 " ReST"
882 ;; The minor mode bindings.
883 rst-mode-map
884 :group 'rst)
885
886;; FIXME: can I somehow install these too?
887;; :abbrev-table rst-mode-abbrev-table
888;; :syntax-table rst-mode-syntax-table
889
890\f
891;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
892;; Section Adornment Adjustment
893;; ============================
894;;
895;; The following functions implement a smart automatic title sectioning feature.
896;; The idea is that with the cursor sitting on a section title, we try to get as
897;; much information from context and try to do the best thing automatically.
898;; This function can be invoked many times and/or with prefix argument to rotate
899;; between the various sectioning adornments.
900;;
901;; Definitions: the two forms of sectioning define semantically separate section
902;; levels. A sectioning ADORNMENT consists in:
903;;
904;; - a CHARACTER
905;;
906;; - a STYLE which can be either of 'simple' or 'over-and-under'.
907;;
908;; - an INDENT (meaningful for the over-and-under style only) which determines
909;; how many characters and over-and-under style is hanging outside of the
910;; title at the beginning and ending.
911;;
912;; Here are two examples of adornments (| represents the window border, column
913;; 0):
914;;
915;; |
916;; 1. char: '-' e |Some Title
917;; style: simple |----------
918;; |
919;; 2. char: '=' |==============
920;; style: over-and-under | Some Title
921;; indent: 2 |==============
922;; |
923;;
924;; Some notes:
925;;
926;; - The underlining character that is used depends on context. The file is
927;; scanned to find other sections and an appropriate character is selected.
928;; If the function is invoked on a section that is complete, the character is
929;; rotated among the existing section adornments.
930;;
931;; Note that when rotating the characters, if we come to the end of the
932;; hierarchy of adornments, the variable rst-preferred-adornments is
933;; consulted to propose a new underline adornment, and if continued, we cycle
934;; the adornments all over again. Set this variable to nil if you want to
935;; limit the underlining character propositions to the existing adornments in
936;; the file.
937;;
938;; - An underline/overline that is not extended to the column at which it should
939;; be hanging is dubbed INCOMPLETE. For example::
940;;
941;; |Some Title
942;; |-------
943;;
944;; Examples of default invocation:
945;;
946;; |Some Title ---> |Some Title
947;; | |----------
948;;
949;; |Some Title ---> |Some Title
950;; |----- |----------
951;;
952;; | |------------
953;; | Some Title ---> | Some Title
954;; | |------------
955;;
956;; In over-and-under style, when alternating the style, a variable is
957;; available to select how much default indent to use (it can be zero). Note
958;; that if the current section adornment already has an indent, we don't
959;; adjust it to the default, we rather use the current indent that is already
960;; there for adjustment (unless we cycle, in which case we use the indent
961;; that has been found previously).
962
963(defgroup rst-adjust nil
964 "Settings for adjustment and cycling of section title adornments."
965 :group 'rst
966 :version "21.1")
967
968(define-obsolete-variable-alias
969 'rst-preferred-decorations 'rst-preferred-adornments "1.0.0")
970(defcustom rst-preferred-adornments '((?= over-and-under 1)
971 (?= simple 0)
972 (?- simple 0)
973 (?~ simple 0)
974 (?+ simple 0)
975 (?` simple 0)
976 (?# simple 0)
977 (?@ simple 0))
978 "Preferred hierarchy of section title adornments.
979
980A list consisting of lists of the form (CHARACTER STYLE INDENT).
981CHARACTER is the character used. STYLE is one of the symbols
982OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted
983indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are
984always used when a section adornment is described. In other
985places t instead of a list stands for a transition.
986
987This sequence is consulted to offer a new adornment suggestion
988when we rotate the underlines at the end of the existing
989hierarchy of characters, or when there is no existing section
990title in the file.
991
992Set this to an empty list to use only the adornment found in the
993file."
994 :group 'rst-adjust
995 :type `(repeat
996 (group :tag "Adornment specification"
997 (choice :tag "Adornment character"
998 ,@(mapcar (lambda (char)
999 (list 'const
1000 :tag (char-to-string char) char))
1001 rst-adornment-chars))
1002 (radio :tag "Adornment type"
1003 (const :tag "Overline and underline" over-and-under)
1004 (const :tag "Underline only" simple))
1005 (integer :tag "Indentation for overline and underline type"
1006 :value 0))))
1007(rst-testcover-defcustom)
1008
1009(defcustom rst-default-indent 1
1010 "Number of characters to indent the section title.
1011
1012This is used for when toggling adornment styles, when switching
1013from a simple adornment style to a over-and-under adornment
1014style."
1015 :group 'rst-adjust
1016 :type '(integer))
1017(rst-testcover-defcustom)
1018
1019(defun rst-compare-adornments (ado1 ado2)
1020 "Compare adornments.
1021Return true if both ADO1 and ADO2 adornments are equal,
1022according to restructured text semantics (only the character and
1023the style are compared, the indentation does not matter)."
1024 (and (eq (car ado1) (car ado2))
1025 (eq (cadr ado1) (cadr ado2))))
1026
1027
1028(defun rst-get-adornment-match (hier ado)
1029 "Return the index (level) in hierarchy HIER of adornment ADO.
1030This basically just searches for the item using the appropriate
1031comparison and returns the index. Return nil if the item is
1032not found."
1033 (let ((cur hier))
1034 (while (and cur (not (rst-compare-adornments (car cur) ado)))
1035 (setq cur (cdr cur)))
1036 cur))
1037
1038;; testcover: FIXME: Test with `rst-preferred-adornments' == nil. Add test
1039;; `rst-adjust-no-preference'.
1040(defun rst-suggest-new-adornment (allados &optional prev)
1041 "Suggest a new, different adornment from all that have been seen.
1042
1043ALLADOS is the set of all adornments, including the line numbers.
1044PREV is the optional previous adornment, in order to suggest a
1045better match."
1046
1047 ;; For all the preferred adornments...
1048 (let* (
1049 ;; If 'prev' is given, reorder the list to start searching after the
1050 ;; match.
1051 (fplist
1052 (cdr (rst-get-adornment-match rst-preferred-adornments prev)))
1053
1054 ;; List of candidates to search.
1055 (curpotential (append fplist rst-preferred-adornments)))
1056 (while
1057 ;; For all the adornments...
1058 (let ((cur allados)
1059 found)
1060 (while (and cur (not found))
1061 (if (rst-compare-adornments (car cur) (car curpotential))
1062 ;; Found it!
1063 (setq found (car curpotential))
1064 (setq cur (cdr cur))))
1065 found)
1066
1067 (setq curpotential (cdr curpotential)))
1068
1069 (copy-sequence (car curpotential))))
1070
1071(defun rst-delete-entire-line ()
1072 "Delete the entire current line without using the `kill-ring'."
1073 (delete-region (line-beginning-position)
1074 (line-beginning-position 2)))
1075
1076(defun rst-update-section (char style &optional indent)
1077 "Unconditionally update the style of a section adornment.
1078
1079Do this using the given character CHAR, with STYLE 'simple
1080or 'over-and-under, and with indent INDENT. If the STYLE
1081is 'simple, whitespace before the title is removed (indent
1082is always assumed to be 0).
1083
1084If there are existing overline and/or underline from the
1085existing adornment, they are removed before adding the
1086requested adornment."
1087 (end-of-line)
1088 (let ((marker (point-marker))
1089 len)
1090
1091 ;; Fixup whitespace at the beginning and end of the line.
1092 (if (or (null indent) (eq style 'simple)) ;; testcover: ok.
1093 (setq indent 0))
1094 (beginning-of-line)
1095 (delete-horizontal-space)
1096 (insert (make-string indent ? ))
1097
1098 (end-of-line)
1099 (delete-horizontal-space)
1100
1101 ;; Set the current column, we're at the end of the title line.
1102 (setq len (+ (current-column) indent))
1103
1104 ;; Remove previous line if it is an adornment.
1105 (save-excursion
1106 (forward-line -1) ;; testcover: FIXME: Doesn't work when in first line
1107 ;; of buffer.
1108 (if (and (looking-at (rst-re 'ado-beg-2-1))
1109 ;; Avoid removing the underline of a title right above us.
1110 (save-excursion (forward-line -1)
1111 (not (looking-at (rst-re 'ttl-beg)))))
1112 (rst-delete-entire-line)))
1113
1114 ;; Remove following line if it is an adornment.
1115 (save-excursion
1116 (forward-line +1) ;; testcover: FIXME: Doesn't work when in last line
1117 ;; of buffer.
1118 (if (looking-at (rst-re 'ado-beg-2-1))
1119 (rst-delete-entire-line))
1120 ;; Add a newline if we're at the end of the buffer, for the subsequence
1121 ;; inserting of the underline.
1122 (if (= (point) (buffer-end 1))
1123 (newline 1)))
1124
1125 ;; Insert overline.
1126 (if (eq style 'over-and-under)
1127 (save-excursion
1128 (beginning-of-line)
1129 (open-line 1)
1130 (insert (make-string len char))))
1131
1132 ;; Insert underline.
1133 (1value ;; Line has been inserted above.
1134 (forward-line +1))
1135 (open-line 1)
1136 (insert (make-string len char))
1137
1138 (1value ;; Line has been inserted above.
1139 (forward-line +1))
1140 (goto-char marker)))
1141
1142(defun rst-classify-adornment (adornment end)
1143 "Classify adornment for section titles and transitions.
1144ADORNMENT is the complete adornment string as found in the buffer
1145with optional trailing whitespace. END is the point after the
1146last character of ADORNMENT.
1147
1148Return a list. The first entry is t for a transition or a
1149cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for
1150the meaning of CHARACTER and STYLE.
1151
1152The remaining list forms four match groups as returned by
1153`match-data'. Match group 0 matches the whole construct. Match
1154group 1 matches the overline adornment if present. Match group 2
1155matches the section title text or the transition. Match group 3
1156matches the underline adornment.
1157
1158Return nil if no syntactically valid adornment is found."
1159 (save-excursion
1160 (save-match-data
1161 (when (string-match (rst-re 'ado-beg-2-1) adornment)
1162 (goto-char end)
1163 (let* ((ado-ch (string-to-char (match-string 2 adornment)))
1164 (ado-re (rst-re ado-ch 'adorep3-hlp))
1165 (end-pnt (point))
1166 (beg-pnt (progn
1167 (1value ;; No lines may be left to move.
1168 (forward-line 0))
1169 (point)))
1170 (nxt-emp ; Next line nonexistent or empty
1171 (save-excursion
1172 (or (not (zerop (forward-line 1)))
1173 ;; testcover: FIXME: Add test classifying at the end of
1174 ;; buffer.
1175 (looking-at (rst-re 'lin-end)))))
1176 (prv-emp ; Previous line nonexistent or empty
1177 (save-excursion
1178 (or (not (zerop (forward-line -1)))
1179 (looking-at (rst-re 'lin-end)))))
1180 (ttl-blw ; Title found below starting here.
1181 (save-excursion
1182 (and
1183 (zerop (forward-line 1)) ;; testcover: FIXME: Add test
1184 ;; classifying at the end of
1185 ;; buffer.
1186 (looking-at (rst-re 'ttl-beg))
1187 (point))))
1188 (ttl-abv ; Title found above starting here.
1189 (save-excursion
1190 (and
1191 (zerop (forward-line -1))
1192 (looking-at (rst-re 'ttl-beg))
1193 (point))))
1194 (und-fnd ; Matching underline found starting here.
1195 (save-excursion
1196 (and ttl-blw
1197 (zerop (forward-line 2)) ;; testcover: FIXME: Add test
1198 ;; classifying at the end of
1199 ;; buffer.
1200 (looking-at (rst-re ado-re 'lin-end))
1201 (point))))
1202 (ovr-fnd ; Matching overline found starting here.
1203 (save-excursion
1204 (and ttl-abv
1205 (zerop (forward-line -2))
1206 (looking-at (rst-re ado-re 'lin-end))
1207 (point))))
1208 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
1209 (cond
1210 ((and nxt-emp prv-emp)
1211 ;; A transition.
1212 (setq key t
1213 beg-txt beg-pnt
1214 end-txt end-pnt))
1215 ((or und-fnd ovr-fnd)
1216 ;; An overline with an underline.
1217 (setq key (cons ado-ch 'over-and-under))
1218 (let (;; Prefer overline match over underline match.
1219 (und-pnt (if ovr-fnd beg-pnt und-fnd))
1220 (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt))
1221 (txt-pnt (if ovr-fnd ttl-abv ttl-blw)))
1222 (goto-char ovr-pnt)
1223 (setq beg-ovr (point)
1224 end-ovr (line-end-position))
1225 (goto-char txt-pnt)
1226 (setq beg-txt (point)
1227 end-txt (line-end-position))
1228 (goto-char und-pnt)
1229 (setq beg-und (point)
1230 end-und (line-end-position))))
1231 (ttl-abv
1232 ;; An underline.
1233 (setq key (cons ado-ch 'simple)
1234 beg-und beg-pnt
1235 end-und end-pnt)
1236 (goto-char ttl-abv)
1237 (setq beg-txt (point)
1238 end-txt (line-end-position)))
1239 (t
1240 ;; Invalid adornment.
1241 (setq key nil)))
1242 (if key
1243 (list key
1244 (or beg-ovr beg-txt)
1245 (or end-und end-txt)
1246 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))))
1247
1248(defun rst-find-title-line ()
1249 "Find a section title line around point and return its characteristics.
1250If the point is on an adornment line find the respective title
1251line. If the point is on an empty line check previous or next
1252line whether it is a suitable title line and use it if so. If
1253point is on a suitable title line use it.
1254
1255If no title line is found return nil.
1256
1257Otherwise return as `rst-classify-adornment' does. However, if
1258the title line has no syntactically valid adornment STYLE is nil
1259in the first element. If there is no adornment around the title
1260CHARACTER is also nil and match groups for overline and underline
1261are nil."
1262 (save-excursion
1263 (1value ;; No lines may be left to move.
1264 (forward-line 0))
1265 (let ((orig-pnt (point))
1266 (orig-end (line-end-position)))
1267 (cond
1268 ((looking-at (rst-re 'ado-beg-2-1))
1269 (let ((char (string-to-char (match-string-no-properties 2)))
1270 (r (rst-classify-adornment (match-string-no-properties 0)
1271 (match-end 0))))
1272 (cond
1273 ((not r)
1274 ;; Invalid adornment - check whether this is an incomplete overline.
1275 (if (and
1276 (zerop (forward-line 1))
1277 (looking-at (rst-re 'ttl-beg)))
1278 (list (cons char nil) orig-pnt (line-end-position)
1279 orig-pnt orig-end (point) (line-end-position) nil nil)))
1280 ((consp (car r))
1281 ;; A section title - not a transition.
1282 r))))
1283 ((looking-at (rst-re 'lin-end))
1284 (or
1285 (save-excursion
1286 (if (and (zerop (forward-line -1))
1287 (looking-at (rst-re 'ttl-beg)))
1288 (list (cons nil nil) (point) (line-end-position)
1289 nil nil (point) (line-end-position) nil nil)))
1290 (save-excursion
1291 (if (and (zerop (forward-line 1))
1292 (looking-at (rst-re 'ttl-beg)))
1293 (list (cons nil nil) (point) (line-end-position)
1294 nil nil (point) (line-end-position) nil nil)))))
1295 ((looking-at (rst-re 'ttl-beg))
1296 ;; Try to use the underline.
1297 (let ((r (rst-classify-adornment
1298 (buffer-substring-no-properties
1299 (line-beginning-position 2) (line-end-position 2))
1300 (line-end-position 2))))
1301 (if r
1302 r
1303 ;; No valid adornment found.
1304 (list (cons nil nil) (point) (line-end-position)
1305 nil nil (point) (line-end-position) nil nil))))))))
1306
1307;; The following function and variables are used to maintain information about
1308;; current section adornment in a buffer local cache. Thus they can be used for
1309;; font-locking and manipulation commands.
1310
1311(defvar rst-all-sections nil
1312 "All section adornments in the buffer as found by `rst-find-all-adornments'.
1313t when no section adornments were found.")
1314(make-variable-buffer-local 'rst-all-sections)
1315
1316;; FIXME: If this variable is set to a different value font-locking of section
1317;; headers is wrong.
1318(defvar rst-section-hierarchy nil
1319 "Section hierarchy in the buffer as determined by `rst-get-hierarchy'.
1320t when no section adornments were found. Value depends on
1321`rst-all-sections'.")
1322(make-variable-buffer-local 'rst-section-hierarchy)
1323
1324(rst-testcover-add-1value 'rst-reset-section-caches)
1325(defun rst-reset-section-caches ()
1326 "Reset all section cache variables.
1327Should be called by interactive functions which deal with sections."
1328 (setq rst-all-sections nil
1329 rst-section-hierarchy nil))
1330
1331(defun rst-find-all-adornments ()
1332 "Return all the section adornments in the current buffer.
1333Return a list of (LINE . ADORNMENT) with ascending LINE where
1334LINE is the line containing the section title. ADORNMENT consists
1335of a (CHARACTER STYLE INDENT) triple as described for
1336`rst-preferred-adornments'.
1337
1338Uses and sets `rst-all-sections'."
1339 (unless rst-all-sections
1340 (let (positions)
1341 ;; Iterate over all the section titles/adornments in the file.
1342 (save-excursion
1343 (goto-char (point-min))
1344 (while (re-search-forward (rst-re 'ado-beg-2-1) nil t)
1345 (let ((ado-data (rst-classify-adornment
1346 (match-string-no-properties 0) (point))))
1347 (when (and ado-data
1348 (consp (car ado-data))) ; Ignore transitions.
1349 (set-match-data (cdr ado-data))
1350 (goto-char (match-beginning 2)) ; Goto the title start.
1351 (push (cons (1+ (count-lines (point-min) (point)))
1352 (list (caar ado-data)
1353 (cdar ado-data)
1354 (current-indentation)))
1355 positions)
1356 (goto-char (match-end 0))))) ; Go beyond the whole thing.
1357 (setq positions (nreverse positions))
1358 (setq rst-all-sections (or positions t)))))
1359 (if (eq rst-all-sections t)
1360 nil
1361 rst-all-sections))
1362
1363(defun rst-infer-hierarchy (adornments)
1364 "Build a hierarchy of adornments using the list of given ADORNMENTS.
1365
1366ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment
1367specifications, in order that they appear in a file, and will
1368infer a hierarchy of section levels by removing adornments that
1369have already been seen in a forward traversal of the adornments,
1370comparing just CHARACTER and STYLE.
1371
1372Similarly returns a list of (CHARACTER STYLE INDENT), where each
1373list element should be unique."
1374 (let (hierarchy-alist)
1375 (dolist (x adornments)
1376 (let ((char (car x))
1377 (style (cadr x)))
1378 (unless (assoc (cons char style) hierarchy-alist)
1379 (push (cons (cons char style) x) hierarchy-alist))))
1380 (mapcar 'cdr (nreverse hierarchy-alist))))
1381
1382(defun rst-get-hierarchy (&optional ignore)
1383 "Return the hierarchy of section titles in the file.
1384
1385Return a list of adornments that represents the hierarchy of
1386section titles in the file. Each element consists of (CHARACTER
1387STYLE INDENT) as described for `rst-find-all-adornments'. If the
1388line number in IGNORE is specified, a possibly adornment found on
1389that line is not taken into account when building the hierarchy.
1390
1391Uses and sets `rst-section-hierarchy' unless IGNORE is given."
1392 (if (and (not ignore) rst-section-hierarchy)
1393 (if (eq rst-section-hierarchy t)
1394 nil
1395 rst-section-hierarchy)
1396 (let ((r (rst-infer-hierarchy
1397 (mapcar 'cdr
1398 (assq-delete-all
1399 ignore
1400 (rst-find-all-adornments))))))
1401 (setq rst-section-hierarchy
1402 (if ignore
1403 ;; Clear cache reflecting that a possible update is not
1404 ;; reflected.
1405 nil
1406 (or r t)))
1407 r)))
1408
1409(defun rst-get-adornments-around ()
1410 "Return the adornments around point.
1411Return a list of the previous and next adornments."
1412 (let* ((all (rst-find-all-adornments))
1413 (curline (line-number-at-pos))
1414 prev next
1415 (cur all))
1416
1417 ;; Search for the adornments around the current line.
1418 (while (and cur (< (caar cur) curline))
1419 (setq prev cur
1420 cur (cdr cur)))
1421 ;; 'cur' is the following adornment.
1422
1423 (if (and cur (caar cur))
1424 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
1425
1426 (mapcar 'cdar (list prev next))))
1427
1428(defun rst-adornment-complete-p (ado)
1429 "Return true if the adornment ADO around point is complete."
1430 ;; Note: we assume that the detection of the overline as being the underline
1431 ;; of a preceding title has already been detected, and has been eliminated
1432 ;; from the adornment that is given to us.
1433
1434 ;; There is some sectioning already present, so check if the current
1435 ;; sectioning is complete and correct.
1436 (let* ((char (car ado))
1437 (style (cadr ado))
1438 (indent (caddr ado))
1439 (endcol (save-excursion (end-of-line) (current-column))))
1440 (if char
1441 (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$")))
1442 (and
1443 (save-excursion (forward-line +1)
1444 (beginning-of-line)
1445 (looking-at exps))
1446 (or (not (eq style 'over-and-under))
1447 (save-excursion (forward-line -1)
1448 (beginning-of-line)
1449 (looking-at exps))))))))
1450
1451
1452(defun rst-get-next-adornment
1453 (curado hier &optional suggestion reverse-direction)
1454 "Get the next adornment for CURADO, in given hierarchy HIER.
1455If suggesting, suggest for new adornment SUGGESTION.
1456REVERSE-DIRECTION is used to reverse the cycling order."
1457
1458 (let* (
1459 (char (car curado))
1460 (style (cadr curado))
1461
1462 ;; Build a new list of adornments for the rotation.
1463 (rotados
1464 (append hier
1465 ;; Suggest a new adornment.
1466 (list suggestion
1467 ;; If nothing to suggest, use first adornment.
1468 (car hier)))) )
1469 (or
1470 ;; Search for next adornment.
1471 (cadr
1472 (let ((cur (if reverse-direction rotados
1473 (reverse rotados))))
1474 (while (and cur
1475 (not (and (eq char (caar cur))
1476 (eq style (cadar cur)))))
1477 (setq cur (cdr cur)))
1478 cur))
1479
1480 ;; If not found, take the first of all adornments.
1481 suggestion)))
1482
1483
1484;; FIXME: A line "``/`` full" is not accepted as a section title.
1485(defun rst-adjust (pfxarg)
1486 "Auto-adjust the adornment around point.
1487
1488Adjust/rotate the section adornment for the section title around
1489point or promote/demote the adornments inside the region,
1490depending on if the region is active. This function is meant to
1491be invoked possibly multiple times, and can vary its behavior
1492with a positive PFXARG (toggle style), or with a negative
1493PFXARG (alternate behavior).
1494
1495This function is a bit of a swiss knife. It is meant to adjust
1496the adornments of a section title in reStructuredText. It tries
1497to deal with all the possible cases gracefully and to do `the
1498right thing' in all cases.
1499
1500See the documentations of `rst-adjust-adornment-work' and
1501`rst-promote-region' for full details.
1502
1503Prefix Arguments
1504================
1505
1506The method can take either (but not both) of
1507
1508a. a (non-negative) prefix argument, which means to toggle the
1509 adornment style. Invoke with a prefix argument for example;
1510
1511b. a negative numerical argument, which generally inverts the
1512 direction of search in the file or hierarchy. Invoke with C--
1513 prefix for example."
1514 (interactive "P")
1515
1516 (let* (;; Save our original position on the current line.
1517 (origpt (point-marker))
1518
1519 (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1520 (toggle-style (and pfxarg (not reverse-direction))))
1521
1522 (if (use-region-p)
1523 ;; Adjust adornments within region.
1524 (rst-promote-region (and pfxarg t))
1525 ;; Adjust adornment around point.
1526 (rst-adjust-adornment-work toggle-style reverse-direction))
1527
1528 ;; Run the hooks to run after adjusting.
1529 (run-hooks 'rst-adjust-hook)
1530
1531 ;; Make sure to reset the cursor position properly after we're done.
1532 (goto-char origpt)))
1533
1534(defcustom rst-adjust-hook nil
1535 "Hooks to be run after running `rst-adjust'."
1536 :group 'rst-adjust
1537 :type '(hook)
1538 :package-version '(rst . "1.1.0"))
1539(rst-testcover-defcustom)
1540
1541(defcustom rst-new-adornment-down nil
1542 "Controls level of new adornment for section headers."
1543 :group 'rst-adjust
1544 :type '(choice
1545 (const :tag "Same level as previous one" nil)
1546 (const :tag "One level down relative to the previous one" t))
1547 :package-version '(rst . "1.1.0"))
1548(rst-testcover-defcustom)
1549
1550(defun rst-adjust-adornment (pfxarg)
1551 "Call `rst-adjust-adornment-work' interactively.
1552
1553Keep this for compatibility for older bindings (are there any?).
1554Argument PFXARG has the same meaning as for `rst-adjust'."
1555 (interactive "P")
1556
1557 (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1558 (toggle-style (and pfxarg (not reverse-direction))))
1559 (rst-adjust-adornment-work toggle-style reverse-direction)))
1560
1561(defun rst-adjust-adornment-work (toggle-style reverse-direction)
1562"Adjust/rotate the section adornment for the section title around point.
1563
1564This function is meant to be invoked possibly multiple times, and
1565can vary its behavior with a true TOGGLE-STYLE argument, or with
1566a REVERSE-DIRECTION argument.
1567
1568General Behavior
1569================
1570
1571The next action it takes depends on context around the point, and
1572it is meant to be invoked possibly more than once to rotate among
1573the various possibilities. Basically, this function deals with:
1574
1575- adding a adornment if the title does not have one;
1576
1577- adjusting the length of the underline characters to fit a
1578 modified title;
1579
1580- rotating the adornment in the set of already existing
1581 sectioning adornments used in the file;
1582
1583- switching between simple and over-and-under styles.
1584
1585You should normally not have to read all the following, just
1586invoke the method and it will do the most obvious thing that you
1587would expect.
1588
1589
1590Adornment Definitions
1591=====================
1592
1593The adornments consist in
1594
15951. a CHARACTER
1596
15972. a STYLE which can be either of 'simple' or 'over-and-under'.
1598
15993. an INDENT (meaningful for the over-and-under style only)
1600 which determines how many characters and over-and-under
1601 style is hanging outside of the title at the beginning and
1602 ending.
1603
1604See source code for mode details.
1605
1606
1607Detailed Behavior Description
1608=============================
1609
1610Here are the gory details of the algorithm (it seems quite
1611complicated, but really, it does the most obvious thing in all
1612the particular cases):
1613
1614Before applying the adornment change, the cursor is placed on
1615the closest line that could contain a section title.
1616
1617Case 1: No Adornment
1618--------------------
1619
1620If the current line has no adornment around it,
1621
1622- search backwards for the last previous adornment, and apply
1623 the adornment one level lower to the current line. If there
1624 is no defined level below this previous adornment, we suggest
1625 the most appropriate of the `rst-preferred-adornments'.
1626
1627 If REVERSE-DIRECTION is true, we simply use the previous
1628 adornment found directly.
1629
1630- if there is no adornment found in the given direction, we use
1631 the first of `rst-preferred-adornments'.
1632
1633TOGGLE-STYLE forces a toggle of the prescribed adornment style.
1634
1635Case 2: Incomplete Adornment
1636----------------------------
1637
1638If the current line does have an existing adornment, but the
1639adornment is incomplete, that is, the underline/overline does
1640not extend to exactly the end of the title line (it is either too
1641short or too long), we simply extend the length of the
1642underlines/overlines to fit exactly the section title.
1643
1644If TOGGLE-STYLE we toggle the style of the adornment as well.
1645
1646REVERSE-DIRECTION has no effect in this case.
1647
1648Case 3: Complete Existing Adornment
1649-----------------------------------
1650
1651If the adornment is complete (i.e. the underline (overline)
1652length is already adjusted to the end of the title line), we
1653search/parse the file to establish the hierarchy of all the
1654adornments (making sure not to include the adornment around
1655point), and we rotate the current title's adornment from within
1656that list (by default, going *down* the hierarchy that is present
1657in the file, i.e. to a lower section level). This is meant to be
1658used potentially multiple times, until the desired adornment is
1659found around the title.
1660
1661If we hit the boundary of the hierarchy, exactly one choice from
1662the list of preferred adornments is suggested/chosen, the first
1663of those adornment that has not been seen in the file yet (and
1664not including the adornment around point), and the next
1665invocation rolls over to the other end of the hierarchy (i.e. it
1666cycles). This allows you to avoid having to set which character
1667to use.
1668
1669If REVERSE-DIRECTION is true, the effect is to change the
1670direction of rotation in the hierarchy of adornments, thus
1671instead going *up* the hierarchy.
1672
1673However, if TOGGLE-STYLE, we do not rotate the adornment, but
1674instead simply toggle the style of the current adornment (this
1675should be the most common way to toggle the style of an existing
1676complete adornment).
1677
1678
1679Point Location
1680==============
1681
1682The invocation of this function can be carried out anywhere
1683within the section title line, on an existing underline or
1684overline, as well as on an empty line following a section title.
1685This is meant to be as convenient as possible.
1686
1687
1688Indented Sections
1689=================
1690
1691Indented section titles such as ::
1692
1693 My Title
1694 --------
1695
1696are invalid in reStructuredText and thus not recognized by the
1697parser. This code will thus not work in a way that would support
1698indented sections (it would be ambiguous anyway).
1699
1700
1701Joint Sections
1702==============
1703
1704Section titles that are right next to each other may not be
1705treated well. More work might be needed to support those, and
1706special conditions on the completeness of existing adornments
1707might be required to make it non-ambiguous.
1708
1709For now we assume that the adornments are disjoint, that is,
1710there is at least a single line between the titles/adornment
1711lines."
1712 (rst-reset-section-caches)
1713 (let ((ttl-fnd (rst-find-title-line))
1714 (orig-pnt (point)))
1715 (when ttl-fnd
1716 (set-match-data (cdr ttl-fnd))
1717 (goto-char (match-beginning 2))
1718 (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt)))
1719 (char (caar ttl-fnd))
1720 (style (cdar ttl-fnd))
1721 (indent (current-indentation))
1722 (curado (list char style indent))
1723 char-new style-new indent-new)
1724 (cond
1725 ;;-------------------------------------------------------------------
1726 ;; Case 1: No valid adornment
1727 ((not style)
1728 (let ((prev (car (rst-get-adornments-around)))
1729 cur
1730 (hier (rst-get-hierarchy)))
1731 ;; Advance one level down.
1732 (setq cur
1733 (if prev
1734 (if (or (and rst-new-adornment-down reverse-direction)
1735 (and (not rst-new-adornment-down)
1736 (not reverse-direction)))
1737 prev
1738 (or (cadr (rst-get-adornment-match hier prev))
1739 (rst-suggest-new-adornment hier prev)))
1740 (copy-sequence (car rst-preferred-adornments))))
1741 ;; Invert the style if requested.
1742 (if toggle-style
1743 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1744 'over-and-under 'simple)) )
1745 (setq char-new (car cur)
1746 style-new (cadr cur)
1747 indent-new (caddr cur))))
1748 ;;-------------------------------------------------------------------
1749 ;; Case 2: Incomplete Adornment
1750 ((not (rst-adornment-complete-p curado))
1751 ;; Invert the style if requested.
1752 (if toggle-style
1753 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1754 (setq char-new char
1755 style-new style
1756 indent-new indent))
1757 ;;-------------------------------------------------------------------
1758 ;; Case 3: Complete Existing Adornment
1759 (t
1760 (if toggle-style
1761 ;; Simply switch the style of the current adornment.
1762 (setq char-new char
1763 style-new (if (eq style 'simple) 'over-and-under 'simple)
1764 indent-new rst-default-indent)
1765 ;; Else, we rotate, ignoring the adornment around the current
1766 ;; line...
1767 (let* ((hier (rst-get-hierarchy (line-number-at-pos)))
1768 ;; Suggestion, in case we need to come up with something new.
1769 (suggestion (rst-suggest-new-adornment
1770 hier
1771 (car (rst-get-adornments-around))))
1772 (nextado (rst-get-next-adornment
1773 curado hier suggestion reverse-direction)))
1774 ;; Indent, if present, always overrides the prescribed indent.
1775 (setq char-new (car nextado)
1776 style-new (cadr nextado)
1777 indent-new (caddr nextado))))))
1778 ;; Override indent with present indent!
1779 (setq indent-new (if (> indent 0) indent indent-new))
1780 (if (and char-new style-new)
1781 (rst-update-section char-new style-new indent-new))
1782 ;; Correct the position of the cursor to more accurately reflect where
1783 ;; it was located when the function was invoked.
1784 (unless (zerop moved)
1785 (forward-line (- moved))
1786 (end-of-line))))))
1787
1788;; Maintain an alias for compatibility.
1789(defalias 'rst-adjust-section-title 'rst-adjust)
1790
1791
1792(defun rst-promote-region (demote)
1793 "Promote the section titles within the region.
1794
1795With argument DEMOTE or a prefix argument, demote the section
1796titles instead. The algorithm used at the boundaries of the
1797hierarchy is similar to that used by `rst-adjust-adornment-work'."
1798 (interactive "P")
1799 (rst-reset-section-caches)
1800 (let* ((cur (rst-find-all-adornments))
1801 (hier (rst-get-hierarchy))
1802 (suggestion (rst-suggest-new-adornment hier))
1803
1804 (region-begin-line (line-number-at-pos (region-beginning)))
1805 (region-end-line (line-number-at-pos (region-end)))
1806
1807 marker-list)
1808
1809 ;; Skip the markers that come before the region beginning.
1810 (while (and cur (< (caar cur) region-begin-line))
1811 (setq cur (cdr cur)))
1812
1813 ;; Create a list of markers for all the adornments which are found within
1814 ;; the region.
1815 (save-excursion
1816 (let (line)
1817 (while (and cur (< (setq line (caar cur)) region-end-line))
1818 (goto-char (point-min))
1819 (forward-line (1- line))
1820 (push (list (point-marker) (cdar cur)) marker-list)
1821 (setq cur (cdr cur)) ))
1822
1823 ;; Apply modifications.
1824 (dolist (p marker-list)
1825 ;; Go to the adornment to promote.
1826 (goto-char (car p))
1827
1828 ;; Update the adornment.
1829 (apply 'rst-update-section
1830 ;; Rotate the next adornment.
1831 (rst-get-next-adornment
1832 (cadr p) hier suggestion demote))
1833
1834 ;; Clear marker to avoid slowing down the editing after we're done.
1835 (set-marker (car p) nil))
1836 (setq deactivate-mark nil))))
1837
1838
1839
1840(defun rst-display-adornments-hierarchy (&optional adornments)
1841 "Display the current file's section title adornments hierarchy.
1842This function expects a list of (CHARACTER STYLE INDENT) triples
1843in ADORNMENTS."
1844 (interactive)
1845 (rst-reset-section-caches)
1846 (if (not adornments)
1847 (setq adornments (rst-get-hierarchy)))
1848 (with-output-to-temp-buffer "*rest section hierarchy*"
1849 (let ((level 1))
1850 (with-current-buffer standard-output
1851 (dolist (x adornments)
1852 (insert (format "\nSection Level %d" level))
1853 (apply 'rst-update-section x)
1854 (goto-char (point-max))
1855 (insert "\n")
1856 (incf level))))))
1857
1858(defun rst-straighten-adornments ()
1859 "Redo all the adornments in the current buffer.
1860This is done using our preferred set of adornments. This can be
1861used, for example, when using somebody else's copy of a document,
1862in order to adapt it to our preferred style."
1863 (interactive)
1864 (rst-reset-section-caches)
1865 (save-excursion
1866 (let (;; Get a list of pairs of (level . marker).
1867 (levels-and-markers (mapcar
1868 (lambda (ado)
1869 (cons (rst-position (cdr ado)
1870 (rst-get-hierarchy))
1871 (progn
1872 (goto-char (point-min))
1873 (forward-line (1- (car ado)))
1874 (point-marker))))
1875 (rst-find-all-adornments))))
1876 (dolist (lm levels-and-markers)
1877 ;; Go to the appropriate position.
1878 (goto-char (cdr lm))
1879
1880 ;; Apply the new style.
1881 (apply 'rst-update-section (nth (car lm) rst-preferred-adornments))
1882
1883 ;; Reset the marker to avoid slowing down editing until it gets GC'ed.
1884 (set-marker (cdr lm) nil)))))
1885
1886\f
1887;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1888;; Insert list items
1889;; =================
1890
1891
1892;=================================================
1893; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>.
1894; I needed to make some tiny changes to the functions, so I put it here.
1895; -- Wei-Wei Guo
1896
1897(defconst rst-arabic-to-roman
1898 '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
1899 (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
1900 (10 . "X") (9 . "IX") (5 . "V") (4 . "IV")
1901 (1 . "I"))
1902 "List of maps between Arabic numbers and their Roman numeral equivalents.")
1903
1904(defun rst-arabic-to-roman (num &optional arg)
1905 "Convert Arabic number NUM to its Roman numeral representation.
1906
1907Obviously, NUM must be greater than zero. Don't blame me, blame the
1908Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
1909apologies to Monty Python).
1910If optional prefix ARG is non-nil, insert in current buffer."
1911 (let ((map rst-arabic-to-roman)
1912 res)
1913 (while (and map (> num 0))
1914 (if (or (= num (caar map))
1915 (> num (caar map)))
1916 (setq res (concat res (cdar map))
1917 num (- num (caar map)))
1918 (setq map (cdr map))))
1919 res))
1920
1921(defun rst-roman-to-arabic (string &optional arg)
1922 "Convert STRING of Roman numerals to an Arabic number.
1923
1924If STRING contains a letter which isn't a valid Roman numeral, the rest
1925of the string from that point onwards is ignored.
1926
1927Hence:
1928MMD == 2500
1929and
1930MMDFLXXVI == 2500.
1931If optional ARG is non-nil, insert in current buffer."
1932 (let ((res 0)
1933 (map rst-arabic-to-roman))
1934 (while map
1935 (if (string-match (concat "^" (cdar map)) string)
1936 (setq res (+ res (caar map))
1937 string (replace-match "" nil t string))
1938 (setq map (cdr map))))
1939 res))
1940;=================================================
1941
1942(defun rst-find-pfx-in-region (beg end pfx-re)
1943 "Find all the positions of prefixes in region between BEG and END.
1944This is used to find bullets and enumerated list items. PFX-RE is
1945a regular expression for matching the lines after indentation
1946with items. Returns a list of cons cells consisting of the point
1947and the column of the point."
1948 (let ((pfx ()))
1949 (save-excursion
1950 (goto-char beg)
1951 (while (< (point) end)
1952 (back-to-indentation)
1953 (when (and
1954 (looking-at pfx-re) ; pfx found and...
1955 (let ((pfx-col (current-column)))
1956 (save-excursion
1957 (forward-line -1) ; ...previous line is...
1958 (back-to-indentation)
1959 (or (looking-at (rst-re 'lin-end)) ; ...empty,
1960 (> (current-column) pfx-col) ; ...deeper level, or
1961 (and (= (current-column) pfx-col)
1962 (looking-at pfx-re)))))) ; ...pfx at same level.
1963 (push (cons (point) (current-column))
1964 pfx))
1965 (forward-line 1)))
1966 (nreverse pfx)))
1967
1968(defun rst-insert-list-pos (newitem)
1969 "Arrange relative position of a newly inserted list item of style NEWITEM.
1970
1971Adding a new list might consider three situations:
1972
1973 (a) Current line is a blank line.
1974 (b) Previous line is a blank line.
1975 (c) Following line is a blank line.
1976
1977When (a) and (b), just add the new list at current line.
1978
1979when (a) and not (b), a blank line is added before adding the new list.
1980
1981When not (a), first forward point to the end of the line, and add two
1982blank lines, then add the new list.
1983
1984Other situations are just ignored and left to users themselves."
1985 (if (save-excursion
1986 (beginning-of-line)
1987 (looking-at (rst-re 'lin-end)))
1988 (if (save-excursion
1989 (forward-line -1)
1990 (looking-at (rst-re 'lin-end)))
1991 (insert newitem " ")
1992 (insert "\n" newitem " "))
1993 (end-of-line)
1994 (insert "\n\n" newitem " ")))
1995
1996;; FIXME: Isn't this a `defconst'?
1997(defvar rst-initial-enums
1998 (let (vals)
1999 (dolist (fmt '("%s." "(%s)" "%s)"))
2000 (dolist (c '("1" "a" "A" "I" "i"))
2001 (push (format fmt c) vals)))
2002 (cons "#." (nreverse vals)))
2003 "List of initial enumerations.")
2004
2005;; FIXME: Isn't this a `defconst'?
2006(defvar rst-initial-items
2007 (append (mapcar 'char-to-string rst-bullets) rst-initial-enums)
2008 "List of initial items. It's collection of bullets and enumerations.")
2009
2010(defun rst-insert-list-new-item ()
2011 "Insert a new list item.
2012
2013User is asked to select the item style first, for example (a), i), +. Use TAB
2014for completion and choices.
2015
2016If user selects bullets or #, it's just added with position arranged by
2017`rst-insert-list-pos'.
2018
2019If user selects enumerations, a further prompt is given. User need to input a
2020starting item, for example 'e' for 'A)' style. The position is also arranged by
2021`rst-insert-list-pos'."
2022 (interactive)
2023 ;; FIXME: Make this comply to `interactive' standards.
2024 (let* ((itemstyle (completing-read
2025 "Select preferred item style [#.]: "
2026 rst-initial-items nil t nil nil "#."))
2027 (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle)
2028 (match-string 0 itemstyle)))
2029 (no
2030 (save-match-data
2031 ;; FIXME: Make this comply to `interactive' standards.
2032 (cond
2033 ((equal cnt "a")
2034 (let ((itemno (read-string "Give starting value [a]: "
2035 nil nil "a")))
2036 (downcase (substring itemno 0 1))))
2037 ((equal cnt "A")
2038 (let ((itemno (read-string "Give starting value [A]: "
2039 nil nil "A")))
2040 (upcase (substring itemno 0 1))))
2041 ((equal cnt "I")
2042 (let ((itemno (read-number "Give starting value [1]: " 1)))
2043 (rst-arabic-to-roman itemno)))
2044 ((equal cnt "i")
2045 (let ((itemno (read-number "Give starting value [1]: " 1)))
2046 (downcase (rst-arabic-to-roman itemno))))
2047 ((equal cnt "1")
2048 (let ((itemno (read-number "Give starting value [1]: " 1)))
2049 (number-to-string itemno)))))))
2050 (if no
2051 (setq itemstyle (replace-match no t t itemstyle)))
2052 (rst-insert-list-pos itemstyle)))
2053
2054(defcustom rst-preferred-bullets
2055 '(?* ?- ?+)
2056 "List of favorite bullets."
2057 :group 'rst
2058 :type `(repeat
2059 (choice ,@(mapcar (lambda (char)
2060 (list 'const
2061 :tag (char-to-string char) char))
2062 rst-bullets)))
2063 :package-version '(rst . "1.1.0"))
2064(rst-testcover-defcustom)
2065
2066(defun rst-insert-list-continue (curitem prefer-roman)
2067 "Insert a list item with list start CURITEM including its indentation level.
2068If PREFER-ROMAN roman numbering is preferred over using letters."
2069 (end-of-line)
2070 (insert
2071 "\n" ; FIXME: Separating lines must be possible.
2072 (cond
2073 ((string-match (rst-re '(:alt enmaut-tag
2074 bul-tag)) curitem)
2075 curitem)
2076 ((string-match (rst-re 'num-tag) curitem)
2077 (replace-match (number-to-string
2078 (1+ (string-to-number (match-string 0 curitem))))
2079 nil nil curitem))
2080 ((and (string-match (rst-re 'rom-tag) curitem)
2081 (save-match-data
2082 (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag.
2083 (save-excursion
2084 ;; FIXME: Assumes one line list items without separating
2085 ;; empty lines.
2086 (if (and (zerop (forward-line -1))
2087 (looking-at (rst-re 'enmexp-beg)))
2088 (string-match
2089 (rst-re 'rom-tag)
2090 (match-string 0)) ; Previous was a roman tag.
2091 prefer-roman)) ; Don't know - use flag.
2092 t))) ; Not a letter tag.
2093 (replace-match
2094 (let* ((old (match-string 0 curitem))
2095 (new (save-match-data
2096 (rst-arabic-to-roman
2097 (1+ (rst-roman-to-arabic
2098 (upcase old)))))))
2099 (if (equal old (upcase old))
2100 (upcase new)
2101 (downcase new)))
2102 t nil curitem))
2103 ((string-match (rst-re 'ltr-tag) curitem)
2104 (replace-match (char-to-string
2105 (1+ (string-to-char (match-string 0 curitem))))
2106 nil nil curitem)))))
2107
2108
2109(defun rst-insert-list (&optional prefer-roman)
2110 "Insert a list item at the current point.
2111
2112The command can insert a new list or a continuing list. When it is called at a
2113non-list line, it will promote to insert new list. When it is called at a list
2114line, it will insert a list with the same list style.
2115
21161. When inserting a new list:
2117
2118User is asked to select the item style first, for example (a), i), +. Use TAB
2119for completion and choices.
2120
2121 (a) If user selects bullets or #, it's just added.
2122 (b) If user selects enumerations, a further prompt is given. User needs to
2123 input a starting item, for example 'e' for 'A)' style.
2124
2125The position of the new list is arranged according to whether or not the
2126current line and the previous line are blank lines.
2127
21282. When continuing a list, one thing need to be noticed:
2129
2130List style alphabetical list, such as 'a.', and roman numerical list, such as
2131'i.', have some overlapping items, for example 'v.' The function can deal with
2132the problem elegantly in most situations. But when those overlapped list are
2133preceded by a blank line, it is hard to determine which type to use
2134automatically. The function uses alphabetical list by default. If you want
2135roman numerical list, just use a prefix to set PREFER-ROMAN."
2136 (interactive "P")
2137 (beginning-of-line)
2138 (if (looking-at (rst-re 'itmany-beg-1))
2139 (rst-insert-list-continue (match-string 0) prefer-roman)
2140 (rst-insert-list-new-item)))
2141
2142(defun rst-straighten-bullets-region (beg end)
2143 "Make all the bulleted list items in the region consistent.
2144The region is specified between BEG and END. You can use this
2145after you have merged multiple bulleted lists to make them use
2146the same/correct/consistent bullet characters.
2147
2148See variable `rst-preferred-bullets' for the list of bullets to
2149adjust. If bullets are found on levels beyond the
2150`rst-preferred-bullets' list, they are not modified."
2151 (interactive "r")
2152
2153 (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta)))
2154 (levtable (make-hash-table :size 4)))
2155
2156 ;; Create a map of levels to list of positions.
2157 (dolist (x bullets)
2158 (let ((key (cdr x)))
2159 (puthash key
2160 (append (gethash key levtable (list))
2161 (list (car x)))
2162 levtable)))
2163
2164 ;; Sort this map and create a new map of prefix char and list of positions.
2165 (let ((poslist ())) ; List of (indent . positions).
2166 (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
2167
2168 (let ((bullets rst-preferred-bullets))
2169 (dolist (x (sort poslist 'car-less-than-car))
2170 (when bullets
2171 ;; Apply the characters.
2172 (dolist (pos (cdr x))
2173 (goto-char pos)
2174 (delete-char 1)
2175 (insert (string (car bullets))))
2176 (setq bullets (cdr bullets))))))))
2177
2178\f
2179;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2180;; Table of contents
2181;; =================
2182
2183;; FIXME: Return value should be a `defstruct'.
2184(defun rst-section-tree ()
2185 "Return the hierarchical tree of section titles.
2186A tree entry looks like ((TITLE MARKER) CHILD...). TITLE is the
2187stripped text of the section title. MARKER is a marker for the
2188beginning of the title text. For the top node or a missing
2189section level node TITLE is nil and MARKER points to the title
2190text of the first child. Each CHILD is another tree entry. The
2191CHILD list may be empty."
2192 (let ((hier (rst-get-hierarchy))
2193 (ch-sty2level (make-hash-table :test 'equal :size 10))
2194 lev-ttl-mrk-l)
2195
2196 (let ((lev 0))
2197 (dolist (ado hier)
2198 ;; Compare just the character and indent in the hash table.
2199 (puthash (cons (car ado) (cadr ado)) lev ch-sty2level)
2200 (incf lev)))
2201
2202 ;; Create a list that contains (LEVEL TITLE MARKER) for each adornment.
2203 (save-excursion
2204 (setq lev-ttl-mrk-l
2205 (mapcar (lambda (ado)
2206 (goto-char (point-min))
2207 (1value ;; This should really succeed.
2208 (forward-line (1- (car ado))))
2209 (list (gethash (cons (cadr ado) (caddr ado)) ch-sty2level)
2210 ;; Get title.
2211 (save-excursion
2212 (if (re-search-forward
2213 (rst-re "\\S .*\\S ") (line-end-position) t)
2214 (buffer-substring-no-properties
2215 (match-beginning 0) (match-end 0))
2216 ""))
2217 (point-marker)))
2218 (rst-find-all-adornments))))
2219 (cdr (rst-section-tree-rec lev-ttl-mrk-l -1))))
2220
2221;; FIXME: Return value should be a `defstruct'.
2222(defun rst-section-tree-rec (remaining lev)
2223 "Process the first entry of REMAINING expected to be on level LEV.
2224REMAINING is the remaining list of adornments consisting
2225of (LEVEL TITLE MARKER) entries.
2226
2227Return (UNPROCESSED (TITLE MARKER) CHILD...) for the first entry
2228of REMAINING where TITLE is nil if the expected level is not
2229matched. UNPROCESSED is the list of still unprocessed entries.
2230Each CHILD is a child of this entry in the same format but
2231without UNPROCESSED."
2232 (let ((cur (car remaining))
2233 (unprocessed remaining)
2234 ttl-mrk children)
2235 ;; If the current adornment matches expected level.
2236 (when (and cur (= (car cur) lev))
2237 ;; Consume the current entry and create the current node with it.
2238 (setq unprocessed (cdr remaining))
2239 (setq ttl-mrk (cdr cur)))
2240
2241 ;; Build the child nodes as long as they have deeper level.
2242 (while (and unprocessed (> (caar unprocessed) lev))
2243 (let ((rem-children (rst-section-tree-rec unprocessed (1+ lev))))
2244 (setq children (cons (cdr rem-children) children))
2245 (setq unprocessed (car rem-children))))
2246 (setq children (reverse children))
2247
2248 (cons unprocessed
2249 (cons (or ttl-mrk
2250 ;; Node on this level missing - use nil as text and the
2251 ;; marker of the first child.
2252 (cons nil (cdaar children)))
2253 children))))
2254
2255(defun rst-section-tree-point (tree &optional point)
2256 "Return section containing POINT by returning the closest node in TREE.
2257TREE is a section tree as returned by `rst-section-tree'
2258consisting of (NODE CHILD...) entries. POINT defaults to the
2259current point. A NODE must have the structure (IGNORED MARKER
2260...).
2261
2262Return (PATH NODE CHILD...). NODE is the node where POINT is in
2263if any. PATH is a list of nodes from the top of the tree down to
2264and including NODE. List of CHILD are the children of NODE if
2265any."
2266 (setq point (or point (point)))
2267 (let ((cur (car tree))
2268 (children (cdr tree)))
2269 ;; Point behind current node?
2270 (if (and (cadr cur) (>= point (cadr cur)))
2271 ;; Iterate all the children, looking for one that might contain the
2272 ;; current section.
2273 (let (found)
2274 (while (and children (>= point (cadaar children)))
2275 (setq found children
2276 children (cdr children)))
2277 (if found
2278 ;; Found section containing point in children.
2279 (let ((sub (rst-section-tree-point (car found) point)))
2280 ;; Extend path with current node and return NODE CHILD... from
2281 ;; sub.
2282 (cons (cons cur (car sub)) (cdr sub)))
2283 ;; Point in this section: Start a new path with current node and
2284 ;; return current NODE CHILD...
2285 (cons (list cur) tree)))
2286 ;; Current node behind point: start a new path with current node and
2287 ;; no NODE CHILD...
2288 (list (list cur)))))
2289
2290(defgroup rst-toc nil
2291 "Settings for reStructuredText table of contents."
2292 :group 'rst
2293 :version "21.1")
2294
2295(defcustom rst-toc-indent 2
2296 "Indentation for table-of-contents display.
2297Also used for formatting insertion, when numbering is disabled."
2298 :group 'rst-toc)
2299(rst-testcover-defcustom)
2300
2301(defcustom rst-toc-insert-style 'fixed
2302 "Insertion style for table-of-contents.
2303Set this to one of the following values to determine numbering and
2304indentation style:
2305- plain: no numbering (fixed indentation)
2306- fixed: numbering, but fixed indentation
2307- aligned: numbering, titles aligned under each other
2308- listed: numbering, with dashes like list items (EXPERIMENTAL)"
2309 :group 'rst-toc)
2310(rst-testcover-defcustom)
2311
2312(defcustom rst-toc-insert-number-separator " "
2313 "Separator that goes between the TOC number and the title."
2314 :group 'rst-toc)
2315(rst-testcover-defcustom)
2316
2317;; This is used to avoid having to change the user's mode.
2318(defvar rst-toc-insert-click-keymap
2319 (let ((map (make-sparse-keymap)))
2320 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
2321 map)
2322 "(Internal) What happens when you click on propertized text in the TOC.")
2323
2324(defcustom rst-toc-insert-max-level nil
2325 "If non-nil, maximum depth of the inserted TOC."
2326 :group 'rst-toc)
2327(rst-testcover-defcustom)
2328
2329(defun rst-toc-insert (&optional pfxarg)
2330 "Insert a simple text rendering of the table of contents.
2331By default the top level is ignored if there is only one, because
2332we assume that the document will have a single title.
2333
2334If a numeric prefix argument PFXARG is given, insert the TOC up
2335to the specified level.
2336
2337The TOC is inserted indented at the current column."
2338 (interactive "P")
2339 (rst-reset-section-caches)
2340 (let* (;; Check maximum level override.
2341 (rst-toc-insert-max-level
2342 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
2343 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
2344
2345 ;; Get the section tree for the current cursor point.
2346 (sectree-pair
2347 (rst-section-tree-point
2348 (rst-section-tree)))
2349
2350 ;; Figure out initial indent.
2351 (initial-indent (make-string (current-column) ? ))
2352 (init-point (point)))
2353
2354 (when (cddr sectree-pair)
2355 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
2356
2357 ;; Fixup for the first line.
2358 (delete-region init-point (+ init-point (length initial-indent)))
2359
2360 ;; Delete the last newline added.
2361 (delete-char -1))))
2362
2363(defun rst-toc-insert-node (node level indent pfx)
2364 "Insert tree node NODE in table-of-contents.
2365Recursive function that does printing of the inserted toc.
2366LEVEL is the depth level of the sections in the tree.
2367INDENT is the indentation string. PFX is the prefix numbering,
2368that includes the alignment necessary for all the children of
2369level to align."
2370
2371 ;; Note: we do child numbering from the parent, so we start number the
2372 ;; children one level before we print them.
2373 (let ((do-print (> level 0))
2374 (count 1))
2375 (when do-print
2376 (insert indent)
2377 (let ((b (point)))
2378 (unless (equal rst-toc-insert-style 'plain)
2379 (insert pfx rst-toc-insert-number-separator))
2380 (insert (or (caar node) "[missing node]"))
2381 ;; Add properties to the text, even though in normal text mode it
2382 ;; won't be doing anything for now. Not sure that I want to change
2383 ;; mode stuff. At least the highlighting gives the idea that this
2384 ;; is generated automatically.
2385 (put-text-property b (point) 'mouse-face 'highlight)
2386 (put-text-property b (point) 'rst-toc-target (cadar node))
2387 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap))
2388 (insert "\n")
2389
2390 ;; Prepare indent for children.
2391 (setq indent
2392 (cond
2393 ((eq rst-toc-insert-style 'plain)
2394 (concat indent (make-string rst-toc-indent ? )))
2395
2396 ((eq rst-toc-insert-style 'fixed)
2397 (concat indent (make-string rst-toc-indent ? )))
2398
2399 ((eq rst-toc-insert-style 'aligned)
2400 (concat indent (make-string (+ (length pfx) 2) ? )))
2401
2402 ((eq rst-toc-insert-style 'listed)
2403 (concat (substring indent 0 -3)
2404 (concat (make-string (+ (length pfx) 2) ? ) " - "))))))
2405
2406 (if (or (eq rst-toc-insert-max-level nil)
2407 (< level rst-toc-insert-max-level))
2408 (let ((do-child-numbering (>= level 0))
2409 fmt)
2410 (if do-child-numbering
2411 (progn
2412 ;; Add a separating dot if there is already a prefix.
2413 (when (> (length pfx) 0)
2414 (string-match (rst-re "[ \t\n]*\\'") pfx)
2415 (setq pfx (concat (replace-match "" t t pfx) ".")))
2416
2417 ;; Calculate the amount of space that the prefix will require
2418 ;; for the numbers.
2419 (if (cdr node)
2420 (setq fmt (format "%%-%dd"
2421 (1+ (floor (log10 (length
2422 (cdr node))))))))))
2423
2424 (dolist (child (cdr node))
2425 (rst-toc-insert-node child
2426 (1+ level)
2427 indent
2428 (if do-child-numbering
2429 (concat pfx (format fmt count)) pfx))
2430 (incf count))))))
2431
2432
2433(defun rst-toc-update ()
2434 "Automatically find the contents section of a document and update.
2435Updates the inserted TOC if present. You can use this in your
2436file-write hook to always make it up-to-date automatically."
2437 (interactive)
2438 (save-excursion
2439 ;; Find and delete an existing comment after the first contents directive.
2440 ;; Delete that region.
2441 (goto-char (point-min))
2442 ;; We look for the following and the following only (in other words, if your
2443 ;; syntax differs, this won't work.).
2444 ;;
2445 ;; .. contents:: [...anything here...]
2446 ;; [:field: value]...
2447 ;; ..
2448 ;; XXXXXXXX
2449 ;; XXXXXXXX
2450 ;; [more lines]
2451 (let ((beg (re-search-forward
2452 (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n"
2453 "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t))
2454 last-real)
2455 (when beg
2456 ;; Look for the first line that starts at the first column.
2457 (forward-line 1)
2458 (while (and
2459 (< (point) (point-max))
2460 (or (if (looking-at
2461 (rst-re 'hws-sta "\\S ")) ; indented content.
2462 (setq last-real (point)))
2463 (looking-at (rst-re 'lin-end)))) ; empty line.
2464 (forward-line 1))
2465 (if last-real
2466 (progn
2467 (goto-char last-real)
2468 (end-of-line)
2469 (delete-region beg (point)))
2470 (goto-char beg))
2471 (insert "\n ")
2472 (rst-toc-insert))))
2473 ;; Note: always return nil, because this may be used as a hook.
2474 nil)
2475
2476;; Note: we cannot bind the TOC update on file write because it messes with
2477;; undo. If we disable undo, since it adds and removes characters, the
2478;; positions in the undo list are not making sense anymore. Dunno what to do
2479;; with this, it would be nice to update when saving.
2480;;
2481;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
2482;; (defun rst-toc-update-fun ()
2483;; ;; Disable undo for the write file hook.
2484;; (let ((buffer-undo-list t)) (rst-toc-update) ))
2485
2486(defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat.
2487
2488;;------------------------------------------------------------------------------
2489
2490(defun rst-toc-node (node level)
2491 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
2492
2493 (if (> level 0)
2494 (let ((b (point)))
2495 ;; Insert line text.
2496 (insert (make-string (* rst-toc-indent (1- level)) ? ))
2497 (insert (or (caar node) "[missing node]"))
2498
2499 ;; Highlight lines.
2500 (put-text-property b (point) 'mouse-face 'highlight)
2501
2502 ;; Add link on lines.
2503 (put-text-property b (point) 'rst-toc-target (cadar node))
2504
2505 (insert "\n")))
2506
2507 (dolist (child (cdr node))
2508 (rst-toc-node child (1+ level))))
2509
2510(defun rst-toc-count-lines (node target-node)
2511 "Count the number of lines from NODE to the TARGET-NODE node.
2512This recursive function returns a cons of the number of
2513additional lines that have been counted for its node and
2514children, and t if the node has been found."
2515
2516 (let ((count 1)
2517 found)
2518 (if (eq node target-node)
2519 (setq found t)
2520 (let ((child (cdr node)))
2521 (while (and child (not found))
2522 (let ((cl (rst-toc-count-lines (car child) target-node)))
2523 (setq count (+ count (car cl))
2524 found (cdr cl)
2525 child (cdr child))))))
2526 (cons count found)))
2527
2528(defvar rst-toc-buffer-name "*Table of Contents*"
2529 "Name of the Table of Contents buffer.")
2530
2531(defvar rst-toc-return-wincfg nil
2532 "Window configuration to which to return when leaving the TOC.")
2533
2534
2535(defun rst-toc ()
2536 "Display a table-of-contents.
2537Finds all the section titles and their adornments in the
2538file, and displays a hierarchically-organized list of the
2539titles, which is essentially a table-of-contents of the
2540document.
2541
2542The Emacs buffer can be navigated, and selecting a section
2543brings the cursor in that section."
2544 (interactive)
2545 (rst-reset-section-caches)
2546 (let* ((curbuf (list (current-window-configuration) (point-marker)))
2547 (sectree (rst-section-tree))
2548
2549 (our-node (cdr (rst-section-tree-point sectree)))
2550 line
2551
2552 ;; Create a temporary buffer.
2553 (buf (get-buffer-create rst-toc-buffer-name)))
2554
2555 (with-current-buffer buf
2556 (let ((inhibit-read-only t))
2557 (rst-toc-mode)
2558 (delete-region (point-min) (point-max))
2559 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
2560 (put-text-property (point-min) (point)
2561 'face (list '(background-color . "gray")))
2562 (rst-toc-node sectree 0)
2563
2564 ;; Count the lines to our found node.
2565 (let ((linefound (rst-toc-count-lines sectree our-node)))
2566 (setq line (if (cdr linefound) (car linefound) 0)))))
2567 (display-buffer buf)
2568 (pop-to-buffer buf)
2569
2570 ;; Save the buffer to return to.
2571 (set (make-local-variable 'rst-toc-return-wincfg) curbuf)
2572
2573 ;; Move the cursor near the right section in the TOC.
2574 (goto-char (point-min))
2575 (forward-line (1- line))))
2576
2577
2578(defun rst-toc-mode-find-section ()
2579 "Get the section from text property at point."
2580 (let ((pos (get-text-property (point) 'rst-toc-target)))
2581 (unless pos
2582 (error "No section on this line"))
2583 (unless (buffer-live-p (marker-buffer pos))
2584 (error "Buffer for this section was killed"))
2585 pos))
2586
2587;; FIXME: Cursor before or behind the list must be handled properly; before the
2588;; list should jump to the top and behind the list to the last normal
2589;; paragraph.
2590(defun rst-goto-section (&optional kill)
2591 "Go to the section the current line describes.
2592If KILL a toc buffer is destroyed."
2593 (interactive)
2594 (let ((pos (rst-toc-mode-find-section)))
2595 (when kill
2596 ;; FIXME: This should rather go to `rst-toc-mode-goto-section'.
2597 (set-window-configuration (car rst-toc-return-wincfg))
2598 (kill-buffer (get-buffer rst-toc-buffer-name)))
2599 (pop-to-buffer (marker-buffer pos))
2600 (goto-char pos)
2601 ;; FIXME: make the recentering conditional on scroll.
2602 (recenter 5)))
2603
2604(defun rst-toc-mode-goto-section ()
2605 "Go to the section the current line describes and kill the TOC buffer."
2606 (interactive)
2607 (rst-goto-section t))
2608
2609(defun rst-toc-mode-mouse-goto (event)
2610 "In `rst-toc' mode, go to the occurrence whose line you click on.
2611EVENT is the input event."
2612 (interactive "e")
2613 (let ((pos
2614 (with-current-buffer (window-buffer (posn-window (event-end event)))
2615 (save-excursion
2616 (goto-char (posn-point (event-end event)))
2617 (rst-toc-mode-find-section)))))
2618 (pop-to-buffer (marker-buffer pos))
2619 (goto-char pos)
2620 (recenter 5)))
2621
2622(defun rst-toc-mode-mouse-goto-kill (event)
2623 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well.
2624EVENT is the input event."
2625 (interactive "e")
2626 (call-interactively 'rst-toc-mode-mouse-goto event)
2627 (kill-buffer (get-buffer rst-toc-buffer-name)))
2628
2629(defun rst-toc-quit-window ()
2630 "Leave the current TOC buffer."
2631 (interactive)
2632 (let ((retbuf rst-toc-return-wincfg))
2633 (set-window-configuration (car retbuf))
2634 (goto-char (cadr retbuf))))
2635
2636(defvar rst-toc-mode-map
2637 (let ((map (make-sparse-keymap)))
2638 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2639 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2640 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2641 (define-key map "f" 'rst-toc-mode-goto-section)
2642 (define-key map "q" 'rst-toc-quit-window)
2643 (define-key map "z" 'kill-this-buffer)
2644 map)
2645 "Keymap for `rst-toc-mode'.")
2646
2647(put 'rst-toc-mode 'mode-class 'special)
2648
2649;; Could inherit from the new `special-mode'.
2650(define-derived-mode rst-toc-mode nil "ReST-TOC"
2651 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2652 (setq buffer-read-only t))
2653
2654;; Note: use occur-mode (replace.el) as a good example to complete missing
2655;; features.
2656
2657;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2658;; Section movement commands
2659;; =========================
2660
2661(defun rst-forward-section (&optional offset)
2662 "Skip to the next reStructuredText section title.
2663OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2664backwards in the file (default is to use 1)."
2665 (interactive)
2666 (rst-reset-section-caches)
2667 (let* (;; Default value for offset.
2668 (offset (or offset 1))
2669
2670 ;; Get all the adornments in the file, with their line numbers.
2671 (allados (rst-find-all-adornments))
2672
2673 ;; Get the current line.
2674 (curline (line-number-at-pos))
2675
2676 (cur allados)
2677 (idx 0))
2678
2679 ;; Find the index of the "next" adornment w.r.t. to the current line.
2680 (while (and cur (< (caar cur) curline))
2681 (setq cur (cdr cur))
2682 (incf idx))
2683 ;; 'cur' is the adornment on or following the current line.
2684
2685 (if (and (> offset 0) cur (= (caar cur) curline))
2686 (incf idx))
2687
2688 ;; Find the final index.
2689 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2690 (setq cur (nth idx allados))
2691
2692 ;; If the index is positive, goto the line, otherwise go to the buffer
2693 ;; boundaries.
2694 (if (and cur (>= idx 0))
2695 (progn
2696 (goto-char (point-min))
2697 (forward-line (1- (car cur))))
2698 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))))
2699
2700(defun rst-backward-section ()
2701 "Like `rst-forward-section', except move back one title."
2702 (interactive)
2703 (rst-forward-section -1))
2704
2705;; FIXME: What is `allow-extend' for?
2706(defun rst-mark-section (&optional count allow-extend)
2707 "Select COUNT sections around point.
2708Mark following sections for positive COUNT or preceding sections
2709for negative COUNT."
2710 ;; Cloned from mark-paragraph.
2711 (interactive "p\np")
2712 (unless count (setq count 1))
2713 (when (zerop count)
2714 (error "Cannot mark zero sections"))
2715 (cond ((and allow-extend
2716 (or (and (eq last-command this-command) (mark t))
2717 (use-region-p)))
2718 (set-mark
2719 (save-excursion
2720 (goto-char (mark))
2721 (rst-forward-section count)
2722 (point))))
2723 (t
2724 (rst-forward-section count)
2725 (push-mark nil t t)
2726 (rst-forward-section (- count)))))
2727
2728\f
2729;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2730;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2731;; always 2 or 3 characters apart horizontally with rest.
2732
2733(defun rst-find-leftmost-column (beg end)
2734 "Return the leftmost column in region BEG to END."
2735 (let (mincol)
2736 (save-excursion
2737 (goto-char beg)
2738 (while (< (point) end)
2739 (back-to-indentation)
2740 (unless (looking-at (rst-re 'lin-end))
2741 (setq mincol (if mincol
2742 (min mincol (current-column))
2743 (current-column))))
2744 (forward-line 1)))
2745 mincol))
2746
2747;; FIXME: This definition is old and deprecated. We need to move to the newer
2748;; version below.
2749(defmacro rst-iterate-leftmost-paragraphs
2750 (beg end first-only body-consequent body-alternative)
2751 ;; FIXME: The following comment is pretty useless.
2752 "Call FUN at the beginning of each line, with an argument that
2753specifies whether we are at the first line of a paragraph that
2754starts at the leftmost column of the given region BEG and END.
2755Set FIRST-ONLY to true if you want to callback on the first line
2756of each paragraph only."
2757 `(save-excursion
2758 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2759 (endm (copy-marker ,end)))
2760
2761 (do* (;; Iterate lines.
2762 (l (progn (goto-char ,beg) (back-to-indentation))
2763 (progn (forward-line 1) (back-to-indentation)))
2764
2765 (previous nil valid)
2766
2767 (curcol (current-column)
2768 (current-column))
2769
2770 (valid (and (= curcol leftcol)
2771 (not (looking-at (rst-re 'lin-end))))
2772 (and (= curcol leftcol)
2773 (not (looking-at (rst-re 'lin-end))))))
2774 ((>= (point) endm))
2775
2776 (if (if ,first-only
2777 (and valid (not previous))
2778 valid)
2779 ,body-consequent
2780 ,body-alternative)))))
2781
2782;; FIXME: This needs to be refactored. Probably this is simply a function
2783;; applying BODY rather than a macro.
2784(defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2785 "Evaluate BODY for each line in region defined by BEG END.
2786LEFTMOST is set to true if the line is one of the leftmost of the
2787entire paragraph. PARABEGIN is set to true if the line is the
2788first of a paragraph."
2789 (declare (indent 1) (debug (sexp body)))
2790 (destructuring-bind
2791 (beg end parabegin leftmost isleftmost isempty) spec
2792
2793 `(save-excursion
2794 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2795 (endm (copy-marker ,end)))
2796
2797 (do* (;; Iterate lines.
2798 (l (progn (goto-char ,beg) (back-to-indentation))
2799 (progn (forward-line 1) (back-to-indentation)))
2800
2801 (empty-line-previous nil ,isempty)
2802
2803 (,isempty (looking-at (rst-re 'lin-end))
2804 (looking-at (rst-re 'lin-end)))
2805
2806 (,parabegin (not ,isempty)
2807 (and empty-line-previous
2808 (not ,isempty)))
2809
2810 (,isleftmost (and (not ,isempty)
2811 (= (current-column) ,leftmost))
2812 (and (not ,isempty)
2813 (= (current-column) ,leftmost))))
2814 ((>= (point) endm))
2815
2816 (progn ,@body))))))
2817
2818;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2819;; Indentation
2820
2821;; FIXME: At the moment only block comments with leading empty comment line are
2822;; supported. Comment lines with leading comment markup should be also
2823;; supported. May be a customizable option could control which style to
2824;; prefer.
2825
2826(defgroup rst-indent nil "Settings for indentation in reStructuredText.
2827
2828In reStructuredText indentation points are usually determined by
2829preceding lines. Sometimes the syntax allows arbitrary
2830indentation points such as where to start the first line
2831following a directive. These indentation widths can be customized
2832here."
2833 :group 'rst
2834 :package-version '(rst . "1.1.0"))
2835
2836(define-obsolete-variable-alias
2837 'rst-shift-basic-offset 'rst-indent-width "1.0.0")
2838(defcustom rst-indent-width 2
2839 "Indentation when there is no more indentation point given."
2840 :group 'rst-indent
2841 :type '(integer))
2842(rst-testcover-defcustom)
2843
2844(defcustom rst-indent-field 3
2845 "Indentation for first line after a field or 0 to always indent for content."
2846 :group 'rst-indent
2847 :type '(integer))
2848(rst-testcover-defcustom)
2849
2850(defcustom rst-indent-literal-normal 3
2851 "Default indentation for literal block after a markup on an own line."
2852 :group 'rst-indent
2853 :type '(integer))
2854(rst-testcover-defcustom)
2855
2856(defcustom rst-indent-literal-minimized 2
2857 "Default indentation for literal block after a minimized markup."
2858 :group 'rst-indent
2859 :type '(integer))
2860(rst-testcover-defcustom)
2861
2862(defcustom rst-indent-comment 3
2863 "Default indentation for first line of a comment."
2864 :group 'rst-indent
2865 :type '(integer))
2866(rst-testcover-defcustom)
2867
2868;; FIXME: Must consider other tabs:
2869;; * Line blocks
2870;; * Definition lists
2871;; * Option lists
2872(defun rst-line-tabs ()
2873 "Return tabs of the current line or nil for no tab.
2874The list is sorted so the tab where writing continues most likely
2875is the first one. Each tab is of the form (COLUMN . INNER).
2876COLUMN is the column of the tab. INNER is non-nil if this is an
2877inner tab. I.e. a tab which does come from the basic indentation
2878and not from inner alignment points."
2879 (save-excursion
2880 (forward-line 0)
2881 (save-match-data
2882 (unless (looking-at (rst-re 'lin-end))
2883 (back-to-indentation)
2884 ;; Current indentation is always the least likely tab.
2885 (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER)
2886 ;; Push inner tabs more likely to continue writing.
2887 (cond
2888 ;; Item.
2889 ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?"))
2890 (when (match-string 2)
2891 (push (list (match-beginning 2) 0 t) tabs)))
2892 ;; Field.
2893 ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag)
2894 '(:grp "\\S ") "?"))
2895 (unless (zerop rst-indent-field)
2896 (push (list (match-beginning 1) rst-indent-field t) tabs))
2897 (if (match-string 3)
2898 (push (list (match-beginning 3) 0 t) tabs)
2899 (if (zerop rst-indent-field)
2900 (push (list (match-end 2)
2901 (if (string= (match-string 2) "") 1 0)
2902 t) tabs))))
2903 ;; Directive.
2904 ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?"))
2905 (push (list (match-end 1) 0 t) tabs)
2906 (unless (string= (match-string 2) "")
2907 (push (list (match-end 2) 0 t) tabs))
2908 (when (match-string 4)
2909 (push (list (match-beginning 4) 0 t) tabs)))
2910 ;; Footnote or citation definition.
2911 ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?"))
2912 (push (list (match-end 1) 0 t) tabs)
2913 (when (match-string 3)
2914 (push (list (match-beginning 3) 0 t) tabs)))
2915 ;; Comment.
2916 ((looking-at (rst-re 'cmt-sta-1))
2917 (push (list (point) rst-indent-comment t) tabs)))
2918 ;; Start of literal block.
2919 (when (looking-at (rst-re 'lit-sta-2))
2920 (let ((tab0 (first tabs)))
2921 (push (list (first tab0)
2922 (+ (second tab0)
2923 (if (match-string 1)
2924 rst-indent-literal-minimized
2925 rst-indent-literal-normal))
2926 t) tabs)))
2927 (mapcar (lambda (tab)
2928 (goto-char (first tab))
2929 (cons (+ (current-column) (second tab)) (third tab)))
2930 tabs))))))
2931
2932(defun rst-compute-tabs (pt)
2933 "Build the list of possible tabs for all lines above.
2934Search backwards from point PT to build the list of possible
2935tabs. Return a list of tabs sorted by likeliness to continue
2936writing like `rst-line-tabs'. Nearer lines have generally a
2937higher likeliness than farther lines. Return nil if no tab is found
2938in the text above."
2939 (save-excursion
2940 (goto-char pt)
2941 (let (leftmost ; Leftmost column found so far.
2942 innermost ; Leftmost column for inner tab.
2943 tablist)
2944 (while (and (zerop (forward-line -1))
2945 (or (not leftmost)
2946 (> leftmost 0)))
2947 (let* ((tabs (rst-line-tabs))
2948 (leftcol (if tabs (apply 'min (mapcar 'car tabs)))))
2949 (when tabs
2950 ;; Consider only lines indented less or same if not INNERMOST.
2951 (when (or (not leftmost)
2952 (< leftcol leftmost)
2953 (and (not innermost) (= leftcol leftmost)))
2954 (dolist (tab tabs)
2955 (let ((inner (cdr tab))
2956 (newcol (car tab)))
2957 (when (and
2958 (or
2959 (and (not inner)
2960 (or (not leftmost)
2961 (< newcol leftmost)))
2962 (and inner
2963 (or (not innermost)
2964 (< newcol innermost))))
2965 (not (memq newcol tablist)))
2966 (push newcol tablist))))
2967 (setq innermost (if (rst-some (mapcar 'cdr tabs)) ; Has inner.
2968 leftcol
2969 innermost))
2970 (setq leftmost leftcol)))))
2971 (nreverse tablist))))
2972
2973(defun rst-indent-line (&optional dflt)
2974 "Indent current line to next best reStructuredText tab.
2975The next best tab is taken from the tab list returned by
2976`rst-compute-tabs' which is used in a cyclic manner. If the
2977current indentation does not end on a tab use the first one. If
2978the current indentation is on a tab use the next tab. This allows
2979a repeated use of \\[indent-for-tab-command] to cycle through all
2980possible tabs. If no indentation is possible return `noindent' or
2981use DFLT. Return the indentation indented to. When point is in
2982indentation it ends up at its end. Otherwise the point is kept
2983relative to the content."
2984 (let* ((pt (point-marker))
2985 (cur (current-indentation))
2986 (clm (current-column))
2987 (tabs (rst-compute-tabs (point)))
2988 (fnd (rst-position cur tabs))
2989 ind)
2990 (if (and (not tabs) (not dflt))
2991 'noindent
2992 (if (not tabs)
2993 (setq ind dflt)
2994 (if (not fnd)
2995 (setq fnd 0)
2996 (setq fnd (1+ fnd))
2997 (if (>= fnd (length tabs))
2998 (setq fnd 0)))
2999 (setq ind (nth fnd tabs)))
3000 (indent-line-to ind)
3001 (if (> clm cur)
3002 (goto-char pt))
3003 (set-marker pt nil)
3004 ind)))
3005
3006(defun rst-shift-region (beg end cnt)
3007 "Shift region BEG to END by CNT tabs.
3008Shift by one tab to the right (CNT > 0) or left (CNT < 0) or
3009remove all indentation (CNT = 0). A tab is taken from the text
3010above. If no suitable tab is found `rst-indent-width' is used."
3011 (interactive "r\np")
3012 (let ((tabs (sort (rst-compute-tabs beg) (lambda (x y) (<= x y))))
3013 (leftmostcol (rst-find-leftmost-column beg end)))
3014 (when (or (> leftmostcol 0) (> cnt 0))
3015 ;; Apply the indent.
3016 (indent-rigidly
3017 beg end
3018 (if (zerop cnt)
3019 (- leftmostcol)
3020 ;; Find the next tab after the leftmost column.
3021 (let* ((cmp (if (> cnt 0) '> '<))
3022 (tabs (if (> cnt 0) tabs (reverse tabs)))
3023 (len (length tabs))
3024 (dir (rst-signum cnt)) ; Direction to take.
3025 (abs (abs cnt)) ; Absolute number of steps to take.
3026 ;; Get the position of the first tab beyond leftmostcol.
3027 (fnd (lexical-let ((cmp cmp)
3028 (leftmostcol leftmostcol)) ; Create closure.
3029 (rst-position-if (lambda (elt)
3030 (funcall cmp elt leftmostcol))
3031 tabs)))
3032 ;; Virtual position of tab.
3033 (pos (+ (or fnd len) (1- abs)))
3034 (tab (if (< pos len)
3035 ;; Tab exists - use it.
3036 (nth pos tabs)
3037 ;; Column needs to be computed.
3038 (let ((col (+ (or (car (last tabs)) leftmostcol)
3039 ;; Base on last known column.
3040 (* (- pos (1- len)) ; Distance left.
3041 dir ; Direction to take.
3042 rst-indent-width))))
3043 (if (< col 0) 0 col)))))
3044 (- tab leftmostcol)))))))
3045
3046;; FIXME: A paragraph with an (incorrectly) indented second line is not filled
3047;; correctly::
3048;;
3049;; Some start
3050;; continued wrong
3051(defun rst-adaptive-fill ()
3052 "Return fill prefix found at point.
3053Value for `adaptive-fill-function'."
3054 (let ((fnd (if (looking-at adaptive-fill-regexp)
3055 (match-string-no-properties 0))))
3056 (if (save-match-data
3057 (not (string-match comment-start-skip fnd)))
3058 ;; An non-comment prefix is fine.
3059 fnd
3060 ;; Matches a comment - return whitespace instead.
3061 (make-string (-
3062 (save-excursion
3063 (goto-char (match-end 0))
3064 (current-column))
3065 (save-excursion
3066 (goto-char (match-beginning 0))
3067 (current-column))) ? ))))
3068
3069;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3070;; Comments
3071
3072(defun rst-comment-line-break (&optional soft)
3073 "Break line and indent, continuing reStructuredText comment if within one.
3074Value for `comment-line-break-function'. If SOFT use soft
3075newlines as mandated by `comment-line-break-function'."
3076 (if soft
3077 (insert-and-inherit ?\n)
3078 (newline 1))
3079 (save-excursion
3080 (forward-char -1)
3081 (delete-horizontal-space))
3082 (delete-horizontal-space)
3083 (let ((tabs (rst-compute-tabs (point))))
3084 (when tabs
3085 (indent-line-to (car tabs)))))
3086
3087(defun rst-comment-indent ()
3088 "Return indentation for current comment line."
3089 (car (rst-compute-tabs (point))))
3090
3091(defun rst-comment-insert-comment ()
3092 "Insert a comment in the current line."
3093 (rst-indent-line 0)
3094 (insert comment-start))
3095
3096(defun rst-comment-region (beg end &optional arg)
3097 "Comment or uncomment the current region.
3098Region is from from BEG to END. Uncomment if ARG."
3099 (save-excursion
3100 (if (consp arg)
3101 (rst-uncomment-region beg end arg)
3102 (goto-char beg)
3103 (let ((ind (current-indentation))
3104 bol)
3105 (forward-line 0)
3106 (setq bol (point))
3107 (indent-rigidly bol end rst-indent-comment)
3108 (goto-char bol)
3109 (open-line 1)
3110 (indent-line-to ind)
3111 (insert (comment-string-strip comment-start t t))))))
3112
3113(defun rst-uncomment-region (beg end &optional arg)
3114 "Uncomment the current region.
3115Region is from BEG to END. ARG is ignored"
3116 (save-excursion
3117 (let (bol eol)
3118 (goto-char beg)
3119 (forward-line 0)
3120 (setq bol (point))
3121 (forward-line 1)
3122 (setq eol (point))
3123 (indent-rigidly eol end (- rst-indent-comment))
3124 (delete-region bol eol))))
3125
3126;;------------------------------------------------------------------------------
3127
3128;; FIXME: These next functions should become part of a larger effort to redo
3129;; the bullets in bulleted lists. The enumerate would just be one of
3130;; the possible outputs.
3131;;
3132;; FIXME: We need to do the enumeration removal as well.
3133
3134(defun rst-enumerate-region (beg end all)
3135 "Add enumeration to all the leftmost paragraphs in the given region.
3136The region is specified between BEG and END. With ALL,
3137do all lines instead of just paragraphs."
3138 (interactive "r\nP")
3139 (let ((count 0)
3140 (last-insert-len nil))
3141 (rst-iterate-leftmost-paragraphs
3142 beg end (not all)
3143 (let ((ins-string (format "%d. " (incf count))))
3144 (setq last-insert-len (length ins-string))
3145 (insert ins-string))
3146 (insert (make-string last-insert-len ?\ )))))
3147
3148(defun rst-bullet-list-region (beg end all)
3149 "Add bullets to all the leftmost paragraphs in the given region.
3150The region is specified between BEG and END. With ALL,
3151do all lines instead of just paragraphs."
3152 (interactive "r\nP")
3153 (rst-iterate-leftmost-paragraphs
3154 beg end (not all)
3155 (insert (car rst-preferred-bullets) " ")
3156 (insert " ")))
3157
3158;; FIXME: Does not deal with a varying number of digits appropriately.
3159;; FIXME: Does not deal with multiple levels independently.
3160;; FIXME: Does not indent a multiline item correctly.
3161(defun rst-convert-bullets-to-enumeration (beg end)
3162 "Convert the bulleted and enumerated items in the region to enumerated lists.
3163Renumber as necessary. Region is from BEG to END."
3164 (interactive "r")
3165 (let* (;; Find items and convert the positions to markers.
3166 (items (mapcar
3167 (lambda (x)
3168 (cons (copy-marker (car x))
3169 (cdr x)))
3170 (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1))))
3171 (count 1))
3172 (save-excursion
3173 (dolist (x items)
3174 (goto-char (car x))
3175 (looking-at (rst-re 'itmany-beg-1))
3176 (replace-match (format "%d." count) nil nil nil 1)
3177 (incf count)))))
3178
3179;;------------------------------------------------------------------------------
3180
3181(defun rst-line-block-region (rbeg rend &optional pfxarg)
3182 "Toggle line block prefixes for a region.
3183Region is from RBEG to REND. With PFXARG set the empty lines too."
3184 (interactive "r\nP")
3185 (let ((comment-start "| ")
3186 (comment-end "")
3187 (comment-start-skip "| ")
3188 (comment-style 'indent)
3189 (force (not (not pfxarg))))
3190 (rst-iterate-leftmost-paragraphs-2
3191 (rbeg rend parbegin leftmost isleft isempty)
3192 (when (or force (not isempty))
3193 (move-to-column leftmost force)
3194 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
3195 (insert "| ")))))
3196
3197
3198\f
3199;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3200;; Font lock
3201;; =========
3202
3203(require 'font-lock)
3204
3205;; FIXME: The obsolete variables need to disappear.
3206
3207;; The following versions have been done inside Emacs and should not be
3208;; replaced by `:package-version' attributes until a change.
3209
3210(defgroup rst-faces nil "Faces used in Rst Mode."
3211 :group 'rst
3212 :group 'faces
3213 :version "21.1")
3214
3215(defface rst-block '((t :inherit font-lock-keyword-face))
3216 "Face used for all syntax marking up a special block."
3217 :version "24.1"
3218 :group 'rst-faces)
3219
3220(defcustom rst-block-face 'rst-block
3221 "All syntax marking up a special block."
3222 :version "24.1"
3223 :group 'rst-faces
3224 :type '(face))
3225(rst-testcover-defcustom)
3226(make-obsolete-variable 'rst-block-face
3227 "customize the face `rst-block' instead."
3228 "24.1")
3229
3230(defface rst-external '((t :inherit font-lock-type-face))
3231 "Face used for field names and interpreted text."
3232 :version "24.1"
3233 :group 'rst-faces)
3234
3235(defcustom rst-external-face 'rst-external
3236 "Field names and interpreted text."
3237 :version "24.1"
3238 :group 'rst-faces
3239 :type '(face))
3240(rst-testcover-defcustom)
3241(make-obsolete-variable 'rst-external-face
3242 "customize the face `rst-external' instead."
3243 "24.1")
3244
3245(defface rst-definition '((t :inherit font-lock-function-name-face))
3246 "Face used for all other defining constructs."
3247 :version "24.1"
3248 :group 'rst-faces)
3249
3250(defcustom rst-definition-face 'rst-definition
3251 "All other defining constructs."
3252 :version "24.1"
3253 :group 'rst-faces
3254 :type '(face))
3255(rst-testcover-defcustom)
3256(make-obsolete-variable 'rst-definition-face
3257 "customize the face `rst-definition' instead."
3258 "24.1")
3259
3260;; XEmacs compatibility (?).
3261(defface rst-directive (if (boundp 'font-lock-builtin-face)
3262 '((t :inherit font-lock-builtin-face))
3263 '((t :inherit font-lock-preprocessor-face)))
3264 "Face used for directives and roles."
3265 :version "24.1"
3266 :group 'rst-faces)
3267
3268(defcustom rst-directive-face 'rst-directive
3269 "Directives and roles."
3270 :group 'rst-faces
3271 :type '(face))
3272(rst-testcover-defcustom)
3273(make-obsolete-variable 'rst-directive-face
3274 "customize the face `rst-directive' instead."
3275 "24.1")
3276
3277(defface rst-comment '((t :inherit font-lock-comment-face))
3278 "Face used for comments."
3279 :version "24.1"
3280 :group 'rst-faces)
3281
3282(defcustom rst-comment-face 'rst-comment
3283 "Comments."
3284 :version "24.1"
3285 :group 'rst-faces
3286 :type '(face))
3287(rst-testcover-defcustom)
3288(make-obsolete-variable 'rst-comment-face
3289 "customize the face `rst-comment' instead."
3290 "24.1")
3291
3292(defface rst-emphasis1 '((t :inherit italic))
3293 "Face used for simple emphasis."
3294 :version "24.1"
3295 :group 'rst-faces)
3296
3297(defcustom rst-emphasis1-face 'rst-emphasis1
3298 "Simple emphasis."
3299 :version "24.1"
3300 :group 'rst-faces
3301 :type '(face))
3302(rst-testcover-defcustom)
3303(make-obsolete-variable 'rst-emphasis1-face
3304 "customize the face `rst-emphasis1' instead."
3305 "24.1")
3306
3307(defface rst-emphasis2 '((t :inherit bold))
3308 "Face used for double emphasis."
3309 :version "24.1"
3310 :group 'rst-faces)
3311
3312(defcustom rst-emphasis2-face 'rst-emphasis2
3313 "Double emphasis."
3314 :group 'rst-faces
3315 :type '(face))
3316(rst-testcover-defcustom)
3317(make-obsolete-variable 'rst-emphasis2-face
3318 "customize the face `rst-emphasis2' instead."
3319 "24.1")
3320
3321(defface rst-literal '((t :inherit font-lock-string-face))
3322 "Face used for literal text."
3323 :version "24.1"
3324 :group 'rst-faces)
3325
3326(defcustom rst-literal-face 'rst-literal
3327 "Literal text."
3328 :version "24.1"
3329 :group 'rst-faces
3330 :type '(face))
3331(rst-testcover-defcustom)
3332(make-obsolete-variable 'rst-literal-face
3333 "customize the face `rst-literal' instead."
3334 "24.1")
3335
3336(defface rst-reference '((t :inherit font-lock-variable-name-face))
3337 "Face used for references to a definition."
3338 :version "24.1"
3339 :group 'rst-faces)
3340
3341(defcustom rst-reference-face 'rst-reference
3342 "References to a definition."
3343 :version "24.1"
3344 :group 'rst-faces
3345 :type '(face))
3346(rst-testcover-defcustom)
3347(make-obsolete-variable 'rst-reference-face
3348 "customize the face `rst-reference' instead."
3349 "24.1")
3350
3351(defface rst-transition '((t :inherit font-lock-keyword-face))
3352 "Face used for a transition."
3353 :package-version '(rst . "1.3.0")
3354 :group 'rst-faces)
3355
3356(defface rst-adornment '((t :inherit font-lock-keyword-face))
3357 "Face used for the adornment of a section header."
3358 :package-version '(rst . "1.3.0")
3359 :group 'rst-faces)
3360
3361;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3362
3363(dolist (var '(rst-level-face-max rst-level-face-base-color
3364 rst-level-face-base-light
3365 rst-level-face-format-light
3366 rst-level-face-step-light
3367 rst-level-1-face
3368 rst-level-2-face
3369 rst-level-3-face
3370 rst-level-4-face
3371 rst-level-5-face
3372 rst-level-6-face))
3373 (make-obsolete-variable var "customize the faces `rst-level-*' instead."
3374 "24.3"))
3375
3376;; Define faces for the first 6 levels. More levels are possible, however.
3377(defface rst-level-1 '((((background light)) (:background "grey85"))
3378 (((background dark)) (:background "grey15")))
3379 "Default face for section title text at level 1."
3380 :package-version '(rst . "1.4.0"))
3381
3382(defface rst-level-2 '((((background light)) (:background "grey78"))
3383 (((background dark)) (:background "grey22")))
3384 "Default face for section title text at level 2."
3385 :package-version '(rst . "1.4.0"))
3386
3387(defface rst-level-3 '((((background light)) (:background "grey71"))
3388 (((background dark)) (:background "grey29")))
3389 "Default face for section title text at level 3."
3390 :package-version '(rst . "1.4.0"))
3391
3392(defface rst-level-4 '((((background light)) (:background "grey64"))
3393 (((background dark)) (:background "grey36")))
3394 "Default face for section title text at level 4."
3395 :package-version '(rst . "1.4.0"))
3396
3397(defface rst-level-5 '((((background light)) (:background "grey57"))
3398 (((background dark)) (:background "grey43")))
3399 "Default face for section title text at level 5."
3400 :package-version '(rst . "1.4.0"))
3401
3402(defface rst-level-6 '((((background light)) (:background "grey50"))
3403 (((background dark)) (:background "grey50")))
3404 "Default face for section title text at level 6."
3405 :package-version '(rst . "1.4.0"))
3406
3407(defcustom rst-adornment-faces-alist
3408 '((t . rst-transition)
3409 (nil . rst-adornment)
3410 (1 . rst-level-1)
3411 (2 . rst-level-2)
3412 (3 . rst-level-3)
3413 (4 . rst-level-4)
3414 (5 . rst-level-5)
3415 (6 . rst-level-6))
3416 "Faces for the various adornment types.
3417Key is a number (for the section title text of that level
3418starting with 1), t (for transitions) or nil (for section title
3419adornment). If you need levels beyond 6 you have to define faces
3420of your own."
3421 :group 'rst-faces
3422 :type '(alist
3423 :key-type
3424 (choice
3425 (integer :tag "Section level")
3426 (const :tag "transitions" t)
3427 (const :tag "section title adornment" nil))
3428 :value-type (face)))
3429(rst-testcover-defcustom)
3430
3431;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3432
3433(defvar rst-font-lock-keywords
3434 ;; The reST-links in the comments below all relate to sections in
3435 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.
3436 `(;; FIXME: Block markup is not recognized in blocks after explicit markup
3437 ;; start.
3438
3439 ;; Simple `Body Elements`_
3440 ;; `Bullet Lists`_
3441 ;; FIXME: A bullet directly after a field name is not recognized.
3442 (,(rst-re 'lin-beg '(:grp bul-sta))
3443 1 rst-block-face)
3444 ;; `Enumerated Lists`_
3445 (,(rst-re 'lin-beg '(:grp enmany-sta))
3446 1 rst-block-face)
3447 ;; `Definition Lists`_
3448 ;; FIXME: missing.
3449 ;; `Field Lists`_
3450 (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx)
3451 1 rst-external-face)
3452 ;; `Option Lists`_
3453 (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*")
3454 '(:alt "$" (:seq hws-prt "\\{2\\}")))
3455 1 rst-block-face)
3456 ;; `Line Blocks`_
3457 ;; Only for lines containing no more bar - to distinguish from tables.
3458 (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$")
3459 1 rst-block-face)
3460
3461 ;; `Tables`_
3462 ;; FIXME: missing
3463
3464 ;; All the `Explicit Markup Blocks`_
3465 ;; `Footnotes`_ / `Citations`_
3466 (,(rst-re 'lin-beg 'fnc-sta-2)
3467 (1 rst-definition-face)
3468 (2 rst-definition-face))
3469 ;; `Directives`_ / `Substitution Definitions`_
3470 (,(rst-re 'lin-beg 'dir-sta-3)
3471 (1 rst-directive-face)
3472 (2 rst-definition-face)
3473 (3 rst-directive-face))
3474 ;; `Hyperlink Targets`_
3475 (,(rst-re 'lin-beg
3476 '(:grp exm-sta "_" (:alt
3477 (:seq "`" ilcbkqdef-tag "`")
3478 (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":")
3479 'bli-sfx)
3480 1 rst-definition-face)
3481 (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx)
3482 1 rst-definition-face)
3483
3484 ;; All `Inline Markup`_
3485 ;; Most of them may be multiline though this is uninteresting.
3486
3487 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
3488 ;; `Strong Emphasis`_.
3489 (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx)
3490 1 rst-emphasis2-face)
3491 ;; `Emphasis`_
3492 (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx)
3493 1 rst-emphasis1-face)
3494 ;; `Inline Literals`_
3495 (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx)
3496 1 rst-literal-face)
3497 ;; `Inline Internal Targets`_
3498 (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx)
3499 1 rst-definition-face)
3500 ;; `Hyperlink References`_
3501 ;; FIXME: `Embedded URIs`_ not considered.
3502 ;; FIXME: Directly adjacent marked up words are not fontified correctly
3503 ;; unless they are not separated by two spaces: foo_ bar_.
3504 (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`")
3505 (:seq "\\sw" (:alt "\\sw" "-") "+\\sw"))
3506 "__?") 'ilm-sfx)
3507 1 rst-reference-face)
3508 ;; `Interpreted Text`_
3509 (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?")
3510 '(:grp "`" ilcbkq-tag "`")
3511 '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx)
3512 (1 rst-directive-face)
3513 (2 rst-external-face)
3514 (3 rst-directive-face))
3515 ;; `Footnote References`_ / `Citation References`_
3516 (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx)
3517 1 rst-reference-face)
3518 ;; `Substitution References`_
3519 ;; FIXME: References substitutions like |this|_ or |this|__ are not
3520 ;; fontified correctly.
3521 (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx)
3522 1 rst-reference-face)
3523 ;; `Standalone Hyperlinks`_
3524 ;; FIXME: This takes it easy by using a whitespace as delimiter.
3525 (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx)
3526 1 rst-definition-face)
3527 (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx)
3528 1 rst-definition-face)
3529
3530 ;; Do all block fontification as late as possible so 'append works.
3531
3532 ;; Sections_ / Transitions_
3533 ;; For sections this is multiline.
3534 (,(rst-re 'ado-beg-2-1)
3535 (rst-font-lock-handle-adornment-matcher
3536 (rst-font-lock-handle-adornment-pre-match-form
3537 (match-string-no-properties 1) (match-end 1))
3538 nil
3539 (1 (cdr (assoc nil rst-adornment-faces-alist)) append t)
3540 (2 (cdr (assoc rst-font-lock-adornment-level
3541 rst-adornment-faces-alist)) append t)
3542 (3 (cdr (assoc nil rst-adornment-faces-alist)) append t)))
3543
3544 ;; FIXME: FACESPEC could be used instead of ordinary faces to set
3545 ;; properties on comments and literal blocks so they are *not*
3546 ;; inline fontified. See (elisp)Search-based Fontification.
3547
3548 ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el`
3549 ;; and other V24 modes. May make `font-lock-extend-region`
3550 ;; superfluous.
3551
3552 ;; `Comments`_
3553 ;; This is multiline.
3554 (,(rst-re 'lin-beg 'cmt-sta-1)
3555 (1 rst-comment-face)
3556 (rst-font-lock-find-unindented-line-match
3557 (rst-font-lock-find-unindented-line-limit (match-end 1))
3558 nil
3559 (0 rst-comment-face append)))
3560 (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$")
3561 (1 rst-comment-face)
3562 (2 rst-comment-face)
3563 (rst-font-lock-find-unindented-line-match
3564 (rst-font-lock-find-unindented-line-limit 'next)
3565 nil
3566 (0 rst-comment-face append)))
3567
3568 ;; FIXME: This is not rendered as comment::
3569 ;; .. .. list-table::
3570 ;; :stub-columns: 1
3571 ;; :header-rows: 1
3572
3573 ;; FIXME: This is rendered wrong::
3574 ;;
3575 ;; xxx yyy::
3576 ;;
3577 ;; ----|> KKKKK <|----
3578 ;; / \
3579 ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|-
3580 ;; | | | |
3581 ;; | | | |
3582 ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB
3583 ;;
3584 ;; Indentation needs to be taken from the line with the ``::`` and not from
3585 ;; the first content line.
3586
3587 ;; `Indented Literal Blocks`_
3588 ;; This is multiline.
3589 (,(rst-re 'lin-beg 'lit-sta-2)
3590 (2 rst-block-face)
3591 (rst-font-lock-find-unindented-line-match
3592 (rst-font-lock-find-unindented-line-limit t)
3593 nil
3594 (0 rst-literal-face append)))
3595
3596 ;; FIXME: `Quoted Literal Blocks`_ missing.
3597 ;; This is multiline.
3598
3599 ;; `Doctest Blocks`_
3600 ;; FIXME: This is wrong according to the specification:
3601 ;;
3602 ;; Doctest blocks are text blocks which begin with ">>> ", the Python
3603 ;; interactive interpreter main prompt, and end with a blank line.
3604 ;; Doctest blocks are treated as a special case of literal blocks,
3605 ;; without requiring the literal block syntax. If both are present, the
3606 ;; literal block syntax takes priority over Doctest block syntax:
3607 ;;
3608 ;; This is an ordinary paragraph.
3609 ;;
3610 ;; >>> print 'this is a Doctest block'
3611 ;; this is a Doctest block
3612 ;;
3613 ;; The following is a literal block::
3614 ;;
3615 ;; >>> This is not recognized as a doctest block by
3616 ;; reStructuredText. It *will* be recognized by the doctest
3617 ;; module, though!
3618 ;;
3619 ;; Indentation is not required for doctest blocks.
3620 (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+"))
3621 (1 rst-block-face)
3622 (2 rst-literal-face)))
3623 "Keywords to highlight in rst mode.")
3624
3625(defvar font-lock-beg)
3626(defvar font-lock-end)
3627
3628(defun rst-font-lock-extend-region ()
3629 "Extend the font-lock region if it might be in a multi-line construct.
3630Return non-nil if so. Font-lock region is from `font-lock-beg'
3631to `font-lock-end'."
3632 (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end)))
3633 (when r
3634 (setq font-lock-beg (car r))
3635 (setq font-lock-end (cdr r))
3636 t)))
3637
3638(defun rst-font-lock-extend-region-internal (beg end)
3639 "Check the region BEG / END for being in the middle of a multi-line construct.
3640Return nil if not or a cons with new values for BEG / END"
3641 (let ((nbeg (rst-font-lock-extend-region-extend beg -1))
3642 (nend (rst-font-lock-extend-region-extend end 1)))
3643 (if (or nbeg nend)
3644 (cons (or nbeg beg) (or nend end)))))
3645
3646(defun rst-forward-line (&optional n)
3647 "Like `forward-line' but always end up in column 0 and return accordingly.
3648Move N lines forward just as `forward-line'."
3649 (let ((moved (forward-line n)))
3650 (if (bolp)
3651 moved
3652 (forward-line 0)
3653 (- moved (rst-signum n)))))
3654
3655;; FIXME: If a single line is made a section header by `rst-adjust' the header
3656;; is not always fontified immediately.
3657(defun rst-font-lock-extend-region-extend (pt dir)
3658 "Extend the region starting at point PT and extending in direction DIR.
3659Return extended point or nil if not moved."
3660 ;; There are many potential multiline constructs but there are two groups
3661 ;; which are really relevant. The first group consists of
3662 ;;
3663 ;; * comment lines without leading explicit markup tag and
3664 ;;
3665 ;; * literal blocks following "::"
3666 ;;
3667 ;; which are both indented. Thus indentation is the first thing recognized
3668 ;; here. The second criteria is an explicit markup tag which may be a comment
3669 ;; or a double colon at the end of a line.
3670 ;;
3671 ;; The second group consists of the adornment cases.
3672 (if (not (get-text-property pt 'font-lock-multiline))
3673 ;; Move only if we don't start inside a multiline construct already.
3674 (save-excursion
3675 (let (;; Non-empty non-indented line, explicit markup tag or literal
3676 ;; block tag.
3677 (stop-re (rst-re '(:alt "[^ \t\n]"
3678 (:seq hws-tag exm-tag)
3679 (:seq ".*" dcl-tag lin-end)))))
3680 ;; The comments below are for dir == -1 / dir == 1.
3681 (goto-char pt)
3682 (forward-line 0)
3683 (setq pt (point))
3684 (while (and (not (looking-at stop-re))
3685 (zerop (rst-forward-line dir)))) ; try previous / next
3686 ; line if it exists.
3687 (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline /
3688 ; overline.
3689 (if (zerop (rst-forward-line dir))
3690 (if (looking-at (rst-re 'ttl-beg)) ; title found, i.e.
3691 ; underline / overline
3692 ; found.
3693 (if (zerop (rst-forward-line dir))
3694 (if (not
3695 (looking-at (rst-re 'ado-beg-2-1))) ; no
3696 ; overline /
3697 ; underline.
3698 (rst-forward-line (- dir)))) ; step back to title
3699 ; / adornment.
3700 (if (< dir 0) ; keep downward adornment.
3701 (rst-forward-line (- dir))))) ; step back to adornment.
3702 (if (looking-at (rst-re 'ttl-beg)) ; may be a title.
3703 (if (zerop (rst-forward-line dir))
3704 (if (not
3705 (looking-at (rst-re 'ado-beg-2-1))) ; no overline /
3706 ; underline.
3707 (rst-forward-line (- dir)))))) ; step back to line.
3708 (if (not (= (point) pt))
3709 (point))))))
3710
3711;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3712;; Indented blocks
3713
3714(defun rst-forward-indented-block (&optional column limit)
3715 "Move forward across one indented block.
3716Find the next non-empty line which is not indented at least to COLUMN (defaults
3717to the column of the point). Moves point to first character of this line or the
3718first empty line immediately before it and returns that position. If there is
3719no such line before LIMIT (defaults to the end of the buffer) returns nil and
3720point is not moved."
3721 (interactive)
3722 (let ((clm (or column (current-column)))
3723 (start (point))
3724 fnd beg cand)
3725 (if (not limit)
3726 (setq limit (point-max)))
3727 (save-match-data
3728 (while (and (not fnd) (< (point) limit))
3729 (forward-line 1)
3730 (when (< (point) limit)
3731 (setq beg (point))
3732 (if (looking-at (rst-re 'lin-end))
3733 (setq cand (or cand beg)) ; An empty line is a candidate.
3734 (move-to-column clm)
3735 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3736 ;; useful way - though it is not clear what this should mean
3737 ;; at all.
3738 (if (string-match
3739 (rst-re 'linemp-tag)
3740 (buffer-substring-no-properties beg (point)))
3741 (setq cand nil) ; An indented line resets a candidate.
3742 (setq fnd (or cand beg)))))))
3743 (goto-char (or fnd start))
3744 fnd))
3745
3746(defvar rst-font-lock-find-unindented-line-begin nil
3747 "Beginning of the match if `rst-font-lock-find-unindented-line-end'.")
3748
3749(defvar rst-font-lock-find-unindented-line-end nil
3750 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
3751Also used as a trigger for
3752`rst-font-lock-find-unindented-line-match'.")
3753
3754(defun rst-font-lock-find-unindented-line-limit (ind-pnt)
3755 "Find the next unindented line relative to indentation at IND-PNT.
3756Return this point, the end of the buffer or nil if nothing found.
3757If IND-PNT is `next' take the indentation from the next line if
3758this is not empty and indented more than the current one. If
3759IND-PNT is non-nil but not a number take the indentation from the
3760next non-empty line if this is indented more than the current
3761one."
3762 (setq rst-font-lock-find-unindented-line-begin ind-pnt)
3763 (setq rst-font-lock-find-unindented-line-end
3764 (save-excursion
3765 (when (not (numberp ind-pnt))
3766 ;; Find indentation point in next line if any.
3767 (setq ind-pnt
3768 ;; FIXME: Should be refactored to two different functions
3769 ;; giving their result to this function, may be
3770 ;; integrated in caller.
3771 (save-match-data
3772 (let ((cur-ind (current-indentation)))
3773 (if (eq ind-pnt 'next)
3774 (when (and (zerop (forward-line 1))
3775 (< (point) (point-max)))
3776 ;; Not at EOF.
3777 (setq rst-font-lock-find-unindented-line-begin
3778 (point))
3779 (when (and (not (looking-at (rst-re 'lin-end)))
3780 (> (current-indentation) cur-ind))
3781 ;; Use end of indentation if non-empty line.
3782 (looking-at (rst-re 'hws-tag))
3783 (match-end 0)))
3784 ;; Skip until non-empty line or EOF.
3785 (while (and (zerop (forward-line 1))
3786 (< (point) (point-max))
3787 (looking-at (rst-re 'lin-end))))
3788 (when (< (point) (point-max))
3789 ;; Not at EOF.
3790 (setq rst-font-lock-find-unindented-line-begin
3791 (point))
3792 (when (> (current-indentation) cur-ind)
3793 ;; Indentation bigger than line of departure.
3794 (looking-at (rst-re 'hws-tag))
3795 (match-end 0))))))))
3796 (when ind-pnt
3797 (goto-char ind-pnt)
3798 (or (rst-forward-indented-block nil (point-max))
3799 (point-max))))))
3800
3801(defun rst-font-lock-find-unindented-line-match (limit)
3802 "Set the match found earlier if match were found.
3803Match has been found by
3804`rst-font-lock-find-unindented-line-limit' the first time called
3805or no match is found. Return non-nil if match was found. LIMIT
3806is not used but mandated by the caller."
3807 (when rst-font-lock-find-unindented-line-end
3808 (set-match-data
3809 (list rst-font-lock-find-unindented-line-begin
3810 rst-font-lock-find-unindented-line-end))
3811 (put-text-property rst-font-lock-find-unindented-line-begin
3812 rst-font-lock-find-unindented-line-end
3813 'font-lock-multiline t)
3814 ;; Make sure this is called only once.
3815 (setq rst-font-lock-find-unindented-line-end nil)
3816 t))
3817
3818;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3819;; Adornments
3820
3821(defvar rst-font-lock-adornment-level nil
3822 "Storage for `rst-font-lock-handle-adornment-matcher'.
3823Either section level of the current adornment or t for a transition.")
3824
3825(defun rst-adornment-level (key)
3826 "Return section level for adornment KEY.
3827KEY is the first element of the return list of
3828`rst-classify-adornment'. If KEY is not a cons return it. If KEY is found
3829in the hierarchy return its level. Otherwise return a level one
3830beyond the existing hierarchy."
3831 (if (not (consp key))
3832 key
3833 (let* ((hier (rst-get-hierarchy))
3834 (char (car key))
3835 (style (cdr key)))
3836 (1+ (or (lexical-let ((char char)
3837 (style style)
3838 (hier hier)) ; Create closure.
3839 (rst-position-if (lambda (elt)
3840 (and (equal (car elt) char)
3841 (equal (cadr elt) style))) hier))
3842 (length hier))))))
3843
3844(defvar rst-font-lock-adornment-match nil
3845 "Storage for match for current adornment.
3846Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used
3847as a trigger for `rst-font-lock-handle-adornment-matcher'.")
3848
3849(defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end)
3850 "Determine limit for adornments.
3851Determine all things necessary for font-locking section titles
3852and transitions and put the result to
3853`rst-font-lock-adornment-match' and
3854`rst-font-lock-adornment-level'. ADO is the complete adornment
3855matched. ADO-END is the point where ADO ends. Return the point
3856where the whole adorned construct ends.
3857
3858Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'."
3859 (let ((ado-data (rst-classify-adornment ado ado-end)))
3860 (if (not ado-data)
3861 (setq rst-font-lock-adornment-level nil
3862 rst-font-lock-adornment-match nil)
3863 (setq rst-font-lock-adornment-level
3864 (rst-adornment-level (car ado-data)))
3865 (setq rst-font-lock-adornment-match (cdr ado-data))
3866 (goto-char (nth 1 ado-data)) ; Beginning of construct.
3867 (nth 2 ado-data)))) ; End of construct.
3868
3869(defun rst-font-lock-handle-adornment-matcher (limit)
3870 "Set the match found earlier if match were found.
3871Match has been found by
3872`rst-font-lock-handle-adornment-pre-match-form' the first time
3873called or no match is found. Return non-nil if match was found.
3874
3875Called as a MATCHER in the sense of `font-lock-keywords'.
3876LIMIT is not used but mandated by the caller."
3877 (let ((match rst-font-lock-adornment-match))
3878 ;; May run only once - enforce this.
3879 (setq rst-font-lock-adornment-match nil)
3880 (when match
3881 (set-match-data match)
3882 (goto-char (match-end 0))
3883 (put-text-property (match-beginning 0) (match-end 0)
3884 'font-lock-multiline t)
3885 t)))
3886
3887\f
3888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3889;; Compilation
3890
3891(defgroup rst-compile nil
3892 "Settings for support of conversion of reStructuredText
3893document with \\[rst-compile]."
3894 :group 'rst
3895 :version "21.1")
3896
3897(defcustom rst-compile-toolsets
3898 `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
3899 ".html" nil)
3900 (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
3901 ".tex" nil)
3902 (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
3903 "rst2newlatex")
3904 ".tex" nil)
3905 (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
3906 "rst2pseudoxml")
3907 ".xml" nil)
3908 (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
3909 ".xml" nil)
3910 (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
3911 ".pdf" nil)
3912 (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
3913 ".html" nil))
3914 "Table describing the command to use for each tool-set.
3915An association list of the tool-set to a list of the (command to use,
3916extension of produced filename, options to the tool (nil or a
3917string)) to be used for converting the document."
3918 ;; FIXME: These are not options but symbols which may be referenced by
3919 ;; `rst-compile-*-toolset` below. The `:validate' keyword of
3920 ;; `defcustom' may help to define this properly in newer Emacs
3921 ;; versions (> 23.1).
3922 :type '(alist :options (html latex newlatex pseudoxml xml pdf s5)
3923 :key-type symbol
3924 :value-type (list :tag "Specification"
3925 (file :tag "Command")
3926 (string :tag "File extension")
3927 (choice :tag "Command options"
3928 (const :tag "No options" nil)
3929 (string :tag "Options"))))
3930 :group 'rst
3931 :package-version "1.2.0")
3932(rst-testcover-defcustom)
3933
3934;; FIXME: Must be `defcustom`.
3935(defvar rst-compile-primary-toolset 'html
3936 "The default tool-set for `rst-compile'.")
3937
3938;; FIXME: Must be `defcustom`.
3939(defvar rst-compile-secondary-toolset 'latex
3940 "The default tool-set for `rst-compile' with a prefix argument.")
3941
3942(defun rst-compile-find-conf ()
3943 "Look for the configuration file in the parents of the current path."
3944 (interactive)
3945 (let ((file-name "docutils.conf")
3946 (buffer-file (buffer-file-name)))
3947 ;; Move up in the dir hierarchy till we find a change log file.
3948 (let* ((dir (file-name-directory buffer-file))
3949 (prevdir nil))
3950 (while (and (or (not (string= dir prevdir))
3951 (setq dir nil)
3952 nil)
3953 (not (file-exists-p (concat dir file-name))))
3954 ;; Move up to the parent dir and try again.
3955 (setq prevdir dir)
3956 (setq dir (expand-file-name (file-name-directory
3957 (directory-file-name
3958 (file-name-directory dir))))))
3959 (or (and dir (concat dir file-name)) nil))))
3960
3961(require 'compile)
3962
3963(defun rst-compile (&optional use-alt)
3964 "Compile command to convert reST document into some output file.
3965Attempts to find configuration file, if it can, overrides the
3966options. There are two commands to choose from, with USE-ALT,
3967select the alternative tool-set."
3968 (interactive "P")
3969 ;; Note: maybe we want to check if there is a Makefile too and not do anything
3970 ;; if that is the case. I dunno.
3971 (let* ((toolset (cdr (assq (if use-alt
3972 rst-compile-secondary-toolset
3973 rst-compile-primary-toolset)
3974 rst-compile-toolsets)))
3975 (command (car toolset))
3976 (extension (cadr toolset))
3977 (options (caddr toolset))
3978 (conffile (rst-compile-find-conf))
3979 (bufname (file-name-nondirectory buffer-file-name))
3980 (outname (file-name-sans-extension bufname)))
3981
3982 ;; Set compile-command before invocation of compile.
3983 (set (make-local-variable 'compile-command)
3984 (mapconcat 'identity
3985 (list command
3986 (or options "")
3987 (if conffile
3988 (concat "--config=" (shell-quote-argument conffile))
3989 "")
3990 (shell-quote-argument bufname)
3991 (shell-quote-argument (concat outname extension)))
3992 " "))
3993
3994 ;; Invoke the compile command.
3995 (if (or compilation-read-command use-alt)
3996 (call-interactively 'compile)
3997 (compile compile-command))))
3998
3999(defun rst-compile-alt-toolset ()
4000 "Compile command with the alternative tool-set."
4001 (interactive)
4002 (rst-compile t))
4003
4004(defun rst-compile-pseudo-region ()
4005 "Show pseudo-XML rendering.
4006Rendering is done of the current active region, or of the entire
4007buffer, if the region is not selected."
4008 ;; FIXME: The region should be given interactively.
4009 (interactive)
4010 (with-output-to-temp-buffer "*pseudoxml*"
4011 (shell-command-on-region
4012 (if mark-active (region-beginning) (point-min))
4013 (if mark-active (region-end) (point-max))
4014 (cadr (assq 'pseudoxml rst-compile-toolsets))
4015 standard-output)))
4016
4017;; FIXME: Should be `defcustom`.
4018(defvar rst-pdf-program "xpdf"
4019 "Program used to preview PDF files.")
4020
4021(defun rst-compile-pdf-preview ()
4022 "Convert the document to a PDF file and launch a preview program."
4023 (interactive)
4024 (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf"))
4025 (command (format "%s %s %s && %s %s ; rm %s"
4026 (cadr (assq 'pdf rst-compile-toolsets))
4027 buffer-file-name tmp-filename
4028 rst-pdf-program tmp-filename tmp-filename)))
4029 (start-process-shell-command "rst-pdf-preview" nil command)
4030 ;; Note: you could also use (compile command) to view the compilation
4031 ;; output.
4032 ))
4033
4034;; FIXME: Should be `defcustom` or use something like `browse-url`.
4035(defvar rst-slides-program "firefox"
4036 "Program used to preview S5 slides.")
4037
4038(defun rst-compile-slides-preview ()
4039 "Convert the document to an S5 slide presentation and launch a preview program."
4040 (interactive)
4041 (let* ((tmp-filename (make-temp-file "rst_el" nil ".html"))
4042 (command (format "%s %s %s && %s %s ; rm %s"
4043 (cadr (assq 's5 rst-compile-toolsets))
4044 buffer-file-name tmp-filename
4045 rst-slides-program tmp-filename tmp-filename)))
4046 (start-process-shell-command "rst-slides-preview" nil command)
4047 ;; Note: you could also use (compile command) to view the compilation
4048 ;; output.
4049 ))
4050
4051\f
4052;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4053;; Imenu support.
4054
4055;; FIXME: Integrate this properly. Consider a key binding.
4056
4057;; Based on code from Masatake YAMATO <yamato@redhat.com>.
4058
4059(defun rst-imenu-find-adornments-for-position (adornments pos)
4060 "Find adornments cell in ADORNMENTS for position POS."
4061 (let ((a nil))
4062 (while adornments
4063 (if (and (car adornments)
4064 (eq (car (car adornments)) pos))
4065 (setq a adornments
4066 adornments nil)
4067 (setq adornments (cdr adornments))))
4068 a))
4069
4070(defun rst-imenu-convert-cell (elt adornments)
4071 "Convert a cell ELT in a tree returned from `rst-section-tree' to imenu index.
4072ADORNMENTS is used as hint information for conversion."
4073 (let* ((kar (car elt))
4074 (kdr (cdr elt))
4075 (title (car kar)))
4076 (if kar
4077 (let* ((p (marker-position (cadr kar)))
4078 (adornments
4079 (rst-imenu-find-adornments-for-position adornments p))
4080 (a (car adornments))
4081 (adornments (cdr adornments))
4082 ;; FIXME: Overline adornment characters need to be in front so
4083 ;; they become visible even for long title lines. May be
4084 ;; an additional level number is also useful.
4085 (title (format "%s%s%s"
4086 (make-string (1+ (nth 3 a)) (nth 1 a))
4087 title
4088 (if (eq (nth 2 a) 'simple)
4089 ""
4090 (char-to-string (nth 1 a))))))
4091 (cons title
4092 (if (null kdr)
4093 p
4094 (cons
4095 ;; A bit ugly but this make which-func happy.
4096 (cons title p)
4097 (mapcar (lambda (elt0)
4098 (rst-imenu-convert-cell elt0 adornments))
4099 kdr)))))
4100 nil)))
4101
4102;; FIXME: Document title and subtitle need to be handled properly. They should
4103;; get an own "Document" top level entry.
4104(defun rst-imenu-create-index ()
4105 "Create index for imenu.
4106Return as described for `imenu--index-alist'."
4107 (rst-reset-section-caches)
4108 (let ((tree (rst-section-tree))
4109 ;; Translate line notation to point notation.
4110 (adornments (save-excursion
4111 (mapcar (lambda (ln-ado)
4112 (cons (progn
4113 (goto-char (point-min))
4114 (forward-line (1- (car ln-ado)))
4115 ;; FIXME: Need to consider
4116 ;; `imenu-use-markers' here?
4117 (point))
4118 (cdr ln-ado)))
4119 (rst-find-all-adornments)))))
4120 (delete nil (mapcar (lambda (elt)
4121 (rst-imenu-convert-cell elt adornments))
4122 tree))))
4123
4124\f
4125;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4126;; Generic text functions that are more convenient than the defaults.
4127
4128;; FIXME: Unbound command - should be bound or removed.
4129(defun rst-replace-lines (fromchar tochar)
4130 "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR."
4131 (interactive "\
4132cSearch for flush-left lines of char:
4133cand replace with char: ")
4134 (save-excursion
4135 (let ((searchre (rst-re "^" fromchar "+\\( *\\)$"))
4136 (found 0))
4137 (while (search-forward-regexp searchre nil t)
4138 (setq found (1+ found))
4139 (goto-char (match-beginning 1))
4140 (let ((width (current-column)))
4141 (rst-delete-entire-line)
4142 (insert-char tochar width)))
4143 (message (format "%d lines replaced." found)))))
4144
4145;; FIXME: Unbound command - should be bound or removed.
4146(defun rst-join-paragraph ()
4147 "Join lines in current paragraph into one line, removing end-of-lines."
4148 (interactive)
4149 (let ((fill-column 65000)) ; Some big number.
4150 (call-interactively 'fill-paragraph)))
4151
4152;; FIXME: Unbound command - should be bound or removed.
4153(defun rst-force-fill-paragraph ()
4154 "Fill paragraph at point, first joining the paragraph's lines into one.
4155This is useful for filling list item paragraphs."
4156 (interactive)
4157 (rst-join-paragraph)
4158 (fill-paragraph nil))
4159
4160
4161;; FIXME: Unbound command - should be bound or removed.
4162;; Generic character repeater function.
4163;; For sections, better to use the specialized function above, but this can
4164;; be useful for creating separators.
4165(defun rst-repeat-last-character (use-next)
4166 "Fill the current line using the last character on the current line.
4167Fill up to the length of the preceding line or up to
4168`fill-column' if preceding line is empty.
4169
4170If USE-NEXT, use the next line rather than the preceding line.
4171
4172If the current line is longer than the desired length, shave the characters off
4173the current line to fit the desired length.
4174
4175As an added convenience, if the command is repeated immediately, the alternative
4176column is used (fill-column vs. end of previous/next line)."
4177 (interactive "P")
4178 (let* ((curcol (current-column))
4179 (curline (+ (count-lines (point-min) (point))
4180 (if (zerop curcol) 1 0)))
4181 (lbp (line-beginning-position 0))
4182 (prevcol (if (and (= curline 1) (not use-next))
4183 fill-column
4184 (save-excursion
4185 (forward-line (if use-next 1 -1))
4186 (end-of-line)
4187 (skip-chars-backward " \t" lbp)
4188 (let ((cc (current-column)))
4189 (if (zerop cc) fill-column cc)))))
4190 (rightmost-column
4191 (cond ((equal last-command 'rst-repeat-last-character)
4192 (if (= curcol fill-column) prevcol fill-column))
4193 (t (save-excursion
4194 (if (zerop prevcol) fill-column prevcol))))))
4195 (end-of-line)
4196 (if (> (current-column) rightmost-column)
4197 ;; Shave characters off the end.
4198 (delete-region (- (point)
4199 (- (current-column) rightmost-column))
4200 (point))
4201 ;; Fill with last characters.
4202 (insert-char (preceding-char)
4203 (- rightmost-column (current-column))))))
4204
4205\f
4206
4207;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex
4208;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc
4209;; LocalWords: XML PNT propertized
4210
4211;; Local Variables:
4212;; sentence-end-double-space: t
4213;; End:
4214
4215(provide 'rst)
4216
4217;;; rst.el ends here