I have a function in Vim script that returns a string.

" Return first directory with ".git" folder, if none is found
" return the current directory
function! s:project_root()
      for vcs in ['.git']
          let dir = finddir(vcs.'/..', expand('%:p:h').';')
          if !empty(dir)
              return dir
      " If there is no root dir use the current dir
      return expand('%:p:h')

I would like to use this function in a key mapping as the argument to a command called Files. So something like this

nnoremap <leader>f :Files<Space><insert result of function call here><CR>

I tried doing:

execute 'nnoremap <leader>f :Files<Space>'.s:project_root()

but I believe this only calls the function once (when the .vimrc is loaded), when I need the function to be called everytime the keybinding is pressed.

  • nnoremap <leader>f :Files s:project_root()<CR> should work. I can't get what a problem you are facing.
    – Alex Kroll
    Commented Jul 14, 2019 at 17:06
  • 1
    I tried that, and I'm pretty sure it just interprets s:project_root() as the directory name itself, instead of calling it.
    – Foobar
    Commented Jul 14, 2019 at 17:14

1 Answer 1


Do the :execute inside your mapping instead.

You don't need to use <Space> in mappings, you can just use an actual space instead.

You probably want to include a <cr> at the end, to actually execute the :Files command and not leave it pending on the command line waiting for you to press enter (but, again, maybe that's what you want?)

Putting it all together:

nnoremap <leader>f :execute 'Files '.<SID>project_root()<cr>

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.