Wikia

Vim Tips Wiki

Changes: Change to directory of the opened file

Edit

Back to page

(Adjust previous/next navigation)
(Contents of this tip are covered by Set working directory to the current file)
 
Line 1: Line 1:
{{Duplicate|64|1146}}
+
#REDIRECT [[Set working directory to the current file]]
{{review}}
 
{{TipImported
 
|id=1185
 
|previous=1183
 
|next=1189
 
|created=March 24, 2006
 
|complexity=basic
 
|author=orsenthil
 
|version=5.7
 
|rating=26/14
 
|category1=
 
|category2=
 
}}
 
The present working directory can be displayed in Vim with:
 
<pre>
 
:pwd
 
</pre>
 
 
To change to the directory of the currently opened file:
 
<pre>
 
:cd %:h
 
</pre>
 
 
==References==
 
{{help|filename-modifiers}}
 
 
==Comments==
 
Here's a mapping to make this easier:
 
<pre>
 
nmap <silent> <Leader>cd :cd %:p:h<CR>
 
</pre>
 
 
Note the use of <tt>:p</tt> first expand the % to a full path -- it takes care of the case where you're already in the correct directory. If that happens, %:h expands to an empty string and the :cd command throws an error. %:p:h is safe as it will never send an empty directory into the :cd command.
 
 
Note that 'autochdir' can be turned on to automatically switch to the directory of the current buffer upon entering the buffer. Alternatively, try:
 
 
<pre>
 
nmap <silent> <Leader>sp :sp <c-r>=expand('%:p:h')<CR>/
 
</pre>
 
 
(The last / can be changed to a backslash if on Windows.) Then, hitting <Leader>sp will produce a command-line all set to allow editing of a file in the same directory as the current buffer.
 
 
----
 
Also see [[VimTip64]] (Always set your working directory to the file you're editing)
 
 
----
 
This is very useful. Personally I have these commands defined:
 
<pre>
 
command! CD cd %:p:h
 
command! LCD lcd %:p:h
 
</pre>
 
 
----
 

Latest revision as of 20:18, August 7, 2011

  1. REDIRECT Set working directory to the current file

Around Wikia's network

Random Wiki