If my buffer list looks like this:
:ls 1 %a "Application/PowerModeServer/test/testTimer.cpp" line 1 2 "Application/PowerModeServer/test/fakeClient.cpp" line 0 3 "Application/PowerModeServer/test/fakeVp.cpp" line 0 7 "Application/PowerModeServer/private/IMsgSender.h" line 0 9 "Application/PowerModeServer/private/UdpSocket.h" line 0 17 "Application/PowerModeServer/src/PowerFsm.cpp" line 0 18 "Application/PowerModeServer/src/lua/src/lfunc.h" line 0 19 "Application/PowerModeServer/src/lua/src/lmem.h" line 0 20 "Application/PowerModeServer/src/lua/src/ltable.h" line 0 41 "Application/PowerModeServer/src/PowerModeServer.cpp" line 0 42 "Application/PowerModeServer/src/UdpSocket.cpp" line 0 43 "Application/PowerModeServer/src/Timer.cpp" line 0
what’s the easiest way to change vim’s current working directory to the parent directory of, say, buffer 19? I’m used to finger-mumbling my way there using:
:cd A<TAB>P<TAB>s<TAB>l<TAB>s<TAB>
but this requires quite a few keystrokes—especially if the completions are ambiguous. I’d like something more concise, like:
:cd ~19
Any recommendations?
EDIT: Added mods suggested by ZyX here since I don’t have sufficient points to edit Jeet’s answer directly:
function! CdBufWorkingDir(target)
if empty(a:target)
let targetdir = expand("%:p:h")
else
if a:target =~# '^\~\d'
let targetdir = fnamemodify(bufname(str2nr(a:target[1:])), ":p:h")
else
let targetdir = a:target
endif
endif
execute "cd ".fnameescape(targetdir)
echo targetdir
endfunction
command! -nargs=? Cdbuf :call CdBufWorkingDir(<q-args>)
I would try something like this in your “~/.vimrc” (UPDATED in accordance to OP’s specs):
Then issuing the command with a buffer number preceded by a “~” as an argument (e.g.,
:Cdbuf ~3) will switch the working directory to that buffer’s working directory. If the argument is not preceded with “~”, it will be treated as a directory path directly to which to change. While the command without an argument will switch the working directory the current buffer’s working directory. For robustness, you should add some idiot-checking codes (e.g., what happens when multiple arguments are given?), or handle special cases (e.g., what happens if a string or buffer name is passed, or the file is a symlink).