Is there a way to print the definition of an existing function in Emacs?

10

2

I want to see the definition of an existing function in Emacs. Is this possible?

I've tried C-h d function-name RET, but it only returns the documentation string for the function, not the actual function itself.

I'm thinking something similar to bash's type command, which will return the whole definition of a function.

(Embarrassing backstory: I accidentally wrote over a working function in my .emacs file with a non-working version. The original function is still in memory! And it works! But I cannot for the life of me remember how I did it.)

Micah R Ledbetter

Posted 2011-11-10T22:50:08.413

Reputation: 302

1If you've kept .emacs opened in a buffer, try undoing like crazy. – Gilles 'SO- stop being evil' – 2011-11-11T01:14:00.247

Answers

10

If you type C-h f function-name RET, you'll get the function's documentation, with a link to the function source if available.

I don't think there's an easy Lisp function you can call to retrieve the location of a function's source; the lookup is pretty intertwined with the rest of the help system. find-lisp-object-file-name is the main function that attempts to figure out where the source of a function is.

Unless function-name is a primitive (defined in Emacs's C source), you can see its code with (symbol-function 'function-name), or more generally (indirect-function 'function-name). However, if the function was byte-compiled, all you'll see is its bytecode.

Gilles 'SO- stop being evil'

Posted 2011-11-10T22:50:08.413

Reputation: 58 319

1Thank you! (symbol-function 'function-name) is exactly what I was looking for! Also, it looks like if you really need the source to C functions you can get it using information from Oleg's answer. – Micah R Ledbetter – 2011-11-14T22:18:03.817

Thanks! Also, if the function is autoloaded, you need to call it once before you can get the source code. – Gerhard Burger – 2014-01-02T10:23:31.823

3

M-x find-function returns the definition of the function near the point.

From the documentation:

Finds the source file containing the definition of the function near point (selected by `function-called-at-point') in a buffer and places point before the definition. Set mark before moving, if the buffer already existed.

If you want to include also functions implemented in C you have to add the following to your .emacs file:

(setq find-function-C-source-directory (concat (getenv "emacs_home") "/path/to/source-dir"))

Oleg Pavliv

Posted 2011-11-10T22:50:08.413

Reputation: 336

Hmm. This is good to know, but I think it only works for built-in functions, which isn't what I was looking for. – Micah R Ledbetter – 2011-11-14T22:17:19.793

1It works for user-defined functions as well – Oleg Pavliv – 2011-11-15T06:24:14.500