Why is (commandp '(customize-option 'foo)) nil? - emacs

I want to bind customize-option for a certain variable to a key, since I need to change it rather often. I have two options:
(global-set-key (kbd "<f12>") '(lambda() (interactive) (customize-option 'my-variable) ) )
(global-set-key (kbd "<f12>") '(customize-option 'my-variable )
The first one works, the second does not, because commandp complains that customize-option is not a command. Why? As far as I know, customize-option is an interactive function, so commandp should be t:
customize-option is an interactive compiled Lisp function.
It is bound to .
(customize-option SYMBOL)
Customize SYMBOL, which must be a user option variable.

It is the form (customize-option 'my-variable) which is not a command. You cannot bind to an arbitrary quoted form, any more than you can bind to a literal string or an unbound symbol. Some of those would be useful to bind to, but it's not hard to work around the limitations. Write a macro if you find it hard to live with. (As the saying goes, now you have two problems.)

The second argument to global-set-key must be a command definition, typically a symbol naming an interactive function. An interactive function is a function that begins with the (interactive) form. For example:
(defun delete-to-end ()
"Delete text from point to the end of buffer."
(interactive)
(delete-region (point) (point-max)))
This defines an interactive function and assigns it to the symbol delete-to-end. After that, delete-to-end is a valid command that you can pass to global-set-key:
(global-set-key [f12] 'delete-to-end)
Without the (interactive) line, delete-to-end would still name a function callable from Lisp programs, but it would not be a "command". Since it is marked interactive, (commandp 'delete-to-end) returns true, and M-x delete-to-end works.
Interactive functions don't need to be bound to a symbol, they can be anonymous. Like any other anonymous functions, they are created using a lambda form, except that for commands it must also include (interactive). Anonymous commands can be passed as the second argument to global-set-key without assigning them to a symbol, so the following definition is equivalent to the one above:
(global-set-key [f12]
(lambda ()
"Delete text from point to the end of buffer."
(interactive)
(delete-region (point) (point-max))))
...except it's somewhat less readable, and looks uglier when inspected with C-h c
or C-h k.
In your case, the first call to global-set-key is given a valid command (a quoted lambda form is itself a valid function), but the second one isn't, it is given a two-element list that can neither be called nor satisfies the requirement of being marked "interactive".

Related

passing function arguments in elisp

I have a function defined in my init.el:
(defun bind-key (keymap)
(evil-define-key '(normal insert) keymap (kbd "C-=") 'some-function))
(bind-key 'c++-mode-map)
But evil-define-key does not bind the C-= to some-function in keymap.
However, invoke evil-define-key directly is ok:
(evil-define-key '(normal insert) c++-mode-map (kbd "C-=") 'some-function)
I have tried:
(bind-key 'c++-mode-map)
(bind-key c++-mode-map)
Neither works.
I have googled for passing keymaps to a function, but found no solution. Then, I noticed evil-define-key is a macro. But I can not found solutions in this situation.
How can I get bind-key to work? By passing a keymap to it, the function binds C-= to some-function in in the keymap?
As you've noticed, this is trickier than it looks because evil-define-key is a macro (defined here). It takes a symbol that names a keymap variable, and binds the key once that variable has been defined. However, in this case it gets the symbol keymap instead of c++-mode-map, since a macro invocation receives as arguments the literal values in the call.
You can get around this by changing your own function into a macro. That means that instead of just running some code, it needs to return some code that then gets evaluated. Like this:
(defmacro bind-key (keymap)
`(evil-define-key '(normal insert) ,keymap (kbd "C-=") 'some-function))
The backquote introduces a form that gets returned verbatim, except for values inside it preceded by a comma.
Invoke it with (bind-key c++-mode-map), and it should be equivalent to your explicit call to evil-define-key.

Why does key binding cause Emacs to execute my function on startup?

I have a function in my Emacs init.el file that lets me rebuild and byte-compile it from a literate source file. It consists of a lambda function wrapped by defun and works exactly as I expect. So far, so good.
(defun tangle-init-and-reload ()
"Tangle the code blocks in init.org, byte-compile, and reload."
(lambda ()
(interactive)
;; Don't run hooks when tangling.
(let ((prog-mode-hook nil))
(org-babel-tangle-file (concat user-emacs-directory "init.org"))
(byte-compile-file (concat user-emacs-directory "init.el"))
(load-file user-init-file))))
When I read about functions in Elisp, it appears to me that I should be able to simply use defun to define a named function and skip the lambda, so I removed the lambda and otherwise left the function intact, like so:
(defun tangle-init-and-reload ()
"Tangle the code blocks in init.org, byte-compile, and reload."
(interactive)
;; Don't run hooks when tangling.
(let ((prog-mode-hook nil))
(org-babel-tangle-file (concat user-emacs-directory "init.org"))
(byte-compile-file (concat user-emacs-directory "init.el"))
(load-file user-init-file)))
Written this way, the function also works as expected -- as long as I call it with M-x tangle-init-and-reload RET. If I assign it a key binding, it executes on startup with one of two different side effects: With some key bindings, it attempts to overwrite init.elc while Emacs still has it open, and with others it successfully overwrites init.elc, but then re-executes on reload, causing an infinite recursion.
I'm perfectly happy to stick with the lambda version, which has no issues with key binding, but I would like to understand what magic lambda is performing and/or what it is about key binding that causes the second version to execute at startup. Can anybody explain?
For whatever it's worth, my key bindings are in a custom minor mode like so:
(defvar custom-map (make-keymap)
"Custom key bindings.")
(define-key custom-map (kbd "C-c C-i") (tangle-init-and-reload))
(define-minor-mode custom-bindings-mode
"Activates custom key bindings."
t nil custom-map)
When you define the key binding, you associate a key to a value, which in your case is:
(tangle-init-and-reload)
This is an expression that is evaluated normally, ie. you call the function when you associate the binding.
In the previous version, evaluating the same function returned a closure, you had one level of indirection, so you established a binding from a key to the function returned by the call to tangle-init-and-reload.
You can simply give the name of the function associated with the binding, by quoting it:
(define-key custom-map (kbd "C-c C-i") 'tangle-init-and-reload)

How to define key-binding with arguments for defun in Emacs?

I have a defun that conveniently adds / removes parentheses to marked expressions. (see code in the end)
As a neophyte in emacs Lisp, I only know how to make simple key-bindings without argument.
However, I believe the defun would be made more convenient if its key-binding could take two optional arguments to specify whether to add / remove (), [], or {}
My current (simple) key-binding is as below, is there a trivial way to make it argument-taking as described?
(global-set-key (kbd "C-M-( )") 'end-of-statement)
Appreciate any advice or direction tips!
(Code: by Istvan Chung)
(defun surround-with-parens ()
(interactive)
(save-excursion
(goto-char (region-beginning))
(insert "("))
(goto-char (region-end))
(insert ")"))
(defun delete-surrounded-parens ()
(interactive)
(let ((beginning (region-beginning))
(end (region-end)))
(cond ((not (eq (char-after beginning) ?\())
(error "Character at region-begin is not an open-parenthesis"))
((not (eq (char-before end) ?\)))
(error "Character at region-end is not a close-parenthesis"))
((save-excursion
(goto-char beginning)
(forward-sexp)
(not (eq (point) end)))
(error "Those parentheses are not matched"))
(t (save-excursion
(goto-char end)
(delete-backward-char 1)
(goto-char beginning)
(delete-char 1))))))
I assume the question is for surround-with-parens, as delete-surrounded-parens is probably better off just guessing the parentheses used by itself.
I also assume that you are doing this for practice more so than for actually solving the problem. If you enable electric-pair-mode in recent Emacsen, configured pairs will wrap around any active region as your command does. But it's a good mid-level emacs lisp exercise.
As the comments noted, you have multiple options.
Command Argument
A command can take arguments, as you asked for. Commands are no different from other lisp functions, except that they have an interactive spec. The interactive spec tells Emacs how to run the command when it is invoked with a key or via M-x.
Simple (interactive) will pass no arguments to the function. (interactive "r") will pass the beginning and end of the region as two arguments. Etc. You can read about the different options in C-h f interactive. You can even write lisp code to calculate the arguments there.
You could use (interactive "cWrap with: "). This would prompt the user for a key, and pass the key to your function. For example, if the user types (, your function receives 40 as the argument, the character code for the opening parenthesis. ?\( is 40 as well, and (make-string 1 40) returns "(". You'll have to create a map to figure out the closing parenthesis.
The drawback here is that you need to press two keys: The first to invoke the command, and then a key to specify the parenthesis to use.
Multiple keys
You can also bind your command to different keys – for example, C-M-( and C-M-[. You can then use this-single-command-keys to get something that specifies the last key event. Sadly, this can be somewhat tricky to translate back to a key sequence. E.g. C-M-( returns [201326632].
Multiple commands
You could also just define one command per parenthesis type, all of which simply call a common function with arguments, and bind those commands to keys.
post-self-insert-hook
Finally, you can use the same method as electric-indent-mode does: Add a function to post-self-insert-hook and decide based on char-before what you want to do.

emacs map several keystrokes and command to one key

I'm trying to map c-u m-x indent-pp-sexp to a single key, like F5, so that working with Emacs doesnt erode my fingerprints.
I use (global-set-key (kbd "C-u M-x indent-pp-sexp") "<f5>") but i'm getting the following error:
global-set-key: Key sequence C-u M-x i n d e n t - p p - s e x p starts with non-prefix key C-u
EDIT
With this lambda function (global-set-key (kbd "<f5>") (lambda (interactive) (universal-argument) (indent-pp-sexp t)))
Getting error:
recursive-edit: Wrong type argument: commandp, (lambda (interactive) (universal-argument) (indent-pp-sexp t))
Weird, because univeral-argument takes no parameters, and indent-pp-sexp takes boolean
You have the arguments the wrong way around, and you bind keys to functions, not to other key sequences. Perhaps you are really looking for a named macro; or you can write some actual Lisp and bind that to F5:
(global-set-key (kbd "<f5>")
(function (lambda () (interactive) (indent-pp-sexp t) )) )
The presence of an argument in the call form appears to be sufficient to select the prefix argument functionality.
You're missing the argument list to the lambda. Additionally I think passing t to indent-pp-sexp negates the need to call universal-argument.
(global-set-key (kbd "<f5>") #'(lambda ()
(interactive)
(indent-pp-sexp t)))
I'm a noob like you, but I already happened to figure basic things like making macros. I don't really know what's wrong with your code, but here's walkthrough of how I do things at home. What you need to do first, is press F3. Then type your keystrokes, and when finished, press F4. Congratulations, you have defined an anonymous macro. You can replay it as many times you wish by pressing F4 again. When you have played enough, enter M-x name-last-keybord-macro, and name it eg. foobar. Go to your ~/.emacs.d/macros/ directory (make it if you don't have one) and visit a file that you will name foobar.el. In its buffer, M-x insert-kbd-macro. When asked about name, say foobar. You will see that emacs has entered the contents of your just recorded macro into the file. Save it. Open your .emacs file, and add lines:
(load (expand-file-name "~/.emacs.d/macros/foobar.el"))
(global-set-key (kbd "M-<f5>") 'foobar)
And things start working for me after restart, with M-F5 as the binding for foobar.el macro.

How to find the location, where an an Emacs Lisp function is bound to a key?

I'm trying to figure out where M-m is bound to back-to-indentation function. When I issue C-h k M-m (describe-key), I get the following output
M-m runs the command back-to-indentation, which is an interactive
compiled Lisp function in `simple.el'.
It is bound to M-m.
(back-to-indentation)
Move point to the first non-whitespace character on this line.
When I look at simple.el, I'm seeing only the definition of function back-to-indentation. I searched throughout the file and I didn't see any keybinding done for that function using define-key. I'm assuming that it happens elsewhere.
How can I identify the location where the function is bound to M-m key?
Emacs version: GNU Emacs 24.2.1 (x86_64-apple-darwin12.2.0, NS apple-appkit-1187.34)
I don't know if that's possible in general, but my guess would be that Emacs doesn't remember where the code was that defined a given key.
C-hb will show the current bindings, from which you can establish which keymap you're interested in, and work from there. For most major or minor mode maps, it won't be too difficult to find the code.
Your specific example is a global binding which Emacs configures in bindings.el.
Adding this at the beginning of my .emacs did the trick for me:
(let ((old-func (symbol-function 'define-key))
(bindings-buffer (get-buffer-create "*Bindings*")))
(defun define-key (keymap key def)
(with-current-buffer bindings-buffer
(insert (format "%s -> %s\n" key def))
(mapbacktrace (lambda (evald func args flags)
(insert (format "* %s\n" (cons func args))))))
(funcall old-func keymap key def)))
The idea is that I redefine the define-key function (which is used to bind key within keymap to def) to first log its arguments to a buffer *Bindings*, together with the stacktrace of where it's being called from. After that it calls the old version of the function.
This creates a closure to store the old value of define-key, so it depends of lexical-bindings being t. In retrospect, I think it would have been possible to use function advising instead; but using a closure felt simpler.
Since I had this at the beginning of my .emacs, this recorded all calls to define-key during initialization. So I just had to switch to that buffer once initialization finished, find the call where the particular key was bound, and then inspect the backtrace to find the site from which that happened.