Go to the first, previous, next, last section, table of contents.

How do I "swap" two keys?

When Emacs receives a character, you can make Emacs behave as though it received another character by setting the value of keyboard-translate-table. The following Emacs Lisp will do this for you, allowing you to "swap" keys. After arranging for this Lisp to be evaluated by Emacs, you can evaluate `(swap-keys ?A ?B)' to swap A and B.

  (defun swap-keys (key1 key2)
    "Swap keys KEY1 and KEY2 using map-key."
    (map-key key1 key2)
    (map-key key2 key1))
  (defun map-key (from to)
    "Make key FROM behave as though key TO was typed instead."
    (setq keyboard-translate-table
          (concat keyboard-translate-table
      	    (let* ((i (length keyboard-translate-table))
      		   (j from)
      		   (k i)
      		   (str (make-string (max 0 (- j (1- i))) ?X)))
      	      (while (<= k j)
      		(aset str (- k i) k)
      		(setq k (1+ k)))
      	      str)))
    (aset keyboard-translate-table from to)
    (let ((i (1- (length keyboard-translate-table))))
      (while (and (>= i 0) (eq (aref keyboard-translate-table i) i))
        (setq i (1- i)))
      (setq keyboard-translate-table
            (if (eq i -1)
      	  nil
      	(substring keyboard-translate-table 0 (1+ i))))))

NOTE: You must evaluate the definition of these functions before calling them! For example, list the function definitions before their use in your .emacs file.

NOTE: These functions take two numbers as arguments. The example above, `(swap-keys ?A ?B)' is actually `(swap-keys 65 66)', because `?A' is merely notation for 65, the ASCII value of `A'.

NOTE: These functions only work for single characters. You cannot swap two multi-character sequences.


Go to the first, previous, next, last section, table of contents.