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

∥☆過路亽.° 提交于 2019-12-19 07:28:33

问题


(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.


回答1:


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



回答2:


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

(Which-function)

more info:

  • https://www.masteringemacs.org/article/which-function-mode
  • http://emacsredux.com/blog/2014/04/05/which-function-mode/



回答3:


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))



回答4:


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.



来源:https://stackoverflow.com/questions/35907038/is-there-a-way-to-obtain-the-function-name-of-current-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!