Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim, open buffer without changing alternate file

Tags:

vim

Often times I like to switch back and forth between the alternate file.

If I need to look at another file just for a second and come back to where I was it's frustrating to lose the alternate file I was toggling between.

Anyway to not overwrite the alternate file for quick one-off buffer edits?

like image 745
Jonathan.Brink Avatar asked Feb 13 '23 22:02

Jonathan.Brink


2 Answers

You should better use the Control-i and Control-o mappings to move between positions across files. That way you can easily get back to your previous file.

Though to actually answer your question, as the alternate file is stored in the # register, I guess you could create a mapping that copies the # into a temporary register, open the file and restore the saved register into #. Theoretically that would be the following:

:let @x=@#|edit file|let @#=@x

but for some reason you can't write into the @# register.

Though in the help of alternate-file, there's the :keepalt command that is suggested to not overwrite the alternate file register with the command given as parameter:

:keepalt {cmd}              Execute {cmd} while keeping the current alternate file
                            name.  Note that commands invoked indirectly (e.g.,
                            with a function) may still set the alternate file
                            name.  {not in Vi}
like image 93
zmo Avatar answered Mar 02 '23 18:03

zmo


This is a wonderful opportunity to use a split. Either a normal split, :sp, or the preview window via :pedit as @RandyMorris suggested.

If you are using ctags you can use <c-w><c-]> to open a tag in a new window or <c-w>} to open the tag in a the preview window.

If you decide to use the preview window you can use <c-w>P to go directly to the preview window and <c-w>z to close the preview window.

Aternatively if you want to keep the alternative buffer you can use :keepalt command. e.g.

:keepalt e foo.c

However I feel as if this doesn't really solve your problem. Say you are looking at file A with an alternative file of B. You use :keepalt e C. Now you are on buffer C with an alt buffer of B. You would have to hit <c-o> (possibly a few times) to get back to file A. This feels a bit kludgy to me.

I should probably be worth noting that there is one time I really like to use the :keepalt command and that is with the :read. e.g. :keepa r foo.c.

If you plan on jumping between files often I really suggest you look into uppercase marks, ctags/cscope, and your split commands. If your project is well structured you may be able to use something like projectionist or maybe use something like a.vim to switch between .h and .c files.

For more help see:

:h :sp
:h :pedit
:h window-tag
:h :keepa
:h 'A
like image 32
Peter Rincker Avatar answered Mar 02 '23 16:03

Peter Rincker