Emacs keylogger - emacs

I'm trying to implement a keylogger in Emacs (for my own, non-nefarious purposes).
It seems that I can reliably capture the last command through real-last-command in the pre-command-hook
So, I can do something like:
(setq keylog-list nil)
(defun my-keylogger-function ()
(setq keylog-list (cons real-last-command keylog-list)))
(add-hook 'pre-command-hook 'my-keylogger-function)
After a few movement commands, we get
keylog-list's value is
(describe-variable left-char left-char previous-line previous-line left-char eval-last-sexp)
However, I'm interested in capturing the arguments to these commands as well (e.g. the arguments to left-char, which will by default be 1 but may be different if prefix arguments are used.
Is there a way to access the args as well? Something like real-last-command-arglist?

A keylogger is also built into emacs: (open-dribble-file).

Why do you log the last (i.e. previous) command? If you log this-command instead, you can log current-prefix-arg, which corresponds to the prefix argument used.

Related

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

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.

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.

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.

How to call interactive Emacs Lisp function with a prefix argument, from another Emacs Lisp function?

I want to write an Emacs Lisp function that will turn on flyspell-mode regardless of the current state of the mode. Function flyspell-mode-on is deprecated. The documentation suggests that a positive prefix argument will turn flyspell-mode, but unfortunately running
(flyspell-mode 1)
results in an error message:
Wrong number of arguments: (lambda (flyspell-mode 1)), 0
If I could figure out how to call flyspell-mode with a prefix argument, I believe I could solve this problem.
The most relevant section I can find in the Emacs Lisp manual is the section entitled "Interactive Call", which describes such commands as call-interactively. This is emphatically not what I want.
(The ultimate problem I am trying to solve is to create a mode hook that turns on the mode regardless of its current state.)
N.B. The title of the question emacs lisp call function with prefix argument programmatically makes it appear to be related, but that question was asking about how to create an interactive command, and the issue was ultimately resolved by using call-interactively.
EDIT: This question is moot; I have found an alternate solution to my original problem:
(add-hook 'text-mode-hook
(function (lambda ()
(require 'flyspell)
(if flyspell-mode nil (flyspell-mode)))))
But I would still like to know how to call an Emacs Lisp function with a prefix argument, from another Emacs Lisp function, with nothing interactive.
UPDATE: Perhaps I should have asked why I was getting that error message...
It looks like your version of Flyspell mode does not follow the minor mode conventions, which require that you can turn on a minor mode with (name-of-mode t) or any positive prefix argument, turn it off with (name-of-mode 0) any negative prefix argument, and toggle it with (name-of-mode nil).
If you have the latest version of Flyspell, a bug report might be in order. I have the version shipped with GNU Emacs 23.2 on my machine, and it respects the convention. My version also defines two functions turn-on-flyspell and turn-off-flyspell, both trivial wrappers around flyspell-mode; functions with such names are common, but not official conventions. The functions flyspell-mode-on and flyspell-mode-off are apparently intended for internal use.
As a general matter, commands read the current prefix argument from the current-prefix-arg variable. Don't confuse that with prefix-arg, which is the value for the next command (only a few commands like universal-argument touch this variable). Thus, if you need to pass a prefix argument when calling a function, bind or set current-prefix-arg.
(let ((current-prefix-arg t))
(flyspell-mode))
If you are not calling a function interactively, then the (interactive) declaration is not used to obtain the arguments.
In the vast majority of cases, you do not need to worry about whether an argument can be a "prefix argument" for non-interactive calls; just check the function documentation, and pass the value you need for whatever it is you want to do.
If for some reason you do need to replicate sending a prefix argument in a non-interactive context, you will need to check that function's (interactive) declaration and determine exactly how it is using that argument, and ensure that you replicate that behaviour for the argument you do pass.
For full details, see:
C-hf interactive RET
M-: (info "(elisp) Prefix Command Arguments") RET
In more complex cases where the function changes its behaviour based on the current-prefix-arg variable, you may be able to set that variable directly.
(let ((current-prefix-arg '(4)))
(foo current-prefix-arg))
I can think of this.. Should be more better
(call-interactively (lambda ()
(interactive)
(flyspell-mode '(4))))
UPDATE:
I can run this directly.. what am i missing from the question.?
(flyspell-mode '(4))
EDITED: Removed quote for lambda expression (I added this note because SX forces an edit to be at least six characters long, so this can be deleted).
FWIW, the `flyspell-mode' function has accepted an argument (as in "(flyspell-mode 1)") at least since Emacs-21, so I don't know how you got that error.
But while I'm here, I might as well point out that (add-hook 'text-mode-hook 'flyspell-mode) has changed meaning in Emacs-24: instead of meaning "toggle flyspell-mode in text modes" it will now mean "enable flyspell-mode in text modes". It's a backward-incompatible change, but I believe it will fix more latent bugs than it will introduce.
See my comment for the fix to the source of your problem. As for the answer to your question, the way the prefix arg is turned into some kind of Lisp argument depends on the interactive spec, so the only way to do it reliably (i.e. without prior knowledge such as the fact that it's a minor mode function) is to call the function interactively:
(let ((current-prefix-arg '(4)))
(call-interactively 'flyspell-mode))
I'm not Emacs and Elisp master (yet ;)) but I think in this case you may use Ctrl-u 1 Alt-x flyspell-mode.

Usage of current-buffer in emacs?

I'm using emacs and I have written a script which uses "current-buffer". However the emacs system doesn't recognise "current-buffer". When I try "M - x current-buffer" i get the response:
no match
: Any idea what I'm doing wrong?
current-buffer is not an interactive function. That is, can't be invoked interactively via M-x as you've tried to do. You can execute non-interactive lisp-code directly by using eval-expression as follows:
M-: (current-buffer) RET
Notice that you have to enter a proper lisp expression. If you want to capture the value in a variable, something like this
M-: (setq xyzzy (current-buffer)) RET
will store the current buffer into the variable xyzzy.
Do I interpret you correct that you have created a function named current-buffer that you want to be available with M-x current-buffer?
To enable functions to be called by M-x function-name the function needs to be marked as interactive.
A sample from the emacs manual:
(defun multiply-by-seven (number) ; Interactive version.
"Multiply NUMBER by seven."
(interactive "p")
(message "The result is %d" (* 7 number)))
The (interactive "p") part makes the function callable from the minibuffer (through M-x).
I sounds like you would (also) like to know how to get the name of the current buffer interactively. Use M-: (buffer-name).