Is there a way to toggle a string between single and double quotes in emacs?

emacs

Solution

Here's a quick hack to get you started:

(defun toggle-quotes ()
  "Toggle single quoted string to double or vice versa, and
  flip the internal quotes as well.  Best to run on the first
  character of the string."
  (interactive)
  (save-excursion
    (re-search-backward "[\"']")
    (let* ((start (point))
           (old-c (char-after start))
           new-c)
      (setq new-c 
            (case old-c
              (?\" "'")
              (?\' "\"")))
      (setq old-c (char-to-string old-c))
      (delete-char 1)
      (insert new-c)
      (re-search-forward old-c)
      (backward-char 1)
      (let ((end (point)))
        (delete-char 1)
        (insert new-c)
        (replace-string new-c old-c nil (1+ start) end)))))

The function swaps the internal quotes to the opposite, which is close to bonus 2.

Problem

I'm looking for an emacs command that will toggle the surrounding quote characters on the string under the point, e.g. with the cursor in the string 'bar', hit a key and change it between: ``` foo = 'bar' <---> foo = "bar" ``` For bonus points it would: handle toggling Python triple-quote strings (`'''` <---> `"""`) automatically change backslash escaping inside the string as appropriate. e.g. ``` foo = 'bar "quote"' <---> foo = "bar \"quote\"" ```

Original source