Initial Commit
[packages] / xemacs-packages / xemacs-base / outline.el
1 ;;; outline.el --- outline mode commands for Emacs
2
3 ;; ----------------------------------------------------------------------
4 ;; This is a port of GNU Emacs outline.el to XEmacs.  The port was
5 ;; done by Greg Chernov and is temporarily made available on the Org-mode
6 ;; homepage http://www.astro.uva.nl/~dominik/Tools/org/, and as part
7 ;; of the Org-mode distribution.
8 ;; ----------------------------------------------------------------------
9
10 ;; Copyright (C) 1986, 1993, 1994, 1995, 1997, 2000, 2001, 2002,
11 ;;   2003, 2004, 2005 Free Software Foundation, Inc.
12
13 ;; Maintainer: FSF
14 ;; Keywords: outlines
15
16 ;; This file is part of GNU Emacs.
17
18 ;; GNU Emacs is free software; you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation; either version 2, or (at your option)
21 ;; any later version.
22
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26 ;; GNU General Public License for more details.
27
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
30 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
31 ;; Boston, MA 02110-1301, USA.
32
33 ;;; Commentary:
34
35 ;; This package is a major mode for editing outline-format documents.
36 ;; An outline can be `abstracted' to show headers at any given level,
37 ;; with all stuff below hidden.  See the Emacs manual for details.
38
39 ;;; Todo:
40
41 ;; - subtree-terminators
42 ;; - better handle comments before function bodies (i.e. heading)
43 ;; - don't bother hiding whitespace
44
45 ;;; Code:
46
47 (require 'xemacs)
48 (require 'easymenu)
49 (require 'easy-mmode)
50
51 ;; XEmacs and compatibility
52
53 (defalias 'match-string-no-properties 'match-string)
54
55 (if (not (fboundp 'add-to-invisibility-spec))
56     (defun add-to-invisibility-spec (arg)
57       "Add elements to `buffer-invisibility-spec'.
58 See documentation for `buffer-invisibility-spec' for the kind of elements
59 that can be added."
60       (if (eq buffer-invisibility-spec t)
61           (setq buffer-invisibility-spec (list t)))
62       (setq buffer-invisibility-spec
63             (cons arg buffer-invisibility-spec))))
64
65 (if (not (fboundp 'remove-from-invisibility-spec))
66     (defun remove-from-invisibility-spec (arg)
67       "Remove elements from `buffer-invisibility-spec'."
68       (if (consp buffer-invisibility-spec)
69           (setq buffer-invisibility-spec
70                 (delete arg buffer-invisibility-spec)))))
71
72 (defvar font-lock-warning-face)
73
74
75 (defgroup outlines nil
76   "Support for hierarchical outlining."
77   :prefix "outline-"
78   :group 'editing)
79
80 (defcustom outline-regexp "[*\^L]+"
81   "Regular expression to match the beginning of a heading.
82 Any line whose beginning matches this regexp is considered to start a heading.
83 Note that Outline mode only checks this regexp at the start of a line,
84 so the regexp need not (and usually does not) start with `^'.
85 The recommended way to set this is with a Local Variables: list
86 in the file it applies to.  See also `outline-heading-end-regexp'."
87   :type '(choice regexp (const nil))
88   :group 'outlines)
89
90 (defcustom outline-heading-end-regexp "\n"
91   "Regular expression to match the end of a heading line.
92 You can assume that point is at the beginning of a heading when this
93 regexp is searched for.  The heading ends at the end of the match.
94 The recommended way to set this is with a `Local Variables:' list
95 in the file it applies to."
96   :type 'regexp
97   :group 'outlines)
98
99 (defvar outline-mode-prefix-map
100   (let ((map (make-sparse-keymap)))
101     (define-key map "@" 'outline-mark-subtree)
102     (define-key map "\C-n" 'outline-next-visible-heading)
103     (define-key map "\C-p" 'outline-previous-visible-heading)
104     (define-key map "\C-i" 'show-children)
105     (define-key map "\C-s" 'show-subtree)
106     (define-key map "\C-d" 'hide-subtree)
107     (define-key map "\C-u" 'outline-up-heading)
108     (define-key map "\C-f" 'outline-forward-same-level)
109     (define-key map "\C-b" 'outline-backward-same-level)
110     (define-key map "\C-t" 'hide-body)
111     (define-key map "\C-a" 'show-all)
112     (define-key map "\C-c" 'hide-entry)
113     (define-key map "\C-e" 'show-entry)
114     (define-key map "\C-l" 'hide-leaves)
115     (define-key map "\C-k" 'show-branches)
116     (define-key map "\C-q" 'hide-sublevels)
117     (define-key map "\C-o" 'hide-other)
118     (define-key map "\C-^" 'outline-move-subtree-up)
119     (define-key map "\C-v" 'outline-move-subtree-down)
120     (define-key map [(control ?<)] 'outline-promote)
121     (define-key map [(control ?>)] 'outline-demote)
122     (define-key map "\C-m" 'outline-insert-heading)
123     ;; Where to bind outline-cycle ?
124     map))
125
126
127
128 (defvar outline-mode-menu-heading
129   '("Headings"
130     ["Up" outline-up-heading t]
131     ["Next" outline-next-visible-heading t]
132     ["Previous" outline-previous-visible-heading t]
133     ["Next Same Level" outline-forward-same-level t]
134     ["Previous Same Level" outline-backward-same-level t]
135     ["New heading" outline-insert-heading t]
136     ["Copy to kill ring" outline-headers-as-kill :active (region-active-p)]
137     ["Move subtree up" outline-move-subtree-up t]
138     ["Move subtree down" outline-move-subtree-down t]
139     ["Promote subtree" outline-promote t]
140     ["Demote subtree" outline-demote t]))
141
142 (defvar outline-mode-menu-show
143   '("Show"
144     ["Show All" show-all t]
145     ["Show Entry" show-entry t]
146     ["Show Branches" show-branches t]
147     ["Show Children" show-children t]
148     ["Show Subtree" show-subtree t]))
149
150 (defvar outline-mode-menu-hide
151   '("Hide"
152     ["Hide Leaves" hide-leaves t]
153     ["Hide Body" hide-body t]
154     ["Hide Entry" hide-entry t]
155     ["Hide Subtree" hide-subtree t]
156     ["Hide Other" hide-other t]
157     ["Hide Sublevels" hide-sublevels t]))
158
159
160
161 (defvar outline-mode-map
162   (let ((map (make-sparse-keymap)))
163     (define-key map "\C-c" outline-mode-prefix-map)
164     map))
165
166 (defvar outline-font-lock-keywords
167   '(;;
168     ;; Highlight headings according to the level.
169     (eval . (list (concat "^\\(?:" outline-regexp "\\).+")
170                   0 '(outline-font-lock-face) nil t)))
171   "Additional expressions to highlight in Outline mode.")
172
173 (defface outline-1
174   '((t (:foreground "Blue1")))
175   "Level 1."
176   :group 'outlines)
177
178 (defface outline-2
179   '((t (:foreground "DarkGoldenrod")))
180   "Level 2."
181   :group 'outlines)
182
183 (defface outline-3
184   '((t (:foreground "Purple")))
185   "Level 3."
186   :group 'outlines)
187
188 (defface outline-4
189   '((t (:foreground "Firebrick")))
190   "Level 4."
191   :group 'outlines)
192
193 (defface outline-5
194   '((t (:foreground "ForestGreen")))
195   "Level 5."
196   :group 'outlines)
197
198 (defface outline-6
199   '((t (:foreground "CadetBlue")))
200   "Level 6."
201   :group 'outlines)
202
203 (defface outline-7
204   '((t (:foreground "Orchid")))
205   "Level 7."
206   :group 'outlines)
207
208 (defface outline-8
209   '((t (:foreground "RosyBrown")))
210   "Level 8."
211   :group 'outlines)
212
213
214
215 (defvar outline-font-lock-faces
216   [outline-1 outline-2 outline-3 outline-4
217    outline-5 outline-6 outline-7 outline-8])
218
219 (defvar outline-font-lock-levels nil)
220 (make-variable-buffer-local 'outline-font-lock-levels)
221
222 (defun outline-font-lock-face ()
223   ;; (save-excursion
224   ;;   (outline-back-to-heading t)
225   ;;   (let* ((count 0)
226   ;;       (start-level (funcall outline-level))
227   ;;       (level start-level)
228   ;;       face-level)
229   ;;     (while (not (setq face-level
230   ;;                    (if (or (bobp) (eq level 1)) 0
231   ;;                      (cdr (assq level outline-font-lock-levels)))))
232   ;;    (outline-up-heading 1 t)
233   ;;    (setq count (1+ count))
234   ;;    (setq level (funcall outline-level)))
235   ;;     ;; Remember for later.
236   ;;     (unless (zerop count)
237   ;;    (setq face-level (+ face-level count))
238   ;;    (push (cons start-level face-level) outline-font-lock-levels))
239   ;;     (condition-case nil
240   ;;      (aref outline-font-lock-faces face-level)
241   ;;    (error font-lock-warning-face))))
242   (save-excursion
243     (goto-char (match-beginning 0))
244     (looking-at outline-regexp)
245     (condition-case nil
246         (aref outline-font-lock-faces (1- (funcall outline-level)))
247       (error font-lock-warning-face))))
248
249 (defvar outline-view-change-hook nil
250   "Normal hook to be run after outline visibility changes.")
251
252 (defvar outline-mode-hook nil
253   "This hook is run when outline mode starts.")
254
255 (defvar outline-blank-line nil
256   "Non-nil means to leave unhidden blank line before heading.")
257
258 ;;;###autoload
259 (define-derived-mode outline-mode text-mode "Outline"
260   "Set major mode for editing outlines with selective display.
261 Headings are lines which start with asterisks: one for major headings,
262 two for subheadings, etc.  Lines not starting with asterisks are body lines.
263
264 Body text or subheadings under a heading can be made temporarily
265 invisible, or visible again.  Invisible lines are attached to the end
266 of the heading, so they move with it, if the line is killed and yanked
267 back.  A heading with text hidden under it is marked with an ellipsis (...).
268
269 Commands:\\<outline-mode-map>
270 \\[outline-next-visible-heading]   outline-next-visible-heading      move by visible headings
271 \\[outline-previous-visible-heading]   outline-previous-visible-heading
272 \\[outline-forward-same-level]   outline-forward-same-level        similar but skip subheadings
273 \\[outline-backward-same-level]   outline-backward-same-level
274 \\[outline-up-heading]   outline-up-heading                 move from subheading to heading
275
276 \\[hide-body]   make all text invisible (not headings).
277 \\[show-all]    make everything in buffer visible.
278 \\[hide-sublevels]  make only the first N levels of headers visible.
279
280 The remaining commands are used when point is on a heading line.
281 They apply to some of the body or subheadings of that heading.
282 \\[hide-subtree]   hide-subtree make body and subheadings invisible.
283 \\[show-subtree]   show-subtree make body and subheadings visible.
284 \\[show-children]   show-children       make direct subheadings visible.
285                  No effect on body, or subheadings 2 or more levels down.
286                  With arg N, affects subheadings N levels down.
287 \\[hide-entry]     make immediately following body invisible.
288 \\[show-entry]     make it visible.
289 \\[hide-leaves]    make body under heading and under its subheadings invisible.
290                      The subheadings remain visible.
291 \\[show-branches]  make all subheadings at all levels visible.
292
293 The variable `outline-regexp' can be changed to control what is a heading.
294 A line is a heading if `outline-regexp' matches something at the
295 beginning of the line.  The longer the match, the deeper the level.
296
297 Turning on outline mode calls the value of `text-mode-hook' and then of
298 `outline-mode-hook', if they are non-nil."
299   (make-local-variable 'line-move-ignore-invisible)
300   (setq line-move-ignore-invisible t)
301   ;; Cause use of ellipses for invisible text.
302   (add-to-invisibility-spec '(outline . t))
303   
304   (easy-menu-add outline-mode-menu-heading)
305   (easy-menu-add outline-mode-menu-show)
306   (easy-menu-add outline-mode-menu-hide)
307   (set (make-local-variable 'paragraph-start)
308        (concat paragraph-start "\\|\\(?:" outline-regexp "\\)"))
309   ;; Inhibit auto-filling of header lines.
310   (set (make-local-variable 'auto-fill-inhibit-regexp) outline-regexp)
311   (set (make-local-variable 'paragraph-separate)
312        (concat paragraph-separate "\\|\\(?:" outline-regexp "\\)"))
313   (set (make-local-variable 'font-lock-defaults)
314        '(outline-font-lock-keywords t nil nil backward-paragraph))
315   (setq imenu-generic-expression
316         (list (list nil (concat "^\\(?:" outline-regexp "\\).*$") 0)))
317   (add-hook 'change-major-mode-hook 'show-all nil t))
318
319 (defcustom outline-minor-mode-prefix "\C-c@"
320   "Prefix key to use for Outline commands in Outline minor mode.
321 The value of this variable is checked as part of loading Outline mode.
322 After that, changing the prefix key requires manipulating keymaps."
323   :type 'string
324   :group 'outlines)
325
326 ;;;###autoload
327 (define-minor-mode outline-minor-mode
328   "Toggle Outline minor mode.
329 With arg, turn Outline minor mode on if arg is positive, off otherwise.
330 See the command `outline-mode' for more information on this mode."
331   nil " Outl" (list (cons outline-minor-mode-prefix outline-mode-prefix-map))
332   :group 'outlines
333   (if outline-minor-mode
334       (progn
335         ;; Turn off this mode if we change major modes.
336         (easy-menu-add outline-mode-menu-heading)
337         (easy-menu-add outline-mode-menu-show)
338         (easy-menu-add outline-mode-menu-hide)
339         (add-hook 'change-major-mode-hook
340                   (lambda () (outline-minor-mode -1))
341                   nil t)
342         (set (make-local-variable 'line-move-ignore-invisible) t)
343         ;; Cause use of ellipses for invisible text.
344         (add-to-invisibility-spec '(outline . t)))
345     (easy-menu-remove outline-mode-menu-heading)
346     (easy-menu-remove outline-mode-menu-show)
347     (easy-menu-remove outline-mode-menu-hide)
348     (setq line-move-ignore-invisible nil)
349     ;; Cause use of ellipses for invisible text.
350     (remove-from-invisibility-spec '(outline . t))
351     ;; When turning off outline mode, get rid of any outline hiding.
352     (show-all)))
353 \f
354 (defvar outline-level 'outline-level
355   "Function of no args to compute a header's nesting level in an outline.
356 It can assume point is at the beginning of a header line and that the match
357 data reflects the `outline-regexp'.")
358
359 (defvar outline-heading-alist ()
360   "Alist associating a heading for every possible level.
361 Each entry is of the form (HEADING . LEVEL).
362 This alist is used two ways: to find the heading corresponding to
363 a given level and to find the level of a given heading.
364 If a mode or document needs several sets of outline headings (for example
365 numbered and unnumbered sections), list them set by set and sorted by level
366 within each set.  For example in texinfo mode:
367
368      (setq outline-heading-alist
369       '((\"@chapter\" . 2) (\"@section\" . 3) (\"@subsection\" . 4)
370            (\"@subsubsection\" . 5)
371         (\"@unnumbered\" . 2) (\"@unnumberedsec\" . 3)
372            (\"@unnumberedsubsec\" . 4)  (\"@unnumberedsubsubsec\" . 5)
373         (\"@appendix\" . 2) (\"@appendixsec\" . 3)...
374            (\"@appendixsubsec\" . 4) (\"@appendixsubsubsec\" . 5) ..))
375
376 Instead of sorting the entries in each set, you can also separate the
377 sets with nil.")
378 (make-variable-buffer-local 'outline-heading-alist)
379
380 ;; This used to count columns rather than characters, but that made ^L
381 ;; appear to be at level 2 instead of 1.  Columns would be better for
382 ;; tab handling, but the default regexp doesn't use tabs, and anyone
383 ;; who changes the regexp can also redefine the outline-level variable
384 ;; as appropriate.
385 (defun outline-level ()
386   "Return the depth to which a statement is nested in the outline.
387 Point must be at the beginning of a header line.
388 This is actually either the level specified in `outline-heading-alist'
389 or else the number of characters matched by `outline-regexp'."
390   (or (cdr (assoc (match-string 0) outline-heading-alist))
391       (- (match-end 0) (match-beginning 0))))
392
393 (defun outline-next-preface ()
394   "Skip forward to just before the next heading line.
395 If there's no following heading line, stop before the newline
396 at the end of the buffer."
397   (if (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
398                          nil 'move)
399       (goto-char (match-beginning 0)))
400   (if (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
401       (forward-char -1)))
402
403 (defun outline-next-heading ()
404   "Move to the next (possibly invisible) heading line."
405   (interactive)
406   ;; Make sure we don't match the heading we're at.
407   (if (and (bolp) (not (eobp))) (forward-char 1))
408   (if (re-search-forward (concat "^\\(?:" outline-regexp "\\)")
409                          nil 'move)
410       (goto-char (match-beginning 0))))
411
412 (defun outline-previous-heading ()
413   "Move to the previous (possibly invisible) heading line."
414   (interactive)
415   (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
416                       nil 'move))
417
418 (defsubst outline-invisible-p (&optional pos)
419   "Non-nil if the character after point is invisible."
420   (eq 'outline (get-char-property (or pos (point)) 'invisible)))
421
422 (defun outline-visible ()
423   (not (outline-invisible-p)))
424 (make-obsolete 'outline-visible 'outline-invisible-p)
425
426 (defun outline-back-to-heading (&optional invisible-ok)
427   "Move to previous heading line, or beg of this line if it's a heading.
428 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
429   (beginning-of-line)
430   (or (outline-on-heading-p invisible-ok)
431       (let (found)
432         (save-excursion
433           (while (not found)
434             (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
435                                     nil t)
436                 (error "before first heading"))
437             (setq found (and (or invisible-ok (not (outline-invisible-p)))
438                              (point)))))
439         (goto-char found)
440         found)))
441
442 (defun outline-on-heading-p (&optional invisible-ok)
443   "Return t if point is on a (visible) heading line.
444 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
445   (save-excursion
446     (beginning-of-line)
447     (and (bolp) (or invisible-ok (not (outline-invisible-p)))
448          (looking-at outline-regexp))))
449
450 (defun outline-insert-heading ()
451   "Insert a new heading at same depth at point."
452   (interactive)
453   (let ((head (save-excursion
454                 (condition-case nil
455                     (outline-back-to-heading)
456                   (error (outline-next-heading)))
457                 (if (eobp)
458                     (or (caar outline-heading-alist) "")
459                   (match-string 0)))))
460     (unless (or (string-match "[ \t]\\'" head)
461                 (not (string-match (concat "\\`\\(?:" outline-regexp "\\)")
462                                    (concat head " "))))
463       (setq head (concat head " ")))
464     (unless (bolp) (end-of-line) (newline))
465     (insert head)
466     (unless (eolp)
467       (save-excursion (newline-and-indent)))
468     (run-hooks 'outline-insert-heading-hook)))
469
470 (defun outline-invent-heading (head up)
471   (save-match-data
472     ;; Let's try to invent one by repeating or deleting the last char.
473     (let ((new-head (if up (substring head 0 -1)
474                       (concat head (substring head -1)))))
475       (if (string-match (concat "\\`\\(?:" outline-regexp "\\)")
476                         new-head)
477           ;; Why bother checking that it is indeed higher/lower level ?
478           new-head
479         ;; Didn't work, so ask what to do.
480         (read-string (format "%s heading for `%s': "
481                              (if up "Parent" "Demoted") head)
482                      head nil nil)))))
483
484 (defun outline-promote (&optional children)
485   "Promote headings higher up the tree.
486 If prefix argument CHILDREN is given, promote also all the children.
487 If the region is active in `transient-mark-mode', promote all headings
488 in the region."
489   (interactive
490    (list (if (and zmacs-regions (region-active-p)) 'region
491            (outline-back-to-heading)
492            (if current-prefix-arg nil 'subtree))))
493   (cond
494    ((eq children 'region)
495     (outline-map-region 'outline-promote (region-beginning) (region-end)))
496    (children
497     (outline-map-region 'outline-promote
498                         (point)
499                         (save-excursion (outline-get-next-sibling) (point))))
500    (t
501     (outline-back-to-heading t)
502     (let* ((head (match-string-no-properties 0))
503            (level (save-match-data (funcall outline-level)))
504            (up-head (or (outline-head-from-level (1- level) head)
505                         ;; Use the parent heading, if it is really
506                         ;; one level less.
507                         (save-excursion
508                           (save-match-data
509                             (outline-up-heading 1 t)
510                             (and (= (1- level) (funcall outline-level))
511                                  (match-string-no-properties 0))))
512                         ;; Bummer!! There is no lower level heading.
513                         (outline-invent-heading head 'up))))
514
515       (unless (rassoc level outline-heading-alist)
516         (push (cons head level) outline-heading-alist))
517
518       (replace-match up-head nil t)))))
519
520 (defun outline-demote (&optional children)
521   "Demote headings lower down the tree.
522 If prefix argument CHILDREN is given, demote also all the children.
523 If the region is active in `transient-mark-mode', demote all headings
524 in the region."
525   (interactive
526    (list (if (and zmacs-regions (region-active-p)) 'region
527            (outline-back-to-heading)
528            (if current-prefix-arg nil 'subtree))))
529   (cond
530    ((eq children 'region)
531     (outline-map-region 'outline-demote (region-beginning) (region-end)))
532    (children
533     (outline-map-region 'outline-demote
534                         (point)
535                         (save-excursion (outline-get-next-sibling) (point))))
536    (t
537     (let* ((head (match-string-no-properties 0))
538            (level (save-match-data (funcall outline-level)))
539            (down-head
540             (or (outline-head-from-level (1+ level) head)
541                 (save-excursion
542                   (save-match-data
543                     (while (and (progn (outline-next-heading) (not (eobp)))
544                                 (<= (funcall outline-level) level)))
545                     (when (eobp)
546                       ;; Try again from the beginning of the buffer.
547                       (goto-char (point-min))
548                       (while (and (progn (outline-next-heading) (not (eobp)))
549                                   (<= (funcall outline-level) level))))
550                     (unless (eobp)
551                       (looking-at outline-regexp)
552                       (match-string-no-properties 0))))
553                 ;; Bummer!! There is no higher-level heading in the buffer.
554                 (outline-invent-heading head nil))))
555
556       (unless (rassoc level outline-heading-alist)
557         (push (cons head level) outline-heading-alist))
558       (replace-match down-head nil t)))))
559
560 (defun outline-head-from-level (level head &optional alist)
561   "Get new heading with level LEVEL from ALIST.
562 If there are no such entries, return nil.
563 ALIST defaults to `outline-heading-alist'.
564 Similar to (car (rassoc LEVEL ALIST)).
565 If there are several different entries with same new level, choose
566 the one with the smallest distance to the assocation of HEAD in the alist.
567 This makes it possible for promotion to work in modes with several
568 independent sets of headings (numbered, unnumbered, appendix...)"
569   (unless alist (setq alist outline-heading-alist))
570   (let ((l (rassoc level alist))
571         ll h hl l2 l2l)
572     (cond
573      ((null l) nil)
574      ;; If there's no HEAD after L, any other entry for LEVEL after L
575      ;; can't be much better than L.
576      ((null (setq h (assoc head (setq ll (memq l alist))))) (car l))
577      ;; If there's no other entry for LEVEL, just keep L.
578      ((null (setq l2 (rassoc level (cdr ll)))) (car l))
579      ;; Now we have L, L2, and H: see if L2 seems better than L.
580      ;; If H is after L2, L2 is better.
581      ((memq h (setq l2l (memq l2 (cdr ll))))
582       (outline-head-from-level level head l2l))
583      ;; Now we have H between L and L2.
584      ;; If there's a separator between L and H, prefer L2.
585      ((memq h (memq nil ll))
586       (outline-head-from-level level head l2l))
587      ;; If there's a separator between L2 and H, prefer L.
588      ((memq l2 (memq nil (setq hl (memq h ll)))) (car l))
589      ;; No separator between L and L2, check the distance.
590      ((< (* 2 (length hl)) (+ (length ll) (length l2l)))
591       (outline-head-from-level level head l2l))
592      ;; If all else fails, just keep L.
593      (t (car l)))))
594
595 (defun outline-map-region (fun beg end)
596   "Call FUN for every heading between BEG and END.
597 When FUN is called, point is at the beginning of the heading and
598 the match data is set appropriately."
599   (save-excursion
600     (setq end (copy-marker end))
601     (goto-char beg)
602     (when (re-search-forward (concat "^\\(?:" outline-regexp "\\)") end t)
603       (goto-char (match-beginning 0))
604       (funcall fun)
605       (while (and (progn
606                     (outline-next-heading)
607                     (< (point) end))
608                   (not (eobp)))
609         (funcall fun)))))
610
611 ;; Vertical tree motion
612
613 (defun outline-move-subtree-up (&optional arg)
614   "Move the currrent subtree up past ARG headlines of the same level."
615   (interactive "p")
616   (outline-move-subtree-down (- arg)))
617
618 (defun outline-move-subtree-down (&optional arg)
619   "Move the currrent subtree down past ARG headlines of the same level."
620   (interactive "p")
621   (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
622                    'outline-get-last-sibling))
623         (ins-point (make-marker))
624         (cnt (abs arg))
625         (tmp-string "")
626         beg end folded)
627     ;; Select the tree
628     (outline-back-to-heading)
629     (setq beg (point))
630     (save-match-data
631       (save-excursion (outline-end-of-heading)
632                       (setq folded (outline-invisible-p)))
633       (outline-end-of-subtree))
634     (if (= (char-after) ?\n) (forward-char 1))
635     (setq end (point))
636     ;; Find insertion point, with error handling
637     (goto-char beg)
638     (while (> cnt 0)
639       (or (funcall movfunc)
640           (progn (goto-char beg)
641                  (error "Cannot move past superior level")))
642       (setq cnt (1- cnt)))
643     (if (> arg 0)
644         ;; Moving forward - still need to move over subtree
645         (progn (outline-end-of-subtree)
646                (if (= (char-after) ?\n) (forward-char 1))))
647     (move-marker ins-point (point))
648     (setq tmp-string (buffer-substring beg end))
649     (delete-region beg end)
650     (insert tmp-string)
651     (goto-char ins-point)
652     (if folded (hide-subtree))
653     (move-marker ins-point nil)))
654
655 (defun outline-end-of-heading ()
656   (if (re-search-forward outline-heading-end-regexp nil 'move)
657       (forward-char -1)))
658
659 (defun outline-next-visible-heading (arg)
660   "Move to the next visible heading line.
661 With argument, repeats or can move backward if negative.
662 A heading line is one that starts with a `*' (or that
663 `outline-regexp' matches)."
664   (interactive "p")
665   (if (< arg 0)
666       (beginning-of-line)
667     (end-of-line))
668   (while (< arg 0)
669     (block nil
670       (while (and (not (bobp))
671                   (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
672                                       nil 'move))
673         (if (not (outline-invisible-p))
674             (return)))
675       (error "Beginning of file"))
676     (setq arg (1+ arg)))
677   (while (> arg 0)
678     (block nil
679       (while (and (not (eobp))
680                   (re-search-forward (concat "^\\(?:" outline-regexp "\\)")
681                                      nil 'move))
682         (if (not (outline-invisible-p (match-beginning 0)))
683             (return)))
684       (error "End of file"))
685     (setq arg (1- arg)))
686   (beginning-of-line))
687
688 (defun outline-previous-visible-heading (arg)
689   "Move to the previous heading line.
690 With argument, repeats or can move forward if negative.
691 A heading line is one that starts with a `*' (or that
692 `outline-regexp' matches)."
693   (interactive "p")
694   (outline-next-visible-heading (- arg)))
695
696 (defun outline-mark-subtree ()
697   "Mark the current subtree in an outlined document.
698 This puts point at the start of the current subtree, and mark at the end."
699   (interactive)
700   (let ((beg))
701     (if (outline-on-heading-p)
702         ;; we are already looking at a heading
703         (beginning-of-line)
704       ;; else go back to previous heading
705       (outline-previous-visible-heading 1))
706     (setq beg (point))
707     (outline-end-of-subtree)
708     (push-mark (point) nil t)
709     (goto-char beg)))
710 \f
711
712 (defvar outline-isearch-open-invisible-function nil
713   "Function called if `isearch' finishes in an invisible overlay.
714 The function is called with the overlay as its only argument.
715 If nil, `show-entry' is called to reveal the invisible text.")
716
717 (defun outline-discard-extents (&optional beg end)
718   "Clear BEG and END of overlays whose property NAME has value VAL.
719 Overlays might be moved and/or split.
720 BEG and END default respectively to the beginning and end of buffer."
721   (unless beg (setq beg (point-min)))
722   (unless end (setq end (point-max)))
723   (if (< end beg)
724       (setq beg (prog1 end (setq end beg))))
725   (save-excursion
726     (map-extents 
727      #'(lambda (ex ignored) 
728          (if (< (extent-start-position ex) beg)
729              (if (> (extent-end-position ex) end)
730                  (progn
731                    (set-extent-endpoints (copy-extent ex)
732                                          (extent-start-position ex) beg)
733                    (set-extent-endpoints ex end (extent-end-position ex)))
734                (set-extent-endpoints ex (extent-start-position ex) beg))
735            (if (> (extent-end-position ex) end)
736                (set-extent-endpoints ex end (extent-end-position ex))
737              (delete-extent ex)))
738          nil)
739      (current-buffer) beg end nil 'end-closed 'outline)))
740
741 (defun outline-flag-region (from to flag)
742   "Hide or show lines from FROM to TO, according to FLAG.
743 If FLAG is nil then text is shown, while if FLAG is t the text is hidden."
744   (when (< to from)
745     (setq from (prog1 to (setq to from))))
746   ;; first clear it all out
747   (outline-discard-extents from to)
748   (when flag
749     (let ((ex (make-extent from to)))
750       (set-extent-property ex 'invisible 'outline)
751       (set-extent-property ex 'outline flag)
752       ;; FIXME: I don't think XEmacs uses this, actually.
753       (set-extent-property ex 'isearch-open-invisible
754                            (or outline-isearch-open-invisible-function
755                                'outline-isearch-open-invisible))))
756   ;; Seems only used by lazy-lock.  I.e. obsolete.
757   (run-hooks 'outline-view-change-hook))
758
759 ;; Function to be set as an outline-isearch-open-invisible' property
760 ;; to the overlay that makes the outline invisible (see
761 ;; `outline-flag-region').
762 (defun outline-isearch-open-invisible (overlay)
763   ;; We rely on the fact that isearch places point on the matched text.
764   (show-entry))
765 \f
766 (defun hide-entry ()
767   "Hide the body directly following this heading."
768   (interactive)
769   (save-excursion
770     (outline-back-to-heading)
771     (outline-end-of-heading)
772     (outline-flag-region (point) (progn (outline-next-preface) (point)) t)))
773
774 (defun show-entry ()
775   "Show the body directly following this heading.
776 Show the heading too, if it is currently invisible."
777   (interactive)
778   (save-excursion
779     (outline-back-to-heading t)
780     (outline-flag-region (max 1 (1- (point)))
781                          (progn (outline-next-preface) (point)) nil)))
782
783 (defun hide-body ()
784   "Hide all body lines in buffer, leaving all headings visible."
785   (interactive)
786   (hide-region-body (point-min) (point-max)))
787
788 (defun hide-region-body (start end)
789   "Hide all body lines in the region, but not headings."
790   ;; Nullify the hook to avoid repeated calls to `outline-flag-region'
791   ;; wasting lots of time running `lazy-lock-fontify-after-outline'
792   ;; and run the hook finally.
793   (let (outline-view-change-hook)
794     (save-excursion
795       (save-restriction
796         (narrow-to-region start end)
797         (goto-char (point-min))
798         (if (outline-on-heading-p)
799             (outline-end-of-heading)
800           (outline-next-preface))
801         (while (not (eobp))
802           (outline-flag-region (point)
803                                (progn (outline-next-preface) (point)) t)
804           (unless (eobp)
805             (forward-char (if (looking-at "\n\n") 2 1))
806             (outline-end-of-heading))))))
807   (run-hooks 'outline-view-change-hook))
808
809 (defun show-all ()
810   "Show all of the text in the buffer."
811   (interactive)
812   (outline-flag-region (point-min) (point-max) nil))
813
814 (defun hide-subtree ()
815   "Hide everything after this heading at deeper levels."
816   (interactive)
817   (outline-flag-subtree t))
818
819 (defun hide-leaves ()
820   "Hide all body after this heading at deeper levels."
821   (interactive)
822   (save-excursion
823     (outline-back-to-heading)
824     (outline-end-of-heading)
825     (hide-region-body (point) (progn (outline-end-of-subtree) (point)))))
826
827 (defun show-subtree ()
828   "Show everything after this heading at deeper levels."
829   (interactive)
830   (outline-flag-subtree nil))
831
832 (defun outline-show-heading ()
833   "Show the current heading and move to its end."
834   (outline-flag-region (- (point)
835                           (if (bobp) 0
836                             (if (and outline-blank-line
837                                      (eq (char-before (1- (point))) ?\n))
838                                 2 1)))
839                        (progn (outline-end-of-heading) (point))
840                        nil))
841
842 (defun hide-sublevels (levels)
843   "Hide everything but the top LEVELS levels of headers, in whole buffer."
844   (interactive "p")
845   (if (< levels 1)
846       (error "Must keep at least one level of headers"))
847   (let (outline-view-change-hook)
848     (save-excursion
849       (goto-char (point-min))
850       ;; Skip the prelude, if any.
851       (unless (outline-on-heading-p t) (outline-next-heading))
852       ;; First hide everything.
853       (outline-flag-region (point) (point-max) t)
854       ;; Then unhide the top level headers.
855       (outline-map-region
856        (lambda ()
857          (if (<= (funcall outline-level) levels)
858              (outline-show-heading)))
859        (point) (point-max))))
860   (run-hooks 'outline-view-change-hook))
861
862 (defun hide-other ()
863   "Hide everything except current body and parent and top-level headings."
864   (interactive)
865   (hide-sublevels 1)
866   (let (outline-view-change-hook)
867     (save-excursion
868       (outline-back-to-heading t)
869       (show-entry)
870       (while (condition-case nil (progn (outline-up-heading 1 t) (not (bobp)))
871                (error nil))
872         (outline-flag-region (max 1 (1- (point)))
873                              (save-excursion (forward-line 1) (point))
874                              nil))))
875   (run-hooks 'outline-view-change-hook))
876
877 (defun outline-toggle-children ()
878   "Show or hide the current subtree depending on its current state."
879   (interactive)
880   (save-excursion
881     (outline-back-to-heading)
882     (if (not (outline-invisible-p (point-at-eol)))
883         (hide-subtree)
884       (show-children)
885       (show-entry))))
886
887 (defun outline-flag-subtree (flag)
888   (save-excursion
889     (outline-back-to-heading)
890     (outline-end-of-heading)
891     (outline-flag-region (point)
892                          (progn (outline-end-of-subtree) (point))
893                          flag)))
894
895 (defun outline-end-of-subtree ()
896   (outline-back-to-heading)
897   (let ((first t)
898         (level (funcall outline-level)))
899     (while (and (not (eobp))
900                 (or first (> (funcall outline-level) level)))
901       (setq first nil)
902       (outline-next-heading))
903     (if (and (bolp) (not (eolp)))
904         ;; We stopped at a nonempty line (the next heading).
905         (progn
906           ;; Go to end of line before heading
907           (forward-char -1)
908           (if (and outline-blank-line (bolp))
909               ;; leave blank line before heading
910               (forward-char -1))))))
911 \f
912 (defun show-branches ()
913   "Show all subheadings of this heading, but not their bodies."
914   (interactive)
915   (show-children 1000))
916
917 (defun show-children (&optional level)
918   "Show all direct subheadings of this heading.
919 Prefix arg LEVEL is how many levels below the current level should be shown.
920 Default is enough to cause the following heading to appear."
921   (interactive "P")
922   (setq level
923         (if level (prefix-numeric-value level)
924           (save-excursion
925             (outline-back-to-heading)
926             (let ((start-level (funcall outline-level)))
927               (outline-next-heading)
928               (if (eobp)
929                   1
930                 (max 1 (- (funcall outline-level) start-level)))))))
931   (let (outline-view-change-hook)
932     (save-excursion
933       (outline-back-to-heading)
934       (setq level (+ level (funcall outline-level)))
935       (outline-map-region
936        (lambda ()
937          (if (<= (funcall outline-level) level)
938              (outline-show-heading)))
939        (point)
940        (progn (outline-end-of-subtree)
941               (if (eobp) (point-max) (1+ (point)))))))
942   (run-hooks 'outline-view-change-hook))
943
944 \f
945
946 (defun outline-up-heading (arg &optional invisible-ok)
947   "Move to the visible heading line of which the present line is a subheading.
948 With argument, move up ARG levels.
949 If INVISIBLE-OK is non-nil, also consider invisible lines."
950   (interactive "p")
951   (and (eq this-command 'outline-up-heading)
952        (or (eq last-command 'outline-up-heading) (push-mark)))
953   (outline-back-to-heading invisible-ok)
954   (let ((start-level (funcall outline-level)))
955     (if (eq start-level 1)
956         (error "Already at top level of the outline"))
957     (while (and (> start-level 1) (> arg 0) (not (bobp)))
958       (let ((level start-level))
959         (while (not (or (< level start-level) (bobp)))
960           (if invisible-ok
961               (outline-previous-heading)
962             (outline-previous-visible-heading 1))
963           (setq level (funcall outline-level)))
964         (setq start-level level))
965       (setq arg (- arg 1))))
966   (looking-at outline-regexp))
967
968 (defun outline-forward-same-level (arg)
969   "Move forward to the ARG'th subheading at same level as this one.
970 Stop at the first and last subheadings of a superior heading."
971   (interactive "p")
972   (outline-back-to-heading)
973   (while (> arg 0)
974     (let ((point-to-move-to (save-excursion
975                               (outline-get-next-sibling))))
976       (if point-to-move-to
977           (progn
978             (goto-char point-to-move-to)
979             (setq arg (1- arg)))
980         (progn
981           (setq arg 0)
982           (error "No following same-level heading"))))))
983
984 (defun outline-get-next-sibling ()
985   "Move to next heading of the same level, and return point or nil if none."
986   (let ((level (funcall outline-level)))
987     (outline-next-visible-heading 1)
988     (while (and (not (eobp)) (> (funcall outline-level) level))
989       (outline-next-visible-heading 1))
990     (if (or (eobp) (< (funcall outline-level) level))
991         nil
992       (point))))
993
994 (defun outline-backward-same-level (arg)
995   "Move backward to the ARG'th subheading at same level as this one.
996 Stop at the first and last subheadings of a superior heading."
997   (interactive "p")
998   (outline-back-to-heading)
999   (while (> arg 0)
1000     (let ((point-to-move-to (save-excursion
1001                               (outline-get-last-sibling))))
1002       (if point-to-move-to
1003           (progn
1004             (goto-char point-to-move-to)
1005             (setq arg (1- arg)))
1006         (progn
1007           (setq arg 0)
1008           (error "No previous same-level heading"))))))
1009
1010 (defun outline-get-last-sibling ()
1011   "Move to previous heading of the same level, and return point or nil if none."
1012   (let ((level (funcall outline-level)))
1013     (outline-previous-visible-heading 1)
1014     (while (and (> (funcall outline-level) level)
1015                 (not (bobp)))
1016       (outline-previous-visible-heading 1))
1017     (if (< (funcall outline-level) level)
1018         nil
1019       (point))))
1020 \f
1021 (defun outline-headers-as-kill (beg end)
1022   "Save the visible outline headers in region at the start of the kill ring.
1023
1024 Text shown between the headers isn't copied.  Two newlines are
1025 inserted between saved headers.  Yanking the result may be a
1026 convenient way to make a table of contents of the buffer."
1027   (interactive "r")
1028   (save-excursion
1029     (save-restriction
1030       (narrow-to-region beg end)
1031       (goto-char (point-min))
1032       (let ((buffer (current-buffer))
1033             start end)
1034         (with-temp-buffer
1035           (with-current-buffer buffer
1036             ;; Boundary condition: starting on heading:
1037             (when (outline-on-heading-p)
1038               (outline-back-to-heading)
1039               (setq start (point)
1040                     end (progn (outline-end-of-heading)
1041                                (point)))
1042               (insert-buffer-substring buffer start end)
1043               (insert "\n\n")))
1044           (let ((temp-buffer (current-buffer)))
1045             (with-current-buffer buffer
1046               (while (outline-next-heading)
1047                 (unless (outline-invisible-p)
1048                   (setq start (point)
1049                         end (progn (outline-end-of-heading) (point)))
1050                   (with-current-buffer temp-buffer
1051                     (insert-buffer-substring buffer start end)
1052                     (insert "\n\n"))))))
1053           (kill-new (buffer-string)))))))
1054
1055 (provide 'outline)
1056 (provide 'noutline)
1057
1058 ;; arch-tag: 1724410e-7d4d-4f46-b801-49e18171e874
1059 ;;; outline.el ends here