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