I have electric-pair-mode on, but the behavior with double quotes is not working as expected in some buffers. In one of the affected buffers:

he said "

it does not insert the matching double quote when I type the " above. But I then type:

he said "hello world"

when I type that second ", it inserts another and I get:

he said "hello world""

That is: the matching double quote is only inserted at the end, or after inserting a starting double quote, or when not preceded by whitespace.

1 Answer 1


This is from unbalanced quotes. For pairs with distinct beginning and end characters, such as parentheses, square brackets, curly brackets, curly quotes and so on, one can use check-parens or something like this code to check the buffer. But for " and ' quotes, the best we can do is count them and see if the number is even. One can use some simple code like this:

;; perhaps a bit silly, but I like semantic names for my code, and it seems emacs lisp doesn't have these?
(defun even-p (n) (eq (mod n 2) 0))
(defun odd-p (n) (not (even-p n)))

(defun count-quote-occurrences ()
  "Count the occurrences of single and double quote characters in buffer.
If both values are even, display a message; otherwise, display a warning.
  (let ((double-quote-occurences (count-matches "\"" (point-min) (point-max)))
        (single-quote-occurences (count-matches "\'" (point-min) (point-max))))
    (if (or (odd-p double-quote-occurences)
            (odd-p single-quote-occurences))
        (warn "Buffer contains %s double quotes and %s single quotes."
        (message "Success: buffer contains %s double quotes and %s single quotes."

(amusingly, the above definition creates unbalanced double quotes, because it's not smart enough to handle the backslash escaping. So one could add a spurious " in a comment to fix that...)

...and if you get unbalanced quotes, use occur with the offending character and M-g n or similar to jump through the buffer and find where the quotes got unbalanced.

  • Note that in emacs lisp code, where one has docstrings the use backticks and single quotes, this won't work. Modifying the above code to handle a single quote as the end character for a either a backtick or starting single quote is left as an exercise to the reader...
    – Dan Drake
    Commented Sep 2, 2023 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.