8

From the documentation of insert-char, I cannot see why

(insert-char "GREEK SMALL LETTER EPSILON")

doesn't work. Is there a non-interactive way to insert a character given its Unicode name?

Drew
  • 75,699
  • 9
  • 109
  • 225
Toothrot
  • 3,204
  • 1
  • 12
  • 30

1 Answers1

14

From the documentation of insert-char, I cannot see why

(insert-char "GREEK SMALL LETTER EPSILON")

doesn't work.

It doesn't work because insert-char understands Unicode character names only when called interactively (e.g. via C-x8RET or M-xinsert-charRET), as stated in its docstring:

Interactively, prompt for CHARACTER.  You can specify CHARACTER in one
of these ways:

 - As its Unicode character name, e.g. "LATIN SMALL LETTER A".
   Completion is available; if you type a substring of the name
   preceded by an asterisk ‘*’, Emacs shows all names which include
   that substring, not necessarily at the beginning of the name.

 - As a hexadecimal code point, e.g. 263A.  Note that code points in
   Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
   the Unicode code space).

 - As a code point with a radix specified with #, e.g. #o21430
   (octal), #x2318 (hex), or #10r8984 (decimal).

The interactive spec of insert-char delegates to read-char-by-name for Unicode name completion and translation to the corresponding character code.

When insert-char is called from Lisp, its first argument CHARACTER should satisfy the predicate characterp.

Is there a non-interactive way to insert a character given its Unicode name?

There are multiple ways; here's one for Emacs 26 and subsequent versions:

(insert (char-from-name "GREEK SMALL LETTER EPSILON"))

Here's another for earlier Emacs versions:

(insert (cdr (assoc "GREEK SMALL LETTER EPSILON" (ucs-names))))
Basil
  • 12,019
  • 43
  • 69
  • Where is `char-from-name` defined? – JeanPierre Jul 04 '18 at 09:49
  • @JeanPierre `M-x find-function RET char-from-name RET`, which reminds me that `char-from-name` was just added in Emacs 26; I've updated the answer accordingly. – Basil Jul 04 '18 at 10:08
  • I can get your "char-from-name" example to work, but the last example using "ucs-names" just gives me an wrong type argument error. – A.Ellett Mar 17 '22 at 18:36
  • @A.Ellett What's your `M-x emacs-version RET`? As stated in the answer, the very last example stopped working in Emacs 26 and subsequent versions. – Basil Mar 18 '22 at 13:01
  • I misunderstood what you meant. I thought you'd meant that the old code would still work and that `char-from-name` only came into being after Emacs 26. I have Emacs 27.2. So you've now explained why the old approach didn't work. Thank you. – A.Ellett Mar 18 '22 at 16:30