(Re)Naming Functions

This is another note to myself. Quite often we want to give a function another name. Sometimes this is because we want a shorter name for a function that we use a lot. For example, even though I use smex I have several lines in my init.el file to quickly switch modes

(defalias 'om 'org-mode)
(defalias 'am 'abbrev-mode)
...

Another reason to rename a function is to change its functionality. The common example that everyone knows (even if they don’t do it) is to rename yes-or-no-p to y-or-n-p. We do this because we want to eliminate Emacs’ annoying insistence that we type “yes” or “no” in answer to certain questions.

There are two ways to rename functions

  1. Use defalias
  2. Use fset

Either one works where the other would but their operation is not identical. I can never remember the rules for when to use defalias versus fset, hence this note to myself.

Almost always, you want to use defalias because it records the file where the definition was made. Use it where a specific function name is being defined. The Elisp manual’s rule of thumb is that if you think of DEFINITION in

(defalias 'SYMBOL 'DEFINITION)

as the definition of the new function SYMBOL then you should use defalias.

Use fset for manipulation of function names. For example, if you want to change a function’s definition, you can use fset to save the old definition:

(fset 'old-some-func (symbol-function 'some-func))
(defalias 'some-func 'some-other-func-definition)

We use symbol-function in the fset so that we get the actual definition of some-func and not just its name, which is about to have its definition changed.

This entry was posted in Programming and tagged , . Bookmark the permalink.