]> git.eshelyaron.com Git - emacs.git/commitdiff
Improve 'key-translate' to support removing translations
authorCharalampos Mitrodimas <charmitro@posteo.net>
Tue, 2 Apr 2024 19:02:46 +0000 (19:02 +0000)
committerEshel Yaron <me@eshelyaron.com>
Thu, 23 May 2024 20:36:32 +0000 (22:36 +0200)
This patch enhances the key-translate function to allow removing
keyboard translations by passing nil as the second argument (TO).
If TO is nil, any existing translation for the FROM key will be
removed.  The compiler macro is updated to only check TO when it
is non-nil.  This change makes key-translate more consistent with
the behavior of 'keyboard-translate', providing a way to remove
translations without having to specify the same key for both FROM
and TO.
The documentation string is updated to reflect the new behavior.

* lisp/keymap.el (key-translate): Support removing translations
by passing nil as the second argument (TO).  Also signal an error
if multiple items are passed.  (Bug#70139)

(cherry picked from commit 8f010e9a2926bd3886c54a0360ff341bc66f8088)

lisp/keymap.el

index cbd26f1060e21d0777015ca0bcff16d782f343af..737c11dbd8301ca6a3602a61f54c940ee3e23657 100644 (file)
@@ -379,20 +379,35 @@ which is
 
 (defun key-translate (from to)
   "Translate character FROM to TO on the current terminal.
+
 This function creates a `keyboard-translate-table' if necessary
 and then modifies one entry in it.
 
-Both FROM and TO should be specified by strings that satisfy `key-valid-p'."
+Both FROM and TO should be specified by strings that satisfy `key-valid-p'.
+If TO is nil, remove any existing translation for FROM."
   (declare (compiler-macro
             (lambda (form) (keymap--compile-check from to) form)))
   (keymap--check from)
-  (keymap--check to)
-  (or (char-table-p keyboard-translate-table)
-      (setq keyboard-translate-table
-            (make-char-table 'keyboard-translate-table nil)))
-  (aset keyboard-translate-table
-        (aref (key-parse from) 0)
-        (aref (key-parse to) 0)))
+  (when to
+    (keymap--check to))
+  (let ((from-key (key-parse from))
+        (to-key (and to (key-parse to))))
+    (cond
+     ((= (length from-key) 0)
+      (error "FROM key is empty"))
+     ((> (length from-key) 1)
+      (error "FROM key %s is not a single key" from)))
+    (cond
+     ((and to (= (length to-key) 0))
+      (error "TO key is empty"))
+     ((and to (> (length to-key) 1))
+      (error "TO key %s is not a single key" to)))
+    (or (char-table-p keyboard-translate-table)
+        (setq keyboard-translate-table
+              (make-char-table 'keyboard-translate-table nil)))
+    (aset keyboard-translate-table
+          (aref from-key 0)
+          (and to (aref to-key 0)))))
 
 (defun keymap-lookup (keymap key &optional accept-default no-remap position)
   "Return the binding for command KEY in KEYMAP.