]> git.donarmstrong.com Git - lib.git/blob - emacs_el/tiny-tools/other/folding.el
add tiny-tools
[lib.git] / emacs_el / tiny-tools / other / folding.el
1 ;;; folding.el --- A folding-editor-like minor mode.
2
3 ;; This file is not part of Emacs
4
5 ;; Copyright (C) 2000-2007
6 ;;           Jari Aalto
7 ;; Copyright (C) 1995-1999
8 ;;           Jari Aalto, Anders Lindgren.
9 ;; Copyright (C) 1994
10 ;;           Jari Aalto
11 ;; Copyright (C) 1992, 1993
12 ;;           Jamie Lokier, All rights reserved.
13 ;;
14 ;; Author:      Jamie Lokier <jamie A T imbolc.ucc dt ie>
15 ;;              Jari Aalto <jari aalto A T cante dt net>
16 ;;              Anders Lindgren <andersl A T csd.uu dt se>
17 ;; Maintainer:  Jari Aalto <jari aalto A T cante dt net>
18 ;; Created:     1992
19 ;; Version:     2007.0506
20 ;; VCS-Version: $Revision: 3.42 $
21 ;; VCS-URL:     http://nongnu.org/projects/emacs-tiny-tools/
22 ;; VCS-Date:    $Date: 2007/05/07 10:50:05 $
23 ;; Keywords:    tools
24
25 ;;{{{ GPL
26
27 ;; This program is free software; you can redistribute it and/or
28 ;; modify it under the terms of the GNU General Public License as
29 ;; published by the Free Software Foundation,
30 ;; or (at your option) any later version.
31 ;;
32 ;; GNU Emacs is distributed in the hope that it will be useful,
33 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
34 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35 ;; GNU General Public License for more details.
36 ;;
37 ;; You should have received a copy of the GNU General Public License
38 ;; along with program; see the file COPYING. If not, write to the
39 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
40 ;; Boston, MA 02110-1301, USA.
41 ;;
42 ;; Visit <http://www.gnu.org/copyleft/gpl.html> for more information
43
44 ;;}}}
45
46 ;;; Commentary:
47
48 ;;{{{ Introduction
49
50 ;; Preface
51 ;;
52 ;;      This package provides a minor mode, compatible with all major
53 ;;      editing modes, for folding (hiding) parts of the edited text or
54 ;;      program.
55 ;;
56 ;;      Folding mode handles a document as a tree, where each branch
57 ;;      is bounded by special markers `{{{' and `}}}'. A branch can be
58 ;;      placed inside another branch, creating a complete hierarchical
59 ;;      structure.
60 ;;
61 ;;      Folding mode can CLOSE a fold, leaving only the initial `{{{'
62 ;;      and possibly a comment visible.
63 ;;
64 ;;      It can also ENTER a fold, which means that only the current
65 ;;      fold will be visible, all text above `{{{' and below `}}}'
66 ;;      will be invisible.
67 ;;
68 ;;      Please note, that the maintainers do not recommend to use only
69 ;;      folding for you your code layout and navigation. Folding.el is
70 ;;      on its best when it can "chunk" large sections of code inside
71 ;;      folds. The larger the chunks, the more the usability of
72 ;;      folding will increase. Folding.el is not meant to hide
73 ;;      individual functions: you may be better served by hideshow.el
74 ;;      or imenu.el (which can parse the function indexes)
75
76 ;;}}}
77 ;;{{{ Installation
78
79 ;;  Installation
80 ;;
81 ;;      To install Folding mode, put this file (folding.el) on your
82 ;;      Emacs `load-path' (or extend the load path to include the
83 ;;      directory containing this file) and optionally byte compile it.
84 ;;
85 ;;      The best way to install folding is the autoload installation,
86 ;;      so that folding is loaded into your emacs only when you turn on
87 ;;      `folding-mode'. This statement speeds up loading your .emacs
88 ;;
89 ;;          (autoload 'folding-mode          "folding" "Folding mode" t)
90 ;;          (autoload 'turn-off-folding-mode "folding" "Folding mode" t)
91 ;;          (autoload 'turn-on-folding-mode  "folding" "Folding mode" t)
92 ;;
93 ;;      But if you always use folding, then perhaps you want more
94 ;;      traditional installation. Here Folding mode starts
95 ;;      automatically when you load a folded file.
96 ;;
97 ;;          ;; (setq folding-default-keys-function
98 ;;          ;;      'folding-bind-backward-compatible-keys)
99 ;;
100 ;;          (if (load "folding" 'nomessage 'noerror)
101 ;;              (folding-mode-add-find-file-hook))
102 ;;
103 ;;      Folding uses a keymap which conforms with the new Emacs
104 ;;      (started 19.29) style. The key bindings are prefixed with
105 ;;      "C-c@" instead of old "C-c". To use the old keyboard bindings,
106 ;;      uncomment the lines in the the above installation example
107 ;;
108 ;;      The same folding marks can be used in `vim' editor command
109 ;;      "set fdm=marker".
110 ;;
111 ;;  Uninstallation
112 ;;
113 ;;      To remove folding, call `M-x' `folding-uninstall'.
114 ;;
115 ;;  To read the manual
116 ;;
117 ;;      At any point you can reach the manual with `M-x'
118 ;;      `finder-commentary' RET folding RET.
119
120 ;;}}}
121 ;;{{{ DOCUMENTATION
122
123 ;;  Compatibility
124 ;;
125 ;;      Folding supports following Emacs flavors:
126 ;;
127 ;;          Unix Emacs  19.28+ and Win32 Emacs  19.34+
128 ;;          Unix XEmacs 19.14+ and Win32 XEmacs 21.0+
129 ;;
130 ;;  Compatibility not for old NT Emacs releases
131 ;;
132 ;;      NOTE: folding version starting from 2.47 gets around this bug
133 ;;      by using adviced kill/yank functions. The advice functions are
134 ;;      only instantiated under problematic NT Emacs versions.
135 ;;
136 ;;      Windows NT/9x 19.34 - 20.3.1 (i386-*-nt4.0) versions contained
137 ;;      a bug which affected using folding. At the time the bug was
138 ;;      reported by Trey Jackson <trey A T cs berkeley edu>
139 ;;
140 ;;          If you kill folded area and yank it back, the ^M marks are
141 ;;          removed for some reason.
142 ;;
143 ;;          Before kill
144 ;;          ;;{{{ fold...
145 ;;
146 ;;          After yank
147 ;;          ;;{{{ fold all lines together }}}
148 ;;
149 ;;  Relates packages or modes
150 ;;
151 ;;      Folding.el was designed to be a content organizer and it is most
152 ;;      suitable for big files. Sometimes people misunderstand the
153 ;;      package's capabilities and try to use folding.el in wrong places,
154 ;;      where some other package would do a better job. Trying to wrap
155 ;;      individual functions inside fold-marks is not where folding is
156 ;;      it's best. Grouping several functions inside a logical fold-block
157 ;;      in the other is. So, to choose a best tool for your need,
158 ;;      here are some suggestions,:
159 ;;
160 ;;      o  Navigating between or hiding individual functions -
161 ;;         use combination of imenu.el, speedbar.el and
162 ;;         hideshow.el
163 ;;      o  Organizing large blocks - use folding.el
164 ;;      o  For text, `outline-mode' is more non-intrusive than folding.
165 ;;         Look at Emacs NEWS file (`C-x' `n') and you can see beatifully
166 ;;         laid content.
167 ;;
168 ;;  Tutorial
169 ;;
170 ;;      To start folding mode, give the command: `M-x' `folding-mode'
171 ;;      `RET'. The mode line should contain the string "Fld" indicating
172 ;;      that folding mode is activated.
173 ;;
174 ;;      When loading a document containing fold marks, Folding mode is
175 ;;      automatically started and all folds are closed. For example when
176 ;;      loading my init file, only the following lines (plus a few lines
177 ;;      of comments) are visible:
178 ;;
179 ;;          ;;{{{ General...
180 ;;          ;;{{{ Keyboard...
181 ;;          ;;{{{ Packages...
182 ;;          ;;{{{ Major modes...
183 ;;          ;;{{{ Minor modes...
184 ;;          ;;{{{ Debug...
185 ;;
186 ;;      To enter a fold, use `C-c @ >'. To show it without entering,
187 ;;      use `C-c @ C-s', which produces this display:
188 ;;
189 ;;          ;;{{{ Minor modes
190 ;;
191 ;;          ;;{{{ Follow mode...
192 ;;          ;;{{{ Font-lock mode...
193 ;;          ;;{{{ Folding...
194 ;;
195 ;;          ;;}}}
196 ;;
197 ;;      To show everything, just as the file would look like if
198 ;;      Folding mode hadn't been activated, give the command `M-x'
199 ;;      `folding-open-buffer' `RET', normally bound to `C-c' `@'
200 ;;      `C-o'.  To close all folds and go to the top level, the
201 ;;      command `folding-whole-buffer' could be used.
202 ;;
203 ;;  Mouse support
204 ;;
205 ;;      Folding mode v2.0 introduced mouse support. Folds can be shown
206 ;;      or hidden by simply clicking on a fold mark using mouse button
207 ;;      3. The mouse routines have been designed to call the original
208 ;;      function bound to button 3 when the user didn't click on a
209 ;;      fold mark.
210 ;;
211 ;;  The menu
212 ;;
213 ;;      A menu is placed in the "Tools" menu. Should no Tools menu exist
214 ;;      (Emacs 19.28) the menu will be placed in the menu bar.
215 ;;
216 ;;  ISearch
217 ;;
218 ;;      When searching using the incremental search (C-s) facilities,
219 ;;      folds will be automagically entered and closed.
220 ;;
221 ;;  Problems
222 ;;
223 ;;     Uneven fold marks
224 ;;
225 ;;      Oops, I just deleted some text, and a fold mark got deleted!
226 ;;      What should I do?  Trust me, you will eventually do this
227 ;;      sometime. the easiest way is to open the buffer using
228 ;;      `folding-open-buffer' (C-c @ C-o) and add the fold mark by
229 ;;      hand. To find mismatching fold marks, the package `occur' is
230 ;;      useful. The command:
231 ;;
232 ;;          M-x occur RET {{{\|}}} RET
233 ;;
234 ;;      will extract all lines containing folding marks and present
235 ;;      them in a separate buffer.
236 ;;
237 ;;      Even though all folding marks are correct, Folding mode
238 ;;      sometimes gets confused, especially when entering and leaving
239 ;;      folds very often. To get it back on track, press C-g a few
240 ;;      times and give the command `folding-open-buffer' (C-c @ C-o).
241 ;;
242 ;;     Fold must have a label
243 ;;
244 ;;      When you make a fold, be sure to write some text for the name
245 ;;      of the fold, otherwise there may be an error "extraneous fold
246 ;;      mark..." Write like this:
247 ;;
248 ;;          ;;{{{ Note
249 ;;          ;;}}}
250 ;;
251 ;;      instead of
252 ;;
253 ;;          ;;{{{
254 ;;          ;;}}}
255 ;;
256 ;;     folding-whole-buffer doesn't fold whole buffer
257 ;;
258 ;;      If you call commands `folding-open-buffer' and
259 ;;      `folding-whole-buffer' and notice that there are open fold
260 ;;      sections in the buffer, then you have mismatch of folds
261 ;;      somewhere. Run ` M-x' `occur' and type regexp `{{{\|}}}' to
262 ;;      check where is the extra open or closing fold mark.
263 ;;
264 ;;  Folding and outline modes
265 ;;
266 ;;      Folding mode is not the same as Outline mode, a major and
267 ;;      minor mode which is part of the Emacs distribution. The two
268 ;;      packages do, however, resemble each other very much.  The main
269 ;;      differences between the two packages are:
270 ;;
271 ;;      o   Folding mode uses explicit marks, `{{{' and `}}}', to
272 ;;          mark the beginning and the end of a branch.
273 ;;          Outline, on the other other hand, tries to use already
274 ;;          existing marks, like the `\section' string in a TeX
275 ;;          document.
276 ;;
277 ;;      o   Outline mode has no end marker which means that it is
278 ;;          impossible for text to follow a sub-branch.
279 ;;
280 ;;      o   Folding mode use the same markers for branches on all depths,
281 ;;          Outline mode requires that marks should be longer the
282 ;;          further, down in the tree you go, e.g `\chap', \section',
283 ;;          `\subsection', `\subsubsection'. This is needed to
284 ;;          distinguish the next mark at the current or higher levels
285 ;;          from a sub-branch, a problem caused by the lack of
286 ;;          end-markers.
287 ;;
288 ;;      o   Folding mode has mouse support, you can navigate through a
289 ;;          folded document by clicking on fold marks. (The XEmacs version
290 ;;          of Outline mode has mouse support.)
291 ;;
292 ;;      o   The Isearch facilities of Folding is capable of
293 ;;          automatically to open folds. Under Outline, the the entire
294 ;;          document must be opened prior isearch.
295 ;;
296 ;;      In conclusion, Outline mode is useful when the document being
297 ;;      edited contains natural markers, like LaTeX. When writing code
298 ;;      natural markers are hard to find, except if you're happy with
299 ;;      one function per fold.
300 ;;
301 ;;  Future development ideas
302 ;;
303 ;;      The plan was from the beginning to rewrite the entire package.
304 ;;      Including replacing the core of the program, written using
305 ;;      old Emacs technology (selective display), and replace it with
306 ;;      modern equivalences, like overlays or text-properties for
307 ;;      Emacs and extents for XEmacs.
308 ;;
309 ;;      It is not likely that any of this will come true considering
310 ;;      the time required to rewrite the core of the package. Since
311 ;;      the package, in it's current state, is much more powerful than
312 ;;      the original, it would be appropriate to write such package
313 ;;      from scratch instead of doing surgery on this one.
314
315 ;;}}}
316
317 ;;{{{ Customization
318
319 ;;  Customization: general
320 ;;
321 ;;      The behavior of Folding mode is controlled mainly by a set of
322 ;;      Emacs Lisp variables. This section will discuss the most
323 ;;      useful ones, for more details please see the code. The
324 ;;      descriptions below assumes that you know a bit about how to
325 ;;      use simple Emacs Lisp and knows how to edit ~/.emacs, your
326 ;;      init file.
327 ;;
328 ;;  Customization: hooks
329 ;;
330 ;;      The normal procedure when customizing a package is to write a
331 ;;      function doing the customization. The function is then added
332 ;;      to a hook which is called at an appropriate time. (Please see
333 ;;      the example section below.)  The following hooks are
334 ;;      available:
335 ;;
336 ;;      o   `folding-mode-hook'
337 ;;           Called when folding mode is activated.
338 ;;      o   `<major mode>-folding-hook'
339 ;;           Called when starting folding mode in a buffer with major
340 ;;           mode set to <major mode>. (e.g. When editing C code
341 ;;           the hook `c-mode-folding-hook' is called.)
342 ;;      o   `folding-load-hook'
343 ;;           Called when folding mode is loaded into Emacs.
344 ;;
345 ;;  Customization: The Mouse
346 ;;
347 ;;      The variable `folding-behave-table' contains the actions which
348 ;;      should be performed when the user clicks on an open fold, a
349 ;;      closed fold etc.  For example, if you prefer to `enter' a fold
350 ;;      rather than `open' it you should rebind this variable.
351 ;;
352 ;;      The variable `folding-default-mouse-keys-function' contains
353 ;;      the name of the function used to bind your mouse keys. To use
354 ;;      your own mouse bindings, create a function, say
355 ;;      `my-folding-bind-mouse', and set this variable to it.
356 ;;
357 ;;  Customization: Keymaps
358 ;;
359 ;;      When Emacs 19.29 was released, the keymap was divided into
360 ;;      strict parts. (This division existed before, but a lot of
361 ;;      packages, even the ones delivered with Emacs, ignored them.)
362 ;;
363 ;;          C-c <letter>    -- Reserved for the users private keymap.
364 ;;          C-c C-<letter>  -- Major mode. (Some other keys are
365 ;;                             reserved as well.)
366 ;;          C-c <Punctuation Char> <Whatever>
367 ;;                          -- Reserved for minor modes.
368 ;;
369 ;;      The reason why `C-c@' was chosen as the default prefix is that
370 ;;      it is used by outline-minor-mode. It is not likely that few
371 ;;      people will try to use folding and outline at the same time.
372 ;;
373 ;;      However, old key bindings have been kept if possible.  The
374 ;;      variable `folding-default-keys-function' specifies which
375 ;;      function should be called to bind the keys. There are various
376 ;;      function to choose from how user can select the keybindings.
377 ;;      To use the old key bindings, add the following line to your
378 ;;      init file:
379 ;;
380 ;;          (setq folding-default-keys-function
381 ;;                'folding-bind-backward-compatible-keys)
382 ;;
383 ;;      To define keys similar to the keys used by Outline mode, use:
384 ;;
385 ;;          (setq folding-default-keys-function
386 ;;                'folding-bind-outline-compatible-keys)
387 ;;
388 ;;  Customization: adding new major modes
389 ;;
390 ;;      To add fold marks for a new major mode, use the function
391 ;;      `folding-add-to-marks-list'. Example:
392 ;;
393 ;;          (folding-add-to-marks-list
394 ;;           'c-mode "/* {{{ " "/* }}} */" " */" t)
395 ;;          (folding-add-to-marks-list
396 ;;           'java-mode "// {{{ " "// }}}" nil t)
397 ;;
398 ;;  Customization: ISearch
399 ;;
400 ;;      If you don't like the extension folding.el applies to isearch,
401 ;;      set the variable `folding-isearch-install' to nil before
402 ;;      loading this package.
403
404 ;;}}}
405 ;;{{{ Examples
406
407 ;;  Example: personal setup
408 ;;
409 ;;      To define your own key binding instead of using the standard
410 ;;      ones, you can do like this:
411 ;;
412 ;;           (setq folding-mode-prefix-key "\C-c")
413 ;;           ;;
414 ;;           (setq folding-default-keys-function
415 ;;               '(folding-bind-backward-compatible-keys))
416 ;;           ;;
417 ;;           (setq folding-load-hook 'my-folding-load-hook)
418 ;;
419 ;;
420 ;;           (defun my-folding-load-hook ()
421 ;;             "Folding setup."
422 ;;
423 ;;             (folding-install)  ;; just to be sure
424 ;;
425 ;;             ;; ............................................... markers ...
426 ;;
427 ;;             ;;  Change text-mode fold marks. Handy for quick
428 ;;             ;;  sh/perl/awk code
429 ;;
430 ;;             (defvar folding-mode-marks-alist nil)
431 ;;
432 ;;             (let* ((ptr (assq 'text-mode folding-mode-marks-alist)))
433 ;;               (setcdr ptr (list "# {{{" "# }}}")))
434 ;;
435 ;;             ;; ........................................ bindings ...
436 ;;
437 ;;             ;;  Put `folding-whole-buffer' and `folding-open-buffer'
438 ;;             ;;  close together.
439 ;;
440 ;;             (defvar folding-mode-prefix-map nil)
441 ;;
442 ;;             (define-key folding-mode-prefix-map "\C-w" nil)
443 ;;             (define-key folding-mode-prefix-map "\C-s"
444 ;;                         'folding-show-current-entry)
445 ;;             (define-key folding-mode-prefix-map "\C-p"
446 ;;                         'folding-whole-buffer))
447 ;;
448 ;;  Example: changing default fold marks
449 ;;
450 ;;      In case you're not happy with the default folding marks, you
451 ;;      can change them easily. Here is an example
452 ;;
453 ;;          (setq folding-load-hook 'my-folding-load-hook)
454 ;;
455 ;;          (defun my-folding-load-hook ()
456 ;;            "Folding vars setup."
457 ;;            (let* ((ptr (assq 'text-mode folding-mode-marks-alist)))
458 ;;              (setcdr ptr (list "# {{{" "# }}}"))))
459 ;;
460 ;;
461 ;;  Example: choosing different fold marks for mode
462 ;;
463 ;;      Suppose you sometimes want to use different fold marks for the
464 ;;      major mode: e.g. to alternate between "# {{{" and "{{{" in
465 ;;      `text-mode' Call `M-x' `my-folding-text-mode-setup' to change
466 ;;      the marks.
467 ;;
468 ;;            (defun my-folding-text-mode-setup (&optional use-custom-folding-marks)
469 ;;              (interactive
470 ;;                (list (y-or-n-p "Use Custom fold marks now? ")))
471 ;;              (let* ((ptr (assq major-mode folding-mode-marks-alist))
472 ;;                     (default-begin "# {{{")
473 ;;                     (default-end   "# }}}")
474 ;;                     (begin "{{{")
475 ;;                     (end   "}}}"))
476 ;;                (when (eq major-mode 'text-mode)
477 ;;                  (unless use-custom-folding-marks
478 ;;                    (setq  begin default-begin  end default-end)))
479 ;;                (setcdr ptr (list begin end))
480 ;;                (folding-set-marks begin end)))
481 ;;
482 ;;  Example: AucTex setup
483 ;;
484 ;;      Suppose you're using comment.sty with AucTeX for editing
485 ;;      LaTeX2e documents and you have these comment types. You would
486 ;;      like to be able to set which of these 3 is to be folded at any
487 ;;      one time, using a simple key sequence: move back and forth
488 ;;      easily between the different comment types, e.g., "unfold
489 ;;      everything then fold on \x".
490 ;;
491 ;;          \O   ...  \endO
492 ;;          \L   ...  \endL
493 ;;          \B   ...  \endB
494 ;;
495 ;;          (setq folding-load-hook 'my-folding-load-hook)
496 ;;
497 ;;          (defun my-folding-load-hook ()
498 ;;            "Folding vars setup."
499 ;;            (let ((ptr (assq 'text-mode folding-mode-marks-alist)))
500 ;;              (setcdr ptr (list "\\O" "\\endO"))
501 ;;              (define-key folding-mode-prefix-map "C"
502 ;;                         'my-folding-marks-change)))
503 ;;
504 ;;          (defun my-folding-marks-change (&optional selection)
505 ;;            "Select folding marks: prefixes nil, C-u and C-u C-u."
506 ;;            (interactive "P")
507 ;;            (let ((ptr (assq major-mode folding-mode-marks-alist))
508 ;;                  input)
509 ;;              (when (string-match "^\\(plain-\\|la\\|auc\\)?tex-"
510 ;;                                  (symbol-name  major-mode))
511 ;;                (setq input
512 ;;                      (read-string "Latex \\end(X) Marker (default O): "
513 ;;                                   nil nil "O" nil))
514 ;;                (setq input (upcase input))
515 ;;                (turn-off-folding-mode)
516 ;;                (folding-add-to-marks-list
517 ;;                 major-mode
518 ;;                 (concat "\\" input) (concat "\\end" input) nil nil t)
519 ;;                ;; (setcdr ptr (list (concat "\\" input) (concat "\\end" input)))
520 ;;                (turn-on-folding-mode))))
521 ;;          ;;  End of example
522 ;;
523 ;;  Bugs: Lazy-shot.el conflict in XEmacs
524 ;;
525 ;;      [XEmacs 20.4 lazy-shot-mode]
526 ;;      1998-05-28 Reported by Solofo Ramangalahy <solofo A T mpi-sb mpg de>
527 ;;
528 ;;          % xemacs -q folding.el
529 ;;          M-x eval-buffer
530 ;;          M-x folding-mode
531 ;;          M-x font-lock-mode
532 ;;          M-x lazy-shot-mode
533 ;;          C-s mouse
534 ;;
535 ;;      then search for mouse again and again. At some point you will
536 ;;      see "Deleting extent" in the minibuffer and XEmacs freezes.
537 ;;
538 ;;      The strange point is that I have this bug only under Solaris
539 ;;      2.5 sparc (binaries from ftp.xemacs.org) but not under Solaris
540 ;;      2.6 x86. (XEmacs 20.4, folding 2.35). I will try to access
541 ;;      more machines to see if it's the same.
542 ;;
543 ;;      I suspect that the culprit is lazy-shot as it is beta, but
544 ;;      maybe you will be able to describe the bug more precisely to
545 ;;      the XEmacs people I you can reproduce it.
546
547 ;;}}}
548 ;;{{{ Old Documentation
549
550 ;;  Old documentation
551 ;;
552 ;;      The following text was written by Jamie Lokier for the release
553 ;;      of Folding V1.6. It is included here for no particular reason:
554 ;;
555 ;;      Emacs 18:
556 ;;      Folding mode has been tested with versions 18.55 and
557 ;;      18.58 of Emacs.
558 ;;
559 ;;      Epoch:
560 ;;      Folding mode has been tested on Epoch 4.0p2.
561 ;;
562 ;;      [X]Emacs:
563 ;;      There is code in here to handle some aspects of XEmacs.
564 ;;      However, up to version 19.6, there appears to be no way to
565 ;;      display folds. Selective-display does not work, and neither do
566 ;;      invisible extents, so Folding mode has no chance of
567 ;;      working. This is likely to change in future versions of
568 ;;      XEmacs.
569 ;;
570 ;;      Emacs 19:
571 ;;      Tested on version 19.8, appears to be fine. Minor bug:
572 ;;      display the buffer in several different frames, then move in
573 ;;      and out of folds in the buffer. The frames are automatically
574 ;;      moved to the top of the stacking order.
575 ;;
576 ;;      Some of the code is quite horrible, generally in order to
577 ;;      avoid some Emacs display "features". Some of it is specific to
578 ;;      certain versions of Emacs. By the time Emacs 19 is around and
579 ;;      everyone is using it, hopefully most of it won't be necessary.
580 ;;
581 ;;  More known bugs
582 ;;
583 ;;      *** Needs folding-fold-region to be more intelligent about
584 ;;      finding a good region. Check folding a whole current fold.
585 ;;
586 ;;      *** Now works with 19!  But check out what happens when you
587 ;;      exit a fold with the file displayed in two frames. Both
588 ;;      windows get fronted. Better fix that sometime.
589 ;;
590 ;;  Future features
591 ;;
592 ;;      *** I will add a `folding-next-error' sometime. It will only
593 ;;      work with Emacs versions later than 18.58, because compile.el
594 ;;      in earlier versions does not count line-numbers in the right
595 ;;      way, when selective display is active.
596 ;;
597 ;;      *** Fold titles should be optionally allowed on the closing
598 ;;      fold marks, and `folding-tidy-inside' should check that the
599 ;;      opening title matches the closing title.
600 ;;
601 ;;      *** `folded-file' set in the local variables at the end of a
602 ;;      file could encode the type of fold marks used in that file,
603 ;;      and other things, like the margins inside folds.
604 ;;
605 ;;      *** I can see a lot of use for the newer features of Emacs 19:
606 ;;
607 ;;      Using invisible text-properties (I hope they are intended to
608 ;;      make text invisible; it isn't implemented like that yet), it
609 ;;      will be possible to hide folded text without affecting the
610 ;;      text of the buffer. At the moment, Folding mode uses selective
611 ;;      display to hide text, which involves substituting
612 ;;      carriage-returns for line-feeds in the buffer. This isn't such
613 ;;      a good way. It may also be possible to display different folds
614 ;;      in different windows in Emacs 19.
615 ;;
616 ;;      Using even more text-properties, it may be possible to track
617 ;;      pointer movements in and out of folds, and have Folding mode
618 ;;      automatically enter or exit folds as necessary to maintain a
619 ;;      sensible display. Because the text itself is not modified (if
620 ;;      overlays are used to hide text), this is quite safe. It would
621 ;;      make it unnecessary to provide functions like
622 ;;      `folding-forward-char', `folding-goto-line' or
623 ;;      `folding-next-error', and things like I-search would
624 ;;      automatically move in and out of folds as necessary.
625 ;;
626 ;;      Yet more text-properties/overlays might make it possible to
627 ;;      avoid using narrowing. This might allow some major modes to
628 ;;      indent text properly, e.g., C++ mode.
629
630 ;;}}}
631
632 ;;; Change Log:
633
634 ;;{{{ History
635 ;; [person version] = developer and his revision tree number.
636 ;;
637 ;; May  06  2007  21.4             [jari 3.38-3.41 2007.0506]
638 ;; - Cleanup. Eol whitespaces removed, extra newlines cleaned.
639 ;;   Paren positions corrected.
640 ;; - 'Personal reflections by Anders Lindgren' topic
641 ;;   rephrased 'Future development ideas'
642 ;;
643 ;; Nov  16  2006  21.4             [jari 3.36-3.37 2006.1118]
644 ;; - Jeremy Hankins <nowan A T nowan org> sent a patch, which
645 ;;   adds variable `folding-narrow-by-default'. The patch affects
646 ;;   mostly `folding-shift-in'. This makes it possible to
647 ;;   advise viper-search to open folds. Thanks.
648 ;; - Added VCS URL header to the beginning for canonnical location.
649 ;;   Updated maintainer section.
650 ;; - Fixed Copyright years.
651 ;;
652 ;; Nov  25  2004  21.3             [jari 3.35 2004.1125]
653 ;; - non-ascii character removed from bibtex-mode.
654 ;;   Changed bib-mode '@comment' => '%'. Closes Debian
655 ;;   Bug#282388
656 ;;
657 ;; Sep  10  2004  21.3             [jari 2.116 2004.0910]
658 ;; - (folding-fold-region): caused to indent bottom fold
659 ;;   some 50 spaces forward in auctex:latex-mode. Disabled
660 ;;   running `indent-according-to-mode' while in latex-mode.
661 ;;   Bug reported by Uwe Brauer; oub A T mat dot ucm dot es
662 ;; - Removed extra newlines from whole buffer.
663 ;; - Changed version scheme to date based YYYY.MMDD
664 ;; - Removed unnecessary 'all rights reserved'.
665 ;; - (folding-check-folded): Added check for \r character, which
666 ;; - protected all email addresses by removing AT-signs.
667 ;;
668 ;; Apr  01  2004  21.3             [jari 2.111-2.115]
669 ;; - Merged in changes made by 2003-11-12  Adrian Aichner
670 ;;   from XEmacs tree 1.15; Typo fixes for docstrings and comments.
671 ;; - Returned to old bug and solved it in a better way (preserve region) by
672 ;;   using different expansion macros for XEmacs and Emacs.
673 ;;   See See http://list-archive.xemacs.org/xemacs-beta/199810/msg00039.html
674 ;; - (folding-forward-char-1): 2.112 Renamed.
675 ;;   Was `folding-forward-char'.
676 ;;   (folding-backward-char-1): 2.112 Renamed.
677 ;;   Was `folding-backward-char'.
678 ;;   (folding-forward-char-macro): 2.112 New. Fix XEmacs
679 ;;   region preservation with '_p' interactive spec.
680 ;;   (folding-backward-char-macro): 2.112 New. Fix XEmacs
681 ;;   region preservation with '_p' interactive spec.
682 ;;   (folding-interactive-spec-p): 2.112 New.
683 ;;
684 ;; Sep  11  2003  21.2             [jari 2.107-2.111]
685 ;; - Added new sections "Uninstallation" and "To read the manual".
686 ;;   M-x finder can invoke folding too provided that patch to
687 ;;   lisp-mnt.el and finder.el is installed. Sent patch to XEmacs and
688 ;;   Emacs developers.
689 ;; - Moved fold-mark ";;{{{ Introduction" after the Commentary:
690 ;;   tag to have it included in M-x finder-commentary.
691 ;; - If called like this: `folding-uninstall' and immediately
692 ;;   `folding-mode', the keybindings were not there any more. Added
693 ;;   call to `folding-install' in `folding-mode'.
694 ;; - Completely rewrote `folding-install'. It's now divided into
695 ;;   `folding-install-keymaps' and `folding-uninstall-keymaps'
696 ;; - Added support for `php-mode', `javascript-mode',
697 ;;   `change-log-mode' and `finder-mode'.
698 ;; - Documentation changes (fit all to 80 characters).
699 ;;
700 ;; Aug  21  2002  21.2             [jari 2.105-2.106]
701 ;; - Added user function `folding-uninstall'.
702 ;; - Removed `interactive' status: `folding-install-hooks' and
703 ;;   `folding-uninstall-hooks'
704 ;;
705 ;; Aug  02  2002  20.7             [jari 2.101-2.104]
706 ;; - Added font lock support. Now beginning and end markers are
707 ;;   highlighted with user variables `folding-font-lock-begin-mark'
708 ;;   `folding-font-lock-end-mark'. Feature suggested by
709 ;;   <Claude BOUCHER A T astrium-space com>
710 ;; - Removed LCD entry - unnecessary.
711 ;;
712 ;; Jan  24  2002  20.7             [jari 2.100]
713 ;; - (folding-context-next-action):New user function.
714 ;;   Code by Scott Evans <gse A T antisleep com>
715 ;; - (folding-bind-default-keys): Added
716 ;;   C-x . to run `folding-context-next-action'
717 ;; - (folding-mouse-call-original): Added `car-safe' to read
718 ;;   EVENT, which may be nil.
719 ;;
720 ;; Jul  31  2001  20.7             [jari 2.98-2.99]
721 ;; - Gleb Arshinov  <gleb A T barsook com> fixed the broken XEmacs
722 ;;   isearch support and sent nice patch.
723 ;;
724 ;; Jul  19  2001  20.7             [jari 2.92-2.97]
725 ;; - Beautified lisp code by removing parens that were alone.
726 ;; - XEmacs latex-mode fix. The folds were strangely indented too
727 ;;   far right. The cause was `indent-according-to-mode' which is
728 ;;   now disabled in latex. bug reported by
729 ;;   Uwe Brauer; oub A T maraton sim ucm es
730 ;; - 2.96 Erroneous `:' in `folding-mode-write-file'
731 ;;   when it should have been `;'. Bug reported by
732 ;;   Brand Michael; michael brand A T siemens com
733 ;;
734 ;; Apr  04  2001  20.7             [jari 2.89-2.91]
735 ;; - Small corrections to find-func.el::find-function-search-for-symbol
736 ;;   implementation.
737 ;;
738 ;; Mar  08  2001  20.6             [jari 2.88]
739 ;; - Dave Masterson <dmasters A T rational com> reported that jumping to a
740 ;;   url displayed by the C-h f FUNCTION which told where the function
741 ;;   was located died. The reason was that the buffer was folded and
742 ;;   find-func.el::find-function-search-for-symbol used regexps that
743 ;;   do not take into account folded buffers. The regexps used there
744 ;;   rely on syntax tables.
745 ;; - Added two new advices to catch find-func.el and unfold the buffer
746 ;;   prior searching: (advice find-file-noselect after) and (advice
747 ;;   find-function-search-for-symbol around)
748 ;;
749 ;; Mar  04  2001  20.6             [jari 2.83-2.87]
750 ;; - Added ###autoload statements, tidied up empty lines and lisp syntax.
751 ;; - Run checkdoc.el 0.6.1 and corrected errors.
752 ;;
753 ;; Jan  04  2001  20.6             [jari 2.82]
754 ;; - Added FOLD highlight feature for XEmacs:
755 ;;   `folding-mode-motion-highlight-fold'
756 ;;   and package `mode-motion' Suggested by
757 ;;   Thomas Ruhnau <thomas ruhnau A T intermetall de>
758 ;; - (folding-bind-default-keys): 2.81 New binding C-k
759 ;;   `folding-marks-kill'
760 ;;   (fold-marks-kill): 2.81 New.
761 ;;
762 ;; Jan  03  2001  20.6             [jari 2.81]
763 ;; - (folding-folding-region): 2.80 Renamed to `folding-fold-region'
764 ;; - (folding-mark-look-at-top-mark-p): 2.80 New.
765 ;; - (folding-mark-look-at-bottom-mark-p): 2.80 New.
766 ;; - (folding-tidy-inside): 2.80 Use `folding-mark-look-at-top-mark-p'
767 ;;   and `folding-mark-look-at-bottom-mark-p'.
768 ;; - Didn't accept spaces in front of fold markers.
769 ;; - (folding-fold-region): 2.80 Added `indent-according-to-mode'
770 ;;   to indent folds as needed.
771 ;;
772 ;; Dec  16  2000  20.6             [jari 2.79-2.80]
773 ;; - `folding-xemacs-p' now test (featurep 'xemacs)
774 ;; - Added missing folding functions to the menubar
775 ;; - `folding-package-url-location' new variable used by function
776 ;;   `folding-insert-advertise-folding-mode'
777 ;; - `folding-keep-hooked' was commented out in `folding-mode'. Added
778 ;;   back.
779 ;;
780 ;; Jul  25  2000  20.6             [jari 2.76-2.78]
781 ;; - 2.75 Added support for modes:
782 ;;   xrdb-mode, ksh-mode and sql-mode contributed by
783 ;;   Juhapekka Tolvanen <juhtolv A T st jyu fi>. Scanned systematically
784 ;;   all modes under Emacs 20.6 progmodes and added support for:
785 ;;   ada-mode, asm-mode, awk-mode, cperl-mode, fortran-mode, f90-mode,
786 ;;   icon-mode, m4-mode, meta-mode, pascal-mode, prolog-mode,
787 ;;   simula-mode, vhdl-mode, bibtex-mode, nroff-mode, scribe-mode(*),
788 ;;   sgml-mode
789 ;; - Mode marked with (*) was not added.
790 ;; - (folding-insert-advertise-folding-mode): 2.76 New. Suggested by
791 ;;   Juhapekka Tolvanen <juhtolv A T st jyu fi>
792 ;; - (folding-bind-default-keys): 2.76
793 ;;   folding-insert-advertise-folding-mode Bound to key "I"
794 ;;
795 ;; Apr  24  1999  20.4             [jari 2.73-2.75]
796 ;; - (folding-bind-terminal-keys): 2.74 New.  Bind C-f and C-b only at
797 ;;   non-window system where they are really needed.  Someone may use
798 ;;   C-f for `isearch-forward' in windowed Emacs.
799 ;; - (folding-bind-default-keys): 2.74 Use `folding-bind-terminal-keys'
800 ;; - (folding-bind-outline-compatible-keys): 2.74
801 ;;   Use `folding-bind-terminal-keys'
802 ;;
803 ;; Feb  13  1999  20.4             [jari 2.71-2.72]
804 ;; - (folding-event-posn): 2.70 Wrong
805 ;;   place of paren and the following was malformed call:
806 ;;   (let* ((el (funcall (symbol-function 'event-start) event)))
807 ;;
808 ;; Jan  13  1999  20.4             [jari 2.70]
809 ;; - 2.69 The `looking-at' is now smarter with
810 ;;   fold beginning marks. The tradition has been the the fold always
811 ;;   has a name, so the requirement to search fold is "{{{ ". Now
812 ;;   the " " is searched as " *", not requiring a space --> not requiring
813 ;;   a fold name.
814 ;; - (folding-skip-folds): >>feature not not enabled<<
815 ;;   2.69 Do not require trailing " " any more.'
816 ;;   (folding-tidy-inside): >>feature not not enabled<<
817 ;;   2.69 Do not require trailing " " any more.
818 ;; - (folding-install): 2.69 Fixed indentation.
819 ;; - (folding-mark-look-at): 2.69 The "em" missed "*" and thus pressing
820 ;;   mouse-3 at the end-fold didn't collapse the whole fold.
821 ;;
822 ;; Jan  12  1999  20.4             [jari 2.69]
823 ;;   (folding-bind-default-mouse): 2.68
824 ;;   XEmacs and Emacs Mouse binding was different. Now use common
825 ;;   bindings: The S-mouse-2 was superfluous, because mouse-3 already
826 ;;   did that, so the binding was removed.
827 ;;   mouse-3     folding-mouse-context-sensitive
828 ;;   S-mouse-2   folding-hide-current-entry
829 ;;   C-S-mouse-2 folding-mouse-pick-move
830 ;;
831 ;;;; Jan  09  1999  20.4             [jari 2.67-2.68]
832 ;; - (folding-event-posn): 2.66 Hide `event-start' From XEmacs
833 ;;   (byte compile silencer)
834 ;;
835 ;; Jan  07  1999  20.4             [jari 2.65-2.66]
836 ;; - The Folding begin and AND mark was not case sensitive;
837 ;;   that's why a latex styles "\B" and "\endB" fold marks couldn't
838 ;;   be used. Added relevant `case-fold-search' settings. Not tested
839 ;;   very well, though.
840 ;; - Added standard "turn-on" "turn-off" functions.
841 ;; - (folding-whole-buffer): 2.65 Better
842 ;;   Error message. Show used folding-mark on error.
843 ;; - (folding-skip-folds): 2.65 Moved docs in function.
844 ;; - (turn-off-folding-mode): 2.65 New.
845 ;; - (turn-on-folding-mode): 2.65 New.
846 ;; - (folding-mark-look-at): 2.65 `case-fold-search'
847 ;; - (folding-next-visible-heading): 2.65 `case-fold-search'
848 ;; - (folding-find-folding-mark): 2.65 `case-fold-search'
849 ;; - (folding-pick-move): 2.65 `case-fold-search'
850 ;; - (folding-skip-folds): 2.65 `case-fold-search'
851 ;; - (folding-tidy-inside): 2.65 `case-fold-search'
852 ;; - (folding-convert-to-major-folds): 2.65 `case-fold-search'
853 ;;
854 ;;  Jan  04  1999  20.4             [jari 2.62-2.64]
855 ;; - (folding-set-local-variables): 2.61 New. Now it is possible to
856 ;;   change the folding marks dynamically.
857 ;; - (folding-mode): 2.61 Call `folding-set-local-variables'
858 ;;   (folding-mode-marks-alist): 2.61 mention
859 ;; - `folding-set-local-variables'
860 ;;   Added documentation section: "Example: AucTex setup"
861 ;; - NT Emacs fix wrapped inside `eval-and-compile'. hs-discard-overlays
862 ;;   are now hidden from byte compiler (since the code is not
863 ;;   executed anyway)
864 ;;
865 ;; May  24  1999  19.34             [jari 2.59-2.61]
866 ;; - New function `folding-all-comment-blocks-in-region'. Requested by
867 ;;   Uwe Brauer <oub A T eucmos sim ucm es>. Bound under "/" key.
868 ;; - (folding-all-comment-blocks-in-region):
869 ;;   Check non-whitespace `comment-end'. Added `matlab-mode' to
870 ;;   fold list
871 ;; - (folding-event-posn): 2.63 Got rid of the XEmacs/Emacs
872 ;;   posn-/event- byte compiler warnings
873 ;; - (folding-mouse-call-original): 2.63 Got rid of the XEmacs
874 ;;   `event-button' byte compiler warning.
875 ;;
876 ;; Apr  15  1999  19.34             [jari 2.57]
877 ;; - (folding-mouse-call-original): Samuel Mikes
878 ;;   <smikes A T alumni hmc edu> reported that the `concat' function was
879 ;;   used to add an integer to "button" event.  Applied patch to use
880 ;;   `format' instead.
881 ;;
882 ;; Mar  03  1999  19.34             [andersl]
883 ;;  - (folding-install): had extra paren. Removed.
884 ;;
885 ;; Feb  22  1999  19.34             [jari 2.56]
886 ;;  - folding-install):
887 ;;    Check if `folding-mode-prefix-map' is nil and call
888 ;;
889 ;; Feb  19  1999  19.34             [jari 2.55]
890 ;;  - (folding-mode-hook-no-re):
891 ;;    Renamed to `folding-mode-hook-no-regexp'
892 ;;  - (fold-inside-mode-name): Renames to `folding-inside-mode-name'
893 ;;    (fold-mode-string): Renamed to `folding-mode-string'
894 ;;  - Renamed all `fold-' prefixes to `folding-'
895 ;;  - Rewrote chapter `Example: personal setup'
896 ;;
897 ;; Jan  01  1999  19.34             [jari 2.54]
898 ;; - Byte compiler error fix: (folding-bind-outline-compatible-keys):
899 ;;   'folding-show-all lacked the quote.
900 ;;
901 ;; Dec  30  1998  19.34             [jari 2.53]
902 ;; - Jesper Pedersen <blackie A T imada ou dk> reported bug that hiding
903 ;;   subtree was broken. This turned out to be a bigger problem in fold
904 ;;   handling in general. This release has big relatively big error
905 ;;   fixes.
906 ;; - Many of the folding functions were also renamed to mimic Emacs 20.3
907 ;;   allout.el names. Outline keybindings were rewritten too.
908 ;; - folding.el (folding-mouse-yank-at-point): Renamed from
909 ;;   `folding-mouse-operate-at-point'. The name is similar to Emacs
910 ;;   standard variable name. The default value changed from nil --> t
911 ;;   according to suggestion by Jesper Pedersen <blackie A T  imada ou dk>
912 ;;   Message "Info, Ignore [X]Emacs specific..." is now displayed only
913 ;;   while byte compiling file.
914 ;;   (folding-bind-outline-compatible-keys):
915 ;;   Checked the Emacs 20.3 allout.el outline bindings and made
916 ;;   folding mimic them
917 ;;   (folding-show-subtree): Renamed to `folding-show-current-subtree'
918 ;;   according to allout.el
919 ;;   (folding-hide-subtree): Renamed to `folding-hide-current-subtree'
920 ;;   according to allout.el
921 ;;   (folding-enter): Renamed to `folding-shift-in'
922 ;;   according to allout.el
923 ;;   (folding-exit): Renamed to `folding-shift-out'
924 ;;   according to allout.el
925 ;;   (folding-move-up): Renamed to `folding-previous-visible-heading'
926 ;;   according to allout.el
927 ;;   (folding-move): Renamed to `folding-next-visible-heading'
928 ;;   according to allout.el
929 ;;   (folding-top-level): Renamed to `folding-show-all'
930 ;;   according to allout.el
931 ;;   (folding-show): Renamed to `folding-show-current-entry'
932 ;;   according to allout.el
933 ;;   (folding-hide): Renamed to `folding-hide-current-entry'
934 ;;   according to allout.el
935 ;;   (folding-region-open-close): While loop rewritten so that if user
936 ;;   is already on a fold mark, then close current fold. This also
937 ;;   fixed the show/hide subtree problem.
938 ;;   (folding-hide-current-subtree): If use hide subtree that only had
939 ;;   one fold, then calling this function caused error. The reason was
940 ;;   error in `folding-pick-move' (folding-pick-move): Test that
941 ;;   `moved' variable is integer and only then move point. This is the
942 ;;   status indicator from `folding-find-folding-mark'
943 ;;   (folding-find-folding-mark): Fixed. mistakenly moved point when
944 ;;   checking TOP level marker, status 11. the point was permanently
945 ;;   moved to point-min.
946 ;;
947 ;; Dec  29  1998  19.34             [jari 2.51]
948 ;; - Jesper Pedersen <blackie A T imada ou dk> reported that prefix key
949 ;;   cannot take vector notation [(key)]. This required changing the way
950 ;;   how folding maps the keys. Now uses intermediate keymap
951 ;;   `folding-mode-prefix-map'
952 ;; - `folding-kbd' is new.
953 ;; - `folding-mode' function description has better layout.
954 ;; - `folding-get-mode-marks' is now defsubst.
955 ;;
956 ;; Dec  13  1998  19.34             [jari 2.49-2.50]
957 ;; - Gleb Arshinov <gleb A T CS Stanford EDU> reported that the XEmacs 21.0
958 ;;   `concat' function won't accept integer argument any more and
959 ;;   provided patch for `folding-set-mode-line'.
960 ;;
961 ;; Nov  28  1998  19.34             [jari 2.49-2.50]
962 ;; - Gleb Arshinov <gleb A T CS Stanford EDU> reported that the
963 ;;   zmacs-region-stays must not be set globally but in the functions
964 ;;   that need it. He tested the change on tested on XEmacs 21.0 beta
965 ;;   and FSF Emacs 19.34.6 on NT and sent a patch . Thank you.
966 ;; - (folding-preserve-active-region): New macro to set
967 ;;   `zmacs-region-stays' to t in XEmacs.
968 ;; - (folding-forward-char): Use `folding-preserve-active-region'
969 ;; - (folding-backward-char): Use `folding-preserve-active-region'
970 ;; - (folding-end-of-line):  Use `folding-preserve-active-region'
971 ;; - (folding-isearch-general): Variables `is-fold' and
972 ;;   `is narrowed' removed, because they were not used. (Byte
973 ;;   Compilation fix)
974 ;; - Later: interestingly using `defmacro'
975 ;;   folding-preserve-active-region does not work in XEmacs 21.0 beta,
976 ;;   but `defsubst' does. Reported and corrected by Gleb.
977 ;;
978 ;; Oct  22  1998  19.34             [jari 2.47-2.48]
979 ;; - NT Emacs has had long time a bug where it strips away ^M when
980 ;;   closed fold is copied to kill ring. When pasted, then ^M are
981 ;;   gone. This cover NT Emacs releases 19.34 - 20.3. Bug report has
982 ;;   been filed.
983 ;; - to cope with the situation I added new advice functions that
984 ;;   get instantiated only for these versions of NT Emacs. See
985 ;;   `kill-new' and `current-kill'
986 ;;
987 ;; Oct  21  1998  19.34             [jari 2.46]
988 ;; - `folding-isearch-general' now enters folds as usual with isearch.
989 ;;   The only test needed was to check `quit-isearch' before calling
990 ;;   `folding-goto-char', because the narrow case was already taken
991 ;;   cared of in the condition case.
992 ;;
993 ;; Oct  19  1998  19.34             [jari 2.44]
994 ;; -  1998-10-19 Uwe Brauer <oub A T sunma4 mat ucm es> reported that
995 ;;    In Netscape version > 4 the {{{ marks cannot be used. For IE they
996 ;;    were fine, but not for Netscape. Some bug there.
997 ;;    --> Marks changed to [[[ ]]]
998 ;;
999 ;; Oct  5  1998  19.34             [jari 2.43]
1000 ;; - The "_p" flag does not exist in Emacs 19.34, so the previous patch
1001 ;;   was removed. <greg A T alphatech com> (Greg Klanderman) suggested using
1002 ;;   `zmacs-region-stays'. Added to the beginning of file.
1003 ;; - todo: folding does not seem to open folds any more with Isearch.
1004 ;;
1005 ;; Oct  5  1998  19.34             [jari 2.42]
1006 ;; - Gleb Arshinov <gleb A T cs stanford edu> reported (and supplied patch):
1007 ;;   I am using the latest beta of folding.el with XEmacs 21.0 "Finnish
1008 ;;   Landrace" [Lucid] (i386-pc-win32) (same bug is present with folding.el
1009 ;;   included with XEmacs). Being a big fan of zmacs-region, I was
1010 ;;   disappointed to find that folding mode caused my usual way of
1011 ;;   selecting regions (e.g. to select a line C-space, C-a, C-e) to break
1012 ;;   :( I discovered that the following 3 functions would unset my mark.
1013 ;;   Upon reading some documentation, this seems to be caused by an
1014 ;;   argument to interactive used by these functions. With the following
1015 ;;   tiny patch, the undesirable behaviour is gone.
1016 ;; - Patch was applied as is. Function affected:
1017 ;;   `folding-forward-char' `folding-backward-char'
1018 ;;   `folding-end-of-line'. Interactive spec changed from "p" to "_p"
1019 ;;
1020 ;; Sep 28  1998  19.34             [jari 2.41]
1021 ;; - Wrote section "folding-whole-buffer doesn't fold whole buffer" to
1022 ;;   Problems topic. Fixed some indentation in documentation so that
1023 ;;   command  ripdoc.pl folding.el | t2html.pl --simple > folding.html
1024 ;;   works properly.
1025 ;;
1026 ;; Sep 24  1998  19.34             [jari 2.40]
1027 ;; - Stephen Smith <steve A T fmrib ox ac uk> wished that the
1028 ;;   `folding-comment-fold' should handle modes that have comment-start
1029 ;;   and comment-end too. That lead to rewriting the comment function so
1030 ;;   that it can be adapted to new modes.
1031 ;; - `folding-pick-move' didn't work in C-mode. Fixed.
1032 ;;    (folding-find-folding-mark):
1033 ;;    m and re must be protected with `regexp-quote'. This
1034 ;;    corrected error eg. in C-mode where `folding-pick-move'
1035 ;;    didn't move at all.
1036 ;;    (folding-comment-fold): Added support for major modes that
1037 ;;    have `comment-start' and `comment-end'. Use
1038 ;;    `folding-comment-folding-table'
1039 ;;    (folding-comment-c-mode): New.
1040 ;;    (folding-uncomment-c-mode): New.
1041 ;;    (folding-comment-folding-table): New. To adapt to any major-mode.
1042 ;;    (folding-uncomment-mode-generic): New.
1043 ;;    (folding-comment-mode-generic): New.
1044 ;;
1045 ;; Aug 08  1998  19.34             [jari 2.39]
1046 ;; - Andrew Maccormack <andrewm A T bristol st com> reported that the
1047 ;;   `em' end marker that was defined in the `let' should also have
1048 ;;   `[ \t\n]' which is in par with the `bm'. This way fold markers do
1049 ;;   not need to be parked to the left any more.
1050 ;;
1051 ;; Jun 05  1998  19.34             [jari 2.37-2.38]
1052 ;; - Alf-Ivar Holm <affi A T osc no> send functions
1053 ;;   `folding-toggle-enter-exit' and `folding-toggle-show-hide' which
1054 ;;   were integrated. Alf also suggested that Fold marks should now
1055 ;;   necessarily be located at the beginning of line, but allow spaces
1056 ;;   at front. The patch was applied to `folding-mark-look-at'
1057 ;;
1058 ;; Mar 17  1998  19.34             [Anders]
1059 ;; - Anders: This patch fixes one problem that was reported in the
1060 ;;   beginning of May by Ryszard Kubiak <R Kubia A T ipipan gda pl>.
1061 ;; - Finally, I think that I have gotten mouse-context-sensitive
1062 ;;   right.  Now, when you click on a fold that fold rather than the
1063 ;;   one the cursor is on is used, while still not breaking commands
1064 ;;   like `mouse-save-then-kill' which assumes that the point hasn't
1065 ;;   been moved.
1066 ;; - Jari: Added topic "Fold must have a label" to the Problem section.
1067 ;;   as reported by Solofo Ramangalahy <solofo A T mpi-sb mpg de>
1068 ;; - 1998-05-04 Ryszard Kubiak <R Kubiak A T ipipan gda pl> reported: I am
1069 ;;   just curious if it is possible to make Emacs' cursor
1070 ;;   automatically follow a mouse-click on the {{{ and }}} lines. I
1071 ;;   mean by this that a [S-mouse-3] (as defined in my settings below
1072 ;;   --- I keep not liking overloading [mouse-3]) first moves the
1073 ;;   cursor to where the click happened and then hides or shows a
1074 ;;   folded area. I presume that i can write a two-lines long
1075 ;;   interactive function to do this. Still, may be this kind of mouse
1076 ;;   behaviour is already available.
1077 ;;
1078 ;; Mar 17  1998  19.34             [Jari 2.34-2.35]
1079 ;; - Added "Example: choosing different fold marks for mode"
1080 ;; - corrected `my-folding-text-mode-setup' example.
1081 ;;
1082 ;; Mar 10  1998  19.34             [Jari 2.32-2.33]
1083 ;; - [Anders] responds to mouse-3 handling problem: I have found the
1084 ;;   cause of the problem, and I have a suggestion for a fix.
1085 ;;
1086 ;;   The problem is caused by two things:
1087 ;;    * The "mouse-save-then-kill" checks that the previous command also
1088 ;;      was "mouse-save-then-kill".
1089 ;;
1090 ;;    * The second (more severe) problem is that
1091 ;;     "folding-mouse-context-sensitive" sets the point to the
1092 ;;     location of the click, effectively making
1093 ;;     "mouse-save-then-kill" mark the area between the point and the
1094 ;;     point! (This is why no region appears.)
1095 ;;
1096 ;;   The first problem can be easily fixed by setting "this-command"
1097 ;;   in "folding-mouse-call-original":
1098 ;;
1099 ;; -  Now the good old mouse-3 binding is back again.
1100 ;; - (folding-mouse-context-sensitive): Added `save-excursion' as
1101 ;;   Anders suggested before setting `state'.
1102 ;;   (folding-mouse-call-original): commented out experimental code and
1103 ;;   used (setq this-command orig-func) as Anders suggested.
1104 ;;
1105 ;; Mar 10  1998  19.34             [Jari 2.31]
1106 ;; - (folding-act): Added `event' to `folding-behave-table' calls.
1107 ;;   Input argument takes now `event' too
1108 ;; - (folding-mouse-context-sensitive): Added argument `event'
1109 ;; - (folding-mouse-call-original): Added  (this-command orig-func)
1110 ;;   when calling original command.
1111 ;; - (folding-bind-default-mouse): Changed mouse bindings. The
1112 ;;   button-3 can't be mapped by folding, because folding is unable to
1113 ;;   call the original function `mouse-save-then-kill'. Passing simple
1114 ;;   element to `mouse-save-then-kill' won't do the job. Eg if I
1115 ;;   (clicked mouse-1) moved mouse pointer to place X and pressed
1116 ;;   mouse-3, the area was not highlighted in folding mode. If folding
1117 ;;   mode was off the are was highlighted. I traced the
1118 ;;   `folding-mouse-call-original' and it was passing exactly the same
1119 ;;   event as without folding mode. I have no clue what to do about
1120 ;;   it...That's why I removed default mouse-3 binding and left it to
1121 ;;   emacs. This bug was reported by Ryszard Kubiak"
1122 ;;   <R Kubiak A T ipipan gda pl>
1123 ;;
1124 ;; Feb 12  1998  19.34             [Jari 2.30]
1125 ;; - (html-mode): New mode added to `folding-mode-marks-alist'
1126 ;; - (folding-get-mode-marks): Rewritten, now return 3rd element too.
1127 ;; - (folding-comment-fold): Added note that function with `comment-end'
1128 ;;   is not supported. Function will flag error in those cases.
1129 ;; - (folding-convert-to-major-folds): Conversion failed if eg; you
1130 ;;   switched between modes that has 2 and 1 comments, like
1131 ;;   /* */ (C) and //(C++). Now the conversion is bit smarter, but it's
1132 ;;   impossible to convert from /* */ to // directly because we don't
1133 ;;   know how to remove */ mark, you see:
1134 ;;
1135 ;;   Original mode was C
1136 ;;
1137 ;;      /* {{{ */
1138 ;;
1139 ;;   And now used changed it to C++ mode, and ran command
1140 ;;   `folding-convert-to-major-folds'. We no longer have information
1141 ;;   about old mode's beginning or end comment markers, so we only
1142 ;;   can convert the folds to format
1143 ;;
1144 ;;     // {{{ */
1145 ;;
1146 ;;   Where the ending comment mark from old mode is left there.
1147 ;;   This is slightly imperfect situation, but at least the fold
1148 ;;   conversion works.
1149 ;;
1150 ;; Jan 28  1998  19.34             [Jari 2.25-2.29]
1151 ;; - Added `generic-mode' to fold list, suggested by Wayne Adams
1152 ;;   <wadams A T galaxy sps mot com>
1153 ;; - Finally rewrote the awesome menu-bar code: now uses standard
1154 ;;   easy-menu Which works in both XEmacs and Emacs. The menu is no
1155 ;;   longer under "Tools", but appear when minor mode is turned on.
1156 ;; - Radical changes: Decided to remove all old lucid and epoch
1157 ;;   dependencies.  Lot of code removed and reprogrammed.
1158 ;; - I also got rid of the `folding-has-minor-mode-map-alist-p' variable
1159 ;;   and old 18.xx function `folding-merge-keymaps'.
1160 ;; - Symbol's value as variable is void ((folding-xemacs-p)) error fixed.
1161 ;; - Optimized 60 `folding-use-overlays-p' calls to only 4 within
1162 ;;   `folding-subst-regions'. (Used elp.el). It seems that half of the
1163 ;;   time is spent in the function `folding-narrow-to-region'
1164 ;;   function. Could it be optimized somehow?
1165 ;; - Changed "lucid" tests to `folding-xemacs-p' variable tests.
1166 ;; - Removed `folding-hack' and print message 'Info, ignore missing
1167 ;;   functions.."  instead. It's better that we see the missing
1168 ;;   functions and not define dummy hacks for them.
1169 ;;
1170 ;; Nov 13  1997  19.34             [Jari 2.18-2.24]
1171 ;; - Added tcl-mode  fold marks, suggested by  Petteri Kettunen
1172 ;;   <Petteri Kettunen A T oulu fi>
1173 ;; - Removed some old code and modified the hook functions a bit.
1174 ;; - Added new user function `folding-convert-to-major-folds', key "%".
1175 ;; - Added missing items to Emacs menubar, didn't dare to touch the
1176 ;;   XEmacs part.
1177 ;; - `folding-comment-fold': Small fix. commenting didn't work on
1178 ;;   closed folds.  or if point was on topmost fold.
1179 ;; - Added `folding-advice-instantiate' And corrected byte compiler
1180 ;;   message: Warning: variable oldposn bound but not referenced
1181 ;;   Warning: reference to free variable folding-stack
1182 ;; - updated (require 'custom) code
1183 ;;
1184 ;; Nov 6  1997  19.34             [Jari 2.17]
1185 ;; - Uwe Brauer <oub A T sunma4 mat ucm es> used folding for Latex files
1186 ;;   and he wished a feature that would allow him to comment away ext
1187 ;;   that was inside fold; when compiling the TeX file.
1188 ;; - Added new user function `folding-comment-fold'. And new
1189 ;;   keybinding ";".
1190 ;;
1191 ;; Oct 8  1997  19.34             [Jari 2.16]
1192 ;; - Now the minor mode map is always re-installed when this file is
1193 ;;   loaded.  If user accidentally made mistake in
1194 ;;   `folding-default-keys-function', he can simply try again and
1195 ;;   reload this file to have the new key definitions.
1196 ;; - Previously user had to manually go and delete the previous map
1197 ;;   from the `minor-mode-map-alist' before he could try again.
1198 ;;
1199 ;; Sep 29 1997  19.34             [Jari 2.14-2.15]
1200 ;; - Robert Marshall <rxmarsha A T bechtel com> Sent enhancement to goto-line
1201 ;;   code. Now M-g works more intuitively.
1202 ;; - Reformatted totally the documentation so that it can be ripped to
1203 ;;   html with jari's ema-doc.pls and t2html.pls Perl scripts.
1204 ;; - Run through checkdoc.el 1.55 and Elint 1.10 and corrected code.
1205 ;; - Added defcustom support. (not tested)
1206 ;;
1207 ;; Sep 19 1997  19.28             [Jari 2.13]
1208 ;; - Robert Marshall <rxmarsha A T bechtel com> Sent small correction to
1209 ;;   overlay code, where the 'owner tag was set wrong.
1210 ;;
1211 ;; Aug 14 1997  19.28             [Jari 2.12 ]
1212 ;; - A small regexp bug (extra whitespace was required after closing
1213 ;;   fold) cause failing of folding-convert-buffer-for-printing in the
1214 ;;   following situation
1215 ;; - Reported by Guide. Fixed now.
1216 ;;
1217 ;;   {{{ Main topic
1218 ;;   {{{ Subsection
1219 ;;   }}}               << no space or end tag here!
1220 ;;   }}} Main topic
1221 ;;
1222 ;; Aug 14 1997  19.28             [Jari 2.11]
1223 ;; - Guide Van Hoecke <Guido Van Hoecke A T bigfoot com> reported that
1224 ;;   he was using closing text for fold like:
1225 ;;
1226 ;;   {{{ Main topic
1227 ;;   {{{ Subsection
1228 ;;   }}} Subsection
1229 ;;   }}} Main topic
1230 ;;
1231 ;;   And when he did folding-convert-buffer-for-printing, it couldn't
1232 ;;   remove those closing marks but threw an error. I modified the
1233 ;;   function so that the regexp accepts anything after closing fold.
1234 ;;
1235 ;; Apr 18 1997  19.28             [Jari 2.10]
1236 ;; - Corrected function folding-show-current-subtree, which didn't
1237 ;;   find the correct end region, because folding-pick-move needed
1238 ;;   point at the top of beginning fold. Bug was reported by Uwe
1239 ;;   Brauer <oub A T sunma4 mat ucm es> Also changed folding-mark-look-at,
1240 ;;   which now has new call parameter 'move.
1241 ;;
1242 ;; Mar 22 1997  19.28             [Jari 2.9]
1243 ;; - Made the XEmacs20 match more stricter, so that
1244 ;;   folding-emacs-version gets value 'XEmacs19. Also added note about
1245 ;;   folding in WinNT in the compatibility section.
1246 ;; - Added sh-script-mode indented-text-mode folding marks.
1247 ;; - Moved the version from branch to the root, because the extra
1248 ;;   overlay code added, seems to be behaving well and it didn't break
1249 ;;   the existing functionality.
1250 ;;
1251 ;; Feb 17 1997  19.28             [Jari 2.8.1.2]
1252 ;; - Cleaned up Dan's changes. First: we must not replace the
1253 ;;   selective display code, but offer these two choices: Added
1254 ;;   folding-use-overlays-p function which looks variable
1255 ;;   folding-allow-overlays.
1256 ;; - Dan uses function from another Emacs specific (19.34+?) package
1257 ;;   hs-discard-overlays. This is not available in 19.28. it should
1258 ;;   be replaced with some new function... I didn't do that yet.
1259 ;; - The overlays don't exist in XEmacs. XE19.15 has promises: at least
1260 ;;   I have heard that they have overlay.el library to mimic Emacs
1261 ;;   functions.
1262 ;; - Now the overlay support can be turned on by setting
1263 ;;   folding-allow-overlays to non-nil. The default is to use selective
1264 ;;   display. Overlay Code is not tested!
1265 ;;
1266 ;; Feb 17 1997  19.28             [Dan  2.8.1.1]
1267 ;; - Dan Nicolaescu <done A T ece arizona edu> sent patch that replaced
1268 ;;   selective display code with overlays.
1269 ;;
1270 ;; Feb 10 1997  19.28             [jari 2.8]
1271 ;; - Ricardo Marek <ricky A T ornet co il> Kindly sent patch that
1272 ;;   makes code XEmacs 20.0 compatible. Thank you.
1273 ;;
1274 ;; Nov 7  1996  19.28             [jari 2.7]
1275 ;; - When I was on picture-mode and turned on folding, and started
1276 ;;   isearch (I don't remember how I got fold mode on exactly) it
1277 ;;   gave error that the fold marks were not defined and emacs
1278 ;;   locked up due to simultaneous isearch-loop
1279 ;; - Added few fixes to the isearch handling function to avoid
1280 ;;   infinite error loops.
1281 ;;
1282 ;; Nov 6 1996  19.28              [jari 2.5 - 2.6]
1283 ;; - Situation: have folded buffer, manually _narrow_ somewhere, C-x n n
1284 ;; - Then try searching --> folding breaks. Now it checks if the
1285 ;;   region is true narrow and not folding-narrow before trying
1286 ;;   to go outside of region and open a fold
1287 ;; - If it's true narrow, then we stay in that narrowed region.
1288 ;;
1289 ;;   folding-isearch-general               :+
1290 ;;   folding-region-has-folding-marks-p       :+
1291 ;;
1292 ;; Oct 23 1996  19.28             [jari 2.4]
1293 ;;   folding-display-name                  :+ new user cmd "C-n"
1294 ;;   folding-find-folding-mark             :+ new
1295 ;;   folding-pick-move                     :! rewritten, full of bugs
1296 ;;   folding-region-open-close             :! rewritten, full of bugs
1297 ;;
1298 ;; Oct 22 1996  19.28             [jari 2.3]
1299 ;; - folding-pick-move                     :! rewritten
1300 ;;   folding-region-open-close             :+ new user cmd "#"
1301 ;;   folding-show-current-subtree          :+ new user cmd "C-s", hides too
1302 ;;
1303 ;; Aug 01 1996  19.31             [andersl]
1304 ;; - folding-subst-regions, variable `font-lock-mode' set to nil.
1305 ;;   Thanks to <stig A T hackvan com>
1306 ;;
1307 ;; Jun 19 1996  19.31             [andersl]
1308 ;; - The code has proven itself stable through the beta testing phase
1309 ;;   which has lasted the past six months.
1310 ;; - A lot of comments written.
1311 ;; - The package `folding-isearch' integrated.
1312 ;; - Some code cleanup:
1313 ;;   BOLP -> folding-BOL                   :! renamed
1314 ;;   folding-behave-table                  :! field `down' removed.
1315 ;;
1316 ;;
1317 ;; Mar 14 1996  19.28             [jari  1.27]
1318 ;; - No code changes. Only some textual corrections/additions.
1319 ;; - Section "about keymaps" added.
1320 ;;
1321 ;; Mar 14 1996  19.28             [jackr 1.26]
1322 ;; - spell-check run over code.
1323 ;;
1324 ;; Mar 14 1996  19.28             [davidm 1.25]
1325 ;; - David Masterson <davidm A T prism kla com> This patch makes the menubar in
1326 ;;   XEmacs work better. After I made this patch, the Hyperbole menus
1327 ;;   starting working as expected again. I believe the use of
1328 ;;   set-buffer-menubar has a problem, so the recommendation in XEmacs
1329 ;;   19.13 is to use set-menubar-dirty-flag.
1330 ;;
1331 ;; Mar 13 1996  19.28             [andersl 1.24]
1332 ;; - Corrected one minor bug in folding-check-if-folding-allowed
1333 ;;
1334 ;; Mar 12 1996  19.28             [jari 1.23]
1335 ;; - Renamed all -func variables to -function.
1336 ;;
1337 ;; mar 12 1996  19.28             [jari 1.22]
1338 ;; - Added new example how to change the fold marks. The automatic folding
1339 ;;   was reported to cause unnecessary delays for big files (eg. when using
1340 ;;   ediff) Now there is new function variable which can totally disable
1341 ;;   automatic folding if the return value is nil.
1342 ;;
1343 ;;   folding-check-allow-folding-function   :+ new variable
1344 ;;   folding-check-if-folding-allowed       :+ new func
1345 ;;   folding-mode-find-file                 :! modified
1346 ;;   folding-mode-write-file                :! better docs
1347 ;;   folding-goto-line                      :! arg "n" --> "N" due to XEmacs 19.13
1348 ;;
1349 ;; Mar 11 1996  19.28             [jari 1.21]
1350 ;; - Integrated changes made by Anders' to v1.19 [folding in beta dir]
1351 ;;
1352 ;; Jan 25 1996  19.28             [jari 1.20]
1353 ;; - ** Mainly cosmetic changes **
1354 ;; - Added some 'Section' codes that can be used with lisp-mnt.el
1355 ;; - Deleted all code in 'special section' because it was never used.
1356 ;; - Moved some old "-v-" named variables to better names.
1357 ;; - Removed folding-mode-flag that was never used.
1358 ;;
1359 ;; Jan 25 1996  19.28             [jari 1.19]
1360 ;; - Put Anders' latest version into RCS tree.
1361 ;;
1362 ;; Jan 03 1996  19.30             [andersl]
1363 ;; - `folding-mouse-call-original' uses `call-interactively'.
1364 ;;   `folding-mouse-context-sensitive' doesn't do `save-excursion'.
1365 ;;   (More changes will come later.)
1366 ;;   `folding-mouse-yank-at-p' macro corrected  (quote added).
1367 ;;   Error for `epoch::version' removed.
1368 ;;   `folding-mark-look-at' Regexp change .* -> [^\n\r]* to avoid error.
1369 ;;
1370 ;; Nov 24 1995  19.28             [andersl]
1371 ;; - (sequencep ) added to the code which checks for the existence
1372 ;;   of a tools menu.
1373 ;;
1374 ;; Aug 27 1995  19.28 19.12       [andersl]
1375 ;; - Keybindings restructured. They now conforms with the
1376 ;;   new 19.29 styleguide. Old keybindings are still available.
1377 ;; - Menus new goes into the "Tools" menu, if present.
1378 ;; - `folding-mouse-open-close' renamed to
1379 ;;   `folding-mouse-context-sensitive'.
1380 ;; - New entry `other' in `folding-behave-table' which defaults to
1381 ;;   `folding-calling-original'.
1382 ;; - `folding-calling-original' now gets the event from `last-input-event'
1383 ;;   if called without arguments (i.e. the way `folding-act' calls it.)
1384 ;; - XEmacs mouse support added.
1385 ;; - `folding-mouse-call-original' can call functions with or without
1386 ;;   the Event argument.
1387 ;; - Byte compiler generates no errors neither for Emacs 19 and XEmacs.
1388 ;;
1389 ;; Aug 24 1995  19.28             [jari  1.17]
1390 ;; - To prevent infinite back calling loop, Anders suggested smart way
1391 ;;   to detect that func call chain is started only once.
1392 ;;   folding-calling-original      :+ v, call chain terminator
1393 ;;   "Internal"                 :! v, all private vars have this string
1394 ;;   folding-mouse-call-original   :! v, stricter chain check.
1395 ;;   "copyright"                :! t, newer notice
1396 ;;   "commentary"               :! t, ripped non-supported emacsen
1397 ;;
1398 ;; Aug 24 1995  19.28             [jari  1.16]
1399 ;; ** mouse interface rewritten
1400 ;; - Anders gave many valuable comments about simplifying the mouse usage,
1401 ;;   he suggested that every mouse function should accept standard event,
1402 ;;   and it should be called directly.
1403 ;;   folding-global                 :- v, not needed
1404 ;;   folding-mode-off-hook          :- v, not needed
1405 ;;   folding-mouse-action-table     :- v, not needed any more
1406 ;;   folding-default-keys-function  :+ v, key settings
1407 ;;   folding-default-mouse-keys-function:+ v, key settings
1408 ;;   folding-mouse                  :- f, unnecessary
1409 ;;   'all mouse funcs'              :! f, now accept "e" parameter
1410 ;;   folding-default-keys           :+ f, defines keys
1411 ;;   folding-mouse-call-original    :+ f, call orig mouse func
1412 ;;   "examples"                     :! t, radical rewrote, only one left
1413 ;;
1414 ;; Aug 24 1995  19.28             [jari  1.15]
1415 ;; - some minor changes. If we're inside a fold, Mouse-3 will go one
1416 ;;   level up if it points END or BEG marker.
1417 ;;   folding-mouse-yank-at-point:! v, added 'up 'down
1418 ;;   folding-mark-look-at       :! f, more return values: '11 and 'end-in
1419 ;;   folding-open-close         :! f, bug, didn't exit if inside fold
1420 ;;   PMIN, PMAX, NEXTP, add-l   :+ more macros fom tinylibm.el
1421 ;;
1422 ;; Aug 23 1995  19.28             [andersl 1.14]
1423 ;; - Added `eval-when-compile' around 1.13 byte-compiler fix
1424 ;;   to avoid code to be executed when using a byte-compiled version
1425 ;;   of folding.el.
1426 ;; - Binds mode keys via `minor-mode-map-alist'
1427 ;;   (i.e. `folding-merge-keymaps' is not used in modern Emacsen.)
1428 ;;   This means that the user can not bind `folding-mode-map' to a new
1429 ;;   keymap, \\(s\\|\\)he must modify the existing one.
1430 ;; - `defvars' for global feature test variables `folding-*-p'.
1431 ;; - `folding-mouse-open-close' now detects when the current fold was been
1432 ;;   pressed. (The "current" is the fold around which the buffer is
1433 ;;   narrowed.)
1434 ;;
1435 ;; Aug 23 1995  19.28             [jari  1.13]
1436 ;; - 19.28 Byte compile doesn't handle fboundp, boundp well. That's a bug.
1437 ;;   Set some dummy functions to get cleaner output.
1438 ;; - The folding-mode-off doesn't seem very useful, because it
1439 ;;   is never run when another major-mode is turned on ... maybe we should
1440 ;;   utilize kill-all-local-variables-hooks with defadvice around
1441 ;;   kill-all-local-variables ...
1442 ;;
1443 ;;   folding-emacs-version  :+ added. it was in the docs, but not defined
1444 ;;   kill-all-local-variables-hooks  :! v, moved to variable section
1445 ;;   list-buffers-mode-alist         :! v, --''--
1446 ;;   "compiler hacks"                :+ section added
1447 ;;   "special"                       :+ section added
1448 ;;   "Compatibility"                 :! moved at the beginning
1449 ;;
1450 ;; Aug 22 1995  19.28             [jari  1.12]
1451 ;; - Only minor changes
1452 ;;   BOLP, BOLPP, EOLP, EOLPP   :+ f, macros added from tinylibm.el
1453 ;;   folding-mouse-pick-move    :! f, when cursor at beolp, move always up
1454 ;;   "bindings"                 :+ added C-cv and C-cC-v
1455 ;;
1456 ;; Aug 22 1995  19.28             [jari  1.11]
1457 ;; - Inspired by mouse so much, that this revision contain substantial
1458 ;;   changes and enhancements. Mouse is now powered!
1459 ;; - Anders wanted mouse to operate according to 'mouse cursor', not
1460 ;;   current 'point'.
1461 ;;   folding-mouse-yank-at-point: controls it. Phwew, I like this
1462 ;;   one a lot.
1463 ;;
1464 ;;   examples                       :! t, totally changed, now 2 choices
1465 ;;   folding-mode-off-hook          :+ v, when folding ends
1466 ;;   folding-global                 :+ v, global store value
1467 ;;   folding-mouse-action-table     :! v, changed
1468 ;;   folding-mouse                  :! f, stores event to global
1469 ;;   folding-mouse-open-close       :! f, renamed, mouse activated open
1470 ;;   folding-mode                   :! f, added 'off' hook
1471 ;;   folding-event-posn             :+ f, handles FSF mouse event
1472 ;;   folding-mouse-yank-at-p        :+ f, check which mouse mode is on
1473 ;;   folding-mouse-point            :+ f, return working point
1474 ;;   folding-mouse-move             :+ f, mouse moving down  , obsolete ??
1475 ;;   folding-mouse-pick-move            :+ f, mouse move accord. fold mark
1476 ;;   folding-next-visible-heading       :+ f, from tinyfold.el
1477 ;;   folding-previous-visible-heading   :+ f, from tinyfold.el
1478 ;;   folding-pick-move                  :+ f, from tinyfold.el
1479 ;;
1480 ;;
1481 ;; Aug 22 1995  19.28             [jari  1.10]
1482 ;; - Minor typing errors corrected : fol-open-close 'hide --> 'close
1483 ;;   This caused error when trying to close open fold with mouse
1484 ;;   when cursor was sitting on fold marker.
1485 ;;
1486 ;; Aug 22 1995  19.28             [jari  1.9]
1487 ;; - Having heard good suggestions from Anders...!
1488 ;;   "install"                  : add-hook for folding missed
1489 ;;   folding-open-close            : generalized
1490 ;;   folding-behave-table          : NEW, logical behavior control
1491 ;;   folding-:mouse-action-table   : now folding-mouse-action-table
1492 ;;
1493 ;; - The mouse function seems to work with FSF emacs only, because
1494 ;;   XEmacs doesn't know about double or triple clicks. We're working
1495 ;;   on the problem...
1496 ;;
1497 ;; Aug 21 1995  19.28             [jari  1.8]
1498 ;; - Rearranged the file structure so that all variables are at the
1499 ;;   beginning of file. With new functions, it easy to open-close
1500 ;;   fold. Added word "code:" or "setup:" to the front of code folds,
1501 ;;   so that the toplevel folds can be recognized more easily.
1502 ;; - Added example hook to install section for easy mouse use.
1503 ;; - Added new functions.
1504 ;;   folding-get-mode-marks : return folding marks
1505 ;;   folding-mark-look-at   : status of current line, fold mark in it?
1506 ;;   folding-mark-mouse     : execute action on fold mark
1507 ;;
1508 ;;
1509 ;; Aug 17 1995  19.28/X19.12      [andersl 1.7]
1510 ;; - Failed when loaded into XEmacs, when `folding-mode-map' was
1511 ;;   undefined.  Folding marks for three new major modes added:
1512 ;;   rexx-mode, erlang-mode and xerl-mode.
1513 ;;
1514 ;; Aug 14 1995  19.28             [jari  1.6]
1515 ;; - After I met Anders we exchanged some thoughts about usage philosophy
1516 ;;   of error and signal commands. I was annoyed by the fact that they
1517 ;;   couldn't be suppressed, when the error was "minor". Later Anders
1518 ;;   developed fdb.el, which will be integrated to FSF 19.30. It
1519 ;;   offers by-passing error/signal interference.
1520 ;;   --> I changed back all the error commands that were taken away.
1521 ;;
1522 ;; Jun 02 1995  19.28             [andersl]
1523 ;; - "Narrow" not present in mode-line when in folding-mode.
1524 ;;
1525 ;; May 12 1995  19.28             [jari  1.5]
1526 ;; - Installation text cleaned: reference to 'install-it' removed,
1527 ;;   because such function doesn't exist any more. The installation is
1528 ;;   now automatic: it's done when user calls folding mode first time.
1529 ;; - Added 'private vars' section. made 'outside all folds' message
1530 ;;   informational, not an error.
1531 ;;
1532 ;; May 12 1995  19.28             [jackr  x.x]
1533 ;; - Corrected 'broken menu bar' problem.
1534 ;; - Even though make-sparse-keymap claims its argument (a string to
1535 ;;   name the  menu) is optional, it's not. Lucid has other
1536 ;;   arrangements for the same thing..
1537 ;;
1538 ;; May 10 1995  19.28             [jari 1.2]
1539 ;; - Moved provide to the end of file.
1540 ;; - Rearranged code so that the common functions are at the beginning.
1541 ;;   Reprogrammed the whole installation with hooks. Added Write file
1542 ;;   hook that makes sure you don't write in 'binary' while folding were
1543 ;;   accidentally off.
1544 ;; - Added regexp text for certain files which are not allowed to
1545 ;;   'auto fold' when loaded.
1546 ;; - changed some 'error' commands to 'messages', this prevent screen
1547 ;;   mixup when debug-on-error is set to t
1548 ;; + folding-list-delete , folding-msg , folding-mode-find-file ,
1549 ;;   folding-mode-write-file , folding-check-folded , folding-keep-hooked
1550 ;;
1551 ;; 1.7.4 May 04 1995  19.28             [jackr 1.11]
1552 ;; - Some compatibility changes:
1553 ;;      v.18 doesn't allow an arg to make-sparse-keymap
1554 ;;      testing epoch::version is trickier than that
1555 ;;      free-variable reference cleanup
1556 ;;
1557 ;; 1.7.3 May 04 1995  19.28             [jari]
1558 ;; - Corrected folding-mode-find-file-hook , so that it has more
1559 ;;   'mode turn on' capabilities through user function
1560 ;; + folding-mode-write-file-hook: Makes sure your file is saved
1561 ;;   properly, so that you don't end up saving in 'binary'.
1562 ;; + folding-check-folded: func, default checker provided
1563 ;; + folding-check-folded-file-function variable added, User can put his
1564 ;;   'detect folding.el file' methods here.
1565 ;; + folding-mode-install-it: func, Automatic installation with it
1566 ;;
1567 ;; 1.7.2  Apr 01 1995   19.28           [jackr] , Design support by [jari]
1568 ;; - Added folding to FSF & XEmacs menus
1569 ;;
1570 ;; 1.7.1  Apr 28 1995   19.28           [jackr]
1571 ;; - The folding editor's merge-keymap couldn't handle FSF menu-bar,
1572 ;;   so some minor changes were made, previous is '>' and enhancements
1573 ;;   are '>'
1574 ;;
1575 ;; <     (buffer-disable-undo new-buffer)
1576 ;; ---
1577 ;; >     (buffer-flush-undo new-buffer)
1578 ;; 1510,1512c1510
1579 ;; <                    key (if (symbolp keycode)
1580 ;; <                            (vector keycode)
1581 ;; <                          (char-to-string keycode))
1582 ;; ---
1583 ;; >                    key (char-to-string keycode)
1584 ;; 1802,1808d1799
1585 ;; < ;;{{{ Compatibility hacks for various Emacs versions
1586 ;; <
1587 ;; < (or (fboundp 'buffer-disable-undo)
1588 ;; <     (fset 'buffer-disable-undo (symbol-function 'buffer-flush-undo)))
1589 ;; <
1590 ;; < ;;}}}
1591 ;;
1592 ;;
1593 ;; X.x  Dec 1   1994    19.28           [jari]
1594 ;; - Only minor change. Made the folding mode string user configurable.
1595 ;;   Added these variables:
1596 ;;   folding-mode-string, folding-inside-string,folding-inside-mode-name
1597 ;; - Changed revision number from 1.6.2 to 1.7 , so that people know
1598 ;;   this package has changed.
1599
1600 ;;}}}
1601
1602 ;;; Code:
1603
1604 ;;{{{ setup: require packages
1605
1606 ;;; ......................................................... &require ...
1607
1608 (eval-when-compile (require 'cl))
1609 (require 'easymenu)
1610
1611 (defvar folding-package-url-location
1612   "Latest folding is available at http://cvs.xemacs.org/viewcvs.cgi/XEmacs/packages/xemacs-packages/text-modes/")
1613
1614 ;;}}}
1615 ;;{{{ setup: byte compiler hacks
1616
1617 ;;; ............................................. &byte-compiler-hacks ...
1618 ;;; - This really only should be evaluated in case we're about to byte
1619 ;;;   compile this file. Since `eval-when-compile' is evaluated when
1620 ;;;   the uncompiled version is used (great!) we test if the
1621 ;;;   byte-compiler is loaded.
1622
1623 ;; Make sure `advice' is loaded when compiling the code.
1624
1625 (eval-and-compile
1626   (require 'advice)
1627   (defvar folding-xemacs-p (or (boundp 'xemacs-logo)
1628                                (featurep 'xemacs))
1629     "Folding determines which emacs version it is running. t if Xemacs.")
1630   ;;  loading overlay.el package removes some byte compiler whinings.
1631   ;;  By default folding does not use overlay code.
1632   (if folding-xemacs-p
1633       (or (fboundp 'overlay-start)  ;; Already loaded
1634           (load "overlay" 'noerr)   ;; No? Try loading it.
1635           (message "\
1636 ** folding.el: XEmacs 19.15+ has package overlay.el, try to get it.
1637                This is only warning. Folding does not use overlays by
1638                default.  You can safely ignore possible overlay byte
1639                compilation error
1640                messages."))))
1641
1642 (eval-when-compile
1643
1644   (when nil ;; Disabled 2000-01-05
1645     ;; While byte compiling
1646     (if (string= (buffer-name) " *Compiler Input*")
1647         (progn
1648           (message "** folding.el:\
1649  Info, Ignore [X]Emacs's missing motion/event/posn functions calls"))))
1650
1651   ;; ARGS: (symbol variable-p library)
1652   (defadvice find-function-search-for-symbol (around folding act)
1653     "Set folding flag for `find-file-noselect' to open all folds."
1654     (let ((file (ad-get-arg 2)))
1655       (when file
1656         (message "FILE %s" file)
1657         (put 'find-file-noselect 'folding file)))
1658     ad-do-it
1659     (put 'find-file-noselect 'folding nil))
1660
1661   (defun folding-find-file-noselect ()
1662     (let* ((file   (get 'find-file-noselect 'folding))
1663            (buffer (and file
1664                         ;; It may be absolute path name, file.el,
1665                         ;; or just "file".
1666                         (or (find-buffer-visiting file)
1667                             (get-buffer file)
1668                             (get-buffer (concat file ".el"))))))
1669       (when buffer
1670         (with-current-buffer buffer
1671           (when (symbol-value 'folding-mode) ;; Byte compiler silencer
1672             (turn-off-folding-mode))))))
1673
1674   ;;  See find.func.el  find-function-search-for-symbol
1675   ;;  Make C-h f  and mouse-click work to jump to a file. Folding mode
1676   ;;  Must be turned off due to regexps in find.func.el that can't
1677   ;;  search ^M lines.
1678
1679   (defadvice find-file-noselect (after folding act)
1680     "When called by `find-function-search-for-symbol', turn folding off."
1681     (folding-find-file-noselect))
1682
1683   (defadvice make-sparse-keymap
1684     (before
1685      make-sparse-keymap-with-optional-argument
1686      (&optional byte-compiler-happyfier)
1687      activate)
1688     "This advice does nothing except adding an optional argument
1689 to keep the byte compiler happy when compiling Emacs specific code
1690 with XEmacs.")
1691
1692   ;; XEmacs and Emacs 19 differs when it comes to obsolete functions.
1693   ;; We're using the Emacs 19 versions, and this simply makes the
1694   ;; byte-compiler stop wining. (Why isn't there a warning flag which
1695   ;; could have turned off?)
1696
1697   (and (boundp 'mode-line-format)
1698        (put 'mode-line-format 'byte-obsolete-variable nil))
1699
1700   (and (fboundp 'byte-code-function-p)
1701        (put 'byte-code-function-p 'byte-compile nil))
1702
1703   (and (fboundp 'eval-current-buffer)
1704        (put 'eval-current-buffer 'byte-compile nil)))
1705
1706 (defsubst folding-preserve-active-region ()
1707   "In XEmacs keep the region alive. In Emacs do nothing."
1708   (if (boundp 'zmacs-region-stays)      ;Keep regions alive
1709       (set 'zmacs-region-stays t))) ;use `set' to Quiet Emacs Byte Compiler
1710
1711 ;; Work around the NT Emacs Cut'n paste bug in selective-display which
1712 ;; doesn't preserve C-m's. Only installed in problematic Emacs and
1713 ;; in other cases these lines are no-op.
1714
1715 (eval-and-compile
1716   (when (and (not folding-xemacs-p)
1717              (memq (symbol-value 'window-system) '(win32 w32)) ; NT Emacs
1718              (string< emacs-version "20.4")) ;at least in 19.34 .. 20.3.1
1719
1720     (unless (fboundp 'char-equal)
1721       (defalias 'char-equal  'equal))
1722
1723     (unless (fboundp 'subst-char)
1724       (defun subst-char (str char to-char)
1725         "Replace in STR every CHAR with TO-CHAR."
1726         (let ((len   (length str))
1727               (ret   (copy-sequence str))) ;because 'aset' is destructive
1728           (while (> len 0)
1729             (if (char-equal (aref str (1- len)) char)
1730                 (aset ret (1- len) to-char))
1731             (decf len))
1732           ret)))
1733
1734     (defadvice kill-new (around folding-win32-fix-selective-display act)
1735       "In selective display, convert each C-m to C-a. See `current-kill'."
1736       (let* ((string (ad-get-arg 0)))
1737         (when (and selective-display (string-match "\C-m" (or string "")))
1738           (setq string (subst-char string ?\C-m ?\C-a)))
1739         ad-do-it))
1740
1741     (defadvice current-kill (around folding-win32-fix-selective-display act)
1742       "In selective display, convert each C-a back to C-m. See `kill-new'."
1743       ad-do-it
1744       (let* ((string ad-return-value))
1745         (when (and selective-display (string-match "\C-a" (or string "")))
1746           (setq string (subst-char string ?\C-a ?\C-m))
1747           (setq ad-return-value string))))))
1748
1749 (defvar folding-mode) ;; Byte Compiler silencer
1750
1751 (when (locate-library "mode-motion") ;; XEmacs
1752   (defun folding-mode-motion-highlight-fold (event)
1753     "Highlight line under mouse if it has a foldmark."
1754     (when folding-mode
1755       (funcall
1756        ;; Emacs Byte Compiler Shutup fix
1757        (symbol-function 'mode-motion-highlight-internal)
1758        event
1759        (function
1760         (lambda ()
1761           (beginning-of-line)
1762           (if (folding-mark-look-at)
1763               (search-forward-regexp "^[ \t]*"))))
1764        (function
1765         (lambda ()
1766           (if (folding-mark-look-at)
1767               (end-of-line)))))))
1768   (require 'mode-motion)
1769   (add-hook 'mode-motion-hook 'folding-mode-motion-highlight-fold 'at-end))
1770
1771 ;;}}}
1772
1773 ;;{{{ setup: some variable
1774
1775 ;;; .................................................. &some-variables ...
1776
1777 ;; This is a list of structures which keep track of folds being entered
1778 ;; and exited. It is a list of (MARKER . MARKER) pairs, followed by the
1779 ;; symbol `folded'. The first of these represents the fold containing
1780 ;; the current one. If the view is currently outside all folds, this
1781 ;; variable has value nil.
1782
1783 (defvar folding-stack nil
1784   "Internal. A list of marker pairs representing folds entered so far.")
1785
1786 (defvar folding-version  (substring "$Revision: 3.42 $" 11 15)
1787   "Version number of folding.el.")
1788
1789 ;;}}}
1790 ;;{{{ setup: bind
1791
1792 ;;; .......................................................... &v-bind ...
1793
1794 ;; Custom hack for Emacs that does not have custom
1795
1796 (eval-and-compile
1797   (condition-case ()
1798       (require 'custom)
1799     (error nil))
1800   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
1801       nil ;; We've got what we needed
1802     ;; We have the old custom-library, hack around it!
1803     (defmacro defgroup (&rest args)
1804       nil)
1805     (defmacro defcustom (var value doc &rest args)
1806       (` (defvar (, var) (, value) (, doc))))))
1807
1808 (defgroup folding nil
1809   "Managing buffers with Folds."
1810   :group 'tools)
1811
1812 (defcustom folding-mode-prefix-key "\C-c@"
1813   "*Prefix key to use for Folding commands in Folding mode."
1814   :type  'string
1815   :group 'folding)
1816
1817 (defcustom folding-goto-key "\M-g"
1818   "*Key to be bound to `folding-goto-line' in folding mode.
1819 The default value is M - g, but you probably don't want folding to
1820 occupy it if you have used M - g got `goto-line'."
1821   :type  'string
1822   :group 'folding)
1823
1824 (defcustom folding-font-lock-begin-mark 'font-lock-reference-face
1825   "Face to highlight beginning fold mark."
1826   :type  'face
1827   :group 'folding)
1828
1829 (defcustom folding-font-lock-end-mark 'font-lock-reference-face
1830   "Face to highlight end fold mark."
1831   :type  'face
1832   :group 'folding)
1833
1834 (defvar folding-mode-map nil
1835   "Keymap used in Folding mode (a minor mode).")
1836
1837 (defvar folding-mode-prefix-map nil
1838   "Keymap used in Folding mode keys sans `folding-mode-prefix-key'.")
1839
1840 ;;;###autoload
1841 (defvar folding-mode nil
1842   "When Non nil, Folding mode is active in the current buffer.")
1843
1844 (make-variable-buffer-local 'folding-mode)
1845 (set-default 'folding-mode nil)
1846
1847 (defmacro folding-kbd (key function)
1848   "Folding: define KEY with FUNCTION to `folding-mode-prefix-map'.
1849 This is used when assigning keybindings to `folding-mode-map'.
1850 See also `folding-mode-prefix-key'."
1851   (` (define-key
1852        folding-mode-prefix-map
1853        (, key) (, function))))
1854
1855 (defun folding-bind-default-mouse ()
1856   "Bind default mouse keys used by Folding mode."
1857   (interactive)
1858   (cond
1859    (folding-xemacs-p
1860     (define-key folding-mode-map [(button3)]
1861       'folding-mouse-context-sensitive)
1862     ;; (define-key folding-mode-map '(double button3) 'folding-hide-current-entry)
1863     (define-key folding-mode-map [(control shift button2)]
1864       'folding-mouse-pick-move))
1865    (t
1866     (define-key folding-mode-map [mouse-3]     'folding-mouse-context-sensitive)
1867     (define-key folding-mode-map [C-S-mouse-2] 'folding-mouse-pick-move))))
1868
1869 (defun folding-bind-terminal-keys ()
1870   "In non-window system, rebind C - f and C - b as folding-{forward,backward}-char."
1871   (unless (or (and (boundp 'window-system)        ;; Emacs
1872                    (symbol-value 'window-system)) ;; Byte compiler silencer
1873               (and (fboundp 'console-type)        ;; XEmacs
1874                    (let ((val (fboundp 'console-type)))
1875                      (not (eq 'tty val)))))
1876     (define-key folding-mode-map "\C-f" 'folding-forward-char)
1877     (define-key folding-mode-map "\C-b" 'folding-backward-char)))
1878
1879 (defun folding-bind-default-keys ()
1880   "Bind the default keys used the `folding-mode'.
1881
1882 The variable `folding-mode-prefix-key' contains the prefix keys,
1883 the default is C - c @.
1884
1885 For the good ol' key bindings, please use the function
1886 `folding-bind-backward-compatible-keys' instead."
1887   (interactive)
1888   (define-key folding-mode-map folding-goto-key 'folding-goto-line)
1889   (folding-bind-terminal-keys)
1890   (define-key folding-mode-map "\C-e" 'folding-end-of-line)
1891   (folding-kbd "\C-f"   'folding-fold-region)
1892   (folding-kbd ">"      'folding-shift-in)
1893   (folding-kbd "<"      'folding-shift-out)
1894   (folding-kbd "\C-t"   'folding-show-all)
1895   (folding-kbd "\C-s"   'folding-show-current-entry)
1896   (folding-kbd "\C-x"   'folding-hide-current-entry)
1897   (folding-kbd "\C-o"   'folding-open-buffer)
1898   (folding-kbd "\C-w"   'folding-whole-buffer)
1899   (folding-kbd "\C-r"   'folding-convert-buffer-for-printing)
1900   (folding-kbd "\C-k"   'folding-marks-kill)
1901   (folding-kbd  "\C-v"  'folding-pick-move)
1902   (folding-kbd  "v"     'folding-previous-visible-heading)
1903   (folding-kbd  " "     'folding-next-visible-heading)
1904   (folding-kbd  "."     'folding-context-next-action)
1905   ;;  C-u:  kinda "up" -- "down"
1906   (folding-kbd "\C-u"   'folding-toggle-enter-exit)
1907   (folding-kbd "\C-q"   'folding-toggle-show-hide)
1908   ;; Think "#" as a 'fence'
1909   (folding-kbd "#"      'folding-region-open-close)
1910   ;; Esc-; is the standard emacs commend add key.
1911   (folding-kbd ";"      'folding-comment-fold)
1912   (folding-kbd "%"      'folding-convert-to-major-folds)
1913   (folding-kbd "/"      'folding-all-comment-blocks-in-region)
1914   (folding-kbd "\C-y"   'folding-show-current-subtree)
1915   (folding-kbd "\C-z"   'folding-hide-current-subtree)
1916   (folding-kbd "\C-n"   'folding-display-name)
1917
1918   (folding-kbd "I"      'folding-insert-advertise-folding-mode))
1919
1920 (defun folding-bind-backward-compatible-keys ()
1921   "Bind keys traditionally used by Folding mode.
1922 For bindings which follow newer Emacs minor mode conventions, please
1923 use the function `folding-bind-default-keys'.
1924
1925 This function sets `folding-mode-prefix-key' to `C-c'."
1926   (interactive)
1927   (setq folding-mode-prefix-key "\C-c")
1928   (folding-bind-default-keys))
1929
1930 (defun folding-bind-outline-compatible-keys ()
1931   "Bind keys used by the minor mode `folding-mode'.
1932 The keys used are as much as possible compatible with
1933 bindings used by Outline mode.
1934
1935 Currently, some outline mode functions doesn't have a corresponding
1936 folding function.
1937
1938 The variable `folding-mode-prefix-key' contains the prefix keys,
1939 the default is C - c @.
1940
1941 For the good ol' key bindings, please use the function
1942 `folding-bind-backward-compatible-keys' instead."
1943   (interactive)
1944   ;; Traditional keys:
1945   (folding-bind-terminal-keys)
1946   (define-key folding-mode-map "\C-e" 'folding-end-of-line)
1947   ;; Mimic Emacs 20.3 allout.el bindings
1948   (folding-kbd ">"          'folding-shift-in)
1949   (folding-kbd "<"          'folding-shift-out)
1950   (folding-kbd "\C-n"  'folding-next-visible-heading)
1951   (folding-kbd "\C-p"  'folding-previous-visible-heading)
1952   ;; ("\C-u" outline-up-current-level)
1953   ;; ("\C-f" outline-forward-current-level)
1954   ;; ("\C-b" outline-backward-current-level)
1955   ;;  (folding-kbd "\C-i"  'folding-show-current-subtree)
1956   (folding-kbd "\C-s"  'folding-show-current-subtree)
1957   (folding-kbd "\C-h"  'folding-hide-current-subtree)
1958   (folding-kbd "\C-k"  'folding-marks-kill)
1959   (folding-kbd "!"     'folding-show-all)
1960   (folding-kbd "\C-d"  'folding-hide-current-entry)
1961   (folding-kbd "\C-o"  'folding-show-current-entry)
1962   ;; (" " outline-open-sibtopic)
1963   ;; ("." outline-open-subtopic)
1964   ;; ("," outline-open-supertopic)
1965   ;; Other bindings not in allout.el
1966   (folding-kbd "\C-a"  'folding-open-buffer)
1967   (folding-kbd "\C-q"  'folding-whole-buffer)
1968   (folding-kbd "\C-r"  'folding-convert-buffer-for-printing)
1969   (folding-kbd "\C-w"  'folding-fold-region)
1970   (folding-kbd "I"      'folding-insert-advertise-folding-mode))
1971
1972 ;;{{{ goto-line (advice)
1973
1974 (defcustom folding-advice-instantiate t
1975   "*In non-nil install advice code. Eg for `goto-line'."
1976   :type  'boolean
1977   :group 'folding)
1978
1979 (defcustom folding-shift-in-on-goto t
1980   "*Flag in folding adviced function `goto-line'.
1981 If non-nil, folds are entered when going to a given line.
1982 Otherwise the buffer is unfolded. Can also be set to 'show.
1983 This variable is used only if `folding-advice-instantiate' was
1984 non-nil when folding was loaded.
1985
1986 See also `folding-goto-key'."
1987   :type  'boolean
1988   :group 'folding)
1989
1990 (when folding-advice-instantiate
1991   (eval-when-compile (require 'advice))
1992   ;; By Robert Marshall <rxmarsha A T bechtel com>
1993   (defadvice goto-line (around folding-goto-line first activate)
1994     "Go to line ARG, entering folds if `folding-shift-in-on-goto' is t.
1995 It attempts to keep the buffer in the same visibility state as before."
1996     (let () ;; (oldposn (point))
1997       ad-do-it
1998       (if (and folding-mode
1999                (or (folding-point-folded-p (point))
2000                    (<= (point) (point-min-marker))
2001                    (>= (point) (point-max-marker))))
2002           (let ((line (ad-get-arg 0)))
2003             (if folding-shift-in-on-goto
2004                 (progn
2005                   (folding-show-all)
2006                   (goto-char 1)
2007                   (and (< 1 line)
2008                        (not (folding-use-overlays-p))
2009                        (re-search-forward "[\n\C-m]" nil 0 (1- line)))
2010                   (let ((goal (point)))
2011                     (while (prog2 (beginning-of-line)
2012                                (if (eq folding-shift-in-on-goto 'show)
2013                                    (progn
2014                                      (folding-show-current-entry t t)
2015                                      (folding-point-folded-p goal))
2016                                  (folding-shift-in t))
2017                              (goto-char goal)))
2018                     (folding-narrow-to-region
2019                      (and folding-narrow-by-default (point-min))
2020                      (point-max) t)))
2021               (if (or folding-stack (folding-point-folded-p (point)))
2022                   (folding-open-buffer))))))))
2023
2024 ;;}}}
2025
2026 (defun folding-bind-foldout-compatible-keys ()
2027   "Bind keys for `folding-mode' compatible with Foldout mode.
2028
2029 The variable `folding-mode-prefix-key' contains the prefix keys,
2030 the default is C - c @."
2031   (interactive)
2032   (folding-kbd "\C-z" 'folding-shift-in)
2033   (folding-kbd "\C-x" 'folding-shift-out))
2034
2035 ;;; This function is here, just in case we ever would like to add
2036 ;;; `hideif' support to folding mode. Currently, it is only used to
2037 ;;; which keys shouldn't be used.
2038
2039 ;;(defun folding-bind-hideif-compatible-keys ()
2040 ;;  "Bind keys for `folding-mode' compatible with Hideif mode.
2041 ;;
2042 ;;The variable `folding-mode-prefix-key' contains the prefix keys,
2043 ;;the default is C-c@."
2044 ;;  (interactive)
2045 ;;    ;; Keys defined by `hideif'
2046 ;;    ;; (folding-kbd "d" 'hide-ifdef-define)
2047 ;;    ;; (folding-kbd "u" 'hide-ifdef-undef)
2048 ;;    ;; (folding-kbd "D" 'hide-ifdef-set-define-alist)
2049 ;;    ;; (folding-kbd "U" 'hide-ifdef-use-define-alist)
2050 ;;
2051 ;;    ;; (folding-kbd "h") 'hide-ifdefs)
2052 ;;    ;; (folding-kbd "s") 'show-ifdefs)
2053 ;;    ;; (folding-kbd "\C-d") 'hide-ifdef-block)
2054 ;;    ;; (folding-kbd "\C-s") 'show-ifdef-block)
2055 ;;
2056 ;;    ;; (folding-kbd "\C-q" 'hide-ifdef-toggle-read-only)
2057 ;;    )
2058
2059 ;;; .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .
2060
2061 ;; Not used for modern Emacsen.
2062 (defvar folding-saved-local-keymap nil
2063   "Keymap used to save non-folding keymap.
2064 (so it can be restored when folding mode is turned off.)")
2065
2066 ;;;###autoload
2067 (defcustom folding-default-keys-function 'folding-bind-default-keys
2068   "*Function or list of functions used to define keys for Folding mode.
2069 Possible values are:
2070   folding-bind-default-key
2071         The standard keymap.
2072
2073   `folding-bind-backward-compatible-keys'
2074         Keys used by older versions of Folding mode. This function
2075         does not conform to Emacs 19.29 style conversions concerning
2076         key bindings. The prefix key is C - c
2077
2078   `folding-bind-outline-compatible-keys'
2079         Define keys compatible with Outline mode.
2080
2081   `folding-bind-foldout-compatible-keys'
2082         Define some extra keys compatible with Foldout.
2083
2084 All except `folding-bind-backward-compatible-keys' used the value of
2085 the variable `folding-mode-prefix-key' as prefix the key.
2086 The default is C - c @"
2087   :type  'function
2088   :group 'folding)
2089
2090 ;; Not yet implemented:
2091 ;;  folding-bind-hideif-compatible-keys
2092 ;;      Define some extra keys compatible with hideif.
2093
2094 ;;;###autoload
2095 (defcustom folding-default-mouse-keys-function 'folding-bind-default-mouse
2096   "*Function to bind default mouse keys to `folding-mode-map'."
2097   :type 'function
2098   :group 'folding)
2099
2100 (defvar folding-mode-menu nil
2101   "Keymap containing the menu for Folding mode.")
2102
2103 (defvar folding-mode-menu-name "Fld" ;; Short menu name
2104   "Name of pull down menu.")
2105
2106 ;;}}}
2107 ;;{{{ setup: hooks
2108
2109 ;;; ......................................................... &v-hooks ...
2110
2111 (defcustom folding-mode-hook nil
2112   "*Hook called when Folding mode is entered.
2113
2114 A hook named `<major-mode>-folding-hook' is also called, if it
2115 exists. Eg., `c-mode-folding-hook' is called whenever Folding mode is
2116 started in C mode."
2117   :type 'hook
2118   :group 'folding)
2119
2120 (defcustom folding-load-hook nil
2121   "*Hook run when file is loaded."
2122   :type 'hook
2123   :group 'folding)
2124
2125 ;;}}}
2126 ;;{{{ setup: user config
2127
2128 ;;; ........................................................ &v-Config ...
2129
2130 (defvar folding-narrow-by-default t
2131   "If t (default) things like isearch will enter folds.  If nil the
2132 folds will be opened, but not entered.")
2133
2134 ;; Q: should this inherit mouse-yank-at-point's value? maybe not.
2135 (defvar folding-mouse-yank-at-point t
2136   "If non-nil, mouse activities are done at point instead of 'mouse cursor'.
2137 Behaves like `mouse-yank-at-point'.")
2138
2139 (defcustom folding-folding-on-startup t
2140   "*If non-nil, buffers are folded when starting Folding mode."
2141   :type 'boolean
2142   :group 'folding)
2143
2144 (defcustom folding-internal-margins 1
2145   "*Number of blank lines left next to fold mark when tidying folds.
2146
2147 This variable is local to each buffer. To set the default value for all
2148 buffers, use `set-default'.
2149
2150 When exiting a fold, and at other times, `folding-tidy-inside' is invoked
2151 to ensure that the fold is in the correct form before leaving it. This
2152 variable specifies the number of blank lines to leave between the
2153 enclosing fold marks and the enclosed text.
2154
2155 If this value is nil or negative, no blank lines are added or removed
2156 inside the fold marks. A value of 0 (zero) is valid, meaning leave no
2157 blank lines.
2158
2159 See also `folding-tidy-inside'."
2160   :type  'boolean
2161   :group 'folding)
2162
2163 (make-variable-buffer-local 'folding-internal-margins)
2164
2165 (defvar folding-mode-string " Fld"
2166   "Buffer-local variable that hold the fold depth description.")
2167
2168 (set-default 'folding-mode-string " Fld")
2169
2170 ;; Sets `folding-mode-string' appropriately. This allows the Folding mode
2171 ;; description in the mode line to reflect the current fold depth.
2172
2173 (defconst folding-inside-string " "     ; was ' inside ',
2174   "Mode line addition to show 'inside' levels of fold.")
2175
2176 ;;;###autoload
2177 (defcustom folding-inside-mode-name "Fld"
2178   "*Mode line addition to show inside levels of 'fold' ."
2179   :type  'string
2180   :group 'folding)
2181
2182 (defcustom folding-check-folded-file-function
2183   'folding-check-folded
2184   "*Function that return t or nil after examining if the file is folded."
2185   :type  'function
2186   :group 'folding)
2187
2188 (defcustom folding-check-allow-folding-function
2189   'folding-check-if-folding-allowed
2190   "*Function that return t or nil after deciding if automatic folding."
2191   :type  'function
2192   :group 'folding)
2193
2194 ;;;###autoload
2195 (defcustom folding-mode-string "Fld"
2196   "*The minor mode string displayed when mode is on."
2197   :type  'string
2198   :group 'folding)
2199
2200 ;;;###autoload
2201 (defcustom folding-mode-hook-no-regexp "RMAIL"
2202   "*Regexp which disable automatic folding mode turn on for certain files."
2203   :type  'string
2204   :group 'folding)
2205
2206 ;;; ... ... ... ... ... ... ... ... ... ... ... ... ... .... &v-tables ...
2207
2208 (defcustom folding-behave-table
2209   '((close      folding-hide-current-entry)
2210     (open       folding-show-current-entry) ; Could also be `folding-shift-in'.
2211     (up         folding-shift-out)
2212     (other      folding-mouse-call-original))
2213   "*Table of of logical commands and their associated functions.
2214 If you want fold to behave like `folding-shift-in', when it 'open'
2215 a fold, you just change the function entry in this table.
2216
2217 Table form:
2218   '( (LOGICAL-ACTION  CMD) (..) ..)"
2219   :type '(repeat
2220           (symbol   :tag "logical action")
2221           (function :tag "callback"))
2222   :group 'folding)
2223
2224 ;;; ... ... ... ... ... ... ... ... ... ... ... ... ... ..... &v-marks ...
2225
2226 ;;;###autoload
2227 (defvar folding-mode-marks-alist nil
2228   "List of (major-mode . fold mark) default combinations to use.
2229 When Folding mode is started, the major mode is checked, and if there
2230 are fold marks for that major mode stored in `folding-mode-marks-alist',
2231 those marks are used by default. If none are found, the default values
2232 of \"{{{ \" and \"}}}\" are used.
2233
2234 Use function  `folding-add-to-marks-list' to add more fold marks. The function
2235 also explains the alist use in details.
2236
2237 Use function `folding-set-local-variables' if you change the current mode's
2238 folding marks during the session.")
2239
2240 ;;}}}
2241 ;;{{{ setup: private
2242
2243 ;;; ....................................................... &v-private ...
2244
2245 (defvar folding-narrow-placeholder nil
2246   "Internal. Mark where \"%n\" used to be in `mode-line-format'.
2247 Must be nil.")
2248
2249 (defvar folding-bottom-mark nil
2250   "Internal marker of the true bottom of a fold.")
2251
2252 (defvar folding-bottom-regexp nil
2253   "Internal. Regexp marking the bottom of a fold.")
2254
2255 (defvar folding-regexp nil
2256   "Internal. Regexp for hunting down the `folding-top-mark' even in comments.")
2257
2258 (defvar folding-secondary-top-mark nil
2259   "Internal. Additional stuff that can be inserted as part of a top marker.")
2260
2261 (defvar folding-top-mark nil
2262   "Internal. The actual string marking the top of a fold.")
2263
2264 (defvar folding-top-regexp nil
2265   "Internal.
2266 Regexp describing the string beginning a fold, possible with
2267 leading comment thingies and like that.")
2268
2269 (defvar folded-file nil
2270   "Enter folding mode when this file is loaded.
2271 (buffer local, use from a local variables list).")
2272
2273 (defvar folding-calling-original nil
2274   "Internal. Non-nil when original mouse binding is executed.")
2275
2276 (defvar folding-narrow-overlays nil
2277   "Internal. Keep the list of overlays.")
2278 (make-variable-buffer-local 'folding-narrow-overlays)
2279
2280 (defcustom folding-allow-overlays nil
2281   "*If non-nil use overlay code. If nil, then selective display is used.
2282 Note, that this code is highly experimental and will not most likely do what
2283 you expect. using value t will not change folding to use overlays
2284 completely. This variable was introduced to experiment with the overlay
2285 interface, but the work never finished and it is unlikely that it
2286 will continued any later time. Folding at present state is designed
2287 too highly for selective display to make the change worthwhile."
2288   :type 'boolean
2289   :group 'folding)
2290
2291 ;;}}}
2292 ;;{{{ Folding install
2293
2294 (defun folding-easy-menu-define ()
2295   "Define folding easy menu."
2296   (interactive)
2297   (easy-menu-define
2298     folding-mode-menu
2299     (if folding-xemacs-p
2300         nil
2301       (list folding-mode-map))
2302     "Folding menu"
2303     (list
2304      folding-mode-menu-name
2305      ["Enter Fold"                       folding-shift-in                t]
2306      ["Exit Fold"                        folding-shift-out               t]
2307      ["Show Fold"                        folding-show-current-entry      t]
2308      ["Hide Fold"                        folding-hide-current-entry      t]
2309      "----"
2310      ["Show Whole Buffer"                folding-open-buffer             t]
2311      ["Fold Whole Buffer"                folding-whole-buffer            t]
2312      ["Show subtree"                     folding-show-current-subtree    t]
2313      ["Hide subtree"                     folding-hide-current-subtree    t]
2314      ["Display fold name"                folding-display-name            t]
2315      "----"
2316      ["Move previous"                    folding-previous-visible-heading t]
2317      ["Move next"                        folding-next-visible-heading    t]
2318      ["Pick fold"                        folding-pick-move               t]
2319      ["Next action (context)"            folding-context-next-action     t]
2320      "----"
2321      ["Foldify region"                   folding-fold-region             t]
2322      ["Open or close folds in region"    folding-region-open-close       t]
2323      ["Open folds to top level"          folding-show-all                t]
2324      "----"
2325      ["Comment text in fold"             folding-comment-fold            t]
2326      ["Convert for printing(temp buffer)"
2327       folding-convert-buffer-for-printing t]
2328      ["Convert to major-mode folds"      folding-convert-to-major-folds  t]
2329      ["Move comments inside folds in region"
2330       folding-all-comment-blocks-in-region t]
2331      ["Delete fold marks in this fold"   folding-marks-kill              t]
2332      ["Insert folding URL reference"
2333       folding-insert-advertise-folding-mode t]
2334      "----"
2335      ["Toggle enter and exit mode"       folding-toggle-enter-exit       t]
2336      ["Toggle show and hide"             folding-toggle-show-hide        t]
2337      "----"
2338      ["Folding mode off"                 folding-mode t])))
2339
2340 (defun folding-install-keymaps ()
2341   "Install keymaps."
2342   (unless folding-mode-map
2343     (setq folding-mode-map          (make-sparse-keymap)))
2344   (unless folding-mode-prefix-map
2345     (setq folding-mode-prefix-map   (make-sparse-keymap)))
2346   (if (listp folding-default-keys-function)
2347       (mapcar 'funcall folding-default-keys-function)
2348     (funcall folding-default-keys-function))
2349   (funcall folding-default-mouse-keys-function)
2350   (folding-easy-menu-define)
2351   (define-key folding-mode-map
2352     folding-mode-prefix-key folding-mode-prefix-map)
2353   ;; Install the keymap into `minor-mode-map-alist'. The keymap will
2354   ;; be activated as soon as the variable `folding-mode' is set to
2355   ;; non-nil.
2356   (let ((elt (assq 'folding-mode minor-mode-map-alist)))
2357     ;;  Always remove old map before adding new definitions.
2358     (if elt
2359         (setq minor-mode-map-alist
2360               (delete elt minor-mode-map-alist)))
2361     (push (cons 'folding-mode folding-mode-map) minor-mode-map-alist))
2362   ;;  Update minor-mode-alist
2363   (or (assq 'folding-mode minor-mode-alist)
2364       (push '(folding-mode folding-mode-string) minor-mode-alist))
2365   ;;  Needed for XEmacs
2366   (or (fboundp 'buffer-disable-undo)
2367       (fset 'buffer-disable-undo (symbol-function 'buffer-flush-undo))))
2368
2369 (defun folding-uninstall-keymaps ()
2370   "Uninstall keymaps."
2371   (let ((elt (assq 'folding-mode minor-mode-map-alist)))
2372     (if elt
2373         (setq minor-mode-map-alist
2374               (delete elt minor-mode-map-alist)))
2375     (if (setq elt (assq 'folding-mode minor-mode-alist))
2376         (setq minor-mode-alist
2377               (delete elt minor-mode-alist)))
2378     (folding-uninstall-hooks)))
2379
2380 (defun folding-install (&optional uninstall)
2381   "Install or UNINSTALL folding."
2382   (interactive "P")
2383   (cond
2384    (uninstall
2385     (folding-uninstall-keymaps)
2386     (folding-uninstall-hooks))
2387    (t
2388     (folding-install-keymaps))))
2389
2390 (defun folding-uninstall ()
2391   "Uninstall folding."
2392   (interactive)
2393   (folding-install 'uninstall)
2394   ;; Unwrap all buffers.
2395   (dolist (buffer (buffer-list))
2396     (with-current-buffer buffer
2397       (goto-char (point-min))
2398       (when (or folding-mode
2399                 ;;  To be sure, check this at the same time
2400                 ;;  Somebody may have just done
2401                 ;;  (setq folding-mode nil), which is bad thing.
2402                 ;;  Setting variable won't restore the buffer.
2403                 (re-search-forward "{{{" nil t))
2404         (turn-off-folding-mode)))))
2405
2406 ;;}}}
2407 ;;{{{ code: misc
2408
2409 (defsubst folding-get-mode-marks (&optional mode)
2410   "Return fold markers for MODE. default is for current `major-mode'.
2411
2412 Return:
2413   \(beg-marker end-marker\)"
2414   (interactive)
2415   (let* (elt)
2416     (unless (setq elt (assq (or mode major-mode)
2417                             folding-mode-marks-alist))
2418       (error "Folding error: mode is not in `folding-mode-marks-alist'"))
2419     (list (nth 1 elt) (nth 2 elt) (nth 3 elt))))
2420
2421 (defun folding-region-has-folding-marks-p (beg end)
2422   "Check is there is fold mark in region BEG END."
2423   (save-excursion
2424     (goto-char beg)
2425     (when (memq (folding-mark-look-at) '(1 11))
2426       (goto-char end)
2427       (memq (folding-mark-look-at) '(end end-in)))))
2428
2429 ;;; - Thumb rule: because "{{{" if more meaningful, all returns values
2430 ;;;   are of type integerp if it is found.
2431 ;;;
2432 (defun folding-mark-look-at (&optional mode)
2433   "Check status of current line. Does it contain a fold mark?.
2434
2435 MODE
2436
2437  'move      move over fold mark
2438
2439 Return:
2440
2441   0 1       numberp, line has fold begin mark
2442             0 = closed, 1 = open,
2443             11 = open, we're inside fold, and this is top marker
2444
2445   'end      end mark
2446
2447   'end-in   end mark, inside fold, floor marker
2448
2449   nil       no fold marks .."
2450   (let* (case-fold-search
2451          (marks  (folding-get-mode-marks))
2452          (stack  folding-stack)
2453          (bm     (regexp-quote (nth 0 marks))) ;begin mark
2454          (em     (concat "^[ \t\n]*" (regexp-quote  (nth 1 marks))))
2455          (bm-re  (concat
2456                   (concat "^[ \t\n]*" bm)
2457                   (if (and nil
2458                            (string=
2459                             " " (substring (nth 0 marks)
2460                                            (length (nth 1 marks)))))
2461                       ;; Like "}}} *"
2462                       "*"
2463                     "")))
2464          ret
2465          point)
2466     (save-excursion
2467       (beginning-of-line)
2468       (cond
2469        ((looking-at bm-re)
2470         (setq point (point))
2471         (cond
2472          ((looking-at (concat "^[ \t\n]*" bm "[^\r\n]*\r")) ;; closed
2473           (setq ret 0))
2474          (t ;; open fold marker
2475           (goto-char (point-min))
2476           (cond
2477            ((and stack ;; we're inside fold
2478                  ;;  allow spaces
2479                  (looking-at (concat "[ \t\n]*" bm)))
2480             (setq ret 11))
2481            (t
2482             (setq ret 1))))))
2483        ((looking-at em)
2484         (setq point (point))
2485         ;; - The stack is a list if we've entered inside fold. There
2486         ;;   is no text after fold END mark
2487         ;; - At bol  ".*\n[^\n]*" doesn't work but "\n[^\n]*" at eol does??
2488         (cond
2489          ((progn
2490             (end-of-line)
2491             (or (and stack (eobp))      ;normal ending
2492                 (and stack             ;empty newlines only, no text ?
2493                      (not (looking-at "\n[^ \t\n]*")))))
2494           (setq ret 'end-in))
2495          (t                             ;all rest are newlines
2496           (setq ret 'end))))))
2497     (cond
2498      ((and mode point)
2499       (goto-char point)
2500       ;;  This call breaks if there is no marks on the point,
2501       ;;  because there is no parameter 'nil t' in call.
2502       ;;  --> there is error in this function if that happens.
2503       (beginning-of-line)
2504       (re-search-forward (concat bm "\\|" em))
2505       (backward-char 1)))
2506     ret))
2507
2508 (defsubst folding-mark-look-at-top-mark-p ()
2509   "Check if line contain folding top marker."
2510   (integerp (folding-mark-look-at)))
2511
2512 (defsubst folding-mark-look-at-bottom-mark-p ()
2513   "Check if line contain folding bottom marker."
2514   (symbolp (folding-mark-look-at)))
2515
2516 (defun folding-act (action &optional event)
2517   "Execute logical ACTION based on EVENT.
2518
2519 References:
2520   `folding-behave-table'"
2521   (let* ((elt (assoc action folding-behave-table)))
2522     (if elt
2523         (funcall (nth 1 elt) event)
2524       (error "Folding mode (folding-act): Unknown action %s" action))))
2525
2526 (defun folding-region-open-close (beg end &optional close)
2527   "Open all folds inside region BEG END. Close if optional CLOSE is non-nil."
2528   (interactive "r\nP")
2529   (let* ((func (if (null close)
2530                    'folding-show-current-entry
2531                  'folding-hide-current-entry))
2532          tmp)
2533     (save-excursion
2534       ;;   make sure the beg is first.
2535       (if (> beg end)                   ;swap order
2536           (setq  tmp beg  beg end   end tmp))
2537       (goto-char beg)
2538       (while (and
2539               ;;   the folding-show-current-entry/hide will move point
2540               ;;   to beg-of-line So we must move to the end of
2541               ;;   line to continue search.
2542               (if (and close
2543                        (eq 0 (folding-mark-look-at))) ;already closed ?
2544                   t
2545                 (funcall func)
2546                 (end-of-line)
2547                 t)
2548               (folding-next-visible-heading)
2549               (< (point) end))))))
2550
2551 (defun fold-marks-kill ()
2552   "If over fold, open fold and kill beginning and end fold marker.
2553 Return t ot nil if marks were removed."
2554   (interactive)
2555   (if (not (folding-mark-look-at))
2556       (when (interactive-p)
2557         (message "Folding: Cursor not over fold. Can't removed fold marks.")
2558         nil)
2559     (multiple-value-bind (beg end)
2560         (folding-show-current-entry)
2561       (let* ((kill-whole-line t))
2562         ;;  must be done in this order, because point moves after kill.
2563         (goto-char end)
2564         (beginning-of-line)
2565         (kill-line)
2566         (goto-char beg)
2567         (beginning-of-line)
2568         (kill-line)
2569         ;; Return status
2570         t))))
2571
2572 (defun folding-hide-current-subtree ()
2573   "Call `folding-show-current-subtree' with argument 'hide."
2574   (interactive)
2575   (folding-show-current-subtree 'hide))
2576
2577 (defun folding-show-current-subtree (&optional hide)
2578   "Show or HIDE all folds inside current fold.
2579 Point must be over beginning fold mark."
2580   (interactive "P")
2581   (let* ((stat  (folding-mark-look-at 'move))
2582          (beg   (point))
2583          end)
2584     (cond
2585      ((memq stat '(0 1 11))             ;It's BEG fold
2586       (when (eq 0 stat)                 ;it was closed
2587         (folding-show-current-entry)
2588         (goto-char beg))        ;folding-pick-move needs point at fold
2589       (save-excursion
2590         (if (folding-pick-move)
2591             (setq end (point))))
2592       (if (and beg end)
2593           (folding-region-open-close beg end hide)))
2594      (t
2595       (if (interactive-p)
2596           (message "point is not at fold beginning."))))))
2597
2598 (defun folding-display-name ()
2599   "Show current active fold name."
2600   (interactive)
2601   (let* ((pos    (folding-find-folding-mark))
2602          name)
2603     (when pos
2604       (save-excursion
2605         (goto-char pos)
2606         (if (looking-at ".*[{]+")       ;Drop "{" mark away.
2607             (setq pos (match-end 0)))
2608         (setq name (buffer-substring
2609                     pos
2610                     (progn
2611                       (end-of-line)
2612                       (point))))))
2613     (if name
2614         (message (format "fold:%s" name)))))
2615
2616 ;;}}}
2617 ;;{{{ code: events
2618
2619 (defun folding-event-posn (act event)
2620   "According to ACT read mouse EVENT struct and return data from it.
2621 Event must be simple click, no dragging.
2622
2623 ACT
2624   'mouse-point  return the 'mouse cursor' point
2625   'window       return window pointer
2626   'col-row      return list (col row)"
2627   (cond
2628    ((not folding-xemacs-p)
2629     ;; short Description of FSF mouse event
2630     ;;
2631     ;; EVENT : (mouse-3 (#<window 34 on *scratch*> 128 (20 . 104) -23723628))
2632     ;; event-start : (#<window 34 on *scratch*> 128 (20 . 104) -23723628))
2633     ;;                                          ^^^MP
2634     ;; mp = mouse point
2635     (let* ((el (funcall (symbol-function 'event-start) event)))
2636       (cond
2637        ((eq act 'mouse-point)
2638         (nth 1 el))                     ;is there macro for this ?
2639        ((eq act 'window)
2640         (funcall (symbol-function 'posn-window) el))
2641        ((eq act 'col-row)
2642         (funcall (symbol-function 'posn-col-row) el))
2643        (t
2644         (error "Unknown request" act)))))
2645
2646    (folding-xemacs-p
2647     (cond
2648      ((eq act 'mouse-point)
2649       (funcall (symbol-function 'event-point) event))
2650      ((eq act 'window)
2651       (funcall (symbol-function 'event-window) event))
2652      ;; Must be tested! (However, it's not used...)
2653      ((eq act 'col-row)
2654       (list (funcall (symbol-function 'event-x) event)
2655             (funcall (symbol-function 'event-y) event)))
2656      (t
2657       (error "Unknown request" act))))
2658    (t
2659     (error "This version of Emacs can't handle events."))))
2660
2661 (defmacro folding-interactive-spec-p ()
2662   "Preserve region during `interactive'.
2663 In XEmacs user could also set `zmacs-region-stays'."
2664   (if folding-xemacs-p
2665       ;;  preserve selected region
2666       `'(interactive "_p")
2667     `'(interactive "p")))
2668
2669 (defmacro folding-mouse-yank-at-p ()
2670   "Check if user use \"yank at mouse point\" feature.
2671
2672 Please see the variable `folding-mouse-yank-at-point'."
2673   'folding-mouse-yank-at-point)
2674
2675 (defun folding-mouse-point (&optional event)
2676   "Return mouse's working point. Optional EVENT is mouse click.
2677 When used on XEmacs, return nil if no character was under the mouse."
2678   (if (or (folding-mouse-yank-at-p)
2679           (null event))
2680       (point)
2681     (folding-event-posn 'mouse-point event)))
2682
2683 ;;}}}
2684
2685 ;;{{{ code: hook
2686
2687 (defun folding-is-hooked ()
2688   "Check if folding hooks are installed."
2689   (and (memq 'folding-mode-write-file write-file-hooks)
2690        (memq 'folding-mode-find-file  find-file-hooks)))
2691
2692 ;;;###autoload
2693 (defun folding-uninstall-hooks ()
2694   "Remove hooks set by folding."
2695   (turn-off-folding-mode)
2696   (remove-hook 'finder-mode-hook 'folding-mode)
2697   (remove-hook 'write-file-hooks 'folding-mode-write-file)
2698   (remove-hook 'find-file-hooks  'folding-mode-find-file))
2699
2700 ;;;###autoload
2701 (defun folding-install-hooks ()
2702   "Install folding hooks."
2703   (folding-mode-add-find-file-hook)
2704   (add-hook 'finder-mode-hook 'folding-mode)
2705   (or (memq 'folding-mode-write-file write-file-hooks)
2706       (add-hook 'write-file-hooks 'folding-mode-write-file 'end)))
2707
2708 ;;;###autoload
2709 (defun folding-keep-hooked ()
2710   "Make sure hooks are in their places."
2711   (unless (folding-is-hooked)
2712     (folding-uninstall-hooks)
2713     (folding-install-hooks)))
2714
2715 ;;}}}
2716 ;;{{{ code: Mouse handling
2717
2718 (defun folding-mouse-call-original (&optional event)
2719   "Execute original mouse function using mouse EVENT.
2720
2721 Do nothing if original function does not exist.
2722
2723 Does nothing when called by a function which has earlier been called
2724 by us.
2725
2726 Sets global:
2727   `folding-calling-original'"
2728   (interactive "@e") ;; Was "e"
2729   ;; Without the following test we could easily end up in a endless
2730   ;; loop in case we would call a function which would call us.
2731   ;;
2732   ;; (An easy constructed example is to bind the function
2733   ;; `folding-mouse-context-sensitive' to the same mouse button both in
2734   ;; `folding-mode-map' and in the global map.)
2735   (if folding-calling-original
2736       nil
2737     ;; `folding-calling-original' is global
2738     (setq folding-calling-original t)
2739     (unwind-protect
2740         (progn
2741           (or event
2742               (setq event last-input-event))
2743           (let (mouse-key)
2744             (cond
2745              ((not folding-xemacs-p)
2746               (setq mouse-key (make-vector 1 (car-safe event))))
2747              (folding-xemacs-p
2748               (setq mouse-key
2749                     (vector
2750                      (append
2751                       (event-modifiers event)
2752                       (list (intern
2753                              (format "button%d"
2754                                      (funcall
2755                                       (symbol-function 'event-button)
2756                                       event))))))))
2757              (t
2758               (error "This version of Emacs can't handle events.")))
2759             ;; Test string: http://www.csd.uu.se/~andersl
2760             ;;              andersl A T csd uu se
2761             ;; (I have `ark-goto-url' bound to the same key as
2762             ;; this function.)
2763             ;;
2764             ;; turn off folding, so that we can see the real
2765             ;; function behind it.
2766             ;;
2767             ;; We have to restore the current buffer, otherwise the
2768             ;; let* won't be able to restore the old value of
2769             ;; folding-mode. In my environment, I have bound a
2770             ;; function which starts mail when I click on an e-mail
2771             ;; address. When returning, the current buffer has
2772             ;; changed.
2773             (let* ((folding-mode nil)
2774                    (orig-buf (current-buffer))
2775                    (orig-func (key-binding mouse-key)))
2776               ;; call only if exist
2777               (when orig-func
2778                 ;; Check if the original function has arguments. If
2779                 ;; it does, call it with the event as argument.
2780                 (unwind-protect
2781                     (progn
2782                       (setq this-command orig-func)
2783                       (call-interactively orig-func))
2784 ;;; #untested, but included here for further reference
2785 ;;;                 (cond
2786 ;;;                  ((not (string-match "mouse" (symbol-name orig-func)))
2787 ;;;                   (call-interactively orig-func))
2788 ;;;                     ((string-match "^mouse" (symbol-name orig-func))
2789 ;;;                      (funcall orig-func event))
2790 ;;;                     (t
2791 ;;;                      ;;  Some other package's mouse command,
2792 ;;;                      ;;  should we do something special here for
2793 ;;;                      ;;  somebody?
2794 ;;;                      (funcall orig-func event)))
2795                   (set-buffer orig-buf))))))
2796       ;; This is always executed, even if the above generates an error.
2797       (setq folding-calling-original nil))))
2798
2799 (defun folding-mouse-context-sensitive (event)
2800   "Perform some operation depending on the context of the mouse pointer.
2801 EVENT is mouse event.
2802
2803 The variable `folding-behave-table' contains a mapping between contexts and
2804 operations to perform.
2805
2806 The following contexts can be handled (They are named after the
2807 natural operation to perform on them):
2808
2809     open   -   A folded fold.
2810     close  -   An open fold, which isn't the one current topmost one.
2811     up     -   The topmost visible fold.
2812     other  -   Anything else.
2813
2814 Note that the `pointer' can be either the buffer point, or the mouse
2815 pointer depending in the setting of the user option
2816 `folding-mouse-yank-at-point'."
2817   (interactive "e")
2818   (let* ( ;;  - Get mouse cursor point, or point
2819          (point (folding-mouse-point event))
2820          state)
2821     (if (null point)
2822         ;; The user didn't click on any text.
2823         (folding-act 'other event)
2824       (save-excursion
2825         (goto-char point)
2826         (setq state (folding-mark-look-at)))
2827       (cond
2828        ((eq state 0)
2829         (folding-act 'open event))
2830        ((eq state 1)
2831         (folding-act 'close event))
2832        ((eq state 11)
2833         (folding-act 'up event))
2834        ((eq 'end state)
2835         (folding-act 'close))
2836        ((eq state 'end-in)
2837         (folding-act 'up event))
2838        (t
2839         (folding-act 'other event))))))
2840
2841 ;;; FIXME: #not used, the pick move handles this too
2842 (defun folding-mouse-move (event)
2843   "Move down if sitting on fold mark using mouse EVENT.
2844
2845 Original function behind the mouse is called if no FOLD action wasn't
2846 taken."
2847   (interactive "e")
2848   (let* ( ;;  - Get mouse cursor point, or point
2849          (point (folding-mouse-point event))
2850          state)
2851     (save-excursion
2852       (goto-char point)
2853       (beginning-of-line)
2854       (setq state (folding-mark-look-at)))
2855     (cond
2856      ((not (null state))
2857       (goto-char point)
2858       (folding-next-visible-heading) t)
2859      (t
2860       (folding-mouse-call-original event)))))
2861
2862 (defun folding-mouse-pick-move (event)
2863   "Pick movement if sitting on beg/end fold mark using mouse EVENT.
2864 If mouse if at the `beginning-of-line' point, then always move up.
2865
2866 Original function behind the mouse is called if no FOLD action wasn't
2867 taken."
2868   (interactive "e")
2869   (let* ( ;;  - Get mouse cursor point, or point
2870          (point (folding-mouse-point event))
2871          state)
2872     (save-excursion
2873       (goto-char point)
2874       (setq state (folding-mark-look-at)))
2875     (cond
2876      ((not (null state))
2877       (goto-char point)
2878       (if (= point
2879              (save-excursion (beginning-of-line) (point)))
2880           (folding-previous-visible-heading)
2881         (folding-pick-move)))
2882      (t
2883       (folding-mouse-call-original event)))))
2884
2885 ;;}}}
2886 ;;{{{ code: engine
2887
2888 (defun folding-set-mode-line ()
2889   "Update modeline with fold level."
2890   (if (null folding-stack)
2891       (kill-local-variable 'folding-mode-string)
2892     (make-local-variable 'folding-mode-string)
2893     (setq folding-mode-string
2894           (if (eq 'folded (car folding-stack))
2895               (concat
2896                folding-inside-string "1" folding-inside-mode-name)
2897             (concat
2898              folding-inside-string
2899              (int-to-string (length folding-stack))
2900              folding-inside-mode-name)))))
2901
2902 (defun folding-clear-stack ()
2903   "Clear the fold stack, and release all the markers it refers to."
2904   (let ((stack folding-stack))
2905     (setq folding-stack nil)
2906     (while (and stack (not (eq 'folded (car stack))))
2907       (set-marker (car (car stack)) nil)
2908       (set-marker (cdr (car stack)) nil)
2909       (setq stack (cdr stack)))))
2910
2911 (defun folding-check-if-folding-allowed ()
2912   "Return non-nil when buffer allowed to be folded automatically.
2913 When buffer is loaded it may not be desirable to fold it immediately,
2914 because the file may be too large, or it may contain fold marks, that
2915 really are not _real_ folds. (Eg. RMAIL saved files may have the
2916 marks)
2917
2918 This function returns t, if it's okay to proceed checking the fold status
2919 of file. Returning nil means that folding should not touch this file.
2920
2921 The variable `folding-check-allow-folding-function' normally contains this
2922 function. Change the variable to use your own scheme."
2923
2924   (or (let ((file (get 'find-file-noselect 'folding)))
2925         ;;  When a file reference is "pushed" is a C-h v buffer that says:
2926         ;;  test is a Lisp function in `~/foo/tmp/test.el' A flag gets set
2927         ;;  (see adviced code) and we must not fold this buffer, because
2928         ;;  it will be immediately searched.
2929         (and file
2930              (not (string-match (regexp-quote file)
2931                                 (or buffer-file-name "")))))
2932       ;;  Do not fold these files
2933       (null (string-match folding-mode-hook-no-regexp (buffer-name)))))
2934
2935 (defun folding-mode-find-file ()
2936   "One of the funcs called whenever a `find-file' is successful.
2937 It checks to see if `folded-file' has been set as a buffer-local
2938 variable, and automatically starts Folding mode if it has.
2939
2940 This allows folded files to be automatically folded when opened.
2941
2942 To make this hook effective, the symbol `folding-mode-find-file-hook'
2943 should be placed at the end of `find-file-hooks'. If you have
2944 some other hook in the list, for example a hook to automatically
2945 uncompress or decrypt a buffer, it should go earlier on in the list.
2946
2947 See also `folding-mode-add-find-file-hook'."
2948   (let* ((check-fold folding-check-folded-file-function)
2949          (allow-fold folding-check-allow-folding-function))
2950     ;;  Turn mode on only if it's allowed
2951     (if (funcall allow-fold)
2952         (or (and (and check-fold (funcall check-fold))
2953                  (folding-mode 1))
2954             (and (assq 'folded-file (buffer-local-variables))
2955                  folded-file
2956                  (folding-mode 1)
2957                  (kill-local-variable 'folded-file)))
2958       ;; In all other cases, unfold buffer.
2959       (if folding-mode
2960           (folding-mode -1)))))
2961
2962 ;;;###autoload
2963 (defun folding-mode-add-find-file-hook ()
2964   "Append `folding-mode-find-file-hook' to the list `find-file-hooks'.
2965
2966 This has the effect that afterwards, when a folded file is visited, if
2967 appropriate Emacs local variable entries are recognized at the end of
2968 the file, Folding mode is started automatically.
2969
2970 If `inhibit-local-variables' is non-nil, this will not happen regardless
2971 of the setting of `find-file-hooks'.
2972
2973 To declare a file to be folded, put `folded-file: t' in the file's
2974 local variables. eg., at the end of a C source file, put:
2975
2976 /*
2977 Local variables:
2978 folded-file: t
2979 */
2980
2981 The local variables can be inside a fold."
2982   (interactive)
2983   (or (memq 'folding-mode-find-file find-file-hooks)
2984       (add-hook 'find-file-hooks 'folding-mode-find-file 'end)))
2985
2986 (defun folding-mode-write-file ()
2987   "Folded files must be controlled by folding before saving.
2988 This function turns on the folding mode if it is not activated.
2989 It prevents 'binary pollution' upon save."
2990   (let* ((check-func  folding-check-folded-file-function)
2991          (no-re      folding-mode-hook-no-regexp)
2992          (bn         (or (buffer-name) "")))
2993     (if (and (not       (string-match no-re bn))
2994              (boundp    'folding-mode)
2995              (null      folding-mode)
2996              (and check-func (funcall check-func)))
2997         (progn
2998           ;;  When folding mode is turned on it also 'folds' whole
2999           ;;  buffer... can't avoid that, since it's more important
3000           ;;  to save safely
3001           (folding-mode 1)))
3002     ;; hook returns nil, good habit
3003     nil))
3004
3005 (defun folding-check-folded ()
3006   "Function to determine if this file is in folded form."
3007   (let* ( ;;  Could use folding-top-regexp , folding-bottom-regexp ,
3008          ;;  folding-regexp But they are not available at load time.
3009          (folding-re1 "^.?.?.?{{{")
3010          (folding-re2 "[\r\n].*}}}"))
3011     (save-excursion
3012       (goto-char (point-min))
3013       ;;  If we found both, we assume file is folded
3014       (and (re-search-forward folding-re1 nil t)
3015            ;; if file is folded, there are \r's
3016            (search-forward "\r" nil t)
3017            (re-search-forward folding-re2 nil t)))))
3018
3019 ;;}}}
3020
3021 ;;{{{ code: Folding mode
3022
3023 (defun folding-font-lock-keywords (&optional mode)
3024   "Return folding font-lock keywords for MODE."
3025   ;;  Add support mode-by-mode basis. Check if mode is already
3026   ;;  handled from the property list.
3027   (multiple-value-bind (beg end)
3028       (folding-get-mode-marks (or mode major-mode))
3029     (setq beg (concat "^[ \t]*" (regexp-quote beg) "[^\r\n]+"))
3030     (setq end (concat "^[ \t]*" (regexp-quote end)))
3031     (list
3032      ;;  the `t' says to overwrite any previous highlight.
3033      ;;  => Needed because folding marks are in comments.
3034      (list beg 0 folding-font-lock-begin-mark  t)
3035      (list end 0 folding-font-lock-end-mark t))))
3036
3037 (defun folding-font-lock-support-instantiate (&optional mode)
3038   "Add fold marks with `font-lock-add-keywords'."
3039   (or mode
3040       (setq mode major-mode))
3041   ;;  Hide function from Byte Compiler.
3042   (let* ((function 'font-lock-add-keywords))
3043     (when (fboundp function)
3044       (funcall function
3045                mode
3046                (folding-font-lock-keywords mode))
3047       ;; In order to see new keywords font lock must be restarted.
3048       (dolist (buffer (buffer-list))
3049         (with-current-buffer buffer
3050           (when (and (eq major-mode mode)
3051                      (or font-lock-mode
3052                          ;;  Hide variable from byte compiler.
3053                          (let ((sym 'global-font-lock-mode))
3054                            (and (boundp sym)
3055                                 (symbol-value sym)))))
3056             ;; #todo: should we use font-lock-fontify-buffer instead?
3057             (font-lock-mode -1)
3058             (font-lock-mode 1)))))))
3059
3060 (defun folding-font-lock-support ()
3061   "Add font lock support."
3062   (let* ((list (get 'folding-mode 'font-lock)))
3063     (unless (memq major-mode list)
3064       ;;  Support added, update known list
3065       (push major-mode list)
3066       (put 'folding-mode 'font-lock list)
3067       (folding-font-lock-support-instantiate major-mode))))
3068
3069 (defun folding-set-local-variables ()
3070   "Set local fold mark variables.
3071 If you're going to change the beginning and end mark in
3072 `folding-mode-marks-alist'; you must call this function."
3073   (set (make-local-variable 'folding-stack) nil)
3074   (make-local-variable 'folding-top-mark)
3075   (make-local-variable 'folding-secondary-top-mark)
3076   (make-local-variable 'folding-top-regexp)
3077   (make-local-variable 'folding-bottom-mark)
3078   (make-local-variable 'folding-bottom-regexp)
3079   (make-local-variable 'folding-regexp)
3080   (or (and (boundp 'folding-top-regexp)
3081            folding-top-regexp
3082            (boundp 'folding-bottom-regexp)
3083            folding-bottom-regexp)
3084       (let ((folding-marks (assq major-mode
3085                                  folding-mode-marks-alist)))
3086         (if folding-marks
3087             (setq folding-marks (cdr folding-marks))
3088           (setq folding-marks '("{{{" "}}}")))
3089         (apply 'folding-set-marks folding-marks))))
3090
3091 ;;;###autoload
3092 (defun turn-off-folding-mode ()
3093   "Turn off folding."
3094   (folding-mode -1))
3095
3096 ;;;###autoload
3097 (defun turn-on-folding-mode ()
3098   "Turn on folding."
3099   (folding-mode 1))
3100
3101 ;;;###autoload
3102 (defun folding-mode (&optional arg inter)
3103   "A folding-editor-like minor mode. ARG INTER.
3104
3105 These are the basic commands that Folding mode provides:
3106
3107 \\{folding-mode-map}
3108
3109 Keys starting with `folding-mode-prefix-key'
3110
3111 \\{folding-mode-prefix-map}
3112
3113      folding-convert-buffer-for-printing:
3114      `\\[folding-convert-buffer-for-printing]'
3115      Makes a ready-to-print, formatted, unfolded copy in another buffer.
3116
3117      Read the documentation for the above functions for more information.
3118
3119 Overview
3120
3121     Folds are a way of hierarchically organizing the text in a file, so
3122     that the text can be viewed and edited at different levels. It is
3123     similar to Outline mode in that parts of the text can be hidden from
3124     view. A fold is a region of text, surrounded by special \"fold marks\",
3125     which act like brackets, grouping the text. Fold mark pairs can be
3126     nested, and they can have titles. When a fold is folded, the text is
3127     hidden from view, except for the first line, which acts like a title
3128     for the fold.
3129
3130     Folding mode is a minor mode, designed to cooperate with many other
3131     major modes, so that many types of text can be folded while they are
3132     being edited (eg., plain text, program source code, Texinfo, etc.).
3133
3134 Folding-mode function
3135
3136     If Folding mode is not called interactively (`(interactive-p)' is nil),
3137     and it is called with two or less arguments, all of which are nil, then
3138     the point will not be altered if `folding-folding-on-startup' is set
3139     and `folding-whole-buffer' is called. This is generally not a good
3140     thing, as it can leave the point inside a hidden region of a fold, but
3141     it is required if the local variables set \"mode: folding\" when the
3142     file is first read (see `hack-local-variables').
3143
3144     Not that you should ever want to, but to call Folding mode from a
3145     program with the default behavior (toggling the mode), call it with
3146     something like `(folding-mode nil t)'.
3147
3148 Fold marks
3149
3150     For most types of folded file, lines representing folds have \"{{{\"
3151     near the beginning. To enter a fold, move the point to the folded line
3152     and type `\\[folding-shift-in]'. You should no longer be able to see
3153     the rest of the file, just the contents of the fold, which you couldn't
3154     see before. You can use `\\[folding-shift-out]' to leave a fold, and
3155     you can enter and exit folds to move around the structure of the file.
3156
3157     All of the text is present in a folded file all of the time. It is just
3158     hidden. Folded text shows up as a line (the top fold mark) with \"...\"
3159     at the end. If you are in a fold, the mode line displays \"inside n
3160     folds Narrow\", and because the buffer is narrowed you can't see outside
3161     of the current fold's text.
3162
3163     By arranging sections of a large file in folds, and maybe subsections
3164     in sub-folds, you can move around a file quickly and easily, and only
3165     have to scroll through a couple of pages at a time. If you pick the
3166     titles for the folds carefully, they can be a useful form of
3167     documentation, and make moving though the file a lot easier. In
3168     general, searching through a folded file for a particular item is much
3169     easier than without folds.
3170
3171 Managing folds
3172
3173     To make a new fold, set the mark at one end of the text you want in the
3174     new fold, and move the point to the other end. Then type
3175     `\\[folding-fold-region]'. The text you selected will be made into a
3176     fold, and the fold will be entered. If you just want a new, empty fold,
3177     set the mark where you want the fold, and then create a new fold there
3178     without moving the point. Don't worry if the point is in the middle of
3179     a line of text, `folding-fold-region' will not break text in the middle
3180     of a line. After making a fold, the fold is entered and the point is
3181     positioned ready to enter a title for the fold. Do not delete the fold
3182     marks, which are usually something like \"{{{\" and \"}}}\". There may
3183     also be a bit of fold mark which goes after the fold title.
3184
3185     If the fold markers get messed up, or you just want to see the whole
3186     unfolded file, use `\\[folding-open-buffer]' to unfolded the whole
3187     file, so you can see all the text and all the marks. This is useful for
3188     checking/correcting unbalanced fold markers, and for searching for
3189     things. Use `\\[folding-whole-file]' to fold the buffer again.
3190
3191     `folding-shift-out' will attempt to tidy the current fold just before
3192     exiting it. It will remove any extra blank lines at the top and bottom,
3193     \(outside the fold marks). It will then ensure that fold marks exists,
3194     and if they are not, will add them (after asking). Finally, the number
3195     of blank lines between the fold marks and the contents of the fold is
3196     set to 1 (by default).
3197
3198 Folding package customizations
3199
3200     If the fold marks are not set on entry to Folding mode, they are set to
3201     a default for current major mode, as defined by
3202     `folding-mode-marks-alist' or to \"{{{ \" and \"}}}\" if none are
3203     specified.
3204
3205     To bind different commands to keys in Folding mode, set the bindings in
3206     the keymap `folding-mode-map'.
3207
3208     The hooks `folding-mode-hook' and `<major-mode-name>-folding-hook' are
3209     called before folding the buffer and applying the key bindings in
3210     `folding-mode-map'. This is a good hook to set extra or different key
3211     bindings in `folding-mode-map'. Note that key bindings in
3212     `folding-mode-map' are only examined just after calling these hooks;
3213     new bindings in those maps only take effect when Folding mode is being
3214     started. The hook `folding-load-hook' is called when Folding mode is
3215     loaded into Emacs.
3216
3217 Mouse behavior
3218
3219     If you want folding to detect point of actual mouse click, please see
3220     variable `folding-mouse-yank-at-p'.
3221
3222     To customise the mouse actions, look at `folding-behave-table'."
3223   (interactive)
3224
3225   (let ((new-folding-mode
3226          (if (not arg)
3227              (not folding-mode)
3228            (> (prefix-numeric-value arg) 0))))
3229     (or (eq new-folding-mode
3230             folding-mode)
3231         (if folding-mode
3232             (progn
3233               ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ progn ^^^
3234               ;; turn off folding
3235               (if (null (folding-use-overlays-p))
3236                   (setq selective-display nil))
3237               (folding-clear-stack)
3238               (folding-narrow-to-region nil nil)
3239               (folding-subst-regions (list 1 (point-max)) ?\r ?\n)
3240
3241               ;; Restore "%n" (Narrow) in the mode line
3242               (setq mode-line-format
3243                     (mapcar
3244                      (function
3245                       (lambda (item)
3246                         (if (equal item 'folding-narrow-placeholder)
3247                             "%n" item)))
3248                      mode-line-format)))
3249           ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ else ^^^
3250           (cond
3251            ((folding-use-overlays-p)
3252             ;;  This may be Emacs specific; how about XEmacs?
3253             ;;
3254             ;; make line-move-ignore-invisible buffer local, matches
3255             ;; outline.el, and the 21 pre-release gets upset if this is
3256             ;; defined globally in shell buffer...
3257             (make-local-variable 'line-move-ignore-invisible)
3258             (setq  line-move-ignore-invisible t
3259                    buffer-invisibility-spec   '((t . t))))
3260            (t
3261             (setq selective-display t)
3262             (setq selective-display-ellipses t)))
3263           (unless (assq 'folding-mode minor-mode-alist)
3264             ;;  User has not run folding-install or he did call
3265             ;;  folding-uninstall which completely wiped package out.
3266             ;;  => anyway now he calls us, so be there for him
3267             (folding-install))
3268           (folding-keep-hooked)         ;set hooks if not there
3269           (widen)
3270           (setq folding-narrow-overlays nil)
3271           (folding-set-local-variables)
3272           (folding-font-lock-support)
3273           (unwind-protect
3274               (let ((hook-symbol (intern-soft
3275                                   (concat
3276                                    (symbol-name major-mode)
3277                                    "-folding-hook"))))
3278                 (run-hooks 'folding-mode-hook)
3279                 (and hook-symbol
3280                      (run-hooks hook-symbol)))
3281             (folding-set-mode-line))
3282           (and folding-folding-on-startup
3283                (if (or (interactive-p)
3284                        arg
3285                        inter)
3286                    (folding-whole-buffer)
3287                  (save-excursion
3288                    (folding-whole-buffer))))
3289           (folding-narrow-to-region nil nil t)
3290           ;; Remove "%n" (Narrow) from the mode line
3291           (setq mode-line-format
3292                 (mapcar
3293                  (function
3294                   (lambda (item)
3295                     (if (equal item "%n")
3296                         'folding-narrow-placeholder item)))
3297                  mode-line-format))))
3298     (setq folding-mode new-folding-mode)
3299     (if folding-mode
3300         (easy-menu-add folding-mode-menu)
3301       (easy-menu-remove folding-mode-menu))))
3302
3303 ;;}}}
3304 ;;{{{ code: setting fold marks
3305
3306 ;; You think those "\\(\\)" pairs are peculiar?  Me too. Emacs regexp
3307 ;; stuff has a bug; sometimes "\\(.*\\)" fails when ".*" succeeds, but
3308 ;; only in a folded file!  Strange bug!  Must check it out sometime.
3309
3310 (defun folding-set-marks (top bottom &optional secondary)
3311   "Set the folding top and bottom mark for the current buffer.
3312
3313 Input:
3314
3315   TOP           The topmost fold mark. Comment start + fold begin string.
3316   BOTTOM        The bottom fold mark Comment end + fold end string.
3317   SECONDARY     Usually the comment end indicator for the mode. This
3318                 is inserted by `folding-fold-region' after the fold top mark,
3319                 and is presumed to be put after the title of the fold.
3320
3321 Example:
3322
3323    html-mode:
3324
3325       top: \"<!-- [[[ \"
3326       bot: \"<!-- ]]] -->\"
3327       sec: \" -->\"
3328
3329 Notice that the top marker needs to be closed with SECONDARY comment end string.
3330
3331 Various regular expressions are set with this function, so don't set the
3332 mark variables directly."
3333   (set (make-local-variable 'folding-top-mark)
3334        top)
3335   (set (make-local-variable 'folding-bottom-mark)
3336        bottom)
3337   (set (make-local-variable 'folding-secondary-top-mark)
3338        secondary)
3339   (set (make-local-variable 'folding-top-regexp)
3340        (concat "\\(^\\|\r+\\)[ \t]*"
3341                (regexp-quote folding-top-mark)))
3342   (set (make-local-variable 'folding-bottom-regexp)
3343        (concat "\\(^\\|\r+\\)[ \t]*"
3344                (regexp-quote folding-bottom-mark)))
3345   (set (make-local-variable 'folding-regexp)
3346        (concat "\\(^\\|\r\\)\\([ \t]*\\)\\(\\("
3347                (regexp-quote folding-top-mark)
3348                "\\)\\|\\("
3349                (regexp-quote folding-bottom-mark)
3350                "[ \t]*\\(\\)\\($\\|\r\\)\\)\\)")))
3351
3352 ;;}}}
3353 ;;{{{ code: movement
3354
3355 (defun folding-next-visible-heading (&optional direction)
3356   "Move up/down fold headers.
3357 Backward if DIRECTION is non-nil returns nil if not moved = no next marker."
3358   (interactive)
3359   (let* ((begin-mark (nth 0 (folding-get-mode-marks)))
3360          case-fold-search)
3361     (if direction
3362         (re-search-backward (concat "^" (regexp-quote begin-mark)) nil t)
3363       (re-search-forward  (concat "^" (regexp-quote begin-mark)) nil t))))
3364
3365 (defun folding-previous-visible-heading ()
3366   "Move upward fold headers."
3367   (interactive)
3368   (beginning-of-line)
3369   (folding-next-visible-heading 'backward))
3370
3371 (defun folding-find-folding-mark (&optional end-fold)
3372   "Search backward to find beginning fold. Skips subfolds.
3373 Optionally searches forward to find END-FOLD mark.
3374
3375 Return:
3376
3377   nil
3378   point     position of fold mark"
3379   (let* (case-fold-search
3380          (elt   (folding-get-mode-marks))
3381          (bm    (regexp-quote (nth 0 elt))) ; markers defined for mode
3382          (em    (regexp-quote (nth 1 elt))) ; markers defined for mode
3383          (re    (concat "^" bm "\\|^" em))
3384          (count 0)
3385          stat
3386          moved)
3387     (save-excursion
3388       (cond
3389        (end-fold
3390         (folding-end-of-line)
3391         ;; We must skip over inner folds
3392         (while (and (null moved)
3393                     (re-search-forward re nil t))
3394           (setq stat (folding-mark-look-at))
3395           (cond
3396            ((symbolp stat)
3397             (setq count (1- count))
3398             (if (< count 0)           ;0 or less means no middle folds
3399                 (setq moved t)))
3400            ((memq stat '(1 11))         ;BEG fold
3401             (setq count (1+ count)))))  ;; end while
3402         (when moved
3403           (forward-char -3)
3404           (setq moved (point))))
3405        (t
3406         (while (and (null moved)
3407                     (re-search-backward  re nil t))
3408           (setq stat (folding-mark-look-at))
3409           (cond
3410            ((memq stat '(1 11))
3411             (setq count (1- count))
3412             (if (< count 0)           ;0 or less means no middle folds
3413                 (setq moved (point))))
3414            ((symbolp stat)
3415             (setq count (1+ count)))))
3416         (when moved                     ;What's the result
3417           (forward-char 3)
3418           (setq moved (point))))))
3419     moved))
3420
3421 (defun folding-pick-move ()
3422   "Pick the logical movement on fold mark.
3423 If at the end of fold, then move to the beginning and vice versa.
3424
3425 If placed over closed fold moves to the next fold. When no next
3426 folds are visible, stops moving.
3427
3428 Return:
3429  t      if moved"
3430   (interactive)
3431   (let* (case-fold-search
3432          (elt   (folding-get-mode-marks))
3433          (bm    (nth 0 elt))            ; markers defined for mode
3434          (stat  (folding-mark-look-at))
3435          moved)
3436     (cond
3437      ((eq 0 stat)                       ;closed fold
3438       (when (re-search-forward  (concat "^" (regexp-quote bm)) nil t)
3439         (setq moved t)
3440         (forward-char 3)))
3441      ((symbolp stat)                    ;End fold
3442       (setq moved (folding-find-folding-mark)))
3443      ((integerp stat)                   ;Beg fold
3444       (setq moved (folding-find-folding-mark 'end-fold))))
3445     (if (integerp moved)
3446         (goto-char moved))
3447     moved))
3448
3449 ;;; Idea by Scott Evans <gse A T antisleep com>
3450 (defun folding-context-next-action ()
3451   "Take next action according to point and context.
3452 If point is at:
3453
3454   Begin Fold  :  toggle open - close
3455   End Fold    :  close
3456   inside      :  fold current level."
3457   (interactive)
3458   (let ((state (folding-mark-look-at)))
3459     (cond
3460      ((eq state 0)
3461       (folding-act 'open))
3462      ((eq state 1)
3463       (folding-act 'close))
3464      ((eq state 11)
3465       (folding-act 'up))
3466      ((eq 'end state)
3467       (folding-act 'close))
3468      ((eq state 'end-in)
3469       (folding-act 'up))
3470      (t
3471       (folding-act 'other)))))
3472
3473 (defun folding-forward-char-1 (&optional arg)
3474   "See `folding-forward-char-1' for ARG."
3475   (if (eq arg 1)
3476       ;; Do it a faster way for arg = 1.
3477       (if (eq (following-char) ?\r)
3478           (let ((saved (point))
3479                 (inhibit-quit t))
3480             (end-of-line)
3481             (if (not (eobp))
3482                 (forward-char)
3483               (goto-char saved)
3484               (error "End of buffer")))
3485         ;; `forward-char' here will do its own error if (eobp).
3486         (forward-char))
3487     (if (> 0 (or arg (setq arg 1)))
3488         (folding-backward-char (- arg))
3489       (let (goal saved)
3490         (while (< 0 arg)
3491           (skip-chars-forward "^\r" (setq goal (+ (point) arg)))
3492           (if (eq goal (point))
3493               (setq arg 0)
3494             (if (eobp)
3495                 (error "End of buffer")
3496               (setq arg (- goal 1 (point))
3497                     saved (point))
3498               (let ((inhibit-quit t))
3499                 (end-of-line)
3500                 (if (not (eobp))
3501                     (forward-char)
3502                   (goto-char saved)
3503                   (error "End of buffer"))))))))))
3504
3505 (defmacro folding-forward-char-macro ()
3506   `(defun folding-forward-char (&optional arg)
3507      "Move point right ARG characters, skipping hidden folded regions.
3508 Moves left if ARG is negative. On reaching end of buffer, stop and
3509 signal error."
3510      ,(folding-interactive-spec-p)
3511      ;; (folding-preserve-active-region)
3512      (folding-forward-char-1 arg)))
3513
3514 (folding-forward-char-macro)
3515
3516 (defun folding-backward-char-1 (&optional arg)
3517   "See `folding-backward-char-1' for ARG."
3518   (if (eq arg 1)
3519       ;; Do it a faster way for arg = 1.
3520       ;; Catch the case where we are in a hidden region, and bump into a \r.
3521       (if (or (eq (preceding-char) ?\n)
3522               (eq (preceding-char) ?\r))
3523           (let ((pos (1- (point)))
3524                 (inhibit-quit t))
3525             (forward-char -1)
3526             (beginning-of-line)
3527             (skip-chars-forward "^\r" pos))
3528         (forward-char -1))
3529     (if (> 0 (or arg (setq arg 1)))
3530         (folding-forward-char (- arg))
3531       (let (goal)
3532         (while (< 0 arg)
3533           (skip-chars-backward "^\r\n" (max (point-min)
3534                                             (setq goal (- (point) arg))))
3535           (if (eq goal (point))
3536               (setq arg 0)
3537             (if (bobp)
3538                 (error "Beginning of buffer")
3539               (setq arg (- (point) 1 goal)
3540                     goal (point))
3541               (let ((inhibit-quit t))
3542                 (forward-char -1)
3543                 (beginning-of-line)
3544                 (skip-chars-forward "^\r" goal)))))))))
3545
3546 (defmacro folding-backward-char-macro ()
3547   `(defun folding-backward-char (&optional arg)
3548      "Move point right ARG characters, skipping hidden folded regions.
3549 Moves left if ARG is negative. On reaching end of buffer, stop and
3550 signal error."
3551      ,(folding-interactive-spec-p)
3552      ;; (folding-preserve-active-region)
3553      (folding-backward-char-1 arg)))
3554
3555 (folding-backward-char-macro)
3556
3557 (defmacro folding-end-of-line-macro ()
3558   `(defun folding-end-of-line (&optional arg)
3559      "Move point to end of current line, but before hidden folded region.
3560 ARG is line count.
3561
3562 Has the same behavior as `end-of-line', except that if the current line
3563 ends with some hidden folded text (represented by an ellipsis), the
3564 point is positioned just before it. This prevents the point from being
3565 placed inside the folded text, which is not normally useful."
3566      ,(folding-interactive-spec-p)
3567      ;;(interactive "p")
3568      ;; (folding-preserve-active-region)
3569      (if (or (eq arg 1)
3570              (not arg))
3571          (beginning-of-line)
3572        ;; `forward-line' also moves point to beginning of line.
3573        (forward-line (1- arg)))
3574      (skip-chars-forward "^\r\n")))
3575
3576 (folding-end-of-line-macro)
3577
3578 (defun folding-skip-ellipsis-backward ()
3579   "Move the point backwards out of folded text.
3580
3581 If the point is inside a folded region, the cursor is displayed at the
3582 end of the ellipsis representing the folded part. This function checks
3583 to see if this is the case, and if so, moves the point backwards until
3584 it is just outside the hidden region, and just before the ellipsis.
3585
3586 Returns t if the point was moved, nil otherwise."
3587   (interactive)
3588   (let ((pos (point))
3589         result)
3590     (save-excursion
3591       (beginning-of-line)
3592       (skip-chars-forward "^\r" pos)
3593       (or (eq pos (point))
3594           (setq pos (point)
3595                 result t)))
3596     (goto-char pos)
3597     result))
3598
3599 ;;}}}
3600
3601 ;;{{{ code: Moving in and out of folds
3602
3603 ;;{{{ folding-shift-in
3604
3605 (defun folding-shift-in (&optional noerror)
3606   "Open and enter the fold at or around the point.
3607
3608 Enters the fold that the point is inside, wherever the point is inside
3609 the fold, provided it is a valid fold with balanced top and bottom
3610 marks. Returns nil if the fold entered contains no sub-folds, t
3611 otherwise. If an optional argument NOERROR is non-nil, returns nil if
3612 there are no folds to enter, instead of causing an error.
3613
3614 If the point is inside a folded, hidden region (as represented by an
3615 ellipsis), the position of the point in the buffer is preserved, and as
3616 many folds as necessary are entered to make the surrounding text
3617 visible. This is useful after some commands eg., search commands."
3618   (interactive)
3619   (labels
3620       ((open-fold nil
3621                   (let ((data (folding-show-current-entry noerror t)))
3622                     (and data
3623                          (progn
3624                            (when folding-narrow-by-default
3625                              (setq folding-stack
3626                                    (if folding-stack
3627                                        (cons (cons (point-min-marker) (point-max-marker))
3628                                              folding-stack)
3629                                      '(folded)))
3630                              (folding-set-mode-line))
3631                            (folding-narrow-to-region (car data) (nth 1 data)))))))
3632     (let ((goal (point)))
3633       (while (folding-skip-ellipsis-backward)
3634         (beginning-of-line)
3635         (open-fold)
3636         (goto-char goal))
3637       (when (not folding-narrow-by-default)
3638         (widen)))))
3639
3640 ;;}}}
3641 ;;{{{ folding-shift-out
3642
3643 (defun folding-shift-out (&optional event)
3644   "Exits the current fold with EVENT."
3645   (interactive)
3646   (if folding-stack
3647       (progn
3648         (folding-tidy-inside)
3649         (cond
3650          ((folding-use-overlays-p)
3651           (folding-subst-regions
3652            (list (overlay-end (car folding-narrow-overlays))
3653                  (overlay-start (cdr folding-narrow-overlays))) ?\n ?\r)
3654           ;; So point is correct in other windows.
3655           (goto-char (overlay-end (car folding-narrow-overlays))))
3656          (t
3657           (folding-subst-regions (list (point-min) (point-max)) ?\n ?\r)
3658           ;; So point is correct in other window
3659           (goto-char (point-min))))
3660
3661         (if (eq (car folding-stack) 'folded)
3662             (folding-narrow-to-region nil nil t)
3663           (folding-narrow-to-region (marker-position (car (car folding-stack)))
3664                                     (marker-position (cdr (car folding-stack))) t))
3665         (and (consp (car folding-stack))
3666              (set-marker (car (car folding-stack)) nil)
3667              (set-marker (cdr (car folding-stack)) nil))
3668         (setq folding-stack (cdr folding-stack)))
3669     (error "Outside all folds"))
3670   (folding-set-mode-line))
3671
3672 ;;}}}
3673 ;;{{{ folding-show-current-entry
3674
3675 (defun folding-show-current-entry (&optional event noerror noskip)
3676   "Opens the fold that the point is on, but does not enter it.
3677 EVENT and optional arg NOERROR means don't signal an error if there is
3678 no fold, just return nil. NOSKIP means don't jump out of a hidden
3679 region first.
3680
3681 Returns ((START END SUBFOLDS-P). START and END indicate the extents of
3682 the fold that was shown. If SUBFOLDS-P is non-nil, the fold contains
3683 subfolds."
3684   (interactive)
3685   (or noskip
3686       (folding-skip-ellipsis-backward))
3687   (let ((point (point))
3688         backward forward start end subfolds-not-p)
3689     (unwind-protect
3690         (or (and (integerp
3691                   (car-safe (setq backward (folding-skip-folds t))))
3692                  (integerp
3693                   (car-safe (setq forward (folding-skip-folds nil))))
3694                  (progn
3695                    (goto-char (car forward))
3696                    (skip-chars-forward "^\r\n")
3697                    (setq end (point))
3698                    (skip-chars-forward "\r\n")
3699                    (not (and folding-stack (eobp))))
3700                  (progn
3701                    (goto-char (car backward))
3702                    (skip-chars-backward "^\r\n")
3703                    (setq start (point))
3704                    (skip-chars-backward "\r\n")
3705                    (not (and folding-stack (bobp))))
3706                  (progn
3707                    (setq point start)
3708                    ;; Avoid holding the list through a GC.
3709                    (setq subfolds-not-p
3710                          (not (or (cdr backward)
3711                                   (cdr forward))))
3712                    (folding-subst-regions
3713                     (append backward (nreverse forward))
3714                     ?\r ?\n)
3715                    (list start end (not subfolds-not-p))))
3716             (if noerror
3717                 nil
3718               (error "Not on a fold")))
3719       (goto-char point))))
3720
3721 ;;}}}
3722 ;;{{{ folding-hide-current-entry
3723
3724 (defun folding-toggle-enter-exit ()
3725   "Run folding-shift-in or folding-shift-out depending on current line's contents."
3726   (interactive)
3727   (beginning-of-line)
3728   (let ((current-line-mark (folding-mark-look-at)))
3729     (if (and (numberp current-line-mark)
3730              (= current-line-mark 0))
3731         (folding-shift-in)
3732       (folding-shift-out))))
3733
3734 (defun folding-toggle-show-hide ()
3735   "Run folding-show-current-entry or folding-hide-current-entry depending on current line's contents."
3736   (interactive)
3737   (beginning-of-line)
3738   (let ((current-line-mark (folding-mark-look-at)))
3739     (if (and (numberp current-line-mark)
3740              (= current-line-mark 0))
3741         (folding-show-current-entry)
3742       (folding-hide-current-entry))))
3743
3744 (defun folding-hide-current-entry (&optional event)
3745   "Close the fold around the point using EVENT.
3746 Undo effect of `folding-show-current-entry'."
3747   (interactive)
3748   (folding-skip-ellipsis-backward)
3749   (let (start end)
3750     (if (and (integerp (setq start (car-safe (folding-skip-folds t))))
3751              (integerp (setq end (car-safe (folding-skip-folds nil)))))
3752         (if (and folding-stack
3753                  (or (eq start (point-min))
3754                      (eq end (point-max))))
3755             ;;(error "Cannot hide current fold")
3756             (folding-shift-out)
3757           (goto-char start)
3758           (skip-chars-backward "^\r\n")
3759           (folding-subst-regions (list start end) ?\n ?\r))
3760       (error "Not on a fold"))))
3761
3762 ;;}}}
3763 ;;{{{ folding-show-all
3764
3765 (defun folding-show-all ()
3766   "Exits all folds, to the top level."
3767   (interactive)
3768   (while folding-stack
3769     (folding-shift-out)))
3770
3771 ;;}}}
3772 ;;{{{ folding-goto-line
3773
3774 (defun folding-goto-line (line)
3775   "Go to LINE, entering as many folds as possible."
3776   (interactive "NGoto line: ")
3777   (folding-show-all)
3778   (goto-char 1)
3779   (and (< 1 line)
3780        (re-search-forward "[\n\C-m]" nil 0 (1- line)))
3781   (let ((goal (point)))
3782     (while (prog2 (beginning-of-line)
3783                (folding-shift-in t)
3784              (goto-char goal))))
3785   (folding-narrow-to-region
3786    (and folding-narrow-by-default (point-min))
3787    (point-max) t))
3788
3789 ;;}}}
3790
3791 ;;}}}
3792 ;;{{{ code: Searching for fold boundaries
3793
3794 ;;{{{ folding-skip-folds
3795
3796 (defun folding-skip-folds (backward &optional outside)
3797   "Skips forward through the buffer (backward if BACKWARD is non-nil)
3798 until it finds a closing fold mark or the end of the buffer. The
3799 point is not moved. Jumps over balanced folding-mark pairs on the way.
3800 Returns t if the end of buffer was found in an unmatched folding-mark
3801 pair, otherwise a list.
3802
3803 If the point is actually on an fold start mark, the mark is ignored;
3804 if it is on an end mark, the mark is noted. This decision is
3805 reversed if BACKWARD is non-nil. If optional OUTSIDE is non-nil and
3806 BACKWARD is nil, either mark is noted.
3807
3808 The first element of the list is a position in the end of the closing
3809 fold mark if one was found, or nil. It is followed by (END START)
3810 pairs (flattened, not a list of pairs). The pairs indicating the
3811 positions of folds skipped over; they are positions in the fold
3812 marks, not necessarily at the ends of the fold marks. They are in
3813 the opposite order to that in which they were skipped. The point is
3814 left in a meaningless place. If going backwards, the pairs are
3815 \(START END) pairs, as the fold marks are scanned in the opposite
3816 order.
3817
3818 Works by maintaining the position of the top and bottom marks found
3819 so far. They are found separately using a normal string search for
3820 the fixed part of a fold mark (because it is faster than a regexp
3821 search if the string does not occur often outside of fold marks),
3822 checking that it really is a proper fold mark, then considering the
3823 earliest one found. The position of the other (if found) is
3824 maintained to avoid an unnecessary search at the next iteration."
3825   (let ((first-mark (if backward folding-bottom-mark folding-top-mark))
3826         (last-mark  (if backward folding-top-mark    folding-bottom-mark))
3827         (top-re     folding-top-regexp)
3828         (depth 0)
3829         pairs point
3830         temp
3831         start
3832         first
3833         last
3834         case-fold-search)
3835     ;; Ignore trailing space?
3836     (when nil
3837       (when (and (stringp first-mark)
3838                  (string-match "^\\(.*[^ ]+\\) +$"  first-mark))
3839         (setq first-mark (match-string 1 first-mark)))
3840       (when (and (stringp last-mark)
3841                  (string-match "^\\(.*[^ ]+\\) +$"  last-mark))
3842         (setq last-mark (match-string 1 last-mark)))
3843       (when (and (stringp top-re)
3844                  (string-match "^\\(.*[^ ]+\\) +$"  top-re))
3845         (setq top-re (match-string 1 top-re))))
3846     (save-excursion
3847       (skip-chars-backward "^\r\n")
3848       (unless outside
3849         (and (eq (preceding-char) ?\r)
3850              (forward-char -1))
3851         (if (looking-at top-re)
3852             (if backward
3853                 (setq last (match-end 1))
3854               (skip-chars-forward "^\r\n"))))
3855       (while (progn
3856                ;;  Find last first, prevents unnecessary searching
3857                ;;  for first.
3858                (setq point (point))
3859                (or last
3860                    (while (and (if backward
3861                                    (search-backward last-mark first t)
3862                                  (search-forward  last-mark first t))
3863                                (progn
3864                                  (setq temp (point))
3865                                  (goto-char (match-beginning 0))
3866                                  (skip-chars-backward " \t")
3867                                  (and (not
3868                                        (setq last
3869                                              (if (eq (preceding-char) ?\r)
3870                                                  temp
3871                                                (and (bolp) temp))))
3872                                       (goto-char temp)))))
3873                    (goto-char point))
3874                (or first
3875                    (while (and (if backward
3876                                    (search-backward first-mark last t)
3877                                  (search-forward  first-mark last t))
3878                                (progn
3879                                  (setq temp (point))
3880                                  (goto-char (match-beginning 0))
3881                                  (skip-chars-backward " \t")
3882                                  (and (not
3883                                        (setq first
3884                                              (if (eq (preceding-char) ?\r)
3885                                                  temp
3886                                                (and (bolp) temp))))
3887                                       (goto-char temp))))))
3888                ;;  Return value of conditional says whether to
3889                ;;  iterate again.
3890                (if (not last)
3891                    ;;  Return from this with the result.
3892                    (not (setq pairs (if first t (cons nil pairs))))
3893                  (if (and first
3894                           (if backward
3895                               (> first last)
3896                             (< first last)))
3897                      (progn
3898                        (goto-char first)
3899                        (if (eq 0 depth)
3900                            (setq start first
3901                                  first nil
3902                                  depth 1) ;; non-nil value, loop again.
3903                          (setq first nil
3904                                ;; non-nil value => loop again
3905                                depth (1+ depth))))
3906                    (goto-char last)
3907                    (if (eq 0 depth)
3908                        (not (setq pairs (cons last pairs)))
3909                      (or (< 0 (setq depth (1- depth)))
3910                          (setq pairs (cons last (cons start pairs))))
3911                      (setq last nil)
3912                      t)))))
3913       pairs)))
3914
3915 ;;}}}
3916
3917 ;;}}}
3918 ;;{{{ code: Functions that actually modify the buffer
3919
3920 ;;{{{ folding-fold-region
3921
3922 (defun folding-fold-region (start end)
3923   "Places fold mark at the beginning and end of a specified region.
3924 The region is specified by two arguments START and END. The point is
3925 left at a suitable place ready to insert the title of the fold.
3926
3927 The fold markers are intended according to mode."
3928   (interactive "r")
3929   (and (< end start)
3930        (setq start (prog1 end
3931                      (setq end start))))
3932   (setq end (set-marker (make-marker) end))
3933   (goto-char start)
3934   (beginning-of-line)
3935   (setq start (point))
3936   (insert-before-markers folding-top-mark)
3937   ;;  XEmacs latex-mode, after (tex-site), indents the whole
3938   ;;  fold 50 characters right. Don't do that.
3939   (unless (string-match "latex" (symbol-name major-mode))
3940     (indent-according-to-mode))
3941   (let ((saved-point (point)))
3942     (and folding-secondary-top-mark
3943          (insert-before-markers folding-secondary-top-mark))
3944     (insert-before-markers ?\n)
3945     (goto-char (marker-position end))
3946     (set-marker end nil)
3947     (and (not (bolp))
3948          (eq 0 (forward-line))
3949          (eobp)
3950          (insert ?\n))
3951     (insert folding-bottom-mark)
3952     (unless (string-match "latex" (symbol-name major-mode))
3953       (indent-according-to-mode))
3954     (insert ?\n)
3955     (setq folding-stack (if folding-stack
3956                             (cons (cons (point-min-marker)
3957                                         (point-max-marker))
3958                                   folding-stack)
3959                           '(folded)))
3960     (folding-narrow-to-region start (1- (point)))
3961     (goto-char saved-point)
3962     (folding-set-mode-line))
3963   (save-excursion (folding-tidy-inside)))
3964
3965 ;;}}}
3966 ;;{{{ folding-tidy-inside
3967
3968 ;; Note to self: The long looking code for checking and modifying those
3969 ;; blank lines is to make sure the text isn't modified unnecessarily.
3970 ;; Don't remove it again!
3971
3972 (defun folding-tidy-inside ()
3973   "Add or remove blank lines at the top and bottom of the current fold.
3974 Also adds fold marks at the top and bottom (after asking), if they are not
3975 there already. The amount of space left depends on the variable
3976 `folding-internal-margins', which is one by default."
3977   (interactive)
3978   (if buffer-read-only nil
3979     (let ()
3980 ;;;          (top-re       (if (string-match "^\\(.*\\) $"  folding-top-mark)
3981 ;;;                            (match-string 1 folding-top-mark)
3982 ;;;                          folding-top-mark))
3983       (if (folding-use-overlays-p)
3984           (goto-char (- (overlay-end (car folding-narrow-overlays)) 1))
3985         (goto-char (point-min)))
3986       (and (eolp)
3987            (progn (skip-chars-forward "\n\t ")
3988                   (delete-region (point-min) (point))))
3989       (and (if (let (case-fold-search) (folding-mark-look-at-top-mark-p))
3990                (progn (forward-line 1)
3991                       (and (eobp) (insert ?\n))
3992                       t)
3993              (and (y-or-n-p "Insert missing folding-top-mark? ")
3994                   (progn (insert (concat folding-top-mark
3995                                          "<Replaced missing fold top mark>"
3996                                          (or folding-secondary-top-mark "")
3997                                          "\n"))
3998                          t)))
3999            folding-internal-margins
4000            (<= 0 folding-internal-margins)
4001            (let* ((p1 (point))
4002                   (p2 (progn (skip-chars-forward "\n") (point)))
4003                   (p3 (progn (skip-chars-forward "\n\t ")
4004                              (skip-chars-backward "\t " p2) (point))))
4005              (if (eq p2 p3)
4006                  (or (eq p2 (setq p3 (+ p1 folding-internal-margins)))
4007                      (if (< p2 p3)
4008                          (newline (- p3 p2))
4009                        (delete-region p3 p2)))
4010                (delete-region p1 p3)
4011                (or (eq 0 folding-internal-margins)
4012                    (newline folding-internal-margins)))))
4013       (if (folding-use-overlays-p)
4014           (goto-char  (overlay-start (cdr folding-narrow-overlays)))
4015         (goto-char (point-max)))
4016       (and (bolp)
4017            (progn (skip-chars-backward "\n")
4018                   (delete-region (point) (point-max))))
4019       (beginning-of-line)
4020       (and (or (let (case-fold-search) (folding-mark-look-at-bottom-mark-p))
4021                (progn (goto-char (point-max)) nil)
4022                (and (y-or-n-p "Insert missing folding-bottom-mark? ")
4023                     (progn
4024                       (insert (concat "\n" folding-bottom-mark))
4025                       (beginning-of-line)
4026                       t)))
4027            folding-internal-margins
4028            (<= 0 folding-internal-margins)
4029            (let* ((p1 (point))
4030                   (p2 (progn (skip-chars-backward "\n") (point)))
4031                   (p3 (progn (skip-chars-backward "\n\t ")
4032                              (skip-chars-forward "\t " p2) (point))))
4033              (if (eq p2 p3)
4034                  (or (eq p2 (setq p3 (- p1 1 folding-internal-margins)))
4035                      (if (> p2 p3)
4036                          (newline (- p2 p3))
4037                        (delete-region p2 p3)))
4038                (delete-region p3 p1)
4039                (newline (1+ folding-internal-margins))))))))
4040
4041 ;;}}}
4042
4043 ;;}}}
4044 ;;{{{ code: Operations on the whole buffer
4045
4046 ;;{{{ folding-whole-buffer
4047
4048 (defun folding-whole-buffer ()
4049   "Folds every fold in the current buffer.
4050 Fails if the fold markers are not balanced correctly.
4051
4052 If the buffer is being viewed in a fold, folds are repeatedly exited to
4053 get to the top level first (this allows the folds to be tidied on the
4054 way out). The buffer modification flag is not affected, and this
4055 function will work on read-only buffers."
4056
4057   (interactive)
4058   (message "Folding buffer...")
4059   (let ((narrow-min (point-min))
4060         (narrow-max (point-max))
4061         folding-list)
4062     (save-excursion
4063       (widen)
4064       (goto-char 1)
4065       (setq folding-list (folding-skip-folds nil t))
4066       (narrow-to-region narrow-min narrow-max)
4067       (and (eq t folding-list)
4068            (error
4069             "Cannot fold whole buffer -- unmatched begin-fold mark `%s' Â´%s'"
4070             (current-buffer)
4071             folding-top-mark))
4072       (and (integerp (car folding-list))
4073            (error
4074             "Cannot fold whole buffer -- extraneous end-fold mark `%s' `%s'"
4075             (current-buffer)
4076             folding-bottom-mark))
4077       (folding-show-all)
4078       (widen)
4079       (goto-char 1)
4080       ;; Do the modifications forwards.
4081       (folding-subst-regions (nreverse (cdr folding-list)) ?\n ?\r))
4082     (beginning-of-line)
4083     (folding-narrow-to-region nil nil t)
4084     (message "Folding buffer... done")))
4085
4086 ;;}}}
4087 ;;{{{ folding-open-buffer
4088
4089 (defun folding-open-buffer ()
4090   "Unfolds the entire buffer, leaving the point where it is.
4091 Does not affect the buffer-modified flag, and can be used on read-only
4092 buffers."
4093   (interactive)
4094   (message "Unfolding buffer...")
4095   (folding-clear-stack)
4096   (folding-set-mode-line)
4097   (unwind-protect
4098       (progn
4099         (widen)
4100         (folding-subst-regions (list 1 (point-max)) ?\r ?\n))
4101     (folding-narrow-to-region nil nil t))
4102   (message "Unfolding buffer... done"))
4103
4104 ;;}}}
4105 ;;{{{ folding-convert-buffer-for-printing
4106
4107 (defun folding-convert-buffer-for-printing (&optional buffer pre-title post-title pad)
4108   "Remove folds from a buffer, for printing.
4109
4110 It copies the contents of the (hopefully) folded buffer BUFFER into a
4111 buffer called `*Unfolded: <Original-name>*', removing all of the fold
4112 marks. It keeps the titles of the folds, however, and numbers them.
4113 Subfolds are numbered in the form 5.1, 5.2, 5.3 etc., and the titles are
4114 indented to eleven characters.
4115
4116 It accepts four arguments. BUFFER is the name of the buffer to be
4117 operated on, or a buffer. nil means use the current buffer. PRE-TITLE
4118 is the text to go before the replacement fold titles, POST-TITLE is the
4119 text to go afterwards. Finally, if PAD is non-nil, the titles are all
4120 indented to the same column, which is eleven plus the length of
4121 PRE-TITLE. Otherwise just one space is placed between the number and
4122 the title."
4123   (interactive (list (read-buffer "Remove folds from buffer: "
4124                                   (buffer-name)
4125                                   t)
4126                      (read-string "String to go before enumerated titles: ")
4127                      (read-string "String to go after enumerated titles: ")
4128                      (y-or-n-p "Pad section numbers with spaces? ")))
4129   (set-buffer (setq buffer (get-buffer buffer)))
4130   (setq pre-title (or pre-title "")
4131         post-title (or post-title ""))
4132   (or folding-mode
4133       (error "Must be in Folding mode before removing folds"))
4134   (let* ((new-buffer (get-buffer-create (concat "*Unfolded: "
4135                                                 (buffer-name buffer)
4136                                                 "*")))
4137          (section-list '(1))
4138          (section-prefix-list '(""))
4139
4140          (secondary-mark-length (length folding-secondary-top-mark))
4141
4142          (secondary-mark folding-secondary-top-mark)
4143          (mode major-mode)
4144
4145          ;;  [jari] Aug 14 1997
4146          ;;  Regexp doesn't allow "footer text" like, so we add one more
4147          ;;  regexp to loosen the end criteria
4148          ;;
4149          ;;  {{{ Subsubsection 1
4150          ;;  }}} Subsubsection 1
4151          ;;
4152          ;;  was:  (regexp folding-regexp)
4153          ;;
4154          (regexp
4155           (concat "\\(^\\|\r\\)\\([ \t]*\\)\\(\\("
4156                   (regexp-quote folding-top-mark)
4157                   "\\)\\|\\("
4158                   (regexp-quote folding-bottom-mark)
4159                   "[ \t]*.*\\(\\)\\($\\|\r\\)\\)\\)"))
4160          title
4161          prefix)
4162     ;;  was obsolete function: (buffer-flush-undo new-buffer)
4163     (buffer-disable-undo new-buffer)
4164     (save-excursion
4165       (set-buffer new-buffer)
4166       (delete-region (point-min)
4167                      (point-max)))
4168     (save-restriction
4169       (widen)
4170       (copy-to-buffer new-buffer (point-min) (point-max)))
4171     (display-buffer new-buffer t)
4172     (set-buffer new-buffer)
4173     (subst-char-in-region (point-min) (point-max) ?\r ?\n)
4174     (funcall mode)
4175     (while (re-search-forward regexp nil t)
4176       (if (match-beginning 4)
4177           (progn
4178             (goto-char (match-end 4))
4179
4180             ;;  - Move after start fold and read the title from there
4181             ;;  - Then move back and kill the fold mark
4182             ;;
4183             (setq title
4184                   (buffer-substring (point)
4185                                     (progn (end-of-line)
4186                                            (point))))
4187             (delete-region (save-excursion
4188                              (goto-char (match-beginning 4))
4189                              (skip-chars-backward "\n\r")
4190                              (point))
4191                            (progn
4192                              (skip-chars-forward "\n\r")
4193                              (point)))
4194             (and (<= secondary-mark-length
4195                      (length title))
4196                  (string-equal secondary-mark
4197                                (substring title
4198                                           (- secondary-mark-length)))
4199                  (setq title (substring title
4200                                         0
4201                                         (- secondary-mark-length))))
4202             (setq section-prefix-list
4203                   (cons (setq prefix (concat (car section-prefix-list)
4204                                              (int-to-string (car section-list))
4205                                              "."))
4206                         section-prefix-list))
4207             (or (cdr section-list)
4208                 (insert ?\n))
4209             (setq section-list (cons 1
4210                                      (cons (1+ (car section-list))
4211                                            (cdr section-list))))
4212             (setq title (concat prefix
4213                                 (if pad
4214                                     (make-string
4215                                      (max 2 (- 8 (length prefix))) ? )
4216                                   " ")
4217                                 title))
4218             (message "Reformatting: %s%s%s"
4219                      pre-title
4220                      title
4221                      post-title)
4222             (insert "\n\n"
4223                     pre-title
4224                     title
4225                     post-title
4226                     "\n\n"))
4227         (goto-char (match-beginning 5))
4228         (or (setq section-list (cdr section-list))
4229             (error "Too many bottom-of-fold marks"))
4230
4231         (setq section-prefix-list (cdr section-prefix-list))
4232         (delete-region (point)
4233                        (progn
4234                          (forward-line 1)
4235                          (point)))))
4236     (and (cdr section-list)
4237          (error
4238           "Too many top-of-fold marks -- reached end of file prematurely"))
4239     (goto-char (point-min))
4240     (buffer-enable-undo)
4241     (set-buffer-modified-p nil)
4242     (message "All folds reformatted.")))
4243
4244 ;;}}}
4245 ;;}}}
4246
4247 ;;{{{ code: Standard fold marks for various major modes
4248
4249 ;;{{{ A function to set default marks, `folding-add-to-marks-list'
4250
4251 (defun folding-add-to-marks-list (mode top bottom
4252                                        &optional secondary noforce message)
4253   "Add/set fold mark list for a particular major mode.
4254 When called interactively, asks for a `major-mode' name, and for
4255 fold marks to be used in that mode. It adds the new set to
4256 `folding-mode-marks-alist', and if the mode name is the same as the current
4257 major mode for the current buffer, the marks in use are also changed.
4258
4259 If called non-interactively, arguments are MODE, TOP, BOTTOM and
4260 SECONDARY. MODE is the symbol for the major mode for which marks are
4261 being set. TOP, BOTTOM and SECONDARY are strings, the three fold marks
4262 to be used. SECONDARY may be nil (as opposed to the empty string), but
4263 the other two must be non-empty strings, and is an optional argument.
4264
4265 Two other optional arguments are NOFORCE, meaning do not change the
4266 marks if marks are already set for the specified mode if non-nil, and
4267 MESSAGE, which causes a message to be displayed if it is non-nil. This
4268 is also the message displayed if the function is called interactively.
4269
4270 To set default fold marks for a particular mode, put something like the
4271 following in your .emacs:
4272
4273 \(folding-add-to-marks-list 'major-mode \"(** {{{ \" \"(** }}} **)\" \" **)\")
4274
4275 Look at the variable `folding-mode-marks-alist' to see what default settings
4276 already apply.
4277
4278 `folding-set-marks' can be used to set the fold marks in use in the current
4279 buffer without affecting the default value for a particular mode."
4280   (interactive
4281    (let* ((mode (completing-read
4282                  (concat "Add fold marks for major mode ("
4283                          (symbol-name major-mode)
4284                          "): ")
4285                  obarray
4286                  (function
4287                   (lambda (arg)
4288                     (and (commandp arg)
4289                          (string-match "-mode\\'"
4290                                        (symbol-name arg)))))
4291                  t))
4292           (mode (if (equal mode "")
4293                     major-mode
4294                   (intern mode)))
4295           (object (assq mode folding-mode-marks-alist))
4296           (old-top (and object
4297                         (nth 1 object)))
4298           top
4299           (old-bottom (and object
4300                            (nth 2 object)))
4301           bottom
4302           (secondary (and object
4303                           (nth 3 object)))
4304           (prompt "Top fold marker: "))
4305      (and (equal secondary "")
4306           (setq secondary nil))
4307      (while (not top)
4308        (setq top (read-string prompt (or old-top "{{{ ")))
4309        (and (equal top "")
4310             (setq top nil)))
4311      (setq prompt (concat prompt
4312                           top
4313                           ", Bottom marker: "))
4314      (while (not bottom)
4315        (setq bottom (read-string prompt (or old-bottom "}}}")))
4316        (and (equal bottom "")
4317             (setq bottom nil)))
4318      (setq prompt (concat prompt
4319                           bottom
4320                           (if secondary
4321                               ", Secondary marker: "
4322                             ", Secondary marker (none): "))
4323            secondary (read-string prompt secondary))
4324      (and (equal secondary "")
4325           (setq secondary nil))
4326      (list mode top bottom secondary nil t)))
4327   (let ((object (assq mode folding-mode-marks-alist)))
4328     (if (and object
4329              noforce
4330              message)
4331         (message "Fold markers for `%s' are already set."
4332                  (symbol-name mode))
4333       (if object
4334           (or noforce
4335               (setcdr object (if secondary
4336                                  (list top bottom secondary)
4337                                (list top bottom))))
4338         (setq folding-mode-marks-alist
4339               (cons (if secondary
4340                         (list mode top bottom secondary)
4341                       (list mode top bottom))
4342                     folding-mode-marks-alist)))
4343       (and message
4344            (message "Set fold marks for `%s' to \"%s\" and \"%s\"."
4345                     (symbol-name mode)
4346                     (if secondary
4347                         (concat top "name" secondary)
4348                       (concat top "name"))
4349                     bottom)
4350            (and (eq major-mode mode)
4351                 (folding-set-marks top bottom secondary))))))
4352
4353 ;;}}}
4354 ;;{{{ Set some useful default fold marks
4355
4356 (folding-add-to-marks-list 'ada-mode               "-- {{{" "-- }}}" nil t)
4357 (folding-add-to-marks-list 'asm-mode               "; {{{"  "; }}}" nil t)
4358 (folding-add-to-marks-list 'awk-mode               "# {{{"  "# }}}" nil t)
4359 (folding-add-to-marks-list 'Bison-mode             "/* {{{" "/* }}} */" " */" t)
4360 (folding-add-to-marks-list 'LaTeX-mode             "%{{{"   "%}}}" nil t)
4361 (folding-add-to-marks-list 'TeX-mode               "%{{{"   "%}}}" nil t)
4362 (folding-add-to-marks-list 'bibtex-mode            "%{{{"   "%}}} */" nil t)
4363 (folding-add-to-marks-list 'bison-mode             "/* {{{" "/* }}} */" " */" t)
4364 (folding-add-to-marks-list 'c++-mode               "// {{{" "// }}}" nil t)
4365 (folding-add-to-marks-list 'c-mode                 "/* {{{" "/* }}} */" " */" t)
4366 (folding-add-to-marks-list 'dcl-mode               "! {{{"  "! }}}" nil t)
4367 (folding-add-to-marks-list 'change-log-mode        "{{{"    "}}}" nil t)
4368 (folding-add-to-marks-list 'cperl-mode             "# {{{"  "# }}}" nil t)
4369 (folding-add-to-marks-list 'emacs-lisp-mode        ";;{{{"  ";;}}}" nil t)
4370 (folding-add-to-marks-list 'erlang-mode            "%%{{{"  "%%}}}" nil t)
4371 (folding-add-to-marks-list 'finder-mode            "{{{"    "}}}" nil t)
4372 (folding-add-to-marks-list 'fortran-mode           "! {{{"  "! }}}" nil t)
4373 (folding-add-to-marks-list 'f90-mode               "! {{{"  "! }}}" nil t)
4374 (folding-add-to-marks-list 'generic-mode           ";# "    ";\$" nil t)
4375 (folding-add-to-marks-list 'gofer-mode             "-- {{{" "-- }}}" nil t)
4376 (folding-add-to-marks-list 'html-mode   "<!-- [[[ " "<!-- ]]] -->" " -->" t)
4377 (folding-add-to-marks-list 'icon-mode              "# {{{" "# }}}" nil t)
4378 (folding-add-to-marks-list 'indented-text-mode     "{{{"    "}}}" nil t)
4379 (folding-add-to-marks-list 'java-mode              "// {{{" "// }}}" nil t)
4380 (folding-add-to-marks-list 'javascript-mode        "// {{{" "// }}}" nil t)
4381 (folding-add-to-marks-list 'jde-mode               "// {{{" "// }}}" nil t)
4382 (folding-add-to-marks-list 'ksh-mode               "# {{{"  "# }}}" nil t)
4383 (folding-add-to-marks-list 'latex-mode             "%{{{"   "%}}}" nil t)
4384 (folding-add-to-marks-list 'lisp-interaction-mode  ";;{{{"  ";;}}}" nil t)
4385 (folding-add-to-marks-list 'lisp-mode              ";;{{{"  ";;}}}" nil t)
4386 (folding-add-to-marks-list 'm4-mode                "# {{{" "# }}}" nil t)
4387 (folding-add-to-marks-list 'makefile-mode          "# {{{"  "# }}}" nil t)
4388 (folding-add-to-marks-list 'matlab-mode            "%%%{{{" "%%%}}}" nil t)
4389 (folding-add-to-marks-list 'meta-mode              "% {{{" "% }}}" nil t)
4390 (folding-add-to-marks-list 'ml-mode                "(* {{{" "(* }}} *)" " *)" t)
4391 (folding-add-to-marks-list 'modula-2-mode          "(* {{{" "(* }}} *)" " *)" t)
4392 (folding-add-to-marks-list 'nroff-mode             "\\\\ {{{" "\\\\ }}}" nil t)
4393 (folding-add-to-marks-list 'occam-mode             "-- {{{" "-- }}}" nil t)
4394 (folding-add-to-marks-list 'orwell-mode            "{{{"    "}}}" nil t)
4395 (folding-add-to-marks-list 'pascal-mode            "{ ((( " "{ ))) }" " }" t)
4396 (folding-add-to-marks-list 'php-mode               "// {{{" "// }}}" nil t)
4397 (folding-add-to-marks-list 'perl-mode              "# {{{"  "# }}}" nil t)
4398 (folding-add-to-marks-list 'plain-TeX-mode         "%{{{"   "%}}}" nil t)
4399 (folding-add-to-marks-list 'plain-tex-mode         "%{{{"   "%}}}" nil t)
4400 (folding-add-to-marks-list 'prolog-mode            "% {{{"   "% }}}" nil t)
4401 (folding-add-to-marks-list 'rexx-mode              "/* {{{" "/* }}} */" " */" t)
4402 (folding-add-to-marks-list 'sh-mode                "# {{{"  "# }}}" nil t)
4403 (folding-add-to-marks-list 'sh-script-mode         "# {{{"  "# }}}" nil t)
4404 (folding-add-to-marks-list 'shellscript-mode       "# {{{"  "# }}}" nil t)
4405 (folding-add-to-marks-list 'sgml-mode   "<!-- [[[ " "<!-- ]]] -->" " -->" t)
4406 (folding-add-to-marks-list 'simula-mode            "! {{{"  "! }}}" nil t)
4407 (folding-add-to-marks-list 'sml-mode               "(* {{{" "(* }}} *)" " *)" t)
4408 (folding-add-to-marks-list 'sql-mode               "-- {{{"  "-- }}}" nil t)
4409 (folding-add-to-marks-list 'tcl-mode               "#{{{"   "#}}}" nil t)
4410 (folding-add-to-marks-list 'tex-mode               "%{{{"   "%}}}" nil t)
4411 (folding-add-to-marks-list 'texinfo-mode   "@c {{{" "@c {{{endfold}}}" " }}}" t)
4412 (folding-add-to-marks-list 'text-mode              "{{{"    "}}}" nil t)
4413 (folding-add-to-marks-list 'vhdl-mode              "# {{{"  "# }}}" nil t)
4414 (folding-add-to-marks-list 'xerl-mode              "%%{{{"  "%%}}}" nil t)
4415 (folding-add-to-marks-list 'xrdb-mode              "! {{{"  "! }}}" nil t)
4416
4417 ;; heavy shell-perl-awk programmer in fundamental-mode need # prefix...
4418
4419 (folding-add-to-marks-list 'fundamental-mode       "# {{{" "# }}}" nil t)
4420
4421 ;;}}}
4422
4423 ;;}}}
4424
4425 ;;{{{ code: Gross, crufty hacks that seem necessary
4426
4427 ;; ----------------------------------------------------------------------
4428 ;; The functions here have been tested with Emacs 18.55, Emacs 18.58,
4429 ;; Epoch 4.0p2 (based on Emacs 18.58) and XEmacs 19.6.
4430
4431 ;; Note that XEmacs 19.6 can't do selective-display, and its
4432 ;; "invisible extents" don't work either, so Folding mode just won't
4433 ;; work with that version.
4434
4435 ;; They shouldn't do the wrong thing with later versions of Emacs, but
4436 ;; they might not have the special effects either. They may appear to
4437 ;; be excessive; that is not the case. All of the peculiar things these
4438 ;; functions do is done to avoid some side-effect of Emacs' internal
4439 ;; logic that I have met. Some of them work around bugs or unfortunate
4440 ;; (lack of) features in Emacs. In most cases, it would be better to
4441 ;; move this into the Emacs C code.
4442
4443 ;; Folding mode is designed to be simple to cooperate with as many
4444 ;; things as possible. These functions go against that principle at the
4445 ;; coding level, but make life for the user bearable.
4446
4447 ;;{{{ folding-subst-regions
4448
4449 ;; Substitute newlines for carriage returns or vice versa.
4450 ;; Avoid excessive file locking.
4451
4452 ;; Substitutes characters in the buffer, even in a read-only buffer.
4453 ;; Takes LIST, a list of regions specified as sequence in the form
4454 ;; (START1 END1 START2 END2 ...). In every region specified by each
4455 ;; pair, substitutes each occurence of character FIND by REPLACE.
4456
4457 ;; The buffer-modified flag is not affected, undo information is not
4458 ;; kept for the change, and the function works on read-only files. This
4459 ;; function is much more efficient called with a long sequence than
4460 ;; called for each region in the sequence.
4461
4462 ;; If the buffer is not modified when the function is called, the
4463 ;; modified-flag is set before performing all the substitutions, and
4464 ;; locking is temporarily disabled. This prevents Emacs from trying to
4465 ;; make then delete a lock file for *every* substitution, which slows
4466 ;; folding considerably, especially on a slow networked filesystem.
4467 ;; Without this, on my system, folding files on startup (and reading
4468 ;; other peoples' folded files) takes about five times longer. Emacs
4469 ;; still locks the file once for this call under those circumstances; I
4470 ;; can't think of a way around that, but it isn't really a problem.
4471
4472 ;; I consider these problems to be a bug in `subst-char-in-region'.
4473
4474 (defun folding-subst-regions (list find replace)
4475   "Substitute \\r and \\n using LIST FIND REPLACE."
4476   (let ((buffer-read-only   buffer-read-only) ;; Protect read-only flag.
4477         (modified           (buffer-modified-p))
4478         (font-lock-mode     nil)
4479         (lazy-lock-mode     nil)
4480         (overlay-p          (folding-use-overlays-p))
4481         (ask1 (symbol-function 'ask-user-about-supersession-threat))
4482         (ask2 (symbol-function 'ask-user-about-lock)))
4483     (if lazy-lock-mode ;; no-op: Byte compiler silencer
4484         (setq lazy-lock-mode t))
4485     (unwind-protect
4486         (progn
4487           (setq buffer-read-only nil)
4488           (or modified
4489               (progn
4490                 (fset 'ask-user-about-supersession-threat
4491                       '(lambda (&rest x) nil))
4492                 (fset 'ask-user-about-lock
4493                       '(lambda (&rest x) nil))
4494                 (set-buffer-modified-p t))) ; Prevent file locking in the loop
4495           (while list
4496             (if overlay-p
4497                 (folding-flag-region (car list) (nth 1 list) (eq find ?\n))
4498               (subst-char-in-region (car list) (nth 1 list) find replace t))
4499             (setq list (cdr (cdr list)))))
4500       ;; buffer-read-only is restored by the let.
4501       ;; Don't want to change MODIFF time if it was modified before.
4502       (or modified
4503           (unwind-protect
4504               (set-buffer-modified-p nil)
4505             (fset 'ask-user-about-supersession-threat ask1)
4506             (fset 'ask-user-about-lock ask2))))))
4507
4508 ;;}}}
4509 ;;{{{ folding-narrow-to-region
4510
4511 ;; Narrow to region, without surprising displays.
4512
4513 ;; Similar to `narrow-to-region', but also adjusts window-start to be
4514 ;; the start of the narrowed region. If an optional argument CENTRE is
4515 ;; non-nil, the window-start is positioned to leave the point at the
4516 ;; centre of the window, like `recenter'. START may be nil, in which
4517 ;; case the function acts more like `widen'.
4518
4519 ;; Actually, all the window-starts for every window displaying the
4520 ;; buffer, as well as the last_window_start for the buffer are set. The
4521 ;; points in every window are set to the point in the current buffer.
4522 ;; All this logic is necessary to prevent the display getting really
4523 ;; weird occasionally, even if there is only one window. Try making
4524 ;; this function like normal `narrow-to-region' with a touch of
4525 ;; `recenter', then moving around lots of folds in a buffer displayed in
4526 ;; several windows. You'll see what I mean.
4527
4528 ;; last_window_start is set by making sure that the selected window is
4529 ;; displaying the current buffer, then setting the window-start, then
4530 ;; making the selected window display another buffer (which sets
4531 ;; last_window_start), then setting the selected window to redisplay the
4532 ;; buffer it displayed originally.
4533
4534 ;; Note that whenever window-start is set, the point cannot be moved
4535 ;; outside the displayed area until after a proper redisplay. If this
4536 ;; is possible, centre the display on the point.
4537
4538 ;; In Emacs 19; Epoch or XEmacs, searches all screens for all
4539 ;; windows. In Emacs 19, they are called "frames".
4540
4541 (defun folding-narrow-to-region (&optional start end centre)
4542   "Narrow to region START END, possibly CENTRE."
4543   (let* ((the-window        (selected-window))
4544          (selected-buffer   (window-buffer the-window))
4545          (window-ring       the-window)
4546          (window            the-window)
4547          (point             (point))
4548          (buffer            (current-buffer))
4549          temp)
4550     (unwind-protect
4551         (progn
4552           (unwind-protect
4553               (progn
4554                 (if (folding-use-overlays-p)
4555                     (if start
4556                         (folding-narrow-aux  start end t)
4557                       (folding-narrow-aux  nil nil nil))
4558                   (if start
4559                       (narrow-to-region start end)
4560                     (widen)))
4561
4562                 (setq point (point))
4563                 (set-window-buffer window buffer)
4564
4565                 (while (progn
4566                          (and (eq buffer (window-buffer window))
4567                               (if centre
4568                                   (progn
4569                                     (select-window window)
4570                                     (goto-char point)
4571                                     (vertical-motion
4572                                      (- (lsh (window-height window) -1)))
4573                                     (set-window-start window (point))
4574                                     (set-window-point window point))
4575                                 (set-window-start window (or start 1))
4576                                 (set-window-point window point)))
4577
4578                          (not (eq (setq window (next-window window nil t))
4579                                   window-ring)))))
4580             nil                         ;; epoch screen
4581             (select-window the-window)) ;; unwind-protect INNER
4582           ;; Set last_window_start.
4583           (unwind-protect
4584               (if (not (eq buffer selected-buffer))
4585                   (set-window-buffer the-window selected-buffer)
4586                 (if (get-buffer "*scratch*")
4587                     (set-window-buffer the-window (get-buffer "*scratch*"))
4588                   (set-window-buffer
4589                    the-window (setq temp (generate-new-buffer " *temp*"))))
4590                 (set-window-buffer the-window buffer))
4591             (and temp
4592                  (kill-buffer temp))))
4593       ;; Undo this side-effect of set-window-buffer.
4594       (set-buffer buffer)
4595       (goto-char (point)))))
4596
4597 ;;}}}
4598
4599 ;;}}}
4600
4601 ;;{{{ code: folding-end-mode-quickly
4602
4603 (defun folding-end-mode-quickly ()
4604   "Replace all ^M's with linefeeds and widen a folded buffer.
4605 Only has any effect if Folding mode is active.
4606
4607 This should not in general be used for anything. It is used when changing
4608 major modes, by being placed in kill-mode-tidy-alist, to tidy the buffer
4609 slightly. It is similar to `(folding-mode 0)', except that it does not
4610 restore saved keymaps etc. Repeat: Do not use this function. Its
4611 behaviour is liable to change."
4612   (and (boundp 'folding-mode)
4613        (assq 'folding-mode
4614              (buffer-local-variables))
4615        folding-mode
4616        (progn
4617          (if (folding-use-overlays-p)
4618              (folding-narrow-to-region nil nil)
4619            (widen))
4620          (folding-clear-stack)
4621          (folding-subst-regions (list 1 (point-max)) ?\r ?\n))))
4622
4623 ;;{{{ folding-eval-current-buffer-open-folds
4624
4625 (defun folding-eval-current-buffer-open-folds (&optional printflag)
4626   "Evaluate all of a folded buffer as Lisp code.
4627 Unlike `eval-current-buffer', this function will evaluate all of a
4628 buffer, even if it is folded. It will also work correctly on non-folded
4629 buffers, so is a good candidate for being bound to a key if you program
4630 in Emacs-Lisp.
4631
4632 It works by making a copy of the current buffer in another buffer,
4633 unfolding it and evaluating it. It then deletes the copy.
4634
4635 Programs can pass argument PRINTFLAG which controls printing of output:
4636 nil means discard it; anything else is stream for print."
4637   (interactive)
4638   (if (or (and (boundp 'folding-mode)
4639                folding-mode))
4640       (let ((temp-buffer
4641              (generate-new-buffer (buffer-name))))
4642         (message "Evaluating unfolded buffer...")
4643         (save-restriction
4644           (widen)
4645           (copy-to-buffer temp-buffer 1 (point-max)))
4646         (set-buffer temp-buffer)
4647         (subst-char-in-region 1 (point-max) ?\r ?\n)
4648         (let ((real-message-def (symbol-function 'message))
4649               (suppress-eval-message))
4650           (fset 'message
4651                 (function
4652                  (lambda (&rest args)
4653                    (setq suppress-eval-message t)
4654                    (fset 'message real-message-def)
4655                    (apply 'message args))))
4656           (unwind-protect
4657               (eval-current-buffer printflag)
4658             (fset 'message real-message-def)
4659             (kill-buffer temp-buffer))
4660           (or suppress-eval-message
4661               (message "Evaluating unfolded buffer... Done"))))
4662     (eval-current-buffer printflag)))
4663
4664 ;;}}}
4665
4666 ;;}}}
4667
4668 ;;{{{ code: ISearch support, walks in and out of folds
4669
4670 ;; This used to be a package of it's own.
4671 ;; Requires Emacs 19 or XEmacs. Does not work under Emacs 18.
4672
4673 ;;{{{ Variables
4674
4675 (defcustom folding-isearch-install t
4676   "*When non-nil, the isearch commands will handle folds."
4677   :type 'boolean
4678   :group 'folding)
4679
4680 (defvar folding-isearch-stack nil
4681   "Temporary storage for `folding-stack' during isearch.")
4682
4683 ;; Lists of isearch commands to replace
4684
4685 ;; These do normal searching.
4686
4687 (defvar folding-isearch-normal-cmds
4688   '(isearch-repeat-forward
4689     isearch-repeat-backward
4690     isearch-toggle-regexp
4691     isearch-toggle-case-fold
4692     isearch-delete-char
4693     isearch-abort
4694     isearch-quote-char
4695     isearch-other-control-char
4696     isearch-other-meta-char
4697     isearch-return-char
4698     isearch-exit
4699     isearch-printing-char
4700     isearch-whitespace-chars
4701     isearch-yank-word
4702     isearch-yank-line
4703     isearch-yank-kill
4704     isearch-*-char
4705     isearch-\|-char
4706     isearch-mode-help
4707     isearch-yank-x-selection
4708     isearch-yank-x-clipboard)
4709   "List if isearch commands doing normal search.")
4710
4711 ;; Enables the user to edit the search string
4712
4713 ;; Missing, present in XEmacs isearch-mode.el. Not necessary?
4714 ;; isearch-ring-advance-edit, isearch-ring-retreat-edit, isearch-complete-edit
4715 ;; isearch-nonincremental-exit-minibuffer, isearch-yank-x-selection,
4716 ;; isearch-yank-x-clipboard
4717
4718 (defvar folding-isearch-edit-enter-cmds
4719   '(isearch-edit-string
4720     isearch-ring-advance
4721     isearch-ring-retreat
4722     isearch-complete)              ; (Could also stay in search mode!)
4723   "List of isearch commands which enters search string edit.")
4724
4725 ;; Continues searching after editing.
4726
4727 (defvar folding-isearch-edit-exit-cmds
4728   '(isearch-forward-exit-minibuffer     ; Exits edit
4729     isearch-reverse-exit-minibuffer
4730     isearch-nonincremental-exit-minibuffer)
4731   "List of isearch commands which exits search string edit.")
4732
4733 ;;}}}
4734 ;;{{{ Keymaps (an Isearch hook)
4735
4736 (defvar folding-isearch-mode-map nil
4737   "Modified copy of the isearch keymap.")
4738
4739 ;; Create local copies of the keymaps. The `isearch-mode-map' is
4740 ;; copied to `folding-isearch-mode-map' while `minibuffer-local-isearch-map'
4741 ;; is made local. (Its name is used explicitly.)
4742 ;;
4743 ;; Note: This is called every time the search is started.
4744
4745 (defun folding-isearch-hook-function ()
4746   "Update the isearch keymaps for usage with folding mode."
4747   (if (and (boundp 'folding-mode) folding-mode)
4748       (let ((cmds (append folding-isearch-normal-cmds
4749                           folding-isearch-edit-enter-cmds
4750                           folding-isearch-edit-exit-cmds)))
4751         (setq folding-isearch-mode-map (copy-keymap isearch-mode-map))
4752         (make-local-variable 'minibuffer-local-isearch-map)
4753         ;; Make sure the destructive operations below doesn't alter
4754         ;; the global instance of the map.
4755         (setq minibuffer-local-isearch-map
4756               (copy-keymap minibuffer-local-isearch-map))
4757         (setq folding-isearch-stack folding-stack)
4758         (while cmds
4759           (substitute-key-definition
4760            (car cmds)
4761            (intern (concat "folding-" (symbol-name (car cmds))))
4762            folding-isearch-mode-map)
4763           (substitute-key-definition
4764            (car cmds)
4765            (intern (concat "folding-" (symbol-name (car cmds))))
4766            minibuffer-local-isearch-map)
4767           (setq cmds (cdr cmds)))
4768         ;; Install our keymap
4769         (cond
4770          (folding-xemacs-p
4771           (let ((f 'set-keymap-name))
4772             (funcall f folding-isearch-mode-map 'folding-isearch-mode-map))
4773           ;; Later version of XEmacs (21.2+) use overriding-local-map
4774           ;; for isearch keymap rather than fiddling with
4775           ;; minor-mode-map-alist.  This is so isearch keymaps take
4776           ;; precedence over extent-local keymaps.  We will support
4777           ;; both ways here.  Keymaps will be restored as side-effect
4778           ;; of isearch-abort and isearch-quit
4779           (cond
4780            ;; if overriding-local-map is in use
4781            ((and (boundp 'overriding-local-map) overriding-local-map)
4782             (set-keymap-parent folding-isearch-mode-map overriding-local-map)
4783             (setq overriding-local-map folding-isearch-mode-map))
4784            ;; otherwise fiddle with minor-mode-map-alist
4785            (t
4786             (setq minor-mode-map-alist
4787                   (cons (cons 'isearch-mode folding-isearch-mode-map)
4788                         (delq (assoc 'isearch-mode minor-mode-map-alist)
4789                               minor-mode-map-alist))))))
4790          ((boundp 'overriding-terminal-local-map)
4791           (funcall (symbol-function 'set)
4792                    'overriding-terminal-local-map folding-isearch-mode-map))
4793          ((boundp 'overriding-local-map)
4794           (setq overriding-local-map folding-isearch-mode-map))))))
4795
4796 ;; Undoes the `folding-isearch-hook-function' function.
4797
4798 (defun folding-isearch-end-hook-function ()
4799   "Actions to perform at the end of isearch in folding mode."
4800   (when (and (boundp 'folding-mode) folding-mode)
4801     (kill-local-variable 'minibuffer-local-isearch-map)
4802     (setq folding-stack folding-isearch-stack)))
4803
4804 (when folding-isearch-install
4805   (add-hook 'isearch-mode-hook 'folding-isearch-hook-function)
4806   (add-hook 'isearch-mode-end-hook 'folding-isearch-end-hook-function))
4807
4808 ;;}}}
4809 ;;{{{ Normal search routines
4810
4811 ;; Generate the replacement functions of the form:
4812 ;;    (defun folding-isearch-repeat-forward ()
4813 ;;      (interactive)
4814 ;;      (folding-isearch-general 'isearch-repeat-forward))
4815
4816 (let ((cmds folding-isearch-normal-cmds))
4817   (while cmds
4818     (eval
4819      (` (defun (, (intern (concat "folding-" (symbol-name (car cmds))))) ()
4820           "Automatically generated"
4821           (interactive)
4822           (folding-isearch-general (quote (, (car cmds)))))))
4823     (setq cmds (cdr cmds))))
4824
4825 ;; The HEART! Executes command and updates the foldings.
4826 ;; This is capable of detecting a `quit'.
4827
4828 (defun folding-isearch-general (function)
4829   "Execute isearch command FUNCTION and adjusts the folding."
4830   (let* ((quit-isearch  nil)
4831          (area-beg      (point-min))
4832          (area-end      (point-max))
4833          pos)
4834     (cond
4835      (t
4836       (save-restriction
4837         (widen)
4838         (condition-case nil
4839             (funcall function)
4840           (quit  (setq quit-isearch t)))
4841         (setq pos (point)))
4842       ;; Situation
4843       ;; o   user has folded buffer
4844       ;; o   He manually narrows, say to function !
4845       ;; --> there is no fold marks at the beg/end --> this is not a fold
4846       (condition-case nil
4847           ;; "current mode has no fold marks..."
4848           (folding-region-has-folding-marks-p area-beg area-end)
4849         (error (setq quit-isearch t)))
4850       (folding-goto-char pos)))
4851     (if quit-isearch
4852         (signal 'quit '(isearch)))))
4853
4854 ;;}}}
4855 ;;{{{ Edit search string support
4856
4857 (defvar folding-isearch-current-buffer nil
4858   "The buffer we are editing, so we can widen it when in minibuffer.")
4859
4860 ;; Functions which enters edit mode.
4861
4862 (defun folding-isearch-edit-string ()
4863   "Replace `isearch-edit-string' when in `folding-mode'."
4864   (interactive)
4865   (folding-isearch-start-edit 'isearch-edit-string))
4866
4867 (defun folding-isearch-ring-advance ()
4868   "Replace `isearch-ring-advance' when in `folding-mode'."
4869   (interactive)
4870   (folding-isearch-start-edit 'isearch-ring-advance))
4871
4872 (defun folding-isearch-ring-retreat ()
4873   "Replace `isearch-ring-retreat' when in `folding-mode'."
4874   (interactive)
4875   (folding-isearch-start-edit 'isearch-ring-retreat))
4876
4877 (defun folding-isearch-complete ()
4878   "Replace `isearch-complete' when in `folding-mode'."
4879   (interactive)
4880   (folding-isearch-start-edit 'isearch-complete))
4881
4882 ;; Start and wait for editing. When (funcall fnk) returns
4883 ;; we are back in interactive search mode.
4884 ;;
4885 ;; Store match data!
4886
4887 (defun folding-isearch-start-edit (function)
4888   "Edit with function FUNCTION."
4889   (let (pos)
4890     (setq folding-isearch-current-buffer (current-buffer))
4891     (save-restriction
4892       (funcall function)
4893       ;; Here, we are widened, by folding-isearch-*-exit-minibuffer.
4894       (setq pos (point)))
4895     (folding-goto-char pos)))
4896
4897 ;; Functions which exits edit mode.
4898
4899 ;; The `widen' below will be caught by the `save-restriction' above, thus
4900 ;; this will not cripple `folding-stack'.
4901
4902 (defun folding-isearch-forward-exit-minibuffer ()
4903   "Replace `isearch-forward-exit-minibuffer' when in `folding-mode'."
4904   (interactive)
4905   ;; Make sure we can continue searching outside narrowing.
4906   (save-excursion
4907     (set-buffer folding-isearch-current-buffer)
4908     (widen))
4909   (isearch-forward-exit-minibuffer))
4910
4911 (defun folding-isearch-reverse-exit-minibuffer ()
4912   "Replace `isearch-reverse-exit-minibuffer' when in `folding-mode'."
4913   (interactive)
4914   ;; Make sure we can continue searching outside narrowing.
4915   (save-excursion
4916     (set-buffer folding-isearch-current-buffer)
4917     (widen))
4918   (isearch-reverse-exit-minibuffer))
4919
4920 (defun folding-isearch-nonincremental-exit-minibuffer ()
4921   "Replace `isearch-reverse-exit-minibuffer' when in `folding-mode'."
4922   (interactive)
4923   ;; Make sure we can continue searching outside narrowing.
4924   (save-excursion
4925     (set-buffer folding-isearch-current-buffer)
4926     (widen))
4927   (isearch-nonincremental-exit-minibuffer))
4928
4929 ;;}}}
4930 ;;{{{ Special XEmacs support
4931
4932 ;; In XEmacs, all isearch commands must have the property `isearch-command'.
4933
4934 (if folding-xemacs-p
4935     (let ((cmds (append folding-isearch-normal-cmds
4936                         folding-isearch-edit-enter-cmds
4937                         folding-isearch-edit-exit-cmds)))
4938       (while cmds
4939         (put (intern (concat "folding-" (symbol-name (car cmds))))
4940              'isearch-command t)
4941         (setq cmds (cdr cmds)))))
4942
4943 ;;}}}
4944 ;;{{{ General purpose function.
4945
4946 (defun folding-goto-char (pos)
4947   "Goto character POS, changing fold if necessary."
4948   ;; Make sure POS is inside the visible area of the buffer.
4949   (goto-char pos)
4950   (if (eq pos (point))                  ; Point inside narrowed area?
4951       nil
4952     (folding-show-all)                 ; Fold everything and goto top.
4953     (goto-char pos))
4954   ;; Enter if point is folded.
4955   (if (folding-point-folded-p pos)
4956       (progn
4957         (folding-shift-in)      ; folding-shift-in can change the pos.
4958         (setq folding-isearch-stack folding-stack)
4959         (setq folding-stack '(folded))
4960         (goto-char pos))))
4961
4962 (defun folding-point-folded-p (pos)
4963   "Non-nil when POS is not visible."
4964   (if (folding-use-overlays-p)
4965       (let ((overlays (overlays-at (point)))
4966             (found nil))
4967         (while (and (not found) (overlayp (car overlays)))
4968           (setq found (overlay-get (car overlays) 'fold)
4969                 overlays (cdr overlays)))
4970         found)
4971     (save-excursion
4972       (goto-char pos)
4973       (beginning-of-line)
4974       (skip-chars-forward "^\r" pos)
4975       (not (eq pos (point))))))
4976
4977 ;;}}}
4978
4979 ;;}}}
4980 ;;{{{ code: Additional functions
4981
4982 (defvar folding-comment-folding-table
4983   '((c-mode
4984      folding-comment-c-mode
4985      folding-uncomment-c-mode))
4986   "Table of functions to comment and uncomment folds.
4987 Function is called with two arguments:
4988
4989   number    start of fold mark
4990   marker    end of fold mark
4991
4992 Function must return:
4993
4994   (beg . end)    start of fold, end of fold
4995
4996 Table Format:
4997  '((MAJOR-MODE COMMENT-FUNCTION UNCOMMENT-FUNCTION) ..)")
4998
4999 (defun folding-insert-advertise-folding-mode ()
5000   "Insert Small text describing where to the get the folding at point.
5001 This may be useful 'banner' to inform other people why your code
5002 is formatted like it is and how to view it correctly."
5003   (interactive)
5004   (let* ((prefix "")
5005          (re    (or comment-start-skip
5006                     (and comment-start
5007                          (concat "^[ \t]*" comment-start "+[ \t]*")))))
5008
5009     (when re
5010       (save-excursion
5011         (beginning-of-line)
5012         (when (or (re-search-forward re nil t)
5013                   (progn
5014                     (goto-char (point-min))
5015                     (re-search-forward re nil t)))
5016           (setq prefix (match-string 0)))))
5017
5018     (beginning-of-line)
5019     (dolist (line
5020              (list
5021               "File layout controlled by Emacs folding.el available at: "
5022               folding-package-url-location))
5023       (insert "\n" prefix line))))
5024
5025 (defun folding-uncomment-mode-generic (beg end tag)
5026   "In region (BEG . END) remove two TAG lines."
5027   (re-search-forward tag (marker-position end))
5028   (beginning-of-line)
5029   (kill-line 1)
5030   (re-search-forward tag (marker-position end))
5031   (beginning-of-line)
5032   (kill-line 1)
5033   (cons beg end))
5034
5035 (defun folding-comment-mode-generic (beg end tag1 &optional tag2)
5036   "Return (BEG . END) and Add two TAG1 and TAG2 lines."
5037   (insert tag1)
5038   (goto-char (marker-position end))
5039   (insert (or tag2 tag1))
5040   (cons beg end))
5041
5042 (defun folding-uncomment-c-mode  (beg end)
5043   "Uncomment region BEG END."
5044   (folding-uncomment-mode-generic
5045    beg end (regexp-quote " comment /* FOLDING -COM- */")))
5046
5047 (defun folding-comment-c-mode  (beg end)
5048   "Comment region BEG END."
5049   (let* ((tag " /* FOLDING -COM- */"))
5050     (folding-comment-mode-generic
5051      beg end
5052      (concat "#if comment"    tag "\n")
5053      (concat "#endif comment" tag "\n"))))
5054
5055 (defun folding-comment-fold  (&optional uncomment)
5056   "Comment or UNCOMMENT all text inside single fold.
5057 If there are subfolds this function won't work as expected.
5058 User must know that there are no subfolds.
5059
5060 The heading has -COM- at the end when the fold is commented.
5061 Point must be over fold heading {{{ when function is called.
5062
5063 Note:
5064
5065  You can use this function only in modes that do _not_ have
5066  `comment-end'. Ie. don't use this function in modes like C (/* */), because
5067  nested comments are not allowed. See this:
5068
5069     /* {{{ fold */
5070        code  /* comment of the code */
5071     /* }}} */
5072
5073  Fold can't know how to comment the `code' inside fold, because comments
5074  do not nest.
5075
5076 Implementation detail:
5077
5078  {{{ FoldHeader-COM-
5079
5080  If the fold header has -COM- at the end, then the fold is supposed to
5081  be commented. And if there is no -COM- then fold will be considered
5082  as normal fold. Do not loose or add the -COM- yourself or it will
5083  confuse the state of the fold.
5084
5085 References:
5086
5087  `folding-comment-folding-table'"
5088   (interactive "P")
5089   (let* ((state     (folding-mark-look-at 'move))
5090          (closed    (eq 0 state))
5091          (id        "-COM-")
5092          (opoint    (point))
5093          (mode-elt  (assq major-mode folding-comment-folding-table))
5094          comment
5095          ret
5096          beg
5097          end)
5098     (unless mode-elt
5099       (if (stringp (nth 2 (folding-get-mode-marks major-mode)))
5100           (error "\
5101 Folding: function usage error, mode with `comment-end' is not supported.")))
5102     (when (or (null comment-start)
5103               (not (string-match "[^ \t\n]" comment-start)))
5104       (error "Empty comment-start."))
5105     (unless (memq state '( 0 1 11))
5106       (error "Incorrect fold state. Point must be over {{{."))
5107     ;;  There is nothing to do if this fold heading does not have
5108     ;;  the ID when uncommenting the fold.
5109     (setq state (looking-at (concat ".*" id)))
5110     (when (or (and uncomment state)
5111               (and (null uncomment) (null state)))
5112       (when closed (save-excursion (folding-show-current-entry)))
5113       (folding-pick-move)               ;Go to end
5114       (beginning-of-line)
5115       (setq end (point-marker))
5116       (goto-char opoint)                ;And off the fold heading
5117       (forward-line 1)
5118       (setq beg (point))
5119       (setq comment (concat comment-start id))
5120       (cond
5121        (mode-elt
5122         (setq ret
5123               (if uncomment
5124                   (funcall (nth 2 mode-elt) (point) end)
5125                 (funcall (nth 1 mode-elt) (point) end)))
5126         (goto-char (cdr ret)))
5127        (uncomment
5128         (while (< (point) (marker-position end))
5129           (if (looking-at comment)
5130               (delete-region (point) (match-end 0)))
5131           (forward-line 1)))
5132        (t
5133         (while (< (point) (marker-position end))
5134           (if (not (looking-at comment))
5135               (insert comment))
5136           (forward-line 1))))
5137       (setq end nil)                    ;kill marker
5138       ;;  Remove the possible tag from the fold name line
5139       (goto-char opoint)
5140       (setq id (concat (or comment-start "") id (or comment-end "")))
5141       (if (re-search-forward (regexp-quote id) beg t)
5142           (delete-region (match-beginning 0)  (match-end 0)))
5143       (when (null uncomment)
5144         (end-of-line)
5145         (insert id))
5146       (if closed
5147           (folding-hide-current-entry))
5148       (goto-char opoint))))
5149
5150 (defun folding-convert-to-major-folds ()
5151   "Convert fold mark items according to `major-mode'.
5152 This function replaces all fold markings }}} and {{{
5153 with major mode's fold marks.
5154
5155 As a side effect also corrects all foldings to standard notation.
5156 Eg. following, where correct folding-beg should be \"#{{{ \"
5157 Note that /// marks foldings.
5158
5159   ///                  ;wrong fold
5160   #     ///           ;too many spaces, fold format error
5161   # ///title            ;ok, but title too close
5162
5163   produces
5164
5165   #///
5166   #///
5167   #/// title
5168
5169 You must 'unfold' whole buffer before using this function."
5170   (interactive)
5171   (let (case-fold-search
5172         (bm "{{{")                      ; begin match mark
5173         (em "}}}")                      ;
5174         el                              ; element
5175         b                               ; begin
5176         e                               ; end
5177         e2                              ; end2
5178         pp)
5179     (catch 'out                         ; is folding active/loaded ??
5180       (unless (setq el (folding-get-mode-marks major-mode))
5181         (throw 'out t))                 ; ** no mode found
5182       ;; ok , we're in business. Search whole buffer and replace.
5183       (setq b  (elt el 0)
5184             e  (elt el 1)
5185             e2 (or (elt el 2) ""))
5186       (save-excursion
5187         (goto-char (point-min))   ; start from the beginning of buffer
5188         (while (re-search-forward (regexp-quote bm) nil t)
5189           ;; set the end position for fold marker
5190           (setq pp (point))
5191           (beginning-of-line)
5192           (if (looking-at (regexp-quote b)) ; should be mode-marked; ok, ignore
5193               (goto-char pp)       ; note that beg-of-l cmd, move rexp
5194             (delete-region (point) pp)
5195             (insert b)
5196             (when (not (string= "" e2))
5197               (unless (looking-at (concat ".*" (regexp-quote e2)))
5198                 ;; replace with right fold mark
5199                 (end-of-line)
5200                 (insert e2)))))
5201         ;; handle end marks , identical func compared to prev.
5202         (goto-char (point-min))
5203         (while (re-search-forward (regexp-quote em)nil t)
5204           (setq pp (point))
5205           (beginning-of-line)
5206           (if (looking-at (regexp-quote e))
5207               (goto-char pp)
5208             (delete-region (point) (progn (end-of-line) (point)))
5209             (insert e)))))))
5210
5211 (defun folding-all-comment-blocks-in-region (beg end)
5212   "Put all comments in folds inside BEG END.
5213 Notice: Make sure there is no interfering folds inside the area,
5214 because the results may and up corrupted.
5215
5216 This only works for modes that DO NOT have `comment-end'.
5217 The `comment-start' must be left flushed in order to counted in.
5218
5219 After this
5220
5221     ;; comment
5222     ;; comment
5223
5224     code
5225
5226     ;; comment
5227     ;; comment
5228
5229     code
5230
5231 The result will be:
5232
5233     ;; {{{ 1
5234
5235     ;; comment
5236     ;; comment
5237
5238     ;; }}}
5239
5240     code
5241
5242     ;; {{{ 2
5243
5244     ;; comment
5245     ;; comment
5246
5247     ;; }}}
5248
5249     code"
5250   (interactive "*r")
5251
5252   (unless comment-start
5253     (error "Folding: Mode does not define `comment-start'"))
5254
5255   (when (and (stringp comment-end)
5256              (string-match "[^ \t]" comment-end))
5257     (error "Folding: Mode defines non-empty `comment-end'."))
5258   (let* ((count          0)
5259          (comment-regexp (concat "^" comment-start))
5260          (marker         (point-marker))
5261          done)
5262     (multiple-value-bind (left right ignore)
5263         (folding-get-mode-marks)
5264       ;; Bytecomp silencer: variable ignore bound but not referenced
5265       (if ignore (setq ignore ignore))
5266       ;; %%%{{{  --> "%%%"
5267       (string-match (concat (regexp-quote comment-start) "+") left)
5268       (save-excursion
5269         (goto-char beg)
5270         (beginning-of-line)
5271         (while (re-search-forward comment-regexp nil t)
5272           (move-marker marker (point))
5273           (setq done nil)
5274           (beginning-of-line)
5275           (forward-line -1)
5276           ;; 2 previous lines Must not contain FOLD beginning already
5277           (unless (looking-at (regexp-quote left))
5278             (forward-line -1)
5279             (unless (looking-at (regexp-quote left))
5280               (goto-char (marker-position marker))
5281               (beginning-of-line)
5282               (insert  left " " (int-to-string count) "\n\n")
5283               (incf count)
5284               (setq done t)))
5285           (goto-char (marker-position marker))
5286           (when done
5287             ;; Try finding pat of the comment block
5288             (if (not (re-search-forward "^[ \t]*$" nil t))
5289                 (goto-char end))
5290             (open-line 1)
5291             (forward-line 1)
5292             (insert right "\n")))))))
5293
5294 ;;}}}
5295 ;;{{{ code: Overlay support
5296
5297 (defun folding-use-overlays-p ()
5298   "Should folding use overlays?."
5299   (if folding-allow-overlays
5300       (if folding-xemacs-p
5301           ;;  See if we can load overlay.el library that comes in 19.15
5302           ;;  This call returns t or nil if load was successful
5303           ;;  Note: is there provide statement? Load is so radical
5304           ;;
5305           (load "overlay" 'noerr)
5306         t)))
5307
5308 (defun folding-flag-region (from to flag)
5309   "Hide or show lines from FROM to TO, according to FLAG.
5310 If FLAG is nil then text is shown, while if FLAG is t the text is hidden."
5311   (let ((inhibit-read-only t)
5312         overlay)
5313     (save-excursion
5314       (goto-char from)
5315       (end-of-line)
5316       (cond
5317        (flag
5318         (setq overlay (make-overlay (point) to))
5319         (folding-make-overlay-hidden overlay))
5320        (t
5321         (if (fboundp 'hs-discard-overlays)
5322             (funcall (symbol-function 'hs-discard-overlays)
5323                      (point) to 'invisible t)))))))
5324
5325 (defun folding-make-overlay-hidden (overlay)
5326   "Make OVERLAY hidden."
5327   (overlay-put overlay  'fold t)
5328   ;;  (overlay-put overlay 'intangible t)
5329   (overlay-put overlay 'invisible t)
5330   (overlay-put overlay 'owner 'folding))
5331
5332 (defun folding-narrow-aux (start end arg)
5333   "Narrow. Make overlay from `point-min' to START.
5334 And from END t `point-min'. If ARG is nil, delete overlays."
5335   (if (null arg)
5336       (cond
5337        (folding-narrow-overlays
5338         (delete-overlay (car folding-narrow-overlays))
5339         (delete-overlay (cdr folding-narrow-overlays))
5340         (setq folding-narrow-overlays nil)))
5341     (let ((overlay-beg (make-overlay (point-min) start))
5342           (overlay-end (make-overlay  end (point-max))))
5343       (overlay-put overlay-beg 'folding-narrow t)
5344       (overlay-put overlay-beg 'invisible t)
5345       (overlay-put overlay-beg 'owner 'folding)
5346       (overlay-put overlay-end 'folding-narrow t)
5347       (overlay-put overlay-end 'invisible t)
5348       (overlay-put overlay-end 'owner 'folding)
5349       (setq folding-narrow-overlays (cons overlay-beg  overlay-end)))))
5350
5351 ;;}}}
5352
5353 ;;{{{ code: end of file tag, provide
5354
5355 (folding-install)
5356
5357 (provide 'folding)
5358 (provide 'folding-isearch) ;; This used to be a separate package.
5359
5360 (run-hooks 'folding-load-hook)
5361
5362 ;;}}}
5363
5364 ;;; folding.el ends here