学习vim使用的一个很好的网址,在google上搜"use vim like a pro"就可以了。但是有的时候进不去,所以在这里备份一下~
Use Vim Like A Pro
Why Bother? (reasons)
There are many other editors, some being quite excellent. There is no reason why you cannot use one of them, however, there are some advantages in using VIM. Likewise none of these reasons are unique to VIM.
Why Write This Tutorial (approach)
There are other tutorials that are very good, and google will help you find them all. Maybe the greatest need in this world is not for another vim tutorial, but this one is mine.
I have taken a slighltly different approach. I think that there is a certain mental model that makes mastering VIM much easier. Also, I include habits that make VIM your friend. I don't know who else does this.
I've agonized and organized (and reorganized, and reorganized) the tutorial for top-to-bottom learning, with the goal that anyone who manages to emerge at the other end of this tutorial will have professional-grade editing skills, probably better than many of their experienced colleagues.
While I advise patience and deep memory, I think this is one of the fastest ways to improve your use of vim, and a pretty good way to start using vim from scratch. I wrote this for the moderately impatient developer.
I decided not to try to write a for-sale book, because anyone should be able to use vim like a pro, any time and place they choose, and without paying me any kind of "vim toll".
How should one use the tutorial? (usage)
Look at each numbered item in this page as a separate lesson, and spend a little time with it before moving onward. Maybe spend a day with each bit of knowledge, and maybe a several days when the lesson is particularly meaty.
Consider doing a few lessons a week. Don't be in a hurry. Don't rush your brain so that each time you learn something new, you lose something old. The tutorial will last as long as you need it. You have permission to breathe.
You can't learn vim without using vim, so you should have some text files (preferably open source program code) to work with. It is better yet if you are using vim at work. It also helps if you work with a partner who is also reading this tutorial, so that you can reinforce each other.
What can I do with this tutorial? (license)
This work is licensed under a Creative Commons Attribution 3.0 License.
Copy it, share it, paste it into your web page. Don't pretend it is your own stuff, and please give me some attribution. As a courtesy, if you find it worth distributing, I wouldn't mind getting a copy or a link. Just let me know.
The Tutorial
1. A little reassurance first.
Nobody knows all of VIM. There is enough in VIM's command system to keep thousands of human beings all using it in their own idiosyncratic way. Luckily, you don't have to know it all. You only need to know how to do your own work.
Because there is so much capability in this program, you will be learning new tricks as long as you continue to use it. The secret is to not settle for crummy ways of doing work.
VIM has word completion, and undo, and shortcuts, and abbreviations, and keyboard customization, and macros, and scripts. You can turn this into *your* editor for *your* environment. That's cool, but it's also reassuring to know that you can probably be much more productive than you are without touching any of those advanced features.
As Bram Moolenaar (VIM's primary author) says, the best way to learn VIM is to use it and ask questions. This little tutorial is full of questions you might not have thought to ask. That's the main value I can give you.
Vim has a built-in tutorial. You might want to try it, especially if you don't like my tutorial. All you have to do is type "vimtutor" at the command line. It is a very nice tutorial, and is rather complete (compared to mine, which is fairly nice but not very complete at all).
Finally, please consider GVIM. It will make your experience much more pleasant. If you only have VIM, then you can still use it and learn, but GVIM has a much nicer look, lets you use your mouse and scroll wheel, and has menus and icons for those of you who are used to such things.
2. Modality
The original vi was invented back when "green screen" ascii terminals were the UI innovation of the day (ask your dad about ascii terminals). There wern't so many shift-like keys (shift, alt, ctrl, windows, fn) and there was no such thing as a pointing device. Let's pretend that there was only a "ctrl" key and a "shift" key, whether it's true or not.
Programming (and all other computer use) was done with your eyes on the screen and two hands on the keyboard. Vi made it possible to do so quickly, because vi is a bit like a video game, where any little gesture on the keyboard causes something to happen.
If you are using vim and pressing keys causes either cool or unfortunate things to happen, you know you are in the command mode, which is the default state of the editor. Commands are assigned to the ordinary everyday keys like 'p' and 'y' and 'g', not chords like Control-Alt-Shift-Escape.
VIM has combinations and sequences to get the special power-ups like navigating between functions in separate files and reformatting entire lists in the middle of a document, code completion, abbreviations, templates and the like but that is for later.
There has to also be a way to type text into a document, but most of the keys already have special meanings! The only reasonable option was for the developers to create an "insert mode" which would make the 'a' key type an 'a' character, just like a typewriter (ask your dad what a typewriter is). This is called "insert mode". Not much happens in "insert mode" except normal, old, boring typing. You only want to use insert mode when you must do typing, but all the cool stuff happens in the normal (control) mode.
You will learn many convenient ways to get into insert mode, but for now you should know that the way out of insert mode, back to the video-game-like control mode, is to press the ESCAPE key.
Understanding that you have basically two modes of operation will make your stay in VIM less confusing, and starts you on your way to VIM guruhood.
3. Know the VIM command pattern
Most of the time you will either get an immediate result from a keystroke, or you will type a command and a movement command (often repeating the same keystroke: the "double-jump"). When you start to learn the other bits and pieces (registers, repeats, etc) then you might think vim is inconsistent, and this is not so. The command pattern is rather consistent, but some parts are optional.
o Register name (optional, with default cut/paste register used if not otherwise specified)
o Repeats (optional): 13
o Operation: y (for yank)
o Movement (depending on the operation): yy (repeated to take current line, a convention used in vi)
VIM commands work with the pattern shown above. There are some commands that don't use register and some that don't take movement, but for the most part this is the way it goes.
A register is essencially a cut-n-paste buffer. In most editors you get only one. In VIM you have too many, but you don't have to use them, so don't worry about it untl you get to the lesson on buffers.
A repeat is a number of times you want to do something. If you don't type in a number, the default is 1.
An operation is a keystroke that tells VIM to do something. These are mostly normal keypresses, and most operators do not require shifts or alts or controls.
Movement is a command that takes the cursor somewhere. There are a lot of them, because there are lots of ways you need to move. Don't panic, though, because you can use the arrow keys if you really have to. There is a whole section of this tutor on moving around.
Lets try an example to clarify how the pattern works. If I want to copy 13 lines into my copy/paste register, I can skip specifying a register name, type 13 for a repeat count, press 'y' for yank, and then press one more 'y' as a movement command (meaning current line). That yanks 13 lines into the default cut-n-paste register. If I press 'p' (choosing to use no register name and no repeat, recognizing that put has no movement command), then those lines are pasted back into my document just after my current line.
If you know this pattern, then you will know how to leverage everything else you learn about vi. Learn all the convenient ways to move, and you will know how to cut, paste, reformat, shift, and many other things you want to do.
4. GET OUT!
You should be able to get out of a VIM session once you are in it. There are a few ways to do so. Try these:
:q |
Quit the current window (or editor if you're out of windows) if there are no unsaved changes. |
:q! |
Quit the current window even if there are unsaved changes. |
:qa |
Quit all windows unless there are unsaved changes. |
:qa! |
Quit all windows even if there are unsaved changes. |
:wq |
Save changes and quit the current window. |
ZZ |
Save changes and quit current window |
When you type a colon, the cursor drops to the lower left corner of the screen. Later you will know why. For now, it's enough to know that it is supposed to do that, and that these :q commands will work. Notice that there is no : in front of ZZ.
If you can't get out of VIM, you should check that caps lock is OFF, and press the escape button. If it feels good, press it a couple of times. If it beeps, you know that you've escaped enough. Then these exit commands should work.
5. Mnemonics
Not all commands are mnemonic. They tried, but there are more than 26 things you might want to do in a text editor, and the distribution of letters means that not that many words start with a 'q' and happen to be meaningful in editing. However, many commands are mnemonic. There are commands for moving Forward, Back, a Word at a time, etc.
A great many are mnemonic if you know the jargon. Since "copy" and "cut" both start with "c", we have the vernacular of "yank" (for copy), "delete" (for cut), and "put" (for paste). Y, D, P. It seems a little funky but it is possible to remember these. Remember, eventually it becomes muscle memory, but the authors of VI and VIM tried not to be arbitrary when it was totally up to them. Sometimes, there wasn't much of an option.
6. Invocation
Now that you know how to get out of VIM, maybe it's time to learn how to get into VIM. We typically start VIM from the command line, though you may have menues or other ways.
There are a few ways you can start VIM.
vim |
start with an empty window |
vim file.txt |
start with an file.txt loaded and ready to edit |
vim +23 file.txt |
start with an file.txt loaded and ready to edit at line 23. |
vimtutor |
Start in tutorial mode. This is a good idea. |
vimdiff oldfile.txt newfile.txt |
Start VIM as a really fancy code merge tool. |
vimdiff . |
Start VIM as a file explorer. |
There is more, not shown. For now, knowing these will help you to get started. DO try out the vimtutor and the vimdiff. Some of these won't work until you set up a .vimrc, but that is explained later.
If you type gvim instead of vim then you will get the gee-whiz, cool, gui version of VIM (if it's installed). It has some extra powers. You'll typically like it better than the plain VIM. It is like VIM with chocolate icing. Everything we say about VIM here is also true of GVIM, so you can use the same tutorial with either.
You don't have to edit one file at a time. You can start (g)vim with multiple filename arguments. When you do, there are a few options you can pass to get some fun additional effects. Of course, these are more fun after you learn how to work with split windows, so you can refer back to it later.
-o |
Open multiple files in horizontally tiled windows . |
-O |
Open multiple files in vertically tiled windows . |
-p |
Open multiple files in separate tabs (I hate this). |
7. Move by context, not position
The poor soul who is using VIM for the first time will be found pressing up and down arrows and executing key repeats, moving horribly inefficiently through any body of code. He will be scrolling or paging (btw: ^f moves forward one page, ^b moves backward one page) and searching with his poor eyeballs through piles of code. This poor soul is slow and clueless, and probably considers VIM to be a really bad version of windows notepad instead of seeing it as the powerful tool it is.
By the way, the arrow keys don't always work for vim, but don't blame vim. It's actually an issue with the way your terminal is set up. Vim can't tell that your arrow keys are arrow keys. If you have the problem, you have more research to do.
To use VIM well, it is essential that you learn how to move well.
Do not search and scroll. Do not use your eyes to find text. They have computers for that now. Here are a handful of the most important movement commands. The best way to move is by searching:
/ |
search forward: will prompt for a pattern |
? |
search backward: will prompt for a pattern |
n |
repeat last search (like dot for searches!) |
N |
repeat last search but in the opposite direction. |
tx |
Move "to" letter 'x' (any letter will do), stopping just before the 'x'. Handy for change/delete commands. |
fx |
"Find" letter 'x' (any letter will do), stopping on the letter 'x'. Also handy for change/delete commands |
If you're not searching, at least consider jumping
gg |
Move to beginning of file |
G |
Move to end of file |
0 |
Jump to the very start of the current line. |
w |
Move forward to the beginning of the next word. |
W |
Move forward to the beginning of the next space-terminated word (ignore punctuation). |
b |
Move backward to the beginning of the current word, or backward one word if already at start. |
B |
Move backward to the beginning of the current space-terminated word, ignoring punctuation. |
e |
Move to end of word, or to next word if already at end. |
E |
Move to end of space-terminated word, ignoring punctuation |
The following commands are handy, and are even sensible and memorable if you know regex:
^ |
Jump to start of text on the current line. Far superior to leaning on left-arrow or h key. |
$ |
Jump to end of the current line. Far superior to leaning on right-arrow or k key. |
Here is some fancy movement
% |
move to matching brace, paren, etc |
} |
Move to end of paragraph (first empty line). |
{ |
Move to start of paragraph. |
( |
Move to start of sentence (separator is both period and space). |
) |
Move to start of next sentence (separator is both period and space). |
'' |
Move to location of your last edit in the current file. |
]] |
Move to next function (in c/java/c++/python) |
[[ |
Move to previous function/class (in c/java/c++/python) |
Finally, if you can't move by searching, jumping, etc, you can still move with the keyboard, so put your mouse down.
h |
move cursor to the left |
l |
move cursor to the right |
k |
move cursor up one line |
j |
move cursor down one line |
^f |
move forward one page |
^b |
move backward one page |
You want to use the option hls (for "highlight search") in your vimrc. You will learn about that soon enough. In the short term you can type ":set hls" and press enter.
8. Quoting Your Regex Metacharacters
If you don't know what a regex is, skip this section. For those who understand what a regex is, and who realize that the "/" command takes a regex rather than just normal text, this will be important. For the rest of you, it will seem totally out of place and should be skipped for now.
You should know how to use regular expressions, because a few tricks in regex will make your whole Unix/Linux/Mac experience a little better. It is too large a topic to expose fully here, but you might try looking at on of the good references or tutorials elsewhere on the web.
The main thing to remember is that VIM will side with convenience when it comes to regex. Since you search a lot, vim will assume that /+ means that you want to search for the nearest + character. As a result, all the metacharacters have to be quoted with the backslash ("\") character. It's sometimes a pain, but if you really want to find a plus sign followed by a left-parenthesis, it is very easy.
9. Don't panic. You have undo/redo
The command for undo is u. That's not too hard to remember, is it? A lot of VIM commands are pretty mnemonic-friendly.
The redo would be the r key, but the r is used for "replace" (we'll talk later about this). We're stuck with control-R instead. Ah, well. You can't have everything.
There is a lot more to undo and redo, but this is enough. Be happy that you can revert changes, and un-revert them. VIM isn't as powerless and unforgiving as you feared it might be, though you might still not like it very much. Just wait for that muscle memory to kick in.
If you get into a real mess, then exit the editor without saving.
If you are really afraid, or really cautious, then you should have version control for your text files. I recommend you start editing with junk files in a junk directory anyway, but when you are working on something important, you should not be afraid to make changes. Version control is a good security blanket and a useful backup strategy. Consider using Git or Mercurial, both of which are easy and powerful.
10. Shifted letters and DEATH BY CAPS!
For a number of commands, shift will either reverse the direction of a command (so N is the opposite of n, see next bullet) or will modify how the command works. When moving forward by one word at a time (pressing w), one may press W to move forward by one word but with W the editor will consider punctuation to be part of the word. The same is true when moving backward with b or B.
Because a shifted letter may mean something very different from the same letter unshifted, you must be very careful not to turn on the capslock! Sometimes a poor unwary soul will accidentally hit the capslock. When he intends to move left with 'j', he instead joins the current line with the next. Many other unwanted edits can take place as his fingers make a quick strafing run for some complex edit. It is ugly.
If you encounter DEATH BY CAPS, you should turn off the capslock, and then try pressing 'u' repeatedly to get rid of unwanted edits. If you feel that it's a lost cause, press ":e!" followed by pressing the enter key. That will reload the file from disk, abandoning all changes. It's a troublesome thing that will eventually happen to you. Some people turn off their capslock key entirely for this reason.
11. Insert, Overwrite, Change
In VIM you have a variety of ways to start entering text, as mentioned above in the section on Modality.
You are normally in command mode. When you type certain keys, you are placed in insert mode or overtype mode. In insert mode, the text you type goes before the cursor position, and everything after the cursor is pushed to the right or to the next line.
In overtype mode your keystrokes are input, just as they are in insert mode, but instead of inserting the keystrokes VIM will replace the next character in the document with the character you type. You get to overtype mode by pressing an overtype key command while in command mode.
In ex mode you are typing a string of commands to run into a little window at the bottom of the screen. We'll talk about this later on, because it's powerful stuff. It's also a little cryptic, so we will wait. You get into ex mode by typing ":" in command mode.
You always return to command mode from overtype, insert, or command mode by pressing escape. That is one handy key.
i |
insert before the current cursor position |
I |
insert at the beginning of the current line. Far better than pressing ^ and then i. |
a |
insert after the current cursor position |
A |
insert/append at the end of the current line. Far better than pressing $ and then i. |
r |
retype just the character under the cursor |
R |
Enter overtype (replace) mode, where you destructively retype everything until you press ESC. |
s |
(substitute) delete the character (letter, number, punctuation, space, etc) under the cursor, and enter insert mode |
c |
the 'change' (retype) command. Follow with a movement command. cw is a favorite, as is cc |
C |
Like 'c', but for the entire line. |
o |
insert in a new line below the current line |
O |
insert in a new line above the current line |
: |
Enter command mode (for the advanced student) |
! |
Enter shell filter mode (for the very advanced student) |
Consider the value of the c command. If you use it with the t or f commands, it becomes very powerful. If you were at the C at the beginning of the previous sentence, you could type ct. and retype the whole first sentence, preserving the period. The same is true with other commands, such as the d for delete. The movement commands add a lot of power to the change command, and that's one reason why it is important to learn to move well.
12. NEVER PARK IN INSERT MODE.
Vim is set up to do more navigating than editing. It rewards you for working in the same way, mostly in control mode with spurts of time in an insert mode.
If you try to use vim as a weak form of notepad, modality and navigation will ensure that you are never really efficient. If you want to sail, you have to get in the boat, and if you want to get good at vim, you need to get good in command mode.
So, if you are stopping to think, hit <esc>. If you aren't in the middle of text typing, you should be in command mode. If you are wanting to move up or down a line, or to some other place, hit <esc>. If you walk away from the keyboard, hit <esc>. Otherwise, you will start to type commands and find that you're not in command mode and you have lost your ability to meaningfully use . or undo.
13. Happiness is a good .vimrc
When VIM starts up, it reads your personal settings before it does anything interesting. You can edit a file named .vimrc in your home directory. The above instructions give you enough information that you should be able to edit your .vimrc file and add all the commands listed below. The idea is to enter the commands in the leftmost column of the table. You will have to type them, and correct any spelling errors. Once the file has been created, you will save and exit and the next you start VIM it will have your settings. You can edit this file at any time.
There is very fine magic in VIM. However, it often comes without the magic turned on. Command line completion, color syntax highlighting, the file explorer, and many other features are "missing" unless you turn them on in ~/.vimrc.
There is a very nice guide to the various settings in vim, and even an interactive display so that you can turn them on and off. This is not very well-known, I suspect, because I only learned it this year. I wish I had known when I was first starting.
:options |
:browse options |
:browse set |
In this window, you can browse through all the available options, and can even set them. You can read the short help messages associated with each, or you can hit the enter button on any short help to see the longer help text. If you press the enter key on an option, it will toggle that option or set a new value.
Each of these commands has a shortcut, but you can learn those later. Try entering just the first five commands (one-per-line), save the file, and then edit it again to add the other commands. You will find that the second session will have color syntax highlighting, and will give you more hints and help as you work.
Command in .vimrc |
Meaning |
syntax enable |
turn on all the magic, including Explorer and syntax highlighting |
set showmode |
Show me when I'm in insert/overtype mode |
set showcmd |
When a command is in progress, show it in the status bar |
set wildmenu |
magic for completion at the : command line. |
set ruler< |
turn on the "ruler" (status info) at the bottom of the screen. |
runtime ftplugin/man.vim |
Turn on man pages (type :Man ) |
set autoindent |
indent in a smart way, instead of returning to the left margin all the time |
set expandtab |
expand tabs to spaces |
set nowrap |
Don't wrap text (makes windows ugly) |
set hlsearch |
Highlight all matches in text when you search |
set showmatch |
Show matches for braces, parens, etc. |
set ignorecase |
do case-insensitive searching |
set smartcase |
When a search phrase has uppercase, don't be case insensitive |
set path=.,..,/usr/include/**,/usr/share/** |
Tell the editor where to search for files |
set spelllang=en_us |
when I want spell-checking, I want it to be english |
14. Help is on its way.
There is an online help mechanism in VIM. You should know how to use it.
Type :help and you will get a split window with help text in it. You can move around with the arrow keys, or with any of the VIM movement commands you will learn.
You can always enter funky keys by pressing ^v first, and then the keystroke. This is most useful in help. You can type :help ^v^t to get help for the keystroke ^t. By convention you can usually get what you want by typing :help CTRL-T also. Don't underestimate how handy this is.
Most distributions of VIM will install a program called vimtutor. This program will teach you to use VIM. It will do so by using VIM. It is a handy piece of work (props to the author!).
Help has links. If you see one you like, you can move the cursor to the link (lets not just beat on the arrow keys, here!) and press ^]. Yeah, it's an odd and arbitrary-looking command. That will not only navigate to the link, but also push it on a stack. If you want to go back, you can press ^t (yes, also pretty arbitrary) to pop the current link off the stack and return to the previous location in the help. The commands ^] and ^t aren't very memorable, but we'll use them for code navigation later, so learning them is not a total waste of mental energy.
15. The Double-Jump
By convention pressing any command twice will tell it to operate on the current line. If you want to yank (copy) the current line, press yy. If you want to delete the current line, press dd. If you want to change (retype) the current line, press cc. This is a pretty consistent convention, down to the special case of "save and exit" being ZZ. Doing operations on the entire current line is very common, and it made sense to make it convenient.
16. Getting rid of things.
You can get rid of the character under the cursor by pressing x. If you want to press it 10 times, you can save effort by typing 10x. It can be pretty handy, but you could very quickly get tired of counting how many times you want to press x, or you could get tired of holding down the x key. I know I would.
The more flexible delete command is very simple. It is the letter 'd' for "delete". It is one of the lucky mnemonic commands.
D will take a movement command. You should have learned several in the earlier paragraph. The basic concept is that you will delete from the character under the cursor to some other point in the file.
You can delete the current line by typing "dd", or you can delete the current line and the one under it by typing d followed by the 'j' or 'down arrow'. Likewise, d followed by the } command (end of paragraph) deletes to the end of the current paragraph. d followed by G will delete to the end of the file. You'll find that all commands that take a movement command will work this way (including 'c'). Every movement command you learn increases your power to copy, delete, and retype. This added power is why it is essential that you learn to move well in VIM.
'd' will also take a repeat count, so you can type 23dd to delete 23 lines starting with the current line. This can be handy.
Finally, we have registers. A VIM register is like the copy-and-paste buffer you have used in lesser gui tools. When you delete, the deleted text is saved for pasting and you can get it back by pressing the p(mnemonic: put or paste) key. The delete key can take another register if you want to specify one. A register is specified with a double-qoute character, followed by the name of a register (which is a lower-case or upper-case letter, where case is significant). That means you may copy multiple bits of text by yanking or deleting them into different register and pasting them into a new place (or new file) by using a register-specific paste.
Pasting also takes a register specification, which is always a double-quote followed by a letter, followed by the 'p' for paste. You could even paste a register many times if you specify a repeat count (see the lesson on the basic command pattern).
You actually have more registers than I told you, and can do more with them than I said, but this is enough for a quick lesson on deleting.
17. Use the Dot.
Edits actions in VIM are recorded. Say that you just deleted a line (by typing dd). The editor knows you deleted a line. You can repeat the edit (that is, delete another line) by pressing the period key ("."). You can even apply the standard pattern and give a register, repeat, and then a dot (the dot knows the command and movement). This is particularly handy if the command you last used was cw. It will repeat the replace operation on the text under the cursor.
Because the dot command repeats the last edit you did, it is one of the most powerful keys on the keyboard. You should learn to rely on it. It is one of the most wonderful things VIM gives you.
18. Use the Star
The star is a great command, especially if you have the option hlsearch turned on in your .vimrc file. It will move to the next use of the word under the cursor. In doing so, it will highlight all uses of the word under the cursor.
* |
Move to next instance of word under cursor. |
# |
Move to previous instance of word under cursor. |
19. Registers
In most editors you get a single cut-n-paste buffer. When you use the cut or copy command, you lose whatever is in the buffer. As a result you end up zipping back and forth in a file, cutting from one place, and pasting in another. If you are lucky you can split the window and go back and forth between tiles, but it's a lot of manual labor and an exercise in hand-eye coordination as you seek, cursor, mark, cut, seek, cursor, paste your way to authoring nirvana.
It probably took a couple of minutes to get sick of that.
In VIM, they have a different answer. Sadly they have different terminology, too. Instead of editing buffers, we have "registers". Same concept, different term (the word "buffer" means something else in VIM). You can find a source in your code, yank/copy to many different registers, move to the destination site in your code, and then paste the various register contents. It's all one move.
The registers are (from the VIM documents, available via :help registers):
" (literally, the quote character) |
The unnamed or default register |
a-z,A-Z |
the lowercase letters and the uppercase letters |
+ |
The system default register (the normal cut/paste one) |
* |
Select/drop registers |
_ |
The black hole -- essentially /dev/null, used to avoid wiping out register " (the unnamed register) |
There are also a few other special-purpose registers which I leave for your exploration in the help system, such as the small delete register and the numbered ones. You don't really need to know these.
To tell the difference between the command y and register y, VIM expects you to prefix the register name with a double-quote character. Therefore, y is the yank command, and "y is the y register. If you type "y, VIM will wait for you to complete the standard pattern with perhaps the optional repeat count, a command, and a movement command (if required). Examples of increasing power/complexity:
dd |
delete the current line into the default, unnamed register ("" or quote-quote) |
"add |
delete the current line into register a |
"xy$ |
Yank from the current character to the end of the line into register x |
"byy |
Yank the current line into register b |
"c24dd |
Literally Into register c, 24 times delete the current line. That's complex to read, maybe it's easier to just say delete the next 24 lines into the c register |
I'm sure that "c24dd seems a little crazy, but think how you would do the same work if you were using notepad or the like. This is 6 keystrokes, and only one of the shifted, and you never had to leave the home row to grab a mouse. It would be an extremely efficient way to cut 24 lines into a named register if you happened to know that you had 24 lines. If you didn't know that, the work of counting the lines would more than make up for the convenience. That makes this a pretty academic example, and opens the door to visual marking of text for copy/cut, etc.
20. Marking
VIM has non-visual marking and it has visual marking. Chances are, you are interested in visual marking for cut-n-paste (yank-n-put) purposes, so let's look at that.
v |
mark character-wise |
V |
mark line-wise |
^v |
column-wise marking |
gv |
Remark the area last marked. |
The command for visual marking is v. You can press v, cursor or search to the end of your current area of interest, and then do a yank or delete command. In fact, you probably should do that and come back. You can press v again to cancel out of visual marking.
Sometimes you want to mark whole lines at a time. For this, VIM uses the shifted (uppercase) V. It works just like the lower-case V but always selects a whole line at a time. Of course a second press of Vwill cancel this mode.
Other times, you might want to mark a rectangle instead of whole lines or contiguous characters. For rectangle (blockwise) marking, VIM uses the control character ^V. Notice that ^V has an entirely different behavior in insert mode. Don't get confused. Pasting rectangular regions is a cool feature.
A cool feature is that you can start marking with v, then press V to switch to line mode, or press ^V to switch to rectangle selection.
Once you leave the visual marking mode, the area is no longer marked. the VIM help tells us that we can go back into visual mode with the same marking mode and marked area by typing gv. I've been playing with it. It's handy.
I've been marking the entire document (ggVG) and then yanking it to the machine's cut-n-paste buffer ("+y) and switching to my blog editor. In the blog editor (not vi) I do the standard ^a ^v to paste my document in. Now I can save a few keystrokes by using gv rather than ggVG before pasting (after the first time).
The marked area becomes a context for other commands, so you can do much more than simple yank and put. You can use the r command and another letter like "X" , and change every character in the marked area to an "X". You can use the marked are for ex commands (which we've not talked about). There is rather a lot of power here, but we'll end the marking lesson here for now.
And since you're reading this anyway I want to remind you to avoid death by caps, and never park in insert mode. It doesn't belong here, but you need to hear it again.
21. Completion
Feel free to use long names and big words, because VIM has completion. It's not intellisense, mind you, but it will finish your words for you. Type enough of a word to be unique, and (without leaving insert mode) press ^n. If the word you're looking for is in any of the loaded files (or buffers) then VIM will present its best guess. If it is not the one you want, press ^n again until either you find your word, or you run out of choices. You can also use ^p to go back to a previous selection.
^n |
In insert mode, complete a word (forward to through choice list) |
^p |
In insert mode, complete a word (backward through choice list) |
In newer version of GVIM (graphical version) a selection box will pop up, and you will pick your word by either typing a little more so it really is unique or else by using arrow keys.
There is a more comprehensive "whole line completion" mechanism availabe to you also. You can press ^x^l to enter a special completion mode. You cycle through choices with ^n for next and ^p for previous, or with arrows (if your vim supports them). Again, if you are using GVIM you will get a popup window with choices. There are times this is more useful than doing cut-and-paste the old-fashioned way.
Less well known, there is a filename completion mechanism, accessed with ^x ^f. I don't usually use this, and have to keep a note like this tutorial around for the few times that I do. Usually having the file explorer mode and wildmenu around means not having to do filename completion in a normal day.
^x^l |
In insert mode, complete a line |
^n |
Get next choice |
^p |
Get previous choice |
When you have your selection, just keep typing. Any key other than a selection key (up/down/^n/^p) will be accepted as new text as is normal in insert mode. This is a little counter-intuitive because you are accustomed to hitting enter or tab to accept the entry.
There are a number of other special commands which are only available in insert mode.
Since you have word-completion and line-completion, you have no excuse for writing short and cryptic variable names. Very long, meaningful names are quite feasible and not tedious at all.
22. Keep text in front of your face
There are commands for moving the current line. The VIM folks were running out of letters I think, so they attached these commands to the z key.
zt |
move current line to top of page |
zz |
move current line to middle of page |
zb |
move current line to bottom of page |
You also can do much to keep reference code in front of your face if you use split windows. Lets assume your are in code.cpp, and want to look at code.h for a while.
type |
effect |
:split code.h<enter> |
splits window horizontally and loads code.h in a new window |
:vsplit code.h<enter> |
splits window vertically and loads code.h in a new window |
Once you have split windows, you'll want to know how to move between them. Here is a small set of commands (all bound up in ^w sequences) that will help you move about. You can always close any window (even a split one) with the :q or ZZ tricks (from "GET OUT", far above).
^W followed by |
Effect |
h or leftarrow |
Move to next window to the left |
l or rightarrow |
Move to next window to the right |
k or uparrow |
Move to window above current window |
j or downarrow |
Move to window below current window |
c |
Close current window |
o |
Close all windows except the current window |
Check out :help CTRL-W for more information about window control and movement.
23. The Explorer
You can edit directories. Give it a shot. There is help available, and you can get more information on the screen by pressing i. This is a kind of "poor man's midnight commander", or maybe a reasonable substitute for the windows explorer. It's quite handy, and highly recommended. This only works if "syntax enable" is in your .gvimrc file.
o |
Open file in a (horizontal) split window |
|
v |
Open file in a (vertical) split window |
|
i |
show more info |
|
s |
sort by column under the cursor |
|
r |
sort in reverse order |
|
D |
delete file |
|
d |
make new directory |
|
enter |
Open file in current window. |
|
|
|
|
24. Indenting and unindenting
Forget using tab. Too many tools use 8-character tabs, which is the standard. if you use tabs, even if you change the tabstop parameter in your code, a lot of programs will display or print your code incorrectly. Tabbing is dead, shifting is king.
So I recommend you set your tabstops to 8 in your .vimrc (set tabstop=8) and set your shiftwidth to the desired level (set shiftwidth=4). No, rather than recommend, I demand you go and add those two commands to your .vimrc right now. I'll wait. Really... go do it..
set tabstop=8 |
Use industry standard 8-char tabs |
|
set shiftwidth=4 |
Use standard 4-char indentation |
|
set shiftround |
Indent/Dedent to nearest 4-char boundary |
|
|
set autoindent |
Automatically indent when adding a new line |
You need to also have autoindent turned on, so you don't have to manually space or indent every line. Autoindent is so handy, I included it as a necessary feature in the .vimrc section. If you followed the tutorial, you will have it turned on already. Not having it on is stupid. You really want it.
In CONTROL mode:
< |
left-shift (requires a movement cmd, works on whole lines) |
|
> |
right-shift (requires a movement cmd, works on whole lines) |
|
If you want to move a paragraph to the left, then <} is your command. For shifting three lines right, it would be 3>>. The shift commands follow the standard VIM command pattern (hence the term "standard"). They do not use a buffer.
In INSERT or OVERTYPE mode:
^T |
Indent |
|
^D |
Dedent/unindent |
|
25. Spelling
VIM can also check your spelling. You can enter the command :set spell to turn on spelling checker. You can also set the dictionary and other options, but :help spell will tell you all about it.
I don't recommend turning this on normally. A lot of the things you will edit will contain stuff other than the dictionary's list of English words, and that can get to be annoying. I prefer to turn it on and off with:set spell and :set nospell.
The earnest student can learn to turn this on and off via special scripts that are run whenever a file is loaded. The less interested can skip it.
26. Little hints
There are some handy commands for showing you information in the status line, or in a scrolling display. When you need a reminder, but don't need to navigate to some part of source, it can be handy to use these.
[i |
show first line containing word under the cursor |
[I |
show every line containing word under the cursor |
:g/pattern/ |
show every line matching the regular expression pattern |
27. Shell Filtering
If you were working at the command line, you would know how to use sort, and filter with grep, maybe how to do various tasks with perl or awk. Those programs are all filters. They read the standard input and they write to standard output.
When you are VIM, however, you may want to do the same things. It is sure a pain to save the part of a file you want to sort, escape to the command line, sort the piece of the file to a new file, and then load the sorted file fragment into the space in the editor where that piece of unsorted text used to be.
What you need to know is that all that work is unnecessary. If you wanted to sort a paragraph, and your cursor were at the start of the paragraph, all you have to type is !}sort and the magic is done.
VIM is written to use filters directly. Not only is this handy for using all those great Linux/Unix filters, but also because you can write your own. Any filter-type program you write is now part of you editor as well as your command-line environment. That is a major bit of editing leverage. It is exciting stuff if you are a command-line guru already.
!!command |
pass current line only through filter |
!}command |
pass area from current line through end of paragraph through filter |
!Gcommand |
pass area from current line through end of file through filter |
:%!command |
pass the entire current buffer through filter |
28. Code Reformatting
You can reformat code or text a number of different ways. One is using shell filtering:
%!astyle |
Restyle the entire file with astyle (a nice reformatting program). |
%!indent |
Restyle the entire file with indent (a nice, older program). |
Another is using the gq command, which re-does the line wrapping, and which has intelligence for wrapping comments correctly.
gqq |
Re-wrap the current line (a double-jump!) |
gqj |
Re-wrap the current line and the line following |
gq} |
Re-wrap lines from the current line to the end of the paragraph. |
You can also retab a file. Retabbing converts tab stops to spaces, and ensures indentation is correct for each. It is done by setting your tabstop variable to the correct indent level, then setting expandtab, and finally by issuing the :retab command. It would be far too much work if I didn't have expandtab and tabstop set normally. Typically, I set tabstop and retab, and then save. That's a sequence I can map to a keyboard command, or can save as a macro.
You can also have the editor wrap your text as you type, and preserve your indentation. This is all done via the linebreak, textwidth, and autoindent settings, which you can easily explore with the helpfacility.
29. QuickFix mode is your friend
VIM can run your makefile and take you to each variable in turn. If you have unit tests set up to run as part of the build, and the unit test framework produces messages in a compatible format, you will be guided through the failed tests just as if they were compile errors. Likewise, any style-checking tool you use may be treated likewise if it has a compatible format.
If you are doing Test-Driven Development, this is a critical feature. with quickfix mode, you can find the rhythm that you're looking for. You can even assign the :mak command to a keystroke (see :help map) so that you don't have to type :make. VIM is a kind of agile editor in that regard. In a separate paper, I'll detail my vim settings for TDD.
Basic quickfix commands
:make |
Run the makefile specified by the makefile variable |
:cw |
Show the compile error window if there are compile errors. |
:cn |
Go to the next compile error. |
:cp |
Go to the previous compile error. |
As always, look at :help quickfix to learn more about this valuable mode of work.
30. Manual page access
In the .vimrc section I recommended that you turn on the Man feature. since you followed those instructions, you can now access man pages from VIM
:Man 5 crontab shows you the crontab man page in a split window. Your cursor will be in the help window where you can navigate as you would with tags, using ^] to go to a tag, and ^t to return. When you are done, type :q or ZZ to quit the window.
If you are looking for a man page for something in your file, you don't have to type the colon and the word man. You can type the leader character (by default "\") and the capital K and vim will find the man page and display it in a split window. By the way, if you change the leader character, you will of course have to adjust these instructions. This is very handy when you are working with scripts or the Linux/Unix C API.
:Man subject |
Get manpage for subject |
\K |
Get manpage for word currently under the cursor |
This feature is more valuable if you ensure that you install all of the man pages for the programming tools and libraries you use. Or at least that you urge your systems admin to do it for you. If you work in perl, and you don't have all the perl man pages, you will lose out on this fine feature of VIM.
31. Ctags lets you navigate like a pro.
I heartily recommend exuberant ctags as the tag program for almost any language. It will quickly span your code and create a 'tags' file, which tells vim all it needs to know to find a symbol in your source. The tag file gives a file and also a regular expression for finding the line you need. It does a very fine job.
!ctags -R * |
Run ctags (better to do this in your makefile) |
^] |
Jump to the definition of the term (class/method/var) under the cursor |
^t |
Pop the browsing stack, return to previous location |
32. Bookmarks.
Vim allows you to set a bookmark on a line, and jump from one bookmark to another.
mx |
Put bookmark 'x' at the current line. |
'x |
Jump to mark 'x'. |
You can use any letter for a bookmark, however there is a difference between a lower-case letter and an upper-case letter.
o The lower-case letters set a file-specific bookmark, so that 'a in one file will take you to a different place than 'a in another file.
o Uppercase letters set global bookmarks, so that jumping to 'A will take you to the line you marked in the file where you marked it. This is very handy, but is also sometimes not what you want, because it loads the marked file in the current window.
33. Pasting in Insert Mode
When in insert mode, you're not just stuck with typing characters and doing line completion. There are other commands, and one of them is the ^r command which will read data from a register and type it for you.
If you last deleted the word falsify and are typing in some part of the document, you can type ^r, followed by the default register named " (doublequote) and the editor will paste the word "falsify" into the text and continue onward in insert mode.
This is particularly helpful when doing something like cw, because the change command will delete the current word (loading the buffer) and then enter insert mode. So say I place my cursor on the word falsify above:
Command |
Effect |
cw |
deletes the current word to register ", and enter insert mode |
<b> |
enters the text (we're in insert mode). This text is the beginning of the html tag for bold text. |
^r |
start the paste-while-in insert mode |
" |
paste from register ' ("falsify") into the current location in the file. |
</b> |
enter the closing tag fror bold |
ESC |
Return to command mode. |
u |
Removes the <b> tag from "falsify"! |
Be warned, the '.' command doesn't see that you used the ^R command, so if you move to the next word and hit '.', vim will change that word to be be the bold-tagged "falsify", too. If you want to bold a bunch of different words, you should learn how to record and playback macros (:help q).
34. Abbreviate!
One of the easiest ways to customize your editor is with abbreviations. For instance, of the most commonly mistyped python lines is the famous "main" invocation:
if __name__ == "__main__":
I would like to type the word "pymain" and have the editor replace it with the invocation above. Easy to do:
:ab pymain if __name__ == "__main__":
Now when I type any non-alphabetic character after the word pymain, it is expanded automatically. All that VIM needs is an "ab" command and a whole word to expand in insert mode. The expansion is immediate and automatic, there is no hotkey by which you request the expansion. As a result, it will happen when you don't want it to happen. Every time I type pymain, I get the expansion listed above, even if it is an accident. I actually have to type the word wrong exit insert mode and then go back to correct it, because I can't safely type it at all.
I can add this line to my .vimrc, as long as I leave out the leading colon. My vimrc has a number of abbreviations in it currently, because I choose my abbreviations carefully.
I find that I sometimes type 'teh' when I mean 'the'. This is easy to fix.
:ab teh the
I never type teh intentionally, so it is a good abbreviation candidate.
You will want to use this feature carefully, so that you don't end up getting unwanted expansions, but it is quite nice if you have common misspellings or long sequences of code that you would otherwise have to type far too often.
35. Record and playback macros.
In the help system, this is referred to as "complex-repeat".
You enter macro recording mode by pressing the command 'q', followed by a register into which the macro will be stored. You can use any of the alphabetic keys (upper or lower case), and any of the digits. Of course you can have all 26 lower case, all uppercase 26 and all digits assigned to macros at one time if you like.
Every keystroke you type will be recorded until you press the 'q' key again.
To replay a macro, you use the @ key, followed by the register name.
Once you have replayed a macro, the undo key will see that macro as a single action. It's very handy, since a macro can make changes in many lines found throughout the file.
VIM remembers what macro you last played, and can repeat it with the double-jump. The double-jump would be "@@".
The dot command will see it as a single action as well. That's very cool, because the above lesson becomes much more useful. It works something like this:
Command |
Effect |
qa |
Start recording the macro to register 'a' |
cw |
deletes the current word to register ", and enter insert mode |
<b> |
enters the text (we're in insert mode). This text is the beginning of the html tag for bold text. |
^r |
start the paste-while-in insert mode |
" |
paste from register ' ("falsify") into the current location in the file. |
</b> |
enter the closing tag fror bold |
ESC |
Return to command mode. |
q |
Stop recording |
W |
Move one word to the right. |
@@ |
replay the macro, wrapping the word under the cursor |
W |
Move one more word to the right. |
. |
replay the macro again, wrapping the word under the cursor |
The macro you recorded is just text in a register. You can paste it into a document, edit it to improve its operation, yank it back into the register, etc. Macros provide a nice way to simplify complex edits.
Try ":help q" to see more about macro usage. I didn't tell it all.
36. Mapping Keys
Whatever you can do by hand, or with a macro, you can also do with key mapping. All a key mapping does is assign a macro to a keystroke. Here is an example:
" Move between files in a long list
map <F3> :prev<CR>
map <F4> :next<CR>
Learn more about mapping via :help map.
37. Colors and Stuff
Vim is amazingly customizable, including the colors it uses. Some people make their vim themes available on the internet, and a number of color themes are included in the standard distribution. The one you have seen most is probably the one called "default". If you are in a separate color scheme, you can see it via the command:
:echo g:colors_name
Try some of the existing color schemes like delek, darkblue, desert, koehler, elflord, peachpuff, or slate. You can always return to default, or just exit and reload the editor. The command you need is:
colorscheme delek
For 'delek', substitue any scheme you like. You can see all the schemes in the explorer mode by typing:
:e $VIM/vim70/colors
(assuming you are using vim 7.0. You may have to adjust for verion numbers).
The colorschemes are built from commands that set individual elements such as the foreground and background of the status line, You can learn an awful lot by reading one or two of the colors files.
The color commands start with "hi" (short for highlight), then the kind of thing to color (called a groupname), and then a string of colors to use for plain terminals (ask your dad) denoted as "term", color terminals denoted as "cterm", and guis (gvim) denoted as "gui".
Here are a few settings I like for gvim:
hi LineNr guibg=lightgray guifg=black
hi StatusLine guibg=yellow guifg=darkblue
hi NonText guibg=darkgray
hi ToDo guifg=DarkRed
These will color the nontext area that comes past the end of text, the number column on the left of the screen (if you do "set nu"), and colors the active status line (title bar) differently from the status line for inactive tiles/windows.
For more on coloring and theming, you should consult the built-in help (:help hi) or perhaps some other more weighty and complete guide to VIM
38. Exploiting the path.
There is a special vim variable called path which will help you to find files which are referenced by the files you will be editing. This feature is specifically useful if you are editing C program files and you point the path variable to the /usr/include/* directories.
The value you provide for path is a comma-separated list of paths where files can be found. This allows you to point to the standard include, and your project includes, and any other dirs you find useful.
To use this feature, place the cursor on the name of a file, and (while in normal/control mode) type gf or ^wf. The file will be loaded into the current window.
set path=.,.**,/usr/include/**,/usr/share/** |
Probably excessive, but sets the path to find just about anything. May take a long time. |
gf |
Goto File: Get the file whose name is under the cursor |
^Wf |
Window File: Same as gf except opens the file in a new window |
:e# |
Return to the previous window |
I find the window version more useful generally, but I find the non-window version so much easier to type that I will use it instead. I wish that the file navigation would add to the tag stack, so that ^t would return you to the previous file, but no. Stefan Berglund informs me that the ^o will, however. Now it is much easier to jump backward through the jump list.
The other workaround is to set a bookmark as a capital letter so that you can do a return to it from another file. I know that sounds a little awful, and it is a little awful, but it works.
Still, for C/C++ programmers, the combination of \K and ^wf allows a lot of file navigation, and the bookmarks are handy for getting in/out of header files and the like.
The path is also used by the name completion (^n) system to find the files in which it will search for word completions.