Emacs: Escape Quotes Command 📜

By Xah Lee. Date: . Last updated: .

This page shows a emacs command to escape/unescape quotes.

For example,

"xyz"

becomes

\"xyz\"

This is very useful when coding lisp to process other languages.

For example, when you have this x = "…", and you want (search-forward "x = \"…\"")

put this in your Emacs Init File:

(defun xah-escape-quotes (Begin End)
  "Add slash before double quote in current line or selection.
Double quote is codepoint 34.
See also: `xah-unescape-quotes'
URL `http://xahlee.info/emacs/emacs/elisp_escape_quotes.html'
Created: 2010-08-16
Version: 2025-11-23"
  (interactive
   (if (region-active-p)
       (list (region-beginning) (region-end))
     (list (line-beginning-position) (line-end-position))))
  (save-excursion
    (save-restriction
      (narrow-to-region Begin End)
      (goto-char (point-min))
      (while (search-forward "\"" nil t)
        (replace-match "\\\"" t t))))
  (message "done. %s" real-this-command))
(defun xah-unescape-quotes (&optional Begin End)
  "Replace  「\\\"」 by 「\"」 in current line or selection.
See also: `xah-escape-quotes'

URL `http://xahlee.info/emacs/emacs/elisp_escape_quotes.html'
Created: 2017-01-11
Version: 2023-11-02"
  (interactive)
  (let (xbeg xend)
    (if (and Begin End)
        (setq xbeg Begin xend End)
      (if (region-active-p)
          (setq xbeg (region-beginning) xend (region-end))
        (setq xbeg (line-beginning-position) xend (line-end-position))))
    (save-excursion
      (save-restriction
        (narrow-to-region xbeg xend)
        (goto-char (point-min))
        (while (search-forward "\\\"" nil t)
          (replace-match "\"" t t))))))

You can assign keys to them. 〔see Emacs Keys: Define Key