staackuser2
staackuser2

Reputation: 12412

Change working directory to currently opened file

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/

Upvotes: 24

Views: 10444

Answers (3)

Bruce
Bruce

Reputation: 127

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).

Upvotes: 3

jkerian
jkerian

Reputation: 17016

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

Upvotes: 30

Peter
Peter

Reputation: 132227

You can just type

:cd %:h

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

Upvotes: 34

Related Questions