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