简体   繁体   中英

VIM: How to open another file from same location as an already open file

Let's say I am in my home directory. I open a file that is present in some deep nested directory structure:

vim /some/really/long/path/file.txt

Now, within vim, I want to start a vertical split with another file from that same long location (but I don't want to change the current directory to that path, I still want to be in the home directory).

A layman (like me) will do something like:

:vsp /some/really/long/path/file2.txt

But I want to find out from all you VIM geniuses out there, is there an easier way to do this?

On the same note, if I had multiple files already open residing in different paths, can VIM automatically assign some sort of internal variables to all the locations? And then when I want to start a new VSP or SP with one of the files from one of those locations, I simply use those internal variables?

Try this:

:vs %:p:h/otherfile

as %:p:h gives you the path of the current file. See :help %:p for more info.

Edit another file in the same directory:

:vs %<Tab><C-w><C-w><C-w>file2<Tab>

With a mapping:

nnoremap <key> :vs <C-R>=expand('%:p:h')<CR>

If you like more navigation than typing the commands, a convenient option could be the use of the embedded Explore command, which opens a window with the list files in the directory of the file in current buffer. Then you can navigate with the cursors and press v when over the file you want to open in a vertical split.

A convenient way is to map the Explore command, like:

" open embedded file system navigator
map <leader>\ :Explore<cr>

Press <leader>\\ and navigate to the file, then press v .

With some versions of vim, the Explore window stays open after pressing v -- in that case, if you want to avoid extra burden to close the Explore window, you can do first the vertical split with :vsp , invoke :Expore and open the desired file by pressing Enter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM