Reputation: 8435
In an .vimrc
file, is it possible to only execute an autocmd if the file is loaded from a particular directory?
In MacVim, i have a line of code in my .vimrc
which automatically cds to the directory that contains the file i am editing - however it causes an error when i access the git files that :Gedit creates (vim package fugitive).
The autocmd is:
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
The error is:
Error detected while processing BufEnter Auto commands for "*":
From :echo expand("%")
it is clear that Fugitive creates paths that begin with fugitive:///
, so i am trying to figure out how to test if the first 12 characters of a file's path == fugitive:///
Upvotes: 4
Views: 1384
Reputation: 23102
There's a ticket for this issue.
autocm BufEnter * if expand('%:p') !~ '://' | :lchdir %:p:h | endif
This works well.
Upvotes: 1
Reputation: 8435
This can be achieved using the strpart
function.
I ended up settling on the following:
if strpart(expand("%:p:h"), 0, 15) == "/Users/myputer/"
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
endif
Which will only cd
to a folder if it begins with /Users/myputer/
Upvotes: 1
Reputation: 196886
Hmm, I think I've misunderstood. Your are changing the directory in the shell, not in Vim, don't you? In that case, autochdir won't be enough.
:Gedit
creates a temporary file with a funky name:
:e vimrc
:Gedit ~2
:echo expand("%")
fugitive:///home/romainl/.vim/.git//8aece3dc3c19522c33c997bc82a2487e3bdf013b/vimrc
:echo expand("%:p:h")
fugitive:///home/romainl/.vim/.git//8aece3dc3c19522c33c997bc82a2487e3bdf013b/
There's no way your shell is going to cd
to that "directory" because it is not a valid path.
However, I have set autochdir
which tells vim to cd
automatically to the directory containing the current file. Thanks to that I can see that the temporary file is in:
:pwd
/tmp/vGiSmH2
I could use the output of :pwd
to cd
there.
Upvotes: 2