7

When I type in terminal something like

mvim ./path/to/my/project

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

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

It occurs, that my current path is my users home directory

so if I want to create file in my project dir, I must type full path like

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

Is it possible somehow to automatically change dir after vim starts?

ib.
  • 27,830
  • 11
  • 80
  • 100
Stanislav Mekhonoshin
  • 4,276
  • 2
  • 20
  • 25
  • possible duplicate of [How to set the correct path for a file in VIM?](http://stackoverflow.com/questions/12022142/how-to-set-the-correct-path-for-a-file-in-vim) – Michael Kristofik Dec 13 '12 at 16:43
  • I think not, autochdir doesn't solve my problem. I want to change dir to the root of my project, and nothing more. – Stanislav Mekhonoshin Dec 13 '12 at 16:49
  • The `:pwd` is supposed to be the directory in which you invoked Vim. Or `~` if you just launch GVim/MacVim. – romainl Dec 13 '12 at 17:56
  • I use vimprj plugin, and I had to disable the "feature" of aways comming back to the vimprj root directory because I didn't like it (`g:vimprj_changeCurDirIfVimprjFound = 0`). You may like this default behavior. – oblitum Dec 14 '12 at 14:45

5 Answers5

4

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')
Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
4

For your particular use case you could try hooking something up on the VimEnter event. For example, try putting this in your vimrc:

autocmd VimEnter * cd %:p:h

Then, when you invoke Vim with $ mvim path/to/my/project/some/file Vim will automatically :cd into the directory file is in.

For this to work with directories you will have to add a little logic to the autocommand, e.g.

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

You can improve on this yourself!

glts
  • 21,808
  • 12
  • 73
  • 94
3

How to best solve this depends on your exact use case. I'm partial to :set autochdir, but if you want the working directory set to the project root, I'd use one of the local vimrc plugins (I use localrc.vim - Enable configuration file of each directory), create a local .vimrc file in each of your project roots with

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

in it. Then, regardless of which file within the project hierarchy you open, the working directory will always be set to the project root.

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
1

in_vimrc

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

Try the following command

:cd %:p:h

https://vim.fandom.com/wiki/Set_working_directory_to_the_current_file

Greg
  • 5,862
  • 1
  • 25
  • 52