It’s actually not that hard to understand. When you call a lisp function, either interactively or not, the caller gives a list of arguments. Those are assigned, one by one, to the list of names given in the definition of the function to be called. That’s basically it.
But there are two edge cases: if the caller doesn’t specify enough arguments, then it checks to see if the called function has those arguments marked as optional. If they are optional, then they get nil
as a value instead. If they are not optional, then it signals an error
.
If the caller specifies too many arguments, then it signals a different error.
Making a function interactive doesn’t change any of that. All it does is tell the Emacs UI how to build the argument list before it actually calls the function. That argument list is then used to call the function in exactly the normal way.
Should one use prefix variable in function if one intends to use the prefix argument?
I think you are asking about the name of the argument? The name doesn’t matter. Assume we have this function:
(defun foo (bar)
(interactive "P")
(message "prefix=%s" bar))
This function foo
takes one argument. The caller can pass anything that they want, but when called interactively Emacs will ensure that the first argument is the prefix argument, if any. Notice that we didn’t have to call this argument prefix
, but we did have to give it some name. If we hadn’t specified a name, the argument list would have been empty and the user would have gotten an error when they called it.
Should the prefix variable be optional?
It won’t matter. If you ask for the prefix to be passed in, then Emacs will always do so. If the user has not entered a prefix, then Emacs will pass in nil.
Should prefix variable always be the first argument?
It doesn’t matter at all. The order of arguments is entirely up to you. Just make sure that arguments you specify in your interactive
form and the names you specify in your argument list match up otherwise it will be confusing.
How would one call the function non-interactively?
The same way you would call any other type of function. Taking the example I gave above, you could call it like this: (foo 42)
. Just remember that the interactive form will not be examined and so you will have to specify all of the arguments yourself. The values you specify need not come from the same source, though.
Since all of this information is available in the Emacs manuals, I hope that you will do us the favor of reporting which parts of those manuals you read and how they failed to answer your questions. With this information we may be able to improve them. Without it, there can be no improvement.
Chapter 10 Evaluation of the Emacs Lisp manual in particular should cover most of what you need to know.