1 ;;; ================================================
2 ;;; rst.el -- ReStructuredText Support for Emacs
3 ;;; ================================================
5 ;;; :Authors: Martin Blais <blais@furius.ca>,
6 ;;; Stefan Merten <smerten@oekonux.de>,
7 ;;; David Goodger <goodger@python.org>
8 ;;; :Revision: $Revision$
10 ;;; :Copyright: 2003-2006 by Martin Blais, Stefan Merten, and David Goodger.
12 ;;; This program is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License version 2,
14 ;;; as published by the Free Software Foundation.
16 ;;; This program is distributed in the hope that it will be useful,
17 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;;; GNU General Public License for more details.
21 ;;; You should have received a copy of the GNU General Public License
22 ;;; version 2 along with this program (../../../licenses/gpl.txt) and
23 ;;; available at http://docutils.sf.net/licenses/gpl.txt
24 ;;; and at http://www.gnu.org/licenses/gpl.txt.
27 ;;; Support code for editing reStructuredText with Emacs. The latest
28 ;;; version of this file lies in the docutils source code repository.
33 ;;; Basically, this package contains:
35 ;;; - Functions to automatically adjust and cycle the section underline
37 ;;; - A mode that displays the table of contents and allows you to jump anywhere
39 ;;; - Functions to insert and automatically update a TOC in your source
41 ;;; - A mode which supports font-lock highlighting of reStructuredText
43 ;;; - Some other convenience functions.
45 ;;; See the accompanying document in the docutils documentation about
46 ;;; the contents of this package and how to use it.
48 ;;; For more information about reStructuredText, see
49 ;;; http://docutils.sourceforge.net/rst.html
51 ;;; For full details on how to use the contents of this file, see
52 ;;; http://docutils.sourceforge.net/docs/user/emacs.html
57 ;;; Click `Here <rst.el>`_ for download.
61 ;; **IMPORTANT NOTE TO PACKAGERS**: this package is the result of merging:
63 ;; - restructuredtext.el
67 ;; Those files are now OBSOLETE and have been replaced by this single package
70 ;; Installation instructions
71 ;; -------------------------
73 ;; Add this line to your .emacs file and bind the versatile sectioning commands
74 ;; in text mode, like this::
77 ;; (add-hook 'text-mode-hook 'rst-text-mode-bindings)
79 ;; rst-prefix-map is the prefix map for all the functionality provide by this
80 ;; module. In addition, other shorter bindings are also provided on the
81 ;; mode-specific-map prefix (i.e C-c).
84 ;; C-c p a (also C-=): rst-adjust
86 ;; Updates or rotates the section title around point or promotes/demotes
87 ;; the decorations within the region (see full details below).
89 ;; Note that C-= is a good binding, since it allows you to specify a
90 ;; negative arg easily with C-- C-= (easy to type), as well as ordinary
91 ;; prefix arg with C-u C-=.
93 ;; C-c p h: rst-display-decorations-hierarchy
95 ;; Displays the level decorations that are available in the file.
99 ;; Displays the hierarchical table-of-contents of the document and allows
100 ;; you to jump to any section from it.
102 ;; C-c p i: rst-toc-insert
104 ;; Inserts a table-of-contents in the document at the column where the
107 ;; C-c p u: rst-toc-insert-update
109 ;; Find an existing inserted table-of-contents in the document an
112 ;; C-c p p, C-c p n (C-c C-p, C-c C-n): rst-backward-section,
113 ;; rst-forward-section
115 ;; Navigate between section titles.
117 ;; C-c p l, C-c p r (C-c C-l, C-c C-r): rst-shift-region-left,
118 ;; rst-shift-region-right
120 ;; Shift the region left or right by two-char increments, which is perfect
121 ;; for bulleted lists.
124 ;; Other specialized and more generic functions are also available (see source
125 ;; code). The most important function provided by this file for section title
126 ;; adjustments is rst-adjust.
128 ;; There are many variables that can be customized, look for defcustom and
129 ;; defvar in this file.
131 ;; If you use the table-of-contents feature, you may want to add a hook to
132 ;; update the TOC automatically everytime you adjust a section title::
134 ;; (add-hook 'rst-adjust-hook 'rst-toc-insert-update)
139 ;; There is a special mode that you can setup if you want to have syntax
140 ;; highlighting. The mode is based on `text-mode' and inherits some things from
141 ;; it. Particularly `text-mode-hook' is run before `rst-mode-hook'.
143 ;; Add the following lines to your `.emacs' file:
145 ;; (setq auto-mode-alist
146 ;; (append '(("\\.rst$" . rst-mode)
147 ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
149 ;; If you are using `.txt' as a standard extension for reST files as
150 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
151 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
152 ;; provides to set the major mode automatically. For instance you may use
154 ;; .. -*- mode: rst -*-
156 ;; in the very first line of your file. However, because this is a major
157 ;; security breach you or your administrator may have chosen to switch that
158 ;; feature off. See `Local Variables in Files' in the Emacs documentation for a
159 ;; more complete discussion.
167 ;; - We need to automatically add the rst-text-mode-bindings to rst-mode
168 ;; - We need to find better bindings because C-= does not generate an event on
171 ;; rst-toc-insert features
172 ;; ------------------------
173 ;; - rst-toc-insert: We should parse the contents:: options to figure out how
174 ;; deep to render the inserted TOC.
175 ;; - On load, detect any existing TOCs and set the properties for links.
176 ;; - TOC insertion should have an option to add empty lines.
177 ;; - TOC insertion should deal with multiple lines
179 ;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
180 ;; automatic toc update. The cursor ends up in the TOC and this is
181 ;; annoying. Gotta fix that.
185 ;; - Look at the possibility of converting rst-mode from a Major mode to a Minor
186 ;; mode of text-mode.
190 ;; - We should rename "adornment" to "decoration" or vice-versa in this
192 ;; - Add an option to forego using the file structure in order to make
193 ;; suggestion, and to always use the preferred decorations to do that.
194 ;; - The shifting functions should look at what is before the region, to try to
195 ;; automatically guess whether we need to shift by 2 or 3 or 4 characters
196 ;; - Finish enumeration removal code
200 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
201 ;; Bindings and hooks
203 (defgroup rst nil
"Support for reStructuredText documents"
206 :link
'(url-link "http://docutils.sourceforge.net/rst.html"))
208 (defun rst-toc-or-hierarchy ()
209 "Binding for either TOC or decorations hierarchy."
211 (if (not current-prefix-arg
)
213 (rst-display-decorations-hierarchy)))
215 ;; Define a prefix map for the long form of key combinations.
216 (defvar rst-prefix-map
(make-sparse-keymap)
217 "Keymap for rst commands.")
219 (dolist (m `(("a" . rst-adjust
)
222 ("h" . rst-display-decorations-hierarchy
)
223 ("s" . rst-straighten-decorations
)
224 ("i" . rst-toc-insert
)
225 ("+" . rst-toc-insert
)
226 ("p" . rst-backward-section
)
227 ("n" . rst-forward-section
)
228 ("r" . rst-shift-region-right
)
229 ("l" . rst-shift-region-left
)
230 ("e" . rst-enumerate-region
)
231 ("u" . rst-toc-insert-update
)
233 ("C" .
,(lambda () (interactive) (rst-compile t
)))))
234 (define-key rst-prefix-map
(car m
) (cdr m
)))
238 (defun rst-text-mode-bindings ()
239 "Default text mode hook for rest."
241 ;; Direct command (somehow this one does not work on the Mac).
242 (local-set-key [(control ?
=)] 'rst-adjust
)
244 (define-key mode-specific-map
[(control p
)] 'rst-backward-section
)
245 (define-key mode-specific-map
[(control n
)] 'rst-forward-section
)
246 (define-key mode-specific-map
[(control r
)] 'rst-shift-region-right
)
247 (define-key mode-specific-map
[(control l
)] 'rst-shift-region-left
)
249 ;; Bind the rst commands on the C-c p prefix.
250 (define-key mode-specific-map
[(p)] rst-prefix-map
)
254 ;; Note: we cannot bind the TOC update on file write because it messes with
255 ;; undo. If we disable undo, since it adds and removes characters, the
256 ;; positions in the undo list are not making sense anymore. Dunno what to do
257 ;; with this, it would be nice to update when saving.
259 ;; (add-hook 'write-contents-hooks 'rst-toc-insert-update-fun)
260 ;; (defun rst-toc-insert-update-fun ()
261 ;; ;; Disable undo for the write file hook.
262 ;; (let ((buffer-undo-list t)) (rst-toc-insert-update) ))
265 ;; Additional abbreviations for text-mode.
266 (define-abbrev text-mode-abbrev-table
267 "con" ".. contents::\n..\n " nil
0)
270 ;; Paragraph separation customization. This will work better for
271 ;; bullet and enumerated lists in restructuredtext documents and
272 ;; should not affect filling for other documents too much. Set it up
275 ;; (add-hook 'text-mode-hook 'rst-set-paragraph-separation)
276 (defvar rst-extra-paragraph-start
277 "\\|[ \t]*\\([-+*] \\|[0-9]+\\. \\)"
278 "Extra parapraph-separate patterns to add for text-mode.")
279 ;; FIXME: What about the missing >?
280 ;; The author uses a hardcoded for paragraph-separate: "\f\\|>*[ \t]*$"
282 (defun rst-set-paragraph-separation ()
283 "Sets the paragraph separation for restructuredtext."
284 ;; FIXME: the variable should be made automatically buffer local rather than
285 ;; using a function here, this function is unnecessary.
286 (make-local-variable 'paragraph-start
) ; prevent it growing every time
287 (setq paragraph-start
(concat paragraph-start rst-extra-paragraph-start
)))
289 ;; FIXME: What about paragraph-separate? paragraph-start and paragraph-separate
290 ;; are different. The author hardcodes the value to
291 ;; "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. "
293 ;; FIXME: the variables above are in limbo and need some fixing.
297 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
302 ;; Generic Filter function.
303 (unless (fboundp 'filter
)
304 (defun filter (pred list
)
305 "Returns a list of all the elements fulfilling the pred requirement (that
306 is for which (pred elem) is true)"
308 (let ((head (car list
))
309 (tail (filter pred
(cdr list
))))
310 (if (funcall pred head
)
316 (unless (fboundp 'line-number-at-pos
)
317 (defun line-number-at-pos (&optional pos
)
318 "Return (narrowed) buffer line number at position POS.
319 If POS is nil, use current buffer location."
320 (let ((opoint (or pos
(point))) start
)
322 (goto-char (point-min))
326 (1+ (count-lines start
(point)))))) )
330 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
331 ;; Section Decoration Adjusment
332 ;; ============================
334 ;; The following functions implement a smart automatic title sectioning feature.
335 ;; The idea is that with the cursor sitting on a section title, we try to get as
336 ;; much information from context and try to do the best thing automatically.
337 ;; This function can be invoked many times and/or with prefix argument to rotate
338 ;; between the various sectioning decorations.
340 ;; Definitions: the two forms of sectioning define semantically separate section
341 ;; levels. A sectioning DECORATION consists in:
345 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
347 ;; - an INDENT (meaningful for the over-and-under style only) which determines
348 ;; how many characters and over-and-under style is hanging outside of the
349 ;; title at the beginning and ending.
351 ;; Important note: an existing decoration must be formed by at least two
352 ;; characters to be recognized.
354 ;; Here are two examples of decorations (| represents the window border, column
358 ;; 1. char: '-' e |Some Title
359 ;; style: simple |----------
361 ;; 2. char: '=' |==============
362 ;; style: over-and-under | Some Title
363 ;; indent: 2 |==============
368 ;; - The underlining character that is used depends on context. The file is
369 ;; scanned to find other sections and an appropriate character is selected.
370 ;; If the function is invoked on a section that is complete, the character is
371 ;; rotated among the existing section decorations.
373 ;; Note that when rotating the characters, if we come to the end of the
374 ;; hierarchy of decorations, the variable rst-preferred-decorations is
375 ;; consulted to propose a new underline decoration, and if continued, we cycle
376 ;; the decorations all over again. Set this variable to nil if you want to
377 ;; limit the underlining character propositions to the existing decorations in
380 ;; - A prefix argument can be used to alternate the style.
382 ;; - An underline/overline that is not extended to the column at which it should
383 ;; be hanging is dubbed INCOMPLETE. For example::
388 ;; Examples of default invocation:
390 ;; |Some Title ---> |Some Title
393 ;; |Some Title ---> |Some Title
394 ;; |----- |----------
397 ;; | Some Title ---> | Some Title
400 ;; In over-and-under style, when alternating the style, a variable is
401 ;; available to select how much default indent to use (it can be zero). Note
402 ;; that if the current section decoration already has an indent, we don't
403 ;; adjust it to the default, we rather use the current indent that is already
404 ;; there for adjustment (unless we cycle, in which case we use the indent
405 ;; that has been found previously).
407 (defgroup rst-adjust nil
408 "Settings for adjustment and cycling of section title
413 (defcustom rst-preferred-decorations
'( (?
= over-and-under
1)
421 "Preferred ordering of section title decorations. This
422 sequence is consulted to offer a new decoration suggestion when
423 we rotate the underlines at the end of the existing hierarchy
424 of characters, or when there is no existing section title in
429 (defcustom rst-default-indent
1
430 "Number of characters to indent the section title when toggling
431 decoration styles. This is used when switching from a simple
432 decoration style to a over-and-under decoration style."
436 (defvar rst-section-text-regexp
"^[ \t]*\\S-*[a-zA-Z0-9]\\S-*"
437 "Regular expression for valid section title text.")
440 (defun rst-line-homogeneous-p (&optional accept-special
)
441 "Predicate return the unique char if the current line is
442 composed only of a single repeated non-whitespace
443 character. This returns the char even if there is whitespace at
444 the beginning of the line.
446 If ACCEPT-SPECIAL is specified we do not ignore special sequences
447 which normally we would ignore when doing a search on many lines.
448 For example, normally we have cases to ignore commonly occuring
449 patterns, such as :: or ...; with the flag do not ignore them."
451 (back-to-indentation)
452 (unless (looking-at "\n")
453 (let ((c (thing-at-point 'char
)))
454 (if (and (looking-at (format "[%s]+[ \t]*$" c
))
458 (not (looking-at "::[ \t]*$"))
459 (not (looking-at "\\.\\.\\.[ \t]*$"))
460 ;; Discard one char line
461 (not (looking-at ".[ \t]*$"))
467 (defun rst-line-homogeneous-nodent-p (&optional accept-special
)
470 (if (looking-at "^[ \t]+")
472 (rst-line-homogeneous-p accept-special
)
476 (defun rst-compare-decorations (deco1 deco2
)
477 "Compare decorations. Returns true if both are equal,
478 according to restructured text semantics (only the character and
479 the style are compared, the indentation does not matter."
480 (and (eq (car deco1
) (car deco2
))
481 (eq (cadr deco1
) (cadr deco2
))))
484 (defun rst-get-decoration-match (hier deco
)
485 "Returns the index (level) of the decoration in the given hierarchy.
486 This basically just searches for the item using the appropriate
487 comparison and returns the index. We return nil if the item is
490 (while (and cur
(not (rst-compare-decorations (car cur
) deco
)))
491 (setq cur
(cdr cur
)))
495 (defun rst-suggest-new-decoration (alldecos &optional prev
)
496 "Suggest a new, different decoration, different from all that
499 ALLDECOS is the set of all decorations, including the line
500 numbers. PREV is the optional previous decoration, in order to
501 suggest a better match."
503 ;; For all the preferred decorations...
505 ;; If 'prev' is given, reorder the list to start searching after the
508 (cdr (rst-get-decoration-match rst-preferred-decorations prev
)))
510 ;; List of candidates to search.
511 (curpotential (append fplist rst-preferred-decorations
)))
513 ;; For all the decorations...
516 (while (and cur
(not found
))
517 (if (rst-compare-decorations (car cur
) (car curpotential
))
519 (setq found
(car curpotential
))
520 (setq cur
(cdr cur
))))
523 (setq curpotential
(cdr curpotential
)))
525 (copy-list (car curpotential
)) ))
527 (defun rst-delete-line ()
528 "A version of kill-line that does not use the kill-ring."
529 (delete-region (line-beginning-position) (min (+ 1 (line-end-position))
532 (defun rst-update-section (char style
&optional indent
)
533 "Unconditionally updates the style of a section decoration
534 using the given character CHAR, with STYLE 'simple or
535 'over-and-under, and with indent INDENT. If the STYLE is
536 'simple, whitespace before the title is removed (indent is
537 always assume to be 0).
539 If there are existing overline and/or underline from the
540 existing decoration, they are removed before adding the
541 requested decoration."
550 (setq marker
(point-marker))
552 ;; Fixup whitespace at the beginning and end of the line
553 (if (or (null indent
) (eq style
'simple
))
556 (delete-horizontal-space)
557 (insert (make-string indent ?
))
560 (delete-horizontal-space)
562 ;; Set the current column, we're at the end of the title line
563 (setq len
(+ (current-column) indent
))
565 ;; Remove previous line if it consists only of a single repeated character
568 (and (rst-line-homogeneous-p 1)
569 ;; Avoid removing the underline of a title right above us.
570 (save-excursion (forward-line -
1)
571 (not (looking-at rst-section-text-regexp
)))
574 ;; Remove following line if it consists only of a single repeated
578 (and (rst-line-homogeneous-p 1)
580 ;; Add a newline if we're at the end of the buffer, for the subsequence
581 ;; inserting of the underline
582 (if (= (point) (buffer-end 1))
586 (if (eq style
'over-and-under
)
590 (insert (make-string len char
))))
595 (insert (make-string len char
))
602 (defun rst-normalize-cursor-position ()
603 "If the cursor is on a decoration line or an empty line , place
604 it on the section title line (at the end). Returns the line
605 offset by which the cursor was moved. This works both over or
607 (if (save-excursion (beginning-of-line)
608 (or (rst-line-homogeneous-p 1)
609 (looking-at "^[ \t]*$")))
613 ((save-excursion (forward-line -
1)
615 (and (looking-at rst-section-text-regexp
)
616 (not (rst-line-homogeneous-p 1))))
617 (progn (forward-line -
1) -
1))
618 ((save-excursion (forward-line +1)
620 (and (looking-at rst-section-text-regexp
)
621 (not (rst-line-homogeneous-p 1))))
622 (progn (forward-line +1) +1))
627 (defun rst-find-all-decorations ()
628 "Finds all the decorations in the file, and returns a list of
629 (line, decoration) pairs. Each decoration consists in a (char,
630 style, indent) triple.
632 This function does not detect the hierarchy of decorations, it
633 just finds all of them in a file. You can then invoke another
634 function to remove redundancies and inconsistencies."
638 ;; Iterate over all the section titles/decorations in the file.
640 (beginning-of-buffer)
641 (while (< (point) (buffer-end 1))
642 (if (rst-line-homogeneous-nodent-p)
644 (setq curline
(+ curline
(rst-normalize-cursor-position)))
646 ;; Here we have found a potential site for a decoration,
648 (let ((deco (rst-get-decoration)))
649 (if (cadr deco
) ;; Style is existing.
650 ;; Found a real decoration site.
652 (push (cons curline deco
) positions
)
653 ;; Push beyond the underline.
655 (setq curline
(+ curline
1))
659 (setq curline
(+ curline
1))
661 (reverse positions
)))
664 (defun rst-infer-hierarchy (decorations)
665 "Build a hierarchy of decorations using the list of given decorations.
667 This function expects a list of (char, style, indent)
668 decoration specifications, in order that they appear in a file,
669 and will infer a hierarchy of section levels by removing
670 decorations that have already been seen in a forward traversal of the
671 decorations, comparing just the character and style.
673 Similarly returns a list of (char, style, indent), where each
674 list element should be unique."
676 (let ((hierarchy-alist (list)))
677 (dolist (x decorations
)
681 (unless (assoc (cons char style
) hierarchy-alist
)
682 (setq hierarchy-alist
683 (append hierarchy-alist
684 (list (cons (cons char style
) x
)))) )
686 (mapcar 'cdr hierarchy-alist
)
690 (defun rst-get-hierarchy (&optional alldecos ignore
)
691 "Returns a list of decorations that represents the hierarchy of
692 section titles in the file.
694 If the line number in IGNORE is specified, the decoration found
695 on that line (if there is one) is not taken into account when
696 building the hierarchy."
697 (let ((all (or alldecos
(rst-find-all-decorations))))
698 (setq all
(assq-delete-all ignore all
))
699 (rst-infer-hierarchy (mapcar 'cdr all
))))
702 (defun rst-get-decoration (&optional point
)
703 "Looks around point and finds the characteristics of the
704 decoration that is found there. We assume that the cursor is
705 already placed on the title line (and not on the overline or
708 This function returns a (char, style, indent) triple. If the
709 characters of overline and underline are different, we return
710 the underline character. The indent is always calculated. A
711 decoration can be said to exist if the style is not nil.
713 A point can be specified to go to the given location before
714 extracting the decoration."
716 (let (char style indent
)
718 (if point
(goto-char point
))
720 (if (looking-at rst-section-text-regexp
)
721 (let* ((over (save-excursion
723 (rst-line-homogeneous-nodent-p)))
725 (under (save-excursion
727 (rst-line-homogeneous-nodent-p)))
730 ;; Check that the line above the overline is not part of a title
734 (and (equal (forward-line -
2) 0)
735 (looking-at rst-section-text-regexp
))))
739 ;; No decoration found, leave all return values nil.
740 ((and (eq over nil
) (eq under nil
)))
742 ;; Overline only, leave all return values nil.
744 ;; Note: we don't return the overline character, but it could
745 ;; perhaps in some cases be used to do something.
746 ((and over
(eq under nil
)))
749 ((and under
(eq over nil
))
753 ;; Both overline and underline.
756 style
'over-and-under
))
761 (setq indent
(save-excursion (back-to-indentation) (current-column)))
764 (list char style indent
)))
767 (defun rst-get-decorations-around (&optional alldecos
)
768 "Given the list of all decorations (with positions),
769 find the decorations before and after the given point.
770 A list of the previous and next decorations is returned."
771 (let* ((all (or alldecos
(rst-find-all-decorations)))
772 (curline (line-number-at-pos))
776 ;; Search for the decorations around the current line.
777 (while (and cur
(< (caar cur
) curline
))
780 ;; 'cur' is the following decoration.
782 (if (and cur
(caar cur
))
783 (setq next
(if (= curline
(caar cur
)) (cdr cur
) cur
)))
785 (mapcar 'cdar
(list prev next
))
789 (defun rst-decoration-complete-p (deco &optional point
)
790 "Return true if the decoration DECO around POINT is complete."
791 ;; Note: we assume that the detection of the overline as being the underline
792 ;; of a preceding title has already been detected, and has been eliminated
793 ;; from the decoration that is given to us.
795 ;; There is some sectioning already present, so check if the current
796 ;; sectioning is complete and correct.
797 (let* ((char (car deco
))
799 (indent (caddr deco
))
800 (endcol (save-excursion (end-of-line) (current-column)))
803 (let ((exps (concat "^"
804 (regexp-quote (make-string (+ endcol indent
) char
))
807 (save-excursion (forward-line +1)
810 (or (not (eq style
'over-and-under
))
811 (save-excursion (forward-line -
1)
818 (defun rst-get-next-decoration
819 (curdeco hier
&optional suggestion reverse-direction
)
820 "Get the next decoration for CURDECO, in given hierarchy HIER,
821 and suggesting for new decoration SUGGESTION."
825 (style (cadr curdeco
))
827 ;; Build a new list of decorations for the rotation.
830 ;; Suggest a new decoration.
832 ;; If nothing to suggest, use first decoration.
835 ;; Search for next decoration.
837 (let ((cur (if reverse-direction rotdecos
841 (not (and (eq char
(caar cur
))
842 (eq style
(cadar cur
)))))
843 (setq cur
(cdr cur
)))
846 ;; If not found, take the first of all decorations.
852 "Adjust/rotate the section decoration for the section title
853 around point or promote/demote the decorations inside the region,
854 depending on if the region is active. This function is meant to
855 be invoked possibly multiple times, and can vary its behaviour
856 with a positive prefix argument (toggle style), or with a
857 negative prefix argument (alternate behaviour).
859 This function is the main focus of this module and is a bit of a
860 swiss knife. It is meant as the single most essential function
861 to be bound to invoke to adjust the decorations of a section
862 title in restructuredtext. It tries to deal with all the
863 possible cases gracefully and to do `the right thing' in all
866 See the documentations of rst-adjust-decoration and
867 rst-promote-region for full details.
872 The method can take either (but not both) of
874 a. a (non-negative) prefix argument, which means to toggle the
875 decoration style. Invoke with C-u prefix for example;
877 b. a negative numerical argument, which generally inverts the
878 direction of search in the file or hierarchy. Invoke with C--
884 (let* ( ;; Parse the positive and negative prefix arguments.
886 (and current-prefix-arg
887 (< (prefix-numeric-value current-prefix-arg
) 0)))
889 (and current-prefix-arg
(not reverse-direction
))))
891 (if (and transient-mark-mode mark-active
)
892 ;; Adjust decorations within region.
893 (rst-promote-region current-prefix-arg
)
894 ;; Adjust decoration around point.
895 (rst-adjust-decoration toggle-style reverse-direction
))
897 ;; Run the hooks to run after adjusting.
898 (run-hooks 'rst-adjust-hook
)
902 (defvar rst-adjust-hook nil
903 "Hooks to be run after running rst-adjust.")
905 (defun rst-adjust-decoration (&optional toggle-style reverse-direction
)
906 "Adjust/rotate the section decoration for the section title around point.
908 This function is meant to be invoked possibly multiple times, and
909 can vary its behaviour with a true TOGGLE-STYLE argument, or with
910 a REVERSE-DIRECTION argument.
915 The next action it takes depends on context around the point, and
916 it is meant to be invoked possibly more than once to rotate among
917 the various possibilities. Basically, this function deals with:
919 - adding a decoration if the title does not have one;
921 - adjusting the length of the underline characters to fit a
924 - rotating the decoration in the set of already existing
925 sectioning decorations used in the file;
927 - switching between simple and over-and-under styles.
929 You should normally not have to read all the following, just
930 invoke the method and it will do the most obvious thing that you
934 Decoration Definitions
935 ======================
937 The decorations consist in
941 2. a STYLE which can be either of 'simple' or 'over-and-under'.
943 3. an INDENT (meaningful for the over-and-under style only)
944 which determines how many characters and over-and-under
945 style is hanging outside of the title at the beginning and
948 See source code for mode details.
951 Detailed Behaviour Description
952 ==============================
954 Here are the gory details of the algorithm (it seems quite
955 complicated, but really, it does the most obvious thing in all
956 the particular cases):
958 Before applying the decoration change, the cursor is placed on
959 the closest line that could contain a section title.
961 Case 1: No Decoration
962 ---------------------
964 If the current line has no decoration around it,
966 - search backwards for the last previous decoration, and apply
967 the decoration one level lower to the current line. If there
968 is no defined level below this previous decoration, we suggest
969 the most appropriate of the rst-preferred-decorations.
971 If REVERSE-DIRECTION is true, we simply use the previous
972 decoration found directly.
974 - if there is no decoration found in the given direction, we use
975 the first of rst-preferred-decorations.
977 The prefix argument forces a toggle of the prescribed decoration
980 Case 2: Incomplete Decoration
981 -----------------------------
983 If the current line does have an existing decoration, but the
984 decoration is incomplete, that is, the underline/overline does
985 not extend to exactly the end of the title line (it is either too
986 short or too long), we simply extend the length of the
987 underlines/overlines to fit exactly the section title.
989 If the prefix argument is given, we toggle the style of the
992 REVERSE-DIRECTION has no effect in this case.
994 Case 3: Complete Existing Decoration
995 ------------------------------------
997 If the decoration is complete (i.e. the underline (overline)
998 length is already adjusted to the end of the title line), we
999 search/parse the file to establish the hierarchy of all the
1000 decorations (making sure not to include the decoration around
1001 point), and we rotate the current title's decoration from within
1002 that list (by default, going *down* the hierarchy that is present
1003 in the file, i.e. to a lower section level). This is meant to be
1004 used potentially multiple times, until the desired decoration is
1005 found around the title.
1007 If we hit the boundary of the hierarchy, exactly one choice from
1008 the list of preferred decorations is suggested/chosen, the first
1009 of those decoration that has not been seen in the file yet (and
1010 not including the decoration around point), and the next
1011 invocation rolls over to the other end of the hierarchy (i.e. it
1012 cycles). This allows you to avoid having to set which character
1013 to use by always using the
1015 If REVERSE-DIRECTION is true, the effect is to change the
1016 direction of rotation in the hierarchy of decorations, thus
1017 instead going *up* the hierarchy.
1019 However, if there is a non-negative prefix argument, we do not
1020 rotate the decoration, but instead simply toggle the style of the
1021 current decoration (this should be the most common way to toggle
1022 the style of an existing complete decoration).
1028 The invocation of this function can be carried out anywhere
1029 within the section title line, on an existing underline or
1030 overline, as well as on an empty line following a section title.
1031 This is meant to be as convenient as possible.
1037 Indented section titles such as ::
1042 are illegal in restructuredtext and thus not recognized by the
1043 parser. This code will thus not work in a way that would support
1044 indented sections (it would be ambiguous anyway).
1050 Section titles that are right next to each other may not be
1051 treated well. More work might be needed to support those, and
1052 special conditions on the completeness of existing decorations
1053 might be required to make it non-ambiguous.
1055 For now we assume that the decorations are disjoint, that is,
1056 there is at least a single line between the titles/decoration
1063 We suggest that you bind this function on C-=. It is close to
1064 C-- so a negative argument can be easily specified with a flick
1065 of the right hand fingers and the binding is unused in text-mode."
1068 ;; If we were invoked directly, parse the prefix arguments into the
1069 ;; arguments of the function.
1070 (if current-prefix-arg
1071 (setq reverse-direction
1072 (and current-prefix-arg
1073 (< (prefix-numeric-value current-prefix-arg
) 0))
1076 (and current-prefix-arg
(not reverse-direction
))))
1078 (let* (;; Check if we're on an underline around a section title, and move the
1079 ;; cursor to the title if this is the case.
1080 (moved (rst-normalize-cursor-position))
1082 ;; Find the decoration and completeness around point.
1083 (curdeco (rst-get-decoration))
1084 (char (car curdeco
))
1085 (style (cadr curdeco
))
1086 (indent (caddr curdeco
))
1088 ;; New values to be computed.
1089 char-new style-new indent-new
1092 ;; We've moved the cursor... if we're not looking at some text, we have
1094 (if (save-excursion (beginning-of-line)
1095 (looking-at rst-section-text-regexp
))
1098 ;;-------------------------------------------------------------------
1099 ;; Case 1: No Decoration
1100 ((and (eq char nil
) (eq style nil
))
1102 (let* ((alldecos (rst-find-all-decorations))
1104 (around (rst-get-decorations-around alldecos
))
1108 (hier (rst-get-hierarchy alldecos
))
1111 ;; Advance one level down.
1114 (if (not reverse-direction
)
1115 (or (cadr (rst-get-decoration-match hier prev
))
1116 (rst-suggest-new-decoration hier prev
))
1118 (copy-list (car rst-preferred-decorations
))
1121 ;; Invert the style if requested.
1123 (setcar (cdr cur
) (if (eq (cadr cur
) 'simple
)
1124 'over-and-under
'simple
)) )
1126 (setq char-new
(car cur
)
1127 style-new
(cadr cur
)
1128 indent-new
(caddr cur
))
1131 ;;-------------------------------------------------------------------
1132 ;; Case 2: Incomplete Decoration
1133 ((not (rst-decoration-complete-p curdeco
))
1135 ;; Invert the style if requested.
1137 (setq style
(if (eq style
'simple
) 'over-and-under
'simple
)))
1143 ;;-------------------------------------------------------------------
1144 ;; Case 3: Complete Existing Decoration
1148 ;; Simply switch the style of the current decoration.
1150 style-new
(if (eq style
'simple
) 'over-and-under
'simple
)
1151 indent-new rst-default-indent
)
1153 ;; Else, we rotate, ignoring the decoration around the current
1155 (let* ((alldecos (rst-find-all-decorations))
1157 (hier (rst-get-hierarchy alldecos
(line-number-at-pos)))
1159 ;; Suggestion, in case we need to come up with something
1161 (suggestion (rst-suggest-new-decoration
1163 (car (rst-get-decorations-around alldecos
))))
1165 (nextdeco (rst-get-next-decoration
1166 curdeco hier suggestion reverse-direction
))
1170 ;; Indent, if present, always overrides the prescribed indent.
1171 (setq char-new
(car nextdeco
)
1172 style-new
(cadr nextdeco
)
1173 indent-new
(caddr nextdeco
))
1178 ;; Override indent with present indent!
1179 (setq indent-new
(if (> indent
0) indent indent-new
))
1181 (if (and char-new style-new
)
1182 (rst-update-section char-new style-new indent-new
))
1186 ;; Correct the position of the cursor to more accurately reflect where it
1187 ;; was located when the function was invoked.
1189 (forward-line (- moved
))
1194 ;; Maintain an alias for compatibility.
1195 (defalias 'rst-adjust-section-title
'rst-adjust
)
1198 (defun rst-promote-region (&optional demote
)
1199 "Promote the section titles within the region.
1201 With argument DEMOTE or a prefix argument, demote the
1202 section titles instead. The algorithm used at the boundaries of
1203 the hierarchy is similar to that used by rst-adjust-decoration."
1206 (let* ((demote (or current-prefix-arg demote
))
1207 (alldecos (rst-find-all-decorations))
1210 (hier (rst-get-hierarchy alldecos
))
1211 (suggestion (rst-suggest-new-decoration hier
))
1213 (region-begin-line (line-number-at-pos (region-beginning)))
1214 (region-end-line (line-number-at-pos (region-end)))
1219 ;; Skip the markers that come before the region beginning
1220 (while (and cur
(< (caar cur
) region-begin-line
))
1221 (setq cur
(cdr cur
)))
1223 ;; Create a list of markers for all the decorations which are found within
1227 (while (and cur
(< (setq line
(caar cur
)) region-end-line
))
1228 (setq m
(make-marker))
1230 (push (list (set-marker m
(point)) (cdar cur
)) marker-list
)
1231 (setq cur
(cdr cur
)) ))
1233 ;; Apply modifications.
1235 (dolist (p marker-list
)
1236 ;; Go to the decoration to promote.
1239 ;; Rotate the next decoration.
1240 (setq nextdeco
(rst-get-next-decoration
1241 (cadr p
) hier suggestion demote
))
1243 ;; Update the decoration.
1244 (apply 'rst-update-section nextdeco
)
1246 ;; Clear marker to avoid slowing down the editing after we're done.
1247 (set-marker (car p
) nil
)
1249 (setq deactivate-mark nil
)
1254 (defun rst-display-decorations-hierarchy (&optional decorations
)
1255 "Display the current file's section title decorations hierarchy.
1256 This function expects a list of (char, style, indent) triples."
1259 (if (not decorations
)
1260 (setq decorations
(rst-get-hierarchy)))
1261 (with-output-to-temp-buffer "*rest section hierarchy*"
1263 (with-current-buffer standard-output
1264 (dolist (x decorations
)
1265 (insert (format "\nSection Level %d" level
))
1266 (apply 'rst-update-section x
)
1273 (defun rst-straighten-decorations (&optional buffer
)
1274 "Redo all the decorations in the given buffer, using our
1275 preferred set of decorations. This can be used, for example,
1276 when using somebody else's copy of a document, in order to
1277 adapt it to our preferred style.
1278 If no buffer is specified, the default buffer is used."
1281 (let* ((alldecos (rst-find-all-decorations))
1282 (hier (rst-get-hierarchy alldecos
))
1284 ;; Get a list of pairs of (level . marker)
1285 (levels-and-markers (mapcar
1287 (cons (position (cdr deco
) hier
:test
'equal
)
1288 (let ((m (make-marker)))
1289 (goto-line (car deco
))
1290 (set-marker m
(point))
1294 (dolist (lm levels-and-markers
)
1295 ;; Go to the appropriate position
1296 (goto-char (cdr lm
))
1298 ;; Apply the new styule
1299 (apply 'rst-update-section
(nth (car lm
) rst-preferred-decorations
))
1301 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1302 (set-marker (cdr lm
) nil
)
1307 (defun rst-rstrip (str)
1308 "Strips the whitespace at the end of a string."
1310 (string-match "[ \t\n]*\\'" str
)
1311 (substring str
0 (match-beginning 0))
1314 (defun rst-get-stripped-line ()
1315 "Returns the line at cursor, stripped from whitespace."
1316 (re-search-forward "\\S-.*\\S-" (line-end-position))
1317 (buffer-substring-no-properties (match-beginning 0)
1320 (defun rst-section-tree (alldecos)
1321 "Returns a hierarchical tree of the sections titles in the
1322 document. This can be used to generate a table of contents for
1323 the document. The top node will always be a nil node, with the
1324 top-level titles as children (there may potentially be more than
1327 Each section title consists in a cons of the stripped title
1328 string and a marker to the section in the original text document.
1330 If there are missing section levels, the section titles are
1331 inserted automatically, and the title string is set to nil, and
1332 the marker set to the first non-nil child of itself.
1333 Conceptually, the nil nodes--i.e. those which have no title--are
1334 to be considered as being the same line as their first non-nil
1335 child. This has advantages later in processing the graph."
1338 (hier (rst-get-hierarchy alldecos
))
1339 (levels (make-hash-table :test
'equal
:size
10))
1344 ;; Compare just the character and indent in the hash table.
1345 (puthash (cons (car deco
) (cadr deco
)) lev levels
)
1348 ;; Create a list of lines that contains (text, level, marker) for each
1352 (mapcar (lambda (deco)
1353 (goto-line (car deco
))
1354 (list (gethash (cons (cadr deco
) (caddr deco
)) levels
)
1355 (rst-get-stripped-line)
1356 (let ((m (make-marker)))
1357 (beginning-of-line 1)
1358 (set-marker m
(point)))
1362 (let ((lcontnr (cons nil lines
)))
1363 (rst-section-tree-rec lcontnr -
1))))
1366 (defun rst-section-tree-rec (decos lev
)
1367 "Recursive function for the implementation of the section tree
1368 building. DECOS is a cons cell whose cdr is the remaining list
1369 of decorations, and we change it as we consume them. LEV is
1370 the current level of that node. This function returns a pair
1371 of the subtree that was built. This treats the decos list
1374 (let ((ndeco (cadr decos
))
1378 ;; If the next decoration matches our level
1379 (when (and ndeco
(= (car ndeco
) lev
))
1380 ;; Pop the next decoration and create the current node with it
1381 (setcdr decos
(cddr decos
))
1382 (setq node
(cdr ndeco
)) )
1383 ;; Else we let the node title/marker be unset.
1385 ;; Build the child nodes
1386 (while (and (cdr decos
) (> (caadr decos
) lev
))
1388 (cons (rst-section-tree-rec decos
(1+ lev
))
1390 (setq children
(reverse children
))
1392 ;; If node is still unset, we use the marker of the first child.
1394 (setq node
(cons nil
(cdaar children
))))
1396 ;; Return this node with its children.
1397 (cons node children
)
1401 (defun rst-section-tree-point (node &optional point
)
1402 "Given a computed and valid section tree SECTREE and a point
1403 POINT (default being the current point in the current buffer),
1404 find and return the node within the sectree where the cursor
1407 Return values: a pair of (parent path, container subtree). The
1408 parent path is simply a list of the nodes above the container
1409 subtree node that we're returning."
1413 (let* ((curpoint (or point
(point))))
1415 ;; Check if we are before the current node.
1416 (if (and (cadar node
) (>= curpoint
(cadar node
)))
1418 ;; Iterate all the children, looking for one that might contain the
1420 (let ((curnode (cdr node
))
1423 (while (and curnode
(>= curpoint
(cadaar curnode
)))
1425 curnode
(cdr curnode
)))
1428 (let ((sub (rst-section-tree-point (car last
) curpoint
)))
1429 (setq path
(car sub
)
1431 (setq outtree node
))
1434 (cons (cons (car node
) path
) outtree
)
1438 (defun rst-toc-insert (&optional pfxarg
)
1439 "Insert a simple text rendering of the table of contents.
1440 By default the top level is ignored if there is only one, because
1441 we assume that the document will have a single title.
1443 If a numeric prefix argument is given, insert the TOC up to the
1446 The TOC is inserted indented at the current column."
1450 (let* (;; Check maximum level override
1451 (rst-toc-insert-max-level
1452 (if (and (integerp pfxarg
) (> (prefix-numeric-value pfxarg
) 0))
1453 (prefix-numeric-value pfxarg
) rst-toc-insert-max-level
))
1455 ;; Get the section tree for the current cursor point.
1457 (rst-section-tree-point
1458 (rst-section-tree (rst-find-all-decorations))))
1460 ;; Figure out initial indent.
1461 (initial-indent (make-string (current-column) ?
))
1462 (init-point (point)))
1464 (when (cddr sectree-pair
)
1465 (rst-toc-insert-node (cdr sectree-pair
) 0 initial-indent
"")
1467 ;; Fixup for the first line.
1468 (delete-region init-point
(+ init-point
(length initial-indent
)))
1470 ;; Delete the last newline added.
1471 (delete-backward-char 1)
1475 (defgroup rst-toc nil
1476 "Settings for reStructuredText table of contents."
1480 (defcustom rst-toc-indent
2
1481 "Indentation for table-of-contents display (also used for
1482 formatting insertion, when numbering is disabled)."
1485 (defcustom rst-toc-insert-style
'fixed
1486 "Set this to one of the following values to determine numbering and
1488 - plain: no numbering (fixed indentation)
1489 - fixed: numbering, but fixed indentation
1490 - aligned: numbering, titles aligned under each other
1491 - listed: numbering, with dashes like list items (EXPERIMENTAL)
1495 (defcustom rst-toc-insert-number-separator
" "
1496 "Separator that goes between the TOC number and the title."
1499 ;; This is used to avoid having to change the user's mode.
1500 (defvar rst-toc-insert-click-keymap
1501 (let ((map (make-sparse-keymap)))
1502 (define-key map
[mouse-1
] 'rst-toc-mode-mouse-goto
)
1504 "(Internal) What happens when you click on propertized text in the TOC.")
1506 (defcustom rst-toc-insert-max-level nil
1507 "If non-nil, maximum depth of the inserted TOC."
1510 (defun rst-toc-insert-node (node level indent pfx
)
1511 "Recursive function that does the print of the inserted
1512 toc. PFX is the prefix numbering, that includes the alignment
1513 necessary for all the children of this level to align."
1515 ;; Note: we do child numbering from the parent, so we start number the
1516 ;; children one level before we print them.
1517 (let ((do-print (> level
0))
1523 (unless (equal rst-toc-insert-style
'plain
)
1524 (insert pfx rst-toc-insert-number-separator
))
1525 (insert (or (caar node
) "[missing node]"))
1526 ;; Add properties to the text, even though in normal text mode it
1527 ;; won't be doing anything for now. Not sure that I want to change
1528 ;; mode stuff. At least the highlighting gives the idea that this
1529 ;; is generated automatically.
1530 (put-text-property b
(point) 'mouse-face
'highlight
)
1531 (put-text-property b
(point) 'rst-toc-target
(cadar node
))
1532 (put-text-property b
(point) 'keymap rst-toc-insert-click-keymap
)
1537 ;; Prepare indent for children.
1540 ((eq rst-toc-insert-style
'plain
)
1541 (concat indent rst-toc-indent
))
1543 ((eq rst-toc-insert-style
'fixed
)
1544 (concat indent
(make-string rst-toc-indent ?
)))
1546 ((eq rst-toc-insert-style
'aligned
)
1547 (concat indent
(make-string (+ (length pfx
) 2) ?
)))
1549 ((eq rst-toc-insert-style
'listed
)
1550 (concat (substring indent
0 -
3)
1551 (concat (make-string (+ (length pfx
) 2) ?
) " - ")))
1555 (if (or (eq rst-toc-insert-max-level nil
)
1556 (< level rst-toc-insert-max-level
))
1557 (let ((do-child-numbering (>= level
0))
1559 (if do-child-numbering
1561 ;; Add a separating dot if there is already a prefix
1562 (if (> (length pfx
) 0)
1563 (setq pfx
(concat (rst-rstrip pfx
) ".")))
1565 ;; Calculate the amount of space that the prefix will require
1568 (setq fmt
(format "%%-%dd"
1569 (1+ (floor (log10 (length
1573 (dolist (child (cdr node
))
1574 (rst-toc-insert-node child
1577 (if do-child-numbering
1578 (concat pfx
(format fmt count
)) pfx
))
1584 (defun rst-toc-insert-find-delete-contents ()
1585 "Finds and deletes an existing comment after the first contents directive and
1586 delete that region. Return t if found and the cursor is left after the comment."
1587 (goto-char (point-min))
1588 ;; We look for the following and the following only (in other words, if your
1589 ;; syntax differs, this won't work. If you would like a more flexible thing,
1590 ;; contact the author, I just can't imagine that this requirement is
1591 ;; unreasonable for now).
1593 ;; .. contents:: [...anything here...]
1600 (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
1604 ;; Look for the first line that starts at the first column.
1608 (< (point) (point-max))
1609 (or (and (looking-at "[ \t]+[^ \t]") (setq last-real
(point)) t
)
1610 (looking-at "\\s-*$")))
1615 (goto-char last-real
)
1617 (delete-region beg
(point)))
1622 (defun rst-toc-insert-update ()
1623 "Automatically find the .. contents:: section of a document and update the
1624 inserted TOC if present. You can use this in your file-write hook to always
1625 make it up-to-date automatically."
1628 (if (rst-toc-insert-find-delete-contents)
1629 (progn (insert "\n ")
1630 (rst-toc-insert))) )
1631 ;; Note: always return nil, because this may be used as a hook.
1635 ;;------------------------------------------------------------------------------
1637 (defun rst-toc-node (node level
)
1638 "Recursive function that does the print of the TOC in rst-toc-mode."
1642 ;; Insert line text.
1643 (insert (make-string (* rst-toc-indent
(1- level
)) ?
))
1644 (insert (or (caar node
) "[missing node]"))
1647 (put-text-property b
(point) 'mouse-face
'highlight
)
1649 ;; Add link on lines.
1650 (put-text-property b
(point) 'rst-toc-target
(cadar node
))
1655 (dolist (child (cdr node
))
1656 (rst-toc-node child
(1+ level
))))
1658 (defun rst-toc-count-lines (node target-node
)
1659 "Count the number of lines to the TARGET-NODE node. This
1660 recursive function returns a cons of the number of additional
1661 lines that have been counted for its node and children and 't if
1662 the node has been found."
1666 (if (eq node target-node
)
1668 (let ((child (cdr node
)))
1669 (while (and child
(not found
))
1670 (let ((cl (rst-toc-count-lines (car child
) target-node
)))
1671 (setq count
(+ count
(car cl
))
1673 child
(cdr child
))))))
1674 (cons count found
)))
1678 "Finds all the section titles and their decorations in the
1679 file, and displays a hierarchically-organized list of the
1680 titles, which is essentially a table-of-contents of the
1683 The emacs buffer can be navigated, and selecting a section
1684 brings the cursor in that section."
1686 (let* ((curbuf (current-buffer))
1688 ;; Get the section tree
1689 (alldecos (rst-find-all-decorations))
1690 (sectree (rst-section-tree alldecos
))
1692 (our-node (cdr (rst-section-tree-point sectree
)))
1695 ;; Create a temporary buffer.
1696 (buf (get-buffer-create rst-toc-buffer-name
))
1699 (with-current-buffer buf
1700 (let ((inhibit-read-only t
))
1702 (delete-region (point-min) (point-max))
1703 (insert (format "Table of Contents: %s\n" (or (caar sectree
) "")))
1704 (put-text-property (point-min) (point)
1705 'face
(list '(background-color .
"lightgray")))
1706 (rst-toc-node sectree
0)
1708 ;; Count the lines to our found node.
1709 (let ((linefound (rst-toc-count-lines sectree our-node
)))
1710 (setq line
(if (cdr linefound
) (car linefound
) 0)))
1712 (display-buffer buf
)
1715 ;; Save the buffer to return to.
1716 (set (make-local-variable 'rst-toc-return-buffer
) curbuf
)
1718 ;; Move the cursor near the right section in the TOC.
1723 (defun rst-toc-mode-find-section ()
1724 (let ((pos (get-text-property (point) 'rst-toc-target
)))
1726 (error "No section on this line"))
1727 (unless (buffer-live-p (marker-buffer pos
))
1728 (error "Buffer for this section was killed"))
1731 (defvar rst-toc-buffer-name
"*Table of Contents*"
1732 "Name of the Table of Contents buffer.")
1734 (defun rst-toc-mode-goto-section ()
1735 "Go to the section the current line describes."
1737 (let ((pos (rst-toc-mode-find-section)))
1738 (kill-buffer (get-buffer rst-toc-buffer-name
))
1739 (pop-to-buffer (marker-buffer pos
))
1743 (defun rst-toc-mode-mouse-goto (event)
1744 "In Rst-Toc mode, go to the occurrence whose line you click on."
1748 (set-buffer (window-buffer (posn-window (event-end event
))))
1750 (goto-char (posn-point (event-end event
)))
1751 (setq pos
(rst-toc-mode-find-section))))
1752 (pop-to-buffer (marker-buffer pos
))
1755 (defun rst-toc-mode-mouse-goto-kill (event)
1757 (call-interactively 'rst-toc-mode-mouse-goto event
)
1758 (kill-buffer (get-buffer rst-toc-buffer-name
)))
1760 (defvar rst-toc-return-buffer nil
1761 "Buffer local variable that is used to return to the original
1762 buffer from the TOC.")
1764 (defun rst-toc-quit-window ()
1767 (pop-to-buffer rst-toc-return-buffer
))
1769 (defvar rst-toc-mode-map
1770 (let ((map (make-sparse-keymap)))
1771 (define-key map
[mouse-1
] 'rst-toc-mode-mouse-goto-kill
)
1772 (define-key map
[mouse-2
] 'rst-toc-mode-mouse-goto
)
1773 (define-key map
"\C-m" 'rst-toc-mode-goto-section
)
1774 (define-key map
"f" 'rst-toc-mode-goto-section
)
1775 (define-key map
"q" 'rst-toc-quit-window
)
1776 (define-key map
"z" 'kill-this-buffer
)
1778 "Keymap for `rst-toc-mode'.")
1780 (put 'rst-toc-mode
'mode-class
'special
)
1782 (defun rst-toc-mode ()
1783 "Major mode for output from \\[rst-toc]."
1785 (kill-all-local-variables)
1786 (use-local-map rst-toc-mode-map
)
1787 (setq major-mode
'rst-toc-mode
)
1788 (setq mode-name
"Rst-TOC")
1789 (setq buffer-read-only t
)
1792 ;; Note: use occur-mode (replace.el) as a good example to complete missing
1796 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1798 ;; Section movement commands.
1801 (defun rst-forward-section (&optional offset
)
1802 "Skip to the next restructured text section title.
1803 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
1804 backwards in the file (default is to use 1)."
1806 (let* (;; Default value for offset.
1807 (offset (or offset
1))
1809 ;; Get all the decorations in the file, with their line numbers.
1810 (alldecos (rst-find-all-decorations))
1812 ;; Get the current line.
1813 (curline (line-number-at-pos))
1820 ;; Find the index of the "next" decoration w.r.t. to the current line.
1821 (while (and cur
(< (caar cur
) curline
))
1822 (setq cur
(cdr cur
))
1824 ;; 'cur' is the decoration on or following the current line.
1826 (if (and (> offset
0) cur
(= (caar cur
) curline
))
1829 ;; Find the final index.
1830 (setq idx
(+ idx
(if (> offset
0) (- offset
1) offset
)))
1831 (setq cur
(nth idx alldecos
))
1833 ;; If the index is positive, goto the line, otherwise go to the buffer
1835 (if (and cur
(>= idx
0))
1836 (goto-line (car cur
))
1837 (if (> offset
0) (end-of-buffer) (beginning-of-buffer)))
1840 (defun rst-backward-section ()
1841 "Like rst-forward-section, except move back one title."
1843 (rst-forward-section -
1))
1848 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1849 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
1850 ;; always 2 or 3 characters apart horizontally with rest.
1852 (defvar rst-shift-fill-region nil
1853 "Set to true if you want to automatically re-fill the region that is being
1855 ;; FIXME: need to finish this feature properly.
1857 (defun rst-shift-region-right ()
1858 "Indent region ridigly, by two characters to the right."
1860 (let ((mbeg (set-marker (make-marker) (region-beginning)))
1861 (mend (set-marker (make-marker) (region-end))))
1862 (indent-rigidly mbeg mend
2)
1863 (when rst-shift-fill-region
1864 (fill-region mbeg mend
))
1867 (defun rst-find-leftmost-column (beg end
)
1868 "Finds the leftmost column in the region."
1869 (let ((mincol 1000))
1872 (while (< (point) end
)
1873 (back-to-indentation)
1874 (unless (looking-at "[ \t]*$")
1875 (setq mincol
(min mincol
(current-column))))
1880 (defun rst-shift-region-left (pfxarg)
1881 "Indent region ridigly, by two characters to the left.
1882 If invoked with a prefix arg, the entire indentation is removed,
1883 up to the leftmost character in the region."
1887 (- (rst-find-leftmost-column (region-beginning) (region-end)))
1889 (mbeg (set-marker (make-marker) (region-beginning)))
1890 (mend (set-marker (make-marker) (region-end)))
1892 (indent-rigidly mbeg mend chars
)
1893 (when rst-shift-fill-region
1894 (fill-region mbeg mend
))
1897 (defun rst-enumerate-region (rbeg rend
)
1898 "Insert numbered enumeration list prefixes to the currently
1899 selected region. With prefix argument, remove the enumeration.
1900 (Note: the removal part of not implemented yet.)"
1908 ;; Count the number of lines in the region
1909 (nlines (count-lines rbeg rend
))
1910 ;; Find the minimum column in all the lines in the region
1911 (lcol (rst-find-leftmost-column rbeg rend
))
1915 (operate-on-rectangle 'rst-enumerate-insert-enum rbeg rend t
)))
1918 (defun rst-enumerate-insert-enum (startpos begextra endextra
)
1919 (back-to-indentation)
1920 (if (= (current-column) lcol
)
1922 (insert (int-to-string curnum
))
1925 (indent-line-to (+ lcol
3))))
1927 ;; FIXME: TODO we need to do the enumeration removal as well.
1931 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1932 ;;; rst-mode.el --- Mode for viewing and editing reStructuredText-documents.
1934 ;; Copyright 2003 Stefan Merten <smerten@oekonux.de>
1936 ;; Note: this is an update from version 0.2.9 of rst-mode.el
1940 ;; This package provides support for documents marked up using the
1941 ;; reStructuredText format. Support includes font locking as well as some
1942 ;; convenience functions for editing. It does this by defining a Emacs major
1945 ;; The package is based on text-mode and inherits some things from it.
1946 ;; Particularly text-mode-hook is run before rst-mode-hook.
1950 ;; There are a number of things which can be customized using the standard
1951 ;; Emacs customization features. There are two customization groups for this
1959 ;; This group contains some general customizable features.
1961 ;; The group is contained in the wp group.
1965 ;; This group contains all necessary for customizing fonts. The default
1966 ;; settings use standard font-lock-*-face's so if you set these to your
1967 ;; liking they are probably good in rst-mode also.
1969 ;; The group is contained in the faces group as well as in the rst group.
1971 ;; rst-faces-defaults
1972 ;; ------------------
1973 ;; This group contains all necessary for customizing the default fonts used for
1974 ;; section title faces.
1976 ;; The general idea for section title faces is to have a non-default background
1977 ;; but do not change the background. The section level is shown by the
1978 ;; lightness of the background color. If you like this general idea of
1979 ;; generating faces for section titles but do not like the details this group
1980 ;; is the point where you can customize the details. If you do not like the
1981 ;; general idea, however, you should customize the faces used in
1982 ;; rst-adornment-faces-alist.
1984 ;; Note: If you are using a dark background please make sure the variable
1985 ;; frame-background-mode is set to the symbol dark. This triggers
1986 ;; some default values which are probably right for you.
1988 ;; The group is contained in the rst-faces group.
1990 ;; All customizable features have a comment explaining their meaning. Refer to
1991 ;; the customization of your Emacs (try ``M-x customize``).
1993 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1996 (defcustom rst-mode-hook nil
1997 "Hook run when Rst Mode is turned on. The hook for Text Mode is run before
2002 (defcustom rst-mode-lazy t
2003 "*If non-nil Rst Mode font-locks comment, literal blocks, and section titles
2004 correctly. Because this is really slow it switches on Lazy Lock Mode
2005 automatically. You may increase Lazy Lock Defer Time for reasonable results.
2007 If nil comments and literal blocks are font-locked only on the line they start.
2009 The value of this variable is used when Rst Mode is turned on."
2013 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2015 (defgroup rst-faces nil
"Faces used in Rst Mode"
2020 (defcustom rst-block-face
'font-lock-keyword-face
2021 "All syntax marking up a special block"
2025 (defcustom rst-external-face
'font-lock-type-face
2026 "Field names and interpreted text"
2030 (defcustom rst-definition-face
'font-lock-function-name-face
2031 "All other defining constructs"
2035 (defcustom rst-directive-face
2036 ;; XEmacs compatibility
2037 (if (boundp 'font-lock-builtin-face
)
2038 'font-lock-builtin-face
2039 'font-lock-preprocessor-face
)
2040 "Directives and roles"
2044 (defcustom rst-comment-face
'font-lock-comment-face
2049 (defcustom rst-emphasis1-face
2050 ;; XEmacs compatibility
2058 (defcustom rst-emphasis2-face
2059 ;; XEmacs compatibility
2067 (defcustom rst-literal-face
'font-lock-string-face
2072 (defcustom rst-reference-face
'font-lock-variable-name-face
2073 "References to a definition"
2077 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2079 (defgroup rst-faces-defaults nil
2080 "Values used to generate default faces for section titles on all levels.
2081 Tweak these if you are content with how section title faces are built in
2082 general but you do not like the details."
2086 (defun rst-define-level-faces ()
2087 "Define the faces for the section title text faces from the values."
2088 ;; All variables used here must be checked in `rst-set-level-default'
2090 (while (<= i rst-level-face-max
)
2091 (let ((sym (intern (format "rst-level-%d-face" i
)))
2092 (doc (format "Face for showing section title text at level %d" i
))
2093 (col (format (concat "%s" rst-level-face-format-light
)
2094 rst-level-face-base-color
2095 (+ (* (1- i
) rst-level-face-step-light
)
2096 rst-level-face-base-light
))))
2097 (make-empty-face sym
)
2098 (set-face-doc-string sym doc
)
2099 (set-face-background sym col
)
2103 (defun rst-set-level-default (sym val
)
2104 "Set a customized value affecting section title text face and recompute the
2106 (custom-set-default sym val
)
2107 ;; Also defines the faces initially when all values are available
2108 (and (boundp 'rst-level-face-max
)
2109 (boundp 'rst-level-face-format-light
)
2110 (boundp 'rst-level-face-base-color
)
2111 (boundp 'rst-level-face-step-light
)
2112 (boundp 'rst-level-face-base-light
)
2113 (rst-define-level-faces)))
2115 ;; Faces for displaying items on several levels; these definitions define
2116 ;; different shades of grey where the lightest one (i.e. least contrasting) is
2118 (defcustom rst-level-face-max
6
2119 "Maximum depth of levels for which section title faces are defined."
2120 :group
'rst-faces-defaults
2122 :set
'rst-set-level-default
)
2123 (defcustom rst-level-face-base-color
"grey"
2124 "The base name of the color to be used for creating background colors in
2125 ection title faces for all levels."
2126 :group
'rst-faces-defaults
2128 :set
'rst-set-level-default
)
2129 (defcustom rst-level-face-base-light
2130 (if (eq frame-background-mode
'dark
)
2133 "The lightness factor for the base color. This value is used for level 1. The
2134 default depends on whether the value of `frame-background-mode' is `dark' or
2136 :group
'rst-faces-defaults
2138 :set
'rst-set-level-default
)
2139 (defcustom rst-level-face-format-light
"%2d"
2140 "The format for the lightness factor appended to the base name of the color.
2141 This value is expanded by `format' with an integer."
2142 :group
'rst-faces-defaults
2144 :set
'rst-set-level-default
)
2145 (defcustom rst-level-face-step-light
2146 (if (eq frame-background-mode
'dark
)
2149 "The step width to use for the next color. The formula
2151 `rst-level-face-base-light'
2152 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
2154 must result in a color level which appended to `rst-level-face-base-color'
2155 using `rst-level-face-format-light' results in a valid color such as `grey50'.
2156 This color is used as background for section title text on level
2157 `rst-level-face-max'."
2158 :group
'rst-faces-defaults
2160 :set
'rst-set-level-default
)
2162 (defcustom rst-adornment-faces-alist
2163 (let ((alist '((t . font-lock-keyword-face
)
2164 (nil . font-lock-keyword-face
)))
2166 (while (<= i rst-level-face-max
)
2167 (nconc alist
(list (cons i
(intern (format "rst-level-%d-face" i
)))))
2170 "Provides faces for the various adornment types. Key is a number (for the
2171 section title text of that level), t (for transitions) or nil (for section
2172 title adornment). If you generally do not like how section title text faces are
2173 set up tweak here. If the general idea is ok for you but you do not like the
2174 details check the Rst Faces Defaults group."
2181 "Section level (may not be bigger than `rst-level-face-max')")
2182 (boolean :tag
"transitions (on) / section title adornment (off)"))
2184 :set-after
'(rst-level-face-max))
2186 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2188 ;; FIXME: Code from `restructuredtext.el' should be integrated
2190 (defvar rst-mode-syntax-table nil
2191 "Syntax table used while in rst mode.")
2193 (unless rst-mode-syntax-table
2194 (setq rst-mode-syntax-table
(make-syntax-table text-mode-syntax-table
))
2195 (modify-syntax-entry ?$
"." rst-mode-syntax-table
)
2196 (modify-syntax-entry ?%
"." rst-mode-syntax-table
)
2197 (modify-syntax-entry ?
& "." rst-mode-syntax-table
)
2198 (modify-syntax-entry ?
' "." rst-mode-syntax-table
)
2199 (modify-syntax-entry ?
* "." rst-mode-syntax-table
)
2200 (modify-syntax-entry ?
+ "." rst-mode-syntax-table
)
2201 (modify-syntax-entry ?.
"_" rst-mode-syntax-table
)
2202 (modify-syntax-entry ?
/ "." rst-mode-syntax-table
)
2203 (modify-syntax-entry ?
< "." rst-mode-syntax-table
)
2204 (modify-syntax-entry ?
= "." rst-mode-syntax-table
)
2205 (modify-syntax-entry ?
> "." rst-mode-syntax-table
)
2206 (modify-syntax-entry ?
\\ "\\" rst-mode-syntax-table
)
2207 (modify-syntax-entry ?|
"." rst-mode-syntax-table
)
2208 (modify-syntax-entry ?_
"." rst-mode-syntax-table
)
2211 (defvar rst-mode-abbrev-table nil
2212 "Abbrev table used while in rst mode.")
2213 (define-abbrev-table 'rst-mode-abbrev-table
())
2215 ;; FIXME: Movement keys to skip forward / backward over or mark an indented
2216 ;; block could be defined; keys to markup section titles based on
2217 ;; `rst-adornment-level-alist' would be useful
2218 (defvar rst-mode-map nil
2219 "Keymap for rst mode. This inherits from Text mode.")
2221 (unless rst-mode-map
2222 (setq rst-mode-map
(copy-keymap text-mode-map
)))
2225 "Major mode for editing reStructuredText documents.
2227 You may customize `rst-mode-lazy' to switch font-locking of blocks.
2230 Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
2233 (kill-all-local-variables)
2236 (use-local-map rst-mode-map
)
2237 (setq local-abbrev-table rst-mode-abbrev-table
)
2238 (set-syntax-table rst-mode-syntax-table
)
2242 ;; FIXME: It would be better if this matches more exactly the start of a reST
2243 ;; paragraph; however, this not always possible with a simple regex because
2244 ;; paragraphs are determined by indentation of the following line
2245 (set (make-local-variable 'paragraph-start
)
2246 (concat page-delimiter
"\\|[ \t]*$"))
2247 (if (eq ?^
(aref paragraph-start
0))
2248 (setq paragraph-start
(substring paragraph-start
1)))
2249 (set (make-local-variable 'paragraph-separate
) paragraph-start
)
2250 (set (make-local-variable 'indent-line-function
) 'indent-relative-maybe
)
2251 (set (make-local-variable 'adaptive-fill-mode
) t
)
2252 (set (make-local-variable 'comment-start
) ".. ")
2254 ;; Special variables
2255 (make-local-variable 'rst-adornment-level-alist
)
2258 (set (make-local-variable 'font-lock-defaults
)
2259 '(rst-font-lock-keywords-function
2261 (font-lock-multiline . t
)
2262 (font-lock-mark-block-function . mark-paragraph
)))
2263 (when (boundp 'font-lock-support-mode
)
2264 ;; rst-mode has its own mind about font-lock-support-mode
2265 (make-local-variable 'font-lock-support-mode
)
2267 ((and (not rst-mode-lazy
) (not font-lock-support-mode
)))
2268 ;; No support mode set and none required - leave it alone
2269 ((or (not font-lock-support-mode
) ;; No support mode set (but required)
2270 (symbolp font-lock-support-mode
)) ;; or a fixed mode for all
2271 (setq font-lock-support-mode
2272 (list (cons 'rst-mode
(and rst-mode-lazy
'lazy-lock-mode
))
2273 (cons t font-lock-support-mode
))))
2274 ((and (listp font-lock-support-mode
)
2275 (not (assoc 'rst-mode font-lock-support-mode
)))
2276 ;; A list of modes missing rst-mode
2277 (setq font-lock-support-mode
2278 (append '((cons 'rst-mode
(and rst-mode-lazy
'lazy-lock-mode
)))
2279 font-lock-support-mode
)))))
2282 (setq mode-name
"reST")
2283 (setq major-mode
'rst-mode
)
2284 (run-hooks 'text-mode-hook
)
2285 (run-hooks 'rst-mode-hook
))
2287 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2290 (defun rst-font-lock-keywords-function ()
2291 "Returns keywords to highlight in rst mode according to current settings."
2292 ;; The reST-links in the comments below all relate to sections in
2293 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
2294 (let* ( ;; This gets big - so let's define some abbreviations
2295 ;; horizontal white space
2297 ;; beginning of line with possible indentation
2298 (re-bol (concat "^" re-hws
"*"))
2299 ;; Separates block lead-ins from their content
2300 (re-blksep1 (concat "\\(" re-hws
"+\\|$\\)"))
2301 ;; explicit markup tag
2303 ;; explicit markup start
2304 (re-ems (concat re-emt re-hws
"+"))
2305 ;; inline markup prefix
2306 (re-imp1 (concat "\\(^\\|" re-hws
"\\|[-'\"([{</:]\\)"))
2307 ;; inline markup suffix
2308 (re-ims1 (concat "\\(" re-hws
"\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
2310 (re-sym1 "\\(\\sw\\|\\s_\\)")
2311 ;; inline markup content begin
2312 (re-imbeg2 "\\(\\S \\|\\S \\([^")
2314 ;; There seems to be a bug leading to error "Stack overflow in regexp
2315 ;; matcher" when "|" or "\\*" are the characters searched for
2317 (if (< emacs-major-version
21)
2320 ;; inline markup content end
2321 (re-imend (concat re-imendbeg
"\\)*[^\t \\\\]\\)"))
2322 ;; inline markup content without asterisk
2323 (re-ima2 (concat re-imbeg2
"*" re-imend
))
2324 ;; inline markup content without backquote
2325 (re-imb2 (concat re-imbeg2
"`" re-imend
))
2326 ;; inline markup content without vertical bar
2327 (re-imv2 (concat re-imbeg2
"|" re-imend
))
2328 ;; Supported URI schemes
2329 (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\\)")
2330 ;; Line starting with adornment and optional whitespace; complete
2331 ;; adornment is in (match-string 1); there must be at least 3
2332 ;; characters because otherwise explicit markup start would be
2334 (re-ado2 (concat "^\\(\\(["
2336 (< emacs-major-version
21)
2338 (string-match "XEmacs\\|Lucid" emacs-version
)))
2339 "^a-zA-Z0-9 \t\x00-\x1F"
2340 "^[:word:][:space:][:cntrl:]")
2341 "]\\)\\2\\2+\\)" re-hws
"*$"))
2344 ;; FIXME: Block markup is not recognized in blocks after explicit markup
2347 ;; Simple `Body Elements`_
2350 (concat re-bol
"\\([-*+]" re-blksep1
"\\)")
2352 ;; `Enumerated Lists`_
2354 (concat re-bol
"\\((?\\([0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
2357 ;; `Definition Lists`_ FIXME: missing
2360 (concat re-bol
"\\(:[^:]+:\\)" re-blksep1
)
2361 1 rst-external-face
)
2364 (concat re-bol
"\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
2365 "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
2368 ;; `Tables`_ FIXME: missing
2370 ;; All the `Explicit Markup Blocks`_
2371 ;; `Footnotes`_ / `Citations`_
2373 (concat re-bol
"\\(" re-ems
"\\[[^[]+\\]\\)" re-blksep1
)
2374 1 rst-definition-face
)
2375 ;; `Directives`_ / `Substitution Definitions`_
2377 (concat re-bol
"\\(" re-ems
"\\)\\(\\(|[^|]+|[\t ]+\\)?\\)\\("
2378 re-sym1
"+::\\)" re-blksep1
)
2379 (list 1 rst-directive-face
)
2380 (list 2 rst-definition-face
)
2381 (list 4 rst-directive-face
))
2382 ;; `Hyperlink Targets`_
2384 (concat re-bol
"\\(" re-ems
"_\\([^:\\`]\\|\\\\.\\|`[^`]+`\\)+:\\)"
2386 1 rst-definition-face
)
2388 (concat re-bol
"\\(__\\)" re-blksep1
)
2389 1 rst-definition-face
)
2391 ;; All `Inline Markup`_
2392 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
2393 ;; `Strong Emphasis`_
2395 (concat re-imp1
"\\(\\*\\*" re-ima2
"\\*\\*\\)" re-ims1
)
2396 2 rst-emphasis2-face
)
2399 (concat re-imp1
"\\(\\*" re-ima2
"\\*\\)" re-ims1
)
2400 2 rst-emphasis1-face
)
2401 ;; `Inline Literals`_
2403 (concat re-imp1
"\\(``" re-imb2
"``\\)" re-ims1
)
2405 ;; `Inline Internal Targets`_
2407 (concat re-imp1
"\\(_`" re-imb2
"`\\)" re-ims1
)
2408 2 rst-definition-face
)
2409 ;; `Hyperlink References`_
2410 ;; FIXME: `Embedded URIs`_ not considered
2412 (concat re-imp1
"\\(\\(`" re-imb2
"`\\|\\sw+\\)__?\\)" re-ims1
)
2413 2 rst-reference-face
)
2414 ;; `Interpreted Text`_
2416 (concat re-imp1
"\\(\\(:" re-sym1
"+:\\)?\\)\\(`" re-imb2
"`\\)\\(\\(:"
2417 re-sym1
"+:\\)?\\)" re-ims1
)
2418 (list 2 rst-directive-face
)
2419 (list 5 rst-external-face
)
2420 (list 8 rst-directive-face
))
2421 ;; `Footnote References`_ / `Citation References`_
2423 (concat re-imp1
"\\(\\[[^]]+\\]_\\)" re-ims1
)
2424 2 rst-reference-face
)
2425 ;; `Substitution References`_
2427 (concat re-imp1
"\\(|" re-imv2
"|\\)" re-ims1
)
2428 2 rst-reference-face
)
2429 ;; `Standalone Hyperlinks`_
2431 ;; FIXME: This takes it easy by using a whitespace as delimiter
2432 (concat re-imp1
"\\(" re-uris1
":\\S +\\)" re-ims1
)
2433 2 rst-definition-face
)
2435 (concat re-imp1
"\\(" re-sym1
"+@" re-sym1
"+\\)" re-ims1
)
2436 2 rst-definition-face
)
2438 ;; Do all block fontification as late as possible so 'append works
2440 ;; Sections_ / Transitions_
2444 (if (not rst-mode-lazy
)
2445 (list 1 rst-block-face
)
2447 (list 'rst-font-lock-handle-adornment
2449 (setq rst-font-lock-adornment-point
(match-end 1))
2452 (list 1 '(cdr (assoc nil rst-adornment-faces-alist
))
2454 (list 2 '(cdr (assoc rst-font-lock-level
2455 rst-adornment-faces-alist
))
2457 (list 3 '(cdr (assoc nil rst-adornment-faces-alist
))
2463 (concat re-bol
"\\(" re-ems
"\\)\[^[|_]\\([^:]\\|:\\([^:]\\|$\\)\\)*$")
2464 (list 1 rst-comment-face
))
2467 (list 'rst-font-lock-find-unindented-line
2469 (setq rst-font-lock-indentation-point
(match-end 1))
2472 (list 0 rst-comment-face
'append
)))))
2475 (concat re-bol
"\\(" re-emt
"\\)\\(\\s *\\)\\?$")
2476 (list 1 rst-comment-face
)
2477 (list 2 rst-comment-face
))
2480 (list 'rst-font-lock-find-unindented-line
2482 (setq rst-font-lock-indentation-point
'next
)
2485 (list 0 rst-comment-face
'append
)))))
2487 ;; `Literal Blocks`_
2490 (concat re-bol
"\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
2491 (list 3 rst-block-face
))
2494 (list 'rst-font-lock-find-unindented-line
2496 (setq rst-font-lock-indentation-point t
)
2499 (list 0 rst-literal-face
'append
)))))
2502 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2505 (defun rst-forward-indented-block (&optional column limit
)
2506 "Move forward across one indented block.
2507 Find the next non-empty line which is not indented at least to COLUMN (defaults
2508 to the column of the point). Moves point to first character of this line or the
2509 first empty line immediately before it and returns that position. If there is
2510 no such line before LIMIT (defaults to the end of the buffer) returns nil and
2511 point is not moved."
2513 (let ((clm (or column
(current-column)))
2517 (setq limit
(point-max)))
2519 (while (and (not fnd
) (< (point) limit
))
2521 (when (< (point) limit
)
2523 (if (looking-at "\\s *$")
2524 (setq cand
(or cand beg
)) ; An empty line is a candidate
2525 (move-to-column clm
)
2526 ;; FIXME: No indentation [(zerop clm)] must be handled in some
2527 ;; useful way - though it is not clear what this should mean at all
2529 "^\\s *$" (buffer-substring-no-properties beg
(point)))
2530 (setq cand nil
) ; An indented line resets a candidate
2531 (setq fnd
(or cand beg
)))))))
2532 (goto-char (or fnd start
))
2535 ;; Stores the point where the current indentation ends if a number. If `next'
2536 ;; indicates `rst-font-lock-find-unindented-line' shall take the indentation
2537 ;; from the next line if this is not empty. If non-nil indicates
2538 ;; `rst-font-lock-find-unindented-line' shall take the indentation from the
2539 ;; next non-empty line. Also used as a trigger for
2540 ;; `rst-font-lock-find-unindented-line'.
2541 (defvar rst-font-lock-indentation-point nil
)
2543 (defun rst-font-lock-find-unindented-line (limit)
2544 (let* ((ind-pnt rst-font-lock-indentation-point
)
2546 ;; May run only once - enforce this
2547 (setq rst-font-lock-indentation-point nil
)
2548 (when (and ind-pnt
(not (numberp ind-pnt
)))
2549 ;; Find indentation point in next line if any
2553 (if (eq ind-pnt
'next
)
2554 (when (and (zerop (forward-line 1)) (< (point) limit
))
2555 (setq beg-pnt
(point))
2556 (when (not (looking-at "\\s *$"))
2557 (looking-at "\\s *")
2559 (while (and (zerop (forward-line 1)) (< (point) limit
)
2560 (looking-at "\\s *$")))
2561 (when (< (point) limit
)
2562 (setq beg-pnt
(point))
2563 (looking-at "\\s *")
2567 ;; Always succeeds because the limit set by PRE-MATCH-FORM is the
2568 ;; ultimate point to find
2569 (goto-char (or (rst-forward-indented-block nil limit
) limit
))
2570 (set-match-data (list beg-pnt
(point)))
2573 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2576 ;; Stores the point where the current adornment ends. Also used as a trigger
2577 ;; for `rst-font-lock-handle-adornment'.
2578 (defvar rst-font-lock-adornment-point nil
)
2580 ;; Here `rst-font-lock-handle-adornment' stores the section level of the
2581 ;; current adornment or t for a transition.
2582 (defvar rst-font-lock-level nil
)
2584 ;; FIXME: It would be good if this could be used to markup section titles of
2585 ;; given level with a special key; it would be even better to be able to
2586 ;; customize this so it can be used for a generally available personal style
2588 ;; FIXME: There should be some way to reset and reload this variable - probably
2591 ;; FIXME: Some support for `outline-mode' would be nice which should be based
2592 ;; on this information
2593 (defvar rst-adornment-level-alist nil
2594 "Associates adornments with section levels.
2595 The key is a two character string. The first character is the adornment
2596 character. The second character distinguishes underline section titles (`u')
2597 from overline/underline section titles (`o'). The value is the section level.
2599 This is made buffer local on start and adornments found during font lock are
2602 ;; Returns section level for adornment key KEY. Adds new section level if KEY
2603 ;; is not found and ADD. If KEY is not a string it is simply returned.
2604 (defun rst-adornment-level (key &optional add
)
2605 (let ((fnd (assoc key rst-adornment-level-alist
))
2608 ((not (stringp key
))
2613 (while (rassoc new rst-adornment-level-alist
)
2614 (setq new
(1+ new
)))
2615 (setq rst-adornment-level-alist
2616 (append rst-adornment-level-alist
(list (cons key new
))))
2619 ;; Classifies adornment for section titles and transitions. ADORNMENT is the
2620 ;; complete adornment string as found in the buffer. END is the point after the
2621 ;; last character of ADORNMENT. For overline section adornment LIMIT limits the
2622 ;; search for the matching underline. Returns a list. The first entry is t for
2623 ;; a transition, or a key string for `rst-adornment-level' for a section title.
2624 ;; The following eight values forming four match groups as can be used for
2625 ;; `set-match-data'. First match group contains the maximum points of the whole
2626 ;; construct. Second and last match group matched pure section title adornment
2627 ;; while third match group matched the section title text or the transition.
2628 ;; Each group but the first may or may not exist.
2629 (defun rst-classify-adornment (adornment end limit
)
2633 (let ((ado-ch (aref adornment
0))
2634 (ado-re (regexp-quote adornment
))
2641 (or (not (zerop (forward-line 1)))
2642 (looking-at "\\s *$"))))
2645 (or (not (zerop (forward-line -
1)))
2646 (looking-at "\\s *$"))))
2647 key beg-ovr end-ovr beg-txt end-txt beg-und end-und
)
2649 ((and nxt-emp prv-emp
)
2652 (setq beg-txt beg-pnt
)
2653 (setq end-txt end-pnt
))
2656 (setq key
(concat (list ado-ch
) "o"))
2657 (setq beg-ovr beg-pnt
)
2658 (setq end-ovr end-pnt
)
2660 (setq beg-txt
(point))
2661 (while (and (< (point) limit
) (not end-txt
))
2662 (if (looking-at "\\s *$")
2663 ;; No underline found
2664 (setq end-txt
(1- (point)))
2665 (when (looking-at (concat "\\(" ado-re
"\\)\\s *$"))
2666 (setq end-und
(match-end 1))
2667 (setq beg-und
(point))
2668 (setq end-txt
(1- beg-und
))))
2672 (setq key
(concat (list ado-ch
) "u"))
2673 (setq beg-und beg-pnt
)
2674 (setq end-und end-pnt
)
2675 (setq end-txt
(1- beg-und
))
2676 (setq beg-txt
(progn
2677 (if (re-search-backward "^\\s *$" 1 'move
)
2681 (or beg-ovr beg-txt beg-und
)
2682 (or end-und end-txt end-und
)
2683 beg-ovr end-ovr beg-txt end-txt beg-und end-und
)))))
2685 ;; Handles adornments for font-locking section titles and transitions. Returns
2686 ;; three match groups. First and last match group matched pure overline /
2687 ;; underline adornment while second group matched section title text. Each
2688 ;; group may not exist.
2689 (defun rst-font-lock-handle-adornment (limit)
2690 (let ((ado-pnt rst-font-lock-adornment-point
))
2691 ;; May run only once - enforce this
2692 (setq rst-font-lock-adornment-point nil
)
2694 (let* ((ado (rst-classify-adornment (match-string-no-properties 1)
2698 (setq rst-font-lock-level
(rst-adornment-level key t
))
2699 (goto-char (nth 1 mtc
))
2700 (set-match-data mtc
)
2703 ;;; rst-mode.el ends here
2707 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2708 ;; Support for conversion from within Emacs
2710 (defgroup rst-compile nil
2711 "Settings for support of conversion of reStructuredText
2712 document with \\[rst-compile]."
2716 (defvar rst-compile-toolsets
2717 '((html .
("rst2html.py" ".html" nil
))
2718 (latex .
("rst2latex.py" ".tex" nil
))
2719 (newlatex .
("rst2newlatex.py" ".tex" nil
))
2720 (pseudoxml .
("rst2pseudoxml.py" ".xml" nil
))
2721 (xml .
("rst2xml.py" ".xml" nil
)))
2722 "An association list of the toolset to a list of the (command to use,
2723 extension of produced filename, options to the tool (nil or a
2724 string)) to be used for converting the document.")
2726 ;; Note for Python programmers not familiar with association lists: you can set
2727 ;; values in an alists like this, e.g. :
2728 ;; (setcdr (assq 'html rst-compile-toolsets)
2729 ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
2732 (defvar rst-compile-primary-toolset
'html
2733 "The default toolset for rst-compile.")
2735 (defvar rst-compile-secondary-toolset
'latex
2736 "The default toolset for rst-compile with a prefix argument.")
2738 (defun rst-compile-find-conf ()
2739 "Look for the configuration file in the parents of the current path."
2741 (let ((file-name "docutils.conf")
2742 (buffer-file (buffer-file-name)))
2743 ;; Move up in the dir hierarchy till we find a change log file.
2744 (let ((dir (file-name-directory buffer-file
)))
2745 (while (and (or (not (string= "/" dir
)) (setq dir nil
) nil
)
2746 (not (file-exists-p (concat dir file-name
))))
2747 ;; Move up to the parent dir and try again.
2748 (setq dir
(expand-file-name (file-name-directory
2749 (directory-file-name
2750 (file-name-directory dir
))))) )
2751 (or (and dir
(concat dir file-name
)) nil
)
2757 (defun rst-compile (&optional pfxarg
)
2758 "Compile command to convert reST document into some output file.
2759 Attempts to find configuration file, if it can, overrides the
2762 ;; Note: maybe we want to check if there is a Makefile too and not do anything
2763 ;; if that is the case. I dunno.
2764 (let* ((toolset (cdr (assq (if pfxarg
2765 rst-compile-secondary-toolset
2766 rst-compile-primary-toolset
)
2767 rst-compile-toolsets
)))
2768 (command (car toolset
))
2769 (extension (cadr toolset
))
2770 (options (caddr toolset
))
2771 (conffile (rst-compile-find-conf))
2772 (bufname (file-name-nondirectory buffer-file-name
))
2773 (outname (file-name-sans-extension bufname
)))
2775 ;; Set compile-command before invocation of compile.
2776 (set (make-local-variable 'compile-command
)
2777 (mapconcat 'identity
2781 (concat "--config=\"" conffile
"\"")
2784 (concat outname extension
))
2787 ;; Invoke the compile command.
2788 (if (or compilation-read-command current-prefix-arg
)
2789 (call-interactively 'compile
)
2790 (compile compile-command
))
2795 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2797 ;; Generic text functions that are more convenient than the defaults.
2800 (defun replace-lines (fromchar tochar
)
2801 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
2802 with equal-length lines of TOCHAR."
2804 cSearch for flush-left lines of char:
2805 cand replace with char: ")
2807 (let* ((fromstr (string fromchar
))
2808 (searchre (concat "^" (regexp-quote fromstr
) "+ *$"))
2812 (search-forward-regexp searchre
)
2813 (setq found
(1+ found
))
2814 (search-backward fromstr
) ;; point will be *before* last char
2815 (setq p
(1+ (point)))
2817 (setq l
(- p
(point)))
2819 (insert-char tochar l
))
2821 (message (format "%d lines replaced." found
)))))))
2823 (defun join-paragraph ()
2824 "Join lines in current paragraph into one line, removing end-of-lines."
2826 (let ((fill-column 65000)) ; some big number
2827 (call-interactively 'fill-paragraph
)))
2829 ;; FIXME: can we remove this?
2830 (defun force-fill-paragraph ()
2831 "Fill paragraph at point, first joining the paragraph's lines into one.
2832 This is useful for filling list item paragraphs."
2835 (fill-paragraph nil
))
2838 ;; Generic character repeater function.
2839 ;; For sections, better to use the specialized function above, but this can
2840 ;; be useful for creating separators.
2841 (defun repeat-last-character (&optional tofill
)
2842 "Fills the current line up to the length of the preceding line (if not
2843 empty), using the last character on the current line. If the preceding line is
2844 empty, we use the fill-column.
2846 If a prefix argument is provided, use the next line rather than the preceding
2849 If the current line is longer than the desired length, shave the characters off
2850 the current line to fit the desired length.
2852 As an added convenience, if the command is repeated immediately, the alternative
2853 column is used (fill-column vs. end of previous/next line)."
2855 (let* ((curcol (current-column))
2856 (curline (+ (count-lines (point-min) (point))
2857 (if (eq curcol
0) 1 0)))
2858 (lbp (line-beginning-position 0))
2859 (prevcol (if (and (= curline
1) (not current-prefix-arg
))
2862 (forward-line (if current-prefix-arg
1 -
1))
2864 (skip-chars-backward " \t" lbp
)
2865 (let ((cc (current-column)))
2866 (if (= cc
0) fill-column cc
)))))
2868 (cond (tofill fill-column
)
2869 ((equal last-command
'repeat-last-character
)
2870 (if (= curcol fill-column
) prevcol fill-column
))
2872 (if (= prevcol
0) fill-column prevcol
)))
2875 (if (> (current-column) rightmost-column
)
2876 ;; shave characters off the end
2877 (delete-region (- (point)
2878 (- (current-column) rightmost-column
))
2880 ;; fill with last characters
2881 (insert-char (preceding-char)
2882 (- rightmost-column
(current-column))))
2888 ;;; rst.el ends here