]> code.delx.au - gnu-emacs/blob - lisp/textmodes/rst.el
Merge from emacs--rel--22
[gnu-emacs] / lisp / textmodes / rst.el
1 ;;; rst.el --- Mode for viewing and editing reStructuredText-documents.
2
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008
4 ;; Free Software Foundation, Inc.
5
6 ;; Authors: Martin Blais <blais@furius.ca>,
7 ;; Stefan Merten <smerten@oekonux.de>,
8 ;; David Goodger <goodger@python.org>
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; This package provides major mode rst-mode, which supports documents marked up
28 ;; using the reStructuredText format. Support includes font locking as well as
29 ;; some convenience functions for editing. It does this by defining a Emacs
30 ;; major mode: rst-mode (ReST). This mode is derived from text-mode (and
31 ;; inherits much of it). This package also contains:
32 ;;
33 ;; - Functions to automatically adjust and cycle the section underline
34 ;; decorations;
35 ;; - A mode that displays the table of contents and allows you to jump anywhere
36 ;; from it;
37 ;; - Functions to insert and automatically update a TOC in your source
38 ;; document;
39 ;; - Font-lock highlighting of notable reStructuredText structures;
40 ;; - Some other convenience functions.
41 ;;
42 ;; See the accompanying document in the docutils documentation about
43 ;; the contents of this package and how to use it.
44 ;;
45 ;; For more information about reStructuredText, see
46 ;; http://docutils.sourceforge.net/rst.html
47 ;;
48 ;; For full details on how to use the contents of this file, see
49 ;; http://docutils.sourceforge.net/docs/user/emacs.html
50 ;;
51 ;;
52 ;; There are a number of convenient keybindings provided by rst-mode.
53 ;; The main one is
54 ;;
55 ;; C-c C-a (also C-=): rst-adjust
56 ;;
57 ;; Updates or rotates the section title around point or promotes/demotes the
58 ;; decorations within the region (see full details below). Note that C-= is a
59 ;; good binding, since it allows you to specify a negative arg easily with C--
60 ;; C-= (easy to type), as well as ordinary prefix arg with C-u C-=.
61 ;;
62 ;; For more on bindings, see rst-mode-map below. There are also many variables
63 ;; that can be customized, look for defcustom and defvar in this file.
64 ;;
65 ;; If you use the table-of-contents feature, you may want to add a hook to
66 ;; update the TOC automatically everytime you adjust a section title::
67 ;;
68 ;; (add-hook 'rst-adjust-hook 'rst-toc-update)
69 ;;
70 ;; Syntax highlighting: font-lock is enabled by default. If you want to turn
71 ;; off syntax highlighting to rst-mode, you can use the following::
72 ;;
73 ;; (setq font-lock-global-modes '(not rst-mode ...))
74 ;;
75
76
77 ;; CUSTOMIZATION
78 ;;
79 ;; rst
80 ;; ---
81 ;; This group contains some general customizable features.
82 ;;
83 ;; The group is contained in the wp group.
84 ;;
85 ;; rst-faces
86 ;; ---------
87 ;; This group contains all necessary for customizing fonts. The default
88 ;; settings use standard font-lock-*-face's so if you set these to your
89 ;; liking they are probably good in rst-mode also.
90 ;;
91 ;; The group is contained in the faces group as well as in the rst group.
92 ;;
93 ;; rst-faces-defaults
94 ;; ------------------
95 ;; This group contains all necessary for customizing the default fonts used for
96 ;; section title faces.
97 ;;
98 ;; The general idea for section title faces is to have a non-default background
99 ;; but do not change the background. The section level is shown by the
100 ;; lightness of the background color. If you like this general idea of
101 ;; generating faces for section titles but do not like the details this group
102 ;; is the point where you can customize the details. If you do not like the
103 ;; general idea, however, you should customize the faces used in
104 ;; rst-adornment-faces-alist.
105 ;;
106 ;; Note: If you are using a dark background please make sure the variable
107 ;; frame-background-mode is set to the symbol dark. This triggers
108 ;; some default values which are probably right for you.
109 ;;
110 ;; The group is contained in the rst-faces group.
111 ;;
112 ;; All customizable features have a comment explaining their meaning.
113 ;; Refer to the customization of your Emacs (try ``M-x customize``).
114
115
116 ;;; DOWNLOAD
117
118 ;; The latest version of this file lies in the docutils source code repository:
119 ;; http://svn.berlios.de/svnroot/repos/docutils/trunk/docutils/tools/editors/emacs/rst.el
120
121
122 ;;; INSTALLATION
123
124 ;; Add the following lines to your `.emacs' file:
125 ;;
126 ;; (require 'rst)
127 ;;
128 ;; If you are using `.txt' as a standard extension for reST files as
129 ;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
130 ;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
131 ;; provides to set the major mode automatically. For instance you may use::
132 ;;
133 ;; .. -*- mode: rst -*-
134 ;;
135 ;; in the very first line of your file. The following code is useful if you
136 ;; want automatically enter rst-mode from any file with compatible extensions:
137 ;;
138 ;; (setq auto-mode-alist
139 ;; (append '(("\\.txt$" . rst-mode)
140 ;; ("\\.rst$" . rst-mode)
141 ;; ("\\.rest$" . rst-mode)) auto-mode-alist))
142 ;;
143
144 ;;; BUGS
145
146 ;; - rst-enumeration-region: Select a single paragraph, with the top at one
147 ;; blank line before the beginning, and it will fail.
148 ;; - The active region goes away when we shift it left or right, and this
149 ;; prevents us from refilling it automatically when shifting many times.
150 ;; - The suggested decorations when adjusting should not have to cycle
151 ;; below one below the last section decoration level preceding the
152 ;; cursor. We need to fix that.
153
154 ;;; TODO LIST
155
156 ;; rst-toc-insert features
157 ;; ------------------------
158 ;; - rst-toc-insert: We should parse the contents:: options to figure out how
159 ;; deep to render the inserted TOC.
160 ;; - On load, detect any existing TOCs and set the properties for links.
161 ;; - TOC insertion should have an option to add empty lines.
162 ;; - TOC insertion should deal with multiple lines.
163 ;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
164 ;; automatic toc update. The cursor ends up in the TOC and this is
165 ;; annoying. Gotta fix that.
166 ;; - numbering: automatically detect if we have a section-numbering directive in
167 ;; the corresponding section, to render the toc.
168 ;;
169 ;; bulleted and enumerated list items
170 ;; ----------------------------------
171 ;; - We need to provide way to rebullet bulleted lists, and that would include
172 ;; automatic enumeration as well.
173 ;;
174 ;; Other
175 ;; -----
176 ;; - It would be nice to differentiate between text files using
177 ;; reStructuredText_ and other general text files. If we had a
178 ;; function to automatically guess whether a .txt file is following the
179 ;; reStructuredText_ conventions, we could trigger rst-mode without
180 ;; having to hard-code this in every text file, nor forcing the user to
181 ;; add a local mode variable at the top of the file.
182 ;; We could perform this guessing by searching for a valid decoration
183 ;; at the top of the document or searching for reStructuredText_
184 ;; directives further on.
185 ;;
186 ;; - We should support imenu in our major mode, with the menu filled with the
187 ;; section titles (this should be really easy).
188 ;;
189 ;; - We should rename "adornment" to "decoration" or vice-versa in this
190 ;; document (Stefan's code ("adornment") vs Martin ("decoration")), maybe some
191 ;; functions even overlap.
192 ;;
193 ;; - We need to automatically recenter on rst-forward-section movement commands.
194
195
196 ;;; HISTORY
197 ;;
198
199 ;;; Code:
200
201 \f
202 (defgroup rst nil "Support for reStructuredText documents."
203 :group 'wp
204 :version "23.1"
205 :link '(url-link "http://docutils.sourceforge.net/rst.html"))
206
207
208
209 \f
210 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
211 ;; Define some generic support functions.
212
213 (eval-when-compile (require 'cl)) ;; We need this for destructuring-bind below.
214
215
216 ;; From Emacs-22
217 (unless (fboundp 'line-number-at-pos)
218 (defun line-number-at-pos (&optional pos)
219 "Return (narrowed) buffer line number at position POS.
220 If POS is nil, use current buffer location."
221 (let ((opoint (or pos (point))) start)
222 (save-excursion
223 (goto-char (point-min))
224 (setq start (point))
225 (goto-char opoint)
226 (forward-line 0)
227 (1+ (count-lines start (point)))))) )
228
229
230 \f
231 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
232 ;; Mode definition.
233
234 ;; Key bindings.
235 (defvar rst-mode-map
236 (let ((map (make-sparse-keymap)))
237
238 ;;
239 ;; Section Decorations.
240 ;;
241 ;; The adjustment function that decorates or rotates a section title.
242 (define-key map [(control c) (control a)] 'rst-adjust)
243 (define-key map [(control c) (control ?=)] 'rst-adjust)
244 (define-key map [(control ?=)] 'rst-adjust) ;; (Does not work on the Mac OSX.)
245 ;; Display the hierarchy of decorations implied by the current document contents.
246 (define-key map [(control c) (control h)] 'rst-display-decorations-hierarchy)
247 ;; Homogeneize the decorations in the document.
248 (define-key map [(control c) (control s)] 'rst-straighten-decorations)
249 ;; (define-key map [(control c) (control s)] 'rst-straighten-deco-spacing)
250
251 ;;
252 ;; Section Movement and Selection.
253 ;;
254 ;; Mark the subsection where the cursor is.
255 (define-key map [(control c) (control m)] 'rst-mark-section)
256 ;; Move forward/backward between section titles.
257 (define-key map [(control c) (control n)] 'rst-forward-section)
258 (define-key map [(control c) (control p)] 'rst-backward-section)
259
260 ;;
261 ;; Operating on Blocks of Text.
262 ;;
263 ;; Makes paragraphs in region as a bullet list.
264 (define-key map [(control c) (control b)] 'rst-bullet-list-region)
265 ;; Makes paragraphs in region as a enumeration.
266 (define-key map [(control c) (control e)] 'rst-enumerate-region)
267 ;; Converts bullets to an enumeration.
268 (define-key map [(control c) (control v)] 'rst-convert-bullets-to-enumeration)
269 ;; Makes region a line-block.
270 (define-key map [(control c) (control d)] 'rst-line-block-region)
271 ;; Make sure that all the bullets in the region are consistent.
272 (define-key map [(control c) (control w)] 'rst-straighten-bullets-region)
273 ;; Shift region left or right (taking into account of enumerations/bullets, etc.).
274 (define-key map [(control c) (control l)] 'rst-shift-region-left)
275 (define-key map [(control c) (control r)] 'rst-shift-region-right)
276 ;; Comment/uncomment the active region.
277 (define-key map [(control c) (control c)] 'comment-region)
278
279 ;;
280 ;; Table-of-Contents Features.
281 ;;
282 ;; Enter a TOC buffer to view and move to a specific section.
283 (define-key map [(control c) (control t)] 'rst-toc)
284 ;; Insert a TOC here.
285 (define-key map [(control c) (control i)] 'rst-toc-insert)
286 ;; Update the document's TOC (without changing the cursor position).
287 (define-key map [(control c) (control u)] 'rst-toc-update)
288 ;; Got to the section under the cursor (cursor must be in TOC).
289 (define-key map [(control c) (control f)] 'rst-goto-section)
290
291 ;;
292 ;; Converting Documents from Emacs.
293 ;;
294 ;; Run one of two pre-configured toolset commands on the document.
295 (define-key map [(control c) (?1)] 'rst-compile)
296 (define-key map [(control c) (?2)] 'rst-compile-alt-toolset)
297 ;; Convert the active region to pseudo-xml using the docutils tools.
298 (define-key map [(control c) (?3)] 'rst-compile-pseudo-region)
299 ;; Convert the current document to PDF and launch a viewer on the results.
300 (define-key map [(control c) (?4)] 'rst-compile-pdf-preview)
301 ;; Convert the current document to S5 slides and view in a web browser.
302 (define-key map [(control c) (?5)] 'rst-compile-slides-preview)
303
304 map)
305 "Keymap for ReStructuredText mode commands.
306 This inherits from Text mode.")
307
308
309 ;; Abbrevs.
310 (defvar rst-mode-abbrev-table nil
311 "Abbrev table used while in Rst mode.")
312 (define-abbrev-table 'rst-mode-abbrev-table
313 '(
314 ("contents" ".. contents::\n..\n " nil 0)
315 ("con" ".. contents::\n..\n " nil 0)
316 ("cont" "[...]" nil 0)
317 ("skip" "\n\n[...]\n\n " nil 0)
318 ("seq" "\n\n[...]\n\n " nil 0)
319 ;; FIXME: Add footnotes, links, and more.
320 ))
321
322
323 ;; Syntax table.
324 (defvar rst-mode-syntax-table
325 (let ((st (copy-syntax-table text-mode-syntax-table)))
326
327 (modify-syntax-entry ?$ "." st)
328 (modify-syntax-entry ?% "." st)
329 (modify-syntax-entry ?& "." st)
330 (modify-syntax-entry ?' "." st)
331 (modify-syntax-entry ?* "." st)
332 (modify-syntax-entry ?+ "." st)
333 (modify-syntax-entry ?. "_" st)
334 (modify-syntax-entry ?/ "." st)
335 (modify-syntax-entry ?< "." st)
336 (modify-syntax-entry ?= "." st)
337 (modify-syntax-entry ?> "." st)
338 (modify-syntax-entry ?\\ "\\" st)
339 (modify-syntax-entry ?| "." st)
340 (modify-syntax-entry ?_ "." st)
341
342 st)
343 "Syntax table used while in `rst-mode'.")
344
345
346 (defcustom rst-mode-hook nil
347 "Hook run when Rst Mode is turned on.
348 The hook for Text Mode is run before this one."
349 :group 'rst
350 :type '(hook))
351
352
353 (defcustom rst-mode-lazy t
354 "If non-nil Rst mode tries to font-lock multi-line elements correctly.
355 Because this is really slow it should be set to nil if neither `jit-lock-mode'
356 not `lazy-lock-mode' and activated.
357
358 If nil, comments and literal blocks are font-locked only on the line they start.
359
360 The value of this variable is used when Rst mode is turned on."
361 :group 'rst
362 :type '(boolean))
363
364 ;; Use rst-mode for *.rst and *.rest files. Many ReStructured-Text files
365 ;; use *.txt, but this is too generic to be set as a default.
366 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.re?st\\'" . rst-mode))
367 ;;;###autoload
368 (define-derived-mode rst-mode text-mode "ReST"
369 "Major mode for editing reStructuredText documents.
370
371 There are a number of convenient keybindings provided by
372 Rst mode. The main one is \\[rst-adjust\], it updates or rotates
373 the section title around point or promotes/demotes the
374 decorations within the region (see full details below).
375 Use negative prefix arg to rotate in the other direction.
376 \\{rst-mode-map}
377
378 Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
379 `rst-mode-hook'. This mode also supports font-lock highlighting.
380 You may customize `rst-mode-lazy' to toggle font-locking of
381 blocks."
382 :abbrev-table rst-mode-abbrev-table
383 :syntax-table rst-mode-syntax-table
384 :group 'rst
385
386 (set (make-local-variable 'paragraph-separate) paragraph-start)
387 (set (make-local-variable 'indent-line-function) 'indent-relative-maybe)
388 (set (make-local-variable 'paragraph-start)
389 "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. ")
390 (set (make-local-variable 'adaptive-fill-mode) t)
391
392 ;; FIXME: No need to reset this.
393 ;; (set (make-local-variable 'indent-line-function) 'indent-relative)
394
395 ;; The details of the following comment setup is important because it affects
396 ;; auto-fill, and it is pretty common in running text to have an ellipsis
397 ;; ("...") which trips because of the rest comment syntax (".. ").
398 (set (make-local-variable 'comment-start) ".. ")
399 (set (make-local-variable 'comment-start-skip) "^\\.\\. ")
400 (set (make-local-variable 'comment-multi-line) nil)
401
402 ;; Special variables
403 (make-local-variable 'rst-adornment-level-alist)
404
405 ;; Font lock
406 (set (make-local-variable 'font-lock-defaults)
407 '(rst-font-lock-keywords-function
408 t nil nil nil
409 (font-lock-mark-block-function . mark-paragraph)))
410 ;; `jit-lock-mode' has been the default since Emacs-21.1, so there's no
411 ;; point messing around with font-lock-support-mode any more.
412 ;; (when (boundp 'font-lock-support-mode)
413 ;; ;; rst-mode has its own mind about font-lock-support-mode
414 ;; (make-local-variable 'font-lock-support-mode)
415 ;; ;; jit-lock-mode replaced lazy-lock-mode in GNU Emacs 21.
416 ;; (let ((jit-or-lazy-lock-mode
417 ;; (cond
418 ;; ((fboundp 'lazy-lock-mode) 'lazy-lock-mode)
419 ;; ((fboundp 'jit-lock-mode) 'jit-lock-mode)
420 ;; ;; if neither lazy-lock nor jit-lock is supported,
421 ;; ;; tell user and disable rst-mode-lazy
422 ;; (t (when rst-mode-lazy
423 ;; (message "Disabled lazy fontification, because no known support mode found.")
424 ;; (setq rst-mode-lazy nil))))))
425 ;; (cond
426 ;; ((and (not rst-mode-lazy) (not font-lock-support-mode)))
427 ;; ;; No support mode set and none required - leave it alone
428 ;; ((or (not font-lock-support-mode) ;; No support mode set (but required)
429 ;; (symbolp font-lock-support-mode)) ;; or a fixed mode for all
430 ;; (setq font-lock-support-mode
431 ;; (list (cons 'rst-mode (and rst-mode-lazy jit-or-lazy-lock-mode))
432 ;; (cons t font-lock-support-mode))))
433 ;; ((and (listp font-lock-support-mode)
434 ;; (not (assoc 'rst-mode font-lock-support-mode)))
435 ;; ;; A list of modes missing rst-mode
436 ;; (setq font-lock-support-mode
437 ;; (cons (cons 'rst-mode (and rst-mode-lazy jit-or-lazy-lock-mode))
438 ;; font-lock-support-mode))))))
439
440 )
441
442
443 ;;;###autoload
444 (define-minor-mode rst-minor-mode
445 "ReST Minor Mode.
446 Toggle ReST minor mode.
447 With no argument, this command toggles the mode.
448 Non-null prefix argument turns on the mode.
449 Null prefix argument turns off the mode.
450
451 When ReST minor mode is enabled, the ReST mode keybindings
452 are installed on top of the major mode bindings. Use this
453 for modes derived from Text mode, like Mail mode."
454 ;; The initial value.
455 nil
456 ;; The indicator for the mode line.
457 " ReST"
458 ;; The minor mode bindings.
459 rst-mode-map
460 :group 'rst)
461
462 ;; FIXME: can I somehow install these too?
463 ;; :abbrev-table rst-mode-abbrev-table
464 ;; :syntax-table rst-mode-syntax-table
465
466
467
468
469 \f
470 ;; Bulleted item lists.
471 (defcustom rst-bullets
472 '(?- ?* ?+)
473 "List of all possible bullet characters for bulleted lists."
474 :group 'rst)
475
476
477
478 \f
479 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
480 ;; Section Decoration Adjusment
481 ;; ============================
482 ;;
483 ;; The following functions implement a smart automatic title sectioning feature.
484 ;; The idea is that with the cursor sitting on a section title, we try to get as
485 ;; much information from context and try to do the best thing automatically.
486 ;; This function can be invoked many times and/or with prefix argument to rotate
487 ;; between the various sectioning decorations.
488 ;;
489 ;; Definitions: the two forms of sectioning define semantically separate section
490 ;; levels. A sectioning DECORATION consists in:
491 ;;
492 ;; - a CHARACTER
493 ;;
494 ;; - a STYLE which can be either of 'simple' or 'over-and-under'.
495 ;;
496 ;; - an INDENT (meaningful for the over-and-under style only) which determines
497 ;; how many characters and over-and-under style is hanging outside of the
498 ;; title at the beginning and ending.
499 ;;
500 ;; Important note: an existing decoration must be formed by at least two
501 ;; characters to be recognized.
502 ;;
503 ;; Here are two examples of decorations (| represents the window border, column
504 ;; 0):
505 ;;
506 ;; |
507 ;; 1. char: '-' e |Some Title
508 ;; style: simple |----------
509 ;; |
510 ;; 2. char: '=' |==============
511 ;; style: over-and-under | Some Title
512 ;; indent: 2 |==============
513 ;; |
514 ;;
515 ;; Some notes:
516 ;;
517 ;; - The underlining character that is used depends on context. The file is
518 ;; scanned to find other sections and an appropriate character is selected.
519 ;; If the function is invoked on a section that is complete, the character is
520 ;; rotated among the existing section decorations.
521 ;;
522 ;; Note that when rotating the characters, if we come to the end of the
523 ;; hierarchy of decorations, the variable rst-preferred-decorations is
524 ;; consulted to propose a new underline decoration, and if continued, we cycle
525 ;; the decorations all over again. Set this variable to nil if you want to
526 ;; limit the underlining character propositions to the existing decorations in
527 ;; the file.
528 ;;
529 ;; - A prefix argument can be used to alternate the style.
530 ;;
531 ;; - An underline/overline that is not extended to the column at which it should
532 ;; be hanging is dubbed INCOMPLETE. For example::
533 ;;
534 ;; |Some Title
535 ;; |-------
536 ;;
537 ;; Examples of default invocation:
538 ;;
539 ;; |Some Title ---> |Some Title
540 ;; | |----------
541 ;;
542 ;; |Some Title ---> |Some Title
543 ;; |----- |----------
544 ;;
545 ;; | |------------
546 ;; | Some Title ---> | Some Title
547 ;; | |------------
548 ;;
549 ;; In over-and-under style, when alternating the style, a variable is
550 ;; available to select how much default indent to use (it can be zero). Note
551 ;; that if the current section decoration already has an indent, we don't
552 ;; adjust it to the default, we rather use the current indent that is already
553 ;; there for adjustment (unless we cycle, in which case we use the indent
554 ;; that has been found previously).
555
556 (defgroup rst-adjust nil
557 "Settings for adjustment and cycling of section title decorations."
558 :group 'rst
559 :version "21.1")
560
561 (defcustom rst-preferred-decorations '( (?= over-and-under 1)
562 (?= simple 0)
563 (?- simple 0)
564 (?~ simple 0)
565 (?+ simple 0)
566 (?` simple 0)
567 (?# simple 0)
568 (?@ simple 0) )
569 "Preferred ordering of section title decorations.
570
571 This sequence is consulted to offer a new decoration suggestion
572 when we rotate the underlines at the end of the existing
573 hierarchy of characters, or when there is no existing section
574 title in the file."
575 :group 'rst-adjust)
576
577
578 (defcustom rst-default-indent 1
579 "Number of characters to indent the section title.
580
581 This is used for when toggling decoration styles, when switching
582 from a simple decoration style to a over-and-under decoration
583 style."
584 :group 'rst-adjust)
585
586
587 (defvar rst-section-text-regexp "^[ \t]*\\S-*\\w\\S-*"
588 "Regular expression for valid section title text.")
589
590
591 (defun rst-line-homogeneous-p (&optional accept-special)
592 "Return true if the line is homogeneous.
593
594 Predicate that returns the unique char if the current line is
595 composed only of a single repeated non-whitespace character.
596 This returns the char even if there is whitespace at the
597 beginning of the line.
598
599 If ACCEPT-SPECIAL is specified we do not ignore special sequences
600 which normally we would ignore when doing a search on many lines.
601 For example, normally we have cases to ignore commonly occurring
602 patterns, such as :: or ...; with the flag do not ignore them."
603 (save-excursion
604 (back-to-indentation)
605 (unless (looking-at "\n")
606 (let ((c (thing-at-point 'char)))
607 (if (and (looking-at (format "[%s]+[ \t]*$" c))
608 (or accept-special
609 (and
610 ;; Common patterns.
611 (not (looking-at "::[ \t]*$"))
612 (not (looking-at "\\.\\.\\.[ \t]*$"))
613 ;; Discard one char line
614 (not (looking-at ".[ \t]*$"))
615 )))
616 (string-to-char c))
617 ))
618 ))
619
620 (defun rst-line-homogeneous-nodent-p (&optional accept-special)
621 "Return true if the line is homogeneous with no indent.
622 See `rst-line-homogeneous-p' about ACCEPT-SPECIAL."
623 (save-excursion
624 (beginning-of-line)
625 (if (looking-at "^[ \t]+")
626 nil
627 (rst-line-homogeneous-p accept-special)
628 )))
629
630
631 (defun rst-compare-decorations (deco1 deco2)
632 "Compare decorations.
633 Return true if both DECO1 and DECO2 decorations are equal,
634 according to restructured text semantics (only the character and
635 the style are compared, the indentation does not matter)."
636 (and (eq (car deco1) (car deco2))
637 (eq (cadr deco1) (cadr deco2))))
638
639
640 (defun rst-get-decoration-match (hier deco)
641 "Return the index (level) in hierarchy HIER of decoration DECO.
642 This basically just searches for the item using the appropriate
643 comparison and returns the index. Return nil if the item is
644 not found."
645 (let ((cur hier))
646 (while (and cur (not (rst-compare-decorations (car cur) deco)))
647 (setq cur (cdr cur)))
648 cur))
649
650
651 (defun rst-suggest-new-decoration (alldecos &optional prev)
652 "Suggest a new, different decoration from all that have been seen.
653
654 ALLDECOS is the set of all decorations, including the line numbers.
655 PREV is the optional previous decoration, in order to suggest a
656 better match."
657
658 ;; For all the preferred decorations...
659 (let* (
660 ;; If 'prev' is given, reorder the list to start searching after the
661 ;; match.
662 (fplist
663 (cdr (rst-get-decoration-match rst-preferred-decorations prev)))
664
665 ;; List of candidates to search.
666 (curpotential (append fplist rst-preferred-decorations)))
667 (while
668 ;; For all the decorations...
669 (let ((cur alldecos)
670 found)
671 (while (and cur (not found))
672 (if (rst-compare-decorations (car cur) (car curpotential))
673 ;; Found it!
674 (setq found (car curpotential))
675 (setq cur (cdr cur))))
676 found)
677
678 (setq curpotential (cdr curpotential)))
679
680 (copy-sequence (car curpotential))))
681
682 (defun rst-delete-entire-line ()
683 "Delete the entire current line without using the `kill-ring'."
684 (delete-region (line-beginning-position)
685 (line-beginning-position 2)))
686
687 (defun rst-update-section (char style &optional indent)
688 "Unconditionally update the style of a section decoration.
689
690 Do this using the given character CHAR, with STYLE 'simple
691 or 'over-and-under, and with indent INDENT. If the STYLE
692 is 'simple, whitespace before the title is removed (indent
693 is always assumed to be 0).
694
695 If there are existing overline and/or underline from the
696 existing decoration, they are removed before adding the
697 requested decoration."
698
699 (interactive)
700 (let (marker
701 len)
702
703 (end-of-line)
704 (setq marker (point-marker))
705
706 ;; Fixup whitespace at the beginning and end of the line
707 (if (or (null indent) (eq style 'simple))
708 (setq indent 0))
709 (beginning-of-line)
710 (delete-horizontal-space)
711 (insert (make-string indent ? ))
712
713 (end-of-line)
714 (delete-horizontal-space)
715
716 ;; Set the current column, we're at the end of the title line
717 (setq len (+ (current-column) indent))
718
719 ;; Remove previous line if it consists only of a single repeated character
720 (save-excursion
721 (forward-line -1)
722 (and (rst-line-homogeneous-p 1)
723 ;; Avoid removing the underline of a title right above us.
724 (save-excursion (forward-line -1)
725 (not (looking-at rst-section-text-regexp)))
726 (rst-delete-entire-line)))
727
728 ;; Remove following line if it consists only of a single repeated
729 ;; character
730 (save-excursion
731 (forward-line +1)
732 (and (rst-line-homogeneous-p 1)
733 (rst-delete-entire-line))
734 ;; Add a newline if we're at the end of the buffer, for the subsequence
735 ;; inserting of the underline
736 (if (= (point) (buffer-end 1))
737 (newline 1)))
738
739 ;; Insert overline
740 (if (eq style 'over-and-under)
741 (save-excursion
742 (beginning-of-line)
743 (open-line 1)
744 (insert (make-string len char))))
745
746 ;; Insert underline
747 (forward-line +1)
748 (open-line 1)
749 (insert (make-string len char))
750
751 (forward-line +1)
752 (goto-char marker)
753 ))
754
755
756 (defun rst-normalize-cursor-position ()
757 "Normalize the cursor position.
758 If the cursor is on a decoration line or an empty line , place it
759 on the section title line (at the end). Returns the line offset
760 by which the cursor was moved. This works both over or under a
761 line."
762 (if (save-excursion (beginning-of-line)
763 (or (rst-line-homogeneous-p 1)
764 (looking-at "^[ \t]*$")))
765 (progn
766 (beginning-of-line)
767 (cond
768 ((save-excursion (forward-line -1)
769 (beginning-of-line)
770 (and (looking-at rst-section-text-regexp)
771 (not (rst-line-homogeneous-p 1))))
772 (progn (forward-line -1) -1))
773 ((save-excursion (forward-line +1)
774 (beginning-of-line)
775 (and (looking-at rst-section-text-regexp)
776 (not (rst-line-homogeneous-p 1))))
777 (progn (forward-line +1) +1))
778 (t 0)))
779 0 ))
780
781
782 (defun rst-find-all-decorations ()
783 "Find all the decorations in the file.
784 Return a list of (line, decoration) pairs. Each decoration
785 consists in a (char, style, indent) triple.
786
787 This function does not detect the hierarchy of decorations, it
788 just finds all of them in a file. You can then invoke another
789 function to remove redundancies and inconsistencies."
790
791 (let (positions
792 (curline 1))
793 ;; Iterate over all the section titles/decorations in the file.
794 (save-excursion
795 (goto-char (point-min))
796 (while (< (point) (buffer-end 1))
797 (if (rst-line-homogeneous-nodent-p)
798 (progn
799 (setq curline (+ curline (rst-normalize-cursor-position)))
800
801 ;; Here we have found a potential site for a decoration,
802 ;; characterize it.
803 (let ((deco (rst-get-decoration)))
804 (if (cadr deco) ;; Style is existing.
805 ;; Found a real decoration site.
806 (progn
807 (push (cons curline deco) positions)
808 ;; Push beyond the underline.
809 (forward-line 1)
810 (setq curline (+ curline 1))
811 )))
812 ))
813 (forward-line 1)
814 (setq curline (+ curline 1))
815 ))
816 (reverse positions)))
817
818
819 (defun rst-infer-hierarchy (decorations)
820 "Build a hierarchy of decorations using the list of given DECORATIONS.
821
822 This function expects a list of (char, style, indent) decoration
823 specifications, in order that they appear in a file, and will
824 infer a hierarchy of section levels by removing decorations that
825 have already been seen in a forward traversal of the decorations,
826 comparing just the character and style.
827
828 Similarly returns a list of (char, style, indent), where each
829 list element should be unique."
830
831 (let ((hierarchy-alist (list)))
832 (dolist (x decorations)
833 (let ((char (car x))
834 (style (cadr x)))
835 (unless (assoc (cons char style) hierarchy-alist)
836 (push (cons (cons char style) x) hierarchy-alist))
837 ))
838
839 (mapcar 'cdr (nreverse hierarchy-alist))
840 ))
841
842
843 (defun rst-get-hierarchy (&optional alldecos ignore)
844 "Return the hierarchy of section titles in the file.
845
846 Return a list of decorations that represents the hierarchy of
847 section titles in the file. Reuse the list of decorations
848 already computed in ALLDECOS if present. If the line number in
849 IGNORE is specified, the decoration found on that line (if there
850 is one) is not taken into account when building the hierarchy."
851 (let ((all (or alldecos (rst-find-all-decorations))))
852 (setq all (assq-delete-all ignore all))
853 (rst-infer-hierarchy (mapcar 'cdr all))))
854
855
856 (defun rst-get-decoration (&optional point)
857 "Get the decoration at POINT.
858
859 Looks around point and finds the characteristics of the
860 decoration that is found there. Assumes that the cursor is
861 already placed on the title line (and not on the overline or
862 underline).
863
864 This function returns a (char, style, indent) triple. If the
865 characters of overline and underline are different, return
866 the underline character. The indent is always calculated.
867 A decoration can be said to exist if the style is not nil.
868
869 A point can be specified to go to the given location before
870 extracting the decoration."
871
872 (let (char style indent)
873 (save-excursion
874 (if point (goto-char point))
875 (beginning-of-line)
876 (if (looking-at rst-section-text-regexp)
877 (let* ((over (save-excursion
878 (forward-line -1)
879 (rst-line-homogeneous-nodent-p)))
880
881 (under (save-excursion
882 (forward-line +1)
883 (rst-line-homogeneous-nodent-p)))
884 )
885
886 ;; Check that the line above the overline is not part of a title
887 ;; above it.
888 (if (and over
889 (save-excursion
890 (and (equal (forward-line -2) 0)
891 (looking-at rst-section-text-regexp))))
892 (setq over nil))
893
894 (cond
895 ;; No decoration found, leave all return values nil.
896 ((and (eq over nil) (eq under nil)))
897
898 ;; Overline only, leave all return values nil.
899 ;;
900 ;; Note: we don't return the overline character, but it could
901 ;; perhaps in some cases be used to do something.
902 ((and over (eq under nil)))
903
904 ;; Underline only.
905 ((and under (eq over nil))
906 (setq char under
907 style 'simple))
908
909 ;; Both overline and underline.
910 (t
911 (setq char under
912 style 'over-and-under))
913 )
914 )
915 )
916 ;; Find indentation.
917 (setq indent (save-excursion (back-to-indentation) (current-column)))
918 )
919 ;; Return values.
920 (list char style indent)))
921
922
923 (defun rst-get-decorations-around (&optional alldecos)
924 "Return the decorations around point.
925
926 Given the list of all decorations ALLDECOS (with positions),
927 find the decorations before and after the given point.
928 A list of the previous and next decorations is returned."
929 (let* ((all (or alldecos (rst-find-all-decorations)))
930 (curline (line-number-at-pos))
931 prev next
932 (cur all))
933
934 ;; Search for the decorations around the current line.
935 (while (and cur (< (caar cur) curline))
936 (setq prev cur
937 cur (cdr cur)))
938 ;; 'cur' is the following decoration.
939
940 (if (and cur (caar cur))
941 (setq next (if (= curline (caar cur)) (cdr cur) cur)))
942
943 (mapcar 'cdar (list prev next))
944 ))
945
946
947 (defun rst-decoration-complete-p (deco)
948 "Return true if the decoration DECO around point is complete."
949 ;; Note: we assume that the detection of the overline as being the underline
950 ;; of a preceding title has already been detected, and has been eliminated
951 ;; from the decoration that is given to us.
952
953 ;; There is some sectioning already present, so check if the current
954 ;; sectioning is complete and correct.
955 (let* ((char (car deco))
956 (style (cadr deco))
957 (indent (caddr deco))
958 (endcol (save-excursion (end-of-line) (current-column)))
959 )
960 (if char
961 (let ((exps (concat "^"
962 (regexp-quote (make-string (+ endcol indent) char))
963 "$")))
964 (and
965 (save-excursion (forward-line +1)
966 (beginning-of-line)
967 (looking-at exps))
968 (or (not (eq style 'over-and-under))
969 (save-excursion (forward-line -1)
970 (beginning-of-line)
971 (looking-at exps))))
972 ))
973 ))
974
975
976 (defun rst-get-next-decoration
977 (curdeco hier &optional suggestion reverse-direction)
978 "Get the next decoration for CURDECO, in given hierarchy HIER.
979 If suggesting, suggest for new decoration SUGGESTION.
980 REVERSE-DIRECTION is used to reverse the cycling order."
981
982 (let* (
983 (char (car curdeco))
984 (style (cadr curdeco))
985
986 ;; Build a new list of decorations for the rotation.
987 (rotdecos
988 (append hier
989 ;; Suggest a new decoration.
990 (list suggestion
991 ;; If nothing to suggest, use first decoration.
992 (car hier)))) )
993 (or
994 ;; Search for next decoration.
995 (cadr
996 (let ((cur (if reverse-direction rotdecos
997 (reverse rotdecos))))
998 (while (and cur
999 (not (and (eq char (caar cur))
1000 (eq style (cadar cur)))))
1001 (setq cur (cdr cur)))
1002 cur))
1003
1004 ;; If not found, take the first of all decorations.
1005 suggestion
1006 )))
1007
1008
1009 (defun rst-adjust ()
1010 "Auto-adjust the decoration around point.
1011
1012 Adjust/rotate the section decoration for the section title
1013 around point or promote/demote the decorations inside the region,
1014 depending on if the region is active. This function is meant to
1015 be invoked possibly multiple times, and can vary its behavior
1016 with a positive prefix argument (toggle style), or with a
1017 negative prefix argument (alternate behavior).
1018
1019 This function is the main focus of this module and is a bit of a
1020 swiss knife. It is meant as the single most essential function
1021 to be bound to invoke to adjust the decorations of a section
1022 title in restructuredtext. It tries to deal with all the
1023 possible cases gracefully and to do `the right thing' in all
1024 cases.
1025
1026 See the documentations of `rst-adjust-decoration' and
1027 `rst-promote-region' for full details.
1028
1029 Prefix Arguments
1030 ================
1031
1032 The method can take either (but not both) of
1033
1034 a. a (non-negative) prefix argument, which means to toggle the
1035 decoration style. Invoke with a prefix arg for example;
1036
1037 b. a negative numerical argument, which generally inverts the
1038 direction of search in the file or hierarchy. Invoke with C--
1039 prefix for example."
1040 (interactive)
1041
1042 (let* (;; Save our original position on the current line.
1043 (origpt (set-marker (make-marker) (point)))
1044
1045 ;; Parse the positive and negative prefix arguments.
1046 (reverse-direction
1047 (and current-prefix-arg
1048 (< (prefix-numeric-value current-prefix-arg) 0)))
1049 (toggle-style
1050 (and current-prefix-arg (not reverse-direction))))
1051
1052 (if (rst-portable-mark-active-p)
1053 ;; Adjust decorations within region.
1054 (rst-promote-region current-prefix-arg)
1055 ;; Adjust decoration around point.
1056 (rst-adjust-decoration toggle-style reverse-direction))
1057
1058 ;; Run the hooks to run after adjusting.
1059 (run-hooks 'rst-adjust-hook)
1060
1061 ;; Make sure to reset the cursor position properly after we're done.
1062 (goto-char origpt)
1063
1064 ))
1065
1066 (defvar rst-adjust-hook nil
1067 "Hooks to be run after running `rst-adjust'.")
1068
1069 (defvar rst-new-decoration-down nil
1070 "Non-nil if new decoration is added deeper.
1071 If non-nil, a new decoration being added will be initialized to
1072 be one level down from the previous decoration. If nil, a new
1073 decoration will be equal to the level of the previous
1074 decoration.")
1075
1076 (defun rst-adjust-decoration (&optional toggle-style reverse-direction)
1077 "Adjust/rotate the section decoration for the section title around point.
1078
1079 This function is meant to be invoked possibly multiple times, and
1080 can vary its behavior with a true TOGGLE-STYLE argument, or with
1081 a REVERSE-DIRECTION argument.
1082
1083 General Behavior
1084 ================
1085
1086 The next action it takes depends on context around the point, and
1087 it is meant to be invoked possibly more than once to rotate among
1088 the various possibilities. Basically, this function deals with:
1089
1090 - adding a decoration if the title does not have one;
1091
1092 - adjusting the length of the underline characters to fit a
1093 modified title;
1094
1095 - rotating the decoration in the set of already existing
1096 sectioning decorations used in the file;
1097
1098 - switching between simple and over-and-under styles.
1099
1100 You should normally not have to read all the following, just
1101 invoke the method and it will do the most obvious thing that you
1102 would expect.
1103
1104
1105 Decoration Definitions
1106 ======================
1107
1108 The decorations consist in
1109
1110 1. a CHARACTER
1111
1112 2. a STYLE which can be either of 'simple' or 'over-and-under'.
1113
1114 3. an INDENT (meaningful for the over-and-under style only)
1115 which determines how many characters and over-and-under
1116 style is hanging outside of the title at the beginning and
1117 ending.
1118
1119 See source code for mode details.
1120
1121
1122 Detailed Behavior Description
1123 =============================
1124
1125 Here are the gory details of the algorithm (it seems quite
1126 complicated, but really, it does the most obvious thing in all
1127 the particular cases):
1128
1129 Before applying the decoration change, the cursor is placed on
1130 the closest line that could contain a section title.
1131
1132 Case 1: No Decoration
1133 ---------------------
1134
1135 If the current line has no decoration around it,
1136
1137 - search backwards for the last previous decoration, and apply
1138 the decoration one level lower to the current line. If there
1139 is no defined level below this previous decoration, we suggest
1140 the most appropriate of the `rst-preferred-decorations'.
1141
1142 If REVERSE-DIRECTION is true, we simply use the previous
1143 decoration found directly.
1144
1145 - if there is no decoration found in the given direction, we use
1146 the first of `rst-preferred-decorations'.
1147
1148 The prefix argument forces a toggle of the prescribed decoration
1149 style.
1150
1151 Case 2: Incomplete Decoration
1152 -----------------------------
1153
1154 If the current line does have an existing decoration, but the
1155 decoration is incomplete, that is, the underline/overline does
1156 not extend to exactly the end of the title line (it is either too
1157 short or too long), we simply extend the length of the
1158 underlines/overlines to fit exactly the section title.
1159
1160 If the prefix argument is given, we toggle the style of the
1161 decoration as well.
1162
1163 REVERSE-DIRECTION has no effect in this case.
1164
1165 Case 3: Complete Existing Decoration
1166 ------------------------------------
1167
1168 If the decoration is complete (i.e. the underline (overline)
1169 length is already adjusted to the end of the title line), we
1170 search/parse the file to establish the hierarchy of all the
1171 decorations (making sure not to include the decoration around
1172 point), and we rotate the current title's decoration from within
1173 that list (by default, going *down* the hierarchy that is present
1174 in the file, i.e. to a lower section level). This is meant to be
1175 used potentially multiple times, until the desired decoration is
1176 found around the title.
1177
1178 If we hit the boundary of the hierarchy, exactly one choice from
1179 the list of preferred decorations is suggested/chosen, the first
1180 of those decoration that has not been seen in the file yet (and
1181 not including the decoration around point), and the next
1182 invocation rolls over to the other end of the hierarchy (i.e. it
1183 cycles). This allows you to avoid having to set which character
1184 to use.
1185
1186 If REVERSE-DIRECTION is true, the effect is to change the
1187 direction of rotation in the hierarchy of decorations, thus
1188 instead going *up* the hierarchy.
1189
1190 However, if there is a non-negative prefix argument, we do not
1191 rotate the decoration, but instead simply toggle the style of the
1192 current decoration (this should be the most common way to toggle
1193 the style of an existing complete decoration).
1194
1195
1196 Point Location
1197 ==============
1198
1199 The invocation of this function can be carried out anywhere
1200 within the section title line, on an existing underline or
1201 overline, as well as on an empty line following a section title.
1202 This is meant to be as convenient as possible.
1203
1204
1205 Indented Sections
1206 =================
1207
1208 Indented section titles such as ::
1209
1210 My Title
1211 --------
1212
1213 are invalid in restructuredtext and thus not recognized by the
1214 parser. This code will thus not work in a way that would support
1215 indented sections (it would be ambiguous anyway).
1216
1217
1218 Joint Sections
1219 ==============
1220
1221 Section titles that are right next to each other may not be
1222 treated well. More work might be needed to support those, and
1223 special conditions on the completeness of existing decorations
1224 might be required to make it non-ambiguous.
1225
1226 For now we assume that the decorations are disjoint, that is,
1227 there is at least a single line between the titles/decoration
1228 lines.
1229
1230
1231 Suggested Binding
1232 =================
1233
1234 We suggest that you bind this function on C-=. It is close to
1235 C-- so a negative argument can be easily specified with a flick
1236 of the right hand fingers and the binding is unused in `text-mode'."
1237 (interactive)
1238
1239 ;; If we were invoked directly, parse the prefix arguments into the
1240 ;; arguments of the function.
1241 (if current-prefix-arg
1242 (setq reverse-direction
1243 (and current-prefix-arg
1244 (< (prefix-numeric-value current-prefix-arg) 0))
1245
1246 toggle-style
1247 (and current-prefix-arg (not reverse-direction))))
1248
1249 (let* (;; Check if we're on an underline around a section title, and move the
1250 ;; cursor to the title if this is the case.
1251 (moved (rst-normalize-cursor-position))
1252
1253 ;; Find the decoration and completeness around point.
1254 (curdeco (rst-get-decoration))
1255 (char (car curdeco))
1256 (style (cadr curdeco))
1257 (indent (caddr curdeco))
1258
1259 ;; New values to be computed.
1260 char-new style-new indent-new
1261 )
1262
1263 ;; We've moved the cursor... if we're not looking at some text, we have
1264 ;; nothing to do.
1265 (if (save-excursion (beginning-of-line)
1266 (looking-at rst-section-text-regexp))
1267 (progn
1268 (cond
1269 ;;-------------------------------------------------------------------
1270 ;; Case 1: No Decoration
1271 ((and (eq char nil) (eq style nil))
1272
1273 (let* ((alldecos (rst-find-all-decorations))
1274
1275 (around (rst-get-decorations-around alldecos))
1276 (prev (car around))
1277 cur
1278
1279 (hier (rst-get-hierarchy alldecos))
1280 )
1281
1282 ;; Advance one level down.
1283 (setq cur
1284 (if prev
1285 (if (not reverse-direction)
1286 (or (funcall (if rst-new-decoration-down 'cadr 'car)
1287 (rst-get-decoration-match hier prev))
1288 (rst-suggest-new-decoration hier prev))
1289 prev)
1290 (copy-sequence (car rst-preferred-decorations))))
1291
1292 ;; Invert the style if requested.
1293 (if toggle-style
1294 (setcar (cdr cur) (if (eq (cadr cur) 'simple)
1295 'over-and-under 'simple)) )
1296
1297 (setq char-new (car cur)
1298 style-new (cadr cur)
1299 indent-new (caddr cur))
1300 ))
1301
1302 ;;-------------------------------------------------------------------
1303 ;; Case 2: Incomplete Decoration
1304 ((not (rst-decoration-complete-p curdeco))
1305
1306 ;; Invert the style if requested.
1307 (if toggle-style
1308 (setq style (if (eq style 'simple) 'over-and-under 'simple)))
1309
1310 (setq char-new char
1311 style-new style
1312 indent-new indent))
1313
1314 ;;-------------------------------------------------------------------
1315 ;; Case 3: Complete Existing Decoration
1316 (t
1317 (if toggle-style
1318
1319 ;; Simply switch the style of the current decoration.
1320 (setq char-new char
1321 style-new (if (eq style 'simple) 'over-and-under 'simple)
1322 indent-new rst-default-indent)
1323
1324 ;; Else, we rotate, ignoring the decoration around the current
1325 ;; line...
1326 (let* ((alldecos (rst-find-all-decorations))
1327
1328 (hier (rst-get-hierarchy alldecos (line-number-at-pos)))
1329
1330 ;; Suggestion, in case we need to come up with something
1331 ;; new
1332 (suggestion (rst-suggest-new-decoration
1333 hier
1334 (car (rst-get-decorations-around alldecos))))
1335
1336 (nextdeco (rst-get-next-decoration
1337 curdeco hier suggestion reverse-direction))
1338
1339 )
1340
1341 ;; Indent, if present, always overrides the prescribed indent.
1342 (setq char-new (car nextdeco)
1343 style-new (cadr nextdeco)
1344 indent-new (caddr nextdeco))
1345
1346 )))
1347 )
1348
1349 ;; Override indent with present indent!
1350 (setq indent-new (if (> indent 0) indent indent-new))
1351
1352 (if (and char-new style-new)
1353 (rst-update-section char-new style-new indent-new))
1354 ))
1355
1356
1357 ;; Correct the position of the cursor to more accurately reflect where it
1358 ;; was located when the function was invoked.
1359 (unless (= moved 0)
1360 (forward-line (- moved))
1361 (end-of-line))
1362
1363 ))
1364
1365 ;; Maintain an alias for compatibility.
1366 (defalias 'rst-adjust-section-title 'rst-adjust)
1367
1368
1369 (defun rst-promote-region (&optional demote)
1370 "Promote the section titles within the region.
1371
1372 With argument DEMOTE or a prefix argument, demote the
1373 section titles instead. The algorithm used at the boundaries of
1374 the hierarchy is similar to that used by `rst-adjust-decoration'."
1375 (interactive)
1376
1377 (let* ((demote (or current-prefix-arg demote))
1378 (alldecos (rst-find-all-decorations))
1379 (cur alldecos)
1380
1381 (hier (rst-get-hierarchy alldecos))
1382 (suggestion (rst-suggest-new-decoration hier))
1383
1384 (region-begin-line (line-number-at-pos (region-beginning)))
1385 (region-end-line (line-number-at-pos (region-end)))
1386
1387 marker-list
1388 )
1389
1390 ;; Skip the markers that come before the region beginning
1391 (while (and cur (< (caar cur) region-begin-line))
1392 (setq cur (cdr cur)))
1393
1394 ;; Create a list of markers for all the decorations which are found within
1395 ;; the region.
1396 (save-excursion
1397 (let (m line)
1398 (while (and cur (< (setq line (caar cur)) region-end-line))
1399 (setq m (make-marker))
1400 (goto-line line)
1401 (push (list (set-marker m (point)) (cdar cur)) marker-list)
1402 (setq cur (cdr cur)) ))
1403
1404 ;; Apply modifications.
1405 (let (nextdeco)
1406 (dolist (p marker-list)
1407 ;; Go to the decoration to promote.
1408 (goto-char (car p))
1409
1410 ;; Rotate the next decoration.
1411 (setq nextdeco (rst-get-next-decoration
1412 (cadr p) hier suggestion demote))
1413
1414 ;; Update the decoration.
1415 (apply 'rst-update-section nextdeco)
1416
1417 ;; Clear marker to avoid slowing down the editing after we're done.
1418 (set-marker (car p) nil)
1419 ))
1420 (setq deactivate-mark nil)
1421 )))
1422
1423
1424
1425 (defun rst-display-decorations-hierarchy (&optional decorations)
1426 "Display the current file's section title decorations hierarchy.
1427 This function expects a list of (char, style, indent) triples in
1428 DECORATIONS."
1429 (interactive)
1430
1431 (if (not decorations)
1432 (setq decorations (rst-get-hierarchy)))
1433 (with-output-to-temp-buffer "*rest section hierarchy*"
1434 (let ((level 1))
1435 (with-current-buffer standard-output
1436 (dolist (x decorations)
1437 (insert (format "\nSection Level %d" level))
1438 (apply 'rst-update-section x)
1439 (goto-char (point-max))
1440 (insert "\n")
1441 (incf level)
1442 ))
1443 )))
1444
1445 (defun rst-position (elem list)
1446 "Return position of ELEM in LIST or nil."
1447 (let ((tail (member elem list)))
1448 (if tail (- (length list) (length tail)))))
1449
1450 (defun rst-straighten-decorations ()
1451 "Redo all the decorations in the current buffer.
1452 This is done using our preferred set of decorations. This can be
1453 used, for example, when using somebody else's copy of a document,
1454 in order to adapt it to our preferred style."
1455 (interactive)
1456 (save-excursion
1457 (let* ((alldecos (rst-find-all-decorations))
1458 (hier (rst-get-hierarchy alldecos))
1459
1460 ;; Get a list of pairs of (level . marker)
1461 (levels-and-markers (mapcar
1462 (lambda (deco)
1463 (cons (rst-position (cdr deco) hier)
1464 (let ((m (make-marker)))
1465 (goto-line (car deco))
1466 (set-marker m (point))
1467 m)))
1468 alldecos))
1469 )
1470 (dolist (lm levels-and-markers)
1471 ;; Go to the appropriate position
1472 (goto-char (cdr lm))
1473
1474 ;; Apply the new styule
1475 (apply 'rst-update-section (nth (car lm) rst-preferred-decorations))
1476
1477 ;; Reset the market to avoid slowing down editing until it gets GC'ed
1478 (set-marker (cdr lm) nil)
1479 )
1480 )))
1481
1482
1483
1484
1485 (defun rst-straighten-deco-spacing ()
1486 "Adjust the spacing before and after decorations in the entire document.
1487 The spacing will be set to two blank lines before the first two
1488 section levels, and one blank line before any of the other
1489 section levels."
1490 ;; FIXME: we need to take care of subtitle at some point.
1491 (interactive)
1492 (save-excursion
1493 (let* ((alldecos (rst-find-all-decorations)))
1494
1495 ;; Work the list from the end, so that we don't have to use markers to
1496 ;; adjust for the changes in the document.
1497 (dolist (deco (nreverse alldecos))
1498 ;; Go to the appropriate position.
1499 (goto-line (car deco))
1500 (insert "@\n")
1501 ;; FIXME: todo, we
1502 )
1503 )))
1504
1505
1506 (defun rst-find-pfx-in-region (beg end pfx-re)
1507 "Find all the positions of prefixes in region between BEG and END.
1508 This is used to find bullets and enumerated list items. PFX-RE
1509 is a regular expression for matching the lines with items."
1510 (let (pfx)
1511 (save-excursion
1512 (goto-char beg)
1513 (while (< (point) end)
1514 (back-to-indentation)
1515 (when (and
1516 (looking-at pfx-re)
1517 (let ((pfx-col (current-column)))
1518 (save-excursion
1519 (forward-line -1)
1520 (back-to-indentation)
1521 (or (looking-at "^[ \t]*$")
1522 (> (current-column) pfx-col)
1523 (and (= (current-column) pfx-col)
1524 (looking-at pfx-re))))))
1525 (push (cons (point) (current-column))
1526 pfx))
1527 (forward-line 1)) )
1528 (nreverse pfx)))
1529
1530 (defvar rst-re-bullets
1531 (format "\\([%s][ \t]\\)[^ \t]" (regexp-quote (concat rst-bullets)))
1532 "Regexp for finding bullets.")
1533
1534 ;; (defvar rst-re-enumerations
1535 ;; "\\(\\(#\\|[0-9]+\\)\\.[ \t]\\)[^ \t]"
1536 ;; "Regexp for finding bullets.")
1537
1538 (defvar rst-re-items
1539 (format "\\(%s\\|%s\\)[^ \t]"
1540 (format "[%s][ \t]" (regexp-quote (concat rst-bullets)))
1541 "\\(#\\|[0-9]+\\)\\.[ \t]")
1542 "Regexp for finding bullets.")
1543
1544 (defvar rst-preferred-bullets
1545 '(?- ?* ?+)
1546 "List of favourite bullets to set for straightening bullets.")
1547
1548 (defun rst-straighten-bullets-region (beg end)
1549 "Make all the bulleted list items in the region consistent.
1550 The region is specified between BEG and END. You can use this
1551 after you have merged multiple bulleted lists to make them use
1552 the same/correct/consistent bullet characters.
1553
1554 See variable `rst-preferred-bullets' for the list of bullets to
1555 adjust. If bullets are found on levels beyond the
1556 `rst-preferred-bullets' list, they are not modified."
1557 (interactive "r")
1558
1559 (let ((bullets (rst-find-pfx-in-region beg end
1560 rst-re-bullets))
1561 (levtable (make-hash-table :size 4)))
1562
1563 ;; Create a map of levels to list of positions.
1564 (dolist (x bullets)
1565 (let ((key (cdr x)))
1566 (puthash key
1567 (append (gethash key levtable (list))
1568 (list (car x)))
1569 levtable)))
1570
1571 ;; Sort this map and create a new map of prefix char and list of positions.
1572 (let ((poslist ())) ; List of (indent . positions).
1573 (maphash (lambda (x y) (push (cons x y) poslist)) levtable)
1574
1575 (let ((bullets rst-preferred-bullets))
1576 (dolist (x (sort poslist 'car-less-than-car))
1577 (when bullets
1578 ;; Apply the characters.
1579 (dolist (pos (cdr x))
1580 (goto-char pos)
1581 (delete-char 1)
1582 (insert (string (car bullets))))
1583 (setq bullets (cdr bullets))))))))
1584
1585 (defun rst-rstrip (str)
1586 "Strips the whitespace at the end of string STR."
1587 (string-match "[ \t\n]*\\'" str)
1588 (substring str 0 (match-beginning 0)))
1589
1590 (defun rst-get-stripped-line ()
1591 "Return the line at cursor, stripped from whitespace."
1592 (re-search-forward "\\S-.*\\S-" (line-end-position))
1593 (buffer-substring-no-properties (match-beginning 0)
1594 (match-end 0)) )
1595
1596 (defun rst-section-tree (alldecos)
1597 "Get the hierarchical tree of section titles.
1598
1599 Returns a hierarchical tree of the sections titles in the
1600 document, for decorations ALLDECOS. This can be used to generate
1601 a table of contents for the document. The top node will always
1602 be a nil node, with the top level titles as children (there may
1603 potentially be more than one).
1604
1605 Each section title consists in a cons of the stripped title
1606 string and a marker to the section in the original text document.
1607
1608 If there are missing section levels, the section titles are
1609 inserted automatically, and the title string is set to nil, and
1610 the marker set to the first non-nil child of itself.
1611 Conceptually, the nil nodes--i.e. those which have no title--are
1612 to be considered as being the same line as their first non-nil
1613 child. This has advantages later in processing the graph."
1614
1615 (let* ((hier (rst-get-hierarchy alldecos))
1616 (levels (make-hash-table :test 'equal :size 10))
1617 lines)
1618
1619 (let ((lev 0))
1620 (dolist (deco hier)
1621 ;; Compare just the character and indent in the hash table.
1622 (puthash (cons (car deco) (cadr deco)) lev levels)
1623 (incf lev)))
1624
1625 ;; Create a list of lines that contains (text, level, marker) for each
1626 ;; decoration.
1627 (save-excursion
1628 (setq lines
1629 (mapcar (lambda (deco)
1630 (goto-line (car deco))
1631 (list (gethash (cons (cadr deco) (caddr deco)) levels)
1632 (rst-get-stripped-line)
1633 (let ((m (make-marker)))
1634 (beginning-of-line 1)
1635 (set-marker m (point)))
1636 ))
1637 alldecos)))
1638
1639 (let ((lcontnr (cons nil lines)))
1640 (rst-section-tree-rec lcontnr -1))))
1641
1642
1643 (defun rst-section-tree-rec (decos lev)
1644 "Recursive guts of the section tree construction.
1645 DECOS is a cons cell whose cdr is the remaining list of
1646 decorations, and we change it as we consume them. LEV is the
1647 current level of that node. This function returns a pair of the
1648 subtree that was built. This treats the decos list
1649 destructively."
1650
1651 (let ((ndeco (cadr decos))
1652 node
1653 children)
1654
1655 ;; If the next decoration matches our level
1656 (when (and ndeco (= (car ndeco) lev))
1657 ;; Pop the next decoration and create the current node with it
1658 (setcdr decos (cddr decos))
1659 (setq node (cdr ndeco)) )
1660 ;; Else we let the node title/marker be unset.
1661
1662 ;; Build the child nodes
1663 (while (and (cdr decos) (> (caadr decos) lev))
1664 (setq children
1665 (cons (rst-section-tree-rec decos (1+ lev))
1666 children)))
1667 (setq children (reverse children))
1668
1669 ;; If node is still unset, we use the marker of the first child.
1670 (when (eq node nil)
1671 (setq node (cons nil (cdaar children))))
1672
1673 ;; Return this node with its children.
1674 (cons node children)
1675 ))
1676
1677
1678 (defun rst-section-tree-point (node &optional point)
1679 "Find tree node at point.
1680 Given a computed and valid section tree in NODE and a point
1681 POINT (default being the current point in the current buffer),
1682 find and return the node within the sectree where the cursor
1683 lives.
1684
1685 Return values: a pair of (parent path, container subtree).
1686 The parent path is simply a list of the nodes above the
1687 container subtree node that we're returning."
1688
1689 (let (path outtree)
1690
1691 (let* ((curpoint (or point (point))))
1692
1693 ;; Check if we are before the current node.
1694 (if (and (cadar node) (>= curpoint (cadar node)))
1695
1696 ;; Iterate all the children, looking for one that might contain the
1697 ;; current section.
1698 (let ((curnode (cdr node))
1699 last)
1700
1701 (while (and curnode (>= curpoint (cadaar curnode)))
1702 (setq last curnode
1703 curnode (cdr curnode)))
1704
1705 (if last
1706 (let ((sub (rst-section-tree-point (car last) curpoint)))
1707 (setq path (car sub)
1708 outtree (cdr sub)))
1709 (setq outtree node))
1710
1711 )))
1712 (cons (cons (car node) path) outtree)
1713 ))
1714
1715
1716 (defgroup rst-toc nil
1717 "Settings for reStructuredText table of contents."
1718 :group 'rst
1719 :version "21.1")
1720
1721 (defcustom rst-toc-indent 2
1722 "Indentation for table-of-contents display.
1723 Also used for formatting insertion, when numbering is disabled."
1724 :group 'rst-toc)
1725
1726 (defcustom rst-toc-insert-style 'fixed
1727 "Insertion style for table-of-contents.
1728 Set this to one of the following values to determine numbering and
1729 indentation style:
1730 - plain: no numbering (fixed indentation)
1731 - fixed: numbering, but fixed indentation
1732 - aligned: numbering, titles aligned under each other
1733 - listed: numbering, with dashes like list items (EXPERIMENTAL)"
1734 :group 'rst-toc)
1735
1736 (defcustom rst-toc-insert-number-separator " "
1737 "Separator that goes between the TOC number and the title."
1738 :group 'rst-toc)
1739
1740 ;; This is used to avoid having to change the user's mode.
1741 (defvar rst-toc-insert-click-keymap
1742 (let ((map (make-sparse-keymap)))
1743 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
1744 map)
1745 "(Internal) What happens when you click on propertized text in the TOC.")
1746
1747 (defcustom rst-toc-insert-max-level nil
1748 "If non-nil, maximum depth of the inserted TOC."
1749 :group 'rst-toc)
1750
1751
1752 (defun rst-toc-insert (&optional pfxarg)
1753 "Insert a simple text rendering of the table of contents.
1754 By default the top level is ignored if there is only one, because
1755 we assume that the document will have a single title.
1756
1757 If a numeric prefix argument PFXARG is given, insert the TOC up
1758 to the specified level.
1759
1760 The TOC is inserted indented at the current column."
1761
1762 (interactive "P")
1763
1764 (let* (;; Check maximum level override
1765 (rst-toc-insert-max-level
1766 (if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
1767 (prefix-numeric-value pfxarg) rst-toc-insert-max-level))
1768
1769 ;; Get the section tree for the current cursor point.
1770 (sectree-pair
1771 (rst-section-tree-point
1772 (rst-section-tree (rst-find-all-decorations))))
1773
1774 ;; Figure out initial indent.
1775 (initial-indent (make-string (current-column) ? ))
1776 (init-point (point)))
1777
1778 (when (cddr sectree-pair)
1779 (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
1780
1781 ;; Fixup for the first line.
1782 (delete-region init-point (+ init-point (length initial-indent)))
1783
1784 ;; Delete the last newline added.
1785 (delete-backward-char 1)
1786 )))
1787
1788 (defun rst-toc-insert-node (node level indent pfx)
1789 "Insert tree node NODE in table-of-contents.
1790 Recursive function that does printing of the inserted toc.
1791 LEVEL is the depth level of the sections in the tree.
1792 INDENT is the indentation string. PFX is the prefix numbering,
1793 that includes the alignment necessary for all the children of
1794 level to align."
1795
1796 ;; Note: we do child numbering from the parent, so we start number the
1797 ;; children one level before we print them.
1798 (let ((do-print (> level 0))
1799 (count 1))
1800 (when do-print
1801 (insert indent)
1802 (let ((b (point)))
1803 (unless (equal rst-toc-insert-style 'plain)
1804 (insert pfx rst-toc-insert-number-separator))
1805 (insert (or (caar node) "[missing node]"))
1806 ;; Add properties to the text, even though in normal text mode it
1807 ;; won't be doing anything for now. Not sure that I want to change
1808 ;; mode stuff. At least the highlighting gives the idea that this
1809 ;; is generated automatically.
1810 (put-text-property b (point) 'mouse-face 'highlight)
1811 (put-text-property b (point) 'rst-toc-target (cadar node))
1812 (put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
1813
1814 )
1815 (insert "\n")
1816
1817 ;; Prepare indent for children.
1818 (setq indent
1819 (cond
1820 ((eq rst-toc-insert-style 'plain)
1821 (concat indent (make-string rst-toc-indent ? )))
1822
1823 ((eq rst-toc-insert-style 'fixed)
1824 (concat indent (make-string rst-toc-indent ? )))
1825
1826 ((eq rst-toc-insert-style 'aligned)
1827 (concat indent (make-string (+ (length pfx) 2) ? )))
1828
1829 ((eq rst-toc-insert-style 'listed)
1830 (concat (substring indent 0 -3)
1831 (concat (make-string (+ (length pfx) 2) ? ) " - ")))
1832 ))
1833 )
1834
1835 (if (or (eq rst-toc-insert-max-level nil)
1836 (< level rst-toc-insert-max-level))
1837 (let ((do-child-numbering (>= level 0))
1838 fmt)
1839 (if do-child-numbering
1840 (progn
1841 ;; Add a separating dot if there is already a prefix
1842 (if (> (length pfx) 0)
1843 (setq pfx (concat (rst-rstrip pfx) ".")))
1844
1845 ;; Calculate the amount of space that the prefix will require
1846 ;; for the numbers.
1847 (if (cdr node)
1848 (setq fmt (format "%%-%dd"
1849 (1+ (floor (log10 (length
1850 (cdr node))))))))
1851 ))
1852
1853 (dolist (child (cdr node))
1854 (rst-toc-insert-node child
1855 (1+ level)
1856 indent
1857 (if do-child-numbering
1858 (concat pfx (format fmt count)) pfx))
1859 (incf count)))
1860
1861 )))
1862
1863
1864 (defun rst-toc-insert-find-delete-contents ()
1865 "Find and delete an existing comment after the first contents directive.
1866 Delete that region. Return t if found and the cursor is left after the comment."
1867 (goto-char (point-min))
1868 ;; We look for the following and the following only (in other words, if your
1869 ;; syntax differs, this won't work. If you would like a more flexible thing,
1870 ;; contact the author, I just can't imagine that this requirement is
1871 ;; unreasonable for now).
1872 ;;
1873 ;; .. contents:: [...anything here...]
1874 ;; ..
1875 ;; XXXXXXXX
1876 ;; XXXXXXXX
1877 ;; [more lines]
1878 ;;
1879 (let ((beg
1880 (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
1881 nil t))
1882 last-real)
1883 (when beg
1884 ;; Look for the first line that starts at the first column.
1885 (forward-line 1)
1886 (beginning-of-line)
1887 (while (and
1888 (< (point) (point-max))
1889 (or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
1890 (looking-at "[ \t]*$")))
1891 (forward-line 1)
1892 )
1893 (if last-real
1894 (progn
1895 (goto-char last-real)
1896 (end-of-line)
1897 (delete-region beg (point)))
1898 (goto-char beg))
1899 t
1900 )))
1901
1902 (defun rst-toc-update ()
1903 "Automatically find the contents section of a document and update.
1904 Updates the inserted TOC if present. You can use this in your
1905 file-write hook to always make it up-to-date automatically."
1906 (interactive)
1907 (let ((p (point)))
1908 (save-excursion
1909 (when (rst-toc-insert-find-delete-contents)
1910 (insert "\n ")
1911 (rst-toc-insert)
1912 ))
1913 ;; Somehow save-excursion does not really work well.
1914 (goto-char p))
1915 ;; Note: always return nil, because this may be used as a hook.
1916 )
1917
1918 ;; Note: we cannot bind the TOC update on file write because it messes with
1919 ;; undo. If we disable undo, since it adds and removes characters, the
1920 ;; positions in the undo list are not making sense anymore. Dunno what to do
1921 ;; with this, it would be nice to update when saving.
1922 ;;
1923 ;; (add-hook 'write-contents-hooks 'rst-toc-update-fun)
1924 ;; (defun rst-toc-update-fun ()
1925 ;; ;; Disable undo for the write file hook.
1926 ;; (let ((buffer-undo-list t)) (rst-toc-update) ))
1927
1928 (defalias 'rst-toc-insert-update 'rst-toc-update) ;; backwards compat.
1929
1930 ;;------------------------------------------------------------------------------
1931
1932 (defun rst-toc-node (node level)
1933 "Recursive function that does insert NODE at LEVEL in the table-of-contents."
1934
1935 (if (> level 0)
1936 (let ((b (point)))
1937 ;; Insert line text.
1938 (insert (make-string (* rst-toc-indent (1- level)) ? ))
1939 (insert (or (caar node) "[missing node]"))
1940
1941 ;; Highlight lines.
1942 (put-text-property b (point) 'mouse-face 'highlight)
1943
1944 ;; Add link on lines.
1945 (put-text-property b (point) 'rst-toc-target (cadar node))
1946
1947 (insert "\n")
1948 ))
1949
1950 (dolist (child (cdr node))
1951 (rst-toc-node child (1+ level))))
1952
1953 (defun rst-toc-count-lines (node target-node)
1954 "Count the number of lines from NODE to the TARGET-NODE node.
1955 This recursive function returns a cons of the number of
1956 additional lines that have been counted for its node and
1957 children, and t if the node has been found."
1958
1959 (let ((count 1)
1960 found)
1961 (if (eq node target-node)
1962 (setq found t)
1963 (let ((child (cdr node)))
1964 (while (and child (not found))
1965 (let ((cl (rst-toc-count-lines (car child) target-node)))
1966 (setq count (+ count (car cl))
1967 found (cdr cl)
1968 child (cdr child))))))
1969 (cons count found)))
1970
1971 (defvar rst-toc-buffer-name "*Table of Contents*"
1972 "Name of the Table of Contents buffer.")
1973
1974 (defvar rst-toc-return-buffer nil
1975 "Buffer to which to return when leaving the TOC.")
1976
1977
1978 (defun rst-toc ()
1979 "Display a table-of-contents.
1980 Finds all the section titles and their decorations in the
1981 file, and displays a hierarchically-organized list of the
1982 titles, which is essentially a table-of-contents of the
1983 document.
1984
1985 The Emacs buffer can be navigated, and selecting a section
1986 brings the cursor in that section."
1987 (interactive)
1988 (let* ((curbuf (current-buffer))
1989
1990 ;; Get the section tree
1991 (alldecos (rst-find-all-decorations))
1992 (sectree (rst-section-tree alldecos))
1993
1994 (our-node (cdr (rst-section-tree-point sectree)))
1995 line
1996
1997 ;; Create a temporary buffer.
1998 (buf (get-buffer-create rst-toc-buffer-name))
1999 )
2000
2001 (with-current-buffer buf
2002 (let ((inhibit-read-only t))
2003 (rst-toc-mode)
2004 (delete-region (point-min) (point-max))
2005 (insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
2006 (put-text-property (point-min) (point)
2007 'face (list '(background-color . "gray")))
2008 (rst-toc-node sectree 0)
2009
2010 ;; Count the lines to our found node.
2011 (let ((linefound (rst-toc-count-lines sectree our-node)))
2012 (setq line (if (cdr linefound) (car linefound) 0)))
2013 ))
2014 (display-buffer buf)
2015 (pop-to-buffer buf)
2016
2017 ;; Save the buffer to return to.
2018 (set (make-local-variable 'rst-toc-return-buffer) curbuf)
2019
2020 ;; Move the cursor near the right section in the TOC.
2021 (goto-line line)
2022 ))
2023
2024
2025 (defun rst-toc-mode-find-section ()
2026 "Get the section from text property at point."
2027 (let ((pos (get-text-property (point) 'rst-toc-target)))
2028 (unless pos
2029 (error "No section on this line"))
2030 (unless (buffer-live-p (marker-buffer pos))
2031 (error "Buffer for this section was killed"))
2032 pos))
2033
2034 (defun rst-goto-section (&optional kill)
2035 "Go to the section the current line describes."
2036 (interactive)
2037 (let ((pos (rst-toc-mode-find-section)))
2038 (when kill
2039 (kill-buffer (get-buffer rst-toc-buffer-name)))
2040 (pop-to-buffer (marker-buffer pos))
2041 (goto-char pos)
2042 ;; FIXME: make the recentering conditional on scroll.
2043 (recenter 5)))
2044
2045 (defun rst-toc-mode-goto-section ()
2046 "Go to the section the current line describes and kill the TOC buffer."
2047 (interactive)
2048 (rst-goto-section t))
2049
2050 (defun rst-toc-mode-mouse-goto (event)
2051 "In `rst-toc' mode, go to the occurrence whose line you click on.
2052 EVENT is the input event."
2053 (interactive "e")
2054 (let (pos)
2055 (with-current-buffer (window-buffer (posn-window (event-end event)))
2056 (save-excursion
2057 (goto-char (posn-point (event-end event)))
2058 (setq pos (rst-toc-mode-find-section))))
2059 (pop-to-buffer (marker-buffer pos))
2060 (goto-char pos)
2061 (recenter 5)))
2062
2063 (defun rst-toc-mode-mouse-goto-kill (event)
2064 "Same as `rst-toc-mode-mouse-goto', but kill TOC buffer as well."
2065 (interactive "e")
2066 (call-interactively 'rst-toc-mode-mouse-goto event)
2067 (kill-buffer (get-buffer rst-toc-buffer-name)))
2068
2069 (defun rst-toc-quit-window ()
2070 "Leave the current TOC buffer."
2071 (interactive)
2072 (quit-window)
2073 (pop-to-buffer rst-toc-return-buffer))
2074
2075 (defvar rst-toc-mode-map
2076 (let ((map (make-sparse-keymap)))
2077 (define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
2078 (define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
2079 (define-key map "\C-m" 'rst-toc-mode-goto-section)
2080 (define-key map "f" 'rst-toc-mode-goto-section)
2081 (define-key map "q" 'rst-toc-quit-window)
2082 (define-key map "z" 'kill-this-buffer)
2083 map)
2084 "Keymap for `rst-toc-mode'.")
2085
2086 (put 'rst-toc-mode 'mode-class 'special)
2087
2088 ;; Could inherit from the new `special-mode'.
2089 (define-derived-mode rst-toc-mode nil "ReST-TOC"
2090 "Major mode for output from \\[rst-toc], the table-of-contents for the document."
2091 (setq buffer-read-only t))
2092
2093 ;; Note: use occur-mode (replace.el) as a good example to complete missing
2094 ;; features.
2095
2096
2097 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2098 ;;
2099 ;; Section movement commands.
2100 ;;
2101
2102 (defun rst-forward-section (&optional offset)
2103 "Skip to the next restructured text section title.
2104 OFFSET specifies how many titles to skip. Use a negative OFFSET to move
2105 backwards in the file (default is to use 1)."
2106 (interactive)
2107 (let* (;; Default value for offset.
2108 (offset (or offset 1))
2109
2110 ;; Get all the decorations in the file, with their line numbers.
2111 (alldecos (rst-find-all-decorations))
2112
2113 ;; Get the current line.
2114 (curline (line-number-at-pos))
2115
2116 (cur alldecos)
2117 (idx 0)
2118 )
2119
2120 ;; Find the index of the "next" decoration w.r.t. to the current line.
2121 (while (and cur (< (caar cur) curline))
2122 (setq cur (cdr cur))
2123 (incf idx))
2124 ;; 'cur' is the decoration on or following the current line.
2125
2126 (if (and (> offset 0) cur (= (caar cur) curline))
2127 (incf idx))
2128
2129 ;; Find the final index.
2130 (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
2131 (setq cur (nth idx alldecos))
2132
2133 ;; If the index is positive, goto the line, otherwise go to the buffer
2134 ;; boundaries.
2135 (if (and cur (>= idx 0))
2136 (goto-line (car cur))
2137 (if (> offset 0) (goto-char (point-max)) (goto-char (point-min))))
2138 ))
2139
2140 (defun rst-backward-section ()
2141 "Like `rst-forward-section', except move back one title.
2142 With a prefix argument, move backward by a page."
2143 (interactive)
2144 (rst-forward-section -1))
2145
2146 (defun rst-mark-section (&optional arg allow-extend)
2147 "Select the section that point is currently in."
2148 ;; Cloned from mark-paragraph.
2149 (interactive "p\np")
2150 (unless arg (setq arg 1))
2151 (when (zerop arg)
2152 (error "Cannot mark zero sections"))
2153 (cond ((and allow-extend
2154 (or (and (eq last-command this-command) (mark t))
2155 (rst-portable-mark-active-p)))
2156 (set-mark
2157 (save-excursion
2158 (goto-char (mark))
2159 (rst-forward-section arg)
2160 (point))))
2161 (t
2162 (rst-forward-section arg)
2163 (push-mark nil t t)
2164 (rst-forward-section (- arg)))))
2165
2166
2167
2168
2169
2170 \f
2171 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2172 ;; Functions to work on item lists (e.g. indent/dedent, enumerate), which are
2173 ;; always 2 or 3 characters apart horizontally with rest.
2174
2175 ;; (FIXME: there is currently a bug that makes the region go away when we do that.)
2176 (defvar rst-shift-fill-region nil
2177 "If non-nil, automatically re-fill the region that is being shifted.")
2178
2179 (defun rst-find-leftmost-column (beg end)
2180 "Find the leftmost column in the region."
2181 (let ((mincol 1000))
2182 (save-excursion
2183 (goto-char beg)
2184 (while (< (point) end)
2185 (back-to-indentation)
2186 (unless (looking-at "[ \t]*$")
2187 (setq mincol (min mincol (current-column))))
2188 (forward-line 1)
2189 ))
2190 mincol))
2191
2192
2193 ;; What we really need to do is compute all the possible alignment possibilities
2194 ;; and then select one.
2195 ;;
2196 ;; .. line-block::
2197 ;;
2198 ;; a) sdjsds
2199 ;;
2200 ;; - sdjsd jsjds
2201 ;;
2202 ;; sdsdsjdsj
2203 ;;
2204 ;; 11. sjdss jddjs
2205 ;;
2206 ;; * * * * * * *
2207 ;;
2208 ;; Move backwards, accumulate the beginning positions, and also the second
2209 ;; positions, in case the line matches the bullet pattern, and then sort.
2210
2211 (defun rst-compute-bullet-tabs (&optional pt)
2212 "Build the list of possible horizontal alignment points.
2213 Search backwards from point (or point PT if specified) to
2214 build the list of possible horizontal alignment points that
2215 includes the beginning and contents of a restructuredtext
2216 bulleted or enumerated list item. Return a sorted list
2217 of (COLUMN-NUMBER . LINE) pairs."
2218 (save-excursion
2219 (when pt (goto-char pt))
2220
2221 ;; We work our way backwards and towards the left.
2222 (let ((leftcol 100000) ;; Current column.
2223 (tablist nil) ;; List of tab positions.
2224 )
2225
2226 ;; Start by skipping the current line.
2227 (beginning-of-line 0)
2228
2229 ;; Search backwards for each line.
2230 (while (and (> (point) (point-min))
2231 (> leftcol 0))
2232
2233 ;; Skip empty lines.
2234 (unless (looking-at "^[ \t]*$")
2235 ;; Inspect the current non-empty line
2236 (back-to-indentation)
2237
2238 ;; Skip lines that are beyond the current column (we want to move
2239 ;; towards the left).
2240 (let ((col (current-column)))
2241 (when (< col leftcol)
2242
2243 ;; Add the beginning of the line as a tabbing point.
2244 (unless (memq col (mapcar 'car tablist))
2245 (push (cons col (point)) tablist))
2246
2247 ;; Look at the line to figure out if it is a bulleted or enumerate
2248 ;; list item.
2249 (when (looking-at
2250 (concat
2251 "\\(?:"
2252 "\\(\\(?:[0-9a-zA-Z#]\\{1,3\\}[.):-]\\|[*+-]\\)[ \t]+\\)[^ \t\n]"
2253 "\\|"
2254 (format "\\(%s%s+[ \t]+\\)[^ \t\n]"
2255 (regexp-quote (thing-at-point 'char))
2256 (regexp-quote (thing-at-point 'char)))
2257 "\\)"
2258 ))
2259 ;; Add the column of the contained item.
2260 (let* ((matchlen (length (or (match-string 1) (match-string 2))))
2261 (newcol (+ col matchlen)))
2262 (unless (or (>= newcol leftcol)
2263 (memq (+ col matchlen) (mapcar 'car tablist)))
2264 (push (cons (+ col matchlen) (+ (point) matchlen))
2265 tablist)))
2266 )
2267
2268 (setq leftcol col)
2269 )))
2270
2271 ;; Move backwards one line.
2272 (beginning-of-line 0))
2273
2274 (sort tablist (lambda (x y) (<= (car x) (car y))))
2275 )))
2276
2277 (defun rst-debug-print-tabs (tablist)
2278 "Insert a line and place special characters at the tab points in TABLIST."
2279 (beginning-of-line)
2280 (insert (concat "\n" (make-string 1000 ? ) "\n"))
2281 (beginning-of-line 0)
2282 (dolist (col tablist)
2283 (beginning-of-line)
2284 (forward-char (car col))
2285 (delete-char 1)
2286 (insert "@")
2287 ))
2288
2289 (defun rst-debug-mark-found (tablist)
2290 "Insert a line and place special characters at the tab points in TABLIST."
2291 (dolist (col tablist)
2292 (when (cdr col)
2293 (goto-char (cdr col))
2294 (insert "@"))))
2295
2296
2297 (defvar rst-shift-basic-offset 2
2298 "Basic horizontal shift distance when there is no preceding alignment tabs.")
2299
2300 (defun rst-shift-region-guts (find-next-fun offset-fun)
2301 "(See `rst-shift-region-right' for a description)."
2302 (let* ((mbeg (set-marker (make-marker) (region-beginning)))
2303 (mend (set-marker (make-marker) (region-end)))
2304 (tabs (rst-compute-bullet-tabs mbeg))
2305 (leftmostcol (rst-find-leftmost-column (region-beginning) (region-end)))
2306 )
2307 ;; Add basic offset tabs at the end of the list. This is a better
2308 ;; implementation technique than hysteresis and a basic offset because it
2309 ;; insures that movement in both directions is consistently using the same
2310 ;; column positions. This makes it more predictable.
2311 (setq tabs
2312 (append tabs
2313 (mapcar (lambda (x) (cons x nil))
2314 (let ((maxcol 120)
2315 (max-lisp-eval-depth 2000))
2316 (flet ((addnum (x)
2317 (if (> x maxcol)
2318 nil
2319 (cons x (addnum
2320 (+ x rst-shift-basic-offset))))))
2321 (addnum (or (caar (last tabs)) 0))))
2322 )))
2323
2324 ;; (For debugging.)
2325 ;;; (save-excursion (goto-char mbeg) (forward-char -1) (rst-debug-print-tabs tabs))))
2326 ;;; (print tabs)
2327 ;;; (save-excursion (rst-debug-mark-found tabs))
2328
2329 ;; Apply the indent.
2330 (indent-rigidly
2331 mbeg mend
2332
2333 ;; Find the next tab after the leftmost columnt.
2334 (let ((tab (funcall find-next-fun tabs leftmostcol)))
2335
2336 (if tab
2337 (progn
2338 (when (cdar tab)
2339 (message "Aligned on '%s'"
2340 (save-excursion
2341 (goto-char (cdar tab))
2342 (buffer-substring-no-properties
2343 (line-beginning-position)
2344 (line-end-position))))
2345 )
2346 (- (caar tab) leftmostcol)) ;; Num chars.
2347
2348 ;; Otherwise use the basic offset
2349 (funcall offset-fun rst-shift-basic-offset)
2350 )))
2351
2352 ;; Optionally reindent.
2353 (when rst-shift-fill-region
2354 (fill-region mbeg mend))
2355 ))
2356
2357 (defun rst-shift-region-right (pfxarg)
2358 "Indent region ridigly, by a few characters to the right.
2359 This function first computes all possible alignment columns by
2360 inspecting the lines preceding the region for bulleted or
2361 enumerated list items. If the leftmost column is beyond the
2362 preceding lines, the region is moved to the right by
2363 `rst-shift-basic-offset'. With a prefix argument, do not
2364 automatically fill the region."
2365 (interactive "P")
2366 (let ((rst-shift-fill-region
2367 (if (not pfxarg) rst-shift-fill-region)))
2368 (rst-shift-region-guts (lambda (tabs leftmostcol)
2369 (let ((cur tabs))
2370 (while (and cur (<= (caar cur) leftmostcol))
2371 (setq cur (cdr cur)))
2372 cur))
2373 'identity
2374 )))
2375
2376 (defun rst-shift-region-left (pfxarg)
2377 "Like `rst-shift-region-right', except we move to the left.
2378 Also, if invoked with a negative prefix arg, the entire
2379 indentation is removed, up to the leftmost character in the
2380 region, and automatic filling is disabled."
2381 (interactive "P")
2382 (let ((mbeg (set-marker (make-marker) (region-beginning)))
2383 (mend (set-marker (make-marker) (region-end)))
2384 (leftmostcol (rst-find-leftmost-column
2385 (region-beginning) (region-end)))
2386 (rst-shift-fill-region
2387 (if (not pfxarg) rst-shift-fill-region)))
2388
2389 (when (> leftmostcol 0)
2390 (if (and pfxarg (< (prefix-numeric-value pfxarg) 0))
2391 (progn
2392 (indent-rigidly (region-beginning) (region-end) (- leftmostcol))
2393 (when rst-shift-fill-region
2394 (fill-region mbeg mend))
2395 )
2396 (rst-shift-region-guts (lambda (tabs leftmostcol)
2397 (let ((cur (reverse tabs)))
2398 (while (and cur (>= (caar cur) leftmostcol))
2399 (setq cur (cdr cur)))
2400 cur))
2401 '-
2402 ))
2403 )))
2404
2405 (defmacro rst-iterate-leftmost-paragraphs
2406 (beg end first-only body-consequent body-alternative)
2407 "FIXME This definition is old and deprecated / we need to move
2408 to the newer version below:
2409
2410 Call FUN at the beginning of each line, with an argument that
2411 specifies whether we are at the first line of a paragraph that
2412 starts at the leftmost column of the given region BEG and END.
2413 Set FIRST-ONLY to true if you want to callback on the first line
2414 of each paragraph only."
2415 `(save-excursion
2416 (let ((leftcol (rst-find-leftmost-column ,beg ,end))
2417 (endm (set-marker (make-marker) ,end))
2418 )
2419
2420 (do* (;; Iterate lines
2421 (l (progn (goto-char ,beg) (back-to-indentation))
2422 (progn (forward-line 1) (back-to-indentation)))
2423
2424 (previous nil valid)
2425
2426 (curcol (current-column)
2427 (current-column))
2428
2429 (valid (and (= curcol leftcol)
2430 (not (looking-at "[ \t]*$")))
2431 (and (= curcol leftcol)
2432 (not (looking-at "[ \t]*$"))))
2433 )
2434 ((>= (point) endm))
2435
2436 (if (if ,first-only
2437 (and valid (not previous))
2438 valid)
2439 ,body-consequent
2440 ,body-alternative)
2441
2442 ))))
2443
2444
2445 (defmacro rst-iterate-leftmost-paragraphs-2 (spec &rest body)
2446 "Evaluate BODY for each line in region defined by BEG END.
2447 LEFTMOST is set to true if the line is one of the leftmost of the
2448 entire paragraph. PARABEGIN is set to true if the line is the
2449 first of a paragraph."
2450 (declare (indent 1) (debug (sexp body)))
2451 (destructuring-bind
2452 (beg end parabegin leftmost isleftmost isempty) spec
2453
2454 `(save-excursion
2455 (let ((,leftmost (rst-find-leftmost-column ,beg ,end))
2456 (endm (set-marker (make-marker) ,end))
2457 )
2458
2459 (do* (;; Iterate lines
2460 (l (progn (goto-char ,beg) (back-to-indentation))
2461 (progn (forward-line 1) (back-to-indentation)))
2462
2463 (empty-line-previous nil ,isempty)
2464
2465 (,isempty (looking-at "[ \t]*$")
2466 (looking-at "[ \t]*$"))
2467
2468 (,parabegin (not ,isempty)
2469 (and empty-line-previous
2470 (not ,isempty)))
2471
2472 (,isleftmost (and (not ,isempty)
2473 (= (current-column) ,leftmost))
2474 (and (not ,isempty)
2475 (= (current-column) ,leftmost)))
2476 )
2477 ((>= (point) endm))
2478
2479 (progn ,@body)
2480
2481 )))))
2482
2483
2484 ;;------------------------------------------------------------------------------
2485
2486 ;; FIXME: these next functions should become part of a larger effort to redo the
2487 ;; bullets in bulletted lists. The enumerate would just be one of the possible
2488 ;; outputs.
2489 ;;
2490 ;; FIXME: TODO we need to do the enumeration removal as well.
2491
2492 (defun rst-enumerate-region (beg end)
2493 "Add enumeration to all the leftmost paragraphs in the given region.
2494 The region is specified between BEG and END. With prefix argument,
2495 do all lines instead of just paragraphs."
2496 (interactive "r")
2497 (let ((count 0)
2498 (last-insert-len nil))
2499 (rst-iterate-leftmost-paragraphs
2500 beg end (not current-prefix-arg)
2501 (let ((ins-string (format "%d. " (incf count))))
2502 (setq last-insert-len (length ins-string))
2503 (insert ins-string))
2504 (insert (make-string last-insert-len ?\ ))
2505 )))
2506
2507 (defun rst-bullet-list-region (beg end)
2508 "Add bullets to all the leftmost paragraphs in the given region.
2509 The region is specified between BEG and END. With prefix argument,
2510 do all lines instead of just paragraphs."
2511 (interactive "r")
2512 (rst-iterate-leftmost-paragraphs
2513 beg end (not current-prefix-arg)
2514 (insert "- ")
2515 (insert " ")
2516 ))
2517
2518
2519 ;; FIXME: there are some problems left with the following function
2520 ;; implementation:
2521 ;;
2522 ;; * It does not deal with a varying number of digits appropriately
2523 ;; * It does not deal with multiple levels independently, and it should.
2524 ;;
2525 ;; I suppose it does 90% of the job for now.
2526
2527 (defun rst-convert-bullets-to-enumeration (beg end)
2528 "Convert all the bulleted items and enumerated items in the
2529 region to enumerated lists, renumbering as necessary."
2530 (interactive "r")
2531 (let* (;; Find items and convert the positions to markers.
2532 (items (mapcar
2533 (lambda (x)
2534 (cons (let ((m (make-marker)))
2535 (set-marker m (car x))
2536 m)
2537 (cdr x)))
2538 (rst-find-pfx-in-region beg end rst-re-items)))
2539 (count 1)
2540 )
2541 (save-excursion
2542 (dolist (x items)
2543 (goto-char (car x))
2544 (looking-at rst-re-items)
2545 (replace-match (format "%d. " count) nil nil nil 1)
2546 (incf count)
2547 ))
2548 ))
2549
2550
2551
2552 ;;------------------------------------------------------------------------------
2553
2554 (defun rst-line-block-region (rbeg rend &optional pfxarg)
2555 "Toggle line block prefixes for a region.
2556 With prefix argument set the empty lines too."
2557 (interactive "r\nP")
2558 (let ((comment-start "| ")
2559 (comment-end "")
2560 (comment-start-skip "| ")
2561 (comment-style 'indent)
2562 (force (not (not pfxarg))))
2563 (rst-iterate-leftmost-paragraphs-2
2564 (rbeg rend parbegin leftmost isleft isempty)
2565 (when (or force (not isempty))
2566 (move-to-column leftmost force)
2567 (delete-region (point) (+ (point) (- (current-indentation) leftmost)))
2568 (insert "| ")))))
2569
2570
2571 \f
2572 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2573
2574 (require 'font-lock)
2575
2576 (defgroup rst-faces nil "Faces used in Rst Mode."
2577 :group 'rst
2578 :group 'faces
2579 :version "21.1")
2580
2581 (defcustom rst-block-face 'font-lock-keyword-face
2582 "All syntax marking up a special block."
2583 :group 'rst-faces
2584 :type '(face))
2585
2586 (defcustom rst-external-face 'font-lock-type-face
2587 "Field names and interpreted text."
2588 :group 'rst-faces
2589 :type '(face))
2590
2591 (defcustom rst-definition-face 'font-lock-function-name-face
2592 "All other defining constructs."
2593 :group 'rst-faces
2594 :type '(face))
2595
2596 (defcustom rst-directive-face
2597 ;; XEmacs compatibility
2598 (if (boundp 'font-lock-builtin-face)
2599 'font-lock-builtin-face
2600 'font-lock-preprocessor-face)
2601 "Directives and roles."
2602 :group 'rst-faces
2603 :type '(face))
2604
2605 (defcustom rst-comment-face 'font-lock-comment-face
2606 "Comments."
2607 :group 'rst-faces
2608 :type '(face))
2609
2610 (defcustom rst-emphasis1-face
2611 ;; XEmacs compatibility
2612 (if (facep 'italic)
2613 ''italic
2614 'italic)
2615 "Simple emphasis."
2616 :group 'rst-faces
2617 :type '(face))
2618
2619 (defcustom rst-emphasis2-face
2620 ;; XEmacs compatibility
2621 (if (facep 'bold)
2622 ''bold
2623 'bold)
2624 "Double emphasis."
2625 :group 'rst-faces
2626 :type '(face))
2627
2628 (defcustom rst-literal-face 'font-lock-string-face
2629 "Literal text."
2630 :group 'rst-faces
2631 :type '(face))
2632
2633 (defcustom rst-reference-face 'font-lock-variable-name-face
2634 "References to a definition."
2635 :group 'rst-faces
2636 :type '(face))
2637
2638 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2639
2640 (defgroup rst-faces-defaults nil
2641 "Values used to generate default faces for section titles on all levels.
2642 Tweak these if you are content with how section title faces are built in
2643 general but you do not like the details."
2644 :group 'rst-faces
2645 :version "21.1")
2646
2647 (defun rst-set-level-default (sym val)
2648 "Set custom var SYM affecting section title text face and recompute the faces."
2649 (custom-set-default sym val)
2650 ;; Also defines the faces initially when all values are available
2651 (and (boundp 'rst-level-face-max)
2652 (boundp 'rst-level-face-format-light)
2653 (boundp 'rst-level-face-base-color)
2654 (boundp 'rst-level-face-step-light)
2655 (boundp 'rst-level-face-base-light)
2656 (fboundp 'rst-define-level-faces)
2657 (rst-define-level-faces)))
2658
2659 ;; Faces for displaying items on several levels; these definitions define
2660 ;; different shades of grey where the lightest one (i.e. least contrasting) is
2661 ;; used for level 1
2662 (defcustom rst-level-face-max 6
2663 "Maximum depth of levels for which section title faces are defined."
2664 :group 'rst-faces-defaults
2665 :type '(integer)
2666 :set 'rst-set-level-default)
2667 (defcustom rst-level-face-base-color "grey"
2668 "The base name of the color to be used for creating background colors in
2669 section title faces for all levels."
2670 :group 'rst-faces-defaults
2671 :type '(string)
2672 :set 'rst-set-level-default)
2673 (defcustom rst-level-face-base-light
2674 (if (eq frame-background-mode 'dark)
2675 15
2676 85)
2677 "The lightness factor for the base color. This value is used for level 1.
2678 The default depends on whether the value of `frame-background-mode' is
2679 `dark' or not."
2680 :group 'rst-faces-defaults
2681 :type '(integer)
2682 :set 'rst-set-level-default)
2683 (defcustom rst-level-face-format-light "%2d"
2684 "The format for the lightness factor appended to the base name of the color.
2685 This value is expanded by `format' with an integer."
2686 :group 'rst-faces-defaults
2687 :type '(string)
2688 :set 'rst-set-level-default)
2689 (defcustom rst-level-face-step-light
2690 (if (eq frame-background-mode 'dark)
2691 7
2692 -7)
2693 "The step width to use for the next color.
2694 The formula
2695
2696 `rst-level-face-base-light'
2697 + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
2698
2699 must result in a color level which appended to `rst-level-face-base-color'
2700 using `rst-level-face-format-light' results in a valid color such as `grey50'.
2701 This color is used as background for section title text on level
2702 `rst-level-face-max'."
2703 :group 'rst-faces-defaults
2704 :type '(integer)
2705 :set 'rst-set-level-default)
2706
2707 (defcustom rst-adornment-faces-alist
2708 (let ((alist '((t . font-lock-keyword-face)
2709 (nil . font-lock-keyword-face)))
2710 (i 1))
2711 (while (<= i rst-level-face-max)
2712 (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
2713 (setq i (1+ i)))
2714 alist)
2715 "Faces for the various adornment types.
2716 Key is a number (for the section title text of that level),
2717 t (for transitions) or nil (for section title adornment).
2718 If you generally do not like how section title text faces are
2719 set up tweak here. If the general idea is ok for you but you do not like the
2720 details check the Rst Faces Defaults group."
2721 :group 'rst-faces
2722 :type '(alist
2723 :key-type
2724 (choice
2725 (integer
2726 :tag
2727 "Section level (may not be bigger than `rst-level-face-max')")
2728 (boolean :tag "transitions (on) / section title adornment (off)"))
2729 :value-type (face))
2730 :set-after '(rst-level-face-max))
2731
2732 (defun rst-define-level-faces ()
2733 "Define the faces for the section title text faces from the values."
2734 ;; All variables used here must be checked in `rst-set-level-default'
2735 (let ((i 1))
2736 (while (<= i rst-level-face-max)
2737 (let ((sym (intern (format "rst-level-%d-face" i)))
2738 (doc (format "Face for showing section title text at level %d" i))
2739 (col (format (concat "%s" rst-level-face-format-light)
2740 rst-level-face-base-color
2741 (+ (* (1- i) rst-level-face-step-light)
2742 rst-level-face-base-light))))
2743 (make-empty-face sym)
2744 (set-face-doc-string sym doc)
2745 (set-face-background sym col)
2746 (set sym sym)
2747 (setq i (1+ i))))))
2748
2749 (rst-define-level-faces)
2750
2751 \f
2752 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2753 ;; Font lock
2754
2755 (defvar rst-use-char-classes
2756 (string-match "[[:alpha:]]" "b")
2757 "Non-nil if we can use the character classes in our regexps.")
2758
2759 (defun rst-font-lock-keywords-function ()
2760 "Return keywords to highlight in Rst mode according to current settings."
2761 ;; The reST-links in the comments below all relate to sections in
2762 ;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
2763 (let* ( ;; This gets big - so let's define some abbreviations
2764 ;; horizontal white space
2765 (re-hws "[\t ]")
2766 ;; beginning of line with possible indentation
2767 (re-bol (concat "^" re-hws "*"))
2768 ;; Separates block lead-ins from their content
2769 (re-blksep1 (concat "\\(" re-hws "+\\|$\\)"))
2770 ;; explicit markup tag
2771 (re-emt "\\.\\.")
2772 ;; explicit markup start
2773 (re-ems (concat re-emt re-hws "+"))
2774 ;; inline markup prefix
2775 (re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{</:]\\)"))
2776 ;; inline markup suffix
2777 (re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
2778 ;; symbol character
2779 (re-sym1 "\\(\\sw\\|\\s_\\)")
2780 ;; inline markup content begin
2781 (re-imbeg2 "\\(\\S \\|\\S \\([^")
2782
2783 ;; There seems to be a bug leading to error "Stack overflow in regexp
2784 ;; matcher" when "|" or "\\*" are the characters searched for
2785 (re-imendbeg
2786 (if (< emacs-major-version 21)
2787 "]"
2788 "\\]\\|\\\\."))
2789 ;; inline markup content end
2790 (re-imend (concat re-imendbeg "\\)*[^\t \\\\]\\)"))
2791 ;; inline markup content without asterisk
2792 (re-ima2 (concat re-imbeg2 "*" re-imend))
2793 ;; inline markup content without backquote
2794 (re-imb2 (concat re-imbeg2 "`" re-imend))
2795 ;; inline markup content without vertical bar
2796 (re-imv2 (concat re-imbeg2 "|" re-imend))
2797 ;; Supported URI schemes
2798 (re-uris1 "\\(acap\\|cid\\|data\\|dav\\|fax\\|file\\|ftp\\|gopher\\|http\\|https\\|imap\\|ldap\\|mailto\\|mid\\|modem\\|news\\|nfs\\|nntp\\|pop\\|prospero\\|rtsp\\|service\\|sip\\|tel\\|telnet\\|tip\\|urn\\|vemmi\\|wais\\)")
2799 ;; Line starting with adornment and optional whitespace; complete
2800 ;; adornment is in (match-string 1); there must be at least 3
2801 ;; characters because otherwise explicit markup start would be
2802 ;; recognized
2803 (re-ado2 (concat "^\\(\\(["
2804 (if rst-use-char-classes
2805 "^[:word:][:space:][:cntrl:]" "^\\w \t\x00-\x1F")
2806 "]\\)\\2\\2+\\)" re-hws "*$"))
2807 )
2808 (list
2809 ;; FIXME: Block markup is not recognized in blocks after explicit markup
2810 ;; start
2811
2812 ;; Simple `Body Elements`_
2813 ;; `Bullet Lists`_
2814 (list
2815 (concat re-bol "\\([-*+]" re-blksep1 "\\)")
2816 1 rst-block-face)
2817 ;; `Enumerated Lists`_
2818 (list
2819 (concat re-bol "\\((?\\(#\\|[0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
2820 re-blksep1 "\\)")
2821 1 rst-block-face)
2822 ;; `Definition Lists`_ FIXME: missing
2823 ;; `Field Lists`_
2824 (list
2825 (concat re-bol "\\(:[^:\n]+:\\)" re-blksep1)
2826 1 rst-external-face)
2827 ;; `Option Lists`_
2828 (list
2829 (concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
2830 "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
2831 1 rst-block-face)
2832
2833 ;; `Tables`_ FIXME: missing
2834
2835 ;; All the `Explicit Markup Blocks`_
2836 ;; `Footnotes`_ / `Citations`_
2837 (list
2838 (concat re-bol "\\(" re-ems "\\[[^[\n]+\\]\\)" re-blksep1)
2839 1 rst-definition-face)
2840 ;; `Directives`_ / `Substitution Definitions`_
2841 (list
2842 (concat re-bol "\\(" re-ems "\\)\\(\\(|[^|\n]+|[\t ]+\\)?\\)\\("
2843 re-sym1 "+::\\)" re-blksep1)
2844 (list 1 rst-directive-face)
2845 (list 2 rst-definition-face)
2846 (list 4 rst-directive-face))
2847 ;; `Hyperlink Targets`_
2848 (list
2849 (concat re-bol "\\(" re-ems "_\\([^:\\`\n]\\|\\\\.\\|`[^`\n]+`\\)+:\\)"
2850 re-blksep1)
2851 1 rst-definition-face)
2852 (list
2853 (concat re-bol "\\(__\\)" re-blksep1)
2854 1 rst-definition-face)
2855
2856 ;; All `Inline Markup`_
2857 ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
2858 ;; `Strong Emphasis`_
2859 (list
2860 (concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
2861 2 rst-emphasis2-face)
2862 ;; `Emphasis`_
2863 (list
2864 (concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
2865 2 rst-emphasis1-face)
2866 ;; `Inline Literals`_
2867 (list
2868 (concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
2869 2 rst-literal-face)
2870 ;; `Inline Internal Targets`_
2871 (list
2872 (concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
2873 2 rst-definition-face)
2874 ;; `Hyperlink References`_
2875 ;; FIXME: `Embedded URIs`_ not considered
2876 (list
2877 (concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\(\\sw\\(\\sw\\|-\\)+\\sw\\)\\)__?\\)" re-ims1)
2878 2 rst-reference-face)
2879 ;; `Interpreted Text`_
2880 (list
2881 (concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:"
2882 re-sym1 "+:\\)?\\)" re-ims1)
2883 (list 2 rst-directive-face)
2884 (list 5 rst-external-face)
2885 (list 8 rst-directive-face))
2886 ;; `Footnote References`_ / `Citation References`_
2887 (list
2888 (concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
2889 2 rst-reference-face)
2890 ;; `Substitution References`_
2891 (list
2892 (concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
2893 2 rst-reference-face)
2894 ;; `Standalone Hyperlinks`_
2895 (list
2896 ;; FIXME: This takes it easy by using a whitespace as delimiter
2897 (concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1)
2898 2 rst-definition-face)
2899 (list
2900 (concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
2901 2 rst-definition-face)
2902
2903 ;; Do all block fontification as late as possible so 'append works
2904
2905 ;; Sections_ / Transitions_
2906 (append
2907 (list
2908 re-ado2)
2909 (if (not rst-mode-lazy)
2910 (list 1 rst-block-face)
2911 (list
2912 (list 'rst-font-lock-handle-adornment
2913 '(progn
2914 (setq rst-font-lock-adornment-point (match-end 1))
2915 (point-max))
2916 nil
2917 (list 1 '(cdr (assoc nil rst-adornment-faces-alist))
2918 'append t)
2919 (list 2 '(cdr (assoc rst-font-lock-level
2920 rst-adornment-faces-alist))
2921 'append t)
2922 (list 3 '(cdr (assoc nil rst-adornment-faces-alist))
2923 'append t)))))
2924
2925 ;; `Comments`_
2926 (append
2927 (list
2928 (concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:\n]\\|:\\([^:\n]\\|$\\)\\)*$")
2929
2930 (list 1 rst-comment-face))
2931 (if rst-mode-lazy
2932 (list
2933 (list 'rst-font-lock-find-unindented-line
2934 '(progn
2935 (setq rst-font-lock-indentation-point (match-end 1))
2936 (point-max))
2937 nil
2938 (list 0 rst-comment-face 'append)))))
2939 (append
2940 (list
2941 (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)$")
2942 (list 1 rst-comment-face)
2943 (list 2 rst-comment-face))
2944 (if rst-mode-lazy
2945 (list
2946 (list 'rst-font-lock-find-unindented-line
2947 '(progn
2948 (setq rst-font-lock-indentation-point 'next)
2949 (point-max))
2950 nil
2951 (list 0 rst-comment-face 'append)))))
2952
2953 ;; `Literal Blocks`_
2954 (append
2955 (list
2956 (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
2957 (list 3 rst-block-face))
2958 (if rst-mode-lazy
2959 (list
2960 (list 'rst-font-lock-find-unindented-line
2961 '(progn
2962 (setq rst-font-lock-indentation-point t)
2963 (point-max))
2964 nil
2965 (list 0 rst-literal-face 'append)))))
2966
2967 ;; `Doctest Blocks`_
2968 (append
2969 (list
2970 (concat re-bol "\\(>>>\\|\\.\\.\\.\\)\\(.+\\)")
2971 (list 1 rst-block-face)
2972 (list 2 rst-literal-face)))
2973 )))
2974
2975
2976
2977 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2978 ;; Indented blocks
2979
2980 (defun rst-forward-indented-block (&optional column limit)
2981 "Move forward across one indented block.
2982 Find the next non-empty line which is not indented at least to COLUMN (defaults
2983 to the column of the point). Moves point to first character of this line or the
2984 first empty line immediately before it and returns that position. If there is
2985 no such line before LIMIT (defaults to the end of the buffer) returns nil and
2986 point is not moved."
2987 (interactive)
2988 (let ((clm (or column (current-column)))
2989 (start (point))
2990 fnd beg cand)
2991 (if (not limit)
2992 (setq limit (point-max)))
2993 (save-match-data
2994 (while (and (not fnd) (< (point) limit))
2995 (forward-line 1)
2996 (when (< (point) limit)
2997 (setq beg (point))
2998 (if (looking-at "\\s *$")
2999 (setq cand (or cand beg)) ; An empty line is a candidate
3000 (move-to-column clm)
3001 ;; FIXME: No indentation [(zerop clm)] must be handled in some
3002 ;; useful way - though it is not clear what this should mean at all
3003 (if (string-match
3004 "^\\s *$" (buffer-substring-no-properties beg (point)))
3005 (setq cand nil) ; An indented line resets a candidate
3006 (setq fnd (or cand beg)))))))
3007 (goto-char (or fnd start))
3008 fnd))
3009
3010 ;; Stores the point where the current indentation ends if a number. If `next'
3011 ;; indicates `rst-font-lock-find-unindented-line' shall take the indentation
3012 ;; from the next line if this is not empty. If non-nil indicates
3013 ;; `rst-font-lock-find-unindented-line' shall take the indentation from the
3014 ;; next non-empty line. Also used as a trigger for
3015 ;; `rst-font-lock-find-unindented-line'.
3016 (defvar rst-font-lock-indentation-point nil)
3017
3018 (defun rst-font-lock-find-unindented-line (limit)
3019 (let* ((ind-pnt rst-font-lock-indentation-point)
3020 (beg-pnt ind-pnt))
3021 ;; May run only once - enforce this
3022 (setq rst-font-lock-indentation-point nil)
3023 (when (and ind-pnt (not (numberp ind-pnt)))
3024 ;; Find indentation point in next line if any
3025 (setq ind-pnt
3026 (save-excursion
3027 (save-match-data
3028 (if (eq ind-pnt 'next)
3029 (when (and (zerop (forward-line 1)) (< (point) limit))
3030 (setq beg-pnt (point))
3031 (when (not (looking-at "\\s *$"))
3032 (looking-at "\\s *")
3033 (match-end 0)))
3034 (while (and (zerop (forward-line 1)) (< (point) limit)
3035 (looking-at "\\s *$")))
3036 (when (< (point) limit)
3037 (setq beg-pnt (point))
3038 (looking-at "\\s *")
3039 (match-end 0)))))))
3040 (when ind-pnt
3041 (goto-char ind-pnt)
3042 ;; Always succeeds because the limit set by PRE-MATCH-FORM is the
3043 ;; ultimate point to find
3044 (goto-char (or (rst-forward-indented-block nil limit) limit))
3045 (save-excursion
3046 ;; Include subsequent empty lines in the font-lock block,
3047 ;; in case the user subsequently changes the indentation of the next
3048 ;; non-empty line to move it into the indented element.
3049 (skip-chars-forward " \t\n")
3050 (put-text-property beg-pnt (point) 'font-lock-multiline t))
3051 (set-match-data (list beg-pnt (point)))
3052 t)))
3053
3054 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3055 ;; Adornments
3056
3057 (defvar rst-font-lock-adornment-point nil
3058 "Stores the point where the current adornment ends.
3059 Also used as a trigger for `rst-font-lock-handle-adornment'.")
3060
3061 ;; Here `rst-font-lock-handle-adornment' stores the section level of the
3062 ;; current adornment or t for a transition.
3063 (defvar rst-font-lock-level nil)
3064
3065 ;; FIXME: It would be good if this could be used to markup section titles of
3066 ;; given level with a special key; it would be even better to be able to
3067 ;; customize this so it can be used for a generally available personal style
3068 ;;
3069 ;; FIXME: There should be some way to reset and reload this variable - probably
3070 ;; a special key
3071 ;;
3072 ;; FIXME: Some support for `outline-mode' would be nice which should be based
3073 ;; on this information
3074 (defvar rst-adornment-level-alist nil
3075 "Associates adornments with section levels.
3076 The key is a two character string. The first character is the adornment
3077 character. The second character distinguishes underline section titles (`u')
3078 from overline/underline section titles (`o'). The value is the section level.
3079
3080 This is made buffer local on start and adornments found during font lock are
3081 entered.")
3082
3083 ;; Returns section level for adornment key KEY. Adds new section level if KEY
3084 ;; is not found and ADD. If KEY is not a string it is simply returned.
3085 (defun rst-adornment-level (key &optional add)
3086 (let ((fnd (assoc key rst-adornment-level-alist))
3087 (new 1))
3088 (cond
3089 ((not (stringp key))
3090 key)
3091 (fnd
3092 (cdr fnd))
3093 (add
3094 (while (rassoc new rst-adornment-level-alist)
3095 (setq new (1+ new)))
3096 (setq rst-adornment-level-alist
3097 (append rst-adornment-level-alist (list (cons key new))))
3098 new))))
3099
3100 ;; Classifies adornment for section titles and transitions. ADORNMENT is the
3101 ;; complete adornment string as found in the buffer. END is the point after the
3102 ;; last character of ADORNMENT. For overline section adornment LIMIT limits the
3103 ;; search for the matching underline. Returns a list. The first entry is t for
3104 ;; a transition, or a key string for `rst-adornment-level' for a section title.
3105 ;; The following eight values forming four match groups as can be used for
3106 ;; `set-match-data'. First match group contains the maximum points of the whole
3107 ;; construct. Second and last match group matched pure section title adornment
3108 ;; while third match group matched the section title text or the transition.
3109 ;; Each group but the first may or may not exist.
3110 (defun rst-classify-adornment (adornment end limit)
3111 (save-excursion
3112 (save-match-data
3113 (goto-char end)
3114 (let ((ado-ch (aref adornment 0))
3115 (ado-re (regexp-quote adornment))
3116 (end-pnt (point))
3117 (beg-pnt (progn
3118 (forward-line 0)
3119 (point)))
3120 (nxt-emp
3121 (save-excursion
3122 (or (not (zerop (forward-line 1)))
3123 (looking-at "\\s *$"))))
3124 (prv-emp
3125 (save-excursion
3126 (or (not (zerop (forward-line -1)))
3127 (looking-at "\\s *$"))))
3128 key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
3129 (cond
3130 ((and nxt-emp prv-emp)
3131 ;; A transition
3132 (setq key t)
3133 (setq beg-txt beg-pnt)
3134 (setq end-txt end-pnt))
3135 (prv-emp
3136 ;; An overline
3137 (setq key (concat (list ado-ch) "o"))
3138 (setq beg-ovr beg-pnt)
3139 (setq end-ovr end-pnt)
3140 (forward-line 1)
3141 (setq beg-txt (point))
3142 (while (and (< (point) limit) (not end-txt))
3143 (if (looking-at "\\s *$")
3144 ;; No underline found
3145 (setq end-txt (1- (point)))
3146 (when (looking-at (concat "\\(" ado-re "\\)\\s *$"))
3147 (setq end-und (match-end 1))
3148 (setq beg-und (point))
3149 (setq end-txt (1- beg-und))))
3150 (forward-line 1)))
3151 (t
3152 ;; An underline
3153 (setq key (concat (list ado-ch) "u"))
3154 (setq beg-und beg-pnt)
3155 (setq end-und end-pnt)
3156 (setq end-txt (1- beg-und))
3157 (setq beg-txt (progn
3158 (if (re-search-backward "^\\s *$" 1 'move)
3159 (forward-line 1))
3160 (point)))))
3161 (list key
3162 (or beg-ovr beg-txt beg-und)
3163 (or end-und end-txt end-und)
3164 beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
3165
3166 ;; Handles adornments for font-locking section titles and transitions. Returns
3167 ;; three match groups. First and last match group matched pure overline /
3168 ;; underline adornment while second group matched section title text. Each
3169 ;; group may not exist.
3170 (defun rst-font-lock-handle-adornment (limit)
3171 (let ((ado-pnt rst-font-lock-adornment-point))
3172 ;; May run only once - enforce this
3173 (setq rst-font-lock-adornment-point nil)
3174 (if ado-pnt
3175 (let* ((ado (rst-classify-adornment (match-string-no-properties 1)
3176 ado-pnt limit))
3177 (key (car ado))
3178 (mtc (cdr ado)))
3179 (setq rst-font-lock-level (rst-adornment-level key t))
3180 (goto-char (nth 1 mtc))
3181 (put-text-property (nth 0 mtc) (nth 1 mtc) 'font-lock-multiline t)
3182 (set-match-data mtc)
3183 t))))
3184
3185
3186
3187 \f
3188 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3189 ;; Support for conversion from within Emacs
3190
3191 (defgroup rst-compile nil
3192 "Settings for support of conversion of reStructuredText
3193 document with \\[rst-compile]."
3194 :group 'rst
3195 :version "21.1")
3196
3197 (defvar rst-compile-toolsets
3198 '((html . ("rst2html.py" ".html" nil))
3199 (latex . ("rst2latex.py" ".tex" nil))
3200 (newlatex . ("rst2newlatex.py" ".tex" nil))
3201 (pseudoxml . ("rst2pseudoxml.py" ".xml" nil))
3202 (xml . ("rst2xml.py" ".xml" nil)))
3203 "Table describing the command to use for each toolset.
3204 An association list of the toolset to a list of the (command to use,
3205 extension of produced filename, options to the tool (nil or a
3206 string)) to be used for converting the document.")
3207
3208 ;; Note for Python programmers not familiar with association lists: you can set
3209 ;; values in an alists like this, e.g. :
3210 ;; (setcdr (assq 'html rst-compile-toolsets)
3211 ;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
3212
3213
3214 (defvar rst-compile-primary-toolset 'html
3215 "The default toolset for `rst-compile'.")
3216
3217 (defvar rst-compile-secondary-toolset 'latex
3218 "The default toolset for `rst-compile' with a prefix argument.")
3219
3220 (defun rst-compile-find-conf ()
3221 "Look for the configuration file in the parents of the current path."
3222 (interactive)
3223 (let ((file-name "docutils.conf")
3224 (buffer-file (buffer-file-name)))
3225 ;; Move up in the dir hierarchy till we find a change log file.
3226 (let* ((dir (file-name-directory buffer-file))
3227 (prevdir nil))
3228 (while (and (or (not (string= dir prevdir))
3229 (setq dir nil)
3230 nil)
3231 (not (file-exists-p (concat dir file-name))))
3232 ;; Move up to the parent dir and try again.
3233 (setq prevdir dir)
3234 (setq dir (expand-file-name (file-name-directory
3235 (directory-file-name
3236 (file-name-directory dir)))))
3237 )
3238 (or (and dir (concat dir file-name)) nil)
3239 )))
3240
3241
3242 (require 'compile)
3243
3244 (defun rst-compile (&optional pfxarg)
3245 "Compile command to convert reST document into some output file.
3246 Attempts to find configuration file, if it can, overrides the
3247 options. There are two commands to choose from, with a prefix
3248 argument, select the alternative toolset."
3249 (interactive "P")
3250 ;; Note: maybe we want to check if there is a Makefile too and not do anything
3251 ;; if that is the case. I dunno.
3252 (let* ((toolset (cdr (assq (if pfxarg
3253 rst-compile-secondary-toolset
3254 rst-compile-primary-toolset)
3255 rst-compile-toolsets)))
3256 (command (car toolset))
3257 (extension (cadr toolset))
3258 (options (caddr toolset))
3259 (conffile (rst-compile-find-conf))
3260 (bufname (file-name-nondirectory buffer-file-name))
3261 (outname (file-name-sans-extension bufname)))
3262
3263 ;; Set compile-command before invocation of compile.
3264 (set (make-local-variable 'compile-command)
3265 (mapconcat 'identity
3266 (list command
3267 (or options "")
3268 (if conffile
3269 (concat "--config=\"" conffile "\"")
3270 "")
3271 bufname
3272 (concat outname extension))
3273 " "))
3274
3275 ;; Invoke the compile command.
3276 (if (or compilation-read-command current-prefix-arg)
3277 (call-interactively 'compile)
3278 (compile compile-command))
3279 ))
3280
3281 (defun rst-compile-alt-toolset ()
3282 "Compile command with the alternative toolset."
3283 (interactive)
3284 (rst-compile 't))
3285
3286 (defun rst-compile-pseudo-region ()
3287 "Show the pseudo-XML rendering of the current active region,
3288 or of the entire buffer, if the region is not selected."
3289 (interactive)
3290 (with-output-to-temp-buffer "*pseudoxml*"
3291 (shell-command-on-region
3292 (if mark-active (region-beginning) (point-min))
3293 (if mark-active (region-end) (point-max))
3294 "rst2pseudoxml.py"
3295 standard-output)))
3296
3297 (defvar rst-pdf-program "xpdf"
3298 "Program used to preview PDF files.")
3299
3300 (defun rst-compile-pdf-preview ()
3301 "Convert the document to a PDF file and launch a preview program."
3302 (interactive)
3303 (let* ((tmp-filename "/tmp/out.pdf")
3304 (command (format "rst2pdf.py %s %s && %s %s"
3305 buffer-file-name tmp-filename
3306 rst-pdf-program tmp-filename)))
3307 (start-process-shell-command "rst-pdf-preview" nil command)
3308 ;; Note: you could also use (compile command) to view the compilation
3309 ;; output.
3310 ))
3311
3312 (defvar rst-slides-program "firefox"
3313 "Program used to preview S5 slides.")
3314
3315 (defun rst-compile-slides-preview ()
3316 "Convert the document to an S5 slide presentation and launch a preview program."
3317 (interactive)
3318 (let* ((tmp-filename "/tmp/slides.html")
3319 (command (format "rst2s5.py %s %s && %s %s"
3320 buffer-file-name tmp-filename
3321 rst-slides-program tmp-filename)))
3322 (start-process-shell-command "rst-slides-preview" nil command)
3323 ;; Note: you could also use (compile command) to view the compilation
3324 ;; output.
3325 ))
3326
3327
3328 \f
3329 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3330 ;;
3331 ;; Generic text functions that are more convenient than the defaults.
3332 ;;
3333
3334 (defun rst-replace-lines (fromchar tochar)
3335 "Replace flush-left lines, consisting of multiple FROMCHAR characters,
3336 with equal-length lines of TOCHAR."
3337 (interactive "\
3338 cSearch for flush-left lines of char:
3339 cand replace with char: ")
3340 (save-excursion
3341 (let ((searchre (concat "^" (regexp-quote (string fromchar)) "+\\( *\\)$"))
3342 (found 0))
3343 (while (search-forward-regexp searchre nil t)
3344 (setq found (1+ found))
3345 (goto-char (match-beginning 1))
3346 (let ((width (current-column)))
3347 (rst-delete-entire-line)
3348 (insert-char tochar width)))
3349 (message (format "%d lines replaced." found)))))
3350
3351 (defun rst-join-paragraph ()
3352 "Join lines in current paragraph into one line, removing end-of-lines."
3353 (interactive)
3354 (let ((fill-column 65000)) ; some big number
3355 (call-interactively 'fill-paragraph)))
3356
3357 (defun rst-force-fill-paragraph ()
3358 "Fill paragraph at point, first joining the paragraph's lines into one.
3359 This is useful for filling list item paragraphs."
3360 (interactive)
3361 (rst-join-paragraph)
3362 (fill-paragraph nil))
3363
3364
3365 ;; Generic character repeater function.
3366 ;; For sections, better to use the specialized function above, but this can
3367 ;; be useful for creating separators.
3368 (defun rst-repeat-last-character (&optional tofill)
3369 "Fills the current line up to the length of the preceding line (if not
3370 empty), using the last character on the current line. If the preceding line is
3371 empty, we use the `fill-column'.
3372
3373 If a prefix argument is provided, use the next line rather than the preceding
3374 line.
3375
3376 If the current line is longer than the desired length, shave the characters off
3377 the current line to fit the desired length.
3378
3379 As an added convenience, if the command is repeated immediately, the alternative
3380 column is used (fill-column vs. end of previous/next line)."
3381 (interactive)
3382 (let* ((curcol (current-column))
3383 (curline (+ (count-lines (point-min) (point))
3384 (if (eq curcol 0) 1 0)))
3385 (lbp (line-beginning-position 0))
3386 (prevcol (if (and (= curline 1) (not current-prefix-arg))
3387 fill-column
3388 (save-excursion
3389 (forward-line (if current-prefix-arg 1 -1))
3390 (end-of-line)
3391 (skip-chars-backward " \t" lbp)
3392 (let ((cc (current-column)))
3393 (if (= cc 0) fill-column cc)))))
3394 (rightmost-column
3395 (cond (tofill fill-column)
3396 ((equal last-command 'rst-repeat-last-character)
3397 (if (= curcol fill-column) prevcol fill-column))
3398 (t (save-excursion
3399 (if (= prevcol 0) fill-column prevcol)))
3400 )) )
3401 (end-of-line)
3402 (if (> (current-column) rightmost-column)
3403 ;; shave characters off the end
3404 (delete-region (- (point)
3405 (- (current-column) rightmost-column))
3406 (point))
3407 ;; fill with last characters
3408 (insert-char (preceding-char)
3409 (- rightmost-column (current-column))))
3410 ))
3411
3412
3413 (defun rst-portable-mark-active-p ()
3414 "A portable function that returns non-nil if the mark is active."
3415 (cond
3416 ((fboundp 'region-active-p) (region-active-p))
3417 ((boundp 'transient-mark-mode) transient-mark-mode mark-active)))
3418
3419
3420 \f
3421 (provide 'rst)
3422
3423 ;; arch-tag: 255ac0a3-a689-44cb-8643-04ca55ae490d
3424 ;;; rst.el ends here