Vim Tips Wiki
No edit summary
(Contents of this tip are covered by Set working directory to the current file)
 
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
  +
#REDIRECT [[Set working directory to the current file]]
{{Duplicate|64|1146}}
 
{{review}}
 
{{TipImported
 
|id=1185
 
|previous=1183
 
|next=1188
 
|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 &lt;silent&gt; &lt;leader&gt;cd :cd %:p:h&lt;cr&gt;
 
</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 &lt;silent&gt; &lt;leader&gt;sp :sp &lt;c-r&gt;=expand('%:p:h')&lt;cr&gt;/
 
</pre>
 
 
(The last / can be changed to a backslash if on Windows.) Then, hitting &lt;leader&gt;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, 7 August 2011