Vim Tips Wiki
(improving "add to path" code)
(Move categories to tip template)
Line 9: Line 9:
 
|version=5.7
 
|version=5.7
 
|rating=140/59
 
|rating=140/59
 
|category1=File Handling
  +
|category2=
 
}}
 
}}
 
Sometimes it's helpful if your working directory is always the same as the buffer you are editing. To achieve this, you can put the following in your vimrc:
 
Sometimes it's helpful if your working directory is always the same as the buffer you are editing. To achieve this, you can put the following in your vimrc:
Line 50: Line 52:
   
 
==Comments==
 
==Comments==
 
 
[[Category:File Handling]]
 

Revision as of 11:06, 24 April 2008

Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Tip 64 Printable Monobook Previous Next

created March 28, 2001 · complexity intermediate · author William Lee · version 5.7


Sometimes it's helpful if your working directory is always the same as the buffer you are editing. To achieve this, you can put the following in your vimrc:

autocmd BufEnter * lcd %:p:h

Doing this will "cd" to the directory of the file in the current buffer, each time you switch to the buffer. This is similar to VimTip2 but more automatic.

To not change the directory if one is editing in /tmp:

autocmd BufEnter * if expand("%:p:h") !~ '^/tmp' | lcd %:p:h | endif

Another approach is to keep Vim's starting directory, but have the capability to easily change directory to the file being edited. The mapping below does that.

map ,cd :cd %:p:h<CR>

If your main purpose in setting the working directory is to easily open files in a project, another approach is to add the directory to the path, so that you can use the "find" command to open any other file in the directory:

" always add the current file's directory to the path if not already there
autocmd BufRead *
      \ let s:tempPath=escape(escape(expand("%:p:h"), ' '), '\ ') |
      \ exec "set path-=".s:tempPath |
      \ exec "set path+=".s:tempPath

References

Comments