tom
tom

Reputation: 1344

Is there a way to obtain the function name of current function?

(defun foo ()
    (send-to-debug-log "Error. Function terminated." (get-current-function-name)))

I currently do this:

(defun foo ()
    (send-to-debug-log "Error. Function terminated." 'foo)))

Hard coding the function name seems not to be a good practice. Any suggestion to implement the get-current-function-name or get-function-name-that-call-me.

Upvotes: 11

Views: 2250

Answers (4)

jpkotta
jpkotta

Reputation: 9417

Here's something that seems to work pretty well:

(defun calling-function ()
  (let ((n 6) ;; nestings in this function + 1 to get out of it
        func
        bt)
    (while (and (setq bt (backtrace-frame n))
              (not func))
        (setq n (1+ n)
              func (and bt
                      (nth 0 bt)
                      (nth 1 bt))))
    func))

If you call it in a lambda, you get the whole lambda. It works with apply, funcall, and eval.

I think the most simple, robust way is to just explicitly write the function name, as you're doing now.

Upvotes: 3

Ehvince
Ehvince

Reputation: 18375

With the package which-function-mode (in melpa), you can programmatically call the function

(Which-function)

more info:

Upvotes: 2

Stefan
Stefan

Reputation: 28521

You could try something like:

(defconst my-defun-macros '(defun cl-defun defmacro cl-defmacro))

(defun my-add-defun-name (orig-fun name &rest args)
  (let* ((my-current-defun-name (if (consp name) (cadr name) name))
         (macroexpand-all-environment
          (cons (cons 'my-get-current-function-name
                      (lambda () my-current-defun-name))
                macroexpand-all-environment))
         (code (apply orig-fun name args)))
    (macroexpand-all code macroexpand-all-environment)))

(defmacro my-get-current-function-name ()
  "Return current defun's name.
Only works within the advised macros in `my-defun-macros'."
  (error "my-get-current-function-name used outside of a defun"))

(dolist (m my-defun-macros)
  (advice-add m :around #'my-add-defun-name))

Upvotes: 5

Michael Albinus
Michael Albinus

Reputation: 1656

(defun foo ()
  (send-to-debug-log "Error. Function terminated." (nth 1 (backtrace-frame 2))))

Upvotes: 6

Related Questions