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