How to go back to previous opened file in Vim?

Vim

Vim Problem Overview


I can use gf to go to the file with name under/after cursor, is there any command to go back to the original file without relaunch vim to open it?

Vim Solutions


Solution 1 - Vim

Try using this shortcut:

CTRL-^

Vim documentation :help CTRL-^:

> CTRL-^ Edit the alternate file. Mostly the alternate file is the previously edited file. This is a quick way to toggle between two files. It is equivalent to ":e #", except that it also works when there is no file name.

And :help alternate-file

>If there already was a current file name, then that one becomes the alternate file name. It can be used with "#" on the command line |:_#| and you can use the |CTRL-^| command to toggle between the current and the alternate file. However, the alternate file name is not changed when |:keepalt| is used. An alternate file name is remembered for each window.

Solution 2 - Vim

Try following command

:e#

It will take you to the previously opened file stored in a buffer.


If you have gone deep down the hierarchy of files by typing multiple gf, vim stores all the files in numbered buffers

Then following command will take you to the nth file in a buffer. (n = 1,2,3,..)

:e#n

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomsonView Question on Stackoverflow
Solution 1 - VimZaffyView Answer on Stackoverflow
Solution 2 - VimjkshahView Answer on Stackoverflow