]> code.delx.au - gnu-emacs/blob - lisp/allout.el
Use allout invisible-text overlays instead of
[gnu-emacs] / lisp / allout.el
1 ;;; allout.el --- extensive outline mode for use alone and with other modes
2
3 ;; Copyright (C) 1992, 1993, 1994, 2001, 2002, 2003, 2004,
4 ;; 2005 Free Software Foundation, Inc.
5
6 ;; Author: Ken Manheimer <ken dot manheimer at gmail dot com>
7 ;; Maintainer: Ken Manheimer <ken dot manheimer at gmail dot com>
8 ;; Created: Dec 1991 - first release to usenet
9 ;; Version: 2.2
10 ;; Keywords: outlines wp languages
11
12 ;; This file is part of GNU Emacs.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to the
26 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27 ;; Boston, MA 02110-1301, USA.
28
29 ;;; Commentary:
30
31 ;; Allout outline minor mode provides extensive outline formatting and
32 ;; and manipulation beyond standard emacs outline mode. Some features:
33 ;;
34 ;; - Classic outline-mode topic-oriented navigation and exposure adjustment
35 ;; - Topic-oriented editing including coherent topic and subtopic
36 ;; creation, promotion, demotion, cut/paste across depths, etc.
37 ;; - Incremental search with dynamic exposure and reconcealment of text
38 ;; - Customizable bullet format - enables programming-language specific
39 ;; outlining, for code-folding editing. (Allout code itself is to try it;
40 ;; formatted as an outline - do ESC-x eval-current-buffer in allout.el; but
41 ;; emacs local file variables need to be enabled when the
42 ;; file was visited - see `enable-local-variables'.)
43 ;; - Configurable per-file initial exposure settings
44 ;; - Symmetric-key and key-pair topic encryption, plus symmetric passphrase
45 ;; mnemonic support, with verification against an established passphrase
46 ;; (using a stashed encrypted dummy string) and user-supplied hint
47 ;; maintenance. (See allout-toggle-current-subtree-encryption docstring.)
48 ;; - Automatic topic-number maintenance
49 ;; - "Hot-spot" operation, for single-keystroke maneuvering and
50 ;; exposure control (see the allout-mode docstring)
51 ;; - Easy rendering of exposed portions into numbered, latex, indented, etc
52 ;; outline styles
53 ;; - Careful attention to whitespace - enabling blank lines between items
54 ;; and maintenance of hanging indentation (in paragraph auto-fill and
55 ;; across topic promotion and demotion) of topic bodies consistent with
56 ;; indentation of their topic header.
57 ;;
58 ;; and more.
59 ;;
60 ;; See the `allout-mode' function's docstring for an introduction to the
61 ;; mode. The development version and helpful notes are available at
62 ;; http://myriadicity.net/Sundry/EmacsAllout .
63 ;;
64 ;; The outline menubar additions provide quick reference to many of
65 ;; the features, and see the docstring of the variable `allout-init'
66 ;; for instructions on priming your emacs session for automatic
67 ;; activation of allout-mode.
68 ;;
69 ;; See the docstring of the variables `allout-layout' and
70 ;; `allout-auto-activation' for details on automatic activation of
71 ;; `allout-mode' as a minor mode. (It has changed since allout
72 ;; 3.x, for those of you that depend on the old method.)
73 ;;
74 ;; Note - the lines beginning with `;;;_' are outline topic headers.
75 ;; Just `ESC-x eval-current-buffer' to give it a whirl.
76
77 ;; ken manheimer (ken dot manheimer at gmail dot com)
78
79 ;;; Code:
80
81 ;;;_* Dependency autoloads
82 (require 'overlay)
83 (eval-when-compile (progn (require 'pgg)
84 (require 'pgg-gpg)
85 (require 'overlay)
86 ))
87 (autoload 'pgg-gpg-symmetric-key-p "pgg-gpg"
88 "True if decoded armor MESSAGE-KEYS has symmetric encryption indicator.")
89
90 ;;;_* USER CUSTOMIZATION VARIABLES:
91
92 ;;;_ > defgroup allout
93 (defgroup allout nil
94 "Extensive outline mode for use alone and with other modes."
95 :prefix "allout-"
96 :group 'outlines)
97
98 ;;;_ + Layout, Mode, and Topic Header Configuration
99
100 ;;;_ = allout-auto-activation
101 (defcustom allout-auto-activation nil
102 "*Regulates auto-activation modality of allout outlines - see `allout-init'.
103
104 Setq-default by `allout-init' to regulate whether or not allout
105 outline mode is automatically activated when the buffer-specific
106 variable `allout-layout' is non-nil, and whether or not the layout
107 dictated by `allout-layout' should be imposed on mode activation.
108
109 With value t, auto-mode-activation and auto-layout are enabled.
110 \(This also depends on `allout-find-file-hook' being installed in
111 `find-file-hook', which is also done by `allout-init'.)
112
113 With value `ask', auto-mode-activation is enabled, and endorsement for
114 performing auto-layout is asked of the user each time.
115
116 With value `activate', only auto-mode-activation is enabled,
117 auto-layout is not.
118
119 With value nil, neither auto-mode-activation nor auto-layout are
120 enabled.
121
122 See the docstring for `allout-init' for the proper interface to
123 this variable."
124 :type '(choice (const :tag "On" t)
125 (const :tag "Ask about layout" "ask")
126 (const :tag "Mode only" "activate")
127 (const :tag "Off" nil))
128 :group 'allout)
129 ;;;_ = allout-layout
130 (defvar allout-layout nil
131 "*Layout specification and provisional mode trigger for allout outlines.
132
133 Buffer-specific.
134
135 A list value specifies a default layout for the current buffer, to be
136 applied upon activation of `allout-mode'. Any non-nil value will
137 automatically trigger `allout-mode' \(provided `allout-init' has been called
138 to enable this behavior).
139
140 See the docstring for `allout-init' for details on setting up for
141 auto-mode-activation, and for `allout-expose-topic' for the format of
142 the layout specification.
143
144 You can associate a particular outline layout with a file by setting
145 this var via the file's local variables. For example, the following
146 lines at the bottom of an Emacs Lisp file:
147
148 ;;;Local variables:
149 ;;;allout-layout: \(0 : -1 -1 0)
150 ;;;End:
151
152 will, modulo the above-mentioned conditions, cause the mode to be
153 activated when the file is visited, followed by the equivalent of
154 `\(allout-expose-topic 0 : -1 -1 0)'. \(This is the layout used for
155 the allout.el source file.)
156
157 Also, allout's mode-specific provisions will make topic prefixes default
158 to the comment-start string, if any, of the language of the file. This
159 is modulo the setting of `allout-use-mode-specific-leader', which see.")
160 (make-variable-buffer-local 'allout-layout)
161 ;;;_ = allout-show-bodies
162 (defcustom allout-show-bodies nil
163 "*If non-nil, show entire body when exposing a topic, rather than
164 just the header."
165 :type 'boolean
166 :group 'allout)
167 (make-variable-buffer-local 'allout-show-bodies)
168
169 ;;;_ = allout-header-prefix
170 (defcustom allout-header-prefix "."
171 "*Leading string which helps distinguish topic headers.
172
173 Outline topic header lines are identified by a leading topic
174 header prefix, which mostly have the value of this var at their front.
175 \(Level 1 topics are exceptions. They consist of only a single
176 character, which is typically set to the `allout-primary-bullet'. Many
177 outlines start at level 2 to avoid this discrepancy."
178 :type 'string
179 :group 'allout)
180 (make-variable-buffer-local 'allout-header-prefix)
181 ;;;_ = allout-primary-bullet
182 (defcustom allout-primary-bullet "*"
183 "Bullet used for top-level outline topics.
184
185 Outline topic header lines are identified by a leading topic header
186 prefix, which is concluded by bullets that includes the value of this
187 var and the respective allout-*-bullets-string vars.
188
189 The value of an asterisk (`*') provides for backwards compatibility
190 with the original Emacs outline mode. See `allout-plain-bullets-string'
191 and `allout-distinctive-bullets-string' for the range of available
192 bullets."
193 :type 'string
194 :group 'allout)
195 (make-variable-buffer-local 'allout-primary-bullet)
196 ;;;_ = allout-plain-bullets-string
197 (defcustom allout-plain-bullets-string ".,"
198 "*The bullets normally used in outline topic prefixes.
199
200 See `allout-distinctive-bullets-string' for the other kind of
201 bullets.
202
203 DO NOT include the close-square-bracket, `]', as a bullet.
204
205 Outline mode has to be reactivated in order for changes to the value
206 of this var to take effect."
207 :type 'string
208 :group 'allout)
209 (make-variable-buffer-local 'allout-plain-bullets-string)
210 ;;;_ = allout-distinctive-bullets-string
211 (defcustom allout-distinctive-bullets-string "*+-=>()[{}&!?#%\"X@$~_\\:;^"
212 "*Persistent outline header bullets used to distinguish special topics.
213
214 These bullets are used to distinguish topics from the run-of-the-mill
215 ones. They are not used in the standard topic headers created by
216 the topic-opening, shifting, and rebulleting \(eg, on topic shift,
217 topic paste, blanket rebulleting) routines, but are offered among the
218 choices for rebulleting. They are not altered by the above automatic
219 rebulleting, so they can be used to characterize topics, eg:
220
221 `?' question topics
222 `\(' parenthetic comment \(with a matching close paren inside)
223 `[' meta-note \(with a matching close ] inside)
224 `\"' a quotation
225 `=' value settings
226 `~' \"more or less\"
227 `^' see above
228
229 ... for example. (`#' typically has a special meaning to the software,
230 according to the value of `allout-numbered-bullet'.)
231
232 See `allout-plain-bullets-string' for the selection of
233 alternating bullets.
234
235 You must run `set-allout-regexp' in order for outline mode to
236 reconcile to changes of this value.
237
238 DO NOT include the close-square-bracket, `]', on either of the bullet
239 strings."
240 :type 'string
241 :group 'allout)
242 (make-variable-buffer-local 'allout-distinctive-bullets-string)
243
244 ;;;_ = allout-use-mode-specific-leader
245 (defcustom allout-use-mode-specific-leader t
246 "*When non-nil, use mode-specific topic-header prefixes.
247
248 Allout outline mode will use the mode-specific `allout-mode-leaders'
249 and/or comment-start string, if any, to lead the topic prefix string,
250 so topic headers look like comments in the programming language.
251
252 String values are used as they stand.
253
254 Value t means to first check for assoc value in `allout-mode-leaders'
255 alist, then use comment-start string, if any, then use default \(`.').
256 \(See note about use of comment-start strings, below.)
257
258 Set to the symbol for either of `allout-mode-leaders' or
259 `comment-start' to use only one of them, respectively.
260
261 Value nil means to always use the default \(`.').
262
263 comment-start strings that do not end in spaces are tripled, and an
264 `_' underscore is tacked on the end, to distinguish them from regular
265 comment strings. comment-start strings that do end in spaces are not
266 tripled, but an underscore is substituted for the space. [This
267 presumes that the space is for appearance, not comment syntax. You
268 can use `allout-mode-leaders' to override this behavior, when
269 incorrect.]"
270 :type '(choice (const t) (const nil) string
271 (const allout-mode-leaders)
272 (const comment-start))
273 :group 'allout)
274 ;;;_ = allout-mode-leaders
275 (defvar allout-mode-leaders '()
276 "Specific allout-prefix leading strings per major modes.
277
278 Entries will be used instead or in lieu of mode-specific
279 comment-start strings. See also `allout-use-mode-specific-leader'.
280
281 If you're constructing a string that will comment-out outline
282 structuring so it can be included in program code, append an extra
283 character, like an \"_\" underscore, to distinguish the lead string
284 from regular comments that start at bol.")
285
286 ;;;_ = allout-old-style-prefixes
287 (defcustom allout-old-style-prefixes nil
288 "*When non-nil, use only old-and-crusty `outline-mode' `*' topic prefixes.
289
290 Non-nil restricts the topic creation and modification
291 functions to asterix-padded prefixes, so they look exactly
292 like the original Emacs-outline style prefixes.
293
294 Whatever the setting of this variable, both old and new style prefixes
295 are always respected by the topic maneuvering functions."
296 :type 'boolean
297 :group 'allout)
298 (make-variable-buffer-local 'allout-old-style-prefixes)
299 ;;;_ = allout-stylish-prefixes - alternating bullets
300 (defcustom allout-stylish-prefixes t
301 "*Do fancy stuff with topic prefix bullets according to level, etc.
302
303 Non-nil enables topic creation, modification, and repositioning
304 functions to vary the topic bullet char (the char that marks the topic
305 depth) just preceding the start of the topic text) according to level.
306 Otherwise, only asterisks (`*') and distinctive bullets are used.
307
308 This is how an outline can look (but sans indentation) with stylish
309 prefixes:
310
311 * Top level
312 .* A topic
313 . + One level 3 subtopic
314 . . One level 4 subtopic
315 . . A second 4 subtopic
316 . + Another level 3 subtopic
317 . #1 A numbered level 4 subtopic
318 . #2 Another
319 . ! Another level 4 subtopic with a different distinctive bullet
320 . #4 And another numbered level 4 subtopic
321
322 This would be an outline with stylish prefixes inhibited (but the
323 numbered and other distinctive bullets retained):
324
325 * Top level
326 .* A topic
327 . * One level 3 subtopic
328 . * One level 4 subtopic
329 . * A second 4 subtopic
330 . * Another level 3 subtopic
331 . #1 A numbered level 4 subtopic
332 . #2 Another
333 . ! Another level 4 subtopic with a different distinctive bullet
334 . #4 And another numbered level 4 subtopic
335
336 Stylish and constant prefixes (as well as old-style prefixes) are
337 always respected by the topic maneuvering functions, regardless of
338 this variable setting.
339
340 The setting of this var is not relevant when `allout-old-style-prefixes'
341 is non-nil."
342 :type 'boolean
343 :group 'allout)
344 (make-variable-buffer-local 'allout-stylish-prefixes)
345
346 ;;;_ = allout-numbered-bullet
347 (defcustom allout-numbered-bullet "#"
348 "*String designating bullet of topics that have auto-numbering; nil for none.
349
350 Topics having this bullet have automatic maintenance of a sibling
351 sequence-number tacked on, just after the bullet. Conventionally set
352 to \"#\", you can set it to a bullet of your choice. A nil value
353 disables numbering maintenance."
354 :type '(choice (const nil) string)
355 :group 'allout)
356 (make-variable-buffer-local 'allout-numbered-bullet)
357 ;;;_ = allout-file-xref-bullet
358 (defcustom allout-file-xref-bullet "@"
359 "*Bullet signifying file cross-references, for `allout-resolve-xref'.
360
361 Set this var to the bullet you want to use for file cross-references."
362 :type '(choice (const nil) string)
363 :group 'allout)
364 ;;;_ = allout-presentation-padding
365 (defcustom allout-presentation-padding 2
366 "*Presentation-format white-space padding factor, for greater indent."
367 :type 'integer
368 :group 'allout)
369
370 (make-variable-buffer-local 'allout-presentation-padding)
371
372 ;;;_ = allout-abbreviate-flattened-numbering
373 (defcustom allout-abbreviate-flattened-numbering nil
374 "*If non-nil, `allout-flatten-exposed-to-buffer' abbreviates topic
375 numbers to minimal amount with some context. Otherwise, entire
376 numbers are always used."
377 :type 'boolean
378 :group 'allout)
379
380 ;;;_ + LaTeX formatting
381 ;;;_ - allout-number-pages
382 (defcustom allout-number-pages nil
383 "*Non-nil turns on page numbering for LaTeX formatting of an outline."
384 :type 'boolean
385 :group 'allout)
386 ;;;_ - allout-label-style
387 (defcustom allout-label-style "\\large\\bf"
388 "*Font and size of labels for LaTeX formatting of an outline."
389 :type 'string
390 :group 'allout)
391 ;;;_ - allout-head-line-style
392 (defcustom allout-head-line-style "\\large\\sl "
393 "*Font and size of entries for LaTeX formatting of an outline."
394 :type 'string
395 :group 'allout)
396 ;;;_ - allout-body-line-style
397 (defcustom allout-body-line-style " "
398 "*Font and size of entries for LaTeX formatting of an outline."
399 :type 'string
400 :group 'allout)
401 ;;;_ - allout-title-style
402 (defcustom allout-title-style "\\Large\\bf"
403 "*Font and size of titles for LaTeX formatting of an outline."
404 :type 'string
405 :group 'allout)
406 ;;;_ - allout-title
407 (defcustom allout-title '(or buffer-file-name (buffer-name))
408 "*Expression to be evaluated to determine the title for LaTeX
409 formatted copy."
410 :type 'sexp
411 :group 'allout)
412 ;;;_ - allout-line-skip
413 (defcustom allout-line-skip ".05cm"
414 "*Space between lines for LaTeX formatting of an outline."
415 :type 'string
416 :group 'allout)
417 ;;;_ - allout-indent
418 (defcustom allout-indent ".3cm"
419 "*LaTeX formatted depth-indent spacing."
420 :type 'string
421 :group 'allout)
422
423 ;;;_ + Topic encryption
424 ;;;_ = allout-topic-encryption-bullet
425 (defcustom allout-topic-encryption-bullet "~"
426 "*Bullet signifying encryption of the entry's body."
427 :type '(choice (const nil) string)
428 :group 'allout)
429 ;;;_ = allout-passphrase-verifier-handling
430 (defcustom allout-passphrase-verifier-handling t
431 "*Enable use of symmetric encryption passphrase verifier if non-nil.
432
433 See the docstring for the `allout-enable-file-variable-adjustment'
434 variable for details about allout ajustment of file variables."
435 :type 'boolean
436 :group 'allout)
437 (make-variable-buffer-local 'allout-passphrase-verifier-handling)
438 ;;;_ = allout-passphrase-hint-handling
439 (defcustom allout-passphrase-hint-handling 'always
440 "*Dictate outline encryption passphrase reminder handling:
441
442 always - always show reminder when prompting
443 needed - show reminder on passphrase entry failure
444 disabled - never present or adjust reminder
445
446 See the docstring for the `allout-enable-file-variable-adjustment'
447 variable for details about allout ajustment of file variables."
448 :type '(choice (const always)
449 (const needed)
450 (const disabled))
451 :group 'allout)
452 (make-variable-buffer-local 'allout-passphrase-hint-handling)
453 ;;;_ = allout-encrypt-unencrypted-on-saves
454 (defcustom allout-encrypt-unencrypted-on-saves t
455 "*When saving, should topics pending encryption be encrypted?
456
457 The idea is to prevent file-system exposure of any un-encrypted stuff, and
458 mostly covers both deliberate file writes and auto-saves.
459
460 - Yes: encrypt all topics pending encryption, even if it's the one
461 currently being edited. \(In that case, the currently edited topic
462 will be automatically decrypted before any user interaction, so they
463 can continue editing but the copy on the file system will be
464 encrypted.)
465 Auto-saves will use the \"All except current topic\" mode if this
466 one is selected, to avoid practical difficulties - see below.
467 - All except current topic: skip the topic currently being edited, even if
468 it's pending encryption. This may expose the current topic on the
469 file sytem, but avoids the nuisance of prompts for the encryption
470 passphrase in the middle of editing for, eg, autosaves.
471 This mode is used for auto-saves for both this option and \"Yes\".
472 - No: leave it to the user to encrypt any unencrypted topics.
473
474 For practical reasons, auto-saves always use the 'except-current policy
475 when auto-encryption is enabled. \(Otherwise, spurious passphrase prompts
476 and unavoidable timing collisions are too disruptive.) If security for a
477 file requires that even the current topic is never auto-saved in the clear,
478 disable auto-saves for that file."
479
480 :type '(choice (const :tag "Yes" t)
481 (const :tag "All except current topic" except-current)
482 (const :tag "No" nil))
483 :group 'allout)
484 (make-variable-buffer-local 'allout-encrypt-unencrypted-on-saves)
485
486 ;;;_ + Miscellaneous customization
487
488 ;;;_ = allout-command-prefix
489 (defcustom allout-command-prefix "\C-c "
490 "*Key sequence to be used as prefix for outline mode command key bindings.
491
492 Default is '\C-c<space>'; just '\C-c' is more short-and-sweet, if you're
493 willing to let allout use a bunch of \C-c keybindings."
494 :type 'string
495 :group 'allout)
496
497 ;;;_ = allout-keybindings-list
498 ;;; You have to reactivate allout-mode - `(allout-mode t)' - to
499 ;;; institute changes to this var.
500 (defvar allout-keybindings-list ()
501 "*List of `allout-mode' key / function bindings, for `allout-mode-map'.
502
503 String or vector key will be prefaced with `allout-command-prefix',
504 unless optional third, non-nil element is present.")
505 (setq allout-keybindings-list
506 '(
507 ; Motion commands:
508 ("\C-n" allout-next-visible-heading)
509 ("\C-p" allout-previous-visible-heading)
510 ("\C-u" allout-up-current-level)
511 ("\C-f" allout-forward-current-level)
512 ("\C-b" allout-backward-current-level)
513 ("\C-a" allout-beginning-of-current-entry)
514 ("\C-e" allout-end-of-entry)
515 ; Exposure commands:
516 ("\C-i" allout-show-children)
517 ("\C-s" allout-show-current-subtree)
518 ("\C-h" allout-hide-current-subtree)
519 ("h" allout-hide-current-subtree)
520 ("\C-o" allout-show-current-entry)
521 ("!" allout-show-all)
522 ("x" allout-toggle-current-subtree-encryption)
523 ; Alteration commands:
524 (" " allout-open-sibtopic)
525 ("." allout-open-subtopic)
526 ("," allout-open-supertopic)
527 ("'" allout-shift-in)
528 (">" allout-shift-in)
529 ("<" allout-shift-out)
530 ("\C-m" allout-rebullet-topic)
531 ("*" allout-rebullet-current-heading)
532 ("#" allout-number-siblings)
533 ("\C-k" allout-kill-line t)
534 ("\C-y" allout-yank t)
535 ("\M-y" allout-yank-pop t)
536 ("\C-k" allout-kill-topic)
537 ; Miscellaneous commands:
538 ;([?\C-\ ] allout-mark-topic)
539 ("@" allout-resolve-xref)
540 ("=c" allout-copy-exposed-to-buffer)
541 ("=i" allout-indented-exposed-to-buffer)
542 ("=t" allout-latexify-exposed)
543 ("=p" allout-flatten-exposed-to-buffer)))
544
545 ;;;_ = allout-use-hanging-indents
546 (defcustom allout-use-hanging-indents t
547 "*If non-nil, topic body text auto-indent defaults to indent of the header.
548 Ie, it is indented to be just past the header prefix. This is
549 relevant mostly for use with indented-text-mode, or other situations
550 where auto-fill occurs."
551 :type 'boolean
552 :group 'allout)
553 (make-variable-buffer-local 'allout-use-hanging-indents)
554
555 ;;;_ = allout-reindent-bodies
556 (defcustom allout-reindent-bodies (if allout-use-hanging-indents
557 'text)
558 "*Non-nil enables auto-adjust of topic body hanging indent with depth shifts.
559
560 When active, topic body lines that are indented even with or beyond
561 their topic header are reindented to correspond with depth shifts of
562 the header.
563
564 A value of t enables reindent in non-programming-code buffers, ie
565 those that do not have the variable `comment-start' set. A value of
566 `force' enables reindent whether or not `comment-start' is set."
567 :type '(choice (const nil) (const t) (const text) (const force))
568 :group 'allout)
569
570 (make-variable-buffer-local 'allout-reindent-bodies)
571
572 ;;;_ = allout-enable-file-variable-adjustment
573 (defcustom allout-enable-file-variable-adjustment t
574 "*If non-nil, some allout outline actions edit Emacs local file var text.
575
576 This can range from changes to existing entries, addition of new ones,
577 and creation of a new local variables section when necessary.
578
579 Emacs file variables adjustments are also inhibited if `enable-local-variables'
580 is nil.
581
582 Operations potentially causing edits include allout encryption routines.
583 For details, see `allout-toggle-current-subtree-encryption's docstring."
584 :type 'boolean
585 :group 'allout)
586 (make-variable-buffer-local 'allout-enable-file-variable-adjustment)
587
588 ;;;_* CODE - no user customizations below.
589
590 ;;;_ #1 Internal Outline Formatting and Configuration
591 ;;;_ : Version
592 ;;;_ = allout-version
593 (defvar allout-version "2.2"
594 "Version of currently loaded outline package. \(allout.el)")
595 ;;;_ > allout-version
596 (defun allout-version (&optional here)
597 "Return string describing the loaded outline version."
598 (interactive "P")
599 (let ((msg (concat "Allout Outline Mode v " allout-version)))
600 (if here (insert msg))
601 (message "%s" msg)
602 msg))
603 ;;;_ : Mode activation (defined here because it's referenced early)
604 ;;;_ = allout-mode
605 (defvar allout-mode nil "Allout outline mode minor-mode flag.")
606 (make-variable-buffer-local 'allout-mode)
607 ;;;_ : Topic header format
608 ;;;_ = allout-regexp
609 (defvar allout-regexp ""
610 "*Regular expression to match the beginning of a heading line.
611
612 Any line whose beginning matches this regexp is considered a
613 heading. This var is set according to the user configuration vars
614 by `set-allout-regexp'.")
615 (make-variable-buffer-local 'allout-regexp)
616 ;;;_ = allout-bullets-string
617 (defvar allout-bullets-string ""
618 "A string dictating the valid set of outline topic bullets.
619
620 This var should *not* be set by the user - it is set by `set-allout-regexp',
621 and is produced from the elements of `allout-plain-bullets-string'
622 and `allout-distinctive-bullets-string'.")
623 (make-variable-buffer-local 'allout-bullets-string)
624 ;;;_ = allout-bullets-string-len
625 (defvar allout-bullets-string-len 0
626 "Length of current buffers' `allout-plain-bullets-string'.")
627 (make-variable-buffer-local 'allout-bullets-string-len)
628 ;;;_ = allout-line-boundary-regexp
629 (defvar allout-line-boundary-regexp ()
630 "`allout-regexp' with outline style beginning-of-line anchor.
631
632 This is properly set when `allout-regexp' is produced by
633 `set-allout-regexp', so that (match-beginning 2) and (match-end
634 2) delimit the prefix.")
635 (make-variable-buffer-local 'allout-line-boundary-regexp)
636 ;;;_ = allout-bob-regexp
637 (defvar allout-bob-regexp ()
638 "Like `allout-line-boundary-regexp', for headers at beginning of buffer.
639 \(match-beginning 2) and \(match-end 2) delimit the prefix.")
640 (make-variable-buffer-local 'allout-bob-regexp)
641 ;;;_ = allout-header-subtraction
642 (defvar allout-header-subtraction (1- (length allout-header-prefix))
643 "Allout-header prefix length to subtract when computing topic depth.")
644 (make-variable-buffer-local 'allout-header-subtraction)
645 ;;;_ = allout-plain-bullets-string-len
646 (defvar allout-plain-bullets-string-len (length allout-plain-bullets-string)
647 "Length of `allout-plain-bullets-string', updated by `set-allout-regexp'.")
648 (make-variable-buffer-local 'allout-plain-bullets-string-len)
649
650
651 ;;;_ X allout-reset-header-lead (header-lead)
652 (defun allout-reset-header-lead (header-lead)
653 "*Reset the leading string used to identify topic headers."
654 (interactive "sNew lead string: ")
655 (setq allout-header-prefix header-lead)
656 (setq allout-header-subtraction (1- (length allout-header-prefix)))
657 (set-allout-regexp))
658 ;;;_ X allout-lead-with-comment-string (header-lead)
659 (defun allout-lead-with-comment-string (&optional header-lead)
660 "*Set the topic-header leading string to specified string.
661
662 Useful when for encapsulating outline structure in programming
663 language comments. Returns the leading string."
664
665 (interactive "P")
666 (if (not (stringp header-lead))
667 (setq header-lead (read-string
668 "String prefix for topic headers: ")))
669 (setq allout-reindent-bodies nil)
670 (allout-reset-header-lead header-lead)
671 header-lead)
672 ;;;_ > allout-infer-header-lead ()
673 (defun allout-infer-header-lead ()
674 "Determine appropriate `allout-header-prefix'.
675
676 Works according to settings of:
677
678 `comment-start'
679 `allout-header-prefix' (default)
680 `allout-use-mode-specific-leader'
681 and `allout-mode-leaders'.
682
683 Apply this via \(re)activation of `allout-mode', rather than
684 invoking it directly."
685 (let* ((use-leader (and (boundp 'allout-use-mode-specific-leader)
686 (if (or (stringp allout-use-mode-specific-leader)
687 (memq allout-use-mode-specific-leader
688 '(allout-mode-leaders
689 comment-start
690 t)))
691 allout-use-mode-specific-leader
692 ;; Oops - garbled value, equate with effect of 't:
693 t)))
694 (leader
695 (cond
696 ((not use-leader) nil)
697 ;; Use the explicitly designated leader:
698 ((stringp use-leader) use-leader)
699 (t (or (and (memq use-leader '(t allout-mode-leaders))
700 ;; Get it from outline mode leaders?
701 (cdr (assq major-mode allout-mode-leaders)))
702 ;; ... didn't get from allout-mode-leaders...
703 (and (memq use-leader '(t comment-start))
704 comment-start
705 ;; Use comment-start, maybe tripled, and with
706 ;; underscore:
707 (concat
708 (if (string= " "
709 (substring comment-start
710 (1- (length comment-start))))
711 ;; Use comment-start, sans trailing space:
712 (substring comment-start 0 -1)
713 (concat comment-start comment-start comment-start))
714 ;; ... and append underscore, whichever:
715 "_")))))))
716 (if (not leader)
717 nil
718 (if (string= leader allout-header-prefix)
719 nil ; no change, nothing to do.
720 (setq allout-header-prefix leader)
721 allout-header-prefix))))
722 ;;;_ > allout-infer-body-reindent ()
723 (defun allout-infer-body-reindent ()
724 "Determine proper setting for `allout-reindent-bodies'.
725
726 Depends on default setting of `allout-reindent-bodies' \(which see)
727 and presence of setting for `comment-start', to tell whether the
728 file is programming code."
729 (if (and allout-reindent-bodies
730 comment-start
731 (not (eq 'force allout-reindent-bodies)))
732 (setq allout-reindent-bodies nil)))
733 ;;;_ > set-allout-regexp ()
734 (defun set-allout-regexp ()
735 "Generate proper topic-header regexp form for outline functions.
736
737 Works with respect to `allout-plain-bullets-string' and
738 `allout-distinctive-bullets-string'."
739
740 (interactive)
741 ;; Derive allout-bullets-string from user configured components:
742 (setq allout-bullets-string "")
743 (let ((strings (list 'allout-plain-bullets-string
744 'allout-distinctive-bullets-string
745 'allout-primary-bullet))
746 cur-string
747 cur-len
748 cur-char
749 index)
750 (while strings
751 (setq index 0)
752 (setq cur-len (length (setq cur-string (symbol-value (car strings)))))
753 (while (< index cur-len)
754 (setq cur-char (aref cur-string index))
755 (setq allout-bullets-string
756 (concat allout-bullets-string
757 (cond
758 ; Single dash would denote a
759 ; sequence, repeated denotes
760 ; a dash:
761 ((eq cur-char ?-) "--")
762 ; literal close-square-bracket
763 ; doesn't work right in the
764 ; expr, exclude it:
765 ((eq cur-char ?\]) "")
766 (t (regexp-quote (char-to-string cur-char))))))
767 (setq index (1+ index)))
768 (setq strings (cdr strings)))
769 )
770 ;; Derive next for repeated use in allout-pending-bullet:
771 (setq allout-plain-bullets-string-len (length allout-plain-bullets-string))
772 (setq allout-header-subtraction (1- (length allout-header-prefix)))
773 ;; Produce the new allout-regexp:
774 (setq allout-regexp (concat "\\(\\"
775 allout-header-prefix
776 "[ \t]*["
777 allout-bullets-string
778 "]\\)\\|\\"
779 allout-primary-bullet
780 "+\\|\^l"))
781 (setq allout-line-boundary-regexp
782 (concat "\\(\n\\)\\(" allout-regexp "\\)"))
783 (setq allout-bob-regexp
784 (concat "\\(\\`\\)\\(" allout-regexp "\\)"))
785 )
786 ;;;_ : Key bindings
787 ;;;_ = allout-mode-map
788 (defvar allout-mode-map nil "Keybindings for (allout) outline minor mode.")
789 ;;;_ > produce-allout-mode-map (keymap-alist &optional base-map)
790 (defun produce-allout-mode-map (keymap-list &optional base-map)
791 "Produce keymap for use as allout-mode-map, from KEYMAP-LIST.
792
793 Built on top of optional BASE-MAP, or empty sparse map if none specified.
794 See doc string for allout-keybindings-list for format of binding list."
795 (let ((map (or base-map (make-sparse-keymap)))
796 (pref (list allout-command-prefix)))
797 (mapcar (function
798 (lambda (cell)
799 (let ((add-pref (null (cdr (cdr cell))))
800 (key-suff (list (car cell))))
801 (apply 'define-key
802 (list map
803 (apply 'concat (if add-pref
804 (append pref key-suff)
805 key-suff))
806 (car (cdr cell)))))))
807 keymap-list)
808 map))
809 ;;;_ = allout-prior-bindings - being deprecated.
810 (defvar allout-prior-bindings nil
811 "Variable for use in V18, with allout-added-bindings, for
812 resurrecting, on mode deactivation, bindings that existed before
813 activation. Being deprecated.")
814 ;;;_ = allout-added-bindings - being deprecated
815 (defvar allout-added-bindings nil
816 "Variable for use in V18, with allout-prior-bindings, for
817 resurrecting, on mode deactivation, bindings that existed before
818 activation. Being deprecated.")
819 ;;;_ : Menu bar
820 (defvar allout-mode-exposure-menu)
821 (defvar allout-mode-editing-menu)
822 (defvar allout-mode-navigation-menu)
823 (defvar allout-mode-misc-menu)
824 (defun produce-allout-mode-menubar-entries ()
825 (require 'easymenu)
826 (easy-menu-define allout-mode-exposure-menu
827 allout-mode-map
828 "Allout outline exposure menu."
829 '("Exposure"
830 ["Show Entry" allout-show-current-entry t]
831 ["Show Children" allout-show-children t]
832 ["Show Subtree" allout-show-current-subtree t]
833 ["Hide Subtree" allout-hide-current-subtree t]
834 ["Hide Leaves" allout-hide-current-leaves t]
835 "----"
836 ["Show All" allout-show-all t]))
837 (easy-menu-define allout-mode-editing-menu
838 allout-mode-map
839 "Allout outline editing menu."
840 '("Headings"
841 ["Open Sibling" allout-open-sibtopic t]
842 ["Open Subtopic" allout-open-subtopic t]
843 ["Open Supertopic" allout-open-supertopic t]
844 "----"
845 ["Shift Topic In" allout-shift-in t]
846 ["Shift Topic Out" allout-shift-out t]
847 ["Rebullet Topic" allout-rebullet-topic t]
848 ["Rebullet Heading" allout-rebullet-current-heading t]
849 ["Number Siblings" allout-number-siblings t]
850 "----"
851 ["Toggle Topic Encryption"
852 allout-toggle-current-subtree-encryption
853 (> (allout-current-depth) 1)]))
854 (easy-menu-define allout-mode-navigation-menu
855 allout-mode-map
856 "Allout outline navigation menu."
857 '("Navigation"
858 ["Next Visible Heading" allout-next-visible-heading t]
859 ["Previous Visible Heading"
860 allout-previous-visible-heading t]
861 "----"
862 ["Up Level" allout-up-current-level t]
863 ["Forward Current Level" allout-forward-current-level t]
864 ["Backward Current Level"
865 allout-backward-current-level t]
866 "----"
867 ["Beginning of Entry"
868 allout-beginning-of-current-entry t]
869 ["End of Entry" allout-end-of-entry t]
870 ["End of Subtree" allout-end-of-current-subtree t]))
871 (easy-menu-define allout-mode-misc-menu
872 allout-mode-map
873 "Allout outlines miscellaneous bindings."
874 '("Misc"
875 ["Version" allout-version t]
876 "----"
877 ["Duplicate Exposed" allout-copy-exposed-to-buffer t]
878 ["Duplicate Exposed, numbered"
879 allout-flatten-exposed-to-buffer t]
880 ["Duplicate Exposed, indented"
881 allout-indented-exposed-to-buffer t]
882 "----"
883 ["Set Header Lead" allout-reset-header-lead t]
884 ["Set New Exposure" allout-expose-topic t])))
885 ;;;_ : Mode-Specific Variable Maintenance Utilities
886 ;;;_ = allout-mode-prior-settings
887 (defvar allout-mode-prior-settings nil
888 "Internal `allout-mode' use; settings to be resumed on mode deactivation.")
889 (make-variable-buffer-local 'allout-mode-prior-settings)
890 ;;;_ > allout-resumptions (name &optional value)
891 (defun allout-resumptions (name &optional value)
892
893 "Registers or resumes settings over `allout-mode' activation/deactivation.
894
895 First arg is NAME of variable affected. Optional second arg is list
896 containing allout-mode-specific VALUE to be imposed on named
897 variable, and to be registered. \(It's a list so you can specify
898 registrations of null values.) If no value is specified, the
899 registered value is returned (encapsulated in the list, so the caller
900 can distinguish nil vs no value), and the registration is popped
901 from the list."
902
903 (let ((on-list (assq name allout-mode-prior-settings))
904 prior-capsule ; By `capsule' i mean a list
905 ; containing a value, so we can
906 ; distinguish nil from no value.
907 )
908
909 (if value
910
911 ;; Registering:
912 (progn
913 (if on-list
914 nil ; Already preserved prior value - don't mess with it.
915 ;; Register the old value, or nil if previously unbound:
916 (setq allout-mode-prior-settings
917 (cons (list name
918 (if (boundp name) (list (symbol-value name))))
919 allout-mode-prior-settings)))
920 ; And impose the new value, locally:
921 (progn (make-local-variable name)
922 (set name (car value))))
923
924 ;; Relinquishing:
925 (if (not on-list)
926
927 ;; Oops, not registered - leave it be:
928 nil
929
930 ;; Some registration:
931 ; reestablish it:
932 (setq prior-capsule (car (cdr on-list)))
933 (if prior-capsule
934 (set name (car prior-capsule)) ; Some prior value - reestablish it.
935 (makunbound name)) ; Previously unbound - demolish var.
936 ; Remove registration:
937 (let (rebuild)
938 (while allout-mode-prior-settings
939 (if (not (eq (car allout-mode-prior-settings)
940 on-list))
941 (setq rebuild
942 (cons (car allout-mode-prior-settings)
943 rebuild)))
944 (setq allout-mode-prior-settings
945 (cdr allout-mode-prior-settings)))
946 (setq allout-mode-prior-settings rebuild)))))
947 )
948 ;;;_ : Mode-specific incidentals
949 ;;;_ > allout-unprotected (expr)
950 (defmacro allout-unprotected (expr)
951 "Enable internal outline operations to alter invisible text."
952 `(let ((inhibit-read-only t))
953 ,expr))
954 ;;;_ = allout-mode-hook
955 (defvar allout-mode-hook nil
956 "*Hook that's run when allout mode starts.")
957 ;;;_ = allout-overlay-category
958 (defvar allout-overlay-category nil
959 "Symbol for use in allout invisible-text overlays as the category.")
960 ;;;_ = allout-view-change-hook
961 (defvar allout-view-change-hook nil
962 "*Hook that's run after allout outline visibility changes.")
963
964 ;;;_ = allout-outside-normal-auto-fill-function
965 (defvar allout-outside-normal-auto-fill-function nil
966 "Value of normal-auto-fill-function outside of allout mode.
967
968 Used by allout-auto-fill to do the mandated normal-auto-fill-function
969 wrapped within allout's automatic fill-prefix setting.")
970 (make-variable-buffer-local 'allout-outside-normal-auto-fill-function)
971 ;;;_ = file-var-bug hack
972 (defvar allout-v18/19-file-var-hack nil
973 "Horrible hack used to prevent invalid multiple triggering of outline
974 mode from prop-line file-var activation. Used by `allout-mode' function
975 to track repeats.")
976 ;;;_ = allout-file-passphrase-verifier-string
977 (defvar allout-file-passphrase-verifier-string nil
978 "Name for use as a file variable for verifying encryption passphrase
979 across sessions.")
980 (make-variable-buffer-local 'allout-file-passphrase-verifier-string)
981 ;;;_ = allout-passphrase-verifier-string
982 (defvar allout-passphrase-verifier-string nil
983 "Setting used to test solicited encryption passphrases against the one
984 already associated with a file.
985
986 It consists of an encrypted random string useful only to verify that a
987 passphrase entered by the user is effective for decryption. The passphrase
988 itself is \*not* recorded in the file anywhere, and the encrypted contents
989 are random binary characters to avoid exposing greater susceptibility to
990 search attacks.
991
992 The verifier string is retained as an Emacs file variable, as well as in
993 the emacs buffer state, if file variable adjustments are enabled. See
994 `allout-enable-file-variable-adjustment' for details about that.")
995 (make-variable-buffer-local 'allout-passphrase-verifier-string)
996 ;;;_ = allout-passphrase-hint-string
997 (defvar allout-passphrase-hint-string ""
998 "Variable used to retain reminder string for file's encryption passphrase.
999
1000 See the description of `allout-passphrase-hint-handling' for details about how
1001 the reminder is deployed.
1002
1003 The hint is retained as an Emacs file variable, as well as in the emacs buffer
1004 state, if file variable adjustments are enabled. See
1005 `allout-enable-file-variable-adjustment' for details about that.")
1006 (make-variable-buffer-local 'allout-passphrase-hint-string)
1007 (setq-default allout-passphrase-hint-string "")
1008 ;;;_ = allout-after-save-decrypt
1009 (defvar allout-after-save-decrypt nil
1010 "Internal variable, is nil or has the value of two points:
1011
1012 - the location of a topic to be decrypted after saving is done
1013 - where to situate the cursor after the decryption is performed
1014
1015 This is used to decrypt the topic that was currently being edited, if it
1016 was encrypted automatically as part of a file write or autosave.")
1017 (make-variable-buffer-local 'allout-after-save-decrypt)
1018 ;;;_ > allout-mode-p ()
1019 ;; Must define this macro above any uses, or byte compilation will lack
1020 ;; proper def, if file isn't loaded - eg, during emacs build!
1021 (defmacro allout-mode-p ()
1022 "Return t if `allout-mode' is active in current buffer."
1023 'allout-mode)
1024 ;;;_ > allout-write-file-hook-handler ()
1025 (defun allout-write-file-hook-handler ()
1026 "Implement `allout-encrypt-unencrypted-on-saves' policy for file writes."
1027
1028 (if (or (not (allout-mode-p))
1029 (not (boundp 'allout-encrypt-unencrypted-on-saves))
1030 (not allout-encrypt-unencrypted-on-saves))
1031 nil
1032 (let ((except-mark (and (equal allout-encrypt-unencrypted-on-saves
1033 'except-current)
1034 (point-marker))))
1035 (if (save-excursion (goto-char (point-min))
1036 (allout-next-topic-pending-encryption except-mark))
1037 (progn
1038 (message "auto-encrypting pending topics")
1039 (sit-for 0)
1040 (condition-case failure
1041 (setq allout-after-save-decrypt
1042 (allout-encrypt-decrypted except-mark))
1043 (error (progn
1044 (message
1045 "allout-write-file-hook-handler suppressing error %s"
1046 failure)
1047 (sit-for 2))))))
1048 ))
1049 nil)
1050 ;;;_ > allout-auto-save-hook-handler ()
1051 (defun allout-auto-save-hook-handler ()
1052 "Implement `allout-encrypt-unencrypted-on-saves' policy for auto save."
1053
1054 (if (and (allout-mode-p) allout-encrypt-unencrypted-on-saves)
1055 ;; Always implement 'except-current policy when enabled.
1056 (let ((allout-encrypt-unencrypted-on-saves 'except-current))
1057 (allout-write-file-hook-handler))))
1058 ;;;_ > allout-after-saves-handler ()
1059 (defun allout-after-saves-handler ()
1060 "Decrypt topic encrypted for save, if it's currently being edited.
1061
1062 Ie, if it was pending encryption and contained the point in its body before
1063 the save.
1064
1065 We use values stored in `allout-after-save-decrypt' to locate the topic
1066 and the place for the cursor after the decryption is done."
1067 (if (not (and (allout-mode-p)
1068 (boundp 'allout-after-save-decrypt)
1069 allout-after-save-decrypt))
1070 t
1071 (goto-char (car allout-after-save-decrypt))
1072 (let ((was-modified (buffer-modified-p)))
1073 (allout-toggle-subtree-encryption)
1074 (if (not was-modified)
1075 (set-buffer-modified-p nil)))
1076 (goto-char (cadr allout-after-save-decrypt))
1077 (setq allout-after-save-decrypt nil))
1078 )
1079
1080 ;;;_ #2 Mode activation
1081 ;;;_ = allout-explicitly-deactivated
1082 (defvar allout-explicitly-deactivated nil
1083 "If t, `allout-mode's last deactivation was deliberate.
1084 So `allout-post-command-business' should not reactivate it...")
1085 (make-variable-buffer-local 'allout-explicitly-deactivated)
1086 ;;;_ > allout-init (&optional mode)
1087 (defun allout-init (&optional mode)
1088 "Prime `allout-mode' to enable/disable auto-activation, wrt `allout-layout'.
1089
1090 MODE is one of the following symbols:
1091
1092 - nil \(or no argument) deactivate auto-activation/layout;
1093 - `activate', enable auto-activation only;
1094 - `ask', enable auto-activation, and enable auto-layout but with
1095 confirmation for layout operation solicited from user each time;
1096 - `report', just report and return the current auto-activation state;
1097 - anything else \(eg, t) for auto-activation and auto-layout, without
1098 any confirmation check.
1099
1100 Use this function to setup your Emacs session for automatic activation
1101 of allout outline mode, contingent to the buffer-specific setting of
1102 the `allout-layout' variable. (See `allout-layout' and
1103 `allout-expose-topic' docstrings for more details on auto layout).
1104
1105 `allout-init' works by setting up (or removing) the `allout-mode'
1106 find-file-hook, and giving `allout-auto-activation' a suitable
1107 setting.
1108
1109 To prime your Emacs session for full auto-outline operation, include
1110 the following two lines in your Emacs init file:
1111
1112 \(require 'allout)
1113 \(allout-init t)"
1114
1115 (interactive)
1116 (if (interactive-p)
1117 (progn
1118 (setq mode
1119 (completing-read
1120 (concat "Select outline auto setup mode "
1121 "(empty for report, ? for options) ")
1122 '(("nil")("full")("activate")("deactivate")
1123 ("ask") ("report") (""))
1124 nil
1125 t))
1126 (if (string= mode "")
1127 (setq mode 'report)
1128 (setq mode (intern-soft mode)))))
1129 (let
1130 ;; convenience aliases, for consistent ref to respective vars:
1131 ((hook 'allout-find-file-hook)
1132 (find-file-hook-var-name (if (boundp 'find-file-hook)
1133 'find-file-hook
1134 'find-file-hooks))
1135 (curr-mode 'allout-auto-activation))
1136
1137 (cond ((not mode)
1138 (set find-file-hook-var-name
1139 (delq hook (symbol-value find-file-hook-var-name)))
1140 (if (interactive-p)
1141 (message "Allout outline mode auto-activation inhibited.")))
1142 ((eq mode 'report)
1143 (if (not (memq hook (symbol-value find-file-hook-var-name)))
1144 (allout-init nil)
1145 ;; Just punt and use the reports from each of the modes:
1146 (allout-init (symbol-value curr-mode))))
1147 (t (add-hook find-file-hook-var-name hook)
1148 (set curr-mode ; `set', not `setq'!
1149 (cond ((eq mode 'activate)
1150 (message
1151 "Outline mode auto-activation enabled.")
1152 'activate)
1153 ((eq mode 'report)
1154 ;; Return the current mode setting:
1155 (allout-init mode))
1156 ((eq mode 'ask)
1157 (message
1158 (concat "Outline mode auto-activation and "
1159 "-layout \(upon confirmation) enabled."))
1160 'ask)
1161 ((message
1162 "Outline mode auto-activation and -layout enabled.")
1163 'full)))))))
1164 ;;;_ > allout-setup-menubar ()
1165 (defun allout-setup-menubar ()
1166 "Populate the current buffer's menubar with `allout-mode' stuff."
1167 (let ((menus (list allout-mode-exposure-menu
1168 allout-mode-editing-menu
1169 allout-mode-navigation-menu
1170 allout-mode-misc-menu))
1171 cur)
1172 (while menus
1173 (setq cur (car menus)
1174 menus (cdr menus))
1175 (easy-menu-add cur))))
1176 ;;;_ > allout-set-overlay-category
1177 (defun allout-set-overlay-category ()
1178 "Set the properties of the allout invisible-text overlay."
1179 (setplist 'allout-overlay-category nil)
1180 (put 'allout-overlay-category 'invisible 'allout)
1181 (put 'allout-overlay-category 'evaporate t)
1182 ;; XXX We use isearch-open-invisible *and* isearch-mode-end-hook. The
1183 ;; latter would be sufficient, but it seems that a separate behavior -
1184 ;; the _transient_ opening of invisible text during isearch - is keyed to
1185 ;; presence of the isearch-open-invisible property - even though this
1186 ;; property controls the isearch _arrival_ behavior. This is the case at
1187 ;; least in emacs 21, 22.0, and xemacs 21.4.
1188 (put 'allout-overlay-category 'isearch-open-invisible
1189 'allout-isearch-end-handler)
1190 (if (featurep 'xemacs)
1191 (put 'allout-overlay-category 'start-open t)
1192 (put 'allout-overlay-category 'insert-in-front-hooks
1193 '(allout-overlay-insert-in-front-handler)))
1194 (if (featurep 'xemacs)
1195 (progn (make-variable-buffer-local 'before-change-functions)
1196 (add-hook 'before-change-functions
1197 'allout-before-change-handler))
1198 (put 'allout-overlay-category 'modification-hooks
1199 '(allout-overlay-interior-modification-handler))))
1200 ;;;_ > allout-mode (&optional toggle)
1201 ;;;_ : Defun:
1202 ;;;###autoload
1203 (defun allout-mode (&optional toggle)
1204 ;;;_ . Doc string:
1205 "Toggle minor mode for controlling exposure and editing of text outlines.
1206 \\<allout-mode-map>
1207
1208 Optional arg forces mode to re-initialize iff arg is positive num or
1209 symbol. Allout outline mode always runs as a minor mode.
1210
1211 Allout outline mode provides extensive outline oriented formatting and
1212 manipulation. It enables structural editing of outlines, as well as
1213 navigation and exposure. It also is specifically aimed at
1214 accommodating syntax-sensitive text like programming languages. \(For
1215 an example, see the allout code itself, which is organized as an allout
1216 outline.)
1217
1218 In addition to outline navigation and exposure, allout includes:
1219
1220 - topic-oriented repositioning, promotion/demotion, cut, and paste
1221 - integral outline exposure-layout
1222 - incremental search with dynamic exposure and reconcealment of hidden text
1223 - automatic topic-number maintenance
1224 - easy topic encryption and decryption
1225 - \"Hot-spot\" operation, for single-keystroke maneuvering and
1226 exposure control. \(See the allout-mode docstring.)
1227
1228 and many other features.
1229
1230 Below is a description of the bindings, and then explanation of
1231 special `allout-mode' features and terminology. See also the outline
1232 menubar additions for quick reference to many of the features, and see
1233 the docstring of the function `allout-init' for instructions on
1234 priming your emacs session for automatic activation of `allout-mode'.
1235
1236
1237 The bindings are dictated by the `allout-keybindings-list' and
1238 `allout-command-prefix' variables.
1239
1240 Navigation: Exposure Control:
1241 ---------- ----------------
1242 \\[allout-next-visible-heading] allout-next-visible-heading | \\[allout-hide-current-subtree] allout-hide-current-subtree
1243 \\[allout-previous-visible-heading] allout-previous-visible-heading | \\[allout-show-children] allout-show-children
1244 \\[allout-up-current-level] allout-up-current-level | \\[allout-show-current-subtree] allout-show-current-subtree
1245 \\[allout-forward-current-level] allout-forward-current-level | \\[allout-show-current-entry] allout-show-current-entry
1246 \\[allout-backward-current-level] allout-backward-current-level | \\[allout-show-all] allout-show-all
1247 \\[allout-end-of-entry] allout-end-of-entry
1248 \\[allout-beginning-of-current-entry] allout-beginning-of-current-entry, alternately, goes to hot-spot
1249
1250 Topic Header Production:
1251 -----------------------
1252 \\[allout-open-sibtopic] allout-open-sibtopic Create a new sibling after current topic.
1253 \\[allout-open-subtopic] allout-open-subtopic ... an offspring of current topic.
1254 \\[allout-open-supertopic] allout-open-supertopic ... a sibling of the current topic's parent.
1255
1256 Topic Level and Prefix Adjustment:
1257 ---------------------------------
1258 \\[allout-shift-in] allout-shift-in Shift current topic and all offspring deeper.
1259 \\[allout-shift-out] allout-shift-out ... less deep.
1260 \\[allout-rebullet-current-heading] allout-rebullet-current-heading Prompt for alternate bullet for
1261 current topic.
1262 \\[allout-rebullet-topic] allout-rebullet-topic Reconcile bullets of topic and its offspring
1263 - distinctive bullets are not changed, others
1264 alternated according to nesting depth.
1265 \\[allout-number-siblings] allout-number-siblings Number bullets of topic and siblings - the
1266 offspring are not affected. With repeat
1267 count, revoke numbering.
1268
1269 Topic-oriented Killing and Yanking:
1270 ----------------------------------
1271 \\[allout-kill-topic] allout-kill-topic Kill current topic, including offspring.
1272 \\[allout-kill-line] allout-kill-line Like kill-line, but reconciles numbering, etc.
1273 \\[allout-yank] allout-yank Yank, adjusting depth of yanked topic to
1274 depth of heading if yanking into bare topic
1275 heading (ie, prefix sans text).
1276 \\[allout-yank-pop] allout-yank-pop Is to allout-yank as yank-pop is to yank
1277
1278 Topic-oriented Encryption:
1279 -------------------------
1280 \\[allout-toggle-current-subtree-encryption] allout-toggle-current-subtree-encryption Encrypt/Decrypt topic content
1281
1282 Misc commands:
1283 -------------
1284 M-x outlineify-sticky Activate outline mode for current buffer,
1285 and establish a default file-var setting
1286 for `allout-layout'.
1287 \\[allout-mark-topic] allout-mark-topic
1288 \\[allout-copy-exposed-to-buffer] allout-copy-exposed-to-buffer
1289 Duplicate outline, sans concealed text, to
1290 buffer with name derived from derived from that
1291 of current buffer - \"*BUFFERNAME exposed*\".
1292 \\[allout-flatten-exposed-to-buffer] allout-flatten-exposed-to-buffer
1293 Like above 'copy-exposed', but convert topic
1294 prefixes to section.subsection... numeric
1295 format.
1296 \\[eval-expression] (allout-init t) Setup Emacs session for outline mode
1297 auto-activation.
1298
1299 Topic Encryption
1300
1301 Outline mode supports gpg encryption of topics, with support for
1302 symmetric and key-pair modes, passphrase timeout, passphrase
1303 consistency checking, user-provided hinting for symmetric key
1304 mode, and auto-encryption of topics pending encryption on save.
1305 \(Topics pending encryption are, by default, automatically
1306 encrypted during file saves; if you're editing the contents of
1307 such a topic, it is automatically decrypted for continued
1308 editing.) The aim is reliable topic privacy while preventing
1309 accidents like neglected encryption before saves, forgetting
1310 which passphrase was used, and other practical pitfalls.
1311
1312 See `allout-toggle-current-subtree-encryption' function docstring and
1313 `allout-encrypt-unencrypted-on-saves' customization variable for details.
1314
1315 HOT-SPOT Operation
1316
1317 Hot-spot operation provides a means for easy, single-keystroke outline
1318 navigation and exposure control.
1319
1320 When the text cursor is positioned directly on the bullet character of
1321 a topic, regular characters (a to z) invoke the commands of the
1322 corresponding allout-mode keymap control chars. For example, \"f\"
1323 would invoke the command typically bound to \"C-c<space>C-f\"
1324 \(\\[allout-forward-current-level] `allout-forward-current-level').
1325
1326 Thus, by positioning the cursor on a topic bullet, you can
1327 execute the outline navigation and manipulation commands with a
1328 single keystroke. Regular navigation keys (eg, \\[forward-char], \\[next-line]) never get
1329 this special translation, so you can use them to get out of the
1330 hot-spot and back to normal operation.
1331
1332 Note that the command `allout-beginning-of-current-entry' \(\\[allout-beginning-of-current-entry]\)
1333 will move to the hot-spot when the cursor is already located at the
1334 beginning of the current entry, so you usually can hit \\[allout-beginning-of-current-entry]
1335 twice in a row to get to the hot-spot.
1336
1337 Terminology
1338
1339 Topic hierarchy constituents - TOPICS and SUBTOPICS:
1340
1341 TOPIC: A basic, coherent component of an Emacs outline. It can
1342 contain and be contained by other topics.
1343 CURRENT topic:
1344 The visible topic most immediately containing the cursor.
1345 DEPTH: The degree of nesting of a topic; it increases with
1346 containment. Also called the:
1347 LEVEL: The same as DEPTH.
1348
1349 ANCESTORS:
1350 The topics that contain a topic.
1351 PARENT: A topic's immediate ancestor. It has a depth one less than
1352 the topic.
1353 OFFSPRING:
1354 The topics contained by a topic;
1355 SUBTOPIC:
1356 An immediate offspring of a topic;
1357 CHILDREN:
1358 The immediate offspring of a topic.
1359 SIBLINGS:
1360 Topics having the same parent and depth.
1361
1362 Topic text constituents:
1363
1364 HEADER: The first line of a topic, include the topic PREFIX and header
1365 text.
1366 PREFIX: The leading text of a topic which distinguishes it from normal
1367 text. It has a strict form, which consists of a prefix-lead
1368 string, padding, and a bullet. The bullet may be followed by a
1369 number, indicating the ordinal number of the topic among its
1370 siblings, a space, and then the header text.
1371
1372 The relative length of the PREFIX determines the nesting depth
1373 of the topic.
1374 PREFIX-LEAD:
1375 The string at the beginning of a topic prefix, normally a `.'.
1376 It can be customized by changing the setting of
1377 `allout-header-prefix' and then reinitializing `allout-mode'.
1378
1379 By setting the prefix-lead to the comment-string of a
1380 programming language, you can embed outline structuring in
1381 program code without interfering with the language processing
1382 of that code. See `allout-use-mode-specific-leader'
1383 docstring for more detail.
1384 PREFIX-PADDING:
1385 Spaces or asterisks which separate the prefix-lead and the
1386 bullet, determining the depth of the topic.
1387 BULLET: A character at the end of the topic prefix, it must be one of
1388 the characters listed on `allout-plain-bullets-string' or
1389 `allout-distinctive-bullets-string'. (See the documentation
1390 for these variables for more details.) The default choice of
1391 bullet when generating topics varies in a cycle with the depth of
1392 the topic.
1393 ENTRY: The text contained in a topic before any offspring.
1394 BODY: Same as ENTRY.
1395
1396
1397 EXPOSURE:
1398 The state of a topic which determines the on-screen visibility
1399 of its offspring and contained text.
1400 CONCEALED:
1401 Topics and entry text whose display is inhibited. Contiguous
1402 units of concealed text is represented by `...' ellipses.
1403
1404 Concealed topics are effectively collapsed within an ancestor.
1405 CLOSED: A topic whose immediate offspring and body-text is concealed.
1406 OPEN: A topic that is not closed, though its offspring or body may be."
1407 ;;;_ . Code
1408 (interactive "P")
1409
1410 (let* ((active (and (not (equal major-mode 'outline))
1411 (allout-mode-p)))
1412 ; Massage universal-arg `toggle' val:
1413 (toggle (and toggle
1414 (or (and (listp toggle)(car toggle))
1415 toggle)))
1416 ; Activation specifically demanded?
1417 (explicit-activation (and toggle
1418 (or (symbolp toggle)
1419 (and (wholenump toggle)
1420 (not (zerop toggle))))))
1421 ;; allout-mode already called once during this complex command?
1422 (same-complex-command (eq allout-v18/19-file-var-hack
1423 (car command-history)))
1424 (write-file-hook-var-name (cond ((boundp 'write-file-functions)
1425 'write-file-functions)
1426 ((boundp 'write-file-hooks)
1427 'write-file-hooks)
1428 (t 'local-write-file-hooks)))
1429 do-layout
1430 )
1431
1432 ; See comments below re v19.18,.19 bug.
1433 (setq allout-v18/19-file-var-hack (car command-history))
1434
1435 (cond
1436
1437 ;; Provision for v19.18, 19.19 bug -
1438 ;; Emacs v 19.18, 19.19 file-var code invokes prop-line-designated
1439 ;; modes twice when file is visited. We have to avoid toggling mode
1440 ;; off on second invocation, so we detect it as best we can, and
1441 ;; skip everything.
1442 ((and same-complex-command ; Still in same complex command
1443 ; as last time `allout-mode' invoked.
1444 active ; Already activated.
1445 (not explicit-activation) ; Prop-line file-vars don't have args.
1446 (string-match "^19.1[89]" ; Bug only known to be in v19.18 and
1447 emacs-version)); 19.19.
1448 t)
1449
1450 ;; Deactivation:
1451 ((and (not explicit-activation)
1452 (or active toggle))
1453 ; Activation not explicitly
1454 ; requested, and either in
1455 ; active state or *de*activation
1456 ; specifically requested:
1457 (setq allout-explicitly-deactivated t)
1458 (if (string-match "^18\." emacs-version)
1459 ; Revoke those keys that remain
1460 ; as we set them:
1461 (let ((curr-loc (current-local-map)))
1462 (mapcar (function
1463 (lambda (cell)
1464 (if (eq (lookup-key curr-loc (car cell))
1465 (car (cdr cell)))
1466 (define-key curr-loc (car cell)
1467 (assq (car cell) allout-prior-bindings)))))
1468 allout-added-bindings)
1469 (allout-resumptions 'allout-added-bindings)
1470 (allout-resumptions 'allout-prior-bindings)))
1471
1472 (if allout-old-style-prefixes
1473 (progn
1474 (allout-resumptions 'allout-primary-bullet)
1475 (allout-resumptions 'allout-old-style-prefixes)))
1476 ;;(allout-resumptions 'selective-display)
1477 (remove-from-invisibility-spec '(allout . t))
1478 (set write-file-hook-var-name
1479 (delq 'allout-write-file-hook-handler
1480 (symbol-value write-file-hook-var-name)))
1481 (setq auto-save-hook
1482 (delq 'allout-auto-save-hook-handler
1483 auto-save-hook))
1484 (allout-resumptions 'paragraph-start)
1485 (allout-resumptions 'paragraph-separate)
1486 (allout-resumptions 'auto-fill-function)
1487 (allout-resumptions 'normal-auto-fill-function)
1488 (allout-resumptions 'allout-former-auto-filler)
1489 (setq allout-mode nil))
1490
1491 ;; Activation:
1492 ((not active)
1493 (setq allout-explicitly-deactivated nil)
1494 (if allout-old-style-prefixes
1495 (progn ; Inhibit all the fancy formatting:
1496 (allout-resumptions 'allout-primary-bullet '("*"))
1497 (allout-resumptions 'allout-old-style-prefixes '(()))))
1498
1499 (allout-set-overlay-category) ; Doesn't hurt to redo this.
1500
1501 (allout-infer-header-lead)
1502 (allout-infer-body-reindent)
1503
1504 (set-allout-regexp)
1505
1506 ; Produce map from current version
1507 ; of allout-keybindings-list:
1508 (if (boundp 'minor-mode-map-alist)
1509
1510 (progn ; V19, and maybe lucid and
1511 ; epoch, minor-mode key bindings:
1512 (setq allout-mode-map
1513 (produce-allout-mode-map allout-keybindings-list))
1514 (produce-allout-mode-menubar-entries)
1515 (fset 'allout-mode-map allout-mode-map)
1516 ; Include on minor-mode-map-alist,
1517 ; if not already there:
1518 (if (not (member '(allout-mode . allout-mode-map)
1519 minor-mode-map-alist))
1520 (setq minor-mode-map-alist
1521 (cons '(allout-mode . allout-mode-map)
1522 minor-mode-map-alist))))
1523
1524 ; V18 minor-mode key bindings:
1525 ; Stash record of added bindings
1526 ; for later revocation:
1527 (allout-resumptions 'allout-added-bindings
1528 (list allout-keybindings-list))
1529 (allout-resumptions 'allout-prior-bindings
1530 (list (current-local-map)))
1531 ; and add them:
1532 (use-local-map (produce-allout-mode-map allout-keybindings-list
1533 (current-local-map)))
1534 )
1535
1536 (add-to-invisibility-spec '(allout . t))
1537 (make-local-variable 'line-move-ignore-invisible)
1538 (setq line-move-ignore-invisible t)
1539 (add-hook 'pre-command-hook 'allout-pre-command-business)
1540 (add-hook 'post-command-hook 'allout-post-command-business)
1541 (add-hook 'isearch-mode-end-hook 'allout-isearch-end-handler)
1542 (add-hook write-file-hook-var-name 'allout-write-file-hook-handler)
1543 (add-hook 'auto-save-hook 'allout-auto-save-hook-handler)
1544 ; Custom auto-fill func, to support
1545 ; respect for topic headline,
1546 ; hanging-indents, etc:
1547 ;; Register prevailing fill func for use by allout-auto-fill:
1548 (allout-resumptions 'allout-former-auto-filler (list auto-fill-function))
1549 ;; Register allout-auto-fill to be used if filling is active:
1550 (allout-resumptions 'auto-fill-function '(allout-auto-fill))
1551 (allout-resumptions 'allout-outside-normal-auto-fill-function
1552 (list normal-auto-fill-function))
1553 (allout-resumptions 'normal-auto-fill-function '(allout-auto-fill))
1554 ;; Paragraphs are broken by topic headlines.
1555 (make-local-variable 'paragraph-start)
1556 (allout-resumptions 'paragraph-start
1557 (list (concat paragraph-start "\\|^\\("
1558 allout-regexp "\\)")))
1559 (make-local-variable 'paragraph-separate)
1560 (allout-resumptions 'paragraph-separate
1561 (list (concat paragraph-separate "\\|^\\("
1562 allout-regexp "\\)")))
1563
1564 (or (assq 'allout-mode minor-mode-alist)
1565 (setq minor-mode-alist
1566 (cons '(allout-mode " Allout") minor-mode-alist)))
1567
1568 (allout-setup-menubar)
1569
1570 (if allout-layout
1571 (setq do-layout t))
1572
1573 (run-hooks 'allout-mode-hook)
1574 (setq allout-mode t))
1575
1576 ;; Reactivation:
1577 ((setq do-layout t)
1578 (allout-infer-body-reindent))
1579 ) ; cond
1580
1581 (if (and do-layout
1582 allout-auto-activation
1583 (listp allout-layout)
1584 (and (not (eq allout-auto-activation 'activate))
1585 (if (eq allout-auto-activation 'ask)
1586 (if (y-or-n-p (format "Expose %s with layout '%s'? "
1587 (buffer-name)
1588 allout-layout))
1589 t
1590 (message "Skipped %s layout." (buffer-name))
1591 nil)
1592 t)))
1593 (save-excursion
1594 (message "Adjusting '%s' exposure..." (buffer-name))
1595 (goto-char 0)
1596 (allout-this-or-next-heading)
1597 (condition-case err
1598 (progn
1599 (apply 'allout-expose-topic (list allout-layout))
1600 (message "Adjusting '%s' exposure... done." (buffer-name)))
1601 ;; Problem applying exposure - notify user, but don't
1602 ;; interrupt, eg, file visit:
1603 (error (message "%s" (car (cdr err)))
1604 (sit-for 1)))))
1605 allout-mode
1606 ) ; let*
1607 ) ; defun
1608 ;;;_ > allout-minor-mode
1609 (defalias 'allout-minor-mode 'allout-mode)
1610
1611 ;;;_ > allout-overlay-insert-in-front-handler (ol after beg end
1612 ;;; &optional prelen)
1613 (defun allout-overlay-insert-in-front-handler (ol after beg end
1614 &optional prelen)
1615 "Shift the overlay so stuff inserted in front of it are excluded."
1616 (if after
1617 (move-overlay ol (1+ beg) (overlay-end ol))))
1618 ;;;_ > allout-overlay-interior-modification-handler (ol after beg end
1619 ;;; &optional prelen)
1620 (defun allout-overlay-interior-modification-handler (ol after beg end
1621 &optional prelen)
1622 "Get confirmation before making arbitrary changes to invisible text.
1623
1624 We expose the invisible text and ask for confirmation. Refusal or
1625 keyboard-quit abandons the changes, with keyboard-quit additionally
1626 reclosing the opened text.
1627
1628 No confirmation is necessary when inhibit-read-only is set - eg, allout
1629 internal functions use this feature cohesively bunch changes."
1630
1631 (when (and (not inhibit-read-only) (not after))
1632 (let ((start (point))
1633 (ol-start (overlay-start ol))
1634 (ol-end (overlay-end ol))
1635 (msg "Change within concealed text disallowed.")
1636 opened
1637 first)
1638 (goto-char beg)
1639 (while (< (point) end)
1640 (when (allout-hidden-p)
1641 (allout-show-to-offshoot)
1642 (if (allout-hidden-p)
1643 (save-excursion (forward-char 1)
1644 (allout-show-to-offshoot)))
1645 (when (not first)
1646 (setq opened t)
1647 (setq first (point))))
1648 (goto-char (if (featurep 'xemacs)
1649 (next-property-change (1+ (point)) nil end)
1650 (next-char-property-change (1+ (point)) end))))
1651 (when first
1652 (goto-char first)
1653 (condition-case nil
1654 (if (not
1655 (yes-or-no-p
1656 (substitute-command-keys
1657 (concat "Modify this concealed text? (\"no\" aborts,"
1658 " \\[keyboard-quit] also reconceals) "))))
1659 (progn (goto-char start)
1660 (error "Concealed-text change refused.")))
1661 (quit (allout-flag-region ol-start ol-end nil)
1662 (allout-flag-region ol-start ol-end t)
1663 (error "Concealed-text change abandoned, text reconcealed."))))
1664 (goto-char start))))
1665 ;;;_ > allout-before-change-handler (beg end)
1666 (defun allout-before-change-handler (beg end)
1667 "Protect against changes to invisible text.
1668
1669 See allout-overlay-interior-modification-handler for details.
1670
1671 This before-change handler is used only where modification-hooks
1672 overlay property is not supported."
1673 (if (not allout-mode)
1674 nil
1675 (allout-overlay-interior-modification-handler nil nil beg end nil)))
1676 ;;;_ > allout-isearch-end-handler (&optional overlay)
1677 (defun allout-isearch-end-handler (&optional overlay)
1678 "Reconcile allout outline exposure on arriving in hidden text after isearch.
1679
1680 Optional OVERLAY parameter is for when this function is used by
1681 `isearch-open-invisible' overlay property. It is otherwise unused, so this
1682 function can also be used as an `isearch-mode-end-hook'."
1683
1684 (if (and (allout-mode-p) (allout-hidden-p))
1685 (allout-show-to-offshoot)))
1686
1687 ;;;_ #3 Internal Position State-Tracking - "allout-recent-*" funcs
1688 ;;; All the basic outline functions that directly do string matches to
1689 ;;; evaluate heading prefix location set the variables
1690 ;;; `allout-recent-prefix-beginning' and `allout-recent-prefix-end'
1691 ;;; when successful. Functions starting with `allout-recent-' all
1692 ;;; use this state, providing the means to avoid redundant searches
1693 ;;; for just-established data. This optimization can provide
1694 ;;; significant speed improvement, but it must be employed carefully.
1695 ;;;_ = allout-recent-prefix-beginning
1696 (defvar allout-recent-prefix-beginning 0
1697 "Buffer point of the start of the last topic prefix encountered.")
1698 (make-variable-buffer-local 'allout-recent-prefix-beginning)
1699 ;;;_ = allout-recent-prefix-end
1700 (defvar allout-recent-prefix-end 0
1701 "Buffer point of the end of the last topic prefix encountered.")
1702 (make-variable-buffer-local 'allout-recent-prefix-end)
1703 ;;;_ = allout-recent-end-of-subtree
1704 (defvar allout-recent-end-of-subtree 0
1705 "Buffer point last returned by `allout-end-of-current-subtree'.")
1706 (make-variable-buffer-local 'allout-recent-end-of-subtree)
1707 ;;;_ > allout-prefix-data (beg end)
1708 (defmacro allout-prefix-data (beg end)
1709 "Register allout-prefix state data - BEGINNING and END of prefix.
1710
1711 For reference by `allout-recent' funcs. Returns BEGINNING."
1712 `(setq allout-recent-prefix-end ,end
1713 allout-recent-prefix-beginning ,beg))
1714 ;;;_ > allout-recent-depth ()
1715 (defmacro allout-recent-depth ()
1716 "Return depth of last heading encountered by an outline maneuvering function.
1717
1718 All outline functions which directly do string matches to assess
1719 headings set the variables `allout-recent-prefix-beginning' and
1720 `allout-recent-prefix-end' if successful. This function uses those settings
1721 to return the current depth."
1722
1723 '(max 1 (- allout-recent-prefix-end
1724 allout-recent-prefix-beginning
1725 allout-header-subtraction)))
1726 ;;;_ > allout-recent-prefix ()
1727 (defmacro allout-recent-prefix ()
1728 "Like `allout-recent-depth', but returns text of last encountered prefix.
1729
1730 All outline functions which directly do string matches to assess
1731 headings set the variables `allout-recent-prefix-beginning' and
1732 `allout-recent-prefix-end' if successful. This function uses those settings
1733 to return the current depth."
1734 '(buffer-substring allout-recent-prefix-beginning
1735 allout-recent-prefix-end))
1736 ;;;_ > allout-recent-bullet ()
1737 (defmacro allout-recent-bullet ()
1738 "Like allout-recent-prefix, but returns bullet of last encountered prefix.
1739
1740 All outline functions which directly do string matches to assess
1741 headings set the variables `allout-recent-prefix-beginning' and
1742 `allout-recent-prefix-end' if successful. This function uses those settings
1743 to return the current depth of the most recently matched topic."
1744 '(buffer-substring (1- allout-recent-prefix-end)
1745 allout-recent-prefix-end))
1746
1747 ;;;_ #4 Navigation
1748
1749 ;;;_ - Position Assessment
1750 ;;;_ > allout-hidden-p (&optional pos)
1751 (defsubst allout-hidden-p (&optional pos)
1752 "Non-nil if the character after point is invisible."
1753 (get-char-property (or pos (point)) 'invisible))
1754 ;;;_ : Location Predicates
1755 ;;;_ > allout-on-current-heading-p ()
1756 (defun allout-on-current-heading-p ()
1757 "Return non-nil if point is on current visible topics' header line.
1758
1759 Actually, returns prefix beginning point."
1760 (save-excursion
1761 (allout-beginning-of-current-line)
1762 (and (looking-at allout-regexp)
1763 (allout-prefix-data (match-beginning 0) (match-end 0)))))
1764 ;;;_ > allout-on-heading-p ()
1765 (defalias 'allout-on-heading-p 'allout-on-current-heading-p)
1766 ;;;_ > allout-e-o-prefix-p ()
1767 (defun allout-e-o-prefix-p ()
1768 "True if point is located where current topic prefix ends, heading begins."
1769 (and (save-excursion (beginning-of-line)
1770 (looking-at allout-regexp))
1771 (= (point)(save-excursion (allout-end-of-prefix)(point)))))
1772 ;;;_ : Location attributes
1773 ;;;_ > allout-depth ()
1774 (defun allout-depth ()
1775 "Return depth of topic most immediately containing point.
1776
1777 Return zero if point is not within any topic.
1778
1779 Like `allout-current-depth', but respects hidden as well as visible topics."
1780 (save-excursion
1781 (let ((start-point (point)))
1782 (if (and (allout-goto-prefix)
1783 (not (< start-point (point))))
1784 (allout-recent-depth)
1785 (progn
1786 ;; Oops, no prefix, zero prefix data:
1787 (allout-prefix-data (point)(point))
1788 ;; ... and return 0:
1789 0)))))
1790 ;;;_ > allout-current-depth ()
1791 (defun allout-current-depth ()
1792 "Return depth of visible topic most immediately containing point.
1793
1794 Return zero if point is not within any topic."
1795 (save-excursion
1796 (if (allout-back-to-current-heading)
1797 (max 1
1798 (- allout-recent-prefix-end
1799 allout-recent-prefix-beginning
1800 allout-header-subtraction))
1801 0)))
1802 ;;;_ > allout-get-current-prefix ()
1803 (defun allout-get-current-prefix ()
1804 "Topic prefix of the current topic."
1805 (save-excursion
1806 (if (allout-goto-prefix)
1807 (allout-recent-prefix))))
1808 ;;;_ > allout-get-bullet ()
1809 (defun allout-get-bullet ()
1810 "Return bullet of containing topic (visible or not)."
1811 (save-excursion
1812 (and (allout-goto-prefix)
1813 (allout-recent-bullet))))
1814 ;;;_ > allout-current-bullet ()
1815 (defun allout-current-bullet ()
1816 "Return bullet of current (visible) topic heading, or none if none found."
1817 (condition-case nil
1818 (save-excursion
1819 (allout-back-to-current-heading)
1820 (buffer-substring (- allout-recent-prefix-end 1)
1821 allout-recent-prefix-end))
1822 ;; Quick and dirty provision, ostensibly for missing bullet:
1823 ('args-out-of-range nil))
1824 )
1825 ;;;_ > allout-get-prefix-bullet (prefix)
1826 (defun allout-get-prefix-bullet (prefix)
1827 "Return the bullet of the header prefix string PREFIX."
1828 ;; Doesn't make sense if we're old-style prefixes, but this just
1829 ;; oughtn't be called then, so forget about it...
1830 (if (string-match allout-regexp prefix)
1831 (substring prefix (1- (match-end 0)) (match-end 0))))
1832 ;;;_ > allout-sibling-index (&optional depth)
1833 (defun allout-sibling-index (&optional depth)
1834 "Item number of this prospective topic among its siblings.
1835
1836 If optional arg DEPTH is greater than current depth, then we're
1837 opening a new level, and return 0.
1838
1839 If less than this depth, ascend to that depth and count..."
1840
1841 (save-excursion
1842 (cond ((and depth (<= depth 0) 0))
1843 ((or (not depth) (= depth (allout-depth)))
1844 (let ((index 1))
1845 (while (allout-previous-sibling (allout-recent-depth) nil)
1846 (setq index (1+ index)))
1847 index))
1848 ((< depth (allout-recent-depth))
1849 (allout-ascend-to-depth depth)
1850 (allout-sibling-index))
1851 (0))))
1852 ;;;_ > allout-topic-flat-index ()
1853 (defun allout-topic-flat-index ()
1854 "Return a list indicating point's numeric section.subsect.subsubsect...
1855 Outermost is first."
1856 (let* ((depth (allout-depth))
1857 (next-index (allout-sibling-index depth))
1858 (rev-sibls nil))
1859 (while (> next-index 0)
1860 (setq rev-sibls (cons next-index rev-sibls))
1861 (setq depth (1- depth))
1862 (setq next-index (allout-sibling-index depth)))
1863 rev-sibls)
1864 )
1865
1866 ;;;_ - Navigation routines
1867 ;;;_ > allout-beginning-of-current-line ()
1868 (defun allout-beginning-of-current-line ()
1869 "Like beginning of line, but to visible text."
1870
1871 ;; XXX We would use `(move-beginning-of-line 1)', but it gets
1872 ;; stuck on some hidden newlines, eg at column 80, as of GNU Emacs 22.0.50.
1873 ;; Conversely, `beginning-of-line' can make no progress in other
1874 ;; situations. Both are necessary, in the order used below.
1875 (move-beginning-of-line 1)
1876 (beginning-of-line)
1877 (while (or (not (bolp)) (allout-hidden-p))
1878 (beginning-of-line)
1879 (if (or (allout-hidden-p) (not (bolp)))
1880 (forward-char -1))))
1881 ;;;_ > allout-end-of-current-line ()
1882 (defun allout-end-of-current-line ()
1883 "Move to the end of line, past concealed text if any."
1884 ;; XXX This is for symmetry with `allout-beginning-of-current-line' -
1885 ;; `move-end-of-line' doesn't suffer the same problem as
1886 ;; `move-beginning-of-line'.
1887 (end-of-line)
1888 (while (allout-hidden-p)
1889 (end-of-line)
1890 (if (allout-hidden-p) (forward-char 1))))
1891 ;;;_ > allout-next-heading ()
1892 (defsubst allout-next-heading ()
1893 "Move to the heading for the topic \(possibly invisible) before this one.
1894
1895 Returns the location of the heading, or nil if none found."
1896
1897 (if (and (bobp) (not (eobp)))
1898 (forward-char 1))
1899
1900 (if (re-search-forward allout-line-boundary-regexp nil 0)
1901 (allout-prefix-data ; Got valid location state - set vars:
1902 (goto-char (or (match-beginning 2)
1903 allout-recent-prefix-beginning))
1904 (or (match-end 2) allout-recent-prefix-end))))
1905 ;;;_ > allout-this-or-next-heading
1906 (defun allout-this-or-next-heading ()
1907 "Position cursor on current or next heading."
1908 ;; A throwaway non-macro that is defined after allout-next-heading
1909 ;; and usable by allout-mode.
1910 (if (not (allout-goto-prefix)) (allout-next-heading)))
1911 ;;;_ > allout-previous-heading ()
1912 (defmacro allout-previous-heading ()
1913 "Move to the prior \(possibly invisible) heading line.
1914
1915 Return the location of the beginning of the heading, or nil if not found."
1916
1917 '(if (bobp)
1918 nil
1919 (allout-goto-prefix)
1920 (if
1921 ;; searches are unbounded and return nil if failed:
1922 (or (re-search-backward allout-line-boundary-regexp nil 0)
1923 (looking-at allout-bob-regexp))
1924 (progn ; Got valid location state - set vars:
1925 (allout-prefix-data
1926 (goto-char (or (match-beginning 2)
1927 allout-recent-prefix-beginning))
1928 (or (match-end 2) allout-recent-prefix-end))))))
1929 ;;;_ > allout-get-invisibility-overlay ()
1930 (defun allout-get-invisibility-overlay ()
1931 "Return the overlay at point that dictates allout invisibility."
1932 (let ((overlays (overlays-at (point)))
1933 got)
1934 (while (and overlays (not got))
1935 (if (equal (overlay-get (car overlays) 'invisible) 'allout)
1936 (setq got (car overlays))))
1937 got))
1938 ;;;_ > allout-back-to-visible-text ()
1939 (defun allout-back-to-visible-text ()
1940 "Move to most recent prior character that is visible, and return point."
1941 (if (allout-hidden-p)
1942 (goto-char (overlay-start (allout-get-invisibility-overlay))))
1943 (point))
1944
1945 ;;;_ - Subtree Charting
1946 ;;;_ " These routines either produce or assess charts, which are
1947 ;;; nested lists of the locations of topics within a subtree.
1948 ;;;
1949 ;;; Use of charts enables efficient navigation of subtrees, by
1950 ;;; requiring only a single regexp-search based traversal, to scope
1951 ;;; out the subtopic locations. The chart then serves as the basis
1952 ;;; for assessment or adjustment of the subtree, without redundant
1953 ;;; traversal of the structure.
1954
1955 ;;;_ > allout-chart-subtree (&optional levels orig-depth prev-depth)
1956 (defun allout-chart-subtree (&optional levels orig-depth prev-depth)
1957 "Produce a location \"chart\" of subtopics of the containing topic.
1958
1959 Optional argument LEVELS specifies the depth \(relative to start
1960 depth) for the chart. Subsequent optional args are not for public
1961 use.
1962
1963 Point is left at the end of the subtree.
1964
1965 Charts are used to capture outline structure, so that outline-altering
1966 routines need assess the structure only once, and then use the chart
1967 for their elaborate manipulations.
1968
1969 Topics are entered in the chart so the last one is at the car.
1970 The entry for each topic consists of an integer indicating the point
1971 at the beginning of the topic. Charts for offspring consists of a
1972 list containing, recursively, the charts for the respective subtopics.
1973 The chart for a topics' offspring precedes the entry for the topic
1974 itself.
1975
1976 The other function parameters are for internal recursion, and should
1977 not be specified by external callers. ORIG-DEPTH is depth of topic at
1978 starting point, and PREV-DEPTH is depth of prior topic."
1979
1980 (let ((original (not orig-depth)) ; `orig-depth' set only in recursion.
1981 chart curr-depth)
1982
1983 (if original ; Just starting?
1984 ; Register initial settings and
1985 ; position to first offspring:
1986 (progn (setq orig-depth (allout-depth))
1987 (or prev-depth (setq prev-depth (1+ orig-depth)))
1988 (allout-next-heading)))
1989
1990 ;; Loop over the current levels' siblings. Besides being more
1991 ;; efficient than tail-recursing over a level, it avoids exceeding
1992 ;; the typically quite constrained Emacs max-lisp-eval-depth.
1993 ;;
1994 ;; Probably would speed things up to implement loop-based stack
1995 ;; operation rather than recursing for lower levels. Bah.
1996
1997 (while (and (not (eobp))
1998 ; Still within original topic?
1999 (< orig-depth (setq curr-depth (allout-recent-depth)))
2000 (cond ((= prev-depth curr-depth)
2001 ;; Register this one and move on:
2002 (setq chart (cons (point) chart))
2003 (if (and levels (<= levels 1))
2004 ;; At depth limit - skip sublevels:
2005 (or (allout-next-sibling curr-depth)
2006 ;; or no more siblings - proceed to
2007 ;; next heading at lesser depth:
2008 (while (and (<= curr-depth
2009 (allout-recent-depth))
2010 (allout-next-heading))))
2011 (allout-next-heading)))
2012
2013 ((and (< prev-depth curr-depth)
2014 (or (not levels)
2015 (> levels 0)))
2016 ;; Recurse on deeper level of curr topic:
2017 (setq chart
2018 (cons (allout-chart-subtree (and levels
2019 (1- levels))
2020 orig-depth
2021 curr-depth)
2022 chart))
2023 ;; ... then continue with this one.
2024 )
2025
2026 ;; ... else nil if we've ascended back to prev-depth.
2027
2028 )))
2029
2030 (if original ; We're at the last sibling on
2031 ; the original level. Position
2032 ; to the end of it:
2033 (progn (and (not (eobp)) (forward-char -1))
2034 (and (= (preceding-char) ?\n)
2035 (= (aref (buffer-substring (max 1 (- (point) 3))
2036 (point))
2037 1)
2038 ?\n)
2039 (forward-char -1))
2040 (setq allout-recent-end-of-subtree (point))))
2041
2042 chart ; (nreverse chart) not necessary,
2043 ; and maybe not preferable.
2044 ))
2045 ;;;_ > allout-chart-siblings (&optional start end)
2046 (defun allout-chart-siblings (&optional start end)
2047 "Produce a list of locations of this and succeeding sibling topics.
2048 Effectively a top-level chart of siblings. See `allout-chart-subtree'
2049 for an explanation of charts."
2050 (save-excursion
2051 (if (allout-goto-prefix)
2052 (let ((chart (list (point))))
2053 (while (allout-next-sibling)
2054 (setq chart (cons (point) chart)))
2055 (if chart (setq chart (nreverse chart)))))))
2056 ;;;_ > allout-chart-to-reveal (chart depth)
2057 (defun allout-chart-to-reveal (chart depth)
2058
2059 "Return a flat list of hidden points in subtree CHART, up to DEPTH.
2060
2061 Note that point can be left at any of the points on chart, or at the
2062 start point."
2063
2064 (let (result here)
2065 (while (and (or (eq depth t) (> depth 0))
2066 chart)
2067 (setq here (car chart))
2068 (if (listp here)
2069 (let ((further (allout-chart-to-reveal here (or (eq depth t)
2070 (1- depth)))))
2071 ;; We're on the start of a subtree - recurse with it, if there's
2072 ;; more depth to go:
2073 (if further (setq result (append further result)))
2074 (setq chart (cdr chart)))
2075 (goto-char here)
2076 (if (allout-hidden-p)
2077 (setq result (cons here result)))
2078 (setq chart (cdr chart))))
2079 result))
2080 ;;;_ X allout-chart-spec (chart spec &optional exposing)
2081 ;; (defun allout-chart-spec (chart spec &optional exposing)
2082 ;; "Not yet \(if ever) implemented.
2083
2084 ;; Produce exposure directives given topic/subtree CHART and an exposure SPEC.
2085
2086 ;; Exposure spec indicates the locations to be exposed and the prescribed
2087 ;; exposure status. Optional arg EXPOSING is an integer, with 0
2088 ;; indicating pending concealment, anything higher indicating depth to
2089 ;; which subtopic headers should be exposed, and negative numbers
2090 ;; indicating (negative of) the depth to which subtopic headers and
2091 ;; bodies should be exposed.
2092
2093 ;; The produced list can have two types of entries. Bare numbers
2094 ;; indicate points in the buffer where topic headers that should be
2095 ;; exposed reside.
2096
2097 ;; - bare negative numbers indicates that the topic starting at the
2098 ;; point which is the negative of the number should be opened,
2099 ;; including their entries.
2100 ;; - bare positive values indicate that this topic header should be
2101 ;; opened.
2102 ;; - Lists signify the beginning and end points of regions that should
2103 ;; be flagged, and the flag to employ. (For concealment: `\(\?r\)', and
2104 ;; exposure:"
2105 ;; (while spec
2106 ;; (cond ((listp spec)
2107 ;; )
2108 ;; )
2109 ;; (setq spec (cdr spec)))
2110 ;; )
2111
2112 ;;;_ - Within Topic
2113 ;;;_ > allout-goto-prefix ()
2114 (defun allout-goto-prefix ()
2115 "Put point at beginning of immediately containing outline topic.
2116
2117 Goes to most immediate subsequent topic if none immediately containing.
2118
2119 Not sensitive to topic visibility.
2120
2121 Returns the point at the beginning of the prefix, or nil if none."
2122
2123 (let (done)
2124 (while (and (not done)
2125 (search-backward "\n" nil 1))
2126 (forward-char 1)
2127 (if (looking-at allout-regexp)
2128 (setq done (allout-prefix-data (match-beginning 0)
2129 (match-end 0)))
2130 (forward-char -1)))
2131 (if (bobp)
2132 (cond ((looking-at allout-regexp)
2133 (allout-prefix-data (match-beginning 0)(match-end 0)))
2134 ((allout-next-heading))
2135 (done))
2136 done)))
2137 ;;;_ > allout-end-of-prefix ()
2138 (defun allout-end-of-prefix (&optional ignore-decorations)
2139 "Position cursor at beginning of header text.
2140
2141 If optional IGNORE-DECORATIONS is non-nil, put just after bullet,
2142 otherwise skip white space between bullet and ensuing text."
2143
2144 (if (not (allout-goto-prefix))
2145 nil
2146 (let ((match-data (match-data)))
2147 (goto-char (match-end 0))
2148 (if ignore-decorations
2149 t
2150 (while (looking-at "[0-9]") (forward-char 1))
2151 (if (and (not (eolp)) (looking-at "\\s-")) (forward-char 1)))
2152 (store-match-data match-data))
2153 ;; Reestablish where we are:
2154 (allout-current-depth)))
2155 ;;;_ > allout-current-bullet-pos ()
2156 (defun allout-current-bullet-pos ()
2157 "Return position of current \(visible) topic's bullet."
2158
2159 (if (not (allout-current-depth))
2160 nil
2161 (1- (match-end 0))))
2162 ;;;_ > allout-back-to-current-heading ()
2163 (defun allout-back-to-current-heading ()
2164 "Move to heading line of current topic, or beginning if already on the line.
2165
2166 Return value of point, unless we started outside of (before any) topics,
2167 in which case we return nil."
2168
2169 (allout-beginning-of-current-line)
2170 (if (or (allout-on-current-heading-p)
2171 (and (re-search-backward (concat "^\\(" allout-regexp "\\)")
2172 nil 'move)
2173 (progn (while (allout-hidden-p)
2174 (allout-beginning-of-current-line)
2175 (if (not (looking-at allout-regexp))
2176 (re-search-backward (concat
2177 "^\\(" allout-regexp "\\)")
2178 nil 'move)))
2179 (allout-prefix-data (match-beginning 1)
2180 (match-end 1)))))
2181 (if (interactive-p)
2182 (allout-end-of-prefix)
2183 (point))))
2184 ;;;_ > allout-back-to-heading ()
2185 (defalias 'allout-back-to-heading 'allout-back-to-current-heading)
2186 ;;;_ > allout-pre-next-prefix ()
2187 (defun allout-pre-next-prefix ()
2188 "Skip forward to just before the next heading line.
2189
2190 Returns that character position."
2191
2192 (if (re-search-forward allout-line-boundary-regexp nil 'move)
2193 (prog1 (goto-char (match-beginning 0))
2194 (allout-prefix-data (match-beginning 2)(match-end 2)))))
2195 ;;;_ > allout-end-of-subtree (&optional current include-trailing-blank)
2196 (defun allout-end-of-subtree (&optional current include-trailing-blank)
2197 "Put point at the end of the last leaf in the containing topic.
2198
2199 Optional CURRENT means put point at the end of the containing
2200 visible topic.
2201
2202 Optional INCLUDE-TRAILING-BLANK means include a trailing blank line, if
2203 any, as part of the subtree. Otherwise, that trailing blank will be
2204 excluded as delimiting whitespace between topics.
2205
2206 Returns the value of point."
2207 (interactive "P")
2208 (if current
2209 (allout-back-to-current-heading)
2210 (allout-goto-prefix))
2211 (let ((level (allout-recent-depth)))
2212 (allout-next-heading)
2213 (while (and (not (eobp))
2214 (> (allout-recent-depth) level))
2215 (allout-next-heading))
2216 (and (not (eobp)) (forward-char -1))
2217 (if (and (not include-trailing-blank) (= ?\n (preceding-char)))
2218 (forward-char -1))
2219 (setq allout-recent-end-of-subtree (point))))
2220 ;;;_ > allout-end-of-current-subtree (&optional include-trailing-blank)
2221 (defun allout-end-of-current-subtree (&optional include-trailing-blank)
2222
2223 "Put point at end of last leaf in currently visible containing topic.
2224
2225 Optional INCLUDE-TRAILING-BLANK means include a trailing blank line, if
2226 any, as part of the subtree. Otherwise, that trailing blank will be
2227 excluded as delimiting whitespace between topics.
2228
2229 Returns the value of point."
2230 (interactive)
2231 (allout-end-of-subtree t include-trailing-blank))
2232 ;;;_ > allout-beginning-of-current-entry ()
2233 (defun allout-beginning-of-current-entry ()
2234 "When not already there, position point at beginning of current topic header.
2235
2236 If already there, move cursor to bullet for hot-spot operation.
2237 \(See `allout-mode' doc string for details on hot-spot operation.)"
2238 (interactive)
2239 (let ((start-point (point)))
2240 (allout-end-of-prefix)
2241 (if (and (interactive-p)
2242 (= (point) start-point))
2243 (goto-char (allout-current-bullet-pos)))))
2244 ;;;_ > allout-end-of-entry (&optional inclusive)
2245 (defun allout-end-of-entry (&optional inclusive)
2246 "Position the point at the end of the current topics' entry.
2247
2248 Optional INCLUSIVE means also include trailing empty line, if any. When
2249 unset, whitespace between items separates them even when the items are
2250 collapsed."
2251 (interactive)
2252 (allout-pre-next-prefix)
2253 (if (and (not inclusive) (not (bobp)) (= ?\n (preceding-char)))
2254 (forward-char -1))
2255 (point))
2256 ;;;_ > allout-end-of-current-heading ()
2257 (defun allout-end-of-current-heading ()
2258 (interactive)
2259 (allout-beginning-of-current-entry)
2260 (search-forward "\n" nil t)
2261 (forward-char -1))
2262 (defalias 'allout-end-of-heading 'allout-end-of-current-heading)
2263 ;;;_ > allout-get-body-text ()
2264 (defun allout-get-body-text ()
2265 "Return the unmangled body text of the topic immediately containing point."
2266 (save-excursion
2267 (allout-end-of-prefix)
2268 (if (not (search-forward "\n" nil t))
2269 nil
2270 (backward-char 1)
2271 (let ((pre-body (point)))
2272 (if (not pre-body)
2273 nil
2274 (allout-end-of-entry t)
2275 (if (not (= pre-body (point)))
2276 (buffer-substring-no-properties (1+ pre-body) (point))))
2277 )
2278 )
2279 )
2280 )
2281
2282 ;;;_ - Depth-wise
2283 ;;;_ > allout-ascend-to-depth (depth)
2284 (defun allout-ascend-to-depth (depth)
2285 "Ascend to depth DEPTH, returning depth if successful, nil if not."
2286 (if (and (> depth 0)(<= depth (allout-depth)))
2287 (let ((last-good (point)))
2288 (while (and (< depth (allout-depth))
2289 (setq last-good (point))
2290 (allout-beginning-of-level)
2291 (allout-previous-heading)))
2292 (if (= (allout-recent-depth) depth)
2293 (progn (goto-char allout-recent-prefix-beginning)
2294 depth)
2295 (goto-char last-good)
2296 nil))
2297 (if (interactive-p) (allout-end-of-prefix))))
2298 ;;;_ > allout-ascend ()
2299 (defun allout-ascend ()
2300 "Ascend one level, returning t if successful, nil if not."
2301 (prog1
2302 (if (allout-beginning-of-level)
2303 (allout-previous-heading))
2304 (if (interactive-p) (allout-end-of-prefix))))
2305 ;;;_ > allout-descend-to-depth (depth)
2306 (defun allout-descend-to-depth (depth)
2307 "Descend to depth DEPTH within current topic.
2308
2309 Returning depth if successful, nil if not."
2310 (let ((start-point (point))
2311 (start-depth (allout-depth)))
2312 (while
2313 (and (> (allout-depth) 0)
2314 (not (= depth (allout-recent-depth))) ; ... not there yet
2315 (allout-next-heading) ; ... go further
2316 (< start-depth (allout-recent-depth)))) ; ... still in topic
2317 (if (and (> (allout-depth) 0)
2318 (= (allout-recent-depth) depth))
2319 depth
2320 (goto-char start-point)
2321 nil))
2322 )
2323 ;;;_ > allout-up-current-level (arg &optional dont-complain)
2324 (defun allout-up-current-level (arg &optional dont-complain)
2325 "Move out ARG levels from current visible topic.
2326
2327 Positions on heading line of containing topic. Error if unable to
2328 ascend that far, or nil if unable to ascend but optional arg
2329 DONT-COMPLAIN is non-nil."
2330 (interactive "p")
2331 (allout-back-to-current-heading)
2332 (let ((present-level (allout-recent-depth))
2333 (last-good (point))
2334 failed)
2335 ;; Loop for iterating arg:
2336 (while (and (> (allout-recent-depth) 1)
2337 (> arg 0)
2338 (not (bobp))
2339 (not failed))
2340 (setq last-good (point))
2341 ;; Loop for going back over current or greater depth:
2342 (while (and (not (< (allout-recent-depth) present-level))
2343 (or (allout-previous-visible-heading 1)
2344 (not (setq failed present-level)))))
2345 (setq present-level (allout-current-depth))
2346 (setq arg (- arg 1)))
2347 (if (or failed
2348 (> arg 0))
2349 (progn (goto-char last-good)
2350 (if (interactive-p) (allout-end-of-prefix))
2351 (if (not dont-complain)
2352 (error "Can't ascend past outermost level")
2353 (if (interactive-p) (allout-end-of-prefix))
2354 nil))
2355 (if (interactive-p) (allout-end-of-prefix))
2356 allout-recent-prefix-beginning)))
2357
2358 ;;;_ - Linear
2359 ;;;_ > allout-next-sibling (&optional depth backward)
2360 (defun allout-next-sibling (&optional depth backward)
2361 "Like `allout-forward-current-level', but respects invisible topics.
2362
2363 Traverse at optional DEPTH, or current depth if none specified.
2364
2365 Go backward if optional arg BACKWARD is non-nil.
2366
2367 Return depth if successful, nil otherwise."
2368
2369 (if (and backward (bobp))
2370 nil
2371 (let ((start-depth (or depth (allout-depth)))
2372 (start-point (point))
2373 last-depth)
2374 (while (and (not (if backward (bobp) (eobp)))
2375 (if backward (allout-previous-heading)
2376 (allout-next-heading))
2377 (> (setq last-depth (allout-recent-depth)) start-depth)))
2378 (if (and (not (eobp))
2379 (and (> (or last-depth (allout-depth)) 0)
2380 (= (allout-recent-depth) start-depth)))
2381 allout-recent-prefix-beginning
2382 (goto-char start-point)
2383 (if depth (allout-depth) start-depth)
2384 nil))))
2385 ;;;_ > allout-previous-sibling (&optional depth backward)
2386 (defun allout-previous-sibling (&optional depth backward)
2387 "Like `allout-forward-current-level' backwards, respecting invisible topics.
2388
2389 Optional DEPTH specifies depth to traverse, default current depth.
2390
2391 Optional BACKWARD reverses direction.
2392
2393 Return depth if successful, nil otherwise."
2394 (allout-next-sibling depth (not backward))
2395 )
2396 ;;;_ > allout-snug-back ()
2397 (defun allout-snug-back ()
2398 "Position cursor at end of previous topic.
2399
2400 Presumes point is at the start of a topic prefix."
2401 (if (or (bobp) (eobp))
2402 nil
2403 (forward-char -1))
2404 (if (or (bobp) (not (= ?\n (preceding-char))))
2405 nil
2406 (forward-char -1))
2407 (point))
2408 ;;;_ > allout-beginning-of-level ()
2409 (defun allout-beginning-of-level ()
2410 "Go back to the first sibling at this level, visible or not."
2411 (allout-end-of-level 'backward))
2412 ;;;_ > allout-end-of-level (&optional backward)
2413 (defun allout-end-of-level (&optional backward)
2414 "Go to the last sibling at this level, visible or not."
2415
2416 (let ((depth (allout-depth)))
2417 (while (allout-previous-sibling depth nil))
2418 (prog1 (allout-recent-depth)
2419 (if (interactive-p) (allout-end-of-prefix)))))
2420 ;;;_ > allout-next-visible-heading (arg)
2421 (defun allout-next-visible-heading (arg)
2422 "Move to the next ARG'th visible heading line, backward if arg is negative.
2423
2424 Move to buffer limit in indicated direction if headings are exhausted."
2425
2426 (interactive "p")
2427 (let* ((backward (if (< arg 0) (setq arg (* -1 arg))))
2428 (step (if backward -1 1))
2429 prev got)
2430
2431 (while (> arg 0) ; limit condition
2432 (while (and (not (if backward (bobp)(eobp))) ; boundary condition
2433 ;; Move, skipping over all those concealed lines:
2434 (prog1 (condition-case nil (or (line-move step) t)
2435 (error nil))
2436 (allout-beginning-of-current-line))
2437 (not (setq got (looking-at allout-regexp)))))
2438 ;; Register this got, it may be the last:
2439 (if got (setq prev got))
2440 (setq arg (1- arg)))
2441 (cond (got ; Last move was to a prefix:
2442 (allout-prefix-data (match-beginning 0) (match-end 0))
2443 (allout-end-of-prefix))
2444 (prev ; Last move wasn't, but prev was:
2445 (allout-prefix-data (match-beginning 0) (match-end 0)))
2446 ((not backward) (end-of-line) nil))))
2447 ;;;_ > allout-previous-visible-heading (arg)
2448 (defun allout-previous-visible-heading (arg)
2449 "Move to the previous heading line.
2450
2451 With argument, repeats or can move forward if negative.
2452 A heading line is one that starts with a `*' (or that `allout-regexp'
2453 matches)."
2454 (interactive "p")
2455 (allout-next-visible-heading (- arg)))
2456 ;;;_ > allout-forward-current-level (arg)
2457 (defun allout-forward-current-level (arg)
2458 "Position point at the next heading of the same level.
2459
2460 Takes optional repeat-count, goes backward if count is negative.
2461
2462 Returns resulting position, else nil if none found."
2463 (interactive "p")
2464 (let ((start-depth (allout-current-depth))
2465 (start-arg arg)
2466 (backward (> 0 arg))
2467 last-depth
2468 (last-good (point))
2469 at-boundary)
2470 (if (= 0 start-depth)
2471 (error "No siblings, not in a topic..."))
2472 (if backward (setq arg (* -1 arg)))
2473 (while (not (or (zerop arg)
2474 at-boundary))
2475 (while (and (not (if backward (bobp) (eobp)))
2476 (if backward (allout-previous-visible-heading 1)
2477 (allout-next-visible-heading 1))
2478 (> (setq last-depth (allout-recent-depth)) start-depth)))
2479 (if (and last-depth (= last-depth start-depth)
2480 (not (if backward (bobp) (eobp))))
2481 (setq last-good (point)
2482 arg (1- arg))
2483 (setq at-boundary t)))
2484 (if (and (not (eobp))
2485 (= arg 0)
2486 (and (> (or last-depth (allout-depth)) 0)
2487 (= (allout-recent-depth) start-depth)))
2488 allout-recent-prefix-beginning
2489 (goto-char last-good)
2490 (if (not (interactive-p))
2491 nil
2492 (allout-end-of-prefix)
2493 (error "Hit %s level %d topic, traversed %d of %d requested"
2494 (if backward "first" "last")
2495 (allout-recent-depth)
2496 (- (abs start-arg) arg)
2497 (abs start-arg))))))
2498 ;;;_ > allout-backward-current-level (arg)
2499 (defun allout-backward-current-level (arg)
2500 "Inverse of `allout-forward-current-level'."
2501 (interactive "p")
2502 (if (interactive-p)
2503 (let ((current-prefix-arg (* -1 arg)))
2504 (call-interactively 'allout-forward-current-level))
2505 (allout-forward-current-level (* -1 arg))))
2506
2507 ;;;_ #5 Alteration
2508
2509 ;;;_ - Fundamental
2510 ;;;_ = allout-post-goto-bullet
2511 (defvar allout-post-goto-bullet nil
2512 "Outline internal var, for `allout-pre-command-business' hot-spot operation.
2513
2514 When set, tells post-processing to reposition on topic bullet, and
2515 then unset it. Set by `allout-pre-command-business' when implementing
2516 hot-spot operation, where literal characters typed over a topic bullet
2517 are mapped to the command of the corresponding control-key on the
2518 `allout-mode-map'.")
2519 (make-variable-buffer-local 'allout-post-goto-bullet)
2520 ;;;_ > allout-post-command-business ()
2521 (defun allout-post-command-business ()
2522 "Outline `post-command-hook' function.
2523
2524 - Implement (and clear) `allout-post-goto-bullet', for hot-spot
2525 outline commands.
2526
2527 - Decrypt topic currently being edited if it was encrypted for a save."
2528
2529 ; Apply any external change func:
2530 (if (not (allout-mode-p)) ; In allout-mode.
2531 nil
2532
2533 (if (and (boundp 'allout-after-save-decrypt)
2534 allout-after-save-decrypt)
2535 (allout-after-saves-handler))
2536
2537 ;; Implement -post-goto-bullet, if set:
2538 (if (and allout-post-goto-bullet
2539 (allout-current-bullet-pos))
2540 (progn (goto-char (allout-current-bullet-pos))
2541 (setq allout-post-goto-bullet nil)))
2542 ))
2543 ;;;_ > allout-pre-command-business ()
2544 (defun allout-pre-command-business ()
2545 "Outline `pre-command-hook' function for outline buffers.
2546 Implements special behavior when cursor is on bullet character.
2547
2548 When the cursor is on the bullet character, self-insert characters are
2549 reinterpreted as the corresponding control-character in the
2550 `allout-mode-map'. The `allout-mode' `post-command-hook' insures that
2551 the cursor which has moved as a result of such reinterpretation is
2552 positioned on the bullet character of the destination topic.
2553
2554 The upshot is that you can get easy, single (ie, unmodified) key
2555 outline maneuvering operations by positioning the cursor on the bullet
2556 char. When in this mode you can use regular cursor-positioning
2557 command/keystrokes to relocate the cursor off of a bullet character to
2558 return to regular interpretation of self-insert characters."
2559
2560 (if (not (allout-mode-p))
2561 ;; Shouldn't be invoked if not in allout-mode, but just in case:
2562 nil
2563 ;; Hot-spot navigation provisions:
2564 (if (and (eq this-command 'self-insert-command)
2565 (eq (point)(allout-current-bullet-pos)))
2566 (let* ((this-key-num (cond
2567 ((numberp last-command-char)
2568 last-command-char)
2569 ;; Only xemacs has characterp.
2570 ((and (fboundp 'characterp)
2571 (apply 'characterp
2572 (list last-command-char)))
2573 (apply 'char-to-int (list last-command-char)))
2574 (t 0)))
2575 mapped-binding)
2576 (if (zerop this-key-num)
2577 nil
2578 ; Map upper-register literals
2579 ; to lower register:
2580 (if (<= 96 this-key-num)
2581 (setq this-key-num (- this-key-num 32)))
2582 ; Check if we have a literal:
2583 (if (and (<= 64 this-key-num)
2584 (>= 96 this-key-num))
2585 (setq mapped-binding
2586 (lookup-key 'allout-mode-map
2587 (concat allout-command-prefix
2588 (char-to-string (- this-key-num
2589 64))))))
2590 (if mapped-binding
2591 (setq allout-post-goto-bullet t
2592 this-command mapped-binding)))))))
2593 ;;;_ > allout-find-file-hook ()
2594 (defun allout-find-file-hook ()
2595 "Activate `allout-mode' when `allout-auto-activation', `allout-layout' non-nil.
2596
2597 See `allout-init' for setup instructions."
2598 (if (and allout-auto-activation
2599 (not (allout-mode-p))
2600 allout-layout)
2601 (allout-mode t)))
2602
2603 ;;;_ - Topic Format Assessment
2604 ;;;_ > allout-solicit-alternate-bullet (depth &optional current-bullet)
2605 (defun allout-solicit-alternate-bullet (depth &optional current-bullet)
2606
2607 "Prompt for and return a bullet char as an alternative to the current one.
2608
2609 Offer one suitable for current depth DEPTH as default."
2610
2611 (let* ((default-bullet (or (and (stringp current-bullet) current-bullet)
2612 (allout-bullet-for-depth depth)))
2613 (sans-escapes (regexp-sans-escapes allout-bullets-string))
2614 choice)
2615 (save-excursion
2616 (goto-char (allout-current-bullet-pos))
2617 (setq choice (solicit-char-in-string
2618 (format "Select bullet: %s ('%s' default): "
2619 sans-escapes
2620 default-bullet)
2621 sans-escapes
2622 t)))
2623 (message "")
2624 (if (string= choice "") default-bullet choice))
2625 )
2626 ;;;_ > allout-distinctive-bullet (bullet)
2627 (defun allout-distinctive-bullet (bullet)
2628 "True if BULLET is one of those on `allout-distinctive-bullets-string'."
2629 (string-match (regexp-quote bullet) allout-distinctive-bullets-string))
2630 ;;;_ > allout-numbered-type-prefix (&optional prefix)
2631 (defun allout-numbered-type-prefix (&optional prefix)
2632 "True if current header prefix bullet is numbered bullet."
2633 (and allout-numbered-bullet
2634 (string= allout-numbered-bullet
2635 (if prefix
2636 (allout-get-prefix-bullet prefix)
2637 (allout-get-bullet)))))
2638 ;;;_ > allout-encrypted-type-prefix (&optional prefix)
2639 (defun allout-encrypted-type-prefix (&optional prefix)
2640 "True if current header prefix bullet is for an encrypted entry \(body)."
2641 (and allout-topic-encryption-bullet
2642 (string= allout-topic-encryption-bullet
2643 (if prefix
2644 (allout-get-prefix-bullet prefix)
2645 (allout-get-bullet)))))
2646 ;;;_ > allout-bullet-for-depth (&optional depth)
2647 (defun allout-bullet-for-depth (&optional depth)
2648 "Return outline topic bullet suited to optional DEPTH, or current depth."
2649 ;; Find bullet in plain-bullets-string modulo DEPTH.
2650 (if allout-stylish-prefixes
2651 (char-to-string (aref allout-plain-bullets-string
2652 (% (max 0 (- depth 2))
2653 allout-plain-bullets-string-len)))
2654 allout-primary-bullet)
2655 )
2656
2657 ;;;_ - Topic Production
2658 ;;;_ > allout-make-topic-prefix (&optional prior-bullet
2659 (defun allout-make-topic-prefix (&optional prior-bullet
2660 new
2661 depth
2662 solicit
2663 number-control
2664 index)
2665 ;; Depth null means use current depth, non-null means we're either
2666 ;; opening a new topic after current topic, lower or higher, or we're
2667 ;; changing level of current topic.
2668 ;; Solicit dominates specified bullet-char.
2669 ;;;_ . Doc string:
2670 "Generate a topic prefix suitable for optional arg DEPTH, or current depth.
2671
2672 All the arguments are optional.
2673
2674 PRIOR-BULLET indicates the bullet of the prefix being changed, or
2675 nil if none. This bullet may be preserved (other options
2676 notwithstanding) if it is on the `allout-distinctive-bullets-string',
2677 for instance.
2678
2679 Second arg NEW indicates that a new topic is being opened after the
2680 topic at point, if non-nil. Default bullet for new topics, eg, may
2681 be set (contingent to other args) to numbered bullets if previous
2682 sibling is one. The implication otherwise is that the current topic
2683 is being adjusted - shifted or rebulleted - and we don't consider
2684 bullet or previous sibling.
2685
2686 Third arg DEPTH forces the topic prefix to that depth, regardless of
2687 the current topics' depth.
2688
2689 If SOLICIT is non-nil, then the choice of bullet is solicited from
2690 user. If it's a character, then that character is offered as the
2691 default, otherwise the one suited to the context \(according to
2692 distinction or depth) is offered. \(This overrides other options,
2693 including, eg, a distinctive PRIOR-BULLET.) If non-nil, then the
2694 context-specific bullet is used.
2695
2696 Fifth arg, NUMBER-CONTROL, matters only if `allout-numbered-bullet'
2697 is non-nil *and* soliciting was not explicitly invoked. Then
2698 NUMBER-CONTROL non-nil forces prefix to either numbered or
2699 denumbered format, depending on the value of the sixth arg, INDEX.
2700
2701 \(Note that NUMBER-CONTROL does *not* apply to level 1 topics. Sorry...)
2702
2703 If NUMBER-CONTROL is non-nil and sixth arg INDEX is non-nil then
2704 the prefix of the topic is forced to be numbered. Non-nil
2705 NUMBER-CONTROL and nil INDEX forces non-numbered format on the
2706 bullet. Non-nil NUMBER-CONTROL and non-nil, non-number INDEX means
2707 that the index for the numbered prefix will be derived, by counting
2708 siblings back to start of level. If INDEX is a number, then that
2709 number is used as the index for the numbered prefix (allowing, eg,
2710 sequential renumbering to not require this function counting back the
2711 index for each successive sibling)."
2712 ;;;_ . Code:
2713 ;; The options are ordered in likely frequence of use, most common
2714 ;; highest, least lowest. Ie, more likely to be doing prefix
2715 ;; adjustments than soliciting, and yet more than numbering.
2716 ;; Current prefix is least dominant, but most likely to be commonly
2717 ;; specified...
2718
2719 (let* (body
2720 numbering
2721 denumbering
2722 (depth (or depth (allout-depth)))
2723 (header-lead allout-header-prefix)
2724 (bullet-char
2725
2726 ;; Getting value for bullet char is practically the whole job:
2727
2728 (cond
2729 ; Simplest situation - level 1:
2730 ((<= depth 1) (setq header-lead "") allout-primary-bullet)
2731 ; Simple, too: all asterisks:
2732 (allout-old-style-prefixes
2733 ;; Cheat - make body the whole thing, null out header-lead and
2734 ;; bullet-char:
2735 (setq body (make-string depth
2736 (string-to-char allout-primary-bullet)))
2737 (setq header-lead "")
2738 "")
2739
2740 ;; (Neither level 1 nor old-style, so we're space padding.
2741 ;; Sneak it in the condition of the next case, whatever it is.)
2742
2743 ;; Solicitation overrides numbering and other cases:
2744 ((progn (setq body (make-string (- depth 2) ?\ ))
2745 ;; The actual condition:
2746 solicit)
2747 (let* ((got (allout-solicit-alternate-bullet depth solicit)))
2748 ;; Gotta check whether we're numbering and got a numbered bullet:
2749 (setq numbering (and allout-numbered-bullet
2750 (not (and number-control (not index)))
2751 (string= got allout-numbered-bullet)))
2752 ;; Now return what we got, regardless:
2753 got))
2754
2755 ;; Numbering invoked through args:
2756 ((and allout-numbered-bullet number-control)
2757 (if (setq numbering (not (setq denumbering (not index))))
2758 allout-numbered-bullet
2759 (if (and prior-bullet
2760 (not (string= allout-numbered-bullet
2761 prior-bullet)))
2762 prior-bullet
2763 (allout-bullet-for-depth depth))))
2764
2765 ;;; Neither soliciting nor controlled numbering ;;;
2766 ;;; (may be controlled denumbering, tho) ;;;
2767
2768 ;; Check wrt previous sibling:
2769 ((and new ; only check for new prefixes
2770 (<= depth (allout-depth))
2771 allout-numbered-bullet ; ... & numbering enabled
2772 (not denumbering)
2773 (let ((sibling-bullet
2774 (save-excursion
2775 ;; Locate correct sibling:
2776 (or (>= depth (allout-depth))
2777 (allout-ascend-to-depth depth))
2778 (allout-get-bullet))))
2779 (if (and sibling-bullet
2780 (string= allout-numbered-bullet sibling-bullet))
2781 (setq numbering sibling-bullet)))))
2782
2783 ;; Distinctive prior bullet?
2784 ((and prior-bullet
2785 (allout-distinctive-bullet prior-bullet)
2786 ;; Either non-numbered:
2787 (or (not (and allout-numbered-bullet
2788 (string= prior-bullet allout-numbered-bullet)))
2789 ;; or numbered, and not denumbering:
2790 (setq numbering (not denumbering)))
2791 ;; Here 'tis:
2792 prior-bullet))
2793
2794 ;; Else, standard bullet per depth:
2795 ((allout-bullet-for-depth depth)))))
2796
2797 (concat header-lead
2798 body
2799 bullet-char
2800 (if numbering
2801 (format "%d" (cond ((and index (numberp index)) index)
2802 (new (1+ (allout-sibling-index depth)))
2803 ((allout-sibling-index))))))
2804 )
2805 )
2806 ;;;_ > allout-open-topic (relative-depth &optional before offer-recent-bullet)
2807 (defun allout-open-topic (relative-depth &optional before offer-recent-bullet)
2808 "Open a new topic at depth DEPTH.
2809
2810 New topic is situated after current one, unless optional flag BEFORE
2811 is non-nil, or unless current line is completely empty - lacking even
2812 whitespace - in which case open is done on the current line.
2813
2814 When adding an offspring, it will be added immediately after the parent if
2815 the other offspring are exposed, or after the last child if the offspring
2816 are hidden. \(The intervening offspring will be exposed in the latter
2817 case.)
2818
2819 If OFFER-RECENT-BULLET is true, offer to use the bullet of the prior sibling.
2820
2821 Nuances:
2822
2823 - Creation of new topics is with respect to the visible topic
2824 containing the cursor, regardless of intervening concealed ones.
2825
2826 - New headers are generally created after/before the body of a
2827 topic. However, they are created right at cursor location if the
2828 cursor is on a blank line, even if that breaks the current topic
2829 body. This is intentional, to provide a simple means for
2830 deliberately dividing topic bodies.
2831
2832 - Double spacing of topic lists is preserved. Also, the first
2833 level two topic is created double-spaced (and so would be
2834 subsequent siblings, if that's left intact). Otherwise,
2835 single-spacing is used.
2836
2837 - Creation of sibling or nested topics is with respect to the topic
2838 you're starting from, even when creating backwards. This way you
2839 can easily create a sibling in front of the current topic without
2840 having to go to its preceding sibling, and then open forward
2841 from there."
2842
2843 (allout-beginning-of-current-line)
2844 (let* ((depth (+ (allout-current-depth) relative-depth))
2845 (opening-on-blank (if (looking-at "^\$")
2846 (not (setq before nil))))
2847 ;; bunch o vars set while computing ref-topic
2848 opening-numbered
2849 ref-depth
2850 ref-bullet
2851 (ref-topic (save-excursion
2852 (cond ((< relative-depth 0)
2853 (allout-ascend-to-depth depth))
2854 ((>= relative-depth 1) nil)
2855 (t (allout-back-to-current-heading)))
2856 (setq ref-depth (allout-recent-depth))
2857 (setq ref-bullet
2858 (if (> allout-recent-prefix-end 1)
2859 (allout-recent-bullet)
2860 ""))
2861 (setq opening-numbered
2862 (save-excursion
2863 (and allout-numbered-bullet
2864 (or (<= relative-depth 0)
2865 (allout-descend-to-depth depth))
2866 (if (allout-numbered-type-prefix)
2867 allout-numbered-bullet))))
2868 (point)))
2869 dbl-space
2870 doing-beginning)
2871
2872 (if (not opening-on-blank)
2873 ; Positioning and vertical
2874 ; padding - only if not
2875 ; opening-on-blank:
2876 (progn
2877 (goto-char ref-topic)
2878 (setq dbl-space ; Determine double space action:
2879 (or (and (<= relative-depth 0) ; not descending;
2880 (save-excursion
2881 ;; at b-o-b or preceded by a blank line?
2882 (or (> 0 (forward-line -1))
2883 (looking-at "^\\s-*$")
2884 (bobp)))
2885 (save-excursion
2886 ;; succeeded by a blank line?
2887 (allout-end-of-current-subtree)
2888 (looking-at "\n\n")))
2889 (and (= ref-depth 1)
2890 (or before
2891 (= depth 1)
2892 (save-excursion
2893 ;; Don't already have following
2894 ;; vertical padding:
2895 (not (allout-pre-next-prefix)))))))
2896
2897 ;; Position to prior heading, if inserting backwards, and not
2898 ;; going outwards:
2899 (if (and before (>= relative-depth 0))
2900 (progn (allout-back-to-current-heading)
2901 (setq doing-beginning (bobp))
2902 (if (not (bobp))
2903 (allout-previous-heading)))
2904 (if (and before (bobp))
2905 (open-line 1)))
2906
2907 (if (<= relative-depth 0)
2908 ;; Not going inwards, don't snug up:
2909 (if doing-beginning
2910 (if (not dbl-space)
2911 (open-line 1)
2912 (open-line 2))
2913 (if before
2914 (progn (end-of-line)
2915 (allout-pre-next-prefix)
2916 (while (and (= ?\n (following-char))
2917 (save-excursion
2918 (forward-char 1)
2919 (allout-hidden-p)))
2920 (forward-char 1))
2921 (if (not (looking-at "^$"))
2922 (open-line 1)))
2923 (allout-end-of-current-subtree)
2924 (if (looking-at "\n\n") (forward-char 1))))
2925 ;; Going inwards - double-space if first offspring is
2926 ;; double-spaced, otherwise snug up.
2927 (allout-end-of-entry)
2928 (line-move 1)
2929 (allout-beginning-of-current-line)
2930 (backward-char 1)
2931 (if (bolp)
2932 ;; Blank lines between current header body and next
2933 ;; header - get to last substantive (non-white-space)
2934 ;; line in body:
2935 (progn (setq dbl-space t)
2936 (re-search-backward "[^ \t\n]" nil t)))
2937 (if (looking-at "\n\n")
2938 (setq dbl-space t))
2939 (if (save-excursion
2940 (allout-next-heading)
2941 (when (> (allout-recent-depth) ref-depth)
2942 ;; This is an offspring.
2943 (forward-line -1)
2944 (looking-at "^\\s-*$")))
2945 (progn (forward-line 1)
2946 (open-line 1)
2947 (forward-line 1)))
2948 (allout-end-of-current-line))
2949
2950 ;;(if doing-beginning (goto-char doing-beginning))
2951 (if (not (bobp))
2952 ;; We insert a newline char rather than using open-line to
2953 ;; avoid rear-stickiness inheritence of read-only property.
2954 (progn (if (and (not (> depth ref-depth))
2955 (not before))
2956 (open-line 1)
2957 (if (and (not dbl-space) (> depth ref-depth))
2958 (newline 1)
2959 (if dbl-space
2960 (open-line 1)
2961 (if (not before)
2962 (newline 1)))))
2963 (if (and dbl-space (not (> relative-depth 0)))
2964 (newline 1))
2965 (if (and (not (eobp))
2966 (not (bolp)))
2967 (forward-char 1))))
2968 ))
2969 (insert (concat (allout-make-topic-prefix opening-numbered t depth)
2970 " "))
2971
2972 (allout-rebullet-heading (and offer-recent-bullet ref-bullet)
2973 depth nil nil t)
2974 (if (> relative-depth 0)
2975 (save-excursion (goto-char ref-topic)
2976 (allout-show-children)))
2977 (end-of-line)
2978 )
2979 )
2980 ;;;_ > allout-open-subtopic (arg)
2981 (defun allout-open-subtopic (arg)
2982 "Open new topic header at deeper level than the current one.
2983
2984 Negative universal arg means to open deeper, but place the new topic
2985 prior to the current one."
2986 (interactive "p")
2987 (allout-open-topic 1 (> 0 arg) (< 1 arg)))
2988 ;;;_ > allout-open-sibtopic (arg)
2989 (defun allout-open-sibtopic (arg)
2990 "Open new topic header at same level as the current one.
2991
2992 Positive universal arg means to use the bullet of the prior sibling.
2993
2994 Negative universal arg means to place the new topic prior to the current
2995 one."
2996 (interactive "p")
2997 (allout-open-topic 0 (> 0 arg) (not (= 1 arg))))
2998 ;;;_ > allout-open-supertopic (arg)
2999 (defun allout-open-supertopic (arg)
3000 "Open new topic header at shallower level than the current one.
3001
3002 Negative universal arg means to open shallower, but place the new
3003 topic prior to the current one."
3004
3005 (interactive "p")
3006 (allout-open-topic -1 (> 0 arg) (< 1 arg)))
3007
3008 ;;;_ - Outline Alteration
3009 ;;;_ : Topic Modification
3010 ;;;_ = allout-former-auto-filler
3011 (defvar allout-former-auto-filler nil
3012 "Name of modal fill function being wrapped by `allout-auto-fill'.")
3013 ;;;_ > allout-auto-fill ()
3014 (defun allout-auto-fill ()
3015 "`allout-mode' autofill function.
3016
3017 Maintains outline hanging topic indentation if
3018 `allout-use-hanging-indents' is set."
3019 (let ((fill-prefix (if allout-use-hanging-indents
3020 ;; Check for topic header indentation:
3021 (save-excursion
3022 (beginning-of-line)
3023 (if (looking-at allout-regexp)
3024 ;; ... construct indentation to account for
3025 ;; length of topic prefix:
3026 (make-string (progn (allout-end-of-prefix)
3027 (current-column))
3028 ?\ )))))
3029 (use-auto-fill-function (or allout-outside-normal-auto-fill-function
3030 auto-fill-function
3031 'do-auto-fill)))
3032 (if (or allout-former-auto-filler allout-use-hanging-indents)
3033 (funcall use-auto-fill-function))))
3034 ;;;_ > allout-reindent-body (old-depth new-depth &optional number)
3035 (defun allout-reindent-body (old-depth new-depth &optional number)
3036 "Reindent body lines which were indented at OLD-DEPTH to NEW-DEPTH.
3037
3038 Optional arg NUMBER indicates numbering is being added, and it must
3039 be accommodated.
3040
3041 Note that refill of indented paragraphs is not done."
3042
3043 (save-excursion
3044 (allout-end-of-prefix)
3045 (let* ((new-margin (current-column))
3046 excess old-indent-begin old-indent-end
3047 ;; We want the column where the header-prefix text started
3048 ;; *before* the prefix was changed, so we infer it relative
3049 ;; to the new margin and the shift in depth:
3050 (old-margin (+ old-depth (- new-margin new-depth))))
3051
3052 ;; Process lines up to (but excluding) next topic header:
3053 (allout-unprotected
3054 (save-match-data
3055 (while
3056 (and (re-search-forward "\n\\(\\s-*\\)"
3057 nil
3058 t)
3059 ;; Register the indent data, before we reset the
3060 ;; match data with a subsequent `looking-at':
3061 (setq old-indent-begin (match-beginning 1)
3062 old-indent-end (match-end 1))
3063 (not (looking-at allout-regexp)))
3064 (if (> 0 (setq excess (- (- old-indent-end old-indent-begin)
3065 old-margin)))
3066 ;; Text starts left of old margin - don't adjust:
3067 nil
3068 ;; Text was hanging at or right of old left margin -
3069 ;; reindent it, preserving its existing indentation
3070 ;; beyond the old margin:
3071 (delete-region old-indent-begin old-indent-end)
3072 (indent-to (+ new-margin excess (current-column))))))))))
3073 ;;;_ > allout-rebullet-current-heading (arg)
3074 (defun allout-rebullet-current-heading (arg)
3075 "Solicit new bullet for current visible heading."
3076 (interactive "p")
3077 (let ((initial-col (current-column))
3078 (on-bullet (eq (point)(allout-current-bullet-pos)))
3079 (backwards (if (< arg 0)
3080 (setq arg (* arg -1)))))
3081 (while (> arg 0)
3082 (save-excursion (allout-back-to-current-heading)
3083 (allout-end-of-prefix)
3084 (allout-rebullet-heading t ;;; solicit
3085 nil ;;; depth
3086 nil ;;; number-control
3087 nil ;;; index
3088 t)) ;;; do-successors
3089 (setq arg (1- arg))
3090 (if (<= arg 0)
3091 nil
3092 (setq initial-col nil) ; Override positioning back to init col
3093 (if (not backwards)
3094 (allout-next-visible-heading 1)
3095 (allout-goto-prefix)
3096 (allout-next-visible-heading -1))))
3097 (message "Done.")
3098 (cond (on-bullet (goto-char (allout-current-bullet-pos)))
3099 (initial-col (move-to-column initial-col)))))
3100 ;;;_ > allout-rebullet-heading (&optional solicit ...)
3101 (defun allout-rebullet-heading (&optional solicit
3102 new-depth
3103 number-control
3104 index
3105 do-successors)
3106
3107 "Adjust bullet of current topic prefix.
3108
3109 All args are optional.
3110
3111 If SOLICIT is non-nil, then the choice of bullet is solicited from
3112 user. If it's a character, then that character is offered as the
3113 default, otherwise the one suited to the context \(according to
3114 distinction or depth) is offered. If non-nil, then the
3115 context-specific bullet is just used.
3116
3117 Second arg DEPTH forces the topic prefix to that depth, regardless
3118 of the topic's current depth.
3119
3120 Third arg NUMBER-CONTROL can force the prefix to or away from
3121 numbered form. It has effect only if `allout-numbered-bullet' is
3122 non-nil and soliciting was not explicitly invoked (via first arg).
3123 Its effect, numbering or denumbering, then depends on the setting
3124 of the forth arg, INDEX.
3125
3126 If NUMBER-CONTROL is non-nil and forth arg INDEX is nil, then the
3127 prefix of the topic is forced to be non-numbered. Null index and
3128 non-nil NUMBER-CONTROL forces denumbering. Non-nil INDEX (and
3129 non-nil NUMBER-CONTROL) forces a numbered-prefix form. If non-nil
3130 INDEX is a number, then that number is used for the numbered
3131 prefix. Non-nil and non-number means that the index for the
3132 numbered prefix will be derived by allout-make-topic-prefix.
3133
3134 Fifth arg DO-SUCCESSORS t means re-resolve count on succeeding
3135 siblings.
3136
3137 Cf vars `allout-stylish-prefixes', `allout-old-style-prefixes',
3138 and `allout-numbered-bullet', which all affect the behavior of
3139 this function."
3140
3141 (let* ((current-depth (allout-depth))
3142 (new-depth (or new-depth current-depth))
3143 (mb allout-recent-prefix-beginning)
3144 (me allout-recent-prefix-end)
3145 (current-bullet (buffer-substring (- me 1) me))
3146 (new-prefix (allout-make-topic-prefix current-bullet
3147 nil
3148 new-depth
3149 solicit
3150 number-control
3151 index)))
3152
3153 ;; Is new one is identical to old?
3154 (if (and (= current-depth new-depth)
3155 (string= current-bullet
3156 (substring new-prefix (1- (length new-prefix)))))
3157 ;; Nothing to do:
3158 t
3159
3160 ;; New prefix probably different from old:
3161 ; get rid of old one:
3162 (allout-unprotected (delete-region mb me))
3163 (goto-char mb)
3164 ; Dispense with number if
3165 ; numbered-bullet prefix:
3166 (if (and allout-numbered-bullet
3167 (string= allout-numbered-bullet current-bullet)
3168 (looking-at "[0-9]+"))
3169 (allout-unprotected
3170 (delete-region (match-beginning 0)(match-end 0))))
3171
3172 ; Put in new prefix:
3173 (allout-unprotected (insert new-prefix))
3174
3175 ;; Reindent the body if elected, margin changed, and not encrypted body:
3176 (if (and allout-reindent-bodies
3177 (not (= new-depth current-depth))
3178 (not (allout-encrypted-topic-p)))
3179 (allout-reindent-body current-depth new-depth))
3180
3181 ;; Recursively rectify successive siblings of orig topic if
3182 ;; caller elected for it:
3183 (if do-successors
3184 (save-excursion
3185 (while (allout-next-sibling new-depth nil)
3186 (setq index
3187 (cond ((numberp index) (1+ index))
3188 ((not number-control) (allout-sibling-index))))
3189 (if (allout-numbered-type-prefix)
3190 (allout-rebullet-heading nil ;;; solicit
3191 new-depth ;;; new-depth
3192 number-control;;; number-control
3193 index ;;; index
3194 nil))))) ;;;(dont!)do-successors
3195 ) ; (if (and (= current-depth new-depth)...))
3196 ) ; let* ((current-depth (allout-depth))...)
3197 ) ; defun
3198 ;;;_ > allout-rebullet-topic (arg)
3199 (defun allout-rebullet-topic (arg)
3200 "Rebullet the visible topic containing point and all contained subtopics.
3201
3202 Descends into invisible as well as visible topics, however.
3203
3204 With repeat count, shift topic depth by that amount."
3205 (interactive "P")
3206 (let ((start-col (current-column)))
3207 (save-excursion
3208 ;; Normalize arg:
3209 (cond ((null arg) (setq arg 0))
3210 ((listp arg) (setq arg (car arg))))
3211 ;; Fill the user in, in case we're shifting a big topic:
3212 (if (not (zerop arg)) (message "Shifting..."))
3213 (allout-back-to-current-heading)
3214 (if (<= (+ (allout-recent-depth) arg) 0)
3215 (error "Attempt to shift topic below level 1"))
3216 (allout-rebullet-topic-grunt arg)
3217 (if (not (zerop arg)) (message "Shifting... done.")))
3218 (move-to-column (max 0 (+ start-col arg)))))
3219 ;;;_ > allout-rebullet-topic-grunt (&optional relative-depth ...)
3220 (defun allout-rebullet-topic-grunt (&optional relative-depth
3221 starting-depth
3222 starting-point
3223 index
3224 do-successors)
3225 "Like `allout-rebullet-topic', but on nearest containing topic
3226 \(visible or not).
3227
3228 See `allout-rebullet-heading' for rebulleting behavior.
3229
3230 All arguments are optional.
3231
3232 First arg RELATIVE-DEPTH means to shift the depth of the entire
3233 topic that amount.
3234
3235 The rest of the args are for internal recursive use by the function
3236 itself. The are STARTING-DEPTH, STARTING-POINT, and INDEX."
3237
3238 (let* ((relative-depth (or relative-depth 0))
3239 (new-depth (allout-depth))
3240 (starting-depth (or starting-depth new-depth))
3241 (on-starting-call (null starting-point))
3242 (index (or index
3243 ;; Leave index null on starting call, so rebullet-heading
3244 ;; calculates it at what might be new depth:
3245 (and (or (zerop relative-depth)
3246 (not on-starting-call))
3247 (allout-sibling-index))))
3248 (moving-outwards (< 0 relative-depth))
3249 (starting-point (or starting-point (point))))
3250
3251 ;; Sanity check for excessive promotion done only on starting call:
3252 (and on-starting-call
3253 moving-outwards
3254 (> 0 (+ starting-depth relative-depth))
3255 (error "Attempt to shift topic out beyond level 1")) ;;; ====>
3256
3257 (cond ((= starting-depth new-depth)
3258 ;; We're at depth to work on this one:
3259 (allout-rebullet-heading nil ;;; solicit
3260 (+ starting-depth ;;; starting-depth
3261 relative-depth)
3262 nil ;;; number
3263 index ;;; index
3264 ;; Every contained topic will get hit,
3265 ;; and we have to get to outside ones
3266 ;; deliberately:
3267 nil) ;;; do-successors
3268 ;; ... and work on subsequent ones which are at greater depth:
3269 (setq index 0)
3270 (allout-next-heading)
3271 (while (and (not (eobp))
3272 (< starting-depth (allout-recent-depth)))
3273 (setq index (1+ index))
3274 (allout-rebullet-topic-grunt relative-depth ;;; relative-depth
3275 (1+ starting-depth);;;starting-depth
3276 starting-point ;;; starting-point
3277 index))) ;;; index
3278
3279 ((< starting-depth new-depth)
3280 ;; Rare case - subtopic more than one level deeper than parent.
3281 ;; Treat this one at an even deeper level:
3282 (allout-rebullet-topic-grunt relative-depth ;;; relative-depth
3283 new-depth ;;; starting-depth
3284 starting-point ;;; starting-point
3285 index))) ;;; index
3286
3287 (if on-starting-call
3288 (progn
3289 ;; Rectify numbering of former siblings of the adjusted topic,
3290 ;; if topic has changed depth
3291 (if (or do-successors
3292 (and (not (zerop relative-depth))
3293 (or (= (allout-recent-depth) starting-depth)
3294 (= (allout-recent-depth) (+ starting-depth
3295 relative-depth)))))
3296 (allout-rebullet-heading nil nil nil nil t))
3297 ;; Now rectify numbering of new siblings of the adjusted topic,
3298 ;; if depth has been changed:
3299 (progn (goto-char starting-point)
3300 (if (not (zerop relative-depth))
3301 (allout-rebullet-heading nil nil nil nil t)))))
3302 )
3303 )
3304 ;;;_ > allout-renumber-to-depth (&optional depth)
3305 (defun allout-renumber-to-depth (&optional depth)
3306 "Renumber siblings at current depth.
3307
3308 Affects superior topics if optional arg DEPTH is less than current depth.
3309
3310 Returns final depth."
3311
3312 ;; Proceed by level, processing subsequent siblings on each,
3313 ;; ascending until we get shallower than the start depth:
3314
3315 (let ((ascender (allout-depth))
3316 was-eobp)
3317 (while (and (not (eobp))
3318 (allout-depth)
3319 (>= (allout-recent-depth) depth)
3320 (>= ascender depth))
3321 ; Skip over all topics at
3322 ; lesser depths, which can not
3323 ; have been disturbed:
3324 (while (and (not (setq was-eobp (eobp)))
3325 (> (allout-recent-depth) ascender))
3326 (allout-next-heading))
3327 ; Prime ascender for ascension:
3328 (setq ascender (1- (allout-recent-depth)))
3329 (if (>= (allout-recent-depth) depth)
3330 (allout-rebullet-heading nil ;;; solicit
3331 nil ;;; depth
3332 nil ;;; number-control
3333 nil ;;; index
3334 t)) ;;; do-successors
3335 (if was-eobp (goto-char (point-max)))))
3336 (allout-recent-depth))
3337 ;;;_ > allout-number-siblings (&optional denumber)
3338 (defun allout-number-siblings (&optional denumber)
3339 "Assign numbered topic prefix to this topic and its siblings.
3340
3341 With universal argument, denumber - assign default bullet to this
3342 topic and its siblings.
3343
3344 With repeated universal argument (`^U^U'), solicit bullet for each
3345 rebulleting each topic at this level."
3346
3347 (interactive "P")
3348
3349 (save-excursion
3350 (allout-back-to-current-heading)
3351 (allout-beginning-of-level)
3352 (let ((depth (allout-recent-depth))
3353 (index (if (not denumber) 1))
3354 (use-bullet (equal '(16) denumber))
3355 (more t))
3356 (while more
3357 (allout-rebullet-heading use-bullet ;;; solicit
3358 depth ;;; depth
3359 t ;;; number-control
3360 index ;;; index
3361 nil) ;;; do-successors
3362 (if index (setq index (1+ index)))
3363 (setq more (allout-next-sibling depth nil))))))
3364 ;;;_ > allout-shift-in (arg)
3365 (defun allout-shift-in (arg)
3366 "Increase depth of current heading and any topics collapsed within it.
3367
3368 We disallow shifts that would result in the topic having a depth more than
3369 one level greater than the immediately previous topic, to avoid containment
3370 discontinuity. The first topic in the file can be adjusted to any positive
3371 depth, however."
3372 (interactive "p")
3373 (if (> arg 0)
3374 (save-excursion
3375 (allout-back-to-current-heading)
3376 (if (not (bobp))
3377 (let* ((current-depth (allout-recent-depth))
3378 (start-point (point))
3379 (predecessor-depth (progn
3380 (forward-char -1)
3381 (allout-goto-prefix)
3382 (if (< (point) start-point)
3383 (allout-recent-depth)
3384 0))))
3385 (if (and (> predecessor-depth 0)
3386 (> (+ current-depth arg)
3387 (1+ predecessor-depth)))
3388 (error (concat "Disallowed shift deeper than"
3389 " containing topic's children.")))))))
3390 (allout-rebullet-topic arg))
3391 ;;;_ > allout-shift-out (arg)
3392 (defun allout-shift-out (arg)
3393 "Decrease depth of current heading and any topics collapsed within it.
3394
3395 We disallow shifts that would result in the topic having a depth more than
3396 one level greater than the immediately previous topic, to avoid containment
3397 discontinuity. The first topic in the file can be adjusted to any positive
3398 depth, however."
3399 (interactive "p")
3400 (if (< arg 0)
3401 (allout-shift-in (* arg -1)))
3402 (allout-rebullet-topic (* arg -1)))
3403 ;;;_ : Surgery (kill-ring) functions with special provisions for outlines:
3404 ;;;_ > allout-kill-line (&optional arg)
3405 (defun allout-kill-line (&optional arg)
3406 "Kill line, adjusting subsequent lines suitably for outline mode."
3407
3408 (interactive "*P")
3409
3410 (if (or (not (allout-mode-p))
3411 (not (bolp))
3412 (not (looking-at allout-regexp)))
3413 ;; Above conditions do not obtain - just do a regular kill:
3414 (kill-line arg)
3415 ;; Ah, have to watch out for adjustments:
3416 (let* ((beg (point))
3417 (beg-hidden (allout-hidden-p))
3418 (end-hidden (save-excursion (allout-end-of-current-line)
3419 (allout-hidden-p)))
3420 (depth (allout-depth))
3421 (collapsed (allout-current-topic-collapsed-p)))
3422
3423 (if collapsed
3424 (put-text-property beg (1+ beg) 'allout-was-collapsed t)
3425 (remove-text-properties beg (1+ beg) '(allout-was-collapsed t)))
3426
3427 (if (and (not beg-hidden) (not end-hidden))
3428 (allout-unprotected (kill-line arg))
3429 (kill-line arg))
3430 ; Provide some feedback:
3431 (sit-for 0)
3432 (if allout-numbered-bullet
3433 (save-excursion ; Renumber subsequent topics if needed:
3434 (if (not (looking-at allout-regexp))
3435 (allout-next-heading))
3436 (allout-renumber-to-depth depth))))))
3437 ;;;_ > allout-kill-topic ()
3438 (defun allout-kill-topic ()
3439 "Kill topic together with subtopics.
3440
3441 Trailing whitespace is killed with a topic if that whitespace:
3442
3443 - would separate the topic from a subsequent sibling
3444 - would separate the topic from the end of buffer
3445 - would not be added to whitespace already separating the topic from the
3446 previous one.
3447
3448 Completely collapsed topics are marked as such, for re-collapse
3449 when yank with allout-yank into an outline as a heading."
3450
3451 ;; Some finagling is done to make complex topic kills appear faster
3452 ;; than they actually are. A redisplay is performed immediately
3453 ;; after the region is deleted, though the renumbering process
3454 ;; has yet to be performed. This means that there may appear to be
3455 ;; a lag *after* a kill has been performed.
3456
3457 (interactive)
3458 (let* ((collapsed (allout-current-topic-collapsed-p))
3459 (beg (prog1 (allout-back-to-current-heading) (beginning-of-line)))
3460 (depth (allout-recent-depth)))
3461 (allout-end-of-current-subtree)
3462 (if (and (/= (current-column) 0) (not (eobp)))
3463 (forward-char 1))
3464 (if (not (eobp))
3465 (if (and (looking-at "\n")
3466 (or (save-excursion
3467 (or (not (allout-next-heading))
3468 (= depth (allout-recent-depth))))
3469 (and (> (- beg (point-min)) 3)
3470 (string= (buffer-substring (- beg 2) beg) "\n\n"))))
3471 (forward-char 1)))
3472
3473 (if collapsed
3474 (put-text-property beg (1+ beg) 'allout-was-collapsed t)
3475 (remove-text-properties beg (1+ beg) '(allout-was-collapsed t)))
3476 (allout-unprotected (kill-region beg (point)))
3477 (sit-for 0)
3478 (save-excursion
3479 (allout-renumber-to-depth depth))))
3480 ;;;_ > allout-yank-processing ()
3481 (defun allout-yank-processing (&optional arg)
3482
3483 "Incidental allout-specific business to be done just after text yanks.
3484
3485 Does depth adjustment of yanked topics, when:
3486
3487 1 the stuff being yanked starts with a valid outline header prefix, and
3488 2 it is being yanked at the end of a line which consists of only a valid
3489 topic prefix.
3490
3491 Also, adjusts numbering of subsequent siblings when appropriate.
3492
3493 Depth adjustment alters the depth of all the topics being yanked
3494 the amount it takes to make the first topic have the depth of the
3495 header into which it's being yanked.
3496
3497 The point is left in front of yanked, adjusted topics, rather than
3498 at the end (and vice-versa with the mark). Non-adjusted yanks,
3499 however, are left exactly like normal, non-allout-specific yanks."
3500
3501 (interactive "*P")
3502 ; Get to beginning, leaving
3503 ; region around subject:
3504 (if (< (allout-mark-marker t) (point))
3505 (exchange-point-and-mark))
3506 (let* ((subj-beg (point))
3507 (into-bol (bolp))
3508 (subj-end (allout-mark-marker t))
3509 (was-collapsed (get-text-property subj-beg 'allout-was-collapsed))
3510 ;; 'resituate' if yanking an entire topic into topic header:
3511 (resituate (and (allout-e-o-prefix-p)
3512 (looking-at (concat "\\(" allout-regexp "\\)"))
3513 (allout-prefix-data (match-beginning 1)
3514 (match-end 1))))
3515 ;; `rectify-numbering' if resituating (where several topics may
3516 ;; be resituating) or yanking a topic into a topic slot (bol):
3517 (rectify-numbering (or resituate
3518 (and into-bol (looking-at allout-regexp)))))
3519 (if resituate
3520 ; The yanked stuff is a topic:
3521 (let* ((prefix-len (- (match-end 1) subj-beg))
3522 (subj-depth (allout-recent-depth))
3523 (prefix-bullet (allout-recent-bullet))
3524 (adjust-to-depth
3525 ;; Nil if adjustment unnecessary, otherwise depth to which
3526 ;; adjustment should be made:
3527 (save-excursion
3528 (and (goto-char subj-end)
3529 (eolp)
3530 (goto-char subj-beg)
3531 (and (looking-at allout-regexp)
3532 (progn
3533 (beginning-of-line)
3534 (not (= (point) subj-beg)))
3535 (looking-at allout-regexp)
3536 (allout-prefix-data (match-beginning 0)
3537 (match-end 0)))
3538 (allout-recent-depth))))
3539 (more t))
3540 (setq rectify-numbering allout-numbered-bullet)
3541 (if adjust-to-depth
3542 ; Do the adjustment:
3543 (progn
3544 (message "... yanking") (sit-for 0)
3545 (save-restriction
3546 (narrow-to-region subj-beg subj-end)
3547 ; Trim off excessive blank
3548 ; line at end, if any:
3549 (goto-char (point-max))
3550 (if (looking-at "^$")
3551 (allout-unprotected (delete-char -1)))
3552 ; Work backwards, with each
3553 ; shallowest level,
3554 ; successively excluding the
3555 ; last processed topic from
3556 ; the narrow region:
3557 (while more
3558 (allout-back-to-current-heading)
3559 ; go as high as we can in each bunch:
3560 (while (allout-ascend-to-depth (1- (allout-depth))))
3561 (save-excursion
3562 (allout-rebullet-topic-grunt (- adjust-to-depth
3563 subj-depth))
3564 (allout-depth))
3565 (if (setq more (not (bobp)))
3566 (progn (widen)
3567 (forward-char -1)
3568 (narrow-to-region subj-beg (point))))))
3569 (message "")
3570 ;; Preserve new bullet if it's a distinctive one, otherwise
3571 ;; use old one:
3572 (if (string-match (regexp-quote prefix-bullet)
3573 allout-distinctive-bullets-string)
3574 ; Delete from bullet of old to
3575 ; before bullet of new:
3576 (progn
3577 (beginning-of-line)
3578 (delete-region (point) subj-beg)
3579 (set-marker (allout-mark-marker t) subj-end)
3580 (goto-char subj-beg)
3581 (allout-end-of-prefix))
3582 ; Delete base subj prefix,
3583 ; leaving old one:
3584 (delete-region (point) (+ (point)
3585 prefix-len
3586 (- adjust-to-depth subj-depth)))
3587 ; and delete residual subj
3588 ; prefix digits and space:
3589 (while (looking-at "[0-9]") (delete-char 1))
3590 (if (looking-at " ") (delete-char 1))))
3591 (exchange-point-and-mark))))
3592 (if rectify-numbering
3593 (progn
3594 (save-excursion
3595 ; Give some preliminary feedback:
3596 (message "... reconciling numbers") (sit-for 0)
3597 ; ... and renumber, in case necessary:
3598 (goto-char subj-beg)
3599 (if (allout-goto-prefix)
3600 (allout-rebullet-heading nil ;;; solicit
3601 (allout-depth) ;;; depth
3602 nil ;;; number-control
3603 nil ;;; index
3604 t))
3605 (message ""))))
3606 (when (and (or into-bol resituate) was-collapsed)
3607 (remove-text-properties subj-beg (1+ subj-beg) '(allout-was-collapsed))
3608 (allout-hide-current-subtree))
3609 (if (not resituate)
3610 (exchange-point-and-mark))))
3611 ;;;_ > allout-yank (&optional arg)
3612 (defun allout-yank (&optional arg)
3613 "`allout-mode' yank, with depth and numbering adjustment of yanked topics.
3614
3615 Non-topic yanks work no differently than normal yanks.
3616
3617 If a topic is being yanked into a bare topic prefix, the depth of the
3618 yanked topic is adjusted to the depth of the topic prefix.
3619
3620 1 we're yanking in an `allout-mode' buffer
3621 2 the stuff being yanked starts with a valid outline header prefix, and
3622 3 it is being yanked at the end of a line which consists of only a valid
3623 topic prefix.
3624
3625 If these conditions hold then the depth of the yanked topics are all
3626 adjusted the amount it takes to make the first one at the depth of the
3627 header into which it's being yanked.
3628
3629 The point is left in front of yanked, adjusted topics, rather than
3630 at the end (and vice-versa with the mark). Non-adjusted yanks,
3631 however, (ones that don't qualify for adjustment) are handled
3632 exactly like normal yanks.
3633
3634 Numbering of yanked topics, and the successive siblings at the depth
3635 into which they're being yanked, is adjusted.
3636
3637 `allout-yank-pop' works with `allout-yank' just like normal `yank-pop'
3638 works with normal `yank' in non-outline buffers."
3639
3640 (interactive "*P")
3641 (setq this-command 'yank)
3642 (yank arg)
3643 (if (allout-mode-p)
3644 (allout-yank-processing))
3645 )
3646 ;;;_ > allout-yank-pop (&optional arg)
3647 (defun allout-yank-pop (&optional arg)
3648 "Yank-pop like `allout-yank' when popping to bare outline prefixes.
3649
3650 Adapts level of popped topics to level of fresh prefix.
3651
3652 Note - prefix changes to distinctive bullets will stick, if followed
3653 by pops to non-distinctive yanks. Bug..."
3654
3655 (interactive "*p")
3656 (setq this-command 'yank)
3657 (yank-pop arg)
3658 (if (allout-mode-p)
3659 (allout-yank-processing)))
3660
3661 ;;;_ - Specialty bullet functions
3662 ;;;_ : File Cross references
3663 ;;;_ > allout-resolve-xref ()
3664 (defun allout-resolve-xref ()
3665 "Pop to file associated with current heading, if it has an xref bullet.
3666
3667 \(Works according to setting of `allout-file-xref-bullet')."
3668 (interactive)
3669 (if (not allout-file-xref-bullet)
3670 (error
3671 "Outline cross references disabled - no `allout-file-xref-bullet'")
3672 (if (not (string= (allout-current-bullet) allout-file-xref-bullet))
3673 (error "Current heading lacks cross-reference bullet `%s'"
3674 allout-file-xref-bullet)
3675 (let (file-name)
3676 (save-excursion
3677 (let* ((text-start allout-recent-prefix-end)
3678 (heading-end (progn (end-of-line) (point))))
3679 (goto-char text-start)
3680 (setq file-name
3681 (if (re-search-forward "\\s-\\(\\S-*\\)" heading-end t)
3682 (buffer-substring (match-beginning 1) (match-end 1))))))
3683 (setq file-name (expand-file-name file-name))
3684 (if (or (file-exists-p file-name)
3685 (if (file-writable-p file-name)
3686 (y-or-n-p (format "%s not there, create one? "
3687 file-name))
3688 (error "%s not found and can't be created" file-name)))
3689 (condition-case failure
3690 (find-file-other-window file-name)
3691 ('error failure))
3692 (error "%s not found" file-name))
3693 )
3694 )
3695 )
3696 )
3697
3698 ;;;_ #6 Exposure Control
3699
3700 ;;;_ - Fundamental
3701 ;;;_ > allout-flag-region (from to flag)
3702 (defun allout-flag-region (from to flag)
3703 "Conceal text from FROM to TO if FLAG is non-nil, else reveal it.
3704
3705 Text is shown if flag is nil and hidden otherwise."
3706 ;; We use outline invisibility spec.
3707 (remove-overlays from to 'category 'allout-overlay-category)
3708 (when flag
3709 (let ((o (make-overlay from to)))
3710 (overlay-put o 'category 'allout-overlay-category)
3711 (when (featurep 'xemacs)
3712 (let ((props (symbol-plist 'allout-overlay-category)))
3713 (while props
3714 (overlay-put o (pop props) (pop props)))))))
3715 (run-hooks 'allout-view-change-hook))
3716 ;;;_ > allout-flag-current-subtree (flag)
3717 (defun allout-flag-current-subtree (flag)
3718 "Conceal currently-visible topic's subtree if FLAG non-nil, else reveal it."
3719
3720 (save-excursion
3721 (allout-back-to-current-heading)
3722 (end-of-line)
3723 (allout-flag-region (point)
3724 ;; Exposing must not leave trailing blanks hidden,
3725 ;; but can leave them exposed when hiding, so we
3726 ;; can use flag's inverse as the
3727 ;; include-trailing-blank cue:
3728 (allout-end-of-current-subtree (not flag))
3729 flag)))
3730
3731 ;;;_ - Topic-specific
3732 ;;;_ > allout-show-entry (&optional inclusive)
3733 (defun allout-show-entry (&optional inclusive)
3734 "Like `allout-show-current-entry', reveals entries nested in hidden topics.
3735
3736 This is a way to give restricted peek at a concealed locality without the
3737 expense of exposing its context, but can leave the outline with aberrant
3738 exposure. `allout-show-offshoot' should be used after the peek to rectify
3739 the exposure."
3740
3741 (interactive)
3742 (save-excursion
3743 (let (beg end)
3744 (allout-goto-prefix)
3745 (setq beg (if (allout-hidden-p) (1- (point)) (point)))
3746 (setq end (allout-pre-next-prefix))
3747 (allout-flag-region beg end nil)
3748 (list beg end))))
3749 ;;;_ > allout-show-children (&optional level strict)
3750 (defun allout-show-children (&optional level strict)
3751
3752 "If point is visible, show all direct subheadings of this heading.
3753
3754 Otherwise, do `allout-show-to-offshoot', and then show subheadings.
3755
3756 Optional LEVEL specifies how many levels below the current level
3757 should be shown, or all levels if t. Default is 1.
3758
3759 Optional STRICT means don't resort to -show-to-offshoot, no matter
3760 what. This is basically so -show-to-offshoot, which is called by
3761 this function, can employ the pure offspring-revealing capabilities of
3762 it.
3763
3764 Returns point at end of subtree that was opened, if any. (May get a
3765 point of non-opened subtree?)"
3766
3767 (interactive "p")
3768 (let ((start-point (point)))
3769 (if (and (not strict)
3770 (allout-hidden-p))
3771
3772 (progn (allout-show-to-offshoot) ; Point's concealed, open to
3773 ; expose it.
3774 ;; Then recurse, but with "strict" set so we don't
3775 ;; infinite regress:
3776 (allout-show-children level t))
3777
3778 (save-excursion
3779 (allout-beginning-of-current-line)
3780 (save-restriction
3781 (let* ((chart (allout-chart-subtree (or level 1)))
3782 (to-reveal (allout-chart-to-reveal chart (or level 1))))
3783 (goto-char start-point)
3784 (when (and strict (allout-hidden-p))
3785 ;; Concealed root would already have been taken care of,
3786 ;; unless strict was set.
3787 (allout-flag-region (point) (allout-snug-back) nil)
3788 (when allout-show-bodies
3789 (goto-char (car to-reveal))
3790 (allout-show-current-entry)))
3791 (while to-reveal
3792 (goto-char (car to-reveal))
3793 (allout-flag-region (save-excursion (allout-snug-back) (point))
3794 (progn (search-forward "\n" nil t)
3795 (1- (point)))
3796 nil)
3797 (when allout-show-bodies
3798 (goto-char (car to-reveal))
3799 (allout-show-current-entry))
3800 (setq to-reveal (cdr to-reveal)))))))
3801 ;; Compensate for `save-excursion's maintenance of point
3802 ;; within invisible text:
3803 (goto-char start-point)))
3804 ;;;_ > allout-show-to-offshoot ()
3805 (defun allout-show-to-offshoot ()
3806 "Like `allout-show-entry', but reveals all concealed ancestors, as well.
3807
3808 Useful for coherently exposing to a random point in a hidden region."
3809 (interactive)
3810 (save-excursion
3811 (let ((orig-pt (point))
3812 (orig-pref (allout-goto-prefix))
3813 (last-at (point))
3814 bag-it)
3815 (while (or bag-it (allout-hidden-p))
3816 (while (allout-hidden-p)
3817 ;; XXX We would use `(move-beginning-of-line 1)', but it gets
3818 ;; stuck on hidden newlines at column 80, as of GNU Emacs 22.0.50.
3819 (beginning-of-line)
3820 (if (allout-hidden-p) (forward-char -1)))
3821 (if (= last-at (setq last-at (point)))
3822 ;; Oops, we're not making any progress! Show the current
3823 ;; topic completely, and bag this try.
3824 (progn (beginning-of-line)
3825 (allout-show-current-subtree)
3826 (goto-char orig-pt)
3827 (setq bag-it t)
3828 (beep)
3829 (message "%s: %s"
3830 "allout-show-to-offshoot: "
3831 "Aberrant nesting encountered.")))
3832 (allout-show-children)
3833 (goto-char orig-pref))
3834 (goto-char orig-pt)))
3835 (if (allout-hidden-p)
3836 (allout-show-entry)))
3837 ;;;_ > allout-hide-current-entry ()
3838 (defun allout-hide-current-entry ()
3839 "Hide the body directly following this heading."
3840 (interactive)
3841 (allout-back-to-current-heading)
3842 (save-excursion
3843 (end-of-line)
3844 (allout-flag-region (point)
3845 (progn (allout-end-of-entry) (point))
3846 t)))
3847 ;;;_ > allout-show-current-entry (&optional arg)
3848 (defun allout-show-current-entry (&optional arg)
3849
3850 "Show body following current heading, or hide entry with universal argument."
3851
3852 (interactive "P")
3853 (if arg
3854 (allout-hide-current-entry)
3855 (save-excursion (allout-show-to-offshoot))
3856 (save-excursion
3857 (allout-flag-region (point)
3858 (progn (allout-end-of-entry t) (point))
3859 nil)
3860 )))
3861 ;;;_ > allout-show-current-subtree (&optional arg)
3862 (defun allout-show-current-subtree (&optional arg)
3863 "Show everything within the current topic. With a repeat-count,
3864 expose this topic and its siblings."
3865 (interactive "P")
3866 (save-excursion
3867 (if (<= (allout-current-depth) 0)
3868 ;; Outside any topics - try to get to the first:
3869 (if (not (allout-next-heading))
3870 (error "No topics")
3871 ;; got to first, outermost topic - set to expose it and siblings:
3872 (message "Above outermost topic - exposing all.")
3873 (allout-flag-region (point-min)(point-max) nil))
3874 (allout-beginning-of-current-line)
3875 (if (not arg)
3876 (allout-flag-current-subtree nil)
3877 (allout-beginning-of-level)
3878 (allout-expose-topic '(* :))))))
3879 ;;;_ > allout-current-topic-collapsed-p (&optional include-single-liners)
3880 (defun allout-current-topic-collapsed-p (&optional include-single-liners)
3881 "True if the currently visible containing topic is already collapsed.
3882
3883 If optional INCLUDE-SINGLE-LINERS is true, then include single-line
3884 topics \(which intrinsically can be considered both collapsed and
3885 not\), as collapsed. Otherwise they are considered uncollapsed."
3886 (save-excursion
3887 (and
3888 (= (progn (allout-back-to-current-heading)
3889 (move-end-of-line 1)
3890 (point))
3891 (allout-end-of-current-subtree))
3892 (or include-single-liners
3893 (progn (backward-char 1) (allout-hidden-p))))))
3894 ;;;_ > allout-hide-current-subtree (&optional just-close)
3895 (defun allout-hide-current-subtree (&optional just-close)
3896 "Close the current topic, or containing topic if this one is already closed.
3897
3898 If this topic is closed and it's a top level topic, close this topic
3899 and its siblings.
3900
3901 If optional arg JUST-CLOSE is non-nil, do not close the parent or
3902 siblings, even if the target topic is already closed."
3903
3904 (interactive)
3905 (let* ((from (point))
3906 (sibs-msg "Top-level topic already closed - closing siblings...")
3907 (current-exposed (not (allout-current-topic-collapsed-p t))))
3908 (cond (current-exposed (allout-flag-current-subtree t))
3909 (just-close nil)
3910 ((allout-up-current-level 1 t) (allout-hide-current-subtree))
3911 (t (goto-char 0)
3912 (message sibs-msg)
3913 (allout-expose-topic '(0 :))
3914 (message (concat sibs-msg " Done."))))
3915 (goto-char from)))
3916 ;;;_ > allout-show-current-branches ()
3917 (defun allout-show-current-branches ()
3918 "Show all subheadings of this heading, but not their bodies."
3919 (interactive)
3920 (beginning-of-line)
3921 (allout-show-children t))
3922 ;;;_ > allout-hide-current-leaves ()
3923 (defun allout-hide-current-leaves ()
3924 "Hide the bodies of the current topic and all its offspring."
3925 (interactive)
3926 (allout-back-to-current-heading)
3927 (allout-hide-region-body (point) (progn (allout-end-of-current-subtree)
3928 (point))))
3929
3930 ;;;_ - Region and beyond
3931 ;;;_ > allout-show-all ()
3932 (defun allout-show-all ()
3933 "Show all of the text in the buffer."
3934 (interactive)
3935 (message "Exposing entire buffer...")
3936 (allout-flag-region (point-min) (point-max) nil)
3937 (message "Exposing entire buffer... Done."))
3938 ;;;_ > allout-hide-bodies ()
3939 (defun allout-hide-bodies ()
3940 "Hide all of buffer except headings."
3941 (interactive)
3942 (allout-hide-region-body (point-min) (point-max)))
3943 ;;;_ > allout-hide-region-body (start end)
3944 (defun allout-hide-region-body (start end)
3945 "Hide all body lines in the region, but not headings."
3946 (save-excursion
3947 (save-restriction
3948 (narrow-to-region start end)
3949 (goto-char (point-min))
3950 (while (not (eobp))
3951 (end-of-line)
3952 (allout-flag-region (point) (allout-end-of-entry) t)
3953 (if (not (eobp))
3954 (forward-char
3955 (if (looking-at "\n\n")
3956 2 1)))))))
3957
3958 ;;;_ > allout-expose-topic (spec)
3959 (defun allout-expose-topic (spec)
3960 "Apply exposure specs to successive outline topic items.
3961
3962 Use the more convenient frontend, `allout-new-exposure', if you don't
3963 need evaluation of the arguments, or even better, the `allout-layout'
3964 variable-keyed mode-activation/auto-exposure feature of allout outline
3965 mode. See the respective documentation strings for more details.
3966
3967 Cursor is left at start position.
3968
3969 SPEC is either a number or a list.
3970
3971 Successive specs on a list are applied to successive sibling topics.
3972
3973 A simple spec \(either a number, one of a few symbols, or the null
3974 list) dictates the exposure for the corresponding topic.
3975
3976 Non-null lists recursively designate exposure specs for respective
3977 subtopics of the current topic.
3978
3979 The `:' repeat spec is used to specify exposure for any number of
3980 successive siblings, up to the trailing ones for which there are
3981 explicit specs following the `:'.
3982
3983 Simple (numeric and null-list) specs are interpreted as follows:
3984
3985 Numbers indicate the relative depth to open the corresponding topic.
3986 - negative numbers force the topic to be closed before opening to the
3987 absolute value of the number, so all siblings are open only to
3988 that level.
3989 - positive numbers open to the relative depth indicated by the
3990 number, but do not force already opened subtopics to be closed.
3991 - 0 means to close topic - hide all offspring.
3992 : - `repeat'
3993 apply prior element to all siblings at current level, *up to*
3994 those siblings that would be covered by specs following the `:'
3995 on the list. Ie, apply to all topics at level but the last
3996 ones. \(Only first of multiple colons at same level is
3997 respected - subsequent ones are discarded.)
3998 * - completely opens the topic, including bodies.
3999 + - shows all the sub headers, but not the bodies
4000 - - exposes the body of the corresponding topic.
4001
4002 Examples:
4003 \(allout-expose-topic '(-1 : 0))
4004 Close this and all following topics at current level, exposing
4005 only their immediate children, but close down the last topic
4006 at this current level completely.
4007 \(allout-expose-topic '(-1 () : 1 0))
4008 Close current topic so only the immediate subtopics are shown;
4009 show the children in the second to last topic, and completely
4010 close the last one.
4011 \(allout-expose-topic '(-2 : -1 *))
4012 Expose children and grandchildren of all topics at current
4013 level except the last two; expose children of the second to
4014 last and completely open the last one."
4015
4016 (interactive "xExposure spec: ")
4017 (if (not (listp spec))
4018 nil
4019 (let ((depth (allout-depth))
4020 (max-pos 0)
4021 prev-elem curr-elem
4022 stay)
4023 (while spec
4024 (setq prev-elem curr-elem
4025 curr-elem (car spec)
4026 spec (cdr spec))
4027 (cond ; Do current element:
4028 ((null curr-elem) nil)
4029 ((symbolp curr-elem)
4030 (cond ((eq curr-elem '*) (allout-show-current-subtree)
4031 (if (> allout-recent-end-of-subtree max-pos)
4032 (setq max-pos allout-recent-end-of-subtree)))
4033 ((eq curr-elem '+) (allout-show-current-branches)
4034 (if (> allout-recent-end-of-subtree max-pos)
4035 (setq max-pos allout-recent-end-of-subtree)))
4036 ((eq curr-elem '-) (allout-show-current-entry))
4037 ((eq curr-elem ':)
4038 (setq stay t)
4039 ;; Expand the `repeat' spec to an explicit version,
4040 ;; w.r.t. remaining siblings:
4041 (let ((residue ; = # of sibs not covered by remaining spec
4042 ;; Dang - could be nice to make use of the chart, sigh:
4043 (- (length (allout-chart-siblings))
4044 (length spec))))
4045 (if (< 0 residue)
4046 ;; Some residue - cover it with prev-elem:
4047 (setq spec (append (make-list residue prev-elem)
4048 spec)))))))
4049 ((numberp curr-elem)
4050 (if (and (>= 0 curr-elem) (not (allout-hidden-p)))
4051 (save-excursion (allout-hide-current-subtree t)
4052 (if (> 0 curr-elem)
4053 nil
4054 (if (> allout-recent-end-of-subtree max-pos)
4055 (setq max-pos
4056 allout-recent-end-of-subtree)))))
4057 (if (> (abs curr-elem) 0)
4058 (progn (allout-show-children (abs curr-elem))
4059 (if (> allout-recent-end-of-subtree max-pos)
4060 (setq max-pos allout-recent-end-of-subtree)))))
4061 ((listp curr-elem)
4062 (if (allout-descend-to-depth (1+ depth))
4063 (let ((got (allout-expose-topic curr-elem)))
4064 (if (and got (> got max-pos)) (setq max-pos got))))))
4065 (cond (stay (setq stay nil))
4066 ((listp (car spec)) nil)
4067 ((> max-pos (point))
4068 ;; Capitalize on max-pos state to get us nearer next sibling:
4069 (progn (goto-char (min (point-max) max-pos))
4070 (allout-next-heading)))
4071 ((allout-next-sibling depth))))
4072 max-pos)))
4073 ;;;_ > allout-old-expose-topic (spec &rest followers)
4074 (defun allout-old-expose-topic (spec &rest followers)
4075
4076 "Deprecated. Use `allout-expose-topic' \(with different schema
4077 format) instead.
4078
4079 Dictate wholesale exposure scheme for current topic, according to SPEC.
4080
4081 SPEC is either a number or a list. Optional successive args
4082 dictate exposure for subsequent siblings of current topic.
4083
4084 A simple spec (either a number, a special symbol, or the null list)
4085 dictates the overall exposure for a topic. Non null lists are
4086 composite specs whose first element dictates the overall exposure for
4087 a topic, with the subsequent elements in the list interpreted as specs
4088 that dictate the exposure for the successive offspring of the topic.
4089
4090 Simple (numeric and null-list) specs are interpreted as follows:
4091
4092 - Numbers indicate the relative depth to open the corresponding topic:
4093 - negative numbers force the topic to be close before opening to the
4094 absolute value of the number.
4095 - positive numbers just open to the relative depth indicated by the number.
4096 - 0 just closes
4097 - `*' completely opens the topic, including bodies.
4098 - `+' shows all the sub headers, but not the bodies
4099 - `-' exposes the body and immediate offspring of the corresponding topic.
4100
4101 If the spec is a list, the first element must be a number, which
4102 dictates the exposure depth of the topic as a whole. Subsequent
4103 elements of the list are nested SPECs, dictating the specific exposure
4104 for the corresponding offspring of the topic.
4105
4106 Optional FOLLOWERS arguments dictate exposure for succeeding siblings."
4107
4108 (interactive "xExposure spec: ")
4109 (let ((depth (allout-current-depth))
4110 max-pos)
4111 (cond ((null spec) nil)
4112 ((symbolp spec)
4113 (if (eq spec '*) (allout-show-current-subtree))
4114 (if (eq spec '+) (allout-show-current-branches))
4115 (if (eq spec '-) (allout-show-current-entry)))
4116 ((numberp spec)
4117 (if (>= 0 spec)
4118 (save-excursion (allout-hide-current-subtree t)
4119 (end-of-line)
4120 (if (or (not max-pos)
4121 (> (point) max-pos))
4122 (setq max-pos (point)))
4123 (if (> 0 spec)
4124 (setq spec (* -1 spec)))))
4125 (if (> spec 0)
4126 (allout-show-children spec)))
4127 ((listp spec)
4128 ;(let ((got (allout-old-expose-topic (car spec))))
4129 ; (if (and got (or (not max-pos) (> got max-pos)))
4130 ; (setq max-pos got)))
4131 (let ((new-depth (+ (allout-current-depth) 1))
4132 got)
4133 (setq max-pos (allout-old-expose-topic (car spec)))
4134 (setq spec (cdr spec))
4135 (if (and spec
4136 (allout-descend-to-depth new-depth)
4137 (not (allout-hidden-p)))
4138 (progn (setq got (apply 'allout-old-expose-topic spec))
4139 (if (and got (or (not max-pos) (> got max-pos)))
4140 (setq max-pos got)))))))
4141 (while (and followers
4142 (progn (if (and max-pos (< (point) max-pos))
4143 (progn (goto-char max-pos)
4144 (setq max-pos nil)))
4145 (end-of-line)
4146 (allout-next-sibling depth)))
4147 (allout-old-expose-topic (car followers))
4148 (setq followers (cdr followers)))
4149 max-pos))
4150 ;;;_ > allout-new-exposure '()
4151 (defmacro allout-new-exposure (&rest spec)
4152 "Literal frontend for `allout-expose-topic', doesn't evaluate arguments.
4153 Some arguments that would need to be quoted in `allout-expose-topic'
4154 need not be quoted in `allout-new-exposure'.
4155
4156 Cursor is left at start position.
4157
4158 Use this instead of obsolete `allout-exposure'.
4159
4160 Examples:
4161 \(allout-new-exposure (-1 () () () 1) 0)
4162 Close current topic at current level so only the immediate
4163 subtopics are shown, except also show the children of the
4164 third subtopic; and close the next topic at the current level.
4165 \(allout-new-exposure : -1 0)
4166 Close all topics at current level to expose only their
4167 immediate children, except for the last topic at the current
4168 level, in which even its immediate children are hidden.
4169 \(allout-new-exposure -2 : -1 *)
4170 Expose children and grandchildren of first topic at current
4171 level, and expose children of subsequent topics at current
4172 level *except* for the last, which should be opened completely."
4173 (list 'save-excursion
4174 '(if (not (or (allout-goto-prefix)
4175 (allout-next-heading)))
4176 (error "allout-new-exposure: Can't find any outline topics"))
4177 (list 'allout-expose-topic (list 'quote spec))))
4178
4179 ;;;_ #7 Systematic outline presentation - copying, printing, flattening
4180
4181 ;;;_ - Mapping and processing of topics
4182 ;;;_ ( See also Subtree Charting, in Navigation code.)
4183 ;;;_ > allout-stringify-flat-index (flat-index)
4184 (defun allout-stringify-flat-index (flat-index &optional context)
4185 "Convert list representing section/subsection/... to document string.
4186
4187 Optional arg CONTEXT indicates interior levels to include."
4188 (let ((delim ".")
4189 result
4190 numstr
4191 (context-depth (or (and context 2) 1)))
4192 ;; Take care of the explicit context:
4193 (while (> context-depth 0)
4194 (setq numstr (int-to-string (car flat-index))
4195 flat-index (cdr flat-index)
4196 result (if flat-index
4197 (cons delim (cons numstr result))
4198 (cons numstr result))
4199 context-depth (if flat-index (1- context-depth) 0)))
4200 (setq delim " ")
4201 ;; Take care of the indentation:
4202 (if flat-index
4203 (progn
4204 (while flat-index
4205 (setq result
4206 (cons delim
4207 (cons (make-string
4208 (1+ (truncate (if (zerop (car flat-index))
4209 1
4210 (log10 (car flat-index)))))
4211 ? )
4212 result)))
4213 (setq flat-index (cdr flat-index)))
4214 ;; Dispose of single extra delim:
4215 (setq result (cdr result))))
4216 (apply 'concat result)))
4217 ;;;_ > allout-stringify-flat-index-plain (flat-index)
4218 (defun allout-stringify-flat-index-plain (flat-index)
4219 "Convert list representing section/subsection/... to document string."
4220 (let ((delim ".")
4221 result)
4222 (while flat-index
4223 (setq result (cons (int-to-string (car flat-index))
4224 (if result
4225 (cons delim result))))
4226 (setq flat-index (cdr flat-index)))
4227 (apply 'concat result)))
4228 ;;;_ > allout-stringify-flat-index-indented (flat-index)
4229 (defun allout-stringify-flat-index-indented (flat-index)
4230 "Convert list representing section/subsection/... to document string."
4231 (let ((delim ".")
4232 result
4233 numstr)
4234 ;; Take care of the explicit context:
4235 (setq numstr (int-to-string (car flat-index))
4236 flat-index (cdr flat-index)
4237 result (if flat-index
4238 (cons delim (cons numstr result))
4239 (cons numstr result)))
4240 (setq delim " ")
4241 ;; Take care of the indentation:
4242 (if flat-index
4243 (progn
4244 (while flat-index
4245 (setq result
4246 (cons delim
4247 (cons (make-string
4248 (1+ (truncate (if (zerop (car flat-index))
4249 1
4250 (log10 (car flat-index)))))
4251 ? )
4252 result)))
4253 (setq flat-index (cdr flat-index)))
4254 ;; Dispose of single extra delim:
4255 (setq result (cdr result))))
4256 (apply 'concat result)))
4257 ;;;_ > allout-listify-exposed (&optional start end format)
4258 (defun allout-listify-exposed (&optional start end format)
4259
4260 "Produce a list representing exposed topics in current region.
4261
4262 This list can then be used by `allout-process-exposed' to manipulate
4263 the subject region.
4264
4265 Optional START and END indicate bounds of region.
4266
4267 optional arg, FORMAT, designates an alternate presentation form for
4268 the prefix:
4269
4270 list - Present prefix as numeric section.subsection..., starting with
4271 section indicated by the list, innermost nesting first.
4272 `indent' \(symbol) - Convert header prefixes to all white space,
4273 except for distinctive bullets.
4274
4275 The elements of the list produced are lists that represents a topic
4276 header and body. The elements of that list are:
4277
4278 - a number representing the depth of the topic,
4279 - a string representing the header-prefix, including trailing whitespace and
4280 bullet.
4281 - a string representing the bullet character,
4282 - and a series of strings, each containing one line of the exposed
4283 portion of the topic entry."
4284
4285 (interactive "r")
4286 (save-excursion
4287 (let*
4288 ;; state vars:
4289 (strings prefix result depth new-depth out gone-out bullet beg
4290 next done)
4291
4292 (goto-char start)
4293 (beginning-of-line)
4294 ;; Goto initial topic, and register preceeding stuff, if any:
4295 (if (> (allout-goto-prefix) start)
4296 ;; First topic follows beginning point - register preliminary stuff:
4297 (setq result (list (list 0 "" nil
4298 (buffer-substring start (1- (point)))))))
4299 (while (and (not done)
4300 (not (eobp)) ; Loop until we've covered the region.
4301 (not (> (point) end)))
4302 (setq depth (allout-recent-depth) ; Current topics depth,
4303 bullet (allout-recent-bullet) ; ... bullet,
4304 prefix (allout-recent-prefix)
4305 beg (progn (allout-end-of-prefix t) (point))) ; and beginning.
4306 (setq done ; The boundary for the current topic:
4307 (not (allout-next-visible-heading 1)))
4308 (setq new-depth (allout-recent-depth))
4309 (setq gone-out out
4310 out (< new-depth depth))
4311 (beginning-of-line)
4312 (setq next (point))
4313 (goto-char beg)
4314 (setq strings nil)
4315 (while (> next (point)) ; Get all the exposed text in
4316 (setq strings
4317 (cons (buffer-substring
4318 beg
4319 ;To hidden text or end of line:
4320 (progn
4321 (end-of-line)
4322 (allout-back-to-visible-text)))
4323 strings))
4324 (when (< (point) next) ; Resume from after hid text, if any.
4325 (line-move 1))
4326 (setq beg (point)))
4327 ;; Accumulate list for this topic:
4328 (setq strings (nreverse strings))
4329 (setq result
4330 (cons
4331 (if format
4332 (let ((special (if (string-match
4333 (regexp-quote bullet)
4334 allout-distinctive-bullets-string)
4335 bullet)))
4336 (cond ((listp format)
4337 (list depth
4338 (if allout-abbreviate-flattened-numbering
4339 (allout-stringify-flat-index format
4340 gone-out)
4341 (allout-stringify-flat-index-plain
4342 format))
4343 strings
4344 special))
4345 ((eq format 'indent)
4346 (if special
4347 (list depth
4348 (concat (make-string (1+ depth) ? )
4349 (substring prefix -1))
4350 strings)
4351 (list depth
4352 (make-string depth ? )
4353 strings)))
4354 (t (error "allout-listify-exposed: %s %s"
4355 "invalid format" format))))
4356 (list depth prefix strings))
4357 result))
4358 ;; Reasses format, if any:
4359 (if (and format (listp format))
4360 (cond ((= new-depth depth)
4361 (setq format (cons (1+ (car format))
4362 (cdr format))))
4363 ((> new-depth depth) ; descending - assume by 1:
4364 (setq format (cons 1 format)))
4365 (t
4366 ; Pop the residue:
4367 (while (< new-depth depth)
4368 (setq format (cdr format))
4369 (setq depth (1- depth)))
4370 ; And increment the current one:
4371 (setq format
4372 (cons (1+ (or (car format)
4373 -1))
4374 (cdr format)))))))
4375 ;; Put the list with first at front, to last at back:
4376 (nreverse result))))
4377 ;;;_ > my-region-active-p ()
4378 (defmacro my-region-active-p ()
4379 (if (fboundp 'region-active-p)
4380 '(region-active-p)
4381 'mark-active))
4382 ;;;_ > allout-process-exposed (&optional func from to frombuf
4383 ;;; tobuf format)
4384 (defun allout-process-exposed (&optional func from to frombuf tobuf
4385 format start-num)
4386 "Map function on exposed parts of current topic; results to another buffer.
4387
4388 All args are options; default values itemized below.
4389
4390 Apply FUNCTION to exposed portions FROM position TO position in buffer
4391 FROMBUF to buffer TOBUF. Sixth optional arg, FORMAT, designates an
4392 alternate presentation form:
4393
4394 `flat' - Present prefix as numeric section.subsection..., starting with
4395 section indicated by the start-num, innermost nesting first.
4396 X`flat-indented' - Prefix is like `flat' for first topic at each
4397 X level, but subsequent topics have only leaf topic
4398 X number, padded with blanks to line up with first.
4399 `indent' \(symbol) - Convert header prefixes to all white space,
4400 except for distinctive bullets.
4401
4402 Defaults:
4403 FUNCTION: `allout-insert-listified'
4404 FROM: region start, if region active, else start of buffer
4405 TO: region end, if region active, else end of buffer
4406 FROMBUF: current buffer
4407 TOBUF: buffer name derived: \"*current-buffer-name exposed*\"
4408 FORMAT: nil"
4409
4410 ; Resolve arguments,
4411 ; defaulting if necessary:
4412 (if (not func) (setq func 'allout-insert-listified))
4413 (if (not (and from to))
4414 (if (my-region-active-p)
4415 (setq from (region-beginning) to (region-end))
4416 (setq from (point-min) to (point-max))))
4417 (if frombuf
4418 (if (not (bufferp frombuf))
4419 ;; Specified but not a buffer - get it:
4420 (let ((got (get-buffer frombuf)))
4421 (if (not got)
4422 (error (concat "allout-process-exposed: source buffer "
4423 frombuf
4424 " not found."))
4425 (setq frombuf got))))
4426 ;; not specified - default it:
4427 (setq frombuf (current-buffer)))
4428 (if tobuf
4429 (if (not (bufferp tobuf))
4430 (setq tobuf (get-buffer-create tobuf)))
4431 ;; not specified - default it:
4432 (setq tobuf (concat "*" (buffer-name frombuf) " exposed*")))
4433 (if (listp format)
4434 (nreverse format))
4435
4436 (let* ((listified
4437 (progn (set-buffer frombuf)
4438 (allout-listify-exposed from to format))))
4439 (set-buffer tobuf)
4440 (mapcar func listified)
4441 (pop-to-buffer tobuf)))
4442
4443 ;;;_ - Copy exposed
4444 ;;;_ > allout-insert-listified (listified)
4445 (defun allout-insert-listified (listified)
4446 "Insert contents of listified outline portion in current buffer.
4447
4448 LISTIFIED is a list representing each topic header and body:
4449
4450 \`(depth prefix text)'
4451
4452 or \`(depth prefix text bullet-plus)'
4453
4454 If `bullet-plus' is specified, it is inserted just after the entire prefix."
4455 (setq listified (cdr listified))
4456 (let ((prefix (prog1
4457 (car listified)
4458 (setq listified (cdr listified))))
4459 (text (prog1
4460 (car listified)
4461 (setq listified (cdr listified))))
4462 (bullet-plus (car listified)))
4463 (insert prefix)
4464 (if bullet-plus (insert (concat " " bullet-plus)))
4465 (while text
4466 (insert (car text))
4467 (if (setq text (cdr text))
4468 (insert "\n")))
4469 (insert "\n")))
4470 ;;;_ > allout-copy-exposed-to-buffer (&optional arg tobuf format)
4471 (defun allout-copy-exposed-to-buffer (&optional arg tobuf format)
4472 "Duplicate exposed portions of current outline to another buffer.
4473
4474 Other buffer has current buffers name with \" exposed\" appended to it.
4475
4476 With repeat count, copy the exposed parts of only the current topic.
4477
4478 Optional second arg TOBUF is target buffer name.
4479
4480 Optional third arg FORMAT, if non-nil, symbolically designates an
4481 alternate presentation format for the outline:
4482
4483 `flat' - Convert topic header prefixes to numeric
4484 section.subsection... identifiers.
4485 `indent' - Convert header prefixes to all white space, except for
4486 distinctive bullets.
4487 `indent-flat' - The best of both - only the first of each level has
4488 the full path, the rest have only the section number
4489 of the leaf, preceded by the right amount of indentation."
4490
4491 (interactive "P")
4492 (if (not tobuf)
4493 (setq tobuf (get-buffer-create (concat "*" (buffer-name) " exposed*"))))
4494 (let* ((start-pt (point))
4495 (beg (if arg (allout-back-to-current-heading) (point-min)))
4496 (end (if arg (allout-end-of-current-subtree) (point-max)))
4497 (buf (current-buffer))
4498 (start-list ()))
4499 (if (eq format 'flat)
4500 (setq format (if arg (save-excursion
4501 (goto-char beg)
4502 (allout-topic-flat-index))
4503 '(1))))
4504 (save-excursion (set-buffer tobuf)(erase-buffer))
4505 (allout-process-exposed 'allout-insert-listified
4506 beg
4507 end
4508 (current-buffer)
4509 tobuf
4510 format start-list)
4511 (goto-char (point-min))
4512 (pop-to-buffer buf)
4513 (goto-char start-pt)))
4514 ;;;_ > allout-flatten-exposed-to-buffer (&optional arg tobuf)
4515 (defun allout-flatten-exposed-to-buffer (&optional arg tobuf)
4516 "Present numeric outline of outline's exposed portions in another buffer.
4517
4518 The resulting outline is not compatible with outline mode - use
4519 `allout-copy-exposed-to-buffer' if you want that.
4520
4521 Use `allout-indented-exposed-to-buffer' for indented presentation.
4522
4523 With repeat count, copy the exposed portions of only current topic.
4524
4525 Other buffer has current buffer's name with \" exposed\" appended to
4526 it, unless optional second arg TOBUF is specified, in which case it is
4527 used verbatim."
4528 (interactive "P")
4529 (allout-copy-exposed-to-buffer arg tobuf 'flat))
4530 ;;;_ > allout-indented-exposed-to-buffer (&optional arg tobuf)
4531 (defun allout-indented-exposed-to-buffer (&optional arg tobuf)
4532 "Present indented outline of outline's exposed portions in another buffer.
4533
4534 The resulting outline is not compatible with outline mode - use
4535 `allout-copy-exposed-to-buffer' if you want that.
4536
4537 Use `allout-flatten-exposed-to-buffer' for numeric sectional presentation.
4538
4539 With repeat count, copy the exposed portions of only current topic.
4540
4541 Other buffer has current buffer's name with \" exposed\" appended to
4542 it, unless optional second arg TOBUF is specified, in which case it is
4543 used verbatim."
4544 (interactive "P")
4545 (allout-copy-exposed-to-buffer arg tobuf 'indent))
4546
4547 ;;;_ - LaTeX formatting
4548 ;;;_ > allout-latex-verb-quote (string &optional flow)
4549 (defun allout-latex-verb-quote (string &optional flow)
4550 "Return copy of STRING for literal reproduction across LaTeX processing.
4551 Expresses the original characters \(including carriage returns) of the
4552 string across LaTeX processing."
4553 (mapconcat (function
4554 (lambda (char)
4555 (cond ((memq char '(?\\ ?$ ?% ?# ?& ?{ ?} ?_ ?^ ?- ?*))
4556 (concat "\\char" (number-to-string char) "{}"))
4557 ((= char ?\n) "\\\\")
4558 (t (char-to-string char)))))
4559 string
4560 ""))
4561 ;;;_ > allout-latex-verbatim-quote-curr-line ()
4562 (defun allout-latex-verbatim-quote-curr-line ()
4563 "Express line for exact \(literal) representation across LaTeX processing.
4564
4565 Adjust line contents so it is unaltered \(from the original line)
4566 across LaTeX processing, within the context of a `verbatim'
4567 environment. Leaves point at the end of the line."
4568 (beginning-of-line)
4569 (let ((beg (point))
4570 (end (progn (end-of-line)(point))))
4571 (goto-char beg)
4572 (while (re-search-forward "\\\\"
4573 ;;"\\\\\\|\\{\\|\\}\\|\\_\\|\\$\\|\\\"\\|\\&\\|\\^\\|\\-\\|\\*\\|#"
4574 end ; bounded by end-of-line
4575 1) ; no matches, move to end & return nil
4576 (goto-char (match-beginning 0))
4577 (insert "\\")
4578 (setq end (1+ end))
4579 (goto-char (1+ (match-end 0))))))
4580 ;;;_ > allout-insert-latex-header (buffer)
4581 (defun allout-insert-latex-header (buffer)
4582 "Insert initial LaTeX commands at point in BUFFER."
4583 ;; Much of this is being derived from the stuff in appendix of E in
4584 ;; the TeXBook, pg 421.
4585 (set-buffer buffer)
4586 (let ((doc-style (format "\n\\documentstyle{%s}\n"
4587 "report"))
4588 (page-numbering (if allout-number-pages
4589 "\\pagestyle{empty}\n"
4590 ""))
4591 (titlecmd (format "\\newcommand{\\titlecmd}[1]{{%s #1}}\n"
4592 allout-title-style))
4593 (labelcmd (format "\\newcommand{\\labelcmd}[1]{{%s #1}}\n"
4594 allout-label-style))
4595 (headlinecmd (format "\\newcommand{\\headlinecmd}[1]{{%s #1}}\n"
4596 allout-head-line-style))
4597 (bodylinecmd (format "\\newcommand{\\bodylinecmd}[1]{{%s #1}}\n"
4598 allout-body-line-style))
4599 (setlength (format "%s%s%s%s"
4600 "\\newlength{\\stepsize}\n"
4601 "\\setlength{\\stepsize}{"
4602 allout-indent
4603 "}\n"))
4604 (oneheadline (format "%s%s%s%s%s%s%s"
4605 "\\newcommand{\\OneHeadLine}[3]{%\n"
4606 "\\noindent%\n"
4607 "\\hspace*{#2\\stepsize}%\n"
4608 "\\labelcmd{#1}\\hspace*{.2cm}"
4609 "\\headlinecmd{#3}\\\\["
4610 allout-line-skip
4611 "]\n}\n"))
4612 (onebodyline (format "%s%s%s%s%s%s"
4613 "\\newcommand{\\OneBodyLine}[2]{%\n"
4614 "\\noindent%\n"
4615 "\\hspace*{#1\\stepsize}%\n"
4616 "\\bodylinecmd{#2}\\\\["
4617 allout-line-skip
4618 "]\n}\n"))
4619 (begindoc "\\begin{document}\n\\begin{center}\n")
4620 (title (format "%s%s%s%s"
4621 "\\titlecmd{"
4622 (allout-latex-verb-quote (if allout-title
4623 (condition-case nil
4624 (eval allout-title)
4625 ('error "<unnamed buffer>"))
4626 "Unnamed Outline"))
4627 "}\n"
4628 "\\end{center}\n\n"))
4629 (hsize "\\hsize = 7.5 true in\n")
4630 (hoffset "\\hoffset = -1.5 true in\n")
4631 (vspace "\\vspace{.1cm}\n\n"))
4632 (insert (concat doc-style
4633 page-numbering
4634 titlecmd
4635 labelcmd
4636 headlinecmd
4637 bodylinecmd
4638 setlength
4639 oneheadline
4640 onebodyline
4641 begindoc
4642 title
4643 hsize
4644 hoffset
4645 vspace)
4646 )))
4647 ;;;_ > allout-insert-latex-trailer (buffer)
4648 (defun allout-insert-latex-trailer (buffer)
4649 "Insert concluding LaTeX commands at point in BUFFER."
4650 (set-buffer buffer)
4651 (insert "\n\\end{document}\n"))
4652 ;;;_ > allout-latexify-one-item (depth prefix bullet text)
4653 (defun allout-latexify-one-item (depth prefix bullet text)
4654 "Insert LaTeX commands for formatting one outline item.
4655
4656 Args are the topics numeric DEPTH, the header PREFIX lead string, the
4657 BULLET string, and a list of TEXT strings for the body."
4658 (let* ((head-line (if text (car text)))
4659 (body-lines (cdr text))
4660 (curr-line)
4661 body-content bop)
4662 ; Do the head line:
4663 (insert (concat "\\OneHeadLine{\\verb\1 "
4664 (allout-latex-verb-quote bullet)
4665 "\1}{"
4666 depth
4667 "}{\\verb\1 "
4668 (if head-line
4669 (allout-latex-verb-quote head-line)
4670 "")
4671 "\1}\n"))
4672 (if (not body-lines)
4673 nil
4674 ;;(insert "\\beginlines\n")
4675 (insert "\\begin{verbatim}\n")
4676 (while body-lines
4677 (setq curr-line (car body-lines))
4678 (if (and (not body-content)
4679 (not (string-match "^\\s-*$" curr-line)))
4680 (setq body-content t))
4681 ; Mangle any occurrences of
4682 ; "\end{verbatim}" in text,
4683 ; it's special:
4684 (if (and body-content
4685 (setq bop (string-match "\\end{verbatim}" curr-line)))
4686 (setq curr-line (concat (substring curr-line 0 bop)
4687 ">"
4688 (substring curr-line bop))))
4689 ;;(insert "|" (car body-lines) "|")
4690 (insert curr-line)
4691 (allout-latex-verbatim-quote-curr-line)
4692 (insert "\n")
4693 (setq body-lines (cdr body-lines)))
4694 (if body-content
4695 (setq body-content nil)
4696 (forward-char -1)
4697 (insert "\\ ")
4698 (forward-char 1))
4699 ;;(insert "\\endlines\n")
4700 (insert "\\end{verbatim}\n")
4701 )))
4702 ;;;_ > allout-latexify-exposed (arg &optional tobuf)
4703 (defun allout-latexify-exposed (arg &optional tobuf)
4704 "Format current topics exposed portions to TOBUF for LaTeX processing.
4705 TOBUF defaults to a buffer named the same as the current buffer, but
4706 with \"*\" prepended and \" latex-formed*\" appended.
4707
4708 With repeat count, copy the exposed portions of entire buffer."
4709
4710 (interactive "P")
4711 (if (not tobuf)
4712 (setq tobuf
4713 (get-buffer-create (concat "*" (buffer-name) " latexified*"))))
4714 (let* ((start-pt (point))
4715 (beg (if arg (point-min) (allout-back-to-current-heading)))
4716 (end (if arg (point-max) (allout-end-of-current-subtree)))
4717 (buf (current-buffer)))
4718 (set-buffer tobuf)
4719 (erase-buffer)
4720 (allout-insert-latex-header tobuf)
4721 (goto-char (point-max))
4722 (allout-process-exposed 'allout-latexify-one-item
4723 beg
4724 end
4725 buf
4726 tobuf)
4727 (goto-char (point-max))
4728 (allout-insert-latex-trailer tobuf)
4729 (goto-char (point-min))
4730 (pop-to-buffer buf)
4731 (goto-char start-pt)))
4732
4733 ;;;_ #8 Encryption
4734 ;;;_ > allout-toggle-current-subtree-encryption (&optional fetch-pass)
4735 (defun allout-toggle-current-subtree-encryption (&optional fetch-pass)
4736 "Encrypt clear or decrypt encoded text of visibly-containing topic's contents.
4737
4738 Optional FETCH-PASS universal argument provokes key-pair encryption with
4739 single universal argument. With doubled universal argument \(value = 16),
4740 it forces prompting for the passphrase regardless of availability from the
4741 passphrase cache. With no universal argument, the appropriate passphrase
4742 is obtained from the cache, if available, else from the user.
4743
4744 Currently only GnuPG encryption is supported.
4745
4746 \**NOTE WELL** that the encrypted text must be ascii-armored. For gnupg
4747 encryption, include the option ``armor'' in your ~/.gnupg/gpg.conf file.
4748
4749 Both symmetric-key and key-pair encryption is implemented. Symmetric is
4750 the default, use a single \(x4) universal argument for keypair mode.
4751
4752 Encrypted topic's bullet is set to a `~' to signal that the contents of the
4753 topic \(body and subtopics, but not heading) is pending encryption or
4754 encrypted. `*' asterisk immediately after the bullet signals that the body
4755 is encrypted, its' absence means the topic is meant to be encrypted but is
4756 not. When a file with topics pending encryption is saved, topics pending
4757 encryption are encrypted. See allout-encrypt-unencrypted-on-saves for
4758 auto-encryption specifics.
4759
4760 \**NOTE WELL** that automatic encryption that happens during saves will
4761 default to symmetric encryption - you must manually \(re)encrypt key-pair
4762 encrypted topics if you want them to continue to use the key-pair cipher.
4763
4764 Level-1 topics, with prefix consisting solely of an `*' asterisk, cannot be
4765 encrypted. If you want to encrypt the contents of a top-level topic, use
4766 \\[allout-shift-in] to increase its depth.
4767
4768 Passphrase Caching
4769
4770 The encryption passphrase is solicited if not currently available in the
4771 passphrase cache from a recent encryption action.
4772
4773 The solicited passphrase is retained for reuse in a buffer-specific cache
4774 for some set period of time \(default, 60 seconds), after which the string
4775 is nulled. The passphrase cache timeout is customized by setting
4776 `pgg-passphrase-cache-expiry'.
4777
4778 Symmetric Passphrase Hinting and Verification
4779
4780 If the file previously had no associated passphrase, or had a different
4781 passphrase than specified, the user is prompted to repeat the new one for
4782 corroboration. A random string encrypted by the new passphrase is set on
4783 the buffer-specific variable `allout-passphrase-verifier-string', for
4784 confirmation of the passphrase when next obtained, before encrypting or
4785 decrypting anything with it. This helps avoid mistakenly shifting between
4786 keys.
4787
4788 If allout customization var `allout-passphrase-verifier-handling' is
4789 non-nil, an entry for `allout-passphrase-verifier-string' and its value is
4790 added to an Emacs 'local variables' section at the end of the file, which
4791 is created if necessary. That setting is for retention of the passphrase
4792 verifier across emacs sessions.
4793
4794 Similarly, `allout-passphrase-hint-string' stores a user-provided reminder
4795 about their passphrase, and `allout-passphrase-hint-handling' specifies
4796 when the hint is presented, or if passphrase hints are disabled. If
4797 enabled \(see the `allout-passphrase-hint-handling' docstring for details),
4798 the hint string is stored in the local-variables section of the file, and
4799 solicited whenever the passphrase is changed."
4800 (interactive "P")
4801 (save-excursion
4802 (allout-back-to-current-heading)
4803 (allout-toggle-subtree-encryption fetch-pass)
4804 )
4805 )
4806 ;;;_ > allout-toggle-subtree-encryption (&optional fetch-pass)
4807 (defun allout-toggle-subtree-encryption (&optional fetch-pass)
4808 "Encrypt clear text or decrypt encoded topic contents \(body and subtopics.)
4809
4810 Optional FETCH-PASS universal argument provokes key-pair encryption with
4811 single universal argument. With doubled universal argument \(value = 16),
4812 it forces prompting for the passphrase regardless of availability from the
4813 passphrase cache. With no universal argument, the appropriate passphrase
4814 is obtained from the cache, if available, else from the user.
4815
4816 Currently only GnuPG encryption is supported.
4817
4818 \**NOTE WELL** that the encrypted text must be ascii-armored. For gnupg
4819 encryption, include the option ``armor'' in your ~/.gnupg/gpg.conf file.
4820
4821 See `allout-toggle-current-subtree-encryption' for more details."
4822
4823 (interactive "P")
4824 (save-excursion
4825 (allout-end-of-prefix t)
4826
4827 (if (= (allout-recent-depth) 1)
4828 (error (concat "Cannot encrypt or decrypt level 1 topics -"
4829 " shift it in to make it encryptable")))
4830
4831 (let* ((allout-buffer (current-buffer))
4832 ;; Asses location:
4833 (after-bullet-pos (point))
4834 (was-encrypted
4835 (progn (if (= (point-max) after-bullet-pos)
4836 (error "no body to encrypt"))
4837 (allout-encrypted-topic-p)))
4838 (was-collapsed (if (not (search-forward "\n" nil t))
4839 nil
4840 (backward-char 1)
4841 (allout-hidden-p)))
4842 (subtree-beg (1+ (point)))
4843 (subtree-end (allout-end-of-subtree))
4844 (subject-text (buffer-substring-no-properties subtree-beg
4845 subtree-end))
4846 (subtree-end-char (char-after (1- subtree-end)))
4847 (subtree-trailing-char (char-after subtree-end))
4848 ;; kluge - result-text needs to be nil, but we also want to
4849 ;; check for the error condition
4850 (result-text (if (or (string= "" subject-text)
4851 (string= "\n" subject-text))
4852 (error "No topic contents to %scrypt"
4853 (if was-encrypted "de" "en"))
4854 nil))
4855 ;; Assess key parameters:
4856 (key-info (or
4857 ;; detect the type by which it is already encrypted
4858 (and was-encrypted
4859 (allout-encrypted-key-info subject-text))
4860 (and (member fetch-pass '(4 (4)))
4861 '(keypair nil))
4862 '(symmetric nil)))
4863 (for-key-type (car key-info))
4864 (for-key-identity (cadr key-info))
4865 (fetch-pass (and fetch-pass (member fetch-pass '(16 (16))))))
4866
4867 (setq result-text
4868 (allout-encrypt-string subject-text was-encrypted
4869 (current-buffer)
4870 for-key-type for-key-identity fetch-pass))
4871
4872 ;; Replace the subtree with the processed product.
4873 (allout-unprotected
4874 (progn
4875 (set-buffer allout-buffer)
4876 (delete-region subtree-beg subtree-end)
4877 (insert result-text)
4878 (if was-collapsed
4879 (allout-flag-region (1- subtree-beg) (point) t))
4880 ;; adjust trailing-blank-lines to preserve topic spacing:
4881 (if (not was-encrypted)
4882 (if (and (= subtree-end-char ?\n)
4883 (= subtree-trailing-char ?\n))
4884 (insert subtree-trailing-char)))
4885 ;; Ensure that the item has an encrypted-entry bullet:
4886 (if (not (string= (buffer-substring-no-properties
4887 (1- after-bullet-pos) after-bullet-pos)
4888 allout-topic-encryption-bullet))
4889 (progn (goto-char (1- after-bullet-pos))
4890 (delete-char 1)
4891 (insert allout-topic-encryption-bullet)))
4892 (if was-encrypted
4893 ;; Remove the is-encrypted bullet qualifier:
4894 (progn (goto-char after-bullet-pos)
4895 (delete-char 1))
4896 ;; Add the is-encrypted bullet qualifier:
4897 (goto-char after-bullet-pos)
4898 (insert "*"))
4899 )
4900 )
4901 )
4902 )
4903 )
4904 ;;;_ > allout-encrypt-string (text decrypt allout-buffer key-type for-key
4905 ;;; fetch-pass &optional retried verifying
4906 ;;; passphrase)
4907 (defun allout-encrypt-string (text decrypt allout-buffer key-type for-key
4908 fetch-pass &optional retried verifying
4909 passphrase)
4910 "Encrypt or decrypt message TEXT.
4911
4912 If DECRYPT is true (default false), then decrypt instead of encrypt.
4913
4914 FETCH-PASS (default false) forces fresh prompting for the passphrase.
4915
4916 KEY-TYPE indicates whether to use a 'symmetric or 'keypair cipher.
4917
4918 FOR-KEY is human readable identification of the first of the user's
4919 eligible secret keys a keypair decryption targets, or else nil.
4920
4921 Optional RETRIED is for internal use - conveys the number of failed keys
4922 that have been solicited in sequence leading to this current call.
4923
4924 Optional PASSPHRASE enables explicit delivery of the decryption passphrase,
4925 for verification purposes.
4926
4927 Returns the resulting string, or nil if the transformation fails."
4928
4929 (require 'pgg)
4930
4931 (if (not (fboundp 'pgg-encrypt-symmetric))
4932 (error "Allout encryption depends on a newer version of pgg"))
4933
4934 (let* ((scheme (upcase
4935 (format "%s" (or pgg-scheme pgg-default-scheme "GPG"))))
4936 (for-key (and (equal key-type 'keypair)
4937 (or for-key
4938 (split-string (read-string
4939 (format "%s message recipients: "
4940 scheme))
4941 "[ \t,]+"))))
4942 (target-prompt-id (if (equal key-type 'keypair)
4943 (if (= (length for-key) 1)
4944 (car for-key) for-key)
4945 (buffer-name allout-buffer)))
4946 (target-cache-id (format "%s-%s"
4947 key-type
4948 (if (equal key-type 'keypair)
4949 target-prompt-id
4950 (or (buffer-file-name allout-buffer)
4951 target-prompt-id))))
4952 result-text status)
4953
4954 (if (and fetch-pass (not passphrase))
4955 ;; Force later fetch by evicting passphrase from the cache.
4956 (pgg-remove-passphrase-from-cache target-cache-id t))
4957
4958 (catch 'encryption-failed
4959
4960 ;; Obtain the passphrase if we don't already have one and we're not
4961 ;; doing a keypair encryption:
4962 (if (not (or passphrase
4963 (and (equal key-type 'keypair)
4964 (not decrypt))))
4965
4966 (setq passphrase (allout-obtain-passphrase for-key
4967 target-cache-id
4968 target-prompt-id
4969 key-type
4970 allout-buffer
4971 retried fetch-pass)))
4972 (with-temp-buffer
4973
4974 (insert text)
4975
4976 (cond
4977
4978 ;; symmetric:
4979 ((equal key-type 'symmetric)
4980 (setq status
4981 (if decrypt
4982
4983 (pgg-decrypt (point-min) (point-max) passphrase)
4984
4985 (pgg-encrypt-symmetric (point-min) (point-max)
4986 passphrase)))
4987
4988 (if status
4989 (pgg-situate-output (point-min) (point-max))
4990 ;; failed - handle passphrase caching
4991 (if verifying
4992 (throw 'encryption-failed nil)
4993 (pgg-remove-passphrase-from-cache target-cache-id t)
4994 (error "Symmetric-cipher encryption failed - %s"
4995 "try again with different passphrase."))))
4996
4997 ;; encrypt 'keypair:
4998 ((not decrypt)
4999
5000 (setq status
5001
5002 (pgg-encrypt for-key
5003 nil (point-min) (point-max) passphrase))
5004
5005 (if status
5006 (pgg-situate-output (point-min) (point-max))
5007 (error (pgg-remove-passphrase-from-cache target-cache-id t)
5008 (error "encryption failed"))))
5009
5010 ;; decrypt 'keypair:
5011 (t
5012
5013 (setq status
5014 (pgg-decrypt (point-min) (point-max) passphrase))
5015
5016 (if status
5017 (pgg-situate-output (point-min) (point-max))
5018 (error (pgg-remove-passphrase-from-cache target-cache-id t)
5019 (error "decryption failed"))))
5020 )
5021
5022 (setq result-text
5023 (buffer-substring 1 (- (point-max) (if decrypt 0 1))))
5024
5025 ;; validate result - non-empty
5026 (cond ((not result-text)
5027 (if verifying
5028 nil
5029 ;; transform was fruitless, retry w/new passphrase.
5030 (pgg-remove-passphrase-from-cache target-cache-id t)
5031 (allout-encrypt-string text allout-buffer decrypt nil
5032 (if retried (1+ retried) 1)
5033 passphrase)))
5034
5035 ;; Barf if encryption yields extraordinary control chars:
5036 ((and (not decrypt)
5037 (string-match "[\C-a\C-k\C-o-\C-z\C-@]"
5038 result-text))
5039 (error (concat "encryption produced unusable"
5040 " non-armored text - reconfigure!")))
5041
5042 ;; valid result and just verifying or non-symmetric:
5043 ((or verifying (not (equal key-type 'symmetric)))
5044 (if (or verifying decrypt)
5045 (pgg-add-passphrase-to-cache target-cache-id
5046 passphrase t))
5047 result-text)
5048
5049 ;; valid result and regular symmetric - "register"
5050 ;; passphrase with mnemonic aids/cache.
5051 (t
5052 (set-buffer allout-buffer)
5053 (if passphrase
5054 (pgg-add-passphrase-to-cache target-cache-id
5055 passphrase t))
5056 (allout-update-passphrase-mnemonic-aids for-key passphrase
5057 allout-buffer)
5058 result-text)
5059 )
5060 )
5061 )
5062 )
5063 )
5064 ;;;_ > allout-obtain-passphrase (for-key cache-id prompt-id key-type
5065 ;;; allout-buffer retried fetch-pass)
5066 (defun allout-obtain-passphrase (for-key cache-id prompt-id key-type
5067 allout-buffer retried fetch-pass)
5068 "Obtain passphrase for a key from the cache or else from the user.
5069
5070 When obtaining from the user, symmetric-cipher passphrases are verified
5071 against either, if available and enabled, a random string that was
5072 encrypted against the passphrase, or else against repeated entry by the
5073 user for corroboration.
5074
5075 FOR-KEY is the key for which the passphrase is being obtained.
5076
5077 CACHE-ID is the cache id of the key for the passphrase.
5078
5079 PROMPT-ID is the id for use when prompting the user.
5080
5081 KEY-TYPE is either 'symmetric or 'keypair.
5082
5083 ALLOUT-BUFFER is the buffer containing the entry being en/decrypted.
5084
5085 RETRIED is the number of this attempt to obtain this passphrase.
5086
5087 FETCH-PASS causes the passphrase to be solicited from the user, regardless
5088 of the availability of a cached copy."
5089
5090 (if (not (equal key-type 'symmetric))
5091 ;; do regular passphrase read on non-symmetric passphrase:
5092 (pgg-read-passphrase (format "%s passphrase%s: "
5093 (upcase (format "%s" (or pgg-scheme
5094 pgg-default-scheme
5095 "GPG")))
5096 (if prompt-id
5097 (format " for %s" prompt-id)
5098 ""))
5099 cache-id t)
5100
5101 ;; Symmetric hereon:
5102
5103 (save-excursion
5104 (set-buffer allout-buffer)
5105 (let* ((hint (if (and (not (string= allout-passphrase-hint-string ""))
5106 (or (equal allout-passphrase-hint-handling 'always)
5107 (and (equal allout-passphrase-hint-handling
5108 'needed)
5109 retried)))
5110 (format " [%s]" allout-passphrase-hint-string)
5111 ""))
5112 (retry-message (if retried (format " (%s retry)" retried) ""))
5113 (prompt-sans-hint (format "'%s' symmetric passphrase%s: "
5114 prompt-id retry-message))
5115 (full-prompt (format "'%s' symmetric passphrase%s%s: "
5116 prompt-id hint retry-message))
5117 (prompt full-prompt)
5118 (verifier-string (allout-get-encryption-passphrase-verifier))
5119
5120 (cached (and (not fetch-pass)
5121 (pgg-read-passphrase-from-cache cache-id t)))
5122 (got-pass (or cached
5123 (pgg-read-passphrase full-prompt cache-id t)))
5124
5125 confirmation)
5126
5127 (if (not got-pass)
5128 nil
5129
5130 ;; Duplicate our handle on the passphrase so it's not clobbered by
5131 ;; deactivate-passwd memory clearing:
5132 (setq got-pass (format "%s" got-pass))
5133
5134 (cond (verifier-string
5135 (save-window-excursion
5136 (if (allout-encrypt-string verifier-string 'decrypt
5137 allout-buffer 'symmetric
5138 for-key nil 0 'verifying
5139 got-pass)
5140 (setq confirmation (format "%s" got-pass))))
5141
5142 (if (and (not confirmation)
5143 (if (yes-or-no-p
5144 (concat "Passphrase differs from established"
5145 " - use new one instead? "))
5146 ;; deactivate password for subsequent
5147 ;; confirmation:
5148 (progn
5149 (pgg-remove-passphrase-from-cache cache-id t)
5150 (setq prompt prompt-sans-hint)
5151 nil)
5152 t))
5153 (progn (pgg-remove-passphrase-from-cache cache-id t)
5154 (error "Wrong passphrase."))))
5155 ;; No verifier string - force confirmation by repetition of
5156 ;; (new) passphrase:
5157 ((or fetch-pass (not cached))
5158 (pgg-remove-passphrase-from-cache cache-id t))))
5159 ;; confirmation vs new input - doing pgg-read-passphrase will do the
5160 ;; right thing, in either case:
5161 (if (not confirmation)
5162 (setq confirmation
5163 (pgg-read-passphrase (concat prompt
5164 " ... confirm spelling: ")
5165 cache-id t)))
5166 (prog1
5167 (if (equal got-pass confirmation)
5168 confirmation
5169 (if (yes-or-no-p (concat "spelling of original and"
5170 " confirmation differ - retry? "))
5171 (progn (setq retried (if retried (1+ retried) 1))
5172 (pgg-remove-passphrase-from-cache cache-id t)
5173 ;; recurse to this routine:
5174 (pgg-read-passphrase prompt-sans-hint cache-id t))
5175 (pgg-remove-passphrase-from-cache cache-id t)
5176 (error "Confirmation failed.")))
5177 ;; reduce opportunity for memory cherry-picking by zeroing duplicate:
5178 (dotimes (i (length got-pass))
5179 (aset got-pass i 0))
5180 )
5181 )
5182 )
5183 )
5184 )
5185 ;;;_ > allout-encrypted-topic-p ()
5186 (defun allout-encrypted-topic-p ()
5187 "True if the current topic is encryptable and encrypted."
5188 (save-excursion
5189 (allout-end-of-prefix t)
5190 (and (string= (buffer-substring-no-properties (1- (point)) (point))
5191 allout-topic-encryption-bullet)
5192 (looking-at "\\*"))
5193 )
5194 )
5195 ;;;_ > allout-encrypted-key-info (text)
5196 ;; XXX gpg-specific, alas
5197 (defun allout-encrypted-key-info (text)
5198 "Return a pair of the key type and identity of a recipient's secret key.
5199
5200 The key type is one of 'symmetric or 'keypair.
5201
5202 if 'keypair, and some of the user's secret keys are among those for which
5203 the message was encoded, return the identity of the first. otherwise,
5204 return nil for the second item of the pair.
5205
5206 An error is raised if the text is not encrypted."
5207 (require 'pgg-parse)
5208 (save-excursion
5209 (with-temp-buffer
5210 (insert text)
5211 (let* ((parsed-armor (pgg-parse-armor-region (point-min) (point-max)))
5212 (type (if (pgg-gpg-symmetric-key-p parsed-armor)
5213 'symmetric
5214 'keypair))
5215 secret-keys first-secret-key for-key-owner)
5216 (if (equal type 'keypair)
5217 (setq secret-keys (pgg-gpg-lookup-all-secret-keys)
5218 first-secret-key (pgg-gpg-select-matching-key parsed-armor
5219 secret-keys)
5220 for-key-owner (and first-secret-key
5221 (pgg-gpg-lookup-key-owner
5222 first-secret-key))))
5223 (list type (pgg-gpg-key-id-from-key-owner for-key-owner))
5224 )
5225 )
5226 )
5227 )
5228 ;;;_ > allout-create-encryption-passphrase-verifier (passphrase)
5229 (defun allout-create-encryption-passphrase-verifier (passphrase)
5230 "Encrypt random message for later validation of symmetric key's passphrase."
5231 ;; use 20 random ascii characters, across the entire ascii range.
5232 (random t)
5233 (let ((spew (make-string 20 ?\0)))
5234 (dotimes (i (length spew))
5235 (aset spew i (1+ (random 254))))
5236 (allout-encrypt-string spew nil (current-buffer) 'symmetric
5237 nil nil 0 passphrase))
5238 )
5239 ;;;_ > allout-update-passphrase-mnemonic-aids (for-key passphrase
5240 ;;; outline-buffer)
5241 (defun allout-update-passphrase-mnemonic-aids (for-key passphrase
5242 outline-buffer)
5243 "Update passphrase verifier and hint strings if necessary.
5244
5245 See `allout-passphrase-verifier-string' and `allout-passphrase-hint-string'
5246 settings.
5247
5248 PASSPHRASE is the passphrase being mnemonicized
5249
5250 OUTLINE-BUFFER is the buffer of the outline being adjusted.
5251
5252 These are used to help the user keep track of the passphrase they use for
5253 symmetric encryption in the file.
5254
5255 Behavior is governed by `allout-passphrase-verifier-handling',
5256 `allout-passphrase-hint-handling', and also, controlling whether the values
5257 are preserved on Emacs local file variables,
5258 `allout-enable-file-variable-adjustment'."
5259
5260 ;; If passphrase doesn't agree with current verifier:
5261 ;; - adjust the verifier
5262 ;; - if passphrase hint handling is enabled, adjust the passphrase hint
5263 ;; - if file var settings are enabled, adjust the file vars
5264
5265 (let* ((new-verifier-needed (not (allout-verify-passphrase
5266 for-key passphrase outline-buffer)))
5267 (new-verifier-string
5268 (if new-verifier-needed
5269 ;; Collapse to a single line and enclose in string quotes:
5270 (subst-char-in-string
5271 ?\n ?\C-a (allout-create-encryption-passphrase-verifier
5272 passphrase))))
5273 new-hint)
5274 (when new-verifier-string
5275 ;; do the passphrase hint first, since it's interactive
5276 (when (and allout-passphrase-hint-handling
5277 (not (equal allout-passphrase-hint-handling 'disabled)))
5278 (setq new-hint
5279 (read-from-minibuffer "Passphrase hint to jog your memory: "
5280 allout-passphrase-hint-string))
5281 (when (not (string= new-hint allout-passphrase-hint-string))
5282 (setq allout-passphrase-hint-string new-hint)
5283 (allout-adjust-file-variable "allout-passphrase-hint-string"
5284 allout-passphrase-hint-string)))
5285 (when allout-passphrase-verifier-handling
5286 (setq allout-passphrase-verifier-string new-verifier-string)
5287 (allout-adjust-file-variable "allout-passphrase-verifier-string"
5288 allout-passphrase-verifier-string))
5289 )
5290 )
5291 )
5292 ;;;_ > allout-get-encryption-passphrase-verifier ()
5293 (defun allout-get-encryption-passphrase-verifier ()
5294 "Return text of the encrypt passphrase verifier, unmassaged, or nil if none.
5295
5296 Derived from value of `allout-file-passphrase-verifier-string'."
5297
5298 (let ((verifier-string (and (boundp 'allout-passphrase-verifier-string)
5299 allout-passphrase-verifier-string)))
5300 (if verifier-string
5301 ;; Return it uncollapsed
5302 (subst-char-in-string ?\C-a ?\n verifier-string))
5303 )
5304 )
5305 ;;;_ > allout-verify-passphrase (key passphrase allout-buffer)
5306 (defun allout-verify-passphrase (key passphrase allout-buffer)
5307 "True if passphrase successfully decrypts verifier, nil otherwise.
5308
5309 \"Otherwise\" includes absence of passphrase verifier."
5310 (save-excursion
5311 (set-buffer allout-buffer)
5312 (and (boundp 'allout-passphrase-verifier-string)
5313 allout-passphrase-verifier-string
5314 (allout-encrypt-string (allout-get-encryption-passphrase-verifier)
5315 'decrypt allout-buffer 'symmetric
5316 key nil 0 'verifying passphrase)
5317 t)))
5318 ;;;_ > allout-next-topic-pending-encryption (&optional except-mark)
5319 (defun allout-next-topic-pending-encryption (&optional except-mark)
5320 "Return the point of the next topic pending encryption, or nil if none.
5321
5322 EXCEPT-MARK identifies a point whose containing topics should be excluded
5323 from encryption. This supports 'except-current mode of
5324 `allout-encrypt-unencrypted-on-saves'.
5325
5326 Such a topic has the allout-topic-encryption-bullet without an
5327 immediately following '*' that would mark the topic as being encrypted. It
5328 must also have content."
5329 (let (done got content-beg)
5330 (while (not done)
5331
5332 (if (not (re-search-forward
5333 (format "\\(\\`\\|\n\\)%s *%s[^*]"
5334 (regexp-quote allout-header-prefix)
5335 (regexp-quote allout-topic-encryption-bullet))
5336 nil t))
5337 (setq got nil
5338 done t)
5339 (goto-char (setq got (match-beginning 0)))
5340 (if (looking-at "\n")
5341 (forward-char 1))
5342 (setq got (point)))
5343
5344 (cond ((not got)
5345 (setq done t))
5346
5347 ((not (search-forward "\n"))
5348 (setq got nil
5349 done t))
5350
5351 ((eobp)
5352 (setq got nil
5353 done t))
5354
5355 (t
5356 (setq content-beg (point))
5357 (backward-char 1)
5358 (allout-end-of-subtree)
5359 (if (or (<= (point) content-beg)
5360 (and except-mark
5361 (<= content-beg except-mark)
5362 (>= (point) except-mark)))
5363 ;; Continue looking
5364 (setq got nil)
5365 ;; Got it!
5366 (setq done t)))
5367 )
5368 )
5369 (if got
5370 (goto-char got))
5371 )
5372 )
5373 ;;;_ > allout-encrypt-decrypted (&optional except-mark)
5374 (defun allout-encrypt-decrypted (&optional except-mark)
5375 "Encrypt topics pending encryption except those containing exemption point.
5376
5377 EXCEPT-MARK identifies a point whose containing topics should be excluded
5378 from encryption. This supports 'except-current mode of
5379 `allout-encrypt-unencrypted-on-saves'.
5380
5381 If a topic that is currently being edited was encrypted, we return a list
5382 containing the location of the topic and the location of the cursor just
5383 before the topic was encrypted. This can be used, eg, to decrypt the topic
5384 and exactly resituate the cursor if this is being done as part of a file
5385 save. See `allout-encrypt-unencrypted-on-saves' for more info."
5386
5387 (interactive "p")
5388 (save-excursion
5389 (let* ((current-mark (point-marker))
5390 (current-mark-position (marker-position current-mark))
5391 was-modified
5392 bo-subtree
5393 editing-topic editing-point)
5394 (goto-char (point-min))
5395 (while (allout-next-topic-pending-encryption except-mark)
5396 (setq was-modified (buffer-modified-p))
5397 (when (save-excursion
5398 (and (boundp 'allout-encrypt-unencrypted-on-saves)
5399 allout-encrypt-unencrypted-on-saves
5400 (setq bo-subtree (re-search-forward "$"))
5401 (not (allout-hidden-p))
5402 (>= current-mark (point))
5403 (allout-end-of-current-subtree)
5404 (<= current-mark (point))))
5405 (setq editing-topic (point)
5406 ;; we had to wait for this 'til now so prior topics are
5407 ;; encrypted, any relevant text shifts are in place:
5408 editing-point (- current-mark-position
5409 (count-trailing-whitespace-region
5410 bo-subtree current-mark-position))))
5411 (allout-toggle-subtree-encryption)
5412 (if (not was-modified)
5413 (set-buffer-modified-p nil))
5414 )
5415 (if (not was-modified)
5416 (set-buffer-modified-p nil))
5417 (if editing-topic (list editing-topic editing-point))
5418 )
5419 )
5420 )
5421
5422 ;;;_ #9 miscellaneous
5423 ;;;_ > allout-mark-topic ()
5424 (defun allout-mark-topic ()
5425 "Put the region around topic currently containing point."
5426 (interactive)
5427 (beginning-of-line)
5428 (allout-goto-prefix)
5429 (push-mark (point))
5430 (allout-end-of-current-subtree)
5431 (exchange-point-and-mark))
5432 ;;;_ > outlineify-sticky ()
5433 ;; outlinify-sticky is correct spelling; provide this alias for sticklers:
5434 ;;;###autoload
5435 (defalias 'outlinify-sticky 'outlineify-sticky)
5436 ;;;###autoload
5437 (defun outlineify-sticky (&optional arg)
5438 "Activate outline mode and establish file var so it is started subsequently.
5439
5440 See doc-string for `allout-layout' and `allout-init' for details on
5441 setup for auto-startup."
5442
5443 (interactive "P")
5444
5445 (allout-mode t)
5446
5447 (save-excursion
5448 (goto-char (point-min))
5449 (if (looking-at allout-regexp)
5450 t
5451 (allout-open-topic 2)
5452 (insert (concat "Dummy outline topic header - see"
5453 "`allout-mode' docstring: `^Hm'."))
5454 (allout-adjust-file-variable
5455 "allout-layout" (format "%s" (or allout-layout '(-1 : 0)))))))
5456 ;;;_ > allout-file-vars-section-data ()
5457 (defun allout-file-vars-section-data ()
5458 "Return data identifying the file-vars section, or nil if none.
5459
5460 Returns list `(beginning-point prefix-string suffix-string)'."
5461 ;; minimally gleaned from emacs 21.4 files.el hack-local-variables function.
5462 (let (beg prefix suffix)
5463 (save-excursion
5464 (goto-char (point-max))
5465 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
5466 (if (let ((case-fold-search t))
5467 (not (search-forward "Local Variables:" nil t)))
5468 nil
5469 (setq beg (- (point) 16))
5470 (setq suffix (buffer-substring-no-properties
5471 (point)
5472 (progn (if (search-forward "\n" nil t)
5473 (forward-char -1))
5474 (point))))
5475 (setq prefix (buffer-substring-no-properties
5476 (progn (if (search-backward "\n" nil t)
5477 (forward-char 1))
5478 (point))
5479 beg))
5480 (list beg prefix suffix))
5481 )
5482 )
5483 )
5484 ;;;_ > allout-adjust-file-variable (varname value)
5485 (defun allout-adjust-file-variable (varname value)
5486 "Adjust the setting of an emacs file variable named VARNAME to VALUE.
5487
5488 This activity is inhibited if either `enable-local-variables'
5489 `allout-enable-file-variable-adjustment' are nil.
5490
5491 When enabled, an entry for the variable is created if not already present,
5492 or changed if established with a different value. The section for the file
5493 variables, itself, is created if not already present. When created, the
5494 section lines \(including the section line) exist as second-level topics in
5495 a top-level topic at the end of the file.
5496
5497 enable-local-variables must be true for any of this to happen."
5498 (if (not (and enable-local-variables
5499 allout-enable-file-variable-adjustment))
5500 nil
5501 (save-excursion
5502 (let ((section-data (allout-file-vars-section-data))
5503 beg prefix suffix)
5504 (if section-data
5505 (setq beg (car section-data)
5506 prefix (cadr section-data)
5507 suffix (car (cddr section-data)))
5508 ;; create the section
5509 (goto-char (point-max))
5510 (open-line 1)
5511 (allout-open-topic 0)
5512 (end-of-line)
5513 (insert "Local emacs vars.\n")
5514 (allout-open-topic 1)
5515 (setq beg (point)
5516 suffix ""
5517 prefix (buffer-substring-no-properties (progn
5518 (beginning-of-line)
5519 (point))
5520 beg))
5521 (goto-char beg)
5522 (insert "Local variables:\n")
5523 (allout-open-topic 0)
5524 (insert "End:\n")
5525 )
5526 ;; look for existing entry or create one, leaving point for insertion
5527 ;; of new value:
5528 (goto-char beg)
5529 (allout-show-to-offshoot)
5530 (if (search-forward (concat "\n" prefix varname ":") nil t)
5531 (let* ((value-beg (point))
5532 (line-end (progn (if (search-forward "\n" nil t)
5533 (forward-char -1))
5534 (point)))
5535 (value-end (- line-end (length suffix))))
5536 (if (> value-end value-beg)
5537 (delete-region value-beg value-end)))
5538 (end-of-line)
5539 (open-line 1)
5540 (forward-line 1)
5541 (insert (concat prefix varname ":")))
5542 (insert (format " %S%s" value suffix))
5543 )
5544 )
5545 )
5546 )
5547 ;;;_ > solicit-char-in-string (prompt string &optional do-defaulting)
5548 (defun solicit-char-in-string (prompt string &optional do-defaulting)
5549 "Solicit (with first arg PROMPT) choice of a character from string STRING.
5550
5551 Optional arg DO-DEFAULTING indicates to accept empty input (CR)."
5552
5553 (let ((new-prompt prompt)
5554 got)
5555
5556 (while (not got)
5557 (message "%s" new-prompt)
5558
5559 ;; We do our own reading here, so we can circumvent, eg, special
5560 ;; treatment for `?' character. (Oughta use minibuffer keymap instead.)
5561 (setq got
5562 (char-to-string (let ((cursor-in-echo-area nil)) (read-char))))
5563
5564 (setq got
5565 (cond ((string-match (regexp-quote got) string) got)
5566 ((and do-defaulting (string= got "\r"))
5567 ;; Return empty string to default:
5568 "")
5569 ((string= got "\C-g") (signal 'quit nil))
5570 (t
5571 (setq new-prompt (concat prompt
5572 got
5573 " ...pick from: "
5574 string
5575 ""))
5576 nil))))
5577 ;; got something out of loop - return it:
5578 got)
5579 )
5580 ;;;_ > regexp-sans-escapes (string)
5581 (defun regexp-sans-escapes (regexp &optional successive-backslashes)
5582 "Return a copy of REGEXP with all character escapes stripped out.
5583
5584 Representations of actual backslashes - '\\\\\\\\' - are left as a
5585 single backslash.
5586
5587 Optional arg SUCCESSIVE-BACKSLASHES is used internally for recursion."
5588
5589 (if (string= regexp "")
5590 ""
5591 ;; Set successive-backslashes to number if current char is
5592 ;; backslash, or else to nil:
5593 (setq successive-backslashes
5594 (if (= (aref regexp 0) ?\\)
5595 (if successive-backslashes (1+ successive-backslashes) 1)
5596 nil))
5597 (if (or (not successive-backslashes) (= 2 successive-backslashes))
5598 ;; Include first char:
5599 (concat (substring regexp 0 1)
5600 (regexp-sans-escapes (substring regexp 1)))
5601 ;; Exclude first char, but maintain count:
5602 (regexp-sans-escapes (substring regexp 1) successive-backslashes))))
5603 ;;;_ > count-trailing-whitespace-region (beg end)
5604 (defun count-trailing-whitespace-region (beg end)
5605 "Return number of trailing whitespace chars between BEG and END.
5606
5607 If BEG is bigger than END we return 0."
5608 (if (> beg end)
5609 0
5610 (save-excursion
5611 (goto-char beg)
5612 (let ((count 0))
5613 (while (re-search-forward "[ ][ ]*$" end t)
5614 (goto-char (1+ (match-beginning 0)))
5615 (setq count (1+ count)))
5616 count))))
5617 ;;;_ > allout-mark-marker to accommodate divergent emacsen:
5618 (defun allout-mark-marker (&optional force buffer)
5619 "Accommodate the different signature for `mark-marker' across Emacsen.
5620
5621 XEmacs takes two optional args, while mainline GNU Emacs does not,
5622 so pass them along when appropriate."
5623 (if (featurep 'xemacs)
5624 (apply 'mark-marker force buffer)
5625 (mark-marker)))
5626 ;;;_ > subst-char-in-string if necessary
5627 (if (not (fboundp 'subst-char-in-string))
5628 (defun subst-char-in-string (fromchar tochar string &optional inplace)
5629 "Replace FROMCHAR with TOCHAR in STRING each time it occurs.
5630 Unless optional argument INPLACE is non-nil, return a new string."
5631 (let ((i (length string))
5632 (newstr (if inplace string (copy-sequence string))))
5633 (while (> i 0)
5634 (setq i (1- i))
5635 (if (eq (aref newstr i) fromchar)
5636 (aset newstr i tochar)))
5637 newstr)))
5638 ;;;_ > wholenump if necessary
5639 (if (not (fboundp 'wholenump))
5640 (defalias 'wholenump 'natnump))
5641 ;;;_ > remove-overlays if necessary
5642 (if (not (fboundp 'remove-overlays))
5643 (defun remove-overlays (&optional beg end name val)
5644 "Clear BEG and END of overlays whose property NAME has value VAL.
5645 Overlays might be moved and/or split.
5646 BEG and END default respectively to the beginning and end of buffer."
5647 (unless beg (setq beg (point-min)))
5648 (unless end (setq end (point-max)))
5649 (if (< end beg)
5650 (setq beg (prog1 end (setq end beg))))
5651 (save-excursion
5652 (dolist (o (overlays-in beg end))
5653 (when (eq (overlay-get o name) val)
5654 ;; Either push this overlay outside beg...end
5655 ;; or split it to exclude beg...end
5656 ;; or delete it entirely (if it is contained in beg...end).
5657 (if (< (overlay-start o) beg)
5658 (if (> (overlay-end o) end)
5659 (progn
5660 (move-overlay (copy-overlay o)
5661 (overlay-start o) beg)
5662 (move-overlay o end (overlay-end o)))
5663 (move-overlay o (overlay-start o) beg))
5664 (if (> (overlay-end o) end)
5665 (move-overlay o end (overlay-end o))
5666 (delete-overlay o)))))))
5667 )
5668 ;;;_ > copy-overlay if necessary - xemacs ~ 21.4
5669 (if (not (fboundp 'copy-overlay))
5670 (defun copy-overlay (o)
5671 "Return a copy of overlay O."
5672 (let ((o1 (make-overlay (overlay-start o) (overlay-end o)
5673 ;; FIXME: there's no easy way to find the
5674 ;; insertion-type of the two markers.
5675 (overlay-buffer o)))
5676 (props (overlay-properties o)))
5677 (while props
5678 (overlay-put o1 (pop props) (pop props)))
5679 o1)))
5680 ;;;_ > add-to-invisibility-spec if necessary - xemacs ~ 21.4
5681 (if (not (fboundp 'add-to-invisibility-spec))
5682 (defun add-to-invisibility-spec (element)
5683 "Add ELEMENT to `buffer-invisibility-spec'.
5684 See documentation for `buffer-invisibility-spec' for the kind of elements
5685 that can be added."
5686 (if (eq buffer-invisibility-spec t)
5687 (setq buffer-invisibility-spec (list t)))
5688 (setq buffer-invisibility-spec
5689 (cons element buffer-invisibility-spec))))
5690 ;;;_ > remove-from-invisibility-spec if necessary - xemacs ~ 21.4
5691 (if (not (fboundp 'remove-from-invisibility-spec))
5692 (defun remove-from-invisibility-spec (element)
5693 "Remove ELEMENT from `buffer-invisibility-spec'."
5694 (if (consp buffer-invisibility-spec)
5695 (setq buffer-invisibility-spec (delete element
5696 buffer-invisibility-spec)))))
5697 ;;;_ > move-beginning-of-line if necessary - older emacs, xemacs
5698 (if (not (fboundp 'move-beginning-of-line))
5699 (defun move-beginning-of-line (arg)
5700 "Move point to beginning of current line as displayed.
5701 \(This disregards invisible newlines such as those
5702 which are part of the text that an image rests on.)
5703
5704 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5705 If point reaches the beginning or end of buffer, it stops there.
5706 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
5707
5708 This function does not move point across a field boundary unless that
5709 would move point to a different line than the original, unconstrained
5710 result. If N is nil or 1, and a front-sticky field starts at point,
5711 the point does not move. To ignore field boundaries bind
5712 `inhibit-field-text-motion' to t."
5713 (interactive "p")
5714 (or arg (setq arg 1))
5715 (if (/= arg 1)
5716 (condition-case nil (line-move (1- arg)) (error nil)))
5717
5718 (let ((orig (point)))
5719 ;; Move to beginning-of-line, ignoring fields and invisibles.
5720 (skip-chars-backward "^\n")
5721 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
5722 (goto-char (if (featurep 'xemacs)
5723 (previous-property-change (point))
5724 (previous-char-property-change (point))))
5725 (skip-chars-backward "^\n"))
5726 (vertical-motion 0)
5727 (if (/= orig (point))
5728 (goto-char (constrain-to-field (point) orig (/= arg 1) t nil)))))
5729 )
5730 ;;;_ > move-end-of-line if necessary - older emacs, xemacs
5731 (if (not (fboundp 'move-end-of-line))
5732 (defun move-end-of-line (arg)
5733 "Move point to end of current line as displayed.
5734 \(This disregards invisible newlines such as those
5735 which are part of the text that an image rests on.)
5736
5737 With argument ARG not nil or 1, move forward ARG - 1 lines first.
5738 If point reaches the beginning or end of buffer, it stops there.
5739 To ignore intangibility, bind `inhibit-point-motion-hooks' to t.
5740
5741 This function does not move point across a field boundary unless that
5742 would move point to a different line than the original, unconstrained
5743 result. If N is nil or 1, and a rear-sticky field ends at point,
5744 the point does not move. To ignore field boundaries bind
5745 `inhibit-field-text-motion' to t."
5746 (interactive "p")
5747 (or arg (setq arg 1))
5748 (let ((orig (point))
5749 done)
5750 (while (not done)
5751 (let ((newpos
5752 (save-excursion
5753 (let ((goal-column 0))
5754 (and (condition-case nil
5755 (or (line-move arg) t)
5756 (error nil))
5757 (not (bobp))
5758 (progn
5759 (while (and (not (bobp)) (line-move-invisible-p (1- (point))))
5760 (goto-char (previous-char-property-change (point))))
5761 (backward-char 1)))
5762 (point)))))
5763 (goto-char newpos)
5764 (if (and (> (point) newpos)
5765 (eq (preceding-char) ?\n))
5766 (backward-char 1)
5767 (if (and (> (point) newpos) (not (eobp))
5768 (not (eq (following-char) ?\n)))
5769 ;; If we skipped something intangible
5770 ;; and now we're not really at eol,
5771 ;; keep going.
5772 (setq arg 1)
5773 (setq done t)))))
5774 (if (/= orig (point))
5775 (goto-char (constrain-to-field (point) orig (/= arg 1) t
5776 nil)))))
5777 )
5778 ;;;_ > line-move-invisible-p if necessary
5779 (if (not (fboundp 'line-move-invisible-p))
5780 (defun line-move-invisible-p (pos)
5781 "Return non-nil if the character after POS is currently invisible."
5782 (let ((prop
5783 (get-char-property pos 'invisible)))
5784 (if (eq buffer-invisibility-spec t)
5785 prop
5786 (or (memq prop buffer-invisibility-spec)
5787 (assq prop buffer-invisibility-spec))))))
5788
5789
5790 ;;;_ #10 Unfinished
5791 ;;;_ > allout-bullet-isearch (&optional bullet)
5792 (defun allout-bullet-isearch (&optional bullet)
5793 "Isearch \(regexp) for topic with bullet BULLET."
5794 (interactive)
5795 (if (not bullet)
5796 (setq bullet (solicit-char-in-string
5797 "ISearch for topic with bullet: "
5798 (regexp-sans-escapes allout-bullets-string))))
5799
5800 (let ((isearch-regexp t)
5801 (isearch-string (concat "^"
5802 allout-header-prefix
5803 "[ \t]*"
5804 bullet)))
5805 (isearch-repeat 'forward)
5806 (isearch-mode t)))
5807
5808 ;;;_ #11 Provide
5809 (provide 'allout)
5810
5811 ;;;_* Local emacs vars.
5812 ;;; The following `allout-layout' local variable setting:
5813 ;;; - closes all topics from the first topic to just before the third-to-last,
5814 ;;; - shows the children of the third to last (config vars)
5815 ;;; - and the second to last (code section),
5816 ;;; - and closes the last topic (this local-variables section).
5817 ;;;Local variables:
5818 ;;;allout-layout: (0 : -1 -1 0)
5819 ;;;End:
5820
5821 ;;; arch-tag: cf38fbc3-c044-450f-8bff-afed8ba5681c
5822 ;;; allout.el ends here