How to get directory of current file.

15 views
Skip to first unread message

DwigtArmyOfChampions

unread,
Apr 17, 2020, 10:47:20 AM4/17/20
to vim_use
I am using gVim on Windows. I open a file in C:\tmp called file1.cpp. After looking around in file1.cpp I now want to open file2.cpp which is also in C:\tmp. So I run the command

:e .\file2.cpp

But this doesn’t work because the “.” is C:\Windows\system32. Is there a different character or function or variable I can use in command mode to designate “the directory that the current file is in”?

Wood, Geoff (Refinitiv)

unread,
Apr 17, 2020, 11:08:55 AM4/17/20
to vim...@googlegroups.com
This seems to cover what you want:

https://vim.fandom.com/wiki/Easy_edit_of_files_in_the_same_directory

Personally I have a key mapped to change to the current file's directory:

map <F7> :cd %:p:h<CR>:pwd<CR>

based on this:

https://vim.fandom.com/wiki/Set_working_directory_to_the_current_file

regards,
Geoff

Gary Johnson

unread,
Apr 17, 2020, 11:23:45 AM4/17/20
to vim_use
One way:

:e %:h/file2.cpp

%:h will expand to the parent directory of the current file.

Another way:

:e ^R%

where ^R is Ctrl-R, will put the current file name on the command
line where you can edit it to the file name you want.

See

:help filename-modifiers
:help c_CTRL-R

Regards,
Gary

Tim Chase

unread,
Apr 17, 2020, 11:41:34 AM4/17/20
to DwigtArmyOfChampions, vim...@googlegroups.com
There are two main ways to do this

1) set 'autochdir'. This will automatically change directory to the
directory of the containing file so that "./" will always refer to
the directory of the current file.

2) use expand() or fnamemodify() with the various available modifiers
(":help filename-modifiers"). In this case you want either :p for the
absolute path or :~ for the path relative to your home directory.

-tim



Reply all
Reply to author
Forward
0 new messages