Navigate though previous edit points in vim? - vim

Is it possible in vim to navigate recursively to previous edit points (i.e. points where the text has been changed)? Such a feature would be incredibly useful for $\TeX$ document editing, where you often need to move large chunks of text fairly large distances, and navigation can get quite confusing.
Plugins with this functionality are welcome, if it can't be done with basic vim.

Something like Ctrl-O and Ctrl-I? These cycle through the 'jumplist' (O goes backwards, I forwards), which is the list of previous edits and jumps.
You can print the current jumpslist with :ju[mps]
For more detail on this funcitonality, check :h jumpslist

You can use g; to move to where the last change occurred.
g, moves back to more recent changes.
:changes shows you where g; and g, will take you.
gi is the same as g; except it also starts insert mode.

Related

Vim: Delete from cursor to next period

Is there a shortcut in vim to delete from the current cursor to the end of the sentence?
cursor
v
This is half a sentence. My cursor is here, but I would
like to delete to this period. I do not want to delete this part.
^
delete from cursor to here
Imagine my cursor is somewhere on the text that says My cursor is here,. How can I delete from this line all the way (and including) that next .?
Though there's no exact motion for that, there are several possibilities:
The ) motion deletes the remainder of the sentence, but that also includes the whitespace after the period.
If there were no hard line break, you could use the useful f motion (which only works in the current line, unless you install a plugin): f. This is also useful if you want to keep the period: t.
The most general motion is search via /. You need to search for a literal period (\.), and to include it, move to the end (/e) of it: /\./e<Enter>.
All of these have to be appended to the d "delete" command, which takes a {motion}.
Learn how to look up commands and navigate the built-in :help (here, :help motion.txt in particular); it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.
you should combine d with motion command. for your example, this will be d/\.<Ret>
This visual-mode editing may help you understand what actually happen:
v/\.<Ret>ld

Preferred way to move around in vim (normal mode)

I haven't seen this asked on stackoverflow, and this is my biggest pain point in vim:
How do you all navigate within a file? I found myself using the hjkl too much, or too repetitively, and I want to get better at this. This is frustrating when you're on a large monitor.
I installed EasyMotion - and so far it's been good for me - I just want to know if there's something better...
Thanks!
I like the cheatsheet of Ted Naleid. It's like a reticle so you can easily find the horizontal and vertical movements. Put it on a wall next to your monitor and you will soon pick up new movements on the fly.
The movements that I liked recently are:
() and {} which let you hop function wise in source code
/ and ? + n/N just search, you normally know where you want to go
fx and tx - to jump to or before the next character x
of course you can do a 2fx to jump to the second occurrence of x, like you can do with all movements
% to move between starting and ending parenthesis
I use b and w to move left and right respectively on a single line. For up and down, I use Ctrl+u and Ctrl+d respectively. IMO Ctrl+u and Ctrl+d are better than Ctrl+b and Ctrl+f because they scroll half window at a time so that you don't loose context.
I haven't really used any plugin for moving around in vim so far.
Forgot to mention two other important keystrokes, $ and ^ to move to end of line and start of line respectively.
Several move commands:
b B e E f F ge gE gj gk go G h H j k l L M n N t T w W { } / ? ^ $ # * ` ' | %
Learn them, plus all commands starting with [ like [{ which is very useful when editing C-style code…
See :help index.txt for reference.
Mostly I use the following (in order of frequency):
'R go to marked position (the ` is too off the baseline keyboard to use much)
/search|?search forward|backward search
n|N next|previous in search
H|L|M top|bottom|middle of display
G go to end of file
1G go to line 1
{ go backward a 'paragraph' (often a code block)
} go forward one 'paragraph'
Most all of these can be augmented with a count before the command.
It depends on how you want to move around, but generally,
A puts you in insert mode at the end of a line
I at the beginning
o inserts a line below
O above
and more powerfully, searching with /<thing you want to jump to> is very handy. In a c file where the functions are formatted
int
funcname()
/^funcname will jump you to the start of the function. There's a bunch more, but this shold be a good start for someone new to vim.
Simple documentation:
http://vim.wikia.com/wiki/Moving_around
Regular movement:
hjkl/arrow keys/page up/page down
% will switch between open/ending braces
gg/G move to top/bottom
Folding:
For collapsing large blocks of code, you can use folding.
http://vimdoc.sourceforge.net/htmldoc/fold.html
Search:
To jump to something in particular type /searchstring (use with set inc for jumping to matches while typing)
* to search forward for the same word the cursor is on
# same but search backward
You can also use marks.
http://vim.wikia.com/wiki/Using_marks
I also use ctags and jumping to find stuff across multiple files.
http://vimdoc.sourceforge.net/htmldoc/tagsrch.html
I've never needed anything else.
I don't really see much to add in terms of general enlightenment but I use (ranked by how often I use them):
w and b
to move by one word to the right and to the left.
/ and ?
to search for a word or pattern to the bottom or to the top.
G and gg
to jump to the bottom and the top of the buffer.
<C-f> and <C-b>
to jump to the next and previous screen.
* and #
to jump to next and previous occurence of the word under the cursor.
f and F
to jump before a character to the right or to the left.
t and T
to jump on a character to the right or to the left.
Ho! and
$ and ^
a lot, too, to jump to the end and the beginning of a line.
Read http://www.viemu.com/a-why-vi-vim.html and run vimtutor, also :help motion.txt will be usefull. I recommend also staying in normal mode all the time - as described in article above. Generally, learning vim is learning piano - you have to practice much.

What are the most-used vim commands/keypresses?

I'm a Ruby programming trying to switch from Textmate to MacVim, and I'm having trouble wading through the gargantuan lists of things you can do in VIM and all of the keypresses for them. I'm tired of hearing "You can use 'I' for inserting text, or 'a' for appending text after the character, or 'A' for appending text at the end of the line, or…" I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?
My ideal cheat sheet would be the 30-40 most-used keypresses or commands that everyone uses for writing code on a daily basis, along with the absolute essential plugins that rubyists use daily and the 10 most-used commands for them. In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.
Or, am I learning VIM the wrong way altogether?
Here's a tip sheet I wrote up once, with the commands I actually use regularly:
References
vim documentation online
advanced vim tips
more useful tips and graphical cheat sheet
General
Nearly all commands can be preceded by a number for a repeat count. eg. 5dd delete 5 lines
<Esc> gets you out of any mode and back to command mode
Commands preceded by : are executed on the command line at the bottom of the screen
:help help with any command
Navigation
Cursor movement: ←h ↓j ↑k l→
By words:
w next word (by punctuation); W next word (by spaces)
b back word (by punctuation); B back word (by spaces)
e end word (by punctuation); E end word (by spaces)
By line:
0 start of line; ^ first non-whitespace
$ end of line
By paragraph:
{ previous blank line; } next blank line
By file:
gg start of file; G end of file
123G go to specific line number
By marker:
mx set mark x; 'x go to mark x
'. go to position of last edit
' ' go back to last point before jump
Scrolling:
^F forward full screen; ^B backward full screen
^D down half screen; ^U up half screen
^E scroll one line up; ^Y scroll one line down
zz centre cursor line
Editing
u undo; ^R redo
. repeat last editing command
Inserting
All insertion commands are terminated with <Esc> to return to command mode.
i insert text at cursor; I insert text at start of line
a append text after cursor; A append text after end of line
o open new line below; O open new line above
Changing
r replace single character; R replace multiple characters
s change single character
cw change word; C change to end of line; cc change whole line
c<motion> changes text in the direction of the motion
ci( change inside parentheses (see text object selection for more examples)
Deleting
x delete char
dw delete word; D delete to end of line; dd delete whole line
d<motion> deletes in the direction of the motion
Cut and paste
yy copy line into paste buffer; dd cut line into paste buffer
p paste buffer below cursor line; P paste buffer above cursor line
xp swap two characters (x to delete one character, then p to put it back after the cursor position)
Blocks
v visual block stream; V visual block line; ^V visual block column
most motion commands extend the block to the new cursor position
o moves the cursor to the other end of the block
d or x cut block into paste buffer
y copy block into paste buffer
> indent block; < unindent block
gv reselect last visual block
Global
:%s/foo/bar/g substitute all occurrences of "foo" to "bar"
% is a range that indicates every line in the file
/g is a flag that changes all occurrences on a line instead of just the first one
Searching
/ search forward; ? search backward
* search forward for word under cursor; # search backward for word under cursor
n next match in same direction; N next match in opposite direction
fx forward to next character x; Fx backward to previous character x
; move again to same character in same direction; , move again to same character in opposite direction
Files
:w write file to disk
:w name write file to disk as name
ZZ write file to disk and quit
:n edit a new file; :n! edit a new file without saving current changes
:q quit editing a file; :q! quit editing without saving changes
:e edit same file again (if changed outside vim)
:e . directory explorer
Windows
^Wn new window
^Wj down to next window; ^Wk up to previous window
^W_ maximise current window; ^W= make all windows equal size
^W+ increase window size; ^W- decrease window size
Source Navigation
% jump to matching parenthesis/bracket/brace, or language block if language module loaded
gd go to definition of local symbol under cursor; ^O return to previous position
^] jump to definition of global symbol (requires tags file); ^T return to previous position (arbitrary stack of positions maintained)
^N (in insert mode) automatic word completion
Show local changes
Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
Here is a great cheat sheet for vim:
Have you run through Vim's built-in tutorial? If not, drop to the command-line and type vimtutor. It's a great way to learn the initial commands.
Vim has an incredible amount of flexibility and power and, if you're like most vim users, you'll learn a lot of new commands and forget old ones, then relearn them. The built-in help is good and worthy of periodic browsing to learn new stuff.
There are several good FAQs and cheatsheets for vim on the internet. I'd recommend searching for vim + faq and vim + cheatsheet. Cheat-Sheets.org#vim is a good source, as is Vim Tips wiki.
What most people do is start out with the bare basics, like maybe i, yw, yy, and p. You can continue to use arrow keys to move around, selecting text with the mouse, using the menus, etc. Then when something is slowing you down, you look up the faster way to do it, and gradually add more and more commands. You might learn one new command per day for a while, then it will trickle to one per week. You'll feel fairly productive in a month. After a year you will have a pretty solid repertoire, and after 2-3 years you won't even consciously think what your fingers are typing, and it will look weird if you have to spell it out for someone. I learned vi in 1993 and still pick up 2 or 3 new commands a year.
#Greg Hewgill's cheatsheet is very good. I started my switch from TextMate a few months ago. Now I'm as productive as I was with TM and constantly amazed by Vim's power.
Here is how I switched. Maybe it can be useful to you.
Grosso modo, I don't think it's a good idea to do a radical switch. Vim is very different and it's best to go progressively.
And to answer your subquestion, yes, I use all of iaIAoO everyday to enter insert mode. It certainly seems weird at first but you don't really think about it after a while.
Some commands incredibly useful for any programming related tasks:
r and R to replace characters
<C-a> and <C-x>to increase and decrease numbers
cit to change the content of an HTML tag, and its variants (cat, dit, dat, ci(, etc.)
<C-x><C-o> (mapped to ,,) for omnicompletion
visual block selection with <C-v>
and so on…
Once you are accustomed to the Vim way it becomes really hard to not hit o or x all the time when editing text in some other editor or textfield.
I can't imagine everyone uses all 20 different keypresses to navigate text, 10 or so keys to start adding text, and 18 ways to visually select an inner block. Or do you!?
I do.
In theory, once I have that and start becoming as proficient in VIM as I am in Textmate, then I can start learning the thousands of other VIM commands that will make me more efficient.
That's the right way to do it. Start with basic commands and then pick up ones that improve your productivity. I like following this blog for tips on how to improve my productivity with vim.
tuxfiles.org holds a pretty good cheat sheet. I think there are a couple of points to learning the commands:
Read the cheat sheet regularly. Don't worry about using all of them, or remembering all the keys, just know that the command exists. Look up the command and use it when you find yourself doing something repetitive.
If you find yourself doing something regularly (like deleting an entire line after a particular character d$), go a quick google search to see if you can find a command for it.
Write down commands you think you'll find useful and keep that list where you can see it while you're writing your code. I would argue against printing something out and instead encourage you to use post it notes for just a few commands at a time.
If possible, watch other programmers use vim, and ask them what commands they are using as you see them do something interesting.
Besides these tips, there are some basic concepts you should understand.
vim will use the same character to represent the same function. For example, to delete a line after a character use d$. To highlight a line after a particular character use v$. So notice that $ indicates you will be doing something to the end of the line from where your cursor currently is.
u is undo, and ctrl+r is redo.
putting a number in front of a command will execute it repeatedly. 3dd will delete the line your cursor is on and the two lines that follow, similarly 3yy will copy the line your cursor is on and the two lines that follow.
understand how to navigate through the buffers use :ls to list the buffers, and :bn, :bp to cycle through them.
read through the tutorial found in :help This is probably the best way to 'learn the ropes', and the rest of the commands you will learn through usage.
Go to Efficient Editing with vim and learn what you need to get started. Not everything on that page is essential starting off, so cherry pick what you want.
From there, use vim for everything. "hjkl", "y", and "p" will get you a long way, even if it's not the most efficient way. When you come up against a task for which you don't know the magic key to do it efficiently (or at all), and you find yourself doing it more than a few times, go look it up. Little by little it will become second nature.
I found vim daunting many moons ago (back when it didn't have the "m" on the end), but it only took about a week of steady use to get efficient. I still find it the quickest editor in which to get stuff done.
Put this in your .bashrc to open vim with last edited file at last edited line
alias vil="vim +\"'\"0"

Is there some pattern behind the many VIM commands?

I have to add a VIM personality to an IDE. I never used VIM for more than the most basic edits and i'm now overwhelmed by the complexity of the command structure.
Is there any overall structure for the combination of counts moves and insert/delete commands?
I just can't see the wood for the trees.
Well, there is obviously a finger position pattern behind h, j, k, l.
The fact that ^ goes to the beginning of a line and $ goes to the end is patterned on common regular expression syntax.
Ctrl-F and Ctrl-B page forward and back, and that's fairly intuitive.
i inserts (before) and a appends (after the cursor). Similarly,
I inserts at the beginning of the line, and A appends at the very end.
> and < indent and outdent, respectively. That's also kind of intuitive.
But on the whole, many of the other commands are on whatever keys were left – it's hard to find an intuitive mapping between the letters of the alphabet and an editor's commands.
Repeat counts are always entered before a command, and mostly repeat the command that many times, but in some cases do something clever but analogous.
I think the secret to not going crazy over vi is to start out with only a small handful of commands. I have a lot of colleagues who don't know to do anything other than
move the cursor around using the arrow keys (you don't have to use h, j, k, l);
insert with i, delete with Del (you don't have to use x);
delete a line with dd
get out of input mode with Esc
get out of vi with :x (exit) or q! (quit, and throw away my changes!)
Because I'm much smarter, the additional commands I know and use are:
go to the top of the file with gg, the bottom with G.
I can go to a specified line number with (line-number)G.
copy a line with y (yank), paste it with p
change a word with cw, the rest of the line with C
delete a word with dw, the rest of the line with D
I sometimes use . to repeat the last command, or u (undo) if I messed up.
When you have occasion to use other commands, you can teach them to yourself one by one as needed.
This is a good article for explaining the VIM philosophy.
I think the characteristic that better defines VIM in respect to other editors is its wide array of motion commands. The first thing to learn to fully use VIM is hitting the arrow keys as little as possible, and think at the text in terms of "blocks" like "a sentence" "a tag" "a word" "a group of brackets".
Say you have function foo($bar, $fooz) you can change the parameters by simply positioning your cursor anywhere inside the brackets and pressing ci) (mnemonic: change inner bracket). The same pattern applies to other commands: yank (y), delete (d) and so on.
I know this doesn't explain the whole "VIM philosophy" but combining normal mode commands with the vast amount of motion modifiers is what really made me see the light.
There are plenty of nice and interesting tutorials. One example is
http://blog.interlinked.org/tutorials/vim_tutorial.html
But the broad structure that most of them would give you is
There are two main modes for editing - Command mode and insert mode. You can move from insert mode to command mode using the key.
You can execute commands in the command mode by typing a single key or a sequence of keys.
Commands can help you achieve a wide variety of things
deletion of lines - dd
yanking (copying of lines ) - yy
pasting lines below the current line - p
pasting lines above the current line - P ( and so on)
Most commands in the command mode can be pre-fixed by a "count" to indicate the number of times the command has to be executed. For example, 3dd would delete three lines.
One set of commands in the command mode lets you move to the insert mode. That is explained below.
There are different ways of entering the insert mode from the command mode. Prominent among them are (i-insert at cursor, I-insert at beginning of line, o-insert a line below, O-insert a line above, a-append, A-append at end of line.
The quick reference at
http://www.andy-roberts.net/misc/vim/vim.pdf
Will help you understand the relevance of "count"

How is the undo tree used in Vim?

This answer says:
Vim's undo/redo system is unbeatable. Type something, undo, type something else, and you can still get back the first thing you typed because Vim uses an undo tree rather than a stack. In almost every other program, the history of the first thing you typed is lost in this circumstance.
This is the first I hear of this. How can I backtrack along the tree?
See also :h undo-redo, which lists all the commands and their usage.
There are two ways to traverse the undo tree. One is to go "back in time". g+ and g- will traverse all of the nodes in the tree in chronological or reverse-chronological order (which can be a bit confusing, because it can jump arbitrarily between undo branches, but if you do g- long enough you'll always get where you need to go eventually). :earlier and :later take a time descriptor like 7m or 1h; again this can jump you arbitrarily between undo branches.
The other way is to jump to specific nodes in the tree using :undo n where n is a number of an action. (All actions, i.e. text additions, deletions, replacements, are numbered sequentially as you do them.) You can look up the number of the actions on the leaves of the undo tree via :undolist. This will let you jump between branches easily. You can then use u and Ctrl-R to move up and down that branch.
There are some good examples in the Vim help. The best way to figure out how this works is to play with it a bit.
I'm a bit late to the party,
but I figured I'd mention that I wrote an undo tree visualization plugin for Vim :
https://github.com/sjl/gundo.vim
Personally I found that graphing the tree like this was the only way I could make sense of it.
This page explains everything you need to know:
http://vimdoc.sourceforge.net/htmldoc/usr_32.html
If you're using vim, you can navigate through the undo tree using:
u: (undo) move back in the undo tree
Ctrl+R: (redo) move forward in the undo tree
Other ways of bringing document back or forward in time:
:earlier 15m: move back in time 15 minutes
:later 15m: move front in time 15 minutes
I'm aware this question has been answered, but I thought I'd add an example.
Create a new file and type:
this is a line
undol will display the undo tree. At this point you haven't undone anything
:undol
number changes when saved
1 1 14:50:36
now press ESC and modify the line to:
this is a old line
switch to normal mode and press u (undo), this should remove "old". If you check undol, at this point you still have only one branch.
now modify the line so it says:
this is a new line
Now :undol shows:
number changes when saved
2 2 87 seconds ago
3 2 3 seconds ago
You can switch to the first branch by typing
:u 2
this will move you to the end of the branch associated with number 2. You can move along this branch with g+ and g-. At this point g+ will do nothing (you are at the leaf). If you press g- “old" will be removed (you are traversing the first undo tree). That is if you remove “old” with g- and press g+ again, “old" will be redone.
If you type
:u 3
You will jump to the leaf of the second undo branch and it will read:
this is a new line
A lot of this is summed up here:
http://vim.wikia.com/wiki/Using_undo_branches
Besides using gundo.vim I like to mention g+ and g-
The package undotree is written in pure vimscript so no requirement.
And add this to your vimrc before it is too late:
set nobackup
set noswapfile
set nowritebackup
set undolevels=10000 " use many levels of undo
set history=10000 " After nocompatible
if has('persistent_undo')
set undodir=$HOME/.vim/undo
set undofile
endif

Resources