Initial Commit
[packages] / xemacs-packages / auctex / texmathp.el
1 ;;; texmathp.el -- Code to check if point is inside LaTeX math environment
2
3 ;; Copyright (C) 1998, 2004 Free Software Foundation, Inc.
4
5 ;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
6 ;; Maintainer: auctex-devel@gnu.org
7 ;; Keywords: tex
8
9 ;; This file is part of AUCTeX.
10
11 ;; AUCTeX is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
15
16 ;; AUCTeX is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with AUCTeX; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
24 ;; 02110-1301, USA.
25
26 ;;; Commentary:
27 ;;
28 ;;  This code provides a function to determine if point in a buffer is
29 ;;  inside a (La)TeX math environment.  This is not trivial since many
30 ;;  different ways are used to switch between the two.  Examples:
31 ;;
32 ;;    \begin{equation}  ... \end{equation}
33 ;;    $ ... $
34 ;;    $$ ... $$
35 ;;    \[ ... \]
36 ;;    \ensuremath{...}
37 ;;    \mbox{...}
38 ;;
39 ;;  To install, put this file on your load-path and compile it.
40 ;;
41 ;;  To use this in a Lisp program, do
42 ;;
43 ;;     (require 'texmathp)
44 ;;
45 ;;  You can then write code like this:
46 ;;
47 ;;     (if (texmathp) ...)
48 ;;
49 ;;  The call to `texmathp' leaves some extra information in the
50 ;;  variable `texmathp-why'.  It's value is a cons cell (MATCH . POSITION),
51 ;;  specifying which command at what position is responsible for math
52 ;;  mode being on or off.
53 ;;
54 ;;  To configure which macros and environments influence LaTeX math mode,
55 ;;  customize the variable `texmathp-tex-commands'.  By default
56 ;;  it recognizes the LaTeX core as well as AMS-LaTeX (see the variable
57 ;;  `texmathp-tex-commands-default', also as an example).
58 ;;
59 ;;  To try out the code interactively, use `M-x texmathp RET'.
60 ;;
61 ;;  Of course, in order to work this function has to assume that the
62 ;;  LaTeX above point is syntactically correct.  In particular:
63 ;;
64 ;;  o The different math delimiters are paired correctly.  Thus if
65 ;;    you do things like "\begin{equation} $"  or "\[ ... \)"
66 ;;    the result of (texmathp) is undefined.  It is in fact possible
67 ;;    in LaTeX to pair \[ with $$ and \( with $, but this will confuse
68 ;;    texmathp (and human readers as well).
69 ;;
70 ;;  o However, texmathp will correctly work with nested delimiters.
71 ;;    Something like the following will be parsed correctly at any point:
72 ;;
73 ;;       \begin{equation}
74 ;;          x = y \mbox{abc \ensuremath{\alpha} cba $2^3$}
75 ;;       \end{equation}
76 ;;
77 ;;  o texmathp is somewhat forgiving if you have an empty line inside
78 ;;    the current math environment, which is not legal in TeX but may
79 ;;    easily happen during editing.  Depending upon the variable
80 ;;    `texmathp-search-n-paragraphs' several paragraphs are checked
81 ;;    backwards, by default 2.  Paragraph here means something limited
82 ;;    by an empty line.
83 ;;--------------------------------------------------------------------------
84 ;;
85 ;;  BUGS:
86 ;;
87 ;;  If any of the the special macros like \mbox or \ensuremath has optional
88 ;;  arguments, math mode inside these optional arguments is *not* influenced
89 ;;  by the macro.
90 ;;--------------------------------------------------------------------------
91 \f
92 ;;; Code:
93
94 (defgroup texmathp nil
95   "Testing TeX and LaTeX documents for math mode."
96   :tag "Test For TeX and LaTeX Math Mode"
97   :prefix "texmathp-"
98   :group 'tex)
99
100 ;; Some internal variables which are computed from `texmathp-tex-commands'
101 ;; and `texmathp-tex-commands-default'.
102 (defvar texmathp-environments nil)
103 (defvar texmathp-macros nil)
104 (defvar texmathp-onoff-regexp nil)
105 (defvar texmathp-toggle-regexp nil)
106 (defvar texmathp-tex-commands1 nil)
107 (defvar texmathp-memory nil)
108
109 (defvar texmathp-tex-commands)          ; silence the compiler
110
111 (defvar texmathp-tex-commands-default
112   '(;; Plain TeX
113     ("$$"            sw-toggle)   ("$"             sw-toggle)
114     ("\\hbox"        arg-off)
115     ("\\vbox"        arg-off)
116     ("\\vtop"        arg-off)
117     ("\\vcenter"     arg-off)
118
119     ;; Standard LaTeX
120     ("equation"      env-on)
121     ("eqnarray"      env-on)      ("eqnarray*"     env-on)
122     ("math"          env-on)
123     ("displaymath"   env-on)
124     ("minipage"      env-off)
125     ("\\fbox"        arg-off)
126     ("\\mbox"        arg-off)
127     ("\\framebox"    arg-off)
128     ("\\label"       arg-off)
129     ("\\textrm"      arg-off)
130     ("\\("           sw-on)       ("\\)"           sw-off)
131     ("\\["           sw-on)       ("\\]"           sw-off)
132     ("\\ensuremath"  arg-on)
133
134     ;; AMS-LaTeX
135     ("equation*"     env-on)
136     ("align"         env-on)      ("align*"        env-on)
137     ("gather"        env-on)      ("gather*"       env-on)
138     ("multline"      env-on)      ("multline*"     env-on)
139     ("flalign"       env-on)      ("flalign*"      env-on)
140     ("alignat"       env-on)      ("alignat*"      env-on)
141     ("xalignat"      env-on)      ("xalignat*"     env-on)
142     ("xxalignat"     env-on)      ("\\boxed"       arg-on)
143     ("\\text"        arg-off)     ("\\intertext"   arg-off)
144
145     ;; mathtools
146     ("\\shortintertext"   arg-off))
147   "The default entries for `texmathp-tex-commands', which see.")
148
149 (defun texmathp-compile ()
150   "Compile the value of `texmathp-tex-commands' into the internal lists.
151 Call this when you have changed the value of that variable without using
152 customize (customize calls it when setting the variable)."
153   (interactive)
154   ;; Extract lists and regexp.
155   (setq texmathp-macros nil texmathp-environments nil)
156   (setq texmathp-memory
157         (cons texmathp-tex-commands texmathp-tex-commands-default))
158   (setq texmathp-tex-commands1 (append texmathp-tex-commands
159                                        texmathp-tex-commands-default))
160   (let ((list (reverse texmathp-tex-commands1))
161         var entry type switches togglers)
162     (while (setq entry (car list))
163       (setq type (nth 1 entry)
164             list (cdr list)
165             var (cond ((memq type '(env-on env-off)) 'texmathp-environments)
166                       ((memq type '(arg-on arg-off)) 'texmathp-macros)
167                       ((memq type '(sw-on sw-off))   'switches)
168                       ((memq type '(sw-toggle))      'togglers)))
169       (set var (cons (car entry) (symbol-value var))))
170     (setq texmathp-onoff-regexp
171           (concat "[^\\\\]\\("
172                   (mapconcat 'regexp-quote switches "\\|")
173                   "\\)")
174           texmathp-toggle-regexp
175           (concat "\\([^\\\\\\$]\\|\\`\\)\\("
176                   (mapconcat 'regexp-quote togglers "\\|")
177                   "\\)"))))
178
179 (defcustom texmathp-tex-commands nil
180   "List of environments and macros influencing (La)TeX math mode.
181 This user-defined list is used in addition to LaTeX and AMSLaTeX defaults.
182 The structure of each entry is (NAME TYPE)
183
184 - The first item in each entry is the name of an environment or macro.
185   If it's a macro, include the backslash.
186
187 - The second item is a symbol indicating how the command works:
188     `env-on'     Environment: turns math mode for its body  on
189     `env-off'    Environment: turns math mode for its body  off
190     `arg-on'     Command: turns math mode for its arguments on
191     `arg-off'    Command: turns math mode for its arguments off
192     `sw-on'      Switch: turns math-mode of following text  on
193     `sw-off'     Switch: turns math-mode of following text  off
194     `sw-toggle'  Switch: toggles math mode of following text"
195   :group 'texmathp
196   :set '(lambda (symbol value) (set-default symbol value) (texmathp-compile))
197   :type
198   '(repeat
199     (list :value ("" env-on)
200      (string  :tag "Name")
201      (choice  :tag "Type"
202       (const :tag "Environment: turns math mode for its body on" env-on)
203       (const :tag "Environment: turns math mode for its body off" env-off)
204       (const :tag "Command: turns math mode for its argument on" arg-on)
205       (const :tag "Command: turns math-mode for its argument off" arg-off)
206       (const :tag "Switch: turns math-mode of following text on" sw-on)
207       (const :tag "Switch: turns math-mode of following text off" sw-off)
208       (const :tag "Switch: toggles math mode of following text" sw-toggle)))))
209
210 (defcustom texmathp-search-n-paragraphs 2
211   "*Number of paragraphs to check before point.
212 Normally, you cannot have an empty line in a math environment in (La)TeX.
213 The fastest method to test for math mode is then limiting the search
214 backward to the nearest empty line.
215 However, during editing it happens that such lines exist temporarily.
216 Therefore we look a little further.  This variable determines how many
217 empty lines we go back to fix the search limit."
218   :group 'texmathp
219   :type 'number)
220
221 (defcustom texmathp-allow-detached-args nil
222   "*Non-nil means, allow arguments of macros to be detached by whitespace.
223 When this is t, `aaa' will be interpreted as an argument of \bb in the
224 following construct:  \bbb [xxx] {aaa}
225 This is legal in TeX.  The disadvantage is that any number of braces expressions
226 will be considered arguments of the macro independent of its definition."
227   :group 'texmathp
228   :type 'boolean)
229
230 (defvar texmathp-why nil
231   "After a call to `texmathp' this variable shows why math-mode is on or off.
232 The value is a cons cell (MATCH . POSITION).
233 MATCH is a string like a car of an entry in `texmathp-tex-commands', e.q.
234 \"equation\" or \"\\ensuremath\" or \"\\=\\[\" or \"$\".
235 POSITION is the buffer position of the match.  If there was no match,
236 it points to the limit used for searches, usually two paragraphs up.")
237
238 ;; We need our own syntax table to play with the syntax of () [] and {}
239 ;; For speed reasons we define it statically instead of copying it each time.
240 (defvar texmathp-syntax-table
241   (let ((table (make-syntax-table)))
242     (mapc (lambda (x) (modify-syntax-entry (car x) (cdr x) table))
243           '((?\\ . "\\") (?\f .">")  (?\n . ">")  (?% . "<")
244             (?\[ . ".")  (?\] . ".") (?\{ . "(}") (?\} . "){")
245             (?\( . ".")  (?\) . ".") (?\" . ".")  (?& . ".")   (?_ . ".")
246             (?@ . "_")   (?~ . " ")  (?$ . "$")   (?' . "w")))
247     table)
248   "Syntax table used while texmathp is parsing.")
249
250 ;;;###autoload
251 (defun texmathp ()
252   "Determine if point is inside (La)TeX math mode.
253 Returns t or nil.  Additional info is placed into `texmathp-why'.
254 The functions assumes that you have (almost) syntactically correct (La)TeX in
255 the buffer.
256 See the variable `texmathp-tex-commands' about which commands are checked."
257   (interactive)
258   (let* ((pos (point)) math-on sw-match
259          (bound (save-excursion
260                   (if (re-search-backward "[\n\t][ \t]*[\n\r]"
261                                           nil 1 texmathp-search-n-paragraphs)
262                       (match-beginning 0)
263                     (point-min))))
264          (mac-match (texmathp-match-macro bound))
265          (env-match (texmathp-match-environment
266                      (if (and mac-match (> (cdr mac-match) bound))
267                          (cdr mac-match)
268                        bound)))
269          (match (cons nil bound)))
270
271     ;; Select the nearer match
272     (and env-match (setq match env-match))
273     (and mac-match (> (cdr mac-match) (cdr match)) (setq match mac-match))
274     (setq math-on (memq (nth 1 (assoc (car match) texmathp-tex-commands1))
275                         '(env-on arg-on)))
276
277     ;; Check for switches
278     (and (not math-on)
279          (setq sw-match (texmathp-match-switch bound))
280          (> (cdr sw-match) (cdr match))
281          (eq (nth 1 (assoc (car sw-match) texmathp-tex-commands1)) 'sw-on)
282          (setq match sw-match math-on t))
283
284     ;; Check for togglers
285     (if (not math-on)
286         (save-excursion
287           (goto-char (cdr match))
288           (while (re-search-forward texmathp-toggle-regexp pos t)
289             (if (setq math-on (not math-on))
290                 (setq sw-match (cons (match-string 2) (match-beginning 2)))
291               (setq sw-match nil)))
292           (and math-on sw-match (setq match sw-match))))
293
294     ;; Store info, show as message when interactive, and return
295     (setq texmathp-why match)
296     (and (interactive-p)
297          (message "math-mode is %s: %s begins at buffer position %d"
298                   (if math-on "on" "off")
299                   (or (car match) "new paragraph")
300                   (cdr match)))
301     (and math-on t)))
302
303 (defun texmathp-match-environment (bound)
304   "Find out if point is inside any of the math environments.
305 Limit searched to BOUND.  The return value is like (\"equation\" . (point))."
306   (catch 'exit
307     (save-excursion
308       (and (null texmathp-environments) (throw 'exit nil))
309       ;; Check if the line we are starting with is a commented one.
310       (let ((orig-comment-flag
311              ;; Could be replaced by `TeX-in-commented-line'.
312              (progn
313                (save-excursion
314                  (beginning-of-line)
315                  (skip-chars-forward " \t")
316                  (string= (buffer-substring-no-properties
317                            (point) (min (point-max)
318                                         (+ (point) (length comment-start))))
319                           comment-start))))
320             end-list env)
321         (while (re-search-backward "\\\\\\(begin\\|end\\)[ \t]*{\\([^}]+\\)}"
322                                    bound t)
323           ;; Check if the match found is inside of a comment.
324           (let ((current-comment-flag
325                  ;; Could be replaced by `TeX-in-comment'.
326                  (when (save-match-data
327                          (re-search-backward comment-start-skip
328                                              (line-beginning-position) t))
329                    ;; We need a t for comparison with `orig-comment-flag',
330                    ;; not a number.
331                    t)))
332             ;; Only consider matching alternatives with respect to
333             ;; "in-commentness", i.e. if we started with a comment
334             ;; only consider matches which are in comments as well and
335             ;; vice versa.
336             (when (eq orig-comment-flag current-comment-flag)
337               (setq env (buffer-substring-no-properties
338                          (match-beginning 2) (match-end 2)))
339               (cond ((string= (match-string 1) "end")
340                      (setq end-list (cons env end-list)))
341                     ((equal env (car end-list))
342                      (setq end-list (cdr end-list)))
343                     ((member env texmathp-environments)
344                      (throw 'exit (cons env (point))))))))
345         nil))))
346
347 (defun texmathp-match-macro (bound)
348   "Find out if point is within the arguments of any of the Math macros.
349 Limit searches to BOUND.  The return value is like (\"\\macro\" . (point))."
350   (catch 'exit
351     (and (null texmathp-macros) (throw 'exit nil))
352     (let (pos cmd (syntax-table (syntax-table)))
353       (unwind-protect
354           (save-restriction
355             (save-excursion
356               (set-syntax-table texmathp-syntax-table)
357               (narrow-to-region (max 1 bound) (point))
358               ;; Move back out of the current parenthesis
359               (while (condition-case nil (progn (up-list -1) t) (error nil))
360                 ;; Move back over any touching sexps (in fact also non-touching)
361                 (while
362                     (and
363                      (cond
364                       ((memq (preceding-char) '(?\] ?\})))
365                       ((and
366                         texmathp-allow-detached-args
367                         (re-search-backward
368                         "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\="
369                         bound t))
370                        (goto-char (1+ (match-beginning 0))) t))
371                      (if (eq (preceding-char) ?\})
372                          ;; Jump back over {}
373                          (condition-case nil
374                              (progn (backward-sexp) t)
375                            (error nil))
376                        ;; Jump back over []. Modify syntax temporarily for this.
377                        (unwind-protect
378                            (progn
379                              (modify-syntax-entry ?\{ ".")
380                              (modify-syntax-entry ?\} ".")
381                              (modify-syntax-entry ?\[ "(]")
382                              (modify-syntax-entry ?\] ")[")
383                              (condition-case nil
384                                  (progn (backward-sexp) t)
385                                (error nil)))
386                          (modify-syntax-entry ?\{ "(}")
387                          (modify-syntax-entry ?\} "){")
388                          (modify-syntax-entry ?\[ ".")
389                          (modify-syntax-entry ?\] ".")
390                          nil))))
391                 (setq pos (point))
392                 (and (memq (following-char) '(?\[ ?\{))
393                      (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t)
394                      (setq cmd (buffer-substring-no-properties
395                                 (match-beginning 0) (match-end 0)))
396                      (member cmd texmathp-macros)
397                      (throw 'exit (cons cmd (point))))
398                 (goto-char pos))
399               (throw 'exit nil)))
400         (set-syntax-table syntax-table)))))
401
402 ;;;###autoload
403 (defun texmathp-match-switch (bound)
404   "Search backward for any of the math switches.
405 Limit searched to BOUND."
406   ;; The return value is like ("\\(" . (point)).
407   (save-excursion
408     (if (re-search-backward texmathp-onoff-regexp bound t)
409         (cons (buffer-substring-no-properties (match-beginning 1) (match-end 1))
410               (match-beginning 1))
411       nil)))
412
413 (provide 'texmathp)
414
415 ;;; texmathp.el ends here