Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace-char in Emacs Lisp ?

Tags:

emacs

elisp

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?

like image 389
bortzmeyer Avatar asked Sep 18 '08 08:09

bortzmeyer


4 Answers

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.

like image 194
notetienne Avatar answered Nov 15 '22 09:11

notetienne


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?

like image 34
cjm Avatar answered Nov 15 '22 09:11

cjm


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.

like image 43
0124816 Avatar answered Nov 15 '22 09:11

0124816


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.

like image 35
Yoo Avatar answered Nov 15 '22 09:11

Yoo