22

How can I change my working directory to the path of the file that I currently have open?

Example

  1. current working directory is $HOME
  2. vim /tmp/test.log
  3. ???
  4. CWD is now /tmp/
staackuser2
  • 12,172
  • 4
  • 42
  • 40

3 Answers3

29

You can just type

:cd %:h

since %:h will be replaced by the head of the path to the current file.

Peter
  • 127,331
  • 53
  • 180
  • 211
29

That's actually a builtin. (here's the help link)

:set autochdir

Stick that in your .vimrc or whatnot (:e $MYVIMRC). As mentioned here, sometimes plugins will have issues with that and you need to use something more complicated like

autocmd BufEnter * lcd %:p:h
jkerian
  • 16,497
  • 3
  • 46
  • 59
  • Thanks, I wasn't aware of this! However, I want to do it manually, when needed. – staackuser2 Oct 02 '10 at 23:01
  • excellent bonus tip re lcd! I didn't know that existed, but will be very useful. – Peter Oct 03 '10 at 04:11
  • Plugins will often have just as many issues using the autocmd method. At least with 'autochdir' they can check to see whether the option is set. In reality good plugins these days account for potential directory changes due to loading files. – Ben Nov 21 '14 at 17:16
3

To change to the directory of the currently open file (this sets the current directory for all windows in Vim):

:cd %:p:h

You can also change the directory only for the current window (each window has a local current directory that can be different from Vim's global current directory):

:lcd %:p:h

In these commands, % gives the name of the current file, %:p gives its full path, and %:p:h gives its directory (the "head" of the full path).

Bruce
  • 107
  • 5