Corrected funky behaviour of rst-shift-region when something like this appears before...
[docutils.git] / tools / editors / emacs / rst.el
blobca6bf09178fae7471513070aefb05ea5703ba21d
1 ;;; ================================================
2 ;;; rst.el -- ReStructuredText Support for Emacs
3 ;;; ================================================
4 ;;;
5 ;;; :Authors: Martin Blais <blais@furius.ca>,
6 ;;; Stefan Merten <smerten@oekonux.de>,
7 ;;; David Goodger <goodger@python.org>
8 ;;; :Revision: $Revision$
9 ;;; :Date: $Date$
10 ;;; :Copyright: 2003-2006 by Martin Blais, Stefan Merten, and David Goodger.
11 ;;; :License:
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.
15 ;;;
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.
20 ;;;
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.
25 ;;;
26 ;;; :Abstract:
27 ;;; Support code for editing reStructuredText with Emacs. The latest
28 ;;; version of this file lies in the docutils source code repository.
29 ;;;
30 ;;; Description
31 ;;; ===========
32 ;;;
33 ;;; Basically, this package contains:
34 ;;;
35 ;;; - Functions to automatically adjust and cycle the section underline
36 ;;; decorations;
37 ;;; - A mode that displays the table of contents and allows you to jump anywhere
38 ;;; from it;
39 ;;; - Functions to insert and automatically update a TOC in your source
40 ;;; document;
41 ;;; - A mode which supports font-lock highlighting of reStructuredText
42 ;;; structures;
43 ;;; - Some other convenience functions.
44 ;;;
45 ;;; See the accompanying document in the docutils documentation about
46 ;;; the contents of this package and how to use it.
47 ;;;
48 ;;; For more information about reStructuredText, see
49 ;;; http://docutils.sourceforge.net/rst.html
50 ;;;
51 ;;; For full details on how to use the contents of this file, see
52 ;;; http://docutils.sourceforge.net/docs/user/emacs.html
53 ;;;
54 ;;; Download
55 ;;; ========
56 ;;;
57 ;;; Click `Here <rst.el>`_ for download.
58 ;;;
59 ;;; END
61 ;; **IMPORTANT NOTE TO PACKAGERS**: this package is the result of merging:
63 ;; - restructuredtext.el
64 ;; - rst-mode.el
65 ;; - rst-html.el
67 ;; Those files are now OBSOLETE and have been replaced by this single package
68 ;; file (2005-10-30).
70 ;; Installation instructions
71 ;; -------------------------
73 ;; Add this line to your .emacs file and bind the versatile sectioning commands
74 ;; in text mode, like this::
76 ;; (require 'rst)
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.
97 ;; C-c p t: rst-toc
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
105 ;; cursor is.
107 ;; C-c p u: rst-toc-insert-update
109 ;; Find an existing inserted table-of-contents in the document an
110 ;; updates it.
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)
136 ;; rst-mode
137 ;; --------
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.
162 ;; TODO list
163 ;; =========
165 ;; Bindings
166 ;; --------
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
169 ;; the Macs.
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.
183 ;; - numbering: automatically detect if we have a section-numbering directive in
184 ;; the corresponding section, to render the toc
186 ;; bulleted and enumerated list items
187 ;; ----------------------------------
188 ;; - We need to provide way to rebullet bulleted lists, and that would include
189 ;; automatic enumeration as well.
191 ;; rst-mode
192 ;; --------
193 ;; - Look at the possibility of converting rst-mode from a Major mode to a Minor
194 ;; mode of text-mode.
196 ;; Other
197 ;; -----
198 ;; - lazy-lock is obsolete, we should look at placing the require conditionally
199 ;; and doing the appropriate setup for font-lock.
200 ;; - We should rename "adornment" to "decoration" or vice-versa in this
201 ;; document.
202 ;; - Add an option to forego using the file structure in order to make
203 ;; suggestion, and to always use the preferred decorations to do that.
204 ;; - We need to automatically recenter on rst-forward-section movment commands.
209 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
210 ;; Bindings and hooks
212 (defgroup rst nil "Support for reStructuredText documents"
213 :group 'wp
214 :version "21.1"
215 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
217 (defun rst-toc-or-hierarchy ()
218 "Binding for either TOC or decorations hierarchy."
219 (interactive)
220 (if (not current-prefix-arg)
221 (rst-toc)
222 (rst-display-decorations-hierarchy)))
224 ;; Define a prefix map for the long form of key combinations.
225 (defvar rst-prefix-map (make-sparse-keymap)
226 "Keymap for rst commands.")
228 (dolist (m `(("a" . rst-adjust)
229 ("=" . rst-adjust)
230 ("t" . rst-toc)
231 ("i" . rst-toc-insert)
232 ("+" . rst-toc-insert)
233 ("u" . rst-toc-insert-update)
234 ("h" . rst-display-decorations-hierarchy)
235 ("s" . rst-straighten-decorations)
236 ("p" . rst-backward-section)
237 ("n" . rst-forward-section)
238 ("r" . rst-shift-region-right)
239 ("l" . rst-shift-region-left)
240 ("e" . rst-enumerate-region)
241 ("b" . rst-line-block-region)
242 ("c" . rst-compile)
243 ("C" . ,(lambda () (interactive) (rst-compile t)))))
244 (define-key rst-prefix-map (car m) (cdr m)))
248 (defun rst-text-mode-bindings ()
249 "Default text mode hook for rest."
251 ;; Direct command (somehow this one does not work on the Mac).
252 (local-set-key [(control ?=)] 'rst-adjust)
254 (define-key mode-specific-map [(control p)] 'rst-backward-section)
255 (define-key mode-specific-map [(control n)] 'rst-forward-section)
256 (define-key mode-specific-map [(control r)] 'rst-shift-region-right)
257 (define-key mode-specific-map [(control l)] 'rst-shift-region-left)
259 ;; Bind the rst commands on the C-c p prefix.
260 (define-key mode-specific-map [(p)] rst-prefix-map)
264 ;; Note: we cannot bind the TOC update on file write because it messes with
265 ;; undo. If we disable undo, since it adds and removes characters, the
266 ;; positions in the undo list are not making sense anymore. Dunno what to do
267 ;; with this, it would be nice to update when saving.
269 ;; (add-hook 'write-contents-hooks 'rst-toc-insert-update-fun)
270 ;; (defun rst-toc-insert-update-fun ()
271 ;; ;; Disable undo for the write file hook.
272 ;; (let ((buffer-undo-list t)) (rst-toc-insert-update) ))
275 ;; Additional abbreviations for text-mode.
276 (define-abbrev text-mode-abbrev-table
277 "con" ".. contents::\n..\n " nil 0)
280 ;; Paragraph separation customization. This will work better for
281 ;; bullet and enumerated lists in restructuredtext documents and
282 ;; should not affect filling for other documents too much. Set it up
283 ;; like this:
285 ;; (add-hook 'text-mode-hook 'rst-set-paragraph-separation)
286 (defvar rst-extra-paragraph-start
287 "\\|[ \t]*\\([-+*] \\|[0-9]+\\. \\)"
288 "Extra parapraph-separate patterns to add for text-mode.")
289 ;; FIXME: What about the missing >?
290 ;; The author uses a hardcoded for paragraph-separate: "\f\\|>*[ \t]*$"
292 (defun rst-set-paragraph-separation ()
293 "Sets the paragraph separation for restructuredtext."
294 ;; FIXME: the variable should be made automatically buffer local rather than
295 ;; using a function here, this function is unnecessary.
296 (make-local-variable 'paragraph-start) ; prevent it growing every time
297 (setq paragraph-start (concat paragraph-start rst-extra-paragraph-start)))
299 ;; FIXME: What about paragraph-separate? paragraph-start and paragraph-separate
300 ;; are different. The author hardcodes the value to
301 ;; "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. "
303 ;; FIXME: the variables above are in limbo and need some fixing.
307 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
308 ;; Support functions
310 (require 'cl)
312 ;; Generic Filter function.
313 (unless (fboundp 'filter)
314 (defun filter (pred list)
315 "Returns a list of all the elements fulfilling the pred requirement (that
316 is for which (pred elem) is true)"
317 (if list
318 (let ((head (car list))
319 (tail (filter pred (cdr list))))
320 (if (funcall pred head)
321 (cons head tail)
322 tail)))))
325 ;; From emacs-22
326 (unless (fboundp 'line-number-at-pos)
327 (defun line-number-at-pos (&optional pos)
328 "Return (narrowed) buffer line number at position POS.
329 If POS is nil, use current buffer location."
330 (let ((opoint (or pos (point))) start)
331 (save-excursion
332 (goto-char (point-min))
333 (setq start (point))
334 (goto-char opoint)
335 (forward-line 0)
336 (1+ (count-lines start (point)))))) )
340 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
341 ;; Section Decoration Adjusment
342 ;; ============================
344 ;; The following functions implement a smart automatic title sectioning feature.
345 ;; The idea is that with the cursor sitting on a section title, we try to get as
346 ;; much information from context and try to do the best thing automatically.
347 ;; This function can be invoked many times and/or with prefix argument to rotate
348 ;; between the various sectioning decorations.
350 ;; Definitions: the two forms of sectioning define semantically separate section
351 ;; levels. A sectioning DECORATION consists in:
353 ;; - a CHARACTER
355 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
357 ;; - an INDENT (meaningful for the over-and-under style only) which determines
358 ;; how many characters and over-and-under style is hanging outside of the
359 ;; title at the beginning and ending.
361 ;; Important note: an existing decoration must be formed by at least two
362 ;; characters to be recognized.
364 ;; Here are two examples of decorations (| represents the window border, column
365 ;; 0):
367 ;; |
368 ;; 1. char: '-' e |Some Title
369 ;; style: simple |----------
370 ;; |
371 ;; 2. char: '=' |==============
372 ;; style: over-and-under | Some Title
373 ;; indent: 2 |==============
374 ;; |
376 ;; Some notes:
378 ;; - The underlining character that is used depends on context. The file is
379 ;; scanned to find other sections and an appropriate character is selected.
380 ;; If the function is invoked on a section that is complete, the character is
381 ;; rotated among the existing section decorations.
383 ;; Note that when rotating the characters, if we come to the end of the
384 ;; hierarchy of decorations, the variable rst-preferred-decorations is
385 ;; consulted to propose a new underline decoration, and if continued, we cycle
386 ;; the decorations all over again. Set this variable to nil if you want to
387 ;; limit the underlining character propositions to the existing decorations in
388 ;; the file.
390 ;; - A prefix argument can be used to alternate the style.
392 ;; - An underline/overline that is not extended to the column at which it should
393 ;; be hanging is dubbed INCOMPLETE. For example::
395 ;; |Some Title
396 ;; |-------
398 ;; Examples of default invocation:
400 ;; |Some Title ---> |Some Title
401 ;; | |----------
403 ;; |Some Title ---> |Some Title
404 ;; |----- |----------
406 ;; | |------------
407 ;; | Some Title ---> | Some Title
408 ;; | |------------
410 ;; In over-and-under style, when alternating the style, a variable is
411 ;; available to select how much default indent to use (it can be zero). Note
412 ;; that if the current section decoration already has an indent, we don't
413 ;; adjust it to the default, we rather use the current indent that is already
414 ;; there for adjustment (unless we cycle, in which case we use the indent
415 ;; that has been found previously).
417 (defgroup rst-adjust nil
418 "Settings for adjustment and cycling of section title
419 decorations."
420 :group 'rst
421 :version "21.1")
423 (defcustom rst-preferred-decorations '( (?= over-and-under 1)
424 (?= simple 0)
425 (?- simple 0)
426 (?~ simple 0)
427 (?+ simple 0)
428 (?` simple 0)
429 (?# simple 0)
430 (?@ simple 0) )
431 "Preferred ordering of section title decorations. This
432 sequence is consulted to offer a new decoration suggestion when
433 we rotate the underlines at the end of the existing hierarchy
434 of characters, or when there is no existing section title in
435 the file."
436 :group 'rst-adjust)
439 (defcustom rst-default-indent 1
440 "Number of characters to indent the section title when toggling
441 decoration styles. This is used when switching from a simple
442 decoration style to a over-and-under decoration style."
443 :group 'rst-adjust)
446 (defvar rst-section-text-regexp "^[ \t]*\\S-*[a-zA-Z0-9]\\S-*"
447 "Regular expression for valid section title text.")
450 (defun rst-line-homogeneous-p (&optional accept-special)
451 "Predicate return the unique char if the current line is
452 composed only of a single repeated non-whitespace
453 character. This returns the char even if there is whitespace at
454 the beginning of the line.
456 If ACCEPT-SPECIAL is specified we do not ignore special sequences
457 which normally we would ignore when doing a search on many lines.
458 For example, normally we have cases to ignore commonly occuring
459 patterns, such as :: or ...; with the flag do not ignore them."
460 (save-excursion
461 (back-to-indentation)
462 (unless (looking-at "\n")
463 (let ((c (thing-at-point 'char)))
464 (if (and (looking-at (format "[%s]+[ \t]*$" c))
465 (or accept-special
466 (and
467 ;; Common patterns.
468 (not (looking-at "::[ \t]*$"))
469 (not (looking-at "\\.\\.\\.[ \t]*$"))
470 ;; Discard one char line
471 (not (looking-at ".[ \t]*$"))
473 (string-to-char c))
477 (defun rst-line-homogeneous-nodent-p (&optional accept-special)
478 (save-excursion
479 (beginning-of-line)
480 (if (looking-at "^[ \t]+")
482 (rst-line-homogeneous-p accept-special)
486 (defun rst-compare-decorations (deco1 deco2)
487 "Compare decorations. Returns true if both are equal,
488 according to restructured text semantics (only the character and
489 the style are compared, the indentation does not matter."
490 (and (eq (car deco1) (car deco2))
491 (eq (cadr deco1) (cadr deco2))))
494 (defun rst-get-decoration-match (hier deco)
495 "Returns the index (level) of the decoration in the given hierarchy.
496 This basically just searches for the item using the appropriate
497 comparison and returns the index. We return nil if the item is
498 not found."
499 (let ((cur hier))
500 (while (and cur (not (rst-compare-decorations (car cur) deco)))
501 (setq cur (cdr cur)))
502 cur))
505 (defun rst-suggest-new-decoration (alldecos &optional prev)
506 "Suggest a new, different decoration, different from all that
507 have been seen.
509 ALLDECOS is the set of all decorations, including the line
510 numbers. PREV is the optional previous decoration, in order to
511 suggest a better match."
513 ;; For all the preferred decorations...
514 (let* (
515 ;; If 'prev' is given, reorder the list to start searching after the
516 ;; match.
517 (fplist
518 (cdr (rst-get-decoration-match rst-preferred-decorations prev)))
520 ;; List of candidates to search.
521 (curpotential (append fplist rst-preferred-decorations)))
522 (while
523 ;; For all the decorations...
524 (let ((cur alldecos)
525 found)
526 (while (and cur (not found))
527 (if (rst-compare-decorations (car cur) (car curpotential))
528 ;; Found it!
529 (setq found (car curpotential))
530 (setq cur (cdr cur))))
531 found)
533 (setq curpotential (cdr curpotential)))
535 (copy-list (car curpotential)) ))
537 (defun rst-delete-line ()
538 "A version of kill-line that does not use the kill-ring."
539 (delete-region (line-beginning-position) (min (+ 1 (line-end-position))
540 (point-max))))
542 (defun rst-update-section (char style &optional indent)
543 "Unconditionally updates the style of a section decoration
544 using the given character CHAR, with STYLE 'simple or
545 'over-and-under, and with indent INDENT. If the STYLE is
546 'simple, whitespace before the title is removed (indent is
547 always assume to be 0).
549 If there are existing overline and/or underline from the
550 existing decoration, they are removed before adding the
551 requested decoration."
553 (interactive)
554 (let (marker
557 (c ?-))
559 (end-of-line)
560 (setq marker (point-marker))
562 ;; Fixup whitespace at the beginning and end of the line
563 (if (or (null indent) (eq style 'simple))
564 (setq indent 0))
565 (beginning-of-line)
566 (delete-horizontal-space)
567 (insert (make-string indent ? ))
569 (end-of-line)
570 (delete-horizontal-space)
572 ;; Set the current column, we're at the end of the title line
573 (setq len (+ (current-column) indent))
575 ;; Remove previous line if it consists only of a single repeated character
576 (save-excursion
577 (forward-line -1)
578 (and (rst-line-homogeneous-p 1)
579 ;; Avoid removing the underline of a title right above us.
580 (save-excursion (forward-line -1)
581 (not (looking-at rst-section-text-regexp)))
582 (rst-delete-line)))
584 ;; Remove following line if it consists only of a single repeated
585 ;; character
586 (save-excursion
587 (forward-line +1)
588 (and (rst-line-homogeneous-p 1)
589 (rst-delete-line))
590 ;; Add a newline if we're at the end of the buffer, for the subsequence
591 ;; inserting of the underline
592 (if (= (point) (buffer-end 1))
593 (newline 1)))
595 ;; Insert overline
596 (if (eq style 'over-and-under)
597 (save-excursion
598 (beginning-of-line)
599 (open-line 1)
600 (insert (make-string len char))))
602 ;; Insert underline
603 (forward-line +1)
604 (open-line 1)
605 (insert (make-string len char))
607 (forward-line +1)
608 (goto-char marker)
612 (defun rst-normalize-cursor-position ()
613 "If the cursor is on a decoration line or an empty line , place
614 it on the section title line (at the end). Returns the line
615 offset by which the cursor was moved. This works both over or
616 under a line."
617 (if (save-excursion (beginning-of-line)
618 (or (rst-line-homogeneous-p 1)
619 (looking-at "^[ \t]*$")))
620 (progn
621 (beginning-of-line)
622 (cond
623 ((save-excursion (forward-line -1)
624 (beginning-of-line)
625 (and (looking-at rst-section-text-regexp)
626 (not (rst-line-homogeneous-p 1))))
627 (progn (forward-line -1) -1))
628 ((save-excursion (forward-line +1)
629 (beginning-of-line)
630 (and (looking-at rst-section-text-regexp)
631 (not (rst-line-homogeneous-p 1))))
632 (progn (forward-line +1) +1))
633 (t 0)))
634 0 ))
637 (defun rst-find-all-decorations ()
638 "Finds all the decorations in the file, and returns a list of
639 (line, decoration) pairs. Each decoration consists in a (char,
640 style, indent) triple.
642 This function does not detect the hierarchy of decorations, it
643 just finds all of them in a file. You can then invoke another
644 function to remove redundancies and inconsistencies."
646 (let (positions
647 (curline 1))
648 ;; Iterate over all the section titles/decorations in the file.
649 (save-excursion
650 (beginning-of-buffer)
651 (while (< (point) (buffer-end 1))
652 (if (rst-line-homogeneous-nodent-p)
653 (progn
654 (setq curline (+ curline (rst-normalize-cursor-position)))
656 ;; Here we have found a potential site for a decoration,
657 ;; characterize it.
658 (let ((deco (rst-get-decoration)))
659 (if (cadr deco) ;; Style is existing.
660 ;; Found a real decoration site.
661 (progn
662 (push (cons curline deco) positions)
663 ;; Push beyond the underline.
664 (forward-line 1)
665 (setq curline (+ curline 1))
668 (forward-line 1)
669 (setq curline (+ curline 1))
671 (reverse positions)))
674 (defun rst-infer-hierarchy (decorations)
675 "Build a hierarchy of decorations using the list of given decorations.
677 This function expects a list of (char, style, indent)
678 decoration specifications, in order that they appear in a file,
679 and will infer a hierarchy of section levels by removing
680 decorations that have already been seen in a forward traversal of the
681 decorations, comparing just the character and style.
683 Similarly returns a list of (char, style, indent), where each
684 list element should be unique."
686 (let ((hierarchy-alist (list)))
687 (dolist (x decorations)
688 (let ((char (car x))
689 (style (cadr x))
690 (indent (caddr x)))
691 (unless (assoc (cons char style) hierarchy-alist)
692 (setq hierarchy-alist
693 (append hierarchy-alist
694 (list (cons (cons char style) x)))) )
696 (mapcar 'cdr hierarchy-alist)
700 (defun rst-get-hierarchy (&optional alldecos ignore)
701 "Returns a list of decorations that represents the hierarchy of
702 section titles in the file.
704 If the line number in IGNORE is specified, the decoration found
705 on that line (if there is one) is not taken into account when
706 building the hierarchy."
707 (let ((all (or alldecos (rst-find-all-decorations))))
708 (setq all (assq-delete-all ignore all))
709 (rst-infer-hierarchy (mapcar 'cdr all))))
712 (defun rst-get-decoration (&optional point)
713 "Looks around point and finds the characteristics of the
714 decoration that is found there. We assume that the cursor is
715 already placed on the title line (and not on the overline or
716 underline).
718 This function returns a (char, style, indent) triple. If the
719 characters of overline and underline are different, we return
720 the underline character. The indent is always calculated. A
721 decoration can be said to exist if the style is not nil.
723 A point can be specified to go to the given location before
724 extracting the decoration."
726 (let (char style indent)
727 (save-excursion
728 (if point (goto-char point))
729 (beginning-of-line)
730 (if (looking-at rst-section-text-regexp)
731 (let* ((over (save-excursion
732 (forward-line -1)
733 (rst-line-homogeneous-nodent-p)))
735 (under (save-excursion
736 (forward-line +1)
737 (rst-line-homogeneous-nodent-p)))
740 ;; Check that the line above the overline is not part of a title
741 ;; above it.
742 (if (and over
743 (save-excursion
744 (and (equal (forward-line -2) 0)
745 (looking-at rst-section-text-regexp))))
746 (setq over nil))
748 (cond
749 ;; No decoration found, leave all return values nil.
750 ((and (eq over nil) (eq under nil)))
752 ;; Overline only, leave all return values nil.
754 ;; Note: we don't return the overline character, but it could
755 ;; perhaps in some cases be used to do something.
756 ((and over (eq under nil)))
758 ;; Underline only.
759 ((and under (eq over nil))
760 (setq char under
761 style 'simple))
763 ;; Both overline and underline.
765 (setq char under
766 style 'over-and-under))
770 ;; Find indentation.
771 (setq indent (save-excursion (back-to-indentation) (current-column)))
773 ;; Return values.
774 (list char style indent)))
777 (defun rst-get-decorations-around (&optional alldecos)
778 "Given the list of all decorations (with positions),
779 find the decorations before and after the given point.
780 A list of the previous and next decorations is returned."
781 (let* ((all (or alldecos (rst-find-all-decorations)))
782 (curline (line-number-at-pos))
783 prev next
784 (cur all))
786 ;; Search for the decorations around the current line.
787 (while (and cur (< (caar cur) curline))
788 (setq prev cur
789 cur (cdr cur)))
790 ;; 'cur' is the following decoration.
792 (if (and cur (caar cur))
793 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
795 (mapcar 'cdar (list prev next))
799 (defun rst-decoration-complete-p (deco &optional point)
800 "Return true if the decoration DECO around POINT is complete."
801 ;; Note: we assume that the detection of the overline as being the underline
802 ;; of a preceding title has already been detected, and has been eliminated
803 ;; from the decoration that is given to us.
805 ;; There is some sectioning already present, so check if the current
806 ;; sectioning is complete and correct.
807 (let* ((char (car deco))
808 (style (cadr deco))
809 (indent (caddr deco))
810 (endcol (save-excursion (end-of-line) (current-column)))
812 (if char
813 (let ((exps (concat "^"
814 (regexp-quote (make-string (+ endcol indent) char))
815 "$")))
816 (and
817 (save-excursion (forward-line +1)
818 (beginning-of-line)
819 (looking-at exps))
820 (or (not (eq style 'over-and-under))
821 (save-excursion (forward-line -1)
822 (beginning-of-line)
823 (looking-at exps))))
828 (defun rst-get-next-decoration
829 (curdeco hier &optional suggestion reverse-direction)
830 "Get the next decoration for CURDECO, in given hierarchy HIER,
831 and suggesting for new decoration SUGGESTION."
833 (let* (
834 (char (car curdeco))
835 (style (cadr curdeco))
837 ;; Build a new list of decorations for the rotation.
838 (rotdecos
839 (append hier
840 ;; Suggest a new decoration.
841 (list suggestion
842 ;; If nothing to suggest, use first decoration.
843 (car hier)))) )
845 ;; Search for next decoration.
846 (cadr
847 (let ((cur (if reverse-direction rotdecos
848 (reverse rotdecos)))
849 found)
850 (while (and cur
851 (not (and (eq char (caar cur))
852 (eq style (cadar cur)))))
853 (setq cur (cdr cur)))
854 cur))
856 ;; If not found, take the first of all decorations.
857 suggestion
861 (defun rst-adjust ()
862 "Adjust/rotate the section decoration for the section title
863 around point or promote/demote the decorations inside the region,
864 depending on if the region is active. This function is meant to
865 be invoked possibly multiple times, and can vary its behaviour
866 with a positive prefix argument (toggle style), or with a
867 negative prefix argument (alternate behaviour).
869 This function is the main focus of this module and is a bit of a
870 swiss knife. It is meant as the single most essential function
871 to be bound to invoke to adjust the decorations of a section
872 title in restructuredtext. It tries to deal with all the
873 possible cases gracefully and to do `the right thing' in all
874 cases.
876 See the documentations of rst-adjust-decoration and
877 rst-promote-region for full details.
879 Prefix Arguments
880 ================
882 The method can take either (but not both) of
884 a. a (non-negative) prefix argument, which means to toggle the
885 decoration style. Invoke with C-u prefix for example;
887 b. a negative numerical argument, which generally inverts the
888 direction of search in the file or hierarchy. Invoke with C--
889 prefix for example.
892 (interactive)
894 (let* ( ;; Parse the positive and negative prefix arguments.
895 (reverse-direction
896 (and current-prefix-arg
897 (< (prefix-numeric-value current-prefix-arg) 0)))
898 (toggle-style
899 (and current-prefix-arg (not reverse-direction))))
901 (if (and transient-mark-mode mark-active)
902 ;; Adjust decorations within region.
903 (rst-promote-region current-prefix-arg)
904 ;; Adjust decoration around point.
905 (rst-adjust-decoration toggle-style reverse-direction))
907 ;; Run the hooks to run after adjusting.
908 (run-hooks 'rst-adjust-hook)
912 (defvar rst-adjust-hook nil
913 "Hooks to be run after running rst-adjust.")
915 (defun rst-adjust-decoration (&optional toggle-style reverse-direction)
916 "Adjust/rotate the section decoration for the section title around point.
918 This function is meant to be invoked possibly multiple times, and
919 can vary its behaviour with a true TOGGLE-STYLE argument, or with
920 a REVERSE-DIRECTION argument.
922 General Behaviour
923 =================
925 The next action it takes depends on context around the point, and
926 it is meant to be invoked possibly more than once to rotate among
927 the various possibilities. Basically, this function deals with:
929 - adding a decoration if the title does not have one;
931 - adjusting the length of the underline characters to fit a
932 modified title;
934 - rotating the decoration in the set of already existing
935 sectioning decorations used in the file;
937 - switching between simple and over-and-under styles.
939 You should normally not have to read all the following, just
940 invoke the method and it will do the most obvious thing that you
941 would expect.
944 Decoration Definitions
945 ======================
947 The decorations consist in
949 1. a CHARACTER
951 2. a STYLE which can be either of 'simple' or 'over-and-under'.
953 3. an INDENT (meaningful for the over-and-under style only)
954 which determines how many characters and over-and-under
955 style is hanging outside of the title at the beginning and
956 ending.
958 See source code for mode details.
961 Detailed Behaviour Description
962 ==============================
964 Here are the gory details of the algorithm (it seems quite
965 complicated, but really, it does the most obvious thing in all
966 the particular cases):
968 Before applying the decoration change, the cursor is placed on
969 the closest line that could contain a section title.
971 Case 1: No Decoration
972 ---------------------
974 If the current line has no decoration around it,
976 - search backwards for the last previous decoration, and apply
977 the decoration one level lower to the current line. If there
978 is no defined level below this previous decoration, we suggest
979 the most appropriate of the rst-preferred-decorations.
981 If REVERSE-DIRECTION is true, we simply use the previous
982 decoration found directly.
984 - if there is no decoration found in the given direction, we use
985 the first of rst-preferred-decorations.
987 The prefix argument forces a toggle of the prescribed decoration
988 style.
990 Case 2: Incomplete Decoration
991 -----------------------------
993 If the current line does have an existing decoration, but the
994 decoration is incomplete, that is, the underline/overline does
995 not extend to exactly the end of the title line (it is either too
996 short or too long), we simply extend the length of the
997 underlines/overlines to fit exactly the section title.
999 If the prefix argument is given, we toggle the style of the
1000 decoration as well.
1002 REVERSE-DIRECTION has no effect in this case.
1004 Case 3: Complete Existing Decoration
1005 ------------------------------------
1007 If the decoration is complete (i.e. the underline (overline)
1008 length is already adjusted to the end of the title line), we
1009 search/parse the file to establish the hierarchy of all the
1010 decorations (making sure not to include the decoration around
1011 point), and we rotate the current title's decoration from within
1012 that list (by default, going *down* the hierarchy that is present
1013 in the file, i.e. to a lower section level). This is meant to be
1014 used potentially multiple times, until the desired decoration is
1015 found around the title.
1017 If we hit the boundary of the hierarchy, exactly one choice from
1018 the list of preferred decorations is suggested/chosen, the first
1019 of those decoration that has not been seen in the file yet (and
1020 not including the decoration around point), and the next
1021 invocation rolls over to the other end of the hierarchy (i.e. it
1022 cycles). This allows you to avoid having to set which character
1023 to use by always using the
1025 If REVERSE-DIRECTION is true, the effect is to change the
1026 direction of rotation in the hierarchy of decorations, thus
1027 instead going *up* the hierarchy.
1029 However, if there is a non-negative prefix argument, we do not
1030 rotate the decoration, but instead simply toggle the style of the
1031 current decoration (this should be the most common way to toggle
1032 the style of an existing complete decoration).
1035 Point Location
1036 ==============
1038 The invocation of this function can be carried out anywhere
1039 within the section title line, on an existing underline or
1040 overline, as well as on an empty line following a section title.
1041 This is meant to be as convenient as possible.
1044 Indented Sections
1045 =================
1047 Indented section titles such as ::
1049 My Title
1050 --------
1052 are illegal in restructuredtext and thus not recognized by the
1053 parser. This code will thus not work in a way that would support
1054 indented sections (it would be ambiguous anyway).
1057 Joint Sections
1058 ==============
1060 Section titles that are right next to each other may not be
1061 treated well. More work might be needed to support those, and
1062 special conditions on the completeness of existing decorations
1063 might be required to make it non-ambiguous.
1065 For now we assume that the decorations are disjoint, that is,
1066 there is at least a single line between the titles/decoration
1067 lines.
1070 Suggested Binding
1071 =================
1073 We suggest that you bind this function on C-=. It is close to
1074 C-- so a negative argument can be easily specified with a flick
1075 of the right hand fingers and the binding is unused in text-mode."
1076 (interactive)
1078 ;; If we were invoked directly, parse the prefix arguments into the
1079 ;; arguments of the function.
1080 (if current-prefix-arg
1081 (setq reverse-direction
1082 (and current-prefix-arg
1083 (< (prefix-numeric-value current-prefix-arg) 0))
1085 toggle-style
1086 (and current-prefix-arg (not reverse-direction))))
1088 (let* (;; Check if we're on an underline around a section title, and move the
1089 ;; cursor to the title if this is the case.
1090 (moved (rst-normalize-cursor-position))
1092 ;; Find the decoration and completeness around point.
1093 (curdeco (rst-get-decoration))
1094 (char (car curdeco))
1095 (style (cadr curdeco))
1096 (indent (caddr curdeco))
1098 ;; New values to be computed.
1099 char-new style-new indent-new
1102 ;; We've moved the cursor... if we're not looking at some text, we have
1103 ;; nothing to do.
1104 (if (save-excursion (beginning-of-line)
1105 (looking-at rst-section-text-regexp))
1106 (progn
1107 (cond
1108 ;;-------------------------------------------------------------------
1109 ;; Case 1: No Decoration
1110 ((and (eq char nil) (eq style nil))
1112 (let* ((alldecos (rst-find-all-decorations))
1114 (around (rst-get-decorations-around alldecos))
1115 (prev (car around))
1118 (hier (rst-get-hierarchy alldecos))
1121 ;; Advance one level down.
1122 (setq cur
1123 (if prev
1124 (if (not reverse-direction)
1125 (or (cadr (rst-get-decoration-match hier prev))
1126 (rst-suggest-new-decoration hier prev))
1127 prev)
1128 (copy-list (car rst-preferred-decorations))
1131 ;; Invert the style if requested.
1132 (if toggle-style
1133 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1134 'over-and-under 'simple)) )
1136 (setq char-new (car cur)
1137 style-new (cadr cur)
1138 indent-new (caddr cur))
1141 ;;-------------------------------------------------------------------
1142 ;; Case 2: Incomplete Decoration
1143 ((not (rst-decoration-complete-p curdeco))
1145 ;; Invert the style if requested.
1146 (if toggle-style
1147 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1149 (setq char-new char
1150 style-new style
1151 indent-new indent))
1153 ;;-------------------------------------------------------------------
1154 ;; Case 3: Complete Existing Decoration
1156 (if toggle-style
1158 ;; Simply switch the style of the current decoration.
1159 (setq char-new char
1160 style-new (if (eq style 'simple) 'over-and-under 'simple)
1161 indent-new rst-default-indent)
1163 ;; Else, we rotate, ignoring the decoration around the current
1164 ;; line...
1165 (let* ((alldecos (rst-find-all-decorations))
1167 (hier (rst-get-hierarchy alldecos (line-number-at-pos)))
1169 ;; Suggestion, in case we need to come up with something
1170 ;; new
1171 (suggestion (rst-suggest-new-decoration
1172 hier
1173 (car (rst-get-decorations-around alldecos))))
1175 (nextdeco (rst-get-next-decoration
1176 curdeco hier suggestion reverse-direction))
1180 ;; Indent, if present, always overrides the prescribed indent.
1181 (setq char-new (car nextdeco)
1182 style-new (cadr nextdeco)
1183 indent-new (caddr nextdeco))
1188 ;; Override indent with present indent!
1189 (setq indent-new (if (> indent 0) indent indent-new))
1191 (if (and char-new style-new)
1192 (rst-update-section char-new style-new indent-new))
1196 ;; Correct the position of the cursor to more accurately reflect where it
1197 ;; was located when the function was invoked.
1198 (unless (= moved 0)
1199 (forward-line (- moved))
1200 (end-of-line))
1204 ;; Maintain an alias for compatibility.
1205 (defalias 'rst-adjust-section-title 'rst-adjust)
1208 (defun rst-promote-region (&optional demote)
1209 "Promote the section titles within the region.
1211 With argument DEMOTE or a prefix argument, demote the
1212 section titles instead. The algorithm used at the boundaries of
1213 the hierarchy is similar to that used by rst-adjust-decoration."
1214 (interactive)
1216 (let* ((demote (or current-prefix-arg demote))
1217 (alldecos (rst-find-all-decorations))
1218 (cur alldecos)
1220 (hier (rst-get-hierarchy alldecos))
1221 (suggestion (rst-suggest-new-decoration hier))
1223 (region-begin-line (line-number-at-pos (region-beginning)))
1224 (region-end-line (line-number-at-pos (region-end)))
1226 marker-list
1229 ;; Skip the markers that come before the region beginning
1230 (while (and cur (< (caar cur) region-begin-line))
1231 (setq cur (cdr cur)))
1233 ;; Create a list of markers for all the decorations which are found within
1234 ;; the region.
1235 (save-excursion
1236 (let (m line)
1237 (while (and cur (< (setq line (caar cur)) region-end-line))
1238 (setq m (make-marker))
1239 (goto-line line)
1240 (push (list (set-marker m (point)) (cdar cur)) marker-list)
1241 (setq cur (cdr cur)) ))
1243 ;; Apply modifications.
1244 (let (nextdeco)
1245 (dolist (p marker-list)
1246 ;; Go to the decoration to promote.
1247 (goto-char (car p))
1249 ;; Rotate the next decoration.
1250 (setq nextdeco (rst-get-next-decoration
1251 (cadr p) hier suggestion demote))
1253 ;; Update the decoration.
1254 (apply 'rst-update-section nextdeco)
1256 ;; Clear marker to avoid slowing down the editing after we're done.
1257 (set-marker (car p) nil)
1259 (setq deactivate-mark nil)
1264 (defun rst-display-decorations-hierarchy (&optional decorations)
1265 "Display the current file's section title decorations hierarchy.
1266 This function expects a list of (char, style, indent) triples."
1267 (interactive)
1269 (if (not decorations)
1270 (setq decorations (rst-get-hierarchy)))
1271 (with-output-to-temp-buffer "*rest section hierarchy*"
1272 (let ((level 1))
1273 (with-current-buffer standard-output
1274 (dolist (x decorations)
1275 (insert (format "\nSection Level %d" level))
1276 (apply 'rst-update-section x)
1277 (end-of-buffer)
1278 (insert "\n")
1279 (incf level)
1283 (defun rst-straighten-decorations (&optional buffer)
1284 "Redo all the decorations in the given buffer, using our
1285 preferred set of decorations. This can be used, for example,
1286 when using somebody else's copy of a document, in order to
1287 adapt it to our preferred style.
1288 If no buffer is specified, the default buffer is used."
1289 (interactive)
1290 (save-excursion
1291 (let* ((alldecos (rst-find-all-decorations))
1292 (hier (rst-get-hierarchy alldecos))
1294 ;; Get a list of pairs of (level . marker)
1295 (levels-and-markers (mapcar
1296 (lambda (deco)
1297 (cons (position (cdr deco) hier :test 'equal)
1298 (let ((m (make-marker)))
1299 (goto-line (car deco))
1300 (set-marker m (point))
1301 m)))
1302 alldecos))
1304 (dolist (lm levels-and-markers)
1305 ;; Go to the appropriate position
1306 (goto-char (cdr lm))
1308 ;; Apply the new styule
1309 (apply 'rst-update-section (nth (car lm) rst-preferred-decorations))
1311 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1312 (set-marker (cdr lm) nil)
1317 (defun rst-rstrip (str)
1318 "Strips the whitespace at the end of a string."
1319 (let ((tmp))
1320 (string-match "[ \t\n]*\\'" str)
1321 (substring str 0 (match-beginning 0))
1324 (defun rst-get-stripped-line ()
1325 "Returns the line at cursor, stripped from whitespace."
1326 (re-search-forward "\\S-.*\\S-" (line-end-position))
1327 (buffer-substring-no-properties (match-beginning 0)
1328 (match-end 0)) )
1330 (defun rst-section-tree (alldecos)
1331 "Returns a hierarchical tree of the sections titles in the
1332 document. This can be used to generate a table of contents for
1333 the document. The top node will always be a nil node, with the
1334 top-level titles as children (there may potentially be more than
1335 one).
1337 Each section title consists in a cons of the stripped title
1338 string and a marker to the section in the original text document.
1340 If there are missing section levels, the section titles are
1341 inserted automatically, and the title string is set to nil, and
1342 the marker set to the first non-nil child of itself.
1343 Conceptually, the nil nodes--i.e. those which have no title--are
1344 to be considered as being the same line as their first non-nil
1345 child. This has advantages later in processing the graph."
1347 (let* (thelist
1348 (hier (rst-get-hierarchy alldecos))
1349 (levels (make-hash-table :test 'equal :size 10))
1350 lines)
1352 (let ((lev 0))
1353 (dolist (deco hier)
1354 ;; Compare just the character and indent in the hash table.
1355 (puthash (cons (car deco) (cadr deco)) lev levels)
1356 (incf lev)))
1358 ;; Create a list of lines that contains (text, level, marker) for each
1359 ;; decoration.
1360 (save-excursion
1361 (setq lines
1362 (mapcar (lambda (deco)
1363 (goto-line (car deco))
1364 (list (gethash (cons (cadr deco) (caddr deco)) levels)
1365 (rst-get-stripped-line)
1366 (let ((m (make-marker)))
1367 (beginning-of-line 1)
1368 (set-marker m (point)))
1370 alldecos)))
1372 (let ((lcontnr (cons nil lines)))
1373 (rst-section-tree-rec lcontnr -1))))
1376 (defun rst-section-tree-rec (decos lev)
1377 "Recursive function for the implementation of the section tree
1378 building. DECOS is a cons cell whose cdr is the remaining list
1379 of decorations, and we change it as we consume them. LEV is
1380 the current level of that node. This function returns a pair
1381 of the subtree that was built. This treats the decos list
1382 destructively."
1384 (let ((ndeco (cadr decos))
1385 node
1386 children)
1388 ;; If the next decoration matches our level
1389 (when (and ndeco (= (car ndeco) lev))
1390 ;; Pop the next decoration and create the current node with it
1391 (setcdr decos (cddr decos))
1392 (setq node (cdr ndeco)) )
1393 ;; Else we let the node title/marker be unset.
1395 ;; Build the child nodes
1396 (while (and (cdr decos) (> (caadr decos) lev))
1397 (setq children
1398 (cons (rst-section-tree-rec decos (1+ lev))
1399 children)))
1400 (setq children (reverse children))
1402 ;; If node is still unset, we use the marker of the first child.
1403 (when (eq node nil)
1404 (setq node (cons nil (cdaar children))))
1406 ;; Return this node with its children.
1407 (cons node children)
1411 (defun rst-section-tree-point (node &optional point)
1412 "Given a computed and valid section tree SECTREE and a point
1413 POINT (default being the current point in the current buffer),
1414 find and return the node within the sectree where the cursor
1415 lives.
1417 Return values: a pair of (parent path, container subtree). The
1418 parent path is simply a list of the nodes above the container
1419 subtree node that we're returning."
1421 (let (path outtree)
1423 (let* ((curpoint (or point (point))))
1425 ;; Check if we are before the current node.
1426 (if (and (cadar node) (>= curpoint (cadar node)))
1428 ;; Iterate all the children, looking for one that might contain the
1429 ;; current section.
1430 (let ((curnode (cdr node))
1431 last)
1433 (while (and curnode (>= curpoint (cadaar curnode)))
1434 (setq last curnode
1435 curnode (cdr curnode)))
1437 (if last
1438 (let ((sub (rst-section-tree-point (car last) curpoint)))
1439 (setq path (car sub)
1440 outtree (cdr sub)))
1441 (setq outtree node))
1444 (cons (cons (car node) path) outtree)
1448 (defun rst-toc-insert (&optional pfxarg)
1449 "Insert a simple text rendering of the table of contents.
1450 By default the top level is ignored if there is only one, because
1451 we assume that the document will have a single title.
1453 If a numeric prefix argument is given, insert the TOC up to the
1454 specified level.
1456 The TOC is inserted indented at the current column."
1458 (interactive "P")
1460 (let* (;; Check maximum level override
1461 (rst-toc-insert-max-level
1462 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
1463 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
1465 ;; Get the section tree for the current cursor point.
1466 (sectree-pair
1467 (rst-section-tree-point
1468 (rst-section-tree (rst-find-all-decorations))))
1470 ;; Figure out initial indent.
1471 (initial-indent (make-string (current-column) ? ))
1472 (init-point (point)))
1474 (when (cddr sectree-pair)
1475 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
1477 ;; Fixup for the first line.
1478 (delete-region init-point (+ init-point (length initial-indent)))
1480 ;; Delete the last newline added.
1481 (delete-backward-char 1)
1485 (defgroup rst-toc nil
1486 "Settings for reStructuredText table of contents."
1487 :group 'rst
1488 :version "21.1")
1490 (defcustom rst-toc-indent 2
1491 "Indentation for table-of-contents display (also used for
1492 formatting insertion, when numbering is disabled)."
1493 :group 'rst-toc)
1495 (defcustom rst-toc-insert-style 'fixed
1496 "Set this to one of the following values to determine numbering and
1497 indentation style:
1498 - plain: no numbering (fixed indentation)
1499 - fixed: numbering, but fixed indentation
1500 - aligned: numbering, titles aligned under each other
1501 - listed: numbering, with dashes like list items (EXPERIMENTAL)
1503 :group 'rst-toc)
1505 (defcustom rst-toc-insert-number-separator " "
1506 "Separator that goes between the TOC number and the title."
1507 :group 'rst-toc)
1509 ;; This is used to avoid having to change the user's mode.
1510 (defvar rst-toc-insert-click-keymap
1511 (let ((map (make-sparse-keymap)))
1512 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
1513 map)
1514 "(Internal) What happens when you click on propertized text in the TOC.")
1516 (defcustom rst-toc-insert-max-level nil
1517 "If non-nil, maximum depth of the inserted TOC."
1518 :group 'rst-toc)
1520 (defun rst-toc-insert-node (node level indent pfx)
1521 "Recursive function that does the print of the inserted
1522 toc. PFX is the prefix numbering, that includes the alignment
1523 necessary for all the children of this level to align."
1525 ;; Note: we do child numbering from the parent, so we start number the
1526 ;; children one level before we print them.
1527 (let ((do-print (> level 0))
1528 (count 1)
1530 (when do-print
1531 (insert indent)
1532 (let ((b (point)))
1533 (unless (equal rst-toc-insert-style 'plain)
1534 (insert pfx rst-toc-insert-number-separator))
1535 (insert (or (caar node) "[missing node]"))
1536 ;; Add properties to the text, even though in normal text mode it
1537 ;; won't be doing anything for now. Not sure that I want to change
1538 ;; mode stuff. At least the highlighting gives the idea that this
1539 ;; is generated automatically.
1540 (put-text-property b (point) 'mouse-face 'highlight)
1541 (put-text-property b (point) 'rst-toc-target (cadar node))
1542 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
1545 (insert "\n")
1547 ;; Prepare indent for children.
1548 (setq indent
1549 (cond
1550 ((eq rst-toc-insert-style 'plain)
1551 (concat indent rst-toc-indent))
1553 ((eq rst-toc-insert-style 'fixed)
1554 (concat indent (make-string rst-toc-indent ? )))
1556 ((eq rst-toc-insert-style 'aligned)
1557 (concat indent (make-string (+ (length pfx) 2) ? )))
1559 ((eq rst-toc-insert-style 'listed)
1560 (concat (substring indent 0 -3)
1561 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
1565 (if (or (eq rst-toc-insert-max-level nil)
1566 (< level rst-toc-insert-max-level))
1567 (let ((do-child-numbering (>= level 0))
1568 fmt)
1569 (if do-child-numbering
1570 (progn
1571 ;; Add a separating dot if there is already a prefix
1572 (if (> (length pfx) 0)
1573 (setq pfx (concat (rst-rstrip pfx) ".")))
1575 ;; Calculate the amount of space that the prefix will require
1576 ;; for the numbers.
1577 (if (cdr node)
1578 (setq fmt (format "%%-%dd"
1579 (1+ (floor (log10 (length
1580 (cdr node))))))))
1583 (dolist (child (cdr node))
1584 (rst-toc-insert-node child
1585 (1+ level)
1586 indent
1587 (if do-child-numbering
1588 (concat pfx (format fmt count)) pfx))
1589 (incf count)))
1594 (defun rst-toc-insert-find-delete-contents ()
1595 "Finds and deletes an existing comment after the first contents directive and
1596 delete that region. Return t if found and the cursor is left after the comment."
1597 (goto-char (point-min))
1598 ;; We look for the following and the following only (in other words, if your
1599 ;; syntax differs, this won't work. If you would like a more flexible thing,
1600 ;; contact the author, I just can't imagine that this requirement is
1601 ;; unreasonable for now).
1603 ;; .. contents:: [...anything here...]
1604 ;; ..
1605 ;; XXXXXXXX
1606 ;; XXXXXXXX
1607 ;; [more lines]
1609 (let ((beg
1610 (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
1611 nil t))
1612 last-real)
1613 (when beg
1614 ;; Look for the first line that starts at the first column.
1615 (forward-line 1)
1616 (beginning-of-line)
1617 (while (and
1618 (< (point) (point-max))
1619 (or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
1620 (looking-at "[ \t]*$")))
1621 (forward-line 1)
1623 (if last-real
1624 (progn
1625 (goto-char last-real)
1626 (end-of-line)
1627 (delete-region beg (point)))
1628 (goto-char beg))
1632 (defun rst-toc-insert-update ()
1633 "Automatically find the .. contents:: section of a document and update the
1634 inserted TOC if present. You can use this in your file-write hook to always
1635 make it up-to-date automatically."
1636 (interactive)
1637 (save-excursion
1638 (if (rst-toc-insert-find-delete-contents)
1639 (progn (insert "\n ")
1640 (rst-toc-insert))) )
1641 ;; Note: always return nil, because this may be used as a hook.
1645 ;;------------------------------------------------------------------------------
1647 (defun rst-toc-node (node level)
1648 "Recursive function that does the print of the TOC in rst-toc-mode."
1650 (if (> level 0)
1651 (let ((b (point)))
1652 ;; Insert line text.
1653 (insert (make-string (* rst-toc-indent (1- level)) ? ))
1654 (insert (or (caar node) "[missing node]"))
1656 ;; Highlight lines.
1657 (put-text-property b (point) 'mouse-face 'highlight)
1659 ;; Add link on lines.
1660 (put-text-property b (point) 'rst-toc-target (cadar node))
1662 (insert "\n")
1665 (dolist (child (cdr node))
1666 (rst-toc-node child (1+ level))))
1668 (defun rst-toc-count-lines (node target-node)
1669 "Count the number of lines to the TARGET-NODE node. This
1670 recursive function returns a cons of the number of additional
1671 lines that have been counted for its node and children and 't if
1672 the node has been found."
1674 (let ((count 1)
1675 found)
1676 (if (eq node target-node)
1677 (setq found t)
1678 (let ((child (cdr node)))
1679 (while (and child (not found))
1680 (let ((cl (rst-toc-count-lines (car child) target-node)))
1681 (setq count (+ count (car cl))
1682 found (cdr cl)
1683 child (cdr child))))))
1684 (cons count found)))
1687 (defun rst-toc ()
1688 "Finds all the section titles and their decorations in the
1689 file, and displays a hierarchically-organized list of the
1690 titles, which is essentially a table-of-contents of the
1691 document.
1693 The emacs buffer can be navigated, and selecting a section
1694 brings the cursor in that section."
1695 (interactive)
1696 (let* ((curbuf (current-buffer))
1698 ;; Get the section tree
1699 (alldecos (rst-find-all-decorations))
1700 (sectree (rst-section-tree alldecos))
1702 (our-node (cdr (rst-section-tree-point sectree)))
1703 line
1705 ;; Create a temporary buffer.
1706 (buf (get-buffer-create rst-toc-buffer-name))
1709 (with-current-buffer buf
1710 (let ((inhibit-read-only t))
1711 (rst-toc-mode)
1712 (delete-region (point-min) (point-max))
1713 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
1714 (put-text-property (point-min) (point)
1715 'face (list '(background-color . "lightgray")))
1716 (rst-toc-node sectree 0)
1718 ;; Count the lines to our found node.
1719 (let ((linefound (rst-toc-count-lines sectree our-node)))
1720 (setq line (if (cdr linefound) (car linefound) 0)))
1722 (display-buffer buf)
1723 (pop-to-buffer buf)
1725 ;; Save the buffer to return to.
1726 (set (make-local-variable 'rst-toc-return-buffer) curbuf)
1728 ;; Move the cursor near the right section in the TOC.
1729 (goto-line line)
1733 (defun rst-toc-mode-find-section ()
1734 (let ((pos (get-text-property (point) 'rst-toc-target)))
1735 (unless pos
1736 (error "No section on this line"))
1737 (unless (buffer-live-p (marker-buffer pos))
1738 (error "Buffer for this section was killed"))
1739 pos))
1741 (defvar rst-toc-buffer-name "*Table of Contents*"
1742 "Name of the Table of Contents buffer.")
1744 (defun rst-toc-mode-goto-section ()
1745 "Go to the section the current line describes."
1746 (interactive)
1747 (let ((pos (rst-toc-mode-find-section)))
1748 (kill-buffer (get-buffer rst-toc-buffer-name))
1749 (pop-to-buffer (marker-buffer pos))
1750 (goto-char pos)
1751 ;; FIMXE: make the recentering conditional on scroll.
1752 (recenter 5)))
1754 (defun rst-toc-mode-mouse-goto (event)
1755 "In Rst-Toc mode, go to the occurrence whose line you click on."
1756 (interactive "e")
1757 (let (pos)
1758 (save-excursion
1759 (set-buffer (window-buffer (posn-window (event-end event))))
1760 (save-excursion
1761 (goto-char (posn-point (event-end event)))
1762 (setq pos (rst-toc-mode-find-section))))
1763 (pop-to-buffer (marker-buffer pos))
1764 (goto-char pos)
1765 (recenter 5)))
1767 (defun rst-toc-mode-mouse-goto-kill (event)
1768 (interactive "e")
1769 (call-interactively 'rst-toc-mode-mouse-goto event)
1770 (kill-buffer (get-buffer rst-toc-buffer-name)))
1772 (defvar rst-toc-return-buffer nil
1773 "Buffer local variable that is used to return to the original
1774 buffer from the TOC.")
1776 (defun rst-toc-quit-window ()
1777 (interactive)
1778 (quit-window)
1779 (pop-to-buffer rst-toc-return-buffer))
1781 (defvar rst-toc-mode-map
1782 (let ((map (make-sparse-keymap)))
1783 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
1784 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
1785 (define-key map "\C-m" 'rst-toc-mode-goto-section)
1786 (define-key map "f" 'rst-toc-mode-goto-section)
1787 (define-key map "q" 'rst-toc-quit-window)
1788 (define-key map "z" 'kill-this-buffer)
1789 map)
1790 "Keymap for `rst-toc-mode'.")
1792 (put 'rst-toc-mode 'mode-class 'special)
1794 (defun rst-toc-mode ()
1795 "Major mode for output from \\[rst-toc]."
1796 (interactive)
1797 (kill-all-local-variables)
1798 (use-local-map rst-toc-mode-map)
1799 (setq major-mode 'rst-toc-mode)
1800 (setq mode-name "Rst-TOC")
1801 (setq buffer-read-only t)
1804 ;; Note: use occur-mode (replace.el) as a good example to complete missing
1805 ;; features.
1808 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1810 ;; Section movement commands.
1813 (defun rst-forward-section (&optional offset)
1814 "Skip to the next restructured text section title.
1815 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
1816 backwards in the file (default is to use 1)."
1817 (interactive)
1818 (let* (;; Default value for offset.
1819 (offset (or offset 1))
1821 ;; Get all the decorations in the file, with their line numbers.
1822 (alldecos (rst-find-all-decorations))
1824 ;; Get the current line.
1825 (curline (line-number-at-pos))
1827 (cur alldecos)
1828 (idx 0)
1829 line
1832 ;; Find the index of the "next" decoration w.r.t. to the current line.
1833 (while (and cur (< (caar cur) curline))
1834 (setq cur (cdr cur))
1835 (incf idx))
1836 ;; 'cur' is the decoration on or following the current line.
1838 (if (and (> offset 0) cur (= (caar cur) curline))
1839 (incf idx))
1841 ;; Find the final index.
1842 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
1843 (setq cur (nth idx alldecos))
1845 ;; If the index is positive, goto the line, otherwise go to the buffer
1846 ;; boundaries.
1847 (if (and cur (>= idx 0))
1848 (goto-line (car cur))
1849 (if (> offset 0) (end-of-buffer) (beginning-of-buffer)))
1852 (defun rst-backward-section ()
1853 "Like rst-forward-section, except move back one title."
1854 (interactive)
1855 (rst-forward-section -1))
1860 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1861 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
1862 ;; always 2 or 3 characters apart horizontally with rest.
1864 (defvar rst-shift-fill-region nil
1865 "Set to true if you want to automatically re-fill the region that is being
1866 shifted.")
1868 (defun rst-find-leftmost-column (beg end)
1869 "Finds the leftmost column in the region."
1870 (let ((mincol 1000))
1871 (save-excursion
1872 (goto-char beg)
1873 (while (< (point) end)
1874 (back-to-indentation)
1875 (unless (looking-at "[ \t]*$")
1876 (setq mincol (min mincol (current-column))))
1877 (forward-line 1)
1879 mincol))
1882 ;; What we really need to do is compute all the possible alignment possibilities
1883 ;; and then select one.
1885 ;; .. line-block::
1887 ;; a) sdjsds
1889 ;; - sdjsd jsjds
1891 ;; sdsdsjdsj
1893 ;; 11. sjdss jddjs
1895 ;; * * * * * * *
1897 ;; Move backwards, accumulate the beginning positions, and also the second
1898 ;; positions, in case the line matches the bullet pattern, and then sort.
1900 (defun rst-compute-bullet-tabs (&optional pt)
1901 "Search backwards from point to build the list of possible
1902 horizontal alignment points that includes the beginning and
1903 contents of a restructuredtext bulleted or enumerated list item.
1904 Return a sorted list of (column-number . line) pairs."
1905 (save-excursion
1906 (when pt (goto-char pt))
1908 ;; We work our way backwards and towards the left.
1909 (let ((leftcol 100000) ;; Current column.
1910 (tablist nil) ;; List of tab positions.
1913 ;; Start by skipping the current line.
1914 (beginning-of-line 0)
1916 ;; Search backwards for each line.
1917 (while (and (> (point) (point-min))
1918 (> leftcol 0))
1920 ;; Skip empty lines.
1921 (unless (looking-at "^[ \t]*$")
1922 ;; Inspect the current non-empty line
1923 (back-to-indentation)
1925 ;; Skip lines that are beyond the current column (we want to move
1926 ;; towards the left).
1927 (let ((col (current-column)))
1928 (when (< col leftcol)
1930 ;; Add the beginning of the line as a tabbing point.
1931 (unless (memq col (mapcar 'car tablist))
1932 (setq tablist (cons (cons col (point)) tablist)))
1934 ;; Look at the line to figure out if it is a bulleted or enumerate
1935 ;; list item.
1936 (when (looking-at
1937 (concat
1938 "\\(?:"
1939 "\\(\\(?:[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]\\)[ \t]+\\)[^ \t\n]"
1940 "\\|"
1941 (format "\\(%s%s+[ \t]+\\)[^ \t\n]"
1942 (regexp-quote (thing-at-point 'char))
1943 (regexp-quote (thing-at-point 'char)))
1944 "\\)"
1946 ;; Add the column of the contained item.
1947 (let* ((matchlen (length (or (match-string 1) (match-string 2))))
1948 (newcol (+ col matchlen)))
1949 (unless (or (>= newcol leftcol)
1950 (memq (+ col matchlen) (mapcar 'car tablist)))
1951 (setq tablist (cons
1952 (cons (+ col matchlen) (+ (point) matchlen))
1953 tablist))))
1956 (setq leftcol col)
1959 ;; Move backwards one line.
1960 (beginning-of-line 0))
1962 (sort tablist (lambda (x y) (<= (car x) (car y))))
1965 (defun rst-debug-print-tabs (tablist)
1966 "A routine that inserts a line and places special characters at
1967 the tab points in the given tablist."
1968 (beginning-of-line)
1969 (insert (concat "\n" (make-string 1000 ? ) "\n"))
1970 (beginning-of-line 0)
1971 (dolist (col tablist)
1972 (beginning-of-line)
1973 (forward-char (car col))
1974 (delete-char 1)
1975 (insert "@")
1978 (defun rst-debug-mark-found (tablist)
1979 "A routine that inserts a line and places special characters at
1980 the tab points in the given tablist."
1981 (dolist (col tablist)
1982 (when (cdr col)
1983 (goto-char (cdr col))
1984 (insert "@"))))
1987 (defvar rst-shift-basic-offset 2
1988 "Basic horizontal shift distance when there is no preceding alignment tabs.")
1990 (defun rst-shift-region-guts (find-next-fun offset-fun)
1991 "(See rst-shift-region-right for a description.)"
1992 (let* ((mbeg (set-marker (make-marker) (region-beginning)))
1993 (mend (set-marker (make-marker) (region-end)))
1994 (tabs (rst-compute-bullet-tabs mbeg))
1995 (leftmostcol (rst-find-leftmost-column (region-beginning) (region-end)))
1997 ;; Add basic offset tabs at the end of the list. This is a better
1998 ;; implementation technique than hysteresis and a basic offset because it
1999 ;; insures that movement in both directions is consistently using the same
2000 ;; column positions. This makes it more predictable.
2001 (setq tabs
2002 (append tabs
2003 (mapcar (lambda (x) (cons x nil))
2004 (let ((maxcol 120)
2005 (max-lisp-eval-depth 2000))
2006 (flet ((addnum (x)
2007 (if (> x maxcol)
2009 (cons x (addnum
2010 (+ x rst-shift-basic-offset))))))
2011 (addnum (caar (last tabs)))))
2014 ;; (For debugging.)
2015 ;;; (save-excursion (goto-char mbeg) (forward-char -1) (rst-debug-print-tabs tabs))))
2016 ;;; (print tabs)
2017 ;;; (save-excursion (rst-debug-mark-found tabs))
2019 ;; Apply the indent.
2020 (indent-rigidly
2021 mbeg mend
2023 ;; Find the next tab after the leftmost columnt.
2024 (let ((tab (funcall find-next-fun tabs leftmostcol)))
2026 (if tab
2027 (progn
2028 (when (cdar tab)
2029 (message "Aligned on '%s'"
2030 (save-excursion
2031 (goto-char (cdar tab))
2032 (buffer-substring-no-properties
2033 (line-beginning-position)
2034 (line-end-position))))
2036 (- (caar tab) leftmostcol)) ;; Num chars.
2038 ;; Otherwise use the basic offset
2039 (funcall offset-fun rst-shift-basic-offset)
2042 ;; Optionally reindent.
2043 (when rst-shift-fill-region
2044 (fill-region mbeg mend))
2047 (defun rst-shift-region-right (pfxarg)
2048 "Indent region ridigly, by a few characters to the right. This
2049 function first computes all possible alignment columns by
2050 inspecting the lines preceding the region for bulleted or
2051 enumerated list items. If the leftmost column is beyond the
2052 preceding lines, the region is moved to the right by
2053 rst-shift-basic-offset. With a prefix argument, do not
2054 automatically fill the region."
2055 (interactive "P")
2056 (let ((rst-shift-fill-region
2057 (if (not pfxarg) rst-shift-fill-region)))
2058 (rst-shift-region-guts (lambda (tabs leftmostcol)
2059 (let ((cur tabs))
2060 (while (and cur (<= (caar cur) leftmostcol))
2061 (setq cur (cdr cur)))
2062 cur))
2063 'identity
2066 (defun rst-shift-region-left (pfxarg)
2067 "Like rst-shift-region-right, except we move to the left.
2068 Also, if invoked with a negative prefix arg, the entire
2069 indentation is removed, up to the leftmost character in the
2070 region, and automatic filling is disabled."
2071 (interactive "P")
2072 (let ((mbeg (set-marker (make-marker) (region-beginning)))
2073 (mend (set-marker (make-marker) (region-end)))
2074 (leftmostcol (rst-find-leftmost-column
2075 (region-beginning) (region-end)))
2076 (rst-shift-fill-region
2077 (if (not pfxarg) rst-shift-fill-region)))
2079 (when (> leftmostcol 0)
2080 (if (and pfxarg (< (prefix-numeric-value pfxarg) 0))
2081 (progn
2082 (indent-rigidly (region-beginning) (region-end) (- leftmostcol))
2083 (when rst-shift-fill-region
2084 (fill-region mbeg mend))
2086 (rst-shift-region-guts (lambda (tabs leftmostcol)
2087 (let ((cur (reverse tabs)))
2088 (while (and cur (>= (caar cur) leftmostcol))
2089 (setq cur (cdr cur)))
2090 cur))
2097 ;; FIXME: these next functions should become part of a larger effort to redo the
2098 ;; bullets in bulletted lists. The enumerate would just be one of the possible
2099 ;; outputs.
2101 ;; FIXME: TODO we need to do the enumeration removal as well.
2103 (defun rst-enumerate-region (rbeg rend)
2104 "Insert numbered enumeration list prefixes to the currently
2105 selected region. With prefix argument, remove the enumeration.
2106 (Note: the removal part of not implemented yet.)"
2107 (interactive "r")
2108 (save-excursion
2109 (goto-char rend)
2110 (beginning-of-line)
2112 (let (tight-rbeg
2113 tight-rend
2114 ;; Count the number of lines in the region
2115 (nlines (count-lines rbeg rend))
2116 ;; Find the minimum column in all the lines in the region
2117 (lcol (rst-find-leftmost-column rbeg rend))
2118 (curnum 1))
2120 (let ((curindex 1))
2121 (operate-on-rectangle 'rst-enumerate-insert-enum rbeg rend t)))
2124 (defun rst-enumerate-insert-enum (startpos begextra endextra)
2125 (back-to-indentation)
2126 (if (= (current-column) lcol)
2127 (progn
2128 (insert (int-to-string curnum))
2129 (insert ". ")
2130 (incf curnum))
2131 (indent-line-to (+ lcol 3))))
2134 (defun rst-line-block-region (rbeg rend &optional pfxarg)
2135 "Toggle line block prefixes for a region."
2136 (interactive "r\nP")
2137 (let ((comment-start "| ")
2138 (comment-end "")
2139 (comment-start-skip "| ")
2140 (comment-style 'indent)
2141 (comment-multi-line nil))
2142 (funcall (if pfxarg 'uncomment-region 'comment-region)
2143 rbeg rend)))
2145 ;; FIXME todo: we need to provide the option of adding the line block chars for
2146 ;; empty lines as well. Sometimes this has to be decided by the user, but in
2147 ;; certain cases it could be detected automatically, e.g.
2149 ;; Foo
2151 ;; Bar
2153 ;; Foo2
2159 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2160 ;;; rst-mode.el --- Mode for viewing and editing reStructuredText-documents.
2162 ;; Copyright 2003 Stefan Merten <smerten@oekonux.de>
2164 ;; Note: this is an update from version 0.2.9 of rst-mode.el
2166 ;; DESCRIPTION
2168 ;; This package provides support for documents marked up using the
2169 ;; reStructuredText format. Support includes font locking as well as some
2170 ;; convenience functions for editing. It does this by defining a Emacs major
2171 ;; mode.
2173 ;; The package is based on text-mode and inherits some things from it.
2174 ;; Particularly text-mode-hook is run before rst-mode-hook.
2176 ;; OPTIONS
2178 ;; There are a number of things which can be customized using the standard
2179 ;; Emacs customization features. There are two customization groups for this
2180 ;; mode.
2182 ;; Customization
2183 ;; =============
2185 ;; rst
2186 ;; ---
2187 ;; This group contains some general customizable features.
2189 ;; The group is contained in the wp group.
2191 ;; rst-faces
2192 ;; ---------
2193 ;; This group contains all necessary for customizing fonts. The default
2194 ;; settings use standard font-lock-*-face's so if you set these to your
2195 ;; liking they are probably good in rst-mode also.
2197 ;; The group is contained in the faces group as well as in the rst group.
2199 ;; rst-faces-defaults
2200 ;; ------------------
2201 ;; This group contains all necessary for customizing the default fonts used for
2202 ;; section title faces.
2204 ;; The general idea for section title faces is to have a non-default background
2205 ;; but do not change the background. The section level is shown by the
2206 ;; lightness of the background color. If you like this general idea of
2207 ;; generating faces for section titles but do not like the details this group
2208 ;; is the point where you can customize the details. If you do not like the
2209 ;; general idea, however, you should customize the faces used in
2210 ;; rst-adornment-faces-alist.
2212 ;; Note: If you are using a dark background please make sure the variable
2213 ;; frame-background-mode is set to the symbol dark. This triggers
2214 ;; some default values which are probably right for you.
2216 ;; The group is contained in the rst-faces group.
2218 ;; All customizable features have a comment explaining their meaning. Refer to
2219 ;; the customization of your Emacs (try ``M-x customize``).
2221 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2222 ;;; Customization:
2224 (defcustom rst-mode-hook nil
2225 "Hook run when Rst Mode is turned on. The hook for Text Mode is run before
2226 this one."
2227 :group 'rst
2228 :type '(hook))
2230 (defcustom rst-mode-lazy t
2231 "*If non-nil Rst Mode font-locks comment, literal blocks, and section titles
2232 correctly. Because this is really slow it switches on Lazy Lock Mode
2233 automatically. You may increase Lazy Lock Defer Time for reasonable results.
2235 If nil comments and literal blocks are font-locked only on the line they start.
2237 The value of this variable is used when Rst Mode is turned on."
2238 :group 'rst
2239 :type '(boolean))
2241 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2243 (defgroup rst-faces nil "Faces used in Rst Mode"
2244 :group 'rst
2245 :group 'faces
2246 :version "21.1")
2248 (defcustom rst-block-face 'font-lock-keyword-face
2249 "All syntax marking up a special block"
2250 :group 'rst-faces
2251 :type '(face))
2253 (defcustom rst-external-face 'font-lock-type-face
2254 "Field names and interpreted text"
2255 :group 'rst-faces
2256 :type '(face))
2258 (defcustom rst-definition-face 'font-lock-function-name-face
2259 "All other defining constructs"
2260 :group 'rst-faces
2261 :type '(face))
2263 (defcustom rst-directive-face
2264 ;; XEmacs compatibility
2265 (if (boundp 'font-lock-builtin-face)
2266 'font-lock-builtin-face
2267 'font-lock-preprocessor-face)
2268 "Directives and roles"
2269 :group 'rst-faces
2270 :type '(face))
2272 (defcustom rst-comment-face 'font-lock-comment-face
2273 "Comments"
2274 :group 'rst-faces
2275 :type '(face))
2277 (defcustom rst-emphasis1-face
2278 ;; XEmacs compatibility
2279 (if (facep 'italic)
2280 ''italic
2281 'italic)
2282 "Simple emphasis"
2283 :group 'rst-faces
2284 :type '(face))
2286 (defcustom rst-emphasis2-face
2287 ;; XEmacs compatibility
2288 (if (facep 'bold)
2289 ''bold
2290 'bold)
2291 "Double emphasis"
2292 :group 'rst-faces
2293 :type '(face))
2295 (defcustom rst-literal-face 'font-lock-string-face
2296 "Literal text"
2297 :group 'rst-faces
2298 :type '(face))
2300 (defcustom rst-reference-face 'font-lock-variable-name-face
2301 "References to a definition"
2302 :group 'rst-faces
2303 :type '(face))
2305 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2307 (defgroup rst-faces-defaults nil
2308 "Values used to generate default faces for section titles on all levels.
2309 Tweak these if you are content with how section title faces are built in
2310 general but you do not like the details."
2311 :group 'rst-faces
2312 :version "21.1")
2314 (defun rst-define-level-faces ()
2315 "Define the faces for the section title text faces from the values."
2316 ;; All variables used here must be checked in `rst-set-level-default'
2317 (let ((i 1))
2318 (while (<= i rst-level-face-max)
2319 (let ((sym (intern (format "rst-level-%d-face" i)))
2320 (doc (format "Face for showing section title text at level %d" i))
2321 (col (format (concat "%s" rst-level-face-format-light)
2322 rst-level-face-base-color
2323 (+ (* (1- i) rst-level-face-step-light)
2324 rst-level-face-base-light))))
2325 (make-empty-face sym)
2326 (set-face-doc-string sym doc)
2327 (set-face-background sym col)
2328 (set sym sym)
2329 (setq i (1+ i))))))
2331 (defun rst-set-level-default (sym val)
2332 "Set a customized value affecting section title text face and recompute the
2333 faces."
2334 (custom-set-default sym val)
2335 ;; Also defines the faces initially when all values are available
2336 (and (boundp 'rst-level-face-max)
2337 (boundp 'rst-level-face-format-light)
2338 (boundp 'rst-level-face-base-color)
2339 (boundp 'rst-level-face-step-light)
2340 (boundp 'rst-level-face-base-light)
2341 (rst-define-level-faces)))
2343 ;; Faces for displaying items on several levels; these definitions define
2344 ;; different shades of grey where the lightest one (i.e. least contrasting) is
2345 ;; used for level 1
2346 (defcustom rst-level-face-max 6
2347 "Maximum depth of levels for which section title faces are defined."
2348 :group 'rst-faces-defaults
2349 :type '(integer)
2350 :set 'rst-set-level-default)
2351 (defcustom rst-level-face-base-color "grey"
2352 "The base name of the color to be used for creating background colors in
2353 ection title faces for all levels."
2354 :group 'rst-faces-defaults
2355 :type '(string)
2356 :set 'rst-set-level-default)
2357 (defcustom rst-level-face-base-light
2358 (if (eq frame-background-mode 'dark)
2361 "The lightness factor for the base color. This value is used for level 1. The
2362 default depends on whether the value of `frame-background-mode' is `dark' or
2363 not."
2364 :group 'rst-faces-defaults
2365 :type '(integer)
2366 :set 'rst-set-level-default)
2367 (defcustom rst-level-face-format-light "%2d"
2368 "The format for the lightness factor appended to the base name of the color.
2369 This value is expanded by `format' with an integer."
2370 :group 'rst-faces-defaults
2371 :type '(string)
2372 :set 'rst-set-level-default)
2373 (defcustom rst-level-face-step-light
2374 (if (eq frame-background-mode 'dark)
2377 "The step width to use for the next color. The formula
2379 `rst-level-face-base-light'
2380 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
2382 must result in a color level which appended to `rst-level-face-base-color'
2383 using `rst-level-face-format-light' results in a valid color such as `grey50'.
2384 This color is used as background for section title text on level
2385 `rst-level-face-max'."
2386 :group 'rst-faces-defaults
2387 :type '(integer)
2388 :set 'rst-set-level-default)
2390 (defcustom rst-adornment-faces-alist
2391 (let ((alist '((t . font-lock-keyword-face)
2392 (nil . font-lock-keyword-face)))
2393 (i 1))
2394 (while (<= i rst-level-face-max)
2395 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
2396 (setq i (1+ i)))
2397 alist)
2398 "Provides faces for the various adornment types. Key is a number (for the
2399 section title text of that level), t (for transitions) or nil (for section
2400 title adornment). If you generally do not like how section title text faces are
2401 set up tweak here. If the general idea is ok for you but you do not like the
2402 details check the Rst Faces Defaults group."
2403 :group 'rst-faces
2404 :type '(alist
2405 :key-type
2406 (choice
2407 (integer
2408 :tag
2409 "Section level (may not be bigger than `rst-level-face-max')")
2410 (boolean :tag "transitions (on) / section title adornment (off)"))
2411 :value-type (face))
2412 :set-after '(rst-level-face-max))
2414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2416 ;; FIXME: Code from `restructuredtext.el' should be integrated
2418 (defvar rst-mode-syntax-table nil
2419 "Syntax table used while in rst mode.")
2421 (unless rst-mode-syntax-table
2422 (setq rst-mode-syntax-table (make-syntax-table text-mode-syntax-table))
2423 (modify-syntax-entry ?$ "." rst-mode-syntax-table)
2424 (modify-syntax-entry ?% "." rst-mode-syntax-table)
2425 (modify-syntax-entry ?& "." rst-mode-syntax-table)
2426 (modify-syntax-entry ?' "." rst-mode-syntax-table)
2427 (modify-syntax-entry ?* "." rst-mode-syntax-table)
2428 (modify-syntax-entry ?+ "." rst-mode-syntax-table)
2429 (modify-syntax-entry ?. "_" rst-mode-syntax-table)
2430 (modify-syntax-entry ?/ "." rst-mode-syntax-table)
2431 (modify-syntax-entry ?< "." rst-mode-syntax-table)
2432 (modify-syntax-entry ?= "." rst-mode-syntax-table)
2433 (modify-syntax-entry ?> "." rst-mode-syntax-table)
2434 (modify-syntax-entry ?\\ "\\" rst-mode-syntax-table)
2435 (modify-syntax-entry ?| "." rst-mode-syntax-table)
2436 (modify-syntax-entry ?_ "." rst-mode-syntax-table)
2439 (defvar rst-mode-abbrev-table nil
2440 "Abbrev table used while in rst mode.")
2441 (define-abbrev-table 'rst-mode-abbrev-table ())
2443 ;; FIXME: Movement keys to skip forward / backward over or mark an indented
2444 ;; block could be defined; keys to markup section titles based on
2445 ;; `rst-adornment-level-alist' would be useful
2446 (defvar rst-mode-map nil
2447 "Keymap for rst mode. This inherits from Text mode.")
2449 (unless rst-mode-map
2450 (setq rst-mode-map (copy-keymap text-mode-map)))
2452 (defun rst-mode ()
2453 "Major mode for editing reStructuredText documents.
2455 You may customize `rst-mode-lazy' to switch font-locking of blocks.
2457 \\{rst-mode-map}
2458 Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
2459 `rst-mode-hook'."
2460 (interactive)
2461 (kill-all-local-variables)
2463 ;; Maps and tables
2464 (use-local-map rst-mode-map)
2465 (setq local-abbrev-table rst-mode-abbrev-table)
2466 (set-syntax-table rst-mode-syntax-table)
2468 ;; For editing text
2470 ;; FIXME: It would be better if this matches more exactly the start of a reST
2471 ;; paragraph; however, this not always possible with a simple regex because
2472 ;; paragraphs are determined by indentation of the following line
2473 (set (make-local-variable 'paragraph-start)
2474 (concat page-delimiter "\\|[ \t]*$"))
2475 (if (eq ?^ (aref paragraph-start 0))
2476 (setq paragraph-start (substring paragraph-start 1)))
2477 (set (make-local-variable 'paragraph-separate) paragraph-start)
2478 (set (make-local-variable 'indent-line-function) 'indent-relative-maybe)
2479 (set (make-local-variable 'adaptive-fill-mode) t)
2480 (set (make-local-variable 'comment-start) ".. ")
2482 ;; Special variables
2483 (make-local-variable 'rst-adornment-level-alist)
2485 ;; Font lock
2486 (set (make-local-variable 'font-lock-defaults)
2487 '(rst-font-lock-keywords-function
2488 t nil nil nil
2489 (font-lock-multiline . t)
2490 (font-lock-mark-block-function . mark-paragraph)))
2491 (when (boundp 'font-lock-support-mode)
2492 ;; rst-mode has its own mind about font-lock-support-mode
2493 (make-local-variable 'font-lock-support-mode)
2494 (cond
2495 ((and (not rst-mode-lazy) (not font-lock-support-mode)))
2496 ;; No support mode set and none required - leave it alone
2497 ((or (not font-lock-support-mode) ;; No support mode set (but required)
2498 (symbolp font-lock-support-mode)) ;; or a fixed mode for all
2499 (setq font-lock-support-mode
2500 (list (cons 'rst-mode (and rst-mode-lazy 'lazy-lock-mode))
2501 (cons t font-lock-support-mode))))
2502 ((and (listp font-lock-support-mode)
2503 (not (assoc 'rst-mode font-lock-support-mode)))
2504 ;; A list of modes missing rst-mode
2505 (setq font-lock-support-mode
2506 (append '((cons 'rst-mode (and rst-mode-lazy 'lazy-lock-mode)))
2507 font-lock-support-mode)))))
2509 ;; Names and hooks
2510 (setq mode-name "reST")
2511 (setq major-mode 'rst-mode)
2512 (run-hooks 'text-mode-hook)
2513 (run-hooks 'rst-mode-hook))
2515 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2516 ;; Font lock
2518 (defun rst-font-lock-keywords-function ()
2519 "Returns keywords to highlight in rst mode according to current settings."
2520 ;; The reST-links in the comments below all relate to sections in
2521 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
2522 (let* ( ;; This gets big - so let's define some abbreviations
2523 ;; horizontal white space
2524 (re-hws "[\t ]")
2525 ;; beginning of line with possible indentation
2526 (re-bol (concat "^" re-hws "*"))
2527 ;; Separates block lead-ins from their content
2528 (re-blksep1 (concat "\\(" re-hws "+\\|$\\)"))
2529 ;; explicit markup tag
2530 (re-emt "\\.\\.")
2531 ;; explicit markup start
2532 (re-ems (concat re-emt re-hws "+"))
2533 ;; inline markup prefix
2534 (re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{</:]\\)"))
2535 ;; inline markup suffix
2536 (re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
2537 ;; symbol character
2538 (re-sym1 "\\(\\sw\\|\\s_\\)")
2539 ;; inline markup content begin
2540 (re-imbeg2 "\\(\\S \\|\\S \\([^")
2542 ;; There seems to be a bug leading to error "Stack overflow in regexp
2543 ;; matcher" when "|" or "\\*" are the characters searched for
2544 (re-imendbeg
2545 (if (< emacs-major-version 21)
2547 "\\]\\|\\\\."))
2548 ;; inline markup content end
2549 (re-imend (concat re-imendbeg "\\)*[^\t \\\\]\\)"))
2550 ;; inline markup content without asterisk
2551 (re-ima2 (concat re-imbeg2 "*" re-imend))
2552 ;; inline markup content without backquote
2553 (re-imb2 (concat re-imbeg2 "`" re-imend))
2554 ;; inline markup content without vertical bar
2555 (re-imv2 (concat re-imbeg2 "|" re-imend))
2556 ;; Supported URI schemes
2557 (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\\)")
2558 ;; Line starting with adornment and optional whitespace; complete
2559 ;; adornment is in (match-string 1); there must be at least 3
2560 ;; characters because otherwise explicit markup start would be
2561 ;; recognized
2562 (re-ado2 (concat "^\\(\\(["
2563 (if (or
2564 (< emacs-major-version 21)
2565 (save-match-data
2566 (string-match "XEmacs\\|Lucid" emacs-version)))
2567 "^a-zA-Z0-9 \t\x00-\x1F"
2568 "^[:word:][:space:][:cntrl:]")
2569 "]\\)\\2\\2+\\)" re-hws "*$"))
2571 (list
2572 ;; FIXME: Block markup is not recognized in blocks after explicit markup
2573 ;; start
2575 ;; Simple `Body Elements`_
2576 ;; `Bullet Lists`_
2577 (list
2578 (concat re-bol "\\([-*+]" re-blksep1 "\\)")
2579 1 rst-block-face)
2580 ;; `Enumerated Lists`_
2581 (list
2582 (concat re-bol "\\((?\\([0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
2583 re-blksep1 "\\)")
2584 1 rst-block-face)
2585 ;; `Definition Lists`_ FIXME: missing
2586 ;; `Field Lists`_
2587 (list
2588 (concat re-bol "\\(:[^:]+:\\)" re-blksep1)
2589 1 rst-external-face)
2590 ;; `Option Lists`_
2591 (list
2592 (concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
2593 "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
2594 1 rst-block-face)
2596 ;; `Tables`_ FIXME: missing
2598 ;; All the `Explicit Markup Blocks`_
2599 ;; `Footnotes`_ / `Citations`_
2600 (list
2601 (concat re-bol "\\(" re-ems "\\[[^[]+\\]\\)" re-blksep1)
2602 1 rst-definition-face)
2603 ;; `Directives`_ / `Substitution Definitions`_
2604 (list
2605 (concat re-bol "\\(" re-ems "\\)\\(\\(|[^|]+|[\t ]+\\)?\\)\\("
2606 re-sym1 "+::\\)" re-blksep1)
2607 (list 1 rst-directive-face)
2608 (list 2 rst-definition-face)
2609 (list 4 rst-directive-face))
2610 ;; `Hyperlink Targets`_
2611 (list
2612 (concat re-bol "\\(" re-ems "_\\([^:\\`]\\|\\\\.\\|`[^`]+`\\)+:\\)"
2613 re-blksep1)
2614 1 rst-definition-face)
2615 (list
2616 (concat re-bol "\\(__\\)" re-blksep1)
2617 1 rst-definition-face)
2619 ;; All `Inline Markup`_
2620 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
2621 ;; `Strong Emphasis`_
2622 (list
2623 (concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
2624 2 rst-emphasis2-face)
2625 ;; `Emphasis`_
2626 (list
2627 (concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
2628 2 rst-emphasis1-face)
2629 ;; `Inline Literals`_
2630 (list
2631 (concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
2632 2 rst-literal-face)
2633 ;; `Inline Internal Targets`_
2634 (list
2635 (concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
2636 2 rst-definition-face)
2637 ;; `Hyperlink References`_
2638 ;; FIXME: `Embedded URIs`_ not considered
2639 (list
2640 (concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\sw+\\)__?\\)" re-ims1)
2641 2 rst-reference-face)
2642 ;; `Interpreted Text`_
2643 (list
2644 (concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:"
2645 re-sym1 "+:\\)?\\)" re-ims1)
2646 (list 2 rst-directive-face)
2647 (list 5 rst-external-face)
2648 (list 8 rst-directive-face))
2649 ;; `Footnote References`_ / `Citation References`_
2650 (list
2651 (concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
2652 2 rst-reference-face)
2653 ;; `Substitution References`_
2654 (list
2655 (concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
2656 2 rst-reference-face)
2657 ;; `Standalone Hyperlinks`_
2658 (list
2659 ;; FIXME: This takes it easy by using a whitespace as delimiter
2660 (concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1)
2661 2 rst-definition-face)
2662 (list
2663 (concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
2664 2 rst-definition-face)
2666 ;; Do all block fontification as late as possible so 'append works
2668 ;; Sections_ / Transitions_
2669 (append
2670 (list
2671 re-ado2)
2672 (if (not rst-mode-lazy)
2673 (list 1 rst-block-face)
2674 (list
2675 (list 'rst-font-lock-handle-adornment
2676 '(progn
2677 (setq rst-font-lock-adornment-point (match-end 1))
2678 (point-max))
2680 (list 1 '(cdr (assoc nil rst-adornment-faces-alist))
2681 'append t)
2682 (list 2 '(cdr (assoc rst-font-lock-level
2683 rst-adornment-faces-alist))
2684 'append t)
2685 (list 3 '(cdr (assoc nil rst-adornment-faces-alist))
2686 'append t)))))
2688 ;; `Comments`_
2689 (append
2690 (list
2691 (concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:]\\|:\\([^:]\\|$\\)\\)*$")
2692 (list 1 rst-comment-face))
2693 (if rst-mode-lazy
2694 (list
2695 (list 'rst-font-lock-find-unindented-line
2696 '(progn
2697 (setq rst-font-lock-indentation-point (match-end 1))
2698 (point-max))
2700 (list 0 rst-comment-face 'append)))))
2701 (append
2702 (list
2703 (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)\\?$")
2704 (list 1 rst-comment-face)
2705 (list 2 rst-comment-face))
2706 (if rst-mode-lazy
2707 (list
2708 (list 'rst-font-lock-find-unindented-line
2709 '(progn
2710 (setq rst-font-lock-indentation-point 'next)
2711 (point-max))
2713 (list 0 rst-comment-face 'append)))))
2715 ;; `Literal Blocks`_
2716 (append
2717 (list
2718 (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
2719 (list 3 rst-block-face))
2720 (if rst-mode-lazy
2721 (list
2722 (list 'rst-font-lock-find-unindented-line
2723 '(progn
2724 (setq rst-font-lock-indentation-point t)
2725 (point-max))
2727 (list 0 rst-literal-face 'append)))))
2730 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2731 ;; Indented blocks
2733 (defun rst-forward-indented-block (&optional column limit)
2734 "Move forward across one indented block.
2735 Find the next non-empty line which is not indented at least to COLUMN (defaults
2736 to the column of the point). Moves point to first character of this line or the
2737 first empty line immediately before it and returns that position. If there is
2738 no such line before LIMIT (defaults to the end of the buffer) returns nil and
2739 point is not moved."
2740 (interactive)
2741 (let ((clm (or column (current-column)))
2742 (start (point))
2743 fnd beg cand)
2744 (if (not limit)
2745 (setq limit (point-max)))
2746 (save-match-data
2747 (while (and (not fnd) (< (point) limit))
2748 (forward-line 1)
2749 (when (< (point) limit)
2750 (setq beg (point))
2751 (if (looking-at "\\s *$")
2752 (setq cand (or cand beg)) ; An empty line is a candidate
2753 (move-to-column clm)
2754 ;; FIXME: No indentation [(zerop clm)] must be handled in some
2755 ;; useful way - though it is not clear what this should mean at all
2756 (if (string-match
2757 "^\\s *$" (buffer-substring-no-properties beg (point)))
2758 (setq cand nil) ; An indented line resets a candidate
2759 (setq fnd (or cand beg)))))))
2760 (goto-char (or fnd start))
2761 fnd))
2763 ;; Stores the point where the current indentation ends if a number. If `next'
2764 ;; indicates `rst-font-lock-find-unindented-line' shall take the indentation
2765 ;; from the next line if this is not empty. If non-nil indicates
2766 ;; `rst-font-lock-find-unindented-line' shall take the indentation from the
2767 ;; next non-empty line. Also used as a trigger for
2768 ;; `rst-font-lock-find-unindented-line'.
2769 (defvar rst-font-lock-indentation-point nil)
2771 (defun rst-font-lock-find-unindented-line (limit)
2772 (let* ((ind-pnt rst-font-lock-indentation-point)
2773 (beg-pnt ind-pnt))
2774 ;; May run only once - enforce this
2775 (setq rst-font-lock-indentation-point nil)
2776 (when (and ind-pnt (not (numberp ind-pnt)))
2777 ;; Find indentation point in next line if any
2778 (setq ind-pnt
2779 (save-excursion
2780 (save-match-data
2781 (if (eq ind-pnt 'next)
2782 (when (and (zerop (forward-line 1)) (< (point) limit))
2783 (setq beg-pnt (point))
2784 (when (not (looking-at "\\s *$"))
2785 (looking-at "\\s *")
2786 (match-end 0)))
2787 (while (and (zerop (forward-line 1)) (< (point) limit)
2788 (looking-at "\\s *$")))
2789 (when (< (point) limit)
2790 (setq beg-pnt (point))
2791 (looking-at "\\s *")
2792 (match-end 0)))))))
2793 (when ind-pnt
2794 (goto-char ind-pnt)
2795 ;; Always succeeds because the limit set by PRE-MATCH-FORM is the
2796 ;; ultimate point to find
2797 (goto-char (or (rst-forward-indented-block nil limit) limit))
2798 (set-match-data (list beg-pnt (point)))
2799 t)))
2801 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2802 ;; Adornments
2804 ;; Stores the point where the current adornment ends. Also used as a trigger
2805 ;; for `rst-font-lock-handle-adornment'.
2806 (defvar rst-font-lock-adornment-point nil)
2808 ;; Here `rst-font-lock-handle-adornment' stores the section level of the
2809 ;; current adornment or t for a transition.
2810 (defvar rst-font-lock-level nil)
2812 ;; FIXME: It would be good if this could be used to markup section titles of
2813 ;; given level with a special key; it would be even better to be able to
2814 ;; customize this so it can be used for a generally available personal style
2816 ;; FIXME: There should be some way to reset and reload this variable - probably
2817 ;; a special key
2819 ;; FIXME: Some support for `outline-mode' would be nice which should be based
2820 ;; on this information
2821 (defvar rst-adornment-level-alist nil
2822 "Associates adornments with section levels.
2823 The key is a two character string. The first character is the adornment
2824 character. The second character distinguishes underline section titles (`u')
2825 from overline/underline section titles (`o'). The value is the section level.
2827 This is made buffer local on start and adornments found during font lock are
2828 entered.")
2830 ;; Returns section level for adornment key KEY. Adds new section level if KEY
2831 ;; is not found and ADD. If KEY is not a string it is simply returned.
2832 (defun rst-adornment-level (key &optional add)
2833 (let ((fnd (assoc key rst-adornment-level-alist))
2834 (new 1))
2835 (cond
2836 ((not (stringp key))
2837 key)
2838 (fnd
2839 (cdr fnd))
2840 (add
2841 (while (rassoc new rst-adornment-level-alist)
2842 (setq new (1+ new)))
2843 (setq rst-adornment-level-alist
2844 (append rst-adornment-level-alist (list (cons key new))))
2845 new))))
2847 ;; Classifies adornment for section titles and transitions. ADORNMENT is the
2848 ;; complete adornment string as found in the buffer. END is the point after the
2849 ;; last character of ADORNMENT. For overline section adornment LIMIT limits the
2850 ;; search for the matching underline. Returns a list. The first entry is t for
2851 ;; a transition, or a key string for `rst-adornment-level' for a section title.
2852 ;; The following eight values forming four match groups as can be used for
2853 ;; `set-match-data'. First match group contains the maximum points of the whole
2854 ;; construct. Second and last match group matched pure section title adornment
2855 ;; while third match group matched the section title text or the transition.
2856 ;; Each group but the first may or may not exist.
2857 (defun rst-classify-adornment (adornment end limit)
2858 (save-excursion
2859 (save-match-data
2860 (goto-char end)
2861 (let ((ado-ch (aref adornment 0))
2862 (ado-re (regexp-quote adornment))
2863 (end-pnt (point))
2864 (beg-pnt (progn
2865 (forward-line 0)
2866 (point)))
2867 (nxt-emp
2868 (save-excursion
2869 (or (not (zerop (forward-line 1)))
2870 (looking-at "\\s *$"))))
2871 (prv-emp
2872 (save-excursion
2873 (or (not (zerop (forward-line -1)))
2874 (looking-at "\\s *$"))))
2875 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
2876 (cond
2877 ((and nxt-emp prv-emp)
2878 ;; A transition
2879 (setq key t)
2880 (setq beg-txt beg-pnt)
2881 (setq end-txt end-pnt))
2882 (prv-emp
2883 ;; An overline
2884 (setq key (concat (list ado-ch) "o"))
2885 (setq beg-ovr beg-pnt)
2886 (setq end-ovr end-pnt)
2887 (forward-line 1)
2888 (setq beg-txt (point))
2889 (while (and (< (point) limit) (not end-txt))
2890 (if (looking-at "\\s *$")
2891 ;; No underline found
2892 (setq end-txt (1- (point)))
2893 (when (looking-at (concat "\\(" ado-re "\\)\\s *$"))
2894 (setq end-und (match-end 1))
2895 (setq beg-und (point))
2896 (setq end-txt (1- beg-und))))
2897 (forward-line 1)))
2899 ;; An underline
2900 (setq key (concat (list ado-ch) "u"))
2901 (setq beg-und beg-pnt)
2902 (setq end-und end-pnt)
2903 (setq end-txt (1- beg-und))
2904 (setq beg-txt (progn
2905 (if (re-search-backward "^\\s *$" 1 'move)
2906 (forward-line 1))
2907 (point)))))
2908 (list key
2909 (or beg-ovr beg-txt beg-und)
2910 (or end-und end-txt end-und)
2911 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
2913 ;; Handles adornments for font-locking section titles and transitions. Returns
2914 ;; three match groups. First and last match group matched pure overline /
2915 ;; underline adornment while second group matched section title text. Each
2916 ;; group may not exist.
2917 (defun rst-font-lock-handle-adornment (limit)
2918 (let ((ado-pnt rst-font-lock-adornment-point))
2919 ;; May run only once - enforce this
2920 (setq rst-font-lock-adornment-point nil)
2921 (if ado-pnt
2922 (let* ((ado (rst-classify-adornment (match-string-no-properties 1)
2923 ado-pnt limit))
2924 (key (car ado))
2925 (mtc (cdr ado)))
2926 (setq rst-font-lock-level (rst-adornment-level key t))
2927 (goto-char (nth 1 mtc))
2928 (set-match-data mtc)
2929 t))))
2931 ;;; rst-mode.el ends here
2935 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2936 ;; Support for conversion from within Emacs
2938 (defgroup rst-compile nil
2939 "Settings for support of conversion of reStructuredText
2940 document with \\[rst-compile]."
2941 :group 'rst
2942 :version "21.1")
2944 (defvar rst-compile-toolsets
2945 '((html . ("rst2html.py" ".html" nil))
2946 (latex . ("rst2latex.py" ".tex" nil))
2947 (newlatex . ("rst2newlatex.py" ".tex" nil))
2948 (pseudoxml . ("rst2pseudoxml.py" ".xml" nil))
2949 (xml . ("rst2xml.py" ".xml" nil)))
2950 "An association list of the toolset to a list of the (command to use,
2951 extension of produced filename, options to the tool (nil or a
2952 string)) to be used for converting the document.")
2954 ;; Note for Python programmers not familiar with association lists: you can set
2955 ;; values in an alists like this, e.g. :
2956 ;; (setcdr (assq 'html rst-compile-toolsets)
2957 ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
2960 (defvar rst-compile-primary-toolset 'html
2961 "The default toolset for rst-compile.")
2963 (defvar rst-compile-secondary-toolset 'latex
2964 "The default toolset for rst-compile with a prefix argument.")
2966 (defun rst-compile-find-conf ()
2967 "Look for the configuration file in the parents of the current path."
2968 (interactive)
2969 (let ((file-name "docutils.conf")
2970 (buffer-file (buffer-file-name)))
2971 ;; Move up in the dir hierarchy till we find a change log file.
2972 (let ((dir (file-name-directory buffer-file)))
2973 (while (and (or (not (string= "/" dir)) (setq dir nil) nil)
2974 (not (file-exists-p (concat dir file-name))))
2975 ;; Move up to the parent dir and try again.
2976 (setq dir (expand-file-name (file-name-directory
2977 (directory-file-name
2978 (file-name-directory dir))))) )
2979 (or (and dir (concat dir file-name)) nil)
2983 (require 'compile)
2985 (defun rst-compile (&optional pfxarg)
2986 "Compile command to convert reST document into some output file.
2987 Attempts to find configuration file, if it can, overrides the
2988 options."
2989 (interactive "P")
2990 ;; Note: maybe we want to check if there is a Makefile too and not do anything
2991 ;; if that is the case. I dunno.
2992 (let* ((toolset (cdr (assq (if pfxarg
2993 rst-compile-secondary-toolset
2994 rst-compile-primary-toolset)
2995 rst-compile-toolsets)))
2996 (command (car toolset))
2997 (extension (cadr toolset))
2998 (options (caddr toolset))
2999 (conffile (rst-compile-find-conf))
3000 (bufname (file-name-nondirectory buffer-file-name))
3001 (outname (file-name-sans-extension bufname)))
3003 ;; Set compile-command before invocation of compile.
3004 (set (make-local-variable 'compile-command)
3005 (mapconcat 'identity
3006 (list command
3007 (or options "")
3008 (if conffile
3009 (concat "--config=\"" conffile "\"")
3011 bufname
3012 (concat outname extension))
3013 " "))
3015 ;; Invoke the compile command.
3016 (if (or compilation-read-command current-prefix-arg)
3017 (call-interactively 'compile)
3018 (compile compile-command))
3023 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3025 ;; Generic text functions that are more convenient than the defaults.
3028 (defun replace-lines (fromchar tochar)
3029 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
3030 with equal-length lines of TOCHAR."
3031 (interactive "\
3032 cSearch for flush-left lines of char:
3033 cand replace with char: ")
3034 (save-excursion
3035 (let* ((fromstr (string fromchar))
3036 (searchre (concat "^" (regexp-quote fromstr) "+ *$"))
3037 (found 0))
3038 (condition-case err
3039 (while t
3040 (search-forward-regexp searchre)
3041 (setq found (1+ found))
3042 (search-backward fromstr) ;; point will be *before* last char
3043 (setq p (1+ (point)))
3044 (beginning-of-line)
3045 (setq l (- p (point)))
3046 (rst-delete-line)
3047 (insert-char tochar l))
3048 (search-failed
3049 (message (format "%d lines replaced." found)))))))
3051 (defun join-paragraph ()
3052 "Join lines in current paragraph into one line, removing end-of-lines."
3053 (interactive)
3054 (let ((fill-column 65000)) ; some big number
3055 (call-interactively 'fill-paragraph)))
3057 ;; FIXME: can we remove this?
3058 (defun force-fill-paragraph ()
3059 "Fill paragraph at point, first joining the paragraph's lines into one.
3060 This is useful for filling list item paragraphs."
3061 (interactive)
3062 (join-paragraph)
3063 (fill-paragraph nil))
3066 ;; Generic character repeater function.
3067 ;; For sections, better to use the specialized function above, but this can
3068 ;; be useful for creating separators.
3069 (defun repeat-last-character (&optional tofill)
3070 "Fills the current line up to the length of the preceding line (if not
3071 empty), using the last character on the current line. If the preceding line is
3072 empty, we use the fill-column.
3074 If a prefix argument is provided, use the next line rather than the preceding
3075 line.
3077 If the current line is longer than the desired length, shave the characters off
3078 the current line to fit the desired length.
3080 As an added convenience, if the command is repeated immediately, the alternative
3081 column is used (fill-column vs. end of previous/next line)."
3082 (interactive)
3083 (let* ((curcol (current-column))
3084 (curline (+ (count-lines (point-min) (point))
3085 (if (eq curcol 0) 1 0)))
3086 (lbp (line-beginning-position 0))
3087 (prevcol (if (and (= curline 1) (not current-prefix-arg))
3088 fill-column
3089 (save-excursion
3090 (forward-line (if current-prefix-arg 1 -1))
3091 (end-of-line)
3092 (skip-chars-backward " \t" lbp)
3093 (let ((cc (current-column)))
3094 (if (= cc 0) fill-column cc)))))
3095 (rightmost-column
3096 (cond (tofill fill-column)
3097 ((equal last-command 'repeat-last-character)
3098 (if (= curcol fill-column) prevcol fill-column))
3099 (t (save-excursion
3100 (if (= prevcol 0) fill-column prevcol)))
3101 )) )
3102 (end-of-line)
3103 (if (> (current-column) rightmost-column)
3104 ;; shave characters off the end
3105 (delete-region (- (point)
3106 (- (current-column) rightmost-column))
3107 (point))
3108 ;; fill with last characters
3109 (insert-char (preceding-char)
3110 (- rightmost-column (current-column))))
3115 (provide 'rst)
3116 ;;; rst.el ends here