Replace version 24.2 with 24.3 where appropriate (hopefully)
[bpt/emacs.git] / lisp / textmodes / rst.el
1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
2
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
4
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>
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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:
33 ;;
34 ;; - Functions to automatically adjust and cycle the section underline
35 ;; adornments;
36 ;; - A mode that displays the table of contents and allows you to jump anywhere
37 ;; from it;
38 ;; - Functions to insert and automatically update a TOC in your source
39 ;; document;
40 ;; - Function to insert list, processing item bullets and enumerations
41 ;; automatically;
42 ;; - Font-lock highlighting of most reStructuredText structures;
43 ;; - Indentation and filling according to reStructuredText syntax;
44 ;; - Cursor movement according to reStructuredText syntax;
45 ;; - Some other convenience functions.
46 ;;
47 ;; See the accompanying document in the docutils documentation about
48 ;; the contents of this package and how to use it.
49 ;;
50 ;; For more information about reStructuredText, see
51 ;; http://docutils.sourceforge.net/rst.html
52 ;;
53 ;; For full details on how to use the contents of this file, see
54 ;; http://docutils.sourceforge.net/docs/user/emacs.html
55 ;;
56 ;;
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.
60 ;;
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::
63 ;;
64 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
65 ;;
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::
68 ;;
69 ;; (setq font-lock-global-modes '(not rst-mode ...))
70 ;;
71 ;;
72 ;;
73 ;; Customization is done by customizable variables contained in customization
74 ;; group "rst" and subgroups. Group "rst" is contained in the "wp" group.
75 ;;
76
77 ;;; DOWNLOAD
78
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
81
82 ;;; INSTALLATION
83
84 ;; Add the following lines to your `.emacs' file:
85 ;;
86 ;; (require 'rst)
87 ;;
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::
92 ;;
93 ;; .. -*- mode: rst -*-
94 ;;
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:
97 ;;
98 ;; (setq auto-mode-alist
99 ;; (append '(("\\.txt\\'" . rst-mode)
100 ;; ("\\.rst\\'" . rst-mode)
101 ;; ("\\.rest\\'" . rst-mode)) auto-mode-alist))
102 ;;
103
104 ;;; Code:
105
106 ;; FIXME: Add proper ";;;###autoload" comments.
107
108 ;; FIXME: When 24.1 is common place remove use of `lexical-let' and put "-*-
109 ;; lexical-binding: t -*-" in the first line.
110
111 ;; Only use of macros is allowed - may be replaced by `cl-lib' some time.
112 (eval-when-compile
113 (require 'cl))
114
115 ;; Redefine some functions from `cl.el' in a proper namespace until they may be
116 ;; used from there.
117
118 (defun rst-signum (x)
119 "Return 1 if X is positive, -1 if negative, 0 if zero."
120 (cond
121 ((> x 0) 1)
122 ((< x 0) -1)
123 (t 0)))
124
125 (defun rst-some (seq &optional pred)
126 "Return non-nil if any element of SEQ yields non-nil when PRED is applied.
127 Apply PRED to each element of list SEQ until the first non-nil
128 result is yielded and return this result. PRED defaults to
129 `identity'."
130 (unless pred
131 (setq pred 'identity))
132 (catch 'rst-some
133 (dolist (elem seq)
134 (let ((r (funcall pred elem)))
135 (when r
136 (throw 'rst-some r))))))
137
138 (defun rst-position-if (pred seq)
139 "Return position of first element satisfying PRED in list SEQ or nil."
140 (catch 'rst-position-if
141 (let ((i 0))
142 (dolist (elem seq)
143 (when (funcall pred elem)
144 (throw 'rst-position-if i))
145 (incf i)))))
146
147 (defun rst-position (elem seq)
148 "Return position of ELEM in list SEQ or nil.
149 Comparison done with `equal'."
150 ;; Create a closure containing `elem' so the `lambda' always sees our
151 ;; parameter instead of an `elem' which may be in dynamic scope at the time
152 ;; of execution of the `lambda'.
153 (lexical-let ((elem elem))
154 (rst-position-if (function (lambda (e)
155 (equal elem e)))
156 seq)))
157
158 ;; FIXME: Embed complicated `defconst's in `eval-when-compile'.
159
160 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
161 ;; Versions
162
163 (defun rst-extract-version (delim-re head-re re tail-re var &optional default)
164 "Extract the version from a variable according to the given regexes.
165 Return the version after regex DELIM-RE and HEAD-RE matching RE
166 and before TAIL-RE and DELIM-RE in VAR or DEFAULT for no match."
167 (if (string-match
168 (concat delim-re head-re "\\(" re "\\)" tail-re delim-re)
169 var)
170 (match-string 1 var)
171 default))
172
173 ;; Use CVSHeader to really get information from CVS and not other version
174 ;; control systems.
175 (defconst rst-cvs-header
176 "$CVSHeader: sm/rst_el/rst.el,v 1.301 2012-07-30 19:29:46 stefan Exp $")
177 (defconst rst-cvs-rev
178 (rst-extract-version "\\$" "CVSHeader: \\S + " "[0-9]+\\(?:\\.[0-9]+\\)+"
179 " .*" rst-cvs-header "0.0")
180 "The CVS revision of this file. CVS revision is the development revision.")
181 (defconst rst-cvs-timestamp
182 (rst-extract-version "\\$" "CVSHeader: \\S + \\S + "
183 "[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+" " .*"
184 rst-cvs-header "1970-01-01 00:00:00")
185 "The CVS time stamp of this file.")
186
187 ;; Use LastChanged... to really get information from SVN.
188 (defconst rst-svn-rev
189 (rst-extract-version "\\$" "LastChangedRevision: " "[0-9]+" " "
190 "$LastChangedRevision: 7490 $")
191 "The SVN revision of this file.
192 SVN revision is the upstream (docutils) revision.")
193 (defconst rst-svn-timestamp
194 (rst-extract-version "\\$" "LastChangedDate: " ".+?+" " "
195 "$LastChangedDate: 2012-07-30 21:29:33 +0200 (Mon, 30 Jul 2012) $")
196 "The SVN time stamp of this file.")
197
198 ;; Maintained by the release process.
199 (defconst rst-official-version
200 (rst-extract-version "%" "OfficialVersion: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
201 "%OfficialVersion: 1.3.1 %")
202 "Official version of the package.")
203 (defconst rst-official-cvs-rev
204 (rst-extract-version "[%$]" "Revision: " "[0-9]+\\(?:\\.[0-9]+\\)+" " "
205 "%Revision: 1.301 %")
206 "CVS revision of this file in the official version.")
207
208 (defconst rst-version
209 (if (equal rst-official-cvs-rev rst-cvs-rev)
210 rst-official-version
211 (format "%s (development %s [%s])" rst-official-version
212 rst-cvs-rev rst-cvs-timestamp))
213 "The version string.
214 Starts with the current official version. For developer versions
215 in parentheses follows the development revision and the time stamp.")
216
217 (defconst rst-package-emacs-version-alist
218 '(("1.0.0" . "24.3")
219 ("1.1.0" . "24.3")
220 ("1.2.0" . "24.3")
221 ("1.2.1" . "24.3")
222 ("1.3.0" . "24.3")
223 ("1.3.1" . "24.3")
224 ))
225
226 (unless (assoc rst-official-version rst-package-emacs-version-alist)
227 (error "Version %s not listed in `rst-package-emacs-version-alist'"
228 rst-version))
229
230 (add-to-list 'customize-package-emacs-version-alist
231 (cons 'ReST rst-package-emacs-version-alist))
232
233 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
234 ;; Initialize customization
235
236 \f
237 (defgroup rst nil "Support for reStructuredText documents."
238 :group 'wp
239 :version "23.1"
240 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
241
242 \f
243 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
244 ;; Facilities for regular expressions used everywhere
245
246 ;; The trailing numbers in the names give the number of referenceable regex
247 ;; groups contained in the regex.
248
249 ;; Used to be customizable but really is not customizable but fixed by the reST
250 ;; syntax.
251 (defconst rst-bullets
252 ;; Sorted so they can form a character class when concatenated.
253 '(?- ?* ?+ ?\u2022 ?\u2023 ?\u2043)
254 "List of all possible bullet characters for bulleted lists.")
255
256 (defconst rst-uri-schemes
257 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https" "imap"
258 "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero" "rtsp"
259 "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
260 "Supported URI schemes.")
261
262 (defconst rst-adornment-chars
263 ;; Sorted so they can form a character class when concatenated.
264 '(?\]
265 ?! ?\" ?# ?$ ?% ?& ?' ?\( ?\) ?* ?+ ?, ?. ?/ ?: ?\; ?< ?= ?> ?? ?@ ?\[ ?\\
266 ?^ ?_ ?` ?{ ?| ?} ?~
267 ?-)
268 "Characters which may be used in adornments for sections and transitions.")
269
270 (defconst rst-max-inline-length
271 1000
272 "Maximum length of inline markup to recognize.")
273
274 (defconst rst-re-alist-def
275 ;; `*-beg' matches * at the beginning of a line.
276 ;; `*-end' matches * at the end of a line.
277 ;; `*-prt' matches a part of *.
278 ;; `*-tag' matches *.
279 ;; `*-sta' matches the start of * which may be followed by respective content.
280 ;; `*-pfx' matches the delimiter left of *.
281 ;; `*-sfx' matches the delimiter right of *.
282 ;; `*-hlp' helper for *.
283 ;;
284 ;; A trailing number says how many referenceable groups are contained.
285 `(
286
287 ;; Horizontal white space (`hws')
288 (hws-prt "[\t ]")
289 (hws-tag hws-prt "*") ; Optional sequence of horizontal white space.
290 (hws-sta hws-prt "+") ; Mandatory sequence of horizontal white space.
291
292 ;; Lines (`lin')
293 (lin-beg "^" hws-tag) ; Beginning of a possibly indented line.
294 (lin-end hws-tag "$") ; End of a line with optional trailing white space.
295 (linemp-tag "^" hws-tag "$") ; Empty line with optional white space.
296
297 ;; Various tags and parts
298 (ell-tag "\\.\\.\\.") ; Ellipsis
299 (bul-tag ,(concat "[" rst-bullets "]")) ; A bullet.
300 (ltr-tag "[a-zA-Z]") ; A letter enumerator tag.
301 (num-prt "[0-9]") ; A number enumerator part.
302 (num-tag num-prt "+") ; A number enumerator tag.
303 (rom-prt "[IVXLCDMivxlcdm]") ; A roman enumerator part.
304 (rom-tag rom-prt "+") ; A roman enumerator tag.
305 (aut-tag "#") ; An automatic enumerator tag.
306 (dcl-tag "::") ; Double colon.
307
308 ;; Block lead in (`bli')
309 (bli-sfx (:alt hws-sta "$")) ; Suffix of a block lead-in with *optional*
310 ; immediate content.
311
312 ;; Various starts
313 (bul-sta bul-tag bli-sfx) ; Start of a bulleted item.
314
315 ;; Explicit markup tag (`exm')
316 (exm-tag "\\.\\.")
317 (exm-sta exm-tag hws-sta)
318 (exm-beg lin-beg exm-sta)
319
320 ;; Counters in enumerations (`cnt')
321 (cntany-tag (:alt ltr-tag num-tag rom-tag aut-tag)) ; An arbitrary counter.
322 (cntexp-tag (:alt ltr-tag num-tag rom-tag)) ; An arbitrary explicit counter.
323
324 ;; Enumerator (`enm')
325 (enmany-tag (:alt
326 (:seq cntany-tag "\\.")
327 (:seq "(?" cntany-tag ")"))) ; An arbitrary enumerator.
328 (enmexp-tag (:alt
329 (:seq cntexp-tag "\\.")
330 (:seq "(?" cntexp-tag ")"))) ; An arbitrary explicit
331 ; enumerator.
332 (enmaut-tag (:alt
333 (:seq aut-tag "\\.")
334 (:seq "(?" aut-tag ")"))) ; An automatic enumerator.
335 (enmany-sta enmany-tag bli-sfx) ; An arbitrary enumerator start.
336 (enmexp-sta enmexp-tag bli-sfx) ; An arbitrary explicit enumerator start.
337 (enmexp-beg lin-beg enmexp-sta) ; An arbitrary explicit enumerator start
338 ; at the beginning of a line.
339
340 ;; Items may be enumerated or bulleted (`itm')
341 (itmany-tag (:alt enmany-tag bul-tag)) ; An arbitrary item tag.
342 (itmany-sta-1 (:grp itmany-tag) bli-sfx) ; An arbitrary item start, group
343 ; is the item tag.
344 (itmany-beg-1 lin-beg itmany-sta-1) ; An arbitrary item start at the
345 ; beginning of a line, group is the
346 ; item tag.
347
348 ;; Inline markup (`ilm')
349 (ilm-pfx (:alt "^" hws-prt "[-'\"([{<\u2018\u201c\u00ab\u2019/:]"))
350 (ilm-sfx (:alt "$" hws-prt "[]-'\")}>\u2019\u201d\u00bb/:.,;!?\\]"))
351
352 ;; Inline markup content (`ilc')
353 (ilcsgl-tag "\\S ") ; A single non-white character.
354 (ilcast-prt (:alt "[^*\\]" "\\\\.")) ; Part of non-asterisk content.
355 (ilcbkq-prt (:alt "[^`\\]" "\\\\.")) ; Part of non-backquote content.
356 (ilcbkqdef-prt (:alt "[^`\\\n]" "\\\\.")) ; Part of non-backquote
357 ; definition.
358 (ilcbar-prt (:alt "[^|\\]" "\\\\.")) ; Part of non-vertical-bar content.
359 (ilcbardef-prt (:alt "[^|\\\n]" "\\\\.")) ; Part of non-vertical-bar
360 ; definition.
361 (ilcast-sfx "[^\t *\\]") ; Suffix of non-asterisk content.
362 (ilcbkq-sfx "[^\t `\\]") ; Suffix of non-backquote content.
363 (ilcbar-sfx "[^\t |\\]") ; Suffix of non-vertical-bar content.
364 (ilcrep-hlp ,(format "\\{0,%d\\}" rst-max-inline-length)) ; Repeat count.
365 (ilcast-tag (:alt ilcsgl-tag
366 (:seq ilcsgl-tag
367 ilcast-prt ilcrep-hlp
368 ilcast-sfx))) ; Non-asterisk content.
369 (ilcbkq-tag (:alt ilcsgl-tag
370 (:seq ilcsgl-tag
371 ilcbkq-prt ilcrep-hlp
372 ilcbkq-sfx))) ; Non-backquote content.
373 (ilcbkqdef-tag (:alt ilcsgl-tag
374 (:seq ilcsgl-tag
375 ilcbkqdef-prt ilcrep-hlp
376 ilcbkq-sfx))) ; Non-backquote definition.
377 (ilcbar-tag (:alt ilcsgl-tag
378 (:seq ilcsgl-tag
379 ilcbar-prt ilcrep-hlp
380 ilcbar-sfx))) ; Non-vertical-bar content.
381 (ilcbardef-tag (:alt ilcsgl-tag
382 (:seq ilcsgl-tag
383 ilcbardef-prt ilcrep-hlp
384 ilcbar-sfx))) ; Non-vertical-bar definition.
385
386 ;; Fields (`fld')
387 (fldnam-prt (:alt "[^:\n]" "\\\\:")) ; Part of a field name.
388 (fldnam-tag fldnam-prt "+") ; A field name.
389 (fld-tag ":" fldnam-tag ":") ; A field marker.
390
391 ;; Options (`opt')
392 (optsta-tag (:alt "[-+/]" "--")) ; Start of an option.
393 (optnam-tag "\\sw" (:alt "-" "\\sw") "*") ; Name of an option.
394 (optarg-tag (:shy "[ =]\\S +")) ; Option argument.
395 (optsep-tag (:shy "," hws-prt)) ; Separator between options.
396 (opt-tag (:shy optsta-tag optnam-tag optarg-tag "?")) ; A complete option.
397
398 ;; Footnotes and citations (`fnc')
399 (fncnam-prt "[^\]\n]") ; Part of a footnote or citation name.
400 (fncnam-tag fncnam-prt "+") ; A footnote or citation name.
401 (fnc-tag "\\[" fncnam-tag "]") ; A complete footnote or citation tag.
402 (fncdef-tag-2 (:grp exm-sta)
403 (:grp fnc-tag)) ; A complete footnote or citation definition
404 ; tag. First group is the explicit markup
405 ; start, second group is the footnote /
406 ; citation tag.
407 (fnc-sta-2 fncdef-tag-2 bli-sfx) ; Start of a footnote or citation
408 ; definition. First group is the explicit
409 ; markup start, second group is the
410 ; footnote / citation tag.
411
412 ;; Substitutions (`sub')
413 (sub-tag "|" ilcbar-tag "|") ; A complete substitution tag.
414 (subdef-tag "|" ilcbardef-tag "|") ; A complete substitution definition
415 ; tag.
416
417 ;; Symbol (`sym')
418 (sym-prt "[-+.:_]") ; Non-word part of a symbol.
419 (sym-tag (:shy "\\sw+" (:shy sym-prt "\\sw+") "*"))
420
421 ;; URIs (`uri')
422 (uri-tag (:alt ,@rst-uri-schemes))
423
424 ;; Adornment (`ado')
425 (ado-prt "[" ,(concat rst-adornment-chars) "]")
426 (adorep3-hlp "\\{3,\\}") ; There must be at least 3 characters because
427 ; otherwise explicit markup start would be
428 ; recognized.
429 (adorep2-hlp "\\{2,\\}") ; As `adorep3-hlp' but when the first of three
430 ; characters is matched differently.
431 (ado-tag-1-1 (:grp ado-prt)
432 "\\1" adorep2-hlp) ; A complete adornment, group is the first
433 ; adornment character and MUST be the FIRST
434 ; group in the whole expression.
435 (ado-tag-1-2 (:grp ado-prt)
436 "\\2" adorep2-hlp) ; A complete adornment, group is the first
437 ; adornment character and MUST be the
438 ; SECOND group in the whole expression.
439 (ado-beg-2-1 "^" (:grp ado-tag-1-2)
440 lin-end) ; A complete adornment line; first group is the whole
441 ; adornment and MUST be the FIRST group in the whole
442 ; expression; second group is the first adornment
443 ; character.
444
445 ;; Titles (`ttl')
446 (ttl-tag "\\S *\\w\\S *") ; A title text.
447 (ttl-beg lin-beg ttl-tag) ; A title text at the beginning of a line.
448
449 ;; Directives and substitution definitions (`dir')
450 (dir-tag-3 (:grp exm-sta)
451 (:grp (:shy subdef-tag hws-sta) "?")
452 (:grp sym-tag dcl-tag)) ; A directive or substitution definition
453 ; tag. First group is explicit markup
454 ; start, second group is a possibly
455 ; empty substitution tag, third group is
456 ; the directive tag including the double
457 ; colon.
458 (dir-sta-3 dir-tag-3 bli-sfx) ; Start of a directive or substitution
459 ; definition. Groups are as in dir-tag-3.
460
461 ;; Literal block (`lit')
462 (lit-sta-2 (:grp (:alt "[^.\n]" "\\.[^.\n]") ".*") "?"
463 (:grp dcl-tag) "$") ; Start of a literal block. First group is
464 ; any text before the double colon tag which
465 ; may not exist, second group is the double
466 ; colon tag.
467
468 ;; Comments (`cmt')
469 (cmt-sta-1 (:grp exm-sta) "[^\[|_\n]"
470 (:alt "[^:\n]" (:seq ":" (:alt "[^:\n]" "$")))
471 "*$") ; Start of a comment block; first group is explicit markup
472 ; start.
473
474 ;; Paragraphs (`par')
475 (par-tag- (:alt itmany-tag fld-tag opt-tag fncdef-tag-2 dir-tag-3 exm-tag)
476 ) ; Tag at the beginning of a paragraph; there may be groups in
477 ; certain cases.
478 )
479 "Definition alist of relevant regexes.
480 Each entry consists of the symbol naming the regex and an
481 argument list for `rst-re'.")
482
483 (defvar rst-re-alist) ; Forward declare to use it in `rst-re'.
484
485 ;; FIXME: Use `sregex` or `rx` instead of re-inventing the wheel.
486 (defun rst-re (&rest args)
487 "Interpret ARGS as regular expressions and return a regex string.
488 Each element of ARGS may be one of the following:
489
490 A string which is inserted unchanged.
491
492 A character which is resolved to a quoted regex.
493
494 A symbol which is resolved to a string using `rst-re-alist-def'.
495
496 A list with a keyword in the car. Each element of the cdr of such
497 a list is recursively interpreted as ARGS. The results of this
498 interpretation are concatenated according to the keyword.
499
500 For the keyword `:seq' the results are simply concatenated.
501
502 For the keyword `:shy' the results are concatenated and
503 surrounded by a shy-group (\"\\(?:...\\)\").
504
505 For the keyword `:alt' the results form an alternative (\"\\|\")
506 which is shy-grouped (\"\\(?:...\\)\").
507
508 For the keyword `:grp' the results are concatenated and form a
509 referenceable group (\"\\(...\\)\").
510
511 After interpretation of ARGS the results are concatenated as for
512 `:seq'."
513 (apply 'concat
514 (mapcar
515 (lambda (re)
516 (cond
517 ((stringp re)
518 re)
519 ((symbolp re)
520 (cadr (assoc re rst-re-alist)))
521 ((characterp re)
522 (regexp-quote (char-to-string re)))
523 ((listp re)
524 (let ((nested
525 (mapcar (lambda (elt)
526 (rst-re elt))
527 (cdr re))))
528 (cond
529 ((eq (car re) :seq)
530 (mapconcat 'identity nested ""))
531 ((eq (car re) :shy)
532 (concat "\\(?:" (mapconcat 'identity nested "") "\\)"))
533 ((eq (car re) :grp)
534 (concat "\\(" (mapconcat 'identity nested "") "\\)"))
535 ((eq (car re) :alt)
536 (concat "\\(?:" (mapconcat 'identity nested "\\|") "\\)"))
537 (t
538 (error "Unknown list car: %s" (car re))))))
539 (t
540 (error "Unknown object type for building regex: %s" re))))
541 args)))
542
543 ;; FIXME: Remove circular dependency between `rst-re' and `rst-re-alist'.
544 (with-no-warnings ; Silence byte-compiler about this construction.
545 (defconst rst-re-alist
546 ;; Shadow global value we are just defining so we can construct it step by
547 ;; step.
548 (let (rst-re-alist)
549 (dolist (re rst-re-alist-def rst-re-alist)
550 (setq rst-re-alist
551 (nconc rst-re-alist
552 (list (list (car re) (apply 'rst-re (cdr re))))))))
553 "Alist mapping symbols from `rst-re-alist-def' to regex strings."))
554
555 \f
556 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
557 ;; Mode definition
558
559 (defun rst-define-key (keymap key def &rest deprecated)
560 "Bind like `define-key' but add deprecated key definitions.
561 KEYMAP, KEY, and DEF are as in `define-key'. DEPRECATED key
562 definitions should be in vector notation. These are defined as
563 well but give an additional message."
564 (define-key keymap key def)
565 (dolist (dep-key deprecated)
566 (define-key keymap dep-key
567 `(lambda ()
568 ,(format "Deprecated binding for %s, use \\[%s] instead." def def)
569 (interactive)
570 (call-interactively ',def)
571 (message "[Deprecated use of key %s; use key %s instead]"
572 (key-description (this-command-keys))
573 (key-description ,key))))))
574
575 ;; Key bindings.
576 (defvar rst-mode-map
577 (let ((map (make-sparse-keymap)))
578
579 ;; \C-c is the general keymap.
580 (rst-define-key map [?\C-c ?\C-h] 'describe-prefix-bindings)
581
582 ;;
583 ;; Section Adornments
584 ;;
585 ;; The adjustment function that adorns or rotates a section title.
586 (rst-define-key map [?\C-c ?\C-=] 'rst-adjust [?\C-c ?\C-a t])
587 (rst-define-key map [?\C-=] 'rst-adjust) ; Does not work on the Mac OSX and
588 ; on consoles.
589
590 ;; \C-c \C-a is the keymap for adornments.
591 (rst-define-key map [?\C-c ?\C-a ?\C-h] 'describe-prefix-bindings)
592 ;; Another binding which works with all types of input.
593 (rst-define-key map [?\C-c ?\C-a ?\C-a] 'rst-adjust)
594 ;; Display the hierarchy of adornments implied by the current document
595 ;; contents.
596 (rst-define-key map [?\C-c ?\C-a ?\C-d] 'rst-display-adornments-hierarchy)
597 ;; Homogenize the adornments in the document.
598 (rst-define-key map [?\C-c ?\C-a ?\C-s] 'rst-straighten-adornments
599 [?\C-c ?\C-s])
600
601 ;;
602 ;; Section Movement and Selection
603 ;;
604 ;; Mark the subsection where the cursor is.
605 (rst-define-key map [?\C-\M-h] 'rst-mark-section
606 ;; Same as mark-defun sgml-mark-current-element.
607 [?\C-c ?\C-m])
608 ;; Move backward/forward between section titles.
609 ;; FIXME: Also bind similar to outline mode.
610 (rst-define-key map [?\C-\M-a] 'rst-backward-section
611 ;; Same as beginning-of-defun.
612 [?\C-c ?\C-n])
613 (rst-define-key map [?\C-\M-e] 'rst-forward-section
614 ;; Same as end-of-defun.
615 [?\C-c ?\C-p])
616
617 ;;
618 ;; Operating on regions
619 ;;
620 ;; \C-c \C-r is the keymap for regions.
621 (rst-define-key map [?\C-c ?\C-r ?\C-h] 'describe-prefix-bindings)
622 ;; Makes region a line-block.
623 (rst-define-key map [?\C-c ?\C-r ?\C-l] 'rst-line-block-region
624 [?\C-c ?\C-d])
625 ;; Shift region left or right according to tabs.
626 (rst-define-key map [?\C-c ?\C-r tab] 'rst-shift-region
627 [?\C-c ?\C-r t] [?\C-c ?\C-l t])
628
629 ;;
630 ;; Operating on lists
631 ;;
632 ;; \C-c \C-l is the keymap for lists.
633 (rst-define-key map [?\C-c ?\C-l ?\C-h] 'describe-prefix-bindings)
634 ;; Makes paragraphs in region as a bullet list.
635 (rst-define-key map [?\C-c ?\C-l ?\C-b] 'rst-bullet-list-region
636 [?\C-c ?\C-b])
637 ;; Makes paragraphs in region as a enumeration.
638 (rst-define-key map [?\C-c ?\C-l ?\C-e] 'rst-enumerate-region
639 [?\C-c ?\C-e])
640 ;; Converts bullets to an enumeration.
641 (rst-define-key map [?\C-c ?\C-l ?\C-c] 'rst-convert-bullets-to-enumeration
642 [?\C-c ?\C-v])
643 ;; Make sure that all the bullets in the region are consistent.
644 (rst-define-key map [?\C-c ?\C-l ?\C-s] 'rst-straighten-bullets-region
645 [?\C-c ?\C-w])
646 ;; Insert a list item.
647 (rst-define-key map [?\C-c ?\C-l ?\C-i] 'rst-insert-list)
648
649 ;;
650 ;; Table-of-Contents Features
651 ;;
652 ;; \C-c \C-t is the keymap for table of contents.
653 (rst-define-key map [?\C-c ?\C-t ?\C-h] 'describe-prefix-bindings)
654 ;; Enter a TOC buffer to view and move to a specific section.
655 (rst-define-key map [?\C-c ?\C-t ?\C-t] 'rst-toc)
656 ;; Insert a TOC here.
657 (rst-define-key map [?\C-c ?\C-t ?\C-i] 'rst-toc-insert
658 [?\C-c ?\C-i])
659 ;; Update the document's TOC (without changing the cursor position).
660 (rst-define-key map [?\C-c ?\C-t ?\C-u] 'rst-toc-update
661 [?\C-c ?\C-u])
662 ;; Go to the section under the cursor (cursor must be in TOC).
663 (rst-define-key map [?\C-c ?\C-t ?\C-j] 'rst-goto-section
664 [?\C-c ?\C-f])
665
666 ;;
667 ;; Converting Documents from Emacs
668 ;;
669 ;; \C-c \C-c is the keymap for compilation.
670 (rst-define-key map [?\C-c ?\C-c ?\C-h] 'describe-prefix-bindings)
671 ;; Run one of two pre-configured toolset commands on the document.
672 (rst-define-key map [?\C-c ?\C-c ?\C-c] 'rst-compile
673 [?\C-c ?1])
674 (rst-define-key map [?\C-c ?\C-c ?\C-a] 'rst-compile-alt-toolset
675 [?\C-c ?2])
676 ;; Convert the active region to pseudo-xml using the docutils tools.
677 (rst-define-key map [?\C-c ?\C-c ?\C-x] 'rst-compile-pseudo-region
678 [?\C-c ?3])
679 ;; Convert the current document to PDF and launch a viewer on the results.
680 (rst-define-key map [?\C-c ?\C-c ?\C-p] 'rst-compile-pdf-preview
681 [?\C-c ?4])
682 ;; Convert the current document to S5 slides and view in a web browser.
683 (rst-define-key map [?\C-c ?\C-c ?\C-s] 'rst-compile-slides-preview
684 [?\C-c ?5])
685
686 map)
687 "Keymap for reStructuredText mode commands.
688 This inherits from Text mode.")
689
690
691 ;; Abbrevs.
692 (define-abbrev-table 'rst-mode-abbrev-table
693 (mapcar (lambda (x) (append x '(nil 0 system)))
694 '(("contents" ".. contents::\n..\n ")
695 ("con" ".. contents::\n..\n ")
696 ("cont" "[...]")
697 ("skip" "\n\n[...]\n\n ")
698 ("seq" "\n\n[...]\n\n ")
699 ;; FIXME: Add footnotes, links, and more.
700 ))
701 "Abbrev table used while in `rst-mode'.")
702
703
704 ;; Syntax table.
705 (defvar rst-mode-syntax-table
706 (let ((st (copy-syntax-table text-mode-syntax-table)))
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 ?/ "." st)
715 (modify-syntax-entry ?< "." st)
716 (modify-syntax-entry ?= "." st)
717 (modify-syntax-entry ?> "." st)
718 (modify-syntax-entry ?\\ "\\" st)
719 (modify-syntax-entry ?_ "." st)
720 (modify-syntax-entry ?| "." st)
721 (modify-syntax-entry ?\u00ab "." st)
722 (modify-syntax-entry ?\u00bb "." st)
723 (modify-syntax-entry ?\u2018 "." st)
724 (modify-syntax-entry ?\u2019 "." st)
725 (modify-syntax-entry ?\u201c "." st)
726 (modify-syntax-entry ?\u201d "." st)
727
728 st)
729 "Syntax table used while in `rst-mode'.")
730
731
732 (defcustom rst-mode-hook nil
733 "Hook run when `rst-mode' is turned on.
734 The hook for `text-mode' is run before this one."
735 :group 'rst
736 :type '(hook))
737
738 ;; Pull in variable definitions silencing byte-compiler.
739 (require 'newcomment)
740
741 ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
742 ;; use *.txt, but this is too generic to be set as a default.
743 ;;;###autoload (add-to-list 'auto-mode-alist (purecopy '("\\.re?st\\'" . rst-mode)))
744 ;;;###autoload
745 (define-derived-mode rst-mode text-mode "ReST"
746 "Major mode for editing reStructuredText documents.
747 \\<rst-mode-map>
748
749 Turning on `rst-mode' calls the normal hooks `text-mode-hook'
750 and `rst-mode-hook'. This mode also supports font-lock
751 highlighting.
752
753 \\{rst-mode-map}"
754 :abbrev-table rst-mode-abbrev-table
755 :syntax-table rst-mode-syntax-table
756 :group 'rst
757
758 ;; Paragraph recognition.
759 (set (make-local-variable 'paragraph-separate)
760 (rst-re '(:alt
761 "\f"
762 lin-end)))
763 (set (make-local-variable 'paragraph-start)
764 (rst-re '(:alt
765 "\f"
766 lin-end
767 (:seq hws-tag par-tag- bli-sfx))))
768
769 ;; Indenting and filling.
770 (set (make-local-variable 'indent-line-function) 'rst-indent-line)
771 (set (make-local-variable 'adaptive-fill-mode) t)
772 (set (make-local-variable 'adaptive-fill-regexp)
773 (rst-re 'hws-tag 'par-tag- "?" 'hws-tag))
774 (set (make-local-variable 'adaptive-fill-function) 'rst-adaptive-fill)
775 (set (make-local-variable 'fill-paragraph-handle-comment) nil)
776
777 ;; Comments.
778 (set (make-local-variable 'comment-start) ".. ")
779 (set (make-local-variable 'comment-start-skip)
780 (rst-re 'lin-beg 'exm-tag 'bli-sfx))
781 (set (make-local-variable 'comment-continue) " ")
782 (set (make-local-variable 'comment-multi-line) t)
783 (set (make-local-variable 'comment-use-syntax) nil)
784 ;; reStructuredText has not really a comment ender but nil is not really a
785 ;; permissible value.
786 (set (make-local-variable 'comment-end) "")
787 (set (make-local-variable 'comment-end-skip) nil)
788
789 ;; Commenting in reStructuredText is very special so use our own set of
790 ;; functions.
791 (set (make-local-variable 'comment-line-break-function)
792 'rst-comment-line-break)
793 (set (make-local-variable 'comment-indent-function)
794 'rst-comment-indent)
795 (set (make-local-variable 'comment-insert-comment-function)
796 'rst-comment-insert-comment)
797 (set (make-local-variable 'comment-region-function)
798 'rst-comment-region)
799 (set (make-local-variable 'uncomment-region-function)
800 'rst-uncomment-region)
801
802 ;; Font lock.
803 (set (make-local-variable 'font-lock-defaults)
804 '(rst-font-lock-keywords
805 t nil nil nil
806 (font-lock-multiline . t)
807 (font-lock-mark-block-function . mark-paragraph)))
808 (add-hook 'font-lock-extend-region-functions 'rst-font-lock-extend-region t)
809
810 ;; Text after a changed line may need new fontification.
811 (set (make-local-variable 'jit-lock-contextually) t))
812
813 ;;;###autoload
814 (define-minor-mode rst-minor-mode
815 "Toggle ReST minor mode.
816 With a prefix argument ARG, enable ReST minor mode if ARG is
817 positive, and disable it otherwise. If called from Lisp, enable
818 the mode if ARG is omitted or nil.
819
820 When ReST minor mode is enabled, the ReST mode keybindings
821 are installed on top of the major mode bindings. Use this
822 for modes derived from Text mode, like Mail mode."
823 ;; The initial value.
824 nil
825 ;; The indicator for the mode line.
826 " ReST"
827 ;; The minor mode bindings.
828 rst-mode-map
829 :group 'rst)
830
831 ;; FIXME: can I somehow install these too?
832 ;; :abbrev-table rst-mode-abbrev-table
833 ;; :syntax-table rst-mode-syntax-table
834
835 \f
836 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
837 ;; Section Adornment Adjustment
838 ;; ============================
839 ;;
840 ;; The following functions implement a smart automatic title sectioning feature.
841 ;; The idea is that with the cursor sitting on a section title, we try to get as
842 ;; much information from context and try to do the best thing automatically.
843 ;; This function can be invoked many times and/or with prefix argument to rotate
844 ;; between the various sectioning adornments.
845 ;;
846 ;; Definitions: the two forms of sectioning define semantically separate section
847 ;; levels. A sectioning ADORNMENT consists in:
848 ;;
849 ;; - a CHARACTER
850 ;;
851 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
852 ;;
853 ;; - an INDENT (meaningful for the over-and-under style only) which determines
854 ;; how many characters and over-and-under style is hanging outside of the
855 ;; title at the beginning and ending.
856 ;;
857 ;; Here are two examples of adornments (| represents the window border, column
858 ;; 0):
859 ;;
860 ;; |
861 ;; 1. char: '-' e |Some Title
862 ;; style: simple |----------
863 ;; |
864 ;; 2. char: '=' |==============
865 ;; style: over-and-under | Some Title
866 ;; indent: 2 |==============
867 ;; |
868 ;;
869 ;; Some notes:
870 ;;
871 ;; - The underlining character that is used depends on context. The file is
872 ;; scanned to find other sections and an appropriate character is selected.
873 ;; If the function is invoked on a section that is complete, the character is
874 ;; rotated among the existing section adornments.
875 ;;
876 ;; Note that when rotating the characters, if we come to the end of the
877 ;; hierarchy of adornments, the variable rst-preferred-adornments is
878 ;; consulted to propose a new underline adornment, and if continued, we cycle
879 ;; the adornments all over again. Set this variable to nil if you want to
880 ;; limit the underlining character propositions to the existing adornments in
881 ;; the file.
882 ;;
883 ;; - An underline/overline that is not extended to the column at which it should
884 ;; be hanging is dubbed INCOMPLETE. For example::
885 ;;
886 ;; |Some Title
887 ;; |-------
888 ;;
889 ;; Examples of default invocation:
890 ;;
891 ;; |Some Title ---> |Some Title
892 ;; | |----------
893 ;;
894 ;; |Some Title ---> |Some Title
895 ;; |----- |----------
896 ;;
897 ;; | |------------
898 ;; | Some Title ---> | Some Title
899 ;; | |------------
900 ;;
901 ;; In over-and-under style, when alternating the style, a variable is
902 ;; available to select how much default indent to use (it can be zero). Note
903 ;; that if the current section adornment already has an indent, we don't
904 ;; adjust it to the default, we rather use the current indent that is already
905 ;; there for adjustment (unless we cycle, in which case we use the indent
906 ;; that has been found previously).
907
908 (defgroup rst-adjust nil
909 "Settings for adjustment and cycling of section title adornments."
910 :group 'rst
911 :version "21.1")
912
913 (define-obsolete-variable-alias
914 'rst-preferred-decorations 'rst-preferred-adornments "1.0.0")
915 (defcustom rst-preferred-adornments '((?= over-and-under 1)
916 (?= simple 0)
917 (?- simple 0)
918 (?~ simple 0)
919 (?+ simple 0)
920 (?` simple 0)
921 (?# simple 0)
922 (?@ simple 0))
923 "Preferred hierarchy of section title adornments.
924
925 A list consisting of lists of the form (CHARACTER STYLE INDENT).
926 CHARACTER is the character used. STYLE is one of the symbols
927 OVER-AND-UNDER or SIMPLE. INDENT is an integer giving the wanted
928 indentation for STYLE OVER-AND-UNDER. CHARACTER and STYLE are
929 always used when a section adornment is described. In other
930 places t instead of a list stands for a transition.
931
932 This sequence is consulted to offer a new adornment suggestion
933 when we rotate the underlines at the end of the existing
934 hierarchy of characters, or when there is no existing section
935 title in the file.
936
937 Set this to an empty list to use only the adornment found in the
938 file."
939 :group 'rst-adjust
940 :type `(repeat
941 (group :tag "Adornment specification"
942 (choice :tag "Adornment character"
943 ,@(mapcar (lambda (char)
944 (list 'const
945 :tag (char-to-string char) char))
946 rst-adornment-chars))
947 (radio :tag "Adornment type"
948 (const :tag "Overline and underline" over-and-under)
949 (const :tag "Underline only" simple))
950 (integer :tag "Indentation for overline and underline type"
951 :value 0))))
952
953 (defcustom rst-default-indent 1
954 "Number of characters to indent the section title.
955
956 This is used for when toggling adornment styles, when switching
957 from a simple adornment style to a over-and-under adornment
958 style."
959 :group 'rst-adjust
960 :type '(integer))
961
962
963 (defun rst-compare-adornments (ado1 ado2)
964 "Compare adornments.
965 Return true if both ADO1 and ADO2 adornments are equal,
966 according to restructured text semantics (only the character and
967 the style are compared, the indentation does not matter)."
968 (and (eq (car ado1) (car ado2))
969 (eq (cadr ado1) (cadr ado2))))
970
971
972 (defun rst-get-adornment-match (hier ado)
973 "Return the index (level) in hierarchy HIER of adornment ADO.
974 This basically just searches for the item using the appropriate
975 comparison and returns the index. Return nil if the item is
976 not found."
977 (let ((cur hier))
978 (while (and cur (not (rst-compare-adornments (car cur) ado)))
979 (setq cur (cdr cur)))
980 cur))
981
982
983 (defun rst-suggest-new-adornment (allados &optional prev)
984 "Suggest a new, different adornment from all that have been seen.
985
986 ALLADOS is the set of all adornments, including the line numbers.
987 PREV is the optional previous adornment, in order to suggest a
988 better match."
989
990 ;; For all the preferred adornments...
991 (let* (
992 ;; If 'prev' is given, reorder the list to start searching after the
993 ;; match.
994 (fplist
995 (cdr (rst-get-adornment-match rst-preferred-adornments prev)))
996
997 ;; List of candidates to search.
998 (curpotential (append fplist rst-preferred-adornments)))
999 (while
1000 ;; For all the adornments...
1001 (let ((cur allados)
1002 found)
1003 (while (and cur (not found))
1004 (if (rst-compare-adornments (car cur) (car curpotential))
1005 ;; Found it!
1006 (setq found (car curpotential))
1007 (setq cur (cdr cur))))
1008 found)
1009
1010 (setq curpotential (cdr curpotential)))
1011
1012 (copy-sequence (car curpotential))))
1013
1014 (defun rst-delete-entire-line ()
1015 "Delete the entire current line without using the `kill-ring'."
1016 (delete-region (line-beginning-position)
1017 (line-beginning-position 2)))
1018
1019 (defun rst-update-section (char style &optional indent)
1020 "Unconditionally update the style of a section adornment.
1021
1022 Do this using the given character CHAR, with STYLE 'simple
1023 or 'over-and-under, and with indent INDENT. If the STYLE
1024 is 'simple, whitespace before the title is removed (indent
1025 is always assumed to be 0).
1026
1027 If there are existing overline and/or underline from the
1028 existing adornment, they are removed before adding the
1029 requested adornment."
1030 (end-of-line)
1031 (let ((marker (point-marker))
1032 len)
1033
1034 ;; Fixup whitespace at the beginning and end of the line.
1035 (if (or (null indent) (eq style 'simple))
1036 (setq indent 0))
1037 (beginning-of-line)
1038 (delete-horizontal-space)
1039 (insert (make-string indent ? ))
1040
1041 (end-of-line)
1042 (delete-horizontal-space)
1043
1044 ;; Set the current column, we're at the end of the title line.
1045 (setq len (+ (current-column) indent))
1046
1047 ;; Remove previous line if it is an adornment.
1048 (save-excursion
1049 (forward-line -1)
1050 (if (and (looking-at (rst-re 'ado-beg-2-1))
1051 ;; Avoid removing the underline of a title right above us.
1052 (save-excursion (forward-line -1)
1053 (not (looking-at (rst-re 'ttl-beg)))))
1054 (rst-delete-entire-line)))
1055
1056 ;; Remove following line if it is an adornment.
1057 (save-excursion
1058 (forward-line +1)
1059 (if (looking-at (rst-re 'ado-beg-2-1))
1060 (rst-delete-entire-line))
1061 ;; Add a newline if we're at the end of the buffer, for the subsequence
1062 ;; inserting of the underline.
1063 (if (= (point) (buffer-end 1))
1064 (newline 1)))
1065
1066 ;; Insert overline.
1067 (if (eq style 'over-and-under)
1068 (save-excursion
1069 (beginning-of-line)
1070 (open-line 1)
1071 (insert (make-string len char))))
1072
1073 ;; Insert underline.
1074 (forward-line +1)
1075 (open-line 1)
1076 (insert (make-string len char))
1077
1078 (forward-line +1)
1079 (goto-char marker)
1080 ))
1081
1082 (defun rst-classify-adornment (adornment end)
1083 "Classify adornment for section titles and transitions.
1084 ADORNMENT is the complete adornment string as found in the buffer
1085 with optional trailing whitespace. END is the point after the
1086 last character of ADORNMENT.
1087
1088 Return a list. The first entry is t for a transition or a
1089 cons (CHARACTER . STYLE). Check `rst-preferred-adornments' for
1090 the meaning of CHARACTER and STYLE.
1091
1092 The remaining list forms four match groups as returned by
1093 `match-data'. Match group 0 matches the whole construct. Match
1094 group 1 matches the overline adornment if present. Match group 2
1095 matches the section title text or the transition. Match group 3
1096 matches the underline adornment.
1097
1098 Return nil if no syntactically valid adornment is found."
1099 (save-excursion
1100 (save-match-data
1101 (when (string-match (rst-re 'ado-beg-2-1) adornment)
1102 (goto-char end)
1103 (let* ((ado-ch (string-to-char (match-string 2 adornment)))
1104 (ado-re (rst-re ado-ch 'adorep3-hlp))
1105 (end-pnt (point))
1106 (beg-pnt (progn
1107 (forward-line 0)
1108 (point)))
1109 (nxt-emp ; Next line nonexistent or empty
1110 (save-excursion
1111 (or (not (zerop (forward-line 1)))
1112 (looking-at (rst-re 'lin-end)))))
1113 (prv-emp ; Previous line nonexistent or empty
1114 (save-excursion
1115 (or (not (zerop (forward-line -1)))
1116 (looking-at (rst-re 'lin-end)))))
1117 (ttl-blw ; Title found below starting here.
1118 (save-excursion
1119 (and
1120 (zerop (forward-line 1))
1121 (looking-at (rst-re 'ttl-beg))
1122 (point))))
1123 (ttl-abv ; Title found above starting here.
1124 (save-excursion
1125 (and
1126 (zerop (forward-line -1))
1127 (looking-at (rst-re 'ttl-beg))
1128 (point))))
1129 (und-fnd ; Matching underline found starting here.
1130 (save-excursion
1131 (and ttl-blw
1132 (zerop (forward-line 2))
1133 (looking-at (rst-re ado-re 'lin-end))
1134 (point))))
1135 (ovr-fnd ; Matching overline found starting here.
1136 (save-excursion
1137 (and ttl-abv
1138 (zerop (forward-line -2))
1139 (looking-at (rst-re ado-re 'lin-end))
1140 (point))))
1141 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
1142 (cond
1143 ((and nxt-emp prv-emp)
1144 ;; A transition.
1145 (setq key t
1146 beg-txt beg-pnt
1147 end-txt end-pnt))
1148 ((or und-fnd ovr-fnd)
1149 ;; An overline with an underline.
1150 (setq key (cons ado-ch 'over-and-under))
1151 (let (;; Prefer overline match over underline match.
1152 (und-pnt (if ovr-fnd beg-pnt und-fnd))
1153 (ovr-pnt (if ovr-fnd ovr-fnd beg-pnt))
1154 (txt-pnt (if ovr-fnd ttl-abv ttl-blw)))
1155 (goto-char ovr-pnt)
1156 (setq beg-ovr (point)
1157 end-ovr (line-end-position))
1158 (goto-char txt-pnt)
1159 (setq beg-txt (point)
1160 end-txt (line-end-position))
1161 (goto-char und-pnt)
1162 (setq beg-und (point)
1163 end-und (line-end-position))))
1164 (ttl-abv
1165 ;; An underline.
1166 (setq key (cons ado-ch 'simple)
1167 beg-und beg-pnt
1168 end-und end-pnt)
1169 (goto-char ttl-abv)
1170 (setq beg-txt (point)
1171 end-txt (line-end-position)))
1172 (t
1173 ;; Invalid adornment.
1174 (setq key nil)))
1175 (if key
1176 (list key
1177 (or beg-ovr beg-txt beg-und)
1178 (or end-und end-txt end-ovr)
1179 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))))
1180
1181 (defun rst-find-title-line ()
1182 "Find a section title line around point and return its characteristics.
1183 If the point is on an adornment line find the respective title
1184 line. If the point is on an empty line check previous or next
1185 line whether it is a suitable title line and use it if so. If
1186 point is on a suitable title line use it.
1187
1188 If no title line is found return nil.
1189
1190 Otherwise return as `rst-classify-adornment' does. However, if
1191 the title line has no syntactically valid adornment STYLE is nil
1192 in the first element. If there is no adornment around the title
1193 CHARACTER is also nil and match groups for overline and underline
1194 are nil."
1195 (save-excursion
1196 (forward-line 0)
1197 (let ((orig-pnt (point))
1198 (orig-end (line-end-position)))
1199 (cond
1200 ((looking-at (rst-re 'ado-beg-2-1))
1201 (let ((char (string-to-char (match-string-no-properties 2)))
1202 (r (rst-classify-adornment (match-string-no-properties 0)
1203 (match-end 0))))
1204 (cond
1205 ((not r)
1206 ;; Invalid adornment - check whether this is an incomplete overline.
1207 (if (and
1208 (zerop (forward-line 1))
1209 (looking-at (rst-re 'ttl-beg)))
1210 (list (cons char nil) orig-pnt (line-end-position)
1211 orig-pnt orig-end (point) (line-end-position) nil nil)))
1212 ((consp (car r))
1213 ;; A section title - not a transition.
1214 r))))
1215 ((looking-at (rst-re 'lin-end))
1216 (or
1217 (save-excursion
1218 (if (and (zerop (forward-line -1))
1219 (looking-at (rst-re 'ttl-beg)))
1220 (list (cons nil nil) (point) (line-end-position)
1221 nil nil (point) (line-end-position) nil nil)))
1222 (save-excursion
1223 (if (and (zerop (forward-line 1))
1224 (looking-at (rst-re 'ttl-beg)))
1225 (list (cons nil nil) (point) (line-end-position)
1226 nil nil (point) (line-end-position) nil nil)))))
1227 ((looking-at (rst-re 'ttl-beg))
1228 ;; Try to use the underline.
1229 (let ((r (rst-classify-adornment
1230 (buffer-substring-no-properties
1231 (line-beginning-position 2) (line-end-position 2))
1232 (line-end-position 2))))
1233 (if r
1234 r
1235 ;; No valid adornment found.
1236 (list (cons nil nil) (point) (line-end-position)
1237 nil nil (point) (line-end-position) nil nil))))))))
1238
1239 ;; The following function and variables are used to maintain information about
1240 ;; current section adornment in a buffer local cache. Thus they can be used for
1241 ;; font-locking and manipulation commands.
1242
1243 (defvar rst-all-sections nil
1244 "All section adornments in the buffer as found by `rst-find-all-adornments'.
1245 t when no section adornments were found.")
1246 (make-variable-buffer-local 'rst-all-sections)
1247
1248 ;; FIXME: If this variable is set to a different value font-locking of section
1249 ;; headers is wrong.
1250 (defvar rst-section-hierarchy nil
1251 "Section hierarchy in the buffer as determined by `rst-get-hierarchy'.
1252 t when no section adornments were found. Value depends on
1253 `rst-all-sections'.")
1254 (make-variable-buffer-local 'rst-section-hierarchy)
1255
1256 (defun rst-reset-section-caches ()
1257 "Reset all section cache variables.
1258 Should be called by interactive functions which deal with sections."
1259 (setq rst-all-sections nil
1260 rst-section-hierarchy nil))
1261
1262 (defun rst-find-all-adornments ()
1263 "Return all the section adornments in the current buffer.
1264 Return a list of (LINE . ADORNMENT) with ascending LINE where
1265 LINE is the line containing the section title. ADORNMENT consists
1266 of a (CHARACTER STYLE INDENT) triple as described for
1267 `rst-preferred-adornments'.
1268
1269 Uses and sets `rst-all-sections'."
1270 (unless rst-all-sections
1271 (let (positions)
1272 ;; Iterate over all the section titles/adornments in the file.
1273 (save-excursion
1274 (goto-char (point-min))
1275 (while (re-search-forward (rst-re 'ado-beg-2-1) nil t)
1276 (let ((ado-data (rst-classify-adornment
1277 (match-string-no-properties 0) (point))))
1278 (when (and ado-data
1279 (consp (car ado-data))) ; Ignore transitions.
1280 (set-match-data (cdr ado-data))
1281 (goto-char (match-beginning 2)) ; Goto the title start.
1282 (push (cons (1+ (count-lines (point-min) (point)))
1283 (list (caar ado-data)
1284 (cdar ado-data)
1285 (current-indentation)))
1286 positions)
1287 (goto-char (match-end 0))))) ; Go beyond the whole thing.
1288 (setq positions (nreverse positions))
1289 (setq rst-all-sections (or positions t)))))
1290 (if (eq rst-all-sections t)
1291 nil
1292 rst-all-sections))
1293
1294 (defun rst-infer-hierarchy (adornments)
1295 "Build a hierarchy of adornments using the list of given ADORNMENTS.
1296
1297 ADORNMENTS is a list of (CHARACTER STYLE INDENT) adornment
1298 specifications, in order that they appear in a file, and will
1299 infer a hierarchy of section levels by removing adornments that
1300 have already been seen in a forward traversal of the adornments,
1301 comparing just CHARACTER and STYLE.
1302
1303 Similarly returns a list of (CHARACTER STYLE INDENT), where each
1304 list element should be unique."
1305 (let (hierarchy-alist)
1306 (dolist (x adornments)
1307 (let ((char (car x))
1308 (style (cadr x)))
1309 (unless (assoc (cons char style) hierarchy-alist)
1310 (push (cons (cons char style) x) hierarchy-alist))))
1311 (mapcar 'cdr (nreverse hierarchy-alist))))
1312
1313 (defun rst-get-hierarchy (&optional ignore)
1314 "Return the hierarchy of section titles in the file.
1315
1316 Return a list of adornments that represents the hierarchy of
1317 section titles in the file. Each element consists of (CHARACTER
1318 STYLE INDENT) as described for `rst-find-all-adornments'. If the
1319 line number in IGNORE is specified, a possibly adornment found on
1320 that line is not taken into account when building the hierarchy.
1321
1322 Uses and sets `rst-section-hierarchy' unless IGNORE is given."
1323 (if (and (not ignore) rst-section-hierarchy)
1324 (if (eq rst-section-hierarchy t)
1325 nil
1326 rst-section-hierarchy)
1327 (let ((r (rst-infer-hierarchy
1328 (mapcar 'cdr
1329 (assq-delete-all
1330 ignore
1331 (rst-find-all-adornments))))))
1332 (setq rst-section-hierarchy
1333 (if ignore
1334 ;; Clear cache reflecting that a possible update is not
1335 ;; reflected.
1336 nil
1337 (or r t)))
1338 r)))
1339
1340 (defun rst-get-adornments-around ()
1341 "Return the adornments around point.
1342 Return a list of the previous and next adornments."
1343 (let* ((all (rst-find-all-adornments))
1344 (curline (line-number-at-pos))
1345 prev next
1346 (cur all))
1347
1348 ;; Search for the adornments around the current line.
1349 (while (and cur (< (caar cur) curline))
1350 (setq prev cur
1351 cur (cdr cur)))
1352 ;; 'cur' is the following adornment.
1353
1354 (if (and cur (caar cur))
1355 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
1356
1357 (mapcar 'cdar (list prev next))
1358 ))
1359
1360
1361 (defun rst-adornment-complete-p (ado)
1362 "Return true if the adornment ADO around point is complete."
1363 ;; Note: we assume that the detection of the overline as being the underline
1364 ;; of a preceding title has already been detected, and has been eliminated
1365 ;; from the adornment that is given to us.
1366
1367 ;; There is some sectioning already present, so check if the current
1368 ;; sectioning is complete and correct.
1369 (let* ((char (car ado))
1370 (style (cadr ado))
1371 (indent (caddr ado))
1372 (endcol (save-excursion (end-of-line) (current-column)))
1373 )
1374 (if char
1375 (let ((exps (rst-re "^" char (format "\\{%d\\}" (+ endcol indent)) "$")))
1376 (and
1377 (save-excursion (forward-line +1)
1378 (beginning-of-line)
1379 (looking-at exps))
1380 (or (not (eq style 'over-and-under))
1381 (save-excursion (forward-line -1)
1382 (beginning-of-line)
1383 (looking-at exps))))
1384 ))
1385 ))
1386
1387
1388 (defun rst-get-next-adornment
1389 (curado hier &optional suggestion reverse-direction)
1390 "Get the next adornment for CURADO, in given hierarchy HIER.
1391 If suggesting, suggest for new adornment SUGGESTION.
1392 REVERSE-DIRECTION is used to reverse the cycling order."
1393
1394 (let* (
1395 (char (car curado))
1396 (style (cadr curado))
1397
1398 ;; Build a new list of adornments for the rotation.
1399 (rotados
1400 (append hier
1401 ;; Suggest a new adornment.
1402 (list suggestion
1403 ;; If nothing to suggest, use first adornment.
1404 (car hier)))) )
1405 (or
1406 ;; Search for next adornment.
1407 (cadr
1408 (let ((cur (if reverse-direction rotados
1409 (reverse rotados))))
1410 (while (and cur
1411 (not (and (eq char (caar cur))
1412 (eq style (cadar cur)))))
1413 (setq cur (cdr cur)))
1414 cur))
1415
1416 ;; If not found, take the first of all adornments.
1417 suggestion
1418 )))
1419
1420
1421 ;; FIXME: A line "``/`` full" is not accepted as a section title.
1422 (defun rst-adjust (pfxarg)
1423 "Auto-adjust the adornment around point.
1424
1425 Adjust/rotate the section adornment for the section title around
1426 point or promote/demote the adornments inside the region,
1427 depending on if the region is active. This function is meant to
1428 be invoked possibly multiple times, and can vary its behavior
1429 with a positive PFXARG (toggle style), or with a negative
1430 PFXARG (alternate behavior).
1431
1432 This function is a bit of a swiss knife. It is meant to adjust
1433 the adornments of a section title in reStructuredText. It tries
1434 to deal with all the possible cases gracefully and to do `the
1435 right thing' in all cases.
1436
1437 See the documentations of `rst-adjust-adornment-work' and
1438 `rst-promote-region' for full details.
1439
1440 Prefix Arguments
1441 ================
1442
1443 The method can take either (but not both) of
1444
1445 a. a (non-negative) prefix argument, which means to toggle the
1446 adornment style. Invoke with a prefix argument for example;
1447
1448 b. a negative numerical argument, which generally inverts the
1449 direction of search in the file or hierarchy. Invoke with C--
1450 prefix for example."
1451 (interactive "P")
1452
1453 (let* (;; Save our original position on the current line.
1454 (origpt (point-marker))
1455
1456 (reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1457 (toggle-style (and pfxarg (not reverse-direction))))
1458
1459 (if (rst-portable-mark-active-p)
1460 ;; Adjust adornments within region.
1461 (rst-promote-region (and pfxarg t))
1462 ;; Adjust adornment around point.
1463 (rst-adjust-adornment-work toggle-style reverse-direction))
1464
1465 ;; Run the hooks to run after adjusting.
1466 (run-hooks 'rst-adjust-hook)
1467
1468 ;; Make sure to reset the cursor position properly after we're done.
1469 (goto-char origpt)
1470
1471 ))
1472
1473 (defcustom rst-adjust-hook nil
1474 "Hooks to be run after running `rst-adjust'."
1475 :group 'rst-adjust
1476 :type '(hook)
1477 :package-version '(rst . "1.1.0"))
1478
1479 (defcustom rst-new-adornment-down nil
1480 "Controls level of new adornment for section headers."
1481 :group 'rst-adjust
1482 :type '(choice
1483 (const :tag "Same level as previous one" nil)
1484 (const :tag "One level down relative to the previous one" t))
1485 :package-version '(rst . "1.1.0"))
1486
1487 (defun rst-adjust-adornment (pfxarg)
1488 "Call `rst-adjust-adornment-work' interactively.
1489
1490 Keep this for compatibility for older bindings (are there any?).
1491 Argument PFXARG has the same meaning as for `rst-adjust'."
1492 (interactive "P")
1493
1494 (let* ((reverse-direction (and pfxarg (< (prefix-numeric-value pfxarg) 0)))
1495 (toggle-style (and pfxarg (not reverse-direction))))
1496 (rst-adjust-adornment-work toggle-style reverse-direction)))
1497
1498 (defun rst-adjust-adornment-work (toggle-style reverse-direction)
1499 "Adjust/rotate the section adornment for the section title around point.
1500
1501 This function is meant to be invoked possibly multiple times, and
1502 can vary its behavior with a true TOGGLE-STYLE argument, or with
1503 a REVERSE-DIRECTION argument.
1504
1505 General Behavior
1506 ================
1507
1508 The next action it takes depends on context around the point, and
1509 it is meant to be invoked possibly more than once to rotate among
1510 the various possibilities. Basically, this function deals with:
1511
1512 - adding a adornment if the title does not have one;
1513
1514 - adjusting the length of the underline characters to fit a
1515 modified title;
1516
1517 - rotating the adornment in the set of already existing
1518 sectioning adornments used in the file;
1519
1520 - switching between simple and over-and-under styles.
1521
1522 You should normally not have to read all the following, just
1523 invoke the method and it will do the most obvious thing that you
1524 would expect.
1525
1526
1527 Adornment Definitions
1528 =====================
1529
1530 The adornments consist in
1531
1532 1. a CHARACTER
1533
1534 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1535
1536 3. an INDENT (meaningful for the over-and-under style only)
1537 which determines how many characters and over-and-under
1538 style is hanging outside of the title at the beginning and
1539 ending.
1540
1541 See source code for mode details.
1542
1543
1544 Detailed Behavior Description
1545 =============================
1546
1547 Here are the gory details of the algorithm (it seems quite
1548 complicated, but really, it does the most obvious thing in all
1549 the particular cases):
1550
1551 Before applying the adornment change, the cursor is placed on
1552 the closest line that could contain a section title.
1553
1554 Case 1: No Adornment
1555 --------------------
1556
1557 If the current line has no adornment around it,
1558
1559 - search backwards for the last previous adornment, and apply
1560 the adornment one level lower to the current line. If there
1561 is no defined level below this previous adornment, we suggest
1562 the most appropriate of the `rst-preferred-adornments'.
1563
1564 If REVERSE-DIRECTION is true, we simply use the previous
1565 adornment found directly.
1566
1567 - if there is no adornment found in the given direction, we use
1568 the first of `rst-preferred-adornments'.
1569
1570 TOGGLE-STYLE forces a toggle of the prescribed adornment style.
1571
1572 Case 2: Incomplete Adornment
1573 ----------------------------
1574
1575 If the current line does have an existing adornment, but the
1576 adornment is incomplete, that is, the underline/overline does
1577 not extend to exactly the end of the title line (it is either too
1578 short or too long), we simply extend the length of the
1579 underlines/overlines to fit exactly the section title.
1580
1581 If TOGGLE-STYLE we toggle the style of the adornment as well.
1582
1583 REVERSE-DIRECTION has no effect in this case.
1584
1585 Case 3: Complete Existing Adornment
1586 -----------------------------------
1587
1588 If the adornment is complete (i.e. the underline (overline)
1589 length is already adjusted to the end of the title line), we
1590 search/parse the file to establish the hierarchy of all the
1591 adornments (making sure not to include the adornment around
1592 point), and we rotate the current title's adornment from within
1593 that list (by default, going *down* the hierarchy that is present
1594 in the file, i.e. to a lower section level). This is meant to be
1595 used potentially multiple times, until the desired adornment is
1596 found around the title.
1597
1598 If we hit the boundary of the hierarchy, exactly one choice from
1599 the list of preferred adornments is suggested/chosen, the first
1600 of those adornment that has not been seen in the file yet (and
1601 not including the adornment around point), and the next
1602 invocation rolls over to the other end of the hierarchy (i.e. it
1603 cycles). This allows you to avoid having to set which character
1604 to use.
1605
1606 If REVERSE-DIRECTION is true, the effect is to change the
1607 direction of rotation in the hierarchy of adornments, thus
1608 instead going *up* the hierarchy.
1609
1610 However, if TOGGLE-STYLE, we do not rotate the adornment, but
1611 instead simply toggle the style of the current adornment (this
1612 should be the most common way to toggle the style of an existing
1613 complete adornment).
1614
1615
1616 Point Location
1617 ==============
1618
1619 The invocation of this function can be carried out anywhere
1620 within the section title line, on an existing underline or
1621 overline, as well as on an empty line following a section title.
1622 This is meant to be as convenient as possible.
1623
1624
1625 Indented Sections
1626 =================
1627
1628 Indented section titles such as ::
1629
1630 My Title
1631 --------
1632
1633 are invalid in reStructuredText and thus not recognized by the
1634 parser. This code will thus not work in a way that would support
1635 indented sections (it would be ambiguous anyway).
1636
1637
1638 Joint Sections
1639 ==============
1640
1641 Section titles that are right next to each other may not be
1642 treated well. More work might be needed to support those, and
1643 special conditions on the completeness of existing adornments
1644 might be required to make it non-ambiguous.
1645
1646 For now we assume that the adornments are disjoint, that is,
1647 there is at least a single line between the titles/adornment
1648 lines."
1649 (rst-reset-section-caches)
1650 (let ((ttl-fnd (rst-find-title-line))
1651 (orig-pnt (point)))
1652 (when ttl-fnd
1653 (set-match-data (cdr ttl-fnd))
1654 (goto-char (match-beginning 2))
1655 (let* ((moved (- (line-number-at-pos) (line-number-at-pos orig-pnt)))
1656 (char (caar ttl-fnd))
1657 (style (cdar ttl-fnd))
1658 (indent (current-indentation))
1659 (curado (list char style indent))
1660 char-new style-new indent-new)
1661 (cond
1662 ;;-------------------------------------------------------------------
1663 ;; Case 1: No valid adornment
1664 ((not style)
1665 (let ((prev (car (rst-get-adornments-around)))
1666 cur
1667 (hier (rst-get-hierarchy)))
1668 ;; Advance one level down.
1669 (setq cur
1670 (if prev
1671 (if (or (and rst-new-adornment-down reverse-direction)
1672 (and (not rst-new-adornment-down)
1673 (not reverse-direction)))
1674 prev
1675 (or (cadr (rst-get-adornment-match hier prev))
1676 (rst-suggest-new-adornment hier prev)))
1677 (copy-sequence (car rst-preferred-adornments))))
1678 ;; Invert the style if requested.
1679 (if toggle-style
1680 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1681 'over-and-under 'simple)) )
1682 (setq char-new (car cur)
1683 style-new (cadr cur)
1684 indent-new (caddr cur))))
1685 ;;-------------------------------------------------------------------
1686 ;; Case 2: Incomplete Adornment
1687 ((not (rst-adornment-complete-p curado))
1688 ;; Invert the style if requested.
1689 (if toggle-style
1690 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1691 (setq char-new char
1692 style-new style
1693 indent-new indent))
1694 ;;-------------------------------------------------------------------
1695 ;; Case 3: Complete Existing Adornment
1696 (t
1697 (if toggle-style
1698 ;; Simply switch the style of the current adornment.
1699 (setq char-new char
1700 style-new (if (eq style 'simple) 'over-and-under 'simple)
1701 indent-new rst-default-indent)
1702 ;; Else, we rotate, ignoring the adornment around the current
1703 ;; line...
1704 (let* ((hier (rst-get-hierarchy (line-number-at-pos)))
1705 ;; Suggestion, in case we need to come up with something new.
1706 (suggestion (rst-suggest-new-adornment
1707 hier
1708 (car (rst-get-adornments-around))))
1709 (nextado (rst-get-next-adornment
1710 curado hier suggestion reverse-direction)))
1711 ;; Indent, if present, always overrides the prescribed indent.
1712 (setq char-new (car nextado)
1713 style-new (cadr nextado)
1714 indent-new (caddr nextado))))))
1715 ;; Override indent with present indent!
1716 (setq indent-new (if (> indent 0) indent indent-new))
1717 (if (and char-new style-new)
1718 (rst-update-section char-new style-new indent-new))
1719 ;; Correct the position of the cursor to more accurately reflect where
1720 ;; it was located when the function was invoked.
1721 (unless (zerop moved)
1722 (forward-line (- moved))
1723 (end-of-line))))))
1724
1725 ;; Maintain an alias for compatibility.
1726 (defalias 'rst-adjust-section-title 'rst-adjust)
1727
1728
1729 (defun rst-promote-region (demote)
1730 "Promote the section titles within the region.
1731
1732 With argument DEMOTE or a prefix argument, demote the section
1733 titles instead. The algorithm used at the boundaries of the
1734 hierarchy is similar to that used by `rst-adjust-adornment-work'."
1735 (interactive "P")
1736 (rst-reset-section-caches)
1737 (let* ((cur (rst-find-all-adornments))
1738 (hier (rst-get-hierarchy))
1739 (suggestion (rst-suggest-new-adornment hier))
1740
1741 (region-begin-line (line-number-at-pos (region-beginning)))
1742 (region-end-line (line-number-at-pos (region-end)))
1743
1744 marker-list
1745 )
1746
1747 ;; Skip the markers that come before the region beginning.
1748 (while (and cur (< (caar cur) region-begin-line))
1749 (setq cur (cdr cur)))
1750
1751 ;; Create a list of markers for all the adornments which are found within
1752 ;; the region.
1753 (save-excursion
1754 (let (line)
1755 (while (and cur (< (setq line (caar cur)) region-end-line))
1756 (goto-char (point-min))
1757 (forward-line (1- line))
1758 (push (list (point-marker) (cdar cur)) marker-list)
1759 (setq cur (cdr cur)) ))
1760
1761 ;; Apply modifications.
1762 (dolist (p marker-list)
1763 ;; Go to the adornment to promote.
1764 (goto-char (car p))
1765
1766 ;; Update the adornment.
1767 (apply 'rst-update-section
1768 ;; Rotate the next adornment.
1769 (rst-get-next-adornment
1770 (cadr p) hier suggestion demote))
1771
1772 ;; Clear marker to avoid slowing down the editing after we're done.
1773 (set-marker (car p) nil))
1774 (setq deactivate-mark nil)
1775 )))
1776
1777
1778
1779 (defun rst-display-adornments-hierarchy (&optional adornments)
1780 "Display the current file's section title adornments hierarchy.
1781 This function expects a list of (CHARACTER STYLE INDENT) triples
1782 in ADORNMENTS."
1783 (interactive)
1784 (rst-reset-section-caches)
1785 (if (not adornments)
1786 (setq adornments (rst-get-hierarchy)))
1787 (with-output-to-temp-buffer "*rest section hierarchy*"
1788 (let ((level 1))
1789 (with-current-buffer standard-output
1790 (dolist (x adornments)
1791 (insert (format "\nSection Level %d" level))
1792 (apply 'rst-update-section x)
1793 (goto-char (point-max))
1794 (insert "\n")
1795 (incf level)
1796 ))
1797 )))
1798
1799 (defun rst-straighten-adornments ()
1800 "Redo all the adornments in the current buffer.
1801 This is done using our preferred set of adornments. This can be
1802 used, for example, when using somebody else's copy of a document,
1803 in order to adapt it to our preferred style."
1804 (interactive)
1805 (rst-reset-section-caches)
1806 (save-excursion
1807 (let (;; Get a list of pairs of (level . marker).
1808 (levels-and-markers (mapcar
1809 (lambda (ado)
1810 (cons (rst-position (cdr ado)
1811 (rst-get-hierarchy))
1812 (progn
1813 (goto-char (point-min))
1814 (forward-line (1- (car ado)))
1815 (point-marker))))
1816 (rst-find-all-adornments))))
1817 (dolist (lm levels-and-markers)
1818 ;; Go to the appropriate position.
1819 (goto-char (cdr lm))
1820
1821 ;; Apply the new style.
1822 (apply 'rst-update-section (nth (car lm) rst-preferred-adornments))
1823
1824 ;; Reset the marker to avoid slowing down editing until it gets GC'ed.
1825 (set-marker (cdr lm) nil)
1826 )
1827 )))
1828
1829
1830 \f
1831 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1832 ;; Insert list items
1833 ;; =================
1834
1835
1836 ;=================================================
1837 ; Borrowed from a2r.el (version 1.3), by Lawrence Mitchell <wence@gmx.li>.
1838 ; I needed to make some tiny changes to the functions, so I put it here.
1839 ; -- Wei-Wei Guo
1840
1841 (defconst rst-arabic-to-roman
1842 '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
1843 (100 . "C") (90 . "XC") (50 . "L") (40 . "XL")
1844 (10 . "X") (9 . "IX") (5 . "V") (4 . "IV")
1845 (1 . "I"))
1846 "List of maps between Arabic numbers and their Roman numeral equivalents.")
1847
1848 (defun rst-arabic-to-roman (num &optional arg)
1849 "Convert Arabic number NUM to its Roman numeral representation.
1850
1851 Obviously, NUM must be greater than zero. Don't blame me, blame the
1852 Romans, I mean \"what have the Romans ever _done_ for /us/?\" (with
1853 apologies to Monty Python).
1854 If optional prefix ARG is non-nil, insert in current buffer."
1855 (let ((map rst-arabic-to-roman)
1856 res)
1857 (while (and map (> num 0))
1858 (if (or (= num (caar map))
1859 (> num (caar map)))
1860 (setq res (concat res (cdar map))
1861 num (- num (caar map)))
1862 (setq map (cdr map))))
1863 res))
1864
1865 (defun rst-roman-to-arabic (string &optional arg)
1866 "Convert STRING of Roman numerals to an Arabic number.
1867
1868 If STRING contains a letter which isn't a valid Roman numeral, the rest
1869 of the string from that point onwards is ignored.
1870
1871 Hence:
1872 MMD == 2500
1873 and
1874 MMDFLXXVI == 2500.
1875 If optional ARG is non-nil, insert in current buffer."
1876 (let ((res 0)
1877 (map rst-arabic-to-roman))
1878 (while map
1879 (if (string-match (concat "^" (cdar map)) string)
1880 (setq res (+ res (caar map))
1881 string (replace-match "" nil t string))
1882 (setq map (cdr map))))
1883 res))
1884 ;=================================================
1885
1886 (defun rst-find-pfx-in-region (beg end pfx-re)
1887 "Find all the positions of prefixes in region between BEG and END.
1888 This is used to find bullets and enumerated list items. PFX-RE is
1889 a regular expression for matching the lines after indentation
1890 with items. Returns a list of cons cells consisting of the point
1891 and the column of the point."
1892 (let ((pfx ()))
1893 (save-excursion
1894 (goto-char beg)
1895 (while (< (point) end)
1896 (back-to-indentation)
1897 (when (and
1898 (looking-at pfx-re) ; pfx found and...
1899 (let ((pfx-col (current-column)))
1900 (save-excursion
1901 (forward-line -1) ; ...previous line is...
1902 (back-to-indentation)
1903 (or (looking-at (rst-re 'lin-end)) ; ...empty,
1904 (> (current-column) pfx-col) ; ...deeper level, or
1905 (and (= (current-column) pfx-col)
1906 (looking-at pfx-re)))))) ; ...pfx at same level.
1907 (push (cons (point) (current-column))
1908 pfx))
1909 (forward-line 1)) )
1910 (nreverse pfx)))
1911
1912 (defun rst-insert-list-pos (newitem)
1913 "Arrange relative position of a newly inserted list item of style NEWITEM.
1914
1915 Adding a new list might consider three situations:
1916
1917 (a) Current line is a blank line.
1918 (b) Previous line is a blank line.
1919 (c) Following line is a blank line.
1920
1921 When (a) and (b), just add the new list at current line.
1922
1923 when (a) and not (b), a blank line is added before adding the new list.
1924
1925 When not (a), first forward point to the end of the line, and add two
1926 blank lines, then add the new list.
1927
1928 Other situations are just ignored and left to users themselves."
1929 (if (save-excursion
1930 (beginning-of-line)
1931 (looking-at (rst-re 'lin-end)))
1932 (if (save-excursion
1933 (forward-line -1)
1934 (looking-at (rst-re 'lin-end)))
1935 (insert newitem " ")
1936 (insert "\n" newitem " "))
1937 (end-of-line)
1938 (insert "\n\n" newitem " ")))
1939
1940 ;; FIXME: Isn't this a `defconst'?
1941 (defvar rst-initial-enums
1942 (let (vals)
1943 (dolist (fmt '("%s." "(%s)" "%s)"))
1944 (dolist (c '("1" "a" "A" "I" "i"))
1945 (push (format fmt c) vals)))
1946 (cons "#." (nreverse vals)))
1947 "List of initial enumerations.")
1948
1949 ;; FIXME: Isn't this a `defconst'?
1950 (defvar rst-initial-items
1951 (append (mapcar 'char-to-string rst-bullets) rst-initial-enums)
1952 "List of initial items. It's collection of bullets and enumerations.")
1953
1954 (defun rst-insert-list-new-item ()
1955 "Insert a new list item.
1956
1957 User is asked to select the item style first, for example (a), i), +. Use TAB
1958 for completion and choices.
1959
1960 If user selects bullets or #, it's just added with position arranged by
1961 `rst-insert-list-pos'.
1962
1963 If user selects enumerations, a further prompt is given. User need to input a
1964 starting item, for example 'e' for 'A)' style. The position is also arranged by
1965 `rst-insert-list-pos'."
1966 (interactive)
1967 ;; FIXME: Make this comply to `interactive' standards.
1968 (let* ((itemstyle (completing-read
1969 "Select preferred item style [#.]: "
1970 rst-initial-items nil t nil nil "#."))
1971 (cnt (if (string-match (rst-re 'cntexp-tag) itemstyle)
1972 (match-string 0 itemstyle)))
1973 (no
1974 (save-match-data
1975 ;; FIXME: Make this comply to `interactive' standards.
1976 (cond
1977 ((equal cnt "a")
1978 (let ((itemno (read-string "Give starting value [a]: "
1979 nil nil "a")))
1980 (downcase (substring itemno 0 1))))
1981 ((equal cnt "A")
1982 (let ((itemno (read-string "Give starting value [A]: "
1983 nil nil "A")))
1984 (upcase (substring itemno 0 1))))
1985 ((equal cnt "I")
1986 (let ((itemno (read-number "Give starting value [1]: " 1)))
1987 (rst-arabic-to-roman itemno)))
1988 ((equal cnt "i")
1989 (let ((itemno (read-number "Give starting value [1]: " 1)))
1990 (downcase (rst-arabic-to-roman itemno))))
1991 ((equal cnt "1")
1992 (let ((itemno (read-number "Give starting value [1]: " 1)))
1993 (number-to-string itemno)))))))
1994 (if no
1995 (setq itemstyle (replace-match no t t itemstyle)))
1996 (rst-insert-list-pos itemstyle)))
1997
1998 (defcustom rst-preferred-bullets
1999 '(?* ?- ?+)
2000 "List of favorite bullets."
2001 :group 'rst
2002 :type `(repeat
2003 (choice ,@(mapcar (lambda (char)
2004 (list 'const
2005 :tag (char-to-string char) char))
2006 rst-bullets)))
2007 :package-version '(rst . "1.1.0"))
2008
2009 (defun rst-insert-list-continue (curitem prefer-roman)
2010 "Insert a list item with list start CURITEM including its indentation level.
2011 If PREFER-ROMAN roman numbering is preferred over using letters."
2012 (end-of-line)
2013 (insert
2014 "\n" ; FIXME: Separating lines must be possible.
2015 (cond
2016 ((string-match (rst-re '(:alt enmaut-tag
2017 bul-tag)) curitem)
2018 curitem)
2019 ((string-match (rst-re 'num-tag) curitem)
2020 (replace-match (number-to-string
2021 (1+ (string-to-number (match-string 0 curitem))))
2022 nil nil curitem))
2023 ((and (string-match (rst-re 'rom-tag) curitem)
2024 (save-match-data
2025 (if (string-match (rst-re 'ltr-tag) curitem) ; Also a letter tag.
2026 (save-excursion
2027 ;; FIXME: Assumes one line list items without separating
2028 ;; empty lines.
2029 (if (and (zerop (forward-line -1))
2030 (looking-at (rst-re 'enmexp-beg)))
2031 (string-match
2032 (rst-re 'rom-tag)
2033 (match-string 0)) ; Previous was a roman tag.
2034 prefer-roman)) ; Don't know - use flag.
2035 t))) ; Not a letter tag.
2036 (replace-match
2037 (let* ((old (match-string 0 curitem))
2038 (new (save-match-data
2039 (rst-arabic-to-roman
2040 (1+ (rst-roman-to-arabic
2041 (upcase old)))))))
2042 (if (equal old (upcase old))
2043 (upcase new)
2044 (downcase new)))
2045 t nil curitem))
2046 ((string-match (rst-re 'ltr-tag) curitem)
2047 (replace-match (char-to-string
2048 (1+ (string-to-char (match-string 0 curitem))))
2049 nil nil curitem)))))
2050
2051
2052 (defun rst-insert-list (&optional prefer-roman)
2053 "Insert a list item at the current point.
2054
2055 The command can insert a new list or a continuing list. When it is called at a
2056 non-list line, it will promote to insert new list. When it is called at a list
2057 line, it will insert a list with the same list style.
2058
2059 1. When inserting a new list:
2060
2061 User is asked to select the item style first, for example (a), i), +. Use TAB
2062 for completion and choices.
2063
2064 (a) If user selects bullets or #, it's just added.
2065 (b) If user selects enumerations, a further prompt is given. User needs to
2066 input a starting item, for example 'e' for 'A)' style.
2067
2068 The position of the new list is arranged according to whether or not the
2069 current line and the previous line are blank lines.
2070
2071 2. When continuing a list, one thing need to be noticed:
2072
2073 List style alphabetical list, such as 'a.', and roman numerical list, such as
2074 'i.', have some overlapping items, for example 'v.' The function can deal with
2075 the problem elegantly in most situations. But when those overlapped list are
2076 preceded by a blank line, it is hard to determine which type to use
2077 automatically. The function uses alphabetical list by default. If you want
2078 roman numerical list, just use a prefix to set PREFER-ROMAN."
2079 (interactive "P")
2080 (beginning-of-line)
2081 (if (looking-at (rst-re 'itmany-beg-1))
2082 (rst-insert-list-continue (match-string 0) prefer-roman)
2083 (rst-insert-list-new-item)))
2084
2085 (defun rst-straighten-bullets-region (beg end)
2086 "Make all the bulleted list items in the region consistent.
2087 The region is specified between BEG and END. You can use this
2088 after you have merged multiple bulleted lists to make them use
2089 the same/correct/consistent bullet characters.
2090
2091 See variable `rst-preferred-bullets' for the list of bullets to
2092 adjust. If bullets are found on levels beyond the
2093 `rst-preferred-bullets' list, they are not modified."
2094 (interactive "r")
2095
2096 (let ((bullets (rst-find-pfx-in-region beg end (rst-re 'bul-sta)))
2097 (levtable (make-hash-table :size 4)))
2098
2099 ;; Create a map of levels to list of positions.
2100 (dolist (x bullets)
2101 (let ((key (cdr x)))
2102 (puthash key
2103 (append (gethash key levtable (list))
2104 (list (car x)))
2105 levtable)))
2106
2107 ;; Sort this map and create a new map of prefix char and list of positions.
2108 (let ((poslist ())) ; List of (indent . positions).
2109 (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
2110
2111 (let ((bullets rst-preferred-bullets))
2112 (dolist (x (sort poslist 'car-less-than-car))
2113 (when bullets
2114 ;; Apply the characters.
2115 (dolist (pos (cdr x))
2116 (goto-char pos)
2117 (delete-char 1)
2118 (insert (string (car bullets))))
2119 (setq bullets (cdr bullets))))))))
2120
2121 \f
2122 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2123 ;; Table of contents
2124 ;; =================
2125
2126 (defun rst-get-stripped-line ()
2127 "Return the line at cursor, stripped from whitespace."
2128 (re-search-forward (rst-re "\\S .*\\S ") (line-end-position))
2129 (buffer-substring-no-properties (match-beginning 0)
2130 (match-end 0)) )
2131
2132 (defun rst-section-tree ()
2133 "Get the hierarchical tree of section titles.
2134
2135 Returns a hierarchical tree of the sections titles in the
2136 document. This can be used to generate a table of contents for
2137 the document. The top node will always be a nil node, with the
2138 top level titles as children (there may potentially be more than
2139 one).
2140
2141 Each section title consists in a cons of the stripped title
2142 string and a marker to the section in the original text document.
2143
2144 If there are missing section levels, the section titles are
2145 inserted automatically, and the title string is set to nil, and
2146 the marker set to the first non-nil child of itself.
2147 Conceptually, the nil nodes--i.e.\ those which have no title--are
2148 to be considered as being the same line as their first non-nil
2149 child. This has advantages later in processing the graph."
2150
2151 (let ((hier (rst-get-hierarchy))
2152 (levels (make-hash-table :test 'equal :size 10))
2153 lines)
2154
2155 (let ((lev 0))
2156 (dolist (ado hier)
2157 ;; Compare just the character and indent in the hash table.
2158 (puthash (cons (car ado) (cadr ado)) lev levels)
2159 (incf lev)))
2160
2161 ;; Create a list of lines that contains (text, level, marker) for each
2162 ;; adornment.
2163 (save-excursion
2164 (setq lines
2165 (mapcar (lambda (ado)
2166 (goto-char (point-min))
2167 (forward-line (1- (car ado)))
2168 (list (gethash (cons (cadr ado) (caddr ado)) levels)
2169 (rst-get-stripped-line)
2170 (progn
2171 (beginning-of-line 1)
2172 (point-marker))))
2173 (rst-find-all-adornments))))
2174 (let ((lcontnr (cons nil lines)))
2175 (rst-section-tree-rec lcontnr -1))))
2176
2177
2178 (defun rst-section-tree-rec (ados lev)
2179 "Recursive guts of the section tree construction.
2180 ADOS is a cons cell whose cdr is the remaining list of
2181 adornments, and we change it as we consume them. LEV is
2182 the current level of that node. This function returns a
2183 pair of the subtree that was built. This treats the ADOS
2184 list destructively."
2185
2186 (let ((nado (cadr ados))
2187 node
2188 children)
2189
2190 ;; If the next adornment matches our level.
2191 (when (and nado (= (car nado) lev))
2192 ;; Pop the next adornment and create the current node with it.
2193 (setcdr ados (cddr ados))
2194 (setq node (cdr nado)) )
2195 ;; Else we let the node title/marker be unset.
2196
2197 ;; Build the child nodes.
2198 (while (and (cdr ados) (> (caadr ados) lev))
2199 (setq children
2200 (cons (rst-section-tree-rec ados (1+ lev))
2201 children)))
2202 (setq children (reverse children))
2203
2204 ;; If node is still unset, we use the marker of the first child.
2205 (when (eq node nil)
2206 (setq node (cons nil (cdaar children))))
2207
2208 ;; Return this node with its children.
2209 (cons node children)
2210 ))
2211
2212
2213 (defun rst-section-tree-point (node &optional point)
2214 "Find tree node at point.
2215 Given a computed and valid section tree in NODE and a point
2216 POINT (default being the current point in the current buffer),
2217 find and return the node within the section tree where the cursor
2218 lives.
2219
2220 Return values: a pair of (parent path, container subtree).
2221 The parent path is simply a list of the nodes above the
2222 container subtree node that we're returning."
2223
2224 (let (path outtree)
2225
2226 (let* ((curpoint (or point (point))))
2227
2228 ;; Check if we are before the current node.
2229 (if (and (cadar node) (>= curpoint (cadar node)))
2230
2231 ;; Iterate all the children, looking for one that might contain the
2232 ;; current section.
2233 (let ((curnode (cdr node))
2234 last)
2235
2236 (while (and curnode (>= curpoint (cadaar curnode)))
2237 (setq last curnode
2238 curnode (cdr curnode)))
2239
2240 (if last
2241 (let ((sub (rst-section-tree-point (car last) curpoint)))
2242 (setq path (car sub)
2243 outtree (cdr sub)))
2244 (setq outtree node))
2245
2246 )))
2247 (cons (cons (car node) path) outtree)
2248 ))
2249
2250
2251 (defgroup rst-toc nil
2252 "Settings for reStructuredText table of contents."
2253 :group 'rst
2254 :version "21.1")
2255
2256 (defcustom rst-toc-indent 2
2257 "Indentation for table-of-contents display.
2258 Also used for formatting insertion, when numbering is disabled."
2259 :group 'rst-toc)
2260
2261 (defcustom rst-toc-insert-style 'fixed
2262 "Insertion style for table-of-contents.
2263 Set this to one of the following values to determine numbering and
2264 indentation style:
2265 - plain: no numbering (fixed indentation)
2266 - fixed: numbering, but fixed indentation
2267 - aligned: numbering, titles aligned under each other
2268 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
2269 :group 'rst-toc)
2270
2271 (defcustom rst-toc-insert-number-separator " "
2272 "Separator that goes between the TOC number and the title."
2273 :group 'rst-toc)
2274
2275 ;; This is used to avoid having to change the user's mode.
2276 (defvar rst-toc-insert-click-keymap
2277 (let ((map (make-sparse-keymap)))
2278 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
2279 map)
2280 "(Internal) What happens when you click on propertized text in the TOC.")
2281
2282 (defcustom rst-toc-insert-max-level nil
2283 "If non-nil, maximum depth of the inserted TOC."
2284 :group 'rst-toc)
2285
2286
2287 (defun rst-toc-insert (&optional pfxarg)
2288 "Insert a simple text rendering of the table of contents.
2289 By default the top level is ignored if there is only one, because
2290 we assume that the document will have a single title.
2291
2292 If a numeric prefix argument PFXARG is given, insert the TOC up
2293 to the specified level.
2294
2295 The TOC is inserted indented at the current column."
2296 (interactive "P")
2297 (rst-reset-section-caches)
2298 (let* (;; Check maximum level override.
2299 (rst-toc-insert-max-level
2300 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
2301 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
2302
2303 ;; Get the section tree for the current cursor point.
2304 (sectree-pair
2305 (rst-section-tree-point
2306 (rst-section-tree)))
2307
2308 ;; Figure out initial indent.
2309 (initial-indent (make-string (current-column) ? ))
2310 (init-point (point)))
2311
2312 (when (cddr sectree-pair)
2313 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
2314
2315 ;; Fixup for the first line.
2316 (delete-region init-point (+ init-point (length initial-indent)))
2317
2318 ;; Delete the last newline added.
2319 (delete-char -1)
2320 )))
2321
2322 (defun rst-toc-insert-node (node level indent pfx)
2323 "Insert tree node NODE in table-of-contents.
2324 Recursive function that does printing of the inserted toc.
2325 LEVEL is the depth level of the sections in the tree.
2326 INDENT is the indentation string. PFX is the prefix numbering,
2327 that includes the alignment necessary for all the children of
2328 level to align."
2329
2330 ;; Note: we do child numbering from the parent, so we start number the
2331 ;; children one level before we print them.
2332 (let ((do-print (> level 0))
2333 (count 1))
2334 (when do-print
2335 (insert indent)
2336 (let ((b (point)))
2337 (unless (equal rst-toc-insert-style 'plain)
2338 (insert pfx rst-toc-insert-number-separator))
2339 (insert (or (caar node) "[missing node]"))
2340 ;; Add properties to the text, even though in normal text mode it
2341 ;; won't be doing anything for now. Not sure that I want to change
2342 ;; mode stuff. At least the highlighting gives the idea that this
2343 ;; is generated automatically.
2344 (put-text-property b (point) 'mouse-face 'highlight)
2345 (put-text-property b (point) 'rst-toc-target (cadar node))
2346 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
2347
2348 )
2349 (insert "\n")
2350
2351 ;; Prepare indent for children.
2352 (setq indent
2353 (cond
2354 ((eq rst-toc-insert-style 'plain)
2355 (concat indent (make-string rst-toc-indent ? )))
2356
2357 ((eq rst-toc-insert-style 'fixed)
2358 (concat indent (make-string rst-toc-indent ? )))
2359
2360 ((eq rst-toc-insert-style 'aligned)
2361 (concat indent (make-string (+ (length pfx) 2) ? )))
2362
2363 ((eq rst-toc-insert-style 'listed)
2364 (concat (substring indent 0 -3)
2365 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
2366 ))
2367 )
2368
2369 (if (or (eq rst-toc-insert-max-level nil)
2370 (< level rst-toc-insert-max-level))
2371 (let ((do-child-numbering (>= level 0))
2372 fmt)
2373 (if do-child-numbering
2374 (progn
2375 ;; Add a separating dot if there is already a prefix.
2376 (when (> (length pfx) 0)
2377 (string-match (rst-re "[ \t\n]*\\'") pfx)
2378 (setq pfx (concat (replace-match "" t t pfx) ".")))
2379
2380 ;; Calculate the amount of space that the prefix will require
2381 ;; for the numbers.
2382 (if (cdr node)
2383 (setq fmt (format "%%-%dd"
2384 (1+ (floor (log10 (length
2385 (cdr node))))))))
2386 ))
2387
2388 (dolist (child (cdr node))
2389 (rst-toc-insert-node child
2390 (1+ level)
2391 indent
2392 (if do-child-numbering
2393 (concat pfx (format fmt count)) pfx))
2394 (incf count)))
2395
2396 )))
2397
2398
2399 (defun rst-toc-update ()
2400 "Automatically find the contents section of a document and update.
2401 Updates the inserted TOC if present. You can use this in your
2402 file-write hook to always make it up-to-date automatically."
2403 (interactive)
2404 (save-excursion
2405 ;; Find and delete an existing comment after the first contents directive.
2406 ;; Delete that region.
2407 (goto-char (point-min))
2408 ;; We look for the following and the following only (in other words, if your
2409 ;; syntax differs, this won't work.).
2410 ;;
2411 ;; .. contents:: [...anything here...]
2412 ;; [:field: value]...
2413 ;; ..
2414 ;; XXXXXXXX
2415 ;; XXXXXXXX
2416 ;; [more lines]
2417 (let ((beg (re-search-forward
2418 (rst-re "^" 'exm-sta "contents" 'dcl-tag ".*\n"
2419 "\\(?:" 'hws-sta 'fld-tag ".*\n\\)*" 'exm-tag) nil t))
2420 last-real)
2421 (when beg
2422 ;; Look for the first line that starts at the first column.
2423 (forward-line 1)
2424 (while (and
2425 (< (point) (point-max))
2426 (or (if (looking-at
2427 (rst-re 'hws-sta "\\S ")) ; indented content.
2428 (setq last-real (point)))
2429 (looking-at (rst-re 'lin-end)))) ; empty line.
2430 (forward-line 1))
2431 (if last-real
2432 (progn
2433 (goto-char last-real)
2434 (end-of-line)
2435 (delete-region beg (point)))
2436 (goto-char beg))
2437 (insert "\n ")
2438 (rst-toc-insert))))
2439 ;; Note: always return nil, because this may be used as a hook.
2440 nil)
2441
2442 ;; Note: we cannot bind the TOC update on file write because it messes with
2443 ;; undo. If we disable undo, since it adds and removes characters, the
2444 ;; positions in the undo list are not making sense anymore. Dunno what to do
2445 ;; with this, it would be nice to update when saving.
2446 ;;
2447 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
2448 ;; (defun rst-toc-update-fun ()
2449 ;; ;; Disable undo for the write file hook.
2450 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
2451
2452 (defalias 'rst-toc-insert-update 'rst-toc-update) ; backwards compat.
2453
2454 ;;------------------------------------------------------------------------------
2455
2456 (defun rst-toc-node (node level)
2457 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
2458
2459 (if (> level 0)
2460 (let ((b (point)))
2461 ;; Insert line text.
2462 (insert (make-string (* rst-toc-indent (1- level)) ? ))
2463 (insert (or (caar node) "[missing node]"))
2464
2465 ;; Highlight lines.
2466 (put-text-property b (point) 'mouse-face 'highlight)
2467
2468 ;; Add link on lines.
2469 (put-text-property b (point) 'rst-toc-target (cadar node))
2470
2471 (insert "\n")
2472 ))
2473
2474 (dolist (child (cdr node))
2475 (rst-toc-node child (1+ level))))
2476
2477 (defun rst-toc-count-lines (node target-node)
2478 "Count the number of lines from NODE to the TARGET-NODE node.
2479 This recursive function returns a cons of the number of
2480 additional lines that have been counted for its node and
2481 children, and t if the node has been found."
2482
2483 (let ((count 1)
2484 found)
2485 (if (eq node target-node)
2486 (setq found t)
2487 (let ((child (cdr node)))
2488 (while (and child (not found))
2489 (let ((cl (rst-toc-count-lines (car child) target-node)))
2490 (setq count (+ count (car cl))
2491 found (cdr cl)
2492 child (cdr child))))))
2493 (cons count found)))
2494
2495 (defvar rst-toc-buffer-name "*Table of Contents*"
2496 "Name of the Table of Contents buffer.")
2497
2498 (defvar rst-toc-return-wincfg nil
2499 "Window configuration to which to return when leaving the TOC.")
2500
2501
2502 (defun rst-toc ()
2503 "Display a table-of-contents.
2504 Finds all the section titles and their adornments in the
2505 file, and displays a hierarchically-organized list of the
2506 titles, which is essentially a table-of-contents of the
2507 document.
2508
2509 The Emacs buffer can be navigated, and selecting a section
2510 brings the cursor in that section."
2511 (interactive)
2512 (rst-reset-section-caches)
2513 (let* ((curbuf (list (current-window-configuration) (point-marker)))
2514 (sectree (rst-section-tree))
2515
2516 (our-node (cdr (rst-section-tree-point sectree)))
2517 line
2518
2519 ;; Create a temporary buffer.
2520 (buf (get-buffer-create rst-toc-buffer-name))
2521 )
2522
2523 (with-current-buffer buf
2524 (let ((inhibit-read-only t))
2525 (rst-toc-mode)
2526 (delete-region (point-min) (point-max))
2527 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
2528 (put-text-property (point-min) (point)
2529 'face (list '(background-color . "gray")))
2530 (rst-toc-node sectree 0)
2531
2532 ;; Count the lines to our found node.
2533 (let ((linefound (rst-toc-count-lines sectree our-node)))
2534 (setq line (if (cdr linefound) (car linefound) 0)))
2535 ))
2536 (display-buffer buf)
2537 (pop-to-buffer buf)
2538
2539 ;; Save the buffer to return to.
2540 (set (make-local-variable 'rst-toc-return-wincfg) curbuf)
2541
2542 ;; Move the cursor near the right section in the TOC.
2543 (goto-char (point-min))
2544 (forward-line (1- line))
2545 ))
2546
2547
2548 (defun rst-toc-mode-find-section ()
2549 "Get the section from text property at point."
2550 (let ((pos (get-text-property (point) 'rst-toc-target)))
2551 (unless pos
2552 (error "No section on this line"))
2553 (unless (buffer-live-p (marker-buffer pos))
2554 (error "Buffer for this section was killed"))
2555 pos))
2556
2557 ;; FIXME: Cursor before or behind the list must be handled properly; before the
2558 ;; list should jump to the top and behind the list to the last normal
2559 ;; paragraph.
2560 (defun rst-goto-section (&optional kill)
2561 "Go to the section the current line describes.
2562 If KILL a toc buffer is destroyed."
2563 (interactive)
2564 (let ((pos (rst-toc-mode-find-section)))
2565 (when kill
2566 ;; FIXME: This should rather go to `rst-toc-mode-goto-section'.
2567 (set-window-configuration (car rst-toc-return-wincfg))
2568 (kill-buffer (get-buffer rst-toc-buffer-name)))
2569 (pop-to-buffer (marker-buffer pos))
2570 (goto-char pos)
2571 ;; FIXME: make the recentering conditional on scroll.
2572 (recenter 5)))
2573
2574 (defun rst-toc-mode-goto-section ()
2575 "Go to the section the current line describes and kill the TOC buffer."
2576 (interactive)
2577 (rst-goto-section t))
2578
2579 (defun rst-toc-mode-mouse-goto (event)
2580 "In `rst-toc' mode, go to the occurrence whose line you click on.
2581 EVENT is the input event."
2582 (interactive "e")
2583 (let ((pos
2584 (with-current-buffer (window-buffer (posn-window (event-end event)))
2585 (save-excursion
2586 (goto-char (posn-point (event-end event)))
2587 (rst-toc-mode-find-section)))))
2588 (pop-to-buffer (marker-buffer pos))
2589 (goto-char pos)
2590 (recenter 5)))
2591
2592 (defun rst-toc-mode-mouse-goto-kill (event)
2593 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well.
2594 EVENT is the input event."
2595 (interactive "e")
2596 (call-interactively 'rst-toc-mode-mouse-goto event)
2597 (kill-buffer (get-buffer rst-toc-buffer-name)))
2598
2599 (defun rst-toc-quit-window ()
2600 "Leave the current TOC buffer."
2601 (interactive)
2602 (let ((retbuf rst-toc-return-wincfg))
2603 (set-window-configuration (car retbuf))
2604 (goto-char (cadr retbuf))))
2605
2606 (defvar rst-toc-mode-map
2607 (let ((map (make-sparse-keymap)))
2608 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2609 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2610 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2611 (define-key map "f" 'rst-toc-mode-goto-section)
2612 (define-key map "q" 'rst-toc-quit-window)
2613 (define-key map "z" 'kill-this-buffer)
2614 map)
2615 "Keymap for `rst-toc-mode'.")
2616
2617 (put 'rst-toc-mode 'mode-class 'special)
2618
2619 ;; Could inherit from the new `special-mode'.
2620 (define-derived-mode rst-toc-mode nil "ReST-TOC"
2621 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2622 (setq buffer-read-only t))
2623
2624 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2625 ;; features.
2626
2627 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2628 ;; Section movement commands
2629 ;; =========================
2630
2631 (defun rst-forward-section (&optional offset)
2632 "Skip to the next reStructuredText section title.
2633 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2634 backwards in the file (default is to use 1)."
2635 (interactive)
2636 (rst-reset-section-caches)
2637 (let* (;; Default value for offset.
2638 (offset (or offset 1))
2639
2640 ;; Get all the adornments in the file, with their line numbers.
2641 (allados (rst-find-all-adornments))
2642
2643 ;; Get the current line.
2644 (curline (line-number-at-pos))
2645
2646 (cur allados)
2647 (idx 0)
2648 )
2649
2650 ;; Find the index of the "next" adornment w.r.t. to the current line.
2651 (while (and cur (< (caar cur) curline))
2652 (setq cur (cdr cur))
2653 (incf idx))
2654 ;; 'cur' is the adornment on or following the current line.
2655
2656 (if (and (> offset 0) cur (= (caar cur) curline))
2657 (incf idx))
2658
2659 ;; Find the final index.
2660 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2661 (setq cur (nth idx allados))
2662
2663 ;; If the index is positive, goto the line, otherwise go to the buffer
2664 ;; boundaries.
2665 (if (and cur (>= idx 0))
2666 (progn
2667 (goto-char (point-min))
2668 (forward-line (1- (car cur))))
2669 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
2670 ))
2671
2672 (defun rst-backward-section ()
2673 "Like `rst-forward-section', except move back one title."
2674 (interactive)
2675 (rst-forward-section -1))
2676
2677 ;; FIXME: What is `allow-extend' for?
2678 (defun rst-mark-section (&optional count allow-extend)
2679 "Select COUNT sections around point.
2680 Mark following sections for positive COUNT or preceding sections
2681 for negative COUNT."
2682 ;; Cloned from mark-paragraph.
2683 (interactive "p\np")
2684 (unless count (setq count 1))
2685 (when (zerop count)
2686 (error "Cannot mark zero sections"))
2687 (cond ((and allow-extend
2688 (or (and (eq last-command this-command) (mark t))
2689 (rst-portable-mark-active-p)))
2690 (set-mark
2691 (save-excursion
2692 (goto-char (mark))
2693 (rst-forward-section count)
2694 (point))))
2695 (t
2696 (rst-forward-section count)
2697 (push-mark nil t t)
2698 (rst-forward-section (- count)))))
2699
2700 \f
2701 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2702 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2703 ;; always 2 or 3 characters apart horizontally with rest.
2704
2705 (defun rst-find-leftmost-column (beg end)
2706 "Return the leftmost column in region BEG to END."
2707 (let (mincol)
2708 (save-excursion
2709 (goto-char beg)
2710 (while (< (point) end)
2711 (back-to-indentation)
2712 (unless (looking-at (rst-re 'lin-end))
2713 (setq mincol (if mincol
2714 (min mincol (current-column))
2715 (current-column))))
2716 (forward-line 1)))
2717 mincol))
2718
2719 ;; FIXME: This definition is old and deprecated. We need to move to the newer
2720 ;; version below.
2721 (defmacro rst-iterate-leftmost-paragraphs
2722 (beg end first-only body-consequent body-alternative)
2723 ;; FIXME: The following comment is pretty useless.
2724 "Call FUN at the beginning of each line, with an argument that
2725 specifies whether we are at the first line of a paragraph that
2726 starts at the leftmost column of the given region BEG and END.
2727 Set FIRST-ONLY to true if you want to callback on the first line
2728 of each paragraph only."
2729 `(save-excursion
2730 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2731 (endm (copy-marker ,end)))
2732
2733 (do* (;; Iterate lines.
2734 (l (progn (goto-char ,beg) (back-to-indentation))
2735 (progn (forward-line 1) (back-to-indentation)))
2736
2737 (previous nil valid)
2738
2739 (curcol (current-column)
2740 (current-column))
2741
2742 (valid (and (= curcol leftcol)
2743 (not (looking-at (rst-re 'lin-end))))
2744 (and (= curcol leftcol)
2745 (not (looking-at (rst-re 'lin-end)))))
2746 )
2747 ((>= (point) endm))
2748
2749 (if (if ,first-only
2750 (and valid (not previous))
2751 valid)
2752 ,body-consequent
2753 ,body-alternative)
2754
2755 ))))
2756
2757 ;; FIXME: This needs to be refactored. Probably this is simply a function
2758 ;; applying BODY rather than a macro.
2759 (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2760 "Evaluate BODY for each line in region defined by BEG END.
2761 LEFTMOST is set to true if the line is one of the leftmost of the
2762 entire paragraph. PARABEGIN is set to true if the line is the
2763 first of a paragraph."
2764 (declare (indent 1) (debug (sexp body)))
2765 (destructuring-bind
2766 (beg end parabegin leftmost isleftmost isempty) spec
2767
2768 `(save-excursion
2769 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2770 (endm (copy-marker ,end)))
2771
2772 (do* (;; Iterate lines.
2773 (l (progn (goto-char ,beg) (back-to-indentation))
2774 (progn (forward-line 1) (back-to-indentation)))
2775
2776 (empty-line-previous nil ,isempty)
2777
2778 (,isempty (looking-at (rst-re 'lin-end))
2779 (looking-at (rst-re 'lin-end)))
2780
2781 (,parabegin (not ,isempty)
2782 (and empty-line-previous
2783 (not ,isempty)))
2784
2785 (,isleftmost (and (not ,isempty)
2786 (= (current-column) ,leftmost))
2787 (and (not ,isempty)
2788 (= (current-column) ,leftmost)))
2789 )
2790 ((>= (point) endm))
2791
2792 (progn ,@body)
2793
2794 )))))
2795
2796 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2797 ;; Indentation
2798
2799 ;; FIXME: At the moment only block comments with leading empty comment line are
2800 ;; supported. Comment lines with leading comment markup should be also
2801 ;; supported. May be a customizable option could control which style to
2802 ;; prefer.
2803
2804 (defgroup rst-indent nil "Settings for indentation in reStructuredText.
2805
2806 In reStructuredText indentation points are usually determined by
2807 preceding lines. Sometimes the syntax allows arbitrary
2808 indentation points such as where to start the first line
2809 following a directive. These indentation widths can be customized
2810 here."
2811 :group 'rst
2812 :package-version '(rst . "1.1.0"))
2813
2814 (define-obsolete-variable-alias
2815 'rst-shift-basic-offset 'rst-indent-width "1.0.0")
2816 (defcustom rst-indent-width 2
2817 "Indentation when there is no more indentation point given."
2818 :group 'rst-indent
2819 :type '(integer))
2820
2821 (defcustom rst-indent-field 3
2822 "Indentation for first line after a field or 0 to always indent for content."
2823 :group 'rst-indent
2824 :type '(integer))
2825
2826 (defcustom rst-indent-literal-normal 3
2827 "Default indentation for literal block after a markup on an own line."
2828 :group 'rst-indent
2829 :type '(integer))
2830
2831 (defcustom rst-indent-literal-minimized 2
2832 "Default indentation for literal block after a minimized markup."
2833 :group 'rst-indent
2834 :type '(integer))
2835
2836 (defcustom rst-indent-comment 3
2837 "Default indentation for first line of a comment."
2838 :group 'rst-indent
2839 :type '(integer))
2840
2841 ;; FIXME: Must consider other tabs:
2842 ;; * Line blocks
2843 ;; * Definition lists
2844 ;; * Option lists
2845 (defun rst-line-tabs ()
2846 "Return tabs of the current line or nil for no tab.
2847 The list is sorted so the tab where writing continues most likely
2848 is the first one. Each tab is of the form (COLUMN . INNER).
2849 COLUMN is the column of the tab. INNER is non-nil if this is an
2850 inner tab. I.e. a tab which does come from the basic indentation
2851 and not from inner alignment points."
2852 (save-excursion
2853 (forward-line 0)
2854 (save-match-data
2855 (unless (looking-at (rst-re 'lin-end))
2856 (back-to-indentation)
2857 ;; Current indentation is always the least likely tab.
2858 (let ((tabs (list (list (point) 0 nil)))) ; (POINT OFFSET INNER)
2859 ;; Push inner tabs more likely to continue writing.
2860 (cond
2861 ;; Item.
2862 ((looking-at (rst-re '(:grp itmany-tag hws-sta) '(:grp "\\S ") "?"))
2863 (when (match-string 2)
2864 (push (list (match-beginning 2) 0 t) tabs)))
2865 ;; Field.
2866 ((looking-at (rst-re '(:grp fld-tag) '(:grp hws-tag)
2867 '(:grp "\\S ") "?"))
2868 (unless (zerop rst-indent-field)
2869 (push (list (match-beginning 1) rst-indent-field t) tabs))
2870 (if (match-string 3)
2871 (push (list (match-beginning 3) 0 t) tabs)
2872 (if (zerop rst-indent-field)
2873 (push (list (match-end 2)
2874 (if (string= (match-string 2) "") 1 0)
2875 t) tabs))))
2876 ;; Directive.
2877 ((looking-at (rst-re 'dir-sta-3 '(:grp "\\S ") "?"))
2878 (push (list (match-end 1) 0 t) tabs)
2879 (unless (string= (match-string 2) "")
2880 (push (list (match-end 2) 0 t) tabs))
2881 (when (match-string 4)
2882 (push (list (match-beginning 4) 0 t) tabs)))
2883 ;; Footnote or citation definition.
2884 ((looking-at (rst-re 'fnc-sta-2 '(:grp "\\S ") "?"))
2885 (push (list (match-end 1) 0 t) tabs)
2886 (when (match-string 3)
2887 (push (list (match-beginning 3) 0 t) tabs)))
2888 ;; Comment.
2889 ((looking-at (rst-re 'cmt-sta-1))
2890 (push (list (point) rst-indent-comment t) tabs)))
2891 ;; Start of literal block.
2892 (when (looking-at (rst-re 'lit-sta-2))
2893 (let ((tab0 (first tabs)))
2894 (push (list (first tab0)
2895 (+ (second tab0)
2896 (if (match-string 1)
2897 rst-indent-literal-minimized
2898 rst-indent-literal-normal))
2899 t) tabs)))
2900 (mapcar (lambda (tab)
2901 (goto-char (first tab))
2902 (cons (+ (current-column) (second tab)) (third tab)))
2903 tabs))))))
2904
2905 (defun rst-compute-tabs (pt)
2906 "Build the list of possible tabs for all lines above.
2907 Search backwards from point PT to build the list of possible
2908 tabs. Return a list of tabs sorted by likeliness to continue
2909 writing like `rst-line-tabs'. Nearer lines have generally a
2910 higher likeliness than farther lines. Return nil if no tab is found
2911 in the text above."
2912 (save-excursion
2913 (goto-char pt)
2914 (let (leftmost ; Leftmost column found so far.
2915 innermost ; Leftmost column for inner tab.
2916 tablist)
2917 (while (and (zerop (forward-line -1))
2918 (or (not leftmost)
2919 (> leftmost 0)))
2920 (let* ((tabs (rst-line-tabs))
2921 (leftcol (if tabs (apply 'min (mapcar 'car tabs)))))
2922 (when tabs
2923 ;; Consider only lines indented less or same if not INNERMOST.
2924 (when (or (not leftmost)
2925 (< leftcol leftmost)
2926 (and (not innermost) (= leftcol leftmost)))
2927 (dolist (tab tabs)
2928 (let ((inner (cdr tab))
2929 (newcol (car tab)))
2930 (when (and
2931 (or
2932 (and (not inner)
2933 (or (not leftmost)
2934 (< newcol leftmost)))
2935 (and inner
2936 (or (not innermost)
2937 (< newcol innermost))))
2938 (not (memq newcol tablist)))
2939 (push newcol tablist))))
2940 (setq innermost (if (rst-some (mapcar 'cdr tabs)) ; Has inner.
2941 leftcol
2942 innermost))
2943 (setq leftmost leftcol)))))
2944 (nreverse tablist))))
2945
2946 (defun rst-indent-line (&optional dflt)
2947 "Indent current line to next best reStructuredText tab.
2948 The next best tab is taken from the tab list returned by
2949 `rst-compute-tabs' which is used in a cyclic manner. If the
2950 current indentation does not end on a tab use the first one. If
2951 the current indentation is on a tab use the next tab. This allows
2952 a repeated use of \\[indent-for-tab-command] to cycle through all
2953 possible tabs. If no indentation is possible return `noindent' or
2954 use DFLT. Return the indentation indented to. When point is in
2955 indentation it ends up at its end. Otherwise the point is kept
2956 relative to the content."
2957 (let* ((pt (point-marker))
2958 (cur (current-indentation))
2959 (clm (current-column))
2960 (tabs (rst-compute-tabs (point)))
2961 (fnd (rst-position cur tabs))
2962 ind)
2963 (if (and (not tabs) (not dflt))
2964 'noindent
2965 (if (not tabs)
2966 (setq ind dflt)
2967 (if (not fnd)
2968 (setq fnd 0)
2969 (setq fnd (1+ fnd))
2970 (if (>= fnd (length tabs))
2971 (setq fnd 0)))
2972 (setq ind (nth fnd tabs)))
2973 (indent-line-to ind)
2974 (if (> clm cur)
2975 (goto-char pt))
2976 (set-marker pt nil)
2977 ind)))
2978
2979 (defun rst-shift-region (beg end cnt)
2980 "Shift region BEG to END by CNT tabs.
2981 Shift by one tab to the right (CNT > 0) or left (CNT < 0) or
2982 remove all indentation (CNT = 0). A tab is taken from the text
2983 above. If no suitable tab is found `rst-indent-width' is used."
2984 (interactive "r\np")
2985 (let ((tabs (sort (rst-compute-tabs beg) (lambda (x y) (<= x y))))
2986 (leftmostcol (rst-find-leftmost-column beg end)))
2987 (when (or (> leftmostcol 0) (> cnt 0))
2988 ;; Apply the indent.
2989 (indent-rigidly
2990 beg end
2991 (if (zerop cnt)
2992 (- leftmostcol)
2993 ;; Find the next tab after the leftmost column.
2994 (let* ((cmp (if (> cnt 0) '> '<))
2995 (tabs (if (> cnt 0) tabs (reverse tabs)))
2996 (len (length tabs))
2997 (dir (rst-signum cnt)) ; Direction to take.
2998 (abs (abs cnt)) ; Absolute number of steps to take.
2999 ;; Get the position of the first tab beyond leftmostcol.
3000 (fnd (lexical-let ((cmp cmp)
3001 (leftmostcol leftmostcol)) ; Create closure.
3002 (rst-position-if (lambda (elt)
3003 (funcall cmp elt leftmostcol))
3004 tabs)))
3005 ;; Virtual position of tab.
3006 (pos (+ (or fnd len) (1- abs)))
3007 (tab (if (< pos len)
3008 ;; Tab exists - use it.
3009 (nth pos tabs)
3010 ;; Column needs to be computed.
3011 (let ((col (+ (or (car (last tabs)) leftmostcol)
3012 ;; Base on last known column.
3013 (* (- pos (1- len)) ; Distance left.
3014 dir ; Direction to take.
3015 rst-indent-width))))
3016 (if (< col 0) 0 col)))))
3017 (- tab leftmostcol)))))))
3018
3019 ;; FIXME: A paragraph with an (incorrectly) indented second line is not filled
3020 ;; correctly::
3021 ;;
3022 ;; Some start
3023 ;; continued wrong
3024 (defun rst-adaptive-fill ()
3025 "Return fill prefix found at point.
3026 Value for `adaptive-fill-function'."
3027 (let ((fnd (if (looking-at adaptive-fill-regexp)
3028 (match-string-no-properties 0))))
3029 (if (save-match-data
3030 (not (string-match comment-start-skip fnd)))
3031 ;; An non-comment prefix is fine.
3032 fnd
3033 ;; Matches a comment - return whitespace instead.
3034 (make-string (-
3035 (save-excursion
3036 (goto-char (match-end 0))
3037 (current-column))
3038 (save-excursion
3039 (goto-char (match-beginning 0))
3040 (current-column))) ? ))))
3041
3042 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3043 ;; Comments
3044
3045 (defun rst-comment-line-break (&optional soft)
3046 "Break line and indent, continuing reStructuredText comment if within one.
3047 Value for `comment-line-break-function'. If SOFT use soft
3048 newlines as mandated by `comment-line-break-function'."
3049 (if soft
3050 (insert-and-inherit ?\n)
3051 (newline 1))
3052 (save-excursion
3053 (forward-char -1)
3054 (delete-horizontal-space))
3055 (delete-horizontal-space)
3056 (let ((tabs (rst-compute-tabs (point))))
3057 (when tabs
3058 (indent-line-to (car tabs)))))
3059
3060 (defun rst-comment-indent ()
3061 "Return indentation for current comment line."
3062 (car (rst-compute-tabs (point))))
3063
3064 (defun rst-comment-insert-comment ()
3065 "Insert a comment in the current line."
3066 (rst-indent-line 0)
3067 (insert comment-start))
3068
3069 (defun rst-comment-region (beg end &optional arg)
3070 "Comment or uncomment the current region.
3071 Region is from from BEG to END. Uncomment if ARG."
3072 (save-excursion
3073 (if (consp arg)
3074 (rst-uncomment-region beg end arg)
3075 (goto-char beg)
3076 (let ((ind (current-indentation))
3077 bol)
3078 (forward-line 0)
3079 (setq bol (point))
3080 (indent-rigidly bol end rst-indent-comment)
3081 (goto-char bol)
3082 (open-line 1)
3083 (indent-line-to ind)
3084 (insert (comment-string-strip comment-start t t))))))
3085
3086 (defun rst-uncomment-region (beg end &optional arg)
3087 "Uncomment the current region.
3088 Region is from BEG to END. ARG is ignored"
3089 (save-excursion
3090 (let (bol eol)
3091 (goto-char beg)
3092 (forward-line 0)
3093 (setq bol (point))
3094 (forward-line 1)
3095 (setq eol (point))
3096 (indent-rigidly eol end (- rst-indent-comment))
3097 (delete-region bol eol))))
3098
3099 ;;------------------------------------------------------------------------------
3100
3101 ;; FIXME: These next functions should become part of a larger effort to redo
3102 ;; the bullets in bulleted lists. The enumerate would just be one of
3103 ;; the possible outputs.
3104 ;;
3105 ;; FIXME: We need to do the enumeration removal as well.
3106
3107 (defun rst-enumerate-region (beg end all)
3108 "Add enumeration to all the leftmost paragraphs in the given region.
3109 The region is specified between BEG and END. With ALL,
3110 do all lines instead of just paragraphs."
3111 (interactive "r\nP")
3112 (let ((count 0)
3113 (last-insert-len nil))
3114 (rst-iterate-leftmost-paragraphs
3115 beg end (not all)
3116 (let ((ins-string (format "%d. " (incf count))))
3117 (setq last-insert-len (length ins-string))
3118 (insert ins-string))
3119 (insert (make-string last-insert-len ?\ ))
3120 )))
3121
3122 (defun rst-bullet-list-region (beg end all)
3123 "Add bullets to all the leftmost paragraphs in the given region.
3124 The region is specified between BEG and END. With ALL,
3125 do all lines instead of just paragraphs."
3126 (interactive "r\nP")
3127 (rst-iterate-leftmost-paragraphs
3128 beg end (not all)
3129 (insert (car rst-preferred-bullets) " ")
3130 (insert " ")
3131 ))
3132
3133 ;; FIXME: Does not deal with a varying number of digits appropriately.
3134 ;; FIXME: Does not deal with multiple levels independently.
3135 ;; FIXME: Does not indent a multiline item correctly.
3136 (defun rst-convert-bullets-to-enumeration (beg end)
3137 "Convert the bulleted and enumerated items in the region to enumerated lists.
3138 Renumber as necessary. Region is from BEG to END."
3139 (interactive "r")
3140 (let* (;; Find items and convert the positions to markers.
3141 (items (mapcar
3142 (lambda (x)
3143 (cons (copy-marker (car x))
3144 (cdr x)))
3145 (rst-find-pfx-in-region beg end (rst-re 'itmany-sta-1))))
3146 (count 1)
3147 )
3148 (save-excursion
3149 (dolist (x items)
3150 (goto-char (car x))
3151 (looking-at (rst-re 'itmany-beg-1))
3152 (replace-match (format "%d." count) nil nil nil 1)
3153 (incf count)
3154 ))
3155 ))
3156
3157
3158
3159 ;;------------------------------------------------------------------------------
3160
3161 (defun rst-line-block-region (rbeg rend &optional pfxarg)
3162 "Toggle line block prefixes for a region.
3163 Region is from RBEG to REND. With PFXARG set the empty lines too."
3164 (interactive "r\nP")
3165 (let ((comment-start "| ")
3166 (comment-end "")
3167 (comment-start-skip "| ")
3168 (comment-style 'indent)
3169 (force (not (not pfxarg))))
3170 (rst-iterate-leftmost-paragraphs-2
3171 (rbeg rend parbegin leftmost isleft isempty)
3172 (when (or force (not isempty))
3173 (move-to-column leftmost force)
3174 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
3175 (insert "| ")))))
3176
3177
3178 \f
3179 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3180 ;; Font lock
3181 ;; =========
3182
3183 (require 'font-lock)
3184
3185 ;; FIXME: The obsolete variables need to disappear.
3186
3187 ;; The following versions have been done inside Emacs and should not be
3188 ;; replaced by `:package-version' attributes until a change.
3189
3190 (defgroup rst-faces nil "Faces used in Rst Mode."
3191 :group 'rst
3192 :group 'faces
3193 :version "21.1")
3194
3195 (defface rst-block '((t :inherit font-lock-keyword-face))
3196 "Face used for all syntax marking up a special block."
3197 :version "24.1"
3198 :group 'rst-faces)
3199
3200 (defcustom rst-block-face 'rst-block
3201 "All syntax marking up a special block."
3202 :version "24.1"
3203 :group 'rst-faces
3204 :type '(face))
3205 (make-obsolete-variable 'rst-block-face
3206 "customize the face `rst-block' instead."
3207 "24.1")
3208
3209 (defface rst-external '((t :inherit font-lock-type-face))
3210 "Face used for field names and interpreted text."
3211 :version "24.1"
3212 :group 'rst-faces)
3213
3214 (defcustom rst-external-face 'rst-external
3215 "Field names and interpreted text."
3216 :version "24.1"
3217 :group 'rst-faces
3218 :type '(face))
3219 (make-obsolete-variable 'rst-external-face
3220 "customize the face `rst-external' instead."
3221 "24.1")
3222
3223 (defface rst-definition '((t :inherit font-lock-function-name-face))
3224 "Face used for all other defining constructs."
3225 :version "24.1"
3226 :group 'rst-faces)
3227
3228 (defcustom rst-definition-face 'rst-definition
3229 "All other defining constructs."
3230 :version "24.1"
3231 :group 'rst-faces
3232 :type '(face))
3233 (make-obsolete-variable 'rst-definition-face
3234 "customize the face `rst-definition' instead."
3235 "24.1")
3236
3237 ;; XEmacs compatibility (?).
3238 (defface rst-directive (if (boundp 'font-lock-builtin-face)
3239 '((t :inherit font-lock-builtin-face))
3240 '((t :inherit font-lock-preprocessor-face)))
3241 "Face used for directives and roles."
3242 :version "24.1"
3243 :group 'rst-faces)
3244
3245 (defcustom rst-directive-face 'rst-directive
3246 "Directives and roles."
3247 :group 'rst-faces
3248 :type '(face))
3249 (make-obsolete-variable 'rst-directive-face
3250 "customize the face `rst-directive' instead."
3251 "24.1")
3252
3253 (defface rst-comment '((t :inherit font-lock-comment-face))
3254 "Face used for comments."
3255 :version "24.1"
3256 :group 'rst-faces)
3257
3258 (defcustom rst-comment-face 'rst-comment
3259 "Comments."
3260 :version "24.1"
3261 :group 'rst-faces
3262 :type '(face))
3263 (make-obsolete-variable 'rst-comment-face
3264 "customize the face `rst-comment' instead."
3265 "24.1")
3266
3267 (defface rst-emphasis1 '((t :inherit italic))
3268 "Face used for simple emphasis."
3269 :version "24.1"
3270 :group 'rst-faces)
3271
3272 (defcustom rst-emphasis1-face 'rst-emphasis1
3273 "Simple emphasis."
3274 :version "24.1"
3275 :group 'rst-faces
3276 :type '(face))
3277 (make-obsolete-variable 'rst-emphasis1-face
3278 "customize the face `rst-emphasis1' instead."
3279 "24.1")
3280
3281 (defface rst-emphasis2 '((t :inherit bold))
3282 "Face used for double emphasis."
3283 :version "24.1"
3284 :group 'rst-faces)
3285
3286 (defcustom rst-emphasis2-face 'rst-emphasis2
3287 "Double emphasis."
3288 :group 'rst-faces
3289 :type '(face))
3290 (make-obsolete-variable 'rst-emphasis2-face
3291 "customize the face `rst-emphasis2' instead."
3292 "24.1")
3293
3294 (defface rst-literal '((t :inherit font-lock-string-face))
3295 "Face used for literal text."
3296 :version "24.1"
3297 :group 'rst-faces)
3298
3299 (defcustom rst-literal-face 'rst-literal
3300 "Literal text."
3301 :version "24.1"
3302 :group 'rst-faces
3303 :type '(face))
3304 (make-obsolete-variable 'rst-literal-face
3305 "customize the face `rst-literal' instead."
3306 "24.1")
3307
3308 (defface rst-reference '((t :inherit font-lock-variable-name-face))
3309 "Face used for references to a definition."
3310 :version "24.1"
3311 :group 'rst-faces)
3312
3313 (defcustom rst-reference-face 'rst-reference
3314 "References to a definition."
3315 :version "24.1"
3316 :group 'rst-faces
3317 :type '(face))
3318 (make-obsolete-variable 'rst-reference-face
3319 "customize the face `rst-reference' instead."
3320 "24.1")
3321
3322 (defface rst-transition '((t :inherit font-lock-keyword-face))
3323 "Face used for a transition."
3324 :package-version '(rst . "1.3.0")
3325 :group 'rst-faces)
3326
3327 (defface rst-adornment '((t :inherit font-lock-keyword-face))
3328 "Face used for the adornment of a section header."
3329 :package-version '(rst . "1.3.0")
3330 :group 'rst-faces)
3331
3332 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3333
3334 ;; FIXME LEVEL-FACE: May be this complicated mechanism should be replaced
3335 ;; simply by a number of customizable faces `rst-header-%d'
3336 ;; which by default are set properly for dark and light
3337 ;; background. Initialization should come from the old
3338 ;; variables if they exist. A maximum level of 6 should
3339 ;; suffice - after that the last level should be repeated.
3340 ;; Only `rst-adornment-faces-alist' is needed outside this
3341 ;; block. Would also fix docutils-Bugs-3479594.
3342
3343 (defgroup rst-faces-defaults nil
3344 "Values used to generate default faces for section titles on all levels.
3345 Tweak these if you are content with how section title faces are built in
3346 general but you do not like the details."
3347 :group 'rst-faces
3348 :version "21.1")
3349
3350 (defun rst-set-level-default (sym val)
3351 "Set custom variable SYM affecting section title text face.
3352 Recompute the faces. VAL is the value to set."
3353 (custom-set-default sym val)
3354 ;; Also defines the faces initially when all values are available.
3355 (and (boundp 'rst-level-face-max)
3356 (boundp 'rst-level-face-format-light)
3357 (boundp 'rst-level-face-base-color)
3358 (boundp 'rst-level-face-step-light)
3359 (boundp 'rst-level-face-base-light)
3360 (fboundp 'rst-define-level-faces)
3361 (rst-define-level-faces)))
3362
3363 ;; Faces for displaying items on several levels. These definitions define
3364 ;; different shades of gray where the lightest one (i.e. least contrasting on a
3365 ;; light background) is used for level 1.
3366 (defcustom rst-level-face-max 6
3367 "Maximum depth of levels for which section title faces are defined."
3368 :group 'rst-faces-defaults
3369 :type '(integer)
3370 :set 'rst-set-level-default)
3371 ;; FIXME: It should be possible to give "#RRGGBB" type of color values.
3372 ;; Together with a `rst-level-face-end-light' this could be used for
3373 ;; computing steps.
3374 ;; FIXME: This variable should be combined with `rst-level-face-format-light'
3375 ;; to a single string.
3376 (defcustom rst-level-face-base-color "grey"
3377 "Base name of the color for creating background colors in section title faces."
3378 :group 'rst-faces-defaults
3379 :type '(string)
3380 :set 'rst-set-level-default)
3381 ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
3382 ;; how they behave for dark and light background using the
3383 ;; relevant options explained in `defface'.
3384 (defcustom rst-level-face-base-light
3385 (if (eq frame-background-mode 'dark)
3386 15
3387 85)
3388 "The lightness factor for the base color. This value is used for level 1.
3389 The default depends on whether the value of `frame-background-mode' is
3390 `dark' or not."
3391 :group 'rst-faces-defaults
3392 :type '(integer)
3393 :set 'rst-set-level-default)
3394 (defcustom rst-level-face-format-light "%2d"
3395 "The format for the lightness factor appended to the base name of the color.
3396 This value is expanded by `format' with an integer."
3397 :group 'rst-faces-defaults
3398 :type '(string)
3399 :set 'rst-set-level-default)
3400 ;; FIXME LEVEL-FACE: This needs to be done differently: The faces must specify
3401 ;; how they behave for dark and light background using the
3402 ;; relevant options explained in `defface'.
3403 ;; FIXME: Alternatively there could be a customizable variable
3404 ;; `rst-level-face-end-light' which defines the end value and steps are
3405 ;; computed
3406 (defcustom rst-level-face-step-light
3407 (if (eq frame-background-mode 'dark)
3408 7
3409 -7)
3410 "The step width to use for the next color.
3411 The formula
3412
3413 `rst-level-face-base-light'
3414 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
3415
3416 must result in a color level which appended to `rst-level-face-base-color'
3417 using `rst-level-face-format-light' results in a valid color such as `grey50'.
3418 This color is used as background for section title text on level
3419 `rst-level-face-max'."
3420 :group 'rst-faces-defaults
3421 :type '(integer)
3422 :set 'rst-set-level-default)
3423
3424 (defcustom rst-adornment-faces-alist
3425 ;; FIXME LEVEL-FACE: Must be redone if `rst-level-face-max' is changed
3426 (let ((alist (copy-sequence '((t . rst-transition)
3427 (nil . rst-adornment))))
3428 (i 1))
3429 (while (<= i rst-level-face-max)
3430 ;; FIXME: why not `push'?
3431 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
3432 (setq i (1+ i)))
3433 alist)
3434 "Faces for the various adornment types.
3435 Key is a number (for the section title text of that level
3436 starting with 1), t (for transitions) or nil (for section title
3437 adornment). If you generally do not like how section title text
3438 faces are set up tweak here. If the general idea is ok for you
3439 but you do not like the details check the Rst Faces Defaults
3440 group."
3441 :group 'rst-faces
3442 :type '(alist
3443 :key-type
3444 (choice
3445 (integer :tag "Section level")
3446 (const :tag "transitions" t)
3447 (const :tag "section title adornment" nil))
3448 :value-type (face))
3449 :set-after '(rst-level-face-max))
3450
3451 (defun rst-define-level-faces ()
3452 "Define the faces for the section title text faces from the values."
3453 ;; All variables used here must be checked in `rst-set-level-default'.
3454 (let ((i 1))
3455 (while (<= i rst-level-face-max)
3456 (let ((sym (intern (format "rst-level-%d-face" i)))
3457 (doc (format "Default face for showing section title text at level %d.
3458 This symbol is *not* meant for customization but modified if a
3459 variable of the `rst-faces-defaults' group is customized. Use
3460 `rst-adornment-faces-alist' for customization instead." i))
3461 (col (format (concat "%s" rst-level-face-format-light)
3462 rst-level-face-base-color
3463 (+ (* (1- i) rst-level-face-step-light)
3464 rst-level-face-base-light))))
3465 (make-empty-face sym)
3466 (set-face-doc-string sym doc)
3467 (set-face-background sym col)
3468 (set sym sym)
3469 (setq i (1+ i))))))
3470
3471 ;; FIXME LEVEL-FACE: This is probably superfluous since it is done by the
3472 ;; customization / `rst-set-level-default'.
3473 (rst-define-level-faces)
3474
3475 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3476
3477 (defvar rst-font-lock-keywords
3478 ;; The reST-links in the comments below all relate to sections in
3479 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.
3480 `(;; FIXME: Block markup is not recognized in blocks after explicit markup
3481 ;; start.
3482
3483 ;; Simple `Body Elements`_
3484 ;; `Bullet Lists`_
3485 ;; FIXME: A bullet directly after a field name is not recognized.
3486 (,(rst-re 'lin-beg '(:grp bul-sta))
3487 1 rst-block-face)
3488 ;; `Enumerated Lists`_
3489 (,(rst-re 'lin-beg '(:grp enmany-sta))
3490 1 rst-block-face)
3491 ;; `Definition Lists`_
3492 ;; FIXME: missing.
3493 ;; `Field Lists`_
3494 (,(rst-re 'lin-beg '(:grp fld-tag) 'bli-sfx)
3495 1 rst-external-face)
3496 ;; `Option Lists`_
3497 (,(rst-re 'lin-beg '(:grp opt-tag (:shy optsep-tag opt-tag) "*")
3498 '(:alt "$" (:seq hws-prt "\\{2\\}")))
3499 1 rst-block-face)
3500 ;; `Line Blocks`_
3501 ;; Only for lines containing no more bar - to distinguish from tables.
3502 (,(rst-re 'lin-beg '(:grp "|" bli-sfx) "[^|\n]*$")
3503 1 rst-block-face)
3504
3505 ;; `Tables`_
3506 ;; FIXME: missing
3507
3508 ;; All the `Explicit Markup Blocks`_
3509 ;; `Footnotes`_ / `Citations`_
3510 (,(rst-re 'lin-beg 'fnc-sta-2)
3511 (1 rst-definition-face)
3512 (2 rst-definition-face))
3513 ;; `Directives`_ / `Substitution Definitions`_
3514 (,(rst-re 'lin-beg 'dir-sta-3)
3515 (1 rst-directive-face)
3516 (2 rst-definition-face)
3517 (3 rst-directive-face))
3518 ;; `Hyperlink Targets`_
3519 (,(rst-re 'lin-beg
3520 '(:grp exm-sta "_" (:alt
3521 (:seq "`" ilcbkqdef-tag "`")
3522 (:seq (:alt "[^:\\\n]" "\\\\.") "+")) ":")
3523 'bli-sfx)
3524 1 rst-definition-face)
3525 (,(rst-re 'lin-beg '(:grp "__") 'bli-sfx)
3526 1 rst-definition-face)
3527
3528 ;; All `Inline Markup`_
3529 ;; Most of them may be multiline though this is uninteresting.
3530
3531 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
3532 ;; `Strong Emphasis`_.
3533 (,(rst-re 'ilm-pfx '(:grp "\\*\\*" ilcast-tag "\\*\\*") 'ilm-sfx)
3534 1 rst-emphasis2-face)
3535 ;; `Emphasis`_
3536 (,(rst-re 'ilm-pfx '(:grp "\\*" ilcast-tag "\\*") 'ilm-sfx)
3537 1 rst-emphasis1-face)
3538 ;; `Inline Literals`_
3539 (,(rst-re 'ilm-pfx '(:grp "``" ilcbkq-tag "``") 'ilm-sfx)
3540 1 rst-literal-face)
3541 ;; `Inline Internal Targets`_
3542 (,(rst-re 'ilm-pfx '(:grp "_`" ilcbkq-tag "`") 'ilm-sfx)
3543 1 rst-definition-face)
3544 ;; `Hyperlink References`_
3545 ;; FIXME: `Embedded URIs`_ not considered.
3546 ;; FIXME: Directly adjacent marked up words are not fontified correctly
3547 ;; unless they are not separated by two spaces: foo_ bar_.
3548 (,(rst-re 'ilm-pfx '(:grp (:alt (:seq "`" ilcbkq-tag "`")
3549 (:seq "\\sw" (:alt "\\sw" "-") "+\\sw"))
3550 "__?") 'ilm-sfx)
3551 1 rst-reference-face)
3552 ;; `Interpreted Text`_
3553 (,(rst-re 'ilm-pfx '(:grp (:shy ":" sym-tag ":") "?")
3554 '(:grp "`" ilcbkq-tag "`")
3555 '(:grp (:shy ":" sym-tag ":") "?") 'ilm-sfx)
3556 (1 rst-directive-face)
3557 (2 rst-external-face)
3558 (3 rst-directive-face))
3559 ;; `Footnote References`_ / `Citation References`_
3560 (,(rst-re 'ilm-pfx '(:grp fnc-tag "_") 'ilm-sfx)
3561 1 rst-reference-face)
3562 ;; `Substitution References`_
3563 ;; FIXME: References substitutions like |this|_ or |this|__ are not
3564 ;; fontified correctly.
3565 (,(rst-re 'ilm-pfx '(:grp sub-tag) 'ilm-sfx)
3566 1 rst-reference-face)
3567 ;; `Standalone Hyperlinks`_
3568 ;; FIXME: This takes it easy by using a whitespace as delimiter.
3569 (,(rst-re 'ilm-pfx '(:grp uri-tag ":\\S +") 'ilm-sfx)
3570 1 rst-definition-face)
3571 (,(rst-re 'ilm-pfx '(:grp sym-tag "@" sym-tag ) 'ilm-sfx)
3572 1 rst-definition-face)
3573
3574 ;; Do all block fontification as late as possible so 'append works.
3575
3576 ;; Sections_ / Transitions_
3577 ;; For sections this is multiline.
3578 (,(rst-re 'ado-beg-2-1)
3579 (rst-font-lock-handle-adornment-matcher
3580 (rst-font-lock-handle-adornment-pre-match-form
3581 (match-string-no-properties 1) (match-end 1))
3582 nil
3583 (1 (cdr (assoc nil rst-adornment-faces-alist)) append t)
3584 (2 (cdr (assoc rst-font-lock-adornment-level
3585 rst-adornment-faces-alist)) append t)
3586 (3 (cdr (assoc nil rst-adornment-faces-alist)) append t)))
3587
3588 ;; FIXME: FACESPEC could be used instead of ordinary faces to set
3589 ;; properties on comments and literal blocks so they are *not*
3590 ;; inline fontified. See (elisp)Search-based Fontification.
3591
3592 ;; FIXME: And / or use `syntax-propertize` functions as in `octave-mod.el`
3593 ;; and other V24 modes. May make `font-lock-extend-region`
3594 ;; superfluous.
3595
3596 ;; `Comments`_
3597 ;; This is multiline.
3598 (,(rst-re 'lin-beg 'cmt-sta-1)
3599 (1 rst-comment-face)
3600 (rst-font-lock-find-unindented-line-match
3601 (rst-font-lock-find-unindented-line-limit (match-end 1))
3602 nil
3603 (0 rst-comment-face append)))
3604 (,(rst-re 'lin-beg '(:grp exm-tag) '(:grp hws-tag) "$")
3605 (1 rst-comment-face)
3606 (2 rst-comment-face)
3607 (rst-font-lock-find-unindented-line-match
3608 (rst-font-lock-find-unindented-line-limit 'next)
3609 nil
3610 (0 rst-comment-face append)))
3611
3612 ;; FIXME: This is not rendered as comment::
3613 ;; .. .. list-table::
3614 ;; :stub-columns: 1
3615 ;; :header-rows: 1
3616
3617 ;; FIXME: This is rendered wrong::
3618 ;;
3619 ;; xxx yyy::
3620 ;;
3621 ;; ----|> KKKKK <|----
3622 ;; / \
3623 ;; -|> AAAAAAAAAAPPPPPP <|- -|> AAAAAAAAAABBBBBBB <|-
3624 ;; | | | |
3625 ;; | | | |
3626 ;; PPPPPP PPPPPPDDDDDDD BBBBBBB PPPPPPBBBBBBB
3627 ;;
3628 ;; Indentation needs to be taken from the line with the ``::`` and not from
3629 ;; the first content line.
3630
3631 ;; `Indented Literal Blocks`_
3632 ;; This is multiline.
3633 (,(rst-re 'lin-beg 'lit-sta-2)
3634 (2 rst-block-face)
3635 (rst-font-lock-find-unindented-line-match
3636 (rst-font-lock-find-unindented-line-limit t)
3637 nil
3638 (0 rst-literal-face append)))
3639
3640 ;; FIXME: `Quoted Literal Blocks`_ missing.
3641 ;; This is multiline.
3642
3643 ;; `Doctest Blocks`_
3644 ;; FIXME: This is wrong according to the specification:
3645 ;;
3646 ;; Doctest blocks are text blocks which begin with ">>> ", the Python
3647 ;; interactive interpreter main prompt, and end with a blank line.
3648 ;; Doctest blocks are treated as a special case of literal blocks,
3649 ;; without requiring the literal block syntax. If both are present, the
3650 ;; literal block syntax takes priority over Doctest block syntax:
3651 ;;
3652 ;; This is an ordinary paragraph.
3653 ;;
3654 ;; >>> print 'this is a Doctest block'
3655 ;; this is a Doctest block
3656 ;;
3657 ;; The following is a literal block::
3658 ;;
3659 ;; >>> This is not recognized as a doctest block by
3660 ;; reStructuredText. It *will* be recognized by the doctest
3661 ;; module, though!
3662 ;;
3663 ;; Indentation is not required for doctest blocks.
3664 (,(rst-re 'lin-beg '(:grp (:alt ">>>" ell-tag)) '(:grp ".+"))
3665 (1 rst-block-face)
3666 (2 rst-literal-face))
3667 )
3668 "Keywords to highlight in rst mode.")
3669
3670 (defvar font-lock-beg)
3671 (defvar font-lock-end)
3672
3673 (defun rst-font-lock-extend-region ()
3674 "Extend the font-lock region if it might be in a multi-line construct.
3675 Return non-nil if so. Font-lock region is from `font-lock-beg'
3676 to `font-lock-end'."
3677 (let ((r (rst-font-lock-extend-region-internal font-lock-beg font-lock-end)))
3678 (when r
3679 (setq font-lock-beg (car r))
3680 (setq font-lock-end (cdr r))
3681 t)))
3682
3683 (defun rst-font-lock-extend-region-internal (beg end)
3684 "Check the region BEG / END for being in the middle of a multi-line construct.
3685 Return nil if not or a cons with new values for BEG / END"
3686 (let ((nbeg (rst-font-lock-extend-region-extend beg -1))
3687 (nend (rst-font-lock-extend-region-extend end 1)))
3688 (if (or nbeg nend)
3689 (cons (or nbeg beg) (or nend end)))))
3690
3691 (defun rst-forward-line (&optional n)
3692 "Like `forward-line' but always end up in column 0 and return accordingly.
3693 Move N lines forward just as `forward-line'."
3694 (let ((moved (forward-line n)))
3695 (if (bolp)
3696 moved
3697 (forward-line 0)
3698 (- moved (rst-signum n)))))
3699
3700 ;; FIXME: If a single line is made a section header by `rst-adjust' the header
3701 ;; is not always fontified immediately.
3702 (defun rst-font-lock-extend-region-extend (pt dir)
3703 "Extend the region starting at point PT and extending in direction DIR.
3704 Return extended point or nil if not moved."
3705 ;; There are many potential multiline constructs but there are two groups
3706 ;; which are really relevant. The first group consists of
3707 ;;
3708 ;; * comment lines without leading explicit markup tag and
3709 ;;
3710 ;; * literal blocks following "::"
3711 ;;
3712 ;; which are both indented. Thus indentation is the first thing recognized
3713 ;; here. The second criteria is an explicit markup tag which may be a comment
3714 ;; or a double colon at the end of a line.
3715 ;;
3716 ;; The second group consists of the adornment cases.
3717 (if (not (get-text-property pt 'font-lock-multiline))
3718 ;; Move only if we don't start inside a multiline construct already.
3719 (save-excursion
3720 (let (;; Non-empty non-indented line, explicit markup tag or literal
3721 ;; block tag.
3722 (stop-re (rst-re '(:alt "[^ \t\n]"
3723 (:seq hws-tag exm-tag)
3724 (:seq ".*" dcl-tag lin-end)))))
3725 ;; The comments below are for dir == -1 / dir == 1.
3726 (goto-char pt)
3727 (forward-line 0)
3728 (setq pt (point))
3729 (while (and (not (looking-at stop-re))
3730 (zerop (rst-forward-line dir)))) ; try previous / next
3731 ; line if it exists.
3732 (if (looking-at (rst-re 'ado-beg-2-1)) ; may be an underline /
3733 ; overline.
3734 (if (zerop (rst-forward-line dir))
3735 (if (looking-at (rst-re 'ttl-beg)) ; title found, i.e.
3736 ; underline / overline
3737 ; found.
3738 (if (zerop (rst-forward-line dir))
3739 (if (not
3740 (looking-at (rst-re 'ado-beg-2-1))) ; no
3741 ; overline /
3742 ; underline.
3743 (rst-forward-line (- dir)))) ; step back to title
3744 ; / adornment.
3745 (if (< dir 0) ; keep downward adornment.
3746 (rst-forward-line (- dir))))) ; step back to adornment.
3747 (if (looking-at (rst-re 'ttl-beg)) ; may be a title.
3748 (if (zerop (rst-forward-line dir))
3749 (if (not
3750 (looking-at (rst-re 'ado-beg-2-1))) ; no overline /
3751 ; underline.
3752 (rst-forward-line (- dir)))))) ; step back to line.
3753 (if (not (= (point) pt))
3754 (point))))))
3755
3756 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3757 ;; Indented blocks
3758
3759 (defun rst-forward-indented-block (&optional column limit)
3760 "Move forward across one indented block.
3761 Find the next non-empty line which is not indented at least to COLUMN (defaults
3762 to the column of the point). Moves point to first character of this line or the
3763 first empty line immediately before it and returns that position. If there is
3764 no such line before LIMIT (defaults to the end of the buffer) returns nil and
3765 point is not moved."
3766 (interactive)
3767 (let ((clm (or column (current-column)))
3768 (start (point))
3769 fnd beg cand)
3770 (if (not limit)
3771 (setq limit (point-max)))
3772 (save-match-data
3773 (while (and (not fnd) (< (point) limit))
3774 (forward-line 1)
3775 (when (< (point) limit)
3776 (setq beg (point))
3777 (if (looking-at (rst-re 'lin-end))
3778 (setq cand (or cand beg)) ; An empty line is a candidate.
3779 (move-to-column clm)
3780 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3781 ;; useful way - though it is not clear what this should mean
3782 ;; at all.
3783 (if (string-match
3784 (rst-re 'linemp-tag)
3785 (buffer-substring-no-properties beg (point)))
3786 (setq cand nil) ; An indented line resets a candidate.
3787 (setq fnd (or cand beg)))))))
3788 (goto-char (or fnd start))
3789 fnd))
3790
3791 (defvar rst-font-lock-find-unindented-line-begin nil
3792 "Beginning of the match if `rst-font-lock-find-unindented-line-end'.")
3793
3794 (defvar rst-font-lock-find-unindented-line-end nil
3795 "End of the match as determined by `rst-font-lock-find-unindented-line-limit'.
3796 Also used as a trigger for
3797 `rst-font-lock-find-unindented-line-match'.")
3798
3799 (defun rst-font-lock-find-unindented-line-limit (ind-pnt)
3800 "Find the next unindented line relative to indentation at IND-PNT.
3801 Return this point, the end of the buffer or nil if nothing found.
3802 If IND-PNT is `next' take the indentation from the next line if
3803 this is not empty and indented more than the current one. If
3804 IND-PNT is non-nil but not a number take the indentation from the
3805 next non-empty line if this is indented more than the current
3806 one."
3807 (setq rst-font-lock-find-unindented-line-begin ind-pnt)
3808 (setq rst-font-lock-find-unindented-line-end
3809 (save-excursion
3810 (when (not (numberp ind-pnt))
3811 ;; Find indentation point in next line if any.
3812 (setq ind-pnt
3813 ;; FIXME: Should be refactored to two different functions
3814 ;; giving their result to this function, may be
3815 ;; integrated in caller.
3816 (save-match-data
3817 (let ((cur-ind (current-indentation)))
3818 (if (eq ind-pnt 'next)
3819 (when (and (zerop (forward-line 1))
3820 (< (point) (point-max)))
3821 ;; Not at EOF.
3822 (setq rst-font-lock-find-unindented-line-begin
3823 (point))
3824 (when (and (not (looking-at (rst-re 'lin-end)))
3825 (> (current-indentation) cur-ind))
3826 ;; Use end of indentation if non-empty line.
3827 (looking-at (rst-re 'hws-tag))
3828 (match-end 0)))
3829 ;; Skip until non-empty line or EOF.
3830 (while (and (zerop (forward-line 1))
3831 (< (point) (point-max))
3832 (looking-at (rst-re 'lin-end))))
3833 (when (< (point) (point-max))
3834 ;; Not at EOF.
3835 (setq rst-font-lock-find-unindented-line-begin
3836 (point))
3837 (when (> (current-indentation) cur-ind)
3838 ;; Indentation bigger than line of departure.
3839 (looking-at (rst-re 'hws-tag))
3840 (match-end 0))))))))
3841 (when ind-pnt
3842 (goto-char ind-pnt)
3843 (or (rst-forward-indented-block nil (point-max))
3844 (point-max))))))
3845
3846 (defun rst-font-lock-find-unindented-line-match (limit)
3847 "Set the match found earlier if match were found.
3848 Match has been found by
3849 `rst-font-lock-find-unindented-line-limit' the first time called
3850 or no match is found. Return non-nil if match was found. LIMIT
3851 is not used but mandated by the caller."
3852 (when rst-font-lock-find-unindented-line-end
3853 (set-match-data
3854 (list rst-font-lock-find-unindented-line-begin
3855 rst-font-lock-find-unindented-line-end))
3856 (put-text-property rst-font-lock-find-unindented-line-begin
3857 rst-font-lock-find-unindented-line-end
3858 'font-lock-multiline t)
3859 ;; Make sure this is called only once.
3860 (setq rst-font-lock-find-unindented-line-end nil)
3861 t))
3862
3863 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3864 ;; Adornments
3865
3866 (defvar rst-font-lock-adornment-level nil
3867 "Storage for `rst-font-lock-handle-adornment-matcher'.
3868 Either section level of the current adornment or t for a transition.")
3869
3870 (defun rst-adornment-level (key)
3871 "Return section level for adornment KEY.
3872 KEY is the first element of the return list of
3873 `rst-classify-adornment'. If KEY is not a cons return it. If KEY is found
3874 in the hierarchy return its level. Otherwise return a level one
3875 beyond the existing hierarchy."
3876 (if (not (consp key))
3877 key
3878 (let* ((hier (rst-get-hierarchy))
3879 (char (car key))
3880 (style (cdr key)))
3881 (1+ (or (lexical-let ((char char)
3882 (style style)
3883 (hier hier)) ; Create closure.
3884 (rst-position-if (lambda (elt)
3885 (and (equal (car elt) char)
3886 (equal (cadr elt) style))) hier))
3887 (length hier))))))
3888
3889 (defvar rst-font-lock-adornment-match nil
3890 "Storage for match for current adornment.
3891 Set by `rst-font-lock-handle-adornment-pre-match-form'. Also used
3892 as a trigger for `rst-font-lock-handle-adornment-matcher'.")
3893
3894 (defun rst-font-lock-handle-adornment-pre-match-form (ado ado-end)
3895 "Determine limit for adornments.
3896 Determine all things necessary for font-locking section titles
3897 and transitions and put the result to
3898 `rst-font-lock-adornment-match' and
3899 `rst-font-lock-adornment-level'. ADO is the complete adornment
3900 matched. ADO-END is the point where ADO ends. Return the point
3901 where the whole adorned construct ends.
3902
3903 Called as a PRE-MATCH-FORM in the sense of `font-lock-keywords'."
3904 (let ((ado-data (rst-classify-adornment ado ado-end)))
3905 (if (not ado-data)
3906 (setq rst-font-lock-adornment-level nil
3907 rst-font-lock-adornment-match nil)
3908 (setq rst-font-lock-adornment-level
3909 (rst-adornment-level (car ado-data)))
3910 (setq rst-font-lock-adornment-match (cdr ado-data))
3911 (goto-char (nth 1 ado-data)) ; Beginning of construct.
3912 (nth 2 ado-data)))) ; End of construct.
3913
3914 (defun rst-font-lock-handle-adornment-matcher (limit)
3915 "Set the match found earlier if match were found.
3916 Match has been found by
3917 `rst-font-lock-handle-adornment-pre-match-form' the first time
3918 called or no match is found. Return non-nil if match was found.
3919
3920 Called as a MATCHER in the sense of `font-lock-keywords'.
3921 LIMIT is not used but mandated by the caller."
3922 (let ((match rst-font-lock-adornment-match))
3923 ;; May run only once - enforce this.
3924 (setq rst-font-lock-adornment-match nil)
3925 (when match
3926 (set-match-data match)
3927 (goto-char (match-end 0))
3928 (put-text-property (match-beginning 0) (match-end 0)
3929 'font-lock-multiline t)
3930 t)))
3931
3932 \f
3933 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3934 ;; Compilation
3935
3936 (defgroup rst-compile nil
3937 "Settings for support of conversion of reStructuredText
3938 document with \\[rst-compile]."
3939 :group 'rst
3940 :version "21.1")
3941
3942 (defcustom rst-compile-toolsets
3943 `((html ,(if (executable-find "rst2html.py") "rst2html.py" "rst2html")
3944 ".html" nil)
3945 (latex ,(if (executable-find "rst2latex.py") "rst2latex.py" "rst2latex")
3946 ".tex" nil)
3947 (newlatex ,(if (executable-find "rst2newlatex.py") "rst2newlatex.py"
3948 "rst2newlatex")
3949 ".tex" nil)
3950 (pseudoxml ,(if (executable-find "rst2pseudoxml.py") "rst2pseudoxml.py"
3951 "rst2pseudoxml")
3952 ".xml" nil)
3953 (xml ,(if (executable-find "rst2xml.py") "rst2xml.py" "rst2xml")
3954 ".xml" nil)
3955 (pdf ,(if (executable-find "rst2pdf.py") "rst2pdf.py" "rst2pdf")
3956 ".pdf" nil)
3957 (s5 ,(if (executable-find "rst2s5.py") "rst2s5.py" "rst2s5")
3958 ".html" nil))
3959 "Table describing the command to use for each tool-set.
3960 An association list of the tool-set to a list of the (command to use,
3961 extension of produced filename, options to the tool (nil or a
3962 string)) to be used for converting the document."
3963 ;; FIXME: These are not options but symbols which may be referenced by
3964 ;; `rst-compile-*-toolset` below. The `:validate' keyword of
3965 ;; `defcustom' may help to define this properly in newer Emacs
3966 ;; versions (> 23.1).
3967 :type '(alist :options (html latex newlatex pseudoxml xml pdf s5)
3968 :key-type symbol
3969 :value-type (list :tag "Specification"
3970 (file :tag "Command")
3971 (string :tag "File extension")
3972 (choice :tag "Command options"
3973 (const :tag "No options" nil)
3974 (string :tag "Options"))))
3975 :group 'rst
3976 :package-version "1.2.0")
3977
3978 ;; FIXME: Must be `defcustom`.
3979 (defvar rst-compile-primary-toolset 'html
3980 "The default tool-set for `rst-compile'.")
3981
3982 ;; FIXME: Must be `defcustom`.
3983 (defvar rst-compile-secondary-toolset 'latex
3984 "The default tool-set for `rst-compile' with a prefix argument.")
3985
3986 (defun rst-compile-find-conf ()
3987 "Look for the configuration file in the parents of the current path."
3988 (interactive)
3989 (let ((file-name "docutils.conf")
3990 (buffer-file (buffer-file-name)))
3991 ;; Move up in the dir hierarchy till we find a change log file.
3992 (let* ((dir (file-name-directory buffer-file))
3993 (prevdir nil))
3994 (while (and (or (not (string= dir prevdir))
3995 (setq dir nil)
3996 nil)
3997 (not (file-exists-p (concat dir file-name))))
3998 ;; Move up to the parent dir and try again.
3999 (setq prevdir dir)
4000 (setq dir (expand-file-name (file-name-directory
4001 (directory-file-name
4002 (file-name-directory dir)))))
4003 )
4004 (or (and dir (concat dir file-name)) nil)
4005 )))
4006
4007
4008 (require 'compile)
4009
4010 (defun rst-compile (&optional use-alt)
4011 "Compile command to convert reST document into some output file.
4012 Attempts to find configuration file, if it can, overrides the
4013 options. There are two commands to choose from, with USE-ALT,
4014 select the alternative tool-set."
4015 (interactive "P")
4016 ;; Note: maybe we want to check if there is a Makefile too and not do anything
4017 ;; if that is the case. I dunno.
4018 (let* ((toolset (cdr (assq (if use-alt
4019 rst-compile-secondary-toolset
4020 rst-compile-primary-toolset)
4021 rst-compile-toolsets)))
4022 (command (car toolset))
4023 (extension (cadr toolset))
4024 (options (caddr toolset))
4025 (conffile (rst-compile-find-conf))
4026 (bufname (file-name-nondirectory buffer-file-name))
4027 (outname (file-name-sans-extension bufname)))
4028
4029 ;; Set compile-command before invocation of compile.
4030 (set (make-local-variable 'compile-command)
4031 (mapconcat 'identity
4032 (list command
4033 (or options "")
4034 (if conffile
4035 (concat "--config=" (shell-quote-argument conffile))
4036 "")
4037 (shell-quote-argument bufname)
4038 (shell-quote-argument (concat outname extension)))
4039 " "))
4040
4041 ;; Invoke the compile command.
4042 (if (or compilation-read-command use-alt)
4043 (call-interactively 'compile)
4044 (compile compile-command))
4045 ))
4046
4047 (defun rst-compile-alt-toolset ()
4048 "Compile command with the alternative tool-set."
4049 (interactive)
4050 (rst-compile t))
4051
4052 (defun rst-compile-pseudo-region ()
4053 "Show pseudo-XML rendering.
4054 Rendering is done of the current active region, or of the entire
4055 buffer, if the region is not selected."
4056 ;; FIXME: The region should be given interactively.
4057 (interactive)
4058 (with-output-to-temp-buffer "*pseudoxml*"
4059 (shell-command-on-region
4060 (if mark-active (region-beginning) (point-min))
4061 (if mark-active (region-end) (point-max))
4062 (cadr (assq 'pseudoxml rst-compile-toolsets))
4063 standard-output)))
4064
4065 ;; FIXME: Should be `defcustom`.
4066 (defvar rst-pdf-program "xpdf"
4067 "Program used to preview PDF files.")
4068
4069 (defun rst-compile-pdf-preview ()
4070 "Convert the document to a PDF file and launch a preview program."
4071 (interactive)
4072 (let* ((tmp-filename (make-temp-file "rst_el" nil ".pdf"))
4073 (command (format "%s %s %s && %s %s ; rm %s"
4074 (cadr (assq 'pdf rst-compile-toolsets))
4075 buffer-file-name tmp-filename
4076 rst-pdf-program tmp-filename tmp-filename)))
4077 (start-process-shell-command "rst-pdf-preview" nil command)
4078 ;; Note: you could also use (compile command) to view the compilation
4079 ;; output.
4080 ))
4081
4082 ;; FIXME: Should be `defcustom` or use something like `browse-url`.
4083 (defvar rst-slides-program "firefox"
4084 "Program used to preview S5 slides.")
4085
4086 (defun rst-compile-slides-preview ()
4087 "Convert the document to an S5 slide presentation and launch a preview program."
4088 (interactive)
4089 (let* ((tmp-filename (make-temp-file "rst_el" nil ".html"))
4090 (command (format "%s %s %s && %s %s ; rm %s"
4091 (cadr (assq 's5 rst-compile-toolsets))
4092 buffer-file-name tmp-filename
4093 rst-slides-program tmp-filename tmp-filename)))
4094 (start-process-shell-command "rst-slides-preview" nil command)
4095 ;; Note: you could also use (compile command) to view the compilation
4096 ;; output.
4097 ))
4098
4099 \f
4100 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4101 ;; Generic text functions that are more convenient than the defaults.
4102
4103 ;; FIXME: Unbound command - should be bound or removed.
4104 (defun rst-replace-lines (fromchar tochar)
4105 "Replace flush-left lines of FROMCHAR with equal-length lines of TOCHAR."
4106 (interactive "\
4107 cSearch for flush-left lines of char:
4108 cand replace with char: ")
4109 (save-excursion
4110 (let ((searchre (rst-re "^" fromchar "+\\( *\\)$"))
4111 (found 0))
4112 (while (search-forward-regexp searchre nil t)
4113 (setq found (1+ found))
4114 (goto-char (match-beginning 1))
4115 (let ((width (current-column)))
4116 (rst-delete-entire-line)
4117 (insert-char tochar width)))
4118 (message (format "%d lines replaced." found)))))
4119
4120 ;; FIXME: Unbound command - should be bound or removed.
4121 (defun rst-join-paragraph ()
4122 "Join lines in current paragraph into one line, removing end-of-lines."
4123 (interactive)
4124 (let ((fill-column 65000)) ; Some big number.
4125 (call-interactively 'fill-paragraph)))
4126
4127 ;; FIXME: Unbound command - should be bound or removed.
4128 (defun rst-force-fill-paragraph ()
4129 "Fill paragraph at point, first joining the paragraph's lines into one.
4130 This is useful for filling list item paragraphs."
4131 (interactive)
4132 (rst-join-paragraph)
4133 (fill-paragraph nil))
4134
4135
4136 ;; FIXME: Unbound command - should be bound or removed.
4137 ;; Generic character repeater function.
4138 ;; For sections, better to use the specialized function above, but this can
4139 ;; be useful for creating separators.
4140 (defun rst-repeat-last-character (use-next)
4141 "Fill the current line using the last character on the current line.
4142 Fill up to the length of the preceding line or up to
4143 `fill-column' if preceding line is empty.
4144
4145 If USE-NEXT, use the next line rather than the preceding line.
4146
4147 If the current line is longer than the desired length, shave the characters off
4148 the current line to fit the desired length.
4149
4150 As an added convenience, if the command is repeated immediately, the alternative
4151 column is used (fill-column vs. end of previous/next line)."
4152 (interactive "P")
4153 (let* ((curcol (current-column))
4154 (curline (+ (count-lines (point-min) (point))
4155 (if (zerop curcol) 1 0)))
4156 (lbp (line-beginning-position 0))
4157 (prevcol (if (and (= curline 1) (not use-next))
4158 fill-column
4159 (save-excursion
4160 (forward-line (if use-next 1 -1))
4161 (end-of-line)
4162 (skip-chars-backward " \t" lbp)
4163 (let ((cc (current-column)))
4164 (if (zerop cc) fill-column cc)))))
4165 (rightmost-column
4166 (cond ((equal last-command 'rst-repeat-last-character)
4167 (if (= curcol fill-column) prevcol fill-column))
4168 (t (save-excursion
4169 (if (zerop prevcol) fill-column prevcol)))
4170 )) )
4171 (end-of-line)
4172 (if (> (current-column) rightmost-column)
4173 ;; Shave characters off the end.
4174 (delete-region (- (point)
4175 (- (current-column) rightmost-column))
4176 (point))
4177 ;; Fill with last characters.
4178 (insert-char (preceding-char)
4179 (- rightmost-column (current-column))))
4180 ))
4181
4182
4183 (defun rst-portable-mark-active-p ()
4184 "Return non-nil if the mark is active.
4185 This is a portable function."
4186 (cond
4187 ((fboundp 'region-active-p) (region-active-p))
4188 ((boundp 'transient-mark-mode) (and transient-mark-mode mark-active))
4189 (t mark-active)))
4190
4191 \f
4192
4193 ;; LocalWords: docutils http sourceforge rst html wp svn svnroot txt reST regex
4194 ;; LocalWords: regexes alist seq alt grp keymap abbrev overline overlines toc
4195 ;; LocalWords: XML PNT propertized
4196
4197 ;; Local Variables:
4198 ;; sentence-end-double-space: t
4199 ;; End:
4200
4201 (provide 'rst)
4202
4203 ;;; rst.el ends here