vimhelp.org replace a pattern ----------------- :g//s///g :g/editer/s//editor/g (replace all mis-spellings...) :g/^M/s///g (nuke all control-M's) :g/^[\w]*$/d (delete all blank lines) alternatives to replace a ^Ms ----------------------------- :g/^M/s///g :set fileformat=unix :1,$s/^V^M//g $ sed 's/^M//g' filename > newfilename $ dos2unix filename newfilename $ cat filename | col -b > newfilename cw - change to end of word C - change to end of line Pasting without indents ----------------------- :set paste :set nopaste OR :set noai (auto-indent) :set ai Moving around ------------- $ - End of line 0 - Beginning of line hjkl - letter at a time w - word at a time vim stuff --------- :colorscheme ron - changes colorscheme :colorscheme pablo :colorscheme will list all colorschemes saved in /usr/share/vim/vimNN/colors where NN is the version number provided colors are in $VIMRUNTIME/colors sometimes /var/share/vim/colors :syntax clear - turn off highlighting temporarily :syntax off - stop highlighting completely :noh - turns off highlighting after a search .vimrc file holds commands... Visual Selection v - Select from beginning cursor V - Select from end cursor ctrl-V - Select rectangular region in GUI gU - change visual selection to uppercase gu - change visual selection to lowercase Below is taken from http://www.oualline.com/10/top_10.html. Top 10 things Vi user need to know about Vim 1. :help Vim has a extensive on-line help system. You can access this by using the: :help 2. You don't get the good features unless you turn them on By default Vim starts in Vi compatibility mode. This means that most of the good features are turned off. The easiest way to turn them on is to create a $HOME/.vimrc file. Here's a sample one. (The documentation for this file is here.) One of the first features you'll notice when your create your .vimrc file is that you have more than one level of undo. 3. Multiple Windows The command: :split splits the current window in two. You can then move the cursor up to a window with CTRL-W j and down a window with CTRL-W k. The command: :split file.txt splits the window and begins editing another file. To close a window, use the normal Vim exit commands ZZ or :q!. 4. Visual Mode Typing v causes Vim. to enter "visual" mode. You can then highlight a block a text and then execute a Vim editing command such as d, y, or > on it. For example, let's highlight a block of text starting with v and then moving the cursor. We now delete it with the d command. The v command selects text by character. The CTRL-V command selects text as a block. The V command selects line. 5. The 'incsearch' and 'hlsearch' options The 'incsearch' option By default, searching starts after you enter the string. With the option: :set incsearch set, incremental searches will be done. The Vim editor will start searching when you type the first character of the search string. As you type in more characters, the search is refined. The 'hlsearch' option The "highlight search option" ('hlsearch') turns on search highlighting. This option is enabled by the command: :set hlsearch After the option is enabled, any search highlights the string matched by the search. 6. The 'cindent' option and the = command The Vi editor has a 'autoindent' option which indents each line the same the previous one. The Vim editor does a much better job of indentation. The 'cindent' option is set with the command: :set cindent This turns on C style indentation. Each new line will be automatically indented the correct amount according to the C indentation standard. 7. The :make command You've created a program. You've even got a Makefile for it. Now you need to compile your program and correct the errors. To do this, start with the command: :make This runs the make command and captures the output. When the command finishes the editor starts editing the first file. The next step is to fix the error. After that you need to go to the line causing the next error. This is done using the command: :cn This command will go to the location of the next error even if it is in another file. You can continue fixing problems and using :cn until all your problems are over or you want to do a recompile. If you want to see the current error message again, use the command: :cc 8. Tag navigation The command: $ ctags *.c generates a "table of contents" file containing all the tags in the files you've listed on the command. The name of this file is tags. This file can be used by Vim to aide in the editing of a program. The command: $ gvim -t a_function starts Vim and positions the cursor at the definition of the function "a_function". (No matter what file it is in.) Tag Navigation Now suppose "a_function" calls "write_block": void a_function(void) { write_block(); //... You need to see what "write_block" does. To do this, position the cursor over the "write_block" call and press CTRL-]. The editor will jump to the definition of "write_block" (even if it has to switch files to do so.) Now "write_block" calls "write_char". So you position the cursor over the "write_char" and press CTRL-]. The editor now jumps to the definition of this function. Having figured everything out, you can return up a level with the CTRL-T command. This causes you to go from "write_char" to the call in "write_block". The next CTRL-T returns to the "write_block" call in "a_function". 9. Abbreviations We have the following abbreviations defined in our ~/.vimrc. :ab #b /**************************************** :ab #e ^V^H*****************************************/ These let use define boxed comments with ease. By typing "#b" we type the top of a boxed comment. Typing "#e" types the bottom line. (We put the ^V^H^V^H in the file to backup over the comment leader.) These abbreviations were chosen to make the end of the comment align on a tab boundary. 10. Word Completion When your typing and you enter a partial word, you can cause Vim to search for a completion by using the ^P (search for previous marching word) and ^N (search for next match). Links The main Vim site: http://www.vim.org The Vim (Vi Improved) book The Vim Cookbook page The Vim Quick Reference --- Below is taken from http://schlitt.info/applications/blog/index.php?/archives/488-Comfortable-PHP-editing-with-VIM-5.html Next occurrence of a word If you hit * in command mode and your cursor resides on a word, you are taken to the next occurrence of the word. This is quite nice, if you like to know, where a function is called again. Find matching brace VIM 7.0 luckily highlights matching parenthesis, if your cursor resides on a brace, but sometimes you need to quickly jump to that matching brace. You can achieve this by hitting the % sign in command mode. Repeat the last change It often occurs, that you need to perform 1 change several times, but not often enough to write a short script or to address the changes with a complex regex. In those cases you can perform the change once, move the cursor to the next place and hit the . (dot) char, in command mode. Enhanced functionality with external programs This tip is quite commonly known, but I repeat it here, because it's really helpful: Although VIM has a huge set of useful functions, it does not have everything. If you don't find a utility in VIM, you can simply use extern shell tools to perform certain tasks, by using :! in command or visual mode. For example sorting a range of lines can easily be achieved with the following 2 steps: 1. Select the lines to sort in visual mode. 2. Type :!sort and hit return. Indenting and unindeting Especially when editing code, it happens often, that you have to indent/unindent a code block. If you use VIM's auto-indenting features (like used by my .vimrc), VIM can do that job for you, too. Simply select the lines to (un-)indent in visual mode and hit <} to unindent 1 level or > to indent 1 more level. This also works (as usual in VIM) with quantifiers like 4> to indent 4 more levels. Remote file editing Often you have to quickly edit a file on a remote server. Usually you SSH to that server or mount a remote file system locally, edit the desired file and quit the session again. VIM allows you to do this i 1 step, using SCP. On your shell type vim scp://user@server//path/to/the/file and VIM will edit the file directly through SCP. Recover the last visual selection It often happens, that you selected some text in visual mode, e.g. to perform a regex on it. Occasionally your regex is incorrect and you have to revert the changes or they don't even happen. What you then need is to re-select the text portion again, which might take quite a long time, if you deal with large files. Hitting gv in command mode, takes that work from you and selects the last visual selection again. Grep within VIM Refactoring happens quite often in dynamic projects. "Real" IDE's offer a lot of tools for this task. While VIM does not, you can enhance your refactoring process a lot with using regex and this tiny tip: To grep through a lot of files for certain strings and then perform changes on each occurrence, vim offers the :grep command. :grep and VIM will store the list of changes for you and :cn will take you to the next occurance of your string. The :grep command utilizes your systems instance of grep, or a custom command stored in the grepprg configuration variable. There is also an internal implementation of grep available in VIM, which you can use with :vimgrep // . The benefit of the external implementation is, that you can easily customize the command to use, e.g. if you need to ignore certain directories while grepping recursively (for instance .svn dirs). You can also get a list of all occurrences of your grep command, using :ll, which is actually a feature of VIMs quickfix tool. Simply select the next entry you want to jump to and hit return in the location list. Placeholders in commands Who doesn't know the case, where you need to open a file in the same directory, the currently edited file resides in? Sure, you can simply use :split , but if your current working directory is far away from the edited file, you possibly will have to type a long long path again. VIM offers you, to replace certain placeholders in commands automatically, most important: % is replaced with the actual file name (so, :split % will open a new window editing the current file - I know that just :split does the same, but it's a nice example to show what % does). So, how does this help in the described case? The replacement text can also be modified by certain modifiers, like :h, which removes the last portion of a file path (the file name). For instance if you currently edit /home/dotxp/dev/ez/ezc/trunk/ConsoleTools/src/table.php and want to split to /home/dotxp/dev/ez/ezc/trunk/ConsoleTools/src/output.php you can do this easily using :split %:h/output.php. Another useful modifier is :s???, which obviously uses a regex to modify the given path. Unlikely the usual replacement command :s, you need to specify the global modifier g before the regex instead of doing so after it. A short example: :split %:gs?trunk?/releases/1.1/? will split to the file table.php of ConsoleTools release 1.1. Emergency help Appending an exclamation mark (!) to a command (:!) forces VIM to execute the command, even if it might be dangerous to do so. Quite useless, but still funny is :help!. Rewrap my text I reached a stage, where do not only edit my source code using VIM, but mainly every other kind of text data (like documentation, todo lists, etc.), because I'm simply so used to its features. When editing plain text, the automatic wrap features (e.g. textwidth) of VIM are quite useful. In some cases, you might edit text later and therefore destroy a nicely wrapped text block. VIM can easily re-perform the wrapping for you: Select the text block in visual mode (using +) and hit "". Spelled correctly? In VIM versions earlier to 7.0 you could add spellchecking using external scripts. The new version has this feature per default. What you need to do before spell checking is available, is to set the language of the document you are currently editing, using :setlocal spell spelllang=en_us (note, :setlocal only sets the value for the current window, use :set to set it globally). Now VIM highlights all unknown words and you have 3 important new commands available (in command mode). All are used when your cursor resides on a highlighted word: <=> opens a list of suggested replacements, you can choose one by typing its number or leave the selection untouched using . adds the highlighted word to the global dictionary, so that it is recognized as correct on any spell checking session, later. only adds the word to the local dictionary, so that is recognized as correct during the actual spell checking session. Macros Performing complex tasks very often might be quite time consuming and often not solvable using even highly complex regex. Before writing a complex script, you should consider, that VIM can simply follow your instructions and record them to a script: Type in command mode, to instruct VIM to record all following commands to the register a. Perform whatever you like and finally hit again (in command mode). Your macro is now recorded. Type <@> in command mode, to execute the contents of register a (namely your just recorded macro). A simple example for this is to move certain lines of a file to its top: Go to the first line you need. Type . Now perform the changes: to delete the line, <'> to set the "last editing position mark", <:><1> to jump to the first line of the file,

to paste the just deleted line, <'><'> (2 single quotes) to return to the last editing position. Finally hit to end the recording. Now you can just do <@> on every line you need at the start of your file. Easy, isn't it? :) Additionally <@><@> repeats the last macro execution (so you even don't need to remember the register you stored it in). Uppercase letters There are a lot of helpful shortcuts on your keyboard, which you might not know about. Every VIM user should now, that deletes something, (yank) copies something and changes something (delete and start inserting) in VIM (all in command mode). Furthermore, most people know that e.g. deletes the next word, etc.. What I did not know for a long time was, that , and are shortcuts to perform the desired operation until the end of the current line. For instance, simply type to change the contents of the current line from your cursors position on. Where am I? If you have a large resolution (e.g. mine is 166x1200), you sometimes loose your cursor when looking at something else in the room. The new customization features of VIM 7 allow you to add a nice finding help: Add the lines autocmd InsertLeave * se nocul and autocmd InsertEnter * se cul to your .vimrc and you will get the current line underlined as soon as you enter insert mode. Regex driven commands Regular expressions belong to every VIM users toolbox. What some people might not know (so didn't I) is, that you can not only do replacements with them in VIM, but also address lines you want to perform commands on. Simply do :s//= to execute the given on each text portion that matches . Magic regex Those of you who are used to PCRE syntax (and I hope all of you PHP developers out there), will often struggle over VIMs POSIX style regex and forget toescape parenthesis and other stuff. Usually VIMs regex work in so called magic mode, which means that VIM treats only a limited set of characters as magic inside a regex (that applies e.g. to ., matching any character, and * as a quantifier). Other characters, like (, ) and | are per default not considered magic and have to be escaped to make them magic (i\(, \) and \|). While this might be convenient insome cases (like simple text replacements without back-references), it becomes quite ugly, if you need to refer to a lot of capturing parenthesis. For this cases, it makes sense to switch VIM into very magic mode, using \v at the beginning of your regex. The opposite of this switch is \V, which makes the regex very nomagic. Because VIM is normally in magic mode (which corresponds to setting \m, if you change the default behaviour), there is also a nomagic mode, which considers less, but still some, characters as magic. Some simple examples: s/(foo)bar/1/ does not work, () must be escaped s/\v(foo)bar//1/ does work, regex is considered very magic s/.*bar$/foobar/ replaces a line with foobar, that ends on bar s/\V.*bar$/foobar/ replaces a line with foobar, contains literaly ".*bar$" --- Below is taken from http://www.vim.org/tips/tip.php?tip_id=12 To insert space characters whenever the tab key is pressed, set the 'expandtab' option: set expandtab With this option set, if you want to enter a real tab character use Ctrl-V key sequence. To control the number of space characters that will be inserted when the tab key is pressed, set the 'tabstop' option. For example, to insert 4 spaces for a tab, use: set tabstop=4 After the 'expandtab' option is set, all the new tab characters entered will be changed to spaces. This will not affect the existing tab characters. To change all the existing tab characters to match the current tab settings, use :retab To change the number of space characters inserted for indentation, use the 'shiftwidth' option: set shiftwidth=4 For example, to get the following coding style, - No tabs in the source file - All tab characters are 4 space characters use the following set of options: set tabstop=4 set shiftwidth=4 set expandtab --- Splitting a line ---------------- i+return+esc . (period) after that keymap in ~/.exrc (or .vimrc?) to say 'F8' is '"i" + "return" + "esc"'