how to emulate a specific key press in Emacs Lisp - emacs

Context: I want to make a minor mode where pressing f twice fast results in whatever the pressing of ( should do at that time. This doesn't always mean just insertion of (. For example, in buffers where paredit mode or autopair mode is enabled, pressing of ( usually results in insertion of (). In a paredit mode buffer, that sometimes results in wrapping the selected text: for example, if I select a b and press (, that should result in replacing the selection with (a b).
For detection of f being pressed twice, I just need to take the logic in the short code in http://www.emacswiki.org/emacs/electric-dot-and-dash.el
So the only missing piece is a Lisp code snippet that tells Emacs "Trigger pressing of ( now!"
The first thing that came to my mind was that the snippet should do
find the command bound to the key (
and then call call-interactively on that command.
but that breaks down if the auto pairing package (autopair or paredit or other similar package) binds ( to a command that has a logic that looks up what key was used to call the command, or if the package simply relies on post-self-insert-hook or post-command-hook instead of binding (.
update
I've looked up Key Chord documentation and it turns out what I am trying to do with answers to this question has a simpler solution:
(require 'key-chord)
(key-chord-mode 1)
(defvar my-easy-open-paren-mode-map
(let ((map (make-sparse-keymap)))
(key-chord-define map ",." (kbd "("))
map))
(define-minor-mode my-easy-open-paren-mode
"In this mode, pressing . and , together is another way of pressing the open paren.")
(defvar my-easy-semicolon-mode-map
(let ((map (make-sparse-keymap)))
(key-chord-define map ";;" (kbd "C-e ;"))
map))
(define-minor-mode my-easy-semicolon-mode
"In this mode, pressing semicolon twice fast is another way of pressing C-e and semicolon.")
(add-hook 'prog-mode-hook 'my-easy-open-paren-mode)
(add-hook 'c-mode-common-hook 'my-easy-semicolon-mode)
Triggering key press may still be useful in other contexts though.

You might appreciate the Key Chord library for binding functions to a double key-press. (I wouldn't recommend using f if you'll be writing in English, mind you; but YMMV.)
post-self-insert-hook would still run if the binding was self-insert-command. post-command-hook will run in any case, but if you're worried about it seeing an incorrect function and/or input event, you can manipulate those...
After looking up the binding, your function can set this-command to the function you're about to call-interactively, and last-command-event to the required key. e.g.:
(defun my-fake-paren ()
(interactive)
(let ((command (key-binding "(")))
(setq last-command-event ?\()
(setq this-command command)
(call-interactively command)))

I use Key Chord for this sort of thing, although the page you link appears to do the same thing. The trick is getting the call to call-interactively to work correctly. I wrapped it in a let that reset the variable last-command-event, such that call-interactively thinks it was a "(". This works for me in paredit and fundamental modes.
(require 'key-chord)
(key-chord-mode 1)
(defun my-paren-call ()
(interactive)
(let ((last-command-event ?\())
(call-interactively (key-binding "("))))
(key-chord-define-global "ff" 'my-paren-call)

Related

What's the right name for CTL-]?

From my .emacs:
(defun flip-window () "Flip this window" (interactive)
(switch-to-buffer (other-buffer)))
;; later
(global-set-key [(control ?])] 'flip-window)
It works great, but I have two questions:
is there a built-in function to flip to most recently visited buffer?
While the above works at emacs startup, it causes problems when I'm trying to update settings, there's a parse error caused by the ?]. So is there a better way to express the control-] keystroke?
Answer to the question 2.
You may try the kbd function while setting the key binding.
Like so:
(global-set-key (kbd "C-]") 'flip-window)
And to the question 1: I guess there is no built in function for that. Emacs redux teaches us to implement it like:
(defun er-switch-to-previous-buffer ()
"Switch to previously open buffer. Repeated invocations toggle between the two most recently open buffers."
(interactive)
(switch-to-buffer (other-buffer (current-buffer) 1)))
This is part of Emacs Prelude distro. See https://emacsredux.com/blog/2013/04/28/switch-to-previous-buffer/
As a side note, you can get a description of any key combination in emacs using using the C-h k key combination, which runs the describe-key function. You'll have to read the textual form of your input from the description buffer. If you want to programmatically retrieve a string containing your key combination, you could also run the following Elisp code:
(destructuring-bind ((str . code)) (help--read-key-sequence)
(help-key-description str code))
It will prompt you for input in the minibuffer and return a string, such as e.g. "C-]".

Predicate-based dynamic key binding with default fallback [duplicate]

I'm trying to write a custom tab completion implementation which tries a bunch of different completions depending on where the point is. However, if none of the conditions for completions are met I would like tab to do what ever the current mode originally intended it to do.
Something like this:
(defun my-custom-tab-completion ()
(interactive)
(cond
(some-condition
(do-something))
(some-other-condition
(do-something-else))
(t
(do-whatever-tab-is-supposed-to-do-in-the-current-mode))) ;; How do I do this?
Currently I'm checking for specific modes and doing the right thing for that mode, but I really would like a solution that just does the right thing without me having to explicitly add a condition for that specific mode.
Any ideas of how to do this?
Thanks! /Erik
BTW, here is another solution:
(define-key <map> <key>
`(menu-item "" <my-cmd> :filter ,(lambda (cmd) (if <my-predicate> cmd))))
Here is a macro I wrote based on Emacs key binding fallback to define a keybinding conditionally. It adds the keybinding to the specified minor mode but if the condition is not true, the previously assigned action is executed:
(defmacro define-key-with-fallback (keymap key def condition &optional mode)
"Define key with fallback. Binds KEY to definition DEF in keymap KEYMAP,
the binding is active when the CONDITION is true. Otherwise turns MODE off
and re-enables previous definition for KEY. If MODE is nil, tries to recover
it by stripping off \"-map\" from KEYMAP name."
`(define-key ,keymap ,key
(lambda () (interactive)
(if ,condition ,def
(let* ((,(if mode mode
(let* ((keymap-str (symbol-name keymap))
(mode-name-end (- (string-width keymap-str) 4)))
(if (string= "-map" (substring keymap-str mode-name-end))
(intern (substring keymap-str 0 mode-name-end))
(error "Could not deduce mode name from keymap name (\"-map\" missing?)"))))
nil)
(original-func (key-binding ,key)))
(call-interactively original-func))))))
Then I can do things like the following to use the special binding for TAB only when I am on a header in outline-minor-mode. Otherwise my default action (I have both indent and yasnippets) is executed:
(define-key-with-fallback outline-minor-mode-map (kbd "TAB")
(outline-cycle 1) (outline-on-heading-p))
You could use functions such as key-binding (or its more specific variants global-key-binding, minor-mode-key-binding and local-key-binding) to probe active keymaps for bindings.
For example:
(call-interactively (key-binding (kbd "TAB")))
;; in an emacs-lisp-mode buffer:
;; --> indent-for-tab-command
;;
;; in a c++-mode buffer with yas/minor-mode:
;; --> yas/expand
One way to avoid infinite loops if your command is bound to TAB could be to put your binding in a minor mode, and temporarily disable its keymap while looking for the TAB binding:
(define-minor-mode my-complete-mode
"Smart completion"
:keymap (let ((map (make-sparse-keymap)))
(define-key map (kbd "TAB") 'my-complete)
map))
(defun my-complete ()
(interactive)
(if (my-condition)
(message "my-complete")
(let ((my-complete-mode nil))
(call-interactively (key-binding (kbd "TAB"))))))
It's possible that you could achieve this without any special workarounds at all. In most modes TAB just does indentation by default, but if you set the global variable tab-always-indent to 'complete it will try to do completion first, and indent if no completion is possible. This usually works really well, although if TAB is bound to another command in one of your major modes you might be out of luck.
If that works in the modes you need, you'll just need to add your custom completion function to the front of the list completion-at-point-functions in all applicable buffers (maybe using a mode hook). The completion-at-point command calls each function listed in completion-at-point-functions until one of them returns non-nil, so all you need to do to have your custom completion function "fall through" to the existing behavior is return nil from it.
This isn't a 100% answer to the question, but if the major modes you're working with are written according to the normal guidelines it might be the cleanest way.
define-key can accept quoted string or interactive lambdas like in this example.
;Static
(define-key evil-normal-state-mapr "m" 'evil-motion-state)
;Conditional
(define-key evil-normal-state-map "m"
(lambda () (interactive) (message "%s" major-mode)))
Lambda's can be replaced with named functions like my-tab-completion and used more effectively.
From define-key's docstring (Emacs 25)
DEF is anything that can be a key's definition:
nil (means key is undefined in this keymap),
a command (a Lisp function suitable for interactive calling),
a string (treated as a keyboard macro),
a keymap (to define a prefix key),
a symbol (when the key is looked up, the symbol will stand for its
function definition, which should at that time be one of the above,
or another symbol whose function definition is used, etc.),
a cons (STRING . DEFN), meaning that DEFN is the definition
(DEFN should be a valid definition in its own right),
or a cons (MAP . CHAR), meaning use definition of CHAR in keymap MAP,
or an extended menu item definition.
(See info node `(elisp)Extended Menu Items'.)

key chords in isearch

I really love key-chord.el. It's become an integral part of my workflow, but sometimes I wish I could have them in the minibuffer (for things like evil-search). Specifically, I'd like jj to exit out of evil-search and move down a line. Is this possible?
I know I can hack together a command that acts as both a prefix and a command (see this SO question), so I could bind j to a self inserting command, and jj to my special command. How would I be able to break the event loop after a specified idle time? I do type jj once in a blue moon, and I'd still like the flexibility of a timeout.
Is there any other way which I am unaware of to achieve what I want?
EDIT:
Origionally, this question was about the minibuffer in general. key-chord.el seems to work fine with minibuffer-local-map. It does not, however, work with isearch-mode-map. Binding a command to a single regular key like j does work in isearch. This is what I'm trying to solve.
I have found a solution which manually reproduces the behaviour of key-chord.el.
(defun isearch-exit-chord-worker (&optional arg)
(interactive "p")
(execute-kbd-macro (kbd "<backspace> <return>")))
(defun isearch-exit-chord (arg)
(interactive "p")
(isearch-printing-char)
(unless (fboundp 'smartrep-read-event-loop)
(require 'smartrep))
(run-at-time 0.3 nil 'keyboard-quit)
(condition-case e
(smartrep-read-event-loop
'(("j" . isearch-exit-chord-worker)
("k" . isearch-exit-chord-worker)))
(quit nil)))
;; example bindings
(define-key isearch-mode-map "j" 'isearch-exit-chord)
(define-key isearch-mode-map "k" 'isearch-exit-chord)
This approach actually has several advantages over key-chord.el.
It does not use an input method, so you can use a different input method in conjunction with this.
The first character is shown immediately, and retracted if it is incorrect, while key-chord.el only shows it after a delay.
I have found this to be useful:
(defun isearch-enable-key-chord ()
(key-chord-mode 1)
(key-chord-define isearch-mode-map "jj" 'isearch-cancel))
(add-hook 'isearch-mode-hook 'isearch-enable-key-chord)

Elisp: Conditionally change keybinding

I'm trying to write a custom tab completion implementation which tries a bunch of different completions depending on where the point is. However, if none of the conditions for completions are met I would like tab to do what ever the current mode originally intended it to do.
Something like this:
(defun my-custom-tab-completion ()
(interactive)
(cond
(some-condition
(do-something))
(some-other-condition
(do-something-else))
(t
(do-whatever-tab-is-supposed-to-do-in-the-current-mode))) ;; How do I do this?
Currently I'm checking for specific modes and doing the right thing for that mode, but I really would like a solution that just does the right thing without me having to explicitly add a condition for that specific mode.
Any ideas of how to do this?
Thanks! /Erik
BTW, here is another solution:
(define-key <map> <key>
`(menu-item "" <my-cmd> :filter ,(lambda (cmd) (if <my-predicate> cmd))))
Here is a macro I wrote based on Emacs key binding fallback to define a keybinding conditionally. It adds the keybinding to the specified minor mode but if the condition is not true, the previously assigned action is executed:
(defmacro define-key-with-fallback (keymap key def condition &optional mode)
"Define key with fallback. Binds KEY to definition DEF in keymap KEYMAP,
the binding is active when the CONDITION is true. Otherwise turns MODE off
and re-enables previous definition for KEY. If MODE is nil, tries to recover
it by stripping off \"-map\" from KEYMAP name."
`(define-key ,keymap ,key
(lambda () (interactive)
(if ,condition ,def
(let* ((,(if mode mode
(let* ((keymap-str (symbol-name keymap))
(mode-name-end (- (string-width keymap-str) 4)))
(if (string= "-map" (substring keymap-str mode-name-end))
(intern (substring keymap-str 0 mode-name-end))
(error "Could not deduce mode name from keymap name (\"-map\" missing?)"))))
nil)
(original-func (key-binding ,key)))
(call-interactively original-func))))))
Then I can do things like the following to use the special binding for TAB only when I am on a header in outline-minor-mode. Otherwise my default action (I have both indent and yasnippets) is executed:
(define-key-with-fallback outline-minor-mode-map (kbd "TAB")
(outline-cycle 1) (outline-on-heading-p))
You could use functions such as key-binding (or its more specific variants global-key-binding, minor-mode-key-binding and local-key-binding) to probe active keymaps for bindings.
For example:
(call-interactively (key-binding (kbd "TAB")))
;; in an emacs-lisp-mode buffer:
;; --> indent-for-tab-command
;;
;; in a c++-mode buffer with yas/minor-mode:
;; --> yas/expand
One way to avoid infinite loops if your command is bound to TAB could be to put your binding in a minor mode, and temporarily disable its keymap while looking for the TAB binding:
(define-minor-mode my-complete-mode
"Smart completion"
:keymap (let ((map (make-sparse-keymap)))
(define-key map (kbd "TAB") 'my-complete)
map))
(defun my-complete ()
(interactive)
(if (my-condition)
(message "my-complete")
(let ((my-complete-mode nil))
(call-interactively (key-binding (kbd "TAB"))))))
It's possible that you could achieve this without any special workarounds at all. In most modes TAB just does indentation by default, but if you set the global variable tab-always-indent to 'complete it will try to do completion first, and indent if no completion is possible. This usually works really well, although if TAB is bound to another command in one of your major modes you might be out of luck.
If that works in the modes you need, you'll just need to add your custom completion function to the front of the list completion-at-point-functions in all applicable buffers (maybe using a mode hook). The completion-at-point command calls each function listed in completion-at-point-functions until one of them returns non-nil, so all you need to do to have your custom completion function "fall through" to the existing behavior is return nil from it.
This isn't a 100% answer to the question, but if the major modes you're working with are written according to the normal guidelines it might be the cleanest way.
define-key can accept quoted string or interactive lambdas like in this example.
;Static
(define-key evil-normal-state-mapr "m" 'evil-motion-state)
;Conditional
(define-key evil-normal-state-map "m"
(lambda () (interactive) (message "%s" major-mode)))
Lambda's can be replaced with named functions like my-tab-completion and used more effectively.
From define-key's docstring (Emacs 25)
DEF is anything that can be a key's definition:
nil (means key is undefined in this keymap),
a command (a Lisp function suitable for interactive calling),
a string (treated as a keyboard macro),
a keymap (to define a prefix key),
a symbol (when the key is looked up, the symbol will stand for its
function definition, which should at that time be one of the above,
or another symbol whose function definition is used, etc.),
a cons (STRING . DEFN), meaning that DEFN is the definition
(DEFN should be a valid definition in its own right),
or a cons (MAP . CHAR), meaning use definition of CHAR in keymap MAP,
or an extended menu item definition.
(See info node `(elisp)Extended Menu Items'.)

Paredit: remove unwanted keybindings

I'm trying ParEdit mode and this is something that it does not the way I'd want: it shadows the original binding for C-M-F and replaces it with C-M-f. I.e. it forwards sexp instead of selecting it :| I couldn't find the place where the bindings are defined at the first glance.
Any way to cancel this behaviour? Or what would be the analogue command in ParEdit for selecting an sexp?
EDIT:
To give you a better idea of what happens, if I do C-h k while ParEdit is active, and then C-M-S-f this is what I get:
C-M-f (translated from C-M-S-f) runs the command paredit-forward,
which is an interactive compiled Lisp function in `paredit.el'.
It is bound to C-M-f.
(paredit-forward)
Move forward an S-expression, or up an S-expression forward.
If there are no more S-expressions in this one before the closing
delimiter, move past that closing delimiter; otherwise, move forward
past the S-expression following the point.
C-M-f
(foo |(bar baz) quux)
->
(foo (bar baz)| quux)
(foo (bar)|)
->
(foo (bar))|
[back]
I don't want it to translate anything, this is absolutely undesired behaviour.
You can use:
(eval-after-load "paredit"
'(progn
(define-key paredit-mode-map (kbd "C-M-f") nil)))
Strictly speaking the progn is unnecessary, but you might want to redefine/remove more keys afterwards
EDIT
Unlike forward-sexp, paredit-forward doesn't check whether shift is pressed. You could try using this
(eval-after-load "paredit"
'(progn
(define-key paredit-mode-map (kbd "C-M-S-f")
(lambda ()
(interactive)
(unless (region-active-p)
(set-mark (point)))
(paredit-forward)))))
EDIT
An alternative way to do the same thing (select the following sexp), would be C-M-space. Then, should you want to do so, you can swap point and mark with C-x C-x (or C-x (no delay here) C-x C-x if you use CUA)
EDIT (last?)
The proper way to make a function also mark when shift is pressed is this:
(put 'paredit-forward 'CUA 'move)
Paredit isn't translating the keys. Emacs is. It's the same in every mode. If there's no binding for C-M-F, Emacs will try C-M-f instead.
If you want to select the S-expression after the point, the standard Emacs key for this is C-M-SPC.
Resurrecting a very old question, but I think I know a more general solution to this.
paredit is a very old package that predates modern packaging hygiene. i.e. aggressive setting of default keybindings.
To undo that, run this after loading the paredit package:
(paredit-do-commands (spec keys _fn _examples) nil
(dolist (key keys)
(define-key paredit-mode-map (read-kbd-macro key) nil)))
now you're back to no keybindings, and you can use the regular mechanisms. Read the value (not the documentation) on paredit-commands to see which commands are available and what their default bindings are, some of which you might want to retain.