1
;;; ================================================
2
;;; rst.el -- ReStructuredText Support for Emacs
3
;;; ================================================
5
;;; :Authors: Martin Blais <blais@furius.ca>,
6
;;; Stefan Merten <smerten@oekonux.de>,
7
;;; David Goodger <goodger@python.org>
8
;;; :Revision: $Revision: 4232 $
9
;;; :Date: $Date: 2005-12-27 14:12:04 +0100 (Tue, 27 Dec 2005) $
10
;;; :Copyright: This module has been placed in the public domain.
13
;;; Support code for editing reStructuredText with Emacs. The latest version
14
;;; of this file lies in the docutils source code repository.
19
;;; Basically, this package contains:
21
;;; - Functions to automatically adjust and cycle the section underline
23
;;; - A mode that displays the table of contents and allows you to jump anywhere
25
;;; - Functions to insert and automatically update a TOC in your source
27
;;; - A mode which supports font-lock highlighting of reStructuredText
29
;;; - Some other convenience functions.
31
;;; See the accompanying document in the docutils documentation about
32
;;; the contents of this package and how to use it.
34
;;; For more information about reStructuredText, see
35
;;; http://docutils.sourceforge.net/rst.html
37
;;; For full details on how to use the contents of this file, see
38
;;; http://docutils.sourceforge.net/docs/user/emacs.html
43
;;; Click `Here <rst.el>`_ for download.
47
;; **IMPORTANT NOTE TO PACKAGERS**: this package is the result of merging:
49
;; - restructuredtext.el
53
;; Those files are now OBSOLETE and have been replaced by this single package
56
;; Installation instructions
57
;; -------------------------
59
;; Add this line to your .emacs file and bind the versatile sectioning commands
60
;; in text mode, like this::
63
;; (add-hook 'text-mode-hook 'rst-text-mode-bindings)
65
;; rst-prefix-map is the prefix map for all the functionality provide by this
66
;; module. In addition, other shorter bindings are also provided on the
67
;; mode-specific-map prefix (i.e C-c).
70
;; C-c p a (also C-=): rst-adjust
72
;; Updates or rotates the section title around point or promotes/demotes
73
;; the decorations within the region (see full details below).
75
;; Note that C-= is a good binding, since it allows you to specify a
76
;; negative arg easily with C-- C-= (easy to type), as well as ordinary
77
;; prefix arg with C-u C-=.
79
;; C-c p h: rst-display-decorations-hierarchy
81
;; Displays the level decorations that are available in the file.
85
;; Displays the hierarchical table-of-contents of the document and allows
86
;; you to jump to any section from it.
88
;; C-c p i: rst-toc-insert
90
;; Inserts a table-of-contents in the document at the column where the
93
;; C-c p u: rst-toc-insert-update
95
;; Find an existing inserted table-of-contents in the document an
98
;; C-c p p, C-c p n (C-c C-p, C-c C-n): rst-backward-section,
99
;; rst-forward-section
101
;; Navigate between section titles.
103
;; C-c p l, C-c p r (C-c C-l, C-c C-r): rst-shift-region-left,
104
;; rst-shift-region-right
106
;; Shift the region left or right by two-char increments, which is perfect
107
;; for bulleted lists.
110
;; Other specialized and more generic functions are also available (see source
111
;; code). The most important function provided by this file for section title
112
;; adjustments is rst-adjust.
114
;; There are many variables that can be customized, look for defcustom and
115
;; defvar in this file.
117
;; If you use the table-of-contents feature, you may want to add a hook to
118
;; update the TOC automatically everytime you adjust a section title::
120
;; (add-hook 'rst-adjust-hook 'rst-toc-insert-update)
125
;; There is a special mode that you can setup if you want to have syntax
126
;; highlighting. The mode is based on `text-mode' and inherits some things from
127
;; it. Particularly `text-mode-hook' is run before `rst-mode-hook'.
129
;; Add the following lines to your `.emacs' file:
131
;; (setq auto-mode-alist
132
;; (append '(("\\.rst$" . rst-mode)
133
;; ("\\.rest$" . rst-mode)) auto-mode-alist))
135
;; If you are using `.txt' as a standard extension for reST files as
136
;; http://docutils.sourceforge.net/FAQ.html#what-s-the-standard-filename-extension-for-a-restructuredtext-file
137
;; suggests you may use one of the `Local Variables in Files' mechanism Emacs
138
;; provides to set the major mode automatically. For instance you may use
140
;; .. -*- mode: rst -*-
142
;; in the very first line of your file. However, because this is a major
143
;; security breach you or your administrator may have chosen to switch that
144
;; feature off. See `Local Variables in Files' in the Emacs documentation for a
145
;; more complete discussion.
153
;; - We need to automatically add the rst-text-mode-bindings to rst-mode
154
;; - We need to find better bindings because C-= does not generate an event on
157
;; rst-toc-insert features
158
;; ------------------------
159
;; - rst-toc-insert: We should parse the contents:: options to figure out how
160
;; deep to render the inserted TOC.
161
;; - On load, detect any existing TOCs and set the properties for links.
162
;; - TOC insertion should have an option to add empty lines.
163
;; - TOC insertion should deal with multiple lines
165
;; - There is a bug on redo after undo of adjust when rst-adjust-hook uses the
166
;; automatic toc update. The cursor ends up in the TOC and this is
167
;; annoying. Gotta fix that.
171
;; - Look at the possibility of converting rst-mode from a Major mode to a Minor
172
;; mode of text-mode.
176
;; - We should rename "adornment" to "decoration" or vice-versa in this
178
;; - Add an option to forego using the file structure in order to make
179
;; suggestion, and to always use the preferred decorations to do that.
183
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
184
;; Bindings and hooks
186
(defgroup rst nil "Support for reStructuredText documents"
189
:link '(url-link "http://docutils.sourceforge.net/rst.html"))
191
(defun rst-toc-or-hierarchy ()
192
"Binding for either TOC or decorations hierarchy."
194
(if (not current-prefix-arg)
196
(rst-display-decorations-hierarchy)))
198
;; Define a prefix map for the long form of key combinations.
199
(defvar rst-prefix-map (make-sparse-keymap)
200
"Keymap for rst commands.")
201
(define-key rst-prefix-map "a" 'rst-adjust)
202
(define-key rst-prefix-map "=" 'rst-adjust)
203
(define-key rst-prefix-map "t" 'rst-toc)
204
(define-key rst-prefix-map "h" 'rst-display-decorations-hierarchy)
205
(define-key rst-prefix-map "i" 'rst-toc-insert)
206
(define-key rst-prefix-map "+" 'rst-toc-insert)
207
(define-key rst-prefix-map "p" 'rst-backward-section)
208
(define-key rst-prefix-map "n" 'rst-forward-section)
209
(define-key rst-prefix-map "r" 'rst-shift-region-right)
210
(define-key rst-prefix-map "l" 'rst-shift-region-left)
211
(define-key rst-prefix-map "u" 'rst-toc-insert-update)
212
(define-key rst-prefix-map "c" 'rst-compile)
213
(define-key rst-prefix-map "C" (lambda () (interactive) (rst-compile t)))
215
(defun rst-text-mode-bindings ()
216
"Default text mode hook for rest."
218
;; Direct command (somehow this one does not work on the Mac).
219
(local-set-key [(control ?=)] 'rst-adjust)
221
(define-key mode-specific-map [(control p)] 'rst-backward-section)
222
(define-key mode-specific-map [(control n)] 'rst-forward-section)
223
(define-key mode-specific-map [(control r)] 'rst-shift-region-right)
224
(define-key mode-specific-map [(control l)] 'rst-shift-region-left)
226
;; Bind the rst commands on the C-c p prefix.
227
(define-key mode-specific-map [(p)] rst-prefix-map)
231
;; Note: we cannot bind the TOC update on file write because it messes with
232
;; undo. If we disable undo, since it adds and removes characters, the
233
;; positions in the undo list are not making sense anymore. Dunno what to do
234
;; with this, it would be nice to update when saving.
236
;; (add-hook 'write-contents-hooks 'rst-toc-insert-update-fun)
237
;; (defun rst-toc-insert-update-fun ()
238
;; ;; Disable undo for the write file hook.
239
;; (let ((buffer-undo-list t)) (rst-toc-insert-update) ))
242
;; Additional abbreviations for text-mode.
243
(define-abbrev text-mode-abbrev-table
244
"con" ".. contents::\n..\n " nil 0)
247
;; Paragraph separation customization. This will work better for
248
;; bullet and enumerated lists in restructuredtext documents and
249
;; should not affect filling for other documents too much. Set it up
252
;; (add-hook 'text-mode-hook 'rst-set-paragraph-separation)
253
(defvar rst-extra-paragraph-start
254
"\\|[ \t]*\\([-+*] \\|[0-9]+\\. \\)"
255
"Extra parapraph-separate patterns to add for text-mode.")
256
;; FIXME: What about the missing >?
257
;; The author uses a hardcoded for paragraph-separate: "\f\\|>*[ \t]*$"
259
(defun rst-set-paragraph-separation ()
260
"Sets the paragraph separation for restructuredtext."
261
;; FIXME: the variable should be made automatically buffer local rather than
262
;; using a function here, this function is unnecessary.
263
(make-local-variable 'paragraph-start) ; prevent it growing every time
264
(setq paragraph-start (concat paragraph-start rst-extra-paragraph-start)))
266
;; FIXME: What about paragraph-separate? paragraph-start and paragraph-separate
267
;; are different. The author hardcodes the value to
268
;; "\f\\|>*[ \t]*$\\|>*[ \t]*[-+*] \\|>*[ \t]*[0-9#]+\\. "
270
;; FIXME: the variables above are in limbo and need some fixing.
274
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
279
;; Generic Filter function.
280
(unless (fboundp 'filter)
281
(defun filter (pred list)
282
"Returns a list of all the elements fulfilling the pred requirement (that
283
is for which (pred elem) is true)"
285
(let ((head (car list))
286
(tail (filter pred (cdr list))))
287
(if (funcall pred head)
293
(unless (fboundp 'line-number-at-pos)
294
(defun line-number-at-pos (&optional pos)
295
"Return (narrowed) buffer line number at position POS.
296
If POS is nil, use current buffer location."
297
(let ((opoint (or pos (point))) start)
299
(goto-char (point-min))
303
(1+ (count-lines start (point)))))) )
307
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
308
;; Section Decoration Adjusment
309
;; ============================
311
;; The following functions implement a smart automatic title sectioning feature.
312
;; The idea is that with the cursor sitting on a section title, we try to get as
313
;; much information from context and try to do the best thing automatically.
314
;; This function can be invoked many times and/or with prefix argument to rotate
315
;; between the various sectioning decorations.
317
;; Definitions: the two forms of sectioning define semantically separate section
318
;; levels. A sectioning DECORATION consists in:
322
;; - a STYLE which can be either of 'simple' or 'over-and-under'.
324
;; - an INDENT (meaningful for the over-and-under style only) which determines
325
;; how many characters and over-and-under style is hanging outside of the
326
;; title at the beginning and ending.
328
;; Important note: an existing decoration must be formed by at least two
329
;; characters to be recognized.
331
;; Here are two examples of decorations (| represents the window border, column
335
;; 1. char: '-' e |Some Title
336
;; style: simple |----------
338
;; 2. char: '=' |==============
339
;; style: over-and-under | Some Title
340
;; indent: 2 |==============
345
;; - The underlining character that is used depends on context. The file is
346
;; scanned to find other sections and an appropriate character is selected.
347
;; If the function is invoked on a section that is complete, the character is
348
;; rotated among the existing section decorations.
350
;; Note that when rotating the characters, if we come to the end of the
351
;; hierarchy of decorations, the variable rst-preferred-decorations is
352
;; consulted to propose a new underline decoration, and if continued, we cycle
353
;; the decorations all over again. Set this variable to nil if you want to
354
;; limit the underlining character propositions to the existing decorations in
357
;; - A prefix argument can be used to alternate the style.
359
;; - An underline/overline that is not extended to the column at which it should
360
;; be hanging is dubbed INCOMPLETE. For example::
365
;; Examples of default invocation:
367
;; |Some Title ---> |Some Title
370
;; |Some Title ---> |Some Title
371
;; |----- |----------
374
;; | Some Title ---> | Some Title
377
;; In over-and-under style, when alternating the style, a variable is
378
;; available to select how much default indent to use (it can be zero). Note
379
;; that if the current section decoration already has an indent, we don't
380
;; adjust it to the default, we rather use the current indent that is already
381
;; there for adjustment (unless we cycle, in which case we use the indent
382
;; that has been found previously).
384
(defgroup rst-adjust nil
385
"Settings for adjustment and cycling of section title
390
(defcustom rst-preferred-decorations '( (?= over-and-under 1)
398
"Preferred ordering of section title decorations. This
399
sequence is consulted to offer a new decoration suggestion when
400
we rotate the underlines at the end of the existing hierarchy
401
of characters, or when there is no existing section title in
406
(defcustom rst-default-indent 1
407
"Number of characters to indent the section title when toggling
408
decoration styles. This is used when switching from a simple
409
decoration style to a over-and-under decoration style."
413
(defvar rst-section-text-regexp "^[ \t]*\\S-*[a-zA-Z0-9]\\S-*"
414
"Regular expression for valid section title text.")
417
(defun rst-line-homogeneous-p (&optional accept-special)
418
"Predicate return the unique char if the current line is
419
composed only of a single repeated non-whitespace
420
character. This returns the char even if there is whitespace at
421
the beginning of the line.
423
If ACCEPT-SPECIAL is specified we do not ignore special sequences
424
which normally we would ignore when doing a search on many lines.
425
For example, normally we have cases to ignore commonly occuring
426
patterns, such as :: or ...; with the flag do not ignore them."
428
(back-to-indentation)
429
(unless (looking-at "\n")
430
(let ((c (thing-at-point 'char)))
431
(if (and (looking-at (format "[%s]+[ \t]*$" c))
435
(not (looking-at "::[ \t]*$"))
436
(not (looking-at "\\.\\.\\.[ \t]*$"))
437
;; Discard one char line
438
(not (looking-at ".[ \t]*$"))
444
(defun rst-line-homogeneous-nodent-p (&optional accept-special)
447
(if (looking-at "^[ \t]+")
449
(rst-line-homogeneous-p accept-special)
453
(defun rst-compare-decorations (deco1 deco2)
454
"Compare decorations. Returns true if both are equal,
455
according to restructured text semantics (only the character and
456
the style are compared, the indentation does not matter."
457
(and (eq (car deco1) (car deco2))
458
(eq (cadr deco1) (cadr deco2))))
461
(defun rst-get-decoration-match (hier deco)
462
"Returns the index (level) of the decoration in the given hierarchy.
463
This basically just searches for the item using the appropriate
464
comparison and returns the index. We return nil if the item is
467
(while (and cur (not (rst-compare-decorations (car cur) deco)))
468
(setq cur (cdr cur)))
472
(defun rst-suggest-new-decoration (alldecos &optional prev)
473
"Suggest a new, different decoration, different from all that
476
ALLDECOS is the set of all decorations, including the line
477
numbers. PREV is the optional previous decoration, in order to
478
suggest a better match."
480
;; For all the preferred decorations...
482
;; If 'prev' is given, reorder the list to start searching after the
485
(cdr (rst-get-decoration-match rst-preferred-decorations prev)))
487
;; List of candidates to search.
488
(curpotential (append fplist rst-preferred-decorations)))
490
;; For all the decorations...
493
(while (and cur (not found))
494
(if (rst-compare-decorations (car cur) (car curpotential))
496
(setq found (car curpotential))
497
(setq cur (cdr cur))))
500
(setq curpotential (cdr curpotential)))
502
(copy-list (car curpotential)) ))
504
(defun rst-delete-line ()
505
"A version of kill-line that does not use the kill-ring."
506
(delete-region (line-beginning-position) (min (+ 1 (line-end-position))
509
(defun rst-update-section (char style &optional indent)
510
"Unconditionally updates the style of a section decoration
511
using the given character CHAR, with STYLE 'simple or
512
'over-and-under, and with indent INDENT. If the STYLE is
513
'simple, whitespace before the title is removed (indent is
514
always assume to be 0).
516
If there are existing overline and/or underline from the
517
existing decoration, they are removed before adding the
518
requested decoration."
527
(setq marker (point-marker))
529
;; Fixup whitespace at the beginning and end of the line
530
(if (or (null indent) (eq style 'simple))
533
(delete-horizontal-space)
534
(insert (make-string indent ? ))
537
(delete-horizontal-space)
539
;; Set the current column, we're at the end of the title line
540
(setq len (+ (current-column) indent))
542
;; Remove previous line if it consists only of a single repeated character
545
(and (rst-line-homogeneous-p 1)
546
;; Avoid removing the underline of a title right above us.
547
(save-excursion (forward-line -1)
548
(not (looking-at rst-section-text-regexp)))
551
;; Remove following line if it consists only of a single repeated
555
(and (rst-line-homogeneous-p 1)
557
;; Add a newline if we're at the end of the buffer, for the subsequence
558
;; inserting of the underline
559
(if (= (point) (buffer-end 1))
563
(if (eq style 'over-and-under)
567
(insert (make-string len char))))
572
(insert (make-string len char))
579
(defun rst-normalize-cursor-position ()
580
"If the cursor is on a decoration line or an empty line , place
581
it on the section title line (at the end). Returns the line
582
offset by which the cursor was moved. This works both over or
584
(if (save-excursion (beginning-of-line)
585
(or (rst-line-homogeneous-p 1)
586
(looking-at "^[ \t]*$")))
590
((save-excursion (forward-line -1)
592
(and (looking-at rst-section-text-regexp)
593
(not (rst-line-homogeneous-p 1))))
594
(progn (forward-line -1) -1))
595
((save-excursion (forward-line +1)
597
(and (looking-at rst-section-text-regexp)
598
(not (rst-line-homogeneous-p 1))))
599
(progn (forward-line +1) +1))
604
(defun rst-find-all-decorations ()
605
"Finds all the decorations in the file, and returns a list of
606
(line, decoration) pairs. Each decoration consists in a (char,
607
style, indent) triple.
609
This function does not detect the hierarchy of decorations, it
610
just finds all of them in a file. You can then invoke another
611
function to remove redundancies and inconsistencies."
615
;; Iterate over all the section titles/decorations in the file.
617
(beginning-of-buffer)
618
(while (< (point) (buffer-end 1))
619
(if (rst-line-homogeneous-nodent-p)
621
(setq curline (+ curline (rst-normalize-cursor-position)))
623
;; Here we have found a potential site for a decoration,
625
(let ((deco (rst-get-decoration)))
626
(if (cadr deco) ;; Style is existing.
627
;; Found a real decoration site.
629
(push (cons curline deco) positions)
630
;; Push beyond the underline.
632
(setq curline (+ curline 1))
636
(setq curline (+ curline 1))
638
(reverse positions)))
641
(defun rst-infer-hierarchy (decorations)
642
"Build a hierarchy of decorations using the list of given decorations.
644
This function expects a list of (char, style, indent)
645
decoration specifications, in order that they appear in a file,
646
and will infer a hierarchy of section levels by removing
647
decorations that have already been seen in a forward traversal of the
648
decorations, comparing just the character and style.
650
Similarly returns a list of (char, style, indent), where each
651
list element should be unique."
653
(let ((hierarchy-alist (list)))
654
(dolist (x decorations)
658
(unless (assoc (cons char style) hierarchy-alist)
659
(setq hierarchy-alist
660
(append hierarchy-alist
661
(list (cons (cons char style) x)))) )
663
(mapcar 'cdr hierarchy-alist)
667
(defun rst-get-hierarchy (&optional alldecos ignore)
668
"Returns a list of decorations that represents the hierarchy of
669
section titles in the file.
671
If the line number in IGNORE is specified, the decoration found
672
on that line (if there is one) is not taken into account when
673
building the hierarchy."
674
(let ((all (or alldecos (rst-find-all-decorations))))
675
(setq all (assq-delete-all ignore all))
676
(rst-infer-hierarchy (mapcar 'cdr all))))
679
(defun rst-get-decoration (&optional point)
680
"Looks around point and finds the characteristics of the
681
decoration that is found there. We assume that the cursor is
682
already placed on the title line (and not on the overline or
685
This function returns a (char, style, indent) triple. If the
686
characters of overline and underline are different, we return
687
the underline character. The indent is always calculated. A
688
decoration can be said to exist if the style is not nil.
690
A point can be specified to go to the given location before
691
extracting the decoration."
693
(let (char style indent)
695
(if point (goto-char point))
697
(if (looking-at rst-section-text-regexp)
698
(let* ((over (save-excursion
700
(rst-line-homogeneous-nodent-p)))
702
(under (save-excursion
704
(rst-line-homogeneous-nodent-p)))
707
;; Check that the line above the overline is not part of a title
711
(and (equal (forward-line -2) 0)
712
(looking-at rst-section-text-regexp))))
716
;; No decoration found, leave all return values nil.
717
((and (eq over nil) (eq under nil)))
719
;; Overline only, leave all return values nil.
721
;; Note: we don't return the overline character, but it could
722
;; perhaps in some cases be used to do something.
723
((and over (eq under nil)))
726
((and under (eq over nil))
730
;; Both overline and underline.
733
style 'over-and-under))
738
(setq indent (save-excursion (back-to-indentation) (current-column)))
741
(list char style indent)))
744
(defun rst-get-decorations-around (&optional alldecos)
745
"Given the list of all decorations (with positions),
746
find the decorations before and after the given point.
747
A list of the previous and next decorations is returned."
748
(let* ((all (or alldecos (rst-find-all-decorations)))
749
(curline (line-number-at-pos))
753
;; Search for the decorations around the current line.
754
(while (and cur (< (caar cur) curline))
757
;; 'cur' is the following decoration.
759
(if (and cur (caar cur))
760
(setq next (if (= curline (caar cur)) (cdr cur) cur)))
762
(mapcar 'cdar (list prev next))
766
(defun rst-decoration-complete-p (deco &optional point)
767
"Return true if the decoration DECO around POINT is complete."
768
;; Note: we assume that the detection of the overline as being the underline
769
;; of a preceding title has already been detected, and has been eliminated
770
;; from the decoration that is given to us.
772
;; There is some sectioning already present, so check if the current
773
;; sectioning is complete and correct.
774
(let* ((char (car deco))
776
(indent (caddr deco))
777
(endcol (save-excursion (end-of-line) (current-column)))
780
(let ((exps (concat "^"
781
(regexp-quote (make-string (+ endcol indent) char))
784
(save-excursion (forward-line +1)
787
(or (not (eq style 'over-and-under))
788
(save-excursion (forward-line -1)
795
(defun rst-get-next-decoration
796
(curdeco hier &optional suggestion reverse-direction)
797
"Get the next decoration for CURDECO, in given hierarchy HIER,
798
and suggesting for new decoration SUGGESTION."
802
(style (cadr curdeco))
804
;; Build a new list of decorations for the rotation.
807
;; Suggest a new decoration.
809
;; If nothing to suggest, use first decoration.
812
;; Search for next decoration.
814
(let ((cur (if reverse-direction rotdecos
818
(not (and (eq char (caar cur))
819
(eq style (cadar cur)))))
820
(setq cur (cdr cur)))
823
;; If not found, take the first of all decorations.
829
"Adjust/rotate the section decoration for the section title
830
around point or promote/demote the decorations inside the region,
831
depending on if the region is active. This function is meant to
832
be invoked possibly multiple times, and can vary its behaviour
833
with a positive prefix argument (toggle style), or with a
834
negative prefix argument (alternate behaviour).
836
This function is the main focus of this module and is a bit of a
837
swiss knife. It is meant as the single most essential function
838
to be bound to invoke to adjust the decorations of a section
839
title in restructuredtext. It tries to deal with all the
840
possible cases gracefully and to do `the right thing' in all
843
See the documentations of rst-adjust-decoration and
844
rst-promote-region for full details.
849
The method can take either (but not both) of
851
a. a (non-negative) prefix argument, which means to toggle the
852
decoration style. Invoke with C-u prefix for example;
854
b. a negative numerical argument, which generally inverts the
855
direction of search in the file or hierarchy. Invoke with C--
861
(let* ( ;; Parse the positive and negative prefix arguments.
863
(and current-prefix-arg
864
(< (prefix-numeric-value current-prefix-arg) 0)))
866
(and current-prefix-arg (not reverse-direction))))
868
(if (and transient-mark-mode mark-active)
869
;; Adjust decorations within region.
870
(rst-promote-region current-prefix-arg)
871
;; Adjust decoration around point.
872
(rst-adjust-decoration toggle-style reverse-direction))
874
;; Run the hooks to run after adjusting.
875
(run-hooks 'rst-adjust-hook)
879
(defvar rst-adjust-hook nil
880
"Hooks to be run after running rst-adjust.")
882
(defun rst-adjust-decoration (&optional toggle-style reverse-direction)
883
"Adjust/rotate the section decoration for the section title around point.
885
This function is meant to be invoked possibly multiple times, and
886
can vary its behaviour with a true TOGGLE-STYLE argument, or with
887
a REVERSE-DIRECTION argument.
892
The next action it takes depends on context around the point, and
893
it is meant to be invoked possibly more than once to rotate among
894
the various possibilities. Basically, this function deals with:
896
- adding a decoration if the title does not have one;
898
- adjusting the length of the underline characters to fit a
901
- rotating the decoration in the set of already existing
902
sectioning decorations used in the file;
904
- switching between simple and over-and-under styles.
906
You should normally not have to read all the following, just
907
invoke the method and it will do the most obvious thing that you
911
Decoration Definitions
912
======================
914
The decorations consist in
918
2. a STYLE which can be either of 'simple' or 'over-and-under'.
920
3. an INDENT (meaningful for the over-and-under style only)
921
which determines how many characters and over-and-under
922
style is hanging outside of the title at the beginning and
925
See source code for mode details.
928
Detailed Behaviour Description
929
==============================
931
Here are the gory details of the algorithm (it seems quite
932
complicated, but really, it does the most obvious thing in all
933
the particular cases):
935
Before applying the decoration change, the cursor is placed on
936
the closest line that could contain a section title.
938
Case 1: No Decoration
939
---------------------
941
If the current line has no decoration around it,
943
- search backwards for the last previous decoration, and apply
944
the decoration one level lower to the current line. If there
945
is no defined level below this previous decoration, we suggest
946
the most appropriate of the rst-preferred-decorations.
948
If REVERSE-DIRECTION is true, we simply use the previous
949
decoration found directly.
951
- if there is no decoration found in the given direction, we use
952
the first of rst-preferred-decorations.
954
The prefix argument forces a toggle of the prescribed decoration
957
Case 2: Incomplete Decoration
958
-----------------------------
960
If the current line does have an existing decoration, but the
961
decoration is incomplete, that is, the underline/overline does
962
not extend to exactly the end of the title line (it is either too
963
short or too long), we simply extend the length of the
964
underlines/overlines to fit exactly the section title.
966
If the prefix argument is given, we toggle the style of the
969
REVERSE-DIRECTION has no effect in this case.
971
Case 3: Complete Existing Decoration
972
------------------------------------
974
If the decoration is complete (i.e. the underline (overline)
975
length is already adjusted to the end of the title line), we
976
search/parse the file to establish the hierarchy of all the
977
decorations (making sure not to include the decoration around
978
point), and we rotate the current title's decoration from within
979
that list (by default, going *down* the hierarchy that is present
980
in the file, i.e. to a lower section level). This is meant to be
981
used potentially multiple times, until the desired decoration is
982
found around the title.
984
If we hit the boundary of the hierarchy, exactly one choice from
985
the list of preferred decorations is suggested/chosen, the first
986
of those decoration that has not been seen in the file yet (and
987
not including the decoration around point), and the next
988
invocation rolls over to the other end of the hierarchy (i.e. it
989
cycles). This allows you to avoid having to set which character
990
to use by always using the
992
If REVERSE-DIRECTION is true, the effect is to change the
993
direction of rotation in the hierarchy of decorations, thus
994
instead going *up* the hierarchy.
996
However, if there is a non-negative prefix argument, we do not
997
rotate the decoration, but instead simply toggle the style of the
998
current decoration (this should be the most common way to toggle
999
the style of an existing complete decoration).
1005
The invocation of this function can be carried out anywhere
1006
within the section title line, on an existing underline or
1007
overline, as well as on an empty line following a section title.
1008
This is meant to be as convenient as possible.
1014
Indented section titles such as ::
1019
are illegal in restructuredtext and thus not recognized by the
1020
parser. This code will thus not work in a way that would support
1021
indented sections (it would be ambiguous anyway).
1027
Section titles that are right next to each other may not be
1028
treated well. More work might be needed to support those, and
1029
special conditions on the completeness of existing decorations
1030
might be required to make it non-ambiguous.
1032
For now we assume that the decorations are disjoint, that is,
1033
there is at least a single line between the titles/decoration
1040
We suggest that you bind this function on C-=. It is close to
1041
C-- so a negative argument can be easily specified with a flick
1042
of the right hand fingers and the binding is unused in text-mode."
1045
;; If we were invoked directly, parse the prefix arguments into the
1046
;; arguments of the function.
1047
(if current-prefix-arg
1048
(setq reverse-direction
1049
(and current-prefix-arg
1050
(< (prefix-numeric-value current-prefix-arg) 0))
1053
(and current-prefix-arg (not reverse-direction))))
1055
(let* (;; Check if we're on an underline around a section title, and move the
1056
;; cursor to the title if this is the case.
1057
(moved (rst-normalize-cursor-position))
1059
;; Find the decoration and completeness around point.
1060
(curdeco (rst-get-decoration))
1061
(char (car curdeco))
1062
(style (cadr curdeco))
1063
(indent (caddr curdeco))
1065
;; New values to be computed.
1066
char-new style-new indent-new
1069
;; We've moved the cursor... if we're not looking at some text, we have
1071
(if (save-excursion (beginning-of-line)
1072
(looking-at rst-section-text-regexp))
1075
;;-------------------------------------------------------------------
1076
;; Case 1: No Decoration
1077
((and (eq char nil) (eq style nil))
1079
(let* ((alldecos (rst-find-all-decorations))
1081
(around (rst-get-decorations-around alldecos))
1085
(hier (rst-get-hierarchy alldecos))
1088
;; Advance one level down.
1091
(if (not reverse-direction)
1092
(or (cadr (rst-get-decoration-match hier prev))
1093
(rst-suggest-new-decoration hier prev))
1095
(copy-list (car rst-preferred-decorations))
1098
;; Invert the style if requested.
1100
(setcar (cdr cur) (if (eq (cadr cur) 'simple)
1101
'over-and-under 'simple)) )
1103
(setq char-new (car cur)
1104
style-new (cadr cur)
1105
indent-new (caddr cur))
1108
;;-------------------------------------------------------------------
1109
;; Case 2: Incomplete Decoration
1110
((not (rst-decoration-complete-p curdeco))
1112
;; Invert the style if requested.
1114
(setq style (if (eq style 'simple) 'over-and-under 'simple)))
1120
;;-------------------------------------------------------------------
1121
;; Case 3: Complete Existing Decoration
1125
;; Simply switch the style of the current decoration.
1127
style-new (if (eq style 'simple) 'over-and-under 'simple)
1128
indent-new rst-default-indent)
1130
;; Else, we rotate, ignoring the decoration around the current
1132
(let* ((alldecos (rst-find-all-decorations))
1134
(hier (rst-get-hierarchy alldecos (line-number-at-pos)))
1136
;; Suggestion, in case we need to come up with something
1138
(suggestion (rst-suggest-new-decoration
1140
(car (rst-get-decorations-around alldecos))))
1142
(nextdeco (rst-get-next-decoration
1143
curdeco hier suggestion reverse-direction))
1147
;; Indent, if present, always overrides the prescribed indent.
1148
(setq char-new (car nextdeco)
1149
style-new (cadr nextdeco)
1150
indent-new (caddr nextdeco))
1155
;; Override indent with present indent!
1156
(setq indent-new (if (> indent 0) indent indent-new))
1158
(if (and char-new style-new)
1159
(rst-update-section char-new style-new indent-new))
1163
;; Correct the position of the cursor to more accurately reflect where it
1164
;; was located when the function was invoked.
1166
(forward-line (- moved))
1171
;; Maintain an alias for compatibility.
1172
(defalias 'rst-adjust-section-title 'rst-adjust)
1175
(defun rst-promote-region (&optional demote)
1176
"Promote the section titles within the region.
1178
With argument DEMOTE or a prefix argument, demote the
1179
section titles instead. The algorithm used at the boundaries of
1180
the hierarchy is similar to that used by rst-adjust-decoration."
1183
(let* ((demote (or current-prefix-arg demote))
1184
(alldecos (rst-find-all-decorations))
1187
(hier (rst-get-hierarchy alldecos))
1188
(suggestion (rst-suggest-new-decoration hier))
1190
(region-begin-line (line-number-at-pos (region-beginning)))
1191
(region-end-line (line-number-at-pos (region-end)))
1196
;; Skip the markers that come before the region beginning
1197
(while (and cur (< (caar cur) region-begin-line))
1198
(setq cur (cdr cur)))
1200
;; Create a list of markers for all the decorations which are found within
1204
(while (and cur (< (setq line (caar cur)) region-end-line))
1205
(setq m (make-marker))
1207
(push (list (set-marker m (point)) (cdar cur)) marker-list)
1208
(setq cur (cdr cur)) ))
1210
;; Apply modifications.
1212
(dolist (p marker-list)
1213
;; Go to the decoration to promote.
1216
;; Rotate the next decoration.
1217
(setq nextdeco (rst-get-next-decoration
1218
(cadr p) hier suggestion demote))
1220
;; Update the decoration.
1221
(apply 'rst-update-section nextdeco)
1223
;; Clear marker to avoid slowing down the editing after we're done.
1224
(set-marker (car p) nil)
1226
(setq deactivate-mark nil)
1231
(defun rst-display-decorations-hierarchy (&optional decorations)
1232
"Display the current file's section title decorations hierarchy.
1233
This function expects a list of (char, style, indent) triples."
1236
(if (not decorations)
1237
(setq decorations (rst-get-hierarchy)))
1238
(with-output-to-temp-buffer "*rest section hierarchy*"
1240
(with-current-buffer standard-output
1241
(dolist (x decorations)
1242
(insert (format "\nSection Level %d" level))
1243
(apply 'rst-update-section x)
1251
(defun rst-rstrip (str)
1252
"Strips the whitespace at the end of a string."
1254
(string-match "[ \t\n]*\\'" str)
1255
(substring str 0 (match-beginning 0))
1258
(defun rst-get-stripped-line ()
1259
"Returns the line at cursor, stripped from whitespace."
1260
(re-search-forward "\\S-.*\\S-" (line-end-position))
1261
(buffer-substring-no-properties (match-beginning 0)
1264
(defun rst-section-tree (alldecos)
1265
"Returns a hierarchical tree of the sections titles in the
1266
document. This can be used to generate a table of contents for
1267
the document. The top node will always be a nil node, with the
1268
top-level titles as children (there may potentially be more than
1271
Each section title consists in a cons of the stripped title
1272
string and a marker to the section in the original text document.
1274
If there are missing section levels, the section titles are
1275
inserted automatically, and the title string is set to nil, and
1276
the marker set to the first non-nil child of itself.
1277
Conceptually, the nil nodes--i.e. those which have no title--are
1278
to be considered as being the same line as their first non-nil
1279
child. This has advantages later in processing the graph."
1282
(hier (rst-get-hierarchy alldecos))
1283
(levels (make-hash-table :test 'equal :size 10))
1288
;; Compare just the character and indent in the hash table.
1289
(puthash (cons (car deco) (cadr deco)) lev levels)
1292
;; Create a list of lines that contains (text, level, marker) for each
1296
(mapcar (lambda (deco)
1297
(goto-line (car deco))
1298
(list (gethash (cons (cadr deco) (caddr deco)) levels)
1299
(rst-get-stripped-line)
1300
(let ((m (make-marker)))
1301
(beginning-of-line 1)
1302
(set-marker m (point)))
1306
(let ((lcontnr (cons nil lines)))
1307
(rst-section-tree-rec lcontnr -1))))
1310
(defun rst-section-tree-rec (decos lev)
1311
"Recursive function for the implementation of the section tree
1312
building. DECOS is a cons cell whose cdr is the remaining list
1313
of decorations, and we change it as we consume them. LEV is
1314
the current level of that node. This function returns a pair
1315
of the subtree that was built. This treats the decos list
1318
(let ((ndeco (cadr decos))
1322
;; If the next decoration matches our level
1323
(when (and ndeco (= (car ndeco) lev))
1324
;; Pop the next decoration and create the current node with it
1325
(setcdr decos (cddr decos))
1326
(setq node (cdr ndeco)) )
1327
;; Else we let the node title/marker be unset.
1329
;; Build the child nodes
1330
(while (and (cdr decos) (> (caadr decos) lev))
1332
(cons (rst-section-tree-rec decos (1+ lev))
1334
(setq children (reverse children))
1336
;; If node is still unset, we use the marker of the first child.
1338
(setq node (cons nil (cdaar children))))
1340
;; Return this node with its children.
1341
(cons node children)
1345
(defun rst-section-tree-point (node &optional point)
1346
"Given a computed and valid section tree SECTREE and a point
1347
POINT (default being the current point in the current buffer),
1348
find and return the node within the sectree where the cursor
1351
Return values: a pair of (parent path, container subtree). The
1352
parent path is simply a list of the nodes above the container
1353
subtree node that we're returning."
1357
(let* ((curpoint (or point (point))))
1359
;; Check if we are before the current node.
1360
(if (and (cadar node) (>= curpoint (cadar node)))
1362
;; Iterate all the children, looking for one that might contain the
1364
(let ((curnode (cdr node))
1367
(while (and curnode (>= curpoint (cadaar curnode)))
1369
curnode (cdr curnode)))
1372
(let ((sub (rst-section-tree-point (car last) curpoint)))
1373
(setq path (car sub)
1375
(setq outtree node))
1378
(cons (cons (car node) path) outtree)
1382
(defun rst-toc-insert (&optional pfxarg)
1383
"Insert a simple text rendering of the table of contents.
1384
By default the top level is ignored if there is only one, because
1385
we assume that the document will have a single title.
1387
If a numeric prefix argument is given, insert the TOC up to the
1390
The TOC is inserted indented at the current column."
1394
(let* (;; Check maximum level override
1395
(rst-toc-insert-max-level
1396
(if (and (integerp pfxarg) (> (prefix-numeric-value pfxarg) 0))
1397
(prefix-numeric-value pfxarg) rst-toc-insert-max-level))
1399
;; Get the section tree for the current cursor point.
1401
(rst-section-tree-point
1402
(rst-section-tree (rst-find-all-decorations))))
1404
;; Figure out initial indent.
1405
(initial-indent (make-string (current-column) ? ))
1406
(init-point (point)))
1408
(when (cddr sectree-pair)
1409
(rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
1411
;; Fixup for the first line.
1412
(delete-region init-point (+ init-point (length initial-indent)))
1414
;; Delete the last newline added.
1415
(delete-backward-char 1)
1419
(defgroup rst-toc nil
1420
"Settings for reStructuredText table of contents."
1424
(defcustom rst-toc-indent 2
1425
"Indentation for table-of-contents display (also used for
1426
formatting insertion, when numbering is disabled)."
1429
(defcustom rst-toc-insert-style 'fixed
1430
"Set this to one of the following values to determine numbering and
1432
- plain: no numbering (fixed indentation)
1433
- fixed: numbering, but fixed indentation
1434
- aligned: numbering, titles aligned under each other
1435
- listed: numbering, with dashes like list items (EXPERIMENTAL)
1439
(defcustom rst-toc-insert-number-separator " "
1440
"Separator that goes between the TOC number and the title."
1443
;; This is used to avoid having to change the user's mode.
1444
(defvar rst-toc-insert-click-keymap
1445
(let ((map (make-sparse-keymap)))
1446
(define-key map [mouse-1] 'rst-toc-mode-mouse-goto)
1448
"(Internal) What happens when you click on propertized text in the TOC.")
1450
(defcustom rst-toc-insert-max-level nil
1451
"If non-nil, maximum depth of the inserted TOC."
1454
(defun rst-toc-insert-node (node level indent pfx)
1455
"Recursive function that does the print of the inserted
1456
toc. PFX is the prefix numbering, that includes the alignment
1457
necessary for all the children of this level to align."
1459
;; Note: we do child numbering from the parent, so we start number the
1460
;; children one level before we print them.
1461
(let ((do-print (> level 0))
1467
(unless (equal rst-toc-insert-style 'plain)
1468
(insert pfx rst-toc-insert-number-separator))
1469
(insert (or (caar node) "[missing node]"))
1470
;; Add properties to the text, even though in normal text mode it
1471
;; won't be doing anything for now. Not sure that I want to change
1472
;; mode stuff. At least the highlighting gives the idea that this
1473
;; is generated automatically.
1474
(put-text-property b (point) 'mouse-face 'highlight)
1475
(put-text-property b (point) 'rst-toc-target (cadar node))
1476
(put-text-property b (point) 'keymap rst-toc-insert-click-keymap)
1481
;; Prepare indent for children.
1484
((eq rst-toc-insert-style 'plain)
1485
(concat indent rst-toc-indent))
1487
((eq rst-toc-insert-style 'fixed)
1488
(concat indent (make-string rst-toc-indent ? )))
1490
((eq rst-toc-insert-style 'aligned)
1491
(concat indent (make-string (+ (length pfx) 2) ? )))
1493
((eq rst-toc-insert-style 'listed)
1494
(concat (substring indent 0 -3)
1495
(concat (make-string (+ (length pfx) 2) ? ) " - ")))
1499
(if (or (eq rst-toc-insert-max-level nil)
1500
(< level rst-toc-insert-max-level))
1501
(let ((do-child-numbering (>= level 0))
1503
(if do-child-numbering
1505
;; Add a separating dot if there is already a prefix
1506
(if (> (length pfx) 0)
1507
(setq pfx (concat (rst-rstrip pfx) ".")))
1509
;; Calculate the amount of space that the prefix will require
1512
(setq fmt (format "%%-%dd"
1513
(1+ (floor (log10 (length
1517
(dolist (child (cdr node))
1518
(rst-toc-insert-node child
1521
(if do-child-numbering
1522
(concat pfx (format fmt count)) pfx))
1528
(defun rst-toc-insert-find-delete-contents ()
1529
"Finds and deletes an existing comment after the first contents directive and
1530
delete that region. Return t if found and the cursor is left after the comment."
1531
(goto-char (point-min))
1532
;; We look for the following and the following only (in other words, if your
1533
;; syntax differs, this won't work. If you would like a more flexible thing,
1534
;; contact the author, I just can't imagine that this requirement is
1535
;; unreasonable for now).
1537
;; .. contents:: [...anything here...]
1544
(re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
1548
;; Look for the first line that starts at the first column.
1552
(< (point) (point-max))
1553
(or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
1554
(looking-at "\\s-*$")))
1559
(goto-char last-real)
1561
(delete-region beg (point)))
1566
(defun rst-toc-insert-update ()
1567
"Automatically find the .. contents:: section of a document and update the
1568
inserted TOC if present. You can use this in your file-write hook to always
1569
make it up-to-date automatically."
1572
(if (rst-toc-insert-find-delete-contents)
1573
(progn (insert "\n ")
1574
(rst-toc-insert))) )
1575
;; Note: always return nil, because this may be used as a hook.
1579
;;------------------------------------------------------------------------------
1581
(defun rst-toc-node (node level)
1582
"Recursive function that does the print of the TOC in rst-toc-mode."
1586
;; Insert line text.
1587
(insert (make-string (* rst-toc-indent (1- level)) ? ))
1588
(insert (or (caar node) "[missing node]"))
1591
(put-text-property b (point) 'mouse-face 'highlight)
1593
;; Add link on lines.
1594
(put-text-property b (point) 'rst-toc-target (cadar node))
1599
(dolist (child (cdr node))
1600
(rst-toc-node child (1+ level))))
1602
(defun rst-toc-count-lines (node target-node)
1603
"Count the number of lines to the TARGET-NODE node. This
1604
recursive function returns a cons of the number of additional
1605
lines that have been counted for its node and children and 't if
1606
the node has been found."
1610
(if (eq node target-node)
1612
(let ((child (cdr node)))
1613
(while (and child (not found))
1614
(let ((cl (rst-toc-count-lines (car child) target-node)))
1615
(setq count (+ count (car cl))
1617
child (cdr child))))))
1618
(cons count found)))
1622
"Finds all the section titles and their decorations in the
1623
file, and displays a hierarchically-organized list of the
1624
titles, which is essentially a table-of-contents of the
1627
The emacs buffer can be navigated, and selecting a section
1628
brings the cursor in that section."
1630
(let* ((curbuf (current-buffer))
1632
;; Get the section tree
1633
(alldecos (rst-find-all-decorations))
1634
(sectree (rst-section-tree alldecos))
1636
(our-node (cdr (rst-section-tree-point sectree)))
1639
;; Create a temporary buffer.
1640
(buf (get-buffer-create rst-toc-buffer-name))
1643
(with-current-buffer buf
1644
(let ((inhibit-read-only t))
1646
(delete-region (point-min) (point-max))
1647
(insert (format "Table of Contents: %s\n" (or (caar sectree) "")))
1648
(put-text-property (point-min) (point)
1649
'face (list '(background-color . "lightgray")))
1650
(rst-toc-node sectree 0)
1652
;; Count the lines to our found node.
1653
(let ((linefound (rst-toc-count-lines sectree our-node)))
1654
(setq line (if (cdr linefound) (car linefound) 0)))
1656
(display-buffer buf)
1659
;; Save the buffer to return to.
1660
(set (make-local-variable 'rst-toc-return-buffer) curbuf)
1662
;; Move the cursor near the right section in the TOC.
1667
(defun rst-toc-mode-find-section ()
1668
(let ((pos (get-text-property (point) 'rst-toc-target)))
1670
(error "No section on this line"))
1671
(unless (buffer-live-p (marker-buffer pos))
1672
(error "Buffer for this section was killed"))
1675
(defvar rst-toc-buffer-name "*Table of Contents*"
1676
"Name of the Table of Contents buffer.")
1678
(defun rst-toc-mode-goto-section ()
1679
"Go to the section the current line describes."
1681
(let ((pos (rst-toc-mode-find-section)))
1682
(kill-buffer (get-buffer rst-toc-buffer-name))
1683
(pop-to-buffer (marker-buffer pos))
1687
(defun rst-toc-mode-mouse-goto (event)
1688
"In Rst-Toc mode, go to the occurrence whose line you click on."
1692
(set-buffer (window-buffer (posn-window (event-end event))))
1694
(goto-char (posn-point (event-end event)))
1695
(setq pos (rst-toc-mode-find-section))))
1696
(pop-to-buffer (marker-buffer pos))
1699
(defun rst-toc-mode-mouse-goto-kill (event)
1701
(call-interactively 'rst-toc-mode-mouse-goto event)
1702
(kill-buffer (get-buffer rst-toc-buffer-name)))
1704
(defvar rst-toc-return-buffer nil
1705
"Buffer local variable that is used to return to the original
1706
buffer from the TOC.")
1708
(defun rst-toc-quit-window ()
1711
(pop-to-buffer rst-toc-return-buffer))
1713
(defvar rst-toc-mode-map
1714
(let ((map (make-sparse-keymap)))
1715
(define-key map [mouse-1] 'rst-toc-mode-mouse-goto-kill)
1716
(define-key map [mouse-2] 'rst-toc-mode-mouse-goto)
1717
(define-key map "\C-m" 'rst-toc-mode-goto-section)
1718
(define-key map "f" 'rst-toc-mode-goto-section)
1719
(define-key map "q" 'rst-toc-quit-window)
1720
(define-key map "z" 'kill-this-buffer)
1722
"Keymap for `rst-toc-mode'.")
1724
(put 'rst-toc-mode 'mode-class 'special)
1726
(defun rst-toc-mode ()
1727
"Major mode for output from \\[rst-toc]."
1729
(kill-all-local-variables)
1730
(use-local-map rst-toc-mode-map)
1731
(setq major-mode 'rst-toc-mode)
1732
(setq mode-name "Rst-TOC")
1733
(setq buffer-read-only t)
1736
;; Note: use occur-mode (replace.el) as a good example to complete missing
1740
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1742
;; Section movement commands.
1745
(defun rst-forward-section (&optional offset)
1746
"Skip to the next restructured text section title.
1747
OFFSET specifies how many titles to skip. Use a negative OFFSET to move
1748
backwards in the file (default is to use 1)."
1750
(let* (;; Default value for offset.
1751
(offset (or offset 1))
1753
;; Get all the decorations in the file, with their line numbers.
1754
(alldecos (rst-find-all-decorations))
1756
;; Get the current line.
1757
(curline (line-number-at-pos))
1764
;; Find the index of the "next" decoration w.r.t. to the current line.
1765
(while (and cur (< (caar cur) curline))
1766
(setq cur (cdr cur))
1768
;; 'cur' is the decoration on or following the current line.
1770
(if (and (> offset 0) cur (= (caar cur) curline))
1773
;; Find the final index.
1774
(setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
1775
(setq cur (nth idx alldecos))
1777
;; If the index is positive, goto the line, otherwise go to the buffer
1779
(if (and cur (>= idx 0))
1780
(goto-line (car cur))
1781
(if (> offset 0) (end-of-buffer) (beginning-of-buffer)))
1784
(defun rst-backward-section ()
1785
"Like rst-forward-section, except move back one title."
1787
(rst-forward-section -1))
1792
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1793
;; Functions to indent/dedent item lists, which are always two-characters apart
1794
;; horizontally with rest.
1796
(defvar rst-shift-fill-region nil
1797
"Set to true if you want to automatically re-fill the region that is being
1799
;; FIXME: need to finish this feature properly.
1802
(defun rst-shift-region-right ()
1803
"Indent region ridigly, by two characters to the right."
1805
(let ((mbeg (set-marker (make-marker) (region-beginning)))
1806
(mend (set-marker (make-marker) (region-end))))
1807
(indent-rigidly mbeg mend 2)
1808
(when rst-shift-fill-region
1809
(fill-region mbeg mend))
1812
(defun rst-find-leftmost-column (beg end)
1813
"Finds the leftmost column in the region."
1814
(let ((mincol 1000))
1817
(while (< (point) end)
1818
(back-to-indentation)
1819
(unless (looking-at "[ \t]*$")
1820
(setq mincol (min mincol (current-column))))
1825
(defun rst-shift-region-left (pfxarg)
1826
"Indent region ridigly, by two characters to the left.
1827
If invoked with a prefix arg, the entire indentation is removed,
1828
up to the leftmost character in the region."
1832
(- (rst-find-leftmost-column (region-beginning) (region-end)))
1834
(mbeg (set-marker (make-marker) (region-beginning)))
1835
(mend (set-marker (make-marker) (region-end)))
1837
(indent-rigidly mbeg mend chars)
1838
(when rst-shift-fill-region
1839
(fill-region mbeg mend))
1844
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1845
;;; rst-mode.el --- Mode for viewing and editing reStructuredText-documents.
1847
;; Copyright 2003 Stefan Merten <smerten@oekonux.de>
1849
;; Note: this is an update from version 0.2.9 of rst-mode.el
1853
;; This package provides support for documents marked up using the
1854
;; reStructuredText format. Support includes font locking as well as some
1855
;; convenience functions for editing. It does this by defining a Emacs major
1858
;; The package is based on text-mode and inherits some things from it.
1859
;; Particularly text-mode-hook is run before rst-mode-hook.
1863
;; There are a number of things which can be customized using the standard
1864
;; Emacs customization features. There are two customization groups for this
1872
;; This group contains some general customizable features.
1874
;; The group is contained in the wp group.
1878
;; This group contains all necessary for customizing fonts. The default
1879
;; settings use standard font-lock-*-face's so if you set these to your
1880
;; liking they are probably good in rst-mode also.
1882
;; The group is contained in the faces group as well as in the rst group.
1884
;; rst-faces-defaults
1885
;; ------------------
1886
;; This group contains all necessary for customizing the default fonts used for
1887
;; section title faces.
1889
;; The general idea for section title faces is to have a non-default background
1890
;; but do not change the background. The section level is shown by the
1891
;; lightness of the background color. If you like this general idea of
1892
;; generating faces for section titles but do not like the details this group
1893
;; is the point where you can customize the details. If you do not like the
1894
;; general idea, however, you should customize the faces used in
1895
;; rst-adornment-faces-alist.
1897
;; Note: If you are using a dark background please make sure the variable
1898
;; frame-background-mode is set to the symbol dark. This triggers
1899
;; some default values which are probably right for you.
1901
;; The group is contained in the rst-faces group.
1903
;; All customizable features have a comment explaining their meaning. Refer to
1904
;; the customization of your Emacs (try ``M-x customize``).
1908
;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
1912
;; Stefan Merten <smerten AT oekonux.de>
1916
;; This program is licensed under the terms of the GPL. See
1918
;; http://www.gnu.org/licenses/gpl.txt
1924
;; http://www.merten-home.de/FreeSoftware/rst-mode/
1929
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1932
(defcustom rst-mode-hook nil
1933
"Hook run when Rst Mode is turned on. The hook for Text Mode is run before
1938
(defcustom rst-mode-lazy t
1939
"*If non-nil Rst Mode font-locks comment, literal blocks, and section titles
1940
correctly. Because this is really slow it switches on Lazy Lock Mode
1941
automatically. You may increase Lazy Lock Defer Time for reasonable results.
1943
If nil comments and literal blocks are font-locked only on the line they start.
1945
The value of this variable is used when Rst Mode is turned on."
1949
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1951
(defgroup rst-faces nil "Faces used in Rst Mode"
1956
(defcustom rst-block-face 'font-lock-keyword-face
1957
"All syntax marking up a special block"
1961
(defcustom rst-external-face 'font-lock-type-face
1962
"Field names and interpreted text"
1966
(defcustom rst-definition-face 'font-lock-function-name-face
1967
"All other defining constructs"
1971
(defcustom rst-directive-face
1972
;; XEmacs compatibility
1973
(if (boundp 'font-lock-builtin-face)
1974
'font-lock-builtin-face
1975
'font-lock-preprocessor-face)
1976
"Directives and roles"
1980
(defcustom rst-comment-face 'font-lock-comment-face
1985
(defcustom rst-emphasis1-face
1986
;; XEmacs compatibility
1994
(defcustom rst-emphasis2-face
1995
;; XEmacs compatibility
2003
(defcustom rst-literal-face 'font-lock-string-face
2008
(defcustom rst-reference-face 'font-lock-variable-name-face
2009
"References to a definition"
2013
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2015
(defgroup rst-faces-defaults nil
2016
"Values used to generate default faces for section titles on all levels.
2017
Tweak these if you are content with how section title faces are built in
2018
general but you do not like the details."
2022
(defun rst-define-level-faces ()
2023
"Define the faces for the section title text faces from the values."
2024
;; All variables used here must be checked in `rst-set-level-default'
2026
(while (<= i rst-level-face-max)
2027
(let ((sym (intern (format "rst-level-%d-face" i)))
2028
(doc (format "Face for showing section title text at level %d" i))
2029
(col (format (concat "%s" rst-level-face-format-light)
2030
rst-level-face-base-color
2031
(+ (* (1- i) rst-level-face-step-light)
2032
rst-level-face-base-light))))
2033
(make-empty-face sym)
2034
(set-face-doc-string sym doc)
2035
(set-face-background sym col)
2039
(defun rst-set-level-default (sym val)
2040
"Set a customized value affecting section title text face and recompute the
2042
(custom-set-default sym val)
2043
;; Also defines the faces initially when all values are available
2044
(and (boundp 'rst-level-face-max)
2045
(boundp 'rst-level-face-format-light)
2046
(boundp 'rst-level-face-base-color)
2047
(boundp 'rst-level-face-step-light)
2048
(boundp 'rst-level-face-base-light)
2049
(rst-define-level-faces)))
2051
;; Faces for displaying items on several levels; these definitions define
2052
;; different shades of grey where the lightest one (i.e. least contrasting) is
2054
(defcustom rst-level-face-max 6
2055
"Maximum depth of levels for which section title faces are defined."
2056
:group 'rst-faces-defaults
2058
:set 'rst-set-level-default)
2059
(defcustom rst-level-face-base-color "grey"
2060
"The base name of the color to be used for creating background colors in
2061
ection title faces for all levels."
2062
:group 'rst-faces-defaults
2064
:set 'rst-set-level-default)
2065
(defcustom rst-level-face-base-light
2066
(if (eq frame-background-mode 'dark)
2069
"The lightness factor for the base color. This value is used for level 1. The
2070
default depends on whether the value of `frame-background-mode' is `dark' or
2072
:group 'rst-faces-defaults
2074
:set 'rst-set-level-default)
2075
(defcustom rst-level-face-format-light "%2d"
2076
"The format for the lightness factor appended to the base name of the color.
2077
This value is expanded by `format' with an integer."
2078
:group 'rst-faces-defaults
2080
:set 'rst-set-level-default)
2081
(defcustom rst-level-face-step-light
2082
(if (eq frame-background-mode 'dark)
2085
"The step width to use for the next color. The formula
2087
`rst-level-face-base-light'
2088
+ (`rst-level-face-max' - 1) * `rst-level-face-step-light'
2090
must result in a color level which appended to `rst-level-face-base-color'
2091
using `rst-level-face-format-light' results in a valid color such as `grey50'.
2092
This color is used as background for section title text on level
2093
`rst-level-face-max'."
2094
:group 'rst-faces-defaults
2096
:set 'rst-set-level-default)
2098
(defcustom rst-adornment-faces-alist
2099
(let ((alist '((t . font-lock-keyword-face)
2100
(nil . font-lock-keyword-face)))
2102
(while (<= i rst-level-face-max)
2103
(nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
2106
"Provides faces for the various adornment types. Key is a number (for the
2107
section title text of that level), t (for transitions) or nil (for section
2108
title adornment). If you generally do not like how section title text faces are
2109
set up tweak here. If the general idea is ok for you but you do not like the
2110
details check the Rst Faces Defaults group."
2117
"Section level (may not be bigger than `rst-level-face-max')")
2118
(boolean :tag "transitions (on) / section title adornment (off)"))
2120
:set-after '(rst-level-face-max))
2122
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2124
;; FIXME: Code from `restructuredtext.el' should be integrated
2126
(defvar rst-mode-syntax-table nil
2127
"Syntax table used while in rst mode.")
2129
(unless rst-mode-syntax-table
2130
(setq rst-mode-syntax-table (make-syntax-table text-mode-syntax-table))
2131
(modify-syntax-entry ?$ "." rst-mode-syntax-table)
2132
(modify-syntax-entry ?% "." rst-mode-syntax-table)
2133
(modify-syntax-entry ?& "." rst-mode-syntax-table)
2134
(modify-syntax-entry ?' "." rst-mode-syntax-table)
2135
(modify-syntax-entry ?* "." rst-mode-syntax-table)
2136
(modify-syntax-entry ?+ "." rst-mode-syntax-table)
2137
(modify-syntax-entry ?. "_" rst-mode-syntax-table)
2138
(modify-syntax-entry ?/ "." rst-mode-syntax-table)
2139
(modify-syntax-entry ?< "." rst-mode-syntax-table)
2140
(modify-syntax-entry ?= "." rst-mode-syntax-table)
2141
(modify-syntax-entry ?> "." rst-mode-syntax-table)
2142
(modify-syntax-entry ?\\ "\\" rst-mode-syntax-table)
2143
(modify-syntax-entry ?| "." rst-mode-syntax-table)
2144
(modify-syntax-entry ?_ "." rst-mode-syntax-table)
2147
(defvar rst-mode-abbrev-table nil
2148
"Abbrev table used while in rst mode.")
2149
(define-abbrev-table 'rst-mode-abbrev-table ())
2151
;; FIXME: Movement keys to skip forward / backward over or mark an indented
2152
;; block could be defined; keys to markup section titles based on
2153
;; `rst-adornment-level-alist' would be useful
2154
(defvar rst-mode-map nil
2155
"Keymap for rst mode. This inherits from Text mode.")
2157
(unless rst-mode-map
2158
(setq rst-mode-map (copy-keymap text-mode-map)))
2161
"Major mode for editing reStructuredText documents.
2163
You may customize `rst-mode-lazy' to switch font-locking of blocks.
2166
Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
2169
(kill-all-local-variables)
2172
(use-local-map rst-mode-map)
2173
(setq local-abbrev-table rst-mode-abbrev-table)
2174
(set-syntax-table rst-mode-syntax-table)
2178
;; FIXME: It would be better if this matches more exactly the start of a reST
2179
;; paragraph; however, this not always possible with a simple regex because
2180
;; paragraphs are determined by indentation of the following line
2181
(set (make-local-variable 'paragraph-start)
2182
(concat page-delimiter "\\|[ \t]*$"))
2183
(if (eq ?^ (aref paragraph-start 0))
2184
(setq paragraph-start (substring paragraph-start 1)))
2185
(set (make-local-variable 'paragraph-separate) paragraph-start)
2186
(set (make-local-variable 'indent-line-function) 'indent-relative-maybe)
2187
(set (make-local-variable 'adaptive-fill-mode) t)
2188
(set (make-local-variable 'comment-start) ".. ")
2190
;; Special variables
2191
(make-local-variable 'rst-adornment-level-alist)
2194
(set (make-local-variable 'font-lock-defaults)
2195
'(rst-font-lock-keywords-function
2197
(font-lock-multiline . t)
2198
(font-lock-mark-block-function . mark-paragraph)))
2199
(when (boundp 'font-lock-support-mode)
2200
;; rst-mode has its own mind about font-lock-support-mode
2201
(make-local-variable 'font-lock-support-mode)
2203
((and (not rst-mode-lazy) (not font-lock-support-mode)))
2204
;; No support mode set and none required - leave it alone
2205
((or (not font-lock-support-mode) ;; No support mode set (but required)
2206
(symbolp font-lock-support-mode)) ;; or a fixed mode for all
2207
(setq font-lock-support-mode
2208
(list (cons 'rst-mode (and rst-mode-lazy 'lazy-lock-mode))
2209
(cons t font-lock-support-mode))))
2210
((and (listp font-lock-support-mode)
2211
(not (assoc 'rst-mode font-lock-support-mode)))
2212
;; A list of modes missing rst-mode
2213
(setq font-lock-support-mode
2214
(append '((cons 'rst-mode (and rst-mode-lazy 'lazy-lock-mode)))
2215
font-lock-support-mode)))))
2218
(setq mode-name "reST")
2219
(setq major-mode 'rst-mode)
2220
(run-hooks 'text-mode-hook)
2221
(run-hooks 'rst-mode-hook))
2223
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2226
(defun rst-font-lock-keywords-function ()
2227
"Returns keywords to highlight in rst mode according to current settings."
2228
;; The reST-links in the comments below all relate to sections in
2229
;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
2230
(let* ( ;; This gets big - so let's define some abbreviations
2231
;; horizontal white space
2233
;; beginning of line with possible indentation
2234
(re-bol (concat "^" re-hws "*"))
2235
;; Separates block lead-ins from their content
2236
(re-blksep1 (concat "\\(" re-hws "+\\|$\\)"))
2237
;; explicit markup tag
2239
;; explicit markup start
2240
(re-ems (concat re-emt re-hws "+"))
2241
;; inline markup prefix
2242
(re-imp1 (concat "\\(^\\|" re-hws "\\|[-'\"([{</:]\\)"))
2243
;; inline markup suffix
2244
(re-ims1 (concat "\\(" re-hws "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
2246
(re-sym1 "\\(\\sw\\|\\s_\\)")
2247
;; inline markup content begin
2248
(re-imbeg2 "\\(\\S \\|\\S \\([^")
2250
;; There seems to be a bug leading to error "Stack overflow in regexp
2251
;; matcher" when "|" or "\\*" are the characters searched for
2253
(if (< emacs-major-version 21)
2256
;; inline markup content end
2257
(re-imend (concat re-imendbeg "\\)*[^\t \\\\]\\)"))
2258
;; inline markup content without asterisk
2259
(re-ima2 (concat re-imbeg2 "*" re-imend))
2260
;; inline markup content without backquote
2261
(re-imb2 (concat re-imbeg2 "`" re-imend))
2262
;; inline markup content without vertical bar
2263
(re-imv2 (concat re-imbeg2 "|" re-imend))
2264
;; Supported URI schemes
2265
(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\\)")
2266
;; Line starting with adornment and optional whitespace; complete
2267
;; adornment is in (match-string 1); there must be at least 3
2268
;; characters because otherwise explicit markup start would be
2270
(re-ado2 (concat "^\\(\\(["
2272
(< emacs-major-version 21)
2274
(string-match "XEmacs\\|Lucid" emacs-version)))
2275
"^a-zA-Z0-9 \t\x00-\x1F"
2276
"^[:word:][:space:][:cntrl:]")
2277
"]\\)\\2\\2+\\)" re-hws "*$"))
2280
;; FIXME: Block markup is not recognized in blocks after explicit markup
2283
;; Simple `Body Elements`_
2286
(concat re-bol "\\([-*+]" re-blksep1 "\\)")
2288
;; `Enumerated Lists`_
2290
(concat re-bol "\\((?\\([0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
2293
;; `Definition Lists`_ FIXME: missing
2296
(concat re-bol "\\(:[^:]+:\\)" re-blksep1)
2297
1 rst-external-face)
2300
(concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
2301
"\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
2304
;; `Tables`_ FIXME: missing
2306
;; All the `Explicit Markup Blocks`_
2307
;; `Footnotes`_ / `Citations`_
2309
(concat re-bol "\\(" re-ems "\\[[^[]+\\]\\)" re-blksep1)
2310
1 rst-definition-face)
2311
;; `Directives`_ / `Substitution Definitions`_
2313
(concat re-bol "\\(" re-ems "\\)\\(\\(|[^|]+|[\t ]+\\)?\\)\\("
2314
re-sym1 "+::\\)" re-blksep1)
2315
(list 1 rst-directive-face)
2316
(list 2 rst-definition-face)
2317
(list 4 rst-directive-face))
2318
;; `Hyperlink Targets`_
2320
(concat re-bol "\\(" re-ems "_\\([^:\\`]\\|\\\\.\\|`[^`]+`\\)+:\\)"
2322
1 rst-definition-face)
2324
(concat re-bol "\\(__\\)" re-blksep1)
2325
1 rst-definition-face)
2327
;; All `Inline Markup`_
2328
;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
2329
;; `Strong Emphasis`_
2331
(concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
2332
2 rst-emphasis2-face)
2335
(concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
2336
2 rst-emphasis1-face)
2337
;; `Inline Literals`_
2339
(concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
2341
;; `Inline Internal Targets`_
2343
(concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
2344
2 rst-definition-face)
2345
;; `Hyperlink References`_
2346
;; FIXME: `Embedded URIs`_ not considered
2348
(concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\sw+\\)__?\\)" re-ims1)
2349
2 rst-reference-face)
2350
;; `Interpreted Text`_
2352
(concat re-imp1 "\\(\\(:" re-sym1 "+:\\)?\\)\\(`" re-imb2 "`\\)\\(\\(:"
2353
re-sym1 "+:\\)?\\)" re-ims1)
2354
(list 2 rst-directive-face)
2355
(list 5 rst-external-face)
2356
(list 8 rst-directive-face))
2357
;; `Footnote References`_ / `Citation References`_
2359
(concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
2360
2 rst-reference-face)
2361
;; `Substitution References`_
2363
(concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
2364
2 rst-reference-face)
2365
;; `Standalone Hyperlinks`_
2367
;; FIXME: This takes it easy by using a whitespace as delimiter
2368
(concat re-imp1 "\\(" re-uris1 ":\\S +\\)" re-ims1)
2369
2 rst-definition-face)
2371
(concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
2372
2 rst-definition-face)
2374
;; Do all block fontification as late as possible so 'append works
2376
;; Sections_ / Transitions_
2380
(if (not rst-mode-lazy)
2381
(list 1 rst-block-face)
2383
(list 'rst-font-lock-handle-adornment
2385
(setq rst-font-lock-adornment-point (match-end 1))
2388
(list 1 '(cdr (assoc nil rst-adornment-faces-alist))
2390
(list 2 '(cdr (assoc rst-font-lock-level
2391
rst-adornment-faces-alist))
2393
(list 3 '(cdr (assoc nil rst-adornment-faces-alist))
2399
(concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:]\\|:\\([^:]\\|$\\)\\)*$")
2400
(list 1 rst-comment-face))
2403
(list 'rst-font-lock-find-unindented-line
2405
(setq rst-font-lock-indentation-point (match-end 1))
2408
(list 0 rst-comment-face 'append)))))
2411
(concat re-bol "\\(" re-emt "\\)\\(\\s *\\)\\?$")
2412
(list 1 rst-comment-face)
2413
(list 2 rst-comment-face))
2416
(list 'rst-font-lock-find-unindented-line
2418
(setq rst-font-lock-indentation-point 'next)
2421
(list 0 rst-comment-face 'append)))))
2423
;; `Literal Blocks`_
2426
(concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
2427
(list 3 rst-block-face))
2430
(list 'rst-font-lock-find-unindented-line
2432
(setq rst-font-lock-indentation-point t)
2435
(list 0 rst-literal-face 'append)))))
2438
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2441
(defun rst-forward-indented-block (&optional column limit)
2442
"Move forward across one indented block.
2443
Find the next non-empty line which is not indented at least to COLUMN (defaults
2444
to the column of the point). Moves point to first character of this line or the
2445
first empty line immediately before it and returns that position. If there is
2446
no such line before LIMIT (defaults to the end of the buffer) returns nil and
2447
point is not moved."
2449
(let ((clm (or column (current-column)))
2453
(setq limit (point-max)))
2455
(while (and (not fnd) (< (point) limit))
2457
(when (< (point) limit)
2459
(if (looking-at "\\s *$")
2460
(setq cand (or cand beg)) ; An empty line is a candidate
2461
(move-to-column clm)
2462
;; FIXME: No indentation [(zerop clm)] must be handled in some
2463
;; useful way - though it is not clear what this should mean at all
2465
"^\\s *$" (buffer-substring-no-properties beg (point)))
2466
(setq cand nil) ; An indented line resets a candidate
2467
(setq fnd (or cand beg)))))))
2468
(goto-char (or fnd start))
2471
;; Stores the point where the current indentation ends if a number. If `next'
2472
;; indicates `rst-font-lock-find-unindented-line' shall take the indentation
2473
;; from the next line if this is not empty. If non-nil indicates
2474
;; `rst-font-lock-find-unindented-line' shall take the indentation from the
2475
;; next non-empty line. Also used as a trigger for
2476
;; `rst-font-lock-find-unindented-line'.
2477
(defvar rst-font-lock-indentation-point nil)
2479
(defun rst-font-lock-find-unindented-line (limit)
2480
(let* ((ind-pnt rst-font-lock-indentation-point)
2482
;; May run only once - enforce this
2483
(setq rst-font-lock-indentation-point nil)
2484
(when (and ind-pnt (not (numberp ind-pnt)))
2485
;; Find indentation point in next line if any
2489
(if (eq ind-pnt 'next)
2490
(when (and (zerop (forward-line 1)) (< (point) limit))
2491
(setq beg-pnt (point))
2492
(when (not (looking-at "\\s *$"))
2493
(looking-at "\\s *")
2495
(while (and (zerop (forward-line 1)) (< (point) limit)
2496
(looking-at "\\s *$")))
2497
(when (< (point) limit)
2498
(setq beg-pnt (point))
2499
(looking-at "\\s *")
2503
;; Always succeeds because the limit set by PRE-MATCH-FORM is the
2504
;; ultimate point to find
2505
(goto-char (or (rst-forward-indented-block nil limit) limit))
2506
(set-match-data (list beg-pnt (point)))
2509
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2512
;; Stores the point where the current adornment ends. Also used as a trigger
2513
;; for `rst-font-lock-handle-adornment'.
2514
(defvar rst-font-lock-adornment-point nil)
2516
;; Here `rst-font-lock-handle-adornment' stores the section level of the
2517
;; current adornment or t for a transition.
2518
(defvar rst-font-lock-level nil)
2520
;; FIXME: It would be good if this could be used to markup section titles of
2521
;; given level with a special key; it would be even better to be able to
2522
;; customize this so it can be used for a generally available personal style
2524
;; FIXME: There should be some way to reset and reload this variable - probably
2527
;; FIXME: Some support for `outline-mode' would be nice which should be based
2528
;; on this information
2529
(defvar rst-adornment-level-alist nil
2530
"Associates adornments with section levels.
2531
The key is a two character string. The first character is the adornment
2532
character. The second character distinguishes underline section titles (`u')
2533
from overline/underline section titles (`o'). The value is the section level.
2535
This is made buffer local on start and adornments found during font lock are
2538
;; Returns section level for adornment key KEY. Adds new section level if KEY
2539
;; is not found and ADD. If KEY is not a string it is simply returned.
2540
(defun rst-adornment-level (key &optional add)
2541
(let ((fnd (assoc key rst-adornment-level-alist))
2544
((not (stringp key))
2549
(while (rassoc new rst-adornment-level-alist)
2550
(setq new (1+ new)))
2551
(setq rst-adornment-level-alist
2552
(append rst-adornment-level-alist (list (cons key new))))
2555
;; Classifies adornment for section titles and transitions. ADORNMENT is the
2556
;; complete adornment string as found in the buffer. END is the point after the
2557
;; last character of ADORNMENT. For overline section adornment LIMIT limits the
2558
;; search for the matching underline. Returns a list. The first entry is t for
2559
;; a transition, or a key string for `rst-adornment-level' for a section title.
2560
;; The following eight values forming four match groups as can be used for
2561
;; `set-match-data'. First match group contains the maximum points of the whole
2562
;; construct. Second and last match group matched pure section title adornment
2563
;; while third match group matched the section title text or the transition.
2564
;; Each group but the first may or may not exist.
2565
(defun rst-classify-adornment (adornment end limit)
2569
(let ((ado-ch (aref adornment 0))
2570
(ado-re (regexp-quote adornment))
2577
(or (not (zerop (forward-line 1)))
2578
(looking-at "\\s *$"))))
2581
(or (not (zerop (forward-line -1)))
2582
(looking-at "\\s *$"))))
2583
key beg-ovr end-ovr beg-txt end-txt beg-und end-und)
2585
((and nxt-emp prv-emp)
2588
(setq beg-txt beg-pnt)
2589
(setq end-txt end-pnt))
2592
(setq key (concat (list ado-ch) "o"))
2593
(setq beg-ovr beg-pnt)
2594
(setq end-ovr end-pnt)
2596
(setq beg-txt (point))
2597
(while (and (< (point) limit) (not end-txt))
2598
(if (looking-at "\\s *$")
2599
;; No underline found
2600
(setq end-txt (1- (point)))
2601
(when (looking-at (concat "\\(" ado-re "\\)\\s *$"))
2602
(setq end-und (match-end 1))
2603
(setq beg-und (point))
2604
(setq end-txt (1- beg-und))))
2608
(setq key (concat (list ado-ch) "u"))
2609
(setq beg-und beg-pnt)
2610
(setq end-und end-pnt)
2611
(setq end-txt (1- beg-und))
2612
(setq beg-txt (progn
2613
(if (re-search-backward "^\\s *$" 1 'move)
2617
(or beg-ovr beg-txt beg-und)
2618
(or end-und end-txt end-und)
2619
beg-ovr end-ovr beg-txt end-txt beg-und end-und)))))
2621
;; Handles adornments for font-locking section titles and transitions. Returns
2622
;; three match groups. First and last match group matched pure overline /
2623
;; underline adornment while second group matched section title text. Each
2624
;; group may not exist.
2625
(defun rst-font-lock-handle-adornment (limit)
2626
(let ((ado-pnt rst-font-lock-adornment-point))
2627
;; May run only once - enforce this
2628
(setq rst-font-lock-adornment-point nil)
2630
(let* ((ado (rst-classify-adornment (match-string-no-properties 1)
2634
(setq rst-font-lock-level (rst-adornment-level key t))
2635
(goto-char (nth 1 mtc))
2636
(set-match-data mtc)
2639
;;; rst-mode.el ends here
2643
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2644
;; Support for conversion from within Emacs
2646
(defgroup rst-compile nil
2647
"Settings for support of conversion of reStructuredText
2648
document with \\[rst-compile]."
2652
(defvar rst-compile-toolsets
2653
'((html . ("rst2html.py" ".html" nil))
2654
(latex . ("rst2latex.py" ".tex" nil))
2655
(newlatex . ("rst2newlatex.py" ".tex" nil))
2656
(pseudoxml . ("rst2pseudoxml.py" ".xml" nil))
2657
(xml . ("rst2xml.py" ".xml" nil)))
2658
"An association list of the toolset to a list of the (command to use,
2659
extension of produced filename, options to the tool (nil or a
2660
string)) to be used for converting the document.")
2662
;; Note for Python programmers not familiar with association lists: you can set
2663
;; values in an alists like this, e.g. :
2664
;; (setcdr (assq 'html rst-compile-toolsets)
2665
;; '("rst2html.py" ".htm" "--stylesheet=/docutils.css"))
2668
(defvar rst-compile-primary-toolset 'html
2669
"The default toolset for rst-compile.")
2671
(defvar rst-compile-secondary-toolset 'latex
2672
"The default toolset for rst-compile with a prefix argument.")
2674
(defun rst-compile-find-conf ()
2675
"Look for the configuration file in the parents of the current path."
2677
(let ((file-name "docutils.conf")
2678
(buffer-file (buffer-file-name)))
2679
;; Move up in the dir hierarchy till we find a change log file.
2680
(let ((dir (file-name-directory buffer-file)))
2681
(while (and (or (not (string= "/" dir)) (setq dir nil) nil)
2682
(not (file-exists-p (concat dir file-name))))
2683
;; Move up to the parent dir and try again.
2684
(setq dir (expand-file-name (file-name-directory
2685
(directory-file-name
2686
(file-name-directory dir))))) )
2687
(or (and dir (concat dir file-name)) nil)
2690
(defun rst-compile (&optional pfxarg)
2691
"Compile command to convert reST document into some output file.
2692
Attempts to find configuration file, if it can, overrides the
2695
;; Note: maybe we want to check if there is a Makefile too and not do anything
2696
;; if that is the case. I dunno.
2697
(let* ((toolset (cdr (assq (if pfxarg
2698
rst-compile-secondary-toolset
2699
rst-compile-primary-toolset)
2700
rst-compile-toolsets)))
2701
(command (car toolset))
2702
(extension (cadr toolset))
2703
(options (caddr toolset))
2704
(conffile (rst-compile-find-conf))
2705
(bufname (file-name-nondirectory buffer-file-name))
2706
(outname (file-name-sans-extension bufname)))
2708
;; Set compile-command before invocation of compile.
2709
(set (make-local-variable 'compile-command)
2710
(mapconcat 'identity
2714
(concat "--config=\"" conffile "\"")
2717
(concat outname extension))
2720
;; Invoke the compile command.
2721
(if (or compilation-read-command current-prefix-arg)
2722
(call-interactively 'compile)
2723
(compile compile-command))
2728
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2730
;; Generic text functions that are more convenient than the defaults.
2733
(defun replace-lines (fromchar tochar)
2734
"Replace flush-left lines, consisting of multiple FROMCHAR characters,
2735
with equal-length lines of TOCHAR."
2737
cSearch for flush-left lines of char:
2738
cand replace with char: ")
2740
(let* ((fromstr (string fromchar))
2741
(searchre (concat "^" (regexp-quote fromstr) "+ *$"))
2745
(search-forward-regexp searchre)
2746
(setq found (1+ found))
2747
(search-backward fromstr) ;; point will be *before* last char
2748
(setq p (1+ (point)))
2750
(setq l (- p (point)))
2752
(insert-char tochar l))
2754
(message (format "%d lines replaced." found)))))))
2756
(defun join-paragraph ()
2757
"Join lines in current paragraph into one line, removing end-of-lines."
2759
(let ((fill-column 65000)) ; some big number
2760
(call-interactively 'fill-paragraph)))
2762
;; FIXME: can we remove this?
2763
(defun force-fill-paragraph ()
2764
"Fill paragraph at point, first joining the paragraph's lines into one.
2765
This is useful for filling list item paragraphs."
2768
(fill-paragraph nil))
2771
;; Generic character repeater function.
2772
;; For sections, better to use the specialized function above, but this can
2773
;; be useful for creating separators.
2774
(defun repeat-last-character (&optional tofill)
2775
"Fills the current line up to the length of the preceding line (if not
2776
empty), using the last character on the current line. If the preceding line is
2777
empty, we use the fill-column.
2779
If a prefix argument is provided, use the next line rather than the preceding
2782
If the current line is longer than the desired length, shave the characters off
2783
the current line to fit the desired length.
2785
As an added convenience, if the command is repeated immediately, the alternative
2786
column is used (fill-column vs. end of previous/next line)."
2788
(let* ((curcol (current-column))
2789
(curline (+ (count-lines (point-min) (point))
2790
(if (eq curcol 0) 1 0)))
2791
(lbp (line-beginning-position 0))
2792
(prevcol (if (and (= curline 1) (not current-prefix-arg))
2795
(forward-line (if current-prefix-arg 1 -1))
2797
(skip-chars-backward " \t" lbp)
2798
(let ((cc (current-column)))
2799
(if (= cc 0) fill-column cc)))))
2801
(cond (tofill fill-column)
2802
((equal last-command 'repeat-last-character)
2803
(if (= curcol fill-column) prevcol fill-column))
2805
(if (= prevcol 0) fill-column prevcol)))
2808
(if (> (current-column) rightmost-column)
2809
;; shave characters off the end
2810
(delete-region (- (point)
2811
(- (current-column) rightmost-column))
2813
;; fill with last characters
2814
(insert-char (preceding-char)
2815
(- rightmost-column (current-column))))
2821
;;; rst.el ends here