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