Is it possible to programmatically let a function knows its own name?

What I am looking for is something which would allow me to write this code (or something similar):

function! myUtils#TestMe() abort
    let l:_self = " a way to get the current function name
    echom l:_self

Which, once called with :call myUtils#TestMe() would print:


2 Answers 2


Yes, there is :) Example:

function! Testing()
    " this is the droid you're looking for
    echo substitute(expand('<sfile>'), '.*\(\.\.\|\s\)', '', '')
    " compare with this (not what you want, just for reference)
    echo expand('<sfile>')

function! OutsideTesting()
    call Testing()

And the test:

:call Testing()
:call OutsideTesting()

Surprisingly perhaps, the solution is based on <sfile>, which returns something like function Testing (if called directly from Testing) or function OutsideTesting..Testing, if called from the "outer" function. See :h <sfile>. The substitute() call removes the first part of the expansion and leaves only the inner function name (you can also change the substitution pattern to leave only the outer function name instead - depends on what you want).

  • 1
    This is amazing! Thank you very much for the detailed answer and for your time.
    – mbilyanov
    Nov 17, 2015 at 23:26
  • This includes the text function preceding the function name.
    – Tom Hale
    Dec 22, 2021 at 5:49

Usage example:

function! PrintMyName()
    echomsg 'My name is: ' . FnName()

call PrintMyName()


My name is: PrintMyName

Behind the scenes:

" Stacktrace - return array of function names
" Eg, to get calling function name:  Stacktrace(expand('<sfile>'))[0]
" Based on: https://stackoverflow.com/a/33094990/5353461
function! Stacktrace(trace)
    return reverse(map(split(substitute(
                \ a:trace,
                \ '^function ', '', ''), '\.\.'),
                \ 'substitute(v:val, ''\m\[\d\+\]$'', "", "")'
            \ )[:-1]) " Remove the sourced file name

" The name of the calling function
" Pass parent = 1 to get the parent of the calling function
function! FnName(parent = 0)
  " + 1 because we want to ignore this function itself
  return Stacktrace(expand('<sfile>'))[a:parent + 1]

It's longer, but more hopefully also more generically useful :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.