怎么保证替换字符串后光标仍在原来位置与状态

自己写一个将当前行一些的非上档字符转成上档字符,

因为多次按 shift 输入一些字符,是很烦的,所以我不想这样。

比如 我写3[attr];'value'(写这个全部都是单个按键直接上屏,不再怎么需要去按 shift)

M-x 调用函数就可以,就会转成 #{attr}:"value"

M-x 肯定比按 shift 爽嘛

(defun shift-to()
  "在当前行一些的非上档字符转成上档字符"
  (interactive)
        (let ((pos (line-beginning-position)))
                (end-of-line)
                (set-mark pos))
        (let (
                (p1 (region-beginning))
                (p2 (region-end)))
        (save-restriction
          (narrow-to-region p1 p2)
          (goto-char (point-min))

          (while (search-forward "[" nil t)
            (replace-match "{" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "]" nil t)
            (replace-match "}" nil t)
            )
          (goto-char (point-min))


          (while (search-forward "1" nil t)
            (replace-match "!" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "2" nil t)
            (replace-match "@" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "3" nil t)
            (replace-match "#" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "4" nil t)
            (replace-match "$" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "5" nil t)
            (replace-match "%" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "6" nil t)
            (replace-match "^" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "7" nil t)
            (replace-match "&" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "8" nil t)
            (replace-match "*" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "9" nil t)
            (replace-match "()" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "=" nil t)
            (replace-match "+" nil t)
            )
          (goto-char (point-min))

          (while (search-forward ";" nil t)
            (replace-match ":" nil t)
            )
          (goto-char (point-min))

          (while (search-forward "'" nil t)
            (replace-match "\"" nil t)
            )
          (goto-char (point-min))

          )
   )
)

代码有些地方没有复用,还请见谅

我想知道 怎么保证替换字符串后光标仍在原来位置与状态

因为这个函数写后光标位置与状态会改变

save-excursion 把整个 body (除 interactive 外)包起来就行了。

Shift 该按的时候还是用吧 :rofl:

    (bookmark-set "org-pos" nil)
    (goto-char (point-min))
    (while (re-search-forward "\\([0-9]+\\):\\([0-9]+\\)" nil t)
      (replace-match "\\1:\\2"))
    (bookmark-jump "org-pos" nil)
    (bookmark-delete "org-pos")

我用的 bookmark,因为在把中文冒号替换成英文冒号时,用 save-excursion 会导致光标位置变化,bookmark 反而不影响。

1 个赞

能把这个改成当前行修改吗

在你想要保存光标的时候使用函数(bookmark-set "XXX" nil)

在你想要跳回保存的光标位置时使用函数(bookmark-jump "XXX" nil)

然后再使用函数(bookmark-delete "XXX")删掉之前保存的书签就好了。