replace-char in Emacs Lisp ?

对着背影说爱祢 提交于 2019-12-07 06:04:22

问题


Emacs Lisp has replace-string but has no replace-char. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:

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

I think it would be better with replace-char.

What is the best way to do this?


回答1:


Why not just use

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

or

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

as recommended in the documentation for replace-string?




回答2:


This is the way I replace characters in elisp:

(subst-char-in-string ?' ?’ "John's")

gives:

"John’s"

Note that this function doesn't accept characters as string. The first and second argument must be a literal character (either using the ? notation or string-to-char).

Also note that this function can be destructive if the optional inplace argument is non-nil.




回答3:


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

Is it actually slow to the point where it matters? My elisp is usually ridiculously inefficient and I never notice. (I only use it for editor tools though, YMMV if you're building the next MS live search with it.)

Also, reading the docs:

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))

This answer is probably GPL licensed now.




回答4:


What about this

(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)))

Once you have that in your dotemacs, you can paste elisp example codes (from blogs and etc) to your scratch buffer and then immediately press C-M-\ (to indent it properly) and then M-x my-replace-smart-quotes (to fix smart quotes) and finally C-x C-e (to run it).

I find that the curly quote is always hexa 2019, are you sure it's 53979 in your case? You can check characters in buffer with C-u C-x =.

I think you can write "’" in place of "\x2019" in the definition of my-replace-smart-quotes and be fine. It's just to be on the safe side.



来源:https://stackoverflow.com/questions/90977/replace-char-in-emacs-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!