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