在Emacs Lisp中替换角色?

时间:2020-03-06 14:20:26  来源:igfitidea点击:

Emacs Lisp具有"替换字符串",但没有"替换字符"。我想用常规的ASCII引号替换"印刷"卷曲引号(此字符的Emacs代码为十六进制53979),我可以这样:

(replace-string (make-string 1 ?\x53979) "'")

我认为用replace-char会更好。

做这个的最好方式是什么?

解决方案

which would certainly be better with replace-char. Any way to improve my code?

它真的慢到了重要的程度吗?我的elisp通常效率低下,我从来没有注意到。 (不过,我仅将它用于编辑器工具,如果要使用它构建下一个MS实时搜索,则为YMMV。)

另外,阅读文档:

This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (search-forward "’" nil t)
    (replace-match "'" nil t))

该答案可能现在已获得GPL许可。

为什么不只是使用

(replace-string "\x53979" "'")

或者

(while (search-forward "\x53979" nil t)
    (replace-match "'" nil t))

如在文档中建议的替换字符串?

那这个呢

(defun my-replace-smart-quotes (beg end)
  "replaces ’ (the curly typographical quote, unicode hexa 2019) to ' (ordinary ascii quote)."
  (interactive "r")
  (save-excursion
    (format-replace-strings '(("\x2019" . "'")) nil beg end)))

一旦在dotemacs中拥有了该代码,就可以将elisp示例代码(来自博客等)粘贴到暂存缓冲区中,然后立即按CM-(正确缩进),然后按Mx my-replace-smart-quotes(修复)智能引号),最后是Cx Ce(运行它)。

我发现卷曲报价始终为hexa 2019,我们确定情况是53979吗?我们可以使用C-u C-x =检查缓冲区中的字符。

我认为我们可以在my-replace-smart-quotes的定义中用""代替" \ x2019"并可以。只是为了安全起见。