Improved font-lock code to use a better `PRE-MATCH-FORM`. As a result
[docutils/kirr.git] / docutils / tools / editors / emacs / rst.el
blob2e03fbb562aa224c21bb9386186917667018188f
1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
3 ;; Copyright 2003-2008 by Martin Blais, Stefan Merten, and David Goodger.
5 ;; Authors: Martin Blais <blais@furius.ca>,
6 ;; Stefan Merten <smerten@oekonux.de>,
7 ;; David Goodger <goodger@python.org>
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License version 2,
11 ;; as published by the Free Software Foundation.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License version 2
19 ;; along with this program and available at
20 ;; http://docutils.sf.net/licenses/gpl.txt and at
21 ;; http://www.gnu.org/licenses/gpl.txt.
23 ;;; Commentary:
25 ;; This package provides major mode rst-mode, which supports documents marked up
26 ;; using the reStructuredText format. Support includes font locking as well as
27 ;; some convenience functions for editing. It does this by defining a Emacs
28 ;; major mode: rst-mode (ReST). This mode is derived from text-mode (and
29 ;; inherits much of it). This package also contains:
31 ;; - Functions to automatically adjust and cycle the section underline
32 ;; decorations;
33 ;; - A mode that displays the table of contents and allows you to jump anywhere
34 ;; from it;
35 ;; - Functions to insert and automatically update a TOC in your source
36 ;; document;
37 ;; - Font-lock highlighting of notable reStructuredText structures;
38 ;; - Some other convenience functions.
40 ;; See the accompanying document in the docutils documentation about
41 ;; the contents of this package and how to use it.
43 ;; For more information about reStructuredText, see
44 ;; http://docutils.sourceforge.net/rst.html
46 ;; For full details on how to use the contents of this file, see
47 ;; http://docutils.sourceforge.net/docs/user/emacs.html
50 ;; There are a number of convenient keybindings provided by rst-mode. The main
51 ;; one is
53 ;; C-c C-a (also C-=): rst-adjust
55 ;; Updates or rotates the section title around point or promotes/demotes the
56 ;; decorations within the region (see full details below). Note that C-= is a
57 ;; good binding, since it allows you to specify a negative arg easily with C--
58 ;; C-= (easy to type), as well as ordinary prefix arg with C-u C-=.
60 ;; For more on bindings, see rst-mode-map below. There are also many variables
61 ;; that can be customized, look for defcustom and defvar in this file.
63 ;; If you use the table-of-contents feature, you may want to add a hook to
64 ;; update the TOC automatically everytime you adjust a section title::
66 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
68 ;; Syntax highlighting: font-lock is enabled by default. If you want to turn off
69 ;; syntax highlighting to rst-mode, you can use the following::
71 ;; (setq font-lock-global-modes '(not rst-mode ...))
75 ;; CUSTOMIZATION
77 ;; rst
78 ;; ---
79 ;; This group contains some general customizable features.
81 ;; The group is contained in the wp group.
83 ;; rst-faces
84 ;; ---------
85 ;; This group contains all necessary for customizing fonts. The default
86 ;; settings use standard font-lock-*-face's so if you set these to your
87 ;; liking they are probably good in rst-mode also.
89 ;; The group is contained in the faces group as well as in the rst group.
91 ;; rst-faces-defaults
92 ;; ------------------
93 ;; This group contains all necessary for customizing the default fonts used for
94 ;; section title faces.
96 ;; The general idea for section title faces is to have a non-default background
97 ;; but do not change the background. The section level is shown by the
98 ;; lightness of the background color. If you like this general idea of
99 ;; generating faces for section titles but do not like the details this group
100 ;; is the point where you can customize the details. If you do not like the
101 ;; general idea, however, you should customize the faces used in
102 ;; rst-adornment-faces-alist.
104 ;; Note: If you are using a dark background please make sure the variable
105 ;; frame-background-mode is set to the symbol dark. This triggers
106 ;; some default values which are probably right for you.
108 ;; The group is contained in the rst-faces group.
110 ;; All customizable features have a comment explaining their meaning. Refer to
111 ;; the customization of your Emacs (try ``M-x customize``).
114 ;;; DOWNLOAD
116 ;; The latest version of this file lies in the docutils source code repository:
117 ;; http://svn.berlios.de/svnroot/repos/docutils/trunk/docutils/tools/editors/emacs/rst.el
120 ;;; INSTALLATION
122 ;; Add the following lines to your `.emacs' file:
124 ;; (require 'rst)
126 ;; If you are using `.txt' as a standard extension for reST files as
127 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
128 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
129 ;; provides to set the major mode automatically. For instance you may use::
131 ;; .. -*- mode: rst -*-
133 ;; in the very first line of your file. The following code is useful if you want
134 ;; to automatically enter rst-mode from any file with compatible extensions:
136 ;; (setq auto-mode-alist
137 ;; (append '(("\\.txt$" . rst-mode)
138 ;; ("\\.rst$" . rst-mode)
139 ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
142 ;;; BUGS
144 ;; - rst-enumeration-region: Select a single paragraph, with the top at one
145 ;; blank line before the beginning, and it will fail.
146 ;; - The active region goes away when we shift it left or right, and this
147 ;; prevents us from refilling it automatically when shifting many times.
148 ;; - The suggested decorations when adjusting should not have to cycle
149 ;; below one below the last section decoration level preceding the
150 ;; cursor. We need to fix that.
152 ;;; TODO LIST
154 ;; rst-toc-insert features
155 ;; ------------------------
156 ;; - rst-toc-insert: We should parse the contents:: options to figure out how
157 ;; deep to render the inserted TOC.
158 ;; - On load, detect any existing TOCs and set the properties for links.
159 ;; - TOC insertion should have an option to add empty lines.
160 ;; - TOC insertion should deal with multiple lines.
161 ;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
162 ;; automatic toc update. The cursor ends up in the TOC and this is
163 ;; annoying. Gotta fix that.
164 ;; - numbering: automatically detect if we have a section-numbering directive in
165 ;; the corresponding section, to render the toc.
167 ;; bulleted and enumerated list items
168 ;; ----------------------------------
169 ;; - We need to provide way to rebullet bulleted lists, and that would include
170 ;; automatic enumeration as well.
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 decoration
181 ;; at the top of the document or searching for reStructuredText_
182 ;; directives further on.
184 ;; - We should support imenu in our major mode, with the menu filled with the
185 ;; section titles (this should be really easy).
187 ;; - We should rename "adornment" to "decoration" or vice-versa in this
188 ;; document (Stefan's code ("adornment") vs Martin ("decoration")), maybe some
189 ;; functions even overlap.
191 ;; - We need to automatically recenter on rst-forward-section movement commands.
194 ;;; HISTORY
197 ;;; CODE
200 (defgroup rst nil "Support for reStructuredText documents"
201 :group 'wp
202 :version "21.1"
203 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
208 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
209 ;; Define some generic support functions.
211 (require 'cl) ;; We need this for destructuring-bind below.
213 ;; Generic Filter function.
214 (unless (fboundp 'filter)
215 (defun filter (pred list)
216 "Returns a list of all the elements fulfilling the pred requirement (that
217 is for which (pred elem) is true)"
218 (if list
219 (let ((head (car list))
220 (tail (filter pred (cdr list))))
221 (if (funcall pred head)
222 (cons head tail)
223 tail)))))
226 ;; From emacs-22
227 (unless (fboundp 'line-number-at-pos)
228 (defun line-number-at-pos (&optional pos)
229 "Return (narrowed) buffer line number at position POS.
230 If POS is nil, use current buffer location."
231 (let ((opoint (or pos (point))) start)
232 (save-excursion
233 (goto-char (point-min))
234 (setq start (point))
235 (goto-char opoint)
236 (forward-line 0)
237 (1+ (count-lines start (point)))))) )
241 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
242 ;; Mode definition.
244 ;; Key bindings.
245 (defvar rst-mode-map
246 (let ((map (make-sparse-keymap)))
249 ;; Section Decorations.
251 ;; The adjustment function that decorates or rotates a section title.
252 (define-key map [(control c) (control a)] 'rst-adjust)
253 (define-key map [(control c) (control ?=)] 'rst-adjust)
254 (define-key map [(control ?=)] 'rst-adjust) ;; (Does not work on the Mac OSX.)
255 ;; Display the hierarchy of decorations implied by the current document contents.
256 (define-key map [(control c) (control h)] 'rst-display-decorations-hierarchy)
257 ;; Homogeneize the decorations in the document.
258 (define-key map [(control c) (control s)] 'rst-straighten-decorations)
259 ;; (define-key map [(control c) (control s)] 'rst-straighten-deco-spacing)
262 ;; Section Movement and Selection.
264 ;; Mark the subsection where the cursor is.
265 (define-key map [(control c) (control m)] 'rst-mark-section)
266 ;; Move forward/backward between section titles.
267 (define-key map [(control c) (control n)] 'rst-forward-section)
268 (define-key map [(control c) (control p)] 'rst-backward-section)
271 ;; Operating on Blocks of Text.
273 ;; Makes paragraphs in region as a bullet list.
274 (define-key map [(control c) (control b)] 'rst-bullet-list-region)
275 ;; Makes paragraphs in region as a enumeration.
276 (define-key map [(control c) (control e)] 'rst-enumerate-region)
277 ;; Converts bullets to an enumeration.
278 (define-key map [(control c) (control v)] 'rst-convert-bullets-to-enumeration)
279 ;; Makes region a line-block.
280 (define-key map [(control c) (control d)] 'rst-line-block-region)
281 ;; Make sure that all the bullets in the region are consistent.
282 (define-key map [(control c) (control w)] 'rst-straighten-bullets-region)
283 ;; Shift region left or right (taking into account of enumerations/bullets, etc.).
284 (define-key map [(control c) (control l)] 'rst-shift-region-left)
285 (define-key map [(control c) (control r)] 'rst-shift-region-right)
286 ;; Comment/uncomment the active region.
287 (define-key map [(control c) (control c)] 'comment-region)
290 ;; Table-of-Contents Features.
292 ;; Enter a TOC buffer to view and move to a specific section.
293 (define-key map [(control c) (control t)] 'rst-toc)
294 ;; Insert a TOC here.
295 (define-key map [(control c) (control i)] 'rst-toc-insert)
296 ;; Update the document's TOC (without changing the cursor position).
297 (define-key map [(control c) (control u)] 'rst-toc-update)
298 ;; Got to the section under the cursor (cursor must be in TOC).
299 (define-key map [(control c) (control f)] 'rst-goto-section)
302 ;; Converting Documents from Emacs.
304 ;; Run one of two pre-configured toolset commands on the document.
305 (define-key map [(control c) (?1)] 'rst-compile)
306 (define-key map [(control c) (?2)] 'rst-compile-alt-toolset)
307 ;; Convert the active region to pseudo-xml using the docutils tools.
308 (define-key map [(control c) (?3)] 'rst-compile-pseudo-region)
309 ;; Convert the current document to PDF and launch a viewer on the results.
310 (define-key map [(control c) (?4)] 'rst-compile-pdf-preview)
311 ;; Convert the current document to S5 slides and view in a web browser.
312 (define-key map [(control c) (?5)] 'rst-compile-slides-preview)
314 map)
315 "Keymap for ReStructuredText mode commands. This inherits from Text mode.")
318 ;; Abbrevs.
319 (defvar rst-mode-abbrev-table nil
320 "Abbrev table used while in rst mode.")
321 (define-abbrev-table 'rst-mode-abbrev-table
323 ("contents" ".. contents::\n..\n " nil 0)
324 ("con" ".. contents::\n..\n " nil 0)
325 ("cont" "[...]" nil 0)
326 ("skip" "\n\n[...]\n\n " nil 0)
327 ("seq" "\n\n[...]\n\n " nil 0)
328 ;; FIXME: Add footnotes, links, and more.
332 ;; Syntax table.
333 (defvar rst-mode-syntax-table
334 (let ((st (copy-syntax-table text-mode-syntax-table)))
336 (modify-syntax-entry ?$ "." st)
337 (modify-syntax-entry ?% "." st)
338 (modify-syntax-entry ?& "." st)
339 (modify-syntax-entry ?' "." st)
340 (modify-syntax-entry ?* "." st)
341 (modify-syntax-entry ?+ "." st)
342 (modify-syntax-entry ?. "_" st)
343 (modify-syntax-entry ?/ "." st)
344 (modify-syntax-entry ?< "." st)
345 (modify-syntax-entry ?= "." st)
346 (modify-syntax-entry ?> "." st)
347 (modify-syntax-entry ?\\ "\\" st)
348 (modify-syntax-entry ?| "." st)
349 (modify-syntax-entry ?_ "." st)
352 "Syntax table used while in `rst-mode'.")
355 (defcustom rst-mode-hook nil
356 "Hook run when Rst Mode is turned on. The hook for Text Mode is run before
357 this one."
358 :group 'rst
359 :type '(hook))
362 ;;;###autoload
363 (define-derived-mode rst-mode text-mode "ReST"
364 :abbrev-table rst-mode-abbrev-table
365 :syntax-table rst-mode-syntax-table
366 :group 'rst
367 "Major mode for editing reStructuredText documents.
369 There are a number of convenient keybindings provided by
370 rst-mode. The main one is \[rst-adjust\], it updates or rotates
371 the section title around point or promotes/demotes the
372 decorations within the region (see full details below). Use
373 negative prefix arg to rotate in the other direction.
374 \\{rst-mode-map}
376 Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
377 `rst-mode-hook'. This mode also supports font-lock highlighting."
379 (set (make-local-variable 'paragraph-separate) paragraph-start)
380 (set (make-local-variable 'indent-line-function) 'indent-relative-maybe)
381 (set (make-local-variable 'paragraph-start)
382 "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. ")
383 (set (make-local-variable 'adaptive-fill-mode) t)
385 ;; FIXME: No need to reset this.
386 ;; (set (make-local-variable 'indent-line-function) 'indent-relative)
388 ;; The details of the following comment setup is important because it affects
389 ;; auto-fill, and it is pretty common in running text to have an ellipsis
390 ;; ("...") which trips because of the rest comment syntax (".. ").
391 (set (make-local-variable 'comment-start) ".. ")
392 (set (make-local-variable 'comment-start-skip) "^\\.\\. ")
393 (set (make-local-variable 'comment-multi-line) nil)
395 ;; Special variables
396 (make-local-variable 'rst-adornment-level-alist)
398 ;; Font lock
399 (set (make-local-variable 'font-lock-defaults)
400 '(rst-font-lock-keywords
401 t nil nil nil
402 (font-lock-multiline . t)
403 (font-lock-mark-block-function . mark-paragraph)))
404 (when (boundp 'font-lock-support-mode)
405 ;; rst-mode does not need font-lock-support-mode and works not well with
406 ;; jit-lock-mode because reST is not made for machines
407 (set (make-local-variable 'font-lock-support-mode) nil)))
409 ;;;###autoload
410 (define-minor-mode rst-minor-mode
411 "ReST Minor Mode.
412 Toggle ReST minor mode.
413 With no argument, this command toggles the mode.
414 Non-null prefix argument turns on the mode.
415 Null prefix argument turns off the mode.
417 When ReST minor mode is enabled, the ReST mode
418 keybindings are installed on top of the major
419 mode bindings. Use this for modes derived from
420 text-mode, like mail-mode.."
421 ;; The initial value.
423 ;; The indicator for the mode line.
424 " ReST"
425 ;; The minor mode bindings.
426 rst-mode-map
427 :group 'rst)
429 ;; FIXME: can I somehow install these too?
430 ;; :abbrev-table rst-mode-abbrev-table
431 ;; :syntax-table rst-mode-syntax-table
437 ;; Bulleted item lists.
438 (defcustom rst-bullets
439 '(?- ?* ?+)
440 "List of all possible bullet characters for bulleted lists."
441 :group 'rst)
446 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
447 ;; Section Decoration Adjusment
448 ;; ============================
450 ;; The following functions implement a smart automatic title sectioning feature.
451 ;; The idea is that with the cursor sitting on a section title, we try to get as
452 ;; much information from context and try to do the best thing automatically.
453 ;; This function can be invoked many times and/or with prefix argument to rotate
454 ;; between the various sectioning decorations.
456 ;; Definitions: the two forms of sectioning define semantically separate section
457 ;; levels. A sectioning DECORATION consists in:
459 ;; - a CHARACTER
461 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
463 ;; - an INDENT (meaningful for the over-and-under style only) which determines
464 ;; how many characters and over-and-under style is hanging outside of the
465 ;; title at the beginning and ending.
467 ;; Important note: an existing decoration must be formed by at least two
468 ;; characters to be recognized.
470 ;; Here are two examples of decorations (| represents the window border, column
471 ;; 0):
473 ;; |
474 ;; 1. char: '-' e |Some Title
475 ;; style: simple |----------
476 ;; |
477 ;; 2. char: '=' |==============
478 ;; style: over-and-under | Some Title
479 ;; indent: 2 |==============
480 ;; |
482 ;; Some notes:
484 ;; - The underlining character that is used depends on context. The file is
485 ;; scanned to find other sections and an appropriate character is selected.
486 ;; If the function is invoked on a section that is complete, the character is
487 ;; rotated among the existing section decorations.
489 ;; Note that when rotating the characters, if we come to the end of the
490 ;; hierarchy of decorations, the variable rst-preferred-decorations is
491 ;; consulted to propose a new underline decoration, and if continued, we cycle
492 ;; the decorations all over again. Set this variable to nil if you want to
493 ;; limit the underlining character propositions to the existing decorations in
494 ;; the file.
496 ;; - A prefix argument can be used to alternate the style.
498 ;; - An underline/overline that is not extended to the column at which it should
499 ;; be hanging is dubbed INCOMPLETE. For example::
501 ;; |Some Title
502 ;; |-------
504 ;; Examples of default invocation:
506 ;; |Some Title ---> |Some Title
507 ;; | |----------
509 ;; |Some Title ---> |Some Title
510 ;; |----- |----------
512 ;; | |------------
513 ;; | Some Title ---> | Some Title
514 ;; | |------------
516 ;; In over-and-under style, when alternating the style, a variable is
517 ;; available to select how much default indent to use (it can be zero). Note
518 ;; that if the current section decoration already has an indent, we don't
519 ;; adjust it to the default, we rather use the current indent that is already
520 ;; there for adjustment (unless we cycle, in which case we use the indent
521 ;; that has been found previously).
523 (defgroup rst-adjust nil
524 "Settings for adjustment and cycling of section title
525 decorations."
526 :group 'rst
527 :version "21.1")
529 (defcustom rst-preferred-decorations '( (?= over-and-under 1)
530 (?= simple 0)
531 (?- simple 0)
532 (?~ simple 0)
533 (?+ simple 0)
534 (?` simple 0)
535 (?# simple 0)
536 (?@ simple 0) )
537 "Preferred ordering of section title decorations.
539 This sequence is consulted to offer a new decoration suggestion
540 when we rotate the underlines at the end of the existing
541 hierarchy of characters, or when there is no existing section
542 title in the file."
543 :group 'rst-adjust)
546 (defcustom rst-default-indent 1
547 "Number of characters to indent the section title.
549 THis is used for when toggling decoration styles, when switching
550 from a simple decoration style to a over-and-under decoration
551 style."
552 :group 'rst-adjust)
555 (defvar rst-section-text-regexp "^[ \t]*\\S-*\\w\\S-*"
556 "Regular expression for valid section title text.")
559 (defun rst-line-homogeneous-p (&optional accept-special)
560 "Return true if the line is homogeneous.
562 Predicate that returns the unique char if the current line is
563 composed only of a single repeated non-whitespace character. This
564 returns the char even if there is whitespace at the beginning of
565 the line.
567 If ACCEPT-SPECIAL is specified we do not ignore special sequences
568 which normally we would ignore when doing a search on many lines.
569 For example, normally we have cases to ignore commonly occuring
570 patterns, such as :: or ...; with the flag do not ignore them."
571 (save-excursion
572 (back-to-indentation)
573 (unless (looking-at "\n")
574 (let ((c (thing-at-point 'char)))
575 (if (and (looking-at (format "[%s]+[ \t]*$" c))
576 (or accept-special
577 (and
578 ;; Common patterns.
579 (not (looking-at "::[ \t]*$"))
580 (not (looking-at "\\.\\.\\.[ \t]*$"))
581 ;; Discard one char line
582 (not (looking-at ".[ \t]*$"))
584 (string-to-char c))
588 (defun rst-line-homogeneous-nodent-p (&optional accept-special)
589 "Return true if the line is homogeneous with no indent.
590 See `rst-line-homogeneous-p' about ACCEPT-SPECIAL."
591 (save-excursion
592 (beginning-of-line)
593 (if (looking-at "^[ \t]+")
595 (rst-line-homogeneous-p accept-special)
599 (defun rst-compare-decorations (deco1 deco2)
600 "Compare decorations.
601 Returns true if both DECO1 and DECO2 decorations are equal,
602 according to restructured text semantics (only the character and
603 the style are compared, the indentation does not matter."
604 (and (eq (car deco1) (car deco2))
605 (eq (cadr deco1) (cadr deco2))))
608 (defun rst-get-decoration-match (hier deco)
609 "Return the index (level) in hierarchy HIER of decoration DECO.
610 This basically just searches for the item using the appropriate
611 comparison and returns the index. We return nil if the item is
612 not found."
613 (let ((cur hier))
614 (while (and cur (not (rst-compare-decorations (car cur) deco)))
615 (setq cur (cdr cur)))
616 cur))
619 (defun rst-suggest-new-decoration (alldecos &optional prev)
620 "Suggest a new, different decoration from all that have been seen.
622 ALLDECOS is the set of all decorations, including the line
623 numbers. PREV is the optional previous decoration, in order to
624 suggest a better match."
626 ;; For all the preferred decorations...
627 (let* (
628 ;; If 'prev' is given, reorder the list to start searching after the
629 ;; match.
630 (fplist
631 (cdr (rst-get-decoration-match rst-preferred-decorations prev)))
633 ;; List of candidates to search.
634 (curpotential (append fplist rst-preferred-decorations)))
635 (while
636 ;; For all the decorations...
637 (let ((cur alldecos)
638 found)
639 (while (and cur (not found))
640 (if (rst-compare-decorations (car cur) (car curpotential))
641 ;; Found it!
642 (setq found (car curpotential))
643 (setq cur (cdr cur))))
644 found)
646 (setq curpotential (cdr curpotential)))
648 (copy-list (car curpotential)) ))
650 (defun rst-delete-entire-line ()
651 "Delete the entire current line without using the `kill-ring'."
652 (delete-region (line-beginning-position) (min (+ 1 (line-end-position))
653 (point-max))))
655 (defun rst-update-section (char style &optional indent)
656 "Unconditionally update the style of a section decoration.
658 Do this using the given character CHAR, with STYLE 'simple or
659 'over-and-under, and with indent INDENT. If the STYLE is
660 'simple, whitespace before the title is removed (indent is always
661 assume to be 0).
663 If there are existing overline and/or underline from the
664 existing decoration, they are removed before adding the
665 requested decoration."
667 (interactive)
668 (let (marker
669 len)
671 (end-of-line)
672 (setq marker (point-marker))
674 ;; Fixup whitespace at the beginning and end of the line
675 (if (or (null indent) (eq style 'simple))
676 (setq indent 0))
677 (beginning-of-line)
678 (delete-horizontal-space)
679 (insert (make-string indent ? ))
681 (end-of-line)
682 (delete-horizontal-space)
684 ;; Set the current column, we're at the end of the title line
685 (setq len (+ (current-column) indent))
687 ;; Remove previous line if it consists only of a single repeated character
688 (save-excursion
689 (forward-line -1)
690 (and (rst-line-homogeneous-p 1)
691 ;; Avoid removing the underline of a title right above us.
692 (save-excursion (forward-line -1)
693 (not (looking-at rst-section-text-regexp)))
694 (rst-delete-entire-line)))
696 ;; Remove following line if it consists only of a single repeated
697 ;; character
698 (save-excursion
699 (forward-line +1)
700 (and (rst-line-homogeneous-p 1)
701 (rst-delete-entire-line))
702 ;; Add a newline if we're at the end of the buffer, for the subsequence
703 ;; inserting of the underline
704 (if (= (point) (buffer-end 1))
705 (newline 1)))
707 ;; Insert overline
708 (if (eq style 'over-and-under)
709 (save-excursion
710 (beginning-of-line)
711 (open-line 1)
712 (insert (make-string len char))))
714 ;; Insert underline
715 (forward-line +1)
716 (open-line 1)
717 (insert (make-string len char))
719 (forward-line +1)
720 (goto-char marker)
724 (defun rst-normalize-cursor-position ()
725 "Normalize the cursor position.
726 If the cursor is on a decoration line or an empty line , place it
727 on the section title line (at the end). Returns the line offset
728 by which the cursor was moved. This works both over or under a
729 line."
730 (if (save-excursion (beginning-of-line)
731 (or (rst-line-homogeneous-p 1)
732 (looking-at "^[ \t]*$")))
733 (progn
734 (beginning-of-line)
735 (cond
736 ((save-excursion (forward-line -1)
737 (beginning-of-line)
738 (and (looking-at rst-section-text-regexp)
739 (not (rst-line-homogeneous-p 1))))
740 (progn (forward-line -1) -1))
741 ((save-excursion (forward-line +1)
742 (beginning-of-line)
743 (and (looking-at rst-section-text-regexp)
744 (not (rst-line-homogeneous-p 1))))
745 (progn (forward-line +1) +1))
746 (t 0)))
747 0 ))
750 (defun rst-find-all-decorations ()
751 "Find all the decorations in the file.
752 Return a list of (line, decoration) pairs. Each decoration
753 consists in a (char, style, indent) triple.
755 This function does not detect the hierarchy of decorations, it
756 just finds all of them in a file. You can then invoke another
757 function to remove redundancies and inconsistencies."
759 (let (positions
760 (curline 1))
761 ;; Iterate over all the section titles/decorations in the file.
762 (save-excursion
763 (goto-char (point-min))
764 (while (< (point) (buffer-end 1))
765 (if (rst-line-homogeneous-nodent-p)
766 (progn
767 (setq curline (+ curline (rst-normalize-cursor-position)))
769 ;; Here we have found a potential site for a decoration,
770 ;; characterize it.
771 (let ((deco (rst-get-decoration)))
772 (if (cadr deco) ;; Style is existing.
773 ;; Found a real decoration site.
774 (progn
775 (push (cons curline deco) positions)
776 ;; Push beyond the underline.
777 (forward-line 1)
778 (setq curline (+ curline 1))
781 (forward-line 1)
782 (setq curline (+ curline 1))
784 (reverse positions)))
787 (defun rst-infer-hierarchy (decorations)
788 "Build a hierarchy of decorations using the list of given DECORATIONS.
790 This function expects a list of (char, style, indent) decoration
791 specifications, in order that they appear in a file, and will
792 infer a hierarchy of section levels by removing decorations that
793 have already been seen in a forward traversal of the decorations,
794 comparing just the character and style.
796 Similarly returns a list of (char, style, indent), where each
797 list element should be unique."
799 (let ((hierarchy-alist (list)))
800 (dolist (x decorations)
801 (let ((char (car x))
802 (style (cadr x)))
803 (unless (assoc (cons char style) hierarchy-alist)
804 (push (cons (cons char style) x) hierarchy-alist))
807 (mapcar 'cdr (nreverse hierarchy-alist))
811 (defun rst-get-hierarchy (&optional alldecos ignore)
812 "Return the hierarchy of section titles in the file.
814 Return a list of decorations that represents the hierarchy of
815 section titles in the file. Reuse the list of decorations
816 already computed in ALLDECOS if present. If the line number in
817 IGNORE is specified, the decoration found on that line (if there
818 is one) is not taken into account when building the hierarchy."
819 (let ((all (or alldecos (rst-find-all-decorations))))
820 (setq all (assq-delete-all ignore all))
821 (rst-infer-hierarchy (mapcar 'cdr all))))
824 (defun rst-get-decoration (&optional point)
825 "Get the decoration at POINT.
827 Looks around point and finds the characteristics of the
828 decoration that is found there. We assume that the cursor is
829 already placed on the title line (and not on the overline or
830 underline).
832 This function returns a (char, style, indent) triple. If the
833 characters of overline and underline are different, we return
834 the underline character. The indent is always calculated. A
835 decoration can be said to exist if the style is not nil.
837 A point can be specified to go to the given location before
838 extracting the decoration."
840 (let (char style indent)
841 (save-excursion
842 (if point (goto-char point))
843 (beginning-of-line)
844 (if (looking-at rst-section-text-regexp)
845 (let* ((over (save-excursion
846 (forward-line -1)
847 (rst-line-homogeneous-nodent-p)))
849 (under (save-excursion
850 (forward-line +1)
851 (rst-line-homogeneous-nodent-p)))
854 ;; Check that the line above the overline is not part of a title
855 ;; above it.
856 (if (and over
857 (save-excursion
858 (and (equal (forward-line -2) 0)
859 (looking-at rst-section-text-regexp))))
860 (setq over nil))
862 (cond
863 ;; No decoration found, leave all return values nil.
864 ((and (eq over nil) (eq under nil)))
866 ;; Overline only, leave all return values nil.
868 ;; Note: we don't return the overline character, but it could
869 ;; perhaps in some cases be used to do something.
870 ((and over (eq under nil)))
872 ;; Underline only.
873 ((and under (eq over nil))
874 (setq char under
875 style 'simple))
877 ;; Both overline and underline.
879 (setq char under
880 style 'over-and-under))
884 ;; Find indentation.
885 (setq indent (save-excursion (back-to-indentation) (current-column)))
887 ;; Return values.
888 (list char style indent)))
891 (defun rst-get-decorations-around (&optional alldecos)
892 "Return the decorations around point.
894 Given the list of all decorations ALLDECOS (with positions), find
895 the decorations before and after the given point. A list of the
896 previous and next decorations is returned."
897 (let* ((all (or alldecos (rst-find-all-decorations)))
898 (curline (line-number-at-pos))
899 prev next
900 (cur all))
902 ;; Search for the decorations around the current line.
903 (while (and cur (< (caar cur) curline))
904 (setq prev cur
905 cur (cdr cur)))
906 ;; 'cur' is the following decoration.
908 (if (and cur (caar cur))
909 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
911 (mapcar 'cdar (list prev next))
915 (defun rst-decoration-complete-p (deco)
916 "Return true if the decoration DECO around POINT is complete."
917 ;; Note: we assume that the detection of the overline as being the underline
918 ;; of a preceding title has already been detected, and has been eliminated
919 ;; from the decoration that is given to us.
921 ;; There is some sectioning already present, so check if the current
922 ;; sectioning is complete and correct.
923 (let* ((char (car deco))
924 (style (cadr deco))
925 (indent (caddr deco))
926 (endcol (save-excursion (end-of-line) (current-column)))
928 (if char
929 (let ((exps (concat "^"
930 (regexp-quote (make-string (+ endcol indent) char))
931 "$")))
932 (and
933 (save-excursion (forward-line +1)
934 (beginning-of-line)
935 (looking-at exps))
936 (or (not (eq style 'over-and-under))
937 (save-excursion (forward-line -1)
938 (beginning-of-line)
939 (looking-at exps))))
944 (defun rst-get-next-decoration
945 (curdeco hier &optional suggestion reverse-direction)
946 "Get the next decoration for CURDECO, in given hierarchy HIER.
947 If suggesting, suggest for new decoration SUGGESTION.
948 REVERSE-DIRECTION is used to reverse the cycling order."
950 (let* (
951 (char (car curdeco))
952 (style (cadr curdeco))
954 ;; Build a new list of decorations for the rotation.
955 (rotdecos
956 (append hier
957 ;; Suggest a new decoration.
958 (list suggestion
959 ;; If nothing to suggest, use first decoration.
960 (car hier)))) )
962 ;; Search for next decoration.
963 (cadr
964 (let ((cur (if reverse-direction rotdecos
965 (reverse rotdecos))))
966 (while (and cur
967 (not (and (eq char (caar cur))
968 (eq style (cadar cur)))))
969 (setq cur (cdr cur)))
970 cur))
972 ;; If not found, take the first of all decorations.
973 suggestion
977 (defun rst-adjust ()
978 "Auto-adjust the decoration around point.
980 Adjust/rotate the section decoration for the section title
981 around point or promote/demote the decorations inside the region,
982 depending on if the region is active. This function is meant to
983 be invoked possibly multiple times, and can vary its behaviour
984 with a positive prefix argument (toggle style), or with a
985 negative prefix argument (alternate behaviour).
987 This function is the main focus of this module and is a bit of a
988 swiss knife. It is meant as the single most essential function
989 to be bound to invoke to adjust the decorations of a section
990 title in restructuredtext. It tries to deal with all the
991 possible cases gracefully and to do `the right thing' in all
992 cases.
994 See the documentations of `rst-adjust-decoration' and
995 `rst-promote-region' for full details.
997 Prefix Arguments
998 ================
1000 The method can take either (but not both) of
1002 a. a (non-negative) prefix argument, which means to toggle the
1003 decoration style. Invoke with a prefix arg for example;
1005 b. a negative numerical argument, which generally inverts the
1006 direction of search in the file or hierarchy. Invoke with C--
1007 prefix for example."
1008 (interactive)
1010 (let* (;; Save our original position on the current line.
1011 (origpt (set-marker (make-marker) (point)))
1013 ;; Parse the positive and negative prefix arguments.
1014 (reverse-direction
1015 (and current-prefix-arg
1016 (< (prefix-numeric-value current-prefix-arg) 0)))
1017 (toggle-style
1018 (and current-prefix-arg (not reverse-direction))))
1020 (if (rst-portable-mark-active-p)
1021 ;; Adjust decorations within region.
1022 (rst-promote-region current-prefix-arg)
1023 ;; Adjust decoration around point.
1024 (rst-adjust-decoration toggle-style reverse-direction))
1026 ;; Run the hooks to run after adjusting.
1027 (run-hooks 'rst-adjust-hook)
1029 ;; Make sure to reset the cursor position properly after we're done.
1030 (goto-char origpt)
1034 (defvar rst-adjust-hook nil
1035 "Hooks to be run after running `rst-adjust'.")
1037 (defvar rst-new-decoration-down nil
1038 "If true, a new decoration being added will be initialized to
1039 be one level down from the previous decoration. If nil, a new
1040 decoration will be equal to the level of the previous
1041 decoration.")
1043 (defun rst-adjust-decoration (&optional toggle-style reverse-direction)
1044 "Adjust/rotate the section decoration for the section title around point.
1046 This function is meant to be invoked possibly multiple times, and
1047 can vary its behaviour with a true TOGGLE-STYLE argument, or with
1048 a REVERSE-DIRECTION argument.
1050 General Behaviour
1051 =================
1053 The next action it takes depends on context around the point, and
1054 it is meant to be invoked possibly more than once to rotate among
1055 the various possibilities. Basically, this function deals with:
1057 - adding a decoration if the title does not have one;
1059 - adjusting the length of the underline characters to fit a
1060 modified title;
1062 - rotating the decoration in the set of already existing
1063 sectioning decorations used in the file;
1065 - switching between simple and over-and-under styles.
1067 You should normally not have to read all the following, just
1068 invoke the method and it will do the most obvious thing that you
1069 would expect.
1072 Decoration Definitions
1073 ======================
1075 The decorations consist in
1077 1. a CHARACTER
1079 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1081 3. an INDENT (meaningful for the over-and-under style only)
1082 which determines how many characters and over-and-under
1083 style is hanging outside of the title at the beginning and
1084 ending.
1086 See source code for mode details.
1089 Detailed Behaviour Description
1090 ==============================
1092 Here are the gory details of the algorithm (it seems quite
1093 complicated, but really, it does the most obvious thing in all
1094 the particular cases):
1096 Before applying the decoration change, the cursor is placed on
1097 the closest line that could contain a section title.
1099 Case 1: No Decoration
1100 ---------------------
1102 If the current line has no decoration around it,
1104 - search backwards for the last previous decoration, and apply
1105 the decoration one level lower to the current line. If there
1106 is no defined level below this previous decoration, we suggest
1107 the most appropriate of the `rst-preferred-decorations'.
1109 If REVERSE-DIRECTION is true, we simply use the previous
1110 decoration found directly.
1112 - if there is no decoration found in the given direction, we use
1113 the first of `rst-preferred-decorations'.
1115 The prefix argument forces a toggle of the prescribed decoration
1116 style.
1118 Case 2: Incomplete Decoration
1119 -----------------------------
1121 If the current line does have an existing decoration, but the
1122 decoration is incomplete, that is, the underline/overline does
1123 not extend to exactly the end of the title line (it is either too
1124 short or too long), we simply extend the length of the
1125 underlines/overlines to fit exactly the section title.
1127 If the prefix argument is given, we toggle the style of the
1128 decoration as well.
1130 REVERSE-DIRECTION has no effect in this case.
1132 Case 3: Complete Existing Decoration
1133 ------------------------------------
1135 If the decoration is complete (i.e. the underline (overline)
1136 length is already adjusted to the end of the title line), we
1137 search/parse the file to establish the hierarchy of all the
1138 decorations (making sure not to include the decoration around
1139 point), and we rotate the current title's decoration from within
1140 that list (by default, going *down* the hierarchy that is present
1141 in the file, i.e. to a lower section level). This is meant to be
1142 used potentially multiple times, until the desired decoration is
1143 found around the title.
1145 If we hit the boundary of the hierarchy, exactly one choice from
1146 the list of preferred decorations is suggested/chosen, the first
1147 of those decoration that has not been seen in the file yet (and
1148 not including the decoration around point), and the next
1149 invocation rolls over to the other end of the hierarchy (i.e. it
1150 cycles). This allows you to avoid having to set which character
1151 to use by always using the
1153 If REVERSE-DIRECTION is true, the effect is to change the
1154 direction of rotation in the hierarchy of decorations, thus
1155 instead going *up* the hierarchy.
1157 However, if there is a non-negative prefix argument, we do not
1158 rotate the decoration, but instead simply toggle the style of the
1159 current decoration (this should be the most common way to toggle
1160 the style of an existing complete decoration).
1163 Point Location
1164 ==============
1166 The invocation of this function can be carried out anywhere
1167 within the section title line, on an existing underline or
1168 overline, as well as on an empty line following a section title.
1169 This is meant to be as convenient as possible.
1172 Indented Sections
1173 =================
1175 Indented section titles such as ::
1177 My Title
1178 --------
1180 are illegal in restructuredtext and thus not recognized by the
1181 parser. This code will thus not work in a way that would support
1182 indented sections (it would be ambiguous anyway).
1185 Joint Sections
1186 ==============
1188 Section titles that are right next to each other may not be
1189 treated well. More work might be needed to support those, and
1190 special conditions on the completeness of existing decorations
1191 might be required to make it non-ambiguous.
1193 For now we assume that the decorations are disjoint, that is,
1194 there is at least a single line between the titles/decoration
1195 lines.
1198 Suggested Binding
1199 =================
1201 We suggest that you bind this function on C-=. It is close to
1202 C-- so a negative argument can be easily specified with a flick
1203 of the right hand fingers and the binding is unused in `text-mode'."
1204 (interactive)
1206 ;; If we were invoked directly, parse the prefix arguments into the
1207 ;; arguments of the function.
1208 (if current-prefix-arg
1209 (setq reverse-direction
1210 (and current-prefix-arg
1211 (< (prefix-numeric-value current-prefix-arg) 0))
1213 toggle-style
1214 (and current-prefix-arg (not reverse-direction))))
1216 (let* (;; Check if we're on an underline around a section title, and move the
1217 ;; cursor to the title if this is the case.
1218 (moved (rst-normalize-cursor-position))
1220 ;; Find the decoration and completeness around point.
1221 (curdeco (rst-get-decoration))
1222 (char (car curdeco))
1223 (style (cadr curdeco))
1224 (indent (caddr curdeco))
1226 ;; New values to be computed.
1227 char-new style-new indent-new
1230 ;; We've moved the cursor... if we're not looking at some text, we have
1231 ;; nothing to do.
1232 (if (save-excursion (beginning-of-line)
1233 (looking-at rst-section-text-regexp))
1234 (progn
1235 (cond
1236 ;;-------------------------------------------------------------------
1237 ;; Case 1: No Decoration
1238 ((and (eq char nil) (eq style nil))
1240 (let* ((alldecos (rst-find-all-decorations))
1242 (around (rst-get-decorations-around alldecos))
1243 (prev (car around))
1246 (hier (rst-get-hierarchy alldecos))
1249 ;; Advance one level down.
1250 (setq cur
1251 (if prev
1252 (if (not reverse-direction)
1253 (or (funcall (if rst-new-decoration-down 'cadr 'car)
1254 (rst-get-decoration-match hier prev))
1255 (rst-suggest-new-decoration hier prev))
1256 prev)
1257 (copy-list (car rst-preferred-decorations))
1260 ;; Invert the style if requested.
1261 (if toggle-style
1262 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1263 'over-and-under 'simple)) )
1265 (setq char-new (car cur)
1266 style-new (cadr cur)
1267 indent-new (caddr cur))
1270 ;;-------------------------------------------------------------------
1271 ;; Case 2: Incomplete Decoration
1272 ((not (rst-decoration-complete-p curdeco))
1274 ;; Invert the style if requested.
1275 (if toggle-style
1276 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1278 (setq char-new char
1279 style-new style
1280 indent-new indent))
1282 ;;-------------------------------------------------------------------
1283 ;; Case 3: Complete Existing Decoration
1285 (if toggle-style
1287 ;; Simply switch the style of the current decoration.
1288 (setq char-new char
1289 style-new (if (eq style 'simple) 'over-and-under 'simple)
1290 indent-new rst-default-indent)
1292 ;; Else, we rotate, ignoring the decoration around the current
1293 ;; line...
1294 (let* ((alldecos (rst-find-all-decorations))
1296 (hier (rst-get-hierarchy alldecos (line-number-at-pos)))
1298 ;; Suggestion, in case we need to come up with something
1299 ;; new
1300 (suggestion (rst-suggest-new-decoration
1301 hier
1302 (car (rst-get-decorations-around alldecos))))
1304 (nextdeco (rst-get-next-decoration
1305 curdeco hier suggestion reverse-direction))
1309 ;; Indent, if present, always overrides the prescribed indent.
1310 (setq char-new (car nextdeco)
1311 style-new (cadr nextdeco)
1312 indent-new (caddr nextdeco))
1317 ;; Override indent with present indent!
1318 (setq indent-new (if (> indent 0) indent indent-new))
1320 (if (and char-new style-new)
1321 (rst-update-section char-new style-new indent-new))
1325 ;; Correct the position of the cursor to more accurately reflect where it
1326 ;; was located when the function was invoked.
1327 (unless (= moved 0)
1328 (forward-line (- moved))
1329 (end-of-line))
1333 ;; Maintain an alias for compatibility.
1334 (defalias 'rst-adjust-section-title 'rst-adjust)
1337 (defun rst-promote-region (&optional demote)
1338 "Promote the section titles within the region.
1340 With argument DEMOTE or a prefix argument, demote the
1341 section titles instead. The algorithm used at the boundaries of
1342 the hierarchy is similar to that used by `rst-adjust-decoration'."
1343 (interactive)
1345 (let* ((demote (or current-prefix-arg demote))
1346 (alldecos (rst-find-all-decorations))
1347 (cur alldecos)
1349 (hier (rst-get-hierarchy alldecos))
1350 (suggestion (rst-suggest-new-decoration hier))
1352 (region-begin-line (line-number-at-pos (region-beginning)))
1353 (region-end-line (line-number-at-pos (region-end)))
1355 marker-list
1358 ;; Skip the markers that come before the region beginning
1359 (while (and cur (< (caar cur) region-begin-line))
1360 (setq cur (cdr cur)))
1362 ;; Create a list of markers for all the decorations which are found within
1363 ;; the region.
1364 (save-excursion
1365 (let (m line)
1366 (while (and cur (< (setq line (caar cur)) region-end-line))
1367 (setq m (make-marker))
1368 (goto-line line)
1369 (push (list (set-marker m (point)) (cdar cur)) marker-list)
1370 (setq cur (cdr cur)) ))
1372 ;; Apply modifications.
1373 (let (nextdeco)
1374 (dolist (p marker-list)
1375 ;; Go to the decoration to promote.
1376 (goto-char (car p))
1378 ;; Rotate the next decoration.
1379 (setq nextdeco (rst-get-next-decoration
1380 (cadr p) hier suggestion demote))
1382 ;; Update the decoration.
1383 (apply 'rst-update-section nextdeco)
1385 ;; Clear marker to avoid slowing down the editing after we're done.
1386 (set-marker (car p) nil)
1388 (setq deactivate-mark nil)
1393 (defun rst-display-decorations-hierarchy (&optional decorations)
1394 "Display the current file's section title decorations hierarchy.
1395 This function expects a list of (char, style, indent) triples in
1396 DECORATIONS."
1397 (interactive)
1399 (if (not decorations)
1400 (setq decorations (rst-get-hierarchy)))
1401 (with-output-to-temp-buffer "*rest section hierarchy*"
1402 (let ((level 1))
1403 (with-current-buffer standard-output
1404 (dolist (x decorations)
1405 (insert (format "\nSection Level %d" level))
1406 (apply 'rst-update-section x)
1407 (goto-char (point-max))
1408 (insert "\n")
1409 (incf level)
1413 (defun rst-straighten-decorations ()
1414 "Redo all the decorations in the current buffer.
1415 This is done using our preferred set of decorations. This can be
1416 used, for example, when using somebody else's copy of a document,
1417 in order to adapt it to our preferred style."
1418 (interactive)
1419 (save-excursion
1420 (let* ((alldecos (rst-find-all-decorations))
1421 (hier (rst-get-hierarchy alldecos))
1423 ;; Get a list of pairs of (level . marker)
1424 (levels-and-markers (mapcar
1425 (lambda (deco)
1426 (cons (position (cdr deco) hier :test 'equal)
1427 (let ((m (make-marker)))
1428 (goto-line (car deco))
1429 (set-marker m (point))
1430 m)))
1431 alldecos))
1433 (dolist (lm levels-and-markers)
1434 ;; Go to the appropriate position
1435 (goto-char (cdr lm))
1437 ;; Apply the new styule
1438 (apply 'rst-update-section (nth (car lm) rst-preferred-decorations))
1440 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1441 (set-marker (cdr lm) nil)
1448 (defun rst-straighten-deco-spacing ()
1449 "Adjust the spacing before and after decorations in the entire document.
1450 The spacing will be set to two blank lines before the first two
1451 section levels, and one blank line before any of the other
1452 section levels."
1453 ;; FIXME: we need to take care of subtitle at some point.
1454 (interactive)
1455 (save-excursion
1456 (let* ((alldecos (rst-find-all-decorations)))
1458 ;; Work the list from the end, so that we don't have to use markers to
1459 ;; adjust for the changes in the document.
1460 (dolist (deco (nreverse alldecos))
1461 ;; Go to the appropriate position.
1462 (goto-line (car deco))
1463 (insert "@\n")
1464 ;; FIXME: todo, we
1469 (defun rst-find-pfx-in-region (beg end pfx-re)
1470 "Find all the positions of prefixes in region between BEG and END.
1471 This is used to find bullets and enumerated list items. PFX-RE
1472 is a regular expression for matching the lines with items."
1473 (let (pfx)
1474 (save-excursion
1475 (goto-char beg)
1476 (while (< (point) end)
1477 (back-to-indentation)
1478 (when (and
1479 (looking-at pfx-re)
1480 (let ((pfx-col (current-column)))
1481 (save-excursion
1482 (forward-line -1)
1483 (back-to-indentation)
1484 (or (looking-at "^[ \t]*$")
1485 (> (current-column) pfx-col)
1486 (and (= (current-column) pfx-col)
1487 (looking-at pfx-re))))))
1488 (setq pfx (cons (cons (point) (current-column))
1489 pfx)))
1490 (forward-line 1)) )
1491 (nreverse pfx)))
1493 (defvar rst-re-bullets
1494 (format "\\([%s][ \t]\\)[^ \t]" (regexp-quote (concat rst-bullets)))
1495 "Regexp for finding bullets.")
1497 (defvar rst-re-enumerations
1498 "\\(\\(#\\|[0-9]+\\)\\.[ \t]\\)[^ \t]"
1499 "Regexp for finding bullets.")
1501 (defvar rst-re-items
1502 (format "\\(%s\\|%s\\)[^ \t]"
1503 (format "[%s][ \t]" (regexp-quote (concat rst-bullets)))
1504 "\\(#\\|[0-9]+\\)\\.[ \t]")
1505 "Regexp for finding bullets.")
1507 (defvar rst-preferred-bullets
1508 '(?- ?* ?+)
1509 "List of favourite bullets to set for straightening bullets.")
1511 (defun rst-straighten-bullets-region (beg end)
1512 "Make all the bulleted list items in the region consistent.
1513 The region is specified between BEG and END. You can use this
1514 after you have merged multiple bulleted lists to make them use
1515 the same/correct/consistent bullet characters.
1517 See variable `rst-preferred-bullets' for the list of bullets to
1518 adjust. If bullets are found on levels beyond the
1519 `rst-preferred-bullets' list, they are not modified."
1520 (interactive "r")
1522 (let ((bullets (rst-find-pfx-in-region beg end
1523 rst-re-bullets))
1524 (levtable (make-hash-table :size 4)))
1526 ;; Create a map of levels to list of positions.
1527 (dolist (x bullets)
1528 (let ((key (cdr x)))
1529 (puthash key
1530 (append (gethash key levtable (list))
1531 (list (car x)))
1532 levtable)))
1534 ;; Sort this map and create a new map of prefix char and list of positions.
1535 (let (poslist)
1536 (maphash (lambda (x y) (setq poslist (cons (cons x y) poslist))) levtable)
1538 (mapcar* (lambda (x char)
1539 ;; Apply the characters.
1540 (dolist (pos (cdr x))
1541 (goto-char pos)
1542 (delete-char 1)
1543 (insert (char-to-string char))))
1545 ;; Sorted list of indent . positions
1546 (sort poslist (lambda (x y) (<= (car x) (car y))))
1548 ;; List of preferred bullets.
1549 rst-preferred-bullets)
1553 (defun rst-rstrip (str)
1554 "Strips the whitespace at the end of string STR."
1555 (string-match "[ \t\n]*\\'" str)
1556 (substring str 0 (match-beginning 0)))
1558 (defun rst-get-stripped-line ()
1559 "Return the line at cursor, stripped from whitespace."
1560 (re-search-forward "\\S-.*\\S-" (line-end-position))
1561 (buffer-substring-no-properties (match-beginning 0)
1562 (match-end 0)) )
1564 (defun rst-section-tree (alldecos)
1565 "Get the hierarchical tree of section titles.
1567 Returns a hierarchical tree of the sections titles in the
1568 document, for decorations ALLDECOS. This can be used to generate
1569 a table of contents for the document. The top node will always
1570 be a nil node, with the top level titles as children (there may
1571 potentially be more than one).
1573 Each section title consists in a cons of the stripped title
1574 string and a marker to the section in the original text document.
1576 If there are missing section levels, the section titles are
1577 inserted automatically, and the title string is set to nil, and
1578 the marker set to the first non-nil child of itself.
1579 Conceptually, the nil nodes--i.e. those which have no title--are
1580 to be considered as being the same line as their first non-nil
1581 child. This has advantages later in processing the graph."
1583 (let* ((hier (rst-get-hierarchy alldecos))
1584 (levels (make-hash-table :test 'equal :size 10))
1585 lines)
1587 (let ((lev 0))
1588 (dolist (deco hier)
1589 ;; Compare just the character and indent in the hash table.
1590 (puthash (cons (car deco) (cadr deco)) lev levels)
1591 (incf lev)))
1593 ;; Create a list of lines that contains (text, level, marker) for each
1594 ;; decoration.
1595 (save-excursion
1596 (setq lines
1597 (mapcar (lambda (deco)
1598 (goto-line (car deco))
1599 (list (gethash (cons (cadr deco) (caddr deco)) levels)
1600 (rst-get-stripped-line)
1601 (let ((m (make-marker)))
1602 (beginning-of-line 1)
1603 (set-marker m (point)))
1605 alldecos)))
1607 (let ((lcontnr (cons nil lines)))
1608 (rst-section-tree-rec lcontnr -1))))
1611 (defun rst-section-tree-rec (decos lev)
1612 "Recursive guts of the section tree construction.
1613 DECOS is a cons cell whose cdr is the remaining list of
1614 decorations, and we change it as we consume them. LEV is the
1615 current level of that node. This function returns a pair of the
1616 subtree that was built. This treats the decos list
1617 destructively."
1619 (let ((ndeco (cadr decos))
1620 node
1621 children)
1623 ;; If the next decoration matches our level
1624 (when (and ndeco (= (car ndeco) lev))
1625 ;; Pop the next decoration and create the current node with it
1626 (setcdr decos (cddr decos))
1627 (setq node (cdr ndeco)) )
1628 ;; Else we let the node title/marker be unset.
1630 ;; Build the child nodes
1631 (while (and (cdr decos) (> (caadr decos) lev))
1632 (setq children
1633 (cons (rst-section-tree-rec decos (1+ lev))
1634 children)))
1635 (setq children (reverse children))
1637 ;; If node is still unset, we use the marker of the first child.
1638 (when (eq node nil)
1639 (setq node (cons nil (cdaar children))))
1641 ;; Return this node with its children.
1642 (cons node children)
1646 (defun rst-section-tree-point (node &optional point)
1647 "Find tree node at point.
1648 Given a computed and valid section tree in NODE and a point
1649 POINT (default being the current point in the current buffer),
1650 find and return the node within the sectree where the cursor
1651 lives.
1653 Return values: a pair of (parent path, container subtree). The
1654 parent path is simply a list of the nodes above the container
1655 subtree node that we're returning."
1657 (let (path outtree)
1659 (let* ((curpoint (or point (point))))
1661 ;; Check if we are before the current node.
1662 (if (and (cadar node) (>= curpoint (cadar node)))
1664 ;; Iterate all the children, looking for one that might contain the
1665 ;; current section.
1666 (let ((curnode (cdr node))
1667 last)
1669 (while (and curnode (>= curpoint (cadaar curnode)))
1670 (setq last curnode
1671 curnode (cdr curnode)))
1673 (if last
1674 (let ((sub (rst-section-tree-point (car last) curpoint)))
1675 (setq path (car sub)
1676 outtree (cdr sub)))
1677 (setq outtree node))
1680 (cons (cons (car node) path) outtree)
1684 (defun rst-toc-insert (&optional pfxarg)
1685 "Insert a simple text rendering of the table of contents.
1686 By default the top level is ignored if there is only one, because
1687 we assume that the document will have a single title.
1689 If a numeric prefix argument PFXARG is given, insert the TOC up
1690 to the specified level.
1692 The TOC is inserted indented at the current column."
1694 (interactive "P")
1696 (let* (;; Check maximum level override
1697 (rst-toc-insert-max-level
1698 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
1699 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
1701 ;; Get the section tree for the current cursor point.
1702 (sectree-pair
1703 (rst-section-tree-point
1704 (rst-section-tree (rst-find-all-decorations))))
1706 ;; Figure out initial indent.
1707 (initial-indent (make-string (current-column) ? ))
1708 (init-point (point)))
1710 (when (cddr sectree-pair)
1711 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
1713 ;; Fixup for the first line.
1714 (delete-region init-point (+ init-point (length initial-indent)))
1716 ;; Delete the last newline added.
1717 (delete-backward-char 1)
1721 (defgroup rst-toc nil
1722 "Settings for reStructuredText table of contents."
1723 :group 'rst
1724 :version "21.1")
1726 (defcustom rst-toc-indent 2
1727 "Indentation for table-of-contents display.
1728 Also used for formatting insertion, when numbering is disabled."
1729 :group 'rst-toc)
1731 (defcustom rst-toc-insert-style 'fixed
1732 "Insertion style for table-of-contents.
1733 Set this to one of the following values to determine numbering and
1734 indentation style:
1735 - plain: no numbering (fixed indentation)
1736 - fixed: numbering, but fixed indentation
1737 - aligned: numbering, titles aligned under each other
1738 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
1739 :group 'rst-toc)
1741 (defcustom rst-toc-insert-number-separator " "
1742 "Separator that goes between the TOC number and the title."
1743 :group 'rst-toc)
1745 ;; This is used to avoid having to change the user's mode.
1746 (defvar rst-toc-insert-click-keymap
1747 (let ((map (make-sparse-keymap)))
1748 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
1749 map)
1750 "(Internal) What happens when you click on propertized text in the TOC.")
1752 (defcustom rst-toc-insert-max-level nil
1753 "If non-nil, maximum depth of the inserted TOC."
1754 :group 'rst-toc)
1756 (defun rst-toc-insert-node (node level indent pfx)
1757 "Insert tree node NODE in table-of-contents.
1758 Recursive function that does printing of the inserted toc. LEVEL
1759 is the depth level of the sections in the tree. INDENT bis the
1760 indentation string. PFX is the prefix numbering, that includes
1761 the alignment necessary for all the children of level to
1762 align."
1764 ;; Note: we do child numbering from the parent, so we start number the
1765 ;; children one level before we print them.
1766 (let ((do-print (> level 0))
1767 (count 1))
1768 (when do-print
1769 (insert indent)
1770 (let ((b (point)))
1771 (unless (equal rst-toc-insert-style 'plain)
1772 (insert pfx rst-toc-insert-number-separator))
1773 (insert (or (caar node) "[missing node]"))
1774 ;; Add properties to the text, even though in normal text mode it
1775 ;; won't be doing anything for now. Not sure that I want to change
1776 ;; mode stuff. At least the highlighting gives the idea that this
1777 ;; is generated automatically.
1778 (put-text-property b (point) 'mouse-face 'highlight)
1779 (put-text-property b (point) 'rst-toc-target (cadar node))
1780 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
1783 (insert "\n")
1785 ;; Prepare indent for children.
1786 (setq indent
1787 (cond
1788 ((eq rst-toc-insert-style 'plain)
1789 (concat indent (make-string rst-toc-indent ? )))
1791 ((eq rst-toc-insert-style 'fixed)
1792 (concat indent (make-string rst-toc-indent ? )))
1794 ((eq rst-toc-insert-style 'aligned)
1795 (concat indent (make-string (+ (length pfx) 2) ? )))
1797 ((eq rst-toc-insert-style 'listed)
1798 (concat (substring indent 0 -3)
1799 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
1803 (if (or (eq rst-toc-insert-max-level nil)
1804 (< level rst-toc-insert-max-level))
1805 (let ((do-child-numbering (>= level 0))
1806 fmt)
1807 (if do-child-numbering
1808 (progn
1809 ;; Add a separating dot if there is already a prefix
1810 (if (> (length pfx) 0)
1811 (setq pfx (concat (rst-rstrip pfx) ".")))
1813 ;; Calculate the amount of space that the prefix will require
1814 ;; for the numbers.
1815 (if (cdr node)
1816 (setq fmt (format "%%-%dd"
1817 (1+ (floor (log10 (length
1818 (cdr node))))))))
1821 (dolist (child (cdr node))
1822 (rst-toc-insert-node child
1823 (1+ level)
1824 indent
1825 (if do-child-numbering
1826 (concat pfx (format fmt count)) pfx))
1827 (incf count)))
1832 (defun rst-toc-insert-find-delete-contents ()
1833 "Find and deletes an existing comment after the first contents directive.
1834 Delete that region. Return t if found and the cursor is left after the comment."
1835 (goto-char (point-min))
1836 ;; We look for the following and the following only (in other words, if your
1837 ;; syntax differs, this won't work. If you would like a more flexible thing,
1838 ;; contact the author, I just can't imagine that this requirement is
1839 ;; unreasonable for now).
1841 ;; .. contents:: [...anything here...]
1842 ;; ..
1843 ;; XXXXXXXX
1844 ;; XXXXXXXX
1845 ;; [more lines]
1847 (let ((beg
1848 (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
1849 nil t))
1850 last-real)
1851 (when beg
1852 ;; Look for the first line that starts at the first column.
1853 (forward-line 1)
1854 (beginning-of-line)
1855 (while (and
1856 (< (point) (point-max))
1857 (or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
1858 (looking-at "[ \t]*$")))
1859 (forward-line 1)
1861 (if last-real
1862 (progn
1863 (goto-char last-real)
1864 (end-of-line)
1865 (delete-region beg (point)))
1866 (goto-char beg))
1870 (defun rst-toc-update ()
1871 "Automatically find the contents section of a document and update.
1872 Updates the inserted TOC if present. You can use this in your
1873 file-write hook to always make it up-to-date automatically."
1874 (interactive)
1875 (let ((p (point)))
1876 (save-excursion
1877 (when (rst-toc-insert-find-delete-contents)
1878 (insert "\n ")
1879 (rst-toc-insert)
1881 ;; Somehow save-excursion does not really work well.
1882 (goto-char p))
1883 ;; Note: always return nil, because this may be used as a hook.
1886 ;; Note: we cannot bind the TOC update on file write because it messes with
1887 ;; undo. If we disable undo, since it adds and removes characters, the
1888 ;; positions in the undo list are not making sense anymore. Dunno what to do
1889 ;; with this, it would be nice to update when saving.
1891 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
1892 ;; (defun rst-toc-update-fun ()
1893 ;; ;; Disable undo for the write file hook.
1894 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
1896 (defalias 'rst-toc-insert-update 'rst-toc-update) ;; backwards compat.
1898 ;;------------------------------------------------------------------------------
1900 (defun rst-toc-node (node level)
1901 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
1903 (if (> level 0)
1904 (let ((b (point)))
1905 ;; Insert line text.
1906 (insert (make-string (* rst-toc-indent (1- level)) ? ))
1907 (insert (or (caar node) "[missing node]"))
1909 ;; Highlight lines.
1910 (put-text-property b (point) 'mouse-face 'highlight)
1912 ;; Add link on lines.
1913 (put-text-property b (point) 'rst-toc-target (cadar node))
1915 (insert "\n")
1918 (dolist (child (cdr node))
1919 (rst-toc-node child (1+ level))))
1921 (defun rst-toc-count-lines (node target-node)
1922 "Count the number of lines from NODE to the TARGET-NODE node.
1923 This recursive function returns a cons of the number of
1924 additional lines that have been counted for its node and children
1925 and 't if the node has been found."
1927 (let ((count 1)
1928 found)
1929 (if (eq node target-node)
1930 (setq found t)
1931 (let ((child (cdr node)))
1932 (while (and child (not found))
1933 (let ((cl (rst-toc-count-lines (car child) target-node)))
1934 (setq count (+ count (car cl))
1935 found (cdr cl)
1936 child (cdr child))))))
1937 (cons count found)))
1940 (defun rst-toc ()
1941 "Display a table-of-contents.
1942 Finds all the section titles and their decorations in the
1943 file, and displays a hierarchically-organized list of the
1944 titles, which is essentially a table-of-contents of the
1945 document.
1947 The Emacs buffer can be navigated, and selecting a section
1948 brings the cursor in that section."
1949 (interactive)
1950 (let* ((curbuf (current-buffer))
1952 ;; Get the section tree
1953 (alldecos (rst-find-all-decorations))
1954 (sectree (rst-section-tree alldecos))
1956 (our-node (cdr (rst-section-tree-point sectree)))
1957 line
1959 ;; Create a temporary buffer.
1960 (buf (get-buffer-create rst-toc-buffer-name))
1963 (with-current-buffer buf
1964 (let ((inhibit-read-only t))
1965 (rst-toc-mode)
1966 (delete-region (point-min) (point-max))
1967 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
1968 (put-text-property (point-min) (point)
1969 'face (list '(background-color . "gray")))
1970 (rst-toc-node sectree 0)
1972 ;; Count the lines to our found node.
1973 (let ((linefound (rst-toc-count-lines sectree our-node)))
1974 (setq line (if (cdr linefound) (car linefound) 0)))
1976 (display-buffer buf)
1977 (pop-to-buffer buf)
1979 ;; Save the buffer to return to.
1980 (set (make-local-variable 'rst-toc-return-buffer) curbuf)
1982 ;; Move the cursor near the right section in the TOC.
1983 (goto-line line)
1987 (defun rst-toc-mode-find-section ()
1988 "Get the section from text property at point."
1989 (let ((pos (get-text-property (point) 'rst-toc-target)))
1990 (unless pos
1991 (error "No section on this line"))
1992 (unless (buffer-live-p (marker-buffer pos))
1993 (error "Buffer for this section was killed"))
1994 pos))
1996 (defvar rst-toc-buffer-name "*Table of Contents*"
1997 "Name of the Table of Contents buffer.")
1999 (defun rst-goto-section (&optional kill)
2000 "Go to the section the current line describes."
2001 (interactive)
2002 (let ((pos (rst-toc-mode-find-section)))
2003 (when kill
2004 (kill-buffer (get-buffer rst-toc-buffer-name)))
2005 (pop-to-buffer (marker-buffer pos))
2006 (goto-char pos)
2007 ;; FIXME: make the recentering conditional on scroll.
2008 (recenter 5)))
2010 (defun rst-toc-mode-goto-section ()
2011 "Go to the section the current line describes and kill the toc buffer."
2012 (interactive)
2013 (rst-goto-section t))
2015 (defun rst-toc-mode-mouse-goto (event)
2016 "In `rst-toc' mode, go to the occurrence whose line you click on.
2017 EVENT is the input event."
2018 (interactive "e")
2019 (let (pos)
2020 (save-excursion
2021 (set-buffer (window-buffer (posn-window (event-end event))))
2022 (save-excursion
2023 (goto-char (posn-point (event-end event)))
2024 (setq pos (rst-toc-mode-find-section))))
2025 (pop-to-buffer (marker-buffer pos))
2026 (goto-char pos)
2027 (recenter 5)))
2029 (defun rst-toc-mode-mouse-goto-kill (event)
2030 (interactive "e")
2031 (call-interactively 'rst-toc-mode-mouse-goto event)
2032 (kill-buffer (get-buffer rst-toc-buffer-name)))
2034 (defvar rst-toc-return-buffer nil
2035 "Buffer local variable that is used to return to the original
2036 buffer from the TOC.")
2038 (defun rst-toc-quit-window ()
2039 (interactive)
2040 (quit-window)
2041 (pop-to-buffer rst-toc-return-buffer))
2043 (defvar rst-toc-mode-map
2044 (let ((map (make-sparse-keymap)))
2045 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2046 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2047 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2048 (define-key map "f" 'rst-toc-mode-goto-section)
2049 (define-key map "q" 'rst-toc-quit-window)
2050 (define-key map "z" 'kill-this-buffer)
2051 map)
2052 "Keymap for `rst-toc-mode'.")
2054 (put 'rst-toc-mode 'mode-class 'special)
2056 (defun rst-toc-mode ()
2057 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2058 (interactive)
2059 (kill-all-local-variables)
2060 (use-local-map rst-toc-mode-map)
2061 (setq major-mode 'rst-toc-mode)
2062 (setq mode-name "ReST-TOC")
2063 (setq buffer-read-only t)
2066 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2067 ;; features.
2070 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2072 ;; Section movement commands.
2075 (defun rst-forward-section (&optional offset)
2076 "Skip to the next restructured text section title.
2077 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2078 backwards in the file (default is to use 1)."
2079 (interactive)
2080 (let* (;; Default value for offset.
2081 (offset (or offset 1))
2083 ;; Get all the decorations in the file, with their line numbers.
2084 (alldecos (rst-find-all-decorations))
2086 ;; Get the current line.
2087 (curline (line-number-at-pos))
2089 (cur alldecos)
2090 (idx 0)
2093 ;; Find the index of the "next" decoration w.r.t. to the current line.
2094 (while (and cur (< (caar cur) curline))
2095 (setq cur (cdr cur))
2096 (incf idx))
2097 ;; 'cur' is the decoration on or following the current line.
2099 (if (and (> offset 0) cur (= (caar cur) curline))
2100 (incf idx))
2102 ;; Find the final index.
2103 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2104 (setq cur (nth idx alldecos))
2106 ;; If the index is positive, goto the line, otherwise go to the buffer
2107 ;; boundaries.
2108 (if (and cur (>= idx 0))
2109 (goto-line (car cur))
2110 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
2113 (defun rst-backward-section ()
2114 "Like rst-forward-section, except move back one title.
2115 With a prefix argument, move backward by a page."
2116 (interactive)
2117 (rst-forward-section -1))
2119 (defun rst-mark-section (&optional arg allow-extend)
2120 "Select the section that point is currently in."
2121 ;; Cloned from mark-paragraph.
2122 (interactive "p\np")
2123 (unless arg (setq arg 1))
2124 (when (zerop arg)
2125 (error "Cannot mark zero sections"))
2126 (cond ((and allow-extend
2127 (or (and (eq last-command this-command) (mark t))
2128 (rst-portable-mark-active-p)))
2129 (set-mark
2130 (save-excursion
2131 (goto-char (mark))
2132 (rst-forward-section arg)
2133 (point))))
2135 (rst-forward-section arg)
2136 (push-mark nil t t)
2137 (rst-forward-section (- arg)))))
2144 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2145 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2146 ;; always 2 or 3 characters apart horizontally with rest.
2148 ;; (FIXME: there is currently a bug that makes the region go away when we do that.)
2149 (defvar rst-shift-fill-region nil
2150 "Set to true if you want to automatically re-fill the region that is being
2151 shifted.")
2153 (defun rst-find-leftmost-column (beg end)
2154 "Finds the leftmost column in the region."
2155 (let ((mincol 1000))
2156 (save-excursion
2157 (goto-char beg)
2158 (while (< (point) end)
2159 (back-to-indentation)
2160 (unless (looking-at "[ \t]*$")
2161 (setq mincol (min mincol (current-column))))
2162 (forward-line 1)
2164 mincol))
2167 ;; What we really need to do is compute all the possible alignment possibilities
2168 ;; and then select one.
2170 ;; .. line-block::
2172 ;; a) sdjsds
2174 ;; - sdjsd jsjds
2176 ;; sdsdsjdsj
2178 ;; 11. sjdss jddjs
2180 ;; * * * * * * *
2182 ;; Move backwards, accumulate the beginning positions, and also the second
2183 ;; positions, in case the line matches the bullet pattern, and then sort.
2185 (defun rst-compute-bullet-tabs (&optional pt)
2186 "Search backwards from point (or point PT if specified) to
2187 build the list of possible horizontal alignment points that
2188 includes the beginning and contents of a restructuredtext
2189 bulleted or enumerated list item. Return a sorted list
2190 of (column-number . line) pairs."
2191 (save-excursion
2192 (when pt (goto-char pt))
2194 ;; We work our way backwards and towards the left.
2195 (let ((leftcol 100000) ;; Current column.
2196 (tablist nil) ;; List of tab positions.
2199 ;; Start by skipping the current line.
2200 (beginning-of-line 0)
2202 ;; Search backwards for each line.
2203 (while (and (> (point) (point-min))
2204 (> leftcol 0))
2206 ;; Skip empty lines.
2207 (unless (looking-at "^[ \t]*$")
2208 ;; Inspect the current non-empty line
2209 (back-to-indentation)
2211 ;; Skip lines that are beyond the current column (we want to move
2212 ;; towards the left).
2213 (let ((col (current-column)))
2214 (when (< col leftcol)
2216 ;; Add the beginning of the line as a tabbing point.
2217 (unless (memq col (mapcar 'car tablist))
2218 (setq tablist (cons (cons col (point)) tablist)))
2220 ;; Look at the line to figure out if it is a bulleted or enumerate
2221 ;; list item.
2222 (when (looking-at
2223 (concat
2224 "\\(?:"
2225 "\\(\\(?:[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]\\)[ \t]+\\)[^ \t\n]"
2226 "\\|"
2227 (format "\\(%s%s+[ \t]+\\)[^ \t\n]"
2228 (regexp-quote (thing-at-point 'char))
2229 (regexp-quote (thing-at-point 'char)))
2230 "\\)"
2232 ;; Add the column of the contained item.
2233 (let* ((matchlen (length (or (match-string 1) (match-string 2))))
2234 (newcol (+ col matchlen)))
2235 (unless (or (>= newcol leftcol)
2236 (memq (+ col matchlen) (mapcar 'car tablist)))
2237 (setq tablist (cons
2238 (cons (+ col matchlen) (+ (point) matchlen))
2239 tablist))))
2242 (setq leftcol col)
2245 ;; Move backwards one line.
2246 (beginning-of-line 0))
2248 (sort tablist (lambda (x y) (<= (car x) (car y))))
2251 (defun rst-debug-print-tabs (tablist)
2252 "A routine that inserts a line and places special characters at
2253 the tab points in the given tablist."
2254 (beginning-of-line)
2255 (insert (concat "\n" (make-string 1000 ? ) "\n"))
2256 (beginning-of-line 0)
2257 (dolist (col tablist)
2258 (beginning-of-line)
2259 (forward-char (car col))
2260 (delete-char 1)
2261 (insert "@")
2264 (defun rst-debug-mark-found (tablist)
2265 "A routine that inserts a line and places special characters at
2266 the tab points in the given tablist."
2267 (dolist (col tablist)
2268 (when (cdr col)
2269 (goto-char (cdr col))
2270 (insert "@"))))
2273 (defvar rst-shift-basic-offset 2
2274 "Basic horizontal shift distance when there is no preceding alignment tabs.")
2276 (defun rst-shift-region-guts (find-next-fun offset-fun)
2277 "(See rst-shift-region-right for a description.)"
2278 (let* ((mbeg (set-marker (make-marker) (region-beginning)))
2279 (mend (set-marker (make-marker) (region-end)))
2280 (tabs (rst-compute-bullet-tabs mbeg))
2281 (leftmostcol (rst-find-leftmost-column (region-beginning) (region-end)))
2283 ;; Add basic offset tabs at the end of the list. This is a better
2284 ;; implementation technique than hysteresis and a basic offset because it
2285 ;; insures that movement in both directions is consistently using the same
2286 ;; column positions. This makes it more predictable.
2287 (setq tabs
2288 (append tabs
2289 (mapcar (lambda (x) (cons x nil))
2290 (let ((maxcol 120)
2291 (max-lisp-eval-depth 2000))
2292 (flet ((addnum (x)
2293 (if (> x maxcol)
2295 (cons x (addnum
2296 (+ x rst-shift-basic-offset))))))
2297 (addnum (or (caar (last tabs)) 0))))
2300 ;; (For debugging.)
2301 ;;; (save-excursion (goto-char mbeg) (forward-char -1) (rst-debug-print-tabs tabs))))
2302 ;;; (print tabs)
2303 ;;; (save-excursion (rst-debug-mark-found tabs))
2305 ;; Apply the indent.
2306 (indent-rigidly
2307 mbeg mend
2309 ;; Find the next tab after the leftmost columnt.
2310 (let ((tab (funcall find-next-fun tabs leftmostcol)))
2312 (if tab
2313 (progn
2314 (when (cdar tab)
2315 (message "Aligned on '%s'"
2316 (save-excursion
2317 (goto-char (cdar tab))
2318 (buffer-substring-no-properties
2319 (line-beginning-position)
2320 (line-end-position))))
2322 (- (caar tab) leftmostcol)) ;; Num chars.
2324 ;; Otherwise use the basic offset
2325 (funcall offset-fun rst-shift-basic-offset)
2328 ;; Optionally reindent.
2329 (when rst-shift-fill-region
2330 (fill-region mbeg mend))
2333 (defun rst-shift-region-right (pfxarg)
2334 "Indent region ridigly, by a few characters to the right. This
2335 function first computes all possible alignment columns by
2336 inspecting the lines preceding the region for bulleted or
2337 enumerated list items. If the leftmost column is beyond the
2338 preceding lines, the region is moved to the right by
2339 rst-shift-basic-offset. With a prefix argument, do not
2340 automatically fill the region."
2341 (interactive "P")
2342 (let ((rst-shift-fill-region
2343 (if (not pfxarg) rst-shift-fill-region)))
2344 (rst-shift-region-guts (lambda (tabs leftmostcol)
2345 (let ((cur tabs))
2346 (while (and cur (<= (caar cur) leftmostcol))
2347 (setq cur (cdr cur)))
2348 cur))
2349 'identity
2352 (defun rst-shift-region-left (pfxarg)
2353 "Like rst-shift-region-right, except we move to the left.
2354 Also, if invoked with a negative prefix arg, the entire
2355 indentation is removed, up to the leftmost character in the
2356 region, and automatic filling is disabled."
2357 (interactive "P")
2358 (let ((mbeg (set-marker (make-marker) (region-beginning)))
2359 (mend (set-marker (make-marker) (region-end)))
2360 (leftmostcol (rst-find-leftmost-column
2361 (region-beginning) (region-end)))
2362 (rst-shift-fill-region
2363 (if (not pfxarg) rst-shift-fill-region)))
2365 (when (> leftmostcol 0)
2366 (if (and pfxarg (< (prefix-numeric-value pfxarg) 0))
2367 (progn
2368 (indent-rigidly (region-beginning) (region-end) (- leftmostcol))
2369 (when rst-shift-fill-region
2370 (fill-region mbeg mend))
2372 (rst-shift-region-guts (lambda (tabs leftmostcol)
2373 (let ((cur (reverse tabs)))
2374 (while (and cur (>= (caar cur) leftmostcol))
2375 (setq cur (cdr cur)))
2376 cur))
2382 ;;------------------------------------------------------------------------------
2384 ;; FIXME: these next functions should become part of a larger effort to redo the
2385 ;; bullets in bulletted lists. The enumerate would just be one of the possible
2386 ;; outputs.
2388 ;; FIXME: TODO we need to do the enumeration removal as well.
2390 (defun rst-enumerate-region (beg end)
2391 "Add enumeration to all the leftmost paragraphs in the given region.
2392 The region is specified between BEG and END. With prefix argument,
2393 do all lines instead of just paragraphs."
2394 (interactive "r")
2395 (let ((count 0)
2396 (last-insert-len nil))
2397 (rst-iterate-leftmost-paragraphs
2398 beg end (not current-prefix-arg)
2399 (let ((ins-string (format "%d. " (incf count))))
2400 (setq last-insert-len (length ins-string))
2401 (insert ins-string))
2402 (insert (make-string last-insert-len ?\ ))
2405 (defun rst-bullet-list-region (beg end)
2406 "Add bullets to all the leftmost paragraphs in the given region.
2407 The region is specified between BEG and END. With prefix argument,
2408 do all lines instead of just paragraphs."
2409 (interactive "r")
2410 (rst-iterate-leftmost-paragraphs
2411 beg end (not current-prefix-arg)
2412 (insert "- ")
2413 (insert " ")
2416 (defmacro rst-iterate-leftmost-paragraphs
2417 (beg end first-only body-consequent body-alternative)
2418 "FIXME This definition is old and deprecated / we need to move
2419 to the newer version below:
2421 Call FUN at the beginning of each line, with an argument that
2422 specifies whether we are at the first line of a paragraph that
2423 starts at the leftmost column of the given region BEG and END.
2424 Set FIRST-ONLY to true if you want to callback on the first line
2425 of each paragraph only."
2426 `(save-excursion
2427 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2428 (endm (set-marker (make-marker) ,end))
2429 ,(when first-only '(in-par nil))
2432 (do* (;; Iterate lines
2433 (l (progn (goto-char ,beg) (back-to-indentation))
2434 (progn (forward-line 1) (back-to-indentation)))
2436 (previous nil valid)
2438 (curcol (current-column)
2439 (current-column))
2441 (valid (and (= curcol leftcol)
2442 (not (looking-at "[ \t]*$")))
2443 (and (= curcol leftcol)
2444 (not (looking-at "[ \t]*$"))))
2446 ((>= (point-marker) endm))
2448 (if (if ,first-only
2449 (and valid (not previous))
2450 valid)
2451 ,body-consequent
2452 ,body-alternative)
2454 ))))
2457 (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2458 "Evaluate BODY for each line in region defined by BEG END.
2459 LEFTMOST is set to true if the line is one of the leftmost of the
2460 entire paragraph. PARABEGIN is set to true if the line is the
2461 first of a paragraph."
2462 (destructuring-bind
2463 (beg end parabegin leftmost isleftmost isempty) spec
2465 `(save-excursion
2466 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2467 (endm (set-marker (make-marker) ,end))
2468 (in-par nil)
2471 (do* (;; Iterate lines
2472 (l (progn (goto-char ,beg) (back-to-indentation))
2473 (progn (forward-line 1) (back-to-indentation)))
2475 (empty-line-previous nil ,isempty)
2477 (,isempty (looking-at "[ \t]*$")
2478 (looking-at "[ \t]*$"))
2480 (,parabegin (not ,isempty)
2481 (and empty-line-previous
2482 (not ,isempty)))
2484 (,isleftmost (and (not ,isempty)
2485 (= (current-column) ,leftmost))
2486 (and (not ,isempty)
2487 (= (current-column) ,leftmost)))
2489 ((>= (point-marker) endm))
2491 (progn ,@body)
2493 )))))
2496 ;; FIXME: there are some problems left with the following function
2497 ;; implementation:
2499 ;; * It does not deal with a varying number of digits appropriately
2500 ;; * It does not deal with multiple levels independently, and it should.
2502 ;; I suppose it does 90% of the job for now.
2504 (defun rst-convert-bullets-to-enumeration (beg end)
2505 "Convert all the bulleted items and enumerated items in the
2506 region to enumerated lists, renumbering as necessary."
2507 (interactive "r")
2508 (let* (;; Find items and convert the positions to markers.
2509 (items (mapcar
2510 (lambda (x)
2511 (cons (let ((m (make-marker)))
2512 (set-marker m (car x))
2514 (cdr x)))
2515 (rst-find-pfx-in-region beg end rst-re-items)))
2516 (count 1)
2518 (save-excursion
2519 (dolist (x items)
2520 (goto-char (car x))
2521 (looking-at rst-re-items)
2522 (replace-match (format "%d. " count) nil nil nil 1)
2523 (incf count)
2529 ;;------------------------------------------------------------------------------
2531 (defun rst-line-block-region (rbeg rend &optional pfxarg)
2532 "Toggle line block prefixes for a region. With prefix argument
2533 set the empty lines too."
2534 (interactive "r\nP")
2535 (let ((comment-start "| ")
2536 (comment-end "")
2537 (comment-start-skip "| ")
2538 (comment-style 'indent)
2539 (force current-prefix-arg))
2540 (rst-iterate-leftmost-paragraphs-2
2541 (rbeg rend parbegin leftmost isleft isempty)
2542 (if force
2543 (progn
2544 (move-to-column leftmost t)
2545 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
2546 (insert "| "))
2547 (when (not isempty)
2548 (move-to-column leftmost)
2549 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
2550 (insert "| ")))
2555 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2557 (require 'font-lock)
2559 (defgroup rst-faces nil "Faces used in Rst Mode"
2560 :group 'rst
2561 :group 'faces
2562 :version "21.1")
2564 (defcustom rst-block-face 'font-lock-keyword-face
2565 "All syntax marking up a special block"
2566 :group 'rst-faces
2567 :type '(face))
2569 (defcustom rst-external-face 'font-lock-type-face
2570 "Field names and interpreted text"
2571 :group 'rst-faces
2572 :type '(face))
2574 (defcustom rst-definition-face 'font-lock-function-name-face
2575 "All other defining constructs"
2576 :group 'rst-faces
2577 :type '(face))
2579 (defcustom rst-directive-face
2580 ;; XEmacs compatibility
2581 (if (boundp 'font-lock-builtin-face)
2582 'font-lock-builtin-face
2583 'font-lock-preprocessor-face)
2584 "Directives and roles"
2585 :group 'rst-faces
2586 :type '(face))
2588 (defcustom rst-comment-face 'font-lock-comment-face
2589 "Comments"
2590 :group 'rst-faces
2591 :type '(face))
2593 (defcustom rst-emphasis1-face
2594 ;; XEmacs compatibility
2595 (if (facep 'italic)
2596 ''italic
2597 'italic)
2598 "Simple emphasis"
2599 :group 'rst-faces
2600 :type '(face))
2602 (defcustom rst-emphasis2-face
2603 ;; XEmacs compatibility
2604 (if (facep 'bold)
2605 ''bold
2606 'bold)
2607 "Double emphasis"
2608 :group 'rst-faces
2609 :type '(face))
2611 (defcustom rst-literal-face 'font-lock-string-face
2612 "Literal text"
2613 :group 'rst-faces
2614 :type '(face))
2616 (defcustom rst-reference-face 'font-lock-variable-name-face
2617 "References to a definition"
2618 :group 'rst-faces
2619 :type '(face))
2621 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2623 (defgroup rst-faces-defaults nil
2624 "Values used to generate default faces for section titles on all levels.
2625 Tweak these if you are content with how section title faces are built in
2626 general but you do not like the details."
2627 :group 'rst-faces
2628 :version "21.1")
2630 (defun rst-define-level-faces ()
2631 "Define the faces for the section title text faces from the values."
2632 ;; All variables used here must be checked in `rst-set-level-default'
2633 (let ((i 1))
2634 (while (<= i rst-level-face-max)
2635 (let ((sym (intern (format "rst-level-%d-face" i)))
2636 (doc (format "Face for showing section title text at level %d" i))
2637 (col (format (concat "%s" rst-level-face-format-light)
2638 rst-level-face-base-color
2639 (+ (* (1- i) rst-level-face-step-light)
2640 rst-level-face-base-light))))
2641 (make-empty-face sym)
2642 (set-face-doc-string sym doc)
2643 (set-face-background sym col)
2644 (set sym sym)
2645 (setq i (1+ i))))))
2647 (defun rst-set-level-default (sym val)
2648 "Set a customized value affecting section title text face and recompute the
2649 faces."
2650 (custom-set-default sym val)
2651 ;; Also defines the faces initially when all values are available
2652 (and (boundp 'rst-level-face-max)
2653 (boundp 'rst-level-face-format-light)
2654 (boundp 'rst-level-face-base-color)
2655 (boundp 'rst-level-face-step-light)
2656 (boundp 'rst-level-face-base-light)
2657 (rst-define-level-faces)))
2659 ;; Faces for displaying items on several levels; these definitions define
2660 ;; different shades of grey where the lightest one (i.e. least contrasting) is
2661 ;; used for level 1
2662 (defcustom rst-level-face-max 6
2663 "Maximum depth of levels for which section title faces are defined."
2664 :group 'rst-faces-defaults
2665 :type '(integer)
2666 :set 'rst-set-level-default)
2667 (defcustom rst-level-face-base-color "grey"
2668 "The base name of the color to be used for creating background colors in
2669 ection title faces for all levels."
2670 :group 'rst-faces-defaults
2671 :type '(string)
2672 :set 'rst-set-level-default)
2673 (defcustom rst-level-face-base-light
2674 (if (eq frame-background-mode 'dark)
2677 "The lightness factor for the base color. This value is used for level 1. The
2678 default depends on whether the value of `frame-background-mode' is `dark' or
2679 not."
2680 :group 'rst-faces-defaults
2681 :type '(integer)
2682 :set 'rst-set-level-default)
2683 (defcustom rst-level-face-format-light "%2d"
2684 "The format for the lightness factor appended to the base name of the color.
2685 This value is expanded by `format' with an integer."
2686 :group 'rst-faces-defaults
2687 :type '(string)
2688 :set 'rst-set-level-default)
2689 (defcustom rst-level-face-step-light
2690 (if (eq frame-background-mode 'dark)
2693 "The step width to use for the next color. The formula
2695 `rst-level-face-base-light'
2696 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
2698 must result in a color level which appended to `rst-level-face-base-color'
2699 using `rst-level-face-format-light' results in a valid color such as `grey50'.
2700 This color is used as background for section title text on level
2701 `rst-level-face-max'."
2702 :group 'rst-faces-defaults
2703 :type '(integer)
2704 :set 'rst-set-level-default)
2706 (defcustom rst-adornment-faces-alist
2707 (let ((alist '((t . font-lock-keyword-face)
2708 (nil . font-lock-keyword-face)))
2709 (i 1))
2710 (while (<= i rst-level-face-max)
2711 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
2712 (setq i (1+ i)))
2713 alist)
2714 "Provides faces for the various adornment types. Key is a number (for the
2715 section title text of that level), t (for transitions) or nil (for section
2716 title adornment). If you generally do not like how section title text faces are
2717 set up tweak here. If the general idea is ok for you but you do not like the
2718 details check the Rst Faces Defaults group."
2719 :group 'rst-faces
2720 :type '(alist
2721 :key-type
2722 (choice
2723 (integer
2724 :tag
2725 "Section level (may not be bigger than `rst-level-face-max')")
2726 (boolean :tag "transitions (on) / section title adornment (off)"))
2727 :value-type (face))
2728 :set-after '(rst-level-face-max))
2732 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2733 ;; Font lock
2735 (defvar rst-use-char-classes
2736 (string-match "[[:alpha:]]" "b")
2737 "Non-nil if we can use the character classes in our regexps.")
2739 (defvar rst-font-lock-keywords
2740 ;; The reST-links in the comments below all relate to sections in
2741 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
2742 (let* ( ;; This gets big - so let's define some abbreviations; the trailing
2743 ;; numbers in the names give the number of regex groups contained
2744 ;; horizontal white space
2745 (re-hws "[\t ]")
2746 ;; beginning of line with possible indentation
2747 (re-bol (concat "^" re-hws "*"))
2748 ;; Separates block lead-ins from their content
2749 (re-blksep1 (concat "\\(" re-hws "+\\|$\\)"))
2750 ;; explicit markup tag
2751 (re-emt "\\.\\.")
2752 ;; explicit markup start
2753 (re-ems (concat re-emt re-hws "+"))
2754 ;; inline markup prefix
2755 (re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{</:]\\)"))
2756 ;; inline markup suffix
2757 (re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
2758 ;; symbol character
2759 (re-sym1 "\\(\\sw\\|\\s_\\)")
2760 ;; inline markup content begin
2761 (re-imbeg2 "\\(\\S \\|\\S \\([^")
2763 ;; There seems to be a bug leading to error "Stack overflow in regexp
2764 ;; matcher" when "|" or "\\*" are the characters searched for
2765 (re-imendbeg
2766 (if (< emacs-major-version 21)
2768 "\\]\\|\\\\."))
2769 ;; inline markup content end
2770 (re-imend (concat re-imendbeg "\\)*[^\t \\\\]\\)"))
2771 ;; inline markup content without asterisk
2772 (re-ima2 (concat re-imbeg2 "*" re-imend))
2773 ;; inline markup content without backquote
2774 (re-imb2 (concat re-imbeg2 "`" re-imend))
2775 ;; inline markup content without vertical bar
2776 (re-imv2 (concat re-imbeg2 "|" re-imend))
2777 ;; Supported URI schemes
2778 (re-uris1 "\\(acap\\|cid\\|data\\|dav\\|fax\\|file\\|ftp\\|gopher\\|http\\|https\\|imap\\|ldap\\|mailto\\|mid\\|modem\\|news\\|nfs\\|nntp\\|pop\\|prospero\\|rtsp\\|service\\|sip\\|tel\\|telnet\\|tip\\|urn\\|vemmi\\|wais\\)")
2779 ;; Line starting with adornment and optional whitespace; complete
2780 ;; adornment is in (match-string 1); there must be at least 3
2781 ;; characters because otherwise explicit markup start would be
2782 ;; recognized
2783 (re-ado2 (concat "^\\(\\(["
2784 (if rst-use-char-classes
2785 "^[:word:][:space:][:cntrl:]"
2786 "^\\w \t\x00-\x1F")
2787 "]\\)\\2\\2+\\)" re-hws "*$"))
2789 (list
2790 ;; FIXME: Block markup is not recognized in blocks after explicit markup
2791 ;; start
2793 ;; Simple `Body Elements`_
2794 ;; `Bullet Lists`_
2795 (list
2796 (concat re-bol "\\([-*+]" re-blksep1 "\\)")
2797 1 rst-block-face)
2798 ;; `Enumerated Lists`_
2799 (list
2800 (concat re-bol "\\((?\\(#\\|[0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
2801 re-blksep1 "\\)")
2802 1 rst-block-face)
2803 ;; `Definition Lists`_ FIXME: missing
2804 ;; `Field Lists`_
2805 (list
2806 (concat re-bol "\\(:[^:\n]+:\\)" re-blksep1)
2807 1 rst-external-face)
2808 ;; `Option Lists`_
2809 (list
2810 (concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
2811 "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
2812 1 rst-block-face)
2814 ;; `Tables`_ FIXME: missing
2816 ;; All the `Explicit Markup Blocks`_
2817 ;; `Footnotes`_ / `Citations`_
2818 (list
2819 (concat re-bol "\\(" re-ems "\\[[^[\n]+\\]\\)" re-blksep1)
2820 1 rst-definition-face)
2821 ;; `Directives`_ / `Substitution Definitions`_
2822 (list
2823 (concat re-bol "\\(" re-ems "\\)\\(\\(|[^|\n]+|[\t ]+\\)?\\)\\("
2824 re-sym1 "+::\\)" re-blksep1)
2825 (list 1 rst-directive-face)
2826 (list 2 rst-definition-face)
2827 (list 4 rst-directive-face))
2828 ;; `Hyperlink Targets`_
2829 (list
2830 (concat re-bol "\\(" re-ems "_\\([^:\\`\n]\\|\\\\.\\|`[^`\n]+`\\)+:\\)"
2831 re-blksep1)
2832 1 rst-definition-face)
2833 (list
2834 (concat re-bol "\\(__\\)" re-blksep1)
2835 1 rst-definition-face)
2837 ;; All `Inline Markup`_
2838 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
2839 ;; `Strong Emphasis`_
2840 (list
2841 (concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
2842 2 rst-emphasis2-face)
2843 ;; `Emphasis`_
2844 (list
2845 (concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
2846 2 rst-emphasis1-face)
2847 ;; `Inline Literals`_
2848 (list
2849 (concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
2850 2 rst-literal-face)
2851 ;; `Inline Internal Targets`_
2852 (list
2853 (concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
2854 2 rst-definition-face)
2855 ;; `Hyperlink References`_
2856 ;; FIXME: `Embedded URIs`_ not considered
2857 (list
2858 (concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\(\\sw\\(\\sw\\|-\\)+\\sw\\)\\)__?\\)" re-ims1)
2859 2 rst-reference-face)
2860 ;; `Interpreted Text`_
2861 (list
2862 (concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:"
2863 re-sym1 "+:\\)?\\)" re-ims1)
2864 (list 2 rst-directive-face)
2865 (list 5 rst-external-face)
2866 (list 8 rst-directive-face))
2867 ;; `Footnote References`_ / `Citation References`_
2868 (list
2869 (concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
2870 2 rst-reference-face)
2871 ;; `Substitution References`_
2872 (list
2873 (concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
2874 2 rst-reference-face)
2875 ;; `Standalone Hyperlinks`_
2876 (list
2877 ;; FIXME: This takes it easy by using a whitespace as delimiter
2878 (concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1)
2879 2 rst-definition-face)
2880 (list
2881 (concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
2882 2 rst-definition-face)
2884 ;; Do all block fontification as late as possible so 'append works
2886 ;; Sections_ / Transitions_
2887 (list
2888 re-ado2
2889 (list 'rst-font-lock-handle-adornment-match
2890 '(rst-font-lock-handle-adornment-limit
2891 (match-string-no-properties 1) (match-end 1))
2893 (list 1 '(cdr (assoc nil rst-adornment-faces-alist))
2894 'append t)
2895 (list 2 '(cdr (assoc rst-font-lock-adornment-level
2896 rst-adornment-faces-alist))
2897 'append t)
2898 (list 3 '(cdr (assoc nil rst-adornment-faces-alist))
2899 'append t)))
2901 ;; `Comments`_
2902 (list
2903 (concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:\n]\\|:\\([^:\n]\\|$\\)\\)*$")
2904 (list 1 rst-comment-face)
2905 (list 'rst-font-lock-find-unindented-line-match
2906 '(rst-font-lock-find-unindented-line-limit (match-end 1))
2908 (list 0 rst-comment-face 'append)))
2909 (list
2910 (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)$")
2911 (list 1 rst-comment-face)
2912 (list 2 rst-comment-face)
2913 (list 'rst-font-lock-find-unindented-line-match
2914 '(rst-font-lock-find-unindented-line-limit 'next)
2916 (list 0 rst-comment-face 'append)))
2918 ;; `Literal Blocks`_
2919 (list
2920 (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
2921 (list 3 rst-block-face)
2922 (list 'rst-font-lock-find-unindented-line-match
2923 '(rst-font-lock-find-unindented-line-limit t)
2925 (list 0 rst-literal-face 'append)))
2927 ;; `Doctest Blocks`_
2928 (list
2929 (concat re-bol "\\(>>>\\|\\.\\.\\.\\)\\(.+\\)")
2930 (list 1 rst-block-face)
2931 (list 2 rst-literal-face))
2933 "Returns keywords to highlight in rst mode according to current settings.")
2935 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2936 ;; Indented blocks
2938 (defun rst-forward-indented-block (&optional column limit)
2939 "Move forward across one indented block.
2940 Find the next non-empty line which is not indented at least to COLUMN (defaults
2941 to the column of the point). Moves point to first character of this line or the
2942 first empty line immediately before it and returns that position. If there is
2943 no such line before LIMIT (defaults to the end of the buffer) returns nil and
2944 point is not moved."
2945 (interactive)
2946 (let ((clm (or column (current-column)))
2947 (start (point))
2948 fnd beg cand)
2949 (if (not limit)
2950 (setq limit (point-max)))
2951 (save-match-data
2952 (while (and (not fnd) (< (point) limit))
2953 (forward-line 1)
2954 (when (< (point) limit)
2955 (setq beg (point))
2956 (if (looking-at "\\s *$")
2957 (setq cand (or cand beg)) ; An empty line is a candidate
2958 (move-to-column clm)
2959 ;; FIXME: No indentation [(zerop clm)] must be handled in some
2960 ;; useful way - though it is not clear what this should mean at all
2961 (if (string-match
2962 "^\\s *$" (buffer-substring-no-properties beg (point)))
2963 (setq cand nil) ; An indented line resets a candidate
2964 (setq fnd (or cand beg)))))))
2965 (goto-char (or fnd start))
2966 fnd))
2968 ;; Beginning of the match if `rst-font-lock-find-unindented-line-end'.
2969 (defvar rst-font-lock-find-unindented-line-begin nil)
2971 ;; End of the match as determined by
2972 ;; `rst-font-lock-find-unindented-line-limit'. Also used as a trigger for
2973 ;; `rst-font-lock-find-unindented-line-match'.
2974 (defvar rst-font-lock-find-unindented-line-end nil)
2976 ;; Finds the next unindented line relative to indenation at IND-PNT and returns
2977 ;; this point, the end of the buffer or nil if nothing found. If IND-PNT is
2978 ;; `next' takes the indentation from the next line if this is not empty. If
2979 ;; IND-PNT is non-nil but not a number takes the indentation from the next
2980 ;; non-empty line.
2981 (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
2982 (setq rst-font-lock-find-unindented-line-begin ind-pnt)
2983 (setq rst-font-lock-find-unindented-line-end
2984 (save-excursion
2985 (when (not (numberp ind-pnt))
2986 ;; Find indentation point in next line if any
2987 (setq ind-pnt
2988 ;; FIXME: Should be refactored to two different functions
2989 ;; giving their result to this function, may be
2990 ;; integrated in caller
2991 (save-match-data
2992 (if (eq ind-pnt 'next)
2993 (when (and (zerop (forward-line 1))
2994 (< (point) (point-max)))
2995 ;; Not at EOF
2996 (setq rst-font-lock-find-unindented-line-begin (point))
2997 (when (not (looking-at "\\s *$"))
2998 ;; Use end of indentation if non-empty line
2999 (looking-at "\\s *")
3000 (match-end 0)))
3001 ;; Skip until non-empty line or EOF
3002 (while (and (zerop (forward-line 1))
3003 (< (point) (point-max))
3004 (looking-at "\\s *$")))
3005 (when (< (point) (point-max))
3006 ;; Not at EOF
3007 (setq rst-font-lock-find-unindented-line-begin (point))
3008 (looking-at "\\s *")
3009 (match-end 0))))))
3010 (when ind-pnt
3011 (goto-char ind-pnt)
3012 (or (rst-forward-indented-block nil (point-max))
3013 (point-max))))))
3015 ;; Sets the match found by `rst-font-lock-find-unindented-line-limit' the first
3016 ;; time called or nil.
3017 (defun rst-font-lock-find-unindented-line-match (limit)
3018 (when rst-font-lock-find-unindented-line-end
3019 (set-match-data
3020 (list rst-font-lock-find-unindented-line-begin
3021 rst-font-lock-find-unindented-line-end))
3022 ;; Make sure this is called only once
3023 (setq rst-font-lock-find-unindented-line-end nil)
3026 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3027 ;; Adornments
3029 ;; Here `rst-font-lock-handle-adornment-match' stores the section level of the
3030 ;; current adornment or t for a transition.
3031 (defvar rst-font-lock-adornment-level nil)
3033 ;; FIXME: It would be good if this could be used to markup section titles of
3034 ;; given level with a special key; it would be even better to be able to
3035 ;; customize this so it can be used for a generally available personal style
3037 ;; FIXME: There should be some way to reset and reload this variable - probably
3038 ;; a special key
3040 ;; FIXME: Some support for `outline-mode' would be nice which should be based
3041 ;; on this information
3042 (defvar rst-adornment-level-alist nil
3043 "Associates adornments with section levels.
3044 The key is a two character string. The first character is the adornment
3045 character. The second character distinguishes underline section titles (`u')
3046 from overline/underline section titles (`o'). The value is the section level.
3048 This is made buffer local on start and adornments found during font lock are
3049 entered.")
3051 ;; Returns section level for adornment key KEY. Adds new section level if KEY
3052 ;; is not found and ADD. If KEY is not a string it is simply returned.
3053 (defun rst-adornment-level (key &optional add)
3054 (let ((fnd (assoc key rst-adornment-level-alist))
3055 (new 1))
3056 (cond
3057 ((not (stringp key))
3058 key)
3059 (fnd
3060 (cdr fnd))
3061 (add
3062 (while (rassoc new rst-adornment-level-alist)
3063 (setq new (1+ new)))
3064 (setq rst-adornment-level-alist
3065 (append rst-adornment-level-alist (list (cons key new))))
3066 new))))
3068 ;; Classifies adornment for section titles and transitions. ADORNMENT is the
3069 ;; complete adornment string as found in the buffer. END is the point after the
3070 ;; last character of ADORNMENT. For overline section adornment LIMIT limits the
3071 ;; search for the matching underline. Returns a list. The first entry is t for
3072 ;; a transition, or a key string for `rst-adornment-level' for a section title.
3073 ;; The following eight values forming four match groups as can be used for
3074 ;; `set-match-data'. First match group contains the maximum points of the whole
3075 ;; construct. Second and last match group matched pure section title adornment
3076 ;; while third match group matched the section title text or the transition.
3077 ;; Each group but the first may or may not exist.
3078 (defun rst-classify-adornment (adornment end limit)
3079 (save-excursion
3080 (save-match-data
3081 (goto-char end)
3082 (let ((ado-ch (aref adornment 0))
3083 (ado-re (regexp-quote adornment))
3084 (end-pnt (point))
3085 (beg-pnt (progn
3086 (forward-line 0)
3087 (point)))
3088 (nxt-emp
3089 (save-excursion
3090 (or (not (zerop (forward-line 1)))
3091 (looking-at "\\s *$"))))
3092 (prv-emp
3093 (save-excursion
3094 (or (not (zerop (forward-line -1)))
3095 (looking-at "\\s *$"))))
3096 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
3097 (cond
3098 ((and nxt-emp prv-emp)
3099 ;; A transition
3100 (setq key t)
3101 (setq beg-txt beg-pnt)
3102 (setq end-txt end-pnt))
3103 (prv-emp
3104 ;; An overline
3105 (setq key (concat (list ado-ch) "o"))
3106 (setq beg-ovr beg-pnt)
3107 (setq end-ovr end-pnt)
3108 (forward-line 1)
3109 (setq beg-txt (point))
3110 (while (and (<= (point) limit) (not end-txt))
3111 (if (or (= (point) limit) (looking-at "\\s *$"))
3112 ;; No underline found
3113 (setq end-txt (1- (point)))
3114 (when (looking-at (concat "\\(" ado-re "\\)\\s *$"))
3115 (setq end-und (match-end 1))
3116 (setq beg-und (point))
3117 (setq end-txt (1- beg-und))))
3118 (forward-line 1)))
3120 ;; An underline
3121 (setq key (concat (list ado-ch) "u"))
3122 (setq beg-und beg-pnt)
3123 (setq end-und end-pnt)
3124 (setq end-txt (1- beg-und))
3125 (setq beg-txt (progn
3126 (goto-char end-txt)
3127 (forward-line 0)
3128 (point)))
3129 (when (and (zerop (forward-line -1))
3130 (looking-at (concat "\\(" ado-re "\\)\\s *$")))
3131 ;; There is a matching overline
3132 (setq key (concat (list ado-ch) "o"))
3133 (setq beg-ovr (point))
3134 (setq end-ovr (match-end 1)))))
3135 (list key
3136 (or beg-ovr beg-txt beg-und)
3137 (or end-und end-txt end-und)
3138 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
3140 ;; Stores the result of `rst-classify-adornment'. Also used as a trigger
3141 ;; for `rst-font-lock-handle-adornment-match'.
3142 (defvar rst-font-lock-adornment-data nil)
3144 ;; Determines limit for adornments for font-locking section titles and
3145 ;; transitions. In fact it determines all things necessary and puts the result
3146 ;; to `rst-font-lock-adornment-data'. ADO is the complete adornment matched.
3147 ;; ADO-END is the point where ADO ends. Returns the point where the whole
3148 ;; adorned construct ends.
3149 (defun rst-font-lock-handle-adornment-limit (ado ado-end)
3150 (let ((ado-data (rst-classify-adornment ado ado-end (point-max))))
3151 (setq rst-font-lock-adornment-level (rst-adornment-level (car ado-data) t))
3152 (setq rst-font-lock-adornment-data (cdr ado-data))
3153 (goto-char (nth 1 ado-data))
3154 (nth 2 ado-data)))
3156 ;; Sets the match found by `rst-font-lock-handle-adornment-limit' the first
3157 ;; time called or nil.
3158 (defun rst-font-lock-handle-adornment-match (limit)
3159 (let ((ado-data rst-font-lock-adornment-data))
3160 ;; May run only once - enforce this
3161 (setq rst-font-lock-adornment-data nil)
3162 (when ado-data
3163 (goto-char (nth 1 ado-data))
3164 (set-match-data ado-data)
3165 t)))
3168 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3169 ;; Support for conversion from within Emacs
3171 (defgroup rst-compile nil
3172 "Settings for support of conversion of reStructuredText
3173 document with \\[rst-compile]."
3174 :group 'rst
3175 :version "21.1")
3177 (defvar rst-compile-toolsets
3178 '((html . ("rst2html.py" ".html" nil))
3179 (latex . ("rst2latex.py" ".tex" nil))
3180 (newlatex . ("rst2newlatex.py" ".tex" nil))
3181 (pseudoxml . ("rst2pseudoxml.py" ".xml" nil))
3182 (xml . ("rst2xml.py" ".xml" nil)))
3183 "An association list of the toolset to a list of the (command to use,
3184 extension of produced filename, options to the tool (nil or a
3185 string)) to be used for converting the document.")
3187 ;; Note for Python programmers not familiar with association lists: you can set
3188 ;; values in an alists like this, e.g. :
3189 ;; (setcdr (assq 'html rst-compile-toolsets)
3190 ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
3193 (defvar rst-compile-primary-toolset 'html
3194 "The default toolset for rst-compile.")
3196 (defvar rst-compile-secondary-toolset 'latex
3197 "The default toolset for rst-compile with a prefix argument.")
3199 (defun rst-compile-find-conf ()
3200 "Look for the configuration file in the parents of the current path."
3201 (interactive)
3202 (let ((file-name "docutils.conf")
3203 (buffer-file (buffer-file-name)))
3204 ;; Move up in the dir hierarchy till we find a change log file.
3205 (let* ((dir (file-name-directory buffer-file))
3206 (prevdir nil))
3207 (while (and (or (not (string= dir prevdir))
3208 (setq dir nil)
3209 nil)
3210 (not (file-exists-p (concat dir file-name))))
3211 ;; Move up to the parent dir and try again.
3212 (setq prevdir dir)
3213 (setq dir (expand-file-name (file-name-directory
3214 (directory-file-name
3215 (file-name-directory dir)))))
3217 (or (and dir (concat dir file-name)) nil)
3221 (require 'compile)
3223 (defun rst-compile (&optional pfxarg)
3224 "Compile command to convert reST document into some output file.
3225 Attempts to find configuration file, if it can, overrides the
3226 options. There are two commands to choose from, with a prefix
3227 argument, select the alternative toolset."
3228 (interactive "P")
3229 ;; Note: maybe we want to check if there is a Makefile too and not do anything
3230 ;; if that is the case. I dunno.
3231 (let* ((toolset (cdr (assq (if pfxarg
3232 rst-compile-secondary-toolset
3233 rst-compile-primary-toolset)
3234 rst-compile-toolsets)))
3235 (command (car toolset))
3236 (extension (cadr toolset))
3237 (options (caddr toolset))
3238 (conffile (rst-compile-find-conf))
3239 (bufname (file-name-nondirectory buffer-file-name))
3240 (outname (file-name-sans-extension bufname)))
3242 ;; Set compile-command before invocation of compile.
3243 (set (make-local-variable 'compile-command)
3244 (mapconcat 'identity
3245 (list command
3246 (or options "")
3247 (if conffile
3248 (concat "--config=\"" conffile "\"")
3250 bufname
3251 (concat outname extension))
3252 " "))
3254 ;; Invoke the compile command.
3255 (if (or compilation-read-command current-prefix-arg)
3256 (call-interactively 'compile)
3257 (compile compile-command))
3260 (defun rst-compile-alt-toolset ()
3261 "Compile command with the alternative toolset."
3262 (interactive)
3263 (rst-compile 't))
3265 (defun rst-compile-pseudo-region ()
3266 "Show the pseudo-XML rendering of the current active region, or
3267 of the entire buffer, if the region is not selected."
3268 (interactive)
3269 (with-output-to-temp-buffer "*pseudoxml*"
3270 (shell-command-on-region
3271 (if mark-active (region-beginning) (point-min))
3272 (if mark-active (region-end) (point-max))
3273 "rst2pseudoxml.py"
3274 standard-output)))
3276 (defvar rst-pdf-program "xpdf"
3277 "Program used to preview PDF files.")
3279 (defun rst-compile-pdf-preview ()
3280 "Convert the document to a PDF file and launch a preview program."
3281 (interactive)
3282 (let* ((tmp-filename "/tmp/out.pdf")
3283 (command (format "rst2pdf.py %s %s && %s %s"
3284 buffer-file-name tmp-filename
3285 rst-pdf-program tmp-filename)))
3286 (start-process-shell-command "rst-pdf-preview" nil command)
3287 ;; Note: you could also use (compile command) to view the compilation
3288 ;; output.
3291 (defvar rst-slides-program "firefox"
3292 "Program used to preview S5 slides.")
3294 (defun rst-compile-slides-preview ()
3295 "Convert the document to an S5 slide presentation and launch a preview program."
3296 (interactive)
3297 (let* ((tmp-filename "/tmp/slides.html")
3298 (command (format "rst2s5.py %s %s && %s %s"
3299 buffer-file-name tmp-filename
3300 rst-slides-program tmp-filename)))
3301 (start-process-shell-command "rst-slides-preview" nil command)
3302 ;; Note: you could also use (compile command) to view the compilation
3303 ;; output.
3308 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3310 ;; Generic text functions that are more convenient than the defaults.
3313 (defun rst-replace-lines (fromchar tochar)
3314 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
3315 with equal-length lines of TOCHAR."
3316 (interactive "\
3317 cSearch for flush-left lines of char:
3318 cand replace with char: ")
3319 (save-excursion
3320 (let* ((fromstr (string fromchar))
3321 (searchre (concat "^" (regexp-quote fromstr) "+ *$"))
3322 (found 0))
3323 (condition-case err
3324 (while t
3325 (search-forward-regexp searchre)
3326 (setq found (1+ found))
3327 (search-backward fromstr) ;; point will be *before* last char
3328 (setq p (1+ (point)))
3329 (beginning-of-line)
3330 (setq l (- p (point)))
3331 (rst-delete-entire-line)
3332 (insert-char tochar l))
3333 (search-failed
3334 (message (format "%d lines replaced." found)))))))
3336 (defun rst-join-paragraph ()
3337 "Join lines in current paragraph into one line, removing end-of-lines."
3338 (interactive)
3339 (let ((fill-column 65000)) ; some big number
3340 (call-interactively 'fill-paragraph)))
3342 (defun rst-force-fill-paragraph ()
3343 "Fill paragraph at point, first joining the paragraph's lines into one.
3344 This is useful for filling list item paragraphs."
3345 (interactive)
3346 (rst-join-paragraph)
3347 (fill-paragraph nil))
3350 ;; Generic character repeater function.
3351 ;; For sections, better to use the specialized function above, but this can
3352 ;; be useful for creating separators.
3353 (defun rst-repeat-last-character (&optional tofill)
3354 "Fills the current line up to the length of the preceding line (if not
3355 empty), using the last character on the current line. If the preceding line is
3356 empty, we use the fill-column.
3358 If a prefix argument is provided, use the next line rather than the preceding
3359 line.
3361 If the current line is longer than the desired length, shave the characters off
3362 the current line to fit the desired length.
3364 As an added convenience, if the command is repeated immediately, the alternative
3365 column is used (fill-column vs. end of previous/next line)."
3366 (interactive)
3367 (let* ((curcol (current-column))
3368 (curline (+ (count-lines (point-min) (point))
3369 (if (eq curcol 0) 1 0)))
3370 (lbp (line-beginning-position 0))
3371 (prevcol (if (and (= curline 1) (not current-prefix-arg))
3372 fill-column
3373 (save-excursion
3374 (forward-line (if current-prefix-arg 1 -1))
3375 (end-of-line)
3376 (skip-chars-backward " \t" lbp)
3377 (let ((cc (current-column)))
3378 (if (= cc 0) fill-column cc)))))
3379 (rightmost-column
3380 (cond (tofill fill-column)
3381 ((equal last-command 'rst-repeat-last-character)
3382 (if (= curcol fill-column) prevcol fill-column))
3383 (t (save-excursion
3384 (if (= prevcol 0) fill-column prevcol)))
3385 )) )
3386 (end-of-line)
3387 (if (> (current-column) rightmost-column)
3388 ;; shave characters off the end
3389 (delete-region (- (point)
3390 (- (current-column) rightmost-column))
3391 (point))
3392 ;; fill with last characters
3393 (insert-char (preceding-char)
3394 (- rightmost-column (current-column))))
3398 (defun rst-portable-mark-active-p ()
3399 "A portable function that returns non-nil if the mark is active."
3400 (cond
3401 ((fboundp 'region-active-p) (region-active-p))
3402 ((boundp 'transient-mark-mode) transient-mark-mode mark-active)))
3406 (provide 'rst)
3407 ;;; rst.el ends here