Refactored adornment recognition for title adjustment. Includes
[docutils/kirr.git] / docutils / tools / editors / emacs / rst.el
bloba10f2d296eb6ca0e3a230dda213a64f6a088a530
1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Maintainer: Stefan Merten <smerten@oekonux.de>
7 ;; Author: Martin Blais <blais@furius.ca>,
8 ;; David Goodger <goodger@python.org>,
9 ;; Wei-Wei Guo <wwguocn@gmail.com>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; This package provides major mode rst-mode, which supports documents marked up
29 ;; using the reStructuredText format. Support includes font locking as well as
30 ;; some convenience functions for editing. It does this by defining a Emacs
31 ;; major mode: rst-mode (ReST). This mode is derived from text-mode (and
32 ;; inherits much of it). This package also contains:
34 ;; - Functions to automatically adjust and cycle the section underline
35 ;; adornments;
36 ;; - A mode that displays the table of contents and allows you to jump anywhere
37 ;; from it;
38 ;; - Functions to insert and automatically update a TOC in your source
39 ;; document;
40 ;; - Function to insert list, processing item bullets and enumerations
41 ;; automatically;
42 ;; - Font-lock highlighting of notable reStructuredText structures;
43 ;; - Some other convenience functions.
45 ;; See the accompanying document in the docutils documentation about
46 ;; the contents of this package and how to use it.
48 ;; For more information about reStructuredText, see
49 ;; http://docutils.sourceforge.net/rst.html
51 ;; For full details on how to use the contents of this file, see
52 ;; http://docutils.sourceforge.net/docs/user/emacs.html
55 ;; There are a number of convenient keybindings provided by rst-mode.
56 ;; The main one is
58 ;; C-c C-a (also C-=): rst-adjust
60 ;; Updates or rotates the section title around point or promotes/demotes the
61 ;; adornments within the region (see full details below). Note that C-= is a
62 ;; good binding, since it allows you to specify a negative arg easily with C--
63 ;; C-= (easy to type), as well as ordinary prefix arg with C-u C-=.
65 ;; For more on bindings, see rst-mode-map below. There are also many variables
66 ;; that can be customized, look for defcustom and defvar in this file.
68 ;; If you use the table-of-contents feature, you may want to add a hook to
69 ;; update the TOC automatically everytime you adjust a section title::
71 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
73 ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
74 ;; off syntax highlighting to rst-mode, you can use the following::
76 ;; (setq font-lock-global-modes '(not rst-mode ...))
80 ;; CUSTOMIZATION
82 ;; rst
83 ;; ---
84 ;; This group contains some general customizable features.
86 ;; The group is contained in the wp group.
88 ;; rst-faces
89 ;; ---------
90 ;; This group contains all necessary for customizing fonts. The default
91 ;; settings use standard font-lock-*-face's so if you set these to your
92 ;; liking they are probably good in rst-mode also.
94 ;; The group is contained in the faces group as well as in the rst group.
96 ;; rst-faces-defaults
97 ;; ------------------
98 ;; This group contains all necessary for customizing the default fonts used for
99 ;; section title faces.
101 ;; The general idea for section title faces is to have a non-default background
102 ;; but do not change the background. The section level is shown by the
103 ;; lightness of the background color. If you like this general idea of
104 ;; generating faces for section titles but do not like the details this group
105 ;; is the point where you can customize the details. If you do not like the
106 ;; general idea, however, you should customize the faces used in
107 ;; rst-adornment-faces-alist.
109 ;; Note: If you are using a dark background please make sure the variable
110 ;; frame-background-mode is set to the symbol dark. This triggers
111 ;; some default values which are probably right for you.
113 ;; The group is contained in the rst-faces group.
115 ;; All customizable features have a comment explaining their meaning.
116 ;; Refer to the customization of your Emacs (try ``M-x customize``).
119 ;;; DOWNLOAD
121 ;; The latest version of this file lies in the docutils source code repository:
122 ;; http://svn.berlios.de/svnroot/repos/docutils/trunk/docutils/tools/editors/emacs/rst.el
125 ;;; INSTALLATION
127 ;; Add the following lines to your `.emacs' file:
129 ;; (require 'rst)
131 ;; If you are using `.txt' as a standard extension for reST files as
132 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
133 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
134 ;; provides to set the major mode automatically. For instance you may use::
136 ;; .. -*- mode: rst -*-
138 ;; in the very first line of your file. The following code is useful if you
139 ;; want automatically enter rst-mode from any file with compatible extensions:
141 ;; (setq auto-mode-alist
142 ;; (append '(("\\.txt$" . rst-mode)
143 ;; ("\\.rst$" . rst-mode)
144 ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
147 ;;; BUGS
149 ;; - rst-enumeration-region: Select a single paragraph, with the top at one
150 ;; blank line before the beginning, and it will fail.
151 ;; - The active region goes away when we shift it left or right, and this
152 ;; prevents us from refilling it automatically when shifting many times.
153 ;; - The suggested adornments when adjusting should not have to cycle
154 ;; below one below the last section adornment level preceding the
155 ;; cursor. We need to fix that.
157 ;;; TODO LIST
159 ;; rst-toc-insert features
160 ;; ------------------------
161 ;; - rst-toc-insert: We should parse the contents:: options to figure out how
162 ;; deep to render the inserted TOC.
163 ;; - On load, detect any existing TOCs and set the properties for links.
164 ;; - TOC insertion should have an option to add empty lines.
165 ;; - TOC insertion should deal with multiple lines.
166 ;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
167 ;; automatic toc update. The cursor ends up in the TOC and this is
168 ;; annoying. Gotta fix that.
169 ;; - numbering: automatically detect if we have a section-numbering directive in
170 ;; the corresponding section, to render the toc.
172 ;; Other
173 ;; -----
174 ;; - It would be nice to differentiate between text files using
175 ;; reStructuredText_ and other general text files. If we had a
176 ;; function to automatically guess whether a .txt file is following the
177 ;; reStructuredText_ conventions, we could trigger rst-mode without
178 ;; having to hard-code this in every text file, nor forcing the user to
179 ;; add a local mode variable at the top of the file.
180 ;; We could perform this guessing by searching for a valid adornment
181 ;; at the top of the document or searching for reStructuredText_
182 ;; directives further on.
185 ;;; HISTORY
188 ;;; Code:
190 (require 'cl)
193 (defgroup rst nil "Support for reStructuredText documents."
194 :group 'wp
195 :version "23.1"
196 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
199 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
200 ;; Facilities for regular expressions used everywhere
202 ;; The trailing numbers in the names give the number of referenceable regex
203 ;; groups contained in the regex
205 ;; Used to be customizable but really is not customizable but fixed by the reST
206 ;; syntax
207 (defconst rst-bullets
208 ;; Sorted so they can form a character class when concatenated
209 '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043)
210 "List of all possible bullet characters for bulleted lists.")
212 (defconst rst-uri-schemes
213 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
214 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
215 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
216 "Supported URI schemes.")
218 (defconst rst-adornment-chars
219 ;; Sorted so they can form a character class when concatenated
220 '(?\]
221 ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
222 ?^ ?_ ?` ?{ ?| ?} ?~
224 "Characters which may be used in adornments for sections and transitions.")
226 (defconst rst-max-inline-length
227 1000
228 "Maximum length of inline markup to recognize.")
230 (defconst rst-re-alist-def
231 ;; `*-beg' matches * at the beginning of a line
232 ;; `*-end' matches * at the end of a line
233 ;; `*-prt' matches a part of *
234 ;; `*-tag' matches *
235 ;; `*-sta' matches the start of * which may be followed by respective content
236 ;; `*-pfx' matches the delimiter left of *
237 ;; `*-sfx' matches the delimiter right of *
238 ;; `*-hlp' helper for *
240 ;; A trailing number says how many referenceable groups are contained.
243 ;; Horizontal white space (`hws')
244 (hws-prt "[\t ]")
245 (hws-tag hws-prt "*") ; Optional sequence of horizontal white space
246 (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space
248 ;; Lines (`lin')
249 (lin-beg "^" hws-tag) ; Beginning of a possibly indented line
250 (lin-end hws-tag "$") ; End of a line with optional trailing white space
251 (linemp-tag "^" hws-tag "$") ; Empty line with optional white space
253 ;; Various tags and parts
254 (ell-tag "\\.\\.\\.") ; Ellipsis
255 (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet
256 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag
257 (num-prt "[0-9]") ; A number enumerator part
258 (num-tag num-prt "+") ; A number enumerator tag
259 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part
260 (rom-tag rom-prt "+") ; A roman enumerator tag
261 (aut-tag "#") ; An automatic enumerator tag
262 (dcl-tag "::") ; Double colon
264 ;; Block lead in (`bli')
265 (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
266 ; immediate content
268 ;; Various starts
269 (bul-sta bul-tag bli-sfx) ; Start of a bulleted item
271 ;; Explicit markup tag (`exm')
272 (exm-tag "\\.\\.")
273 (exm-sta exm-tag hws-sta)
274 (exm-beg lin-beg exm-sta)
276 ;; Counters in enumerations (`cnt')
277 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter
278 (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter
280 ;; Enumerator (`enm')
281 (enmany-tag (:alt
282 (:seq cntany-tag "\\.")
283 (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator
284 (enmexp-tag (:alt
285 (:seq cntexp-tag "\\.")
286 (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
287 ; enumerator
288 (enmaut-tag (:alt
289 (:seq aut-tag "\\.")
290 (:seq "(?" aut-tag ")"))) ; An automatic enumerator
291 (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start
292 (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start
293 (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
294 ; at the beginning of a line
296 ;; Items may be enumerated or bulleted (`itm')
297 (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag
298 (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
299 ; is the item tag
300 (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
301 ; beginning of a line, group is the
302 ; item tag
304 ;; Inline markup (`ilm')
305 (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
306 (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
308 ;; Inline markup content (`ilc')
309 (ilcsgl-tag "\\S ") ; A single non-white character
310 (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content
311 (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content
312 (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
313 ; definition
314 (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content
315 (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
316 ; definition
317 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content
318 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content
319 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content
320 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count
321 (ilcast-tag (:alt ilcsgl-tag
322 (:seq ilcsgl-tag
323 ilcast-prt ilcrep-hlp
324 ilcast-sfx))) ; Non-asterisk content
325 (ilcbkq-tag (:alt ilcsgl-tag
326 (:seq ilcsgl-tag
327 ilcbkq-prt ilcrep-hlp
328 ilcbkq-sfx))) ; Non-backquote content
329 (ilcbkqdef-tag (:alt ilcsgl-tag
330 (:seq ilcsgl-tag
331 ilcbkqdef-prt ilcrep-hlp
332 ilcbkq-sfx))) ; Non-backquote definition
333 (ilcbar-tag (:alt ilcsgl-tag
334 (:seq ilcsgl-tag
335 ilcbar-prt ilcrep-hlp
336 ilcbar-sfx))) ; Non-vertical-bar content
337 (ilcbardef-tag (:alt ilcsgl-tag
338 (:seq ilcsgl-tag
339 ilcbardef-prt ilcrep-hlp
340 ilcbar-sfx))) ; Non-vertical-bar definition
342 ;; Fields (`fld')
343 (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name
344 (fldnam-tag fldnam-prt "+") ; A field name
345 (fld-tag ":" fldnam-tag ":") ; A field marker
347 ;; Options (`opt')
348 (optsta-tag (:alt "[-+/]" "--")) ; Start of an option
349 (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option
350 (optarg-tag (:shy "[ =]\\S +")) ; Option argument
351 (optsep-tag (:shy "," hws-prt)) ; Separator between options
352 (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option
354 ;; Footnotes and citations (`fnc')
355 (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name
356 (fncnam-tag fncnam-prt "+") ; A footnote or citation name
357 (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag
359 ;; Substitutions (`sub')
360 (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag
361 (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
362 ; tag
364 ;; Symbol (`sym')
365 (sym-prt (:alt "\\sw" "\\s_"))
366 (sym-tag sym-prt "+")
368 ;; URIs (`uri')
369 (uri-tag (:alt ,@rst-uri-schemes))
371 ;; Adornment (`ado')
372 (ado-prt "[" ,(concat rst-adornment-chars) "]")
373 (adorep-hlp "\\{2,\\}") ; there must be at least 3 characters because
374 ; otherwise explicit markup start would be
375 ; recognized
376 (ado-tag-1-1 (:grp ado-prt)
377 "\\1" adorep-hlp) ; A complete adornment, group is the first
378 ; adornment character and MUST be the FIRST
379 ; group in the whole expression
380 (ado-tag-1-2 (:grp ado-prt)
381 "\\2" adorep-hlp) ; A complete adornment, group is the first
382 ; adornment character and MUST be the
383 ; SECOND group in the whole expression
384 (ado-beg-2-1 "^" (:grp ado-tag-1-2)
385 lin-end) ; A complete adornment line; first group is the whole
386 ; adornment and MUST be the FIRST group in the whole
387 ; expression; second group is the first adornment
388 ; character
390 ;; Titles (`ttl')
391 (ttl-tag "\\S *\\w\\S *") ; A title text
392 (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line
394 "Definition alist of relevant regexes.
395 Each entry consists of the symbol naming the regex and an
396 argument list for `rst-re'.")
398 (defun rst-re (&rest args)
399 "Interpret ARGS as regular expressions and return a regex string.
400 Each element of ARGS may be one of the following:
402 A string which is inserted unchanged.
404 A character which is resolved to a quoted regex.
406 A symbol which is resolved to a string using `rst-re-alist-def'.
408 A list with a keyword in the car. Each element of the cdr of such
409 a list is recursively interpreted as ARGS. The results of this
410 interpretation are concatenated according to the keyword.
412 For the keyword `:seq' the results are simply concatenated.
414 For the keyword `:shy' the results are concatenated and
415 surrounded by a shy-group (\"\\(?:...\\)\").
417 For the keyword `:alt' the results form an alternative (\"\\|\")
418 which is shy-grouped (\"\\(?:...\\)\").
420 For the keyword `:grp' the results are concatenated and form a
421 referencable grouped (\"\\(...\\)\").
423 After interpretation of ARGS the results are concatenated as for
424 `:seq'.
426 (apply 'concat
427 (mapcar
428 (lambda (re)
429 (cond
430 ((stringp re)
432 ((symbolp re)
433 (cadr (assoc re rst-re-alist)))
434 ((char-valid-p re)
435 (regexp-quote (char-to-string re)))
436 ((listp re)
437 (let ((nested
438 (mapcar (lambda (elt)
439 (rst-re elt))
440 (cdr re))))
441 (cond
442 ((eq (car re) :seq)
443 (mapconcat 'identity nested ""))
444 ((eq (car re) :shy)
445 (concat "\\(?:" (mapconcat 'identity nested "") "\\)"))
446 ((eq (car re) :grp)
447 (concat "\\(" (mapconcat 'identity nested "") "\\)"))
448 ((eq (car re) :alt)
449 (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)"))
451 (error "Unknown list car: %s" (car re))))))
453 (error "Unknown object type for building regex: %s" re))))
454 args)))
456 (defconst rst-re-alist
457 ;; Shadow global value we are just defining so we can construct it step by
458 ;; step
459 (let (rst-re-alist)
460 (dolist (re rst-re-alist-def)
461 (setq rst-re-alist
462 (nconc rst-re-alist
463 (list (list (car re) (apply 'rst-re (cdr re)))))))
464 rst-re-alist)
465 "Alist mapping symbols from `rst-re-alist-def' to regex strings.")
468 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
469 ;; Mode definition.
471 (defvar rst-deprecated-keys nil
472 "Alist mapping deprecated keys to the new key to use and the definition.")
474 (require 'edmacro)
476 (defun rst-call-deprecated ()
477 (interactive)
478 (let* ((dep-key (this-command-keys-vector))
479 (dep-key-s (format-kbd-macro dep-key))
480 (fnd (assoc dep-key rst-deprecated-keys)))
481 (if (not fnd)
482 ;; Exact key sequence not found. Maybe a deprecated key sequence has
483 ;; been followed by another key.
484 (let* ((dep-key-pfx (butlast (append dep-key nil) 1))
485 (dep-key-def (vconcat dep-key-pfx '(t)))
486 (fnd-def (assoc dep-key-def rst-deprecated-keys)))
487 (if (not fnd-def)
488 (error "Unknown deprecated key sequence %s" dep-key-s)
489 ;; Don't execute the command in this case
490 (message "[Deprecated use of key %s; use key %s instead]"
491 (format-kbd-macro dep-key-pfx)
492 (format-kbd-macro (second fnd-def)))))
493 (message "[Deprecated use of key %s; use key %s instead]"
494 dep-key-s (format-kbd-macro (second fnd)))
495 (call-interactively (third fnd)))))
497 (defun rst-define-key (keymap key def &rest deprecated)
498 "Bind like `define-key' using DEPRECATED as deprecated key definitions.
499 DEPRECATED key definitions should be in vector notation. These
500 are defined as well but give an additional message."
501 (define-key keymap key def)
502 (dolist (dep-key deprecated)
503 (push (list dep-key key def) rst-deprecated-keys)
504 (define-key keymap dep-key 'rst-call-deprecated)))
506 ;; Key bindings.
507 (defvar rst-mode-map
508 (let ((map (make-sparse-keymap)))
510 ;; \C-c is the general keymap
511 (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings)
514 ;; Section Adornments.
516 ;; The adjustment function that adorns or rotates a section title.
517 (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t])
518 (rst-define-key map [?\C-=] 'rst-adjust) ; (Does not work on the Mac OSX.)
520 ;; \C-c \C-a is the keymap for adornments
521 (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings)
522 ;; Display the hierarchy of adornments implied by the current document contents.
523 (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy)
524 ;; Homogeneize the adornments in the document.
525 (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments
526 [?\C-c ?\C-s])
529 ;; Section Movement and Selection.
531 ;; Mark the subsection where the cursor is.
532 (rst-define-key map [?\C-\M-h] 'rst-mark-section
533 ;; same as mark-defun sgml-mark-current-element
534 [?\C-c ?\C-m])
535 ;; Move forward/backward between section titles.
536 (rst-define-key map [?\C-\M-a] 'rst-forward-section
537 ;; same as beginning-of-defun
538 [?\C-c ?\C-n])
539 (rst-define-key map [?\C-\M-e] 'rst-backward-section
540 ;; same as end-of-defun
541 [?\C-c ?\C-p])
544 ;; Operating on regions.
546 ;; \C-c \C-r is the keymap for regions
547 (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings)
548 ;; Makes region a line-block.
549 (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region
550 [?\C-c ?\C-d])
551 ;; Shift region left or right (taking into account of enumerations/bullets,
552 ;; etc.).
553 (rst-define-key map [?\C-c ?\C-r backtab] 'rst-shift-region-left
554 [?\C-c ?\C-l t])
555 (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region-right
556 [?\C-c ?\C-r t])
559 ;; Operating on lists.
561 ;; \C-c \C-l is the keymap for regions
562 (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings)
563 ;; Makes paragraphs in region as a bullet list.
564 (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region
565 [?\C-c ?\C-b])
566 ;; Makes paragraphs in region as a enumeration.
567 (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region
568 [?\C-c ?\C-e])
569 ;; Converts bullets to an enumeration.
570 (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration
571 [?\C-c ?\C-v])
572 ;; Make sure that all the bullets in the region are consistent.
573 (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region
574 [?\C-c ?\C-w])
575 ;; Insert a list item
576 (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list)
579 ;; Table-of-Contents Features.
581 ;; \C-c \C-t is the keymap for table of contents
582 (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings)
583 ;; Enter a TOC buffer to view and move to a specific section.
584 (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc)
585 ;; Insert a TOC here.
586 (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert
587 [?\C-c ?\C-i])
588 ;; Update the document's TOC (without changing the cursor position).
589 (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update
590 [?\C-c ?\C-u])
591 ;; Got to the section under the cursor (cursor must be in TOC).
592 (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section
593 [?\C-c ?\C-f])
596 ;; Converting Documents from Emacs.
598 ;; \C-c \C-c is the keymap for compilation
599 (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings)
600 ;; Run one of two pre-configured toolset commands on the document.
601 (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile
602 [?\C-c ?1])
603 (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset
604 [?\C-c ?2])
605 ;; Convert the active region to pseudo-xml using the docutils tools.
606 (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region
607 [?\C-c ?3])
608 ;; Convert the current document to PDF and launch a viewer on the results.
609 (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview
610 [?\C-c ?4])
611 ;; Convert the current document to S5 slides and view in a web browser.
612 (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview
613 [?\C-c ?5])
615 map)
616 "Keymap for reStructuredText mode commands.
617 This inherits from Text mode.")
620 ;; Abbrevs.
621 (defvar rst-mode-abbrev-table nil
622 "Abbrev table used while in `rst-mode'.")
623 (define-abbrev-table 'rst-mode-abbrev-table
624 (mapcar (lambda (x) (append x '(nil 0 system)))
625 '(("contents" ".. contents::\n..\n ")
626 ("con" ".. contents::\n..\n ")
627 ("cont" "[...]")
628 ("skip" "\n\n[...]\n\n ")
629 ("seq" "\n\n[...]\n\n ")
630 ;; FIXME: Add footnotes, links, and more.
634 ;; Syntax table.
635 (defvar rst-mode-syntax-table
636 (let ((st (copy-syntax-table text-mode-syntax-table)))
638 (modify-syntax-entry ?$ "." st)
639 (modify-syntax-entry ?% "." st)
640 (modify-syntax-entry ?& "." st)
641 (modify-syntax-entry ?' "." st)
642 (modify-syntax-entry ?* "." st)
643 (modify-syntax-entry ?+ "." st)
644 (modify-syntax-entry ?. "_" st)
645 (modify-syntax-entry ?/ "." st)
646 (modify-syntax-entry ?< "." st)
647 (modify-syntax-entry ?= "." st)
648 (modify-syntax-entry ?> "." st)
649 (modify-syntax-entry ?\\ "\\" st)
650 (modify-syntax-entry ?| "." st)
651 (modify-syntax-entry ?_ "." st)
652 (modify-syntax-entry (aref "\u00ab" 0) "." st)
653 (modify-syntax-entry (aref "\u00bb" 0) "." st)
654 (modify-syntax-entry (aref "\u2018" 0) "." st)
655 (modify-syntax-entry (aref "\u2019" 0) "." st)
656 (modify-syntax-entry (aref "\u201c" 0) "." st)
657 (modify-syntax-entry (aref "\u201d" 0) "." st)
660 "Syntax table used while in `rst-mode'.")
663 (defcustom rst-mode-hook nil
664 "Hook run when `rst-mode' is turned on.
665 The hook for `text-mode' is run before this one."
666 :group 'rst
667 :type '(hook))
670 ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
671 ;; use *.txt, but this is too generic to be set as a default.
672 ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
673 ;;;###autoload
674 (define-derived-mode rst-mode text-mode "ReST"
675 "Major mode for editing reStructuredText documents.
676 \\<rst-mode-map>
678 There are a number of convenient keybindings provided by Rst
679 mode. The main one is \\[rst-adjust], it updates or rotates the
680 section title around point or promotes/demotes the adornments
681 within the region (see full details below). Use negative prefix
682 arg to rotate in the other direction.
684 Turning on `rst-mode' calls the normal hooks `text-mode-hook'
685 and `rst-mode-hook'. This mode also supports font-lock
686 highlighting.
688 \\{rst-mode-map}"
689 :abbrev-table rst-mode-abbrev-table
690 :syntax-table rst-mode-syntax-table
691 :group 'rst
693 (set (make-local-variable 'paragraph-separate)
694 (rst-re '(:alt
695 "\f"
696 lin-end)))
697 (set (make-local-variable 'indent-line-function)
698 (if (<= emacs-major-version 21)
699 'indent-relative-maybe
700 'indent-relative))
701 (set (make-local-variable 'paragraph-start)
702 (rst-re '(:alt
703 "\f"
704 lin-end
705 (:seq hws-tag itmany-sta-1))))
706 (set (make-local-variable 'adaptive-fill-mode) t)
708 ;; The details of the following comment setup is important because it affects
709 ;; auto-fill, and it is pretty common in running text to have an ellipsis
710 ;; ("...") which trips because of the rest comment syntax (".. ").
711 ;; FIXME: Auto-fill continues a comment if there is an explicit markup start;
712 ;; maybe comments can be made multi-line somehow (see
713 ;; `comment-multi-line')
714 (set (make-local-variable 'comment-start) ".. ")
715 (set (make-local-variable 'comment-start-skip) (rst-re "^" 'exm-sta))
716 (set (make-local-variable 'comment-multi-line) nil)
717 ;; Text after a changed line may need new fontification - though we don't use
718 ;; jit-lock-mode at the moment...
719 (set (make-local-variable 'jit-lock-contextually) t)
721 ;; Special variables
722 (make-local-variable 'rst-adornment-level-alist)
724 ;; Font lock
725 (setq font-lock-defaults
726 '(rst-font-lock-keywords
727 t nil nil nil
728 (font-lock-multiline . t)
729 (font-lock-mark-block-function . mark-paragraph)
730 ;; rst-mode does not need font-lock-support-mode because it's fast
731 ;; enough. In fact using `jit-lock-mode` slows things down
732 ;; considerably even if `rst-font-lock-extend-region` is in place and
733 ;; compiled.
734 (font-lock-support-mode . nil)
736 (setq font-lock-extend-region-functions
737 (append font-lock-extend-region-functions
738 '(rst-font-lock-extend-region))))
740 ;;;###autoload
741 (define-minor-mode rst-minor-mode
742 "ReST Minor Mode.
743 Toggle ReST minor mode.
744 With no argument, this command toggles the mode.
745 Non-null prefix argument turns on the mode.
746 Null prefix argument turns off the mode.
748 When ReST minor mode is enabled, the ReST mode keybindings
749 are installed on top of the major mode bindings. Use this
750 for modes derived from Text mode, like Mail mode."
751 ;; The initial value.
753 ;; The indicator for the mode line.
754 " ReST"
755 ;; The minor mode bindings.
756 rst-mode-map
757 :group 'rst)
759 ;; FIXME: can I somehow install these too?
760 ;; :abbrev-table rst-mode-abbrev-table
761 ;; :syntax-table rst-mode-syntax-table
764 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
765 ;; Section Adornment Adjustment
766 ;; ============================
768 ;; The following functions implement a smart automatic title sectioning feature.
769 ;; The idea is that with the cursor sitting on a section title, we try to get as
770 ;; much information from context and try to do the best thing automatically.
771 ;; This function can be invoked many times and/or with prefix argument to rotate
772 ;; between the various sectioning adornments.
774 ;; Definitions: the two forms of sectioning define semantically separate section
775 ;; levels. A sectioning ADORNMENT consists in:
777 ;; - a CHARACTER
779 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
781 ;; - an INDENT (meaningful for the over-and-under style only) which determines
782 ;; how many characters and over-and-under style is hanging outside of the
783 ;; title at the beginning and ending.
785 ;; Important note: an existing adornment must be formed by at least two
786 ;; characters to be recognized.
788 ;; Here are two examples of adornments (| represents the window border, column
789 ;; 0):
791 ;; |
792 ;; 1. char: '-' e |Some Title
793 ;; style: simple |----------
794 ;; |
795 ;; 2. char: '=' |==============
796 ;; style: over-and-under | Some Title
797 ;; indent: 2 |==============
798 ;; |
800 ;; Some notes:
802 ;; - The underlining character that is used depends on context. The file is
803 ;; scanned to find other sections and an appropriate character is selected.
804 ;; If the function is invoked on a section that is complete, the character is
805 ;; rotated among the existing section adornments.
807 ;; Note that when rotating the characters, if we come to the end of the
808 ;; hierarchy of adornments, the variable rst-preferred-adornments is
809 ;; consulted to propose a new underline adornment, and if continued, we cycle
810 ;; the adornments all over again. Set this variable to nil if you want to
811 ;; limit the underlining character propositions to the existing adornments in
812 ;; the file.
814 ;; - A prefix argument can be used to alternate the style.
816 ;; - An underline/overline that is not extended to the column at which it should
817 ;; be hanging is dubbed INCOMPLETE. For example::
819 ;; |Some Title
820 ;; |-------
822 ;; Examples of default invocation:
824 ;; |Some Title ---> |Some Title
825 ;; | |----------
827 ;; |Some Title ---> |Some Title
828 ;; |----- |----------
830 ;; | |------------
831 ;; | Some Title ---> | Some Title
832 ;; | |------------
834 ;; In over-and-under style, when alternating the style, a variable is
835 ;; available to select how much default indent to use (it can be zero). Note
836 ;; that if the current section adornment already has an indent, we don't
837 ;; adjust it to the default, we rather use the current indent that is already
838 ;; there for adjustment (unless we cycle, in which case we use the indent
839 ;; that has been found previously).
841 (defgroup rst-adjust nil
842 "Settings for adjustment and cycling of section title adornments."
843 :group 'rst
844 :version "21.1")
846 (defcustom rst-preferred-adornments '((?= over-and-under 1)
847 (?= simple 0)
848 (?- simple 0)
849 (?~ simple 0)
850 (?+ simple 0)
851 (?` simple 0)
852 (?# simple 0)
853 (?@ simple 0))
854 "Preferred ordering of section title adornments.
856 This sequence is consulted to offer a new adornment suggestion
857 when we rotate the underlines at the end of the existing
858 hierarchy of characters, or when there is no existing section
859 title in the file."
860 :group 'rst-adjust)
863 (defcustom rst-default-indent 1
864 "Number of characters to indent the section title.
866 This is used for when toggling adornment styles, when switching
867 from a simple adornment style to a over-and-under adornment
868 style."
869 :group 'rst-adjust)
872 (defun rst-compare-adornments (ado1 ado2)
873 "Compare adornments.
874 Return true if both ADO1 and ADO2 adornments are equal,
875 according to restructured text semantics (only the character and
876 the style are compared, the indentation does not matter)."
877 (and (eq (car ado1) (car ado2))
878 (eq (cadr ado1) (cadr ado2))))
881 (defun rst-get-adornment-match (hier ado)
882 "Return the index (level) in hierarchy HIER of adornment ADO.
883 This basically just searches for the item using the appropriate
884 comparison and returns the index. Return nil if the item is
885 not found."
886 (let ((cur hier))
887 (while (and cur (not (rst-compare-adornments (car cur) ado)))
888 (setq cur (cdr cur)))
889 cur))
892 (defun rst-suggest-new-adornment (allados &optional prev)
893 "Suggest a new, different adornment from all that have been seen.
895 ALLADOS is the set of all adornments, including the line numbers.
896 PREV is the optional previous adornment, in order to suggest a
897 better match."
899 ;; For all the preferred adornments...
900 (let* (
901 ;; If 'prev' is given, reorder the list to start searching after the
902 ;; match.
903 (fplist
904 (cdr (rst-get-adornment-match rst-preferred-adornments prev)))
906 ;; List of candidates to search.
907 (curpotential (append fplist rst-preferred-adornments)))
908 (while
909 ;; For all the adornments...
910 (let ((cur allados)
911 found)
912 (while (and cur (not found))
913 (if (rst-compare-adornments (car cur) (car curpotential))
914 ;; Found it!
915 (setq found (car curpotential))
916 (setq cur (cdr cur))))
917 found)
919 (setq curpotential (cdr curpotential)))
921 (copy-sequence (car curpotential))))
923 (defun rst-delete-entire-line ()
924 "Delete the entire current line without using the `kill-ring'."
925 (delete-region (line-beginning-position)
926 (line-beginning-position 2)))
928 (defun rst-update-section (char style &optional indent)
929 "Unconditionally update the style of a section adornment.
931 Do this using the given character CHAR, with STYLE 'simple
932 or 'over-and-under, and with indent INDENT. If the STYLE
933 is 'simple, whitespace before the title is removed (indent
934 is always assumed to be 0).
936 If there are existing overline and/or underline from the
937 existing adornment, they are removed before adding the
938 requested adornment."
940 (interactive)
941 (let (marker
942 len)
944 (end-of-line)
945 (setq marker (point-marker))
947 ;; Fixup whitespace at the beginning and end of the line
948 (if (or (null indent) (eq style 'simple))
949 (setq indent 0))
950 (beginning-of-line)
951 (delete-horizontal-space)
952 (insert (make-string indent ? ))
954 (end-of-line)
955 (delete-horizontal-space)
957 ;; Set the current column, we're at the end of the title line
958 (setq len (+ (current-column) indent))
960 ;; Remove previous line if it is an adornment
961 (save-excursion
962 (forward-line -1)
963 (if (and (looking-at (rst-re 'ado-beg-2-1))
964 ;; Avoid removing the underline of a title right above us.
965 (save-excursion (forward-line -1)
966 (not (looking-at (rst-re 'ttl-beg)))))
967 (rst-delete-entire-line)))
969 ;; Remove following line if it is an adornment
970 (save-excursion
971 (forward-line +1)
972 (if (looking-at (rst-re 'ado-beg-2-1))
973 (rst-delete-entire-line))
974 ;; Add a newline if we're at the end of the buffer, for the subsequence
975 ;; inserting of the underline
976 (if (= (point) (buffer-end 1))
977 (newline 1)))
979 ;; Insert overline
980 (if (eq style 'over-and-under)
981 (save-excursion
982 (beginning-of-line)
983 (open-line 1)
984 (insert (make-string len char))))
986 ;; Insert underline
987 (forward-line +1)
988 (open-line 1)
989 (insert (make-string len char))
991 (forward-line +1)
992 (goto-char marker)
996 (defun rst-normalize-cursor-position ()
997 "Normalize the cursor position.
998 If the cursor is on an adornment line or an empty line, place it
999 on the section title line (at the beginning). Return the line
1000 offset by which the cursor was moved. This works both over or
1001 under a line."
1002 (if (save-excursion (beginning-of-line)
1003 (or (looking-at (rst-re 'ado-beg-2-1))
1004 (looking-at (rst-re 'lin-end))))
1005 (progn
1006 (beginning-of-line)
1007 (cond
1008 ((save-excursion (forward-line -1)
1009 (and (looking-at (rst-re 'ttl-beg))
1010 (not (looking-at (rst-re 'ado-beg-2-1)))))
1011 (forward-line -1)
1013 ((save-excursion (forward-line +1)
1014 (and (looking-at (rst-re 'ttl-beg))
1015 (not (looking-at (rst-re 'ado-beg-2-1)))))
1016 (forward-line +1)
1019 0)))
1023 (defun rst-find-all-adornments ()
1024 "Find all the adornments in the file.
1025 Return a list of (line, adornment) pairs. Each adornment
1026 consists in a (char, style, indent) triple.
1028 This function does not detect the hierarchy of adornments, it
1029 just finds all of them in a file. You can then invoke another
1030 function to remove redundancies and inconsistencies."
1032 (let (positions
1033 (curline 1))
1034 ;; Iterate over all the section titles/adornments in the file.
1035 (save-excursion
1036 (goto-char (point-min))
1037 (while (< (point) (buffer-end 1))
1038 (if (looking-at (rst-re 'ado-beg-2-1))
1039 (progn
1040 (setq curline (+ curline (rst-normalize-cursor-position)))
1042 ;; Here we have found a potential site for a adornment,
1043 ;; characterize it.
1044 (let ((ado (rst-get-adornment)))
1045 (if (cadr ado) ; Style is existing.
1046 ;; Found a real adornment site.
1047 (progn
1048 (push (cons curline ado) positions)
1049 ;; Push beyond the underline.
1050 (forward-line 1)
1051 (setq curline (+ curline 1))
1054 (forward-line 1)
1055 (setq curline (+ curline 1))
1057 (reverse positions)))
1060 (defun rst-infer-hierarchy (adornments)
1061 "Build a hierarchy of adornments using the list of given ADORNMENTS.
1063 This function expects a list of (char, style, indent) adornment
1064 specifications, in order that they appear in a file, and will
1065 infer a hierarchy of section levels by removing adornments that
1066 have already been seen in a forward traversal of the adornments,
1067 comparing just the character and style.
1069 Similarly returns a list of (char, style, indent), where each
1070 list element should be unique."
1072 (let ((hierarchy-alist (list)))
1073 (dolist (x adornments)
1074 (let ((char (car x))
1075 (style (cadr x)))
1076 (unless (assoc (cons char style) hierarchy-alist)
1077 (push (cons (cons char style) x) hierarchy-alist))
1080 (mapcar 'cdr (nreverse hierarchy-alist))
1084 (defun rst-get-hierarchy (&optional allados ignore)
1085 "Return the hierarchy of section titles in the file.
1087 Return a list of adornments that represents the hierarchy of
1088 section titles in the file. Reuse the list of adornments
1089 already computed in ALLADOS if present. If the line number in
1090 IGNORE is specified, the adornment found on that line (if there
1091 is one) is not taken into account when building the hierarchy."
1092 (let ((all (or allados (rst-find-all-adornments))))
1093 (setq all (assq-delete-all ignore all))
1094 (rst-infer-hierarchy (mapcar 'cdr all))))
1097 (defun rst-get-adornment (&optional point)
1098 "Get the adornment at POINT.
1100 Looks around point and finds the characteristics of the
1101 adornment that is found there. Assumes that the cursor is
1102 already placed on the title line (and not on the overline or
1103 underline).
1105 This function returns a (char, style, indent) triple. If the
1106 characters of overline and underline are different, return
1107 the underline character. The indent is always calculated.
1108 A adornment can be said to exist if the style is not nil.
1110 A point can be specified to go to the given location before
1111 extracting the adornment."
1113 (let (char style indent)
1114 (save-excursion
1115 (if point (goto-char point))
1116 (beginning-of-line)
1117 (if (looking-at (rst-re 'ttl-beg))
1118 (let* ((over (save-excursion
1119 (forward-line -1)
1120 (if (looking-at (rst-re 'ado-beg-2-1))
1121 (string-to-char (match-string 2)))))
1122 (under (save-excursion
1123 (forward-line +1)
1124 (if (looking-at (rst-re 'ado-beg-2-1))
1125 (string-to-char (match-string 2)))))
1128 ;; Check that the line above the overline is not part of a title
1129 ;; above it.
1130 (if (and over
1131 (save-excursion
1132 (and (equal (forward-line -2) 0)
1133 (looking-at (rst-re 'ttl-beg)))))
1134 (setq over nil))
1136 (cond
1137 ;; No adornment found, leave all return values nil.
1138 ((and (eq over nil) (eq under nil)))
1140 ;; Overline only, leave all return values nil.
1142 ;; Note: we don't return the overline character, but it could
1143 ;; perhaps in some cases be used to do something.
1144 ((and over (eq under nil)))
1146 ;; Underline only.
1147 ((and under (eq over nil))
1148 (setq char under
1149 style 'simple))
1151 ;; Both overline and underline.
1153 (setq char under
1154 style 'over-and-under))
1158 ;; Find indentation.
1159 (setq indent (save-excursion (back-to-indentation) (current-column)))
1161 ;; Return values.
1162 (list char style indent)))
1165 (defun rst-get-adornments-around (&optional allados)
1166 "Return the adornments around point.
1168 Given the list of all adornments ALLADOS (with positions),
1169 find the adornments before and after the given point.
1170 A list of the previous and next adornments is returned."
1171 (let* ((all (or allados (rst-find-all-adornments)))
1172 (curline (line-number-at-pos))
1173 prev next
1174 (cur all))
1176 ;; Search for the adornments around the current line.
1177 (while (and cur (< (caar cur) curline))
1178 (setq prev cur
1179 cur (cdr cur)))
1180 ;; 'cur' is the following adornment.
1182 (if (and cur (caar cur))
1183 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
1185 (mapcar 'cdar (list prev next))
1189 (defun rst-adornment-complete-p (ado)
1190 "Return true if the adornment ADO around point is complete."
1191 ;; Note: we assume that the detection of the overline as being the underline
1192 ;; of a preceding title has already been detected, and has been eliminated
1193 ;; from the adornment that is given to us.
1195 ;; There is some sectioning already present, so check if the current
1196 ;; sectioning is complete and correct.
1197 (let* ((char (car ado))
1198 (style (cadr ado))
1199 (indent (caddr ado))
1200 (endcol (save-excursion (end-of-line) (current-column)))
1202 (if char
1203 (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$")))
1204 (and
1205 (save-excursion (forward-line +1)
1206 (beginning-of-line)
1207 (looking-at exps))
1208 (or (not (eq style 'over-and-under))
1209 (save-excursion (forward-line -1)
1210 (beginning-of-line)
1211 (looking-at exps))))
1216 (defun rst-get-next-adornment
1217 (curado hier &optional suggestion reverse-direction)
1218 "Get the next adornment for CURADO, in given hierarchy HIER.
1219 If suggesting, suggest for new adornment SUGGESTION.
1220 REVERSE-DIRECTION is used to reverse the cycling order."
1222 (let* (
1223 (char (car curado))
1224 (style (cadr curado))
1226 ;; Build a new list of adornments for the rotation.
1227 (rotados
1228 (append hier
1229 ;; Suggest a new adornment.
1230 (list suggestion
1231 ;; If nothing to suggest, use first adornment.
1232 (car hier)))) )
1234 ;; Search for next adornment.
1235 (cadr
1236 (let ((cur (if reverse-direction rotados
1237 (reverse rotados))))
1238 (while (and cur
1239 (not (and (eq char (caar cur))
1240 (eq style (cadar cur)))))
1241 (setq cur (cdr cur)))
1242 cur))
1244 ;; If not found, take the first of all adornments.
1245 suggestion
1249 (defun rst-adjust (pfxarg)
1250 "Auto-adjust the adornment around point.
1252 Adjust/rotate the section adornment for the section title
1253 around point or promote/demote the adornments inside the region,
1254 depending on if the region is active. This function is meant to
1255 be invoked possibly multiple times, and can vary its behavior
1256 with a positive prefix argument (toggle style), or with a
1257 negative prefix argument (alternate behavior).
1259 This function is the main focus of this module and is a bit of a
1260 swiss knife. It is meant as the single most essential function
1261 to be bound to invoke to adjust the adornments of a section
1262 title in restructuredtext. It tries to deal with all the
1263 possible cases gracefully and to do `the right thing' in all
1264 cases.
1266 See the documentations of `rst-adjust-adornment-work' and
1267 `rst-promote-region' for full details.
1269 Prefix Arguments
1270 ================
1272 The method can take either (but not both) of
1274 a. a (non-negative) prefix argument, which means to toggle the
1275 adornment style. Invoke with a prefix arg for example;
1277 b. a negative numerical argument, which generally inverts the
1278 direction of search in the file or hierarchy. Invoke with C--
1279 prefix for example."
1280 (interactive "P")
1282 (let* (;; Save our original position on the current line.
1283 (origpt (set-marker (make-marker) (point)))
1285 (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1286 (toggle-style (and pfxarg (not reverse-direction))))
1288 (if (rst-portable-mark-active-p)
1289 ;; Adjust adornments within region.
1290 (rst-promote-region (and pfxarg t))
1291 ;; Adjust adornment around point.
1292 (rst-adjust-adornment-work toggle-style reverse-direction))
1294 ;; Run the hooks to run after adjusting.
1295 (run-hooks 'rst-adjust-hook)
1297 ;; Make sure to reset the cursor position properly after we're done.
1298 (goto-char origpt)
1302 (defvar rst-adjust-hook nil
1303 "Hooks to be run after running `rst-adjust'.")
1305 (defvar rst-new-adornment-down nil
1306 "Non-nil if new adornment is added deeper.
1307 If non-nil, a new adornment being added will be initialized to
1308 be one level down from the previous adornment. If nil, a new
1309 adornment will be equal to the level of the previous
1310 adornment.")
1312 (defun rst-adjust-adornment (pfxarg)
1313 "Call `rst-adjust-adornment-work' interactively.
1315 Keep this for compatibility for older bindings (are there any?)."
1316 (interactive "P")
1318 (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1319 (toggle-style (and pfxarg (not reverse-direction))))
1320 (rst-adjust-adornment-work toggle-style reverse-direction)))
1322 (defun rst-adjust-adornment-work (toggle-style reverse-direction)
1323 "Adjust/rotate the section adornment for the section title around point.
1325 This function is meant to be invoked possibly multiple times, and
1326 can vary its behavior with a true TOGGLE-STYLE argument, or with
1327 a REVERSE-DIRECTION argument.
1329 General Behavior
1330 ================
1332 The next action it takes depends on context around the point, and
1333 it is meant to be invoked possibly more than once to rotate among
1334 the various possibilities. Basically, this function deals with:
1336 - adding a adornment if the title does not have one;
1338 - adjusting the length of the underline characters to fit a
1339 modified title;
1341 - rotating the adornment in the set of already existing
1342 sectioning adornments used in the file;
1344 - switching between simple and over-and-under styles.
1346 You should normally not have to read all the following, just
1347 invoke the method and it will do the most obvious thing that you
1348 would expect.
1351 Adornment Definitions
1352 =====================
1354 The adornments consist in
1356 1. a CHARACTER
1358 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1360 3. an INDENT (meaningful for the over-and-under style only)
1361 which determines how many characters and over-and-under
1362 style is hanging outside of the title at the beginning and
1363 ending.
1365 See source code for mode details.
1368 Detailed Behavior Description
1369 =============================
1371 Here are the gory details of the algorithm (it seems quite
1372 complicated, but really, it does the most obvious thing in all
1373 the particular cases):
1375 Before applying the adornment change, the cursor is placed on
1376 the closest line that could contain a section title.
1378 Case 1: No Adornment
1379 --------------------
1381 If the current line has no adornment around it,
1383 - search backwards for the last previous adornment, and apply
1384 the adornment one level lower to the current line. If there
1385 is no defined level below this previous adornment, we suggest
1386 the most appropriate of the `rst-preferred-adornments'.
1388 If REVERSE-DIRECTION is true, we simply use the previous
1389 adornment found directly.
1391 - if there is no adornment found in the given direction, we use
1392 the first of `rst-preferred-adornments'.
1394 The prefix argument forces a toggle of the prescribed adornment
1395 style.
1397 Case 2: Incomplete Adornment
1398 ----------------------------
1400 If the current line does have an existing adornment, but the
1401 adornment is incomplete, that is, the underline/overline does
1402 not extend to exactly the end of the title line (it is either too
1403 short or too long), we simply extend the length of the
1404 underlines/overlines to fit exactly the section title.
1406 If the prefix argument is given, we toggle the style of the
1407 adornment as well.
1409 REVERSE-DIRECTION has no effect in this case.
1411 Case 3: Complete Existing Adornment
1412 -----------------------------------
1414 If the adornment is complete (i.e. the underline (overline)
1415 length is already adjusted to the end of the title line), we
1416 search/parse the file to establish the hierarchy of all the
1417 adornments (making sure not to include the adornment around
1418 point), and we rotate the current title's adornment from within
1419 that list (by default, going *down* the hierarchy that is present
1420 in the file, i.e. to a lower section level). This is meant to be
1421 used potentially multiple times, until the desired adornment is
1422 found around the title.
1424 If we hit the boundary of the hierarchy, exactly one choice from
1425 the list of preferred adornments is suggested/chosen, the first
1426 of those adornment that has not been seen in the file yet (and
1427 not including the adornment around point), and the next
1428 invocation rolls over to the other end of the hierarchy (i.e. it
1429 cycles). This allows you to avoid having to set which character
1430 to use.
1432 If REVERSE-DIRECTION is true, the effect is to change the
1433 direction of rotation in the hierarchy of adornments, thus
1434 instead going *up* the hierarchy.
1436 However, if there is a non-negative prefix argument, we do not
1437 rotate the adornment, but instead simply toggle the style of the
1438 current adornment (this should be the most common way to toggle
1439 the style of an existing complete adornment).
1442 Point Location
1443 ==============
1445 The invocation of this function can be carried out anywhere
1446 within the section title line, on an existing underline or
1447 overline, as well as on an empty line following a section title.
1448 This is meant to be as convenient as possible.
1451 Indented Sections
1452 =================
1454 Indented section titles such as ::
1456 My Title
1457 --------
1459 are invalid in restructuredtext and thus not recognized by the
1460 parser. This code will thus not work in a way that would support
1461 indented sections (it would be ambiguous anyway).
1464 Joint Sections
1465 ==============
1467 Section titles that are right next to each other may not be
1468 treated well. More work might be needed to support those, and
1469 special conditions on the completeness of existing adornments
1470 might be required to make it non-ambiguous.
1472 For now we assume that the adornments are disjoint, that is,
1473 there is at least a single line between the titles/adornment
1474 lines."
1475 (let* (;; Check if we're on an underline around a section title, and move the
1476 ;; cursor to the title if this is the case.
1477 (moved (rst-normalize-cursor-position))
1479 ;; Find the adornment and completeness around point.
1480 (curado (rst-get-adornment))
1481 (char (car curado))
1482 (style (cadr curado))
1483 (indent (caddr curado))
1485 ;; New values to be computed.
1486 char-new style-new indent-new
1489 ;; We've moved the cursor... if we're not looking at some text, we have
1490 ;; nothing to do.
1491 (if (save-excursion (beginning-of-line)
1492 (looking-at (rst-re 'ttl-beg)))
1493 (progn
1494 (cond
1495 ;;-------------------------------------------------------------------
1496 ;; Case 1: No Adornment
1497 ((and (eq char nil) (eq style nil))
1499 (let* ((allados (rst-find-all-adornments))
1501 (around (rst-get-adornments-around allados))
1502 (prev (car around))
1505 (hier (rst-get-hierarchy allados))
1508 ;; Advance one level down.
1509 (setq cur
1510 (if prev
1511 (if (or (and rst-new-adornment-down reverse-direction)
1512 (and (not rst-new-adornment-down) (not reverse-direction)))
1513 prev
1514 (or (cadr (rst-get-adornment-match hier prev))
1515 (rst-suggest-new-adornment hier prev)))
1516 (copy-sequence (car rst-preferred-adornments))))
1518 ;; Invert the style if requested.
1519 (if toggle-style
1520 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1521 'over-and-under 'simple)) )
1523 (setq char-new (car cur)
1524 style-new (cadr cur)
1525 indent-new (caddr cur))
1528 ;;-------------------------------------------------------------------
1529 ;; Case 2: Incomplete Adornment
1530 ((not (rst-adornment-complete-p curado))
1532 ;; Invert the style if requested.
1533 (if toggle-style
1534 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1536 (setq char-new char
1537 style-new style
1538 indent-new indent))
1540 ;;-------------------------------------------------------------------
1541 ;; Case 3: Complete Existing Adornment
1543 (if toggle-style
1545 ;; Simply switch the style of the current adornment.
1546 (setq char-new char
1547 style-new (if (eq style 'simple) 'over-and-under 'simple)
1548 indent-new rst-default-indent)
1550 ;; Else, we rotate, ignoring the adornment around the current
1551 ;; line...
1552 (let* ((allados (rst-find-all-adornments))
1554 (hier (rst-get-hierarchy allados (line-number-at-pos)))
1556 ;; Suggestion, in case we need to come up with something
1557 ;; new
1558 (suggestion (rst-suggest-new-adornment
1559 hier
1560 (car (rst-get-adornments-around allados))))
1562 (nextado (rst-get-next-adornment
1563 curado hier suggestion reverse-direction))
1567 ;; Indent, if present, always overrides the prescribed indent.
1568 (setq char-new (car nextado)
1569 style-new (cadr nextado)
1570 indent-new (caddr nextado))
1575 ;; Override indent with present indent!
1576 (setq indent-new (if (> indent 0) indent indent-new))
1578 (if (and char-new style-new)
1579 (rst-update-section char-new style-new indent-new))
1583 ;; Correct the position of the cursor to more accurately reflect where it
1584 ;; was located when the function was invoked.
1585 (unless (= moved 0)
1586 (forward-line (- moved))
1587 (end-of-line))
1591 ;; Maintain an alias for compatibility.
1592 (defalias 'rst-adjust-section-title 'rst-adjust)
1595 (defun rst-promote-region (demote)
1596 "Promote the section titles within the region.
1598 With argument DEMOTE or a prefix argument, demote the section
1599 titles instead. The algorithm used at the boundaries of the
1600 hierarchy is similar to that used by `rst-adjust-adornment-work'."
1601 (interactive "P")
1603 (let* ((allados (rst-find-all-adornments))
1604 (cur allados)
1606 (hier (rst-get-hierarchy allados))
1607 (suggestion (rst-suggest-new-adornment hier))
1609 (region-begin-line (line-number-at-pos (region-beginning)))
1610 (region-end-line (line-number-at-pos (region-end)))
1612 marker-list
1615 ;; Skip the markers that come before the region beginning
1616 (while (and cur (< (caar cur) region-begin-line))
1617 (setq cur (cdr cur)))
1619 ;; Create a list of markers for all the adornments which are found within
1620 ;; the region.
1621 (save-excursion
1622 (let (m line)
1623 (while (and cur (< (setq line (caar cur)) region-end-line))
1624 (setq m (make-marker))
1625 (goto-char (point-min))
1626 (forward-line (1- line))
1627 (push (list (set-marker m (point)) (cdar cur)) marker-list)
1628 (setq cur (cdr cur)) ))
1630 ;; Apply modifications.
1631 (let (nextado)
1632 (dolist (p marker-list)
1633 ;; Go to the adornment to promote.
1634 (goto-char (car p))
1636 ;; Rotate the next adornment.
1637 (setq nextado (rst-get-next-adornment
1638 (cadr p) hier suggestion demote))
1640 ;; Update the adornment.
1641 (apply 'rst-update-section nextado)
1643 ;; Clear marker to avoid slowing down the editing after we're done.
1644 (set-marker (car p) nil)
1646 (setq deactivate-mark nil)
1651 (defun rst-display-adornments-hierarchy (&optional adornments)
1652 "Display the current file's section title adornments hierarchy.
1653 This function expects a list of (char, style, indent) triples in
1654 ADORNMENTS."
1655 (interactive)
1657 (if (not adornments)
1658 (setq adornments (rst-get-hierarchy)))
1659 (with-output-to-temp-buffer "*rest section hierarchy*"
1660 (let ((level 1))
1661 (with-current-buffer standard-output
1662 (dolist (x adornments)
1663 (insert (format "\nSection Level %d" level))
1664 (apply 'rst-update-section x)
1665 (goto-char (point-max))
1666 (insert "\n")
1667 (incf level)
1671 (defun rst-position (elem list)
1672 "Return position of ELEM in LIST or nil."
1673 (let ((tail (member elem list)))
1674 (if tail (- (length list) (length tail)))))
1676 (defun rst-straighten-adornments ()
1677 "Redo all the adornments in the current buffer.
1678 This is done using our preferred set of adornments. This can be
1679 used, for example, when using somebody else's copy of a document,
1680 in order to adapt it to our preferred style."
1681 (interactive)
1682 (save-excursion
1683 (let* ((allados (rst-find-all-adornments))
1684 (hier (rst-get-hierarchy allados))
1686 ;; Get a list of pairs of (level . marker)
1687 (levels-and-markers (mapcar
1688 (lambda (ado)
1689 (cons (rst-position (cdr ado) hier)
1690 (let ((m (make-marker)))
1691 (goto-char (point-min))
1692 (forward-line (1- (car ado)))
1693 (set-marker m (point))
1694 m)))
1695 allados))
1697 (dolist (lm levels-and-markers)
1698 ;; Go to the appropriate position
1699 (goto-char (cdr lm))
1701 ;; Apply the new styule
1702 (apply 'rst-update-section (nth (car lm) rst-preferred-adornments))
1704 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1705 (set-marker (cdr lm) nil)
1711 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1712 ;; Insert list items
1713 ;; =================
1716 ;=================================================
1717 ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>
1718 ; I needed to make some tiny changes to the functions, so I put it here.
1719 ; -- Wei-Wei Guo
1721 (defconst rst-arabic-to-roman
1722 '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
1723 (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
1724 (10 . "X") (9 . "IX") (5 . "V") (4 . "IV")
1725 (1 . "I"))
1726 "List of maps between Arabic numbers and their Roman numeral equivalents.")
1728 (defun rst-arabic-to-roman (num &optional arg)
1729 "Convert Arabic number NUM to its Roman numeral representation.
1731 Obviously, NUM must be greater than zero. Don't blame me, blame the
1732 Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
1733 apologies to Monty Python).
1734 If optional prefix ARG is non-nil, insert in current buffer."
1735 (let ((map rst-arabic-to-roman)
1736 res)
1737 (while (and map (> num 0))
1738 (if (or (= num (caar map))
1739 (> num (caar map)))
1740 (setq res (concat res (cdar map))
1741 num (- num (caar map)))
1742 (setq map (cdr map))))
1743 res))
1745 (defun rst-roman-to-arabic (string &optional arg)
1746 "Convert STRING of Roman numerals to an Arabic number.
1748 If STRING contains a letter which isn't a valid Roman numeral, the rest
1749 of the string from that point onwards is ignored.
1751 Hence:
1752 MMD == 2500
1754 MMDFLXXVI == 2500.
1755 If optional ARG is non-nil, insert in current buffer."
1756 (let ((res 0)
1757 (map rst-arabic-to-roman))
1758 (while map
1759 (if (string-match (concat "^" (cdar map)) string)
1760 (setq res (+ res (caar map))
1761 string (replace-match "" nil t string))
1762 (setq map (cdr map))))
1763 res))
1764 ;=================================================
1766 (defun rst-find-pfx-in-region (beg end pfx-re)
1767 "Find all the positions of prefixes in region between BEG and END.
1768 This is used to find bullets and enumerated list items. PFX-RE is
1769 a regular expression for matching the lines after indentation
1770 with items. Returns a list of cons cells consisting of the point
1771 and the column of the point."
1772 (let (pfx)
1773 (save-excursion
1774 (goto-char beg)
1775 (while (< (point) end)
1776 (back-to-indentation)
1777 (when (and
1778 (looking-at pfx-re) ; pfx found and...
1779 (let ((pfx-col (current-column)))
1780 (save-excursion
1781 (forward-line -1) ; ...previous line is...
1782 (back-to-indentation)
1783 (or (looking-at (rst-re 'lin-end)) ; ...empty,
1784 (> (current-column) pfx-col) ; ...deeper level, or
1785 (and (= (current-column) pfx-col)
1786 (looking-at pfx-re)))))) ; ...pfx at same level
1787 (push (cons (point) (current-column))
1788 pfx))
1789 (forward-line 1)) )
1790 (nreverse pfx)))
1792 (defun rst-insert-list-pos (newitem)
1793 "Arrange relative position of a newly inserted list item.
1795 Adding a new list might consider three situations:
1797 (a) Current line is a blank line.
1798 (b) Previous line is a blank line.
1799 (c) Following line is a blank line.
1801 When (a) and (b), just add the new list at current line.
1803 when (a) and not (b), a blank line is added before adding the new list.
1805 When not (a), first forward point to the end of the line, and add two
1806 blank lines, then add the new list.
1808 Other situations are just ignored and left to users themselves."
1809 (if (save-excursion
1810 (beginning-of-line)
1811 (looking-at (rst-re 'lin-end)))
1812 (if (save-excursion
1813 (forward-line -1)
1814 (looking-at (rst-re 'lin-end)))
1815 (insert newitem " ")
1816 (insert "\n" newitem " "))
1817 (end-of-line)
1818 (insert "\n\n" newitem " ")))
1820 (defvar rst-initial-enums
1821 (let (vals)
1822 (dolist (fmt '("%s." "(%s)" "%s)"))
1823 (dolist (c '("1" "a" "A" "I" "i"))
1824 (push (format fmt c) vals)))
1825 (cons "#." (nreverse vals)))
1826 "List of initial enumerations.")
1828 (defvar rst-initial-items
1829 (append (mapcar 'char-to-string rst-bullets) rst-initial-enums)
1830 "List of initial items. It's collection of bullets and enumerations.")
1832 (defun rst-insert-list-new-item ()
1833 "Insert a new list item.
1835 User is asked to select the item style first, for example (a), i), +. Use TAB
1836 for completition and choices.
1838 If user selects bullets or #, it's just added with position arranged by
1839 `rst-insert-list-pos'.
1841 If user selects enumerations, a further prompt is given. User need to input a
1842 starting item, for example 'e' for 'A)' style. The position is also arranged by
1843 `rst-insert-list-pos'."
1844 (interactive)
1845 ;; FIXME: Make this comply to `interactive' standards
1846 (let* ((itemstyle (completing-read
1847 "Select preferred item style [#.]: "
1848 rst-initial-items nil t nil nil "#."))
1849 (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle)
1850 (match-string 0 itemstyle)))
1852 (save-match-data
1853 ;; FIXME: Make this comply to `interactive' standards
1854 (cond
1855 ((equal cnt "a")
1856 (let ((itemno (read-string "Give starting value [a]: "
1857 nil nil "a")))
1858 (downcase (substring itemno 0 1))))
1859 ((equal cnt "A")
1860 (let ((itemno (read-string "Give starting value [A]: "
1861 nil nil "A")))
1862 (upcase (substring itemno 0 1))))
1863 ((equal cnt "I")
1864 (let ((itemno (read-number "Give starting value [1]: " 1)))
1865 (rst-arabic-to-roman itemno)))
1866 ((equal cnt "i")
1867 (let ((itemno (read-number "Give starting value [1]: " 1)))
1868 (downcase (rst-arabic-to-roman itemno))))
1869 ((equal cnt "1")
1870 (let ((itemno (read-number "Give starting value [1]: " 1)))
1871 (number-to-string itemno)))))))
1872 (if no
1873 (setq itemstyle (replace-match no t t itemstyle)))
1874 (rst-insert-list-pos itemstyle)))
1876 (defvar rst-preferred-bullets
1877 '(?- ?* ?+)
1878 "List of favourite bullets.")
1880 (defun rst-insert-list-continue (curitem prefer-roman)
1881 "Insert a list item with list start CURITEM including its indentation level."
1882 (end-of-line)
1883 (insert
1884 "\n" ; FIXME: Separating lines must be possible
1885 (cond
1886 ((string-match (rst-re '(:alt enmaut-tag
1887 bul-tag)) curitem)
1888 curitem)
1889 ((string-match (rst-re 'num-tag) curitem)
1890 (replace-match (number-to-string
1891 (1+ (string-to-number (match-string 0 curitem))))
1892 nil nil curitem))
1893 ((and (string-match (rst-re 'rom-tag) curitem)
1894 (save-match-data
1895 (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag
1896 (save-excursion
1897 ;; FIXME: Assumes one line list items without separating
1898 ;; empty lines
1899 (if (and (= (forward-line -1) 0)
1900 (looking-at (rst-re 'enmexp-beg)))
1901 (string-match
1902 (rst-re 'rom-tag)
1903 (match-string 0)) ; Previous was a roman tag
1904 prefer-roman)) ; Don't know - use flag
1905 t))) ; Not a letter tag
1906 (replace-match
1907 (let* ((old (match-string 0 curitem))
1908 (new (save-match-data
1909 (rst-arabic-to-roman
1910 (1+ (rst-roman-to-arabic
1911 (upcase old)))))))
1912 (if (equal old (upcase old))
1913 (upcase new)
1914 (downcase new)))
1915 t nil curitem))
1916 ((string-match (rst-re 'ltr-tag) curitem)
1917 (replace-match (char-to-string
1918 (1+ (string-to-char (match-string 0 curitem))))
1919 nil nil curitem)))))
1922 (defun rst-insert-list (&optional prefer-roman)
1923 "Insert a list item at the current point.
1925 The command can insert a new list or a continuing list. When it is called at a
1926 non-list line, it will promote to insert new list. When it is called at a list
1927 line, it will insert a list with the same list style.
1929 1. When inserting a new list:
1931 User is asked to select the item style first, for example (a), i), +. Use TAB
1932 for completition and choices.
1934 (a) If user selects bullets or #, it's just added.
1935 (b) If user selects enumerations, a further prompt is given. User needs to
1936 input a starting item, for example 'e' for 'A)' style.
1938 The position of the new list is arranged according to whether or not the
1939 current line and the previous line are blank lines.
1941 2. When continuing a list, one thing need to be noticed:
1943 List style alphabetical list, such as 'a.', and roman numerical list, such as
1944 'i.', have some overlapping items, for example 'v.' The function can deal with
1945 the problem elegantly in most situations. But when those overlapped list are
1946 preceded by a blank line, it is hard to determine which type to use
1947 automatically. The function uses alphabetical list by default. If you want
1948 roman numerical list, just use a prefix (\\[universal-argument])."
1949 (interactive "P")
1950 (beginning-of-line)
1951 (if (looking-at (rst-re 'itmany-beg-1))
1952 (rst-insert-list-continue (match-string 0) prefer-roman)
1953 (rst-insert-list-new-item)))
1955 (defun rst-straighten-bullets-region (beg end)
1956 "Make all the bulleted list items in the region consistent.
1957 The region is specified between BEG and END. You can use this
1958 after you have merged multiple bulleted lists to make them use
1959 the same/correct/consistent bullet characters.
1961 See variable `rst-preferred-bullets' for the list of bullets to
1962 adjust. If bullets are found on levels beyond the
1963 `rst-preferred-bullets' list, they are not modified."
1964 (interactive "r")
1966 (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta)))
1967 (levtable (make-hash-table :size 4)))
1969 ;; Create a map of levels to list of positions.
1970 (dolist (x bullets)
1971 (let ((key (cdr x)))
1972 (puthash key
1973 (append (gethash key levtable (list))
1974 (list (car x)))
1975 levtable)))
1977 ;; Sort this map and create a new map of prefix char and list of positions.
1978 (let ((poslist ())) ; List of (indent . positions).
1979 (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
1981 (let ((bullets rst-preferred-bullets))
1982 (dolist (x (sort poslist 'car-less-than-car))
1983 (when bullets
1984 ;; Apply the characters.
1985 (dolist (pos (cdr x))
1986 (goto-char pos)
1987 (delete-char 1)
1988 (insert (string (car bullets))))
1989 (setq bullets (cdr bullets))))))))
1992 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1993 ;; Table of contents
1994 ;; =================
1996 (defun rst-get-stripped-line ()
1997 "Return the line at cursor, stripped from whitespace."
1998 (re-search-forward (rst-re "\\S .*\\S ") (line-end-position))
1999 (buffer-substring-no-properties (match-beginning 0)
2000 (match-end 0)) )
2002 (defun rst-section-tree (allados)
2003 "Get the hierarchical tree of section titles.
2005 Returns a hierarchical tree of the sections titles in the
2006 document, for adornments ALLADOS. This can be used to generate
2007 a table of contents for the document. The top node will always
2008 be a nil node, with the top level titles as children (there may
2009 potentially be more than one).
2011 Each section title consists in a cons of the stripped title
2012 string and a marker to the section in the original text document.
2014 If there are missing section levels, the section titles are
2015 inserted automatically, and the title string is set to nil, and
2016 the marker set to the first non-nil child of itself.
2017 Conceptually, the nil nodes--i.e. those which have no title--are
2018 to be considered as being the same line as their first non-nil
2019 child. This has advantages later in processing the graph."
2021 (let* ((hier (rst-get-hierarchy allados))
2022 (levels (make-hash-table :test 'equal :size 10))
2023 lines)
2025 (let ((lev 0))
2026 (dolist (ado hier)
2027 ;; Compare just the character and indent in the hash table.
2028 (puthash (cons (car ado) (cadr ado)) lev levels)
2029 (incf lev)))
2031 ;; Create a list of lines that contains (text, level, marker) for each
2032 ;; adornment.
2033 (save-excursion
2034 (setq lines
2035 (mapcar (lambda (ado)
2036 (goto-char (point-min))
2037 (forward-line (1- (car ado)))
2038 (list (gethash (cons (cadr ado) (caddr ado)) levels)
2039 (rst-get-stripped-line)
2040 (let ((m (make-marker)))
2041 (beginning-of-line 1)
2042 (set-marker m (point)))
2044 allados)))
2046 (let ((lcontnr (cons nil lines)))
2047 (rst-section-tree-rec lcontnr -1))))
2050 (defun rst-section-tree-rec (ados lev)
2051 "Recursive guts of the section tree construction.
2052 ADOS is a cons cell whose cdr is the remaining list of
2053 adornments, and we change it as we consume them. LEV is
2054 the current level of that node. This function returns a
2055 pair of the subtree that was built. This treats the ADOS
2056 list destructively."
2058 (let ((nado (cadr ados))
2059 node
2060 children)
2062 ;; If the next adornment matches our level
2063 (when (and nado (= (car nado) lev))
2064 ;; Pop the next adornment and create the current node with it
2065 (setcdr ados (cddr ados))
2066 (setq node (cdr nado)) )
2067 ;; Else we let the node title/marker be unset.
2069 ;; Build the child nodes
2070 (while (and (cdr ados) (> (caadr ados) lev))
2071 (setq children
2072 (cons (rst-section-tree-rec ados (1+ lev))
2073 children)))
2074 (setq children (reverse children))
2076 ;; If node is still unset, we use the marker of the first child.
2077 (when (eq node nil)
2078 (setq node (cons nil (cdaar children))))
2080 ;; Return this node with its children.
2081 (cons node children)
2085 (defun rst-section-tree-point (node &optional point)
2086 "Find tree node at point.
2087 Given a computed and valid section tree in NODE and a point
2088 POINT (default being the current point in the current buffer),
2089 find and return the node within the sectree where the cursor
2090 lives.
2092 Return values: a pair of (parent path, container subtree).
2093 The parent path is simply a list of the nodes above the
2094 container subtree node that we're returning."
2096 (let (path outtree)
2098 (let* ((curpoint (or point (point))))
2100 ;; Check if we are before the current node.
2101 (if (and (cadar node) (>= curpoint (cadar node)))
2103 ;; Iterate all the children, looking for one that might contain the
2104 ;; current section.
2105 (let ((curnode (cdr node))
2106 last)
2108 (while (and curnode (>= curpoint (cadaar curnode)))
2109 (setq last curnode
2110 curnode (cdr curnode)))
2112 (if last
2113 (let ((sub (rst-section-tree-point (car last) curpoint)))
2114 (setq path (car sub)
2115 outtree (cdr sub)))
2116 (setq outtree node))
2119 (cons (cons (car node) path) outtree)
2123 (defgroup rst-toc nil
2124 "Settings for reStructuredText table of contents."
2125 :group 'rst
2126 :version "21.1")
2128 (defcustom rst-toc-indent 2
2129 "Indentation for table-of-contents display.
2130 Also used for formatting insertion, when numbering is disabled."
2131 :group 'rst-toc)
2133 (defcustom rst-toc-insert-style 'fixed
2134 "Insertion style for table-of-contents.
2135 Set this to one of the following values to determine numbering and
2136 indentation style:
2137 - plain: no numbering (fixed indentation)
2138 - fixed: numbering, but fixed indentation
2139 - aligned: numbering, titles aligned under each other
2140 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
2141 :group 'rst-toc)
2143 (defcustom rst-toc-insert-number-separator " "
2144 "Separator that goes between the TOC number and the title."
2145 :group 'rst-toc)
2147 ;; This is used to avoid having to change the user's mode.
2148 (defvar rst-toc-insert-click-keymap
2149 (let ((map (make-sparse-keymap)))
2150 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
2151 map)
2152 "(Internal) What happens when you click on propertized text in the TOC.")
2154 (defcustom rst-toc-insert-max-level nil
2155 "If non-nil, maximum depth of the inserted TOC."
2156 :group 'rst-toc)
2159 (defun rst-toc-insert (&optional pfxarg)
2160 "Insert a simple text rendering of the table of contents.
2161 By default the top level is ignored if there is only one, because
2162 we assume that the document will have a single title.
2164 If a numeric prefix argument PFXARG is given, insert the TOC up
2165 to the specified level.
2167 The TOC is inserted indented at the current column."
2169 (interactive "P")
2171 (let* (;; Check maximum level override
2172 (rst-toc-insert-max-level
2173 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
2174 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
2176 ;; Get the section tree for the current cursor point.
2177 (sectree-pair
2178 (rst-section-tree-point
2179 (rst-section-tree (rst-find-all-adornments))))
2181 ;; Figure out initial indent.
2182 (initial-indent (make-string (current-column) ? ))
2183 (init-point (point)))
2185 (when (cddr sectree-pair)
2186 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
2188 ;; Fixup for the first line.
2189 (delete-region init-point (+ init-point (length initial-indent)))
2191 ;; Delete the last newline added.
2192 (delete-backward-char 1)
2195 (defun rst-toc-insert-node (node level indent pfx)
2196 "Insert tree node NODE in table-of-contents.
2197 Recursive function that does printing of the inserted toc.
2198 LEVEL is the depth level of the sections in the tree.
2199 INDENT is the indentation string. PFX is the prefix numbering,
2200 that includes the alignment necessary for all the children of
2201 level to align."
2203 ;; Note: we do child numbering from the parent, so we start number the
2204 ;; children one level before we print them.
2205 (let ((do-print (> level 0))
2206 (count 1))
2207 (when do-print
2208 (insert indent)
2209 (let ((b (point)))
2210 (unless (equal rst-toc-insert-style 'plain)
2211 (insert pfx rst-toc-insert-number-separator))
2212 (insert (or (caar node) "[missing node]"))
2213 ;; Add properties to the text, even though in normal text mode it
2214 ;; won't be doing anything for now. Not sure that I want to change
2215 ;; mode stuff. At least the highlighting gives the idea that this
2216 ;; is generated automatically.
2217 (put-text-property b (point) 'mouse-face 'highlight)
2218 (put-text-property b (point) 'rst-toc-target (cadar node))
2219 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
2222 (insert "\n")
2224 ;; Prepare indent for children.
2225 (setq indent
2226 (cond
2227 ((eq rst-toc-insert-style 'plain)
2228 (concat indent (make-string rst-toc-indent ? )))
2230 ((eq rst-toc-insert-style 'fixed)
2231 (concat indent (make-string rst-toc-indent ? )))
2233 ((eq rst-toc-insert-style 'aligned)
2234 (concat indent (make-string (+ (length pfx) 2) ? )))
2236 ((eq rst-toc-insert-style 'listed)
2237 (concat (substring indent 0 -3)
2238 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
2242 (if (or (eq rst-toc-insert-max-level nil)
2243 (< level rst-toc-insert-max-level))
2244 (let ((do-child-numbering (>= level 0))
2245 fmt)
2246 (if do-child-numbering
2247 (progn
2248 ;; Add a separating dot if there is already a prefix
2249 (when (> (length pfx) 0)
2250 (string-match (rst-re "[ \t\n]*\\'") pfx)
2251 (setq pfx (concat (replace-match "" t t pfx) ".")))
2253 ;; Calculate the amount of space that the prefix will require
2254 ;; for the numbers.
2255 (if (cdr node)
2256 (setq fmt (format "%%-%dd"
2257 (1+ (floor (log10 (length
2258 (cdr node))))))))
2261 (dolist (child (cdr node))
2262 (rst-toc-insert-node child
2263 (1+ level)
2264 indent
2265 (if do-child-numbering
2266 (concat pfx (format fmt count)) pfx))
2267 (incf count)))
2272 (defun rst-toc-update ()
2273 "Automatically find the contents section of a document and update.
2274 Updates the inserted TOC if present. You can use this in your
2275 file-write hook to always make it up-to-date automatically."
2276 (interactive)
2277 (save-excursion
2278 ;; Find and delete an existing comment after the first contents directive.
2279 ;; Delete that region.
2280 (goto-char (point-min))
2281 ;; We look for the following and the following only (in other words, if your
2282 ;; syntax differs, this won't work.).
2284 ;; .. contents:: [...anything here...]
2285 ;; [:field: value]...
2286 ;; ..
2287 ;; XXXXXXXX
2288 ;; XXXXXXXX
2289 ;; [more lines]
2290 (let ((beg (re-search-forward
2291 (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n"
2292 "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t))
2293 last-real)
2294 (when beg
2295 ;; Look for the first line that starts at the first column.
2296 (forward-line 1)
2297 (while (and
2298 (< (point) (point-max))
2299 (or (if (looking-at
2300 (rst-re 'hws-sta "\\S ")) ; indented content
2301 (setq last-real (point)))
2302 (looking-at (rst-re 'lin-end)))) ; empty line
2303 (forward-line 1))
2304 (if last-real
2305 (progn
2306 (goto-char last-real)
2307 (end-of-line)
2308 (delete-region beg (point)))
2309 (goto-char beg))
2310 (insert "\n ")
2311 (rst-toc-insert))))
2312 ;; Note: always return nil, because this may be used as a hook.
2313 nil)
2315 ;; Note: we cannot bind the TOC update on file write because it messes with
2316 ;; undo. If we disable undo, since it adds and removes characters, the
2317 ;; positions in the undo list are not making sense anymore. Dunno what to do
2318 ;; with this, it would be nice to update when saving.
2320 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
2321 ;; (defun rst-toc-update-fun ()
2322 ;; ;; Disable undo for the write file hook.
2323 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
2325 (defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat.
2327 ;;------------------------------------------------------------------------------
2329 (defun rst-toc-node (node level)
2330 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
2332 (if (> level 0)
2333 (let ((b (point)))
2334 ;; Insert line text.
2335 (insert (make-string (* rst-toc-indent (1- level)) ? ))
2336 (insert (or (caar node) "[missing node]"))
2338 ;; Highlight lines.
2339 (put-text-property b (point) 'mouse-face 'highlight)
2341 ;; Add link on lines.
2342 (put-text-property b (point) 'rst-toc-target (cadar node))
2344 (insert "\n")
2347 (dolist (child (cdr node))
2348 (rst-toc-node child (1+ level))))
2350 (defun rst-toc-count-lines (node target-node)
2351 "Count the number of lines from NODE to the TARGET-NODE node.
2352 This recursive function returns a cons of the number of
2353 additional lines that have been counted for its node and
2354 children, and t if the node has been found."
2356 (let ((count 1)
2357 found)
2358 (if (eq node target-node)
2359 (setq found t)
2360 (let ((child (cdr node)))
2361 (while (and child (not found))
2362 (let ((cl (rst-toc-count-lines (car child) target-node)))
2363 (setq count (+ count (car cl))
2364 found (cdr cl)
2365 child (cdr child))))))
2366 (cons count found)))
2368 (defvar rst-toc-buffer-name "*Table of Contents*"
2369 "Name of the Table of Contents buffer.")
2371 (defvar rst-toc-return-buffer nil
2372 "Window configuration to which to return when leaving the TOC.")
2375 (defun rst-toc ()
2376 "Display a table-of-contents.
2377 Finds all the section titles and their adornments in the
2378 file, and displays a hierarchically-organized list of the
2379 titles, which is essentially a table-of-contents of the
2380 document.
2382 The Emacs buffer can be navigated, and selecting a section
2383 brings the cursor in that section."
2384 (interactive)
2385 (let* ((curbuf (list (current-window-configuration) (point-marker)))
2387 ;; Get the section tree
2388 (allados (rst-find-all-adornments))
2389 (sectree (rst-section-tree allados))
2391 (our-node (cdr (rst-section-tree-point sectree)))
2392 line
2394 ;; Create a temporary buffer.
2395 (buf (get-buffer-create rst-toc-buffer-name))
2398 (with-current-buffer buf
2399 (let ((inhibit-read-only t))
2400 (rst-toc-mode)
2401 (delete-region (point-min) (point-max))
2402 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
2403 (put-text-property (point-min) (point)
2404 'face (list '(background-color . "gray")))
2405 (rst-toc-node sectree 0)
2407 ;; Count the lines to our found node.
2408 (let ((linefound (rst-toc-count-lines sectree our-node)))
2409 (setq line (if (cdr linefound) (car linefound) 0)))
2411 (display-buffer buf)
2412 (pop-to-buffer buf)
2414 ;; Save the buffer to return to.
2415 (set (make-local-variable 'rst-toc-return-buffer) curbuf)
2417 ;; Move the cursor near the right section in the TOC.
2418 (goto-char (point-min))
2419 (forward-line (1- line))
2423 (defun rst-toc-mode-find-section ()
2424 "Get the section from text property at point."
2425 (let ((pos (get-text-property (point) 'rst-toc-target)))
2426 (unless pos
2427 (error "No section on this line"))
2428 (unless (buffer-live-p (marker-buffer pos))
2429 (error "Buffer for this section was killed"))
2430 pos))
2432 ;; FIXME: Cursor before of behind the list must be handled properly, before the
2433 ;; list should jump to the top and behind the list to the last normal
2434 ;; paragraph
2435 (defun rst-goto-section (&optional kill)
2436 "Go to the section the current line describes."
2437 (interactive)
2438 (let ((pos (rst-toc-mode-find-section)))
2439 (when kill
2440 (set-window-configuration (car rst-toc-return-buffer))
2441 (kill-buffer (get-buffer rst-toc-buffer-name)))
2442 (pop-to-buffer (marker-buffer pos))
2443 (goto-char pos)
2444 ;; FIXME: make the recentering conditional on scroll.
2445 (recenter 5)))
2447 (defun rst-toc-mode-goto-section ()
2448 "Go to the section the current line describes and kill the TOC buffer."
2449 (interactive)
2450 (rst-goto-section t))
2452 (defun rst-toc-mode-mouse-goto (event)
2453 "In `rst-toc' mode, go to the occurrence whose line you click on.
2454 EVENT is the input event."
2455 (interactive "e")
2456 (let (pos)
2457 (with-current-buffer (window-buffer (posn-window (event-end event)))
2458 (save-excursion
2459 (goto-char (posn-point (event-end event)))
2460 (setq pos (rst-toc-mode-find-section))))
2461 (pop-to-buffer (marker-buffer pos))
2462 (goto-char pos)
2463 (recenter 5)))
2465 (defun rst-toc-mode-mouse-goto-kill (event)
2466 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well."
2467 (interactive "e")
2468 (call-interactively 'rst-toc-mode-mouse-goto event)
2469 (kill-buffer (get-buffer rst-toc-buffer-name)))
2471 (defun rst-toc-quit-window ()
2472 "Leave the current TOC buffer."
2473 (interactive)
2474 (let ((retbuf rst-toc-return-buffer))
2475 (set-window-configuration (car retbuf))
2476 (goto-char (cadr retbuf))))
2478 (defvar rst-toc-mode-map
2479 (let ((map (make-sparse-keymap)))
2480 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2481 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2482 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2483 (define-key map "f" 'rst-toc-mode-goto-section)
2484 (define-key map "q" 'rst-toc-quit-window)
2485 (define-key map "z" 'kill-this-buffer)
2486 map)
2487 "Keymap for `rst-toc-mode'.")
2489 (put 'rst-toc-mode 'mode-class 'special)
2491 ;; Could inherit from the new `special-mode'.
2492 (define-derived-mode rst-toc-mode nil "ReST-TOC"
2493 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2494 (setq buffer-read-only t))
2496 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2497 ;; features.
2500 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2501 ;; Section movement commands
2502 ;; =========================
2504 (defun rst-forward-section (&optional offset)
2505 "Skip to the next restructured text section title.
2506 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2507 backwards in the file (default is to use 1)."
2508 (interactive)
2509 (let* (;; Default value for offset.
2510 (offset (or offset 1))
2512 ;; Get all the adornments in the file, with their line numbers.
2513 (allados (rst-find-all-adornments))
2515 ;; Get the current line.
2516 (curline (line-number-at-pos))
2518 (cur allados)
2519 (idx 0)
2522 ;; Find the index of the "next" adornment w.r.t. to the current line.
2523 (while (and cur (< (caar cur) curline))
2524 (setq cur (cdr cur))
2525 (incf idx))
2526 ;; 'cur' is the adornment on or following the current line.
2528 (if (and (> offset 0) cur (= (caar cur) curline))
2529 (incf idx))
2531 ;; Find the final index.
2532 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2533 (setq cur (nth idx allados))
2535 ;; If the index is positive, goto the line, otherwise go to the buffer
2536 ;; boundaries.
2537 (if (and cur (>= idx 0))
2538 (progn
2539 (goto-char (point-min))
2540 (forward-line (1- (car cur))))
2541 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
2544 (defun rst-backward-section ()
2545 "Like `rst-forward-section', except move back one title."
2546 (interactive)
2547 (rst-forward-section -1))
2549 (defun rst-mark-section (&optional arg allow-extend)
2550 "Select the section that point is currently in."
2551 ;; Cloned from mark-paragraph.
2552 (interactive "p\np")
2553 (unless arg (setq arg 1))
2554 (when (zerop arg)
2555 (error "Cannot mark zero sections"))
2556 (cond ((and allow-extend
2557 (or (and (eq last-command this-command) (mark t))
2558 (rst-portable-mark-active-p)))
2559 (set-mark
2560 (save-excursion
2561 (goto-char (mark))
2562 (rst-forward-section arg)
2563 (point))))
2565 (rst-forward-section arg)
2566 (push-mark nil t t)
2567 (rst-forward-section (- arg)))))
2570 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2571 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2572 ;; always 2 or 3 characters apart horizontally with rest.
2574 ;; (FIXME: there is currently a bug that makes the region go away when we do that.)
2575 (defvar rst-shift-fill-region nil
2576 "If non-nil, automatically re-fill the region that is being shifted.")
2578 (defun rst-find-leftmost-column (beg end)
2579 "Find the leftmost column in the region."
2580 (let ((mincol 1000))
2581 (save-excursion
2582 (goto-char beg)
2583 (while (< (point) end)
2584 (back-to-indentation)
2585 (unless (looking-at (rst-re 'lin-end))
2586 (setq mincol (min mincol (current-column))))
2587 (forward-line 1)
2589 mincol))
2592 ;; What we really need to do is compute all the possible alignment possibilities
2593 ;; and then select one.
2595 ;; .. line-block::
2597 ;; a) sdjsds
2599 ;; - sdjsd jsjds
2601 ;; sdsdsjdsj
2603 ;; 11. sjdss jddjs
2605 ;; * * * * * * *
2607 ;; Move backwards, accumulate the beginning positions, and also the second
2608 ;; positions, in case the line matches the bullet pattern, and then sort.
2610 (defun rst-compute-bullet-tabs (&optional pt)
2611 "Build the list of possible horizontal alignment points.
2612 Search backwards from point (or point PT if specified) to
2613 build the list of possible horizontal alignment points that
2614 includes the beginning and contents of a restructuredtext
2615 bulleted or enumerated list item. Return a sorted list
2616 of (COLUMN-NUMBER . LINE) pairs."
2617 (save-excursion
2618 (when pt (goto-char pt))
2620 ;; We work our way backwards and towards the left.
2621 (let ((leftcol 100000) ; Current column.
2622 (tablist nil) ; List of tab positions.
2625 ;; Start by skipping the current line.
2626 (forward-line -1)
2628 ;; Search backwards for each line.
2629 (while (and (> (point) (point-min))
2630 (> leftcol 0))
2632 ;; Skip empty lines.
2633 (unless (looking-at (rst-re 'lin-end))
2634 ;; Inspect the current non-empty line
2635 (back-to-indentation)
2637 ;; Skip lines that are beyond the current column (we want to move
2638 ;; towards the left).
2639 (let ((col (current-column)))
2640 (when (< col leftcol)
2642 ;; Add the beginning of the line as a tabbing point.
2643 (unless (memq col (mapcar 'car tablist))
2644 (push (cons col (point)) tablist))
2646 ;; Look at the line to figure out if it is a bulleted or enumerate
2647 ;; list item.
2648 (when (looking-at (rst-re
2649 `(:grp
2650 (:alt
2651 itmany-tag
2652 ;; FIXME: What does this mean?
2653 (:seq ,(char-after) "\\{2,\\}"))
2654 hws-sta)
2655 "\\S "))
2656 ;; Add the column of the contained item.
2657 (let* ((matchlen (length (match-string 1)))
2658 (newcol (+ col matchlen)))
2659 (unless (or (>= newcol leftcol)
2660 (memq (+ col matchlen) (mapcar 'car tablist)))
2661 (push (cons (+ col matchlen) (+ (point) matchlen))
2662 tablist)))
2665 (setq leftcol col)
2668 (forward-line -1))
2670 (sort tablist (lambda (x y) (<= (car x) (car y))))
2673 (defun rst-debug-print-tabs (tablist)
2674 "Insert a line and place special characters at the tab points in TABLIST."
2675 (beginning-of-line)
2676 (insert (concat "\n" (make-string 1000 ? ) "\n"))
2677 (beginning-of-line 0)
2678 (dolist (col tablist)
2679 (beginning-of-line)
2680 (forward-char (car col))
2681 (delete-char 1)
2682 (insert "@")
2685 (defun rst-debug-mark-found (tablist)
2686 "Insert a line and place special characters at the tab points in TABLIST."
2687 (dolist (col tablist)
2688 (when (cdr col)
2689 (goto-char (cdr col))
2690 (insert "@"))))
2693 (defvar rst-shift-basic-offset 2
2694 "Basic horizontal shift distance when there is no preceding alignment tabs.")
2696 (defun rst-shift-region-guts (find-next-fun offset-fun)
2697 "(See `rst-shift-region-right' for a description)."
2698 (let* ((mbeg (set-marker (make-marker) (region-beginning)))
2699 (mend (set-marker (make-marker) (region-end)))
2700 (tabs (rst-compute-bullet-tabs mbeg))
2701 (leftmostcol (rst-find-leftmost-column (region-beginning) (region-end)))
2703 ;; Add basic offset tabs at the end of the list. This is a better
2704 ;; implementation technique than hysteresis and a basic offset because it
2705 ;; insures that movement in both directions is consistently using the same
2706 ;; column positions. This makes it more predictable.
2707 (setq tabs
2708 (append tabs
2709 (mapcar (lambda (x) (cons x nil))
2710 (let ((maxcol 120)
2711 (max-lisp-eval-depth 2000))
2712 (flet ((addnum (x)
2713 (if (> x maxcol)
2715 (cons x (addnum
2716 (+ x rst-shift-basic-offset))))))
2717 (addnum (or (caar (last tabs)) 0))))
2720 ;; (For debugging.)
2721 ;;; (save-excursion (goto-char mbeg) (forward-char -1) (rst-debug-print-tabs tabs))))
2722 ;;; (print tabs)
2723 ;;; (save-excursion (rst-debug-mark-found tabs))
2725 ;; Apply the indent.
2726 (indent-rigidly
2727 mbeg mend
2729 ;; Find the next tab after the leftmost columnt.
2730 (let ((tab (funcall find-next-fun tabs leftmostcol)))
2732 (if tab
2733 (progn
2734 (when (cdar tab)
2735 (message "Aligned on '%s'"
2736 (save-excursion
2737 (goto-char (cdar tab))
2738 (buffer-substring-no-properties
2739 (line-beginning-position)
2740 (line-end-position))))
2742 (- (caar tab) leftmostcol)) ; Num chars.
2744 ;; Otherwise use the basic offset
2745 (funcall offset-fun rst-shift-basic-offset)
2748 ;; Optionally reindent.
2749 (when rst-shift-fill-region
2750 (fill-region mbeg mend))
2753 ;; FIXME Doesn't keep the region
2754 ;; FIXME Should work more like `indent-rigidly'
2755 (defun rst-shift-region-right (pfxarg)
2756 "Indent region ridigly, by a few characters to the right.
2757 This function first computes all possible alignment columns by
2758 inspecting the lines preceding the region for bulleted or
2759 enumerated list items. If the leftmost column is beyond the
2760 preceding lines, the region is moved to the right by
2761 `rst-shift-basic-offset'. With a prefix argument, do not
2762 automatically fill the region."
2763 (interactive "P")
2764 (let ((rst-shift-fill-region
2765 (if (not pfxarg) rst-shift-fill-region)))
2766 (rst-shift-region-guts (lambda (tabs leftmostcol)
2767 (let ((cur tabs))
2768 (while (and cur (<= (caar cur) leftmostcol))
2769 (setq cur (cdr cur)))
2770 cur))
2771 'identity
2774 (defun rst-shift-region-left (pfxarg)
2775 "Like `rst-shift-region-right', except we move to the left.
2776 Also, if invoked with a negative prefix arg, the entire
2777 indentation is removed, up to the leftmost character in the
2778 region, and automatic filling is disabled."
2779 (interactive "P")
2780 (let ((mbeg (set-marker (make-marker) (region-beginning)))
2781 (mend (set-marker (make-marker) (region-end)))
2782 (leftmostcol (rst-find-leftmost-column
2783 (region-beginning) (region-end)))
2784 (rst-shift-fill-region
2785 (if (not pfxarg) rst-shift-fill-region)))
2787 (when (> leftmostcol 0)
2788 (if (and pfxarg (< (prefix-numeric-value pfxarg) 0))
2789 (progn
2790 (indent-rigidly (region-beginning) (region-end) (- leftmostcol))
2791 (when rst-shift-fill-region
2792 (fill-region mbeg mend))
2794 (rst-shift-region-guts (lambda (tabs leftmostcol)
2795 (let ((cur (reverse tabs)))
2796 (while (and cur (>= (caar cur) leftmostcol))
2797 (setq cur (cdr cur)))
2798 cur))
2803 (defmacro rst-iterate-leftmost-paragraphs
2804 (beg end first-only body-consequent body-alternative)
2805 "FIXME This definition is old and deprecated / we need to move
2806 to the newer version below:
2808 Call FUN at the beginning of each line, with an argument that
2809 specifies whether we are at the first line of a paragraph that
2810 starts at the leftmost column of the given region BEG and END.
2811 Set FIRST-ONLY to true if you want to callback on the first line
2812 of each paragraph only."
2813 `(save-excursion
2814 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2815 (endm (set-marker (make-marker) ,end))
2818 (do* (;; Iterate lines
2819 (l (progn (goto-char ,beg) (back-to-indentation))
2820 (progn (forward-line 1) (back-to-indentation)))
2822 (previous nil valid)
2824 (curcol (current-column)
2825 (current-column))
2827 (valid (and (= curcol leftcol)
2828 (not (looking-at (rst-re 'lin-end))))
2829 (and (= curcol leftcol)
2830 (not (looking-at (rst-re 'lin-end)))))
2832 ((>= (point) endm))
2834 (if (if ,first-only
2835 (and valid (not previous))
2836 valid)
2837 ,body-consequent
2838 ,body-alternative)
2840 ))))
2843 (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2844 "Evaluate BODY for each line in region defined by BEG END.
2845 LEFTMOST is set to true if the line is one of the leftmost of the
2846 entire paragraph. PARABEGIN is set to true if the line is the
2847 first of a paragraph."
2848 (declare (indent 1) (debug (sexp body)))
2849 (destructuring-bind
2850 (beg end parabegin leftmost isleftmost isempty) spec
2852 `(save-excursion
2853 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2854 (endm (set-marker (make-marker) ,end))
2857 (do* (;; Iterate lines
2858 (l (progn (goto-char ,beg) (back-to-indentation))
2859 (progn (forward-line 1) (back-to-indentation)))
2861 (empty-line-previous nil ,isempty)
2863 (,isempty (looking-at (rst-re 'lin-end))
2864 (looking-at (rst-re 'lin-end)))
2866 (,parabegin (not ,isempty)
2867 (and empty-line-previous
2868 (not ,isempty)))
2870 (,isleftmost (and (not ,isempty)
2871 (= (current-column) ,leftmost))
2872 (and (not ,isempty)
2873 (= (current-column) ,leftmost)))
2875 ((>= (point) endm))
2877 (progn ,@body)
2879 )))))
2882 ;;------------------------------------------------------------------------------
2884 ;; FIXME: these next functions should become part of a larger effort to redo the
2885 ;; bullets in bulletted lists. The enumerate would just be one of the possible
2886 ;; outputs.
2888 ;; FIXME: TODO we need to do the enumeration removal as well.
2890 (defun rst-enumerate-region (beg end all)
2891 "Add enumeration to all the leftmost paragraphs in the given region.
2892 The region is specified between BEG and END. With ALL,
2893 do all lines instead of just paragraphs."
2894 (interactive "r\nP")
2895 (let ((count 0)
2896 (last-insert-len nil))
2897 (rst-iterate-leftmost-paragraphs
2898 beg end (not all)
2899 (let ((ins-string (format "%d. " (incf count))))
2900 (setq last-insert-len (length ins-string))
2901 (insert ins-string))
2902 (insert (make-string last-insert-len ?\ ))
2905 (defun rst-bullet-list-region (beg end all)
2906 "Add bullets to all the leftmost paragraphs in the given region.
2907 The region is specified between BEG and END. With ALL,
2908 do all lines instead of just paragraphs."
2909 (interactive "r\nP")
2910 (rst-iterate-leftmost-paragraphs
2911 beg end (not all)
2912 (insert (car rst-preferred-bullets) " ")
2913 (insert " ")
2917 ;; FIXME: there are some problems left with the following function
2918 ;; implementation:
2920 ;; * It does not deal with a varying number of digits appropriately
2921 ;; * It does not deal with multiple levels independently, and it should.
2923 ;; I suppose it does 90% of the job for now.
2925 (defun rst-convert-bullets-to-enumeration (beg end)
2926 "Convert the bulleted and enumerated items in the region to enumerated lists.
2927 Renumber as necessary."
2928 (interactive "r")
2929 (let* (;; Find items and convert the positions to markers.
2930 (items (mapcar
2931 (lambda (x)
2932 (cons (let ((m (make-marker)))
2933 (set-marker m (car x))
2935 (cdr x)))
2936 (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1))))
2937 (count 1)
2939 (save-excursion
2940 (dolist (x items)
2941 (goto-char (car x))
2942 (looking-at (rst-re 'itmany-beg-1))
2943 (replace-match (format "%d." count) nil nil nil 1)
2944 (incf count)
2950 ;;------------------------------------------------------------------------------
2952 (defun rst-line-block-region (rbeg rend &optional pfxarg)
2953 "Toggle line block prefixes for a region.
2954 With prefix argument set the empty lines too."
2955 (interactive "r\nP")
2956 (let ((comment-start "| ")
2957 (comment-end "")
2958 (comment-start-skip "| ")
2959 (comment-style 'indent)
2960 (force (not (not pfxarg))))
2961 (rst-iterate-leftmost-paragraphs-2
2962 (rbeg rend parbegin leftmost isleft isempty)
2963 (when (or force (not isempty))
2964 (move-to-column leftmost force)
2965 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
2966 (insert "| ")))))
2970 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2971 ;; Font lock
2972 ;; =========
2974 (require 'font-lock)
2976 (defgroup rst-faces nil "Faces used in Rst Mode."
2977 :group 'rst
2978 :group 'faces
2979 :version "21.1")
2981 (defcustom rst-block-face 'font-lock-keyword-face
2982 "All syntax marking up a special block."
2983 :group 'rst-faces
2984 :type '(face))
2986 (defcustom rst-external-face 'font-lock-type-face
2987 "Field names and interpreted text."
2988 :group 'rst-faces
2989 :type '(face))
2991 (defcustom rst-definition-face 'font-lock-function-name-face
2992 "All other defining constructs."
2993 :group 'rst-faces
2994 :type '(face))
2996 (defcustom rst-directive-face
2997 ;; XEmacs compatibility
2998 (if (boundp 'font-lock-builtin-face)
2999 'font-lock-builtin-face
3000 'font-lock-preprocessor-face)
3001 "Directives and roles."
3002 :group 'rst-faces
3003 :type '(face))
3005 (defcustom rst-comment-face 'font-lock-comment-face
3006 "Comments."
3007 :group 'rst-faces
3008 :type '(face))
3010 (defcustom rst-emphasis1-face
3011 ;; XEmacs compatibility
3012 (if (facep 'italic)
3013 ''italic
3014 'italic)
3015 "Simple emphasis."
3016 :group 'rst-faces
3017 :type '(face))
3019 (defcustom rst-emphasis2-face
3020 ;; XEmacs compatibility
3021 (if (facep 'bold)
3022 ''bold
3023 'bold)
3024 "Double emphasis."
3025 :group 'rst-faces
3026 :type '(face))
3028 (defcustom rst-literal-face 'font-lock-string-face
3029 "Literal text."
3030 :group 'rst-faces
3031 :type '(face))
3033 (defcustom rst-reference-face 'font-lock-variable-name-face
3034 "References to a definition."
3035 :group 'rst-faces
3036 :type '(face))
3038 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3040 (defgroup rst-faces-defaults nil
3041 "Values used to generate default faces for section titles on all levels.
3042 Tweak these if you are content with how section title faces are built in
3043 general but you do not like the details."
3044 :group 'rst-faces
3045 :version "21.1")
3047 (defun rst-set-level-default (sym val)
3048 "Set custom var SYM affecting section title text face and recompute the faces."
3049 (custom-set-default sym val)
3050 ;; Also defines the faces initially when all values are available
3051 (and (boundp 'rst-level-face-max)
3052 (boundp 'rst-level-face-format-light)
3053 (boundp 'rst-level-face-base-color)
3054 (boundp 'rst-level-face-step-light)
3055 (boundp 'rst-level-face-base-light)
3056 (fboundp 'rst-define-level-faces)
3057 (rst-define-level-faces)))
3059 ;; Faces for displaying items on several levels; these definitions define
3060 ;; different shades of grey where the lightest one (i.e. least contrasting) is
3061 ;; used for level 1
3062 (defcustom rst-level-face-max 6
3063 "Maximum depth of levels for which section title faces are defined."
3064 :group 'rst-faces-defaults
3065 :type '(integer)
3066 :set 'rst-set-level-default)
3067 (defcustom rst-level-face-base-color "grey"
3068 "Base name of the color for creating background colors in section title faces."
3069 :group 'rst-faces-defaults
3070 :type '(string)
3071 :set 'rst-set-level-default)
3072 (defcustom rst-level-face-base-light
3073 (if (eq frame-background-mode 'dark)
3076 "The lightness factor for the base color. This value is used for level 1.
3077 The default depends on whether the value of `frame-background-mode' is
3078 `dark' or not."
3079 :group 'rst-faces-defaults
3080 :type '(integer)
3081 :set 'rst-set-level-default)
3082 (defcustom rst-level-face-format-light "%2d"
3083 "The format for the lightness factor appended to the base name of the color.
3084 This value is expanded by `format' with an integer."
3085 :group 'rst-faces-defaults
3086 :type '(string)
3087 :set 'rst-set-level-default)
3088 (defcustom rst-level-face-step-light
3089 (if (eq frame-background-mode 'dark)
3092 "The step width to use for the next color.
3093 The formula
3095 `rst-level-face-base-light'
3096 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
3098 must result in a color level which appended to `rst-level-face-base-color'
3099 using `rst-level-face-format-light' results in a valid color such as `grey50'.
3100 This color is used as background for section title text on level
3101 `rst-level-face-max'."
3102 :group 'rst-faces-defaults
3103 :type '(integer)
3104 :set 'rst-set-level-default)
3106 (defcustom rst-adornment-faces-alist
3107 (let ((alist '((t . font-lock-keyword-face)
3108 (nil . font-lock-keyword-face)))
3109 (i 1))
3110 (while (<= i rst-level-face-max)
3111 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
3112 (setq i (1+ i)))
3113 alist)
3114 "Faces for the various adornment types.
3115 Key is a number (for the section title text of that level),
3116 t (for transitions) or nil (for section title adornment).
3117 If you generally do not like how section title text faces are
3118 set up tweak here. If the general idea is ok for you but you do not like the
3119 details check the Rst Faces Defaults group."
3120 :group 'rst-faces
3121 :type '(alist
3122 :key-type
3123 (choice
3124 (integer
3125 :tag
3126 "Section level (may not be bigger than `rst-level-face-max')")
3127 (boolean :tag "transitions (on) / section title adornment (off)"))
3128 :value-type (face))
3129 :set-after '(rst-level-face-max))
3131 (defun rst-define-level-faces ()
3132 "Define the faces for the section title text faces from the values."
3133 ;; All variables used here must be checked in `rst-set-level-default'
3134 (let ((i 1))
3135 (while (<= i rst-level-face-max)
3136 (let ((sym (intern (format "rst-level-%d-face" i)))
3137 (doc (format "Face for showing section title text at level %d" i))
3138 (col (format (concat "%s" rst-level-face-format-light)
3139 rst-level-face-base-color
3140 (+ (* (1- i) rst-level-face-step-light)
3141 rst-level-face-base-light))))
3142 (make-empty-face sym)
3143 (set-face-doc-string sym doc)
3144 (set-face-background sym col)
3145 (set sym sym)
3146 (setq i (1+ i))))))
3148 (rst-define-level-faces)
3150 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3152 (defvar rst-font-lock-keywords
3153 ;; The reST-links in the comments below all relate to sections in
3154 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
3155 `(;; FIXME: Block markup is not recognized in blocks after explicit markup
3156 ;; start
3158 ;; Simple `Body Elements`_
3159 ;; `Bullet Lists`_
3160 ;; FIXME: A bullet directly after a field name is not recognized
3161 (,(rst-re 'lin-beg '(:grp bul-sta))
3162 1 ,rst-block-face)
3163 ;; `Enumerated Lists`_
3164 (,(rst-re 'lin-beg '(:grp enmany-sta))
3165 1 ,rst-block-face)
3166 ;; `Definition Lists`_ FIXME: missing
3167 ;; `Field Lists`_
3168 (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx)
3169 1 ,rst-external-face)
3170 ;; `Option Lists`_
3171 (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*")
3172 '(:alt "$" (:seq hws-prt "\\{2\\}")))
3173 1 ,rst-block-face)
3174 ;; `Line Blocks`_
3175 ;; Only for lines containing no more bar - to distinguish from tables
3176 (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$")
3177 1 ,rst-block-face)
3179 ;; `Tables`_ FIXME: missing
3181 ;; All the `Explicit Markup Blocks`_
3182 ;; `Footnotes`_ / `Citations`_
3183 (,(rst-re 'lin-beg '(:grp exm-sta fnc-tag) 'bli-sfx)
3184 1 ,rst-definition-face)
3185 ;; `Directives`_ / `Substitution Definitions`_
3186 (,(rst-re 'lin-beg '(:grp exm-sta)
3187 '(:grp (:shy subdef-tag hws-sta) "?")
3188 '(:grp sym-tag dcl-tag) 'bli-sfx)
3189 (1 ,rst-directive-face)
3190 (2 ,rst-definition-face)
3191 (3 ,rst-directive-face))
3192 ;; `Hyperlink Targets`_
3193 (,(rst-re 'lin-beg
3194 '(:grp exm-sta "_" (:alt
3195 (:seq "`" ilcbkqdef-tag "`")
3196 (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":")
3197 'bli-sfx)
3198 1 ,rst-definition-face)
3199 (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx)
3200 1 ,rst-definition-face)
3202 ;; All `Inline Markup`_ - most of them may be multiline though this is
3203 ;; uninteresting
3205 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
3206 ;; `Strong Emphasis`_
3207 (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx)
3208 1 ,rst-emphasis2-face)
3209 ;; `Emphasis`_
3210 (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx)
3211 1 ,rst-emphasis1-face)
3212 ;; `Inline Literals`_
3213 (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx)
3214 1 ,rst-literal-face)
3215 ;; `Inline Internal Targets`_
3216 (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx)
3217 1 ,rst-definition-face)
3218 ;; `Hyperlink References`_
3219 ;; FIXME: `Embedded URIs`_ not considered
3220 ;; FIXME: Directly adjacing marked up words are not fontified correctly
3221 ;; unless they are not separated by two spaces: foo_ bar_
3222 (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`")
3223 (:seq "\\sw" (:alt "\\sw" "-") "+\\sw"))
3224 "__?") 'ilm-sfx)
3225 1 ,rst-reference-face)
3226 ;; `Interpreted Text`_
3227 (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?")
3228 '(:grp "`" ilcbkq-tag "`")
3229 '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx)
3230 (1 ,rst-directive-face)
3231 (2 ,rst-external-face)
3232 (3 ,rst-directive-face))
3233 ;; `Footnote References`_ / `Citation References`_
3234 (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx)
3235 1 ,rst-reference-face)
3236 ;; `Substitution References`_
3237 ;; FIXME: References substitutions like |this|_ or |this|__ are not
3238 ;; fontified correctly
3239 (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx)
3240 1 ,rst-reference-face)
3241 ;; `Standalone Hyperlinks`_
3242 ;; FIXME: This takes it easy by using a whitespace as delimiter
3243 (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx)
3244 1 ,rst-definition-face)
3245 (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx)
3246 1 ,rst-definition-face)
3248 ;; Do all block fontification as late as possible so 'append works
3250 ;; Sections_ / Transitions_ - for sections this is multiline
3251 (,(rst-re 'ado-beg-2-1)
3252 (rst-font-lock-handle-adornment-match
3253 (rst-font-lock-handle-adornment-limit
3254 (match-string-no-properties 1) (match-end 1))
3256 (1 (cdr (assoc nil rst-adornment-faces-alist)) append t)
3257 (2 (cdr (assoc rst-font-lock-adornment-level
3258 rst-adornment-faces-alist)) append t)
3259 (3 (cdr (assoc nil rst-adornment-faces-alist)) append t)))
3261 ;; FIXME: FACESPEC could be used instead of ordinary faces to set
3262 ;; properties on comments and literal blocks so they are *not*
3263 ;; inline fontified; see (elisp)Search-based Fontification
3265 ;; `Comments`_ - this is multiline
3266 (,(rst-re 'lin-beg '(:grp exm-sta) "[^\[|_\n]"
3267 '(:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$"))) "*$")
3268 (1 ,rst-comment-face)
3269 (rst-font-lock-find-unindented-line-match
3270 (rst-font-lock-find-unindented-line-limit (match-end 1))
3272 (0 ,rst-comment-face append)))
3273 (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$")
3274 (1 ,rst-comment-face)
3275 (2 ,rst-comment-face)
3276 (rst-font-lock-find-unindented-line-match
3277 (rst-font-lock-find-unindented-line-limit 'next)
3279 (0 ,rst-comment-face append)))
3281 ;; FIXME: This is not rendered as comment::
3282 ;; .. .. list-table::
3283 ;; :stub-columns: 1
3284 ;; :header-rows: 1
3286 ;; `Literal Blocks`_ - this is multiline
3287 (,(rst-re 'lin-beg '(:shy (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
3288 '(:grp dcl-tag) "$")
3289 (1 ,rst-block-face)
3290 (rst-font-lock-find-unindented-line-match
3291 (rst-font-lock-find-unindented-line-limit t)
3293 (0 ,rst-literal-face append)))
3295 ;; `Doctest Blocks`_
3296 (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+"))
3297 (1,rst-block-face)
3298 (2 ,rst-literal-face))
3300 "Keywords to highlight in rst mode.")
3302 (defun rst-font-lock-extend-region ()
3303 "Extend the region `font-lock-beg' / `font-lock-end' iff it may
3304 be in the middle of a multiline construct and return non-nil if so."
3305 ;; There are many potential multiline constructs but really relevant ones are
3306 ;; comment lines without leading explicit markup tag and literal blocks
3307 ;; following "::" which are both indented. Thus indendation is what is
3308 ;; recognized here. The second criteria is an explicit markup tag which may
3309 ;; be a comment or a double colon at the end of a line.
3310 (if (not (get-text-property font-lock-beg 'font-lock-multiline))
3311 ;; Don't move if we start with a multiline construct already
3312 (save-excursion
3313 (let ((cont t))
3314 (move-to-window-line 0) ; Start at the top window line
3315 (if (>= (point) font-lock-beg)
3316 (goto-char font-lock-beg))
3317 (forward-line 0)
3318 (while cont
3319 (if (looking-at (rst-re '(:alt
3320 "[^ \t]"
3321 (:seq hws-tag exm-tag "[^ \t]")
3322 ;; FIXME: Shouldn't this allow whitespace
3323 ;; after the explicit markup tag?
3324 (:seq ".*" dcl-tag lin-end))))
3325 ;; non-empty indented line, explicit markup tag or literal
3326 ;; block tag
3327 (setq cont nil)
3328 (if (not (= (forward-line -1) 0)) ; try previous line
3329 ;; no more previous line
3330 (setq cont nil))))
3331 (when (not (= (point) font-lock-beg))
3332 (setq font-lock-beg (point))
3333 t)))))
3335 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3336 ;; Indented blocks
3338 (defun rst-forward-indented-block (&optional column limit)
3339 "Move forward across one indented block.
3340 Find the next non-empty line which is not indented at least to COLUMN (defaults
3341 to the column of the point). Moves point to first character of this line or the
3342 first empty line immediately before it and returns that position. If there is
3343 no such line before LIMIT (defaults to the end of the buffer) returns nil and
3344 point is not moved."
3345 (interactive)
3346 (let ((clm (or column (current-column)))
3347 (start (point))
3348 fnd beg cand)
3349 (if (not limit)
3350 (setq limit (point-max)))
3351 (save-match-data
3352 (while (and (not fnd) (< (point) limit))
3353 (forward-line 1)
3354 (when (< (point) limit)
3355 (setq beg (point))
3356 (if (looking-at (rst-re 'lin-end))
3357 (setq cand (or cand beg)) ; An empty line is a candidate
3358 (move-to-column clm)
3359 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3360 ;; useful way - though it is not clear what this should mean at all
3361 (if (string-match
3362 (rst-re 'linemp-tag)
3363 (buffer-substring-no-properties beg (point)))
3364 (setq cand nil) ; An indented line resets a candidate
3365 (setq fnd (or cand beg)))))))
3366 (goto-char (or fnd start))
3367 fnd))
3369 (defvar rst-font-lock-find-unindented-line-begin nil
3370 "Beginning of the match if `rst-font-lock-find-unindented-line-end'")
3372 (defvar rst-font-lock-find-unindented-line-end nil
3373 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
3374 Also used as a trigger for
3375 `rst-font-lock-find-unindented-line-match'.")
3377 (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
3378 "Find the next unindented line relative to indenation at IND-PNT.
3379 Return this point, the end of the buffer or nil if nothing found.
3380 If IND-PNT is `next' take the indentation from the next line if
3381 this is not empty and indented more than the current one. If
3382 IND-PNT is non-nil but not a number take the indentation from the
3383 next non-empty line if this is indented more than the current
3384 one."
3385 (setq rst-font-lock-find-unindented-line-begin ind-pnt)
3386 (setq rst-font-lock-find-unindented-line-end
3387 (save-excursion
3388 (when (not (numberp ind-pnt))
3389 ;; Find indentation point in next line if any
3390 (setq ind-pnt
3391 ;; FIXME: Should be refactored to two different functions
3392 ;; giving their result to this function, may be
3393 ;; integrated in caller
3394 (save-match-data
3395 (let ((cur-ind (current-indentation)))
3396 (if (eq ind-pnt 'next)
3397 (when (and (zerop (forward-line 1))
3398 (< (point) (point-max)))
3399 ;; Not at EOF
3400 (setq rst-font-lock-find-unindented-line-begin
3401 (point))
3402 (when (and (not (looking-at (rst-re 'lin-end)))
3403 (> (current-indentation) cur-ind))
3404 ;; Use end of indentation if non-empty line
3405 (looking-at (rst-re 'hws-tag))
3406 (match-end 0)))
3407 ;; Skip until non-empty line or EOF
3408 (while (and (zerop (forward-line 1))
3409 (< (point) (point-max))
3410 (looking-at (rst-re 'lin-end))))
3411 (when (< (point) (point-max))
3412 ;; Not at EOF
3413 (setq rst-font-lock-find-unindented-line-begin
3414 (point))
3415 (when (> (current-indentation) cur-ind)
3416 ;; Indentation bigger than line of departure
3417 (looking-at (rst-re 'hws-tag))
3418 (match-end 0))))))))
3419 (when ind-pnt
3420 (goto-char ind-pnt)
3421 (or (rst-forward-indented-block nil (point-max))
3422 (point-max))))))
3424 (defun rst-font-lock-find-unindented-line-match (limit)
3425 "Set the match found by
3426 `rst-font-lock-find-unindented-line-limit' the first time called
3427 or nil."
3428 (when rst-font-lock-find-unindented-line-end
3429 (set-match-data
3430 (list rst-font-lock-find-unindented-line-begin
3431 rst-font-lock-find-unindented-line-end))
3432 (put-text-property rst-font-lock-find-unindented-line-begin
3433 rst-font-lock-find-unindented-line-end
3434 'font-lock-multiline t)
3435 ;; Make sure this is called only once
3436 (setq rst-font-lock-find-unindented-line-end nil)
3439 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3440 ;; Adornments
3442 ;; FIXMEFIXME: This must be merged with the adornment functions for section
3443 ;; adjustment.
3445 (defvar rst-font-lock-adornment-level nil
3446 "Storage for `rst-font-lock-handle-adornment-match'.
3447 Either section level of the current adornment or t for a transition.")
3449 ;; FIXME: It would be good if this could be used to markup section titles of
3450 ;; given level with a special key; it would be even better to be able to
3451 ;; customize this so it can be used for a generally available personal style
3453 ;; FIXME: There should be some way to reset and reload this variable - probably
3454 ;; a special key
3456 ;; FIXME: Some support for `outline-mode' would be nice which should be based
3457 ;; on this information
3458 (defvar rst-adornment-level-alist nil
3459 "Associates adornments with section levels.
3460 The key is a two character string. The first character is the adornment
3461 character. The second character distinguishes underline section titles (`u')
3462 from overline/underline section titles (`o'). The value is the section level.
3464 This is made buffer local on start and adornments found during font lock are
3465 entered.")
3467 (defun rst-adornment-level (key &optional add)
3468 "Return section level for adornment key KEY.
3469 Add new section level if KEY is not found and ADD. If KEY is not
3470 a string it is simply returned."
3471 (let ((fnd (assoc key rst-adornment-level-alist))
3472 (new 1))
3473 (cond
3474 ((not (stringp key))
3475 key)
3476 (fnd
3477 (cdr fnd))
3478 (add
3479 (while (rassoc new rst-adornment-level-alist)
3480 (setq new (1+ new)))
3481 (setq rst-adornment-level-alist
3482 (append rst-adornment-level-alist (list (cons key new))))
3483 new))))
3485 (defun rst-classify-adornment (adornment end limit)
3486 "Classify adornment for section titles and transitions.
3487 ADORNMENT is the complete adornment string as found in the
3488 buffer. END is the point after the last character of ADORNMENT.
3489 For overline section adornment LIMIT limits the search for the
3490 matching underline.
3492 Return a list. The first entry is t for a transition, or a key
3493 string for `rst-adornment-level' for a section title. The
3494 following eight values forming four match groups as can be used
3495 for `set-match-data'. First match group contains the maximum
3496 points of the whole construct. Second and last match group
3497 matched pure section title adornment while third match group
3498 matched the section title text or the transition. Each group but
3499 the first may or may not exist."
3500 (save-excursion
3501 (save-match-data
3502 (goto-char end)
3503 (let ((ado-ch (aref adornment 0))
3504 (ado-re (rst-re (regexp-quote adornment)))
3505 (end-pnt (point))
3506 (beg-pnt (progn
3507 (forward-line 0)
3508 (point)))
3509 (nxt-emp
3510 (save-excursion
3511 (or (not (zerop (forward-line 1)))
3512 (looking-at (rst-re 'lin-end)))))
3513 (prv-emp
3514 (save-excursion
3515 (or (not (zerop (forward-line -1)))
3516 (looking-at (rst-re 'lin-end)))))
3517 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
3518 (cond
3519 ((and nxt-emp prv-emp)
3520 ;; A transition
3521 (setq key t)
3522 (setq beg-txt beg-pnt)
3523 (setq end-txt end-pnt))
3524 (prv-emp
3525 ;; An overline
3526 (setq key (concat (list ado-ch) "o"))
3527 (setq beg-ovr beg-pnt)
3528 (setq end-ovr end-pnt)
3529 (forward-line 1)
3530 (setq beg-txt (point))
3531 (while (and (<= (point) limit) (not end-txt))
3532 (if (or (= (point) limit) (looking-at (rst-re 'lin-end)))
3533 ;; No underline found
3534 (setq end-txt (1- (point)))
3535 (when (looking-at (rst-re (list :grp
3536 ado-re)
3537 'lin-end))
3538 (setq end-und (match-end 1))
3539 (setq beg-und (point))
3540 (setq end-txt (1- beg-und))))
3541 (forward-line 1)))
3543 ;; An underline
3544 (setq key (concat (list ado-ch) "u"))
3545 (setq beg-und beg-pnt)
3546 (setq end-und end-pnt)
3547 (setq end-txt (1- beg-und))
3548 (setq beg-txt (progn
3549 (goto-char end-txt)
3550 (forward-line 0)
3551 (point)))
3552 (when (and (zerop (forward-line -1))
3553 (looking-at (rst-re (list :grp
3554 ado-re)
3555 'lin-end)))
3556 ;; There is a matching overline
3557 (setq key (concat (list ado-ch) "o"))
3558 (setq beg-ovr (point))
3559 (setq end-ovr (match-end 1)))))
3560 (list key
3561 (or beg-ovr beg-txt beg-und)
3562 (or end-und end-txt end-und)
3563 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
3565 (defvar rst-font-lock-adornment-data nil
3566 "Storage for `rst-classify-adornment'.
3567 Also used as a trigger for
3568 `rst-font-lock-handle-adornment-match'.")
3570 (defun rst-font-lock-handle-adornment-limit (ado ado-end)
3571 "Determine limit for adornments for font-locking section titles and transitions.
3572 In fact determine all things necessary and put the result to
3573 `rst-font-lock-adornment-data'. ADO is the complete adornment
3574 matched. ADO-END is the point where ADO ends. Return the point
3575 where the whole adorned construct ends."
3576 (let ((ado-data (rst-classify-adornment ado ado-end (point-max))))
3577 (setq rst-font-lock-adornment-level (rst-adornment-level (car ado-data) t))
3578 (setq rst-font-lock-adornment-data (cdr ado-data))
3579 (goto-char (nth 1 ado-data))
3580 (nth 2 ado-data)))
3582 (defun rst-font-lock-handle-adornment-match (limit)
3583 "Set the match found by `rst-font-lock-handle-adornment-limit'
3584 the first time called or nil"
3585 (let ((ado-data rst-font-lock-adornment-data))
3586 ;; May run only once - enforce this
3587 (setq rst-font-lock-adornment-data nil)
3588 (when ado-data
3589 (goto-char (nth 1 ado-data))
3590 (put-text-property (nth 0 ado-data) (nth 1 ado-data)
3591 'font-lock-multiline t)
3592 (set-match-data ado-data)
3593 t)))
3596 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3597 ;; Support for conversion from within Emacs
3599 (defgroup rst-compile nil
3600 "Settings for support of conversion of reStructuredText
3601 document with \\[rst-compile]."
3602 :group 'rst
3603 :version "21.1")
3605 (defvar rst-compile-toolsets
3606 '((html . ("rst2html.py" ".html" nil))
3607 (latex . ("rst2latex.py" ".tex" nil))
3608 (newlatex . ("rst2newlatex.py" ".tex" nil))
3609 (pseudoxml . ("rst2pseudoxml.py" ".xml" nil))
3610 (xml . ("rst2xml.py" ".xml" nil))
3611 (pdf . ("rst2pdf.py" ".pdf" nil))
3612 (s5 . ("rst2s5.py" ".xml" nil)))
3613 "Table describing the command to use for each toolset.
3614 An association list of the toolset to a list of the (command to use,
3615 extension of produced filename, options to the tool (nil or a
3616 string)) to be used for converting the document.")
3618 ;; Note for Python programmers not familiar with association lists: you can set
3619 ;; values in an alists like this, e.g. :
3620 ;; (setcdr (assq 'html rst-compile-toolsets)
3621 ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
3624 (defvar rst-compile-primary-toolset 'html
3625 "The default toolset for `rst-compile'.")
3627 (defvar rst-compile-secondary-toolset 'latex
3628 "The default toolset for `rst-compile' with a prefix argument.")
3630 (defun rst-compile-find-conf ()
3631 "Look for the configuration file in the parents of the current path."
3632 (interactive)
3633 (let ((file-name "docutils.conf")
3634 (buffer-file (buffer-file-name)))
3635 ;; Move up in the dir hierarchy till we find a change log file.
3636 (let* ((dir (file-name-directory buffer-file))
3637 (prevdir nil))
3638 (while (and (or (not (string= dir prevdir))
3639 (setq dir nil)
3640 nil)
3641 (not (file-exists-p (concat dir file-name))))
3642 ;; Move up to the parent dir and try again.
3643 (setq prevdir dir)
3644 (setq dir (expand-file-name (file-name-directory
3645 (directory-file-name
3646 (file-name-directory dir)))))
3648 (or (and dir (concat dir file-name)) nil)
3652 (require 'compile)
3654 (defun rst-compile (&optional use-alt)
3655 "Compile command to convert reST document into some output file.
3656 Attempts to find configuration file, if it can, overrides the
3657 options. There are two commands to choose from, with USE-ALT,
3658 select the alternative toolset."
3659 (interactive "P")
3660 ;; Note: maybe we want to check if there is a Makefile too and not do anything
3661 ;; if that is the case. I dunno.
3662 (let* ((toolset (cdr (assq (if use-alt
3663 rst-compile-secondary-toolset
3664 rst-compile-primary-toolset)
3665 rst-compile-toolsets)))
3666 (command (car toolset))
3667 (extension (cadr toolset))
3668 (options (caddr toolset))
3669 (conffile (rst-compile-find-conf))
3670 (bufname (file-name-nondirectory buffer-file-name))
3671 (outname (file-name-sans-extension bufname)))
3673 ;; Set compile-command before invocation of compile.
3674 (set (make-local-variable 'compile-command)
3675 (mapconcat 'identity
3676 (list command
3677 (or options "")
3678 (if conffile
3679 (concat "--config=" (shell-quote-argument conffile))
3681 (shell-quote-argument bufname)
3682 (shell-quote-argument (concat outname extension)))
3683 " "))
3685 ;; Invoke the compile command.
3686 (if (or compilation-read-command use-alt)
3687 (call-interactively 'compile)
3688 (compile compile-command))
3691 (defun rst-compile-alt-toolset ()
3692 "Compile command with the alternative toolset."
3693 (interactive)
3694 (rst-compile t))
3696 (defun rst-compile-pseudo-region ()
3697 "Show the pseudo-XML rendering of the current active region,
3698 or of the entire buffer, if the region is not selected."
3699 (interactive)
3700 (with-output-to-temp-buffer "*pseudoxml*"
3701 (shell-command-on-region
3702 (if mark-active (region-beginning) (point-min))
3703 (if mark-active (region-end) (point-max))
3704 (cadr (assq 'pseudoxml rst-compile-toolsets))
3705 standard-output)))
3707 (defvar rst-pdf-program "xpdf"
3708 "Program used to preview PDF files.")
3710 (defun rst-compile-pdf-preview ()
3711 "Convert the document to a PDF file and launch a preview program."
3712 (interactive)
3713 (let* ((tmp-filename "/tmp/out.pdf")
3714 (command (format "%s %s %s && %s %s"
3715 (cadr (assq 'pdf rst-compile-toolsets))
3716 buffer-file-name tmp-filename
3717 rst-pdf-program tmp-filename)))
3718 (start-process-shell-command "rst-pdf-preview" nil command)
3719 ;; Note: you could also use (compile command) to view the compilation
3720 ;; output.
3723 (defvar rst-slides-program "firefox"
3724 "Program used to preview S5 slides.")
3726 (defun rst-compile-slides-preview ()
3727 "Convert the document to an S5 slide presentation and launch a preview program."
3728 (interactive)
3729 (let* ((tmp-filename "/tmp/slides.html")
3730 (command (format "%s %s %s && %s %s"
3731 (cadr (assq 's5 rst-compile-toolsets))
3732 buffer-file-name tmp-filename
3733 rst-slides-program tmp-filename)))
3734 (start-process-shell-command "rst-slides-preview" nil command)
3735 ;; Note: you could also use (compile command) to view the compilation
3736 ;; output.
3741 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3742 ;; Generic text functions that are more convenient than the defaults.
3744 (defun rst-replace-lines (fromchar tochar)
3745 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
3746 with equal-length lines of TOCHAR."
3747 (interactive "\
3748 cSearch for flush-left lines of char:
3749 cand replace with char: ")
3750 (save-excursion
3751 (let ((searchre (rst-re "^" fromchar "+\\( *\\)$"))
3752 (found 0))
3753 (while (search-forward-regexp searchre nil t)
3754 (setq found (1+ found))
3755 (goto-char (match-beginning 1))
3756 (let ((width (current-column)))
3757 (rst-delete-entire-line)
3758 (insert-char tochar width)))
3759 (message (format "%d lines replaced." found)))))
3761 (defun rst-join-paragraph ()
3762 "Join lines in current paragraph into one line, removing end-of-lines."
3763 (interactive)
3764 (let ((fill-column 65000)) ; some big number
3765 (call-interactively 'fill-paragraph)))
3767 (defun rst-force-fill-paragraph ()
3768 "Fill paragraph at point, first joining the paragraph's lines into one.
3769 This is useful for filling list item paragraphs."
3770 (interactive)
3771 (rst-join-paragraph)
3772 (fill-paragraph nil))
3775 ;; Generic character repeater function.
3776 ;; For sections, better to use the specialized function above, but this can
3777 ;; be useful for creating separators.
3778 (defun rst-repeat-last-character (use-next)
3779 "Fill the current line up to the length of the preceding line (if not
3780 empty), using the last character on the current line. If the preceding line is
3781 empty, we use the `fill-column'.
3783 If USE-NEXT, use the next line rather than the preceding line.
3785 If the current line is longer than the desired length, shave the characters off
3786 the current line to fit the desired length.
3788 As an added convenience, if the command is repeated immediately, the alternative
3789 column is used (fill-column vs. end of previous/next line)."
3790 (interactive "P")
3791 (let* ((curcol (current-column))
3792 (curline (+ (count-lines (point-min) (point))
3793 (if (eq curcol 0) 1 0)))
3794 (lbp (line-beginning-position 0))
3795 (prevcol (if (and (= curline 1) (not use-next))
3796 fill-column
3797 (save-excursion
3798 (forward-line (if use-next 1 -1))
3799 (end-of-line)
3800 (skip-chars-backward " \t" lbp)
3801 (let ((cc (current-column)))
3802 (if (= cc 0) fill-column cc)))))
3803 (rightmost-column
3804 (cond ((equal last-command 'rst-repeat-last-character)
3805 (if (= curcol fill-column) prevcol fill-column))
3806 (t (save-excursion
3807 (if (= prevcol 0) fill-column prevcol)))
3808 )) )
3809 (end-of-line)
3810 (if (> (current-column) rightmost-column)
3811 ;; shave characters off the end
3812 (delete-region (- (point)
3813 (- (current-column) rightmost-column))
3814 (point))
3815 ;; fill with last characters
3816 (insert-char (preceding-char)
3817 (- rightmost-column (current-column))))
3821 (defun rst-portable-mark-active-p ()
3822 "A portable function that returns non-nil if the mark is active."
3823 (cond
3824 ((fboundp 'region-active-p) (region-active-p))
3825 ((boundp 'transient-mark-mode) transient-mark-mode mark-active)))
3829 (provide 'rst)
3830 ;;; rst.el ends here