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