suppose I want to bind a key to a partial key sequence (i.e. a key sequence that is a prefix of some other bound keybindings).
I've tried the obvious
(global-set-key (kbd "C-x C-x") (kbd "C-c"))
But that doesn't work for some reason.
suppose I want to bind a key to a partial key sequence (i.e. a key sequence that is a prefix of some other bound keybindings).
I've tried the obvious
(global-set-key (kbd "C-x C-x") (kbd "C-c"))
But that doesn't work for some reason.
If you want to no longer have the prefix key be a prefix key, and you want to instead bind it to a single command, you can do that - no problem: just bind it.
If you want to have the prefix key act as both a single command and as a prefix key then that is of course impossible - a key is bound to either a command or a keymap (or to a command that is a keymap).
But if you want to bind a different prefix key to the same keymap that is bound to some other prefix key, that is not a problem. What you tried to do suggests that this is maybe what you really want: to make the key sequence C-x C-x
act as a prefix key the same way that C-c
does.
To do that, you bind C-x C-x
not to C-c
but to the binding of C-c
. (lookup-key global-map (kbd "C-c"))
tells you that C-c
is bound to command mode-specific-command-prefix
(which is in fact a keymap). So if you bind C-x C-x
to that then it will behave like C-c
:
(global-set-key (kbd "C-x C-x") (lookup-key global-map (kbd "C-c")))
or just:
(global-set-key (kbd "C-x C-x") 'mode-specific-command-prefix)
For completeness, here's an alternative to Drew's answer. It may or may not be completely equivalent.
(defun simulate-key-press (key)
"Pretend that KEY was pressed.
KEY must be given in `kbd' notation."
`(lambda () (interactive)
(setq prefix-arg current-prefix-arg)
(setq unread-command-events (listify-key-sequence (read-kbd-macro ,key)))))
(global-set-key (kbd "C-x C-x") (simulate-key-press "C-c"))
OPTION # 1:
(global-unset-key "\C-x\C-x")
(global-set-key (kbd "C-x C-x C-c") 'help-for-help)
OPTION # 2:
The following example is taken from: .../lisp/textmodes/page-ext.el
and modified slightly:
(global-unset-key "\C-x\C-x")
(defvar ctl-x-ctl-x-map (make-sparse-keymap)
"Keymap for subcommands of C-x C-x, which are for PythonNut.")
(define-key ctl-x-map "\C-x" 'ctl-x-ctl-x-prefix)
(fset 'ctl-x-ctl-x-prefix ctl-x-ctl-x-map)
(define-key ctl-x-ctl-x-map "\C-c" 'help-for-help)
Example creating C-z
as a new global prefix key:
(global-unset-key "\C-z")
(defalias 'ctl-z-keymap (make-sparse-keymap))
(defvar ctl-z-map (symbol-function 'ctl-z-keymap)
"Global keymap for characters following C-z.")
(define-key global-map "\C-z" 'ctl-z-keymap)
(define-key ctl-z-map "\C-c" 'help-for-help)