1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Maintainer: Stefan Merten <smerten@oekonux.de>
6 ;; Author: Martin Blais <blais@furius.ca>,
7 ;; David Goodger <goodger@python.org>,
8 ;; Wei-Wei Guo <wwguocn@gmail.com>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; This package provides major mode rst-mode, which supports documents marked
28 ;; up using the reStructuredText format. Support includes font locking as well
29 ;; as a lot of convenience functions for editing. It does this by defining a
30 ;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode. This
31 ;; package also contains:
33 ;; - Functions to automatically adjust and cycle the section underline
35 ;; - A mode that displays the table of contents and allows you to jump anywhere
37 ;; - Functions to insert and automatically update a TOC in your source
39 ;; - Function to insert list, processing item bullets and enumerations
41 ;; - Font-lock highlighting of most reStructuredText structures;
42 ;; - Indentation and filling according to reStructuredText syntax;
43 ;; - Cursor movement according to reStructuredText syntax;
44 ;; - Some other convenience functions.
46 ;; See the accompanying document in the docutils documentation about
47 ;; the contents of this package and how to use it.
49 ;; For more information about reStructuredText, see
50 ;; http://docutils.sourceforge.net/rst.html
52 ;; For full details on how to use the contents of this file, see
53 ;; http://docutils.sourceforge.net/docs/user/emacs.html
56 ;; There are a number of convenient keybindings provided by rst-mode.
57 ;; For more on bindings, see rst-mode-map below. There are also many variables
58 ;; that can be customized, look for defcustom in this file.
60 ;; If you use the table-of-contents feature, you may want to add a hook to
61 ;; update the TOC automatically everytime you adjust a section title::
63 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
65 ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
66 ;; off syntax highlighting to rst-mode, you can use the following::
68 ;; (setq font-lock-global-modes '(not rst-mode ...))
72 ;; Customization is done by customizable variables contained in customization
73 ;; group "rst" and subgroups. Group "rst" is contained in the "wp" group.
78 ;; The latest release of this file lies in the docutils source code repository:
79 ;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el
83 ;; Add the following lines to your `.emacs' file:
87 ;; If you are using `.txt' as a standard extension for reST files as
88 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
89 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
90 ;; provides to set the major mode automatically. For instance you may use::
92 ;; .. -*- mode: rst -*-
94 ;; in the very first line of your file. The following code is useful if you
95 ;; want automatically enter rst-mode from any file with compatible extensions:
97 ;; (setq auto-mode-alist
98 ;; (append '(("\\.txt$" . rst-mode)
99 ;; ("\\.rst$" . rst-mode)
100 ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
107 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
110 (defun rst-extract-version (delim-re head-re re tail-re var &optional default)
111 "Return the version matching RE after regex DELIM-RE and HEAD-RE
112 and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match"
114 (concat delim-re head-re "\\(" re "\\)" tail-re delim-re)
119 ;; Use CVSHeader to really get information from CVS and not other version
121 (defconst rst-cvs-header
122 "$CVSHeader: sm/rst_el/rst.el,v 1.257 2012-04-29 15:01:17 stefan Exp $")
123 (defconst rst-cvs-rev
124 (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
125 " .*" rst-cvs-header "0.0")
126 "The CVS revision of this file. CVS revision is the development revision.")
127 (defconst rst-cvs-timestamp
128 (rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
129 "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
130 rst-cvs-header "1970-01-01 00:00:00")
131 "The CVS timestamp of this file.")
133 ;; Use LastChanged... to really get information from SVN
134 (defconst rst-svn-rev
135 (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
136 "$LastChangedRevision: 7399 $")
137 "The SVN revision of this file.
138 SVN revision is the upstream (docutils) revision.")
139 (defconst rst-svn-timestamp
140 (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " "
141 "$LastChangedDate: 2012-04-29 17:01:05 +0200 (Sun, 29 Apr 2012) $")
142 "The SVN timestamp of this file.")
144 ;; Maintained by the release process
145 (defconst rst-official-version
146 (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
147 "%OfficialVersion: 1.2.1 %")
148 "Official version of the package.")
149 (defconst rst-official-cvs-rev
150 (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
151 "%Revision: 1.256 %")
152 "CVS revision of this file in the official version.")
154 (defconst rst-version
155 (if (equal rst-official-cvs-rev rst-cvs-rev)
157 (format "%s (development %s [%s])" rst-official-version
158 rst-cvs-rev rst-cvs-timestamp))
160 Starts with the current official version. For developer versions
161 in parentheses follows the development revision and the timestamp.")
163 (defconst rst-package-emacs-version-alist
169 (unless (assoc rst-official-version rst-package-emacs-version-alist)
170 (error "Version %s not listed in `rst-package-emacs-version-alist'"
173 (add-to-list 'customize-package-emacs-version-alist
174 (cons 'ReST rst-package-emacs-version-alist))
176 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
177 ;; Initialize customization
180 (defgroup rst nil "Support for reStructuredText documents."
183 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
186 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
187 ;; Facilities for regular expressions used everywhere
189 ;; The trailing numbers in the names give the number of referenceable regex
190 ;; groups contained in the regex
192 ;; Used to be customizable but really is not customizable but fixed by the reST
194 (defconst rst-bullets
195 ;; Sorted so they can form a character class when concatenated
196 '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043)
197 "List of all possible bullet characters for bulleted lists.")
199 (defconst rst-uri-schemes
200 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
201 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
202 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
203 "Supported URI schemes.")
205 (defconst rst-adornment-chars
206 ;; Sorted so they can form a character class when concatenated
208 ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
211 "Characters which may be used in adornments for sections and transitions.")
213 (defconst rst-max-inline-length
215 "Maximum length of inline markup to recognize.")
217 (defconst rst-re-alist-def
218 ;; `*-beg' matches * at the beginning of a line
219 ;; `*-end' matches * at the end of a line
220 ;; `*-prt' matches a part of *
222 ;; `*-sta' matches the start of * which may be followed by respective content
223 ;; `*-pfx' matches the delimiter left of *
224 ;; `*-sfx' matches the delimiter right of *
225 ;; `*-hlp' helper for *
227 ;; A trailing number says how many referenceable groups are contained.
230 ;; Horizontal white space (`hws')
232 (hws-tag hws-prt "*") ; Optional sequence of horizontal white space
233 (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space
236 (lin-beg "^" hws-tag) ; Beginning of a possibly indented line
237 (lin-end hws-tag "$") ; End of a line with optional trailing white space
238 (linemp-tag "^" hws-tag "$") ; Empty line with optional white space
240 ;; Various tags and parts
241 (ell-tag "\\.\\.\\.") ; Ellipsis
242 (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet
243 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag
244 (num-prt "[0-9]") ; A number enumerator part
245 (num-tag num-prt "+") ; A number enumerator tag
246 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part
247 (rom-tag rom-prt "+") ; A roman enumerator tag
248 (aut-tag "#") ; An automatic enumerator tag
249 (dcl-tag "::") ; Double colon
251 ;; Block lead in (`bli')
252 (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
256 (bul-sta bul-tag bli-sfx) ; Start of a bulleted item
258 ;; Explicit markup tag (`exm')
260 (exm-sta exm-tag hws-sta)
261 (exm-beg lin-beg exm-sta)
263 ;; Counters in enumerations (`cnt')
264 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter
265 (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter
267 ;; Enumerator (`enm')
269 (:seq cntany-tag "\\.")
270 (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator
272 (:seq cntexp-tag "\\.")
273 (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
277 (:seq "(?" aut-tag ")"))) ; An automatic enumerator
278 (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start
279 (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start
280 (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
281 ; at the beginning of a line
283 ;; Items may be enumerated or bulleted (`itm')
284 (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag
285 (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
287 (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
288 ; beginning of a line, group is the
291 ;; Inline markup (`ilm')
292 (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
293 (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
295 ;; Inline markup content (`ilc')
296 (ilcsgl-tag "\\S ") ; A single non-white character
297 (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content
298 (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content
299 (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
301 (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content
302 (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
304 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content
305 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content
306 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content
307 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count
308 (ilcast-tag (:alt ilcsgl-tag
310 ilcast-prt ilcrep-hlp
311 ilcast-sfx))) ; Non-asterisk content
312 (ilcbkq-tag (:alt ilcsgl-tag
314 ilcbkq-prt ilcrep-hlp
315 ilcbkq-sfx))) ; Non-backquote content
316 (ilcbkqdef-tag (:alt ilcsgl-tag
318 ilcbkqdef-prt ilcrep-hlp
319 ilcbkq-sfx))) ; Non-backquote definition
320 (ilcbar-tag (:alt ilcsgl-tag
322 ilcbar-prt ilcrep-hlp
323 ilcbar-sfx))) ; Non-vertical-bar content
324 (ilcbardef-tag (:alt ilcsgl-tag
326 ilcbardef-prt ilcrep-hlp
327 ilcbar-sfx))) ; Non-vertical-bar definition
330 (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name
331 (fldnam-tag fldnam-prt "+") ; A field name
332 (fld-tag ":" fldnam-tag ":") ; A field marker
335 (optsta-tag (:alt "[-+/]" "--")) ; Start of an option
336 (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option
337 (optarg-tag (:shy "[ =]\\S +")) ; Option argument
338 (optsep-tag (:shy "," hws-prt)) ; Separator between options
339 (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option
341 ;; Footnotes and citations (`fnc')
342 (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name
343 (fncnam-tag fncnam-prt "+") ; A footnote or citation name
344 (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag
345 (fncdef-tag-2 (:grp exm-sta)
346 (:grp fnc-tag)) ; A complete footnote or citation definition
347 ; tag; first group is the explicit markup
348 ; start, second group is the footnote /
350 (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation
351 ; definition; first group is the explicit
352 ; markup start, second group is the
353 ; footnote / citation tag
355 ;; Substitutions (`sub')
356 (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag
357 (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
361 (sym-tag (:shy "\\sw+" (:shy "\\s_\\sw+") "*"))
364 (uri-tag (:alt ,@rst-uri-schemes))
367 (ado-prt "[" ,(concat rst-adornment-chars) "]")
368 (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
369 ; otherwise explicit markup start would be
371 (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
372 ; characters is matched differently
373 (ado-tag-1-1 (:grp ado-prt)
374 "\\1" adorep2-hlp) ; A complete adornment, group is the first
375 ; adornment character and MUST be the FIRST
376 ; group in the whole expression
377 (ado-tag-1-2 (:grp ado-prt)
378 "\\2" adorep2-hlp) ; A complete adornment, group is the first
379 ; adornment character and MUST be the
380 ; SECOND group in the whole expression
381 (ado-beg-2-1 "^" (:grp ado-tag-1-2)
382 lin-end) ; A complete adornment line; first group is the whole
383 ; adornment and MUST be the FIRST group in the whole
384 ; expression; second group is the first adornment
388 (ttl-tag "\\S *\\w\\S *") ; A title text
389 (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line
391 ;; Directives and substitution definitions (`dir')
392 (dir-tag-3 (:grp exm-sta)
393 (:grp (:shy subdef-tag hws-sta) "?")
394 (:grp sym-tag dcl-tag)) ; A directive or substitution definition
395 ; tag; first group is explicit markup
396 ; start, second group is a possibly
397 ; empty substitution tag, third group is
398 ; the directive tag including the double
400 (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution
401 ; definition; groups are as in dir-tag-3
403 ;; Literal block (`lit')
404 (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
405 (:grp dcl-tag) "$") ; Start of a literal block; first group is
406 ; any text before the double colon tag which
407 ; may not exist, second group is the double
411 (cmt-sta-1 (:grp exm-sta) "[^\[|_\n]"
412 (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$")))
413 "*$") ; Start of a comment block; first group is explicit markup
416 ;; Paragraphs (`par')
417 (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag)
418 ) ; Tag at the beginning of a paragraph; there may be groups in
421 "Definition alist of relevant regexes.
422 Each entry consists of the symbol naming the regex and an
423 argument list for `rst-re'.")
425 ;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel
426 (defun rst-re (&rest args)
427 "Interpret ARGS as regular expressions and return a regex string.
428 Each element of ARGS may be one of the following:
430 A string which is inserted unchanged.
432 A character which is resolved to a quoted regex.
434 A symbol which is resolved to a string using `rst-re-alist-def'.
436 A list with a keyword in the car. Each element of the cdr of such
437 a list is recursively interpreted as ARGS. The results of this
438 interpretation are concatenated according to the keyword.
440 For the keyword `:seq' the results are simply concatenated.
442 For the keyword `:shy' the results are concatenated and
443 surrounded by a shy-group (\"\\(?:...\\)\").
445 For the keyword `:alt' the results form an alternative (\"\\|\")
446 which is shy-grouped (\"\\(?:...\\)\").
448 For the keyword `:grp' the results are concatenated and form a
449 referencable grouped (\"\\(...\\)\").
451 After interpretation of ARGS the results are concatenated as for
461 (cadr (assoc re rst-re-alist)))
463 (regexp-quote (char-to-string re)))
466 (mapcar (lambda (elt)
471 (mapconcat 'identity nested ""))
473 (concat "\\(?:" (mapconcat 'identity nested "") "\\)"))
475 (concat "\\(" (mapconcat 'identity nested "") "\\)"))
477 (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)"))
479 (error "Unknown list car: %s" (car re))))))
481 (error "Unknown object type for building regex: %s" re))))
484 (defconst rst-re-alist
485 ;; Shadow global value we are just defining so we can construct it step by
488 (dolist (re rst-re-alist-def)
491 (list (list (car re) (apply 'rst-re (cdr re)))))))
493 "Alist mapping symbols from `rst-re-alist-def' to regex strings.")
496 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
499 (defvar rst-deprecated-keys nil
500 "Alist mapping deprecated keys to the new key to use and the definition.")
504 (defun rst-call-deprecated ()
506 (let* ((dep-key (this-command-keys-vector))
507 (dep-key-s (format-kbd-macro dep-key))
508 (fnd (assoc dep-key rst-deprecated-keys)))
510 ;; Exact key sequence not found. Maybe a deprecated key sequence has
511 ;; been followed by another key.
512 (let* ((dep-key-pfx (butlast (append dep-key nil) 1))
513 (dep-key-def (vconcat dep-key-pfx '(t)))
514 (fnd-def (assoc dep-key-def rst-deprecated-keys)))
516 (error "Unknown deprecated key sequence %s" dep-key-s)
517 ;; Don't execute the command in this case
518 (message "[Deprecated use of key %s; use key %s instead]"
519 (format-kbd-macro dep-key-pfx)
520 (format-kbd-macro (second fnd-def)))))
521 (message "[Deprecated use of key %s; use key %s instead]"
522 dep-key-s (format-kbd-macro (second fnd)))
523 (call-interactively (third fnd)))))
525 (defun rst-define-key (keymap key def &rest deprecated)
526 "Bind like `define-key' using DEPRECATED as deprecated key definitions.
527 DEPRECATED key definitions should be in vector notation. These
528 are defined as well but give an additional message."
529 (define-key keymap key def)
530 (dolist (dep-key deprecated)
531 (push (list dep-key key def) rst-deprecated-keys)
532 (define-key keymap dep-key 'rst-call-deprecated)))
536 (let ((map (make-sparse-keymap)))
538 ;; \C-c is the general keymap
539 (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings)
542 ;; Section Adornments.
544 ;; The adjustment function that adorns or rotates a section title.
545 (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t])
546 (rst-define-key map [?\C-=] 'rst-adjust) ; (Does not work on the Mac OSX.)
548 ;; \C-c \C-a is the keymap for adornments
549 (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings)
550 ;; Display the hierarchy of adornments implied by the current document contents.
551 (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy)
552 ;; Homogenize the adornments in the document.
553 (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments
557 ;; Section Movement and Selection.
559 ;; Mark the subsection where the cursor is.
560 (rst-define-key map [?\C-\M-h] 'rst-mark-section
561 ;; same as mark-defun sgml-mark-current-element
563 ;; Move forward/backward between section titles.
564 (rst-define-key map [?\C-\M-a] 'rst-forward-section
565 ;; same as beginning-of-defun
567 (rst-define-key map [?\C-\M-e] 'rst-backward-section
568 ;; same as end-of-defun
572 ;; Operating on regions.
574 ;; \C-c \C-r is the keymap for regions
575 (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings)
576 ;; Makes region a line-block.
577 (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region
579 ;; Shift region left or right according to tabs
580 (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region
581 [?\C-c ?\C-r t] [?\C-c ?\C-l t])
584 ;; Operating on lists.
586 ;; \C-c \C-l is the keymap for lists
587 (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings)
588 ;; Makes paragraphs in region as a bullet list.
589 (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region
591 ;; Makes paragraphs in region as a enumeration.
592 (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region
594 ;; Converts bullets to an enumeration.
595 (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration
597 ;; Make sure that all the bullets in the region are consistent.
598 (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region
600 ;; Insert a list item
601 (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list)
604 ;; Table-of-Contents Features.
606 ;; \C-c \C-t is the keymap for table of contents
607 (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings)
608 ;; Enter a TOC buffer to view and move to a specific section.
609 (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc)
610 ;; Insert a TOC here.
611 (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert
613 ;; Update the document's TOC (without changing the cursor position).
614 (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update
616 ;; Got to the section under the cursor (cursor must be in TOC).
617 (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section
621 ;; Converting Documents from Emacs.
623 ;; \C-c \C-c is the keymap for compilation
624 (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings)
625 ;; Run one of two pre-configured toolset commands on the document.
626 (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile
628 (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset
630 ;; Convert the active region to pseudo-xml using the docutils tools.
631 (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region
633 ;; Convert the current document to PDF and launch a viewer on the results.
634 (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview
636 ;; Convert the current document to S5 slides and view in a web browser.
637 (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview
641 "Keymap for reStructuredText mode commands.
642 This inherits from Text mode.")
646 (defvar rst-mode-abbrev-table nil
647 "Abbrev table used while in `rst-mode'.")
648 (define-abbrev-table 'rst-mode-abbrev-table
649 (mapcar (lambda (x) (append x '(nil 0 system)))
650 '(("contents" ".. contents::\n..\n ")
651 ("con" ".. contents::\n..\n ")
653 ("skip" "\n\n[...]\n\n ")
654 ("seq" "\n\n[...]\n\n ")
655 ;; FIXME: Add footnotes, links, and more.
660 (defvar rst-mode-syntax-table
661 (let ((st (copy-syntax-table text-mode-syntax-table)))
663 (modify-syntax-entry ?$ "." st)
664 (modify-syntax-entry ?% "." st)
665 (modify-syntax-entry ?& "." st)
666 (modify-syntax-entry ?' "." st)
667 (modify-syntax-entry ?* "." st)
668 (modify-syntax-entry ?+ "_" st)
669 (modify-syntax-entry ?. "_" st)
670 (modify-syntax-entry ?/ "." st)
671 (modify-syntax-entry ?: "_" st)
672 (modify-syntax-entry ?< "." st)
673 (modify-syntax-entry ?= "." st)
674 (modify-syntax-entry ?> "." st)
675 (modify-syntax-entry ?\\ "\\" st)
676 (modify-syntax-entry ?| "." st)
677 (modify-syntax-entry ?_ "_" st)
678 (modify-syntax-entry ?\u00ab "." st)
679 (modify-syntax-entry ?\u00bb "." st)
680 (modify-syntax-entry ?\u2018 "." st)
681 (modify-syntax-entry ?\u2019 "." st)
682 (modify-syntax-entry ?\u201c "." st)
683 (modify-syntax-entry ?\u201d "." st)
686 "Syntax table used while in `rst-mode'.")
689 (defcustom rst-mode-hook nil
690 "Hook run when `rst-mode' is turned on.
691 The hook for `text-mode' is run before this one."
696 ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
697 ;; use *.txt, but this is too generic to be set as a default.
698 ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
700 (define-derived-mode rst-mode text-mode "ReST"
701 "Major mode for editing reStructuredText documents.
704 Turning on `rst-mode' calls the normal hooks `text-mode-hook'
705 and `rst-mode-hook'. This mode also supports font-lock
709 :abbrev-table rst-mode-abbrev-table
710 :syntax-table rst-mode-syntax-table
713 ;; Paragraph recognition
714 (set (make-local-variable 'paragraph-separate)
718 (set (make-local-variable 'paragraph-start)
722 (:seq hws-tag par-tag- bli-sfx))))
724 ;; Indenting and filling
725 (set (make-local-variable 'indent-line-function) 'rst-indent-line)
726 (set (make-local-variable 'adaptive-fill-mode) t)
727 (set (make-local-variable 'adaptive-fill-regexp)
728 (rst-re 'hws-tag 'par-tag- "?" 'hws-tag))
729 (set (make-local-variable 'adaptive-fill-function) 'rst-adaptive-fill)
730 (set (make-local-variable 'fill-paragraph-handle-comment) nil)
733 (set (make-local-variable 'comment-start) ".. ")
734 (set (make-local-variable 'comment-start-skip)
735 (rst-re 'lin-beg 'exm-tag 'bli-sfx))
736 (set (make-local-variable 'comment-continue) " ")
737 (set (make-local-variable 'comment-multi-line) t)
738 (set (make-local-variable 'comment-use-syntax) nil)
739 ;; reStructuredText has not really a comment ender but nil is not really a
741 (set (make-local-variable 'comment-end) "")
742 (set (make-local-variable 'comment-end-skip) nil)
744 (set (make-local-variable 'comment-line-break-function)
745 'rst-comment-line-break)
746 (set (make-local-variable 'comment-indent-function)
748 (set (make-local-variable 'comment-insert-comment-function)
749 'rst-comment-insert-comment)
750 (set (make-local-variable 'comment-region-function)
752 (set (make-local-variable 'uncomment-region-function)
753 'rst-uncomment-region)
756 (setq font-lock-defaults
757 '(rst-font-lock-keywords
759 (font-lock-multiline . t)
760 (font-lock-mark-block-function . mark-paragraph)
761 ;; rst-mode does not need font-lock-support-mode because it's fast
762 ;; enough. In fact using `jit-lock-mode` slows things down
763 ;; considerably even if `rst-font-lock-extend-region` is in place and
765 ;;(font-lock-support-mode . nil)
767 (add-hook 'font-lock-extend-region-functions 'rst-font-lock-extend-region t)
769 ;; Text after a changed line may need new fontification
770 (set (make-local-variable 'jit-lock-contextually) t))
773 (define-minor-mode rst-minor-mode
774 "Toggle ReST minor mode.
775 With a prefix argument ARG, enable ReST minor mode if ARG is
776 positive, and disable it otherwise. If called from Lisp, enable
777 the mode if ARG is omitted or nil.
779 When ReST minor mode is enabled, the ReST mode keybindings
780 are installed on top of the major mode bindings. Use this
781 for modes derived from Text mode, like Mail mode."
782 ;; The initial value.
784 ;; The indicator for the mode line.
786 ;; The minor mode bindings.
790 ;; FIXME: can I somehow install these too?
791 ;; :abbrev-table rst-mode-abbrev-table
792 ;; :syntax-table rst-mode-syntax-table
795 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
796 ;; Section Adornment Adjustment
797 ;; ============================
799 ;; The following functions implement a smart automatic title sectioning feature.
800 ;; The idea is that with the cursor sitting on a section title, we try to get as
801 ;; much information from context and try to do the best thing automatically.
802 ;; This function can be invoked many times and/or with prefix argument to rotate
803 ;; between the various sectioning adornments.
805 ;; Definitions: the two forms of sectioning define semantically separate section
806 ;; levels. A sectioning ADORNMENT consists in:
810 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
812 ;; - an INDENT (meaningful for the over-and-under style only) which determines
813 ;; how many characters and over-and-under style is hanging outside of the
814 ;; title at the beginning and ending.
816 ;; Here are two examples of adornments (| represents the window border, column
820 ;; 1. char: '-' e |Some Title
821 ;; style: simple |----------
823 ;; 2. char: '=' |==============
824 ;; style: over-and-under | Some Title
825 ;; indent: 2 |==============
830 ;; - The underlining character that is used depends on context. The file is
831 ;; scanned to find other sections and an appropriate character is selected.
832 ;; If the function is invoked on a section that is complete, the character is
833 ;; rotated among the existing section adornments.
835 ;; Note that when rotating the characters, if we come to the end of the
836 ;; hierarchy of adornments, the variable rst-preferred-adornments is
837 ;; consulted to propose a new underline adornment, and if continued, we cycle
838 ;; the adornments all over again. Set this variable to nil if you want to
839 ;; limit the underlining character propositions to the existing adornments in
842 ;; - An underline/overline that is not extended to the column at which it should
843 ;; be hanging is dubbed INCOMPLETE. For example::
848 ;; Examples of default invocation:
850 ;; |Some Title ---> |Some Title
853 ;; |Some Title ---> |Some Title
854 ;; |----- |----------
857 ;; | Some Title ---> | Some Title
860 ;; In over-and-under style, when alternating the style, a variable is
861 ;; available to select how much default indent to use (it can be zero). Note
862 ;; that if the current section adornment already has an indent, we don't
863 ;; adjust it to the default, we rather use the current indent that is already
864 ;; there for adjustment (unless we cycle, in which case we use the indent
865 ;; that has been found previously).
867 (defgroup rst-adjust nil
868 "Settings for adjustment and cycling of section title adornments."
872 (define-obsolete-variable-alias
873 'rst-preferred-decorations 'rst-preferred-adornments "r6506")
874 (defcustom rst-preferred-adornments '((?= over-and-under 1)
882 "Preferred hierarchy of section title adornments.
884 A list consisting of lists of the form (CHARACTER STYLE INDENT).
885 CHARACTER is the character used. STYLE is one of the symbols
886 OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted
887 indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are
888 always used when a section adornment is described. In other
889 places t instead of a list stands for a transition.
891 This sequence is consulted to offer a new adornment suggestion
892 when we rotate the underlines at the end of the existing
893 hierarchy of characters, or when there is no existing section
896 Set this to an empty list to use only the adornment found in the
900 (group :tag "Adornment specification"
901 (choice :tag "Adornment character"
902 ,@(mapcar (lambda (char)
904 :tag (char-to-string char) char))
905 rst-adornment-chars))
906 (radio :tag "Adornment type"
907 (const :tag "Overline and underline" over-and-under)
908 (const :tag "Underline only" simple))
909 (integer :tag "Indentation for overline and underline type"
912 (defcustom rst-default-indent 1
913 "Number of characters to indent the section title.
915 This is used for when toggling adornment styles, when switching
916 from a simple adornment style to a over-and-under adornment
922 (defun rst-compare-adornments (ado1 ado2)
924 Return true if both ADO1 and ADO2 adornments are equal,
925 according to restructured text semantics (only the character and
926 the style are compared, the indentation does not matter)."
927 (and (eq (car ado1) (car ado2))
928 (eq (cadr ado1) (cadr ado2))))
931 (defun rst-get-adornment-match (hier ado)
932 "Return the index (level) in hierarchy HIER of adornment ADO.
933 This basically just searches for the item using the appropriate
934 comparison and returns the index. Return nil if the item is
937 (while (and cur (not (rst-compare-adornments (car cur) ado)))
938 (setq cur (cdr cur)))
942 (defun rst-suggest-new-adornment (allados &optional prev)
943 "Suggest a new, different adornment from all that have been seen.
945 ALLADOS is the set of all adornments, including the line numbers.
946 PREV is the optional previous adornment, in order to suggest a
949 ;; For all the preferred adornments...
951 ;; If 'prev' is given, reorder the list to start searching after the
954 (cdr (rst-get-adornment-match rst-preferred-adornments prev)))
956 ;; List of candidates to search.
957 (curpotential (append fplist rst-preferred-adornments)))
959 ;; For all the adornments...
962 (while (and cur (not found))
963 (if (rst-compare-adornments (car cur) (car curpotential))
965 (setq found (car curpotential))
966 (setq cur (cdr cur))))
969 (setq curpotential (cdr curpotential)))
971 (copy-sequence (car curpotential))))
973 (defun rst-delete-entire-line ()
974 "Delete the entire current line without using the `kill-ring'."
975 (delete-region (line-beginning-position)
976 (line-beginning-position 2)))
978 (defun rst-update-section (char style &optional indent)
979 "Unconditionally update the style of a section adornment.
981 Do this using the given character CHAR, with STYLE 'simple
982 or 'over-and-under, and with indent INDENT. If the STYLE
983 is 'simple, whitespace before the title is removed (indent
984 is always assumed to be 0).
986 If there are existing overline and/or underline from the
987 existing adornment, they are removed before adding the
988 requested adornment."
990 (let ((marker (point-marker))
993 ;; Fixup whitespace at the beginning and end of the line
994 (if (or (null indent) (eq style 'simple))
997 (delete-horizontal-space)
998 (insert (make-string indent ? ))
1001 (delete-horizontal-space)
1003 ;; Set the current column, we're at the end of the title line
1004 (setq len (+ (current-column) indent))
1006 ;; Remove previous line if it is an adornment
1009 (if (and (looking-at (rst-re 'ado-beg-2-1))
1010 ;; Avoid removing the underline of a title right above us.
1011 (save-excursion (forward-line -1)
1012 (not (looking-at (rst-re 'ttl-beg)))))
1013 (rst-delete-entire-line)))
1015 ;; Remove following line if it is an adornment
1018 (if (looking-at (rst-re 'ado-beg-2-1))
1019 (rst-delete-entire-line))
1020 ;; Add a newline if we're at the end of the buffer, for the subsequence
1021 ;; inserting of the underline
1022 (if (= (point) (buffer-end 1))
1026 (if (eq style 'over-and-under)
1030 (insert (make-string len char))))
1035 (insert (make-string len char))
1041 (defun rst-classify-adornment (adornment end)
1042 "Classify adornment for section titles and transitions.
1043 ADORNMENT is the complete adornment string as found in the buffer
1044 with optional trailing whitespace. END is the point after the
1045 last character of ADORNMENT.
1047 Return a list. The first entry is t for a transition or a
1048 cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for
1049 the meaning of CHARACTER and STYLE.
1051 The remaining list forms four match groups as returned by
1052 `match-data'. Match group 0 matches the whole construct. Match
1053 group 1 matches the overline adornment if present. Match group 2
1054 matches the section title text or the transition. Match group 3
1055 matches the underline adornment.
1057 Return nil if no syntactically valid adornment is found."
1060 (when (string-match (rst-re 'ado-beg-2-1) adornment)
1062 (let* ((ado-ch (string-to-char (match-string 2 adornment)))
1063 (ado-re (rst-re ado-ch 'adorep3-hlp))
1068 (nxt-emp ; Next line inexistant or empty
1070 (or (not (zerop (forward-line 1)))
1071 (looking-at (rst-re 'lin-end)))))
1072 (prv-emp ; Previous line inexistant or empty
1074 (or (not (zerop (forward-line -1)))
1075 (looking-at (rst-re 'lin-end)))))
1076 (ttl-blw ; Title found below starting here
1079 (zerop (forward-line 1))
1080 (looking-at (rst-re 'ttl-beg))
1082 (ttl-abv ; Title found above starting here
1085 (zerop (forward-line -1))
1086 (looking-at (rst-re 'ttl-beg))
1088 (und-fnd ; Matching underline found starting here
1091 (zerop (forward-line 2))
1092 (looking-at (rst-re ado-re 'lin-end))
1094 (ovr-fnd ; Matching overline found starting here
1097 (zerop (forward-line -2))
1098 (looking-at (rst-re ado-re 'lin-end))
1100 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
1102 ((and nxt-emp prv-emp)
1107 ((or und-fnd ovr-fnd)
1108 ;; An overline with an underline
1109 (setq key (cons ado-ch 'over-and-under))
1110 (let (;; Prefer overline match over underline match
1111 (und-pnt (if ovr-fnd beg-pnt und-fnd))
1112 (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt))
1113 (txt-pnt (if ovr-fnd ttl-abv ttl-blw)))
1115 (setq beg-ovr (point)
1116 end-ovr (line-end-position))
1118 (setq beg-txt (point)
1119 end-txt (line-end-position))
1121 (setq beg-und (point)
1122 end-und (line-end-position))))
1125 (setq key (cons ado-ch 'simple)
1129 (setq beg-txt (point)
1130 end-txt (line-end-position)))
1132 ;; Invalid adornment
1136 (or beg-ovr beg-txt beg-und)
1137 (or end-und end-txt end-ovr)
1138 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))))
1140 (defun rst-find-title-line ()
1141 "Find a section title line around point and return its characteristics.
1142 If the point is on an adornment line find the respective title
1143 line. If the point is on an empty line check previous or next
1144 line whether it is a suitable title line and use it if so. If
1145 point is on a suitable title line use it.
1147 If no title line is found return nil.
1149 Otherwise return as `rst-classify-adornment' does. However, if
1150 the title line has no syntactically valid adornment STYLE is nil
1151 in the first element. If there is no adornment around the title
1152 CHARACTER is also nil and match groups for overline and underline
1156 (let ((orig-pnt (point))
1157 (orig-end (line-end-position)))
1159 ((looking-at (rst-re 'ado-beg-2-1))
1160 (let ((char (string-to-char (match-string-no-properties 2)))
1161 (r (rst-classify-adornment (match-string-no-properties 0)
1165 ;; Invalid adornment - check whether this is an incomplete overline
1167 (zerop (forward-line 1))
1168 (looking-at (rst-re 'ttl-beg)))
1169 (list (cons char nil) orig-pnt (line-end-position)
1170 orig-pnt orig-end (point) (line-end-position) nil nil)))
1172 ;; A section title - not a transition
1174 ((looking-at (rst-re 'lin-end))
1177 (if (and (zerop (forward-line -1))
1178 (looking-at (rst-re 'ttl-beg)))
1179 (list (cons nil nil) (point) (line-end-position)
1180 nil nil (point) (line-end-position) nil nil)))
1182 (if (and (zerop (forward-line 1))
1183 (looking-at (rst-re 'ttl-beg)))
1184 (list (cons nil nil) (point) (line-end-position)
1185 nil nil (point) (line-end-position) nil nil)))))
1186 ((looking-at (rst-re 'ttl-beg))
1187 ;; Try to use the underline
1188 (let ((r (rst-classify-adornment
1189 (buffer-substring-no-properties
1190 (line-beginning-position 2) (line-end-position 2))
1191 (line-end-position 2))))
1194 ;; No valid adornment found
1195 (list (cons nil nil) (point) (line-end-position)
1196 nil nil (point) (line-end-position) nil nil))))))))
1198 ;; The following function and variables are used to maintain information about
1199 ;; current section adornment in a buffer local cache. Thus they can be used for
1200 ;; font-locking and manipulation commands.
1202 (defun rst-reset-section-caches ()
1203 "Reset all section cache variables.
1204 Should be called by interactive functions which deal with sections."
1205 (setq rst-all-sections nil
1206 rst-section-hierarchy nil))
1208 (defvar rst-all-sections nil
1209 "All section adornments in the buffer as found by `rst-find-all-adornments'.
1210 t when no section adornments were found.")
1211 (make-variable-buffer-local 'rst-all-sections)
1213 ;; FIXME: If this variable is set to a different value font-locking of section
1215 (defvar rst-section-hierarchy nil
1216 "Section hierarchy in the buffer as determined by `rst-get-hierarchy'.
1217 t when no section adornments were found. Value depends on
1218 `rst-all-sections'.")
1219 (make-variable-buffer-local 'rst-section-hierarchy)
1221 (defun rst-find-all-adornments ()
1222 "Return all the section adornments in the current buffer.
1223 Return a list of (LINE . ADORNMENT) with ascending LINE where
1224 LINE is the line containing the section title. ADORNMENT consists
1225 of a (CHARACTER STYLE INDENT) triple as described for
1226 `rst-preferred-adornments'.
1228 Uses and sets `rst-all-sections'."
1229 (unless rst-all-sections
1231 ;; Iterate over all the section titles/adornments in the file.
1233 (goto-char (point-min))
1234 (while (re-search-forward (rst-re 'ado-beg-2-1) nil t)
1235 (let ((ado-data (rst-classify-adornment
1236 (match-string-no-properties 0) (point))))
1238 (consp (car ado-data))) ; Ignore transitions
1239 (set-match-data (cdr ado-data))
1240 (goto-char (match-beginning 2)) ; Goto the title start
1241 (push (cons (1+ (count-lines (point-min) (point)))
1242 (list (caar ado-data)
1244 (current-indentation)))
1246 (goto-char (match-end 0))))) ; Go beyond the whole thing
1247 (setq positions (nreverse positions))
1248 (setq rst-all-sections (or positions t)))))
1249 (if (eq rst-all-sections t)
1253 (defun rst-infer-hierarchy (adornments)
1254 "Build a hierarchy of adornments using the list of given ADORNMENTS.
1256 ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment
1257 specifications, in order that they appear in a file, and will
1258 infer a hierarchy of section levels by removing adornments that
1259 have already been seen in a forward traversal of the adornments,
1260 comparing just CHARACTER and STYLE.
1262 Similarly returns a list of (CHARACTER STYLE INDENT), where each
1263 list element should be unique."
1264 (let (hierarchy-alist)
1265 (dolist (x adornments)
1266 (let ((char (car x))
1268 (unless (assoc (cons char style) hierarchy-alist)
1269 (push (cons (cons char style) x) hierarchy-alist))))
1270 (mapcar 'cdr (nreverse hierarchy-alist))))
1272 (defun rst-get-hierarchy (&optional ignore)
1273 "Return the hierarchy of section titles in the file.
1275 Return a list of adornments that represents the hierarchy of
1276 section titles in the file. Each element consists of (CHARACTER
1277 STYLE INDENT) as described for `rst-find-all-adornments'. If the
1278 line number in IGNORE is specified, a possibly adornment found on
1279 that line is not taken into account when building the hierarchy.
1281 Uses and sets `rst-section-hierarchy' unless IGNORE is given."
1282 (if (and (not ignore) rst-section-hierarchy)
1283 (if (eq rst-section-hierarchy t)
1285 rst-section-hierarchy)
1286 (let ((r (rst-infer-hierarchy
1290 (rst-find-all-adornments))))))
1291 (setq rst-section-hierarchy
1293 ;; Clear cache reflecting that a possible update is not
1299 (defun rst-get-adornments-around ()
1300 "Return the adornments around point.
1301 Return a list of the previous and next adornments."
1302 (let* ((all (rst-find-all-adornments))
1303 (curline (line-number-at-pos))
1307 ;; Search for the adornments around the current line.
1308 (while (and cur (< (caar cur) curline))
1311 ;; 'cur' is the following adornment.
1313 (if (and cur (caar cur))
1314 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
1316 (mapcar 'cdar (list prev next))
1320 (defun rst-adornment-complete-p (ado)
1321 "Return true if the adornment ADO around point is complete."
1322 ;; Note: we assume that the detection of the overline as being the underline
1323 ;; of a preceding title has already been detected, and has been eliminated
1324 ;; from the adornment that is given to us.
1326 ;; There is some sectioning already present, so check if the current
1327 ;; sectioning is complete and correct.
1328 (let* ((char (car ado))
1330 (indent (caddr ado))
1331 (endcol (save-excursion (end-of-line) (current-column)))
1334 (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$")))
1336 (save-excursion (forward-line +1)
1339 (or (not (eq style 'over-and-under))
1340 (save-excursion (forward-line -1)
1342 (looking-at exps))))
1347 (defun rst-get-next-adornment
1348 (curado hier &optional suggestion reverse-direction)
1349 "Get the next adornment for CURADO, in given hierarchy HIER.
1350 If suggesting, suggest for new adornment SUGGESTION.
1351 REVERSE-DIRECTION is used to reverse the cycling order."
1355 (style (cadr curado))
1357 ;; Build a new list of adornments for the rotation.
1360 ;; Suggest a new adornment.
1362 ;; If nothing to suggest, use first adornment.
1365 ;; Search for next adornment.
1367 (let ((cur (if reverse-direction rotados
1368 (reverse rotados))))
1370 (not (and (eq char (caar cur))
1371 (eq style (cadar cur)))))
1372 (setq cur (cdr cur)))
1375 ;; If not found, take the first of all adornments.
1380 ;; FIXME: A line "``/`` full" is not accepted as a section title
1381 (defun rst-adjust (pfxarg)
1382 "Auto-adjust the adornment around point.
1384 Adjust/rotate the section adornment for the section title
1385 around point or promote/demote the adornments inside the region,
1386 depending on if the region is active. This function is meant to
1387 be invoked possibly multiple times, and can vary its behavior
1388 with a positive prefix argument (toggle style), or with a
1389 negative prefix argument (alternate behavior).
1391 This function is a bit of a swiss knife. It is meant to adjust
1392 the adornments of a section title in reStructuredText. It tries
1393 to deal with all the possible cases gracefully and to do `the
1394 right thing' in all cases.
1396 See the documentations of `rst-adjust-adornment-work' and
1397 `rst-promote-region' for full details.
1402 The method can take either (but not both) of
1404 a. a (non-negative) prefix argument, which means to toggle the
1405 adornment style. Invoke with a prefix arg for example;
1407 b. a negative numerical argument, which generally inverts the
1408 direction of search in the file or hierarchy. Invoke with C--
1409 prefix for example."
1412 (let* (;; Save our original position on the current line.
1413 (origpt (point-marker))
1415 (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1416 (toggle-style (and pfxarg (not reverse-direction))))
1418 (if (rst-portable-mark-active-p)
1419 ;; Adjust adornments within region.
1420 (rst-promote-region (and pfxarg t))
1421 ;; Adjust adornment around point.
1422 (rst-adjust-adornment-work toggle-style reverse-direction))
1424 ;; Run the hooks to run after adjusting.
1425 (run-hooks 'rst-adjust-hook)
1427 ;; Make sure to reset the cursor position properly after we're done.
1432 (defcustom rst-adjust-hook nil
1433 "Hooks to be run after running `rst-adjust'."
1436 :package-version '(rst . "1.1.0"))
1438 (defcustom rst-new-adornment-down nil
1439 "Controls level of new adornment for section headers."
1442 (const :tag "Same level as previous one" nil)
1443 (const :tag "One level down relative to the previous one" t))
1444 :package-version '(rst . "1.1.0"))
1446 (defun rst-adjust-adornment (pfxarg)
1447 "Call `rst-adjust-adornment-work' interactively.
1449 Keep this for compatibility for older bindings (are there any?)."
1452 (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1453 (toggle-style (and pfxarg (not reverse-direction))))
1454 (rst-adjust-adornment-work toggle-style reverse-direction)))
1456 (defun rst-adjust-adornment-work (toggle-style reverse-direction)
1457 "Adjust/rotate the section adornment for the section title around point.
1459 This function is meant to be invoked possibly multiple times, and
1460 can vary its behavior with a true TOGGLE-STYLE argument, or with
1461 a REVERSE-DIRECTION argument.
1466 The next action it takes depends on context around the point, and
1467 it is meant to be invoked possibly more than once to rotate among
1468 the various possibilities. Basically, this function deals with:
1470 - adding a adornment if the title does not have one;
1472 - adjusting the length of the underline characters to fit a
1475 - rotating the adornment in the set of already existing
1476 sectioning adornments used in the file;
1478 - switching between simple and over-and-under styles.
1480 You should normally not have to read all the following, just
1481 invoke the method and it will do the most obvious thing that you
1485 Adornment Definitions
1486 =====================
1488 The adornments consist in
1492 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1494 3. an INDENT (meaningful for the over-and-under style only)
1495 which determines how many characters and over-and-under
1496 style is hanging outside of the title at the beginning and
1499 See source code for mode details.
1502 Detailed Behavior Description
1503 =============================
1505 Here are the gory details of the algorithm (it seems quite
1506 complicated, but really, it does the most obvious thing in all
1507 the particular cases):
1509 Before applying the adornment change, the cursor is placed on
1510 the closest line that could contain a section title.
1512 Case 1: No Adornment
1513 --------------------
1515 If the current line has no adornment around it,
1517 - search backwards for the last previous adornment, and apply
1518 the adornment one level lower to the current line. If there
1519 is no defined level below this previous adornment, we suggest
1520 the most appropriate of the `rst-preferred-adornments'.
1522 If REVERSE-DIRECTION is true, we simply use the previous
1523 adornment found directly.
1525 - if there is no adornment found in the given direction, we use
1526 the first of `rst-preferred-adornments'.
1528 TOGGLE-STYLE forces a toggle of the prescribed adornment style.
1530 Case 2: Incomplete Adornment
1531 ----------------------------
1533 If the current line does have an existing adornment, but the
1534 adornment is incomplete, that is, the underline/overline does
1535 not extend to exactly the end of the title line (it is either too
1536 short or too long), we simply extend the length of the
1537 underlines/overlines to fit exactly the section title.
1539 If TOGGLE-STYLE we toggle the style of the adornment as well.
1541 REVERSE-DIRECTION has no effect in this case.
1543 Case 3: Complete Existing Adornment
1544 -----------------------------------
1546 If the adornment is complete (i.e. the underline (overline)
1547 length is already adjusted to the end of the title line), we
1548 search/parse the file to establish the hierarchy of all the
1549 adornments (making sure not to include the adornment around
1550 point), and we rotate the current title's adornment from within
1551 that list (by default, going *down* the hierarchy that is present
1552 in the file, i.e. to a lower section level). This is meant to be
1553 used potentially multiple times, until the desired adornment is
1554 found around the title.
1556 If we hit the boundary of the hierarchy, exactly one choice from
1557 the list of preferred adornments is suggested/chosen, the first
1558 of those adornment that has not been seen in the file yet (and
1559 not including the adornment around point), and the next
1560 invocation rolls over to the other end of the hierarchy (i.e. it
1561 cycles). This allows you to avoid having to set which character
1564 If REVERSE-DIRECTION is true, the effect is to change the
1565 direction of rotation in the hierarchy of adornments, thus
1566 instead going *up* the hierarchy.
1568 However, if TOGGLE-STYLE, we do not rotate the adornment, but
1569 instead simply toggle the style of the current adornment (this
1570 should be the most common way to toggle the style of an existing
1571 complete adornment).
1577 The invocation of this function can be carried out anywhere
1578 within the section title line, on an existing underline or
1579 overline, as well as on an empty line following a section title.
1580 This is meant to be as convenient as possible.
1586 Indented section titles such as ::
1591 are invalid in reStructuredText and thus not recognized by the
1592 parser. This code will thus not work in a way that would support
1593 indented sections (it would be ambiguous anyway).
1599 Section titles that are right next to each other may not be
1600 treated well. More work might be needed to support those, and
1601 special conditions on the completeness of existing adornments
1602 might be required to make it non-ambiguous.
1604 For now we assume that the adornments are disjoint, that is,
1605 there is at least a single line between the titles/adornment
1607 (rst-reset-section-caches)
1608 (let ((ttl-fnd (rst-find-title-line))
1611 (set-match-data (cdr ttl-fnd))
1612 (goto-char (match-beginning 2))
1613 (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt)))
1614 (char (caar ttl-fnd))
1615 (style (cdar ttl-fnd))
1616 (indent (current-indentation))
1617 (curado (list char style indent))
1618 char-new style-new indent-new)
1620 ;;-------------------------------------------------------------------
1621 ;; Case 1: No valid adornment
1623 (let ((prev (car (rst-get-adornments-around)))
1625 (hier (rst-get-hierarchy)))
1626 ;; Advance one level down.
1629 (if (or (and rst-new-adornment-down reverse-direction)
1630 (and (not rst-new-adornment-down)
1631 (not reverse-direction)))
1633 (or (cadr (rst-get-adornment-match hier prev))
1634 (rst-suggest-new-adornment hier prev)))
1635 (copy-sequence (car rst-preferred-adornments))))
1636 ;; Invert the style if requested.
1638 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1639 'over-and-under 'simple)) )
1640 (setq char-new (car cur)
1641 style-new (cadr cur)
1642 indent-new (caddr cur))))
1643 ;;-------------------------------------------------------------------
1644 ;; Case 2: Incomplete Adornment
1645 ((not (rst-adornment-complete-p curado))
1646 ;; Invert the style if requested.
1648 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1652 ;;-------------------------------------------------------------------
1653 ;; Case 3: Complete Existing Adornment
1656 ;; Simply switch the style of the current adornment.
1658 style-new (if (eq style 'simple) 'over-and-under 'simple)
1659 indent-new rst-default-indent)
1660 ;; Else, we rotate, ignoring the adornment around the current
1662 (let* ((hier (rst-get-hierarchy (line-number-at-pos)))
1663 ;; Suggestion, in case we need to come up with something new
1664 (suggestion (rst-suggest-new-adornment
1666 (car (rst-get-adornments-around))))
1667 (nextado (rst-get-next-adornment
1668 curado hier suggestion reverse-direction)))
1669 ;; Indent, if present, always overrides the prescribed indent.
1670 (setq char-new (car nextado)
1671 style-new (cadr nextado)
1672 indent-new (caddr nextado))))))
1673 ;; Override indent with present indent!
1674 (setq indent-new (if (> indent 0) indent indent-new))
1675 (if (and char-new style-new)
1676 (rst-update-section char-new style-new indent-new))
1677 ;; Correct the position of the cursor to more accurately reflect where
1678 ;; it was located when the function was invoked.
1679 (unless (zerop moved)
1680 (forward-line (- moved))
1683 ;; Maintain an alias for compatibility.
1684 (defalias 'rst-adjust-section-title 'rst-adjust)
1687 (defun rst-promote-region (demote)
1688 "Promote the section titles within the region.
1690 With argument DEMOTE or a prefix argument, demote the section
1691 titles instead. The algorithm used at the boundaries of the
1692 hierarchy is similar to that used by `rst-adjust-adornment-work'."
1694 (rst-reset-section-caches)
1695 (let* ((cur (rst-find-all-adornments))
1696 (hier (rst-get-hierarchy))
1697 (suggestion (rst-suggest-new-adornment hier))
1699 (region-begin-line (line-number-at-pos (region-beginning)))
1700 (region-end-line (line-number-at-pos (region-end)))
1705 ;; Skip the markers that come before the region beginning
1706 (while (and cur (< (caar cur) region-begin-line))
1707 (setq cur (cdr cur)))
1709 ;; Create a list of markers for all the adornments which are found within
1713 (while (and cur (< (setq line (caar cur)) region-end-line))
1714 (goto-char (point-min))
1715 (forward-line (1- line))
1716 (push (list (point-marker) (cdar cur)) marker-list)
1717 (setq cur (cdr cur)) ))
1719 ;; Apply modifications.
1720 (dolist (p marker-list)
1721 ;; Go to the adornment to promote.
1724 ;; Update the adornment.
1725 (apply 'rst-update-section
1726 ;; Rotate the next adornment.
1727 (rst-get-next-adornment
1728 (cadr p) hier suggestion demote))
1730 ;; Clear marker to avoid slowing down the editing after we're done.
1731 (set-marker (car p) nil))
1732 (setq deactivate-mark nil)
1737 (defun rst-display-adornments-hierarchy (&optional adornments)
1738 "Display the current file's section title adornments hierarchy.
1739 This function expects a list of (CHARACTER STYLE INDENT) triples
1742 (rst-reset-section-caches)
1743 (if (not adornments)
1744 (setq adornments (rst-get-hierarchy)))
1745 (with-output-to-temp-buffer "*rest section hierarchy*"
1747 (with-current-buffer standard-output
1748 (dolist (x adornments)
1749 (insert (format "\nSection Level %d" level))
1750 (apply 'rst-update-section x)
1751 (goto-char (point-max))
1757 (defun rst-position (elem list)
1758 "Return position of ELEM in LIST or nil."
1759 (let ((tail (member elem list)))
1760 (if tail (- (length list) (length tail)))))
1762 (defun rst-straighten-adornments ()
1763 "Redo all the adornments in the current buffer.
1764 This is done using our preferred set of adornments. This can be
1765 used, for example, when using somebody else's copy of a document,
1766 in order to adapt it to our preferred style."
1768 (rst-reset-section-caches)
1770 (let (;; Get a list of pairs of (level . marker)
1771 (levels-and-markers (mapcar
1773 (cons (rst-position (cdr ado)
1774 (rst-get-hierarchy))
1776 (goto-char (point-min))
1777 (forward-line (1- (car ado)))
1779 (rst-find-all-adornments))))
1780 (dolist (lm levels-and-markers)
1781 ;; Go to the appropriate position
1782 (goto-char (cdr lm))
1784 ;; Apply the new styule
1785 (apply 'rst-update-section (nth (car lm) rst-preferred-adornments))
1787 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1788 (set-marker (cdr lm) nil)
1794 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1795 ;; Insert list items
1796 ;; =================
1799 ;=================================================
1800 ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>
1801 ; I needed to make some tiny changes to the functions, so I put it here.
1804 (defconst rst-arabic-to-roman
1805 '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
1806 (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
1807 (10 . "X") (9 . "IX") (5 . "V") (4 . "IV")
1809 "List of maps between Arabic numbers and their Roman numeral equivalents.")
1811 (defun rst-arabic-to-roman (num &optional arg)
1812 "Convert Arabic number NUM to its Roman numeral representation.
1814 Obviously, NUM must be greater than zero. Don't blame me, blame the
1815 Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
1816 apologies to Monty Python).
1817 If optional prefix ARG is non-nil, insert in current buffer."
1818 (let ((map rst-arabic-to-roman)
1820 (while (and map (> num 0))
1821 (if (or (= num (caar map))
1823 (setq res (concat res (cdar map))
1824 num (- num (caar map)))
1825 (setq map (cdr map))))
1828 (defun rst-roman-to-arabic (string &optional arg)
1829 "Convert STRING of Roman numerals to an Arabic number.
1831 If STRING contains a letter which isn't a valid Roman numeral, the rest
1832 of the string from that point onwards is ignored.
1838 If optional ARG is non-nil, insert in current buffer."
1840 (map rst-arabic-to-roman))
1842 (if (string-match (concat "^" (cdar map)) string)
1843 (setq res (+ res (caar map))
1844 string (replace-match "" nil t string))
1845 (setq map (cdr map))))
1847 ;=================================================
1849 (defun rst-find-pfx-in-region (beg end pfx-re)
1850 "Find all the positions of prefixes in region between BEG and END.
1851 This is used to find bullets and enumerated list items. PFX-RE is
1852 a regular expression for matching the lines after indentation
1853 with items. Returns a list of cons cells consisting of the point
1854 and the column of the point."
1858 (while (< (point) end)
1859 (back-to-indentation)
1861 (looking-at pfx-re) ; pfx found and...
1862 (let ((pfx-col (current-column)))
1864 (forward-line -1) ; ...previous line is...
1865 (back-to-indentation)
1866 (or (looking-at (rst-re 'lin-end)) ; ...empty,
1867 (> (current-column) pfx-col) ; ...deeper level, or
1868 (and (= (current-column) pfx-col)
1869 (looking-at pfx-re)))))) ; ...pfx at same level
1870 (push (cons (point) (current-column))
1875 (defun rst-insert-list-pos (newitem)
1876 "Arrange relative position of a newly inserted list item.
1878 Adding a new list might consider three situations:
1880 (a) Current line is a blank line.
1881 (b) Previous line is a blank line.
1882 (c) Following line is a blank line.
1884 When (a) and (b), just add the new list at current line.
1886 when (a) and not (b), a blank line is added before adding the new list.
1888 When not (a), first forward point to the end of the line, and add two
1889 blank lines, then add the new list.
1891 Other situations are just ignored and left to users themselves."
1894 (looking-at (rst-re 'lin-end)))
1897 (looking-at (rst-re 'lin-end)))
1898 (insert newitem " ")
1899 (insert "\n" newitem " "))
1901 (insert "\n\n" newitem " ")))
1903 (defvar rst-initial-enums
1905 (dolist (fmt '("%s." "(%s)" "%s)"))
1906 (dolist (c '("1" "a" "A" "I" "i"))
1907 (push (format fmt c) vals)))
1908 (cons "#." (nreverse vals)))
1909 "List of initial enumerations.")
1911 (defvar rst-initial-items
1912 (append (mapcar 'char-to-string rst-bullets) rst-initial-enums)
1913 "List of initial items. It's collection of bullets and enumerations.")
1915 (defun rst-insert-list-new-item ()
1916 "Insert a new list item.
1918 User is asked to select the item style first, for example (a), i), +. Use TAB
1919 for completition and choices.
1921 If user selects bullets or #, it's just added with position arranged by
1922 `rst-insert-list-pos'.
1924 If user selects enumerations, a further prompt is given. User need to input a
1925 starting item, for example 'e' for 'A)' style. The position is also arranged by
1926 `rst-insert-list-pos'."
1928 ;; FIXME: Make this comply to `interactive' standards
1929 (let* ((itemstyle (completing-read
1930 "Select preferred item style [#.]: "
1931 rst-initial-items nil t nil nil "#."))
1932 (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle)
1933 (match-string 0 itemstyle)))
1936 ;; FIXME: Make this comply to `interactive' standards
1939 (let ((itemno (read-string "Give starting value [a]: "
1941 (downcase (substring itemno 0 1))))
1943 (let ((itemno (read-string "Give starting value [A]: "
1945 (upcase (substring itemno 0 1))))
1947 (let ((itemno (read-number "Give starting value [1]: " 1)))
1948 (rst-arabic-to-roman itemno)))
1950 (let ((itemno (read-number "Give starting value [1]: " 1)))
1951 (downcase (rst-arabic-to-roman itemno))))
1953 (let ((itemno (read-number "Give starting value [1]: " 1)))
1954 (number-to-string itemno)))))))
1956 (setq itemstyle (replace-match no t t itemstyle)))
1957 (rst-insert-list-pos itemstyle)))
1959 (defcustom rst-preferred-bullets
1961 "List of favorite bullets."
1964 (choice ,@(mapcar (lambda (char)
1966 :tag (char-to-string char) char))
1968 :package-version '(rst . "1.1.0"))
1970 (defun rst-insert-list-continue (curitem prefer-roman)
1971 "Insert a list item with list start CURITEM including its indentation level."
1974 "\n" ; FIXME: Separating lines must be possible
1976 ((string-match (rst-re '(:alt enmaut-tag
1979 ((string-match (rst-re 'num-tag) curitem)
1980 (replace-match (number-to-string
1981 (1+ (string-to-number (match-string 0 curitem))))
1983 ((and (string-match (rst-re 'rom-tag) curitem)
1985 (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag
1987 ;; FIXME: Assumes one line list items without separating
1989 (if (and (zerop (forward-line -1))
1990 (looking-at (rst-re 'enmexp-beg)))
1993 (match-string 0)) ; Previous was a roman tag
1994 prefer-roman)) ; Don't know - use flag
1995 t))) ; Not a letter tag
1997 (let* ((old (match-string 0 curitem))
1998 (new (save-match-data
1999 (rst-arabic-to-roman
2000 (1+ (rst-roman-to-arabic
2002 (if (equal old (upcase old))
2006 ((string-match (rst-re 'ltr-tag) curitem)
2007 (replace-match (char-to-string
2008 (1+ (string-to-char (match-string 0 curitem))))
2009 nil nil curitem)))))
2012 (defun rst-insert-list (&optional prefer-roman)
2013 "Insert a list item at the current point.
2015 The command can insert a new list or a continuing list. When it is called at a
2016 non-list line, it will promote to insert new list. When it is called at a list
2017 line, it will insert a list with the same list style.
2019 1. When inserting a new list:
2021 User is asked to select the item style first, for example (a), i), +. Use TAB
2022 for completition and choices.
2024 (a) If user selects bullets or #, it's just added.
2025 (b) If user selects enumerations, a further prompt is given. User needs to
2026 input a starting item, for example 'e' for 'A)' style.
2028 The position of the new list is arranged according to whether or not the
2029 current line and the previous line are blank lines.
2031 2. When continuing a list, one thing need to be noticed:
2033 List style alphabetical list, such as 'a.', and roman numerical list, such as
2034 'i.', have some overlapping items, for example 'v.' The function can deal with
2035 the problem elegantly in most situations. But when those overlapped list are
2036 preceded by a blank line, it is hard to determine which type to use
2037 automatically. The function uses alphabetical list by default. If you want
2038 roman numerical list, just use a prefix (\\[universal-argument])."
2041 (if (looking-at (rst-re 'itmany-beg-1))
2042 (rst-insert-list-continue (match-string 0) prefer-roman)
2043 (rst-insert-list-new-item)))
2045 (defun rst-straighten-bullets-region (beg end)
2046 "Make all the bulleted list items in the region consistent.
2047 The region is specified between BEG and END. You can use this
2048 after you have merged multiple bulleted lists to make them use
2049 the same/correct/consistent bullet characters.
2051 See variable `rst-preferred-bullets' for the list of bullets to
2052 adjust. If bullets are found on levels beyond the
2053 `rst-preferred-bullets' list, they are not modified."
2056 (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta)))
2057 (levtable (make-hash-table :size 4)))
2059 ;; Create a map of levels to list of positions.
2061 (let ((key (cdr x)))
2063 (append (gethash key levtable (list))
2067 ;; Sort this map and create a new map of prefix char and list of positions.
2068 (let ((poslist ())) ; List of (indent . positions).
2069 (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
2071 (let ((bullets rst-preferred-bullets))
2072 (dolist (x (sort poslist 'car-less-than-car))
2074 ;; Apply the characters.
2075 (dolist (pos (cdr x))
2078 (insert (string (car bullets))))
2079 (setq bullets (cdr bullets))))))))
2082 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2083 ;; Table of contents
2084 ;; =================
2086 (defun rst-get-stripped-line ()
2087 "Return the line at cursor, stripped from whitespace."
2088 (re-search-forward (rst-re "\\S .*\\S ") (line-end-position))
2089 (buffer-substring-no-properties (match-beginning 0)
2092 (defun rst-section-tree ()
2093 "Get the hierarchical tree of section titles.
2095 Returns a hierarchical tree of the sections titles in the
2096 document. This can be used to generate a table of contents for
2097 the document. The top node will always be a nil node, with the
2098 top level titles as children (there may potentially be more than
2101 Each section title consists in a cons of the stripped title
2102 string and a marker to the section in the original text document.
2104 If there are missing section levels, the section titles are
2105 inserted automatically, and the title string is set to nil, and
2106 the marker set to the first non-nil child of itself.
2107 Conceptually, the nil nodes--i.e. those which have no title--are
2108 to be considered as being the same line as their first non-nil
2109 child. This has advantages later in processing the graph."
2111 (let ((hier (rst-get-hierarchy))
2112 (levels (make-hash-table :test 'equal :size 10))
2117 ;; Compare just the character and indent in the hash table.
2118 (puthash (cons (car ado) (cadr ado)) lev levels)
2121 ;; Create a list of lines that contains (text, level, marker) for each
2125 (mapcar (lambda (ado)
2126 (goto-char (point-min))
2127 (forward-line (1- (car ado)))
2128 (list (gethash (cons (cadr ado) (caddr ado)) levels)
2129 (rst-get-stripped-line)
2131 (beginning-of-line 1)
2133 (rst-find-all-adornments))))
2134 (let ((lcontnr (cons nil lines)))
2135 (rst-section-tree-rec lcontnr -1))))
2138 (defun rst-section-tree-rec (ados lev)
2139 "Recursive guts of the section tree construction.
2140 ADOS is a cons cell whose cdr is the remaining list of
2141 adornments, and we change it as we consume them. LEV is
2142 the current level of that node. This function returns a
2143 pair of the subtree that was built. This treats the ADOS
2144 list destructively."
2146 (let ((nado (cadr ados))
2150 ;; If the next adornment matches our level
2151 (when (and nado (= (car nado) lev))
2152 ;; Pop the next adornment and create the current node with it
2153 (setcdr ados (cddr ados))
2154 (setq node (cdr nado)) )
2155 ;; Else we let the node title/marker be unset.
2157 ;; Build the child nodes
2158 (while (and (cdr ados) (> (caadr ados) lev))
2160 (cons (rst-section-tree-rec ados (1+ lev))
2162 (setq children (reverse children))
2164 ;; If node is still unset, we use the marker of the first child.
2166 (setq node (cons nil (cdaar children))))
2168 ;; Return this node with its children.
2169 (cons node children)
2173 (defun rst-section-tree-point (node &optional point)
2174 "Find tree node at point.
2175 Given a computed and valid section tree in NODE and a point
2176 POINT (default being the current point in the current buffer),
2177 find and return the node within the sectree where the cursor
2180 Return values: a pair of (parent path, container subtree).
2181 The parent path is simply a list of the nodes above the
2182 container subtree node that we're returning."
2186 (let* ((curpoint (or point (point))))
2188 ;; Check if we are before the current node.
2189 (if (and (cadar node) (>= curpoint (cadar node)))
2191 ;; Iterate all the children, looking for one that might contain the
2193 (let ((curnode (cdr node))
2196 (while (and curnode (>= curpoint (cadaar curnode)))
2198 curnode (cdr curnode)))
2201 (let ((sub (rst-section-tree-point (car last) curpoint)))
2202 (setq path (car sub)
2204 (setq outtree node))
2207 (cons (cons (car node) path) outtree)
2211 (defgroup rst-toc nil
2212 "Settings for reStructuredText table of contents."
2216 (defcustom rst-toc-indent 2
2217 "Indentation for table-of-contents display.
2218 Also used for formatting insertion, when numbering is disabled."
2221 (defcustom rst-toc-insert-style 'fixed
2222 "Insertion style for table-of-contents.
2223 Set this to one of the following values to determine numbering and
2225 - plain: no numbering (fixed indentation)
2226 - fixed: numbering, but fixed indentation
2227 - aligned: numbering, titles aligned under each other
2228 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
2231 (defcustom rst-toc-insert-number-separator " "
2232 "Separator that goes between the TOC number and the title."
2235 ;; This is used to avoid having to change the user's mode.
2236 (defvar rst-toc-insert-click-keymap
2237 (let ((map (make-sparse-keymap)))
2238 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
2240 "(Internal) What happens when you click on propertized text in the TOC.")
2242 (defcustom rst-toc-insert-max-level nil
2243 "If non-nil, maximum depth of the inserted TOC."
2247 (defun rst-toc-insert (&optional pfxarg)
2248 "Insert a simple text rendering of the table of contents.
2249 By default the top level is ignored if there is only one, because
2250 we assume that the document will have a single title.
2252 If a numeric prefix argument PFXARG is given, insert the TOC up
2253 to the specified level.
2255 The TOC is inserted indented at the current column."
2257 (rst-reset-section-caches)
2258 (let* (;; Check maximum level override
2259 (rst-toc-insert-max-level
2260 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
2261 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
2263 ;; Get the section tree for the current cursor point.
2265 (rst-section-tree-point
2266 (rst-section-tree)))
2268 ;; Figure out initial indent.
2269 (initial-indent (make-string (current-column) ? ))
2270 (init-point (point)))
2272 (when (cddr sectree-pair)
2273 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
2275 ;; Fixup for the first line.
2276 (delete-region init-point (+ init-point (length initial-indent)))
2278 ;; Delete the last newline added.
2282 (defun rst-toc-insert-node (node level indent pfx)
2283 "Insert tree node NODE in table-of-contents.
2284 Recursive function that does printing of the inserted toc.
2285 LEVEL is the depth level of the sections in the tree.
2286 INDENT is the indentation string. PFX is the prefix numbering,
2287 that includes the alignment necessary for all the children of
2290 ;; Note: we do child numbering from the parent, so we start number the
2291 ;; children one level before we print them.
2292 (let ((do-print (> level 0))
2297 (unless (equal rst-toc-insert-style 'plain)
2298 (insert pfx rst-toc-insert-number-separator))
2299 (insert (or (caar node) "[missing node]"))
2300 ;; Add properties to the text, even though in normal text mode it
2301 ;; won't be doing anything for now. Not sure that I want to change
2302 ;; mode stuff. At least the highlighting gives the idea that this
2303 ;; is generated automatically.
2304 (put-text-property b (point) 'mouse-face 'highlight)
2305 (put-text-property b (point) 'rst-toc-target (cadar node))
2306 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
2311 ;; Prepare indent for children.
2314 ((eq rst-toc-insert-style 'plain)
2315 (concat indent (make-string rst-toc-indent ? )))
2317 ((eq rst-toc-insert-style 'fixed)
2318 (concat indent (make-string rst-toc-indent ? )))
2320 ((eq rst-toc-insert-style 'aligned)
2321 (concat indent (make-string (+ (length pfx) 2) ? )))
2323 ((eq rst-toc-insert-style 'listed)
2324 (concat (substring indent 0 -3)
2325 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
2329 (if (or (eq rst-toc-insert-max-level nil)
2330 (< level rst-toc-insert-max-level))
2331 (let ((do-child-numbering (>= level 0))
2333 (if do-child-numbering
2335 ;; Add a separating dot if there is already a prefix
2336 (when (> (length pfx) 0)
2337 (string-match (rst-re "[ \t\n]*\\'") pfx)
2338 (setq pfx (concat (replace-match "" t t pfx) ".")))
2340 ;; Calculate the amount of space that the prefix will require
2343 (setq fmt (format "%%-%dd"
2344 (1+ (floor (log10 (length
2348 (dolist (child (cdr node))
2349 (rst-toc-insert-node child
2352 (if do-child-numbering
2353 (concat pfx (format fmt count)) pfx))
2359 (defun rst-toc-update ()
2360 "Automatically find the contents section of a document and update.
2361 Updates the inserted TOC if present. You can use this in your
2362 file-write hook to always make it up-to-date automatically."
2365 ;; Find and delete an existing comment after the first contents directive.
2366 ;; Delete that region.
2367 (goto-char (point-min))
2368 ;; We look for the following and the following only (in other words, if your
2369 ;; syntax differs, this won't work.).
2371 ;; .. contents:: [...anything here...]
2372 ;; [:field: value]...
2377 (let ((beg (re-search-forward
2378 (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n"
2379 "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t))
2382 ;; Look for the first line that starts at the first column.
2385 (< (point) (point-max))
2387 (rst-re 'hws-sta "\\S ")) ; indented content
2388 (setq last-real (point)))
2389 (looking-at (rst-re 'lin-end)))) ; empty line
2393 (goto-char last-real)
2395 (delete-region beg (point)))
2399 ;; Note: always return nil, because this may be used as a hook.
2402 ;; Note: we cannot bind the TOC update on file write because it messes with
2403 ;; undo. If we disable undo, since it adds and removes characters, the
2404 ;; positions in the undo list are not making sense anymore. Dunno what to do
2405 ;; with this, it would be nice to update when saving.
2407 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
2408 ;; (defun rst-toc-update-fun ()
2409 ;; ;; Disable undo for the write file hook.
2410 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
2412 (defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat.
2414 ;;------------------------------------------------------------------------------
2416 (defun rst-toc-node (node level)
2417 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
2421 ;; Insert line text.
2422 (insert (make-string (* rst-toc-indent (1- level)) ? ))
2423 (insert (or (caar node) "[missing node]"))
2426 (put-text-property b (point) 'mouse-face 'highlight)
2428 ;; Add link on lines.
2429 (put-text-property b (point) 'rst-toc-target (cadar node))
2434 (dolist (child (cdr node))
2435 (rst-toc-node child (1+ level))))
2437 (defun rst-toc-count-lines (node target-node)
2438 "Count the number of lines from NODE to the TARGET-NODE node.
2439 This recursive function returns a cons of the number of
2440 additional lines that have been counted for its node and
2441 children, and t if the node has been found."
2445 (if (eq node target-node)
2447 (let ((child (cdr node)))
2448 (while (and child (not found))
2449 (let ((cl (rst-toc-count-lines (car child) target-node)))
2450 (setq count (+ count (car cl))
2452 child (cdr child))))))
2453 (cons count found)))
2455 (defvar rst-toc-buffer-name "*Table of Contents*"
2456 "Name of the Table of Contents buffer.")
2458 (defvar rst-toc-return-wincfg nil
2459 "Window configuration to which to return when leaving the TOC.")
2463 "Display a table-of-contents.
2464 Finds all the section titles and their adornments in the
2465 file, and displays a hierarchically-organized list of the
2466 titles, which is essentially a table-of-contents of the
2469 The Emacs buffer can be navigated, and selecting a section
2470 brings the cursor in that section."
2472 (rst-reset-section-caches)
2473 (let* ((curbuf (list (current-window-configuration) (point-marker)))
2474 (sectree (rst-section-tree))
2476 (our-node (cdr (rst-section-tree-point sectree)))
2479 ;; Create a temporary buffer.
2480 (buf (get-buffer-create rst-toc-buffer-name))
2483 (with-current-buffer buf
2484 (let ((inhibit-read-only t))
2486 (delete-region (point-min) (point-max))
2487 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
2488 (put-text-property (point-min) (point)
2489 'face (list '(background-color . "gray")))
2490 (rst-toc-node sectree 0)
2492 ;; Count the lines to our found node.
2493 (let ((linefound (rst-toc-count-lines sectree our-node)))
2494 (setq line (if (cdr linefound) (car linefound) 0)))
2496 (display-buffer buf)
2499 ;; Save the buffer to return to.
2500 (set (make-local-variable 'rst-toc-return-wincfg) curbuf)
2502 ;; Move the cursor near the right section in the TOC.
2503 (goto-char (point-min))
2504 (forward-line (1- line))
2508 (defun rst-toc-mode-find-section ()
2509 "Get the section from text property at point."
2510 (let ((pos (get-text-property (point) 'rst-toc-target)))
2512 (error "No section on this line"))
2513 (unless (buffer-live-p (marker-buffer pos))
2514 (error "Buffer for this section was killed"))
2517 ;; FIXME: Cursor before or behind the list must be handled properly; before the
2518 ;; list should jump to the top and behind the list to the last normal
2520 (defun rst-goto-section (&optional kill)
2521 "Go to the section the current line describes."
2523 (let ((pos (rst-toc-mode-find-section)))
2525 (set-window-configuration (car rst-toc-return-wincfg))
2526 (kill-buffer (get-buffer rst-toc-buffer-name)))
2527 (pop-to-buffer (marker-buffer pos))
2529 ;; FIXME: make the recentering conditional on scroll.
2532 (defun rst-toc-mode-goto-section ()
2533 "Go to the section the current line describes and kill the TOC buffer."
2535 (rst-goto-section t))
2537 (defun rst-toc-mode-mouse-goto (event)
2538 "In `rst-toc' mode, go to the occurrence whose line you click on.
2539 EVENT is the input event."
2542 (with-current-buffer (window-buffer (posn-window (event-end event)))
2544 (goto-char (posn-point (event-end event)))
2545 (rst-toc-mode-find-section)))))
2546 (pop-to-buffer (marker-buffer pos))
2550 (defun rst-toc-mode-mouse-goto-kill (event)
2551 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well."
2553 (call-interactively 'rst-toc-mode-mouse-goto event)
2554 (kill-buffer (get-buffer rst-toc-buffer-name)))
2556 (defun rst-toc-quit-window ()
2557 "Leave the current TOC buffer."
2559 (let ((retbuf rst-toc-return-wincfg))
2560 (set-window-configuration (car retbuf))
2561 (goto-char (cadr retbuf))))
2563 (defvar rst-toc-mode-map
2564 (let ((map (make-sparse-keymap)))
2565 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2566 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2567 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2568 (define-key map "f" 'rst-toc-mode-goto-section)
2569 (define-key map "q" 'rst-toc-quit-window)
2570 (define-key map "z" 'kill-this-buffer)
2572 "Keymap for `rst-toc-mode'.")
2574 (put 'rst-toc-mode 'mode-class 'special)
2576 ;; Could inherit from the new `special-mode'.
2577 (define-derived-mode rst-toc-mode nil "ReST-TOC"
2578 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2579 (setq buffer-read-only t))
2581 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2585 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2586 ;; Section movement commands
2587 ;; =========================
2589 (defun rst-forward-section (&optional offset)
2590 "Skip to the next reStructuredText section title.
2591 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2592 backwards in the file (default is to use 1)."
2594 (rst-reset-section-caches)
2595 (let* (;; Default value for offset.
2596 (offset (or offset 1))
2598 ;; Get all the adornments in the file, with their line numbers.
2599 (allados (rst-find-all-adornments))
2601 ;; Get the current line.
2602 (curline (line-number-at-pos))
2608 ;; Find the index of the "next" adornment w.r.t. to the current line.
2609 (while (and cur (< (caar cur) curline))
2610 (setq cur (cdr cur))
2612 ;; 'cur' is the adornment on or following the current line.
2614 (if (and (> offset 0) cur (= (caar cur) curline))
2617 ;; Find the final index.
2618 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2619 (setq cur (nth idx allados))
2621 ;; If the index is positive, goto the line, otherwise go to the buffer
2623 (if (and cur (>= idx 0))
2625 (goto-char (point-min))
2626 (forward-line (1- (car cur))))
2627 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
2630 (defun rst-backward-section ()
2631 "Like `rst-forward-section', except move back one title."
2633 (rst-forward-section -1))
2635 (defun rst-mark-section (&optional arg allow-extend)
2636 "Select the section that point is currently in."
2637 ;; Cloned from mark-paragraph.
2638 (interactive "p\np")
2639 (unless arg (setq arg 1))
2641 (error "Cannot mark zero sections"))
2642 (cond ((and allow-extend
2643 (or (and (eq last-command this-command) (mark t))
2644 (rst-portable-mark-active-p)))
2648 (rst-forward-section arg)
2651 (rst-forward-section arg)
2653 (rst-forward-section (- arg)))))
2656 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2657 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2658 ;; always 2 or 3 characters apart horizontally with rest.
2660 (defun rst-find-leftmost-column (beg end)
2661 "Return the leftmost column in region BEG to END."
2665 (while (< (point) end)
2666 (back-to-indentation)
2667 (unless (looking-at (rst-re 'lin-end))
2668 (setq mincol (if mincol
2669 (min mincol (current-column))
2674 (defmacro rst-iterate-leftmost-paragraphs
2675 (beg end first-only body-consequent body-alternative)
2676 "FIXME This definition is old and deprecated / we need to move
2677 to the newer version below:
2679 Call FUN at the beginning of each line, with an argument that
2680 specifies whether we are at the first line of a paragraph that
2681 starts at the leftmost column of the given region BEG and END.
2682 Set FIRST-ONLY to true if you want to callback on the first line
2683 of each paragraph only."
2685 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2686 (endm (copy-marker ,end)))
2688 (do* (;; Iterate lines
2689 (l (progn (goto-char ,beg) (back-to-indentation))
2690 (progn (forward-line 1) (back-to-indentation)))
2692 (previous nil valid)
2694 (curcol (current-column)
2697 (valid (and (= curcol leftcol)
2698 (not (looking-at (rst-re 'lin-end))))
2699 (and (= curcol leftcol)
2700 (not (looking-at (rst-re 'lin-end)))))
2705 (and valid (not previous))
2712 (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2713 "Evaluate BODY for each line in region defined by BEG END.
2714 LEFTMOST is set to true if the line is one of the leftmost of the
2715 entire paragraph. PARABEGIN is set to true if the line is the
2716 first of a paragraph."
2717 (declare (indent 1) (debug (sexp body)))
2719 (beg end parabegin leftmost isleftmost isempty) spec
2722 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2723 (endm (copy-marker ,end)))
2725 (do* (;; Iterate lines
2726 (l (progn (goto-char ,beg) (back-to-indentation))
2727 (progn (forward-line 1) (back-to-indentation)))
2729 (empty-line-previous nil ,isempty)
2731 (,isempty (looking-at (rst-re 'lin-end))
2732 (looking-at (rst-re 'lin-end)))
2734 (,parabegin (not ,isempty)
2735 (and empty-line-previous
2738 (,isleftmost (and (not ,isempty)
2739 (= (current-column) ,leftmost))
2741 (= (current-column) ,leftmost)))
2749 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2752 ;; FIXME: At the moment only block comments with leading empty comment line are
2753 ;; supported; comment lines with leading comment markup should be also
2754 ;; supported; may be a customizable option could control which style to prefer
2756 (defgroup rst-indent nil "Settings for indendation in reStructuredText.
2758 In reStructuredText indendation points are usually determined by
2759 preceding lines. Sometimes the syntax allows arbitrary
2760 indendation points such as where to start the first line
2761 following a directive. These indentation widths can be customized
2764 :package-version '(rst . "1.1.0"))
2766 (define-obsolete-variable-alias
2767 'rst-shift-basic-offset 'rst-indent-width "r6713")
2768 (defcustom rst-indent-width 2
2769 "Indentation when there is no more indentation point given."
2773 (defcustom rst-indent-field 3
2774 "Default indendation for first line after a field or 0 to always indent for
2779 (defcustom rst-indent-literal-normal 3
2780 "Default indendation for literal block after a markup on an own
2785 (defcustom rst-indent-literal-minimized 2
2786 "Default indendation for literal block after a minimized
2791 (defcustom rst-indent-comment 3
2792 "Default indendation for first line of a comment."
2796 ;; FIXME: Must consider other tabs:
2798 ;; * Definition lists
2800 (defun rst-line-tabs ()
2801 "Return tabs of the current line or nil for no tab.
2802 The list is sorted so the tab where writing continues most likely
2803 is the first one. Each tab is of the form (COLUMN . INNER).
2804 COLUMN is the column of the tab. INNER is non-nil if this is an
2805 inner tab. I.e. a tab which does come from the basic indentation
2806 and not from inner alignment points."
2810 (unless (looking-at (rst-re 'lin-end))
2811 (back-to-indentation)
2812 ;; Current indendation is always the least likely tab
2813 (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER)
2814 ;; Push inner tabs more likely to continue writing
2817 ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?"))
2818 (when (match-string 2)
2819 (push (list (match-beginning 2) 0 t) tabs)))
2821 ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag)
2822 '(:grp "\\S ") "?"))
2823 (unless (zerop rst-indent-field)
2824 (push (list (match-beginning 1) rst-indent-field t) tabs))
2825 (if (match-string 3)
2826 (push (list (match-beginning 3) 0 t) tabs)
2827 (if (zerop rst-indent-field)
2828 (push (list (match-end 2)
2829 (if (string= (match-string 2) "") 1 0)
2832 ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?"))
2833 (push (list (match-end 1) 0 t) tabs)
2834 (unless (string= (match-string 2) "")
2835 (push (list (match-end 2) 0 t) tabs))
2836 (when (match-string 4)
2837 (push (list (match-beginning 4) 0 t) tabs)))
2838 ;; Footnote or citation definition
2839 ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?"))
2840 (push (list (match-end 1) 0 t) tabs)
2841 (when (match-string 3)
2842 (push (list (match-beginning 3) 0 t) tabs)))
2844 ((looking-at (rst-re 'cmt-sta-1))
2845 (push (list (point) rst-indent-comment t) tabs)))
2846 ;; Start of literal block
2847 (when (looking-at (rst-re 'lit-sta-2))
2848 (let ((tab0 (first tabs)))
2849 (push (list (first tab0)
2851 (if (match-string 1)
2852 rst-indent-literal-minimized
2853 rst-indent-literal-normal))
2855 (mapcar (lambda (tab)
2856 (goto-char (first tab))
2857 (cons (+ (current-column) (second tab)) (third tab)))
2860 (defun rst-compute-tabs (pt)
2861 "Build the list of possible tabs for all lines above.
2862 Search backwards from point PT to build the list of possible
2863 tabs. Return a list of tabs sorted by likeliness to continue
2864 writing like `rst-line-tabs'. Nearer lines have generally a
2865 higher likeliness than farer lines. Return nil if no tab is found
2869 (let (leftmost ; Leftmost column found so far
2870 innermost ; Leftmost column for inner tab
2872 (while (and (zerop (forward-line -1))
2875 (let* ((tabs (rst-line-tabs))
2876 (leftcol (if tabs (apply 'min (mapcar 'car tabs)))))
2878 ;; Consider only lines indented less or same if not INNERMOST
2879 (when (or (not leftmost)
2880 (< leftcol leftmost)
2881 (and (not innermost) (= leftcol leftmost)))
2883 (let ((inner (cdr tab))
2889 (< newcol leftmost)))
2892 (< newcol innermost))))
2893 (not (memq newcol tablist)))
2894 (push newcol tablist))))
2895 (setq innermost (if (some 'identity
2896 (mapcar 'cdr tabs)) ; Has inner
2899 (setq leftmost leftcol)))))
2900 (nreverse tablist))))
2902 (defun rst-indent-line (&optional dflt)
2903 "Indent current line to next best reStructuredText tab.
2904 The next best tab is taken from the tab list returned by
2905 `rst-compute-tabs' which is used in a cyclic manner. If the
2906 current indentation does not end on a tab use the first one. If
2907 the current indentation is on a tab use the next tab. This allows
2908 a repeated use of \\[indent-for-tab-command] to cycle through all
2909 possible tabs. If no indentation is possible return `noindent' or
2910 use DFLT. Return the indentation indented to. When point is in
2911 indentation it ends up at its end. Otherwise the point is kept
2912 relative to the content."
2913 (let* ((pt (point-marker))
2914 (cur (current-indentation))
2915 (clm (current-column))
2916 (tabs (rst-compute-tabs (point)))
2917 (fnd (position cur tabs))
2919 (if (and (not tabs) (not dflt))
2926 (if (>= fnd (length tabs))
2928 (setq ind (nth fnd tabs)))
2929 (indent-line-to ind)
2935 (defun rst-shift-region (beg end cnt)
2936 "Shift region BEG to END by CNT tabs.
2937 Shift by one tab to the right (CNT > 0) or left (CNT < 0) or
2938 remove all indentation (CNT = 0). An tab is taken from the text
2939 above. If no suitable tab is found `rst-indent-width' is used."
2940 (interactive "r\np")
2941 (let ((tabs (sort (rst-compute-tabs beg) (lambda (x y) (<= x y))))
2942 (leftmostcol (rst-find-leftmost-column beg end)))
2943 (when (or (> leftmostcol 0) (> cnt 0))
2949 ;; Find the next tab after the leftmost column
2950 (let* ((cmp (if (> cnt 0) '> '<))
2951 (tabs (if (> cnt 0) tabs (reverse tabs)))
2953 (dir (signum cnt)) ; Direction to take
2954 (abs (abs cnt)) ; Absolute number of steps to take
2955 ;; Get the position of the first tab beyond leftmostcol
2956 (fnd (position-if (lambda (elt)
2957 (funcall cmp elt leftmostcol))
2959 ;; Virtual position of tab
2960 (pos (+ (or fnd len) (1- abs)))
2961 (tab (if (< pos len)
2962 ;; Tab exists - use it
2964 ;; Column needs to be computed
2965 (let ((col (+ (or (car (last tabs)) leftmostcol)
2966 ;; Base on last known column
2967 (* (- pos (1- len)) ; Distance left
2968 dir ; Direction to take
2969 rst-indent-width))))
2970 (if (< col 0) 0 col)))))
2971 (- tab leftmostcol)))))))
2973 ;; FIXME: A paragraph with an (incorrectly) indented second line is not filled
2978 (defun rst-adaptive-fill ()
2979 "Return fill prefix found at point.
2980 Value for `adaptive-fill-function'."
2981 (let ((fnd (if (looking-at adaptive-fill-regexp)
2982 (match-string-no-properties 0))))
2983 (if (save-match-data
2984 (not (string-match comment-start-skip fnd)))
2985 ;; An non-comment prefix is fine
2987 ;; Matches a comment - return whitespace instead
2990 (goto-char (match-end 0))
2993 (goto-char (match-beginning 0))
2994 (current-column))) ? ))))
2996 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2999 (defun rst-comment-line-break (&optional soft)
3000 "Break line and indent, continuing reStructuredText comment if within one.
3001 Value for `comment-line-break-function'."
3003 (insert-and-inherit ?\n)
3007 (delete-horizontal-space))
3008 (delete-horizontal-space)
3009 (let ((tabs (rst-compute-tabs (point))))
3011 (indent-line-to (car tabs)))))
3013 (defun rst-comment-indent ()
3014 "Return indentation for current comment line."
3015 (car (rst-compute-tabs (point))))
3017 (defun rst-comment-insert-comment ()
3018 "Insert a comment in the current line."
3020 (insert comment-start))
3022 (defun rst-comment-region (beg end &optional arg)
3023 "Comment the current region or uncomment it if ARG is \\[universal-argument]."
3026 (rst-uncomment-region beg end arg)
3028 (let ((ind (current-indentation))
3032 (indent-rigidly bol end rst-indent-comment)
3035 (indent-line-to ind)
3036 (insert (comment-string-strip comment-start t t))))))
3038 (defun rst-uncomment-region (beg end &optional arg)
3039 "Uncomment the current region.
3048 (indent-rigidly eol end (- rst-indent-comment))
3049 (delete-region bol eol))))
3051 ;;------------------------------------------------------------------------------
3053 ;; FIXME: these next functions should become part of a larger effort to redo the
3054 ;; bullets in bulleted lists. The enumerate would just be one of the possible
3057 ;; FIXME: We need to do the enumeration removal as well.
3059 (defun rst-enumerate-region (beg end all)
3060 "Add enumeration to all the leftmost paragraphs in the given region.
3061 The region is specified between BEG and END. With ALL,
3062 do all lines instead of just paragraphs."
3063 (interactive "r\nP")
3065 (last-insert-len nil))
3066 (rst-iterate-leftmost-paragraphs
3068 (let ((ins-string (format "%d. " (incf count))))
3069 (setq last-insert-len (length ins-string))
3070 (insert ins-string))
3071 (insert (make-string last-insert-len ?\ ))
3074 (defun rst-bullet-list-region (beg end all)
3075 "Add bullets to all the leftmost paragraphs in the given region.
3076 The region is specified between BEG and END. With ALL,
3077 do all lines instead of just paragraphs."
3078 (interactive "r\nP")
3079 (rst-iterate-leftmost-paragraphs
3081 (insert (car rst-preferred-bullets) " ")
3085 ;; FIXME: Does not deal with a varying number of digits appropriately
3086 ;; FIXME: Does not deal with multiple levels independently
3087 ;; FIXME: Does not indent a multiline item correctly
3088 (defun rst-convert-bullets-to-enumeration (beg end)
3089 "Convert the bulleted and enumerated items in the region to enumerated lists.
3090 Renumber as necessary."
3092 (let* (;; Find items and convert the positions to markers.
3095 (cons (copy-marker (car x))
3097 (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1))))
3103 (looking-at (rst-re 'itmany-beg-1))
3104 (replace-match (format "%d." count) nil nil nil 1)
3111 ;;------------------------------------------------------------------------------
3113 (defun rst-line-block-region (rbeg rend &optional pfxarg)
3114 "Toggle line block prefixes for a region.
3115 With prefix argument set the empty lines too."
3116 (interactive "r\nP")
3117 (let ((comment-start "| ")
3119 (comment-start-skip "| ")
3120 (comment-style 'indent)
3121 (force (not (not pfxarg))))
3122 (rst-iterate-leftmost-paragraphs-2
3123 (rbeg rend parbegin leftmost isleft isempty)
3124 (when (or force (not isempty))
3125 (move-to-column leftmost force)
3126 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
3131 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3135 (require 'font-lock)
3137 ;; FIXME: The obsolete variables need to disappear
3139 (defgroup rst-faces nil "Faces used in Rst Mode."
3144 (defface rst-block '((t :inherit font-lock-keyword-face))
3145 "Face used for all syntax marking up a special block."
3149 (defcustom rst-block-face 'rst-block
3150 "All syntax marking up a special block."
3154 (make-obsolete-variable 'rst-block-face
3155 "customize the face `rst-block' instead."
3158 (defface rst-external '((t :inherit font-lock-type-face))
3159 "Face used for field names and interpreted text."
3163 (defcustom rst-external-face 'rst-external
3164 "Field names and interpreted text."
3168 (make-obsolete-variable 'rst-external-face
3169 "customize the face `rst-external' instead."
3172 (defface rst-definition '((t :inherit font-lock-function-name-face))
3173 "Face used for all other defining constructs."
3177 (defcustom rst-definition-face 'rst-definition
3178 "All other defining constructs."
3182 (make-obsolete-variable 'rst-definition-face
3183 "customize the face `rst-definition' instead."
3186 ;; XEmacs compatibility (?).
3187 (defface rst-directive (if (boundp 'font-lock-builtin-face)
3188 '((t :inherit font-lock-builtin-face))
3189 '((t :inherit font-lock-preprocessor-face)))
3190 "Face used for directives and roles."
3194 (defcustom rst-directive-face 'rst-directive
3195 "Directives and roles."
3198 (make-obsolete-variable 'rst-directive-face
3199 "customize the face `rst-directive' instead."
3202 (defface rst-comment '((t :inherit font-lock-comment-face))
3203 "Face used for comments."
3207 (defcustom rst-comment-face 'rst-comment
3212 (make-obsolete-variable 'rst-comment-face
3213 "customize the face `rst-comment' instead."
3216 (defface rst-emphasis1 '((t :inherit italic))
3217 "Face used for simple emphasis."
3221 (defcustom rst-emphasis1-face 'rst-emphasis1
3226 (make-obsolete-variable 'rst-emphasis1-face
3227 "customize the face `rst-emphasis1' instead."
3230 (defface rst-emphasis2 '((t :inherit bold))
3231 "Face used for double emphasis."
3235 (defcustom rst-emphasis2-face 'rst-emphasis2
3239 (make-obsolete-variable 'rst-emphasis2-face
3240 "customize the face `rst-emphasis2' instead."
3243 (defface rst-literal '((t :inherit font-lock-string-face))
3244 "Face used for literal text."
3248 (defcustom rst-literal-face 'rst-literal
3253 (make-obsolete-variable 'rst-literal-face
3254 "customize the face `rst-literal' instead."
3257 (defface rst-reference '((t :inherit font-lock-variable-name-face))
3258 "Face used for references to a definition."
3262 (defcustom rst-reference-face 'rst-reference
3263 "References to a definition."
3267 (make-obsolete-variable 'rst-reference-face
3268 "customize the face `rst-reference' instead."
3271 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3273 (defgroup rst-faces-defaults nil
3274 "Values used to generate default faces for section titles on all levels.
3275 Tweak these if you are content with how section title faces are built in
3276 general but you do not like the details."
3280 (defun rst-set-level-default (sym val)
3281 "Set custom var SYM affecting section title text face and recompute the faces."
3282 (custom-set-default sym val)
3283 ;; Also defines the faces initially when all values are available
3284 (and (boundp 'rst-level-face-max)
3285 (boundp 'rst-level-face-format-light)
3286 (boundp 'rst-level-face-base-color)
3287 (boundp 'rst-level-face-step-light)
3288 (boundp 'rst-level-face-base-light)
3289 (fboundp 'rst-define-level-faces)
3290 (rst-define-level-faces)))
3292 ;; Faces for displaying items on several levels; these definitions define
3293 ;; different shades of gray where the lightest one (i.e. least contrasting) is
3295 (defcustom rst-level-face-max 6
3296 "Maximum depth of levels for which section title faces are defined."
3297 :group 'rst-faces-defaults
3299 :set 'rst-set-level-default)
3300 (defcustom rst-level-face-base-color "grey"
3301 "Base name of the color for creating background colors in section title faces."
3302 :group 'rst-faces-defaults
3304 :set 'rst-set-level-default)
3305 (defcustom rst-level-face-base-light
3306 (if (eq frame-background-mode 'dark)
3309 "The lightness factor for the base color. This value is used for level 1.
3310 The default depends on whether the value of `frame-background-mode' is
3312 :group 'rst-faces-defaults
3314 :set 'rst-set-level-default)
3315 (defcustom rst-level-face-format-light "%2d"
3316 "The format for the lightness factor appended to the base name of the color.
3317 This value is expanded by `format' with an integer."
3318 :group 'rst-faces-defaults
3320 :set 'rst-set-level-default)
3321 (defcustom rst-level-face-step-light
3322 (if (eq frame-background-mode 'dark)
3325 "The step width to use for the next color.
3328 `rst-level-face-base-light'
3329 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
3331 must result in a color level which appended to `rst-level-face-base-color'
3332 using `rst-level-face-format-light' results in a valid color such as `grey50'.
3333 This color is used as background for section title text on level
3334 `rst-level-face-max'."
3335 :group 'rst-faces-defaults
3337 :set 'rst-set-level-default)
3339 (defcustom rst-adornment-faces-alist
3340 (let ((alist '((t . font-lock-keyword-face)
3341 (nil . font-lock-keyword-face)))
3343 (while (<= i rst-level-face-max)
3344 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
3347 "Faces for the various adornment types.
3348 Key is a number (for the section title text of that level),
3349 t (for transitions) or nil (for section title adornment).
3350 If you generally do not like how section title text faces are
3351 set up tweak here. If the general idea is ok for you but you do not like the
3352 details check the Rst Faces Defaults group."
3359 "Section level (may not be bigger than `rst-level-face-max')")
3360 (boolean :tag "transitions (on) / section title adornment (off)"))
3362 :set-after '(rst-level-face-max))
3364 ;; FIXME: It should be possible to give "#RRGGBB" type of color values
3365 (defun rst-define-level-faces ()
3366 "Define the faces for the section title text faces from the values."
3367 ;; All variables used here must be checked in `rst-set-level-default'
3369 (while (<= i rst-level-face-max)
3370 (let ((sym (intern (format "rst-level-%d-face" i)))
3371 (doc (format "Face for showing section title text at level %d" i))
3372 (col (format (concat "%s" rst-level-face-format-light)
3373 rst-level-face-base-color
3374 (+ (* (1- i) rst-level-face-step-light)
3375 rst-level-face-base-light))))
3377 (make-empty-face sym)
3378 (set-face-doc-string sym doc)
3379 (set-face-background sym col)
3383 (rst-define-level-faces)
3385 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3387 (defvar rst-font-lock-keywords
3388 ;; The reST-links in the comments below all relate to sections in
3389 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
3390 `(;; FIXME: Block markup is not recognized in blocks after explicit markup
3393 ;; Simple `Body Elements`_
3395 ;; FIXME: A bullet directly after a field name is not recognized
3396 (,(rst-re 'lin-beg '(:grp bul-sta))
3398 ;; `Enumerated Lists`_
3399 (,(rst-re 'lin-beg '(:grp enmany-sta))
3401 ;; `Definition Lists`_ FIXME: missing
3403 (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx)
3404 1 rst-external-face)
3406 (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*")
3407 '(:alt "$" (:seq hws-prt "\\{2\\}")))
3410 ;; Only for lines containing no more bar - to distinguish from tables
3411 (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$")
3414 ;; `Tables`_ FIXME: missing
3416 ;; All the `Explicit Markup Blocks`_
3417 ;; `Footnotes`_ / `Citations`_
3418 (,(rst-re 'lin-beg 'fnc-sta-2)
3419 (1 rst-definition-face)
3420 (2 rst-definition-face))
3421 ;; `Directives`_ / `Substitution Definitions`_
3422 (,(rst-re 'lin-beg 'dir-sta-3)
3423 (1 rst-directive-face)
3424 (2 rst-definition-face)
3425 (3 rst-directive-face))
3426 ;; `Hyperlink Targets`_
3428 '(:grp exm-sta "_" (:alt
3429 (:seq "`" ilcbkqdef-tag "`")
3430 (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":")
3432 1 rst-definition-face)
3433 (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx)
3434 1 rst-definition-face)
3436 ;; All `Inline Markup`_ - most of them may be multiline though this is
3439 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
3440 ;; `Strong Emphasis`_
3441 (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx)
3442 1 rst-emphasis2-face)
3444 (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx)
3445 1 rst-emphasis1-face)
3446 ;; `Inline Literals`_
3447 (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx)
3449 ;; `Inline Internal Targets`_
3450 (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx)
3451 1 rst-definition-face)
3452 ;; `Hyperlink References`_
3453 ;; FIXME: `Embedded URIs`_ not considered
3454 ;; FIXME: Directly adjacing marked up words are not fontified correctly
3455 ;; unless they are not separated by two spaces: foo_ bar_
3456 (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`")
3457 (:seq "\\sw" (:alt "\\sw" "-") "+\\sw"))
3459 1 rst-reference-face)
3460 ;; `Interpreted Text`_
3461 (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?")
3462 '(:grp "`" ilcbkq-tag "`")
3463 '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx)
3464 (1 rst-directive-face)
3465 (2 rst-external-face)
3466 (3 rst-directive-face))
3467 ;; `Footnote References`_ / `Citation References`_
3468 (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx)
3469 1 rst-reference-face)
3470 ;; `Substitution References`_
3471 ;; FIXME: References substitutions like |this|_ or |this|__ are not
3472 ;; fontified correctly
3473 (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx)
3474 1 rst-reference-face)
3475 ;; `Standalone Hyperlinks`_
3476 ;; FIXME: This takes it easy by using a whitespace as delimiter
3477 (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx)
3478 1 rst-definition-face)
3479 (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx)
3480 1 rst-definition-face)
3482 ;; Do all block fontification as late as possible so 'append works
3484 ;; Sections_ / Transitions_ - for sections this is multiline
3485 (,(rst-re 'ado-beg-2-1)
3486 (rst-font-lock-handle-adornment-matcher
3487 (rst-font-lock-handle-adornment-pre-match-form
3488 (match-string-no-properties 1) (match-end 1))
3490 (1 (cdr (assoc nil rst-adornment-faces-alist)) append t)
3491 (2 (cdr (assoc rst-font-lock-adornment-level
3492 rst-adornment-faces-alist)) append t)
3493 (3 (cdr (assoc nil rst-adornment-faces-alist)) append t)))
3495 ;; FIXME: FACESPEC could be used instead of ordinary faces to set
3496 ;; properties on comments and literal blocks so they are *not*
3497 ;; inline fontified; see (elisp)Search-based Fontification
3499 ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el`
3500 ;; and other V24 modes; may make `font-lock-extend-region`
3503 ;; `Comments`_ - this is multiline
3504 (,(rst-re 'lin-beg 'cmt-sta-1)
3505 (1 rst-comment-face)
3506 (rst-font-lock-find-unindented-line-match
3507 (rst-font-lock-find-unindented-line-limit (match-end 1))
3509 (0 rst-comment-face append)))
3510 (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$")
3511 (1 rst-comment-face)
3512 (2 rst-comment-face)
3513 (rst-font-lock-find-unindented-line-match
3514 (rst-font-lock-find-unindented-line-limit 'next)
3516 (0 rst-comment-face append)))
3518 ;; FIXME: This is not rendered as comment::
3519 ;; .. .. list-table::
3523 ;; FIXME: This is rendered wrong::
3527 ;; ----|> KKKKK <|----
3529 ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|-
3532 ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB
3534 ;; Indentation needs to be taken from the line with the ``::`` and not from
3535 ;; the first content line.
3537 ;; `Indented Literal Blocks`_ - this is multiline
3538 (,(rst-re 'lin-beg 'lit-sta-2)
3540 (rst-font-lock-find-unindented-line-match
3541 (rst-font-lock-find-unindented-line-limit t)
3543 (0 rst-literal-face append)))
3545 ;; FIXME: `Quoted Literal Blocks`_ missing - this is multiline
3547 ;; `Doctest Blocks`_
3548 ;; FIXME: This is wrong according to the specification:
3550 ;; Doctest blocks are text blocks which begin with ">>> ", the Python
3551 ;; interactive interpreter main prompt, and end with a blank line.
3552 ;; Doctest blocks are treated as a special case of literal blocks,
3553 ;; without requiring the literal block syntax. If both are present, the
3554 ;; literal block syntax takes priority over Doctest block syntax:
3556 ;; This is an ordinary paragraph.
3558 ;; >>> print 'this is a Doctest block'
3559 ;; this is a Doctest block
3561 ;; The following is a literal block::
3563 ;; >>> This is not recognized as a doctest block by
3564 ;; reStructuredText. It *will* be recognized by the doctest
3567 ;; Indentation is not required for doctest blocks.
3568 (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+"))
3570 (2 rst-literal-face))
3572 "Keywords to highlight in rst mode.")
3574 (defun rst-font-lock-extend-region ()
3575 "Extend the region `font-lock-beg' / `font-lock-end' iff it may
3576 be in the middle of a multiline construct and return non-nil if so."
3577 (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end)))
3579 (setq font-lock-beg (car r))
3580 (setq font-lock-end (cdr r))
3583 (defun rst-font-lock-extend-region-internal (beg end)
3584 "Check the region BEG / END for being in the middle of a multiline construct.
3585 Return nil if not or a cons with new values for BEG / END"
3586 (let ((nbeg (rst-font-lock-extend-region-extend beg -1))
3587 (nend (rst-font-lock-extend-region-extend end 1)))
3589 (cons (or nbeg beg) (or nend end)))))
3591 (defun rst-forward-line (&optional n)
3592 "Like `forward-line' but always end up in column 0 and return accordingly."
3593 (let ((moved (forward-line n)))
3597 (- moved (signum n)))))
3599 (defun rst-font-lock-extend-region-extend (pt dir)
3600 "Extend the region starting at point PT and extending in direction DIR.
3601 Return extended point or nil if not moved."
3602 ;; There are many potential multiline constructs but there are two groups
3603 ;; which are really relevant. The first group consists of
3605 ;; * comment lines without leading explicit markup tag and
3607 ;; * literal blocks following "::"
3609 ;; which are both indented. Thus indendation is the first thing recognized
3610 ;; here. The second criteria is an explicit markup tag which may be a comment
3611 ;; or a double colon at the end of a line.
3613 ;; The second group consists of the adornment cases.
3614 (if (not (get-text-property pt 'font-lock-multiline))
3615 ;; Move only if we don't start inside a multiline construct already
3617 (let (;; non-empty non-indented line, explicit markup tag or literal
3619 (stop-re (rst-re '(:alt "[^ \t\n]"
3620 (:seq hws-tag exm-tag)
3621 (:seq ".*" dcl-tag lin-end)))))
3622 ;; The comments below are for dir == -1 / dir == 1
3626 (while (and (not (looking-at stop-re))
3627 (zerop (rst-forward-line dir)))) ; try previous / next
3629 (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline /
3631 (if (zerop (rst-forward-line dir))
3632 (if (looking-at (rst-re 'ttl-beg)) ; title found, i.e.
3633 ; underline / overline
3635 (if (zerop (rst-forward-line dir))
3637 (looking-at (rst-re 'ado-beg-2-1))) ; no
3640 (rst-forward-line (- dir)))) ; step back to title
3642 (if (< dir 0) ; keep downward adornment
3643 (rst-forward-line (- dir))))) ; step back to adornment
3644 (if (looking-at (rst-re 'ttl-beg)) ; may be a title
3645 (if (zerop (rst-forward-line dir))
3647 (looking-at (rst-re 'ado-beg-2-1))) ; no overline /
3649 (rst-forward-line (- dir)))))) ; step back to line
3650 (if (not (= (point) pt))
3653 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3656 (defun rst-forward-indented-block (&optional column limit)
3657 "Move forward across one indented block.
3658 Find the next non-empty line which is not indented at least to COLUMN (defaults
3659 to the column of the point). Moves point to first character of this line or the
3660 first empty line immediately before it and returns that position. If there is
3661 no such line before LIMIT (defaults to the end of the buffer) returns nil and
3662 point is not moved."
3664 (let ((clm (or column (current-column)))
3668 (setq limit (point-max)))
3670 (while (and (not fnd) (< (point) limit))
3672 (when (< (point) limit)
3674 (if (looking-at (rst-re 'lin-end))
3675 (setq cand (or cand beg)) ; An empty line is a candidate
3676 (move-to-column clm)
3677 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3678 ;; useful way - though it is not clear what this should mean at all
3680 (rst-re 'linemp-tag)
3681 (buffer-substring-no-properties beg (point)))
3682 (setq cand nil) ; An indented line resets a candidate
3683 (setq fnd (or cand beg)))))))
3684 (goto-char (or fnd start))
3687 (defvar rst-font-lock-find-unindented-line-begin nil
3688 "Beginning of the match if `rst-font-lock-find-unindented-line-end'")
3690 (defvar rst-font-lock-find-unindented-line-end nil
3691 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
3692 Also used as a trigger for
3693 `rst-font-lock-find-unindented-line-match'.")
3695 (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
3696 "Find the next unindented line relative to indenation at IND-PNT.
3697 Return this point, the end of the buffer or nil if nothing found.
3698 If IND-PNT is `next' take the indentation from the next line if
3699 this is not empty and indented more than the current one. If
3700 IND-PNT is non-nil but not a number take the indentation from the
3701 next non-empty line if this is indented more than the current
3703 (setq rst-font-lock-find-unindented-line-begin ind-pnt)
3704 (setq rst-font-lock-find-unindented-line-end
3706 (when (not (numberp ind-pnt))
3707 ;; Find indentation point in next line if any
3709 ;; FIXME: Should be refactored to two different functions
3710 ;; giving their result to this function, may be
3711 ;; integrated in caller
3713 (let ((cur-ind (current-indentation)))
3714 (if (eq ind-pnt 'next)
3715 (when (and (zerop (forward-line 1))
3716 (< (point) (point-max)))
3718 (setq rst-font-lock-find-unindented-line-begin
3720 (when (and (not (looking-at (rst-re 'lin-end)))
3721 (> (current-indentation) cur-ind))
3722 ;; Use end of indentation if non-empty line
3723 (looking-at (rst-re 'hws-tag))
3725 ;; Skip until non-empty line or EOF
3726 (while (and (zerop (forward-line 1))
3727 (< (point) (point-max))
3728 (looking-at (rst-re 'lin-end))))
3729 (when (< (point) (point-max))
3731 (setq rst-font-lock-find-unindented-line-begin
3733 (when (> (current-indentation) cur-ind)
3734 ;; Indentation bigger than line of departure
3735 (looking-at (rst-re 'hws-tag))
3736 (match-end 0))))))))
3739 (or (rst-forward-indented-block nil (point-max))
3742 (defun rst-font-lock-find-unindented-line-match (limit)
3743 "Set the match found by
3744 `rst-font-lock-find-unindented-line-limit' the first time called
3746 (when rst-font-lock-find-unindented-line-end
3748 (list rst-font-lock-find-unindented-line-begin
3749 rst-font-lock-find-unindented-line-end))
3750 (put-text-property rst-font-lock-find-unindented-line-begin
3751 rst-font-lock-find-unindented-line-end
3752 'font-lock-multiline t)
3753 ;; Make sure this is called only once
3754 (setq rst-font-lock-find-unindented-line-end nil)
3757 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3760 (defvar rst-font-lock-adornment-level nil
3761 "Storage for `rst-font-lock-handle-adornment-matcher'.
3762 Either section level of the current adornment or t for a transition.")
3764 (defun rst-adornment-level (key)
3765 "Return section level for adornment KEY.
3766 KEY is the first element of the return list of
3767 `rst-classify-adornment'. If KEY is not a cons return it. If KEY is found
3768 in the hierarchy return its level. Otherwise return a level one
3769 beyond the existing hierarchy."
3770 (if (not (consp key))
3772 (let* ((hier (rst-get-hierarchy))
3775 (1+ (or (position-if (lambda (elt)
3776 (and (equal (car elt) char)
3777 (equal (cadr elt) style))) hier)
3780 (defvar rst-font-lock-adornment-match nil
3781 "Storage for match for current adornment.
3782 Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used
3783 as a trigger for `rst-font-lock-handle-adornment-matcher'.")
3785 (defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end)
3786 "Determine limit for adornments for font-locking section titles and transitions.
3787 In fact determine all things necessary and put the result to
3788 `rst-font-lock-adornment-match' and
3789 `rst-font-lock-adornment-level'. ADO is the complete adornment
3790 matched. ADO-END is the point where ADO ends. Return the point
3791 where the whole adorned construct ends.
3793 Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'."
3794 (let ((ado-data (rst-classify-adornment ado ado-end)))
3796 (setq rst-font-lock-adornment-level nil
3797 rst-font-lock-adornment-match nil)
3798 (setq rst-font-lock-adornment-level
3799 (rst-adornment-level (car ado-data)))
3800 (setq rst-font-lock-adornment-match (cdr ado-data))
3801 (goto-char (nth 1 ado-data)) ; Beginning of construct
3802 (nth 2 ado-data)))) ; End of construct
3804 (defun rst-font-lock-handle-adornment-matcher (limit)
3805 "Set the match found by `rst-font-lock-handle-adornment-pre-match-form'
3806 the first time called or nil.
3808 Called as a MATCHER in the sense of `font-lock-keywords'."
3809 (let ((match rst-font-lock-adornment-match))
3810 ;; May run only once - enforce this
3811 (setq rst-font-lock-adornment-match nil)
3813 (set-match-data match)
3814 (goto-char (match-end 0))
3815 (put-text-property (match-beginning 0) (match-end 0)
3816 'font-lock-multiline t)
3820 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3823 (defgroup rst-compile nil
3824 "Settings for support of conversion of reStructuredText
3825 document with \\[rst-compile]."
3829 (defcustom rst-compile-toolsets
3830 `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
3832 (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
3834 (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
3837 (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
3840 (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
3842 (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
3844 (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
3846 "Table describing the command to use for each toolset.
3847 An association list of the toolset to a list of the (command to use,
3848 extension of produced filename, options to the tool (nil or a
3849 string)) to be used for converting the document."
3850 ;; FIXME: These are not options but symbols which may be referenced by
3851 ;; `rst-compile-*-toolset` below
3852 :type '(alist :options (html latex newlatex pseudoxml xml pdf s5)
3854 :value-type (list :tag "Specification"
3855 (file :tag "Command")
3856 (string :tag "File extension")
3857 (choice :tag "Command options"
3858 (const :tag "No options" nil)
3859 (string :tag "Options"))))
3863 ;; FIXME: Must be `defcustom`
3864 (defvar rst-compile-primary-toolset 'html
3865 "The default toolset for `rst-compile'.")
3867 ;; FIXME: Must be `defcustom`
3868 (defvar rst-compile-secondary-toolset 'latex
3869 "The default toolset for `rst-compile' with a prefix argument.")
3871 (defun rst-compile-find-conf ()
3872 "Look for the configuration file in the parents of the current path."
3874 (let ((file-name "docutils.conf")
3875 (buffer-file (buffer-file-name)))
3876 ;; Move up in the dir hierarchy till we find a change log file.
3877 (let* ((dir (file-name-directory buffer-file))
3879 (while (and (or (not (string= dir prevdir))
3882 (not (file-exists-p (concat dir file-name))))
3883 ;; Move up to the parent dir and try again.
3885 (setq dir (expand-file-name (file-name-directory
3886 (directory-file-name
3887 (file-name-directory dir)))))
3889 (or (and dir (concat dir file-name)) nil)
3895 (defun rst-compile (&optional use-alt)
3896 "Compile command to convert reST document into some output file.
3897 Attempts to find configuration file, if it can, overrides the
3898 options. There are two commands to choose from, with USE-ALT,
3899 select the alternative toolset."
3901 ;; Note: maybe we want to check if there is a Makefile too and not do anything
3902 ;; if that is the case. I dunno.
3903 (let* ((toolset (cdr (assq (if use-alt
3904 rst-compile-secondary-toolset
3905 rst-compile-primary-toolset)
3906 rst-compile-toolsets)))
3907 (command (car toolset))
3908 (extension (cadr toolset))
3909 (options (caddr toolset))
3910 (conffile (rst-compile-find-conf))
3911 (bufname (file-name-nondirectory buffer-file-name))
3912 (outname (file-name-sans-extension bufname)))
3914 ;; Set compile-command before invocation of compile.
3915 (set (make-local-variable 'compile-command)
3916 (mapconcat 'identity
3920 (concat "--config=" (shell-quote-argument conffile))
3922 (shell-quote-argument bufname)
3923 (shell-quote-argument (concat outname extension)))
3926 ;; Invoke the compile command.
3927 (if (or compilation-read-command use-alt)
3928 (call-interactively 'compile)
3929 (compile compile-command))
3932 (defun rst-compile-alt-toolset ()
3933 "Compile command with the alternative toolset."
3937 (defun rst-compile-pseudo-region ()
3938 "Show the pseudo-XML rendering of the current active region,
3939 or of the entire buffer, if the region is not selected."
3941 (with-output-to-temp-buffer "*pseudoxml*"
3942 (shell-command-on-region
3943 (if mark-active (region-beginning) (point-min))
3944 (if mark-active (region-end) (point-max))
3945 (cadr (assq 'pseudoxml rst-compile-toolsets))
3948 ;; FIXME: Should be `defcustom`
3949 (defvar rst-pdf-program "xpdf"
3950 "Program used to preview PDF files.")
3952 (defun rst-compile-pdf-preview ()
3953 "Convert the document to a PDF file and launch a preview program."
3955 (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf"))
3956 (command (format "%s %s %s && %s %s ; rm %s"
3957 (cadr (assq 'pdf rst-compile-toolsets))
3958 buffer-file-name tmp-filename
3959 rst-pdf-program tmp-filename tmp-filename)))
3960 (start-process-shell-command "rst-pdf-preview" nil command)
3961 ;; Note: you could also use (compile command) to view the compilation
3965 ;; FIXME: Should be `defcustom` or use something like `browse-url`
3966 (defvar rst-slides-program "firefox"
3967 "Program used to preview S5 slides.")
3969 (defun rst-compile-slides-preview ()
3970 "Convert the document to an S5 slide presentation and launch a preview program."
3972 (let* ((tmp-filename (make-temp-file "rst_el" nil ".html"))
3973 (command (format "%s %s %s && %s %s ; rm %s"
3974 (cadr (assq 's5 rst-compile-toolsets))
3975 buffer-file-name tmp-filename
3976 rst-slides-program tmp-filename tmp-filename)))
3977 (start-process-shell-command "rst-slides-preview" nil command)
3978 ;; Note: you could also use (compile command) to view the compilation
3983 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3984 ;; Generic text functions that are more convenient than the defaults.
3986 ;; FIXME: Unbound command - should be bound or removed
3987 (defun rst-replace-lines (fromchar tochar)
3988 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
3989 with equal-length lines of TOCHAR."
3991 cSearch for flush-left lines of char:
3992 cand replace with char: ")
3994 (let ((searchre (rst-re "^" fromchar "+\\( *\\)$"))
3996 (while (search-forward-regexp searchre nil t)
3997 (setq found (1+ found))
3998 (goto-char (match-beginning 1))
3999 (let ((width (current-column)))
4000 (rst-delete-entire-line)
4001 (insert-char tochar width)))
4002 (message (format "%d lines replaced." found)))))
4004 ;; FIXME: Unbound command - should be bound or removed
4005 (defun rst-join-paragraph ()
4006 "Join lines in current paragraph into one line, removing end-of-lines."
4008 (let ((fill-column 65000)) ; some big number
4009 (call-interactively 'fill-paragraph)))
4011 ;; FIXME: Unbound command - should be bound or removed
4012 (defun rst-force-fill-paragraph ()
4013 "Fill paragraph at point, first joining the paragraph's lines into one.
4014 This is useful for filling list item paragraphs."
4016 (rst-join-paragraph)
4017 (fill-paragraph nil))
4020 ;; FIXME: Unbound command - should be bound or removed
4021 ;; Generic character repeater function.
4022 ;; For sections, better to use the specialized function above, but this can
4023 ;; be useful for creating separators.
4024 (defun rst-repeat-last-character (use-next)
4025 "Fill the current line up to the length of the preceding line (if not
4026 empty), using the last character on the current line. If the preceding line is
4027 empty, we use the `fill-column'.
4029 If USE-NEXT, use the next line rather than the preceding line.
4031 If the current line is longer than the desired length, shave the characters off
4032 the current line to fit the desired length.
4034 As an added convenience, if the command is repeated immediately, the alternative
4035 column is used (fill-column vs. end of previous/next line)."
4037 (let* ((curcol (current-column))
4038 (curline (+ (count-lines (point-min) (point))
4039 (if (zerop curcol) 1 0)))
4040 (lbp (line-beginning-position 0))
4041 (prevcol (if (and (= curline 1) (not use-next))
4044 (forward-line (if use-next 1 -1))
4046 (skip-chars-backward " \t" lbp)
4047 (let ((cc (current-column)))
4048 (if (zerop cc) fill-column cc)))))
4050 (cond ((equal last-command 'rst-repeat-last-character)
4051 (if (= curcol fill-column) prevcol fill-column))
4053 (if (zerop prevcol) fill-column prevcol)))
4056 (if (> (current-column) rightmost-column)
4057 ;; shave characters off the end
4058 (delete-region (- (point)
4059 (- (current-column) rightmost-column))
4061 ;; fill with last characters
4062 (insert-char (preceding-char)
4063 (- rightmost-column (current-column))))
4067 (defun rst-portable-mark-active-p ()
4068 "A portable function that returns non-nil if the mark is active."
4070 ((fboundp 'region-active-p) (region-active-p))
4071 ((boundp 'transient-mark-mode) (and transient-mark-mode mark-active))
4076 ;;; rst.el ends here