12

Q: is there a way to detect if point is inside a LaTeX math environment?

How would one detect whether point is or is not inside a LaTeX math environment, whether delineated inline by $...$ or by named environments (equation, displaymath, etc.)?

Dan
  • 32,584
  • 6
  • 98
  • 168

1 Answers1

10

The function texmathp defined in AUCTeX (autoloaded from texmathp) does exactly that (ok, actually it does a bit more).

Used interactively, it will give you some more information, including whether the point is in a math construct.

Used in elisp, it will be t if in math, nil otherwise. The additional pieces of informations are then stored in the variable texmathp-why.

When texmathp returns t, this is a cons of (MATCH . POSITION), where MATCH is a string containing the TeX command or the name of the environment that triggered math mode, and POSITION is the position at which that string was found in the buffer. MATCH is something like "$", "$$", "\\(", "\\[" "\\ensuremath", "displaymath", "equation", … When texmathp returns nil, the variable texmathp-why is (nil . pos) where pos is the beginning of the paragraph.

Warning from the docstring:

The functions assumes that you have (almost) syntactically correct (La)TeX in the buffer.

It is aware of all environments that AUCTeX knows of (for example for font-locking), and you can add more using the variable texmathp-tex-commands.

T. Verron
  • 4,233
  • 1
  • 22
  • 55
  • Also note that (shameless self-promotion ahead) this command is very convenient when mixed with emacs regular expressions: http://tex.stackexchange.com/a/91175/9517 – T. Verron Oct 01 '14 at 14:01
  • Self-promotion is an afterthought when sharing useful and relevant information :) – Sean Allred Dec 09 '14 at 00:15