2013-09-18 Selective replacement in LaTeX documents (en)

A few days ago, I was working on a LaTeX file written by a someone. The person who typed it in didn’t care about putting dollar signs around single-letter formulae, so that there were parts like “Let $x\in A$.”, but also “Let A be a nonempty set.”. No need to mention that it is rather tedious to correct these kind of errors – but Emacs to the rescue, I thought. Now most such occurences were the sets A through C and variables x to z, so I thought I could be clever (especially after reading this excellent post from Mastering Emacs about \, in regexp-replace) and tried to regexp-replace \b\([A-Cx-z]\)\b with \,(if (texmathp) \1 (concat "$" \1 "$")). To my surprise, it didn’t work: it started replacing things with weird strings. After a bit of searching I found the culprit: AUCTeX’s texmathp isn’t a pure function – it does some searching on its own, so \1 gets cluttered. The solution was quick and dirty: \,(let ((letter \1)) (if (texmathp) letter (concat "$" letter "$"))); after a while, I realized that \,(if (save-match-data (texmathp)) \1 (concat "$" \1 "$")) is much better. Anyway, I wrote an email to Carsten Dominik, who is the author of the relevant portion of AUCTeX, and asked him to add a save-match-data to texmathp itself. It quickly turned out that this behavior is actually a feature, not a bug, since Emacs functions (even interactive ones) aren’t required to save match data. I don’t like it, but this is what it is; a possible solution might be advising texmathp, and a cleaner policy might be to have two functions: an “internal” one, not saving the match data, and an interactive wrapper with save-match-data. Anyway, I have to make it clear that this is Emacs’ core developers’ policy, not one of Carsten’s! And now that I know about it, it’s no longer a huge problem for me.

What can be learned from this experience? First of all, if not for the save-match-data problem, I’d pull this trick off in just a few minutes, including searching for texmathp. Second: don’t get me wrong, but you know, I’m not a Vim expert, but I’m just wondering whether it’s possible to do something like that in it. (Maybe yes, maybe not. Just wondering.;) And if yes, then how much time you would need to code it.). Third, when I got suspicious about texmathp messing around with match data, confirming this was a matter of seconds due to the self-documenting nature of Emacs: the source was just a few keystrokes away. And last but not least: my email exchange with Carsten was yet another example of the Emacs community being an extremely friendly and supportive one – especially towards a relative newbie like me.

It’s so good to be an Emacs user.

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryTeX, CategoryLaTeX