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