Why can't I execute `following-char` using `execute-extended-command`? [duplicate] - emacs

This Stack Overflow answer told me that I can set Emacs’s font size with set-face-attribute:
(set-face-attribute 'default nil :height 100)
The comments reveal that you can’t run set-face-attribute with M-x:
Instead, you have to run it with M-::
Why are some commands, like set-face-attribute, not available via M-x?

M-x is bound to the command execute-extended-command, which lets you type the name of a command and runs it.
M-: is bound to the command eval-expression, which lets you type an arbitrary S-expression containing function calls and evaluates it.
Functions, which you can call with M-:, are used to implement Emacs features, customizations (such as in your .emacs), and plugins. Function arguments are normally passed by calling the function in an S-expression.
Any function can also be a command if it has an interactive form in its definition. The interactive form describes how the function should get its arguments when called as a command. For example, if the function has (interactive "bGive me a buffer: ") in its definition, then the function will be callable with M-x. When the user calls the function with M-x, Emacs will prompt the user for a buffer name (because of the b), and the name they type will be passed as an argument to the function.
The point of making a function a command is to make calling it easy for end-users, not just for Emacs Lisp programmers. Commands (run with M-x) are easier to run interactively in these ways:
You don’t have to surround the command name with () to make it a valid S-expression.
Arguments can be passed automatically (such as the cursor position), or you can be prompted for them so you don’t have to remember what arguments are needed.
When prompted for an argument, you can auto-complete it, because the interactive form’s code characters (like b) specify what type of input to expect.
The reason you can’t call the function set-face-attribute with M-x is that its definition does not contain an interactive form, and so set-face-attribute is not a command. You must call it as a plain function, in S-expressions. You can do that from the minibuffer with M-:, or from other places with any of the other ways of evaluating code.
Emacs Mini Manual → Concepts → Command has a short, differently-worded explanation of the difference between normal functions and commands. Relationship between Emacs functions and commands explains some details not in this answer.

Related

Emacs I want to call execute-kbd-macro from a lisp function

I want to call a keyboard macro from a Lisp function. I hope to layer in some custom error handling.
mykey is a keyboard macro stored in a text file in (fset ...) format.
I loaded it with load-file and it works fine when called with M-x mykey.
When I execute this function and plug in mykey I get only the name of the key displayed in current buffer, not it's execution. Is there a step I'm missing?
(defun gn-batch-search (key-name)
"Execute a keyboard macro that has already been loaded."
(interactive "sName of macro key:")
(execute-kbd-macro key-name))
Try
(defun gn-batch-search (key-name)
"Execute a keyboard macro that has already been loaded."
(interactive "sName of macro key:")
(execute-kbd-macro (intern key-name)))
The issue you bumped into is that the "sName of macro key:" interactive spec prompts the user and returns a string, and you want to run the command whose name is described by this string. That explains why it didn't do what you wanted and why you need intern.
As for why it did what it did: a keyboard macro is represented as a vector of events, where events can be things like mouse clicks or key presses. And as it turns out, a string is considered as a kind of vector (a vector characters) and a character is also an event (it represents the event that is sent when you press that character on your keyboard), so the string "hi" is a valid keyboard macro which represents the act of pressing h followed by pressing i, so when you run this macro, it will (usually) end up inserting "itself" in the current buffer (except in special buffers like dired, *Help*, ... where h and i are bound to other commands).
Also, rather than execute-kbd-macro you can use command-execute which will work with "any" command, whether it's defined as a keyboard macro or a normal function.

What is the difference between using "setq" or not to set an Emacs setting?

Very simple question but confuse me for some time:
(setq visible-bell t)
and
(visible-bell t)
both seem work.
But
(desktop-save-mode 1)
works, while
(setq desktop-save-mode 1)
not.
May I ask why is this?
They're different because they're different :)
(setq visible-bell t)
is assigning the value t to a variable named visible-bell.
(visible-bell t)
is calling a function1 named visible-bell (and passing the value t as a parameter).
(Although FYI there is no visible-bell function by default in current versions of Emacs, so it's not obvious to me that this is actually working the way you think? However, assuming for the moment that you do indeed have such a function...)
Emacs Lisp is a 'Lisp-2' meaning it has separate name spaces for variables and functions, and therefore you can -- and commonly do -- have a variable and a function with the same name. Which one is being referred to is always implicit in the context of the code (e.g. setq always refers to a variable).
In short, the two pieces of code are doing very different things. This doesn't mean they couldn't have an equivalent effect (e.g. the function might simply set the value of the variable); but whether or not that's actually the case is entirely up to the definition of the function.
1 In fact the first line of code is also calling a function2: it's calling setq and passing it two parameters visible-bell and t, and setq then sets the value in accordance with its parameters. Hopefully you're now starting to see how lisp syntax works?
2 Strictly speaking, setq is actually a "special form" rather than a function, and special forms are closer to macros than to functions; but these distinctions are not important for this Q&A.
Others have told you the basic points about what setq does and about variables versus functions.
Wrt visible-bell itself:
There is no function visible-bell delivered with Emacs, in any Emacs version I know of, and there never has been. (I've checked back through Emacs 20, and by memory I believe the same was true from the beginning. There is only the variable visible-bell.
So as #phils suggested, is not clear that what you said is true: "both seem to work". Unless some extra code you are loading defines a function of that name (and then there is no way for us to comment on it, not having it to see), evaluating (visible-bell t) raises an undefined (void) function error.
Variable visible-bell is not just a variable. It is a user option, and it has been, again, since at least Emacs 20.
You should not, in general, just use setq to change the value of a user option. In many cases you won't get into trouble if you do that, but sometimes you will, and it is not a good habit to get into.
setq does not perform any special initialization or updating actions that might be appropriate for a given user option. It is not intended for user options. Or rather, user options are not intended for setq - they can be more complex than what setq can offer.
What you should use instead of setq is Customize. Either interactively (M-x customize-option RET visible-bell RET, or C-h v RET visible-bell RET followed by clicking the customize link) or using Lisp code in your init file.
If you use Lisp code then use one of these functions (not setq):
customize-set-variable
customize-set-value
custom-set-variables
Use C-h f followed by each of those function names, to see what (minor) differences there are.
There are 3 issues here.
In Emacs Lisp, the same symbol can be both variable and function.
in the case of desktop-save-mode, it's a function but also a variable.
Because it's a function, so you can call
(desktop-save-mode 1)
Because it's a variable, so you set value to it
(setq desktop-save-mode t)
You can define your own function and also a variable of the same name to test it.
Note: exactly what a function's arguments should be or what the value of a variable makes sense depends on the function or variable.
Now, a second issue. In general, for function (commands) to activate a minor mode, the convention is that a positive integer should mean to turn it on, and otherwise turn off.
Also, for command to activate a minor mode, typically there's a variable of the same name, with value of t or nil, to indicate if the mode is on.
Now, there's third issue. For command to activate the mode, before emacs 24 or so, by convention, if no arg is given, the command toggle current state.
Because all of the above, the issue is confusing. You might see in init things like this:
(desktop-save-mode 1) ; correct. To turn on.
(desktop-save-mode) ; Confusing. Should take value 1 to turn on. Usually works because by default it's off.
(desktop-save-mode t) ; wrong. Take value of positive integer to turn on.
(desktop-save-mode nil) ; Confusing. Value should be integer
(setq desktop-save-mode t) ; wrong. Shoud call function instead
(setq desktop-save-mode nil) ; wrong. Shoud call function instead
(setq desktop-save-mode 1) ; wrong. Shoud call function instead. Besides, only t and nil make sense
So, there's a lot confusion. In emacs 24 (or 23.x), the convention changed so that, if it receives no value, it will turn on, if called in elisp code. (when called interactively as command, it toggles.)
In the end, always call describe-function or describe-variable to read the doc.
Well setq (which is "set" with an auto-quoting feature) is used in assigning a value to a variable. In this example, it's obviously not required because as you mentioned, omitting it works for the first set of examples.
Basically, visible-bell is a variable, and you assign it the value "t" to enable visible bells.
However, desktop-save-mode is an interactive function, so you don't use setq to assign it a value, you call it with parameters.
One good thing to do when you're not sure what something is, is to use the built-in help function:
C-h v visible-bell RET
This will return the information for visible bell -- notice the "v" in the command is because it's a variable. If you wanted to search for information on a function, you would do this:
C-h f desktop-save-mode RET
Incidentally in this case, desktop-save-mode is also a variable, but it's a read-only variable to determine whether or not desktop-save-mode is enabled, so trying to alter it will not work.

Binding a key to a command and automatically using the (interactive) default values for its interactive arguments

I would like F5 to switch to the most recently used buffer. This functionality is accomplished by running M-x icicle-buffer and then hitting enter to not specify the buffer I want to switch to -- (the default behavior of icicle is to switch to the most recent buffer.)
I have tried editing my .emacs thus:
(defun most-recent-buffer-please ()
(interactive)
(icicle-buffer " "))
(global-set-key [(f5)] 'most-recent-buffer-please)
but when I evaluate this lisp, and then hit F5, I get an error that starts with Wrong number of arguments followed by a lot of gibberish characters. What am I doing wrong?
A function can have mandatory and/or optional arguments, or no arguments at all. When writing elisp, it is usually a good idea to find out what arguments are available for certain functions by typing M-x describe-function RET [name of the function] RET. Drew (the author of Icicles) has indicated in his comment underneath the original question that the function icicle-buffer is not designed to be used in conjunction with any arguments -- therefore, adding " " causes the error message that the original poster experienced.
To switch to the previous buffer, Emacs already has a built-in function called previous-buffer. Since the original poster has indicated a preference for the f5 key, the following is an example of how to configure that keyboard shortcut so that it triggers previous-buffer -- brackets are sufficient and the parentheses used by the original poster around f5 can be omitted:
(global-set-key [f5] 'previous-buffer)

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.

Unable to understand a line of Emacs Lisp

The line is
function info() {
emacs -eval "(progn (setq Man-notify-method 'bully) (info \"$1\"))"
}
I know from manuals that
Progn
progn is a special form in `C source
code'.
Setq
setq is a special form in `C source
code'. (setq SYM VAL SYM VAL ...)
Set each SYM to the value of its VAL.
The symbols SYM are variables; they
are literal (not evaluated). The
values VAL are expressions; they are
evaluated. Thus, (setq x (1+ y)) sets
x' to the value of(1+ y)'. The
second VAL is not computed until after
the first SYM is set, and so on; each
VAL can use the new value of variables
set earlier in the setq'. The return
value of thesetq' form is the value
of the last VAL.
$1 seems to a reference to the first parameter after the command man which the user gives.
'bully seems to be a random variable.
Man-notify-method seems to be an action function which is run when man command is executed.
-eval seems to be an evalutian statemant which tells Emacs to run the statement which follows it.
However, I am not completely sure about the function.
I need to understand the function, since I want to bind a bash code of mine to the action function of man. Man-notify-method seems to be that action function, at least in Emacs.
How do you understand the line of Emacs Lisp?
The code you posted is a combination of shell script and elisp.
function info()
{
emacs -eval "(progn (setq Man-notify-method 'bully) (info \"$1\"))"
}
This defines a shell script function named info. It takes 1 parameter, named $1. When you call this function (say, from another shell script), the value of the argument gets substituted in for $1, and it runs the commands specified in sequence. So, if you were to call it like this:
info("something")
The shell would execute this command:
emacs -eval "(progn (setq Man-notify-method 'bully) (info \"something\"))"
This invokes the emacs executable with two arguments, -eval and the command string, which contains embedded escaped quotes. This is asking emacs to invoke the following elisp code:
(progn (setq Man-notify-method 'bully) (info "something"))
progn is a special form. Special forms evaluate their arguments differently than normal function calls. You can find the documentation for progn in chapter 10.1 of the GNU Emacs Lisp Reference Manual. progn is a simple construct for executing a sequence of statements in order. The reason you may need to do this is for cases when you want to execute multiple statements, but the context that you're in only expects a single statement.
For example, an if statement takes 3 (or more) arguments: the condition to evaluate, the expression to evaluate if true, and the expression to evaluate if false. If more than 3 arguments are provided, the subsequent arguments are part of the else branch. If you want to use more than one statement in the true branch, you have to use progn:
(if condition
(progn first-statement-if-true
second-statement-if-true)
first-statement-if-false
second-statement-if-false
)
In this case, if condition is true, then first-statement-if-true and second-statement-if-true will be evaluated. Otherwise, first-statement-if-false and second-statement-if-false will be evaluated.
Thus, your code will simply evaluate the two statements (setq Man-notify-method 'bully) and (info "something") in order.
setq is another special form. See chapter 11.8 for its documentation. It simply sets a variable, named by the first parameter, to the value of the second parameter. The first parameter is not evaluated -- it is taken literally.
A value preceded by a single quote (such as 'bully) is not evaluated. See chapter 9.3 for details on quoting. Hence, (setq Man-notify-method) sets a variable named Man-notify-method to the literal token bully (which is a data type called a symbol, which is distinct from the string "bully").
I can't find the documentation on the info function online, you can get help on any given function in emacs by typing C-h f function-name. So, by typing C-h f info, I got this:
info is an interactive autoloaded Lisp function in `info'.
[Arg list not available until function definition is loaded.]
Enter Info, the documentation browser.
Optional argument FILE specifies the file to examine;
the default is the top-level directory of Info.
Called from a program, FILE may specify an Info node of the form
`(FILENAME)NODENAME'.
In interactive use, a prefix argument directs this command
to read a file name from the minibuffer.
The search path for Info files is in the variable `Info-directory-list'.
The top-level Info directory is made by combining all the files named `dir'
in all the directories in that path.
The online reference manual is very useful, and emacs' interactive help is also indispensible. If you don't understand what a particular function does, just C-h f it.
PROGN simply evaluates the expressions in order, returning the return value of the last one.
SETQ is the basic assignment operator.
INFO enters the emacs info browser.
So, what this does is first assign the symbol 'bully to the variable Man-notify-method, then enter the info browser. 'bully is likely the name of a function, and Man-notify-method a place where the info browser looks up a function to call for some notification (Warning: I am just guessing here).
I guess that you will have to define your own function that calls your shell command like this:
(defun my-cmd ()
(call-process ; Look up the syntax in the emacs lisp manual
))
Then assign its symbol to Man-notify-method:
(setq Man-notify-method 'my-cmd)