Initial Commit
[packages] / xemacs-packages / auctex / tex-fold.el
1 ;;; tex-fold.el --- Fold TeX macros.
2
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011-2012
4 ;;   Free Software Foundation, Inc.
5
6 ;; Author: Ralf Angeli <angeli@caeruleus.net>
7 ;; Maintainer: auctex-devel@gnu.org
8 ;; Created: 2004-07-04
9 ;; Keywords: tex, wp
10
11 ;; This file is part of AUCTeX.
12
13 ;; AUCTeX is free software; you can redistribute it and/or modify it
14 ;; under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
17
18 ;; AUCTeX is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 ;; General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with AUCTeX; see the file COPYING.  If not, write to the Free
25 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 ;; 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;; This file provides support for hiding and unhiding TeX, LaTeX,
31 ;; ContTeXt, Texinfo and similar macros and environments inside of
32 ;; AUCTeX.
33 ;;
34 ;; Caveats:
35 ;;
36 ;; The display string of content which should display part of itself
37 ;; is made by copying the text from the buffer together with its text
38 ;; properties.  If fontification has not happened when this is done
39 ;; (e.g. because of lazy or just-in-time font locking) the intended
40 ;; fontification will not show up.  Maybe this could be improved by
41 ;; using some sort of "lazy folding" or refreshing the window upon
42 ;; scrolling.  As a workaround fontification of the whole buffer
43 ;; currently is forced before folding it.
44
45 ;;; Code:
46
47 (when (featurep 'xemacs)
48   (require 'overlay))
49 (require 'tex)
50 (autoload 'LaTeX-forward-paragraph "latex")
51 (autoload 'LaTeX-backward-paragraph "latex")
52 (autoload 'LaTeX-find-matching-begin "latex")
53 (autoload 'LaTeX-find-matching-end "latex")
54 (autoload 'ConTeXt-find-matching-start "context")
55 (autoload 'ConTeXt-find-matching-stop "context")
56 (autoload 'Texinfo-find-env-start "tex-info")
57 (autoload 'Texinfo-find-env-end "tex-info")
58
59 (defgroup TeX-fold nil
60   "Fold TeX macros."
61   :group 'AUCTeX)
62
63 (defcustom TeX-fold-type-list '(env macro math)
64   "List of item types to consider when folding.
65 Valid items are the symbols 'env for environments, 'macro for
66 macros, 'math for math macros and 'comment for comments."
67   :type '(set (const :tag "Environments" env)
68               (const :tag "Macros" macro)
69               (const :tag "Math Macros" math)
70               (const :tag "Comments" comment))
71   :group 'TeX-fold)
72
73 (defcustom TeX-fold-macro-spec-list
74   `(("[f]" ("footnote" "marginpar"))
75     ("[c]" ("cite"))
76     ("[l]" ("label"))
77     ("[r]" ("ref" "pageref" "eqref"))
78     ("[i]" ("index" "glossary"))
79     ("[1]:||*" ("item"))
80     ("..." ("dots"))
81     ("(C)" ("copyright"))
82     ("(R)" ("textregistered"))
83     ("TM"  ("texttrademark"))
84     (1 ("part" "chapter" "section" "subsection" "subsubsection"
85         "paragraph" "subparagraph"
86         "part*" "chapter*" "section*" "subsection*" "subsubsection*"
87         "paragraph*" "subparagraph*"
88         "emph" "textit" "textsl" "textmd" "textrm" "textsf" "texttt"
89         "textbf" "textsc" "textup")))
90   "List of replacement specifiers and macros to fold.
91
92 The first element of each item can be a string, an integer or a
93 function symbol.  The second element is a list of macros two fold
94 without the leading backslash.
95
96 If the first element is a string, it will be used as a display
97 replacement for the whole macro.  Numbers in braces, brackets,
98 parens or angle brackets will be replaced by the respective macro
99 argument.  For example \"{1}\" will be replaced by the first
100 mandatory argument of the macro.  One can also define
101 alternatives within the specifier which are used if an argument
102 is not found.  Alternatives are separated by \"||\".  They are
103 most useful with optional arguments.  As an example, the default
104 specifier for \\item is \"[1]:||*\" which means that if there is
105 an optional argument, its value is shown followed by a colon.  If
106 there is no optional argument, only an asterisk is used as the
107 display string.
108
109 If the first element is an integer, the macro will be replaced by
110 the respective macro argument.
111
112 If the first element is a function symbol, the function will be
113 called with all mandatory arguments of the macro and the result
114 of the function call will be used as a replacement for the macro.
115
116 Setting this variable does not take effect immediately.  Use
117 Customize or reset the mode."
118   :type '(repeat (group (choice (string :tag "Display String")
119                                 (integer :tag "Number of argument" :value 1)
120                                 (function :tag "Function to execute"))
121                         (repeat :tag "Macros" (string))))
122   :group 'TeX-fold)
123
124 (defvar TeX-fold-macro-spec-list-internal nil
125   "Internal list of display strings and macros to fold.
126 Is updated when the TeX Fold mode is being activated and then
127 contains all constructs to fold for the given buffer or mode
128 respectively, i.e. contents of both `TeX-fold-macro-spec-list'
129 and <mode-prefix>-fold-macro-spec-list.")
130 (make-variable-buffer-local 'TeX-fold-macro-spec-list-internal)
131
132 (defcustom TeX-fold-env-spec-list
133   '(("[comment]" ("comment")))
134   "List of display strings and environments to fold."
135   :type '(repeat (group (choice (string :tag "Display String")
136                                 (integer :tag "Number of argument" :value 1))
137                         (repeat :tag "Environments" (string))))
138   :group 'TeX-fold)
139
140 (defvar TeX-fold-env-spec-list-internal nil
141   "Internal list of display strings and environments to fold.
142 Is updated when the TeX Fold mode is being activated and then
143 contains all constructs to fold for the given buffer or mode
144 respectively, i.e. contents of both `TeX-fold-env-spec-list'
145 and <mode-prefix>-fold-env-spec-list.")
146 (make-variable-buffer-local 'TeX-fold-env-spec-list-internal)
147
148 (defcustom TeX-fold-math-spec-list nil
149   "List of display strings and math macros to fold."
150   :type '(repeat (group (choice (string :tag "Display String")
151                                 (integer :tag "Number of argument" :value 1))
152                         (repeat :tag "Math Macros" (string))))
153   :group 'TeX-fold)
154
155 (defvar TeX-fold-math-spec-list-internal nil
156   "Internal list of display strings and math macros to fold.
157 Is updated when the TeX Fold mode is being activated and then
158 contains all constructs to fold for the given buffer or mode
159 respectively, i.e. contents of both `TeX-fold-math-spec-list'
160 and <mode-prefix>-fold-math-spec-list.")
161 (make-variable-buffer-local 'TeX-fold-math-spec-list-internal)
162
163 (defcustom TeX-fold-unspec-macro-display-string "[m]"
164   "Display string for unspecified macros.
165 This string will be displayed if a single macro is being hidden
166 which is not specified in `TeX-fold-macro-spec-list'."
167   :type '(string)
168   :group 'TeX-fold)
169
170 (defcustom TeX-fold-unspec-env-display-string "[env]"
171   "Display string for unspecified environments.
172 This string will be displayed if a single environment is being
173 hidden which is not specified in `TeX-fold-env-spec-list'."
174   :type '(string)
175   :group 'TeX-fold)
176
177 (defcustom TeX-fold-unspec-use-name t
178   "If non-nil use the name of an unspecified item as display string.
179 Set it to nil if you want to use the values of the variables
180 `TeX-fold-unspec-macro-display-string' or
181 `TeX-fold-unspec-env-display-string' respectively as a display
182 string for any unspecified macro or environment."
183   :type 'boolean
184   :group 'TeX-fold)
185
186 (defcustom TeX-fold-preserve-comments nil
187   "If non-nil do not fold in comments."
188   :type 'boolean
189   :group 'TeX-fold)
190
191 (defcustom TeX-fold-unfold-around-mark t
192   "Unfold text around the mark, if active."
193   :type 'boolean
194   :group 'TeX-fold)
195
196 (defcustom TeX-fold-help-echo-max-length 70
197   "Maximum length of help echo message for folded overlays.
198 Set it to zero in order to disable help echos."
199   :type 'integer
200   :group 'TeX-fold)
201
202 (defcustom TeX-fold-force-fontify t
203   "Force the buffer to be fully fontified by folding it."
204   :group 'TeX-fold
205   :type 'boolean)
206
207 (defcustom TeX-fold-auto nil
208   "If non-nil, fold macros automatically after `TeX-insert-macro'."
209   :group 'TeX-fold
210   :type 'boolean)
211
212 (defface TeX-fold-folded-face
213   '((((class color) (background light))
214      (:foreground "SlateBlue"))
215     (((class color) (background dark))
216      (:foreground "SlateBlue1"))
217     (((class grayscale) (background light))
218      (:foreground "DimGray"))
219     (((class grayscale) (background dark))
220      (:foreground "LightGray"))
221     (t (:slant italic)))
222   "Face for the display string of folded content."
223   :group 'TeX-fold)
224
225 (defvar TeX-fold-folded-face 'TeX-fold-folded-face
226   "Face for the display string of folded content.")
227
228 (defface TeX-fold-unfolded-face
229   '((((class color) (background light))
230      (:background "#f2f0fd"))
231     (((class color) (background dark))
232      (:background "#38405d"))
233     (((class grayscale) (background light))
234      (:background "LightGray"))
235     (((class grayscale) (background dark))
236      (:background "DimGray"))
237     (t (:inverse-video t)))
238   "Face for folded content when it is temporarily opened."
239   :group 'TeX-fold)
240
241 (defvar TeX-fold-unfolded-face 'TeX-fold-unfolded-face
242   "Face for folded content when it is temporarily opened.")
243
244 (defvar TeX-fold-ellipsis "..."
245   "String used as display string for overlays instead of a zero-length string.")
246
247 (defvar TeX-fold-open-spots nil)
248 (make-variable-buffer-local 'TeX-fold-open-spots)
249
250 (defcustom TeX-fold-command-prefix "\C-c\C-o"
251   "Prefix key to use for commands in TeX Fold mode.
252 The value of this variable is checked as part of loading TeX Fold mode.
253 After that, changing the prefix key requires manipulating keymaps."
254   :type 'string
255   :group 'TeX-fold)
256
257 (defvar TeX-fold-keymap
258   (let ((map (make-sparse-keymap)))
259     (define-key map "\C-o" 'TeX-fold-dwim)
260     (define-key map "\C-b" 'TeX-fold-buffer)
261     (define-key map "\C-r" 'TeX-fold-region)
262     (define-key map "\C-p" 'TeX-fold-paragraph)
263     (define-key map "\C-m" 'TeX-fold-macro)
264     (define-key map "\C-e" 'TeX-fold-env)
265     (define-key map "\C-c" 'TeX-fold-comment)
266     (define-key map "b"    'TeX-fold-clearout-buffer)
267     (define-key map "r"    'TeX-fold-clearout-region)
268     (define-key map "p"    'TeX-fold-clearout-paragraph)
269     (define-key map "i"    'TeX-fold-clearout-item)
270     map))
271
272
273 ;;; Folding
274
275 (defun TeX-fold-dwim ()
276   "Hide or show items according to the current context.
277 If there is folded content, unfold it.  If there is a marked
278 region, fold all configured content in this region.  If there is
279 no folded content but a macro or environment, fold it."
280   (interactive)
281   (cond ((TeX-fold-clearout-item))
282         ((TeX-active-mark) (TeX-fold-region (mark) (point)))
283         ((TeX-fold-item 'macro))
284         ((TeX-fold-item 'math))
285         ((TeX-fold-item 'env))
286         ((TeX-fold-comment))))
287
288 (defun TeX-fold-buffer ()
289   "Hide all configured macros and environments in the current buffer.
290 The relevant macros are specified in the variable `TeX-fold-macro-spec-list'
291 and `TeX-fold-math-spec-list', and environments in `TeX-fold-env-spec-list'."
292   (interactive)
293   (TeX-fold-clearout-region (point-min) (point-max))
294   (when (and TeX-fold-force-fontify
295              (boundp 'jit-lock-mode)
296              jit-lock-mode
297              (fboundp 'jit-lock-fontify-now))
298     ;; We force fontification here only because it should rarely be
299     ;; needed for the other folding commands.
300     (jit-lock-fontify-now))
301   (TeX-fold-region (point-min) (point-max)))
302
303 (defun TeX-fold-paragraph ()
304   "Hide all configured macros and environments in the current paragraph.
305 The relevant macros are specified in the variable `TeX-fold-macro-spec-list'
306 and `TeX-fold-math-spec-list', and environments in `TeX-fold-env-spec-list'."
307   (interactive)
308   (save-excursion
309     (let ((end (progn (LaTeX-forward-paragraph) (point)))
310           (start (progn (LaTeX-backward-paragraph) (point))))
311       (TeX-fold-clearout-region start end)
312       (TeX-fold-region start end))))
313
314 (defun TeX-fold-region (start end)
315   "Fold all items in region from START to END."
316   (interactive "r")
317   (when (and (memq 'env TeX-fold-type-list)
318              (not (eq major-mode 'plain-tex-mode)))
319     (TeX-fold-region-macro-or-env start end 'env))
320   (when (memq 'macro TeX-fold-type-list)
321     (TeX-fold-region-macro-or-env start end 'macro))
322   (when (memq 'math TeX-fold-type-list)
323     (TeX-fold-region-macro-or-env start end 'math))
324   (when (memq 'comment TeX-fold-type-list)
325     (TeX-fold-region-comment start end)))
326
327 (defun TeX-fold-region-macro-or-env (start end type)
328   "Fold all items of type TYPE in region from START to END.
329 TYPE can be one of the symbols 'env for environments, 'macro
330 for macros and 'math for math macros."
331   (save-excursion
332     (let (fold-list item-list regexp)
333       (dolist (item (cond ((eq type 'env) TeX-fold-env-spec-list-internal)
334                           ((eq type 'math) TeX-fold-math-spec-list-internal)
335                           (t TeX-fold-macro-spec-list-internal)))
336         (dolist (i (cadr item))
337           (add-to-list 'fold-list (list i (car item)))
338           (add-to-list 'item-list i)))
339       (when item-list
340         (setq regexp (cond ((and (eq type 'env)
341                                  (eq major-mode 'context-mode))
342                             (concat (regexp-quote TeX-esc)
343                                     "start" (regexp-opt item-list t)))
344                            ((and (eq type 'env)
345                                  (eq major-mode 'texinfo-mode))
346                             (concat (regexp-quote TeX-esc)
347                                     (regexp-opt item-list t)))
348                            ((eq type 'env)
349                             (concat (regexp-quote TeX-esc)
350                                     "begin[ \t]*{"
351                                     (regexp-opt item-list t) "}"))
352                            (t
353                             (concat (regexp-quote TeX-esc)
354                                     (regexp-opt item-list t)))))
355         (save-restriction
356           (narrow-to-region start end)
357           ;; Start from the bottom so that it is easier to prioritize
358           ;; nested macros.
359           (goto-char (point-max))
360           (let ((case-fold-search nil)
361                 item-name)
362             (while (re-search-backward regexp nil t)
363               (setq item-name (match-string 1))
364               (unless (or (and TeX-fold-preserve-comments
365                                (TeX-in-commented-line))
366                           ;; Make sure no partially matched macros are
367                           ;; folded.  For macros consisting of letters
368                           ;; this means there should be none of the
369                           ;; characters [A-Za-z@*] after the matched
370                           ;; string.  Single-char non-letter macros like
371                           ;; \, don't have this requirement.
372                           (and (memq type '(macro math))
373                                (save-match-data
374                                  (string-match "[A-Za-z]" item-name))
375                                (save-match-data
376                                  (string-match "[A-Za-z@*]"
377                                                (string (char-after
378                                                         (match-end 0)))))))
379                 (let* ((item-start (match-beginning 0))
380                        (display-string-spec (cadr (assoc item-name
381                                                          fold-list)))
382                        (item-end (TeX-fold-item-end item-start type))
383                        (ov (TeX-fold-make-overlay item-start item-end type
384                                                   display-string-spec)))
385                   (TeX-fold-hide-item ov))))))))))
386
387 (defun TeX-fold-region-comment (start end)
388   "Fold all comments in region from START to END."
389   (save-excursion
390     (goto-char start)
391     (let (beg)
392       (while (setq beg (TeX-search-forward-comment-start end))
393         (goto-char beg)
394         ;; Determine the start of the region to be folded just behind
395         ;; the comment starter.
396         (looking-at TeX-comment-start-regexp)
397         (setq beg (match-end 0))
398         ;; Search for the end of the comment.
399         (while (TeX-comment-forward))
400         (end-of-line 0)
401         ;; Hide the whole region.
402         (TeX-fold-hide-item (TeX-fold-make-overlay beg (point) 'comment
403                                                    TeX-fold-ellipsis))))))
404
405 (defun TeX-fold-macro ()
406   "Hide the macro on which point currently is located."
407   (interactive)
408   (unless (TeX-fold-item 'macro)
409     (message "No macro found")))
410
411 (defun TeX-fold-math ()
412   "Hide the math macro on which point currently is located."
413   (interactive)
414   (unless (TeX-fold-item 'math)
415     (message "No macro found")))
416
417 (defun TeX-fold-env ()
418   "Hide the environment on which point currently is located."
419   (interactive)
420   (unless (TeX-fold-item 'env)
421     (message "No environment found")))
422
423 (defun TeX-fold-comment ()
424   "Hide the comment on which point currently is located."
425   (interactive)
426   (unless (TeX-fold-comment-do)
427     (message "No comment found")))
428
429 (defun TeX-fold-item (type)
430   "Hide the item on which point currently is located.
431 TYPE specifies the type of item and can be one of the symbols
432 'env for environments, 'macro for macros or 'math for math
433 macros.
434 Return non-nil if an item was found and folded, nil otherwise."
435   (if (and (eq type 'env)
436            (eq major-mode 'plain-tex-mode))
437       (message
438        "Folding of environments is not supported in current mode")
439     (let ((item-start (cond ((and (eq type 'env)
440                                   (eq major-mode 'context-mode))
441                              (save-excursion
442                                (ConTeXt-find-matching-start) (point)))
443                             ((and (eq type 'env)
444                                   (eq major-mode 'texinfo-mode))
445                              (save-excursion
446                                (Texinfo-find-env-start) (point)))
447                             ((eq type 'env)
448                              (condition-case nil
449                                  (save-excursion
450                                    (LaTeX-find-matching-begin) (point))
451                                (error nil)))
452                             (t
453                              (TeX-find-macro-start)))))
454       (when item-start
455         (let* ((item-name (save-excursion
456                             (goto-char item-start)
457                             (looking-at
458                              (cond ((and (eq type 'env)
459                                          (eq major-mode 'context-mode))
460                                     (concat (regexp-quote TeX-esc)
461                                             "start\\([A-Za-z]+\\)"))
462                                    ((and (eq type 'env)
463                                          (eq major-mode 'texinfo-mode))
464                                     (concat (regexp-quote TeX-esc)
465                                             "\\([A-Za-z]+\\)"))
466                                    ((eq type 'env)
467                                     (concat (regexp-quote TeX-esc)
468                                             "begin[ \t]*{"
469                                             "\\([A-Za-z]+\\)}"))
470                                    (t
471                                     (concat (regexp-quote TeX-esc)
472                                             "\\([A-Za-z@*]+\\)"))))
473                             (if (fboundp 'match-string-no-properties)
474                                 (match-string-no-properties 1)
475                               (match-string 1))))
476                (fold-list (cond ((eq type 'env) TeX-fold-env-spec-list-internal)
477                                 ((eq type 'math)
478                                  TeX-fold-math-spec-list-internal)
479                                 (t TeX-fold-macro-spec-list-internal)))
480                fold-item
481                (display-string-spec
482                 (or (catch 'found
483                       (while fold-list
484                         (setq fold-item (car fold-list))
485                         (setq fold-list (cdr fold-list))
486                         (when (member item-name (cadr fold-item))
487                           (throw 'found (car fold-item)))))
488                     ;; Item is not specified.
489                     (if TeX-fold-unspec-use-name
490                         (concat "[" item-name "]")
491                       (if (eq type 'env)
492                           TeX-fold-unspec-env-display-string
493                         TeX-fold-unspec-macro-display-string))))
494                (item-end (TeX-fold-item-end item-start type))
495                (ov (TeX-fold-make-overlay item-start item-end type
496                                           display-string-spec)))
497           (TeX-fold-hide-item ov))))))
498
499 (defun TeX-fold-comment-do ()
500   "Hide the comment on which point currently is located.
501 This is the function doing the work for `TeX-fold-comment'.  It
502 is an internal function communicating with return values rather
503 than with messages for the user.
504 Return non-nil if a comment was found and folded, nil otherwise."
505   (if (and (not (TeX-in-comment)) (not (TeX-in-line-comment)))
506       nil
507     (let (beg)
508       (save-excursion
509         (while (progn
510                  (beginning-of-line 0)
511                  (and (TeX-in-line-comment)
512                       (not (bobp)))))
513         (goto-char (TeX-search-forward-comment-start (line-end-position 2)))
514         (looking-at TeX-comment-start-regexp)
515         (setq beg (match-end 0))
516         (while (TeX-comment-forward))
517         (end-of-line 0)
518         (when (> (point) beg)
519           (TeX-fold-hide-item (TeX-fold-make-overlay beg (point) 'comment
520                                                      TeX-fold-ellipsis)))))))
521
522
523 ;;; Utilities
524
525 (defun TeX-fold-make-overlay (ov-start ov-end type display-string-spec)
526   "Make a TeX-fold overlay extending from OV-START to OV-END.
527 TYPE is a symbol which is used to describe the content to hide
528 and may be 'macro for macros, 'math for math macro and 'env for
529 environments.
530 DISPLAY-STRING-SPEC is the original specification of the display
531 string in the variables `TeX-fold-macro-spec-list' or
532 `TeX-fold-env-spec-list' and may be a string or an integer."
533   ;; Calculate priority before the overlay is instantiated.  We don't
534   ;; want `TeX-overlay-prioritize' to pick up a non-prioritized one.
535   (let ((priority (TeX-overlay-prioritize ov-start ov-end))
536         (ov (make-overlay ov-start ov-end (current-buffer) t nil)))
537     (overlay-put ov 'category 'TeX-fold)
538     (overlay-put ov 'priority priority)
539     (overlay-put ov 'evaporate t)
540     (overlay-put ov 'TeX-fold-type type)
541     (overlay-put ov 'TeX-fold-display-string-spec display-string-spec)
542     ov))
543
544 (defun TeX-fold-item-end (start type)
545   "Return the end of an item of type TYPE starting at START.
546 TYPE can be either 'env for environments, 'macro for macros or
547 'math for math macros."
548   (save-excursion
549     (cond ((and (eq type 'env)
550                 (eq major-mode 'context-mode))
551            (goto-char start)
552            (ConTeXt-find-matching-stop)
553            (point))
554           ((and (eq type 'env)
555                 (eq major-mode 'texinfo-mode))
556            (goto-char (1+ start))
557            (Texinfo-find-env-end)
558            (point))
559           ((eq type 'env)
560            (goto-char (1+ start))
561            (LaTeX-find-matching-end)
562            (point))
563           (t
564            (goto-char start)
565            (TeX-find-macro-end)))))
566
567 (defun TeX-fold-overfull-p (ov-start ov-end display-string)
568   "Return t if an overfull line will result after adding an overlay.
569 The overlay extends from OV-START to OV-END and will display the
570 string DISPLAY-STRING."
571   (and (not (featurep 'xemacs)) ; Linebreaks in glyphs don't
572                                 ; work in XEmacs anyway.
573        (save-excursion
574          (goto-char ov-end)
575          (search-backward "\n" ov-start t))
576        (not (string-match "\n" display-string))
577        (> (+ (- ov-start
578                 (save-excursion
579                   (goto-char ov-start)
580                   (line-beginning-position)))
581              (length display-string)
582              (- (save-excursion
583                   (goto-char ov-end)
584                   (line-end-position))
585                 ov-end))
586           (current-fill-column))))
587
588 (defun TeX-fold-macro-nth-arg (n macro-start &optional macro-end delims)
589   "Return a property list of the argument number N of a macro.
590 The start of the macro to examine is given by MACRO-START, its
591 end optionally by MACRO-END.  With DELIMS the type of delimiters
592 can be specified as a cons cell containing the opening char as
593 the car and the closing char as the cdr.  The chars have to have
594 opening and closing syntax as defined in
595 `TeX-search-syntax-table'.
596
597 The first item in the returned list is the string specified in
598 the argument, the second item may be a face if the argument
599 string was fontified.  In Emacs the string holds text properties
600 as well, so the second item is always nil.  In XEmacs the string
601 does not enclose any faces, so these are given in the second item
602 of the resulting list."
603   (save-excursion
604     (let* ((macro-end (or macro-end
605                           (save-excursion (goto-char macro-start)
606                                           (TeX-find-macro-end))))
607            (open-char (if delims (car delims) ?{))
608            (open-string (char-to-string open-char))
609            (close-char (if delims (cdr delims) ?}))
610            (close-string (char-to-string close-char))
611            content-start content-end)
612       (goto-char macro-start)
613       (if (condition-case nil
614               (progn
615                 (while (> n 0)
616                   (skip-chars-forward (concat "^" open-string) macro-end)
617                   (when (= (point) macro-end)
618                     (error nil))
619                   (setq content-start (progn
620                                         (skip-chars-forward
621                                          (concat open-string " \t"))
622                                         (point)))
623                   (goto-char
624                    (if delims
625                        (with-syntax-table
626                            (TeX-search-syntax-table open-char close-char)
627                          (scan-lists (point) 1 1))
628                      (TeX-find-closing-brace)))
629                   (setq content-end (save-excursion
630                                       (backward-char)
631                                       (skip-chars-backward " \t")
632                                       (point)))
633                   (setq n (1- n)))
634                 t)
635             (error nil))
636           (list (TeX-fold-buffer-substring content-start content-end)
637                 (when (and (featurep 'xemacs)
638                            (extent-at content-start))
639                   ;; A glyph in XEmacs does not seem to be able to hold more
640                   ;; than one face, so we just use the first one we get.
641                   (car (extent-property (extent-at content-start) 'face))))
642         nil))))
643
644 (defun TeX-fold-buffer-substring (start end)
645   "Return the contents of buffer from START to END as a string.
646 Like `buffer-substring' but copy overlay display strings as well."
647   ;; Swap values of `start' and `end' if necessary.
648   (when (> start end) (let ((tmp start)) (setq start end end tmp)))
649   (let ((overlays (overlays-in start end))
650         result)
651     ;; Get rid of overlays not under our control or not completely
652     ;; inside the specified region.
653     (dolist (ov overlays)
654       (when (or (not (eq (overlay-get ov 'category) 'TeX-fold))
655                 (< (overlay-start ov) start)
656                 (> (overlay-end ov) end))
657         (setq overlays (remove ov overlays))))
658     (if (null overlays)
659         (buffer-substring start end)
660       ;; Sort list according to ascending starts.
661       (setq overlays (sort (copy-sequence overlays)
662                            (lambda (a b)
663                              (< (overlay-start a) (overlay-start b)))))
664       ;; Get the string from the start of the region up to the first overlay.
665       (setq result (buffer-substring start (overlay-start (car overlays))))
666       (let (ov)
667         (while overlays
668           (setq ov (car overlays)
669                 overlays (cdr overlays))
670           ;; Add the display string of the overlay.
671           (setq result (concat result (overlay-get ov 'display)))
672           ;; Remove overlays contained in the current one.
673           (dolist (elt overlays)
674             (when (< (overlay-start elt) (overlay-end ov))
675               (setq overlays (remove elt overlays))))
676           ;; Add the string from the end of the current overlay up to
677           ;; the next overlay or the end of the specified region.
678           (setq result (concat result (buffer-substring (overlay-end ov)
679                                                         (if overlays
680                                                             (overlay-start
681                                                              (car overlays))
682                                                           end))))))
683       result)))
684
685 (defun TeX-fold-make-help-echo (start end)
686   "Return a string to be used as the help echo of folded overlays.
687 The text between START and END will be used for this but cropped
688 to the length defined by `TeX-fold-help-echo-max-length'.  Line
689 breaks will be replaced by spaces."
690   (let* ((spill (+ start TeX-fold-help-echo-max-length))
691          (lines (split-string (buffer-substring start (min end spill)) "\n"))
692          (result (pop lines)))
693     (dolist (line lines)
694       ;; Strip leading whitespace
695       (when (string-match "^[ \t]+" line)
696         (setq line (replace-match "" nil nil line)))
697       ;; Strip trailing whitespace
698       (when (string-match "[ \t]+$" line)
699         (setq line (replace-match "" nil nil line)))
700       (setq result (concat result " " line)))
701     (when (> end spill) (setq result (concat result "...")))
702     result))
703
704 (defun TeX-fold-update-at-point ()
705   "Update all TeX-fold overlays at point displaying computed content."
706   (let (overlays)
707     ;; Get all overlays at point under our control.
708     (dolist (ov (overlays-at (point)))
709       (when (and (eq (overlay-get ov 'category) 'TeX-fold)
710                  (numberp (overlay-get ov 'TeX-fold-display-string-spec)))
711         (add-to-list 'overlays ov)))
712     (when overlays
713       ;; Sort list according to descending starts.
714       (setq overlays (sort (copy-sequence overlays)
715                            (lambda (a b)
716                              (> (overlay-start a) (overlay-start b)))))
717       (dolist (ov overlays)
718         (TeX-fold-hide-item ov)))))
719
720
721 ;;; Removal
722
723 (defun TeX-fold-clearout-buffer ()
724   "Permanently show all macros in the buffer."
725   (interactive)
726   (TeX-fold-clearout-region (point-min) (point-max)))
727
728 (defun TeX-fold-clearout-paragraph ()
729   "Permanently show all macros in the paragraph point is located in."
730   (interactive)
731   (save-excursion
732     (let ((end (progn (LaTeX-forward-paragraph) (point)))
733           (start (progn (LaTeX-backward-paragraph) (point))))
734       (TeX-fold-clearout-region start end))))
735
736 (defun TeX-fold-clearout-region (start end)
737   "Permanently show all macros in region starting at START and ending at END."
738   (interactive "r")
739   (let ((overlays (overlays-in start end)))
740     (TeX-fold-remove-overlays overlays)))
741
742 (defun TeX-fold-clearout-item ()
743   "Permanently show the macro on which point currently is located."
744   (interactive)
745   (let ((overlays (overlays-at (point))))
746     (TeX-fold-remove-overlays overlays)))
747
748 (defun TeX-fold-remove-overlays (overlays)
749   "Remove all overlays set by TeX-fold in OVERLAYS.
750 Return non-nil if a removal happened, nil otherwise."
751   (let (found)
752     (while overlays
753       (when (eq (overlay-get (car overlays) 'category) 'TeX-fold)
754         (delete-overlay (car overlays))
755         (setq found t))
756       (setq overlays (cdr overlays)))
757     found))
758
759
760 ;;; Toggling
761
762 (defun TeX-fold-expand-spec (spec ov-start ov-end)
763   "Expand instances of {<num>}, [<num>], <<num>>, and (<num>).
764 Replace them with the respective macro argument."
765   (let ((spec-list (split-string spec "||"))
766         (delims '((?{ . ?}) (?[ . ?]) (?< . ?>) (?\( . ?\))))
767         index success)
768     (catch 'success
769       ;; Iterate over alternatives.
770       (dolist (elt spec-list)
771         (setq spec elt
772               index nil)
773         ;; Find and expand every placeholder.
774         (while (and (string-match "\\([[{<]\\)\\([1-9]\\)\\([]}>]\\)" elt index)
775                     ;; Does the closing delim match the opening one?
776                     (string-equal
777                      (match-string 3 elt)
778                      (char-to-string
779                       (cdr (assq (string-to-char (match-string 1 elt))
780                                  delims)))))
781           (setq index (match-end 0))
782           (let ((arg (car (save-match-data
783                             ;; Get the argument.
784                             (TeX-fold-macro-nth-arg
785                              (string-to-number (match-string 2 elt))
786                              ov-start ov-end
787                              (assoc (string-to-char (match-string 1 elt))
788                                     delims))))))
789             (when arg (setq success t))
790             ;; Replace the placeholder in the string.
791             (setq elt (replace-match (or arg TeX-fold-ellipsis) nil t elt)
792                   index (+ index (- (length elt) (length spec)))
793                   spec elt)))
794         (when success (throw 'success nil))))
795     spec))
796
797 (defun TeX-fold-hide-item (ov)
798   "Hide a single macro or environment.
799 That means, put respective properties onto overlay OV."
800   (let* ((ov-start (overlay-start ov))
801          (ov-end (overlay-end ov))
802          (spec (overlay-get ov 'TeX-fold-display-string-spec))
803          (computed (cond
804                     ((stringp spec)
805                      (TeX-fold-expand-spec spec ov-start ov-end))
806                     ((functionp spec)
807                      (let (arg arg-list
808                            (n 1))
809                        (while (setq arg (TeX-fold-macro-nth-arg
810                                          n ov-start ov-end))
811                          (add-to-list 'arg-list (car arg) t)
812                          (setq n (1+ n)))
813                        (or (condition-case nil
814                                (apply spec arg-list)
815                              (error nil))
816                            "[Error: No content or function found]")))
817                     (t (or (TeX-fold-macro-nth-arg spec ov-start ov-end)
818                            "[Error: No content found]"))))
819          (display-string (if (listp computed) (car computed) computed))
820          (face (when (listp computed) (cadr computed))))
821     ;; Cater for zero-length display strings.
822     (when (string= display-string "") (setq display-string TeX-fold-ellipsis))
823     ;; Add a linebreak to the display string and adjust the overlay end
824     ;; in case of an overfull line.
825     (when (TeX-fold-overfull-p ov-start ov-end display-string)
826       (setq display-string (concat display-string "\n"))
827       (move-overlay ov ov-start (save-excursion
828                                   (goto-char ov-end)
829                                   (skip-chars-forward " \t")
830                                   (point))))
831     (overlay-put ov 'mouse-face 'highlight)
832     (overlay-put ov 'display display-string)
833     (if (featurep 'xemacs)
834         (let ((glyph (make-glyph (if (listp display-string)
835                                      (car display-string)
836                                    display-string))))
837           (overlay-put ov 'invisible t)
838           (when font-lock-mode
839             (if face
840                 (set-glyph-property glyph 'face face)
841               (set-glyph-property glyph 'face TeX-fold-folded-face)))
842           (set-extent-property ov 'end-glyph glyph))
843       (when font-lock-mode
844         (overlay-put ov 'face TeX-fold-folded-face))
845       (unless (zerop TeX-fold-help-echo-max-length)
846         (overlay-put ov 'help-echo (TeX-fold-make-help-echo
847                                     (overlay-start ov) (overlay-end ov)))))))
848
849 (defun TeX-fold-show-item (ov)
850   "Show a single LaTeX macro or environment.
851 Remove the respective properties from the overlay OV."
852   (overlay-put ov 'mouse-face nil)
853   (if (featurep 'xemacs)
854       (progn
855         (set-extent-property ov 'end-glyph nil)
856         (overlay-put ov 'invisible nil))
857     (overlay-put ov 'display nil)
858     (overlay-put ov 'help-echo nil)
859     (when font-lock-mode
860       (overlay-put ov 'face TeX-fold-unfolded-face))))
861
862 ;; Copy and adaption of `reveal-post-command' from reveal.el in GNU
863 ;; Emacs on 2004-07-04.
864 (defun TeX-fold-post-command ()
865   ;; `with-local-quit' is not supported in XEmacs.
866   (condition-case nil
867       (let ((inhibit-quit nil))
868         (condition-case err
869             (let* ((spots (TeX-fold-partition-list
870                            (lambda (x)
871                              ;; We refresh any spot in the current
872                              ;; window as well as any spots associated
873                              ;; with a dead window or a window which
874                              ;; does not show this buffer any more.
875                              (or (eq (car x) (selected-window))
876                                  (not (window-live-p (car x)))
877                                  (not (eq (window-buffer (car x))
878                                           (current-buffer)))))
879                            TeX-fold-open-spots))
880                    (old-ols (mapcar 'cdr (car spots))))
881               (setq TeX-fold-open-spots (cdr spots))
882               (when (or (and (boundp 'disable-point-adjustment)
883                              disable-point-adjustment)
884                         (and (boundp 'global-disable-point-adjustment)
885                              global-disable-point-adjustment)
886                         ;; See preview.el on how to make this configurable.
887                         (memq this-command
888                               (list (key-binding [left]) (key-binding [right])
889                                     'backward-char 'forward-char
890                                     'mouse-set-point)))
891                 ;; Open new overlays.
892                 (dolist (ol (nconc (when (and TeX-fold-unfold-around-mark
893                                               (boundp 'mark-active)
894                                               mark-active)
895                                      (overlays-at (mark)))
896                                    (overlays-at (point))))
897                   (when (eq (overlay-get ol 'category) 'TeX-fold)
898                     (push (cons (selected-window) ol) TeX-fold-open-spots)
899                     (setq old-ols (delq ol old-ols))
900                     (TeX-fold-show-item ol))))
901               ;; Close old overlays.
902               (dolist (ol old-ols)
903                 (when (and (eq (current-buffer) (overlay-buffer ol))
904                            (not (rassq ol TeX-fold-open-spots))
905                            (or (not (featurep 'xemacs))
906                                (and (featurep 'xemacs)
907                                     (not (extent-detached-p ol)))))
908                   (if (and (>= (point) (overlay-start ol))
909                            (<= (point) (overlay-end ol)))
910                       ;; Still near the overlay: keep it open.
911                       (push (cons (selected-window) ol) TeX-fold-open-spots)
912                     ;; Really close it.
913                     (TeX-fold-hide-item ol)))))
914           (error (message "TeX-fold: %s" err))))
915     (quit (setq quit-flag t))))
916
917
918 ;;; Misc
919
920 ;; Copy and adaption of `cvs-partition' from pcvs-util.el in GNU Emacs
921 ;; on 2004-07-05 to make tex-fold.el mainly self-contained.
922 (defun TeX-fold-partition-list (p l)
923   "Partition a list L into two lists based on predicate P.
924 The function returns a `cons' cell where the `car' contains
925 elements of L for which P is true while the `cdr' contains
926 the other elements.  The ordering among elements is maintained."
927   (let (car cdr)
928     (dolist (x l)
929       (if (funcall p x) (push x car) (push x cdr)))
930     (cons (nreverse car) (nreverse cdr))))
931
932
933 ;;; The mode
934
935 ;; This autoload cookie had to be changed because of XEmacs.  This is
936 ;; very dissatisfactory, because we now don't have the full doc string
937 ;; available to tell people what to expect when using this mode before
938 ;; loading it.
939
940 ;;;###autoload (autoload 'TeX-fold-mode "tex-fold" "Minor mode for hiding and revealing macros and environments." t)
941 (define-minor-mode TeX-fold-mode
942   "Minor mode for hiding and revealing macros and environments.
943
944 Called interactively, with no prefix argument, toggle the mode.
945 With universal prefix ARG (or if ARG is nil) turn mode on.
946 With zero or negative ARG turn mode off."
947   nil nil (list (cons TeX-fold-command-prefix TeX-fold-keymap))
948   (if TeX-fold-mode
949       (progn
950         (set (make-local-variable 'search-invisible) t)
951         (add-hook 'post-command-hook 'TeX-fold-post-command nil t)
952         (add-hook 'LaTeX-fill-newline-hook 'TeX-fold-update-at-point nil t)
953         (add-hook 'TeX-after-insert-macro-hook
954                   (lambda ()
955                     (when (and TeX-fold-mode TeX-fold-auto)
956                       (save-excursion
957                         (backward-char)
958                         (or (TeX-fold-item 'macro)
959                             (TeX-fold-item 'math)
960                             (TeX-fold-item 'env))))))
961         ;; Update the `TeX-fold-*-spec-list-internal' variables.
962         (dolist (elt '("macro" "env" "math"))
963           (set (intern (format "TeX-fold-%s-spec-list-internal" elt))
964                ;; Append the value of `TeX-fold-*-spec-list' to the
965                ;; mode-specific `<mode-prefix>-fold-*-spec-list' variable.
966                (append (symbol-value (intern (format "TeX-fold-%s-spec-list"
967                                                      elt)))
968                        (let ((symbol (intern (format "%s-fold-%s-spec-list"
969                                                      (TeX-mode-prefix) elt))))
970                          (when (boundp symbol)
971                            (symbol-value symbol)))))))
972     (kill-local-variable 'search-invisible)
973     (remove-hook 'post-command-hook 'TeX-fold-post-command t)
974     (remove-hook 'LaTeX-fill-newline-hook 'TeX-fold-update-at-point t)
975     (TeX-fold-clearout-buffer))
976   (TeX-set-mode-name))
977
978 ;;;###autoload
979 (defalias 'tex-fold-mode 'TeX-fold-mode)
980
981 (provide 'tex-fold)
982
983 ;;; tex-fold.el ends here