2022-11-14 Doubling backslashes

Today’s post is not meant to be very useful to most people, but it serves as a demonstration of a point (well, that, and a bit of advertisement;-)).

However strange it may sound, a few days ago I have a very atypical need. I needed to move some LaTeX code to a JSON file. This meant that all the backslashes had to be doubled, of course – LaTeX code is full of them, and they need to be escaped in JSON. Obviously, query-replace​’ing backslashes with double backslashes is easy, and query-replace only operates on the region when it is active, but I wanted to make sure I didn’t replace them twice by accidentally marking too much. So – partly as an exercise, I guess – I decided to write a command to replace every backslash in the region by two backslashes, but only if it was a single one.

Well.

(defun double-slashes-in-region (beg end)
  "Change every single dash in region to a double one."
  (interactive "*r")
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (while (search-forward "\\" nil t)
        (backward-char 1)
        (when (looking-at "\\\\[^\\\\]")
          (insert "\\"))
        (forward-char 2)))))

The real kick is that you can write such a function basically in no time (assuming you have some experience). In fact, it took me exactly 6 minutes to put it together (including the inevitable debugging – of course I didn’t get it right the first time!;-)).

And here, I cannot not mention that I wrote a textbook on Emacs Lisp. Check it out if you want to learn to code little convenience Elisp functions, too!

CategoryEnglish, CategoryBlog, CategoryEmacs