Updated answer with expansion time lookup:
I said in my original answer that there may be a way to do this at expansion/compile time instead of run time to give better performance and I finally implemented that today while working on my answer for this question: How can I determine which function was called interactively in the stack?
Here is a function that yields all current backtrace frames
(defun call-stack ()
"Return the current call stack frames."
(let ((frames)
(frame)
(index 5))
(while (setq frame (backtrace-frame index))
(push frame frames)
(incf index))
(remove-if-not 'car frames)))
Using that in a macro we can look up the expansion stack to see what function definition is being expanded at the time and put that value right in the code.
Here is the function to do the expansion:
(defmacro compile-time-function-name ()
"Get the name of calling function at expansion time."
(symbol-name
(cadadr
(third
(find-if (lambda (frame) (ignore-errors (equal (car (third frame)) 'defalias)))
(reverse (call-stack)))))))
Here it is in action.
(defun my-test-function ()
(message "This function is named '%s'" (compile-time-function-name)))
(symbol-function 'my-test-function)
;; you can see the function body contains the name, not a lookup
(lambda nil (message "This function is named '%s'" "my-test-function"))
(my-test-function)
;; results in:
"This function is named 'my-test-function'"
Original Answer:
You can use backtrace-frame
to look up the stack until you see frame that represents a direct function call and get the name from that.
(defun get-current-func-name ()
"Get the symbol of the function this function is called from."
;; 5 is the magic number that makes us look
;; above this function
(let* ((index 5)
(frame (backtrace-frame index)))
;; from what I can tell, top level function call frames
;; start with t and the second value is the symbol of the function
(while (not (equal t (first frame)))
(setq frame (backtrace-frame (incf index))))
(second frame)))
(defun my-function ()
;; here's the call inside my-function
(when t (progn (or (and (get-current-func-name))))))
(defun my-other-function ()
;; we should expect the return value of this function
;; to be the return value of my-function which is the
;; symbol my-function
(my-function))
(my-other-function) ;; => 'my-function
Here I am doing the function name lookup at runtime though it is probably possible to implement this at a macro that expands directly into the function symbol which would be more performant for repeat calls and compiled elisp.
I found this information while trying to write a sort of function call logger for elisp which can be found here in it's incomplete form, but it might be useful to you. https://github.com/jordonbiondo/call-log