2015-01-17 A quick-and-dirty hack with a dollar sign

I sometimes yank some fragments of text into my LaTeX files. This creates some problems, which can be more or less easily solved by query-replace and friends. The real problem is with math formulae. In general, anyone expecting that copying a formula from a pdf and yanking it into a LaTeX file will Just Work™, will be seriously disappointed. Converting such yanked formulae to correct LaTeX syntax is a painful process.

One can, however, use Emacs to ease the pain a bit. After a handful of such situations, being quite frustrated, I came up with this solution:

(defun TeX-smart-dollar (count)
  "Insert a dollar sign (first skipping any spaces).  If not at end of
line, assume we are at the beginning of a formula with missing dollars
and insert a closing one after a given number of words (one by
default)."
  (interactive "p")
  (skip-syntax-forward " " (line-end-position))
  (insert "$")
  (unless (eolp)
    (forward-word count)
    (insert "$")))

(eval-after-load 'tex '(define-key TeX-mode-map (kbd "$") 'TeX-smart-dollar))

The “not at eol” condition, BTW, is here so that this function does not interefere with ordinary typing of TeX formulae (usually when I type, I am at the end of line!).

This isn’t very robust, but it isn’t supposed to be – if the closing dollar is not at the right place, it is usually earlier in the buffer, and then I just press C-t and hold it until the dollar flies to the right spot. (Also, I could have written a piece of code to disable this binding, but I can just use local-set-key and that’s it.) So it is what it is: a quick-and-dirty hack, but still one that can make life easier. And – more importantly – this is again an example of a hack which can be implemented in just a few minutes.

CategoryEnglish, CategoryBlog, CategoryTeX, CategoryEmacs