How to change the current path in Vim automatically?

When I type in the terminal something like

mvim ./path/to/my/project 

Vim opens this project directory, in my NERDTree I can see the files, but when I try to run some CLI command, for example

 :!touch some/file/in/my/project 

It happens that my current path is the home directory of my users

so if I want to create a file in my project, I have to enter the full path, for example

 :!touch ./path/to/my/project/some/file/in/my/project/name 

Is it possible to somehow change the directory automatically after starting vim?

+7
source share
5 answers

I use this in my vimrc:

 " Use %% on the command line to expand to the path of the current file cabbr <expr> %% expand('%:p:h') 
+4
source

In your specific use case, you can try connecting something to the VimEnter event. For example, try putting this in your vimrc:

 autocmd VimEnter * cd %:p:h 

Then, when you call Vim using $ mvim path/to/my/project/some/file Vim will automatically :cd into the file directory.

To do this, to work with directories, you will need to add a little logic to the auto command, for example.

 autocmd VimEnter * exe 'cd '.(isdirectory(expand('%:p')) ? '%:p' : '%:p:h') 

You can improve it yourself!

+4
source

How best to solve this depends on your specific use case. I am incomplete to :set autochdir , but if you want the working directory to be installed in the project root directory, I would use one of the local vimrc plugins (I use localrc.vim - Include a configuration file for each directory ), create a local .vimrc file in each of the roots of the project using

 :cd expand('<sfile>:p:h') 

. Then, no matter what file in the project hierarchy you open, the working directory will always be installed in the root directory of the project.

+3
source

in_vimrc

 au BufEnter * silent! lcd %:p:h 
0
source
0
source

All Articles