有没有办法在emacs中的单引号和双引号之间切换字符串?

Tom*_*Tom 5 emacs

我正在寻找一个emacs命令,它将在点下的字符串上切换周围的引号字符,例如将光标放在字符串'bar'中,点击一个键并在以下之间进行更改:

foo = 'bar'   <--->   foo = "bar"
Run Code Online (Sandbox Code Playgroud)

对于奖励积分,它会:

  • 处理切换Python三引号字符串('''<---> """)

  • 根据需要自动更改字符串内部的反斜杠.

例如

foo = 'bar "quote"'   <--->   foo = "bar \"quote\""
Run Code Online (Sandbox Code Playgroud)

小智 6

这可能会更健壮:

(defun toggle-quotes ()
  (interactive)
  (save-excursion
    (let ((start (nth 8 (syntax-ppss)))
          (quote-length 0) sub kind replacement)
      (goto-char start)
      (setq sub (buffer-substring start (progn (forward-sexp) (point)))
            kind (aref sub 0))
      (while (char-equal kind (aref sub 0))
        (setq sub (substring sub 1)
              quote-length (1+ quote-length)))
      (setq sub (substring sub 0 (- (length sub) quote-length)))
      (goto-char start)
      (delete-region start (+ start (* 2 quote-length) (length sub)))
      (setq kind (if (char-equal kind ?\") ?\' ?\"))
      (loop for i from 0
            for c across sub
            for slash = (char-equal c ?\\)
            then (if (and (not slash) (char-equal c ?\\)) t nil) do
            (unless slash
              (when (member c '(?\" ?\'))
                (aset sub i
                      (if (char-equal kind ?\") ?\' ?\")))))
      (setq replacement (make-string quote-length kind))
      (insert replacement sub replacement))))
Run Code Online (Sandbox Code Playgroud)

它将使用缓冲区中的语法信息来查找字符串开头的引号(即字符串被引用),并且还会尝试在字符串中翻转引号,除非它们使用反斜杠进行转义 - 看起来像这可能是一个常见的情况.

PS.我刚刚意识到你也想要它找到三重引号,所以她去了.


Bur*_*rad 5

这是一个帮助您入门的快速技巧:

(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)))))
Run Code Online (Sandbox Code Playgroud)

该函数将内部报价交换为相反的报价,接近奖金 2。