2014-09-20 Smart ties in Emacs

As all TeX users know, in all flavors of TeX you use the tilde (~), called a “tie” in The TeXbook, to denote non-breakable spaces. Of course, if you use Emacs, you may use some helpers, like tildify to insert them interactively or after typing/yanking some text. But what I sometimes do is yank some short fragments of text from various sources, or just forget to type a tie (though I trained myself to type them after e.g. all one-letter prepositions, which – according to Polish rules of typesetting – should not dangle at the end of the line by themselves). Then, I prefer to insert the tie by hand. The problem is, I had to delete the space and then press ~; two keystrokes instead of one. Blechhh. So I wrote this short piece of Elisp, and tied (pun intended) it to ~ (thanks to this answer on StackOverflow, I learned how to bind it using eval-after-load).

(defun electric-tie ()
  "Inserts a tilde at point unless the point is at a space
character(s), in which case it deletes the space(s) first."
  (interactive)
  (while (equal (char-after) ?\s) (delete-char 1))
  (while (equal (char-before) ?\s) (delete-char -1))
  (call-interactively 'self-insert-command))

(eval-after-load 'tex '(define-key TeX-mode-map "~" 'electric-tie))

(Note: the quoted answer contains some suggestions of improving this code in terms of style. While I didn’t bother to do that, reading that answer is probably a good idea.)

CategoryEnglish, CategoryBlog, CategoryEmacs