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