Posts Tagged ‘vim’

7th July
2009
written by feicipet

I wrote this as a response to a VI question in LowYat forums. Hope it’s useful to someone else out there.

  1. :$ - Move to the last line (why this instead of shift-G? read below)
  2. :10 - Move to line no 10, just substitute with any other number. So, just remember “$” means “last line” and you will find it more intuitive.
  3. :0,$ s/replace this/with this/g - Literally, it means “from lines 0 to last line ($), search for “replace this” and replace with “with this”. If you want you can just change the range, for e.g. “2,10″ to mean lines 2 to 10. If you omit the “g” at the end of the command, it means only replace the first instance that vim encounters on a particular line. With “g”, it will replace all instances. Try “:0,$ s/hello/goodbye/g” and “:0,$ s/hello/goodbye/” on a file that has “hello Sam hello Delilah” to see how this works.
  4. v - Type the character “v” and start moving your cursor around. You’ll see that it highlights an entire block, readying a selection for you to do cut n paste (see below for cut n paste)
  5. shift-v - Does the same as “v” but for whole lines
  6. ctrl-v - Does the same as “v” but in arbitrary block mode (hard to explain, try and you’ll know)
  7. To copy, first highlight a selection of text using any instruction from 4-6. Then press “ay (with the double quote). The selection will disappear. Move your cursor some where else. Then press “ap .
  8. To cut, do the same as “7″ but substitute “ay with “ax .
  9. All the copy n paste shit above is nice, but has been rendered obsolete by modern terminal emulators that allow you to use a mouse to highlight and copy/paste. But this is why I still use this trick. After you have done either 7 or 8, do NOT quit the editor, but highlight another block of text using any instruction from 4-6. Now type “by . Now move your cursor somewhere else and type “bp . Now type “ap again. You will see that the text that you copied using “ay and “byhave actually been stored into different buffers (or “registers” in VIM convention). You can declare many more registers just by swapping “a” and “b” with “c” or “d” or… you get the idea.
  10. And finally, remember that you can tell vim to perform a command X times very easily. For e.g., highlight a line and type “ay to copy into register “a”. Then type 10″ap. You will see that it has pasted register “a” 10 times. Cool, huh? Just prepend your command with a number to tell vim to run it that number of times.

Note that these tricks work mostly with VIM (VI Improved), not plain vi.

In (K)Ubuntu, only a minimal build of vim is installed by default. To upgrade it, just type “sudo aptitude install vim”. You should know which version you’re using pretty easily. Just edit a shell script, if there’s no syntax highlighting, it means you don’t have the full VIM installed. Otherwise, things are cool.

Tags: ,