Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo up to last write in vim?

Tags:

Let me pose the question this way. I open a new file in vim, (version 1)

#include<stdio.h>
main()
{
...blah
}

and then use <Esc>:w<Enter> to write the file. Then made changes (version 2)

#include<stdio.h>
main()
{
...blah
... edit1
... edit2 //and large number of changes here and there in code
}

then I save changes using <Esc>:w<Enter>.

Is there a way to undo changes to version 1 directly (Since it was a last save) i.e., without constantly pressing u for undoing

like image 354
SKPS Avatar asked Aug 29 '13 00:08

SKPS


People also ask

How do you undo the last command in Vim?

Remember, yo undo a change in Vim / Vi use the command u , and to redo a change which was undone use Ctrl-R .

How do I undo last action in Vi?

To undo changes in Vim and Vi use the u , :u or :undo commands: If you are in insert or any other mode, press the Esc key to go back to the normal mode, which is also known as command mode. Type u to undo the last change.

Which command is used to undo the previous steps?

To undo an action press Ctrl+Z. If you prefer your mouse, click Undo on the Quick Access Toolbar. You can press Undo (or CTRL+Z) repeatedly if you want to undo multiple steps.


2 Answers

From Vim's help:

:earlier {N}f   Go to older text state {N} file writes before.
                When changes were made since the last write
                ":earlier 1f" will revert the text to the state when
                it was written.  Otherwise it will go to the write
                before that.
                When at the state of the first file write, or when
                the file was not written, ":earlier 1f" will go to
                before the first change.

So, if you didn't make changes after the second save, you can do what you want with:

:earlier 1f

On the other hand, if you did unsaved changes after the second save, then:

:earlier 2f

will solve your problem.

See :help :earlier, :help :undolist.

like image 113
elmart Avatar answered Sep 19 '22 20:09

elmart


You can get all the way back to when you first opened the file pretty easily. Just type a number before u.

10000u, will undo 10000 times. If that's not enough try 1000000u :)

If you want to undo bit by bit, you can do it in any increment, try 5u.

If you just want to reload the file from disk use :e.

like image 26
Paul Avatar answered Sep 17 '22 20:09

Paul