1 ;;; texmathp.el -- Code to check if point is inside LaTeX math environment
3 ;; Copyright (C) 1998, 2004 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
6 ;; Maintainer: auctex-devel@gnu.org
9 ;; This file is part of AUCTeX.
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)
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.
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
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:
32 ;; \begin{equation} ... \end{equation}
39 ;; To install, put this file on your load-path and compile it.
41 ;; To use this in a Lisp program, do
43 ;; (require 'texmathp)
45 ;; You can then write code like this:
47 ;; (if (texmathp) ...)
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.
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).
59 ;; To try out the code interactively, use `M-x texmathp RET'.
61 ;; Of course, in order to work this function has to assume that the
62 ;; LaTeX above point is syntactically correct. In particular:
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).
70 ;; o However, texmathp will correctly work with nested delimiters.
71 ;; Something like the following will be parsed correctly at any point:
74 ;; x = y \mbox{abc \ensuremath{\alpha} cba $2^3$}
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
83 ;;--------------------------------------------------------------------------
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
90 ;;--------------------------------------------------------------------------
94 (defgroup texmathp nil
95 "Testing TeX and LaTeX documents for math mode."
96 :tag "Test For TeX and LaTeX Math Mode"
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)
109 (defvar texmathp-tex-commands) ; silence the compiler
111 (defvar texmathp-tex-commands-default
113 ("$$" sw-toggle) ("$" sw-toggle)
117 ("\\vcenter" arg-off)
120 ("equation" env-on) ("equation*" env-on)
121 ("eqnarray" env-on) ("eqnarray*" env-on)
123 ("displaymath" env-on)
127 ("\\framebox" arg-off)
130 ("\\(" sw-on) ("\\)" sw-off)
131 ("\\[" sw-on) ("\\]" sw-off)
132 ("\\ensuremath" arg-on)
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.")
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)."
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)
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
168 (mapconcat 'regexp-quote switches "\\|")
170 texmathp-toggle-regexp
171 (concat "\\([^\\\\\\$]\\|\\`\\)\\("
172 (mapconcat 'regexp-quote togglers "\\|")
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)
180 - The first item in each entry is the name of an environment or macro.
181 If it's a macro, include the backslash.
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"
192 :set '(lambda (symbol value) (set-default symbol value) (texmathp-compile))
195 (list :value ("" env-on)
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)))))
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."
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."
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.")
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")))
244 "Syntax table used while texmathp is parsing.")
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
252 See the variable `texmathp-tex-commands' about which commands are checked."
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)
260 (mac-match (texmathp-match-macro bound))
261 (env-match (texmathp-match-environment
262 (if (and mac-match (> (cdr mac-match) bound))
265 (match (cons nil bound)))
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))
273 ;; Check for switches
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))
280 ;; Check for togglers
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))))
290 ;; Store info, show as message when interactive, and return
291 (setq texmathp-why match)
293 (message "math-mode is %s: %s begins at buffer position %d"
294 (if math-on "on" "off")
295 (or (car match) "new paragraph")
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))."
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'.
311 (skip-chars-forward " \t")
312 (string= (buffer-substring-no-properties
313 (point) (min (point-max)
314 (+ (point) (length comment-start))))
317 (while (re-search-backward "\\\\\\(begin\\|end\\)[ \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',
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
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))))))))
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))."
347 (and (null texmathp-macros) (throw 'exit nil))
348 (let (pos cmd (syntax-table (syntax-table)))
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)
360 ((memq (preceding-char) '(?\] ?\})))
362 texmathp-allow-detached-args
364 "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\="
366 (goto-char (1+ (match-beginning 0))) t))
367 (if (eq (preceding-char) ?\})
370 (progn (backward-sexp) t)
372 ;; Jump back over []. Modify syntax temporarily for this.
375 (modify-syntax-entry ?\{ ".")
376 (modify-syntax-entry ?\} ".")
377 (modify-syntax-entry ?\[ "(]")
378 (modify-syntax-entry ?\] ")[")
380 (progn (backward-sexp) t)
382 (modify-syntax-entry ?\{ "(}")
383 (modify-syntax-entry ?\} "){")
384 (modify-syntax-entry ?\[ ".")
385 (modify-syntax-entry ?\] ".")
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))))
396 (set-syntax-table syntax-table)))))
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)).
404 (if (re-search-backward texmathp-onoff-regexp bound t)
405 (cons (buffer-substring-no-properties (match-beginning 1) (match-end 1))
411 ;;; texmathp.el ends here