How to find aliases in emacs - emacs

I want to check if there is a default\ existing aliasing for a function (in this case:x-clipboard-yank, but the question is general).
Is there an emacs function that displays active aliases I can use to figure it up?
The expected behavior is like the shell alias command.

You can check the value of (symbol-function 'THE-FUNCTION). If the value is a symbol then THE-FUNCTION is an alias.
However, if the value is not a symbol THE-FUNCTION might nevertheless have been defined using defalias (or fset). In that case, THE-FUNCTION was aliased not to another function's symbol but to a function definition (e.g. the current function definition of some symbol, instead of the symbol itself) or to a variable definition (e.g. the value of a keymap variable).
You probably do not care about this case anyway - you probably do not even think of it as an alias. So testing whether the symbol-function value is a non-nil symbol is probably sufficient. (A value of nil means the there is neither a function alias nor any other function definition for the given symbol.)
So for example:
(defun aliased-p (fn)
"Return non-nil if function FN is aliased to a function symbol."
(let ((val (symbol-function fn)))
(and val ; `nil' means not aliased
(symbolp val))))
In response to the question in your comment: Here is a command version of the function:
(defun aliased-p (fn &optional msgp)
"Prompt for a function name and say whether it is an alias.
Return non-nil if the function is aliased."
(interactive "aFunction: \np")
(let* ((val (symbol-function fn))
(ret (and val (symbolp val))))
(when msgp (message "`%s' %s an alias" fn (if ret "IS" "is NOT")))
ret))
To be clear about the non-symbol case - If the code does this:
(defalias 'foo (symbol-function 'bar))
then foo is aliased to the current function definition of bar. If the definition of bar is subsequently changed, that will have no effect on the definition of foo. foo's definition is a snapshot of bar's definition at the time of the defaliasing.
But if the code does this:
(defalias 'foo 'bar)
then foo is aliased to the symbol bar. foo's function definition is the symbol bar: (symbol-function 'foo) = bar. So if bar's function definition gets changed then foo's definition follows accordingly.

To go in the other direction from what Drew mentioned, you'd need to scan the entire list of symbols to see if any 'pointed to' a given function symbol, since aliases are one-way relations.
So this function will give you a list of aliases that refer to a given function, using mapatoms to iterate over all symbols:
(defun get-aliases (fn-symbol)
"Return a list of aliases for the given function."
(let ((aliases nil))
(mapatoms (lambda (sym)
(if (eq fn-symbol (symbol-function sym))
(setq aliases (cons sym aliases)))))
(nreverse aliases)))
e.g.
(get-aliases 'cl-caddr) => (caddr cl-third)
since caddr and cl-third 'point to' cl-caddr.

Related

How do I define a function that creates a function alias?

The Lisp forum thread Define macro alias? has an example of creating function alias using a form such as
(setf (symbol-function 'zero?) #'zerop)
This works fine, making zero? a valid predicate. Is it possible to parametrize this form without resorting to macros? I'd like to be able to call the following and have it create function?:
(define-predicate-alias 'functionp)`
My take was approximately:
(defun defalias (old new)
(setf (symbol-function (make-symbol new))
(symbol-function old)))
(defun define-predicate-alias (predicate-function-name)
(let ((alias (format nil "~A?" (string-right-trim "-pP" predicate-function-name))))
(defalias predicate-function-name alias)))
(define-predicate-alias 'zerop)
(zero? '())
This fails when trying to call zero? saying
The function COMMON-LISP-USER::ZERO? is undefined.
make-symbol creates an uninterned symbol. That's why zero? is undefined.
Replace your (make-symbol new) with e.g. (intern new *package*). (Or you may want to think more carefully in which package to intern your new symbol.)
Your code makes a symbol, via MAKE-SYMBOL, but you don't put it into a package.
Use the function INTERN to add a symbol to a package.
To expand on Lars' answer, choose the right package. In this case the default might be to use the same package from the aliased function:
About style:
Anything that begins with DEF should actually be a macro. If you have a function, don't use a name beginning with "DEF". If you look at the Common Lisp language, all those are macro. For example: With those defining forms, one would typically expect that they have a side-effect during compilation of files: the compiler gets informed about them. A function can't.
If I put something like this in a file
(define-predicate-alias zerop)
(zero? '())
and then compile the file, I would expect to not see any warnings about an undefined ZERO?. Thus a macro needs to expand (define-predicate-alias 'zerop) into something which makes the new ZERO? known into the compile-time environment.
I would also make the new name the first argument.
Thus use something like MAKE-PREDICATE-ALIAS instead of DEFINE-PREDICATE-ALIAS, for the function.
There are already some answers that explain how you can do this, but I'd point out:
Naming conventions, P, and -P
Common Lisp has a naming convention that is mostly adhered to (there are exceptions, even in the standard library), that if a type name is multiple words (contains a -), then its predicate is named with -P suffix, whereas if it doesn't, the suffix is just P. So we'd have keyboardp and lcd-monitor-p. It's good then, that you're using (string-right-trim "-pP" predicate-function-name)), but since the …P and …-P names in the standard, and those generated by, e.g., defstruct, will be using P, not p, you might just use (string-right-trim "-P" predicate-function-name)). Of course, even this has the possible issues with some names (e.g., pop), but I guess that just comes with the territory.
Symbol names, format, and *print-case*
More importantly, using format to create symbol names for subsequent interning is dangerous, because format doesn't always print a symbol's name with the characters in the same case that they actually appear in its name. E.g.,
(let ((*print-case* :downcase))
(list (intern (symbol-name 'foo))
(intern (format nil "~A" 'foo))))
;=> (FOO |foo|) ; first symbol has name "FOO", second has name "foo"
You may be better off using string concatenation and extracting symbol names directly. This means you could write code like (this is slightly different use case, since the other questions already explain how you can do what you're trying to do):
(defmacro defpredicate (symbol)
(flet ((predicate-name (symbol)
(let* ((name (symbol-name symbol))
(suffix (if (find #\- name) "-P" "P")))
(intern (concatenate 'string name suffix)))))
`(defun ,(predicate-name symbol) (x)
(typep x ',symbol)))) ; however you're checking the type
(macroexpand-1 '(defpredicate zero))
;=> (DEFUN ZEROP (X) (TYPEP X 'ZERO))
(macroexpand-1 '(defpredicate lcd-monitor))
;=> (DEFUN LCD-MONITOR-P (X) (TYPEP X 'LCD-MONITOR))

define a symbol local inside the function?

Just as an example, put inside the function create x property and its value globally:
(defun foo ()
(put 'spam 'x 1))
(foo)
(get 'spam 'x) ; -> 1
Is it there way to set the symbol property locally?
No, because 'spam is always the same symbol a property can't be set on it locally.
I don't know if this would be appropriate for your situation, but you could create a fresh symbol and put the property on that. Because the symbol wouldn't be available outside the function neither would the property.
(defun foo ()
(let ((private (make-symbol "private")))
(put private 'x 1)
(get private 'x)))
(foo) ;=> 1
(get 'private 'x) ;=> nil
make-symbol returns a "newly allocated [and] uninterned symbol", which means the symbol returned by (make-symbol "private") is a different symbol from the global 'private and all others. See here for the Emacs manual's section on creating and interning symbols for more information.
Emacs also supports buffer-local variables, though that's not quite the same thing (the symbol's value is local to a particular buffer, but the symbol itself and its properties are still global).
If you just need to bind a value to a name locally, you could also use either Emacs 24's support for lexical binding or, if you're on an older version, lexical-let from the cl package (which is included with Emacs).
You can do it "locally" in the sense of dynamic-scoping:
(require 'cl-lib)
(defun foo ()
(cl-letf (((get 'spam 'x) 1))
(get 'spam 'x)))
(foo) ; -> 1
(get 'spam 'x) ; -> nil
Although I don't quite understand what is that you want to do, seems to me that you are looking for a closure, that is, a function with an environment. To do so you have to enable lexical binding, which is supported starting from emacs 24.3 IIRC. To enable it set the buffer local variable lexical-binding to t. The popular example of a closure would be an adder factory, that is a function that returns a function that adds by a constant.
(defun make-adder (constant)
(lambda (y) (+ y constant)))
(make-adder 3)
;; As you can see a closure is a function with an environment associated
=> (closure ((constant . 3) t) (y) (+ y constant))
(funcall (make-adder 3) 2)
=> 5
(funcall (make-adder 5) 2)
=> 8
So yes, using closures you can have private variables for a function.

why defun is not the same as (setq <name> <lambda>)?

I'm confused about how defun macro works, because
(defun x () "hello")
will create function x, but symbol x still will be unbound.
If I'll bind some lambda to x then x will have a value, but it will not be treated by interpreter as function in form like this:
(x)
I think that it is related to the fact that defun should define function in global environment, but I'm not sure what does it exactly mean. Why can't I shadow it in the current environment?
Is there any way to force interpreter treat symbol as function if some lambda was bound to it? For example:
(setq y (lambda () "I want to be a named function"))
(y)
P.S.: I'm using SBCL.
Common Lisp has different namespaces for functions and values.
You define functions in the function namespace with DEFUN, FLET, LABELS and some others.
If you want to get a function object as a value, you use FUNCTION.
(defun foo (x) (1+ x))
(function foo) -> #<the function foo>
or shorter:
#'foo -> #<the function foo>
If you want to call a function, then you write (foo 100).
If you want to call the function as a value then you need to use FUNCALL or APPLY:
(funcall #'foo 1)
You can pass functions around and call them:
(defun bar (f arg)
(funcall f arg arg))
(bar #'+ 2) -> 4
In the case of DEFUN:
It is not (setf (symbol-value 'FOO) (lambda ...)).
It is more like (setf (symbol-function 'foo) (lambda ...)).
Note that the two namespaces enable you to write:
(defun foo (list)
(list list))
(foo '(1 2 3)) -> ((1 2 3))
There is no conflict between the built-in function LIST and the variable LIST. Since we have two different namespaces we can use the same name for two different purposes.
Note also that in the case of local functions there is no symbol involved. The namespaces are not necessarily tied to symbols. Thus for local variables a function lookup via a symbol name is not possible.
Common Lisp has multiple slots for each symbol, including a value-slot, and a function-slot. When you use the syntax (x), common lisp looks for the function-slot-binding of x. If you want to call the value-binding, use funcall or apply.
See http://cl-cookbook.sourceforge.net/functions.html

lisp macro expand with partial eval

I have following code which confuse me now, I hope some can tell me the difference and how to fix this.
(defmacro tm(a)
`(concat ,(symbol-name a)))
(defun tf(a)
(list (quote concat) (symbol-name a)))
I just think they should be the same effect, but actually they seem not.
I try to following call:
CL-USER> (tf 'foo)
(CONCAT "FOO")
CL-USER> (tm 'foo)
value 'FOO is not of the expected type SYMBOL.
[Condition of type TYPE-ERROR]
So, what's the problem?
What i want is:
(tm 'foo) ==> (CONCAT "FOO")
The first problem is that 'foo is expanded by the reader to (quote foo), which is not a symbol, but a list. The macro tries to expand (tm (quote foo)). The list (quote foo) is passed as the parameter a to the macro expansion function, which tries to get its symbol-name. A list is not a valid argument for symbol-name. Therefore, your macro expansion fails.
The second problem is that while (tm foo) (note: no quote) does expand to (concat "FOO"), this form will then be executed by the REPL, so that this is also not the same as your tf function. This is not surprising, of course, because macros do different things than functions.
First, note that
`(concat ,(symbol-name a))
and
(list (quote concat) (symbol-name a))
do the exact same thing. They are equivalent pieces of code (backquote syntax isn't restricted to macro bodies!): Both construct a list whose first element is the symbol CONCAT and whose second element is the symbol name of whatever the variable A refers to.
Clearly, this only makes sense if A refers to a symbol, which, as Svante has pointed out, isn't the case in the macro call example.
You could, of course, extract the symbol from the list (QUOTE FOO), but that prevents you from calling the macro like this:
(let ((x 'foo))
(tm x))
which raises the question of why you would event want to force the user of the macro to explicitly quote the symbol where it needs to be a literal constant anyway.
Second, the way macros work is this: They take pieces of code (such as (QUOTE FOO)) as arguments and produce a new piece of code that, upon macroexpansion, (more or less) replaces the macro call in the source code. It is often useful to reuse macro arguments within the generated code by putting them where they are going to be evaluated later, such as in
(defmacro tm2 (a)
`(print (symbol-name ,a)))
Think about what this piece of code does and whether or not my let example above works now. That should get you on the right track.
Finally, a piece of advice: Avoid macros when a function will do. It will make life much easier for both the implementer and the user.

Can you create interactive functions in an Emacs Lisp macro?

I'm trying to write a macro in emacs lisp to create some ‘helper functions.’
Ultimately, my helper functions will be more useful than what I have here. I realize that there may be better/more intuitive ways to accomplish the same thing (please post) but my basic question is why won't this work/what am I doing wrong:
(defmacro deftext (functionname texttoinsert)
`(defun ,(make-symbol (concatenate 'string "text-" functionname)) ()
(interactive)
(insert-string ,texttoinsert)))
(deftext "swallow" "What is the flight speed velocity of a laden swallow?")
(deftext "ni" "What is the flight speed velocity of a laden swallow?")
If I take the output of the macroexpand and evaluate that, I get the interactive functions I was intending to get with the macro, but even though the macro runs and appears to evaluate, I can't call M-x text-ni or text-swallow.
This does what you want:
(defmacro deftext (functionname texttoinsert)
(let ((funsymbol (intern (concat "text-" functionname))))
`(defun ,funsymbol () (interactive) (insert-string ,texttoinsert))))
As has been pointed out, the solution is to use intern instead of make-symbol.
It's possible to create multiple independent symbols with the same name, but only one of them can be the canonical symbol for the given name -- i.e. the symbol you will obtain when you refer to it elsewhere.
intern returns the canonical symbol for the given name. It creates a new symbol only if no interned symbol by that name already exists. This means that it will only ever create one symbol for any given name1.
make-symbol, on the other hand, creates a new symbol every time it is called. These are uninterned symbols -- each one is a completely valid and functional symbol, but not the one which will be seen when you refer to a symbol by its name.
See: C-hig (elisp) Creating Symbols RET
Because defun returns the symbol it sets, you can observe what's going on by capturing the return value and using it as a function:
(defalias 'foo (deftext "ni" "What is the flight speed velocity of a laden swallow?"))
M-x text-ni ;; doesn't work
M-x foo ;; works
or similarly:
(call-interactively (deftext "shrubbery" "It is a good shrubbery. I like the laurels particularly."))
The tricky part in all this -- and the reason that evaluating the expanded form did what you wanted, and yet the macro didn't -- is to do with exactly how and when (or indeed if) the lisp reader translates the name of the function into a symbol.
If we write a function foo1:
(defun foo1 (texttoinsert) (insert-string texttoinsert))
The lisp reader reads that as text, and converts it into a lisp object. We can use read-from-string to do the same thing, and we can look at the printed representation of the resulting lisp object:
ELISP> (car (read-from-string "(defun foo1 (texttoinsert) (insert-string texttoinsert))"))
(defun foo1
(texttoinsert)
(insert-string texttoinsert))
Within that object, the function name is the canonical symbol with the name "foo1". Note, however, that the return value we see from read-from-string is only the printed representation of that object, and the canonical symbol is represented only by its name. The printed representation does not enable us to distinguish between interned and uninterned symbols, as all symbols are represented only by their name.
(Skipping ahead momentarily, this is the source of your issue when evaluating the printed expansion of your macro, as that printed form is passed through the lisp reader, and what was once an uninterned symbol becomes an interned symbol.)
If we then move on to macros:
(defmacro deffoo2 ()
`(defun foo2 (texttoinsert) (insert-string texttoinsert)))
ELISP> (car (read-from-string "(defmacro deffoo2 ()
`(defun foo2 (texttoinsert) (insert-string texttoinsert)))"))
(defmacro deffoo2 nil
`(defun foo2
(texttoinsert)
(insert-string texttoinsert)))
This time the reader has read the macro definition into a lisp object, and within that object is the canonical symbol foo2. We can verify this by inspecting the object directly:
ELISP> (eq 'foo2
(cadr (cadr (nth 3
(car (read-from-string "(defmacro deffoo2 ()
`(defun foo2 () (insert-string texttoinsert)))"))))))
t
So for this macro, it is already dealing with that canonical symbol foo2 before any macro call/expansion happens, because the lisp reader established that when reading the macro itself. Unlike our previous simple function definition (in which the function symbol was determined by the lisp reader as the function was defined), when a macro is called & expanded the lisp reader is not utilised. The macro expansion is performed using pre-existing lisp objects -- no reading is necessary.
In this example the function symbol is already present in the macro, and because it is the canonical symbol we could use (foo2) elsewhere in our code to call that function. (Or, had I made the definition interactive, use M-x foo2.)
Finally getting back to the original macro from the question, it's obvious that the lisp reader never encounters a function name symbol for the function it will define:
ELISP> (car (read-from-string "(defmacro deftext (functionname texttoinsert)
`(defun ,(make-symbol (concatenate 'string \"text-\" functionname)) ()
(interactive)
(insert-string ,texttoinsert)))"))
(defmacro deftext
(functionname texttoinsert)
`(defun ,(make-symbol
(concatenate 'string "text-" functionname))
nil
(interactive)
(insert-string ,texttoinsert)))
Instead this object produced by the lisp reader contains the expression ,(make-symbol (concatenate 'string "text-" functionname)); and that backquoted expression will be evaluated at expansion time to create a new uninterned symbol which will be a part of the object created by that expansion.
In our earlier examples the resulting object had a car of defun (interned), and a cadr of foo1 or foo2 (both also interned).
In this last example, the object has a car of defun (interned) but a cadr of an uninterned symbol (with the name resulting from the concatenate expression).
And finally, if you print that object, the printed representation of that uninterned function symbol will be the symbol name, and reading that printed representation back by evaluating it would cause the function cell for the canonical symbol to be defined instead.
1 In fact the unintern function can be used to unintern a symbol, after which calling intern for the same name would naturally create a new symbol; but that's not important for this discussion.
FWIW, if you use lexical-binding, you don't need to use a macro:
(defun deftext (functionname texttoinsert)
(defalias (intern (concat "text-" functionname))
(lambda ()
(interactive)
(insert-string texttoinsert))))
It's been years, but I think you're probably missing an fset to define the function; see the docs if you are wanting it a compile time too.