6

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
endfunction

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

myUtils#TestMe
11

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

function! OutsideTesting()
    call Testing()
endfunction

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 '15 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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