Question

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?

Was it helpful?

Solution

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?

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top