~ubuntu-branches/ubuntu/karmic/python-docutils/karmic

« back to all changes in this revision

Viewing changes to tools/editors/emacs/rst.el

  • Committer: Bazaar Package Importer
  • Author(s): martin f. krafft
  • Date: 2006-07-10 11:45:05 UTC
  • mfrom: (2.1.4 edgy)
  • Revision ID: james.westby@ubuntu.com-20060710114505-otkhqcslevewxmz5
Tags: 0.4-3
Added build dependency on python-central (closes: #377580).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
;;; ================================================
 
2
;;;   rst.el -- ReStructuredText Support for Emacs
 
3
;;; ================================================
 
4
;;;
 
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.
 
11
;;; :Abstract:
 
12
;;;
 
13
;;;    Support code for editing reStructuredText with Emacs.  The latest version
 
14
;;;    of this file lies in the docutils source code repository.
 
15
;;;
 
16
;;; Description
 
17
;;; ===========
 
18
;;;
 
19
;;; Basically, this package contains:
 
20
;;;
 
21
;;; - Functions to automatically adjust and cycle the section underline
 
22
;;;   decorations;
 
23
;;; - A mode that displays the table of contents and allows you to jump anywhere
 
24
;;;   from it;
 
25
;;; - Functions to insert and automatically update a TOC in your source
 
26
;;;   document;
 
27
;;; - A mode which supports font-lock highlighting of reStructuredText
 
28
;;;   structures;
 
29
;;; - Some other convenience functions.
 
30
;;;
 
31
;;; See the accompanying document in the docutils documentation about
 
32
;;; the contents of this package and how to use it.
 
33
;;;
 
34
;;; For more information about reStructuredText, see
 
35
;;; http://docutils.sourceforge.net/rst.html
 
36
;;;
 
37
;;; For full details on how to use the contents of this file, see
 
38
;;; http://docutils.sourceforge.net/docs/user/emacs.html
 
39
;;;
 
40
;;; Download
 
41
;;; ========
 
42
;;;
 
43
;;; Click `Here <rst.el>`_ for download.
 
44
;;;
 
45
;;; END
 
46
;;
 
47
;; **IMPORTANT NOTE TO PACKAGERS**: this package is the result of merging:
 
48
;;
 
49
;; - restructuredtext.el
 
50
;; - rst-mode.el
 
51
;; - rst-html.el
 
52
;;
 
53
;; Those files are now OBSOLETE and have been replaced by this single package
 
54
;; file (2005-10-30).
 
55
;;
 
56
;; Installation instructions
 
57
;; -------------------------
 
58
;;
 
59
;; Add this line to your .emacs file and bind the versatile sectioning commands
 
60
;; in text mode, like this::
 
61
;;
 
62
;;   (require 'rst)
 
63
;;   (add-hook 'text-mode-hook 'rst-text-mode-bindings)
 
64
;;
 
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).
 
68
;;
 
69
;;
 
70
;;    C-c p a (also C-=): rst-adjust
 
71
;;
 
72
;;       Updates or rotates the section title around point or promotes/demotes
 
73
;;       the decorations within the region (see full details below).
 
74
;;
 
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-=.
 
78
;;
 
79
;;    C-c p h: rst-display-decorations-hierarchy
 
80
;;
 
81
;;       Displays the level decorations that are available in the file.
 
82
;;
 
83
;;    C-c p t: rst-toc
 
84
;;
 
85
;;       Displays the hierarchical table-of-contents of the document and allows
 
86
;;       you to jump to any section from it.
 
87
;;
 
88
;;    C-c p i: rst-toc-insert
 
89
;;
 
90
;;       Inserts a table-of-contents in the document at the column where the
 
91
;;       cursor is.
 
92
;;
 
93
;;    C-c p u: rst-toc-insert-update
 
94
;;
 
95
;;       Find an existing inserted table-of-contents in the document an
 
96
;;       updates it.
 
97
;;
 
98
;;    C-c p p, C-c p n (C-c C-p, C-c C-n): rst-backward-section,
 
99
;;    rst-forward-section
 
100
;;
 
101
;;       Navigate between section titles.
 
102
;;
 
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
 
105
;;
 
106
;;       Shift the region left or right by two-char increments, which is perfect
 
107
;;       for bulleted lists.
 
108
;;
 
109
;;
 
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.
 
113
;;
 
114
;; There are many variables that can be customized, look for defcustom and
 
115
;; defvar in this file.
 
116
;;
 
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::
 
119
;;
 
120
;;   (add-hook 'rst-adjust-hook 'rst-toc-insert-update)
 
121
;;
 
122
;; rst-mode
 
123
;; --------
 
124
;;
 
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'.
 
128
;;
 
129
;; Add the following lines to your `.emacs' file:
 
130
;;
 
131
;; (setq auto-mode-alist
 
132
;;       (append '(("\\.rst$" . rst-mode)
 
133
;;                 ("\\.rest$" . rst-mode)) auto-mode-alist))
 
134
;;
 
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
 
139
;;
 
140
;; .. -*- mode: rst -*-
 
141
;;
 
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.
 
146
;;
 
147
;;
 
148
;; TODO list
 
149
;; =========
 
150
;;
 
151
;; Bindings
 
152
;; --------
 
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
 
155
;;   the Macs.
 
156
;;
 
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
 
164
;;
 
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.
 
168
;;
 
169
;; rst-mode
 
170
;; --------
 
171
;; - Look at the possibility of converting rst-mode from a Major mode to a Minor
 
172
;;   mode of text-mode.
 
173
;;
 
174
;; Other
 
175
;; -----
 
176
;; - We should rename "adornment" to "decoration" or vice-versa in this
 
177
;;   document.
 
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.
 
180
;;
 
181
 
 
182
 
 
183
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
184
;; Bindings and hooks
 
185
 
 
186
(defgroup rst nil "Support for reStructuredText documents"
 
187
  :group 'wp
 
188
  :version "21.1"
 
189
  :link '(url-link "http://docutils.sourceforge.net/rst.html"))
 
190
 
 
191
(defun rst-toc-or-hierarchy ()
 
192
  "Binding for either TOC or decorations hierarchy."
 
193
  (interactive)
 
194
  (if (not current-prefix-arg)
 
195
      (rst-toc)
 
196
    (rst-display-decorations-hierarchy)))
 
197
 
 
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)))
 
214
 
 
215
(defun rst-text-mode-bindings ()
 
216
  "Default text mode hook for rest."
 
217
 
 
218
  ;; Direct command (somehow this one does not work on the Mac).
 
219
  (local-set-key [(control ?=)] 'rst-adjust)
 
220
 
 
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)
 
225
 
 
226
  ;; Bind the rst commands on the C-c p prefix.
 
227
  (define-key mode-specific-map [(p)] rst-prefix-map)
 
228
  )
 
229
 
 
230
 
 
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.
 
235
;;
 
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) ))
 
240
 
 
241
 
 
242
;; Additional abbreviations for text-mode.
 
243
(define-abbrev text-mode-abbrev-table
 
244
  "con" ".. contents::\n..\n   " nil 0)
 
245
 
 
246
 
 
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
 
250
;; like this:
 
251
;;
 
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]*$"
 
258
 
 
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)))
 
265
 
 
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#]+\\. "
 
269
 
 
270
;; FIXME: the variables above are in limbo and need some fixing.
 
271
 
 
272
 
 
273
 
 
274
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
275
;; Support functions
 
276
 
 
277
(require 'cl)
 
278
 
 
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)"
 
284
    (if list
 
285
        (let ((head (car list))
 
286
              (tail (filter pred (cdr list))))
 
287
          (if (funcall pred head)
 
288
              (cons head tail)
 
289
            tail)))))
 
290
 
 
291
 
 
292
;; From emacs-22
 
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)
 
298
      (save-excursion
 
299
        (goto-char (point-min))
 
300
        (setq start (point))
 
301
        (goto-char opoint)
 
302
        (forward-line 0)
 
303
        (1+ (count-lines start (point)))))) )
 
304
 
 
305
 
 
306
 
 
307
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
308
;; Section Decoration Adjusment
 
309
;; ============================
 
310
;;
 
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.
 
316
;;
 
317
;; Definitions: the two forms of sectioning define semantically separate section
 
318
;; levels.  A sectioning DECORATION consists in:
 
319
;;
 
320
;;   - a CHARACTER
 
321
;;
 
322
;;   - a STYLE which can be either of 'simple' or 'over-and-under'.
 
323
;;
 
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.
 
327
;;
 
328
;; Important note: an existing decoration must be formed by at least two
 
329
;; characters to be recognized.
 
330
;;
 
331
;; Here are two examples of decorations (| represents the window border, column
 
332
;; 0):
 
333
;;
 
334
;;                                  |
 
335
;; 1. char: '-'   e                 |Some Title
 
336
;;    style: simple                 |----------
 
337
;;                                  |
 
338
;; 2. char: '='                     |==============
 
339
;;    style: over-and-under         |  Some Title
 
340
;;    indent: 2                     |==============
 
341
;;                                  |
 
342
;;
 
343
;; Some notes:
 
344
;;
 
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.
 
349
;;
 
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
 
355
;;   the file.
 
356
;;
 
357
;; - A prefix argument can be used to alternate the style.
 
358
;;
 
359
;; - An underline/overline that is not extended to the column at which it should
 
360
;;   be hanging is dubbed INCOMPLETE.  For example::
 
361
;;
 
362
;;      |Some Title
 
363
;;      |-------
 
364
;;
 
365
;; Examples of default invocation:
 
366
;;
 
367
;;   |Some Title       --->    |Some Title
 
368
;;   |                         |----------
 
369
;;
 
370
;;   |Some Title       --->    |Some Title
 
371
;;   |-----                    |----------
 
372
;;
 
373
;;   |                         |------------
 
374
;;   | Some Title      --->    | Some Title
 
375
;;   |                         |------------
 
376
;;
 
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).
 
383
 
 
384
(defgroup rst-adjust nil
 
385
  "Settings for adjustment and cycling of section title
 
386
decorations."
 
387
  :group 'rst
 
388
  :version "21.1")
 
389
 
 
390
(defcustom rst-preferred-decorations '( (?= over-and-under 1)
 
391
                                         (?= simple 0)
 
392
                                         (?- simple 0)
 
393
                                         (?~ simple 0)
 
394
                                         (?+ simple 0)
 
395
                                         (?` simple 0)
 
396
                                         (?# simple 0)
 
397
                                         (?@ simple 0) )
 
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
 
402
  the file."
 
403
  :group 'rst-adjust)
 
404
 
 
405
 
 
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."
 
410
  :group 'rst-adjust)
 
411
 
 
412
 
 
413
(defvar rst-section-text-regexp "^[ \t]*\\S-*[a-zA-Z0-9]\\S-*"
 
414
  "Regular expression for valid section title text.")
 
415
 
 
416
 
 
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.
 
422
 
 
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."
 
427
  (save-excursion
 
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))
 
432
                 (or accept-special
 
433
                     (and
 
434
                      ;; Common patterns.
 
435
                      (not (looking-at "::[ \t]*$"))
 
436
                      (not (looking-at "\\.\\.\\.[ \t]*$"))
 
437
                      ;; Discard one char line
 
438
                      (not (looking-at ".[ \t]*$"))
 
439
                      )))
 
440
            (string-to-char c))
 
441
        ))
 
442
    ))
 
443
 
 
444
(defun rst-line-homogeneous-nodent-p (&optional accept-special)
 
445
  (save-excursion
 
446
    (beginning-of-line)
 
447
    (if (looking-at "^[ \t]+")
 
448
        nil
 
449
      (rst-line-homogeneous-p accept-special)
 
450
      )))
 
451
 
 
452
 
 
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))))
 
459
 
 
460
 
 
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
 
465
not found."
 
466
  (let ((cur hier))
 
467
    (while (and cur (not (rst-compare-decorations (car cur) deco)))
 
468
      (setq cur (cdr cur)))
 
469
    cur))
 
470
 
 
471
 
 
472
(defun rst-suggest-new-decoration (alldecos &optional prev)
 
473
  "Suggest a new, different decoration, different from all that
 
474
have been seen.
 
475
 
 
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."
 
479
 
 
480
  ;; For all the preferred decorations...
 
481
  (let* (
 
482
         ;; If 'prev' is given, reorder the list to start searching after the
 
483
         ;; match.
 
484
         (fplist
 
485
          (cdr (rst-get-decoration-match rst-preferred-decorations prev)))
 
486
 
 
487
         ;; List of candidates to search.
 
488
         (curpotential (append fplist rst-preferred-decorations)))
 
489
    (while
 
490
        ;; For all the decorations...
 
491
        (let ((cur alldecos)
 
492
              found)
 
493
          (while (and cur (not found))
 
494
            (if (rst-compare-decorations (car cur) (car curpotential))
 
495
                ;; Found it!
 
496
                (setq found (car curpotential))
 
497
              (setq cur (cdr cur))))
 
498
          found)
 
499
 
 
500
      (setq curpotential (cdr curpotential)))
 
501
 
 
502
    (copy-list (car curpotential)) ))
 
503
 
 
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))
 
507
                                                (point-max))))
 
508
 
 
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).
 
515
 
 
516
  If there are existing overline and/or underline from the
 
517
  existing decoration, they are removed before adding the
 
518
  requested decoration."
 
519
 
 
520
  (interactive)
 
521
  (let (marker
 
522
        len
 
523
        ec
 
524
        (c ?-))
 
525
 
 
526
      (end-of-line)
 
527
      (setq marker (point-marker))
 
528
 
 
529
      ;; Fixup whitespace at the beginning and end of the line
 
530
      (if (or (null indent) (eq style 'simple))
 
531
          (setq indent 0))
 
532
      (beginning-of-line)
 
533
      (delete-horizontal-space)
 
534
      (insert (make-string indent ? ))
 
535
 
 
536
      (end-of-line)
 
537
      (delete-horizontal-space)
 
538
 
 
539
      ;; Set the current column, we're at the end of the title line
 
540
      (setq len (+ (current-column) indent))
 
541
 
 
542
      ;; Remove previous line if it consists only of a single repeated character
 
543
      (save-excursion
 
544
        (forward-line -1)
 
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)))
 
549
             (rst-delete-line)))
 
550
 
 
551
      ;; Remove following line if it consists only of a single repeated
 
552
      ;; character
 
553
      (save-excursion
 
554
        (forward-line +1)
 
555
        (and (rst-line-homogeneous-p 1)
 
556
             (rst-delete-line))
 
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))
 
560
            (newline 1)))
 
561
 
 
562
      ;; Insert overline
 
563
      (if (eq style 'over-and-under)
 
564
          (save-excursion
 
565
            (beginning-of-line)
 
566
            (open-line 1)
 
567
            (insert (make-string len char))))
 
568
 
 
569
      ;; Insert underline
 
570
      (forward-line +1)
 
571
      (open-line 1)
 
572
      (insert (make-string len char))
 
573
 
 
574
      (forward-line +1)
 
575
      (goto-char marker)
 
576
      ))
 
577
 
 
578
 
 
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
 
583
  under a line."
 
584
  (if (save-excursion (beginning-of-line)
 
585
                      (or (rst-line-homogeneous-p 1)
 
586
                          (looking-at "^[ \t]*$")))
 
587
      (progn
 
588
        (beginning-of-line)
 
589
        (cond
 
590
         ((save-excursion (forward-line -1)
 
591
                          (beginning-of-line)
 
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)
 
596
                          (beginning-of-line)
 
597
                          (and (looking-at rst-section-text-regexp)
 
598
                               (not (rst-line-homogeneous-p 1))))
 
599
          (progn (forward-line +1) +1))
 
600
         (t 0)))
 
601
    0 ))
 
602
 
 
603
 
 
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.
 
608
 
 
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."
 
612
 
 
613
  (let (positions
 
614
        (curline 1))
 
615
    ;; Iterate over all the section titles/decorations in the file.
 
616
    (save-excursion
 
617
      (beginning-of-buffer)
 
618
      (while (< (point) (buffer-end 1))
 
619
        (if (rst-line-homogeneous-nodent-p)
 
620
            (progn
 
621
              (setq curline (+ curline (rst-normalize-cursor-position)))
 
622
 
 
623
              ;; Here we have found a potential site for a decoration,
 
624
              ;; characterize it.
 
625
              (let ((deco (rst-get-decoration)))
 
626
                (if (cadr deco) ;; Style is existing.
 
627
                    ;; Found a real decoration site.
 
628
                    (progn
 
629
                      (push (cons curline deco) positions)
 
630
                      ;; Push beyond the underline.
 
631
                      (forward-line 1)
 
632
                      (setq curline (+ curline 1))
 
633
                      )))
 
634
              ))
 
635
        (forward-line 1)
 
636
        (setq curline (+ curline 1))
 
637
        ))
 
638
    (reverse positions)))
 
639
 
 
640
 
 
641
(defun rst-infer-hierarchy (decorations)
 
642
  "Build a hierarchy of decorations using the list of given decorations.
 
643
 
 
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.
 
649
 
 
650
  Similarly returns a list of (char, style, indent), where each
 
651
  list element should be unique."
 
652
 
 
653
  (let ((hierarchy-alist (list)))
 
654
    (dolist (x decorations)
 
655
      (let ((char (car x))
 
656
            (style (cadr x))
 
657
            (indent (caddr x)))
 
658
        (unless (assoc (cons char style) hierarchy-alist)
 
659
          (setq hierarchy-alist
 
660
                (append hierarchy-alist
 
661
                        (list (cons (cons char style) x)))) )
 
662
        ))
 
663
    (mapcar 'cdr hierarchy-alist)
 
664
    ))
 
665
 
 
666
 
 
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.
 
670
 
 
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))))
 
677
 
 
678
 
 
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
 
683
  underline).
 
684
 
 
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.
 
689
 
 
690
  A point can be specified to go to the given location before
 
691
  extracting the decoration."
 
692
 
 
693
  (let (char style indent)
 
694
    (save-excursion
 
695
      (if point (goto-char point))
 
696
      (beginning-of-line)
 
697
      (if (looking-at rst-section-text-regexp)
 
698
          (let* ((over (save-excursion
 
699
                         (forward-line -1)
 
700
                         (rst-line-homogeneous-nodent-p)))
 
701
 
 
702
                (under (save-excursion
 
703
                         (forward-line +1)
 
704
                         (rst-line-homogeneous-nodent-p)))
 
705
                )
 
706
 
 
707
            ;; Check that the line above the overline is not part of a title
 
708
            ;; above it.
 
709
            (if (and over
 
710
                     (save-excursion
 
711
                       (and (equal (forward-line -2) 0)
 
712
                            (looking-at rst-section-text-regexp))))
 
713
                (setq over nil))
 
714
 
 
715
            (cond
 
716
             ;; No decoration found, leave all return values nil.
 
717
             ((and (eq over nil) (eq under nil)))
 
718
 
 
719
             ;; Overline only, leave all return values nil.
 
720
             ;;
 
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)))
 
724
 
 
725
             ;; Underline only.
 
726
             ((and under (eq over nil))
 
727
              (setq char under
 
728
                    style 'simple))
 
729
 
 
730
             ;; Both overline and underline.
 
731
             (t
 
732
              (setq char under
 
733
                    style 'over-and-under))
 
734
             )
 
735
            )
 
736
        )
 
737
      ;; Find indentation.
 
738
      (setq indent (save-excursion (back-to-indentation) (current-column)))
 
739
      )
 
740
    ;; Return values.
 
741
    (list char style indent)))
 
742
 
 
743
 
 
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))
 
750
         prev next
 
751
         (cur all))
 
752
 
 
753
    ;; Search for the decorations around the current line.
 
754
    (while (and cur (< (caar cur) curline))
 
755
      (setq prev cur
 
756
            cur (cdr cur)))
 
757
    ;; 'cur' is the following decoration.
 
758
 
 
759
    (if (and cur (caar cur))
 
760
        (setq next (if (= curline (caar cur)) (cdr cur) cur)))
 
761
 
 
762
    (mapcar 'cdar (list prev next))
 
763
    ))
 
764
 
 
765
 
 
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.
 
771
 
 
772
  ;; There is some sectioning already present, so check if the current
 
773
  ;; sectioning is complete and correct.
 
774
  (let* ((char (car deco))
 
775
         (style (cadr deco))
 
776
         (indent (caddr deco))
 
777
         (endcol (save-excursion (end-of-line) (current-column)))
 
778
         )
 
779
    (if char
 
780
        (let ((exps (concat "^"
 
781
                            (regexp-quote (make-string (+ endcol indent) char))
 
782
                            "$")))
 
783
          (and
 
784
           (save-excursion (forward-line +1)
 
785
                           (beginning-of-line)
 
786
                           (looking-at exps))
 
787
           (or (not (eq style 'over-and-under))
 
788
               (save-excursion (forward-line -1)
 
789
                               (beginning-of-line)
 
790
                               (looking-at exps))))
 
791
          ))
 
792
    ))
 
793
 
 
794
 
 
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."
 
799
 
 
800
  (let* (
 
801
         (char (car curdeco))
 
802
         (style (cadr curdeco))
 
803
 
 
804
         ;; Build a new list of decorations for the rotation.
 
805
         (rotdecos
 
806
          (append hier
 
807
                  ;; Suggest a new decoration.
 
808
                  (list suggestion
 
809
                        ;; If nothing to suggest, use first decoration.
 
810
                        (car hier)))) )
 
811
    (or
 
812
     ;; Search for next decoration.
 
813
     (cadr
 
814
      (let ((cur (if reverse-direction rotdecos
 
815
                   (reverse rotdecos)))
 
816
            found)
 
817
        (while (and cur
 
818
                    (not (and (eq char (caar cur))
 
819
                              (eq style (cadar cur)))))
 
820
          (setq cur (cdr cur)))
 
821
        cur))
 
822
 
 
823
     ;; If not found, take the first of all decorations.
 
824
     suggestion
 
825
     )))
 
826
 
 
827
 
 
828
(defun rst-adjust ()
 
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).
 
835
 
 
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
 
841
cases.
 
842
 
 
843
See the documentations of rst-adjust-decoration and
 
844
rst-promote-region for full details.
 
845
 
 
846
Prefix Arguments
 
847
================
 
848
 
 
849
The method can take either (but not both) of
 
850
 
 
851
a. a (non-negative) prefix argument, which means to toggle the
 
852
   decoration style.  Invoke with C-u prefix for example;
 
853
 
 
854
b. a negative numerical argument, which generally inverts the
 
855
   direction of search in the file or hierarchy.  Invoke with C--
 
856
   prefix for example.
 
857
 
 
858
"
 
859
  (interactive)
 
860
 
 
861
  (let* ( ;; Parse the positive and negative prefix arguments.
 
862
         (reverse-direction
 
863
          (and current-prefix-arg
 
864
               (< (prefix-numeric-value current-prefix-arg) 0)))
 
865
         (toggle-style
 
866
          (and current-prefix-arg (not reverse-direction))))
 
867
 
 
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))
 
873
 
 
874
    ;; Run the hooks to run after adjusting.
 
875
    (run-hooks 'rst-adjust-hook)
 
876
 
 
877
    ))
 
878
 
 
879
(defvar rst-adjust-hook nil
 
880
  "Hooks to be run after running rst-adjust.")
 
881
 
 
882
(defun rst-adjust-decoration (&optional toggle-style reverse-direction)
 
883
"Adjust/rotate the section decoration for the section title around point.
 
884
 
 
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.
 
888
 
 
889
General Behaviour
 
890
=================
 
891
 
 
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:
 
895
 
 
896
- adding a decoration if the title does not have one;
 
897
 
 
898
- adjusting the length of the underline characters to fit a
 
899
  modified title;
 
900
 
 
901
- rotating the decoration in the set of already existing
 
902
  sectioning decorations used in the file;
 
903
 
 
904
- switching between simple and over-and-under styles.
 
905
 
 
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
 
908
would expect.
 
909
 
 
910
 
 
911
Decoration Definitions
 
912
======================
 
913
 
 
914
The decorations consist in
 
915
 
 
916
1. a CHARACTER
 
917
 
 
918
2. a STYLE which can be either of 'simple' or 'over-and-under'.
 
919
 
 
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
 
923
   ending.
 
924
 
 
925
See source code for mode details.
 
926
 
 
927
 
 
928
Detailed Behaviour Description
 
929
==============================
 
930
 
 
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):
 
934
 
 
935
Before applying the decoration change, the cursor is placed on
 
936
the closest line that could contain a section title.
 
937
 
 
938
Case 1: No Decoration
 
939
---------------------
 
940
 
 
941
If the current line has no decoration around it,
 
942
 
 
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.
 
947
 
 
948
  If REVERSE-DIRECTION is true, we simply use the previous
 
949
  decoration found directly.
 
950
 
 
951
- if there is no decoration found in the given direction, we use
 
952
  the first of rst-preferred-decorations.
 
953
 
 
954
The prefix argument forces a toggle of the prescribed decoration
 
955
style.
 
956
 
 
957
Case 2: Incomplete Decoration
 
958
-----------------------------
 
959
 
 
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.
 
965
 
 
966
If the prefix argument is given, we toggle the style of the
 
967
decoration as well.
 
968
 
 
969
REVERSE-DIRECTION has no effect in this case.
 
970
 
 
971
Case 3: Complete Existing Decoration
 
972
------------------------------------
 
973
 
 
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.
 
983
 
 
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
 
991
 
 
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.
 
995
 
 
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).
 
1000
 
 
1001
 
 
1002
Point Location
 
1003
==============
 
1004
 
 
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.
 
1009
 
 
1010
 
 
1011
Indented Sections
 
1012
=================
 
1013
 
 
1014
Indented section titles such as ::
 
1015
 
 
1016
   My Title
 
1017
   --------
 
1018
 
 
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).
 
1022
 
 
1023
 
 
1024
Joint Sections
 
1025
==============
 
1026
 
 
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.
 
1031
 
 
1032
For now we assume that the decorations are disjoint, that is,
 
1033
there is at least a single line between the titles/decoration
 
1034
lines.
 
1035
 
 
1036
 
 
1037
Suggested Binding
 
1038
=================
 
1039
 
 
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."
 
1043
  (interactive)
 
1044
 
 
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))
 
1051
 
 
1052
            toggle-style
 
1053
            (and current-prefix-arg (not reverse-direction))))
 
1054
 
 
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))
 
1058
 
 
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))
 
1064
 
 
1065
         ;; New values to be computed.
 
1066
         char-new style-new indent-new
 
1067
         )
 
1068
 
 
1069
    ;; We've moved the cursor... if we're not looking at some text, we have
 
1070
    ;; nothing to do.
 
1071
    (if (save-excursion (beginning-of-line)
 
1072
                        (looking-at rst-section-text-regexp))
 
1073
        (progn
 
1074
          (cond
 
1075
           ;;-------------------------------------------------------------------
 
1076
           ;; Case 1: No Decoration
 
1077
           ((and (eq char nil) (eq style nil))
 
1078
 
 
1079
            (let* ((alldecos (rst-find-all-decorations))
 
1080
 
 
1081
                   (around (rst-get-decorations-around alldecos))
 
1082
                   (prev (car around))
 
1083
                   cur
 
1084
 
 
1085
                   (hier (rst-get-hierarchy alldecos))
 
1086
                   )
 
1087
 
 
1088
              ;; Advance one level down.
 
1089
              (setq cur
 
1090
                    (if prev
 
1091
                        (if (not reverse-direction)
 
1092
                            (or (cadr (rst-get-decoration-match hier prev))
 
1093
                                (rst-suggest-new-decoration hier prev))
 
1094
                          prev)
 
1095
                      (copy-list (car rst-preferred-decorations))
 
1096
                      ))
 
1097
 
 
1098
              ;; Invert the style if requested.
 
1099
              (if toggle-style
 
1100
                  (setcar (cdr cur) (if (eq (cadr cur) 'simple)
 
1101
                                        'over-and-under 'simple)) )
 
1102
 
 
1103
              (setq char-new (car cur)
 
1104
                    style-new (cadr cur)
 
1105
                    indent-new (caddr cur))
 
1106
              ))
 
1107
 
 
1108
           ;;-------------------------------------------------------------------
 
1109
           ;; Case 2: Incomplete Decoration
 
1110
           ((not (rst-decoration-complete-p curdeco))
 
1111
 
 
1112
            ;; Invert the style if requested.
 
1113
            (if toggle-style
 
1114
                (setq style (if (eq style 'simple) 'over-and-under 'simple)))
 
1115
 
 
1116
            (setq char-new char
 
1117
                  style-new style
 
1118
                  indent-new indent))
 
1119
 
 
1120
           ;;-------------------------------------------------------------------
 
1121
           ;; Case 3: Complete Existing Decoration
 
1122
           (t
 
1123
            (if toggle-style
 
1124
 
 
1125
                ;; Simply switch the style of the current decoration.
 
1126
                (setq char-new char
 
1127
                      style-new (if (eq style 'simple) 'over-and-under 'simple)
 
1128
                      indent-new rst-default-indent)
 
1129
 
 
1130
              ;; Else, we rotate, ignoring the decoration around the current
 
1131
              ;; line...
 
1132
              (let* ((alldecos (rst-find-all-decorations))
 
1133
 
 
1134
                     (hier (rst-get-hierarchy alldecos (line-number-at-pos)))
 
1135
 
 
1136
                     ;; Suggestion, in case we need to come up with something
 
1137
                     ;; new
 
1138
                     (suggestion (rst-suggest-new-decoration
 
1139
                                  hier
 
1140
                                  (car (rst-get-decorations-around alldecos))))
 
1141
 
 
1142
                     (nextdeco (rst-get-next-decoration
 
1143
                                curdeco hier suggestion reverse-direction))
 
1144
 
 
1145
                     )
 
1146
 
 
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))
 
1151
 
 
1152
                )))
 
1153
           )
 
1154
 
 
1155
          ;; Override indent with present indent!
 
1156
          (setq indent-new (if (> indent 0) indent indent-new))
 
1157
 
 
1158
          (if (and char-new style-new)
 
1159
              (rst-update-section char-new style-new indent-new))
 
1160
          ))
 
1161
 
 
1162
 
 
1163
    ;; Correct the position of the cursor to more accurately reflect where it
 
1164
    ;; was located when the function was invoked.
 
1165
    (unless (= moved 0)
 
1166
      (forward-line (- moved))
 
1167
      (end-of-line))
 
1168
 
 
1169
    ))
 
1170
 
 
1171
;; Maintain an alias for compatibility.
 
1172
(defalias 'rst-adjust-section-title 'rst-adjust)
 
1173
 
 
1174
 
 
1175
(defun rst-promote-region (&optional demote)
 
1176
  "Promote the section titles within the region.
 
1177
 
 
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."
 
1181
  (interactive)
 
1182
 
 
1183
  (let* ((demote (or current-prefix-arg demote))
 
1184
         (alldecos (rst-find-all-decorations))
 
1185
         (cur alldecos)
 
1186
 
 
1187
         (hier (rst-get-hierarchy alldecos))
 
1188
         (suggestion (rst-suggest-new-decoration hier))
 
1189
 
 
1190
         (region-begin-line (line-number-at-pos (region-beginning)))
 
1191
         (region-end-line (line-number-at-pos (region-end)))
 
1192
 
 
1193
         marker-list
 
1194
         )
 
1195
 
 
1196
    ;; Skip the markers that come before the region beginning
 
1197
    (while (and cur (< (caar cur) region-begin-line))
 
1198
      (setq cur (cdr cur)))
 
1199
 
 
1200
    ;; Create a list of markers for all the decorations which are found within
 
1201
    ;; the region.
 
1202
    (save-excursion
 
1203
      (let (m line)
 
1204
        (while (and cur (< (setq line (caar cur)) region-end-line))
 
1205
          (setq m (make-marker))
 
1206
          (goto-line line)
 
1207
          (push (list (set-marker m (point)) (cdar cur)) marker-list)
 
1208
          (setq cur (cdr cur)) ))
 
1209
 
 
1210
      ;; Apply modifications.
 
1211
      (let (nextdeco)
 
1212
        (dolist (p marker-list)
 
1213
          ;; Go to the decoration to promote.
 
1214
          (goto-char (car p))
 
1215
 
 
1216
          ;; Rotate the next decoration.
 
1217
          (setq nextdeco (rst-get-next-decoration
 
1218
                          (cadr p) hier suggestion demote))
 
1219
 
 
1220
          ;; Update the decoration.
 
1221
          (apply 'rst-update-section nextdeco)
 
1222
 
 
1223
          ;; Clear marker to avoid slowing down the editing after we're done.
 
1224
          (set-marker (car p) nil)
 
1225
          ))
 
1226
      (setq deactivate-mark nil)
 
1227
    )))
 
1228
 
 
1229
 
 
1230
 
 
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."
 
1234
  (interactive)
 
1235
 
 
1236
  (if (not decorations)
 
1237
      (setq decorations (rst-get-hierarchy)))
 
1238
  (with-output-to-temp-buffer "*rest section hierarchy*"
 
1239
    (let ((level 1))
 
1240
      (with-current-buffer standard-output
 
1241
        (dolist (x decorations)
 
1242
          (insert (format "\nSection Level %d" level))
 
1243
          (apply 'rst-update-section x)
 
1244
          (end-of-buffer)
 
1245
          (insert "\n")
 
1246
          (incf level)
 
1247
          ))
 
1248
    )))
 
1249
 
 
1250
 
 
1251
(defun rst-rstrip (str)
 
1252
  "Strips the whitespace at the end of a string."
 
1253
  (let ((tmp))
 
1254
    (string-match "[ \t\n]*\\'" str)
 
1255
    (substring str 0 (match-beginning 0))
 
1256
    ))
 
1257
 
 
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)
 
1262
                                  (match-end 0)) )
 
1263
 
 
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
 
1269
one).
 
1270
 
 
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.
 
1273
 
 
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."
 
1280
 
 
1281
  (let* (thelist
 
1282
         (hier (rst-get-hierarchy alldecos))
 
1283
         (levels (make-hash-table :test 'equal :size 10))
 
1284
         lines)
 
1285
 
 
1286
    (let ((lev 0))
 
1287
      (dolist (deco hier)
 
1288
        ;; Compare just the character and indent in the hash table.
 
1289
        (puthash (cons (car deco) (cadr deco)) lev levels)
 
1290
        (incf lev)))
 
1291
 
 
1292
    ;; Create a list of lines that contains (text, level, marker) for each
 
1293
    ;; decoration.
 
1294
    (save-excursion
 
1295
      (setq lines
 
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)))
 
1303
                            ))
 
1304
                    alldecos)))
 
1305
 
 
1306
    (let ((lcontnr (cons nil lines)))
 
1307
      (rst-section-tree-rec lcontnr -1))))
 
1308
 
 
1309
 
 
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
 
1316
  destructively."
 
1317
 
 
1318
  (let ((ndeco (cadr decos))
 
1319
        node
 
1320
        children)
 
1321
 
 
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.
 
1328
 
 
1329
    ;; Build the child nodes
 
1330
    (while (and (cdr decos) (> (caadr decos) lev))
 
1331
      (setq children
 
1332
            (cons (rst-section-tree-rec decos (1+ lev))
 
1333
                  children)))
 
1334
    (setq children (reverse children))
 
1335
 
 
1336
    ;; If node is still unset, we use the marker of the first child.
 
1337
    (when (eq node nil)
 
1338
      (setq node (cons nil (cdaar children))))
 
1339
 
 
1340
    ;; Return this node with its children.
 
1341
    (cons node children)
 
1342
    ))
 
1343
 
 
1344
 
 
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
 
1349
  lives.
 
1350
 
 
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."
 
1354
 
 
1355
  (let (path outtree)
 
1356
 
 
1357
    (let* ((curpoint (or point (point))))
 
1358
 
 
1359
      ;; Check if we are before the current node.
 
1360
      (if (and (cadar node) (>= curpoint (cadar node)))
 
1361
 
 
1362
          ;; Iterate all the children, looking for one that might contain the
 
1363
          ;; current section.
 
1364
          (let ((curnode (cdr node))
 
1365
                last)
 
1366
 
 
1367
            (while (and curnode (>= curpoint (cadaar curnode)))
 
1368
              (setq last curnode
 
1369
                    curnode (cdr curnode)))
 
1370
 
 
1371
            (if last
 
1372
                (let ((sub (rst-section-tree-point (car last) curpoint)))
 
1373
                  (setq path (car sub)
 
1374
                        outtree (cdr sub)))
 
1375
              (setq outtree node))
 
1376
 
 
1377
            )))
 
1378
    (cons (cons (car node) path) outtree)
 
1379
    ))
 
1380
 
 
1381
 
 
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.
 
1386
 
 
1387
If a numeric prefix argument is given, insert the TOC up to the
 
1388
specified level.
 
1389
 
 
1390
The TOC is inserted indented at the current column."
 
1391
 
 
1392
  (interactive "P")
 
1393
 
 
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))
 
1398
 
 
1399
         ;; Get the section tree for the current cursor point.
 
1400
         (sectree-pair
 
1401
          (rst-section-tree-point
 
1402
           (rst-section-tree (rst-find-all-decorations))))
 
1403
 
 
1404
         ;; Figure out initial indent.
 
1405
         (initial-indent (make-string (current-column) ? ))
 
1406
         (init-point (point)))
 
1407
 
 
1408
    (when (cddr sectree-pair)
 
1409
      (rst-toc-insert-node (cdr sectree-pair) 0 initial-indent "")
 
1410
 
 
1411
      ;; Fixup for the first line.
 
1412
      (delete-region init-point (+ init-point (length initial-indent)))
 
1413
 
 
1414
      ;; Delete the last newline added.
 
1415
      (delete-backward-char 1)
 
1416
    )))
 
1417
 
 
1418
 
 
1419
(defgroup rst-toc nil
 
1420
  "Settings for reStructuredText table of contents."
 
1421
  :group 'rst
 
1422
  :version "21.1")
 
1423
 
 
1424
(defcustom rst-toc-indent 2
 
1425
  "Indentation for table-of-contents display (also used for
 
1426
  formatting insertion, when numbering is disabled)."
 
1427
  :group 'rst-toc)
 
1428
 
 
1429
(defcustom rst-toc-insert-style 'fixed
 
1430
  "Set this to one of the following values to determine numbering and
 
1431
indentation style:
 
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)
 
1436
"
 
1437
  :group 'rst-toc)
 
1438
 
 
1439
(defcustom rst-toc-insert-number-separator "  "
 
1440
  "Separator that goes between the TOC number and the title."
 
1441
  :group 'rst-toc)
 
1442
 
 
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)
 
1447
       map)
 
1448
  "(Internal) What happens when you click on propertized text in the TOC.")
 
1449
 
 
1450
(defcustom rst-toc-insert-max-level nil
 
1451
  "If non-nil, maximum depth of the inserted TOC."
 
1452
  :group 'rst-toc)
 
1453
 
 
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."
 
1458
 
 
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))
 
1462
        (count 1)
 
1463
        b)
 
1464
    (when do-print
 
1465
      (insert indent)
 
1466
      (let ((b (point)))
 
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)
 
1477
 
 
1478
        )
 
1479
      (insert "\n")
 
1480
 
 
1481
      ;; Prepare indent for children.
 
1482
      (setq indent
 
1483
            (cond
 
1484
             ((eq rst-toc-insert-style 'plain)
 
1485
              (concat indent rst-toc-indent))
 
1486
 
 
1487
             ((eq rst-toc-insert-style 'fixed)
 
1488
              (concat indent (make-string rst-toc-indent ? )))
 
1489
 
 
1490
             ((eq rst-toc-insert-style 'aligned)
 
1491
              (concat indent (make-string (+ (length pfx) 2) ? )))
 
1492
 
 
1493
             ((eq rst-toc-insert-style 'listed)
 
1494
              (concat (substring indent 0 -3)
 
1495
                      (concat (make-string (+ (length pfx) 2) ? ) " - ")))
 
1496
             ))
 
1497
      )
 
1498
 
 
1499
    (if (or (eq rst-toc-insert-max-level nil)
 
1500
            (< level rst-toc-insert-max-level))
 
1501
        (let ((do-child-numbering (>= level 0))
 
1502
              fmt)
 
1503
          (if do-child-numbering
 
1504
              (progn
 
1505
                ;; Add a separating dot if there is already a prefix
 
1506
                (if (> (length pfx) 0)
 
1507
                    (setq pfx (concat (rst-rstrip pfx) ".")))
 
1508
 
 
1509
                ;; Calculate the amount of space that the prefix will require
 
1510
                ;; for the numbers.
 
1511
                (if (cdr node)
 
1512
                    (setq fmt (format "%%-%dd"
 
1513
                                      (1+ (floor (log10 (length
 
1514
                                                         (cdr node))))))))
 
1515
                ))
 
1516
 
 
1517
          (dolist (child (cdr node))
 
1518
            (rst-toc-insert-node child
 
1519
                                 (1+ level)
 
1520
                                 indent
 
1521
                                 (if do-child-numbering
 
1522
                                     (concat pfx (format fmt count)) pfx))
 
1523
            (incf count)))
 
1524
 
 
1525
      )))
 
1526
 
 
1527
 
 
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).
 
1536
  ;;
 
1537
  ;;   .. contents:: [...anything here...]
 
1538
  ;;   ..
 
1539
  ;;      XXXXXXXX
 
1540
  ;;      XXXXXXXX
 
1541
  ;;      [more lines]
 
1542
  ;;
 
1543
  (let ((beg
 
1544
         (re-search-forward "^\\.\\. contents[ \t]*::\\(.*\\)\n\\.\\."
 
1545
                            nil t))
 
1546
        last-real)
 
1547
    (when beg
 
1548
      ;; Look for the first line that starts at the first column.
 
1549
      (forward-line 1)
 
1550
      (beginning-of-line)
 
1551
      (while (and
 
1552
              (< (point) (point-max))
 
1553
              (or (and (looking-at "[ \t]+[^ \t]") (setq last-real (point)) t)
 
1554
                  (looking-at "\\s-*$")))
 
1555
        (forward-line 1)
 
1556
        )
 
1557
      (if last-real
 
1558
          (progn
 
1559
            (goto-char last-real)
 
1560
            (end-of-line)
 
1561
            (delete-region beg (point)))
 
1562
        (goto-char beg))
 
1563
      t
 
1564
      )))
 
1565
 
 
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."
 
1570
  (interactive)
 
1571
  (save-excursion
 
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.
 
1576
  )
 
1577
 
 
1578
 
 
1579
;;------------------------------------------------------------------------------
 
1580
 
 
1581
(defun rst-toc-node (node level)
 
1582
  "Recursive function that does the print of the TOC in rst-toc-mode."
 
1583
 
 
1584
  (if (> level 0)
 
1585
      (let ((b (point)))
 
1586
        ;; Insert line text.
 
1587
        (insert (make-string (* rst-toc-indent (1- level)) ? ))
 
1588
        (insert (or (caar node) "[missing node]"))
 
1589
 
 
1590
        ;; Highlight lines.
 
1591
        (put-text-property b (point) 'mouse-face 'highlight)
 
1592
 
 
1593
        ;; Add link on lines.
 
1594
        (put-text-property b (point) 'rst-toc-target (cadar node))
 
1595
 
 
1596
        (insert "\n")
 
1597
        ))
 
1598
 
 
1599
  (dolist (child (cdr node))
 
1600
    (rst-toc-node child (1+ level))))
 
1601
 
 
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."
 
1607
 
 
1608
  (let ((count 1)
 
1609
        found)
 
1610
    (if (eq node target-node)
 
1611
        (setq found t)
 
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))
 
1616
                  found (cdr cl)
 
1617
                  child (cdr child))))))
 
1618
    (cons count found)))
 
1619
 
 
1620
 
 
1621
(defun rst-toc ()
 
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
 
1625
  document.
 
1626
 
 
1627
  The emacs buffer can be navigated, and selecting a section
 
1628
  brings the cursor in that section."
 
1629
  (interactive)
 
1630
  (let* ((curbuf (current-buffer))
 
1631
 
 
1632
         ;; Get the section tree
 
1633
         (alldecos (rst-find-all-decorations))
 
1634
         (sectree (rst-section-tree alldecos))
 
1635
 
 
1636
         (our-node (cdr (rst-section-tree-point sectree)))
 
1637
         line
 
1638
 
 
1639
         ;; Create a temporary buffer.
 
1640
         (buf (get-buffer-create rst-toc-buffer-name))
 
1641
         )
 
1642
 
 
1643
    (with-current-buffer buf
 
1644
      (let ((inhibit-read-only t))
 
1645
        (rst-toc-mode)
 
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)
 
1651
 
 
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)))
 
1655
        ))
 
1656
    (display-buffer buf)
 
1657
    (pop-to-buffer buf)
 
1658
 
 
1659
    ;; Save the buffer to return to.
 
1660
    (set (make-local-variable 'rst-toc-return-buffer) curbuf)
 
1661
 
 
1662
    ;; Move the cursor near the right section in the TOC.
 
1663
    (goto-line line)
 
1664
    ))
 
1665
 
 
1666
 
 
1667
(defun rst-toc-mode-find-section ()
 
1668
  (let ((pos (get-text-property (point) 'rst-toc-target)))
 
1669
    (unless pos
 
1670
      (error "No section on this line"))
 
1671
    (unless (buffer-live-p (marker-buffer pos))
 
1672
      (error "Buffer for this section was killed"))
 
1673
    pos))
 
1674
 
 
1675
(defvar rst-toc-buffer-name "*Table of Contents*"
 
1676
  "Name of the Table of Contents buffer.")
 
1677
 
 
1678
(defun rst-toc-mode-goto-section ()
 
1679
  "Go to the section the current line describes."
 
1680
  (interactive)
 
1681
  (let ((pos (rst-toc-mode-find-section)))
 
1682
    (kill-buffer (get-buffer rst-toc-buffer-name))
 
1683
    (pop-to-buffer (marker-buffer pos))
 
1684
    (goto-char pos)
 
1685
    (recenter 5)))
 
1686
 
 
1687
(defun rst-toc-mode-mouse-goto (event)
 
1688
  "In Rst-Toc mode, go to the occurrence whose line you click on."
 
1689
  (interactive "e")
 
1690
  (let (pos)
 
1691
    (save-excursion
 
1692
      (set-buffer (window-buffer (posn-window (event-end event))))
 
1693
      (save-excursion
 
1694
        (goto-char (posn-point (event-end event)))
 
1695
        (setq pos (rst-toc-mode-find-section))))
 
1696
    (pop-to-buffer (marker-buffer pos))
 
1697
    (goto-char pos)))
 
1698
 
 
1699
(defun rst-toc-mode-mouse-goto-kill (event)
 
1700
  (interactive "e")
 
1701
  (call-interactively 'rst-toc-mode-mouse-goto event)
 
1702
  (kill-buffer (get-buffer rst-toc-buffer-name)))
 
1703
 
 
1704
(defvar rst-toc-return-buffer nil
 
1705
  "Buffer local variable that is used to return to the original
 
1706
  buffer from the TOC.")
 
1707
 
 
1708
(defun rst-toc-quit-window ()
 
1709
  (interactive)
 
1710
  (quit-window)
 
1711
  (pop-to-buffer rst-toc-return-buffer))
 
1712
 
 
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)
 
1721
    map)
 
1722
  "Keymap for `rst-toc-mode'.")
 
1723
 
 
1724
(put 'rst-toc-mode 'mode-class 'special)
 
1725
 
 
1726
(defun rst-toc-mode ()
 
1727
  "Major mode for output from \\[rst-toc]."
 
1728
  (interactive)
 
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)
 
1734
  )
 
1735
 
 
1736
;; Note: use occur-mode (replace.el) as a good example to complete missing
 
1737
;; features.
 
1738
 
 
1739
 
 
1740
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
1741
;;
 
1742
;; Section movement commands.
 
1743
;;
 
1744
 
 
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)."
 
1749
  (interactive)
 
1750
  (let* (;; Default value for offset.
 
1751
         (offset (or offset 1))
 
1752
 
 
1753
         ;; Get all the decorations in the file, with their line numbers.
 
1754
         (alldecos (rst-find-all-decorations))
 
1755
 
 
1756
         ;; Get the current line.
 
1757
         (curline (line-number-at-pos))
 
1758
 
 
1759
         (cur alldecos)
 
1760
         (idx 0)
 
1761
         line
 
1762
         )
 
1763
 
 
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))
 
1767
      (incf idx))
 
1768
    ;; 'cur' is the decoration on or following the current line.
 
1769
 
 
1770
    (if (and (> offset 0) cur (= (caar cur) curline))
 
1771
        (incf idx))
 
1772
 
 
1773
    ;; Find the final index.
 
1774
    (setq idx (+ idx (if (> offset 0) (- offset 1) offset)))
 
1775
    (setq cur (nth idx alldecos))
 
1776
 
 
1777
    ;; If the index is positive, goto the line, otherwise go to the buffer
 
1778
    ;; boundaries.
 
1779
    (if (and cur (>= idx 0))
 
1780
        (goto-line (car cur))
 
1781
      (if (> offset 0) (end-of-buffer) (beginning-of-buffer)))
 
1782
    ))
 
1783
 
 
1784
(defun rst-backward-section ()
 
1785
  "Like rst-forward-section, except move back one title."
 
1786
  (interactive)
 
1787
  (rst-forward-section -1))
 
1788
 
 
1789
 
 
1790
 
 
1791
 
 
1792
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
1793
;; Functions to indent/dedent item lists, which are always two-characters apart
 
1794
;; horizontally with rest.
 
1795
 
 
1796
(defvar rst-shift-fill-region nil
 
1797
  "Set to true if you want to automatically re-fill the region that is being
 
1798
shifted.")
 
1799
;; FIXME: need to finish this feature properly.
 
1800
 
 
1801
 
 
1802
(defun rst-shift-region-right ()
 
1803
  "Indent region ridigly, by two characters to the right."
 
1804
  (interactive)
 
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))
 
1810
    ))
 
1811
 
 
1812
(defun rst-find-leftmost-column (beg end)
 
1813
  "Finds the leftmost column in the region."
 
1814
  (let ((mincol 1000))
 
1815
    (save-excursion
 
1816
      (goto-char beg)
 
1817
      (while (< (point) end)
 
1818
        (back-to-indentation)
 
1819
        (unless (looking-at "[ \t]*$")
 
1820
          (setq mincol (min mincol (current-column))))
 
1821
        (forward-line 1)
 
1822
        ))
 
1823
    mincol))
 
1824
 
 
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."
 
1829
  (interactive "P")
 
1830
  (let ((chars
 
1831
         (if pfxarg
 
1832
             (- (rst-find-leftmost-column (region-beginning) (region-end)))
 
1833
           -2))
 
1834
        (mbeg (set-marker (make-marker) (region-beginning)))
 
1835
        (mend (set-marker (make-marker) (region-end)))
 
1836
        )
 
1837
    (indent-rigidly mbeg mend chars)
 
1838
    (when rst-shift-fill-region
 
1839
      (fill-region mbeg mend))
 
1840
    ))
 
1841
 
 
1842
 
 
1843
 
 
1844
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
1845
;;; rst-mode.el --- Mode for viewing and editing reStructuredText-documents.
 
1846
;;
 
1847
;; Copyright 2003 Stefan Merten <smerten@oekonux.de>
 
1848
;;
 
1849
;; Note: this is an update from version 0.2.9 of rst-mode.el
 
1850
;;
 
1851
;; DESCRIPTION
 
1852
;;
 
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
 
1856
;; mode.
 
1857
;;
 
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.
 
1860
;;
 
1861
;; OPTIONS
 
1862
;;
 
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
 
1865
;; mode.
 
1866
;;
 
1867
;; Customization
 
1868
;; =============
 
1869
;;
 
1870
;; rst
 
1871
;; ---
 
1872
;; This group contains some general customizable features.
 
1873
;;
 
1874
;; The group is contained in the wp group.
 
1875
;;
 
1876
;; rst-faces
 
1877
;; ---------
 
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.
 
1881
;;
 
1882
;; The group is contained in the faces group as well as in the rst group.
 
1883
;;
 
1884
;; rst-faces-defaults
 
1885
;; ------------------
 
1886
;; This group contains all necessary for customizing the default fonts used for
 
1887
;; section title faces.
 
1888
;;
 
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.
 
1896
;;
 
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.
 
1900
;;
 
1901
;; The group is contained in the rst-faces group.
 
1902
;;
 
1903
;; All customizable features have a comment explaining their meaning. Refer to
 
1904
;; the customization of your Emacs (try ``M-x customize``).
 
1905
 
 
1906
;; SEE ALSO
 
1907
;;
 
1908
;; http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html
 
1909
 
 
1910
;; AUTHOR
 
1911
;;
 
1912
;; Stefan Merten <smerten AT oekonux.de>
 
1913
 
 
1914
;; LICENSE
 
1915
;;
 
1916
;; This program is licensed under the terms of the GPL. See
 
1917
;;
 
1918
;;   http://www.gnu.org/licenses/gpl.txt
 
1919
 
 
1920
;; AVAILABILITY
 
1921
;;
 
1922
;; See
 
1923
;;
 
1924
;;   http://www.merten-home.de/FreeSoftware/rst-mode/
 
1925
 
 
1926
 
 
1927
;;; Code:
 
1928
 
 
1929
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
1930
;;; Customization:
 
1931
 
 
1932
(defcustom rst-mode-hook nil
 
1933
  "Hook run when Rst Mode is turned on. The hook for Text Mode is run before
 
1934
  this one."
 
1935
  :group 'rst
 
1936
  :type '(hook))
 
1937
 
 
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.
 
1942
 
 
1943
If nil comments and literal blocks are font-locked only on the line they start.
 
1944
 
 
1945
The value of this variable is used when Rst Mode is turned on."
 
1946
  :group 'rst
 
1947
  :type '(boolean))
 
1948
 
 
1949
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
1950
 
 
1951
(defgroup rst-faces nil "Faces used in Rst Mode"
 
1952
  :group 'rst
 
1953
  :group 'faces
 
1954
  :version "21.1")
 
1955
 
 
1956
(defcustom rst-block-face 'font-lock-keyword-face
 
1957
  "All syntax marking up a special block"
 
1958
  :group 'rst-faces
 
1959
  :type '(face))
 
1960
 
 
1961
(defcustom rst-external-face 'font-lock-type-face
 
1962
  "Field names and interpreted text"
 
1963
  :group 'rst-faces
 
1964
  :type '(face))
 
1965
 
 
1966
(defcustom rst-definition-face 'font-lock-function-name-face
 
1967
  "All other defining constructs"
 
1968
  :group 'rst-faces
 
1969
  :type '(face))
 
1970
 
 
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"
 
1977
  :group 'rst-faces
 
1978
  :type '(face))
 
1979
 
 
1980
(defcustom rst-comment-face 'font-lock-comment-face
 
1981
  "Comments"
 
1982
  :group 'rst-faces
 
1983
  :type '(face))
 
1984
 
 
1985
(defcustom rst-emphasis1-face
 
1986
  ;; XEmacs compatibility
 
1987
  (if (facep 'italic)
 
1988
      ''italic
 
1989
    'italic)
 
1990
  "Simple emphasis"
 
1991
  :group 'rst-faces
 
1992
  :type '(face))
 
1993
 
 
1994
(defcustom rst-emphasis2-face
 
1995
  ;; XEmacs compatibility
 
1996
  (if (facep 'bold)
 
1997
      ''bold
 
1998
    'bold)
 
1999
  "Double emphasis"
 
2000
  :group 'rst-faces
 
2001
  :type '(face))
 
2002
 
 
2003
(defcustom rst-literal-face 'font-lock-string-face
 
2004
  "Literal text"
 
2005
  :group 'rst-faces
 
2006
  :type '(face))
 
2007
 
 
2008
(defcustom rst-reference-face 'font-lock-variable-name-face
 
2009
  "References to a definition"
 
2010
  :group 'rst-faces
 
2011
  :type '(face))
 
2012
 
 
2013
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2014
 
 
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."
 
2019
  :group 'rst-faces
 
2020
  :version "21.1")
 
2021
 
 
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'
 
2025
  (let ((i 1))
 
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)
 
2036
        (set sym sym)
 
2037
        (setq i (1+ i))))))
 
2038
 
 
2039
(defun rst-set-level-default (sym val)
 
2040
  "Set a customized value affecting section title text face and recompute the
 
2041
faces."
 
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)))
 
2050
 
 
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
 
2053
;; used for level 1
 
2054
(defcustom rst-level-face-max 6
 
2055
  "Maximum depth of levels for which section title faces are defined."
 
2056
  :group 'rst-faces-defaults
 
2057
  :type '(integer)
 
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
 
2063
  :type '(string)
 
2064
  :set 'rst-set-level-default)
 
2065
(defcustom rst-level-face-base-light
 
2066
  (if (eq frame-background-mode 'dark)
 
2067
      15
 
2068
    85)
 
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
 
2071
not."
 
2072
  :group 'rst-faces-defaults
 
2073
  :type '(integer)
 
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
 
2079
  :type '(string)
 
2080
  :set 'rst-set-level-default)
 
2081
(defcustom rst-level-face-step-light
 
2082
  (if (eq frame-background-mode 'dark)
 
2083
      7
 
2084
    -7)
 
2085
  "The step width to use for the next color. The formula
 
2086
 
 
2087
    `rst-level-face-base-light'
 
2088
    + (`rst-level-face-max' - 1) * `rst-level-face-step-light'
 
2089
 
 
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
 
2095
  :type '(integer)
 
2096
  :set 'rst-set-level-default)
 
2097
 
 
2098
(defcustom rst-adornment-faces-alist
 
2099
  (let ((alist '((t . font-lock-keyword-face)
 
2100
                 (nil . font-lock-keyword-face)))
 
2101
        (i 1))
 
2102
    (while (<= i rst-level-face-max)
 
2103
      (nconc alist (list (cons i (intern (format "rst-level-%d-face" i)))))
 
2104
      (setq i (1+ i)))
 
2105
    alist)
 
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."
 
2111
  :group 'rst-faces
 
2112
  :type '(alist
 
2113
          :key-type
 
2114
          (choice
 
2115
           (integer
 
2116
            :tag
 
2117
            "Section level (may not be bigger than `rst-level-face-max')")
 
2118
           (boolean :tag "transitions (on) / section title adornment (off)"))
 
2119
          :value-type (face))
 
2120
  :set-after '(rst-level-face-max))
 
2121
 
 
2122
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2123
 
 
2124
;; FIXME: Code from `restructuredtext.el' should be integrated
 
2125
 
 
2126
(defvar rst-mode-syntax-table nil
 
2127
  "Syntax table used while in rst mode.")
 
2128
 
 
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)
 
2145
  )
 
2146
 
 
2147
(defvar rst-mode-abbrev-table nil
 
2148
 "Abbrev table used while in rst mode.")
 
2149
(define-abbrev-table 'rst-mode-abbrev-table ())
 
2150
 
 
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.")
 
2156
 
 
2157
(unless rst-mode-map
 
2158
  (setq rst-mode-map (copy-keymap text-mode-map)))
 
2159
 
 
2160
(defun rst-mode ()
 
2161
  "Major mode for editing reStructuredText documents.
 
2162
 
 
2163
You may customize `rst-mode-lazy' to switch font-locking of blocks.
 
2164
 
 
2165
\\{rst-mode-map}
 
2166
Turning on `rst-mode' calls the normal hooks `text-mode-hook' and
 
2167
`rst-mode-hook'."
 
2168
  (interactive)
 
2169
  (kill-all-local-variables)
 
2170
 
 
2171
  ;; Maps and tables
 
2172
  (use-local-map rst-mode-map)
 
2173
  (setq local-abbrev-table rst-mode-abbrev-table)
 
2174
  (set-syntax-table rst-mode-syntax-table)
 
2175
 
 
2176
  ;; For editing text
 
2177
  ;;
 
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) ".. ")
 
2189
 
 
2190
  ;; Special variables
 
2191
  (make-local-variable 'rst-adornment-level-alist)
 
2192
 
 
2193
  ;; Font lock
 
2194
  (set (make-local-variable 'font-lock-defaults)
 
2195
       '(rst-font-lock-keywords-function
 
2196
         t nil nil nil
 
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)
 
2202
    (cond
 
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)))))
 
2216
 
 
2217
  ;; Names and hooks
 
2218
  (setq mode-name "reST")
 
2219
  (setq major-mode 'rst-mode)
 
2220
  (run-hooks 'text-mode-hook)
 
2221
  (run-hooks 'rst-mode-hook))
 
2222
 
 
2223
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2224
;; Font lock
 
2225
 
 
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
 
2232
         (re-hws "[\t ]")
 
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
 
2238
         (re-emt "\\.\\.")
 
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 "\\|[]-'\")}>/:.,;!?\\]\\|$\\)"))
 
2245
         ;; symbol character
 
2246
         (re-sym1 "\\(\\sw\\|\\s_\\)")
 
2247
         ;; inline markup content begin
 
2248
         (re-imbeg2 "\\(\\S \\|\\S \\([^")
 
2249
 
 
2250
         ;; There seems to be a bug leading to error "Stack overflow in regexp
 
2251
         ;; matcher" when "|" or "\\*" are the characters searched for
 
2252
         (re-imendbeg
 
2253
          (if (< emacs-major-version 21)
 
2254
              "]"
 
2255
            "\\]\\|\\\\."))
 
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
 
2269
         ;; recognized
 
2270
         (re-ado2 (concat "^\\(\\(["
 
2271
                          (if (or
 
2272
                               (< emacs-major-version 21)
 
2273
                               (save-match-data
 
2274
                                 (string-match "XEmacs\\|Lucid" emacs-version)))
 
2275
                              "^a-zA-Z0-9 \t\x00-\x1F"
 
2276
                            "^[:word:][:space:][:cntrl:]")
 
2277
                          "]\\)\\2\\2+\\)" re-hws "*$"))
 
2278
         )
 
2279
    (list
 
2280
     ;; FIXME: Block markup is not recognized in blocks after explicit markup
 
2281
     ;; start
 
2282
 
 
2283
     ;; Simple `Body Elements`_
 
2284
     ;; `Bullet Lists`_
 
2285
     (list
 
2286
      (concat re-bol "\\([-*+]" re-blksep1 "\\)")
 
2287
      1 rst-block-face)
 
2288
     ;; `Enumerated Lists`_
 
2289
     (list
 
2290
      (concat re-bol "\\((?\\([0-9]+\\|[A-Za-z]\\|[IVXLCMivxlcm]+\\)[.)]"
 
2291
              re-blksep1 "\\)")
 
2292
      1 rst-block-face)
 
2293
     ;; `Definition Lists`_ FIXME: missing
 
2294
     ;; `Field Lists`_
 
2295
     (list
 
2296
      (concat re-bol "\\(:[^:]+:\\)" re-blksep1)
 
2297
      1 rst-external-face)
 
2298
     ;; `Option Lists`_
 
2299
     (list
 
2300
      (concat re-bol "\\(\\(\\(\\([-+/]\\|--\\)\\sw\\(-\\|\\sw\\)*"
 
2301
              "\\([ =]\\S +\\)?\\)\\(,[\t ]\\)?\\)+\\)\\($\\|[\t ]\\{2\\}\\)")
 
2302
      1 rst-block-face)
 
2303
 
 
2304
     ;; `Tables`_ FIXME: missing
 
2305
 
 
2306
     ;; All the `Explicit Markup Blocks`_
 
2307
     ;; `Footnotes`_ / `Citations`_
 
2308
     (list
 
2309
      (concat re-bol "\\(" re-ems "\\[[^[]+\\]\\)" re-blksep1)
 
2310
      1 rst-definition-face)
 
2311
     ;; `Directives`_ / `Substitution Definitions`_
 
2312
     (list
 
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`_
 
2319
     (list
 
2320
      (concat re-bol "\\(" re-ems "_\\([^:\\`]\\|\\\\.\\|`[^`]+`\\)+:\\)"
 
2321
              re-blksep1)
 
2322
      1 rst-definition-face)
 
2323
     (list
 
2324
      (concat re-bol "\\(__\\)" re-blksep1)
 
2325
      1 rst-definition-face)
 
2326
 
 
2327
     ;; All `Inline Markup`_
 
2328
     ;; FIXME: Condition 5 preventing fontification of e.g. "*" not implemented
 
2329
     ;; `Strong Emphasis`_
 
2330
     (list
 
2331
      (concat re-imp1 "\\(\\*\\*" re-ima2 "\\*\\*\\)" re-ims1)
 
2332
      2 rst-emphasis2-face)
 
2333
     ;; `Emphasis`_
 
2334
     (list
 
2335
      (concat re-imp1 "\\(\\*" re-ima2 "\\*\\)" re-ims1)
 
2336
      2 rst-emphasis1-face)
 
2337
     ;; `Inline Literals`_
 
2338
     (list
 
2339
      (concat re-imp1 "\\(``" re-imb2 "``\\)" re-ims1)
 
2340
      2 rst-literal-face)
 
2341
     ;; `Inline Internal Targets`_
 
2342
     (list
 
2343
      (concat re-imp1 "\\(_`" re-imb2 "`\\)" re-ims1)
 
2344
      2 rst-definition-face)
 
2345
     ;; `Hyperlink References`_
 
2346
     ;; FIXME: `Embedded URIs`_ not considered
 
2347
     (list
 
2348
      (concat re-imp1 "\\(\\(`" re-imb2 "`\\|\\sw+\\)__?\\)" re-ims1)
 
2349
      2 rst-reference-face)
 
2350
     ;; `Interpreted Text`_
 
2351
     (list
 
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`_
 
2358
     (list
 
2359
      (concat re-imp1 "\\(\\[[^]]+\\]_\\)" re-ims1)
 
2360
      2 rst-reference-face)
 
2361
     ;; `Substitution References`_
 
2362
     (list
 
2363
      (concat re-imp1 "\\(|" re-imv2 "|\\)" re-ims1)
 
2364
      2 rst-reference-face)
 
2365
     ;; `Standalone Hyperlinks`_
 
2366
     (list
 
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)
 
2370
     (list
 
2371
      (concat re-imp1 "\\(" re-sym1 "+@" re-sym1 "+\\)" re-ims1)
 
2372
      2 rst-definition-face)
 
2373
 
 
2374
     ;; Do all block fontification as late as possible so 'append works
 
2375
 
 
2376
     ;; Sections_ / Transitions_
 
2377
     (append
 
2378
      (list
 
2379
       re-ado2)
 
2380
      (if (not rst-mode-lazy)
 
2381
          (list 1 rst-block-face)
 
2382
        (list
 
2383
         (list 'rst-font-lock-handle-adornment
 
2384
               '(progn
 
2385
                  (setq rst-font-lock-adornment-point (match-end 1))
 
2386
                  (point-max))
 
2387
               nil
 
2388
               (list 1 '(cdr (assoc nil rst-adornment-faces-alist))
 
2389
                     'append t)
 
2390
               (list 2 '(cdr (assoc rst-font-lock-level
 
2391
                                    rst-adornment-faces-alist))
 
2392
                     'append t)
 
2393
               (list 3 '(cdr (assoc nil rst-adornment-faces-alist))
 
2394
                     'append t)))))
 
2395
 
 
2396
     ;; `Comments`_
 
2397
     (append
 
2398
      (list
 
2399
       (concat re-bol "\\(" re-ems "\\)\[^[|_]\\([^:]\\|:\\([^:]\\|$\\)\\)*$")
 
2400
       (list 1 rst-comment-face))
 
2401
      (if rst-mode-lazy
 
2402
          (list
 
2403
           (list 'rst-font-lock-find-unindented-line
 
2404
                 '(progn
 
2405
                    (setq rst-font-lock-indentation-point (match-end 1))
 
2406
                    (point-max))
 
2407
                 nil
 
2408
                 (list 0 rst-comment-face 'append)))))
 
2409
     (append
 
2410
      (list
 
2411
       (concat re-bol "\\(" re-emt "\\)\\(\\s *\\)\\?$")
 
2412
       (list 1 rst-comment-face)
 
2413
       (list 2 rst-comment-face))
 
2414
      (if rst-mode-lazy
 
2415
          (list
 
2416
           (list 'rst-font-lock-find-unindented-line
 
2417
                 '(progn
 
2418
                    (setq rst-font-lock-indentation-point 'next)
 
2419
                    (point-max))
 
2420
                 nil
 
2421
                 (list 0 rst-comment-face 'append)))))
 
2422
 
 
2423
     ;; `Literal Blocks`_
 
2424
     (append
 
2425
      (list
 
2426
       (concat re-bol "\\(\\([^.\n]\\|\\.[^.\n]\\).*\\)?\\(::\\)$")
 
2427
       (list 3 rst-block-face))
 
2428
      (if rst-mode-lazy
 
2429
          (list
 
2430
           (list 'rst-font-lock-find-unindented-line
 
2431
                 '(progn
 
2432
                    (setq rst-font-lock-indentation-point t)
 
2433
                    (point-max))
 
2434
                 nil
 
2435
                 (list 0 rst-literal-face 'append)))))
 
2436
     )))
 
2437
 
 
2438
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2439
;; Indented blocks
 
2440
 
 
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."
 
2448
  (interactive)
 
2449
  (let ((clm (or column (current-column)))
 
2450
        (start (point))
 
2451
        fnd beg cand)
 
2452
    (if (not limit)
 
2453
        (setq limit (point-max)))
 
2454
    (save-match-data
 
2455
      (while (and (not fnd) (< (point) limit))
 
2456
        (forward-line 1)
 
2457
        (when (< (point) limit)
 
2458
          (setq beg (point))
 
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
 
2464
            (if (string-match
 
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))
 
2469
    fnd))
 
2470
 
 
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)
 
2478
 
 
2479
(defun rst-font-lock-find-unindented-line (limit)
 
2480
  (let* ((ind-pnt rst-font-lock-indentation-point)
 
2481
         (beg-pnt ind-pnt))
 
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
 
2486
      (setq ind-pnt
 
2487
            (save-excursion
 
2488
              (save-match-data
 
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 *")
 
2494
                        (match-end 0)))
 
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 *")
 
2500
                    (match-end 0)))))))
 
2501
    (when ind-pnt
 
2502
      (goto-char ind-pnt)
 
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)))
 
2507
      t)))
 
2508
 
 
2509
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2510
;; Adornments
 
2511
 
 
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)
 
2515
 
 
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)
 
2519
 
 
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
 
2523
;;
 
2524
;; FIXME: There should be some way to reset and reload this variable - probably
 
2525
;; a special key
 
2526
;;
 
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.
 
2534
 
 
2535
This is made buffer local on start and adornments found during font lock are
 
2536
entered.")
 
2537
 
 
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))
 
2542
        (new 1))
 
2543
    (cond
 
2544
     ((not (stringp key))
 
2545
      key)
 
2546
     (fnd
 
2547
      (cdr fnd))
 
2548
     (add
 
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))))
 
2553
      new))))
 
2554
 
 
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)
 
2566
  (save-excursion
 
2567
    (save-match-data
 
2568
      (goto-char end)
 
2569
      (let ((ado-ch (aref adornment 0))
 
2570
            (ado-re (regexp-quote adornment))
 
2571
            (end-pnt (point))
 
2572
            (beg-pnt (progn
 
2573
                       (forward-line 0)
 
2574
                       (point)))
 
2575
            (nxt-emp
 
2576
             (save-excursion
 
2577
               (or (not (zerop (forward-line 1)))
 
2578
                   (looking-at "\\s *$"))))
 
2579
            (prv-emp
 
2580
             (save-excursion
 
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)
 
2584
        (cond
 
2585
         ((and nxt-emp prv-emp)
 
2586
          ;; A transition
 
2587
          (setq key t)
 
2588
          (setq beg-txt beg-pnt)
 
2589
          (setq end-txt end-pnt))
 
2590
         (prv-emp
 
2591
          ;; An overline
 
2592
          (setq key (concat (list ado-ch) "o"))
 
2593
          (setq beg-ovr beg-pnt)
 
2594
          (setq end-ovr end-pnt)
 
2595
          (forward-line 1)
 
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))))
 
2605
            (forward-line 1)))
 
2606
         (t
 
2607
          ;; An underline
 
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)
 
2614
                              (forward-line 1))
 
2615
                          (point)))))
 
2616
        (list key
 
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)))))
 
2620
 
 
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)
 
2629
    (if ado-pnt
 
2630
      (let* ((ado (rst-classify-adornment (match-string-no-properties 1)
 
2631
                                          ado-pnt limit))
 
2632
             (key (car ado))
 
2633
             (mtc (cdr ado)))
 
2634
        (setq rst-font-lock-level (rst-adornment-level key t))
 
2635
        (goto-char (nth 1 mtc))
 
2636
        (set-match-data mtc)
 
2637
        t))))
 
2638
 
 
2639
;;; rst-mode.el ends here
 
2640
 
 
2641
 
 
2642
 
 
2643
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2644
;; Support for conversion from within Emacs
 
2645
 
 
2646
(defgroup rst-compile nil
 
2647
  "Settings for support of conversion of reStructuredText
 
2648
document with \\[rst-compile]."
 
2649
  :group 'rst
 
2650
  :version "21.1")
 
2651
 
 
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.")
 
2661
 
 
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"))
 
2666
 
 
2667
 
 
2668
(defvar rst-compile-primary-toolset 'html
 
2669
  "The default toolset for rst-compile.")
 
2670
 
 
2671
(defvar rst-compile-secondary-toolset 'latex
 
2672
  "The default toolset for rst-compile with a prefix argument.")
 
2673
 
 
2674
(defun rst-compile-find-conf ()
 
2675
  "Look for the configuration file in the parents of the current path."
 
2676
  (interactive)
 
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)
 
2688
    )))
 
2689
 
 
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
 
2693
options."
 
2694
  (interactive "P")
 
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)))
 
2707
 
 
2708
    ;; Set compile-command before invocation of compile.
 
2709
    (set (make-local-variable 'compile-command)
 
2710
         (mapconcat 'identity
 
2711
                    (list command
 
2712
                          (or options "")
 
2713
                          (if conffile
 
2714
                              (concat "--config=\"" conffile "\"")
 
2715
                            "")
 
2716
                          bufname
 
2717
                          (concat outname extension))
 
2718
                    " "))
 
2719
 
 
2720
    ;; Invoke the compile command.
 
2721
    (if (or compilation-read-command current-prefix-arg)
 
2722
        (call-interactively 'compile)
 
2723
      (compile compile-command))
 
2724
    ))
 
2725
 
 
2726
 
 
2727
 
 
2728
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
2729
;;
 
2730
;; Generic text functions that are more convenient than the defaults.
 
2731
;;
 
2732
 
 
2733
(defun replace-lines (fromchar tochar)
 
2734
  "Replace flush-left lines, consisting of multiple FROMCHAR characters,
 
2735
with equal-length lines of TOCHAR."
 
2736
  (interactive "\
 
2737
cSearch for flush-left lines of char:
 
2738
cand replace with char: ")
 
2739
  (save-excursion
 
2740
    (let* ((fromstr (string fromchar))
 
2741
           (searchre (concat "^" (regexp-quote fromstr) "+ *$"))
 
2742
           (found 0))
 
2743
      (condition-case err
 
2744
          (while t
 
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)))
 
2749
            (beginning-of-line)
 
2750
            (setq l (- p (point)))
 
2751
            (rst-delete-line)
 
2752
            (insert-char tochar l))
 
2753
        (search-failed
 
2754
         (message (format "%d lines replaced." found)))))))
 
2755
 
 
2756
(defun join-paragraph ()
 
2757
  "Join lines in current paragraph into one line, removing end-of-lines."
 
2758
  (interactive)
 
2759
  (let ((fill-column 65000)) ; some big number
 
2760
    (call-interactively 'fill-paragraph)))
 
2761
 
 
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."
 
2766
  (interactive)
 
2767
  (join-paragraph)
 
2768
  (fill-paragraph nil))
 
2769
 
 
2770
 
 
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.
 
2778
 
 
2779
If a prefix argument is provided, use the next line rather than the preceding
 
2780
line.
 
2781
 
 
2782
If the current line is longer than the desired length, shave the characters off
 
2783
the current line to fit the desired length.
 
2784
 
 
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)."
 
2787
  (interactive)
 
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))
 
2793
                      fill-column
 
2794
                    (save-excursion
 
2795
                      (forward-line (if current-prefix-arg 1 -1))
 
2796
                      (end-of-line)
 
2797
                      (skip-chars-backward " \t" lbp)
 
2798
                      (let ((cc (current-column)))
 
2799
                        (if (= cc 0) fill-column cc)))))
 
2800
         (rightmost-column
 
2801
          (cond (tofill fill-column)
 
2802
                ((equal last-command 'repeat-last-character)
 
2803
                 (if (= curcol fill-column) prevcol fill-column))
 
2804
                (t (save-excursion
 
2805
                     (if (= prevcol 0) fill-column prevcol)))
 
2806
                )) )
 
2807
    (end-of-line)
 
2808
    (if (> (current-column) rightmost-column)
 
2809
        ;; shave characters off the end
 
2810
        (delete-region (- (point)
 
2811
                          (- (current-column) rightmost-column))
 
2812
                       (point))
 
2813
      ;; fill with last characters
 
2814
      (insert-char (preceding-char)
 
2815
                   (- rightmost-column (current-column))))
 
2816
    ))
 
2817
 
 
2818
 
 
2819
 
 
2820
(provide 'rst)
 
2821
;;; rst.el ends here