How to go back to previous opened file in Vim? [duplicate]

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?


Solution 1:

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:

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