Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elisp: make symbol-function return the source?

Tags:

emacs

elisp

Here's the setup:

(defun square (x)
  (* x x))
;; square
(symbol-function 'square)
;; (lambda (x) (* x x))
(byte-compile 'square)
;; #[(x) "\211_\207" [x] 2]
(symbol-function 'square)
;; #[(x) "\211_\207" [x] 2]

Is there a way to get the source (lambda (x) (* x x)) after square has been byte-compiled?

The two uses that I can think of are inlining the current function call and doing a debug-step-in.

I've tried messing with find-definition-noselect to get the source, but I wonder if there's a better way, because it sometimes raises

(error "Don't know where ... is defined")
like image 568
abo-abo Avatar asked Jan 26 '26 00:01

abo-abo


1 Answers

Emacs keeps track of which function name is defined in which file (this info is kept in load-history). To find the definition, Emacs looks in load-history and if the function is listed there, it looks for the corresponding source file and then in that file looks for something that looks like a likely definition of the function (using regexps). That's what find-definition-noselect does.

As for the source code, no in general Emacs does not keep the source definition. If you define the function with cl-defsubst, then the source is kept around, but otherwise it isn't. For Edebugging, having the source wouldn't help anyway (because Edebug needs not just the source cod but also the precise location of each sub-expression); for plain debugging the source is not really needed either (you can always click on the function's name to jump to the source); for inlining the source is not needed either (the byte-compiler can inline at the source-code level, indeed, but it can just as well inline at the byte-code level).

like image 108
Stefan Avatar answered Jan 28 '26 00:01

Stefan