1

I'm writing some functions to make it easier to manage vim's current directory and I'm trying to figure out how to quote the directory name when assembling a command to execute.

Basically, I'm running execute printf("chdir %s", expand("%:h")) and I'd like to know how to make it more secure/predictable/functionally correct.

I can make that snippet a little bit more robust by using ' like this:

execute printf("chdir '%s'", expand("%:h"))

But I'm wondering if there's a solution that handles all cases.

For some context/motivation,

I have noautochdir set and a global variable g:dir_jump_orig to the value of the current working directory on startup:

set noautochdir
let g:dir_jump_orig = $PWD

function! DirJumpGoFocused()
  execute printf("chdir %s", expand("%:h"))
endfunction

function! DirJumpGoOrig()
  execute printf("chdir %s", g:dir_jump_orig))
endfunction

nnoremap <leader><c-i> :<c-u>call DirJumpGoOrig()<CR>
nnoremap <leader>c     :<c-u>call DirJumpGoFocused()<CR>

I'd like to make DirJumpGoOrig and DirJumpGoFocused more reliable.

1 Answer 1

4

You are looking for fnameescape():

execute 'cd ' . fnameescape(expand("%:h"))

For more help see :h fnameescape().

Your Answer

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

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