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