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