]> code.delx.au - gnu-emacs-elpa/blob - packages/auctex/texmathp.el
Remove version numbers in packages/ directory
[gnu-emacs-elpa] / 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) ("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 ("align" env-on) ("align*" env-on)
136 ("gather" env-on) ("gather*" env-on)
137 ("multline" env-on) ("multline*" env-on)
138 ("flalign" env-on) ("flalign*" env-on)
139 ("alignat" env-on) ("alignat*" env-on)
140 ("xalignat" env-on) ("xalignat*" env-on)
141 ("xxalignat" env-on) ("\\boxed" arg-on)
142 ("\\text" arg-off) ("\\intertext" arg-off))
143 "The default entries for `texmathp-tex-commands', which see.")
144
145 (defun texmathp-compile ()
146 "Compile the value of `texmathp-tex-commands' into the internal lists.
147 Call this when you have changed the value of that variable without using
148 customize (customize calls it when setting the variable)."
149 (interactive)
150 ;; Extract lists and regexp.
151 (setq texmathp-macros nil texmathp-environments nil)
152 (setq texmathp-memory
153 (cons texmathp-tex-commands texmathp-tex-commands-default))
154 (setq texmathp-tex-commands1 (append texmathp-tex-commands
155 texmathp-tex-commands-default))
156 (let ((list (reverse texmathp-tex-commands1))
157 var entry type switches togglers)
158 (while (setq entry (car list))
159 (setq type (nth 1 entry)
160 list (cdr list)
161 var (cond ((memq type '(env-on env-off)) 'texmathp-environments)
162 ((memq type '(arg-on arg-off)) 'texmathp-macros)
163 ((memq type '(sw-on sw-off)) 'switches)
164 ((memq type '(sw-toggle)) 'togglers)))
165 (set var (cons (car entry) (symbol-value var))))
166 (setq texmathp-onoff-regexp
167 (concat "[^\\\\]\\("
168 (mapconcat 'regexp-quote switches "\\|")
169 "\\)")
170 texmathp-toggle-regexp
171 (concat "\\([^\\\\\\$]\\|\\`\\)\\("
172 (mapconcat 'regexp-quote togglers "\\|")
173 "\\)"))))
174
175 (defcustom texmathp-tex-commands nil
176 "List of environments and macros influencing (La)TeX math mode.
177 This user-defined list is used in addition to LaTeX and AMSLaTeX defaults.
178 The structure of each entry is (NAME TYPE)
179
180 - The first item in each entry is the name of an environment or macro.
181 If it's a macro, include the backslash.
182
183 - The second item is a symbol indicating how the command works:
184 `env-on' Environment: turns math mode for its body on
185 `env-off' Environment: turns math mode for its body off
186 `arg-on' Command: turns math mode for its arguments on
187 `arg-off' Command: turns math mode for its arguments off
188 `sw-on' Switch: turns math-mode of following text on
189 `sw-off' Switch: turns math-mode of following text off
190 `sw-toggle' Switch: toggles math mode of following text"
191 :group 'texmathp
192 :set '(lambda (symbol value) (set-default symbol value) (texmathp-compile))
193 :type
194 '(repeat
195 (list :value ("" env-on)
196 (string :tag "Name")
197 (choice :tag "Type"
198 (const :tag "Environment: turns math mode for its body on" env-on)
199 (const :tag "Environment: turns math mode for its body off" env-off)
200 (const :tag "Command: turns math mode for its argument on" arg-on)
201 (const :tag "Command: turns math-mode for its argument off" arg-off)
202 (const :tag "Switch: turns math-mode of following text on" sw-on)
203 (const :tag "Switch: turns math-mode of following text off" sw-off)
204 (const :tag "Switch: toggles math mode of following text" sw-toggle)))))
205
206 (defcustom texmathp-search-n-paragraphs 2
207 "*Number of paragraphs to check before point.
208 Normally, you cannot have an empty line in a math environment in (La)TeX.
209 The fastest method to test for math mode is then limiting the search
210 backward to the nearest empty line.
211 However, during editing it happens that such lines exist temporarily.
212 Therefore we look a little further. This variable determines how many
213 empty lines we go back to fix the search limit."
214 :group 'texmathp
215 :type 'number)
216
217 (defcustom texmathp-allow-detached-args nil
218 "*Non-nil means, allow arguments of macros to be detached by whitespace.
219 When this is t, `aaa' will be interpreted as an argument of \bb in the
220 following construct: \bbb [xxx] {aaa}
221 This is legal in TeX. The disadvantage is that any number of braces expressions
222 will be considered arguments of the macro independent of its definition."
223 :group 'texmathp
224 :type 'boolean)
225
226 (defvar texmathp-why nil
227 "After a call to `texmathp' this variable shows why math-mode is on or off.
228 The value is a cons cell (MATCH . POSITION).
229 MATCH is a string like a car of an entry in `texmathp-tex-commands', e.q.
230 \"equation\" or \"\\ensuremath\" or \"\\[\" or \"$\".
231 POSITION is the buffer position of the match. If there was no match,
232 it points to the limit used for searches, usually two paragraphs up.")
233
234 ;; We need our own syntax table to play with the syntax of () [] and {}
235 ;; For speed reasons we define it statically instead of copying it each time.
236 (defvar texmathp-syntax-table
237 (let ((table (make-syntax-table)))
238 (mapc (lambda (x) (modify-syntax-entry (car x) (cdr x) table))
239 '((?\\ . "\\") (?\f .">") (?\n . ">") (?% . "<")
240 (?\[ . ".") (?\] . ".") (?\{ . "(}") (?\} . "){")
241 (?\( . ".") (?\) . ".") (?\" . ".") (?& . ".") (?_ . ".")
242 (?@ . "_") (?~ . " ") (?$ . "$") (?' . "w")))
243 table)
244 "Syntax table used while texmathp is parsing.")
245
246 ;;;###autoload
247 (defun texmathp ()
248 "Determine if point is inside (La)TeX math mode.
249 Returns t or nil. Additional info is placed into `texmathp-why'.
250 The functions assumes that you have (almost) syntactically correct (La)TeX in
251 the buffer.
252 See the variable `texmathp-tex-commands' about which commands are checked."
253 (interactive)
254 (let* ((pos (point)) math-on sw-match
255 (bound (save-excursion
256 (if (re-search-backward "[\n\t][ \t]*[\n\r]"
257 nil 1 texmathp-search-n-paragraphs)
258 (match-beginning 0)
259 (point-min))))
260 (mac-match (texmathp-match-macro bound))
261 (env-match (texmathp-match-environment
262 (if (and mac-match (> (cdr mac-match) bound))
263 (cdr mac-match)
264 bound)))
265 (match (cons nil bound)))
266
267 ;; Select the nearer match
268 (and env-match (setq match env-match))
269 (and mac-match (> (cdr mac-match) (cdr match)) (setq match mac-match))
270 (setq math-on (memq (nth 1 (assoc (car match) texmathp-tex-commands1))
271 '(env-on arg-on)))
272
273 ;; Check for switches
274 (and (not math-on)
275 (setq sw-match (texmathp-match-switch bound))
276 (> (cdr sw-match) (cdr match))
277 (eq (nth 1 (assoc (car sw-match) texmathp-tex-commands1)) 'sw-on)
278 (setq match sw-match math-on t))
279
280 ;; Check for togglers
281 (if (not math-on)
282 (save-excursion
283 (goto-char (cdr match))
284 (while (re-search-forward texmathp-toggle-regexp pos t)
285 (if (setq math-on (not math-on))
286 (setq sw-match (cons (match-string 2) (match-beginning 2)))
287 (setq sw-match nil)))
288 (and math-on sw-match (setq match sw-match))))
289
290 ;; Store info, show as message when interactive, and return
291 (setq texmathp-why match)
292 (and (interactive-p)
293 (message "math-mode is %s: %s begins at buffer position %d"
294 (if math-on "on" "off")
295 (or (car match) "new paragraph")
296 (cdr match)))
297 (and math-on t)))
298
299 (defun texmathp-match-environment (bound)
300 "Find out if point is inside any of the math environments.
301 Limit searched to BOUND. The return value is like (\"equation\" . (point))."
302 (catch 'exit
303 (save-excursion
304 (and (null texmathp-environments) (throw 'exit nil))
305 ;; Check if the line we are starting with is a commented one.
306 (let ((orig-comment-flag
307 ;; Could be replaced by `TeX-in-commented-line'.
308 (progn
309 (save-excursion
310 (beginning-of-line)
311 (skip-chars-forward " \t")
312 (string= (buffer-substring-no-properties
313 (point) (min (point-max)
314 (+ (point) (length comment-start))))
315 comment-start))))
316 end-list env)
317 (while (re-search-backward "\\\\\\(begin\\|end\\)[ \t]*{\\([^}]+\\)}"
318 bound t)
319 ;; Check if the match found is inside of a comment.
320 (let ((current-comment-flag
321 ;; Could be replaced by `TeX-in-comment'.
322 (when (save-match-data
323 (re-search-backward comment-start-skip
324 (line-beginning-position) t))
325 ;; We need a t for comparison with `orig-comment-flag',
326 ;; not a number.
327 t)))
328 ;; Only consider matching alternatives with respect to
329 ;; "in-commentness", i.e. if we started with a comment
330 ;; only consider matches which are in comments as well and
331 ;; vice versa.
332 (when (eq orig-comment-flag current-comment-flag)
333 (setq env (buffer-substring-no-properties
334 (match-beginning 2) (match-end 2)))
335 (cond ((string= (match-string 1) "end")
336 (setq end-list (cons env end-list)))
337 ((equal env (car end-list))
338 (setq end-list (cdr end-list)))
339 ((member env texmathp-environments)
340 (throw 'exit (cons env (point))))))))
341 nil))))
342
343 (defun texmathp-match-macro (bound)
344 "Find out if point is within the arguments of any of the Math macros.
345 Limit searches to BOUND. The return value is like (\"\\macro\" . (point))."
346 (catch 'exit
347 (and (null texmathp-macros) (throw 'exit nil))
348 (let (pos cmd (syntax-table (syntax-table)))
349 (unwind-protect
350 (save-restriction
351 (save-excursion
352 (set-syntax-table texmathp-syntax-table)
353 (narrow-to-region (max 1 bound) (point))
354 ;; Move back out of the current parenthesis
355 (while (condition-case nil (progn (up-list -1) t) (error nil))
356 ;; Move back over any touching sexps (in fact also non-touching)
357 (while
358 (and
359 (cond
360 ((memq (preceding-char) '(?\] ?\})))
361 ((and
362 texmathp-allow-detached-args
363 (re-search-backward
364 "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\="
365 bound t))
366 (goto-char (1+ (match-beginning 0))) t))
367 (if (eq (preceding-char) ?\})
368 ;; Jump back over {}
369 (condition-case nil
370 (progn (backward-sexp) t)
371 (error nil))
372 ;; Jump back over []. Modify syntax temporarily for this.
373 (unwind-protect
374 (progn
375 (modify-syntax-entry ?\{ ".")
376 (modify-syntax-entry ?\} ".")
377 (modify-syntax-entry ?\[ "(]")
378 (modify-syntax-entry ?\] ")[")
379 (condition-case nil
380 (progn (backward-sexp) t)
381 (error nil)))
382 (modify-syntax-entry ?\{ "(}")
383 (modify-syntax-entry ?\} "){")
384 (modify-syntax-entry ?\[ ".")
385 (modify-syntax-entry ?\] ".")
386 nil))))
387 (setq pos (point))
388 (and (memq (following-char) '(?\[ ?\{))
389 (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t)
390 (setq cmd (buffer-substring-no-properties
391 (match-beginning 0) (match-end 0)))
392 (member cmd texmathp-macros)
393 (throw 'exit (cons cmd (point))))
394 (goto-char pos))
395 (throw 'exit nil)))
396 (set-syntax-table syntax-table)))))
397
398 ;;;###autoload
399 (defun texmathp-match-switch (bound)
400 "Search backward for any of the math switches.
401 Limit searched to BOUND."
402 ;; The return value is like ("\\(" . (point)).
403 (save-excursion
404 (if (re-search-backward texmathp-onoff-regexp bound t)
405 (cons (buffer-substring-no-properties (match-beginning 1) (match-end 1))
406 (match-beginning 1))
407 nil)))
408
409 (provide 'texmathp)
410
411 ;;; texmathp.el ends here