1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Maintainer: Stefan Merten <smerten@oekonux.de>
6 ;; Author: Stefan Merten <smerten@oekonux.de>,
7 ;; Martin Blais <blais@furius.ca>,
8 ;; David Goodger <goodger@python.org>,
9 ;; Wei-Wei Guo <wwguocn@gmail.com>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; This package provides major mode rst-mode, which supports documents marked
29 ;; up using the reStructuredText format. Support includes font locking as well
30 ;; as a lot of convenience functions for editing. It does this by defining a
31 ;; Emacs major mode: rst-mode (ReST). This mode is derived from text-mode.
32 ;; This package also contains:
34 ;; - Functions to automatically adjust and cycle the section underline
36 ;; - A mode that displays the table of contents and allows you to jump anywhere
38 ;; - Functions to insert and automatically update a TOC in your source
40 ;; - Function to insert list, processing item bullets and enumerations
42 ;; - Font-lock highlighting of most reStructuredText structures;
43 ;; - Indentation and filling according to reStructuredText syntax;
44 ;; - Cursor movement according to reStructuredText syntax;
45 ;; - Some other convenience functions.
47 ;; See the accompanying document in the docutils documentation about
48 ;; the contents of this package and how to use it.
50 ;; For more information about reStructuredText, see
51 ;; http://docutils.sourceforge.net/rst.html
53 ;; For full details on how to use the contents of this file, see
54 ;; http://docutils.sourceforge.net/docs/user/emacs.html
57 ;; There are a number of convenient key bindings provided by rst-mode.
58 ;; For more on bindings, see rst-mode-map below. There are also many variables
59 ;; that can be customized, look for defcustom in this file.
61 ;; If you use the table-of-contents feature, you may want to add a hook to
62 ;; update the TOC automatically every time you adjust a section title::
64 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
66 ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
67 ;; off syntax highlighting to rst-mode, you can use the following::
69 ;; (setq font-lock-global-modes '(not rst-mode ...))
73 ;; Customization is done by customizable variables contained in customization
74 ;; group "rst" and subgroups. Group "rst" is contained in the "wp" group.
79 ;; The latest release of this file lies in the docutils source code repository:
80 ;; http://docutils.svn.sourceforge.net/svnroot/docutils/trunk/docutils/tools/editors/emacs/rst.el
84 ;; Add the following lines to your `.emacs' file:
88 ;; If you are using `.txt' as a standard extension for reST files as
89 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
90 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
91 ;; provides to set the major mode automatically. For instance you may use::
93 ;; .. -*- mode: rst -*-
95 ;; in the very first line of your file. The following code is useful if you
96 ;; want automatically enter rst-mode from any file with compatible extensions:
98 ;; (setq auto-mode-alist
99 ;; (append '(("\\.txt\\'" . rst-mode)
100 ;; ("\\.rst\\'" . rst-mode)
101 ;; ("\\.rest\\'" . rst-mode)) auto-mode-alist))
106 ;; FIXME: When 24.1 is common place remove use of `lexical-let' and put "-*-
107 ;; lexical-binding: t -*-" in the first line.
109 ;; Only use of macros is allowed - may be replaced by `cl-lib' some time.
113 ;; Redefine some functions from `cl.el' in a proper namespace until they may be
116 (defun rst-signum (x)
117 "Return 1 if X is positive, -1 if negative, 0 if zero."
123 (defun rst-some (seq &optional pred
)
124 "Return non-nil if any element of SEQ yields non-nil when PRED is applied.
125 Apply PRED to each element of list SEQ until the first non-nil
126 result is yielded and return this result. PRED defaults to
129 (setq pred
'identity
))
132 (let ((r (funcall pred elem
)))
134 (throw 'rst-some r
))))))
136 (defun rst-position-if (pred seq
)
137 "Return position of first element satisfying PRED in list SEQ or nil."
138 (catch 'rst-position-if
141 (when (funcall pred elem
)
142 (throw 'rst-position-if i
))
145 (defun rst-position (elem seq
)
146 "Return position of ELEM in list SEQ or nil.
147 Comparison done with `equal'."
148 ;; Create a closure containing `elem' so the `lambda' always sees our
149 ;; parameter instead of an `elem' which may be in dynamic scope at the time
150 ;; of execution of the `lambda'.
151 (lexical-let ((elem elem
))
152 (rst-position-if (function (lambda (e)
156 ;; FIXME: Embed complicated `defconst's in `eval-when-compile'.
158 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
161 (defun rst-extract-version (delim-re head-re re tail-re var
&optional default
)
162 "Extract the version from a variable according to the given regexes.
163 Return the version after regex DELIM-RE and HEAD-RE matching RE
164 and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match."
166 (concat delim-re head-re
"\\(" re
"\\)" tail-re delim-re
)
171 ;; Use CVSHeader to really get information from CVS and not other version
173 (defconst rst-cvs-header
174 "$CVSHeader: sm/rst_el/rst.el,v 1.287 2012-06-16 09:41:47 stefan Exp $")
175 (defconst rst-cvs-rev
176 (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
177 " .*" rst-cvs-header
"0.0")
178 "The CVS revision of this file. CVS revision is the development revision.")
179 (defconst rst-cvs-timestamp
180 (rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
181 "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
182 rst-cvs-header
"1970-01-01 00:00:00")
183 "The CVS time stamp of this file.")
185 ;; Use LastChanged... to really get information from SVN.
186 (defconst rst-svn-rev
187 (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
188 "$LastChangedRevision: 7444 $")
189 "The SVN revision of this file.
190 SVN revision is the upstream (docutils) revision.")
191 (defconst rst-svn-timestamp
192 (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " "
193 "$LastChangedDate: 2012-06-16 11:41:40 +0200 (Sat, 16 Jun 2012) $")
194 "The SVN time stamp of this file.")
196 ;; Maintained by the release process.
197 (defconst rst-official-version
198 (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
199 "%OfficialVersion: 1.3.0 %")
200 "Official version of the package.")
201 (defconst rst-official-cvs-rev
202 (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
203 "%Revision: 1.287 %")
204 "CVS revision of this file in the official version.")
206 (defconst rst-version
207 (if (equal rst-official-cvs-rev rst-cvs-rev
)
209 (format "%s (development %s [%s])" rst-official-version
210 rst-cvs-rev rst-cvs-timestamp
))
212 Starts with the current official version. For developer versions
213 in parentheses follows the development revision and the time stamp.")
215 (defconst rst-package-emacs-version-alist
222 (unless (assoc rst-official-version rst-package-emacs-version-alist
)
223 (error "Version %s not listed in `rst-package-emacs-version-alist'"
226 (add-to-list 'customize-package-emacs-version-alist
227 (cons 'ReST rst-package-emacs-version-alist
))
229 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
230 ;; Initialize customization
233 (defgroup rst nil
"Support for reStructuredText documents."
236 :link
'(url-link "http://docutils.sourceforge.net/rst.html"))
239 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
240 ;; Facilities for regular expressions used everywhere
242 ;; The trailing numbers in the names give the number of referenceable regex
243 ;; groups contained in the regex.
245 ;; Used to be customizable but really is not customizable but fixed by the reST
247 (defconst rst-bullets
248 ;; Sorted so they can form a character class when concatenated.
249 '(?- ?
* ?
+ ?
\u2022 ?
\u2023 ?
\u2043)
250 "List of all possible bullet characters for bulleted lists.")
252 (defconst rst-uri-schemes
253 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
254 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
255 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
256 "Supported URI schemes.")
258 (defconst rst-adornment-chars
259 ;; Sorted so they can form a character class when concatenated.
261 ?
! ?
\" ?
# ?$ ?% ?
& ?
' ?\
( ?\
) ?
* ?
+ ?
, ?. ?
/ ?
: ?\
; ?< ?= ?> ?? ?@ ?\[ ?\\
264 "Characters which may be used in adornments for sections and transitions.")
266 (defconst rst-max-inline-length
268 "Maximum length of inline markup to recognize.")
270 (defconst rst-re-alist-def
271 ;; `*-beg' matches * at the beginning of a line.
272 ;; `*-end' matches * at the end of a line.
273 ;; `*-prt' matches a part of *.
274 ;; `*-tag' matches *.
275 ;; `*-sta' matches the start of * which may be followed by respective content.
276 ;; `*-pfx' matches the delimiter left of *.
277 ;; `*-sfx' matches the delimiter right of *.
278 ;; `*-hlp' helper for *.
280 ;; A trailing number says how many referenceable groups are contained.
283 ;; Horizontal white space (`hws')
285 (hws-tag hws-prt
"*") ; Optional sequence of horizontal white space.
286 (hws-sta hws-prt
"+") ; Mandatory sequence of horizontal white space.
289 (lin-beg "^" hws-tag
) ; Beginning of a possibly indented line.
290 (lin-end hws-tag
"$") ; End of a line with optional trailing white space.
291 (linemp-tag "^" hws-tag
"$") ; Empty line with optional white space.
293 ;; Various tags and parts
294 (ell-tag "\\.\\.\\.") ; Ellipsis
295 (bul-tag ,(concat "[" rst-bullets
"]")) ; A bullet.
296 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag.
297 (num-prt "[0-9]") ; A number enumerator part.
298 (num-tag num-prt
"+") ; A number enumerator tag.
299 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part.
300 (rom-tag rom-prt
"+") ; A roman enumerator tag.
301 (aut-tag "#") ; An automatic enumerator tag.
302 (dcl-tag "::") ; Double colon.
304 ;; Block lead in (`bli')
305 (bli-sfx (:alt hws-sta
"$")) ; Suffix of a block lead-in with *optional*
309 (bul-sta bul-tag bli-sfx
) ; Start of a bulleted item.
311 ;; Explicit markup tag (`exm')
313 (exm-sta exm-tag hws-sta
)
314 (exm-beg lin-beg exm-sta
)
316 ;; Counters in enumerations (`cnt')
317 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag
)) ; An arbitrary counter.
318 (cntexp-tag (:alt ltr-tag num-tag rom-tag
)) ; An arbitrary explicit counter.
320 ;; Enumerator (`enm')
322 (:seq cntany-tag
"\\.")
323 (:seq
"(?" cntany-tag
")"))) ; An arbitrary enumerator.
325 (:seq cntexp-tag
"\\.")
326 (:seq
"(?" cntexp-tag
")"))) ; An arbitrary explicit
330 (:seq
"(?" aut-tag
")"))) ; An automatic enumerator.
331 (enmany-sta enmany-tag bli-sfx
) ; An arbitrary enumerator start.
332 (enmexp-sta enmexp-tag bli-sfx
) ; An arbitrary explicit enumerator start.
333 (enmexp-beg lin-beg enmexp-sta
) ; An arbitrary explicit enumerator start
334 ; at the beginning of a line.
336 ;; Items may be enumerated or bulleted (`itm')
337 (itmany-tag (:alt enmany-tag bul-tag
)) ; An arbitrary item tag.
338 (itmany-sta-1 (:grp itmany-tag
) bli-sfx
) ; An arbitrary item start, group
340 (itmany-beg-1 lin-beg itmany-sta-1
) ; An arbitrary item start at the
341 ; beginning of a line, group is the
344 ;; Inline markup (`ilm')
345 (ilm-pfx (:alt
"^" hws-prt
"[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
346 (ilm-sfx (:alt
"$" hws-prt
"[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
348 ;; Inline markup content (`ilc')
349 (ilcsgl-tag "\\S ") ; A single non-white character.
350 (ilcast-prt (:alt
"[^*\\]" "\\\\.")) ; Part of non-asterisk content.
351 (ilcbkq-prt (:alt
"[^`\\]" "\\\\.")) ; Part of non-backquote content.
352 (ilcbkqdef-prt (:alt
"[^`\\\n]" "\\\\.")) ; Part of non-backquote
354 (ilcbar-prt (:alt
"[^|\\]" "\\\\.")) ; Part of non-vertical-bar content.
355 (ilcbardef-prt (:alt
"[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
357 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content.
358 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content.
359 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content.
360 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length
)) ; Repeat count.
361 (ilcast-tag (:alt ilcsgl-tag
363 ilcast-prt ilcrep-hlp
364 ilcast-sfx
))) ; Non-asterisk content.
365 (ilcbkq-tag (:alt ilcsgl-tag
367 ilcbkq-prt ilcrep-hlp
368 ilcbkq-sfx
))) ; Non-backquote content.
369 (ilcbkqdef-tag (:alt ilcsgl-tag
371 ilcbkqdef-prt ilcrep-hlp
372 ilcbkq-sfx
))) ; Non-backquote definition.
373 (ilcbar-tag (:alt ilcsgl-tag
375 ilcbar-prt ilcrep-hlp
376 ilcbar-sfx
))) ; Non-vertical-bar content.
377 (ilcbardef-tag (:alt ilcsgl-tag
379 ilcbardef-prt ilcrep-hlp
380 ilcbar-sfx
))) ; Non-vertical-bar definition.
383 (fldnam-prt (:alt
"[^:\n]" "\\\\:")) ; Part of a field name.
384 (fldnam-tag fldnam-prt
"+") ; A field name.
385 (fld-tag ":" fldnam-tag
":") ; A field marker.
388 (optsta-tag (:alt
"[-+/]" "--")) ; Start of an option.
389 (optnam-tag "\\sw" (:alt
"-" "\\sw") "*") ; Name of an option.
390 (optarg-tag (:shy
"[ =]\\S +")) ; Option argument.
391 (optsep-tag (:shy
"," hws-prt
)) ; Separator between options.
392 (opt-tag (:shy optsta-tag optnam-tag optarg-tag
"?")) ; A complete option.
394 ;; Footnotes and citations (`fnc')
395 (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name.
396 (fncnam-tag fncnam-prt
"+") ; A footnote or citation name.
397 (fnc-tag "\\[" fncnam-tag
"]") ; A complete footnote or citation tag.
398 (fncdef-tag-2 (:grp exm-sta
)
399 (:grp fnc-tag
)) ; A complete footnote or citation definition
400 ; tag. First group is the explicit markup
401 ; start, second group is the footnote /
403 (fnc-sta-2 fncdef-tag-2 bli-sfx
) ; Start of a footnote or citation
404 ; definition. First group is the explicit
405 ; markup start, second group is the
406 ; footnote / citation tag.
408 ;; Substitutions (`sub')
409 (sub-tag "|" ilcbar-tag
"|") ; A complete substitution tag.
410 (subdef-tag "|" ilcbardef-tag
"|") ; A complete substitution definition
414 (sym-prt "[-+.:_]") ; Non-word part of a symbol.
415 (sym-tag (:shy
"\\sw+" (:shy sym-prt
"\\sw+") "*"))
418 (uri-tag (:alt
,@rst-uri-schemes
))
421 (ado-prt "[" ,(concat rst-adornment-chars
) "]")
422 (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
423 ; otherwise explicit markup start would be
425 (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
426 ; characters is matched differently.
427 (ado-tag-1-1 (:grp ado-prt
)
428 "\\1" adorep2-hlp
) ; A complete adornment, group is the first
429 ; adornment character and MUST be the FIRST
430 ; group in the whole expression.
431 (ado-tag-1-2 (:grp ado-prt
)
432 "\\2" adorep2-hlp
) ; A complete adornment, group is the first
433 ; adornment character and MUST be the
434 ; SECOND group in the whole expression.
435 (ado-beg-2-1 "^" (:grp ado-tag-1-2
)
436 lin-end
) ; A complete adornment line; first group is the whole
437 ; adornment and MUST be the FIRST group in the whole
438 ; expression; second group is the first adornment
442 (ttl-tag "\\S *\\w\\S *") ; A title text.
443 (ttl-beg lin-beg ttl-tag
) ; A title text at the beginning of a line.
445 ;; Directives and substitution definitions (`dir')
446 (dir-tag-3 (:grp exm-sta
)
447 (:grp
(:shy subdef-tag hws-sta
) "?")
448 (:grp sym-tag dcl-tag
)) ; A directive or substitution definition
449 ; tag. First group is explicit markup
450 ; start, second group is a possibly
451 ; empty substitution tag, third group is
452 ; the directive tag including the double
454 (dir-sta-3 dir-tag-3 bli-sfx
) ; Start of a directive or substitution
455 ; definition. Groups are as in dir-tag-3.
457 ;; Literal block (`lit')
458 (lit-sta-2 (:grp
(:alt
"[^.\n]" "\\.[^.\n]") ".*") "?"
459 (:grp dcl-tag
) "$") ; Start of a literal block. First group is
460 ; any text before the double colon tag which
461 ; may not exist, second group is the double
465 (cmt-sta-1 (:grp exm-sta
) "[^\[|_\n]"
466 (:alt
"[^:\n]" (:seq
":" (:alt
"[^:\n]" "$")))
467 "*$") ; Start of a comment block; first group is explicit markup
470 ;; Paragraphs (`par')
471 (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag
)
472 ) ; Tag at the beginning of a paragraph; there may be groups in
475 "Definition alist of relevant regexes.
476 Each entry consists of the symbol naming the regex and an
477 argument list for `rst-re'.")
479 (defvar rst-re-alist
) ; Forward declare to use it in `rst-re'.
481 ;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel.
482 (defun rst-re (&rest args
)
483 "Interpret ARGS as regular expressions and return a regex string.
484 Each element of ARGS may be one of the following:
486 A string which is inserted unchanged.
488 A character which is resolved to a quoted regex.
490 A symbol which is resolved to a string using `rst-re-alist-def'.
492 A list with a keyword in the car. Each element of the cdr of such
493 a list is recursively interpreted as ARGS. The results of this
494 interpretation are concatenated according to the keyword.
496 For the keyword `:seq' the results are simply concatenated.
498 For the keyword `:shy' the results are concatenated and
499 surrounded by a shy-group (\"\\(?:...\\)\").
501 For the keyword `:alt' the results form an alternative (\"\\|\")
502 which is shy-grouped (\"\\(?:...\\)\").
504 For the keyword `:grp' the results are concatenated and form a
505 referenceable group (\"\\(...\\)\").
507 After interpretation of ARGS the results are concatenated as for
516 (cadr (assoc re rst-re-alist
)))
518 (regexp-quote (char-to-string re
)))
521 (mapcar (lambda (elt)
526 (mapconcat 'identity nested
""))
528 (concat "\\(?:" (mapconcat 'identity nested
"") "\\)"))
530 (concat "\\(" (mapconcat 'identity nested
"") "\\)"))
532 (concat "\\(?:" (mapconcat 'identity nested
"\\|") "\\)"))
534 (error "Unknown list car: %s" (car re
))))))
536 (error "Unknown object type for building regex: %s" re
))))
539 ;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'.
540 (with-no-warnings ; Silence byte-compiler about this construction.
541 (defconst rst-re-alist
542 ;; Shadow global value we are just defining so we can construct it step by
545 (dolist (re rst-re-alist-def rst-re-alist
)
548 (list (list (car re
) (apply 'rst-re
(cdr re
))))))))
549 "Alist mapping symbols from `rst-re-alist-def' to regex strings."))
552 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
555 (defun rst-define-key (keymap key def
&rest deprecated
)
556 "Bind like `define-key' but add deprecated key definitions.
557 KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key
558 definitions should be in vector notation. These are defined as
559 well but give an additional message."
560 (define-key keymap key def
)
561 (dolist (dep-key deprecated
)
562 (define-key keymap dep-key
564 ,(format "Deprecated binding for %s, use \\[%s] instead." def def
)
566 (call-interactively ',def
)
567 (message "[Deprecated use of key %s; use key %s instead]"
568 (key-description (this-command-keys))
569 (key-description ,key
))))))
573 (let ((map (make-sparse-keymap)))
575 ;; \C-c is the general keymap.
576 (rst-define-key map
[?\C-c ?\C-h
] 'describe-prefix-bindings
)
579 ;; Section Adornments
581 ;; The adjustment function that adorns or rotates a section title.
582 (rst-define-key map
[?\C-c ?\C-
=] 'rst-adjust
[?\C-c ?\C-a t
])
583 (rst-define-key map
[?\C-
=] 'rst-adjust
) ; (Does not work on the Mac OSX.)
585 ;; \C-c \C-a is the keymap for adornments.
586 (rst-define-key map
[?\C-c ?\C-a ?\C-h
] 'describe-prefix-bindings
)
587 ;; Display the hierarchy of adornments implied by the current document
589 (rst-define-key map
[?\C-c ?\C-a ?\C-d
] 'rst-display-adornments-hierarchy
)
590 ;; Homogenize the adornments in the document.
591 (rst-define-key map
[?\C-c ?\C-a ?\C-s
] 'rst-straighten-adornments
595 ;; Section Movement and Selection
597 ;; Mark the subsection where the cursor is.
598 (rst-define-key map
[?\C-\M-h
] 'rst-mark-section
599 ;; Same as mark-defun sgml-mark-current-element.
601 ;; Move backward/forward between section titles.
602 ;; FIXME: Also bind similar to outline mode.
603 (rst-define-key map
[?\C-\M-a
] 'rst-backward-section
604 ;; Same as beginning-of-defun.
606 (rst-define-key map
[?\C-\M-e
] 'rst-forward-section
607 ;; Same as end-of-defun.
611 ;; Operating on regions
613 ;; \C-c \C-r is the keymap for regions.
614 (rst-define-key map
[?\C-c ?\C-r ?\C-h
] 'describe-prefix-bindings
)
615 ;; Makes region a line-block.
616 (rst-define-key map
[?\C-c ?\C-r ?\C-l
] 'rst-line-block-region
618 ;; Shift region left or right according to tabs.
619 (rst-define-key map
[?\C-c ?\C-r tab
] 'rst-shift-region
620 [?\C-c ?\C-r t
] [?\C-c ?\C-l t
])
623 ;; Operating on lists
625 ;; \C-c \C-l is the keymap for lists.
626 (rst-define-key map
[?\C-c ?\C-l ?\C-h
] 'describe-prefix-bindings
)
627 ;; Makes paragraphs in region as a bullet list.
628 (rst-define-key map
[?\C-c ?\C-l ?\C-b
] 'rst-bullet-list-region
630 ;; Makes paragraphs in region as a enumeration.
631 (rst-define-key map
[?\C-c ?\C-l ?\C-e
] 'rst-enumerate-region
633 ;; Converts bullets to an enumeration.
634 (rst-define-key map
[?\C-c ?\C-l ?\C-c
] 'rst-convert-bullets-to-enumeration
636 ;; Make sure that all the bullets in the region are consistent.
637 (rst-define-key map
[?\C-c ?\C-l ?\C-s
] 'rst-straighten-bullets-region
639 ;; Insert a list item.
640 (rst-define-key map
[?\C-c ?\C-l ?\C-i
] 'rst-insert-list
)
643 ;; Table-of-Contents Features
645 ;; \C-c \C-t is the keymap for table of contents.
646 (rst-define-key map
[?\C-c ?\C-t ?\C-h
] 'describe-prefix-bindings
)
647 ;; Enter a TOC buffer to view and move to a specific section.
648 (rst-define-key map
[?\C-c ?\C-t ?\C-t
] 'rst-toc
)
649 ;; Insert a TOC here.
650 (rst-define-key map
[?\C-c ?\C-t ?\C-i
] 'rst-toc-insert
652 ;; Update the document's TOC (without changing the cursor position).
653 (rst-define-key map
[?\C-c ?\C-t ?\C-u
] 'rst-toc-update
655 ;; Go to the section under the cursor (cursor must be in TOC).
656 (rst-define-key map
[?\C-c ?\C-t ?\C-j
] 'rst-goto-section
660 ;; Converting Documents from Emacs
662 ;; \C-c \C-c is the keymap for compilation.
663 (rst-define-key map
[?\C-c ?\C-c ?\C-h
] 'describe-prefix-bindings
)
664 ;; Run one of two pre-configured toolset commands on the document.
665 (rst-define-key map
[?\C-c ?\C-c ?\C-c
] 'rst-compile
667 (rst-define-key map
[?\C-c ?\C-c ?\C-a
] 'rst-compile-alt-toolset
669 ;; Convert the active region to pseudo-xml using the docutils tools.
670 (rst-define-key map
[?\C-c ?\C-c ?\C-x
] 'rst-compile-pseudo-region
672 ;; Convert the current document to PDF and launch a viewer on the results.
673 (rst-define-key map
[?\C-c ?\C-c ?\C-p
] 'rst-compile-pdf-preview
675 ;; Convert the current document to S5 slides and view in a web browser.
676 (rst-define-key map
[?\C-c ?\C-c ?\C-s
] 'rst-compile-slides-preview
680 "Keymap for reStructuredText mode commands.
681 This inherits from Text mode.")
685 (define-abbrev-table 'rst-mode-abbrev-table
686 (mapcar (lambda (x) (append x
'(nil 0 system
)))
687 '(("contents" ".. contents::\n..\n ")
688 ("con" ".. contents::\n..\n ")
690 ("skip" "\n\n[...]\n\n ")
691 ("seq" "\n\n[...]\n\n ")
692 ;; FIXME: Add footnotes, links, and more.
694 "Abbrev table used while in `rst-mode'.")
698 (defvar rst-mode-syntax-table
699 (let ((st (copy-syntax-table text-mode-syntax-table
)))
700 (modify-syntax-entry ?$
"." st
)
701 (modify-syntax-entry ?%
"." st
)
702 (modify-syntax-entry ?
& "." st
)
703 (modify-syntax-entry ?
' "." st
)
704 (modify-syntax-entry ?
* "." st
)
705 (modify-syntax-entry ?
+ "." st
)
706 (modify-syntax-entry ?-
"." st
)
707 (modify-syntax-entry ?
/ "." st
)
708 (modify-syntax-entry ?
< "." st
)
709 (modify-syntax-entry ?
= "." st
)
710 (modify-syntax-entry ?
> "." st
)
711 (modify-syntax-entry ?
\\ "\\" st
)
712 (modify-syntax-entry ?_
"." st
)
713 (modify-syntax-entry ?|
"." st
)
714 (modify-syntax-entry ?
\u00ab "." st
)
715 (modify-syntax-entry ?
\u00bb "." st
)
716 (modify-syntax-entry ?
\u2018 "." st
)
717 (modify-syntax-entry ?
\u2019 "." st
)
718 (modify-syntax-entry ?
\u201c "." st
)
719 (modify-syntax-entry ?
\u201d "." st
)
722 "Syntax table used while in `rst-mode'.")
725 (defcustom rst-mode-hook nil
726 "Hook run when `rst-mode' is turned on.
727 The hook for `text-mode' is run before this one."
731 ;; Pull in variable definitions silencing byte-compiler.
732 (require 'newcomment
)
734 ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
735 ;; use *.txt, but this is too generic to be set as a default.
736 ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
738 (define-derived-mode rst-mode text-mode
"ReST"
739 "Major mode for editing reStructuredText documents.
742 Turning on `rst-mode' calls the normal hooks `text-mode-hook'
743 and `rst-mode-hook'. This mode also supports font-lock
747 :abbrev-table rst-mode-abbrev-table
748 :syntax-table rst-mode-syntax-table
751 ;; Paragraph recognition.
752 (set (make-local-variable 'paragraph-separate
)
756 (set (make-local-variable 'paragraph-start
)
760 (:seq hws-tag par-tag- bli-sfx
))))
762 ;; Indenting and filling.
763 (set (make-local-variable 'indent-line-function
) 'rst-indent-line
)
764 (set (make-local-variable 'adaptive-fill-mode
) t
)
765 (set (make-local-variable 'adaptive-fill-regexp
)
766 (rst-re 'hws-tag
'par-tag-
"?" 'hws-tag
))
767 (set (make-local-variable 'adaptive-fill-function
) 'rst-adaptive-fill
)
768 (set (make-local-variable 'fill-paragraph-handle-comment
) nil
)
771 (set (make-local-variable 'comment-start
) ".. ")
772 (set (make-local-variable 'comment-start-skip
)
773 (rst-re 'lin-beg
'exm-tag
'bli-sfx
))
774 (set (make-local-variable 'comment-continue
) " ")
775 (set (make-local-variable 'comment-multi-line
) t
)
776 (set (make-local-variable 'comment-use-syntax
) nil
)
777 ;; reStructuredText has not really a comment ender but nil is not really a
778 ;; permissible value.
779 (set (make-local-variable 'comment-end
) "")
780 (set (make-local-variable 'comment-end-skip
) nil
)
782 ;; Commenting in reStructuredText is very special so use our own set of
784 (set (make-local-variable 'comment-line-break-function
)
785 'rst-comment-line-break
)
786 (set (make-local-variable 'comment-indent-function
)
788 (set (make-local-variable 'comment-insert-comment-function
)
789 'rst-comment-insert-comment
)
790 (set (make-local-variable 'comment-region-function
)
792 (set (make-local-variable 'uncomment-region-function
)
793 'rst-uncomment-region
)
796 (set (make-local-variable 'font-lock-defaults
)
797 '(rst-font-lock-keywords
799 (font-lock-multiline . t
)
800 (font-lock-mark-block-function . mark-paragraph
)))
801 (add-hook 'font-lock-extend-region-functions
'rst-font-lock-extend-region t
)
803 ;; Text after a changed line may need new fontification.
804 (set (make-local-variable 'jit-lock-contextually
) t
))
807 (define-minor-mode rst-minor-mode
808 "Toggle ReST minor mode.
809 With a prefix argument ARG, enable ReST minor mode if ARG is
810 positive, and disable it otherwise. If called from Lisp, enable
811 the mode if ARG is omitted or nil.
813 When ReST minor mode is enabled, the ReST mode keybindings
814 are installed on top of the major mode bindings. Use this
815 for modes derived from Text mode, like Mail mode."
816 ;; The initial value.
818 ;; The indicator for the mode line.
820 ;; The minor mode bindings.
824 ;; FIXME: can I somehow install these too?
825 ;; :abbrev-table rst-mode-abbrev-table
826 ;; :syntax-table rst-mode-syntax-table
829 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
830 ;; Section Adornment Adjustment
831 ;; ============================
833 ;; The following functions implement a smart automatic title sectioning feature.
834 ;; The idea is that with the cursor sitting on a section title, we try to get as
835 ;; much information from context and try to do the best thing automatically.
836 ;; This function can be invoked many times and/or with prefix argument to rotate
837 ;; between the various sectioning adornments.
839 ;; Definitions: the two forms of sectioning define semantically separate section
840 ;; levels. A sectioning ADORNMENT consists in:
844 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
846 ;; - an INDENT (meaningful for the over-and-under style only) which determines
847 ;; how many characters and over-and-under style is hanging outside of the
848 ;; title at the beginning and ending.
850 ;; Here are two examples of adornments (| represents the window border, column
854 ;; 1. char: '-' e |Some Title
855 ;; style: simple |----------
857 ;; 2. char: '=' |==============
858 ;; style: over-and-under | Some Title
859 ;; indent: 2 |==============
864 ;; - The underlining character that is used depends on context. The file is
865 ;; scanned to find other sections and an appropriate character is selected.
866 ;; If the function is invoked on a section that is complete, the character is
867 ;; rotated among the existing section adornments.
869 ;; Note that when rotating the characters, if we come to the end of the
870 ;; hierarchy of adornments, the variable rst-preferred-adornments is
871 ;; consulted to propose a new underline adornment, and if continued, we cycle
872 ;; the adornments all over again. Set this variable to nil if you want to
873 ;; limit the underlining character propositions to the existing adornments in
876 ;; - An underline/overline that is not extended to the column at which it should
877 ;; be hanging is dubbed INCOMPLETE. For example::
882 ;; Examples of default invocation:
884 ;; |Some Title ---> |Some Title
887 ;; |Some Title ---> |Some Title
888 ;; |----- |----------
891 ;; | Some Title ---> | Some Title
894 ;; In over-and-under style, when alternating the style, a variable is
895 ;; available to select how much default indent to use (it can be zero). Note
896 ;; that if the current section adornment already has an indent, we don't
897 ;; adjust it to the default, we rather use the current indent that is already
898 ;; there for adjustment (unless we cycle, in which case we use the indent
899 ;; that has been found previously).
901 (defgroup rst-adjust nil
902 "Settings for adjustment and cycling of section title adornments."
906 (define-obsolete-variable-alias
907 'rst-preferred-decorations
'rst-preferred-adornments
"1.0.0")
908 (defcustom rst-preferred-adornments
'((?
= over-and-under
1)
916 "Preferred hierarchy of section title adornments.
918 A list consisting of lists of the form (CHARACTER STYLE INDENT).
919 CHARACTER is the character used. STYLE is one of the symbols
920 OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted
921 indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are
922 always used when a section adornment is described. In other
923 places t instead of a list stands for a transition.
925 This sequence is consulted to offer a new adornment suggestion
926 when we rotate the underlines at the end of the existing
927 hierarchy of characters, or when there is no existing section
930 Set this to an empty list to use only the adornment found in the
934 (group :tag
"Adornment specification"
935 (choice :tag
"Adornment character"
936 ,@(mapcar (lambda (char)
938 :tag
(char-to-string char
) char
))
939 rst-adornment-chars
))
940 (radio :tag
"Adornment type"
941 (const :tag
"Overline and underline" over-and-under
)
942 (const :tag
"Underline only" simple
))
943 (integer :tag
"Indentation for overline and underline type"
946 (defcustom rst-default-indent
1
947 "Number of characters to indent the section title.
949 This is used for when toggling adornment styles, when switching
950 from a simple adornment style to a over-and-under adornment
956 (defun rst-compare-adornments (ado1 ado2
)
958 Return true if both ADO1 and ADO2 adornments are equal,
959 according to restructured text semantics (only the character and
960 the style are compared, the indentation does not matter)."
961 (and (eq (car ado1
) (car ado2
))
962 (eq (cadr ado1
) (cadr ado2
))))
965 (defun rst-get-adornment-match (hier ado
)
966 "Return the index (level) in hierarchy HIER of adornment ADO.
967 This basically just searches for the item using the appropriate
968 comparison and returns the index. Return nil if the item is
971 (while (and cur
(not (rst-compare-adornments (car cur
) ado
)))
972 (setq cur
(cdr cur
)))
976 (defun rst-suggest-new-adornment (allados &optional prev
)
977 "Suggest a new, different adornment from all that have been seen.
979 ALLADOS is the set of all adornments, including the line numbers.
980 PREV is the optional previous adornment, in order to suggest a
983 ;; For all the preferred adornments...
985 ;; If 'prev' is given, reorder the list to start searching after the
988 (cdr (rst-get-adornment-match rst-preferred-adornments prev
)))
990 ;; List of candidates to search.
991 (curpotential (append fplist rst-preferred-adornments
)))
993 ;; For all the adornments...
996 (while (and cur
(not found
))
997 (if (rst-compare-adornments (car cur
) (car curpotential
))
999 (setq found
(car curpotential
))
1000 (setq cur
(cdr cur
))))
1003 (setq curpotential
(cdr curpotential
)))
1005 (copy-sequence (car curpotential
))))
1007 (defun rst-delete-entire-line ()
1008 "Delete the entire current line without using the `kill-ring'."
1009 (delete-region (line-beginning-position)
1010 (line-beginning-position 2)))
1012 (defun rst-update-section (char style
&optional indent
)
1013 "Unconditionally update the style of a section adornment.
1015 Do this using the given character CHAR, with STYLE 'simple
1016 or 'over-and-under, and with indent INDENT. If the STYLE
1017 is 'simple, whitespace before the title is removed (indent
1018 is always assumed to be 0).
1020 If there are existing overline and/or underline from the
1021 existing adornment, they are removed before adding the
1022 requested adornment."
1024 (let ((marker (point-marker))
1027 ;; Fixup whitespace at the beginning and end of the line.
1028 (if (or (null indent
) (eq style
'simple
))
1031 (delete-horizontal-space)
1032 (insert (make-string indent ?
))
1035 (delete-horizontal-space)
1037 ;; Set the current column, we're at the end of the title line.
1038 (setq len
(+ (current-column) indent
))
1040 ;; Remove previous line if it is an adornment.
1043 (if (and (looking-at (rst-re 'ado-beg-2-1
))
1044 ;; Avoid removing the underline of a title right above us.
1045 (save-excursion (forward-line -
1)
1046 (not (looking-at (rst-re 'ttl-beg
)))))
1047 (rst-delete-entire-line)))
1049 ;; Remove following line if it is an adornment.
1052 (if (looking-at (rst-re 'ado-beg-2-1
))
1053 (rst-delete-entire-line))
1054 ;; Add a newline if we're at the end of the buffer, for the subsequence
1055 ;; inserting of the underline.
1056 (if (= (point) (buffer-end 1))
1060 (if (eq style
'over-and-under
)
1064 (insert (make-string len char
))))
1066 ;; Insert underline.
1069 (insert (make-string len char
))
1075 (defun rst-classify-adornment (adornment end
)
1076 "Classify adornment for section titles and transitions.
1077 ADORNMENT is the complete adornment string as found in the buffer
1078 with optional trailing whitespace. END is the point after the
1079 last character of ADORNMENT.
1081 Return a list. The first entry is t for a transition or a
1082 cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for
1083 the meaning of CHARACTER and STYLE.
1085 The remaining list forms four match groups as returned by
1086 `match-data'. Match group 0 matches the whole construct. Match
1087 group 1 matches the overline adornment if present. Match group 2
1088 matches the section title text or the transition. Match group 3
1089 matches the underline adornment.
1091 Return nil if no syntactically valid adornment is found."
1094 (when (string-match (rst-re 'ado-beg-2-1
) adornment
)
1096 (let* ((ado-ch (string-to-char (match-string 2 adornment
)))
1097 (ado-re (rst-re ado-ch
'adorep3-hlp
))
1102 (nxt-emp ; Next line nonexistent or empty
1104 (or (not (zerop (forward-line 1)))
1105 (looking-at (rst-re 'lin-end
)))))
1106 (prv-emp ; Previous line nonexistent or empty
1108 (or (not (zerop (forward-line -
1)))
1109 (looking-at (rst-re 'lin-end
)))))
1110 (ttl-blw ; Title found below starting here.
1113 (zerop (forward-line 1))
1114 (looking-at (rst-re 'ttl-beg
))
1116 (ttl-abv ; Title found above starting here.
1119 (zerop (forward-line -
1))
1120 (looking-at (rst-re 'ttl-beg
))
1122 (und-fnd ; Matching underline found starting here.
1125 (zerop (forward-line 2))
1126 (looking-at (rst-re ado-re
'lin-end
))
1128 (ovr-fnd ; Matching overline found starting here.
1131 (zerop (forward-line -
2))
1132 (looking-at (rst-re ado-re
'lin-end
))
1134 key beg-ovr end-ovr beg-txt end-txt beg-und end-und
)
1136 ((and nxt-emp prv-emp
)
1141 ((or und-fnd ovr-fnd
)
1142 ;; An overline with an underline.
1143 (setq key
(cons ado-ch
'over-and-under
))
1144 (let (;; Prefer overline match over underline match.
1145 (und-pnt (if ovr-fnd beg-pnt und-fnd
))
1146 (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt
))
1147 (txt-pnt (if ovr-fnd ttl-abv ttl-blw
)))
1149 (setq beg-ovr
(point)
1150 end-ovr
(line-end-position))
1152 (setq beg-txt
(point)
1153 end-txt
(line-end-position))
1155 (setq beg-und
(point)
1156 end-und
(line-end-position))))
1159 (setq key
(cons ado-ch
'simple
)
1163 (setq beg-txt
(point)
1164 end-txt
(line-end-position)))
1166 ;; Invalid adornment.
1170 (or beg-ovr beg-txt beg-und
)
1171 (or end-und end-txt end-ovr
)
1172 beg-ovr end-ovr beg-txt end-txt beg-und end-und
)))))))
1174 (defun rst-find-title-line ()
1175 "Find a section title line around point and return its characteristics.
1176 If the point is on an adornment line find the respective title
1177 line. If the point is on an empty line check previous or next
1178 line whether it is a suitable title line and use it if so. If
1179 point is on a suitable title line use it.
1181 If no title line is found return nil.
1183 Otherwise return as `rst-classify-adornment' does. However, if
1184 the title line has no syntactically valid adornment STYLE is nil
1185 in the first element. If there is no adornment around the title
1186 CHARACTER is also nil and match groups for overline and underline
1190 (let ((orig-pnt (point))
1191 (orig-end (line-end-position)))
1193 ((looking-at (rst-re 'ado-beg-2-1
))
1194 (let ((char (string-to-char (match-string-no-properties 2)))
1195 (r (rst-classify-adornment (match-string-no-properties 0)
1199 ;; Invalid adornment - check whether this is an incomplete overline.
1201 (zerop (forward-line 1))
1202 (looking-at (rst-re 'ttl-beg
)))
1203 (list (cons char nil
) orig-pnt
(line-end-position)
1204 orig-pnt orig-end
(point) (line-end-position) nil nil
)))
1206 ;; A section title - not a transition.
1208 ((looking-at (rst-re 'lin-end
))
1211 (if (and (zerop (forward-line -
1))
1212 (looking-at (rst-re 'ttl-beg
)))
1213 (list (cons nil nil
) (point) (line-end-position)
1214 nil nil
(point) (line-end-position) nil nil
)))
1216 (if (and (zerop (forward-line 1))
1217 (looking-at (rst-re 'ttl-beg
)))
1218 (list (cons nil nil
) (point) (line-end-position)
1219 nil nil
(point) (line-end-position) nil nil
)))))
1220 ((looking-at (rst-re 'ttl-beg
))
1221 ;; Try to use the underline.
1222 (let ((r (rst-classify-adornment
1223 (buffer-substring-no-properties
1224 (line-beginning-position 2) (line-end-position 2))
1225 (line-end-position 2))))
1228 ;; No valid adornment found.
1229 (list (cons nil nil
) (point) (line-end-position)
1230 nil nil
(point) (line-end-position) nil nil
))))))))
1232 ;; The following function and variables are used to maintain information about
1233 ;; current section adornment in a buffer local cache. Thus they can be used for
1234 ;; font-locking and manipulation commands.
1236 (defvar rst-all-sections nil
1237 "All section adornments in the buffer as found by `rst-find-all-adornments'.
1238 t when no section adornments were found.")
1239 (make-variable-buffer-local 'rst-all-sections
)
1241 ;; FIXME: If this variable is set to a different value font-locking of section
1242 ;; headers is wrong.
1243 (defvar rst-section-hierarchy nil
1244 "Section hierarchy in the buffer as determined by `rst-get-hierarchy'.
1245 t when no section adornments were found. Value depends on
1246 `rst-all-sections'.")
1247 (make-variable-buffer-local 'rst-section-hierarchy
)
1249 (defun rst-reset-section-caches ()
1250 "Reset all section cache variables.
1251 Should be called by interactive functions which deal with sections."
1252 (setq rst-all-sections nil
1253 rst-section-hierarchy nil
))
1255 (defun rst-find-all-adornments ()
1256 "Return all the section adornments in the current buffer.
1257 Return a list of (LINE . ADORNMENT) with ascending LINE where
1258 LINE is the line containing the section title. ADORNMENT consists
1259 of a (CHARACTER STYLE INDENT) triple as described for
1260 `rst-preferred-adornments'.
1262 Uses and sets `rst-all-sections'."
1263 (unless rst-all-sections
1265 ;; Iterate over all the section titles/adornments in the file.
1267 (goto-char (point-min))
1268 (while (re-search-forward (rst-re 'ado-beg-2-1
) nil t
)
1269 (let ((ado-data (rst-classify-adornment
1270 (match-string-no-properties 0) (point))))
1272 (consp (car ado-data
))) ; Ignore transitions.
1273 (set-match-data (cdr ado-data
))
1274 (goto-char (match-beginning 2)) ; Goto the title start.
1275 (push (cons (1+ (count-lines (point-min) (point)))
1276 (list (caar ado-data
)
1278 (current-indentation)))
1280 (goto-char (match-end 0))))) ; Go beyond the whole thing.
1281 (setq positions
(nreverse positions
))
1282 (setq rst-all-sections
(or positions t
)))))
1283 (if (eq rst-all-sections t
)
1287 (defun rst-infer-hierarchy (adornments)
1288 "Build a hierarchy of adornments using the list of given ADORNMENTS.
1290 ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment
1291 specifications, in order that they appear in a file, and will
1292 infer a hierarchy of section levels by removing adornments that
1293 have already been seen in a forward traversal of the adornments,
1294 comparing just CHARACTER and STYLE.
1296 Similarly returns a list of (CHARACTER STYLE INDENT), where each
1297 list element should be unique."
1298 (let (hierarchy-alist)
1299 (dolist (x adornments
)
1300 (let ((char (car x
))
1302 (unless (assoc (cons char style
) hierarchy-alist
)
1303 (push (cons (cons char style
) x
) hierarchy-alist
))))
1304 (mapcar 'cdr
(nreverse hierarchy-alist
))))
1306 (defun rst-get-hierarchy (&optional ignore
)
1307 "Return the hierarchy of section titles in the file.
1309 Return a list of adornments that represents the hierarchy of
1310 section titles in the file. Each element consists of (CHARACTER
1311 STYLE INDENT) as described for `rst-find-all-adornments'. If the
1312 line number in IGNORE is specified, a possibly adornment found on
1313 that line is not taken into account when building the hierarchy.
1315 Uses and sets `rst-section-hierarchy' unless IGNORE is given."
1316 (if (and (not ignore
) rst-section-hierarchy
)
1317 (if (eq rst-section-hierarchy t
)
1319 rst-section-hierarchy
)
1320 (let ((r (rst-infer-hierarchy
1324 (rst-find-all-adornments))))))
1325 (setq rst-section-hierarchy
1327 ;; Clear cache reflecting that a possible update is not
1333 (defun rst-get-adornments-around ()
1334 "Return the adornments around point.
1335 Return a list of the previous and next adornments."
1336 (let* ((all (rst-find-all-adornments))
1337 (curline (line-number-at-pos))
1341 ;; Search for the adornments around the current line.
1342 (while (and cur
(< (caar cur
) curline
))
1345 ;; 'cur' is the following adornment.
1347 (if (and cur
(caar cur
))
1348 (setq next
(if (= curline
(caar cur
)) (cdr cur
) cur
)))
1350 (mapcar 'cdar
(list prev next
))
1354 (defun rst-adornment-complete-p (ado)
1355 "Return true if the adornment ADO around point is complete."
1356 ;; Note: we assume that the detection of the overline as being the underline
1357 ;; of a preceding title has already been detected, and has been eliminated
1358 ;; from the adornment that is given to us.
1360 ;; There is some sectioning already present, so check if the current
1361 ;; sectioning is complete and correct.
1362 (let* ((char (car ado
))
1364 (indent (caddr ado
))
1365 (endcol (save-excursion (end-of-line) (current-column)))
1368 (let ((exps (rst-re "^" char
(format "\\{%d\\}" (+ endcol indent
)) "$")))
1370 (save-excursion (forward-line +1)
1373 (or (not (eq style
'over-and-under
))
1374 (save-excursion (forward-line -
1)
1376 (looking-at exps
))))
1381 (defun rst-get-next-adornment
1382 (curado hier
&optional suggestion reverse-direction
)
1383 "Get the next adornment for CURADO, in given hierarchy HIER.
1384 If suggesting, suggest for new adornment SUGGESTION.
1385 REVERSE-DIRECTION is used to reverse the cycling order."
1389 (style (cadr curado
))
1391 ;; Build a new list of adornments for the rotation.
1394 ;; Suggest a new adornment.
1396 ;; If nothing to suggest, use first adornment.
1399 ;; Search for next adornment.
1401 (let ((cur (if reverse-direction rotados
1402 (reverse rotados
))))
1404 (not (and (eq char
(caar cur
))
1405 (eq style
(cadar cur
)))))
1406 (setq cur
(cdr cur
)))
1409 ;; If not found, take the first of all adornments.
1414 ;; FIXME: A line "``/`` full" is not accepted as a section title.
1415 (defun rst-adjust (pfxarg)
1416 "Auto-adjust the adornment around point.
1418 Adjust/rotate the section adornment for the section title around
1419 point or promote/demote the adornments inside the region,
1420 depending on if the region is active. This function is meant to
1421 be invoked possibly multiple times, and can vary its behavior
1422 with a positive PFXARG (toggle style), or with a negative
1423 PFXARG (alternate behavior).
1425 This function is a bit of a swiss knife. It is meant to adjust
1426 the adornments of a section title in reStructuredText. It tries
1427 to deal with all the possible cases gracefully and to do `the
1428 right thing' in all cases.
1430 See the documentations of `rst-adjust-adornment-work' and
1431 `rst-promote-region' for full details.
1436 The method can take either (but not both) of
1438 a. a (non-negative) prefix argument, which means to toggle the
1439 adornment style. Invoke with a prefix argument for example;
1441 b. a negative numerical argument, which generally inverts the
1442 direction of search in the file or hierarchy. Invoke with C--
1443 prefix for example."
1446 (let* (;; Save our original position on the current line.
1447 (origpt (point-marker))
1449 (reverse-direction (and pfxarg
(< (prefix-numeric-value pfxarg
) 0)))
1450 (toggle-style (and pfxarg
(not reverse-direction
))))
1452 (if (rst-portable-mark-active-p)
1453 ;; Adjust adornments within region.
1454 (rst-promote-region (and pfxarg t
))
1455 ;; Adjust adornment around point.
1456 (rst-adjust-adornment-work toggle-style reverse-direction
))
1458 ;; Run the hooks to run after adjusting.
1459 (run-hooks 'rst-adjust-hook
)
1461 ;; Make sure to reset the cursor position properly after we're done.
1466 (defcustom rst-adjust-hook nil
1467 "Hooks to be run after running `rst-adjust'."
1470 :package-version
'(rst .
"1.1.0"))
1472 (defcustom rst-new-adornment-down nil
1473 "Controls level of new adornment for section headers."
1476 (const :tag
"Same level as previous one" nil
)
1477 (const :tag
"One level down relative to the previous one" t
))
1478 :package-version
'(rst .
"1.1.0"))
1480 (defun rst-adjust-adornment (pfxarg)
1481 "Call `rst-adjust-adornment-work' interactively.
1483 Keep this for compatibility for older bindings (are there any?).
1484 Argument PFXARG has the same meaning as for `rst-adjust'."
1487 (let* ((reverse-direction (and pfxarg
(< (prefix-numeric-value pfxarg
) 0)))
1488 (toggle-style (and pfxarg
(not reverse-direction
))))
1489 (rst-adjust-adornment-work toggle-style reverse-direction
)))
1491 (defun rst-adjust-adornment-work (toggle-style reverse-direction
)
1492 "Adjust/rotate the section adornment for the section title around point.
1494 This function is meant to be invoked possibly multiple times, and
1495 can vary its behavior with a true TOGGLE-STYLE argument, or with
1496 a REVERSE-DIRECTION argument.
1501 The next action it takes depends on context around the point, and
1502 it is meant to be invoked possibly more than once to rotate among
1503 the various possibilities. Basically, this function deals with:
1505 - adding a adornment if the title does not have one;
1507 - adjusting the length of the underline characters to fit a
1510 - rotating the adornment in the set of already existing
1511 sectioning adornments used in the file;
1513 - switching between simple and over-and-under styles.
1515 You should normally not have to read all the following, just
1516 invoke the method and it will do the most obvious thing that you
1520 Adornment Definitions
1521 =====================
1523 The adornments consist in
1527 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1529 3. an INDENT (meaningful for the over-and-under style only)
1530 which determines how many characters and over-and-under
1531 style is hanging outside of the title at the beginning and
1534 See source code for mode details.
1537 Detailed Behavior Description
1538 =============================
1540 Here are the gory details of the algorithm (it seems quite
1541 complicated, but really, it does the most obvious thing in all
1542 the particular cases):
1544 Before applying the adornment change, the cursor is placed on
1545 the closest line that could contain a section title.
1547 Case 1: No Adornment
1548 --------------------
1550 If the current line has no adornment around it,
1552 - search backwards for the last previous adornment, and apply
1553 the adornment one level lower to the current line. If there
1554 is no defined level below this previous adornment, we suggest
1555 the most appropriate of the `rst-preferred-adornments'.
1557 If REVERSE-DIRECTION is true, we simply use the previous
1558 adornment found directly.
1560 - if there is no adornment found in the given direction, we use
1561 the first of `rst-preferred-adornments'.
1563 TOGGLE-STYLE forces a toggle of the prescribed adornment style.
1565 Case 2: Incomplete Adornment
1566 ----------------------------
1568 If the current line does have an existing adornment, but the
1569 adornment is incomplete, that is, the underline/overline does
1570 not extend to exactly the end of the title line (it is either too
1571 short or too long), we simply extend the length of the
1572 underlines/overlines to fit exactly the section title.
1574 If TOGGLE-STYLE we toggle the style of the adornment as well.
1576 REVERSE-DIRECTION has no effect in this case.
1578 Case 3: Complete Existing Adornment
1579 -----------------------------------
1581 If the adornment is complete (i.e. the underline (overline)
1582 length is already adjusted to the end of the title line), we
1583 search/parse the file to establish the hierarchy of all the
1584 adornments (making sure not to include the adornment around
1585 point), and we rotate the current title's adornment from within
1586 that list (by default, going *down* the hierarchy that is present
1587 in the file, i.e. to a lower section level). This is meant to be
1588 used potentially multiple times, until the desired adornment is
1589 found around the title.
1591 If we hit the boundary of the hierarchy, exactly one choice from
1592 the list of preferred adornments is suggested/chosen, the first
1593 of those adornment that has not been seen in the file yet (and
1594 not including the adornment around point), and the next
1595 invocation rolls over to the other end of the hierarchy (i.e. it
1596 cycles). This allows you to avoid having to set which character
1599 If REVERSE-DIRECTION is true, the effect is to change the
1600 direction of rotation in the hierarchy of adornments, thus
1601 instead going *up* the hierarchy.
1603 However, if TOGGLE-STYLE, we do not rotate the adornment, but
1604 instead simply toggle the style of the current adornment (this
1605 should be the most common way to toggle the style of an existing
1606 complete adornment).
1612 The invocation of this function can be carried out anywhere
1613 within the section title line, on an existing underline or
1614 overline, as well as on an empty line following a section title.
1615 This is meant to be as convenient as possible.
1621 Indented section titles such as ::
1626 are invalid in reStructuredText and thus not recognized by the
1627 parser. This code will thus not work in a way that would support
1628 indented sections (it would be ambiguous anyway).
1634 Section titles that are right next to each other may not be
1635 treated well. More work might be needed to support those, and
1636 special conditions on the completeness of existing adornments
1637 might be required to make it non-ambiguous.
1639 For now we assume that the adornments are disjoint, that is,
1640 there is at least a single line between the titles/adornment
1642 (rst-reset-section-caches)
1643 (let ((ttl-fnd (rst-find-title-line))
1646 (set-match-data (cdr ttl-fnd
))
1647 (goto-char (match-beginning 2))
1648 (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt
)))
1649 (char (caar ttl-fnd
))
1650 (style (cdar ttl-fnd
))
1651 (indent (current-indentation))
1652 (curado (list char style indent
))
1653 char-new style-new indent-new
)
1655 ;;-------------------------------------------------------------------
1656 ;; Case 1: No valid adornment
1658 (let ((prev (car (rst-get-adornments-around)))
1660 (hier (rst-get-hierarchy)))
1661 ;; Advance one level down.
1664 (if (or (and rst-new-adornment-down reverse-direction
)
1665 (and (not rst-new-adornment-down
)
1666 (not reverse-direction
)))
1668 (or (cadr (rst-get-adornment-match hier prev
))
1669 (rst-suggest-new-adornment hier prev
)))
1670 (copy-sequence (car rst-preferred-adornments
))))
1671 ;; Invert the style if requested.
1673 (setcar (cdr cur
) (if (eq (cadr cur
) 'simple
)
1674 'over-and-under
'simple
)) )
1675 (setq char-new
(car cur
)
1676 style-new
(cadr cur
)
1677 indent-new
(caddr cur
))))
1678 ;;-------------------------------------------------------------------
1679 ;; Case 2: Incomplete Adornment
1680 ((not (rst-adornment-complete-p curado
))
1681 ;; Invert the style if requested.
1683 (setq style
(if (eq style
'simple
) 'over-and-under
'simple
)))
1687 ;;-------------------------------------------------------------------
1688 ;; Case 3: Complete Existing Adornment
1691 ;; Simply switch the style of the current adornment.
1693 style-new
(if (eq style
'simple
) 'over-and-under
'simple
)
1694 indent-new rst-default-indent
)
1695 ;; Else, we rotate, ignoring the adornment around the current
1697 (let* ((hier (rst-get-hierarchy (line-number-at-pos)))
1698 ;; Suggestion, in case we need to come up with something new.
1699 (suggestion (rst-suggest-new-adornment
1701 (car (rst-get-adornments-around))))
1702 (nextado (rst-get-next-adornment
1703 curado hier suggestion reverse-direction
)))
1704 ;; Indent, if present, always overrides the prescribed indent.
1705 (setq char-new
(car nextado
)
1706 style-new
(cadr nextado
)
1707 indent-new
(caddr nextado
))))))
1708 ;; Override indent with present indent!
1709 (setq indent-new
(if (> indent
0) indent indent-new
))
1710 (if (and char-new style-new
)
1711 (rst-update-section char-new style-new indent-new
))
1712 ;; Correct the position of the cursor to more accurately reflect where
1713 ;; it was located when the function was invoked.
1714 (unless (zerop moved
)
1715 (forward-line (- moved
))
1718 ;; Maintain an alias for compatibility.
1719 (defalias 'rst-adjust-section-title
'rst-adjust
)
1722 (defun rst-promote-region (demote)
1723 "Promote the section titles within the region.
1725 With argument DEMOTE or a prefix argument, demote the section
1726 titles instead. The algorithm used at the boundaries of the
1727 hierarchy is similar to that used by `rst-adjust-adornment-work'."
1729 (rst-reset-section-caches)
1730 (let* ((cur (rst-find-all-adornments))
1731 (hier (rst-get-hierarchy))
1732 (suggestion (rst-suggest-new-adornment hier
))
1734 (region-begin-line (line-number-at-pos (region-beginning)))
1735 (region-end-line (line-number-at-pos (region-end)))
1740 ;; Skip the markers that come before the region beginning.
1741 (while (and cur
(< (caar cur
) region-begin-line
))
1742 (setq cur
(cdr cur
)))
1744 ;; Create a list of markers for all the adornments which are found within
1748 (while (and cur
(< (setq line
(caar cur
)) region-end-line
))
1749 (goto-char (point-min))
1750 (forward-line (1- line
))
1751 (push (list (point-marker) (cdar cur
)) marker-list
)
1752 (setq cur
(cdr cur
)) ))
1754 ;; Apply modifications.
1755 (dolist (p marker-list
)
1756 ;; Go to the adornment to promote.
1759 ;; Update the adornment.
1760 (apply 'rst-update-section
1761 ;; Rotate the next adornment.
1762 (rst-get-next-adornment
1763 (cadr p
) hier suggestion demote
))
1765 ;; Clear marker to avoid slowing down the editing after we're done.
1766 (set-marker (car p
) nil
))
1767 (setq deactivate-mark nil
)
1772 (defun rst-display-adornments-hierarchy (&optional adornments
)
1773 "Display the current file's section title adornments hierarchy.
1774 This function expects a list of (CHARACTER STYLE INDENT) triples
1777 (rst-reset-section-caches)
1778 (if (not adornments
)
1779 (setq adornments
(rst-get-hierarchy)))
1780 (with-output-to-temp-buffer "*rest section hierarchy*"
1782 (with-current-buffer standard-output
1783 (dolist (x adornments
)
1784 (insert (format "\nSection Level %d" level
))
1785 (apply 'rst-update-section x
)
1786 (goto-char (point-max))
1792 (defun rst-straighten-adornments ()
1793 "Redo all the adornments in the current buffer.
1794 This is done using our preferred set of adornments. This can be
1795 used, for example, when using somebody else's copy of a document,
1796 in order to adapt it to our preferred style."
1798 (rst-reset-section-caches)
1800 (let (;; Get a list of pairs of (level . marker).
1801 (levels-and-markers (mapcar
1803 (cons (rst-position (cdr ado
)
1804 (rst-get-hierarchy))
1806 (goto-char (point-min))
1807 (forward-line (1- (car ado
)))
1809 (rst-find-all-adornments))))
1810 (dolist (lm levels-and-markers
)
1811 ;; Go to the appropriate position.
1812 (goto-char (cdr lm
))
1814 ;; Apply the new style.
1815 (apply 'rst-update-section
(nth (car lm
) rst-preferred-adornments
))
1817 ;; Reset the marker to avoid slowing down editing until it gets GC'ed.
1818 (set-marker (cdr lm
) nil
)
1824 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1825 ;; Insert list items
1826 ;; =================
1829 ;=================================================
1830 ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>.
1831 ; I needed to make some tiny changes to the functions, so I put it here.
1834 (defconst rst-arabic-to-roman
1835 '((1000 .
"M") (900 .
"CM") (500 .
"D") (400 .
"CD")
1836 (100 .
"C") (90 .
"XC") (50 .
"L") (40 .
"XL")
1837 (10 .
"X") (9 .
"IX") (5 .
"V") (4 .
"IV")
1839 "List of maps between Arabic numbers and their Roman numeral equivalents.")
1841 (defun rst-arabic-to-roman (num &optional arg
)
1842 "Convert Arabic number NUM to its Roman numeral representation.
1844 Obviously, NUM must be greater than zero. Don't blame me, blame the
1845 Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
1846 apologies to Monty Python).
1847 If optional prefix ARG is non-nil, insert in current buffer."
1848 (let ((map rst-arabic-to-roman
)
1850 (while (and map
(> num
0))
1851 (if (or (= num
(caar map
))
1853 (setq res
(concat res
(cdar map
))
1854 num
(- num
(caar map
)))
1855 (setq map
(cdr map
))))
1858 (defun rst-roman-to-arabic (string &optional arg
)
1859 "Convert STRING of Roman numerals to an Arabic number.
1861 If STRING contains a letter which isn't a valid Roman numeral, the rest
1862 of the string from that point onwards is ignored.
1868 If optional ARG is non-nil, insert in current buffer."
1870 (map rst-arabic-to-roman
))
1872 (if (string-match (concat "^" (cdar map
)) string
)
1873 (setq res
(+ res
(caar map
))
1874 string
(replace-match "" nil t string
))
1875 (setq map
(cdr map
))))
1877 ;=================================================
1879 (defun rst-find-pfx-in-region (beg end pfx-re
)
1880 "Find all the positions of prefixes in region between BEG and END.
1881 This is used to find bullets and enumerated list items. PFX-RE is
1882 a regular expression for matching the lines after indentation
1883 with items. Returns a list of cons cells consisting of the point
1884 and the column of the point."
1888 (while (< (point) end
)
1889 (back-to-indentation)
1891 (looking-at pfx-re
) ; pfx found and...
1892 (let ((pfx-col (current-column)))
1894 (forward-line -
1) ; ...previous line is...
1895 (back-to-indentation)
1896 (or (looking-at (rst-re 'lin-end
)) ; ...empty,
1897 (> (current-column) pfx-col
) ; ...deeper level, or
1898 (and (= (current-column) pfx-col
)
1899 (looking-at pfx-re
)))))) ; ...pfx at same level.
1900 (push (cons (point) (current-column))
1905 (defun rst-insert-list-pos (newitem)
1906 "Arrange relative position of a newly inserted list item of style NEWITEM.
1908 Adding a new list might consider three situations:
1910 (a) Current line is a blank line.
1911 (b) Previous line is a blank line.
1912 (c) Following line is a blank line.
1914 When (a) and (b), just add the new list at current line.
1916 when (a) and not (b), a blank line is added before adding the new list.
1918 When not (a), first forward point to the end of the line, and add two
1919 blank lines, then add the new list.
1921 Other situations are just ignored and left to users themselves."
1924 (looking-at (rst-re 'lin-end
)))
1927 (looking-at (rst-re 'lin-end
)))
1928 (insert newitem
" ")
1929 (insert "\n" newitem
" "))
1931 (insert "\n\n" newitem
" ")))
1933 ;; FIXME: Isn't this a `defconst'?
1934 (defvar rst-initial-enums
1936 (dolist (fmt '("%s." "(%s)" "%s)"))
1937 (dolist (c '("1" "a" "A" "I" "i"))
1938 (push (format fmt c
) vals
)))
1939 (cons "#." (nreverse vals
)))
1940 "List of initial enumerations.")
1942 ;; FIXME: Isn't this a `defconst'?
1943 (defvar rst-initial-items
1944 (append (mapcar 'char-to-string rst-bullets
) rst-initial-enums
)
1945 "List of initial items. It's collection of bullets and enumerations.")
1947 (defun rst-insert-list-new-item ()
1948 "Insert a new list item.
1950 User is asked to select the item style first, for example (a), i), +. Use TAB
1951 for completion and choices.
1953 If user selects bullets or #, it's just added with position arranged by
1954 `rst-insert-list-pos'.
1956 If user selects enumerations, a further prompt is given. User need to input a
1957 starting item, for example 'e' for 'A)' style. The position is also arranged by
1958 `rst-insert-list-pos'."
1960 ;; FIXME: Make this comply to `interactive' standards.
1961 (let* ((itemstyle (completing-read
1962 "Select preferred item style [#.]: "
1963 rst-initial-items nil t nil nil
"#."))
1964 (cnt (if (string-match (rst-re 'cntexp-tag
) itemstyle
)
1965 (match-string 0 itemstyle
)))
1968 ;; FIXME: Make this comply to `interactive' standards.
1971 (let ((itemno (read-string "Give starting value [a]: "
1973 (downcase (substring itemno
0 1))))
1975 (let ((itemno (read-string "Give starting value [A]: "
1977 (upcase (substring itemno
0 1))))
1979 (let ((itemno (read-number "Give starting value [1]: " 1)))
1980 (rst-arabic-to-roman itemno
)))
1982 (let ((itemno (read-number "Give starting value [1]: " 1)))
1983 (downcase (rst-arabic-to-roman itemno
))))
1985 (let ((itemno (read-number "Give starting value [1]: " 1)))
1986 (number-to-string itemno
)))))))
1988 (setq itemstyle
(replace-match no t t itemstyle
)))
1989 (rst-insert-list-pos itemstyle
)))
1991 (defcustom rst-preferred-bullets
1993 "List of favorite bullets."
1996 (choice ,@(mapcar (lambda (char)
1998 :tag
(char-to-string char
) char
))
2000 :package-version
'(rst .
"1.1.0"))
2002 (defun rst-insert-list-continue (curitem prefer-roman
)
2003 "Insert a list item with list start CURITEM including its indentation level.
2004 If PREFER-ROMAN roman numbering is preferred over using letters."
2007 "\n" ; FIXME: Separating lines must be possible.
2009 ((string-match (rst-re '(:alt enmaut-tag
2012 ((string-match (rst-re 'num-tag
) curitem
)
2013 (replace-match (number-to-string
2014 (1+ (string-to-number (match-string 0 curitem
))))
2016 ((and (string-match (rst-re 'rom-tag
) curitem
)
2018 (if (string-match (rst-re 'ltr-tag
) curitem
) ; Also a letter tag.
2020 ;; FIXME: Assumes one line list items without separating
2022 (if (and (zerop (forward-line -
1))
2023 (looking-at (rst-re 'enmexp-beg
)))
2026 (match-string 0)) ; Previous was a roman tag.
2027 prefer-roman
)) ; Don't know - use flag.
2028 t
))) ; Not a letter tag.
2030 (let* ((old (match-string 0 curitem
))
2031 (new (save-match-data
2032 (rst-arabic-to-roman
2033 (1+ (rst-roman-to-arabic
2035 (if (equal old
(upcase old
))
2039 ((string-match (rst-re 'ltr-tag
) curitem
)
2040 (replace-match (char-to-string
2041 (1+ (string-to-char (match-string 0 curitem
))))
2042 nil nil curitem
)))))
2045 (defun rst-insert-list (&optional prefer-roman
)
2046 "Insert a list item at the current point.
2048 The command can insert a new list or a continuing list. When it is called at a
2049 non-list line, it will promote to insert new list. When it is called at a list
2050 line, it will insert a list with the same list style.
2052 1. When inserting a new list:
2054 User is asked to select the item style first, for example (a), i), +. Use TAB
2055 for completion and choices.
2057 (a) If user selects bullets or #, it's just added.
2058 (b) If user selects enumerations, a further prompt is given. User needs to
2059 input a starting item, for example 'e' for 'A)' style.
2061 The position of the new list is arranged according to whether or not the
2062 current line and the previous line are blank lines.
2064 2. When continuing a list, one thing need to be noticed:
2066 List style alphabetical list, such as 'a.', and roman numerical list, such as
2067 'i.', have some overlapping items, for example 'v.' The function can deal with
2068 the problem elegantly in most situations. But when those overlapped list are
2069 preceded by a blank line, it is hard to determine which type to use
2070 automatically. The function uses alphabetical list by default. If you want
2071 roman numerical list, just use a prefix to set PREFER-ROMAN."
2074 (if (looking-at (rst-re 'itmany-beg-1
))
2075 (rst-insert-list-continue (match-string 0) prefer-roman
)
2076 (rst-insert-list-new-item)))
2078 (defun rst-straighten-bullets-region (beg end
)
2079 "Make all the bulleted list items in the region consistent.
2080 The region is specified between BEG and END. You can use this
2081 after you have merged multiple bulleted lists to make them use
2082 the same/correct/consistent bullet characters.
2084 See variable `rst-preferred-bullets' for the list of bullets to
2085 adjust. If bullets are found on levels beyond the
2086 `rst-preferred-bullets' list, they are not modified."
2089 (let ((bullets (rst-find-pfx-in-region beg end
(rst-re 'bul-sta
)))
2090 (levtable (make-hash-table :size
4)))
2092 ;; Create a map of levels to list of positions.
2094 (let ((key (cdr x
)))
2096 (append (gethash key levtable
(list))
2100 ;; Sort this map and create a new map of prefix char and list of positions.
2101 (let ((poslist ())) ; List of (indent . positions).
2102 (maphash (lambda (x y
) (push (cons x y
) poslist
)) levtable
)
2104 (let ((bullets rst-preferred-bullets
))
2105 (dolist (x (sort poslist
'car-less-than-car
))
2107 ;; Apply the characters.
2108 (dolist (pos (cdr x
))
2111 (insert (string (car bullets
))))
2112 (setq bullets
(cdr bullets
))))))))
2115 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2116 ;; Table of contents
2117 ;; =================
2119 (defun rst-get-stripped-line ()
2120 "Return the line at cursor, stripped from whitespace."
2121 (re-search-forward (rst-re "\\S .*\\S ") (line-end-position))
2122 (buffer-substring-no-properties (match-beginning 0)
2125 (defun rst-section-tree ()
2126 "Get the hierarchical tree of section titles.
2128 Returns a hierarchical tree of the sections titles in the
2129 document. This can be used to generate a table of contents for
2130 the document. The top node will always be a nil node, with the
2131 top level titles as children (there may potentially be more than
2134 Each section title consists in a cons of the stripped title
2135 string and a marker to the section in the original text document.
2137 If there are missing section levels, the section titles are
2138 inserted automatically, and the title string is set to nil, and
2139 the marker set to the first non-nil child of itself.
2140 Conceptually, the nil nodes--i.e.\ those which have no title--are
2141 to be considered as being the same line as their first non-nil
2142 child. This has advantages later in processing the graph."
2144 (let ((hier (rst-get-hierarchy))
2145 (levels (make-hash-table :test
'equal
:size
10))
2150 ;; Compare just the character and indent in the hash table.
2151 (puthash (cons (car ado
) (cadr ado
)) lev levels
)
2154 ;; Create a list of lines that contains (text, level, marker) for each
2158 (mapcar (lambda (ado)
2159 (goto-char (point-min))
2160 (forward-line (1- (car ado
)))
2161 (list (gethash (cons (cadr ado
) (caddr ado
)) levels
)
2162 (rst-get-stripped-line)
2164 (beginning-of-line 1)
2166 (rst-find-all-adornments))))
2167 (let ((lcontnr (cons nil lines
)))
2168 (rst-section-tree-rec lcontnr -
1))))
2171 (defun rst-section-tree-rec (ados lev
)
2172 "Recursive guts of the section tree construction.
2173 ADOS is a cons cell whose cdr is the remaining list of
2174 adornments, and we change it as we consume them. LEV is
2175 the current level of that node. This function returns a
2176 pair of the subtree that was built. This treats the ADOS
2177 list destructively."
2179 (let ((nado (cadr ados
))
2183 ;; If the next adornment matches our level.
2184 (when (and nado
(= (car nado
) lev
))
2185 ;; Pop the next adornment and create the current node with it.
2186 (setcdr ados
(cddr ados
))
2187 (setq node
(cdr nado
)) )
2188 ;; Else we let the node title/marker be unset.
2190 ;; Build the child nodes.
2191 (while (and (cdr ados
) (> (caadr ados
) lev
))
2193 (cons (rst-section-tree-rec ados
(1+ lev
))
2195 (setq children
(reverse children
))
2197 ;; If node is still unset, we use the marker of the first child.
2199 (setq node
(cons nil
(cdaar children
))))
2201 ;; Return this node with its children.
2202 (cons node children
)
2206 (defun rst-section-tree-point (node &optional point
)
2207 "Find tree node at point.
2208 Given a computed and valid section tree in NODE and a point
2209 POINT (default being the current point in the current buffer),
2210 find and return the node within the section tree where the cursor
2213 Return values: a pair of (parent path, container subtree).
2214 The parent path is simply a list of the nodes above the
2215 container subtree node that we're returning."
2219 (let* ((curpoint (or point
(point))))
2221 ;; Check if we are before the current node.
2222 (if (and (cadar node
) (>= curpoint
(cadar node
)))
2224 ;; Iterate all the children, looking for one that might contain the
2226 (let ((curnode (cdr node
))
2229 (while (and curnode
(>= curpoint
(cadaar curnode
)))
2231 curnode
(cdr curnode
)))
2234 (let ((sub (rst-section-tree-point (car last
) curpoint
)))
2235 (setq path
(car sub
)
2237 (setq outtree node
))
2240 (cons (cons (car node
) path
) outtree
)
2244 (defgroup rst-toc nil
2245 "Settings for reStructuredText table of contents."
2249 (defcustom rst-toc-indent
2
2250 "Indentation for table-of-contents display.
2251 Also used for formatting insertion, when numbering is disabled."
2254 (defcustom rst-toc-insert-style
'fixed
2255 "Insertion style for table-of-contents.
2256 Set this to one of the following values to determine numbering and
2258 - plain: no numbering (fixed indentation)
2259 - fixed: numbering, but fixed indentation
2260 - aligned: numbering, titles aligned under each other
2261 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
2264 (defcustom rst-toc-insert-number-separator
" "
2265 "Separator that goes between the TOC number and the title."
2268 ;; This is used to avoid having to change the user's mode.
2269 (defvar rst-toc-insert-click-keymap
2270 (let ((map (make-sparse-keymap)))
2271 (define-key map
[mouse-1
] 'rst-toc-mode-mouse-goto
)
2273 "(Internal) What happens when you click on propertized text in the TOC.")
2275 (defcustom rst-toc-insert-max-level nil
2276 "If non-nil, maximum depth of the inserted TOC."
2280 (defun rst-toc-insert (&optional pfxarg
)
2281 "Insert a simple text rendering of the table of contents.
2282 By default the top level is ignored if there is only one, because
2283 we assume that the document will have a single title.
2285 If a numeric prefix argument PFXARG is given, insert the TOC up
2286 to the specified level.
2288 The TOC is inserted indented at the current column."
2290 (rst-reset-section-caches)
2291 (let* (;; Check maximum level override.
2292 (rst-toc-insert-max-level
2293 (if (and (integerp pfxarg
) (> (prefix-numeric-value pfxarg
) 0))
2294 (prefix-numeric-value pfxarg
) rst-toc-insert-max-level
))
2296 ;; Get the section tree for the current cursor point.
2298 (rst-section-tree-point
2299 (rst-section-tree)))
2301 ;; Figure out initial indent.
2302 (initial-indent (make-string (current-column) ?
))
2303 (init-point (point)))
2305 (when (cddr sectree-pair
)
2306 (rst-toc-insert-node (cdr sectree-pair
) 0 initial-indent
"")
2308 ;; Fixup for the first line.
2309 (delete-region init-point
(+ init-point
(length initial-indent
)))
2311 ;; Delete the last newline added.
2315 (defun rst-toc-insert-node (node level indent pfx
)
2316 "Insert tree node NODE in table-of-contents.
2317 Recursive function that does printing of the inserted toc.
2318 LEVEL is the depth level of the sections in the tree.
2319 INDENT is the indentation string. PFX is the prefix numbering,
2320 that includes the alignment necessary for all the children of
2323 ;; Note: we do child numbering from the parent, so we start number the
2324 ;; children one level before we print them.
2325 (let ((do-print (> level
0))
2330 (unless (equal rst-toc-insert-style
'plain
)
2331 (insert pfx rst-toc-insert-number-separator
))
2332 (insert (or (caar node
) "[missing node]"))
2333 ;; Add properties to the text, even though in normal text mode it
2334 ;; won't be doing anything for now. Not sure that I want to change
2335 ;; mode stuff. At least the highlighting gives the idea that this
2336 ;; is generated automatically.
2337 (put-text-property b
(point) 'mouse-face
'highlight
)
2338 (put-text-property b
(point) 'rst-toc-target
(cadar node
))
2339 (put-text-property b
(point) 'keymap rst-toc-insert-click-keymap
)
2344 ;; Prepare indent for children.
2347 ((eq rst-toc-insert-style
'plain
)
2348 (concat indent
(make-string rst-toc-indent ?
)))
2350 ((eq rst-toc-insert-style
'fixed
)
2351 (concat indent
(make-string rst-toc-indent ?
)))
2353 ((eq rst-toc-insert-style
'aligned
)
2354 (concat indent
(make-string (+ (length pfx
) 2) ?
)))
2356 ((eq rst-toc-insert-style
'listed
)
2357 (concat (substring indent
0 -
3)
2358 (concat (make-string (+ (length pfx
) 2) ?
) " - ")))
2362 (if (or (eq rst-toc-insert-max-level nil
)
2363 (< level rst-toc-insert-max-level
))
2364 (let ((do-child-numbering (>= level
0))
2366 (if do-child-numbering
2368 ;; Add a separating dot if there is already a prefix.
2369 (when (> (length pfx
) 0)
2370 (string-match (rst-re "[ \t\n]*\\'") pfx
)
2371 (setq pfx
(concat (replace-match "" t t pfx
) ".")))
2373 ;; Calculate the amount of space that the prefix will require
2376 (setq fmt
(format "%%-%dd"
2377 (1+ (floor (log10 (length
2381 (dolist (child (cdr node
))
2382 (rst-toc-insert-node child
2385 (if do-child-numbering
2386 (concat pfx
(format fmt count
)) pfx
))
2392 (defun rst-toc-update ()
2393 "Automatically find the contents section of a document and update.
2394 Updates the inserted TOC if present. You can use this in your
2395 file-write hook to always make it up-to-date automatically."
2398 ;; Find and delete an existing comment after the first contents directive.
2399 ;; Delete that region.
2400 (goto-char (point-min))
2401 ;; We look for the following and the following only (in other words, if your
2402 ;; syntax differs, this won't work.).
2404 ;; .. contents:: [...anything here...]
2405 ;; [:field: value]...
2410 (let ((beg (re-search-forward
2411 (rst-re "^" 'exm-sta
"contents" 'dcl-tag
".*\n"
2412 "\\(?:" 'hws-sta
'fld-tag
".*\n\\)*" 'exm-tag
) nil t
))
2415 ;; Look for the first line that starts at the first column.
2418 (< (point) (point-max))
2420 (rst-re 'hws-sta
"\\S ")) ; indented content.
2421 (setq last-real
(point)))
2422 (looking-at (rst-re 'lin-end
)))) ; empty line.
2426 (goto-char last-real
)
2428 (delete-region beg
(point)))
2432 ;; Note: always return nil, because this may be used as a hook.
2435 ;; Note: we cannot bind the TOC update on file write because it messes with
2436 ;; undo. If we disable undo, since it adds and removes characters, the
2437 ;; positions in the undo list are not making sense anymore. Dunno what to do
2438 ;; with this, it would be nice to update when saving.
2440 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
2441 ;; (defun rst-toc-update-fun ()
2442 ;; ;; Disable undo for the write file hook.
2443 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
2445 (defalias 'rst-toc-insert-update
'rst-toc-update
) ; backwards compat.
2447 ;;------------------------------------------------------------------------------
2449 (defun rst-toc-node (node level
)
2450 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
2454 ;; Insert line text.
2455 (insert (make-string (* rst-toc-indent
(1- level
)) ?
))
2456 (insert (or (caar node
) "[missing node]"))
2459 (put-text-property b
(point) 'mouse-face
'highlight
)
2461 ;; Add link on lines.
2462 (put-text-property b
(point) 'rst-toc-target
(cadar node
))
2467 (dolist (child (cdr node
))
2468 (rst-toc-node child
(1+ level
))))
2470 (defun rst-toc-count-lines (node target-node
)
2471 "Count the number of lines from NODE to the TARGET-NODE node.
2472 This recursive function returns a cons of the number of
2473 additional lines that have been counted for its node and
2474 children, and t if the node has been found."
2478 (if (eq node target-node
)
2480 (let ((child (cdr node
)))
2481 (while (and child
(not found
))
2482 (let ((cl (rst-toc-count-lines (car child
) target-node
)))
2483 (setq count
(+ count
(car cl
))
2485 child
(cdr child
))))))
2486 (cons count found
)))
2488 (defvar rst-toc-buffer-name
"*Table of Contents*"
2489 "Name of the Table of Contents buffer.")
2491 (defvar rst-toc-return-wincfg nil
2492 "Window configuration to which to return when leaving the TOC.")
2496 "Display a table-of-contents.
2497 Finds all the section titles and their adornments in the
2498 file, and displays a hierarchically-organized list of the
2499 titles, which is essentially a table-of-contents of the
2502 The Emacs buffer can be navigated, and selecting a section
2503 brings the cursor in that section."
2505 (rst-reset-section-caches)
2506 (let* ((curbuf (list (current-window-configuration) (point-marker)))
2507 (sectree (rst-section-tree))
2509 (our-node (cdr (rst-section-tree-point sectree
)))
2512 ;; Create a temporary buffer.
2513 (buf (get-buffer-create rst-toc-buffer-name
))
2516 (with-current-buffer buf
2517 (let ((inhibit-read-only t
))
2519 (delete-region (point-min) (point-max))
2520 (insert (format "Table of Contents: %s\n" (or (caar sectree
) "")))
2521 (put-text-property (point-min) (point)
2522 'face
(list '(background-color .
"gray")))
2523 (rst-toc-node sectree
0)
2525 ;; Count the lines to our found node.
2526 (let ((linefound (rst-toc-count-lines sectree our-node
)))
2527 (setq line
(if (cdr linefound
) (car linefound
) 0)))
2529 (display-buffer buf
)
2532 ;; Save the buffer to return to.
2533 (set (make-local-variable 'rst-toc-return-wincfg
) curbuf
)
2535 ;; Move the cursor near the right section in the TOC.
2536 (goto-char (point-min))
2537 (forward-line (1- line
))
2541 (defun rst-toc-mode-find-section ()
2542 "Get the section from text property at point."
2543 (let ((pos (get-text-property (point) 'rst-toc-target
)))
2545 (error "No section on this line"))
2546 (unless (buffer-live-p (marker-buffer pos
))
2547 (error "Buffer for this section was killed"))
2550 ;; FIXME: Cursor before or behind the list must be handled properly; before the
2551 ;; list should jump to the top and behind the list to the last normal
2553 (defun rst-goto-section (&optional kill
)
2554 "Go to the section the current line describes.
2555 If KILL a toc buffer is destroyed."
2557 (let ((pos (rst-toc-mode-find-section)))
2559 ;; FIXME: This should rather go to `rst-toc-mode-goto-section'.
2560 (set-window-configuration (car rst-toc-return-wincfg
))
2561 (kill-buffer (get-buffer rst-toc-buffer-name
)))
2562 (pop-to-buffer (marker-buffer pos
))
2564 ;; FIXME: make the recentering conditional on scroll.
2567 (defun rst-toc-mode-goto-section ()
2568 "Go to the section the current line describes and kill the TOC buffer."
2570 (rst-goto-section t
))
2572 (defun rst-toc-mode-mouse-goto (event)
2573 "In `rst-toc' mode, go to the occurrence whose line you click on.
2574 EVENT is the input event."
2577 (with-current-buffer (window-buffer (posn-window (event-end event
)))
2579 (goto-char (posn-point (event-end event
)))
2580 (rst-toc-mode-find-section)))))
2581 (pop-to-buffer (marker-buffer pos
))
2585 (defun rst-toc-mode-mouse-goto-kill (event)
2586 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well.
2587 EVENT is the input event."
2589 (call-interactively 'rst-toc-mode-mouse-goto event
)
2590 (kill-buffer (get-buffer rst-toc-buffer-name
)))
2592 (defun rst-toc-quit-window ()
2593 "Leave the current TOC buffer."
2595 (let ((retbuf rst-toc-return-wincfg
))
2596 (set-window-configuration (car retbuf
))
2597 (goto-char (cadr retbuf
))))
2599 (defvar rst-toc-mode-map
2600 (let ((map (make-sparse-keymap)))
2601 (define-key map
[mouse-1
] 'rst-toc-mode-mouse-goto-kill
)
2602 (define-key map
[mouse-2
] 'rst-toc-mode-mouse-goto
)
2603 (define-key map
"\C-m" 'rst-toc-mode-goto-section
)
2604 (define-key map
"f" 'rst-toc-mode-goto-section
)
2605 (define-key map
"q" 'rst-toc-quit-window
)
2606 (define-key map
"z" 'kill-this-buffer
)
2608 "Keymap for `rst-toc-mode'.")
2610 (put 'rst-toc-mode
'mode-class
'special
)
2612 ;; Could inherit from the new `special-mode'.
2613 (define-derived-mode rst-toc-mode nil
"ReST-TOC"
2614 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2615 (setq buffer-read-only t
))
2617 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2620 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2621 ;; Section movement commands
2622 ;; =========================
2624 (defun rst-forward-section (&optional offset
)
2625 "Skip to the next reStructuredText section title.
2626 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2627 backwards in the file (default is to use 1)."
2629 (rst-reset-section-caches)
2630 (let* (;; Default value for offset.
2631 (offset (or offset
1))
2633 ;; Get all the adornments in the file, with their line numbers.
2634 (allados (rst-find-all-adornments))
2636 ;; Get the current line.
2637 (curline (line-number-at-pos))
2643 ;; Find the index of the "next" adornment w.r.t. to the current line.
2644 (while (and cur
(< (caar cur
) curline
))
2645 (setq cur
(cdr cur
))
2647 ;; 'cur' is the adornment on or following the current line.
2649 (if (and (> offset
0) cur
(= (caar cur
) curline
))
2652 ;; Find the final index.
2653 (setq idx
(+ idx
(if (> offset
0) (- offset
1) offset
)))
2654 (setq cur
(nth idx allados
))
2656 ;; If the index is positive, goto the line, otherwise go to the buffer
2658 (if (and cur
(>= idx
0))
2660 (goto-char (point-min))
2661 (forward-line (1- (car cur
))))
2662 (if (> offset
0) (goto-char (point-max)) (goto-char (point-min))))
2665 (defun rst-backward-section ()
2666 "Like `rst-forward-section', except move back one title."
2668 (rst-forward-section -
1))
2670 ;; FIXME: What is `allow-extend' for?
2671 (defun rst-mark-section (&optional count allow-extend
)
2672 "Select COUNT sections around point.
2673 Mark following sections for positive COUNT or preceding sections
2674 for negative COUNT."
2675 ;; Cloned from mark-paragraph.
2676 (interactive "p\np")
2677 (unless count
(setq count
1))
2679 (error "Cannot mark zero sections"))
2680 (cond ((and allow-extend
2681 (or (and (eq last-command this-command
) (mark t
))
2682 (rst-portable-mark-active-p)))
2686 (rst-forward-section count
)
2689 (rst-forward-section count
)
2691 (rst-forward-section (- count
)))))
2694 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2695 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2696 ;; always 2 or 3 characters apart horizontally with rest.
2698 (defun rst-find-leftmost-column (beg end
)
2699 "Return the leftmost column in region BEG to END."
2703 (while (< (point) end
)
2704 (back-to-indentation)
2705 (unless (looking-at (rst-re 'lin-end
))
2706 (setq mincol
(if mincol
2707 (min mincol
(current-column))
2712 ;; FIXME: This definition is old and deprecated. We need to move to the newer
2714 (defmacro rst-iterate-leftmost-paragraphs
2715 (beg end first-only body-consequent body-alternative
)
2716 ;; FIXME: The following comment is pretty useless.
2717 "Call FUN at the beginning of each line, with an argument that
2718 specifies whether we are at the first line of a paragraph that
2719 starts at the leftmost column of the given region BEG and END.
2720 Set FIRST-ONLY to true if you want to callback on the first line
2721 of each paragraph only."
2723 (let ((leftcol (rst-find-leftmost-column ,beg
,end
))
2724 (endm (copy-marker ,end
)))
2726 (do* (;; Iterate lines.
2727 (l (progn (goto-char ,beg
) (back-to-indentation))
2728 (progn (forward-line 1) (back-to-indentation)))
2730 (previous nil valid
)
2732 (curcol (current-column)
2735 (valid (and (= curcol leftcol
)
2736 (not (looking-at (rst-re 'lin-end
))))
2737 (and (= curcol leftcol
)
2738 (not (looking-at (rst-re 'lin-end
)))))
2743 (and valid
(not previous
))
2750 ;; FIXME: This needs to be refactored. Probably this is simply a function
2751 ;; applying BODY rather than a macro.
2752 (defmacro rst-iterate-leftmost-paragraphs-2
(spec &rest body
)
2753 "Evaluate BODY for each line in region defined by BEG END.
2754 LEFTMOST is set to true if the line is one of the leftmost of the
2755 entire paragraph. PARABEGIN is set to true if the line is the
2756 first of a paragraph."
2757 (declare (indent 1) (debug (sexp body
)))
2759 (beg end parabegin leftmost isleftmost isempty
) spec
2762 (let ((,leftmost
(rst-find-leftmost-column ,beg
,end
))
2763 (endm (copy-marker ,end
)))
2765 (do* (;; Iterate lines.
2766 (l (progn (goto-char ,beg
) (back-to-indentation))
2767 (progn (forward-line 1) (back-to-indentation)))
2769 (empty-line-previous nil
,isempty
)
2771 (,isempty
(looking-at (rst-re 'lin-end
))
2772 (looking-at (rst-re 'lin-end
)))
2774 (,parabegin
(not ,isempty
)
2775 (and empty-line-previous
2778 (,isleftmost
(and (not ,isempty
)
2779 (= (current-column) ,leftmost
))
2781 (= (current-column) ,leftmost
)))
2789 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2792 ;; FIXME: At the moment only block comments with leading empty comment line are
2793 ;; supported. Comment lines with leading comment markup should be also
2794 ;; supported. May be a customizable option could control which style to
2797 (defgroup rst-indent nil
"Settings for indentation in reStructuredText.
2799 In reStructuredText indentation points are usually determined by
2800 preceding lines. Sometimes the syntax allows arbitrary
2801 indentation points such as where to start the first line
2802 following a directive. These indentation widths can be customized
2805 :package-version
'(rst .
"1.1.0"))
2807 (define-obsolete-variable-alias
2808 'rst-shift-basic-offset
'rst-indent-width
"1.0.0")
2809 (defcustom rst-indent-width
2
2810 "Indentation when there is no more indentation point given."
2814 (defcustom rst-indent-field
3
2815 "Indentation for first line after a field or 0 to always indent for content."
2819 (defcustom rst-indent-literal-normal
3
2820 "Default indentation for literal block after a markup on an own line."
2824 (defcustom rst-indent-literal-minimized
2
2825 "Default indentation for literal block after a minimized markup."
2829 (defcustom rst-indent-comment
3
2830 "Default indentation for first line of a comment."
2834 ;; FIXME: Must consider other tabs:
2836 ;; * Definition lists
2838 (defun rst-line-tabs ()
2839 "Return tabs of the current line or nil for no tab.
2840 The list is sorted so the tab where writing continues most likely
2841 is the first one. Each tab is of the form (COLUMN . INNER).
2842 COLUMN is the column of the tab. INNER is non-nil if this is an
2843 inner tab. I.e. a tab which does come from the basic indentation
2844 and not from inner alignment points."
2848 (unless (looking-at (rst-re 'lin-end
))
2849 (back-to-indentation)
2850 ;; Current indentation is always the least likely tab.
2851 (let ((tabs (list (list (point) 0 nil
)))) ; (POINT OFFSET INNER)
2852 ;; Push inner tabs more likely to continue writing.
2855 ((looking-at (rst-re '(:grp itmany-tag hws-sta
) '(:grp
"\\S ") "?"))
2856 (when (match-string 2)
2857 (push (list (match-beginning 2) 0 t
) tabs
)))
2859 ((looking-at (rst-re '(:grp fld-tag
) '(:grp hws-tag
)
2860 '(:grp
"\\S ") "?"))
2861 (unless (zerop rst-indent-field
)
2862 (push (list (match-beginning 1) rst-indent-field t
) tabs
))
2863 (if (match-string 3)
2864 (push (list (match-beginning 3) 0 t
) tabs
)
2865 (if (zerop rst-indent-field
)
2866 (push (list (match-end 2)
2867 (if (string= (match-string 2) "") 1 0)
2870 ((looking-at (rst-re 'dir-sta-3
'(:grp
"\\S ") "?"))
2871 (push (list (match-end 1) 0 t
) tabs
)
2872 (unless (string= (match-string 2) "")
2873 (push (list (match-end 2) 0 t
) tabs
))
2874 (when (match-string 4)
2875 (push (list (match-beginning 4) 0 t
) tabs
)))
2876 ;; Footnote or citation definition.
2877 ((looking-at (rst-re 'fnc-sta-2
'(:grp
"\\S ") "?"))
2878 (push (list (match-end 1) 0 t
) tabs
)
2879 (when (match-string 3)
2880 (push (list (match-beginning 3) 0 t
) tabs
)))
2882 ((looking-at (rst-re 'cmt-sta-1
))
2883 (push (list (point) rst-indent-comment t
) tabs
)))
2884 ;; Start of literal block.
2885 (when (looking-at (rst-re 'lit-sta-2
))
2886 (let ((tab0 (first tabs
)))
2887 (push (list (first tab0
)
2889 (if (match-string 1)
2890 rst-indent-literal-minimized
2891 rst-indent-literal-normal
))
2893 (mapcar (lambda (tab)
2894 (goto-char (first tab
))
2895 (cons (+ (current-column) (second tab
)) (third tab
)))
2898 (defun rst-compute-tabs (pt)
2899 "Build the list of possible tabs for all lines above.
2900 Search backwards from point PT to build the list of possible
2901 tabs. Return a list of tabs sorted by likeliness to continue
2902 writing like `rst-line-tabs'. Nearer lines have generally a
2903 higher likeliness than farther lines. Return nil if no tab is found
2907 (let (leftmost ; Leftmost column found so far.
2908 innermost
; Leftmost column for inner tab.
2910 (while (and (zerop (forward-line -
1))
2913 (let* ((tabs (rst-line-tabs))
2914 (leftcol (if tabs
(apply 'min
(mapcar 'car tabs
)))))
2916 ;; Consider only lines indented less or same if not INNERMOST.
2917 (when (or (not leftmost
)
2918 (< leftcol leftmost
)
2919 (and (not innermost
) (= leftcol leftmost
)))
2921 (let ((inner (cdr tab
))
2927 (< newcol leftmost
)))
2930 (< newcol innermost
))))
2931 (not (memq newcol tablist
)))
2932 (push newcol tablist
))))
2933 (setq innermost
(if (rst-some (mapcar 'cdr tabs
)) ; Has inner.
2936 (setq leftmost leftcol
)))))
2937 (nreverse tablist
))))
2939 (defun rst-indent-line (&optional dflt
)
2940 "Indent current line to next best reStructuredText tab.
2941 The next best tab is taken from the tab list returned by
2942 `rst-compute-tabs' which is used in a cyclic manner. If the
2943 current indentation does not end on a tab use the first one. If
2944 the current indentation is on a tab use the next tab. This allows
2945 a repeated use of \\[indent-for-tab-command] to cycle through all
2946 possible tabs. If no indentation is possible return `noindent' or
2947 use DFLT. Return the indentation indented to. When point is in
2948 indentation it ends up at its end. Otherwise the point is kept
2949 relative to the content."
2950 (let* ((pt (point-marker))
2951 (cur (current-indentation))
2952 (clm (current-column))
2953 (tabs (rst-compute-tabs (point)))
2954 (fnd (rst-position cur tabs
))
2956 (if (and (not tabs
) (not dflt
))
2963 (if (>= fnd
(length tabs
))
2965 (setq ind
(nth fnd tabs
)))
2966 (indent-line-to ind
)
2972 (defun rst-shift-region (beg end cnt
)
2973 "Shift region BEG to END by CNT tabs.
2974 Shift by one tab to the right (CNT > 0) or left (CNT < 0) or
2975 remove all indentation (CNT = 0). A tab is taken from the text
2976 above. If no suitable tab is found `rst-indent-width' is used."
2977 (interactive "r\np")
2978 (let ((tabs (sort (rst-compute-tabs beg
) (lambda (x y
) (<= x y
))))
2979 (leftmostcol (rst-find-leftmost-column beg end
)))
2980 (when (or (> leftmostcol
0) (> cnt
0))
2981 ;; Apply the indent.
2986 ;; Find the next tab after the leftmost column.
2987 (let* ((cmp (if (> cnt
0) '> '<))
2988 (tabs (if (> cnt
0) tabs
(reverse tabs
)))
2990 (dir (rst-signum cnt
)) ; Direction to take.
2991 (abs (abs cnt
)) ; Absolute number of steps to take.
2992 ;; Get the position of the first tab beyond leftmostcol.
2993 (fnd (lexical-let ((cmp cmp
)
2994 (leftmostcol leftmostcol
)) ; Create closure.
2995 (rst-position-if (lambda (elt)
2996 (funcall cmp elt leftmostcol
))
2998 ;; Virtual position of tab.
2999 (pos (+ (or fnd len
) (1- abs
)))
3000 (tab (if (< pos len
)
3001 ;; Tab exists - use it.
3003 ;; Column needs to be computed.
3004 (let ((col (+ (or (car (last tabs
)) leftmostcol
)
3005 ;; Base on last known column.
3006 (* (- pos
(1- len
)) ; Distance left.
3007 dir
; Direction to take.
3008 rst-indent-width
))))
3009 (if (< col
0) 0 col
)))))
3010 (- tab leftmostcol
)))))))
3012 ;; FIXME: A paragraph with an (incorrectly) indented second line is not filled
3017 (defun rst-adaptive-fill ()
3018 "Return fill prefix found at point.
3019 Value for `adaptive-fill-function'."
3020 (let ((fnd (if (looking-at adaptive-fill-regexp
)
3021 (match-string-no-properties 0))))
3022 (if (save-match-data
3023 (not (string-match comment-start-skip fnd
)))
3024 ;; An non-comment prefix is fine.
3026 ;; Matches a comment - return whitespace instead.
3029 (goto-char (match-end 0))
3032 (goto-char (match-beginning 0))
3033 (current-column))) ?
))))
3035 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3038 (defun rst-comment-line-break (&optional soft
)
3039 "Break line and indent, continuing reStructuredText comment if within one.
3040 Value for `comment-line-break-function'. If SOFT use soft
3041 newlines as mandated by `comment-line-break-function'."
3043 (insert-and-inherit ?
\n)
3047 (delete-horizontal-space))
3048 (delete-horizontal-space)
3049 (let ((tabs (rst-compute-tabs (point))))
3051 (indent-line-to (car tabs
)))))
3053 (defun rst-comment-indent ()
3054 "Return indentation for current comment line."
3055 (car (rst-compute-tabs (point))))
3057 (defun rst-comment-insert-comment ()
3058 "Insert a comment in the current line."
3060 (insert comment-start
))
3062 (defun rst-comment-region (beg end
&optional arg
)
3063 "Comment or uncomment the current region.
3064 Region is from from BEG to END. Uncomment if ARG."
3067 (rst-uncomment-region beg end arg
)
3069 (let ((ind (current-indentation))
3073 (indent-rigidly bol end rst-indent-comment
)
3076 (indent-line-to ind
)
3077 (insert (comment-string-strip comment-start t t
))))))
3079 (defun rst-uncomment-region (beg end
&optional arg
)
3080 "Uncomment the current region.
3081 Region is from BEG to END. ARG is ignored"
3089 (indent-rigidly eol end
(- rst-indent-comment
))
3090 (delete-region bol eol
))))
3092 ;;------------------------------------------------------------------------------
3094 ;; FIXME: These next functions should become part of a larger effort to redo
3095 ;; the bullets in bulleted lists. The enumerate would just be one of
3096 ;; the possible outputs.
3098 ;; FIXME: We need to do the enumeration removal as well.
3100 (defun rst-enumerate-region (beg end all
)
3101 "Add enumeration to all the leftmost paragraphs in the given region.
3102 The region is specified between BEG and END. With ALL,
3103 do all lines instead of just paragraphs."
3104 (interactive "r\nP")
3106 (last-insert-len nil
))
3107 (rst-iterate-leftmost-paragraphs
3109 (let ((ins-string (format "%d. " (incf count
))))
3110 (setq last-insert-len
(length ins-string
))
3111 (insert ins-string
))
3112 (insert (make-string last-insert-len ?\
))
3115 (defun rst-bullet-list-region (beg end all
)
3116 "Add bullets to all the leftmost paragraphs in the given region.
3117 The region is specified between BEG and END. With ALL,
3118 do all lines instead of just paragraphs."
3119 (interactive "r\nP")
3120 (rst-iterate-leftmost-paragraphs
3122 (insert (car rst-preferred-bullets
) " ")
3126 ;; FIXME: Does not deal with a varying number of digits appropriately.
3127 ;; FIXME: Does not deal with multiple levels independently.
3128 ;; FIXME: Does not indent a multiline item correctly.
3129 (defun rst-convert-bullets-to-enumeration (beg end
)
3130 "Convert the bulleted and enumerated items in the region to enumerated lists.
3131 Renumber as necessary. Region is from BEG to END."
3133 (let* (;; Find items and convert the positions to markers.
3136 (cons (copy-marker (car x
))
3138 (rst-find-pfx-in-region beg end
(rst-re 'itmany-sta-1
))))
3144 (looking-at (rst-re 'itmany-beg-1
))
3145 (replace-match (format "%d." count
) nil nil nil
1)
3152 ;;------------------------------------------------------------------------------
3154 (defun rst-line-block-region (rbeg rend
&optional pfxarg
)
3155 "Toggle line block prefixes for a region.
3156 Region is from RBEG to REND. With PFXARG set the empty lines too."
3157 (interactive "r\nP")
3158 (let ((comment-start "| ")
3160 (comment-start-skip "| ")
3161 (comment-style 'indent
)
3162 (force (not (not pfxarg
))))
3163 (rst-iterate-leftmost-paragraphs-2
3164 (rbeg rend parbegin leftmost isleft isempty
)
3165 (when (or force
(not isempty
))
3166 (move-to-column leftmost force
)
3167 (delete-region (point) (+ (point) (- (current-indentation) leftmost
)))
3172 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3176 (require 'font-lock
)
3178 ;; FIXME: The obsolete variables need to disappear.
3180 ;; The following versions have been done inside Emacs and should not be
3181 ;; replaced by `:package-version' attributes until a change.
3183 (defgroup rst-faces nil
"Faces used in Rst Mode."
3188 (defface rst-block
'((t :inherit font-lock-keyword-face
))
3189 "Face used for all syntax marking up a special block."
3193 (defcustom rst-block-face
'rst-block
3194 "All syntax marking up a special block."
3198 (make-obsolete-variable 'rst-block-face
3199 "customize the face `rst-block' instead."
3202 (defface rst-external
'((t :inherit font-lock-type-face
))
3203 "Face used for field names and interpreted text."
3207 (defcustom rst-external-face
'rst-external
3208 "Field names and interpreted text."
3212 (make-obsolete-variable 'rst-external-face
3213 "customize the face `rst-external' instead."
3216 (defface rst-definition
'((t :inherit font-lock-function-name-face
))
3217 "Face used for all other defining constructs."
3221 (defcustom rst-definition-face
'rst-definition
3222 "All other defining constructs."
3226 (make-obsolete-variable 'rst-definition-face
3227 "customize the face `rst-definition' instead."
3230 ;; XEmacs compatibility (?).
3231 (defface rst-directive
(if (boundp 'font-lock-builtin-face
)
3232 '((t :inherit font-lock-builtin-face
))
3233 '((t :inherit font-lock-preprocessor-face
)))
3234 "Face used for directives and roles."
3238 (defcustom rst-directive-face
'rst-directive
3239 "Directives and roles."
3242 (make-obsolete-variable 'rst-directive-face
3243 "customize the face `rst-directive' instead."
3246 (defface rst-comment
'((t :inherit font-lock-comment-face
))
3247 "Face used for comments."
3251 (defcustom rst-comment-face
'rst-comment
3256 (make-obsolete-variable 'rst-comment-face
3257 "customize the face `rst-comment' instead."
3260 (defface rst-emphasis1
'((t :inherit italic
))
3261 "Face used for simple emphasis."
3265 (defcustom rst-emphasis1-face
'rst-emphasis1
3270 (make-obsolete-variable 'rst-emphasis1-face
3271 "customize the face `rst-emphasis1' instead."
3274 (defface rst-emphasis2
'((t :inherit bold
))
3275 "Face used for double emphasis."
3279 (defcustom rst-emphasis2-face
'rst-emphasis2
3283 (make-obsolete-variable 'rst-emphasis2-face
3284 "customize the face `rst-emphasis2' instead."
3287 (defface rst-literal
'((t :inherit font-lock-string-face
))
3288 "Face used for literal text."
3292 (defcustom rst-literal-face
'rst-literal
3297 (make-obsolete-variable 'rst-literal-face
3298 "customize the face `rst-literal' instead."
3301 (defface rst-reference
'((t :inherit font-lock-variable-name-face
))
3302 "Face used for references to a definition."
3306 (defcustom rst-reference-face
'rst-reference
3307 "References to a definition."
3311 (make-obsolete-variable 'rst-reference-face
3312 "customize the face `rst-reference' instead."
3315 (defface rst-transition
'((t :inherit font-lock-keyword-face
))
3316 "Face used for a transition."
3317 :package-version
'(rst .
"1.3.0")
3320 (defface rst-adornment
'((t :inherit font-lock-keyword-face
))
3321 "Face used for the adornment of a section header."
3322 :package-version
'(rst .
"1.3.0")
3325 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3327 ;; FIXME LEVEL-FACE: May be this complicated mechanism should be replaced
3328 ;; simply by a number of customizable faces `rst-header-%d'
3329 ;; which by default are set properly for dark and light
3330 ;; background. Initialization should come from the old
3331 ;; variables if they exist. A maximum level of 6 should
3332 ;; suffice - after that the last level should be repeated.
3333 ;; Only `rst-adornment-faces-alist' is needed outside this
3334 ;; block. Would also fix docutils-Bugs-3479594.
3336 (defgroup rst-faces-defaults nil
3337 "Values used to generate default faces for section titles on all levels.
3338 Tweak these if you are content with how section title faces are built in
3339 general but you do not like the details."
3343 (defun rst-set-level-default (sym val
)
3344 "Set custom variable SYM affecting section title text face.
3345 Recompute the faces. VAL is the value to set."
3346 (custom-set-default sym val
)
3347 ;; Also defines the faces initially when all values are available.
3348 (and (boundp 'rst-level-face-max
)
3349 (boundp 'rst-level-face-format-light
)
3350 (boundp 'rst-level-face-base-color
)
3351 (boundp 'rst-level-face-step-light
)
3352 (boundp 'rst-level-face-base-light
)
3353 (fboundp 'rst-define-level-faces
)
3354 (rst-define-level-faces)))
3356 ;; Faces for displaying items on several levels. These definitions define
3357 ;; different shades of gray where the lightest one (i.e. least contrasting on a
3358 ;; light background) is used for level 1.
3359 (defcustom rst-level-face-max
6
3360 "Maximum depth of levels for which section title faces are defined."
3361 :group
'rst-faces-defaults
3363 :set
'rst-set-level-default
)
3364 ;; FIXME: It should be possible to give "#RRGGBB" type of color values.
3365 ;; Together with a `rst-level-face-end-light' this could be used for
3367 ;; FIXME: This variable should be combined with `rst-level-face-format-light'
3368 ;; to a single string.
3369 (defcustom rst-level-face-base-color
"grey"
3370 "Base name of the color for creating background colors in section title faces."
3371 :group
'rst-faces-defaults
3373 :set
'rst-set-level-default
)
3374 ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
3375 ;; how they behave for dark and light background using the
3376 ;; relevant options explained in `defface'.
3377 (defcustom rst-level-face-base-light
3378 (if (eq frame-background-mode
'dark
)
3381 "The lightness factor for the base color. This value is used for level 1.
3382 The default depends on whether the value of `frame-background-mode' is
3384 :group
'rst-faces-defaults
3386 :set
'rst-set-level-default
)
3387 (defcustom rst-level-face-format-light
"%2d"
3388 "The format for the lightness factor appended to the base name of the color.
3389 This value is expanded by `format' with an integer."
3390 :group
'rst-faces-defaults
3392 :set
'rst-set-level-default
)
3393 ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
3394 ;; how they behave for dark and light background using the
3395 ;; relevant options explained in `defface'.
3396 ;; FIXME: Alternatively there could be a customizable variable
3397 ;; `rst-level-face-end-light' which defines the end value and steps are
3399 (defcustom rst-level-face-step-light
3400 (if (eq frame-background-mode
'dark
)
3403 "The step width to use for the next color.
3406 `rst-level-face-base-light'
3407 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
3409 must result in a color level which appended to `rst-level-face-base-color'
3410 using `rst-level-face-format-light' results in a valid color such as `grey50'.
3411 This color is used as background for section title text on level
3412 `rst-level-face-max'."
3413 :group
'rst-faces-defaults
3415 :set
'rst-set-level-default
)
3417 (defcustom rst-adornment-faces-alist
3418 ;; FIXME LEVEL-FACE: Must be redone if `rst-level-face-max' is changed
3419 (let ((alist (copy-sequence '((t . rst-transition
)
3420 (nil . rst-adornment
))))
3422 (while (<= i rst-level-face-max
)
3423 ;; FIXME: why not `push'?
3424 (nconc alist
(list (cons i
(intern (format "rst-level-%d-face" i
)))))
3427 "Faces for the various adornment types.
3428 Key is a number (for the section title text of that level
3429 starting with 1), t (for transitions) or nil (for section title
3430 adornment). If you generally do not like how section title text
3431 faces are set up tweak here. If the general idea is ok for you
3432 but you do not like the details check the Rst Faces Defaults
3438 (integer :tag
"Section level")
3439 (const :tag
"transitions" t
)
3440 (const :tag
"section title adornment" nil
))
3442 :set-after
'(rst-level-face-max))
3444 (defun rst-define-level-faces ()
3445 "Define the faces for the section title text faces from the values."
3446 ;; All variables used here must be checked in `rst-set-level-default'.
3448 (while (<= i rst-level-face-max
)
3449 (let ((sym (intern (format "rst-level-%d-face" i
)))
3450 (doc (format "Default face for showing section title text at level %d.
3451 This symbol is *not* meant for customization but modified if a
3452 variable of the `rst-faces-defaults' group is customized. Use
3453 `rst-adornment-faces-alist' for customization instead." i
))
3454 (col (format (concat "%s" rst-level-face-format-light
)
3455 rst-level-face-base-color
3456 (+ (* (1- i
) rst-level-face-step-light
)
3457 rst-level-face-base-light
))))
3458 (make-empty-face sym
)
3459 (set-face-doc-string sym doc
)
3460 (set-face-background sym col
)
3464 ;; FIXME LEVEL-FACE: This is probably superfluous since it is done by the
3465 ;; customization / `rst-set-level-default'.
3466 (rst-define-level-faces)
3468 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3470 (defvar rst-font-lock-keywords
3471 ;; The reST-links in the comments below all relate to sections in
3472 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.
3473 `(;; FIXME: Block markup is not recognized in blocks after explicit markup
3476 ;; Simple `Body Elements`_
3478 ;; FIXME: A bullet directly after a field name is not recognized.
3479 (,(rst-re 'lin-beg
'(:grp bul-sta
))
3481 ;; `Enumerated Lists`_
3482 (,(rst-re 'lin-beg
'(:grp enmany-sta
))
3484 ;; `Definition Lists`_
3487 (,(rst-re 'lin-beg
'(:grp fld-tag
) 'bli-sfx
)
3488 1 rst-external-face
)
3490 (,(rst-re 'lin-beg
'(:grp opt-tag
(:shy optsep-tag opt-tag
) "*")
3491 '(:alt
"$" (:seq hws-prt
"\\{2\\}")))
3494 ;; Only for lines containing no more bar - to distinguish from tables.
3495 (,(rst-re 'lin-beg
'(:grp
"|" bli-sfx
) "[^|\n]*$")
3501 ;; All the `Explicit Markup Blocks`_
3502 ;; `Footnotes`_ / `Citations`_
3503 (,(rst-re 'lin-beg
'fnc-sta-2
)
3504 (1 rst-definition-face
)
3505 (2 rst-definition-face
))
3506 ;; `Directives`_ / `Substitution Definitions`_
3507 (,(rst-re 'lin-beg
'dir-sta-3
)
3508 (1 rst-directive-face
)
3509 (2 rst-definition-face
)
3510 (3 rst-directive-face
))
3511 ;; `Hyperlink Targets`_
3513 '(:grp exm-sta
"_" (:alt
3514 (:seq
"`" ilcbkqdef-tag
"`")
3515 (:seq
(:alt
"[^:\\\n]" "\\\\.") "+")) ":")
3517 1 rst-definition-face
)
3518 (,(rst-re 'lin-beg
'(:grp
"__") 'bli-sfx
)
3519 1 rst-definition-face
)
3521 ;; All `Inline Markup`_
3522 ;; Most of them may be multiline though this is uninteresting.
3524 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
3525 ;; `Strong Emphasis`_.
3526 (,(rst-re 'ilm-pfx
'(:grp
"\\*\\*" ilcast-tag
"\\*\\*") 'ilm-sfx
)
3527 1 rst-emphasis2-face
)
3529 (,(rst-re 'ilm-pfx
'(:grp
"\\*" ilcast-tag
"\\*") 'ilm-sfx
)
3530 1 rst-emphasis1-face
)
3531 ;; `Inline Literals`_
3532 (,(rst-re 'ilm-pfx
'(:grp
"``" ilcbkq-tag
"``") 'ilm-sfx
)
3534 ;; `Inline Internal Targets`_
3535 (,(rst-re 'ilm-pfx
'(:grp
"_`" ilcbkq-tag
"`") 'ilm-sfx
)
3536 1 rst-definition-face
)
3537 ;; `Hyperlink References`_
3538 ;; FIXME: `Embedded URIs`_ not considered.
3539 ;; FIXME: Directly adjacent marked up words are not fontified correctly
3540 ;; unless they are not separated by two spaces: foo_ bar_.
3541 (,(rst-re 'ilm-pfx
'(:grp
(:alt
(:seq
"`" ilcbkq-tag
"`")
3542 (:seq
"\\sw" (:alt
"\\sw" "-") "+\\sw"))
3544 1 rst-reference-face
)
3545 ;; `Interpreted Text`_
3546 (,(rst-re 'ilm-pfx
'(:grp
(:shy
":" sym-tag
":") "?")
3547 '(:grp
"`" ilcbkq-tag
"`")
3548 '(:grp
(:shy
":" sym-tag
":") "?") 'ilm-sfx
)
3549 (1 rst-directive-face
)
3550 (2 rst-external-face
)
3551 (3 rst-directive-face
))
3552 ;; `Footnote References`_ / `Citation References`_
3553 (,(rst-re 'ilm-pfx
'(:grp fnc-tag
"_") 'ilm-sfx
)
3554 1 rst-reference-face
)
3555 ;; `Substitution References`_
3556 ;; FIXME: References substitutions like |this|_ or |this|__ are not
3557 ;; fontified correctly.
3558 (,(rst-re 'ilm-pfx
'(:grp sub-tag
) 'ilm-sfx
)
3559 1 rst-reference-face
)
3560 ;; `Standalone Hyperlinks`_
3561 ;; FIXME: This takes it easy by using a whitespace as delimiter.
3562 (,(rst-re 'ilm-pfx
'(:grp uri-tag
":\\S +") 'ilm-sfx
)
3563 1 rst-definition-face
)
3564 (,(rst-re 'ilm-pfx
'(:grp sym-tag
"@" sym-tag
) 'ilm-sfx
)
3565 1 rst-definition-face
)
3567 ;; Do all block fontification as late as possible so 'append works.
3569 ;; Sections_ / Transitions_
3570 ;; For sections this is multiline.
3571 (,(rst-re 'ado-beg-2-1
)
3572 (rst-font-lock-handle-adornment-matcher
3573 (rst-font-lock-handle-adornment-pre-match-form
3574 (match-string-no-properties 1) (match-end 1))
3576 (1 (cdr (assoc nil rst-adornment-faces-alist
)) append t
)
3577 (2 (cdr (assoc rst-font-lock-adornment-level
3578 rst-adornment-faces-alist
)) append t
)
3579 (3 (cdr (assoc nil rst-adornment-faces-alist
)) append t
)))
3581 ;; FIXME: FACESPEC could be used instead of ordinary faces to set
3582 ;; properties on comments and literal blocks so they are *not*
3583 ;; inline fontified. See (elisp)Search-based Fontification.
3585 ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el`
3586 ;; and other V24 modes. May make `font-lock-extend-region`
3590 ;; This is multiline.
3591 (,(rst-re 'lin-beg
'cmt-sta-1
)
3592 (1 rst-comment-face
)
3593 (rst-font-lock-find-unindented-line-match
3594 (rst-font-lock-find-unindented-line-limit (match-end 1))
3596 (0 rst-comment-face append
)))
3597 (,(rst-re 'lin-beg
'(:grp exm-tag
) '(:grp hws-tag
) "$")
3598 (1 rst-comment-face
)
3599 (2 rst-comment-face
)
3600 (rst-font-lock-find-unindented-line-match
3601 (rst-font-lock-find-unindented-line-limit 'next
)
3603 (0 rst-comment-face append
)))
3605 ;; FIXME: This is not rendered as comment::
3606 ;; .. .. list-table::
3610 ;; FIXME: This is rendered wrong::
3614 ;; ----|> KKKKK <|----
3616 ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|-
3619 ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB
3621 ;; Indentation needs to be taken from the line with the ``::`` and not from
3622 ;; the first content line.
3624 ;; `Indented Literal Blocks`_
3625 ;; This is multiline.
3626 (,(rst-re 'lin-beg
'lit-sta-2
)
3628 (rst-font-lock-find-unindented-line-match
3629 (rst-font-lock-find-unindented-line-limit t
)
3631 (0 rst-literal-face append
)))
3633 ;; FIXME: `Quoted Literal Blocks`_ missing.
3634 ;; This is multiline.
3636 ;; `Doctest Blocks`_
3637 ;; FIXME: This is wrong according to the specification:
3639 ;; Doctest blocks are text blocks which begin with ">>> ", the Python
3640 ;; interactive interpreter main prompt, and end with a blank line.
3641 ;; Doctest blocks are treated as a special case of literal blocks,
3642 ;; without requiring the literal block syntax. If both are present, the
3643 ;; literal block syntax takes priority over Doctest block syntax:
3645 ;; This is an ordinary paragraph.
3647 ;; >>> print 'this is a Doctest block'
3648 ;; this is a Doctest block
3650 ;; The following is a literal block::
3652 ;; >>> This is not recognized as a doctest block by
3653 ;; reStructuredText. It *will* be recognized by the doctest
3656 ;; Indentation is not required for doctest blocks.
3657 (,(rst-re 'lin-beg
'(:grp
(:alt
">>>" ell-tag
)) '(:grp
".+"))
3659 (2 rst-literal-face
))
3661 "Keywords to highlight in rst mode.")
3663 (defvar font-lock-beg
)
3664 (defvar font-lock-end
)
3666 (defun rst-font-lock-extend-region ()
3667 "Extend the font-lock region if it might be in a multi-line construct.
3668 Return non-nil if so. Font-lock region is from `font-lock-beg'
3669 to `font-lock-end'."
3670 (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end
)))
3672 (setq font-lock-beg
(car r
))
3673 (setq font-lock-end
(cdr r
))
3676 (defun rst-font-lock-extend-region-internal (beg end
)
3677 "Check the region BEG / END for being in the middle of a multi-line construct.
3678 Return nil if not or a cons with new values for BEG / END"
3679 (let ((nbeg (rst-font-lock-extend-region-extend beg -
1))
3680 (nend (rst-font-lock-extend-region-extend end
1)))
3682 (cons (or nbeg beg
) (or nend end
)))))
3684 (defun rst-forward-line (&optional n
)
3685 "Like `forward-line' but always end up in column 0 and return accordingly.
3686 Move N lines forward just as `forward-line'."
3687 (let ((moved (forward-line n
)))
3691 (- moved
(rst-signum n
)))))
3693 ;; FIXME: If a single line is made a section header by `rst-adjust' the header
3694 ;; is not always fontified immediately.
3695 (defun rst-font-lock-extend-region-extend (pt dir
)
3696 "Extend the region starting at point PT and extending in direction DIR.
3697 Return extended point or nil if not moved."
3698 ;; There are many potential multiline constructs but there are two groups
3699 ;; which are really relevant. The first group consists of
3701 ;; * comment lines without leading explicit markup tag and
3703 ;; * literal blocks following "::"
3705 ;; which are both indented. Thus indentation is the first thing recognized
3706 ;; here. The second criteria is an explicit markup tag which may be a comment
3707 ;; or a double colon at the end of a line.
3709 ;; The second group consists of the adornment cases.
3710 (if (not (get-text-property pt
'font-lock-multiline
))
3711 ;; Move only if we don't start inside a multiline construct already.
3713 (let (;; Non-empty non-indented line, explicit markup tag or literal
3715 (stop-re (rst-re '(:alt
"[^ \t\n]"
3716 (:seq hws-tag exm-tag
)
3717 (:seq
".*" dcl-tag lin-end
)))))
3718 ;; The comments below are for dir == -1 / dir == 1.
3722 (while (and (not (looking-at stop-re
))
3723 (zerop (rst-forward-line dir
)))) ; try previous / next
3724 ; line if it exists.
3725 (if (looking-at (rst-re 'ado-beg-2-1
)) ; may be an underline /
3727 (if (zerop (rst-forward-line dir
))
3728 (if (looking-at (rst-re 'ttl-beg
)) ; title found, i.e.
3729 ; underline / overline
3731 (if (zerop (rst-forward-line dir
))
3733 (looking-at (rst-re 'ado-beg-2-1
))) ; no
3736 (rst-forward-line (- dir
)))) ; step back to title
3738 (if (< dir
0) ; keep downward adornment.
3739 (rst-forward-line (- dir
))))) ; step back to adornment.
3740 (if (looking-at (rst-re 'ttl-beg
)) ; may be a title.
3741 (if (zerop (rst-forward-line dir
))
3743 (looking-at (rst-re 'ado-beg-2-1
))) ; no overline /
3745 (rst-forward-line (- dir
)))))) ; step back to line.
3746 (if (not (= (point) pt
))
3749 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3752 (defun rst-forward-indented-block (&optional column limit
)
3753 "Move forward across one indented block.
3754 Find the next non-empty line which is not indented at least to COLUMN (defaults
3755 to the column of the point). Moves point to first character of this line or the
3756 first empty line immediately before it and returns that position. If there is
3757 no such line before LIMIT (defaults to the end of the buffer) returns nil and
3758 point is not moved."
3760 (let ((clm (or column
(current-column)))
3764 (setq limit
(point-max)))
3766 (while (and (not fnd
) (< (point) limit
))
3768 (when (< (point) limit
)
3770 (if (looking-at (rst-re 'lin-end
))
3771 (setq cand
(or cand beg
)) ; An empty line is a candidate.
3772 (move-to-column clm
)
3773 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3774 ;; useful way - though it is not clear what this should mean
3777 (rst-re 'linemp-tag
)
3778 (buffer-substring-no-properties beg
(point)))
3779 (setq cand nil
) ; An indented line resets a candidate.
3780 (setq fnd
(or cand beg
)))))))
3781 (goto-char (or fnd start
))
3784 (defvar rst-font-lock-find-unindented-line-begin nil
3785 "Beginning of the match if `rst-font-lock-find-unindented-line-end'.")
3787 (defvar rst-font-lock-find-unindented-line-end nil
3788 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
3789 Also used as a trigger for
3790 `rst-font-lock-find-unindented-line-match'.")
3792 (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
3793 "Find the next unindented line relative to indentation at IND-PNT.
3794 Return this point, the end of the buffer or nil if nothing found.
3795 If IND-PNT is `next' take the indentation from the next line if
3796 this is not empty and indented more than the current one. If
3797 IND-PNT is non-nil but not a number take the indentation from the
3798 next non-empty line if this is indented more than the current
3800 (setq rst-font-lock-find-unindented-line-begin ind-pnt
)
3801 (setq rst-font-lock-find-unindented-line-end
3803 (when (not (numberp ind-pnt
))
3804 ;; Find indentation point in next line if any.
3806 ;; FIXME: Should be refactored to two different functions
3807 ;; giving their result to this function, may be
3808 ;; integrated in caller.
3810 (let ((cur-ind (current-indentation)))
3811 (if (eq ind-pnt
'next
)
3812 (when (and (zerop (forward-line 1))
3813 (< (point) (point-max)))
3815 (setq rst-font-lock-find-unindented-line-begin
3817 (when (and (not (looking-at (rst-re 'lin-end
)))
3818 (> (current-indentation) cur-ind
))
3819 ;; Use end of indentation if non-empty line.
3820 (looking-at (rst-re 'hws-tag
))
3822 ;; Skip until non-empty line or EOF.
3823 (while (and (zerop (forward-line 1))
3824 (< (point) (point-max))
3825 (looking-at (rst-re 'lin-end
))))
3826 (when (< (point) (point-max))
3828 (setq rst-font-lock-find-unindented-line-begin
3830 (when (> (current-indentation) cur-ind
)
3831 ;; Indentation bigger than line of departure.
3832 (looking-at (rst-re 'hws-tag
))
3833 (match-end 0))))))))
3836 (or (rst-forward-indented-block nil
(point-max))
3839 (defun rst-font-lock-find-unindented-line-match (limit)
3840 "Set the match found earlier if match were found.
3841 Match has been found by
3842 `rst-font-lock-find-unindented-line-limit' the first time called
3843 or no match is found. Return non-nil if match was found. LIMIT
3844 is not used but mandated by the caller."
3845 (when rst-font-lock-find-unindented-line-end
3847 (list rst-font-lock-find-unindented-line-begin
3848 rst-font-lock-find-unindented-line-end
))
3849 (put-text-property rst-font-lock-find-unindented-line-begin
3850 rst-font-lock-find-unindented-line-end
3851 'font-lock-multiline t
)
3852 ;; Make sure this is called only once.
3853 (setq rst-font-lock-find-unindented-line-end nil
)
3856 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3859 (defvar rst-font-lock-adornment-level nil
3860 "Storage for `rst-font-lock-handle-adornment-matcher'.
3861 Either section level of the current adornment or t for a transition.")
3863 (defun rst-adornment-level (key)
3864 "Return section level for adornment KEY.
3865 KEY is the first element of the return list of
3866 `rst-classify-adornment'. If KEY is not a cons return it. If KEY is found
3867 in the hierarchy return its level. Otherwise return a level one
3868 beyond the existing hierarchy."
3869 (if (not (consp key
))
3871 (let* ((hier (rst-get-hierarchy))
3874 (1+ (or (lexical-let ((char char
)
3876 (hier hier
)) ; Create closure.
3877 (rst-position-if (lambda (elt)
3878 (and (equal (car elt
) char
)
3879 (equal (cadr elt
) style
))) hier
))
3882 (defvar rst-font-lock-adornment-match nil
3883 "Storage for match for current adornment.
3884 Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used
3885 as a trigger for `rst-font-lock-handle-adornment-matcher'.")
3887 (defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end
)
3888 "Determine limit for adornments.
3889 Determine all things necessary for font-locking section titles
3890 and transitions and put the result to
3891 `rst-font-lock-adornment-match' and
3892 `rst-font-lock-adornment-level'. ADO is the complete adornment
3893 matched. ADO-END is the point where ADO ends. Return the point
3894 where the whole adorned construct ends.
3896 Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'."
3897 (let ((ado-data (rst-classify-adornment ado ado-end
)))
3899 (setq rst-font-lock-adornment-level nil
3900 rst-font-lock-adornment-match nil
)
3901 (setq rst-font-lock-adornment-level
3902 (rst-adornment-level (car ado-data
)))
3903 (setq rst-font-lock-adornment-match
(cdr ado-data
))
3904 (goto-char (nth 1 ado-data
)) ; Beginning of construct.
3905 (nth 2 ado-data
)))) ; End of construct.
3907 (defun rst-font-lock-handle-adornment-matcher (limit)
3908 "Set the match found earlier if match were found.
3909 Match has been found by
3910 `rst-font-lock-handle-adornment-pre-match-form' the first time
3911 called or no match is found. Return non-nil if match was found.
3913 Called as a MATCHER in the sense of `font-lock-keywords'.
3914 LIMIT is not used but mandated by the caller."
3915 (let ((match rst-font-lock-adornment-match
))
3916 ;; May run only once - enforce this.
3917 (setq rst-font-lock-adornment-match nil
)
3919 (set-match-data match
)
3920 (goto-char (match-end 0))
3921 (put-text-property (match-beginning 0) (match-end 0)
3922 'font-lock-multiline t
)
3926 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3929 (defgroup rst-compile nil
3930 "Settings for support of conversion of reStructuredText
3931 document with \\[rst-compile]."
3935 (defcustom rst-compile-toolsets
3936 `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
3938 (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
3940 (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
3943 (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
3946 (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
3948 (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
3950 (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
3952 "Table describing the command to use for each tool-set.
3953 An association list of the tool-set to a list of the (command to use,
3954 extension of produced filename, options to the tool (nil or a
3955 string)) to be used for converting the document."
3956 ;; FIXME: These are not options but symbols which may be referenced by
3957 ;; `rst-compile-*-toolset` below.
3958 :type
'(alist :options
(html latex newlatex pseudoxml xml pdf s5
)
3960 :value-type
(list :tag
"Specification"
3961 (file :tag
"Command")
3962 (string :tag
"File extension")
3963 (choice :tag
"Command options"
3964 (const :tag
"No options" nil
)
3965 (string :tag
"Options"))))
3967 :package-version
"1.2.0")
3969 ;; FIXME: Must be `defcustom`.
3970 (defvar rst-compile-primary-toolset
'html
3971 "The default tool-set for `rst-compile'.")
3973 ;; FIXME: Must be `defcustom`.
3974 (defvar rst-compile-secondary-toolset
'latex
3975 "The default tool-set for `rst-compile' with a prefix argument.")
3977 (defun rst-compile-find-conf ()
3978 "Look for the configuration file in the parents of the current path."
3980 (let ((file-name "docutils.conf")
3981 (buffer-file (buffer-file-name)))
3982 ;; Move up in the dir hierarchy till we find a change log file.
3983 (let* ((dir (file-name-directory buffer-file
))
3985 (while (and (or (not (string= dir prevdir
))
3988 (not (file-exists-p (concat dir file-name
))))
3989 ;; Move up to the parent dir and try again.
3991 (setq dir
(expand-file-name (file-name-directory
3992 (directory-file-name
3993 (file-name-directory dir
)))))
3995 (or (and dir
(concat dir file-name
)) nil
)
4001 (defun rst-compile (&optional use-alt
)
4002 "Compile command to convert reST document into some output file.
4003 Attempts to find configuration file, if it can, overrides the
4004 options. There are two commands to choose from, with USE-ALT,
4005 select the alternative tool-set."
4007 ;; Note: maybe we want to check if there is a Makefile too and not do anything
4008 ;; if that is the case. I dunno.
4009 (let* ((toolset (cdr (assq (if use-alt
4010 rst-compile-secondary-toolset
4011 rst-compile-primary-toolset
)
4012 rst-compile-toolsets
)))
4013 (command (car toolset
))
4014 (extension (cadr toolset
))
4015 (options (caddr toolset
))
4016 (conffile (rst-compile-find-conf))
4017 (bufname (file-name-nondirectory buffer-file-name
))
4018 (outname (file-name-sans-extension bufname
)))
4020 ;; Set compile-command before invocation of compile.
4021 (set (make-local-variable 'compile-command
)
4022 (mapconcat 'identity
4026 (concat "--config=" (shell-quote-argument conffile
))
4028 (shell-quote-argument bufname
)
4029 (shell-quote-argument (concat outname extension
)))
4032 ;; Invoke the compile command.
4033 (if (or compilation-read-command use-alt
)
4034 (call-interactively 'compile
)
4035 (compile compile-command
))
4038 (defun rst-compile-alt-toolset ()
4039 "Compile command with the alternative tool-set."
4043 (defun rst-compile-pseudo-region ()
4044 "Show pseudo-XML rendering.
4045 Rendering is done of the current active region, or of the entire
4046 buffer, if the region is not selected."
4047 ;; FIXME: The region should be given interactively.
4049 (with-output-to-temp-buffer "*pseudoxml*"
4050 (shell-command-on-region
4051 (if mark-active
(region-beginning) (point-min))
4052 (if mark-active
(region-end) (point-max))
4053 (cadr (assq 'pseudoxml rst-compile-toolsets
))
4056 ;; FIXME: Should be `defcustom`.
4057 (defvar rst-pdf-program
"xpdf"
4058 "Program used to preview PDF files.")
4060 (defun rst-compile-pdf-preview ()
4061 "Convert the document to a PDF file and launch a preview program."
4063 (let* ((tmp-filename (make-temp-file "rst_el" nil
".pdf"))
4064 (command (format "%s %s %s && %s %s ; rm %s"
4065 (cadr (assq 'pdf rst-compile-toolsets
))
4066 buffer-file-name tmp-filename
4067 rst-pdf-program tmp-filename tmp-filename
)))
4068 (start-process-shell-command "rst-pdf-preview" nil command
)
4069 ;; Note: you could also use (compile command) to view the compilation
4073 ;; FIXME: Should be `defcustom` or use something like `browse-url`.
4074 (defvar rst-slides-program
"firefox"
4075 "Program used to preview S5 slides.")
4077 (defun rst-compile-slides-preview ()
4078 "Convert the document to an S5 slide presentation and launch a preview program."
4080 (let* ((tmp-filename (make-temp-file "rst_el" nil
".html"))
4081 (command (format "%s %s %s && %s %s ; rm %s"
4082 (cadr (assq 's5 rst-compile-toolsets
))
4083 buffer-file-name tmp-filename
4084 rst-slides-program tmp-filename tmp-filename
)))
4085 (start-process-shell-command "rst-slides-preview" nil command
)
4086 ;; Note: you could also use (compile command) to view the compilation
4091 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4092 ;; Generic text functions that are more convenient than the defaults.
4094 ;; FIXME: Unbound command - should be bound or removed.
4095 (defun rst-replace-lines (fromchar tochar
)
4096 "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR."
4098 cSearch for flush-left lines of char:
4099 cand replace with char: ")
4101 (let ((searchre (rst-re "^" fromchar
"+\\( *\\)$"))
4103 (while (search-forward-regexp searchre nil t
)
4104 (setq found
(1+ found
))
4105 (goto-char (match-beginning 1))
4106 (let ((width (current-column)))
4107 (rst-delete-entire-line)
4108 (insert-char tochar width
)))
4109 (message (format "%d lines replaced." found
)))))
4111 ;; FIXME: Unbound command - should be bound or removed.
4112 (defun rst-join-paragraph ()
4113 "Join lines in current paragraph into one line, removing end-of-lines."
4115 (let ((fill-column 65000)) ; Some big number.
4116 (call-interactively 'fill-paragraph
)))
4118 ;; FIXME: Unbound command - should be bound or removed.
4119 (defun rst-force-fill-paragraph ()
4120 "Fill paragraph at point, first joining the paragraph's lines into one.
4121 This is useful for filling list item paragraphs."
4123 (rst-join-paragraph)
4124 (fill-paragraph nil
))
4127 ;; FIXME: Unbound command - should be bound or removed.
4128 ;; Generic character repeater function.
4129 ;; For sections, better to use the specialized function above, but this can
4130 ;; be useful for creating separators.
4131 (defun rst-repeat-last-character (use-next)
4132 "Fill the current line using the last character on the current line.
4133 Fill up to the length of the preceding line or up to
4134 `fill-column' if preceding line is empty.
4136 If USE-NEXT, use the next line rather than the preceding line.
4138 If the current line is longer than the desired length, shave the characters off
4139 the current line to fit the desired length.
4141 As an added convenience, if the command is repeated immediately, the alternative
4142 column is used (fill-column vs. end of previous/next line)."
4144 (let* ((curcol (current-column))
4145 (curline (+ (count-lines (point-min) (point))
4146 (if (zerop curcol
) 1 0)))
4147 (lbp (line-beginning-position 0))
4148 (prevcol (if (and (= curline
1) (not use-next
))
4151 (forward-line (if use-next
1 -
1))
4153 (skip-chars-backward " \t" lbp
)
4154 (let ((cc (current-column)))
4155 (if (zerop cc
) fill-column cc
)))))
4157 (cond ((equal last-command
'rst-repeat-last-character
)
4158 (if (= curcol fill-column
) prevcol fill-column
))
4160 (if (zerop prevcol
) fill-column prevcol
)))
4163 (if (> (current-column) rightmost-column
)
4164 ;; Shave characters off the end.
4165 (delete-region (- (point)
4166 (- (current-column) rightmost-column
))
4168 ;; Fill with last characters.
4169 (insert-char (preceding-char)
4170 (- rightmost-column
(current-column))))
4174 (defun rst-portable-mark-active-p ()
4175 "Return non-nil if the mark is active.
4176 This is a portable function."
4178 ((fboundp 'region-active-p
) (region-active-p))
4179 ((boundp 'transient-mark-mode
) (and transient-mark-mode mark-active
))
4184 ;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex
4185 ;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc
4186 ;; LocalWords: XML PNT propertized
4189 ;; sentence-end-double-space: t
4194 ;;; rst.el ends here