Retrieve source code of a function in emacs lisp

Discussion of Emacs Lisp

Retrieve source code of a function in emacs lisp

Postby erjoalgo » Wed Oct 31, 2012 11:50 am

Is there a function that extracts the source code definition of a given function in elisp?
For example, supposing "get-source" does what I need,
Code: Select all
ELISP> (defun say-hi () "Says hi" (message "Hi"))
say-hi
ELISP> (get-source 'say-hi)
"(defun say-hi () "Says hi" (message "Hi"))"
erjoalgo
 
Posts: 4
Joined: Sun Oct 28, 2012 9:31 am

Re: Retrieve source code of a function in emacs lisp

Postby stackman » Sat Nov 03, 2012 9:50 am

In your example, the definition is stored in the history of the ielm repl.
So I would suggest searching the history, e.g. with M-r defun say-hi RET
or, a bit more programmatically,
Code: Select all
(comint-previous-matching-input "^(defun say-hi" 1)

The whole history can be accessed from the tool bar, menu In/Out > List input history.
If you really want to get the code returned by the repl as a string, you can modify slightly
the definition of comint-previous-matching-history as follows
Code: Select all
  (defun get-source (regexp)
    (interactive (comint-regexp-arg "Previous input matching (regexp): "))
    (setq n (comint-search-arg 1))
    (let ((pos (comint-previous-matching-input-string-position
                  (concat "^\\s-*(defun\\s-*" (symbol-name regexp)) n)))
      (if (null pos) (error "Not found")
        (if (null comint-input-ring-index)
       (setq comint-stored-incomplete-input
        (funcall comint-get-old-input)))
        (setq comint-input-ring-index pos)
        (message "History item: %d" (1+ pos))
        (comint-delete-input)
        (substring-no-properties(ring-ref comint-input-ring pos)))))


This gives
Code: Select all
ELISP> (defun say-hi () "Says hi" (message "Hi"))
say-hi
ELISP> (get-source 'say-hi)
"(defun say-hi () \"Says hi\" (message \"Hi\"))"
stackman
 
Posts: 28
Joined: Sat Oct 06, 2012 5:44 am

Re: Retrieve source code of a function in emacs lisp

Postby edgar-rft » Sun Nov 04, 2012 4:27 am

Code: Select all
ELISP> (defun say-hi () "Says hi" (message "Hi"))
say-hi

ELISP> (symbol-function 'say-hi)
(lambda nil "Says hi"
  (message "Hi"))

But this works only if the function isn't byte-compiled or a built-in function written in C. In such cases use C-h f <function-name>.

- edgar
edgar-rft
 
Posts: 155
Joined: Fri Aug 06, 2010 6:34 am
Location: Germany


Return to Emacs Lisp

Who is online

Users browsing this forum: No registered users and 2 guests