Emacs command history including commands called by keys and with arguments passed to them - emacs

Is there a way to show full command history with arguments?
repeat-complex-command which is bound to:
<again>, <redo>, C-x M-:, C-x M-ESC
does not show commands that are invoked from key bindings, and kmacro-edit-macro (which is bound to C-x C-k RET) does not show arguments passed to commands.
Motivation. It would make it faster to turn a keyboard macro into an elisp function. For now, I invoke kmacro-edit-macro to see names of commands to use and then work out what arguments to pass by reading documentation of commands one by one. (Example workflow: https://stackoverflow.com/a/24784563/1446335)
Note. It is possible to programmatically press key sequence from within an elisp function, but its usefulness is small.

Yes, to get what you want, use pre-command-hook to invoke a function that adds the given command to extended-command-history. For example, this is what the Icicles code does to add commands executed by menu to this history:
;; This is done when you turn on Icicle mode.
(if icicle-menu-items-to-history-flag
(add-hook 'pre-command-hook 'icicle-add-menu-item-to-cmd-history)
(remove-hook 'pre-command-hook 'icicle-add-menu-item-to-cmd-history))
(defun icicle-add-menu-item-to-cmd-history ()
"Add `this-command' to command history, if it is a menu item.
Menu items that are not associated with a command symbol are ignored.
Used on `pre-command-hook'."
(condition-case nil ; Just in case, since this is on `pre-command-hook'.
(when (and (> (length (this-command-keys-vector)) 0)
(equal '(menu-bar) (elt (this-command-keys-vector) 0))
;; Exclude uninterned symbols such as `menu-function-356'.
(symbolp this-command) (or (< emacs-major-version 21) (intern-soft this-command)))
(pushnew (symbol-name this-command) extended-command-history))
(error nil)))

It would be great to have a way to turn a keyboard-macro into a chunk of Elisp code, but for this chunk of Elisp code to be useful, it should be somewhat idiomatic, yet in many cases, the idiomatic Elisp code to do something is quite different from the keyboard-macro way to do it (e.g. idiomatic code should not use the mark and the kill ring just to extract and move text around).
So the transcription is not straightforward. I think the way to write such a thing is to "start small" and accept the fact that it will not be 100% reliable.

Related

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.

Emacs/AUCTeX prefix arguments

In LaTeX mode C-c C-c is bound to:
(TeX-command-master &optional OVERRIDE-CONFIRM)
Normally this interactive function runs a command, perhaps a LaTeX compilation, asking for confirmation.
In tex-buf.el it reads:
If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
depend on it being positive instead of the entry in `TeX-command-list'.
This is a bit cryptic for me and reading C-h v TeX-command-list didn't help.
How can I pass the prefix argument to "TeX-command-master" so that I avoid all the confirmation requests?
Take a look at Emacs' documentation to find out about prefix arguments. In general, you can pass a command a prefix argument with C-u followed by a number. For one-digit numbers, you can also just type Meta followed by the digit. Thus to pass a positive prefix argument to TeX-command-master you could type:
M-1 C-c C-c
However, this will actually add another minibuffer confirmation, namely about the shell command to be used to compile the LaTeX source. Without the prefix argument, a command-dependent default is used for that.
If you want to avoid the question about the command to use, you can bind the undocumented variable TeX-command-force to "LaTeX" via:
(setq TeX-command-force "LaTeX")
However, this will have the downside that you're basically binding C-c C-c to the "latex" command, you cannot use any of the other commands such as "bibtex" or "view".
Other than that, LaTeX-mode does not allow for any customization of C-c C-c. Your best options are to either advise the function TeX-command-query or to bind C-c C-c to a wrapper function to set TeX-command-force dynamically. The latter would probably be the preferred option if you also want to auto-save the buffer.
It seems that the mystery of the OVERRIDE-CONFIRM continues. In the meantime a fellow suggests that, if we are unable to manage TeX-command-master, we can simply rewrite it.
In my version, based on his, if the buffer is not modified, the external viewer is launched; if the buffer is modified the compiler is run.
Everything with no confirmation for saving or running the given command.
(defun my-run-latex ()
(interactive)
(if (buffer-modified-p)
(progn
(setq TeX-save-query nil)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
(TeX-view)))
Of course one can bind my-run-latex to whatever keybinding.
On the user's point of view this is a solution to my own question.
Do I click the close tag? Well, on the curious guy point of view I am still interested in understanding the mysterious TeX-command-master technicalities.
If someone should happen to know...
P.S.
Yes, TeX-save-query overrides the save-file request, also with TeX-command-master, that is C-c C-c. But you will still be asked to confirm the command action.
Build & view
Again, this solution, instead of modifying the behaviour of the TeX-command-master, rewrites it. The rewritten version of the command, named build-view, follows a rather straightforward logic.
If the LaTeX file buffer is not-modified, it runs the default viewer;
If the buffer is dirty, it runs the default LaTeX compiler and, after the build, opens the output in the default viewer.
Here's the code:
(defun build-view ()
(interactive)
(if (buffer-modified-p)
(progn
(let ((TeX-save-query nil))
(TeX-save-document (TeX-master-file)))
(setq build-proc (TeX-command "LaTeX" 'TeX-master-file -1))
(set-process-sentinel build-proc 'build-sentinel))
(TeX-view)))
(defun build-sentinel (process event)
(if (string= event "finished\n")
(TeX-view)
(message "Errors! Check with C-`")))
You can now type M-x build-view and start the told build-view process or associate it with a new keybinding such as “F2”:
(add-hook 'LaTeX-mode-hook '(lambda () (local-set-key (kbd "<f2>") 'build-view)))
Note: As suggested by Tyler, TeX-save-query variable is changed locally, therefore the old C-c C-c/ TeX-command-master is unaffected and will keep asking confirmations.
Do edit this code to make it better or easier to read!
I puzzled over the OVERRIDE-CONFIRM bit for a while, and couldn't figure out how it was supposed to work. If you want to automatically run Latex on your file, without being bothered about saving it first, or confirming that you want latex (rather than view, bibtex etc), you could use a function like this:
(defun my-run-latex ()
(interactive)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
Bind this to something handy, and you'll still have C-c C-c for when you want to use the default processing commands. You may want to modify the TeX-command line if "Latex" isn't the processor you want to call.
If you are just looking to compile the latex source without a confirmation dialog, just add the following to your .emacs:
(setq TeX-command-force "")
You can then compile the source with C-c C-c and it won't ask to confirm. The only problem with this solution is that you can no longer change the command, but with most documents you won't want to. I might suggest that at the same time you can add this to your .emacs for even more flexibility, giving you a C-c C-c equivalent to the former behavior:
(define-key LaTeX-mode-map "\C-c\C-a"
;;; 'a' for ask, change to anything you want
(lambda (arg) (interactive "P")
(let ((TeX-command-force nil))
(TeX-command-master arg))))
You can then just work away at your document, do a C-x C-s, C-c C-c and then C-c C-v to see it. Like others have suggested you can also do the same for the save command and have it compile automatically on save, but some of my documents are in CVS and so I avoid putting hooks on that.
Credit to Ivan for some help on this one - don't know if he is on StackOverflow
I think the gist of this question is "how do I quickly compile my TeX document from AUCTeX without all the key presses and confirmations?"
My answer to that is to use the latexmk command rather than trying to coerce AUCTeX to do it.
latexmk -pdf -pvc myfile.tex
latexmk will monitor the file in question and rebuilt it as soon as you save it. If you use a good pdf viewer, it will notice the change in PDF and re-display it immediately. On OS X, skim works well for this.

Execute a particular command on multiple emacs buffers

Is there a way to execute emacs command on multiple buffers without having to selecting them individually and executing it on each individual buffer.
I usually open multiple files matching a particular regex, e.g. ~/*.py and wish to enable a particular mode, say hs-minor-mode or glasses-mode on each, or say execute C-c # C-M-h on each. Currently I have to select each one of them and do it individually. So is there a hack or a loop to automate the task.
Lets say I mark the buffers from the buffer-list and then run the command for all those marked.
I tried this but after executing the commands in eval-expression I completely lost access to my minibuffer, meaning whenever I typed M-x the minibuffer returned this
unable to access the minibuffer emacs error "Process Menu Mode doesn't support Hideshow Minor Mode"
and I was forced to actually kill the entire emacs process because the C-x C-s wasn't working neither was the End Task.
PS: I have no experience in elisp
You can use ibuffer mode for this (It is part of the default Emacs distribution).
(global-set-key "\C-x\C-b" 'ibuffer) ;; make ibuffer the default
In *Ibuffer* you can mark the required buffers with m and then
execute a form in each with E.
Generally, ibuffer is a lot more flexible then the usual buffer list and I think ibuffer should really be the default buffer-list in Emacs.
If you do this often, you might want to switch those particular modes on every time you enter python mode by attaching them to the mode-hook:
(add-hook 'python-mode-hook 'hs-minor-mode)
(add-hook 'python-mode-hook 'glasses-mode)
I didn't know ibuffer had that feature!
Anyway, for those who are more familiar with dired, here is a command that do the same. Select the files in dired with m or any other more powerful method. Then do, M-xdired-do-command and write a form or a command just as in M-x.
(defun dired-do-command (command)
"Run COMMAND on marked files. Any files not already open will be opened.
After this command has been run, any buffers it's modified will remain
open and unsaved."
(interactive
(list
(let ((print-level nil)
(minibuffer-history-position 0)
(minibuffer-history-sexp-flag (1+ (minibuffer-depth))))
(unwind-protect
(read-from-minibuffer
"Command: " (prin1-to-string (nth 0 command-history))
read-expression-map t
(cons 'command-history 0))
;; If command was added to command-history as a
;; string, get rid of that. We want only
;; evaluable expressions there.
(if (stringp (car command-history))
(setq command-history (cdr command-history)))))))
(dolist (filename (dired-get-marked-files))
(with-current-buffer (find-file-noselect filename)
(if (symbolp command)
(call-interactively command)
(eval command)))))

before defadvice not executing before the function?

[I apologize for the poor title, but couldn't come up with a better one.]
bin chen asked on Google+:
How to input relative path of (buffer-file-name) in minibuffer after M-! in #emacs?
I thought if the buffer-file-name is saved in a register, it should be accessible by invoking insert-register (C-x r i) while at the shell-command prompt.
(defun save-buffer-file-name-in-register ()
(set-register ?F (buffer-file-name))
(set-register ?D (file-name-directory buffer-file-name)))
(defadvice shell-command (before save-buffer-file-name)
"Save buffer-file-name to register F before running shell-command"
(save-buffer-file-name-in-register))
(ad-activate 'shell-command)
When I invoke shell-command (M-!) followed by insert-register (C-x r i), I get the error message: Register does not contain any text.
But when I run list-registers I do see that the registers F and D are set with the appropriate values. If I run the shell-command again, I can access the values from the registers previously saved.
Is it possible that the registers are being set too late for the first time? How can I fix the code to do what I want?
Edit: Changed around to before (Thanks to #phils)
n.b. You have defined around advice, not before advice.
Around advice acts as a wrapper, and must include the token ad-do-it to execute the code of the function it is wrapping.
You have effectively replaced the body of the shell-command function with a call to save-buffer-file-name-in-register
As to your main question, I'd need to check the documentation, but I suspect that because the arguments to the advised function are available to advice, the original function's interactive declaration probably executes before the advice does, which would explain why your register values are not visible at the interactive shell-command prompt.
(If the around in the above code is indeed what you were using, the fact that you were still being prompted for a shell command would seem to verify this sequence.)
When the interactive form runs, your advice hasn't executed yet. See: this question
You need to specify an interactive form in your advice that redefines the original if you want to stick with this approach. However, this approach is a little fancy-pants for the sake of fancy-pants-ness.
Just define your own interactive function which does what you want without registers.
(defun insert-cur-dir ()
(interactive)
(let ((dir-name (file-name-directory (buffer-file-name (window-buffer (minibuffer-selected-window))))))
(insert (or dir-name ""))))
(define-key minibuffer-local-map (kbd "C-c i") 'insert-cur-dir)
An alternative, but way awesomer approach is to use yasnippet.

Emacs Modes: "Command attempted to use minibuffer while in minibuffer"

Scenario:
I start to type M-x to type a command
I switch to another emacs window/buffer because I realise I'm executing the command in the wrong window
I start to type M-x again to execute the command in the correct window
Result: I get the dreaded "Command attempted to use minibuffer while in minibuffer"
This happens to me multiple times a day while using emacs, and not just in this scenario. This behaviour is highly user-hostile (ref. Modes and Pseudo-modes in The Humane Interface by Jef Raskin)
Is there a way to customize emacs behaviour so that instead of giving this error, it just cancels the first minibuffer and replaces it with a new one?
You can set the variable enable-recursive-minibuffers, which will prevent that error message from coming up. But it just enables multiple calls to the minibuffer - it doesn't redirect the current minibuffer's command to the new buffer. You can give this a try, but I think it'll be more confusing because the original action is still pending...
M-x is bound to 'execute-extended-command, and re-hosting (changing the original buffer) for that command is kind of like programming with continuation. i.e. you call a subroutine from location X, but instead of returning to X when done, you return to Y. I personally think it'd open up more confusion than it'd solve. But I understand the frustration (and know others who have the same frustration).
Indeed this emacs "feature" is aggressive and annoying.
I found this to be the right answer to the problem .Most likely you lost focus of the minibuffer because you switched windows with the mouse and NOT a minibuffer command. So whenever you lose focus using the mouse, the minibuffer will be cleared. Check this post. It works for me and it's way better than recursive minibuffers which will cause a headache
http://trey-jackson.blogspot.com/2010/04/emacs-tip-36-abort-minibuffer-when.html
I'm not sure if there is such a customization, but the way I avoid this is hitting ctrl-g to cancel the command I was in the middle of writing in the minibuffer.
Since my first answer doesn't directly give you what you want, I thought I'd come up with a real solution. This is what I have:
(defvar my-execute-extended-command-source-buffer nil
"var holding the buffer to which the extended-execute-command should apply")
(defvar in-my-execute-extended-command nil
"internal use - indicates whether we're in a 'recursive edit' of sorts")
(defun my-execute-extended-command (command)
"home-grown version of execute-extended-command that supports re-hosting the buffer"
(interactive (list (if in-my-execute-extended-command
nil
(let ((in-my-execute-extended-command t))
(setq my-execute-extended-command-source-buffer (current-buffer))
(completing-read "My-x " obarray 'commandp t nil 'extended-command-history nil nil)))))
(if in-my-execute-extended-command
(progn (setq my-execute-extended-command-source-buffer (current-buffer))
(select-window (minibuffer-window)))
(switch-to-buffer my-execute-extended-command-source-buffer)
(call-interactively (symbol-function (intern command)))))
I've tested it this way. I bound it to a key (F10 in my case b/c I didn't want to lose M-x). Then, with two windows open, each showing a different buffer (say A and B):
From window showing buffer A: F10 isearch-for
Switch from minibuffer to window showing A: C-x o
Switch from window showing A to that showing B: C-x o
"re-host" the command from buffer B: F10
Now back in the minibuffer, finish the command ward RET
When I started typing a search term, the search applied to buffer B.
This only replaces the M-x functionality, not the commands invoked from M-x. Also, this version does not support the prefix argument.
Hopefully this is what you want.
Here you go:
;; automatically cancel the minibuffer when you switch to it, to avoid
;; "attempted to use minibuffer" error.
;; cy was here
(provide 'cancel-minibuffer)
(defun cancel-minibuffer-first (sub-read &rest args)
(let ((active (active-minibuffer-window)))
(if active
(progn
;; we have to trampoline, since we're IN the minibuffer right now.
(apply 'run-at-time 0 nil sub-read args)
(abort-recursive-edit))
(apply sub-read args))))
(advice-add 'read-from-minibuffer :around #'cancel-minibuffer-first)
Can anyone improve on the following?
I've given up and just want to set \C-w to cancel any previous minibuffer before opening a new one (like doing \C-g\C-w)
So far thanks to Trey I've got:
(defun cancel-completing-read ()
(if (> (minibuffer-depth) 0) (exit-minibuffer))
(completing-read "My-x " obarray 'commandp t nil 'extended-command-history nil nil))
(defun cancel-and-execute-command (command)
(interactive (list (cancel-completing-read)))
(call-interactively (symbol-function (intern command))))
(global-set-key "\M-x" 'cancel-and-execute-command)
What command should I use in the place of exit-minibuffer above?
I've tried
keyboard-escape-quit
exit-minibuffer
keyboard-quit