Skip to content
This repository was archived by the owner on Aug 23, 2025. It is now read-only.
This repository was archived by the owner on Aug 23, 2025. It is now read-only.

Better version of unbind-key which really deletes bindings #884

@minad

Description

@minad

@jwiegley Would it be possible to provide a version of bind-key/unbind-key which removes the bindings instead of only overwriting them with nil? If bind-key is passed nil as argument, it could call unbind-key.

The following function seems to work. It is derived from https://github.com/tarsius/keymap-utils/blob/master/keymap-utils.el by @tarsius.

(defun remove-key (key &optional map)
  (setq map (or map global-map)
        key (if (vectorp key) key (vconcat (kbd key))))
  (define-key map key nil)
  ;; Split M-key in ESC key
  (setq key (mapcan (lambda (k)
                      (if (and (integerp k) (/= (logand k ?\M-\0) 0))
                          (list ?\e (logxor k ?\M-\0))
                        (list k)))
                    key))
  ;; Delete single keys directly
  (if (= (length key) 1)
      (delete key map)
    ;; Lookup submap and delete key from there
    (let* ((prefix (vconcat (butlast key)))
           (submap (lookup-key map prefix)))
      (unless (keymapp submap)
        (error "Not a keymap for %s" key))
      (when (symbolp submap)
        (setq submap (symbol-function submap)))
      (delete (last key) submap)
      ;; Delete submap if it is empty
      (when (= 1 (length submap))
          (remove-key prefix map)))))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions