Vim Cmd Manual
User Manual:
Open the PDF directly: View PDF .
Page Count: 258
Download | |
Open PDF In Browser | View PDF |
.\usr_doc.txt Page 1 *usr_toc.txt* For Vim version 7.4. Last change: 2010 Jul 20 VIM USER MANUAL − by Bram Moolenaar Table Of Contents *user−manual* ============================================================================== Overview Getting Started |usr_01.txt| About the manuals |usr_02.txt| The first steps in Vim |usr_03.txt| Moving around |usr_04.txt| Making small changes |usr_05.txt| Set your settings |usr_06.txt| Using syntax highlighting |usr_07.txt| Editing more than one file |usr_08.txt| Splitting windows |usr_09.txt| Using the GUI |usr_10.txt| Making big changes |usr_11.txt| Recovering from a crash |usr_12.txt| Clever tricks Editing Effectively |usr_20.txt| Typing command−line commands quickly |usr_21.txt| Go away and come back |usr_22.txt| Finding the file to edit |usr_23.txt| Editing other files |usr_24.txt| Inserting quickly |usr_25.txt| Editing formatted text |usr_26.txt| Repeating |usr_27.txt| Search commands and patterns |usr_28.txt| Folding |usr_29.txt| Moving through programs |usr_30.txt| Editing programs |usr_31.txt| Exploiting the GUI |usr_32.txt| The undo tree Tuning Vim |usr_40.txt| |usr_41.txt| |usr_42.txt| |usr_43.txt| |usr_44.txt| |usr_45.txt| Make new commands Write a Vim script Add new menus Using filetypes Your own syntax highlighted Select your language Making Vim Run |usr_90.txt| Installing Vim Reference manual |reference_toc| More detailed information for all commands The user manual is available as a single, ready to print HTML and PDF file here: http://vimdoc.sf.net ============================================================================== Getting Started Read this from start to end to learn the essential commands. |usr_01.txt| About the |01.1| |01.2| |01.3| |01.4| manuals Two manuals Vim installed Using the Vim tutor Copyright |usr_02.txt| The first steps in Vim |02.1| Running Vim for the First Time |02.2| Inserting text .\usr_doc.txt Page 2 |02.3| |02.4| |02.5| |02.6| |02.7| |02.8| Moving around Deleting characters Undo and Redo Other editing commands Getting out Finding help |usr_03.txt| Moving around |03.1| Word movement |03.2| Moving to the start or end of a line |03.3| Moving to a character |03.4| Matching a paren |03.5| Moving to a specific line |03.6| Telling where you are |03.7| Scrolling around |03.8| Simple searches |03.9| Simple search patterns |03.10| Using marks |usr_04.txt| Making small changes |04.1| Operators and motions |04.2| Changing text |04.3| Repeating a change |04.4| Visual mode |04.5| Moving text |04.6| Copying text |04.7| Using the clipboard |04.8| Text objects |04.9| Replace mode |04.10| Conclusion |usr_05.txt| Set your settings |05.1| The vimrc file |05.2| The example vimrc file explained |05.3| Simple mappings |05.4| Adding a plugin |05.5| Adding a help file |05.6| The option window |05.7| Often used options |usr_06.txt| Using syntax highlighting |06.1| Switching it on |06.2| No or wrong colors? |06.3| Different colors |06.4| With colors or without colors |06.5| Printing with colors |06.6| Further reading |usr_07.txt| Editing more than one file |07.1| Edit another file |07.2| A list of files |07.3| Jumping from file to file |07.4| Backup files |07.5| Copy text between files |07.6| Viewing a file |07.7| Changing the file name |usr_08.txt| Splitting |08.1| |08.2| |08.3| |08.4| |08.5| |08.6| |08.7| |08.8| windows Split a window Split a window on another file Window size Vertical splits Moving windows Commands for all windows Viewing differences with vimdiff Various |usr_09.txt| Using the |09.1| |09.2| |09.3| GUI Parts of the GUI Using the mouse The clipboard .\usr_doc.txt Page 3 |09.4| Select mode |usr_10.txt| Making big changes |10.1| Record and playback commands |10.2| Substitution |10.3| Command ranges |10.4| The global command |10.5| Visual block mode |10.6| Reading and writing part of a file |10.7| Formatting text |10.8| Changing case |10.9| Using an external program |usr_11.txt| Recovering from a crash |11.1| Basic recovery |11.2| Where is the swap file? |11.3| Crashed or not? |11.4| Further reading |usr_12.txt| Clever tricks |12.1| Replace a word |12.2| Change "Last, First" to "First Last" |12.3| Sort a list |12.4| Reverse line order |12.5| Count words |12.6| Find a man page |12.7| Trim blanks |12.8| Find where a word is used ============================================================================== Editing Effectively Subjects that can be read independently. |usr_20.txt| Typing command−line commands quickly |20.1| Command line editing |20.2| Command line abbreviations |20.3| Command line completion |20.4| Command line history |20.5| Command line window |usr_21.txt| Go away and come back |21.1| Suspend and resume |21.2| Executing shell commands |21.3| Remembering information; viminfo |21.4| Sessions |21.5| Views |21.6| Modelines |usr_22.txt| Finding the file to edit |22.1| The file explorer |22.2| The current directory |22.3| Finding a file |22.4| The buffer list |usr_23.txt| Editing other files |23.1| DOS, Mac and Unix files |23.2| Files on the internet |23.3| Encryption |23.4| Binary files |23.5| Compressed files |usr_24.txt| Inserting |24.1| |24.2| |24.3| |24.4| |24.5| |24.6| |24.7| |24.8| quickly Making corrections Showing matches Completion Repeating an insert Copying from another line Inserting a register Abbreviations Entering special characters .\usr_doc.txt Page 4 |24.9| Digraphs |24.10| Normal mode commands |usr_25.txt| Editing formatted text |25.1| Breaking lines |25.2| Aligning text |25.3| Indents and tabs |25.4| Dealing with long lines |25.5| Editing tables |usr_26.txt| Repeating |26.1| |26.2| |26.3| |26.4| Repeating with Visual mode Add and subtract Making a change in many files Using Vim from a shell script |usr_27.txt| Search commands and patterns |27.1| Ignoring case |27.2| Wrapping around the file end |27.3| Offsets |27.4| Matching multiple times |27.5| Alternatives |27.6| Character ranges |27.7| Character classes |27.8| Matching a line break |27.9| Examples |usr_28.txt| Folding |28.1| |28.2| |28.3| |28.4| |28.5| |28.6| |28.7| |28.8| |28.9| |28.10| What is folding? Manual folding Working with folds Saving and restoring folds Folding by indent Folding with markers Folding by syntax Folding by expression Folding unchanged lines Which fold method to use? |usr_29.txt| Moving through programs |29.1| Using tags |29.2| The preview window |29.3| Moving through a program |29.4| Finding global identifiers |29.5| Finding local identifiers |usr_30.txt| Editing programs |30.1| Compiling |30.2| Indenting C files |30.3| Automatic indenting |30.4| Other indenting |30.5| Tabs and spaces |30.6| Formatting comments |usr_31.txt| Exploiting the GUI |31.1| The file browser |31.2| Confirmation |31.3| Menu shortcuts |31.4| Vim window position and size |31.5| Various |usr_32.txt| The undo tree |32.1| Undo up to a file write |32.2| Numbering changes |32.3| Jumping around the tree |32.4| Time travelling ============================================================================== Tuning Vim Make Vim work as you like it. .\usr_doc.txt Page 5 |usr_40.txt| Make new commands |40.1| Key mapping |40.2| Defining command−line commands |40.3| Autocommands |usr_41.txt| Write a Vim script |41.1| Introduction |41.2| Variables |41.3| Expressions |41.4| Conditionals |41.5| Executing an expression |41.6| Using functions |41.7| Defining a function |41.8| Lists and Dictionaries |41.9| Exceptions |41.10| Various remarks |41.11| Writing a plugin |41.12| Writing a filetype plugin |41.13| Writing a compiler plugin |41.14| Writing a plugin that loads quickly |41.15| Writing library scripts |41.16| Distributing Vim scripts |usr_42.txt| Add new menus |42.1| Introduction |42.2| Menu commands |42.3| Various |42.4| Toolbar and popup menus |usr_43.txt| Using filetypes |43.1| Plugins for a filetype |43.2| Adding a filetype |usr_44.txt| Your own syntax highlighted |44.1| Basic syntax commands |44.2| Keywords |44.3| Matches |44.4| Regions |44.5| Nested items |44.6| Following groups |44.7| Other arguments |44.8| Clusters |44.9| Including another syntax file |44.10| Synchronizing |44.11| Installing a syntax file |44.12| Portable syntax file layout |usr_45.txt| Select your language |45.1| Language for Messages |45.2| Language for Menus |45.3| Using another encoding |45.4| Editing files with a different encoding |45.5| Entering language text ============================================================================== Making Vim Run Before you can use Vim. |usr_90.txt| Installing Vim |90.1| Unix |90.2| MS−Windows |90.3| Upgrading |90.4| Common installation issues |90.5| Uninstalling Vim ============================================================================== Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_01.txt* Page 6 For Vim version 7.4. Last change: 2010 Nov 03 VIM USER MANUAL − by Bram Moolenaar About the manuals This chapter introduces the manuals available with Vim. conditions under which the commands are explained. |01.1| |01.2| |01.3| |01.4| Read this to know the Two manuals Vim installed Using the Vim tutor Copyright Next chapter: |usr_02.txt| The first steps in Vim Table of contents: |usr_toc.txt| ============================================================================== *01.1* Two manuals The Vim documentation consists of two parts: 1. The User manual Task oriented explanations, from simple to complex. end like a book. Reads from start to 2. The Reference manual Precise description of how everything in Vim works. The notation used in these manuals is explained here: |notation| JUMPING AROUND The text contains hyperlinks between the two parts, allowing you to quickly jump between the description of an editing task and a precise explanation of the commands and options used for it. Use these two commands: Press Press CTRL−] CTRL−O to jump to a subject under the cursor. to jump back (repeat to go further back). Many links are in vertical bars, like this: |bars|. The bars themselves may be hidden or invisible, see below. An option name, like 'number', a command in double quotes like ":write" and any other word can also be used as a link. Try it out: Move the cursor to CTRL−] and press CTRL−] on it. Other subjects can be found with the ":help" command, see |help.txt|. The bars and stars are usually hidden with the |conceal| feature. They also use |hl−Ignore|, using the same color for the text as the background. You can make them visible with: :set conceallevel=0 :hi link HelpBar Normal :hi link HelpStar Normal ============================================================================== *01.2* Vim installed Most of the manuals assume that Vim has been properly installed. If you didn't do that yet, or if Vim doesn't run properly (e.g., files can't be found or in the GUI the menus do not show up) first read the chapter on installation: |usr_90.txt|. *not−compatible* The manuals often assume you are using Vim with Vi−compatibility switched off. For most commands this doesn't matter, but sometimes it is important, e.g., for multi−level undo. An easy way to make sure you are using a nice setup is to copy the example vimrc file. By doing this inside Vim you don't have to check out where it is located. How to do this depends on the system you are using: .\usr_doc.txt Page 7 Unix: :!cp −i $VIMRUNTIME/vimrc_example.vim ~/.vimrc MS−DOS, MS−Windows, OS/2: :!copy $VIMRUNTIME/vimrc_example.vim $VIM/_vimrc Amiga: :!copy $VIMRUNTIME/vimrc_example.vim $VIM/.vimrc If the file already exists you probably want to keep it. If you start Vim now, the 'compatible' option should be off. with this command: You can check it :set compatible? If it responds with "nocompatible" you are doing well. If the response is "compatible" you are in trouble. You will have to find out why the option is still set. Perhaps the file you wrote above is not found. Use this command to find out: :scriptnames If your file is not in the list, check its location and name. If it is in the list, there must be some other place where the 'compatible' option is switched back on. For more info see |vimrc| and |compatible−default|. Note: This manual is about using Vim in the normal way. There is an alternative called "evim" (easy Vim). This is still Vim, but used in a way that resembles a click−and−type editor like Notepad. It always stays in Insert mode, thus it feels very different. It is not explained in the user manual, since it should be mostly self explanatory. See |evim−keys| for details. ============================================================================== *01.3* Using the Vim tutor *tutor* *vimtutor* Instead of reading the text (boring!) you can use the vimtutor to learn your first Vim commands. This is a 30 minute tutorial that teaches the most basic Vim functionality hands−on. On Unix, if Vim has been properly installed, you can start it from the shell: vimtutor On MS−Windows you can find it in the Program/Vim menu. vimtutor.bat in the $VIMRUNTIME directory. Or execute This will make a copy of the tutor file, so that you can edit it without the risk of damaging the original. There are a few translated versions of the tutor. To find out if yours is available, use the two−letter language code. For French: vimtutor fr On Unix, if you prefer using the GUI version of Vim, use "gvimtutor" or "vimtutor −g" instead of "vimtutor". For OpenVMS, if Vim has been properly installed, you can start vimtutor from a VMS prompt with: @VIM:vimtutor Optionally add the two−letter language code as above. On other systems, you have to do a little work: 1. Copy the tutor file. You can do this with Vim (it knows where to find it): .\usr_doc.txt Page 8 vim −u NONE −c 'e $VIMRUNTIME/tutor/tutor' −c 'w! TUTORCOPY' −c 'q' This will write the file "TUTORCOPY" in the current directory. To use a translated version of the tutor, append the two−letter language code to the filename. For French: vim −u NONE −c 'e $VIMRUNTIME/tutor/tutor.fr' −c 'w! TUTORCOPY' −c 'q' 2. Edit the copied file with Vim: vim −u NONE −c "set nocp" TUTORCOPY The extra arguments make sure Vim is started in a good mood. 3. Delete the copied file when you are finished with it: del TUTORCOPY ============================================================================== *01.4* Copyright *manual−copyright* The Vim user manual and reference manual are Copyright (c) 1988−2003 by Bram Moolenaar. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later. The latest version is presently available at: http://www.opencontent.org/openpub/ People who contribute to the manuals must agree with the above copyright notice. *frombook* Parts of the user manual come from the book "Vi IMproved − Vim" by Steve Oualline (published by New Riders Publishing, ISBN: 0735710015). The Open Publication License applies to this book. Only selected parts are included and these have been modified (e.g., by removing the pictures, updating the text for Vim 6.0 and later, fixing mistakes). The omission of the |frombook| tag does not mean that the text does not come from the book. Many thanks to Steve Oualline and New Riders for creating this book and publishing it under the OPL! It has been a great help while writing the user manual. Not only by providing literal text, but also by setting the tone and style. If you make money through selling the manuals, you are strongly encouraged to donate part of the profit to help AIDS victims in Uganda. See |iccf|. ============================================================================== Next chapter: |usr_02.txt| The first steps in Vim Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_02.txt* Page 9 For Vim version 7.4. Last change: 2010 Jul 20 VIM USER MANUAL − by Bram Moolenaar The first steps in Vim This chapter provides just enough information to edit a file with Vim. well or fast, but you can edit. Take some time to practice with these commands, they form the base for what follows. |02.1| |02.2| |02.3| |02.4| |02.5| |02.6| |02.7| |02.8| Not Running Vim for the First Time Inserting text Moving around Deleting characters Undo and Redo Other editing commands Getting out Finding help Next chapter: |usr_03.txt| Moving around Previous chapter: |usr_01.txt| About the manuals Table of contents: |usr_toc.txt| ============================================================================== *02.1* Running Vim for the First Time To start Vim, enter this command: gvim file.txt In UNIX you can type this at any command prompt. If you are running Microsoft Windows, open an MS−DOS prompt window and enter the command. In either case, Vim starts editing a file called file.txt. Because this is a new file, you get a blank window. This is what your screen will look like: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |# | |~ | |~ | |~ | |~ | |"file.txt" [New file] | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ ('#" is the cursor position.) The tilde (~) lines indicate lines not in the file. In other words, when Vim runs out of file to display, it displays tilde lines. At the bottom of the screen, a message line indicates the file is named file.txt and shows that you are creating a new file. The message information is temporary and other information overwrites it. THE VIM COMMAND The gvim command causes the editor to create a new window for editing. use this command: If you vim file.txt the editing occurs inside your command window. In other words, if you are running inside an xterm, the editor uses your xterm window. If you are using an MS−DOS command prompt window under Microsoft Windows, the editing occurs inside this window. The text in the window will look the same for both versions, but with gvim you have extra features, like a menu bar. More about that later. ============================================================================== *02.2* Inserting text .\usr_doc.txt Page 10 The Vim editor is a modal editor. That means that the editor behaves differently, depending on which mode you are in. The two basic modes are called Normal mode and Insert mode. In Normal mode the characters you type are commands. In Insert mode the characters are inserted as text. Since you have just started Vim it will be in Normal mode. To start Insert mode you type the "i" command (i for Insert). Then you can enter the text. It will be inserted into the file. Do not worry if you make mistakes; you can correct them later. To enter the following programmer's limerick, this is what you type: iA very intelligent turtle Found programming UNIX a hurdle After typing "turtle" you press thekey to start a new line. Finally you press the key to stop Insert mode and go back to Normal mode. You now have two lines of text in your Vim window: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |A very intelligent turtle | |Found programming UNIX a hurdle | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ WHAT IS THE MODE? To be able to see what mode you are in, type this command: :set showmode You will notice that when typing the colon Vim moves the cursor to the last line of the window. That's where you type colon commands (commands that start with a colon). Finish this command by pressing the key (all commands that start with a colon are finished this way). Now, if you type the "i" command Vim will display −−INSERT−− at the bottom of the window. This indicates you are in Insert mode. +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |A very intelligent turtle | |Found programming UNIX a hurdle | |~ | |~ | |−− INSERT −− | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ If you press to go back to Normal mode the last line will be made blank. GETTING OUT OF TROUBLE One of the problems for Vim novices is mode confusion, which is caused by forgetting which mode you are in or by accidentally typing a command that switches modes. To get back to Normal mode, no matter what mode you are in, press the key. Sometimes you have to press it twice. If Vim beeps back at you, you already are in Normal mode. ============================================================================== *02.3* Moving around After you return to Normal mode, you can move around by using these keys: h j k l left down up right *hjkl* At first, it may appear that these commands were chosen at random. After all, who ever heard of using l for right? But actually, there is a very good .\usr_doc.txt Page 11 reason for these choices: an editor, and these keys words, these commands are (especially when you type Moving the cursor is the most common thing you do in are on the home row of your right hand. In other placed where you can type them the fastest with ten fingers). Note: You can also move the cursor by using the arrow keys. If you do, however, you greatly slow down your editing because to press the arrow keys, you must move your hand from the text keys to the arrow keys. Considering that you might be doing it hundreds of times an hour, this can take a significant amount of time. Also, there are keyboards which do not have arrow keys, or which locate them in unusual places; therefore, knowing the use of the hjkl keys helps in those situations. One way to remember these commands is that h is on the left, l is on the right and j points down. In a picture: k h l j The best way to learn these commands is by using them. Use the "i" command to insert some more lines of text. Then use the hjkl keys to move around and insert a word somewhere. Don't forget to press to go back to Normal mode. The |vimtutor| is also a nice way to learn by doing. For Japanese users, Hiroshi Iwatani suggested using this: Huan Ho (Yellow river) Komsomolsk ^ | <−−− −−−> Los Angeles | v Java (the island, not the programming language) ============================================================================== *02.4* Deleting characters To delete a character, move the cursor over it and type "x". (This is a throwback to the old days of the typewriter, when you deleted things by typing xxxx over them.) Move the cursor to the beginning of the first line, for example, and type xxxxxxx (seven x's) to delete "A very ". The result should look like this: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |intelligent turtle | |Found programming UNIX a hurdle | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Now you can insert new text, for example by typing: iA young This begins an insert (the i), inserts the words "A young", and then exits insert mode (the final ). The result: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |A young intelligent turtle | |Found programming UNIX a hurdle | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ DELETING A LINE .\usr_doc.txt Page 12 To delete a whole line use the "dd" command. then move up to fill the gap: The following line will +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |Found programming UNIX a hurdle | |~ | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ DELETING A LINE BREAK In Vim you can join two lines together, which means that the line break between them is deleted. The "J" command does this. Take these two lines: A young intelligent turtle Move the cursor to the first line and press "J": A young intelligent turtle ============================================================================== *02.5* Undo and Redo Suppose you delete too much. Well, you can type it in again, but an easier way exists. The "u" command undoes the last edit. Take a look at this in action: After using "dd" to delete the first line, "u" brings it back. Another one: Move the cursor to the A in the first line: A young intelligent turtle Now type xxxxxxx to delete "A young". The result is as follows: intelligent turtle Type "u" to undo the last delete. restores the character. That delete removed the g, so the undo g intelligent turtle The next u command restores the next−to−last character deleted: ng intelligent turtle The next u command gives you the u, and so on: ung intelligent turtle oung intelligent turtle young intelligent turtle young intelligent turtle A young intelligent turtle Note: If you type "u" twice, and the result is that you get the same text back, you have Vim configured to work Vi compatible. Look here to fix this: |not−compatible|. This text assumes you work "The Vim Way". You might prefer to use the good old Vi way, but you will have to watch out for small differences in the text then. REDO If you undo too many times, you can press CTRL−R (redo) to reverse the preceding command. In other words, it undoes the undo. To see this in action, press CTRL−R twice. The character A and the space after it disappear: .\usr_doc.txt Page 13 young intelligent turtle There's a special version of the undo command, the "U" (undo line) command. The undo line command undoes all the changes made on the last line that was edited. Typing this command twice cancels the preceding "U". A very intelligent turtle xxxx Delete very A intelligent turtle xxxxxx Delete turtle A intelligent Restore line with "U" A very intelligent turtle Undo "U" with "u" A intelligent The "U" command is a change by itself, which the "u" command undoes and CTRL−R redoes. This might be a bit confusing. Don't worry, with "u" and CTRL−R you can go to any of the situations you had. More about that in section |32.2|. ============================================================================== *02.6* Other editing commands Vim has a large number of commands to change the text. Here are a few often used ones. See |Q_in| and below. APPENDING The "i" command inserts a character before the character under the cursor. That works fine; but what happens if you want to add stuff to the end of the line? For that you need to insert text after the cursor. This is done with the "a" (append) command. For example, to change the line and that's not saying much for the turtle. to and that's not saying much for the turtle!!! move the cursor over to the dot at the end of the line. Then type "x" to delete the period. The cursor is now positioned at the end of the line on the e in turtle. Now type a!!! to append three exclamation points after the e in turtle: and that's not saying much for the turtle!!! OPENING UP A NEW LINE The "o" command creates a new, empty line below the cursor and puts Vim in Insert mode. Then you can type the text for the new line. Suppose the cursor is somewhere in the first of these two lines: A very intelligent turtle Found programming UNIX a hurdle If you now use the "o" command and type new text: oThat liked using Vim The result is: A very intelligent turtle That liked using Vim Found programming UNIX a hurdle .\usr_doc.txt Page 14 The "O" command (uppercase) opens a line above the cursor. USING A COUNT Suppose you want to move up nine lines. You can type "kkkkkkkkk" or you can enter the command "9k". In fact, you can precede many commands with a number. Earlier in this chapter, for instance, you added three exclamation points to the end of a line by typing "a!!! ". Another way to do this is to use the command "3a! ". The count of 3 tells the command that follows to triple its effect. Similarly, to delete three characters, use the command "3x". The count always comes before the command it applies to. ============================================================================== *02.7* Getting out To exit, use the "ZZ" command. This command writes the file and exits. Note: Unlike many other editors, Vim does not automatically make a backup file. If you type "ZZ", your changes are committed and there's no turning back. You can configure the Vim editor to produce backup files, see |07.4|. DISCARDING CHANGES Sometimes you will make a sequence of changes and suddenly realize you were better off before you started. Not to worry; Vim has a quit−and−throw−things−away command. It is: :q! Don't forget to press to finish the command. For those of you interested in the details, the three parts of this command are the colon (:), which enters Command−line mode; the q command, which tells the editor to quit; and the override command modifier (!). The override command modifier is needed because Vim is reluctant to throw away changes. If you were to just type ":q", Vim would display an error message and refuse to exit: E37: No write since last change (use ! to override) By specifying the override, you are in effect telling Vim, "I know that what I'm doing looks stupid, but I'm a big boy and really want to do this." If you want to continue editing with Vim: The ":e!" command reloads the original version of the file. ============================================================================== *02.8* Finding help Everything you always wanted to know can be found in the Vim help files. Don't be afraid to ask! To get generic help use this command: :help You could also use the first function key . If your keyboard has a key it might work as well. If you don't supply a subject, ":help" displays the general help window. The creators of Vim did something very clever (or very lazy) with the help system: They made the help window a normal editing window. You can use all the normal Vim commands to move through the help information. Therefore h, j, k, and l move left, down, up and right. To get out of the help window, use the same command you use to get out of the editor: "ZZ". This will only close the help window, not exit Vim. As you read the help text, you will notice some text enclosed in vertical bars .\usr_doc.txt Page 15 (for example, |help|). This indicates a hyperlink. If you position the cursor anywhere between the bars and press CTRL−] (jump to tag), the help system takes you to the indicated subject. (For reasons not discussed here, the Vim terminology for a hyperlink is tag. So CTRL−] jumps to the location of the tag given by the word under the cursor.) After a few jumps, you might want to go back. CTRL−T (pop tag) takes you back to the preceding position. CTRL−O (jump to older position) also works nicely here. At the top of the help screen, there is the notation *help.txt*. This name between "*" characters is used by the help system to define a tag (hyperlink destination). See |29.1| for details about using tags. To get help on a given subject, use the following command: :help {subject} To get help on the "x" command, for example, enter the following: :help x To find out how to delete text, use this command: :help deleting To get a complete index of all Vim commands, use the following command: :help index When you need to get help for a control character command (for example, CTRL−A), you need to spell it with the prefix "CTRL−". :help CTRL−A The Vim editor has many different modes. By default, the help system displays the normal−mode commands. For example, the following command displays help for the normal−mode CTRL−H command: :help CTRL−H To identify other modes, use a mode prefix. insert−mode version of a command, use "i_". following command: If you want the help for the For CTRL−H this gives you the :help i_CTRL−H When you start the Vim editor, you can use several command−line arguments. These all begin with a dash (−). To find what the −t argument does, for example, use the command: :help −t The Vim editor has a number of options that enable you to configure and customize the editor. If you want help for an option, you need to enclose it in single quotation marks. To find out what the 'number' option does, for example, use the following command: :help 'number' The table with all mode prefixes can be found here: |help−context|. Special keys are enclosed in angle brackets. To find help on the up−arrow key in Insert mode, for instance, use this command: :help i_ If you see an error message that you don't understand, for example: E37: No write since last change (use ! to override) You can use the error ID at the start to find help about it: .\usr_doc.txt Page 16 :help E37 Summary: *help−summary* :help Gives you very general help. Scroll down to see a list of all helpfiles, including those added locally (i.e. not distributed with Vim). :help user−toc.txt Table of contents of the User Manual. :help :subject Ex−command "subject", for instance the following: :help :help Help on getting help. :help abc normal−mode command "abc". :help CTRL−B Control key in Normal mode. :help i_abc :help i_CTRL−B The same in Insert mode. :help v_abc :help v_CTRL−B The same in Visual mode. :help c_abc :help c_CTRL−B The same in Command−line mode. :help 'subject' Option 'subject'. :help subject() Function "subject". :help −subject Command−line option "−subject". :help +subject Compile−time feature "+subject". :help EventName Autocommand event "EventName". :help digraphs.txt The top of the helpfile "digraph.txt". Similarly for any other helpfile. :help pattern Find a help tag starting with "pattern". Repeat for others. :help pattern See all possible help tag matches "pattern" at once. :helpgrep pattern Search the whole text of all help files for pattern "pattern". Jumps to the first match. Jump to other matches with: :cn next match :cprev :cN previous match :cfirst :clast first or last match :copen :cclose open/close the quickfix window; press to jump to the item under the cursor ============================================================================== Next chapter: |usr_03.txt| Moving around Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_03.txt* Page 17 For Vim version 7.4. Last change: 2006 Jun 21 VIM USER MANUAL − by Bram Moolenaar Moving around Before you can insert or delete text the cursor has to be moved to the right place. Vim has a large number of commands to position the cursor. This chapter shows you how to use the most important ones. You can find a list of these commands below |Q_lr|. |03.1| |03.2| |03.3| |03.4| |03.5| |03.6| |03.7| |03.8| |03.9| |03.10| Word movement Moving to the start or end of a line Moving to a character Matching a parenthesis Moving to a specific line Telling where you are Scrolling around Simple searches Simple search patterns Using marks Next chapter: |usr_04.txt| Making small changes Previous chapter: |usr_02.txt| The first steps in Vim Table of contents: |usr_toc.txt| ============================================================================== *03.1* Word movement To move the cursor forward one word, use the "w" command. Like most Vim commands, you can use a numeric prefix to move past multiple words. For example, "3w" moves three words. This figure shows how it works: This is a line with example text −−−>−−>−>−−−−−−−−−−−−−−−−−> w w w 3w Notice that "w" moves to the start of the next word if it already is at the start of a word. The "b" command moves backward to the start of the previous word: This is a line with example text <−−−−<−−<−<−−−−−−−−−<−−− b b b 2b b There is also the "e" command that moves to the next end of a word and "ge", which moves to the previous end of a word: This is a line with example text <− <−−− −−−−−> −−−−> ge ge e e If you are at the last word of a line, the "w" command will take you to the first word in the next line. Thus you can use this to move through a paragraph, much faster than using "l". "b" does the same in the other direction. A word ends at a non−word character, such as a ".", "−" or ")". To change what Vim considers to be a word, see the 'iskeyword' option. It is also possible to move by white−space separated WORDs. This is not a word in the normal sense, that's why the uppercase is used. The commands for moving by WORDs are also uppercase, as this figure shows: ge b w e <− <− −−−> −−−> This is−a line, with special/separated/words (and some more). <−−−−− <−−−−− −−−−−−−−−−−−−−−−−−−−> −−−−−> gE B W E .\usr_doc.txt Page 18 With this mix of lowercase and uppercase commands, you can quickly move forward and backward through a paragraph. ============================================================================== *03.2* Moving to the start or end of a line The "$" command moves the cursor to the end of a line. an key it will do the same thing. If your keyboard has The "^" command moves to the first non−blank character of the line. The "0" command (zero) moves to the very first character of the line. The key does the same thing. In a picture: ^ <−−−−−−−−−−−− .....This is a line with example text <−−−−−−−−−−−−−−−−− −−−−−−−−−−−−−−−> 0 $ (the "....." indicates blanks here) The "$" command takes a count, like most movement commands. But moving to the end of the line several times doesn't make sense. Therefore it causes the editor to move to the end of another line. For example, "1$" moves you to the end of the first line (the one you're on), "2$" to the end of the next line, and so on. The "0" command doesn't take a count argument, because the "0" would be part of the count. Unexpectedly, using a count with "^" doesn't have any effect. ============================================================================== *03.3* Moving to a character One of the most useful movement commands is command. The command "fx" searches forward character x. Hint: "f" stands for "Find". For example, you are at the beginning of want to go to the h of human. Just execute will be positioned over the h: the single−character search in the line for the single the following line. Suppose you the command "fh" and the cursor To err is human. To really foul up you need a computer. −−−−−−−−−−>−−−−−−−−−−−−−−−> fh fy This also shows that the command "fy" moves to the end of the word really. You can specify a count; therefore, you can go to the "l" of "foul" with "3fl": To err is human. To really foul up you need a computer. −−−−−−−−−−−−−−−−−−−−−> 3fl The "F" command searches to the left: To err is human. To really foul up you need a computer. <−−−−−−−−−−−−−−−−−−−−− Fh The "tx" command works like the "fx" command, except it stops one character before the searched character. Hint: "t" stands for "To". The backward version of this command is "Tx". To err is human. To really foul up you need a computer. <−−−−−−−−−−−− −−−−−−−−−−−−−> Th tn These four commands can be repeated with ";". "," repeats in the other direction. The cursor is never moved to another line. Not even when the sentence continues. Sometimes you will start a search, only to realize that you have typed the .\usr_doc.txt wrong command. that you really aborted forward operations, not Page 19 You type "f" to search backward, for example, only to realize meant "F". To abort a search, press . So "f " is an search and doesn't do anything. Note: cancels most just searches. ============================================================================== *03.4* Matching a parenthesis When writing a program you often end up with nested () constructs. Then the "%" command is very handy: It moves to the matching paren. If the cursor is on a "(" it will move to the matching ")". If it's on a ")" it will move to the matching "(". % <−−−−−> if (a == (b * c) / d) <−−−−−−−−−−−−−−−−> % This also works for [] and {} pairs. 'matchpairs' option.) (This can be defined with the When the cursor is not on a useful character, "%" will search forward to find one. Thus if the cursor is at the start of the line of the previous example, "%" will search forward and find the first "(". Then it moves to its match: if (a == (b * c) / d) −−−+−−−−−−−−−−−−−−−−> % ============================================================================== *03.5* Moving to a specific line If you are a C or C++ programmer, you are familiar with error messages such as the following: prog.c:33: j undeclared (first use in this function) This tells you that you might want to fix something on line 33. So how do you find line 33? One way is to do "9999k" to go to the top of the file and "32j" to go down thirty two lines. It is not a good way, but it works. A much better way of doing things is to use the "G" command. With a count, this command positions you at the given line number. For example, "33G" puts you on line 33. (For a better way of going through a compiler's error list, see |usr_30.txt|, for information on the :make command.) With no argument, "G" positions you at the end of the file. A quick way to go to the start of a file use "gg". "1G" will do the same, but is a tiny bit more typing. 7G | | | | | | V first line of a file text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text last line of a file ^ | | | gg | | | V G Another way to move to a line is using the "%" command with a count. For example "50%" moves you to halfway the file. "90%" goes to near the end. The previous assumes that you want to move to a line in the file, no matter if it's currently visible or not. What if you want to move to one of the lines you can see? This figure shows the three commands you can use: H −−> +−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | text sample text | | sample text | | text sample text | .\usr_doc.txt Page 20 M −−> L −−> | sample text | | text sample text | | sample text | | text sample text | | sample text | | text sample text | +−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Hints: "H" stands for Home, "M" for Middle and "L" for Last. ============================================================================== *03.6* Telling where you are To see where you are in a file, there are three ways: 1. Use the CTRL−G command. option is off): You get a message like this (assuming the 'ruler' "usr_03.txt" line 233 of 650 −−35%−− col 45−52 This shows the name of the file you are editing, the line number where the cursor is, the total number of lines, the percentage of the way through the file and the column of the cursor. Sometimes you will see a split column number. For example, "col 2−9". This indicates that the cursor is positioned on the second character, but because character one is a tab, occupying eight spaces worth of columns, the screen column is 9. 2. Set the 'number' option. every line: This will display a line number in front of :set number To switch this off again: :set nonumber Since 'number' is a boolean option, prepending "no" to its name has the effect of switching it off. A boolean option has only these two values, it is either on or off. Vim has many options. Besides the boolean ones there are options with a numerical value and string options. You will see examples of this where they are used. 3. Set the 'ruler' option. This will display the cursor position in the lower right corner of the Vim window: :set ruler Using the 'ruler' option has the advantage that it doesn't take much room, thus there is more space for your text. ============================================================================== *03.7* Scrolling around The CTRL−U command scrolls down half a screen of text. Think of looking through a viewing window at the text and moving this window up by half the height of the window. Thus the window moves up over the text, which is backward in the file. Don't worry if you have a little trouble remembering which end is up. Most users have the same problem. The CTRL−D command moves the viewing window down half a screen in the file, thus scrolls the text up half a screen. +−−−−−−−−−−−−−−−+ | some text | | | | 123456 | CTRL−U +−−−−−−−−−−−−−−−−+ | some text | | some text | | some text | | some text | −−> | | | 123456 | +−−−−−−−−−−−−−−−−+ .\usr_doc.txt | 7890 | | | | example | +−−−−−−−−−−−−−−−+ Page 21 CTRL−D −−> +−−−−−−−−−−−−−−−−+ | 7890 | | | | example | | example | | example | | example | +−−−−−−−−−−−−−−−−+ To scroll one line at a time use CTRL−E (scroll up) and CTRL−Y (scroll down). Think of CTRL−E to give you one line Extra. (If you use MS−Windows compatible key mappings CTRL−Y will redo a change instead of scroll.) To scroll forward by a whole screen (except for two lines) use CTRL−F. The other way is backward, CTRL−B is the command to use. Fortunately CTRL−F is Forward and CTRL−B is Backward, that's easy to remember. A common issue is that after moving down many lines with "j" your cursor is at the bottom of the screen. You would like to see the context of the line with the cursor. That's done with the "zz" command. +−−−−−−−−−−−−−−−−−−+ | some text | | some text | | some text | | some text | | some text | | some text | | line with cursor | +−−−−−−−−−−−−−−−−−−+ zz −−> +−−−−−−−−−−−−−−−−−−+ | some text | | some text | | some text | | line with cursor | | some text | | some text | | some text | +−−−−−−−−−−−−−−−−−−+ The "zt" command puts the cursor line at the top, "zb" at the bottom. There are a few more scrolling commands, see |Q_sc|. To always keep a few lines of context around the cursor, use the 'scrolloff' option. ============================================================================== *03.8* Simple searches To search for a string, use the "/string" command. for example, use the command: To find the word include, /include You will notice that when you type the "/" the cursor jumps to the last line of the Vim window, like with colon commands. That is where you type the word. You can press the backspace key (backarrow or ) to make corrections. Use the and cursor keys when necessary. Pressing executes the command. Note: The characters .*[]^%/\?~$ have special meanings. If you want to use them in a search you must put a \ in front of them. See below. To find the next occurrence of the same string use the "n" command. to find the first #include after the cursor: Use this /#include And then type "n" several times. You will move to each #include in the text. You can also use a count if you know which match you want. Thus "3n" finds the third match. Using a count with "/" doesn't work. The "?" command works like "/" but searches backwards: ?word The "N" command repeats the last search the opposite direction. Thus using "N" after a "/" command search backwards, using "N" after "?" searches forward. .\usr_doc.txt Page 22 IGNORING CASE Normally you have to type exactly what you want to find. If you don't care about upper or lowercase in a word, set the 'ignorecase' option: :set ignorecase If you now search for "word", it will also match "Word" and "WORD". case again: To match :set noignorecase HISTORY Suppose you do three searches: /one /two /three Now let's start searching by typing a simple "/" without pressing . If you press (the cursor key), Vim puts "/three" on the command line. Pressing at this point searches for three. If you do not press , but press instead, Vim changes the prompt to "/two". Another press of moves you to "/one". You can also use the cursor key to move through the history of search commands in the other direction. If you know what a previously used pattern starts with, and you want to use it again, type that character before pressing . With the previous example, you can type "/o " and Vim will put "/one" on the command line. The commands starting with ":" also have a history. That allows you to recall a previous command and execute it again. These two histories are separate. SEARCHING FOR A WORD IN THE TEXT Suppose you see the word "TheLongFunctionName" in the text and you want to find the next occurrence of it. You could type "/TheLongFunctionName", but that's a lot of typing. And when you make a mistake Vim won't find it. There is an easier way: Position the cursor on the word and use the "*" command. Vim will grab the word under the cursor and use it as the search string. The "#" command does the same in the other direction. You can prepend a count: "3*" searches for the third occurrence of the word under the cursor. SEARCHING FOR WHOLE WORDS If you type "/the" it will also match "there". in "the" use: To only find words that end /the\> The "\>" item is a special marker that only matches at the end of a word. Similarly "\<" only matches at the begin of a word. Thus to search for the word "the" only: /\ This does not match "there" or "soothe". Notice that the "*" and "#" commands use these start−of−word and end−of−word markers to only find whole words (you can use "g*" and "g#" to match partial words). HIGHLIGHTING MATCHES While editing a program you see a variable called "nr". You want to check .\usr_doc.txt Page 23 where it's used. You could move the cursor to "nr" and use the "*" command and press "n" to go along all the matches. There is another way. Type this command: :set hlsearch If you now search for "nr", Vim will highlight all matches. That is a very good way to see where the variable is used, without the need to type commands. To switch this off: :set nohlsearch Then you need to switch it on again if you want to use it for the next search command. If you only want to remove the highlighting, use this command: :nohlsearch This doesn't reset the option. Instead, it disables the highlighting. As soon as you execute a search command, the highlighting will be used again. Also for the "n" and "N" commands. TUNING SEARCHES There are a few options that change how searching works. essential ones: These are the :set incsearch This makes Vim display the match for the string while you are still typing it. Use this to check if the right match will be found. Then press to really jump to that location. Or type more to change the search string. :set nowrapscan This stops the search at the end of the file. Or, when you are searching backwards, at the start of the file. The 'wrapscan' option is on by default, thus searching wraps around the end of the file. INTERMEZZO If you like one of the options mentioned before, and set it each time you use Vim, you can put the command in your Vim startup file. Edit the file, as mentioned at |not−compatible|. Or use this command to find out where it is: :scriptnames Edit the file, for example with: :edit ~/.vimrc Then add a line with the command to set the option, just like you typed it in Vim. Example: Go:set hlsearch "G" moves to the end of the file. "o" starts a new line, where you type the ":set" command. You end insert mode with . Then write the file: ZZ If you now start Vim again, the 'hlsearch' option will already be set. ============================================================================== *03.9* Simple search patterns The Vim editor uses regular expressions to specify what to search for. Regular expressions are an extremely powerful and compact way to specify a search pattern. Unfortunately, this power comes at a price, because regular .\usr_doc.txt Page 24 expressions are a bit tricky to specify. In this section we mention only a few essential ones. More about search patterns and commands in chapter 27 |usr_27.txt|. You can find the full explanation here: |pattern|. BEGINNING AND END OF A LINE The ^ character matches the beginning of a line. On an English−US keyboard you find it above the 6. The pattern "include" matches the word include anywhere on the line. But the pattern "^include" matches the word include only if it is at the beginning of a line. The $ character matches the end of a line. Therefore, "was$" matches the word was only if it is at the end of a line. Let's mark the places where "the" matches in this example line with "x"s: the solder holding one of the chips melted and the xxx xxx xxx Using "/the$" we find this match: the solder holding one of the chips melted and the xxx And with "/^the" we find this one: the solder holding one of the chips melted and the xxx You can try searching with "/^the$", it will only match a single line consisting of "the". White space does matter here, thus if a line contains a space after the word, like "the ", the pattern will not match. MATCHING ANY SINGLE CHARACTER The . (dot) character matches any existing character. For example, the pattern "c.m" matches a string whose first character is a c, whose second character is anything, and whose the third character is m. Example: We use a computer that became the cummin winter. xxx xxx xxx MATCHING SPECIAL CHARACTERS If you really want to match a dot, you must avoid its special meaning by putting a backslash before it. If you search for "ter.", you will find these matches: We use a computer that became the cummin winter. xxxx xxxx Searching for "ter\." only finds the second match. ============================================================================== *03.10* Using marks When you make a jump to a position with the "G" command, Vim remembers the position from before this jump. This position is called a mark. To go back where you came from, use this command: `` This ` is a backtick or open single−quote character. If you use the same command a second time you will jump back again. That's because the ` command is a jump itself, and the position from before this jump is remembered. Generally, every time you do a command that can move the cursor further than within the same line, this is called a jump. This includes the search .\usr_doc.txt Page 25 commands "/" and "n" (it doesn't matter how far away the match is). But not the character searches with "fx" and "tx" or the word movements "w" and "e". Also, "j" and "k" are not considered to be a jump. Even when you use a count to make them move the cursor quite a long way away. The `` command jumps back and forth, between two points. The CTRL−O command jumps to older positions (Hint: O for older). CTRL−I then jumps back to newer positions (Hint: I is just next to O on the keyboard). Consider this sequence of commands: 33G /^The CTRL−O You first jump to line 33, then search for a line that starts with "The". Then with CTRL−O you jump back to line 33. Another CTRL−O takes you back to where you started. If you now use CTRL−I you jump to line 33 again. And to the match for "The" with another CTRL−I. | | | V | /^The | V 33G example text example text example text line 33 text example text example text There you are example text ^ | | ^ | | | CTRL−O CTRL−O | | CTRL−I | V | | CTRL−I V Note: CTRL−I is the same as . The ":jumps" command gives a list of positions you jumped to. you used last is marked with a ">". NAMED MARKS The entry which *bookmark* Vim enables you to place your own marks in the text. The command "ma" marks the place under the cursor as mark a. You can place 26 marks (a through z) in your text. You can't see them, it's just a position that Vim remembers. To go to a mark, use the command `{mark}, where {mark} is the mark letter. Thus to move to the a mark: `a The command 'mark (single quotation mark, or apostrophe) moves you to the beginning of the line containing the mark. This differs from the `mark command, which moves you to marked column. The marks can be very useful when working on two related parts in a file. Suppose you have some text near the start of the file you need to look at, while working on some text near the end of the file. Move to the text at the start and place the s (start) mark there: ms Then move to the text you want to work on and put the e (end) mark there: me Now you can move around, and when you want to look at the start of the file, you use this to jump there: 's Then you can use '' to jump back to where you were, or 'e to jump to the text you were working on at the end. There is nothing special about using s for start and e for end, they are just easy to remember. .\usr_doc.txt Page 26 You can use this command to get a list of marks: :marks You will notice a few special marks. ' " [ ] These include: The cursor position before doing a jump The cursor position when last editing the file Start of the last change End of the last change ============================================================================== Next chapter: |usr_04.txt| Making small changes Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_04.txt* Page 27 For Vim version 7.4. Last change: 2014 Aug 29 VIM USER MANUAL − by Bram Moolenaar Making small changes This chapter shows you several ways of making corrections and moving text around. It teaches you the three basic ways to change text: operator−motion, Visual mode and text objects. |04.1| |04.2| |04.3| |04.4| |04.5| |04.6| |04.7| |04.8| |04.9| |04.10| Operators and motions Changing text Repeating a change Visual mode Moving text Copying text Using the clipboard Text objects Replace mode Conclusion Next chapter: |usr_05.txt| Set your settings Previous chapter: |usr_03.txt| Moving around Table of contents: |usr_toc.txt| ============================================================================== *04.1* Operators and motions In chapter 2 you learned the "x" command to delete a single character. And using a count: "4x" deletes four characters. The "dw" command deletes a word. You may recognize the "w" command as the move word command. In fact, the "d" command may be followed by any motion command, and it deletes from the current location to the place where the cursor winds up. The "4w" command, for example, moves the cursor over four words. The d4w command deletes four words. To err is human. To really foul up you need a computer. −−−−−−−−−−−−−−−−−−> d4w To err is human. you need a computer. Vim only deletes up to the position where the motion takes the cursor. That's because Vim knows that you probably don't want to delete the first character of a word. If you use the "e" command to move to the end of a word, Vim guesses that you do want to include that last character: To err is human. you need a computer. −−−−−−−−> d2e To err is human. a computer. Whether the character under the cursor is included depends on the command you used to move to that character. The reference manual calls this "exclusive" when the character isn't included and "inclusive" when it is. The "$" command moves to the end of a line. The "d$" command deletes from the cursor to the end of the line. This is an inclusive motion, thus the last character of the line is included in the delete operation: To err is human. a computer. −−−−−−−−−−−−> d$ To err is human There is a pattern here: operator−motion. You first type an operator command. .\usr_doc.txt Page 28 For example, "d" is the delete operator. Then you type a motion command like "4l" or "w". This way you can operate on any text you can move over. ============================================================================== *04.2* Changing text Another operator is "c", change. It acts just like the "d" operator, except it leaves you in Insert mode. For example, "cw" changes a word. Or more specifically, it deletes a word and then puts you in Insert mode. To err is human −−−−−−−> c2wbe To be human This "c2wbe " contains these bits: c 2w be the change operator move two words (they are deleted and Insert mode started) insert this text back to Normal mode If you have paid attention, you will have noticed something strange: The space before "human" isn't deleted. There is a saying that for every problem there is an answer that is simple, clear, and wrong. That is the case with the example used here for the "cw" command. The c operator works just like the d operator, with one exception: "cw". It actually works like "ce", change to end of word. Thus the space after the word isn't included. This is an exception that dates back to the old Vi. Since many people are used to it now, the inconsistency has remained in Vim. MORE CHANGES Like "dd" deletes a whole line, "cc" changes a whole line. existing indent (leading white space) though. It keeps the Just like "d$" deletes until the end of the line, "c$" changes until the end of the line. It's like doing "d$" to delete the text and then "a" to start Insert mode and append new text. SHORTCUTS Some operator−motion commands are used so often that they have been given a single letter command: x X D C s S stands stands stands stands stands stands for for for for for for dl dh d$ c$ cl cc (delete (delete (delete (change (change (change character under the cursor) character left of the cursor) to end of the line) to end of the line) one character) a whole line) WHERE TO PUT THE COUNT The commands "3dw" and "d3w" delete three words. If you want to get really picky about things, the first command, "3dw", deletes one word three times; the command "d3w" deletes three words once. This is a difference without a distinction. You can actually put in two counts, however. For example, "3d2w" deletes two words, repeated three times, for a total of six words. REPLACING WITH ONE CHARACTER The "r" command is not an operator. It waits for you to type a character, and will replace the character under the cursor with it. You could do the same with "cl" or with the "s" command, but with "r" you don't have to press .\usr_doc.txt Page 29 there is somerhing grong here rT rt rw There is something wrong here Using a count with "r" causes that many characters to be replaced with the same character. Example: There is something wrong here 5rx There is something xxxxx here To replace a character with a line break use "r ". This deletes one character and inserts a line break. Using a count here only applies to the number of characters deleted: "4r " replaces four characters with one line break. ============================================================================== *04.3* Repeating a change The "." command is one of the most simple yet powerful commands in Vim. It repeats the last change. For instance, suppose you are editing an HTML file and want to delete all the tags. You position the cursor on the first and delete the with the command "df>". You then go to the < of the next and kill it using the "." command. The "." command executes the last change command (in this case, "df>"). To delete another tag, position the cursor on the < and use the "." command. f< df> f< . f< . find first < delete to > find next < repeat df> find next < repeat df> To generate a table of contents −−−> −−> −−−−−−−−−> −−−> −−−−−−−−−−−−−> −−> The "." command works for all changes you make, except for the "u" (undo), CTRL−R (redo) and commands that start with a colon (:). Another example: You want to change the word "four" to "five". It appears several times in your text. You can do this quickly with this sequence of commands: /four cwfive n . n . find the first string "four" change the word to "five" find the next "four" repeat the change to "five" find the next "four" repeat the change etc. ============================================================================== *04.4* Visual mode To delete simple items the operator−motion changes work quite well. But often it's not so easy to decide which command will move over the text you want to change. Then you can use Visual mode. You start Visual mode by pressing "v". You move the cursor over the text you want to work on. While you do this, the text is highlighted. Finally type the operator command. For example, to delete from halfway one word to halfway another word: This is an examination sample of visual mode −−−−−−−−−−> velllld This is an example of visual mode When doing this you don't really have to count how many times you have to .\usr_doc.txt Page 30 press "l" to end up in the right position. will be deleted when you press "d". You can immediately see what text If at any time you decide you don't want to do anything with the highlighted text, just press and Visual mode will stop without doing anything. SELECTING LINES If you want to work on whole lines, use "V" to start Visual mode. You will see right away that the whole line is highlighted, without moving around. When you move left or right nothing changes. When you move up or down the selection is extended whole lines at a time. For example, select three lines with "Vjj": +−−−−−−−−−−−−−−−−−−−−−−−−+ | text more text | >> | more text more text | | selected lines >> | text text text | | Vjj >> | text more | V | more text more | +−−−−−−−−−−−−−−−−−−−−−−−−+ SELECTING BLOCKS If you want to work on a rectangular block of characters, use CTRL−V to start Visual mode. This is very useful when working on tables. name pierre john steve Q1 123 0 392 Q2 455 90 63 Q3 234 39 334 To delete the middle "Q2" column, move the cursor to the "Q" of "Q2". Press CTRL−V to start blockwise Visual mode. Now move the cursor three lines down with "3j" and to the next word with "w". You can see the first character of the last column is included. To exclude it, use "h". Now press "d" and the middle column is gone. GOING TO THE OTHER SIDE If you have selected some text in Visual mode, and discover that you need to change the other end of the selection, use the "o" command (Hint: o for other end). The cursor will go to the other end, and you can move the cursor to change where the selection starts. Pressing "o" again brings you back to the other end. When using blockwise selection, you have four corners. "o" only takes you to one of the other corners, diagonally. Use "O" to move to the other corner in the same line. Note that "o" and "O" in Visual mode work very differently from Normal mode, where they open a new line below or above the cursor. ============================================================================== *04.5* Moving text When you delete something with the "d", "x", or another command, the text is saved. You can paste it back by using the p command. (The Vim name for this is put). Take a look at how this works. First you will delete an entire line, by putting the cursor on the line you want to delete and typing "dd". Now you move the cursor to where you want to put the line and use the "p" (put) command. The line is inserted on the line below the cursor. a line line 2 line 3 dd a line line 3 p a line line 3 line 2 .\usr_doc.txt Page 31 Because you deleted an entire line, the "p" command placed the text line below the cursor. If you delete part of a line (a word, for instance), the "p" command puts it just after the cursor. Some more boring try text to out commands. −−−−> dw Some more boring text to out commands. −−−−−−−> welp Some more boring text to try out commands. MORE ON PUTTING The "P" command puts text like "p", but before the cursor. When you deleted a whole line with "dd", "P" will put it back above the cursor. When you deleted a word with "dw", "P" will put it back just before the cursor. You can repeat putting as many times as you like. The same text will be used. You can use a count with "p" and "P". The text will be repeated as many times as specified with the count. Thus "dd" and then "3p" puts three copies of the same deleted line. SWAPPING TWO CHARACTERS Frequently when you are typing, your fingers get ahead of your brain (or the other way around?). The result is a typo such as "teh" for "the". Vim makes it easy to correct such problems. Just put the cursor on the e of "teh" and execute the command "xp". This works as follows: "x" deletes the character e and places it in a register. "p" puts the text after the cursor, which is after the h. teh x th p the ============================================================================== *04.6* Copying text To copy text from one place to another, you could delete it, use "u" to undo the deletion and then "p" to put it somewhere else. There is an easier way: yanking. The "y" operator copies text into a register. Then a "p" command can be used to put it. Yanking is just a Vim name for copying. The "c" letter was already used for the change operator, and "y" was still available. Calling this operator "yank" made it easier to remember to use the "y" key. Since "y" is an operator, you use "yw" to yank a word. usual. To yank two words use "y2w". Example: A count is possible as let sqr = LongVariable * −−−−−−−−−−−−−−> y2w let sqr = LongVariable * p let sqr = LongVariable * LongVariable Notice that "yw" includes the white space after a word. this, use "ye". If you don't want The "yy" command yanks a whole line, just like "dd" deletes a whole line. Unexpectedly, while "D" deletes from the cursor to the end of the line, "Y" works like "yy", it yanks the whole line. Watch out for this inconsistency! Use "y$" to yank to the end of the line. .\usr_doc.txt a text line line 2 last line Page 32 yy a text line line 2 last line a text line line 2 a text line last line p ============================================================================== *04.7* Using the clipboard If you are using the GUI version of Vim (gvim), you can find the "Copy" item in the "Edit" menu. First select some text with Visual mode, then use the Edit/Copy menu. The selected text is now copied to the clipboard. You can paste the text in other programs. In Vim itself too. If you have copied text to the clipboard in another application, you can paste it in Vim with the Edit/Paste menu. This works in Normal mode and Insert mode. In Visual mode the selected text is replaced with the pasted text. The "Cut" menu item deletes the text before it's put on the clipboard. The "Copy", "Cut" and "Paste" items are also available in the popup menu (only when there is a popup menu, of course). If your Vim has a toolbar, you can also find these items there. If you are not using the GUI, or if you don't like using a menu, you have to use another way. You use the normal "y" (yank) and "p" (put) commands, but prepend "* (double−quote star) before it. To copy a line to the clipboard: "*yy To put text from the clipboard back into the text: "*p This only works on versions of Vim that include clipboard support. the clipboard in section |09.3| and here: |clipboard|. More about ============================================================================== *04.8* Text objects If the cursor is in the middle of a word and you want to delete that word, you need to move back to its start before you can do "dw". There is a simpler way to do this: "daw". this is some example text. daw this is some text. The "d" of "daw" is the delete operator. "aw" is a text object. Hint: "aw" stands for "A Word". Thus "daw" is "Delete A Word". To be precise, the white space after the word is also deleted (the white space before the word at the end of the line). Using text objects is the third way to make changes in Vim. We already had operator−motion and Visual mode. Now we add operator−text object. It is very similar to operator−motion, but instead of operating on the text between the cursor position before and after a movement command, the text object is used as a whole. It doesn't matter where in the object the cursor was. To change a whole sentence use "cis". Take this text: Hello there. This is an example. Just some text. Move to the start of the second line, on "is an". Hello there. some text. Now use "cis": Just The cursor is in between the blanks in the first line. Now you type the new .\usr_doc.txt Page 33 sentence "Another line.": Hello there. some text. Another line. Just "cis" consists of the "c" (change) operator and the "is" text object. This stands for "Inner Sentence". There is also the "as" (a sentence) object. The difference is that "as" includes the white space after the sentence and "is" doesn't. If you would delete a sentence, you want to delete the white space at the same time, thus use "das". If you want to type new text the white space can remain, thus you use "cis". You can also use text objects in Visual mode. It will include the text object in the Visual selection. Visual mode continues, thus you can do this several times. For example, start Visual mode with "v" and select a sentence with "as". Now you can repeat "as" to include more sentences. Finally you use an operator to do something with the selected sentences. You can find a long list of text objects here: |text−objects|. ============================================================================== *04.9* Replace mode The "R" command causes Vim to enter replace mode. In this mode, each character you type replaces the one under the cursor. This continues until you type . In this example you start Replace mode on the first "t" of "text": This is text. Rinteresting. This is interesting. You may have noticed that this command replaced 5 characters in the line with twelve others. The "R" command automatically extends the line if it runs out of characters to replace. It will not continue on the next line. You can switch between Insert mode and Replace mode with the key. When you use (backspace) to make correction, you will notice that the old text is put back. Thus it works like an undo command for the last typed character. ============================================================================== *04.10* Conclusion The operators, movement commands and text objects give you the possibility to make lots of combinations. Now that you know how it works, you can use N operators with M movement commands to make N * M commands! You can find a list of operators here: |operator| For example, there are many other ways to delete pieces of text. few often used ones: x X D dw db diw daw dG dgg delete delete delete delete delete delete delete delete delete Here are a character under the cursor (short for "dl") character before the cursor (short for "dh") from cursor to end of line (short for "d$") from cursor to next start of word from cursor to previous start of word word under the cursor (excluding white space) word under the cursor (including white space) until the end of the file until the start of the file If you use "c" instead of "d" they become change commands. yank the text. And so forth. And with "y" you There are a few often used commands to make changes that didn't fit somewhere else: .\usr_doc.txt Page 34 ~ change case of the character under the cursor, and move the cursor to the next character. This is not an operator (unless 'tildeop' is set), thus you can't use it with a motion command. It does work in Visual mode and changes case for all the selected text then. I Start Insert mode after moving the cursor to the first non−blank in the line. A Start Insert mode after moving the cursor to the end of the line. ============================================================================== Next chapter: |usr_05.txt| Set your settings Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_05.txt* Page 35 For Vim version 7.4. Last change: 2012 Nov 20 VIM USER MANUAL − by Bram Moolenaar Set your settings Vim can be tuned to work like you want it to. This chapter shows you how to make Vim start with options set to different values. Add plugins to extend Vim's capabilities. Or define your own macros. |05.1| |05.2| |05.3| |05.4| |05.5| |05.6| |05.7| The vimrc file The example vimrc file explained Simple mappings Adding a plugin Adding a help file The option window Often used options Next chapter: |usr_06.txt| Using syntax highlighting Previous chapter: |usr_04.txt| Making small changes Table of contents: |usr_toc.txt| ============================================================================== *05.1* The vimrc file *vimrc−intro* You probably got tired of typing commands that you use very often. To start Vim with all your favorite option settings and mappings, you write them in what is called the vimrc file. Vim executes the commands in this file when it starts up. If you already have a vimrc file (e.g., when your sysadmin has one setup for you), you can edit it this way: :edit $MYVIMRC If you don't have a vimrc file yet, see |vimrc| to find out where you can create a vimrc file. Also, the ":version" command mentions the name of the "user vimrc file" Vim looks for. For Unix and Macintosh this file is always used and is recommended: ~/.vimrc For MS−DOS and MS−Windows you can use one of these: $HOME/_vimrc $VIM/_vimrc The vimrc file can contain all the commands that you type after a colon. The most simple ones are for setting options. For example, if you want Vim to always start with the 'incsearch' option on, add this line your vimrc file: set incsearch For this new line to take effect you need to exit Vim and start it again. Later you will learn how to do this without exiting Vim. This chapter only explains the most basic items. to write a Vim script file: |usr_41.txt|. For more information on how ============================================================================== *05.2* The example vimrc file explained *vimrc_example.vim* In the first chapter was explained how the example vimrc (included in the Vim distribution) file can be used to make Vim startup in not−compatible mode (see |not−compatible|). The file can be found here: $VIMRUNTIME/vimrc_example.vim .\usr_doc.txt Page 36 In this section we will explain the various commands used in this file. This will give you hints about how to set up your own preferences. Not everything will be explained though. Use the ":help" command to find out more. set nocompatible As mentioned in the first chapter, these manuals explain Vim working in an improved way, thus not completely Vi compatible. Setting the 'compatible' option off, thus 'nocompatible' takes care of this. set backspace=indent,eol,start This specifies where in Insert mode the is allowed to delete the character in front of the cursor. The three items, separated by commas, tell Vim to delete the white space at the start of the line, a line break and the character before where Insert mode started. set autoindent This makes Vim use the indent of the previous line for a newly created line. Thus there is the same amount of white space before the new line. For example when pressing in Insert mode, and when using the "o" command to open a new line. if has("vms") set nobackup else set backup endif This tells Vim to keep a backup copy of a file when overwriting it. But not on the VMS system, since it keeps old versions of files already. The backup file will have the same name as the original file with "~" added. See |07.4| set history=50 Keep 50 commands and 50 search patterns in the history. you want to remember fewer or more lines. Use another number if set ruler Always display the current cursor position in the lower right corner of the Vim window. set showcmd Display an incomplete command in the lower right corner of the Vim window, left of the ruler. For example, when you type "2f", Vim is waiting for you to type the character to find and "2f" is displayed. When you press "w" next, the "2fw" command is executed and the displayed "2f" is removed. +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |text in the Vim window | |~ | |~ | |−− VISUAL −− 2f 43,8 17% | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ ^^^^^^^^^^^ ^^^^^^^^ ^^^^^^^^^^ 'showmode' 'showcmd' 'ruler' set incsearch Display the match for a search pattern when halfway typing it. .\usr_doc.txt Page 37 map Q gq This defines a key mapping. More about that in the next section. This defines the "Q" command to do formatting with the "gq" operator. This is how it worked before Vim 5.0. Otherwise the "Q" command starts Ex mode, but you will not need it. vnoremap _g y:exe "grep /" . escape(@", '\\/') . "/ *.c *.h" This mapping yanks the visually selected text and searches for it in C files. This is a complicated mapping. You can see that mappings can be used to do quite complicated things. Still, it is just a sequence of commands that are executed like you typed them. if &t_Co > 2 || has("gui_running") syntax on set hlsearch endif This switches on syntax highlighting, but only if colors are available. And the 'hlsearch' option tells Vim to highlight matches with the last used search pattern. The "if" command is very useful to set options only when some condition is met. More about that in |usr_41.txt|. *vimrc−filetype* filetype plugin indent on This switches on three very clever mechanisms: 1. Filetype detection. Whenever you start editing a file, Vim will try to figure out what kind of file this is. When you edit "main.c", Vim will see the ".c" extension and recognize this as a "c" filetype. When you edit a file that starts with "#!/bin/sh", Vim will recognize it as a "sh" filetype. The filetype detection is used for syntax highlighting and the other two items below. See |filetypes|. 2. Using filetype plugin files Many different filetypes are edited with different options. For example, when you edit a "c" file, it's very useful to set the 'cindent' option to automatically indent the lines. These commonly useful option settings are included with Vim in filetype plugins. You can also add your own, see |write−filetype−plugin|. 3. Using indent files When editing programs, the indent of a line can often be computed automatically. Vim comes with these indent rules for a number of filetypes. See |:filetype−indent−on| and 'indentexpr'. autocmd FileType text setlocal textwidth=78 This makes Vim break text to avoid lines getting longer than 78 characters. But only for files that have been detected to be plain text. There are actually two parts here. "autocmd FileType text" is an autocommand. This defines that when the file type is set to "text" the following command is automatically executed. "setlocal textwidth=78" sets the 'textwidth' option to 78, but only locally in one file. *restore−cursor* autocmd BufReadPost * \ if line("'\"") > 1 && line("'\"") <= line("$") | \ exe "normal! g`\"" | \ endif Another autocommand. This time it is used after reading any file. The complicated stuff after it checks if the '" mark is defined, and jumps to it .\usr_doc.txt Page 38 if so. The backslash at the start of a line is used to continue the command from the previous line. That avoids a line getting very long. See |line−continuation|. This only works in a Vim script file, not when typing commands at the command−line. ============================================================================== *05.3* Simple mappings A mapping enables you for example, that you other words, you need the :map command, you is as follows: to bind a set of Vim commands to a single key. Suppose, need to surround certain words with curly braces. In to change a word such as "amount" into "{amount}". With can tell Vim that the F5 key does this job. The command :map i{ ea} Note: When entering this command, you must enter by typing four characters. Similarly, is not entered by pressing the key, but by typing five characters. Watch out for this difference when reading the manual! Let's break this down: The F5 function key. This is the trigger key that causes the command to be executed as the key is pressed. i{ Insert the { character. The key ends Insert mode. e Move to the end of the word. a} Append the } to the word. After you execute the ":map" command, all you have to do to put {} around a word is to put the cursor on the first character and press F5. In this example, the trigger is a single key; it can be any string. But when you use an existing Vim command, that command will no longer be available. You better avoid that. One key that can be used with mappings is the backslash. Since you probably want to define more than one mapping, add another character. You could map "\p" to add parentheses around a word, and "\c" to add curly braces, for example: :map \p i( ea) :map \c i{ ea} You need to type the \ and the p quickly after another, so that Vim knows they belong together. The ":map" command (with no arguments) lists your current mappings. At least the ones for Normal mode. More about mappings in section |40.1|. ============================================================================== *05.4* Adding a plugin *add−plugin* *plugin* Vim's functionality can be extended by adding plugins. A plugin is nothing more than a Vim script file that is loaded automatically when Vim starts. You can add a plugin very easily by dropping it in your plugin directory. {not available when Vim was compiled without the |+eval| feature} There are two types of plugins: global plugin: Used for all kinds of files filetype plugin: Only used for a specific type of file The global plugins will be discussed first, then the filetype ones |add−filetype−plugin|. GLOBAL PLUGINS *standard−plugin* .\usr_doc.txt Page 39 When you start Vim, it will automatically load a number of global plugins. You don't have to do anything for this. They add functionality that most people will want to use, but which was implemented as a Vim script instead of being compiled into Vim. You can find them listed in the help index |standard−plugin−list|. Also see |load−plugins|. *add−global−plugin* You can add a global plugin to add functionality that will always be present when you use Vim. There are only two steps for adding a global plugin: 1. Get a copy of the plugin. 2. Drop it in the right directory. GETTING A GLOBAL PLUGIN Where can you find plugins? − Some come with Vim. You can find them in the directory $VIMRUNTIME/macros and its sub−directories. − Download from the net. There is a large collection on http://www.vim.org. − They are sometimes posted in a Vim |maillist|. − You could write one yourself, see |write−plugin|. Some plugins come as a vimball archive, see |vimball|. Some plugins can be updated automatically, see |getscript|. USING A GLOBAL PLUGIN First read the text in the plugin itself to check for any special conditions. Then copy the file to your plugin directory: system Unix PC and OS/2 Amiga Macintosh Mac OS X RISC−OS plugin directory ~/.vim/plugin/ $HOME/vimfiles/plugin or $VIM/vimfiles/plugin s:vimfiles/plugin $VIM:vimfiles:plugin ~/.vim/plugin/ Choices:vimfiles.plugin Example for Unix (assuming you didn't have a plugin directory yet): mkdir ~/.vim mkdir ~/.vim/plugin cp /usr/local/share/vim/vim60/macros/justify.vim ~/.vim/plugin That's all! text. Now you can use the commands defined in this plugin to justify Instead of putting plugins directly into the plugin/ directory, you may better organize them by putting them into subdirectories under plugin/. As an example, consider using "~/.vim/plugin/perl/*.vim" for all your Perl plugins. FILETYPE PLUGINS *add−filetype−plugin* *ftplugins* The Vim distribution comes with a set of plugins for different filetypes that you can start using with this command: :filetype plugin on That's all! See |vimrc−filetype|. If you are missing a plugin for a filetype you are using, or you found a better one, you can add it. There are two steps for adding a filetype plugin: 1. Get a copy of the plugin. 2. Drop it in the right directory. GETTING A FILETYPE PLUGIN .\usr_doc.txt Page 40 You can find them in the same places as the global plugins. Watch out if the type of file is mentioned, then you know if the plugin is a global or a filetype one. The scripts in $VIMRUNTIME/macros are global ones, the filetype plugins are in $VIMRUNTIME/ftplugin. *ftplugin−name* USING A FILETYPE PLUGIN You can add a filetype plugin by dropping it in the right directory. The name of this directory is in the same directory mentioned above for global plugins, but the last part is "ftplugin". Suppose you have found a plugin for the "stuff" filetype, and you are on Unix. Then you can move this file to the ftplugin directory: mv thefile ~/.vim/ftplugin/stuff.vim If that file already exists you already have a plugin for "stuff". You might want to check if the existing plugin doesn't conflict with the one you are adding. If it's OK, you can give the new one another name: mv thefile ~/.vim/ftplugin/stuff_too.vim The underscore is used to separate the name of the filetype from the rest, which can be anything. If you use "otherstuff.vim" it wouldn't work, it would be loaded for the "otherstuff" filetype. On MS−DOS you cannot use long filenames. You would run into trouble if you add a second plugin and the filetype has more than six characters. You can use an extra directory to get around this: mkdir $VIM/vimfiles/ftplugin/fortran copy thefile $VIM/vimfiles/ftplugin/fortran/too.vim The generic names for the filetype plugins are: ftplugin/ .vim ftplugin/ _ .vim ftplugin/ / .vim Here " " can be any name that you prefer. Examples for the "stuff" filetype on Unix: ~/.vim/ftplugin/stuff.vim ~/.vim/ftplugin/stuff_def.vim ~/.vim/ftplugin/stuff/header.vim The part is the name of the filetype the plugin is to be used for. Only files of this filetype will use the settings from the plugin. The part of the plugin file doesn't matter, you can use it to have several plugins for the same filetype. Note that it must end in ".vim". Further reading: |filetype−plugins| |load−plugins| |ftplugin−overrule| |write−plugin| |plugin−details| |new−filetype| Documentation for the filetype plugins and information about how to avoid that mappings cause problems. When the global plugins are loaded during startup. Overruling the settings from a global plugin. How to write a plugin script. For more information about using plugins or when your plugin doesn't work. How to detect a new file type. ============================================================================== *05.5* Adding a help file *add−local−help* *matchit−install* If you are lucky, the plugin you installed also comes with a help file. We will explain how to install the help file, so that you can easily find help for your new plugin. Let us use the "matchit.vim" plugin as an example (it is included with Vim). This plugin makes the "%" command jump to matching HTML tags, if/else/endif in Vim scripts, etc. Very useful, although it's not backwards .\usr_doc.txt Page 41 compatible (that's why it is not enabled by default). This plugin comes with documentation: "matchit.txt". Let's first copy the plugin to the right directory. This time we will do it from inside Vim, so that we can use $VIMRUNTIME. (You may skip some of the "mkdir" commands if you already have the directory.) :!mkdir ~/.vim :!mkdir ~/.vim/plugin :!cp $VIMRUNTIME/macros/matchit.vim ~/.vim/plugin The "cp" command is for Unix, on MS−DOS you can use "copy". Now create a "doc" directory in one of the directories in 'runtimepath'. :!mkdir ~/.vim/doc Copy the help file to the "doc" directory. :!cp $VIMRUNTIME/macros/matchit.txt ~/.vim/doc Now comes the trick, which allows you to jump to the subjects in the new help file: Generate the local tags file with the |:helptags| command. :helptags ~/.vim/doc Now you can use the :help g% command to find help for "g%" in the help file you just added. entry for the local help file when you do: You can see an :help local−additions The title lines from the local help files are automagically added to this section. There you can see which local help files have been added and jump to them through the tag. For writing a local help file, see |write−local−help|. ============================================================================== *05.6* The option window If you are looking for an option that does what you want, you can search in the help files here: |options|. Another way is by using this command: :options This opens a new window, with a list of options with a one−line explanation. The options are grouped by subject. Move the cursor to a subject and press to jump there. Press again to jump back. Or use CTRL−O. You can change the value of an option. For example, move to the "displaying text" subject. Then move the cursor down to this line: set wrap nowrap When you hit , the line will change to: set nowrap wrap The option has now been switched off. Just above this line is a short description of the 'wrap' option. Move the cursor one line up to place it in this line. Now hit and you jump to the full help on the 'wrap' option. For options that take a number or string argument you can edit the value. Then press to apply the new value. For example, move the cursor a few lines up to this line: .\usr_doc.txt Page 42 set so=0 Position the cursor on the zero with "$". Change it into a five with "r5". Then press to apply the new value. When you now move the cursor around you will notice that the text starts scrolling before you reach the border. This is what the 'scrolloff' option does, it specifies an offset from the window border where scrolling starts. ============================================================================== *05.7* Often used options There are an awful lot of options. Most of them you will hardly ever use. Some of the more useful ones will be mentioned here. Don't forget you can find more help on these options with the ":help" command, with single quotes before and after the option name. For example: :help 'wrap' In case you have messed up an option value, you can set it back to the default by putting an ampersand (&) after the option name. Example: :set iskeyword& NOT WRAPPING LINES Vim normally wraps long lines, so that you can see all of the text. Sometimes it's better to let the text continue right of the window. Then you need to scroll the text left−right to see all of a long line. Switch wrapping off with this command: :set nowrap Vim will automatically scroll the text when you move to text that is not displayed. To see a context of ten characters, do this: :set sidescroll=10 This doesn't change the text in the file, only the way it is displayed. WRAPPING MOVEMENT COMMANDS Most commands for moving around will stop moving at the start and end of a line. You can change that with the 'whichwrap' option. This sets it to the default value: :set whichwrap=b,s This allows the key, when used in the first position of a line, to move the cursor to the end of the previous line. And the key moves from the end of a line to the start of the next one. To allow the cursor keys and to also wrap, use this command: :set whichwrap=b,s,<,> This is still only for Normal mode. Insert mode as well: To let and do this in :set whichwrap=b,s,<,>,[,] There are a few other flags that can be added, see 'whichwrap'. VIEWING TABS When there are tabs in a file, you cannot see where they are. visible: :set list To make them .\usr_doc.txt Page 43 Now every tab is displayed as ^I. And a $ is displayed at the end of each line, so that you can spot trailing spaces that would otherwise go unnoticed. A disadvantage is that this looks ugly when there are many Tabs in a file. If you have a color terminal, or are using the GUI, Vim can show the spaces and tabs as highlighted characters. Use the 'listchars' option: :set listchars=tab:>−,trail:− Now every tab will be displayed as ">−−−" (with more or less "−") and trailing white space as "−". Looks a lot better, doesn't it? KEYWORDS The 'iskeyword' option specifies which characters can appear in a word: :set iskeyword iskeyword=@,48−57,_,192−255 The "@" stands for all alphabetic letters. "48−57" stands for ASCII characters 48 to 57, which are the numbers 0 to 9. "192−255" are the printable latin characters. Sometimes you will want to include a dash in keywords, so that commands like "w" consider "upper−case" to be one word. You can do it like this: :set iskeyword+=− :set iskeyword iskeyword=@,48−57,_,192−255,− If you look at the new value, you will see that Vim has added a comma for you. To remove a character use "−=". For example, to remove the underscore: :set iskeyword−=_ :set iskeyword iskeyword=@,48−57,192−255,− This time a comma is automatically deleted. ROOM FOR MESSAGES When Vim starts there is one line at the bottom that is used for messages. When a message is long, it is either truncated, thus you can only see part of it, or the text scrolls and you have to press to continue. You can set the 'cmdheight' option to the number of lines used for messages. Example: :set cmdheight=3 This does mean there is less room to edit text, thus it's a compromise. ============================================================================== Next chapter: |usr_06.txt| Using syntax highlighting Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_06.txt* Page 44 For Vim version 7.4. Last change: 2009 Oct 28 VIM USER MANUAL − by Bram Moolenaar Using syntax highlighting Black and white text is boring. With colors your file comes to life. This not only looks nice, it also speeds up your work. Change the colors used for the different sorts of text. Print your text, with the colors you see on the screen. |06.1| |06.2| |06.3| |06.4| |06.5| |06.6| Switching it on No or wrong colors? Different colors With colors or without colors Printing with colors Further reading Next chapter: |usr_07.txt| Editing more than one file Previous chapter: |usr_05.txt| Set your settings Table of contents: |usr_toc.txt| ============================================================================== *06.1* Switching it on It all starts with one simple command: :syntax enable That should work in most situations to get color in your files. Vim will automagically detect the type of file and load the right syntax highlighting. Suddenly comments are blue, keywords brown and strings red. This makes it easy to overview the file. After a while you will find that black&white text slows you down! If you always want to use syntax highlighting, put the ":syntax enable" command in your |vimrc| file. If you want syntax highlighting only when the terminal supports colors, you can put this in your |vimrc| file: if &t_Co > 1 syntax enable endif If you want syntax highlighting only in the GUI version, put the ":syntax enable" command in your |gvimrc| file. ============================================================================== *06.2* No or wrong colors? There can be a number of reasons why you don't see colors: − Your terminal does not support colors. Vim will use bold, italic and underlined text, but this doesn't look very nice. You probably will want to try to get a terminal with colors. For Unix, I recommend the xterm from the XFree86 project: |xfree−xterm|. − Your terminal does support colors, but Vim doesn't know this. Make sure your $TERM setting is correct. For example, when using an xterm that supports colors: setenv TERM xterm−color or (depending on your shell): TERM=xterm−color; export TERM .\usr_doc.txt Page 45 The terminal name must match the terminal you are using. If it still doesn't work, have a look at |xterm−color|, which shows a few ways to make Vim display colors (not only for an xterm). − The file type is not recognized. Vim doesn't know all file types, and sometimes it's near to impossible to tell what language a file uses. Try this command: :set filetype If the result is "filetype=" then the problem is indeed that Vim doesn't know what type of file this is. You can set the type manually: :set filetype=fortran To see which types are available, look in the directory $VIMRUNTIME/syntax. For the GUI you can use the Syntax menu. Setting the filetype can also be done with a |modeline|, so that the file will be highlighted each time you edit it. For example, this line can be used in a Makefile (put it near the start or end of the file): # vim: syntax=make You might know how to detect the file type yourself. Often the file name extension (after the dot) can be used. See |new−filetype| for how to tell Vim to detect that file type. − There is no highlighting for your file type. You could try using a similar file type by manually setting it as mentioned above. If that isn't good enough, you can write your own syntax file, see |mysyntaxfile|. Or the colors could be wrong: − The colored text is very hard to read. Vim guesses the background color that you are using. If it is black (or another dark color) it will use light colors for text. If it is white (or another light color) it will use dark colors for text. If Vim guessed wrong the text will be hard to read. To solve this, set the 'background' option. For a dark background: :set background=dark And for a light background: :set background=light Make sure you put this _before_ the ":syntax enable" command, otherwise the colors will already have been set. You could do ":syntax reset" after setting 'background' to make Vim set the default colors again. − The colors are wrong when scrolling bottom to top. Vim doesn't read the whole file to parse the text. It starts parsing wherever you are viewing the file. That saves a lot of time, but sometimes the colors are wrong. A simple fix is hitting CTRL−L. Or scroll back a bit and then forward again. For a real fix, see |:syn−sync|. Some syntax files have a way to make it look further back, see the help for the specific syntax file. For example, |tex.vim| for the TeX syntax. ============================================================================== *06.3* Different colors *:syn−default−override* If you don't like the default colors, you can select another color scheme. the GUI use the Edit/Color Scheme menu. You can also type the command: :colorscheme evening In .\usr_doc.txt Page 46 "evening" is the name of the color scheme. There are several others you might want to try out. Look in the directory $VIMRUNTIME/colors. When you found the color scheme that you like, add the ":colorscheme" command to your |vimrc| file. You could also write your own color scheme. 1. Select a color scheme that comes close. directory. For Unix, this should work: This is how you do it: Copy this file to your own Vim !mkdir ~/.vim/colors !cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim This is done from Vim, because it knows the value of $VIMRUNTIME. 2. Edit the color scheme file. term cterm ctermfg ctermbg gui guifg guibg These entries are useful: attributes attributes foreground background attributes foreground background in a B&W terminal in a color terminal color in a color terminal color in a color terminal in the GUI color in the GUI color in the GUI For example, to make comments green: :highlight Comment ctermfg=green guifg=green Attributes you can use for "cterm" and "gui" are "bold" and "underline". If you want both, use "bold,underline". For details see the |:highlight| command. 3. Tell Vim to always use your color scheme. Put this line in your |vimrc|: colorscheme mine If you want to see what the most often used color combinations look like, use this command: :runtime syntax/colortest.vim You will see text in various color combinations. readable and look nice. You can check which ones are ============================================================================== *06.4* With colors or without colors Displaying text in color takes a lot of effort. If you find the displaying too slow, you might want to disable syntax highlighting for a moment: :syntax clear When editing another file (or the same one) the colors will come back. *:syn−off* If you want to stop highlighting completely use: :syntax off This will completely disable syntax highlighting and remove it immediately for all buffers. *:syn−manual* If you want syntax highlighting only for specific files, use this: :syntax manual This will enable the syntax highlighting, but not switch it on automatically .\usr_doc.txt Page 47 when starting to edit a buffer. To switch highlighting on for the current buffer, set the 'syntax' option: :set syntax=ON ============================================================================== *06.5* Printing with colors *syntax−printing* In the MS−Windows version you can print the current file with this command: :hardcopy You will get the usual printer dialog, where you can select the printer and a few settings. If you have a color printer, the paper output should look the same as what you see inside Vim. But when you use a dark background the colors will be adjusted to look good on white paper. There are several options that change the way Vim prints: 'printdevice' 'printheader' 'printfont' 'printoptions' To print only a range of lines, type the command: use Visual mode to select the lines and then v100j:hardcopy "v" starts Visual mode. "100j" moves a hundred lines down, they will be highlighted. Then ":hardcopy" will print those lines. You can use other commands to move in Visual mode, of course. This also works on Unix, if you have a PostScript printer. Otherwise, you will have to do a bit more work. You need to convert the text to HTML first, and then print it from a web browser. Convert the current file to HTML with this command: :TOhtml In case that doesn't work: :source $VIMRUNTIME/syntax/2html.vim You will see it crunching away, this can take quite a while for a large file. Some time later another window shows the HTML code. Now write this somewhere (doesn't matter where, you throw it away later): :write main.c.html Open this file in your favorite browser and print it from there. If all goes well, the output should look exactly as it does in Vim. See |2html.vim| for details. Don't forget to delete the HTML file when you are done with it. Instead of printing, you could also put the HTML file on a web server, and let others look at the colored text. ============================================================================== *06.6* Further reading |usr_44.txt| |syntax| Your own syntax highlighted. All the details. ============================================================================== Next chapter: |usr_07.txt| Editing more than one file Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_07.txt* Page 48 For Vim version 7.4. Last change: 2006 Apr 24 VIM USER MANUAL − by Bram Moolenaar Editing more than one file No matter how many files you have, you can edit them without leaving Vim. Define a list of files to work on and jump from one to the other. Copy text from one file and put it in another one. |07.1| |07.2| |07.3| |07.4| |07.5| |07.6| |07.7| Edit another file A list of files Jumping from file to file Backup files Copy text between files Viewing a file Changing the file name Next chapter: |usr_08.txt| Splitting windows Previous chapter: |usr_06.txt| Using syntax highlighting Table of contents: |usr_toc.txt| ============================================================================== *07.1* Edit another file So far you had to start Vim for every file you wanted to edit. simpler way. To start editing another file, use this command: There is a :edit foo.txt You can use any file name instead of "foo.txt". Vim will close the current file and open the new one. If the current file has unsaved changes, however, Vim displays an error message and does not open the new file: E37: No write since last change (use ! to override) Note: Vim puts an error ID at the start of each error message. If you do not understand the message or what caused it, look in the help system for this ID. In this case: :help E37 At this point, you have a number of alternatives. using this command: You can write the file :write Or you can force Vim to discard your changes and edit the new file, using the force (!) character: :edit! foo.txt If you want to edit another file, but not write the changes in the current file yet, you can make it hidden: :hide edit foo.txt The text with changes is still there, but you can't see it. explained in section |22.4|: The buffer list. This is further ============================================================================== *07.2* A list of files You can start Vim to edit a sequence of files. For example: vim one.c two.c three.c This command starts Vim and tells it that you will be editing three files. .\usr_doc.txt Page 49 Vim displays just the first file. After you have done your thing in this file, to edit the next file you use this command: :next If you have unsaved changes in the current file, you will get an error message and the ":next" will not work. This is the same problem as with ":edit" mentioned in the previous section. To abandon the changes: :next! But mostly you want to save the changes and move on to the next file. is a special command for this: There :wnext This does the same as using two separate commands: :write :next WHERE AM I? To see which file in the argument list you are editing, look in the window title. It should show something like "(2 of 3)". This means you are editing the second file out of three files. If you want to see the list of files, use this command: :args This is short for "arguments". The output might look like this: one.c [two.c] three.c These are the files you started Vim with. "two.c", is in square brackets. The one you are currently editing, MOVING TO OTHER ARGUMENTS To go back one file: :previous This is just like the ":next" command, except that it moves in the other direction. Again, there is a shortcut command for when you want to write the file first: :wprevious To move to the very last file in the list: :last And to move back to the first one again: :first There is no ":wlast" or ":wfirst" command though! You can use a count for ":next" and ":previous". To skip two files forward: :2next AUTOMATIC WRITING When moving around the files and making changes, you have to remember to use ":write". Otherwise you will get an error message. If you are sure you always want to write modified files, you can tell Vim to automatically write .\usr_doc.txt Page 50 them: :set autowrite When you are editing a file which you may not want to write, switch it off again: :set noautowrite EDITING ANOTHER LIST OF FILES You can redefine the list of files without the need to exit Vim and start it again. Use this command to edit three other files: :args five.c six.c seven.h Or use a wildcard, like it's used in the shell: :args *.txt Vim will take you to the first file in the list. Again, if the current file has changes, you can either write the file first, or use ":args!" (with ! added) to abandon the changes. DID YOU EDIT THE LAST FILE? *arglist−quit* When you use a list of files, Vim assumes you want to edit them all. To protect you from exiting too early, you will get this error when you didn't edit the last file in the list yet: E173: 46 more files to edit If you really want to exit, just do it again. you did other commands in between). Then it will work (but not when ============================================================================== *07.3* Jumping from file to file To quickly jump between two files, press CTRL−^ (on English−US keyboards the ^ is above the 6 key). Example: :args one.c two.c three.c You are now in one.c. :next Now you are in two.c. Now use CTRL−^ to go back to one.c. Another CTRL−^ and you are back in two.c. Another CTRL−^ and you are in one.c again. If you now do: :next You are in three.c. Notice that the CTRL−^ command does not change the idea of where you are in the list of files. Only commands like ":next" and ":previous" do that. The file you were previously editing is called the "alternate" file. When you just started Vim CTRL−^ will not work, since there isn't a previous file. PREDEFINED MARKS After jumping to another file, you can use two predefined marks which are very useful: `" This takes you to the position where the cursor was when you left the file. .\usr_doc.txt Page 51 Another mark that is remembered is the position where you made the last change: `. Suppose you are editing the file "one.txt". Somewhere halfway the file you use "x" to delete a character. Then you go to the last line with "G" and write the file with ":w". You edit several other files, and then use ":edit one.txt" to come back to "one.txt". If you now use `" Vim jumps to the last line of the file. Using `. takes you to the position where you deleted the character. Even when you move around in the file `" and `. will take you to the remembered position. At least until you make another change or leave the file. FILE MARKS In chapter 4 was explained how you can place a mark in a file with "mx" and jump to that position with "`x". That works within one file. If you edit another file and place marks there, these are specific for that file. Thus each file has its own set of marks, they are local to the file. So far we were using marks with a lowercase letter. There are also marks with an uppercase letter. These are global, they can be used from any file. For example suppose that we are editing the file "foo.txt". Go to halfway the file ("50%") and place the F mark there (F for foo): 50%mF Now edit the file "bar.txt" and place the B mark (B for bar) at its last line: GmB Now you can use the "'F" command to jump back to halfway foo.txt. another file, type "'B" and you are at the end of bar.txt again. Or edit yet The file marks are remembered until they are placed somewhere else. Thus you can place the mark, do hours of editing and still be able to jump back to that mark. It's often useful to think of a simple connection between the mark letter and where it is placed. For example, use the H mark in a header file, M in a Makefile and C in a C code file. To see where a specific mark is, give an argument to the ":marks" command: :marks M You can also give several arguments: :marks MCP Don't forget that you can use CTRL−O and CTRL−I to jump to older and newer positions without placing marks there. ============================================================================== *07.4* Backup files Usually Vim does not produce a backup file. If you want to have one, all you need to do is execute the following command: :set backup The name of the backup file is the original file with a ~ added to the end. If your file is named data.txt, for example, the backup file name is data.txt~. If you do not like the fact that the backup files end with ~, you can change the extension: :set backupext=.bak This will use data.txt.bak instead of data.txt~. Another option that matters here is 'backupdir'. It specifies where the .\usr_doc.txt Page 52 backup file is written. The default, to write the backup in the same directory as the original file, will mostly be the right thing. Note: When the 'backup' option isn't set but the 'writebackup' is, Vim will still create a backup file. However, it is deleted as soon as writing the file was completed successfully. This functions as a safety against losing your original file when writing fails in some way (disk full is the most common cause; being hit by lightning might be another, although less common). KEEPING THE ORIGINAL FILE If you are editing source files, you might want to keep the file before you make any changes. But the backup file will be overwritten each time you write the file. Thus it only contains the previous version, not the first one. To make Vim keep the original file, set the 'patchmode' option. This specifies the extension used for the first backup of a changed file. Usually you would do this: :set patchmode=.orig When you now edit the file data.txt for the first time, make changes and write the file, Vim will keep a copy of the unchanged file under the name "data.txt.orig". If you make further changes to the file, Vim will notice that "data.txt.orig" already exists and leave it alone. Further backup files will then be called "data.txt~" (or whatever you specified with 'backupext'). If you leave 'patchmode' empty (that is the default), the original file will not be kept. ============================================================================== *07.5* Copy text between files This explains how to copy text from one file to another. Let's start with a simple example. Edit the file that contains the text you want to copy. Move the cursor to the start of the text and press "v". This starts Visual mode. Now move the cursor to the end of the text and press "y". This yanks (copies) the selected text. To copy the above paragraph, you would do: :edit thisfile /This vjjjj$y Now edit the file you want to put the text in. Move the cursor to the character where you want the text to appear after. Use "p" to put the text there. :edit otherfile /There p Of course you can use many other commands to yank the text. For example, to select whole lines start Visual mode with "V". Or use CTRL−V to select a rectangular block. Or use "Y" to yank a single line, "yaw" to yank−a−word, etc. The "p" command puts the text after the cursor. Use "P" to put the text before the cursor. Notice that Vim remembers if you yanked a whole line or a block, and puts it back that way. USING REGISTERS When you want to copy several pieces of text from one file to another, having to switch between the files and writing the target file takes a lot of time. To avoid this, copy each piece of text to its own register. A register is a place where Vim stores text. Here we will use the registers named a to z (later you will find out there are others). Let's copy a sentence to the f register (f for First): .\usr_doc.txt Page 53 "fyas The "yas" command yanks a sentence like before. It's the "f that tells Vim the text should be place in the f register. This must come just before the yank command. Now yank three whole lines to the l register (l for line): "l3Y The count could be before the "l just as well. b (for block) register: To yank a block of text to the CTRL−Vjjww"by Notice that the register specification "b is just before the "y" command. This is required. If you would have put it before the "w" command, it would not have worked. Now you have three pieces of text in the f, l and b registers. Edit another file, move around and place the text where you want it: "fp Again, the register specification "f comes before the "p" command. You can put the registers in any order. And the text stays in the register until you yank something else into it. Thus you can put it as many times as you like. When you delete text, you can also specify a register. Use this to move several pieces of text around. For example, to delete−a−word and write it in the w register: "wdaw Again, the register specification comes before the delete command "d". APPENDING TO A FILE When collecting lines of text into one file, you can use this command: :write >> logfile This will write the text of the current file to the end of "logfile". Thus it is appended. This avoids that you have to copy the lines, edit the log file and put them there. Thus you save two steps. But you can only append to the end of a file. To append only a few lines, select them in Visual mode before typing ":write". In chapter 10 you will learn other ways to select a range of lines. ============================================================================== *07.6* Viewing a file Sometimes you only want to see what a file contains, without the intention to ever write it back. There is the risk that you type ":w" without thinking and overwrite the original file anyway. To avoid this, edit the file read−only. To start Vim in readonly mode, use this command: vim −R file On Unix this command should do the same thing: view file You are now editing "file" in read−only mode. When you try using ":w" you will get an error message and the file won't be written. When you try to make a change to the file Vim will give you a warning: W10: Warning: Changing a readonly file The change will be done though. This allows for formatting the file, for example, to be able to read it easily. .\usr_doc.txt Page 54 If you make changes to a file and forgot that it was read−only, you can still write it. Add the ! to the write command to force writing. If you really want to forbid making changes in a file, do this: vim −M file Now every attempt to change the text will fail. The help files are like this, for example. If you try to make a change you get this error message: E21: Cannot make changes, 'modifiable' is off You could use the −M argument to setup Vim to work in a viewer mode. This is only voluntary though, since these commands will remove the protection: :set modifiable :set write ============================================================================== *07.7* Changing the file name A clever way to start editing a new file is by using an existing file that contains most of what you need. For example, you start writing a new program to move a file. You know that you already have a program that copies a file, thus you start with: :edit copy.c You can delete the stuff you don't need. Now you need to save the file under a new name. The ":saveas" command can be used for this: :saveas move.c Vim will write the file under the given name, and edit that file. Thus the next time you do ":write", it will write "move.c". "copy.c" remains unmodified. When you want to change the name of the file you are editing, but don't want to write the file, you can use this command: :file move.c Vim will mark the file as "not edited". This means that Vim knows this is not the file you started editing. When you try to write the file, you might get this message: E13: File exists (use ! to override) This protects you from accidentally overwriting another file. ============================================================================== Next chapter: |usr_08.txt| Splitting windows Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_08.txt* Page 55 For Vim version 7.4. Last change: 2014 Jul 06 VIM USER MANUAL − by Bram Moolenaar Splitting windows Display two different files above each other. Or view two locations in the file at the same time. See the difference between two files by putting them side by side. All this is possible with split windows. |08.1| |08.2| |08.3| |08.4| |08.5| |08.6| |08.7| |08.8| |08.9| Split a window Split a window on another file Window size Vertical splits Moving windows Commands for all windows Viewing differences with vimdiff Various Tab pages Next chapter: |usr_09.txt| Using the GUI Previous chapter: |usr_07.txt| Editing more than one file Table of contents: |usr_toc.txt| ============================================================================== *08.1* Split a window The easiest way to open a new window is to use the following command: :split This command splits the screen into two windows and leaves the cursor in the top one: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* file one.c */ | |~ | |~ | |one.c=============================| |/* file one.c */ | |~ | |one.c=============================| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ What you see here is two windows on the same file. The line with that status line. It displays information about the window above practice the status line will be in reverse video.) The two windows allow you to view two parts of the same file. you could make the top window show the variable declarations of a the bottom one the code that uses these variables. "====" is it. (In For example, program, and The CTRL−W w command can be used to jump between the windows. If you are in the top window, CTRL−W w jumps to the window below it. If you are in the bottom window it will jump to the first window. (CTRL−W CTRL−W does the same thing, in case you let go of the CTRL key a bit later.) CLOSE THE WINDOW To close a window, use the command: :close Actually, any command that quits editing a file works, like ":quit" and "ZZ". But ":close" prevents you from accidentally exiting Vim when you close the last window. .\usr_doc.txt Page 56 CLOSING ALL OTHER WINDOWS If you have opened a whole bunch of windows, but now want to concentrate on one of them, this command will be useful: :only This closes all windows, except for the current one. If any of the other windows has changes, you will get an error message and that window won't be closed. ============================================================================== *08.2* Split a window on another file The following command opens a second window and starts editing the given file: :split two.c If you were editing one.c, then the result looks like this: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* file two.c */ | |~ | |~ | |two.c=============================| |/* file one.c */ | |~ | |one.c=============================| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ To open a window on a new, empty file, use this: :new You can repeat the ":split" and ":new" commands to create as many windows as you like. ============================================================================== *08.3* Window size The ":split" command can take a number argument. If specified, this will be the height of the new window. For example, the following opens a new window three lines high and starts editing the file alpha.c: :3split alpha.c For existing windows you can change the size in several ways. When you have a working mouse, it is easy: Move the mouse pointer to the status line that separates two windows, and drag it up or down. To increase the size of a window: CTRL−W + To decrease it: CTRL−W − Both of these commands take a count and increase or decrease the window size by that many lines. Thus "4 CTRL−W +" make the window four lines higher. To set the window height to a specified number of lines: {height}CTRL−W _ That's: a number {height}, CTRL−W and then an underscore (the − key with Shift on English−US keyboards). To make a window as high as it can be, use the CTRL−W _ command without a count. .\usr_doc.txt Page 57 USING THE MOUSE In Vim you can do many things very quickly from the keyboard. Unfortunately, the window resizing commands require quite a bit of typing. In this case, using the mouse is faster. Position the mouse pointer on a status line. Now press the left mouse button and drag. The status line will move, thus making the window on one side higher and the other smaller. OPTIONS The 'winheight' option can be set to a minimal desired height of a window and 'winminheight' to a hard minimum height. Likewise, there is 'winwidth' for the minimal desired width and 'winminwidth' for the hard minimum width. The 'equalalways' option, when set, makes Vim equalize the windows sizes when a window is closed or opened. ============================================================================== *08.4* Vertical splits The ":split" command creates the new window above the current one. the window appear at the left side, use: To make :vsplit or: :vsplit two.c The result looks something like this: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* file two.c */ |/* file one.c */ | |~ |~ | |~ |~ | |~ |~ | |two.c===============one.c=============| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Actually, the | lines in the middle will be in reverse video. This is called the vertical separator. It separates the two windows left and right of it. There is also the ":vnew" command, to open a vertically split window on a new, empty file. Another way to do this: :vertical new The ":vertical" command can be inserted before another command that splits a window. This will cause that command to split the window vertically instead of horizontally. (If the command doesn't split a window, it works unmodified.) MOVING BETWEEN WINDOWS Since you can split windows horizontally and vertically as much as you like, you can create almost any layout of windows. Then you can use these commands to move between them: CTRL−W CTRL−W CTRL−W CTRL−W h j k l CTRL−W t CTRL−W b move move move move to to to to the the the the window window window window on the left below above on the right move to the TOP window move to the BOTTOM window You will notice the same letters as used for moving the cursor. cursor keys can also be used, if you like. And the .\usr_doc.txt Page 58 More commands to move to other windows: |Q_wi|. ============================================================================== *08.5* Moving windows You have split a few windows, but now they are in the wrong place. Then you need a command to move the window somewhere else. For example, you have three windows like this: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* file two.c */ | |~ | |~ | |two.c=============================| |/* file three.c */ | |~ | |~ | |three.c===========================| |/* file one.c */ | |~ | |one.c=============================| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Clearly the last one should be at the top. and the type this command: Go to that window (using CTRL−W w) CTRL−W K This uses the uppercase letter K. What happens is that the window is moved to the very top. You will notice that K is again used for moving upwards. When you have vertical splits, CTRL−W K will move the current window to the top and make it occupy the full width of the Vim window. If this is your layout: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* two.c */ |/* three.c */ |/* one.c */ | |~ |~ |~ | |~ |~ |~ | |~ |~ |~ | |~ |~ |~ | |~ |~ |~ | |two.c=========three.c=========one.c========| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Then using CTRL−W K in the middle window (three.c) will result in: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |/* three.c */ | |~ | |~ | |three.c====================================| |/* two.c */ |/* one.c */ | |~ |~ | |two.c==================one.c===============| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ The other three similar commands (you can probably guess these now): CTRL−W H CTRL−W J CTRL−W L move window to the far left move window to the bottom move window to the far right ============================================================================== *08.6* Commands for all windows When you have several windows open and you want to quit Vim, you can close each window separately. A quicker way is using this command: .\usr_doc.txt Page 59 :qall This stands for "quit all". If any of the windows contain changes, Vim will not exit. The cursor will automatically be positioned in a window with changes. You can then either use ":write" to save the changes, or ":quit!" to throw them away. If you know there are windows with changes, and you want to save all these changes, use this command: :wall This stands for "write all". But actually, it only writes files with changes. Vim knows it doesn't make sense to write files that were not changed. And then there is the combination of ":qall" and ":wall": the "write and quit all" command: :wqall This writes all modified files and quits Vim. Finally, there is a command that quits Vim and throws away all changes: :qall! Be careful, there is no way to undo this command! OPENING A WINDOW FOR ALL ARGUMENTS To make Vim open a window for each file, start it with the "−o" argument: vim −o one.txt two.txt three.txt This results in: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |file one.txt | |~ | |one.txt========================| |file two.txt | |~ | |two.txt========================| |file three.txt | |~ | |three.txt======================| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ The "−O" argument is used to get vertically split windows. When Vim is already running, the ":all" command opens a window for each file in the argument list. ":vertical all" does it with vertical splits. ============================================================================== *08.7* Viewing differences with vimdiff There is a special way to start Vim, which shows the differences between two files. Let's take a file "main.c" and insert a few characters in one line. Write this file with the 'backup' option set, so that the backup file "main.c~" will contain the previous version of the file. Type this command in a shell (not in Vim): vimdiff main.c~ main.c Vim will start, with two windows side by side. You will only see the line in which you added characters, and a few lines above and below it. VV VV +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |+ +−−123 lines: /* a|+ +−−123 lines: /* a| | text | text | <− fold .\usr_doc.txt | text | text | | text | text | | text | changed text | | text | text | | text | −−−−−−−−−−−−−−−−−−| | text | text | | text | text | | text | text | |+ +−−432 lines: text|+ +−−432 lines: text| | ~ | ~ | | ~ | ~ | |main.c~==============main.c==============| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ Page 60 <− changed line <− deleted line <− fold (This picture doesn't show the highlighting, use the vimdiff command for a better look.) The lines that were not modified have been collapsed into one line. This is called a closed fold. They are indicated in the picture with "<− fold". Thus the single fold line at the top stands for 123 text lines. These lines are equal in both files. The line marked with "<− changed line" is highlighted, and the inserted text is displayed with another color. This clearly shows what the difference is between the two files. The line that was deleted is displayed with "−−−" in the main.c window. See the "<− deleted line" marker in the picture. These characters are not really there. They just fill up main.c, so that it displays the same number of lines as the other window. THE FOLD COLUMN Each window has a column on the left with a slightly different background. In the picture above these are indicated with "VV". You notice there is a plus character there, in front of each closed fold. Move the mouse pointer to that plus and click the left button. The fold will open, and you can see the text that it contains. The fold column contains a minus sign for an open fold. If you click on this −, the fold will close. Obviously, this only works when you have a working mouse. You can also use "zo" to open a fold and "zc" to close it. DIFFING IN VIM Another way to start in diff mode can be done from inside Vim. "main.c" file, then make a split and show the differences: Edit the :edit main.c :vertical diffsplit main.c~ The ":vertical" command is used to make the window split vertically. omit this, you will get a horizontal split. If you If you have a patch or diff file, you can use the third way to start diff mode. First edit the file to which the patch applies. Then tell Vim the name of the patch file: :edit main.c :vertical diffpatch main.c.diff WARNING: The patch file must contain only one patch, for the file you are editing. Otherwise you will get a lot of error messages, and some files might be patched unexpectedly. The patching will only be done to the copy of the file in Vim. The file on your harddisk will remain unmodified (until you decide to write the file). SCROLL BINDING .\usr_doc.txt Page 61 When the files have more changes, you can scroll in the usual way. Vim will try to keep both the windows start at the same position, so you can easily see the differences side by side. When you don't want this for a moment, use this command: :set noscrollbind JUMPING TO CHANGES When you have disabled folding in some way, it may be difficult to find the changes. Use this command to jump forward to the next change: ]c To go the other way use: [c Prepended a count to jump further away. REMOVING CHANGES You can move text from one window to the other. This either removes differences or adds new ones. Vim doesn't keep the highlighting updated in all situations. To update it use this command: :diffupdate To remove a difference, you can move the text in a highlighted block from one window to another. Take the "main.c" and "main.c~" example above. Move the cursor to the left window, on the line that was deleted in the other window. Now type this command: dp The change will be removed by putting the text of the current window in the other window. "dp" stands for "diff put". You can also do it the other way around. Move the cursor to the right window, to the line where "changed" was inserted. Now type this command: do The change will Since there are "do" stands for has a different now be removed by getting the text from the other window. no changes left now, Vim puts all text in a closed fold. "diff obtain". "dg" would have been better, but that already meaning ("dgg" deletes from the cursor until the first line). For details about diff mode, see |vimdiff|. ============================================================================== *08.8* Various The 'laststatus' option can be used to specify when the last window has a statusline: 0 1 2 never only when there are split windows (the default) always Many commands that edit another file have a variant that splits the window. For Command−line commands this is done by prepending an "s". For example: ":tag" jumps to a tag, ":stag" splits the window and jumps to a tag. For Normal mode commands a CTRL−W is prepended. CTRL−^ jumps to the alternate file, CTRL−W CTRL−^ splits the window and edits the alternate file. The 'splitbelow' option can be set to make a new window appear below the current window. The 'splitright' option can be set to make a vertically split window appear right of the current window. .\usr_doc.txt Page 62 When splitting a window you can prepend a modifier command to tell where the window is to appear: :leftabove {cmd} :aboveleft {cmd} :rightbelow {cmd} :belowright {cmd} :topleft {cmd} :botright {cmd} left or above the current window idem right or below the current window idem at the top or left of the Vim window at the bottom or right of the Vim window ============================================================================== *08.9* Tab pages You will have noticed that windows never overlap. That means you quickly run out of screen space. The solution for this is called Tab pages. Assume you are editing "thisfile". To create a new tab page use this command: :tabedit thatfile This will edit the file "thatfile" in a window that occupies the whole Vim window. And you will notice a bar at the top with the two file names: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | thisfile | /thatfile/ __________X| |/* thatfile */ | |that | |that | |~ | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ (thatfile is bold) You now have two tab pages. The first one has a window for "thisfile" and the second one a window for "thatfile". It's like two pages that are on top of each other, with a tab sticking out of each page showing the file name. Now use the mouse to click on "thisfile" in the top line. +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | /thisfile/ | thatfile __________X| |/* thisfile */ | |this | |this | |~ | |~ | |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ The result is (thisfile is bold) Thus you can switch between tab pages by clicking on the label in the top line. If you don't have a mouse or don't want to use it, you can use the "gt" command. Mnemonic: Goto Tab. Now let's create another tab page with the command: :tab split This makes a new tab page with one window that is editing the same buffer as the window we were in: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | thisfile | /thisfile/ | thatfile __X| |/* thisfile */ | |this | |this | |~ | |~ | (thisfile is bold) .\usr_doc.txt Page 63 |~ | | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ You can put ":tab" before any Ex command that opens a window. be opened in a new tab page. Another example: The window will :tab help gt Will show the help text for "gt" in a new tab page. A few more things you can do with tab pages: − click with the mouse in the space after the last label The next tab page will be selected, like with "gt". − click with the mouse on the "X" in the top right corner The current tab page will be closed. Unless there are unsaved changes in the current tab page. − double click with the mouse in the top line A new tab page will be created. − the "tabonly" command Closes all tab pages except the current one. changes in other tab pages. Unless there are unsaved For more information about tab pages see |tab−page|. ============================================================================== Next chapter: |usr_09.txt| Using the GUI Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_09.txt* Page 64 For Vim version 7.4. Last change: 2006 Apr 24 VIM USER MANUAL − by Bram Moolenaar Using the GUI Vim works in an ordinary terminal. GVim can do the same things and a few more. The GUI offers menus, a toolbar, scrollbars and other items. This chapter is about these extra things that the GUI offers. |09.1| |09.2| |09.3| |09.4| Parts of the GUI Using the mouse The clipboard Select mode Next chapter: |usr_10.txt| Making big changes Previous chapter: |usr_08.txt| Splitting windows Table of contents: |usr_toc.txt| ============================================================================== *09.1* Parts of the GUI You might have an icon on your desktop that starts gVim. these commands should do it: Otherwise, one of gvim file.txt vim −g file.txt If this doesn't work you don't have a version of Vim with GUI support. You will have to install one first. Vim will open a window and display "file.txt" in it. What the window looks like depends on the version of Vim. It should resemble the following picture (for as far as this can be shown in ASCII!). +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | file.txt + (~/dir) − VIM X | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | File Edit Tools Syntax Buffers Window Help | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | aaa bbb ccc ddd eee fff ggg hhh iii jjj | | aaa bbb ccc ddd eee fff ggg hhh iii jjj | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | file text | ^ | | ~ | # | | ~ | # | | ~ | # | | ~ | # | | ~ | # | | | V | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ <− window title <− menubar <− toolbar <− scrollbar The largest space is occupied by the file text. This shows the file in the same way as in a terminal. With some different colors and another font perhaps. THE WINDOW TITLE At the very top is the window title. This is drawn by your window system. Vim will set the title to show the name of the current file. First comes the name of the file. Then some special characters and the directory of the file in parens. These special character can be present: − + = =+ The The The The file file file file cannot be modified (e.g., a help file) contains changes is read−only is read−only, contains changes anyway If nothing is shown you have an ordinary, unchanged file. .\usr_doc.txt Page 65 THE MENUBAR You know how menus work, right? Vim has the usual items, plus a few more. Browse them to get an idea of what you can use them for. A relevant submenu is Edit/Global Settings. You will find these entries: Toggle Toggle Toggle Toggle Toolbar Bottom Scrollbar Left Scrollbar Right Scrollbar make make make make the toolbar a scrollbar a scrollbar a scrollbar appear/disappear appear/disappear at the bottom appear/disappear at the left appear/disappear at the right On most systems you can tear−off the menus. Select the top item of the menu, the one that looks like a dashed line. You will get a separate window with the items of the menu. It will hang around until you close the window. THE TOOLBAR This contains icons for the most often used actions. Hopefully the icons are self−explanatory. There are tooltips to get an extra hint (move the mouse pointer to the icon without clicking and don't move it for a second). The "Edit/Global Settings/Toggle Toolbar" menu item can be used to make the toolbar disappear. If you never want a toolbar, use this command in your vimrc file: :set guioptions−=T This removes the 'T' flag from the 'guioptions' option. Other parts of the GUI can also be enabled or disabled with this option. See the help for it. THE SCROLLBARS By default there is one scrollbar on the right. It does the obvious thing. When you split the window, each window will get its own scrollbar. You can make a horizontal scrollbar appear with the menu item Edit/Global Settings/Toggle Bottom Scrollbar. This is useful in diff mode, or when the 'wrap' option has been reset (more about that later). When there are vertically split windows, only the windows on the right side will have a scrollbar. However, when you move the cursor to a window on the left, it will be this one the that scrollbar controls. This takes a bit of time to get used to. When you work with vertically split windows, consider adding a scrollbar on the left. This can be done with a menu item, or with the 'guioptions' option: :set guioptions+=l This adds the 'l' flag to 'guioptions'. ============================================================================== *09.2* Using the mouse Standards are wonderful. In Microsoft Windows, you can use the mouse to select text in a standard manner. The X Window system also has a standard system for using the mouse. Unfortunately, these two standards are not the same. Fortunately, you can customize Vim. You can make the behavior of the mouse work like an X Window system mouse or a Microsoft Windows mouse. The following command makes the mouse behave like an X Window mouse: :behave xterm The following command makes the mouse work like a Microsoft Windows mouse: :behave mswin The default behavior of the mouse on UNIX systems is xterm. The default .\usr_doc.txt Page 66 behavior on a Microsoft Windows system is selected during the installation process. For details about what the two behaviors are, see |:behave|. Here follows a summary. XTERM MOUSE BEHAVIOR Left mouse click Left mouse drag Middle mouse click Right mouse click position the cursor select text in Visual mode paste text from the clipboard extend the selected text until the mouse pointer MSWIN MOUSE BEHAVIOR Left mouse click Left mouse drag Left mouse click, with Shift Middle mouse click Right mouse click The mouse can be further tuned. the way how the mouse works: 'mouse' 'mousemodel' 'mousetime' 'mousehide' 'selectmode' position the cursor select text in Select mode (see |09.4|) extend the selected text until the mouse pointer paste text from the clipboard display a pop−up menu Check out these options if you want to change in which mode the mouse is used by Vim what effect a mouse click has time between clicks for a double−click hide the mouse while typing whether the mouse starts Visual or Select mode ============================================================================== *09.3* The clipboard In section |04.7| the basic use of the clipboard was explained. There is one essential thing to explain about X−windows: There are actually two places to exchange text between programs. MS−Windows doesn't have this. In X−Windows there is the "current selection". This is the text that is currently highlighted. In Vim this is the Visual area (this assumes you are using the default option settings). You can paste this selection in another application without any further action. For example, in this text select a few words with the mouse. Vim will switch to Visual mode and highlight the text. Now start another gVim, without a file name argument, so that it displays an empty window. Click the middle mouse button. The selected text will be inserted. The "current selection" will only remain valid until some other text is selected. After doing the paste in the other gVim, now select some characters in that window. You will notice that the words that were previously selected in the other gVim window are displayed differently. This means that it no longer is the current selection. You don't need to select text with the mouse, using the keyboard commands for Visual mode works just as well. THE REAL CLIPBOARD Now for the other place with which text can be exchanged. We call this the "real clipboard", to avoid confusion. Often both the "current selection" and the "real clipboard" are called clipboard, you'll have to get used to that. To put text on the real clipboard, select a few different words in one of the gVims you have running. Then use the Edit/Copy menu entry. Now the text has been copied to the real clipboard. You can't see this, unless you have some application that shows the clipboard contents (e.g., KDE's klipper). Now select the other gVim, position the cursor somewhere and use the Edit/Paste menu. You will see the text from the real clipboard is inserted. .\usr_doc.txt Page 67 USING BOTH This use of both the "current selection" and the "real clipboard" might sound a bit confusing. But it is very useful. Let's show this with an example. Use one gVim with a text file and perform these actions: − − − − − Select two words in Visual mode. Use the Edit/Copy menu to get these words onto the clipboard. Select one other word in Visual mode. Use the Edit/Paste menu item. What will happen is that the single selected word is replaced with the two words from the clipboard. Move the mouse pointer somewhere else and click the middle button. You will see that the word you just overwrote with the clipboard is inserted here. If you use the "current selection" and the "real clipboard" with care, you can do a lot of useful editing with them. USING THE KEYBOARD If you don't like using the mouse, you can access the current selection and the real clipboard with two registers. The "* register is for the current selection. To make text become the current selection, use Visual mode. For example, to select a whole line just press "V". To insert the current selection before the cursor: "*P Notice the uppercase "P". The lowercase "p" puts the text after the cursor. The "+ register is used for the real clipboard. For example, to copy the text from the cursor position until the end of the line to the clipboard: "+y$ Remember, "y" is yank, which is Vim's copy command. To insert the contents of the real clipboard before the cursor: "+P It's the same as for the current selection, but uses the plus (+) register instead of the star (*) register. ============================================================================== *09.4* Select mode And now something that is used more often on MS−Windows than on X−Windows. But both can do it. You already know about Visual mode. Select mode is like Visual mode, because it is also used to select text. But there is an obvious difference: When typing text, the selected text is deleted and the typed text replaces it. To start working with Select mode, you must first enable it (for MS−Windows it is probably already enabled, but you can do this anyway): :set selectmode+=mouse Now use the mouse to select some text. It is highlighted like in Visual mode. Now press a letter. The selected text is deleted, and the single letter replaces it. You are in Insert mode now, thus you can continue typing. Since typing normal text causes the selected text to be deleted, you can not use the normal movement commands "hjkl", "w", etc. Instead, use the shifted function keys. (shifted cursor left key) moves the cursor left. The selected text is changed like in Visual mode. The other shifted cursor keys do what you expect.andalso work. You can tune the way Select mode works with the 'selectmode' option. .\usr_doc.txt Page 68 ============================================================================== Next chapter: |usr_10.txt| Making big changes Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_10.txt* Page 69 For Vim version 7.4. Last change: 2006 Nov 05 VIM USER MANUAL − by Bram Moolenaar Making big changes In chapter 4 several ways to make small changes were explained. This chapter goes into making changes that are repeated or can affect a large amount of text. The Visual mode allows doing various things with blocks of text. Use an external program to do really complicated things. |10.1| |10.2| |10.3| |10.4| |10.5| |10.6| |10.7| |10.8| |10.9| Record and playback commands Substitution Command ranges The global command Visual block mode Reading and writing part of a file Formatting text Changing case Using an external program Next chapter: |usr_11.txt| Recovering from a crash Previous chapter: |usr_09.txt| Using the GUI Table of contents: |usr_toc.txt| ============================================================================== *10.1* Record and playback commands The "." command repeats the preceding change. But what if you want to do something more complex than a single change? That's where command recording comes in. There are three steps: 1. The "q{register}" command starts recording keystrokes into the register named {register}. The register name must be between a and z. 2. Type your commands. 3. To finish recording, press q (without any extra character). You can now execute the macro by typing the command "@{register}". Take a look at how to use these commands in practice. filenames that look like this: You have a list of stdio.h fcntl.h unistd.h stdlib.h And what you want is the following: #include #include #include #include "stdio.h" "fcntl.h" "unistd.h" "stdlib.h" You start by moving to the first character of the first line. execute the following commands: qa ^ i#include "$ a" j q Next you Start recording a macro in register a. Move to the beginning of the line. Insert the string #include " at the beginning of the line. Move to the end of the line. Append the character double quotation mark (") to the end of the line. Go to the next line. Stop recording the macro. Now that you have done the work once, you can repeat the change by typing the command "@a" three times. .\usr_doc.txt Page 70 The "@a" command can be preceded by a count, which will cause the macro to be executed that number of times. In this case you would type: 3@a MOVE AND EXECUTE You might have the lines you want to change in various places. Just move the cursor to each location and use the "@a" command. If you have done that once, you can do it again with "@@". That's a bit easier to type. If you now execute register b with "@b", the next "@@" will use register b. If you compare the playback method with using ".", there are several differences. First of all, "." can only repeat one change. As seen in the example above, "@a" can do several changes, and move around as well. Secondly, "." can only remember the last change. Executing a register allows you to make any changes and then still use "@a" to replay the recorded commands. Finally, you can use 26 different registers. Thus you can remember 26 different command sequences to execute. USING REGISTERS The registers used for recording are the same ones you used for yank and delete commands. This allows you to mix recording with other commands to manipulate the registers. Suppose you have recorded a few commands in register n. When you execute this with "@n" you notice you did something wrong. You could try recording again, but perhaps you will make another mistake. Instead, use this trick: G o "np {edits} 0 "ny$ dd Go to the end of the file. Create an empty line. Put the text from the n register. You now see the commands you typed as text in the file. Change the commands that were wrong. This is just like editing text. Go to the start of the line. Yank the corrected commands into the n register. Delete the scratch line. Now you can execute the corrected commands with "@n". (If your recorded commands include line breaks, adjust the last two items in the example to include all the lines.) APPENDING TO A REGISTER So far we have used a lowercase letter for the register name. To append to a register, use an uppercase letter. Suppose you have recorded a command to change a word to register c. It works properly, but you would like to add a search for the next word to change. This can be done with: qC/word q You start with "qC", which records to the c register and appends. Thus writing to an uppercase register name means to append to the register with the same letter, but lowercase. This works both with recording and with yank and delete commands. For example, you want to collect a sequence of lines into the a register. Yank the first line with: "aY Now move to the second line, and type: "AY Repeat this command for all lines. The a register now contains all those .\usr_doc.txt Page 71 lines, in the order you yanked them. ============================================================================== *10.2* Substitution *find−replace* The ":substitute" command enables you to perform string replacements on a whole range of lines. The general form of this command is as follows: :[range]substitute/from/to/[flags] This command changes the "from" string to the "to" string in the lines specified with [range]. For example, you can change "Professor" to "Teacher" in all lines with the following command: :%substitute/Professor/Teacher/ Note: The ":substitute" command is almost never spelled out completely. Most of the time, people use the abbreviated version ":s". From here on the abbreviation will be used. The "%" before the command specifies the command works on all lines. Without a range, ":s" only works on the current line. More about ranges in the next section |10.3|. By default, the ":substitute" command changes only the first occurrence on each line. For example, the preceding command changes the line: Professor Smith criticized Professor Johnson today. to: Teacher Smith criticized Professor Johnson today. To change every occurrence on the line, you need to add the g (global) flag. The command: :%s/Professor/Teacher/g results in (starting with the original line): Teacher Smith criticized Teacher Johnson today. Other flags include p (print), which causes the ":substitute" command to print out the last line it changes. The c (confirm) flag tells ":substitute" to ask you for confirmation before it performs each substitution. Enter the following: :%s/Professor/Teacher/c Vim finds the first occurrence of "Professor" and displays the text it is about to change. You get the following prompt: replace with Teacher (y/n/a/q/l/^E/^Y)? At this point, you must enter one of the following answers: y n a q l CTRL−E CTRL−Y Yes; make this change. No; skip this match. All; make this change and all remaining ones without further confirmation. Quit; don't make any more changes. Last; make this change and then quit. Scroll the text one line up. Scroll the text one line down. The "from" part of the substitute command is actually a pattern. The same kind as used for the search command. For example, this command only substitutes "the" when it appears at the start of a line: .\usr_doc.txt Page 72 :s/^the/these/ If you are substituting with a "from" or "to" part that includes a slash, you need to put a backslash before it. A simpler way is to use another character instead of the slash. A plus, for example: :s+one/two+one or two+ ============================================================================== *10.3* Command ranges The ":substitute" command, and many other : commands, can be applied to a selection of lines. This is called a range. The simple form of a range is {number},{number}. For example: :1,5s/this/that/g Executes the substitute command on the lines 1 to 5. The range is always placed before the command. Line 5 is included. A single number can be used to address one specific line: :54s/President/Fool/ Some commands work on the whole file when you do not specify a range. To make them work on the current line the "." address is used. The ":write" command works like that. Without a range, it writes the whole file. To make it write only the current line into a file: :.write otherfile The first line always has number one. How about the last line? The "$" character is used for this. For example, to substitute in the lines from the cursor to the end: :.,$s/yes/no/ The "%" range that we used before, is actually a short way to say "1,$", from the first to the last line. USING A PATTERN IN A RANGE Suppose you are editing a chapter in a book, and want to replace all occurrences of "grey" with "gray". But only in this chapter, not in the next one. You know that only chapter boundaries have the word "Chapter" in the first column. This command will work then: :?^Chapter?,/^Chapter/s=grey=gray=g You can see a search pattern is used twice. The first "?^Chapter?" finds the line above the current position that matches this pattern. Thus the ?pattern? range is used to search backwards. Similarly, "/^Chapter/" is used to search forward for the start of the next chapter. To avoid confusion with the slashes, the "=" character was used in the substitute command here. A slash or another character would have worked as well. ADD AND SUBTRACT There is a slight error in the above command: If the title of the next chapter had included "grey" it would be replaced as well. Maybe that's what you wanted, but what if you didn't? Then you can specify an offset. To search for a pattern and then use the line above it: /Chapter/−1 You can use any number instead of the 1. match: To address the second line below the .\usr_doc.txt Page 73 /Chapter/+2 The offsets can also be used with the other items in a range. one: Look at this :.+3,$−5 This specifies the range that starts three lines below the cursor and ends five lines before the last line in the file. USING MARKS Instead of figuring out the line numbers of certain positions, remembering them and typing them in a range, you can use marks. Place the marks as mentioned in chapter 3. For example, use "mt" to mark the top of an area and "mb" to mark the bottom. Then you can use this range to specify the lines between the marks (including the lines with the marks): :'t,'b VISUAL MODE AND RANGES You can select text with Visual mode. command, you will see this: If you then press ":" to start a colon :'<,'> Now you can type the command and it will be applied to the range of lines that was visually selected. Note: When using Visual mode to select part of a line, or using CTRL−V to select a block of text, the colon commands will still apply to whole lines. This might change in a future version of Vim. The '< and '> are actually marks, placed at the start and end of the Visual selection. The marks remain at their position until another Visual selection is made. Thus you can use the "'<" command to jump to position where the Visual area started. And you can mix the marks with other items: :'>,$ This addresses the lines from the end of the Visual area to the end of the file. A NUMBER OF LINES When you know how many lines you want to change, you can type the number and then ":". For example, when you type "5:", you will get: :.,.+4 Now you can type the command you want to use. (current line) until ".+4" (four lines down). It will use the range "." Thus it spans five lines. ============================================================================== *10.4* The global command The ":global" command is one of the more powerful features of Vim. It allows you to find a match for a pattern and execute a command there. The general form is: :[range]global/{pattern}/{command} This is similar to the ":substitute" command. But, instead of replacing the matched text with other text, the command {command} is executed. Note: .\usr_doc.txt Page 74 The command executed for ":global" must be one that starts with a colon. Normal mode commands can not be used directly. The |:normal| command can do this for you. Suppose you want to change "foobar" to "barfoo", but only in C++ style comments. These comments start with "//". Use this command: :g+//+s/foobar/barfoo/g This starts with ":g". That is short for ":global", just like ":s" is short for ":substitute". Then the pattern, enclosed in plus characters. Since the pattern we are looking for contains a slash, this uses the plus character to separate the pattern. Next comes the substitute command that changes "foobar" into "barfoo". The default range for the global command is the whole file. Thus no range was specified in this example. This is different from ":substitute", which works on one line without a range. The command isn't perfect, since it also matches lines where "//" appears halfway a line, and the substitution will also take place before the "//". Just like with ":substitute", any pattern can be used. complicated patterns later, you can use them here. When you learn more ============================================================================== *10.5* Visual block mode With CTRL−V you can start selection of a rectangular area of text. a few commands that do something special with the text block. There are There is something special about using the "$" command in Visual block mode. When the last motion command used was "$", all lines in the Visual selection will extend until the end of the line, also when the line with the cursor is shorter. This remains effective until you use a motion command that moves the cursor horizontally. Thus using "j" keeps it, "h" stops it. INSERTING TEXT The command "I{string} " inserts the text {string} in each line, just left of the visual block. You start by pressing CTRL−V to enter visual block mode. Now you move the cursor to define your block. Next you type I to enter Insert mode, followed by the text to insert. As you type, the text appears on the first line only. After you press to end the insert, the text will magically be inserted in the rest of the lines contained in the visual selection. Example: include include include include one two three four Move the cursor to the "o" of "one" and press CTRL−V. Move it down with "3j" to "four". You now have a block selection that spans four lines. Now type: Imain. The result: include include include include main.one main.two main.three main.four If the block spans short lines that do not extend into the block, the text is not inserted in that line. For example, make a Visual block selection that includes the word "long" in the first and last line of this text, and thus has no text selected in the second line: This is a long line short Any other long line .\usr_doc.txt Page 75 ^^^^ selected block Now use the command "Ivery ". The result is: This is a very long line short Any other very long line In the short line no text was inserted. If the string you insert contains a newline, the "I" acts just like a Normal insert command and affects only the first line of the block. The "A" command works the same way, except that it appends after the right side of the block. And it does insert text in a short line. Thus you can make a choice whether you do or don't want to append text to a short line. There is one special case for "A": Select a Visual block and then use "$" to make the block extend to the end of each line. Using "A" now will append the text to the end of each line. Using the same example from above, and then typing "$A XXX , you get this result: This is a long line XXX short XXX Any other long line XXX This really requires using the "$" command. Vim remembers that it was used. Making the same selection by moving the cursor to the end of the longest line with other movement commands will not have the same result. CHANGING TEXT The Visual block "c" command deletes the block and then throws you into Insert mode to enable you to type in a string. The string will be inserted in each line in the block. Starting with the same selection of the "long" words as above, then typing "c_LONG_ ", you get this: This is a _LONG_ line short Any other _LONG_ line Just like with "I" the short line is not changed. newline in the new text. Also, you can't enter a The "C" command deletes text from the left edge of the block to the end of line. It then puts you in Insert mode so that you can type in a string, which is added to the end of each line. Starting with the same text again, and typing "Cnew text " you get: This is a new text short Any other new text Notice that, even though only the "long" word was selected, the text after it is deleted as well. Thus only the location of the left edge of the visual block really matters. Again, short lines that do not reach into the block are excluded. Other commands that change the characters in the block: ~ U u swap case make uppercase make lowercase (a −> A and A −> a) (a −> A and A −> A) (a −> a and A −> a) FILLING WITH A CHARACTER To fill the whole block with one character, use the "r" command. Again, .\usr_doc.txt Page 76 starting with the same example text from above, and then typing "rx": This is a xxxx line short Any other xxxx line Note: If you want to include characters beyond the end of the line in the block, check out the 'virtualedit' feature in chapter 25. SHIFTING The command ">" shifts the selected text to the right one shift amount, inserting whitespace. The starting point for this shift is the left edge of the visual block. With the same example again, ">" gives this result: This is a short Any other long line long line The shift amount is specified with the 'shiftwidth' option. use 4 spaces: To change it to :set shiftwidth=4 The "<" command removes one shift amount of whitespace at the left edge of the block. This command is limited by the amount of text that is there; so if there is less than a shift amount of whitespace available, it removes what it can. JOINING LINES The "J" command joins all selected lines together into one line. Thus it removes the line breaks. Actually, the line break, leading white space and trailing white space is replaced by one space. Two spaces are used after a line ending (that can be changed with the 'joinspaces' option). Let's use the example that we got so familiar with now. The result of using the "J" command: This is a long line short Any other long line The "J" command doesn't require a blockwise selection. "V" selection in exactly the same way. It works with "v" and If you don't want the white space to be changed, use the "gJ" command. ============================================================================== *10.6* Reading and writing part of a file When you are writing an e−mail message, you may want to include another file. This can be done with the ":read {filename}" command. The text of the file is put below the cursor line. Starting with this text: Hi John, Here is the diff that fixes the bug: Bye, Pierre. Move the cursor to the second line and type: :read patch The file named "patch" will be inserted, with this result: Hi John, Here is the diff that fixes the bug: 2c2 .\usr_doc.txt Page 77 for (i = 0; i <= length; ++i) −−− for (i = 0; i < length; ++i) Bye, Pierre. The ":read" command accepts number of this range. Thus the file. What if you want to read with the line number zero. error message when using it a range. The file will be put below the last line ":$r patch" appends the file "patch" at the end of the file above the first line? This can be done This line doesn't really exist, you will get an with most commands. But this command is allowed: :0read patch The file "patch" will be put above the first line of the file. WRITING A RANGE OF LINES To write a range of lines to a file, the ":write" command can be used. Without a range it writes the whole file. With a range only the specified lines are written: :.,$write tempo This writes the lines from the cursor until the end of the file into the file "tempo". If this file already exists you will get an error message. Vim protects you from accidentally overwriting an existing file. If you know what you are doing and want to overwrite the file, append !: :.,$write! tempo CAREFUL: The ! must follow the ":write" command immediately, without white space. Otherwise it becomes a filter command, which is explained later in this chapter. APPENDING TO A FILE In the first section of this chapter was explained how to collect a number of lines into a register. The same can be done to collect lines in a file. Write the first line with this command: :.write collection Now move the cursor to the second line you want to collect, and type this: :.write >>collection The ">>" tells Vim the "collection" file is not to be written as a new file, but the line must be appended at the end. You can repeat this as many times as you like. ============================================================================== *10.7* Formatting text When you are typing plain text, it's nice if the length of each line is automatically trimmed to fit in the window. To make this happen while inserting text, set the 'textwidth' option: :set textwidth=72 You might remember that in the example vimrc file this command was used for every text file. Thus if you are using that vimrc file, you were already using it. To check the current value of 'textwidth': :set textwidth Now lines will be broken to take only up to 72 characters. But when you insert text halfway a line, or when you delete a few words, the lines will get too long or too short. Vim doesn't automatically reformat the text. .\usr_doc.txt Page 78 To tell Vim to format the current paragraph: gqap This starts with the "gq" command, which is an operator. Following is "ap", the text object that stands for "a paragraph". A paragraph is separated from the next paragraph by an empty line. Note: A blank line, which contains white space, does NOT separate paragraphs. This is hard to notice! Instead of "ap" you could use any motion or text object. If your paragraphs are properly separated, you can use this command to format the whole file: gggqG "gg" takes you to the first line, "gq" is the format operator and "G" the motion that jumps to the last line. In case your paragraphs aren't clearly defined, you can format just the lines you manually select. Move the cursor to the first line you want to format. Start with the command "gqj". This formats the current line and the one below it. If the first line was short, words from the next line will be appended. If it was too long, words will be moved to the next line. The cursor moves to the second line. Now you can use "." to repeat the command. Keep doing this until you are at the end of the text you want to format. ============================================================================== *10.8* Changing case You have text with section headers in lowercase. You want to make the word "section" all uppercase. Do this with the "gU" operator. Start with the cursor in the first column: section header gUw −−−−> SECTION header The "gu" operator does exactly the opposite: SECTION header guw −−−−> section header You can also use "g~" to swap case. All these are operators, thus they work with any motion command, with text objects and in Visual mode. To make an operator work on lines you double it. The delete operator is "d", thus to delete a line you use "dd". Similarly, "gugu" makes a whole line lowercase. This can be shortened to "guu". "gUgU" is shortened to "gUU" and "g~g~" to "g~~". Example: Some GIRLS have Fun g~~ −−−−> sOME girls HAVE fUN ============================================================================== *10.9* Using an external program Vim has a very powerful set of commands, it can do anything. But there may still be something that an external command can do better or faster. The command "!{motion}{program}" takes a block of text and filters it through an external program. In other words, it runs the system command represented by {program}, giving it the block of text represented by {motion} as input. The output of this command then replaces the selected block. Because this summarizes badly if you are unfamiliar with UNIX filters, take a look at an example. The sort command sorts a file. If you execute the following command, the unsorted file input.txt will be sorted and written to output.txt. (This works on both UNIX and Microsoft Windows.) sort output.txt Now do the same thing in Vim. You want to sort lines 1 through 5 of a file. You start by putting the cursor on line 1. Next you execute the following .\usr_doc.txt Page 79 command: !5G The "!" tells Vim that you are performing a filter operation. The Vim editor expects a motion command to follow, indicating which part of the file to filter. The "5G" command tells Vim to go to line 5, so it now knows that it is to filter lines 1 (the current line) through 5. In anticipation of the filtering, the cursor drops to the bottom of the screen and a ! prompt displays. You can now type in the name of the filter program, in this case "sort". Therefore, your full command is as follows: !5Gsort The result is that the sort program is run on the first 5 lines. of the program replaces these lines. line line line line line last 55 33 11 22 44 line −−> line line line line line last The output 11 22 33 44 55 line The "!!" command filters the current line through a filter. In Unix the "date" command prints the current time and date. "!!date " replaces the current line with the output of "date". This is useful to add a timestamp to a file. WHEN IT DOESN'T WORK Starting a shell, sending it text and capturing the output requires that Vim knows how the shell works exactly. When you have problems with filtering, check the values of these options: 'shell' 'shellcmdflag' 'shellquote' 'shellxquote' 'shelltype' 'shellslash' 'shellredir' specifies the program that Vim uses to execute external programs. argument to pass a command to the shell quote to be used around the command quote to be used around the command and redirection kind of shell (only for the Amiga) use forward slashes in the command (only for MS−Windows and alikes) string used to write the command output into a file On Unix this is hardly ever a problem, because there are two kinds of shells: "sh" like and "csh" like. Vim checks the 'shell' option and sets related options automatically, depending on whether it sees "csh" somewhere in 'shell'. On MS−Windows, however, there are many different shells and you might have to tune the options to make filtering work. Check the help for the options for more information. READING COMMAND OUTPUT To read the contents of the current directory into the file, use this: on Unix: :read !ls on MS−Windows: :read !dir The output of the "ls" or "dir" command is captured and inserted in the text, below the cursor. This is similar to reading a file, except that the "!" is used to tell Vim that a command follows. The command may have arguments. And a range can be used to tell where Vim should put the lines: :0read !date −u .\usr_doc.txt Page 80 This inserts the current time and date in UTC format at the top of the file. (Well, if you have a date command that accepts the "−u" argument.) Note the difference with using "!!date": that replaced a line, while ":read !date" will insert a line. WRITING TEXT TO A COMMAND The Unix command "wc" counts words. To count the words in the current file: :write !wc This is the same write command as before, but instead of a file name the "!" character is used and the name of an external command. The written text will be passed to the specified command as its standard input. The output could look like this: 4 47 249 The "wc" command isn't verbose. characters. This means you have 4 lines, 47 words and 249 Watch out for this mistake: :write! wc This will write the file "wc" in the current directory, with force. space is important here! White REDRAWING THE SCREEN If the external command produced an error message, the display may have been messed up. Vim is very efficient and only redraws those parts of the screen that it knows need redrawing. But it can't know about what another program has written. To tell Vim to redraw the screen: CTRL−L ============================================================================== Next chapter: |usr_11.txt| Recovering from a crash Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_11.txt* Page 81 For Vim version 7.4. Last change: 2010 Jul 20 VIM USER MANUAL − by Bram Moolenaar Recovering from a crash Did your computer crash? And you just spent hours editing? Don't panic! Vim stores enough information to be able to restore most of your work. This chapter shows you how to get your work back and explains how the swap file is used. |11.1| |11.2| |11.3| |11.4| Basic recovery Where is the swap file? Crashed or not? Further reading Next chapter: |usr_12.txt| Clever tricks Previous chapter: |usr_10.txt| Making big changes Table of contents: |usr_toc.txt| ============================================================================== *11.1* Basic recovery In most cases recovering a file is quite simple, assuming you know which file you were editing (and the harddisk is still working). Start Vim on the file, with the "−r" argument added: vim −r help.txt Vim will read the swap file (used to store text you were editing) and may read bits and pieces of the original file. If Vim recovered your changes you will see these messages (with different file names, of course): Using swap file ".help.txt.swp" Original file "~/vim/runtime/doc/help.txt" Recovery completed. You should check if everything is OK. (You might want to write out this file under another name and run diff with the original file to check for changes) You may want to delete the .swp file now. To be on the safe side, write this file under another name: :write help.txt.recovered Compare the file with the original file to check if you ended up with what you expected. Vimdiff is very useful for this |08.7|. For example: :write help.txt.recovered :edit # :diffsp help.txt Watch out for the original file to contain a more recent version (you saved the file just before the computer crashed). And check that no lines are missing (something went wrong that Vim could not recover). If Vim produces warning messages when recovering, read them carefully. This is rare though. If the recovery resulted in text that is exactly the same as the file contents, you will get this message: Using swap file ".help.txt.swp" Original file "~/vim/runtime/doc/help.txt" Recovery completed. Buffer contents equals file contents. You may want to delete the .swp file now. This usually happens if you already recovered your changes, or you wrote the file after making changes. It is safe to delete the swap file now. It is normal that the last few changes can not be recovered. Vim flushes the .\usr_doc.txt Page 82 changes to disk when you don't type for about four seconds, or after typing about two hundred characters. This is set with the 'updatetime' and 'updatecount' options. Thus when Vim didn't get a chance to save itself when the system went down, the changes after the last flush will be lost. If you were editing without a file name, give an empty string as argument: vim −r "" You must be in the right directory, otherwise Vim can't find the swap file. ============================================================================== *11.2* Where is the swap file? Vim can store the swap file in several places. Normally it is in the same directory as the original file. To find it, change to the directory of the file, and use: vim −r Vim will list the swap files that it can find. It will also look in other directories where the swap file for files in the current directory may be located. It will not find swap files in any other directories though, it doesn't search the directory tree. The output could look like this: Swap files found: In current directory: 1. .main.c.swp owned by: mool dated: Tue May 29 21:00:25 2001 file name: ~mool/vim/vim6/src/main.c modified: YES user name: mool host name: masaka.moolenaar.net process ID: 12525 In directory ~/tmp: −− none −− In directory /var/tmp: −− none −− In directory /tmp: −− none −− If there are several swap files that look like they may be the one you want to use, a list is given of these swap files and you are requested to enter the number of the one you want to use. Carefully look at the dates to decide which one you want to use. In case you don't know which one to use, just try them one by one and check the resulting files if they are what you expected. USING A SPECIFIC SWAP FILE If you know which swap file needs to be used, you can recover by giving the swap file name. Vim will then finds out the name of the original file from the swap file. Example: vim −r .help.txt.swo This is also handy when the swap file is in another directory than expected. Vim recognizes files with the pattern *.s[uvw][a−z] as swap files. If this still does not work, see what file names Vim reports and rename the files accordingly. Check the 'directory' option to see where Vim may have put the swap file. Note: Vim tries to find the swap file by searching the directories in the 'dir' option, looking for files that match "filename.sw?". If wildcard expansion doesn't work (e.g., when the 'shell' option is invalid), Vim does a desperate try to find the file "filename.swp". If that fails too, you will have to give the name of the swapfile .\usr_doc.txt Page 83 itself to be able to recover the file. ============================================================================== *11.3* Crashed or not? *ATTENTION* *E325* Vim tries to protect you from doing stupid things. Suppose you innocently start editing a file, expecting the contents of the file to show up. Instead, Vim produces a very long message: E325: ATTENTION Found a swap file by the name ".main.c.swp" owned by: mool dated: Tue May 29 21:09:28 2001 file name: ~mool/vim/vim6/src/main.c modified: no user name: mool host name: masaka.moolenaar.net process ID: 12559 (still running) While opening file "main.c" dated: Tue May 29 19:46:12 2001 (1) Another program may be editing the same file. If this is the case, be careful not to end up with two different instances of the same file when making changes. Quit, or continue with caution. (2) An If to If to edit session for this file crashed. this is the case, use ":recover" or "vim −r main.c" recover the changes (see ":help recovery"). you did this already, delete the swap file ".main.c.swp" avoid this message. You get this message, because, when starting to edit a file, Vim checks if a swap file already exists for that file. If there is one, there must be something wrong. It may be one of these two situations. 1. Another edit session is active on this file. Look in the message for the line with "process ID". It might look like this: process ID: 12559 (still running) The text "(still running)" indicates that the process editing this file runs on the same computer. When working on a non−Unix system you will not get this extra hint. When editing a file over a network, you may not see the hint, because the process might be running on another computer. In those two cases you must find out what the situation is yourself. If there is another Vim editing the same file, continuing to edit will result in two versions of the same file. The one that is written last will overwrite the other one, resulting in loss of changes. You better quit this Vim. 2. The swap file might be the result from a previous crash of Vim or the computer. Check the dates mentioned in the message. If the date of the swap file is newer than the file you were editing, and this line appears: modified: YES Then you very likely have a crashed edit session that is worth recovering. If the date of the file is newer than the date of the swap file, then either it was changed after the crash (perhaps you recovered it earlier, but didn't delete the swap file?), or else the file was saved before the crash but after the last write of the swap file (then you're lucky: you don't even need that old swap file). Vim will warn you for this with this extra line: NEWER than swap file! UNREADABLE SWAP FILE Sometimes the line [cannot be read] .\usr_doc.txt will appear under the name of the swap file. depending on circumstances. Page 84 This can be good or bad, It is good if a previous editing session crashed without having made any changes to the file. Then a directory listing of the swap file will show that it has zero bytes. You may delete it and proceed. It is slightly bad if you don't have read permission for the swap file. You may want to view the file read−only, or quit. On multi−user systems, if you yourself did the last changes under a different login name, a logout followed by a login under that other name might cure the "read error". Or else you might want to find out who last edited (or is editing) the file and have a talk with them. It is very bad if it means there is a physical read error on the disk containing the swap file. Fortunately, this almost never happens. You may want to view the file read−only at first (if you can), to see the extent of the changes that were "forgotten". If you are the one in charge of that file, be prepared to redo your last changes. WHAT TO DO? *swap−exists−choices* If dialogs are supported you will be asked to select one of five choices: Swap file ".main.c.swp" already exists! [O]pen Read−Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort, (D)elete it: O Open the file readonly. Use this when you just want to view the file and don't need to recover it. You might want to use this when you know someone else is editing the file, but you just want to look in it and not make changes. E Edit the file anyway. Use this with caution! If the file is being edited in another Vim, you might end up with two versions of the file. Vim will try to warn you when this happens, but better be safe then sorry. R Recover the file from the swap file. Use this if you know that the swap file contains changes that you want to recover. Q Quit. This avoids starting to edit the file. Use this if there is another Vim editing the same file. When you just started Vim, this will exit Vim. When starting Vim with files in several windows, Vim quits only if there is a swap file for the first one. When using an edit command, the file will not be loaded and you are taken back to the previously edited file. A Abort. Like Quit, but also abort further commands. This is useful when loading a script that edits several files, such as a session with multiple windows. D Delete the swap file. Use this when you are sure you no longer need it. For example, when it doesn't contain changes, or when the file itself is newer than the swap file. On Unix this choice is only offered when the process that created the swap file does not appear to be running. If you do not get the dialog (you are running a version of Vim that does not support it), you will have to do it manually. To recover the file, use this command: :recover Vim cannot always detect that a swap file already exists for a file. This is the case when the other edit session puts the swap files in another directory or when the path name for the file is different when editing it on different machines. Therefore, don't rely on Vim always warning you. If you really don't want to see this message, you can add the 'A' flag to the .\usr_doc.txt Page 85 'shortmess' option. But it's very unusual that you need this. For remarks about encryption and the swap file, see |:recover−crypt|. ============================================================================== *11.4* Further reading |swap−file| |:preserve| |:swapname| 'updatecount' 'updatetime' 'swapsync' 'directory' 'maxmem' 'maxmemtot' An explanation about where the swap file will be created and what its name is. Manually flushing the swap file to disk. See the name of the swap file for the current file. Number of key strokes after which the swap file is flushed to disk. Timeout after which the swap file is flushed to disk. Whether the disk is synced when the swap file is flushed. List of directory names where to store the swap file. Limit for memory usage before writing text to the swap file. Same, but for all files in total. ============================================================================== Next chapter: |usr_12.txt| Clever tricks Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_12.txt* Page 86 For Vim version 7.4. Last change: 2007 May 11 VIM USER MANUAL − by Bram Moolenaar Clever tricks By combining several commands you can make Vim do nearly everything. In this chapter a number of useful combinations will be presented. This uses the commands introduced in the previous chapters and a few more. |12.1| |12.2| |12.3| |12.4| |12.5| |12.6| |12.7| |12.8| Replace a word Change "Last, First" to "First Last" Sort a list Reverse line order Count words Find a man page Trim blanks Find where a word is used Next chapter: |usr_20.txt| Typing command−line commands quickly Previous chapter: |usr_11.txt| Recovering from a crash Table of contents: |usr_toc.txt| ============================================================================== *12.1* Replace a word The substitute command can be used to replace all occurrences of a word with another word: :%s/four/4/g The "%" range means to replace in all lines. The "g" flag at the end causes all words in a line to be replaced. This will not do the right thing if your file also contains "thirtyfour". It would be replaced with "thirty4". To avoid this, use the "\<" item to match the start of a word: :%s/\ " to match the end of :%s/\ /4/g If you are programming, you might want to replace "four" in comments, but not in the code. Since this is difficult to specify, add the "c" flag to have the substitute command prompt you for each replacement: :%s/\ /4/gc REPLACING IN SEVERAL FILES Suppose you want to replace a word in more than one file. You could edit each file and type the command manually. It's a lot faster to use record and playback. Let's assume you have a directory with C++ files, all ending in ".cpp". There is a function called "GetResp" that you want to rename to "GetAnswer". vim *.cpp Start Vim, defining the argument list to contain all the C++ files. You are now in the first file. qq Start recording into the q register :%s/\ /GetAnswer/g Do the replacements in the first file. :wnext Write this file and move to the next one. q Stop recording. @q Execute the q register. This will replay the .\usr_doc.txt 999@q Page 87 substitution and ":wnext". You can verify that this doesn't produce an error message. Execute the q register on the remaining files. At the last file you will get an error message, because ":wnext" cannot move to the next file. This stops the execution, and everything is done. Note: When playing back a recorded sequence, an error stops the execution. Therefore, make sure you don't get an error message when recording. There is one catch: If one of the .cpp files does not contain the word "GetResp", you will get an error and replacing will stop. To avoid this, add the "e" flag to the substitute command: :%s/\ /GetAnswer/ge The "e" flag tells ":substitute" that not finding a match is not an error. ============================================================================== *12.2* Change "Last, First" to "First Last" You have a list of names in this form: Doe, John Smith, Peter You want to change that to: John Doe Peter Smith This can be done with just one command: :%s/\([^,]*\), \(.*\)/\2 \1/ Let's break this down in parts. Obviously it starts with a substitute command. The "%" is the line range, which stands for the whole file. Thus the substitution is done in every line in the file. The arguments for the substitute command are "/from/to/". The slashes separate the "from" pattern and the "to" string. This is what the "from" pattern contains: \([^,]*\), \(.*\) The first part between \( \) matches "Last" match anything but a comma any number of times matches ", " literally The second part between \( \) matches "First" any character any number of times \( \) [^,] * , \( \) . * In the "to" part we have "\2" and "\1". These are called backreferences. They refer to the text matched by the "\( \)" parts in the pattern. "\2" refers to the text matched by the second "\( \)", which is the "First" name. "\1" refers to the first "\( \)", which is the "Last" name. You can use up to nine backreferences in the "to" part of a substitute command. "\0" stands for the whole matched pattern. There are a few more special items in a substitute command, see |sub−replace−special|. ============================================================================== *12.3* Sort a list In a Makefile you often have a list of files. OBJS = \ version.o \ pch.o \ getopt.o \ util.o \ getopt1.o \ For example: .\usr_doc.txt Page 88 inp.o \ patch.o \ backup.o To sort this list, filter the text through the external sort command: /^OBJS j :.,/^$/−1!sort This goes to the first line, where "OBJS" is the first thing in the line. Then it goes one line down and filters the lines until the next empty line. You could also select the lines in Visual mode and then use "!sort". That's easier to type, but more work when there are many lines. The result is this: OBJS = \ backup.o getopt.o \ getopt1.o \ inp.o \ patch.o \ pch.o \ util.o \ version.o \ Notice that a backslash at the end of each line is used to indicate the line continues. After sorting, this is wrong! The "backup.o" line that was at the end didn't have a backslash. Now that it sorts to another place, it must have a backslash. The simplest solution is to add the backslash with "A \ ". You can keep the backslash in the last line, if you make sure an empty line comes after it. That way you don't have this problem again. ============================================================================== *12.4* Reverse line order The |:global| command can be combined with the |:move| command to move all the lines before the first line, resulting in a reversed file. The command is: :global/^/m 0 Abbreviated: :g/^/m 0 The "^" regular expression matches the beginning of the line (even if the line is blank). The |:move| command moves the matching line to after the mythical zeroth line, so the current matching line becomes the first line of the file. As the |:global| command is not confused by the changing line numbering, |:global| proceeds to match all remaining lines of the file and puts each as the first. This also works on a range of lines. First move to above the first line and mark it with "mt". Then move the cursor to the last line in the range and type: :'t+1,.g/^/m 't ============================================================================== *12.5* Count words Sometimes you have to write a text with a maximum number of words. Vim can count the words for you. When the whole file is what you want to count the words in, use this command: g CTRL−G Do not type a space after the g, this is just used here to make the command .\usr_doc.txt Page 89 easy to read. The output looks like this: Col 1 of 0; Line 141 of 157; Word 748 of 774; Byte 4489 of 4976 You can see on which word you are (748), and the total number of words in the file (774). When the text is only part of a file, you could move to the start of the type "g CTRL−G", move to the end of the text, type "g CTRL−G" again, and use your brain to compute the difference in the word position. That's a exercise, but there is an easier way. With Visual mode, select the text want to count words in. Then type g CTRL−G. The result: text, then good you Selected 5 of 293 Lines; 70 of 1884 Words; 359 of 10928 Bytes For other ways to count words, lines and other items, see |count−items|. ============================================================================== *12.6* Find a man page *find−manpage* While editing a shell script or C program, you are using a command or function that you want to find the man page for (this is on Unix). Let's first use a simple way: Move the cursor to the word you want to find help on and press K Vim will run the external "man" program on the word. If the man page is found, it is displayed. This uses the normal pager to scroll through the text (mostly the "more" program). When you get to the end pressing will get you back into Vim. A disadvantage is that you can't see the man page and the text you are working on at the same time. There is a trick to make the man page appear in a Vim window. First, load the man filetype plugin: :runtime! ftplugin/man.vim Put this command in your vimrc file if you intend to do this often. can use the ":Man" command to open a window on a man page: Now you :Man csh You can scroll around and the text is highlighted. This allows you to find the help you were looking for. Use CTRL−W w to jump to the window with the text you were working on. To find a man page in a specific section, put the section number first. For example, to look in section 3 for "echo": :Man 3 echo To jump to another man page, which is in the text with the typical form "word(1)", press CTRL−] on it. Further ":Man" commands will use the same window. To display a man page for the word under the cursor, use this: \K (If you redefined the , use it instead of the backslash). For example, you want to know the return value of "strstr()" while editing this line: if ( strstr (input, "aap") == ) Move the cursor to somewhere on "strstr" and type "\K". to display the man page for strstr(). A window will open ============================================================================== *12.7* Trim blanks .\usr_doc.txt Page 90 Some people find spaces and tabs at the end of a line useless, wasteful, and ugly. To remove whitespace at the end of every line, execute the following command: :%s/\s\+$// The line range "%" is used, thus this works on the whole file. The pattern that the ":substitute" command matches with is "\s\+$". This finds white space characters (\s), 1 or more of them (\+), before the end−of−line ($). Later will be explained how you write patterns like this |usr_27.txt|. The "to" part of the substitute command is empty: "//". Thus it replaces with nothing, effectively deleting the matched white space. Another wasteful use of spaces is placing them before a tab. Often these can be deleted without changing the amount of white space. But not always! Therefore, you can best do this manually. Use this search command: / You cannot see it, but there is a space before a tab in this command. Thus it's "/ ". Now use "x" to delete the space and check that the amount of white space doesn't change. You might have to insert a tab if it does change. Type "n" to find the next match. Repeat this until no more matches can be found. ============================================================================== *12.8* Find where a word is used If you are a UNIX user, you can use a combination of Vim and the grep command to edit all the files that contain a given word. This is extremely useful if you are working on a program and want to view or edit all the files that contain a specific variable. For example, suppose you want to edit all the C program files that contain the word "frame_counter". To do this you use the command: vim `grep −l frame_counter *.c` Let's look at this command in detail. The grep command searches through a set of files for a given word. Because the −l argument is specified, the command will only list the files containing the word and not print the matching lines. The word it is searching for is "frame_counter". Actually, this can be any regular expression. (Note: What grep uses for regular expressions is not exactly the same as what Vim uses.) The entire command is enclosed in backticks (`). This tells the UNIX shell to run this command and pretend that the results were typed on the command line. So what happens is that the grep command is run and produces a list of files, these files are put on the Vim command line. This results in Vim editing the file list that is the output of grep. You can then use commands like ":next" and ":first" to browse through the files. FINDING EACH LINE The above command only finds the files in which the word is found. You still have to find the word within the files. Vim has a built−in command that you can use to search a set of files for a given string. If you want to find all occurrences of "error_string" in all C program files, for example, enter the following command: :grep error_string *.c This causes Vim to search for the string "error_string" in all the specified files (*.c). The editor will now open the first file where a match is found and position the cursor on the first matching line. To go to the next matching line (no matter in what file it is), use the ":cnext" command. To go to the previous match, use the ":cprev" command. Use ":clist" to see all the matches and where they are. The ":grep" command uses the external commands grep (on Unix) or findstr (on Windows). You can change this by setting the option 'grepprg'. ============================================================================== .\usr_doc.txt Next chapter: |usr_20.txt| Page 91 Typing command−line commands quickly Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_20.txt* Page 92 For Vim version 7.4. Last change: 2006 Apr 24 VIM USER MANUAL − by Bram Moolenaar Typing command−line commands quickly Vim has a few generic features that makes it easier to enter commands. Colon commands can be abbreviated, edited and repeated. Completion is available for nearly everything. |20.1| |20.2| |20.3| |20.4| |20.5| Command Command Command Command Command line line line line line editing abbreviations completion history window Next chapter: |usr_21.txt| Go away and come back Previous chapter: |usr_12.txt| Clever tricks Table of contents: |usr_toc.txt| ============================================================================== *20.1* Command line editing When you use a colon (:) command or search for a string with / or ?, Vim puts the cursor on the bottom of the screen. There you type the command or search pattern. This is called the Command line. Also when it's used for entering a search command. The most obvious way to edit the command you type is by pressing the key. This erases the character before the cursor. To erase another character, typed earlier, first move the cursor with the cursor keys. For example, you have typed this: :s/col/pig/ Before you hit , you notice that "col" should be "cow". To correct this, you type five times. The cursor is now just after "col". Type and "w" to correct: :s/cow/pig/ Now you can press directly. You don't have to move the cursor to the end of the line before executing the command. The most often used keys to move around in the command line: ororCTRL−B or CTRL−E or one character left one character right one word left one word right to begin of command line to end of command line Note: (cursor left key with Shift key pressed) and(cursor left key with Control pressed) will not work on all keyboards. Same for the other Shift and Control combinations. You can also use the mouse to move the cursor. DELETING As mentioned, deletes the character before the cursor. word use CTRL−W. /the fine pig CTRL−W To delete a whole .\usr_doc.txt Page 93 /the fine CTRL−U removes all text, thus allows you to start all over again. OVERSTRIKE The key toggles between inserting characters and replacing the existing ones. Start with this text: /the fine pig Move the cursor to the start of "fine" with twice (oreight times, if doesn't work). Now pressto switch to overstrike and type "great": /the greatpig Oops, we lost the space. Now, don't use , because it would delete the "t" (this is different from Replace mode). Instead, press to switch from overstrike to inserting, and type the space: /the great pig CANCELLING You thought of executing a : or / command, but changed your mind. To get rid of what you already typed, without executing it, press CTRL−C or . Note: is the universal "get out" key. Unfortunately, in the good old Vi pressing in a command line executed the command! Since that might be considered to be a bug, Vim uses to cancel the command. But with the 'cpoptions' option it can be made Vi compatible. And when using a mapping (which might be written for Vi) also works Vi compatible. Therefore, using CTRL−C is a method that always works. If you are at the start of the command line, pressing will cancel the command. It's like deleting the ":" or "/" that the line starts with. ============================================================================== *20.2* Command line abbreviations Some of the ":" commands are really long. ":substitute" can be abbreviated to ":s". ":" commands can be abbreviated. We already mentioned that This is a generic mechanism, all How short can a command get? There are 26 letters, and many more commands. For example, ":set" also starts with ":s", but ":s" doesn't start a ":set" command. Instead ":set" can be abbreviated to ":se". When the shorter form of a command could be used for two commands, it stands for only one of them. There is no logic behind which one, you have to learn them. In the help files the shortest form that works is mentioned. For example: :s[ubstitute] This means that the shortest form of ":substitute" is ":s". characters are optional. Thus ":su" and ":sub" also work. The following In the user manual we will either use the full name of command, or a short version that is still readable. For example, ":function" can be abbreviated to ":fu". But since most people don't understand what that stands for, we will use ":fun". (Vim doesn't have a ":funny" command, otherwise ":fun" would be confusing too.) It is recommended that in Vim scripts you write the full command name. That makes it easier to read back when you make later changes. Except for some often used commands like ":w" (":write") and ":r" (":read"). .\usr_doc.txt Page 94 A particularly confusing one is ":end", which could stand for ":endif", ":endwhile" or ":endfunction". Therefore, always use the full name. SHORT OPTION NAMES In the user manual the long version of the option names is used. Many options also have a short name. Unlike ":" commands, there is only one short name that works. For example, the short name of 'autoindent' is 'ai'. Thus these two commands do the same thing: :set autoindent :set ai You can find the full list of long and short names here: |option−list|. ============================================================================== *20.3* Command line completion This is one of those Vim features that, by itself, is a reason to switch from Vi to Vim. Once you have used this, you can't do without. Suppose you have a directory that contains these files: info.txt intro.txt bodyofthepaper.txt To edit the last one, you use the command: :edit bodyofthepaper.txt It's easy to type this wrong. A much quicker way is: :edit b Which will result in the same command. What happened? The key does completion of the word before the cursor. In this case "b". Vim looks in the directory and finds only one file that starts with a "b". That must be the one you are looking for, thus Vim completes the file name for you. Now type: :edit i Vim will beep, and give you: :edit info.txt The beep means that Vim has found more than one match. It then uses the first match it found (alphabetically). If you press again, you get: :edit intro.txt Thus, if the first doesn't give you the file you were looking for, press it again. If there are more matches, you will see them all, one at a time. If you press on the last matching entry, you will go back to what you first typed: :edit i Then it starts all over again. Thus Vim cycles through the list of matches. Use CTRL−P to go through the list in the other direction: <−−−−−−−−−−−−−−−−−−− −−−−−−−−−−−−−−−−−−−−−−−−−+ | −−> −−> :edit i :edit info.txt :edit intro.txt <−− CTRL−P <−− CTRL−P | +−−−−−−−−−−−−−−−−−−−−−− CTRL−P −−−−−−−−−−−−−−−−−−−−−−−−> .\usr_doc.txt Page 95 CONTEXT When you type ":set i" instead of ":edit i" and press you get: :set icon Hey, why didn't you get ":set info.txt"? That's because Vim has context sensitive completion. The kind of words Vim will look for depends on the command before it. Vim knows that you cannot use a file name just after a ":set" command, but you can use an option name. Again, if you repeat typing the , Vim will cycle through all matches. There are quite a few, it's better to type more characters first: :set isk Gives: :set iskeyword Now type "=" and press : :set iskeyword=@,48−57,_,192−255 What happens here is that Vim inserts the old value of the option. Now you can edit it. What is completed with is what Vim expects in that place. Just try it out to see how it works. In some situations you will not get what you want. That's either because Vim doesn't know what you want, or because completion was not implemented for that situation. In that case you will get a inserted (displayed as ^I). LIST MATCHES When there are many matches, you would like to see an overview. pressing CTRL−D. For example, pressing CTRL−D after: Do this by :set is results in: :set is incsearch :set is isfname isident iskeyword isprint Vim lists the matches and then comes back with the text you typed. You can now check the list for the item you wanted. If it isn't there, you can use to correct the word. If there are many matches, type a few more characters before pressing to complete the rest. If you have watched carefully, you will have noticed that "incsearch" doesn't start with "is". In this case "is" stands for the short name of "incsearch". (Many options have a short and a long name.) Vim is clever enough to know that you might have wanted to expand the short name of the option into the long name. THERE IS MORE The CTRL−L command completes the word to the longest unambiguous string. If you type ":edit i" and there are files "info.txt" and "info_backup.txt" you will get ":edit info". The 'wildmode' option can be used to change the way completion works. The 'wildmenu' option can be used to get a menu−like list of matches. Use the 'suffixes' option to specify files that are less important and appear at the end of the list of files. The 'wildignore' option specifies files that are not listed at all. More about all of this here: |cmdline−completion| .\usr_doc.txt Page 96 ============================================================================== *20.4* Command line history In chapter 3 we briefly mentioned the history. The basics are that you can use the key to recall an older command line. then takes you back to newer commands. There are actually four histories. The ones we will mention here are for ":" commands and for "/" and "?" search commands. The "/" and "?" commands share the same history, because they are both search commands. The two other histories are for expressions and input lines for the input() function. |cmdline−history| Suppose you have done a ":set" command, typed ten more colon commands and then want to repeat that ":set" command again. You could press ":" and then ten times . There is a quicker way: :se Vim will now go back to the previous command that started with "se". You have a good chance that this is the ":set" command you were looking for. At least you should not have to press very often (unless ":set" commands is all you have done). The key will use the text typed so far and compare it with the lines in the history. Only matching lines will be used. If you do not find the line you were looking for, use to go back to what you typed and correct that. Or use CTRL−U to start all over again. To see all the lines in the history: :history That's the history of ":" commands. command: The search history is displayed with this :history / CTRL−P will work like , except that it doesn't matter what you already typed. Similarly for CTRL−N and . CTRL−P stands for previous, CTRL−N for next. ============================================================================== *20.5* Command line window Typing the text in the command line works different from typing text in Insert mode. It doesn't allow many commands to change the text. For most commands that's OK, but sometimes you have to type a complicated command. That's where the command line window is useful. Open the command line window with this command: q: Vim now opens a (small) window at the bottom. history, and an empty line at the end: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ |other window | |~ | |file.txt=============================| |:e c | |:e config.h.in | |:set path=.,/usr/include,, | |:set iskeyword=@,48−57,_,192−255 | |:set is | |:q | |: | |command−line=========================| | | It contains the command line .\usr_doc.txt Page 97 +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ You are now in Normal mode. You can use the "hjkl" keys to move around. For example, move up with "5k" to the ":e config.h.in" line. Type "$h" to go to the "i" of "in" and type "cwout". Now you have changed the line to: :e config.h.out Now press and this command will be executed. The command line window will close. The command will execute the line under the cursor. It doesn't matter whether Vim is in Insert mode or in Normal mode. Changes in the command line window are lost. They do not result in the history to be changed. Except that the command you execute will be added to the end of the history, like with all executed commands. The command line window is very useful when you want to have overview of the history, lookup a similar command, change it a bit and execute it. A search command can be used to find something. In the previous example the "?config" search command could have been used to find the previous command that contains "config". It's a bit strange, because you are using a command line to search in the command line window. While typing that search command you can't open another command line window, there can be only one. ============================================================================== Next chapter: |usr_21.txt| Go away and come back Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_21.txt* Page 98 For Vim version 7.4. Last change: 2012 Nov 02 VIM USER MANUAL − by Bram Moolenaar Go away and come back This chapter goes into mixing the use of other programs with Vim. Either by executing program from inside Vim or by leaving Vim and coming back later. Furthermore, this is about the ways to remember the state of Vim and restore it later. |21.1| |21.2| |21.3| |21.4| |21.5| |21.6| Suspend and resume Executing shell commands Remembering information; viminfo Sessions Views Modelines Next chapter: |usr_22.txt| Finding the file to edit Previous chapter: |usr_20.txt| Typing command−line commands quickly Table of contents: |usr_toc.txt| ============================================================================== *21.1* Suspend and resume Like most Unix programs Vim can be suspended by pressing CTRL−Z. This stops Vim and takes you back to the shell it was started in. You can then do any other commands until you are bored with them. Then bring back Vim with the "fg" command. CTRL−Z {any sequence of shell commands} fg You are right back where you left Vim, nothing has changed. In case pressing CTRL−Z doesn't work, you can also use ":suspend". Don't forget to bring Vim back to the foreground, you would lose any changes that you made! Only Unix has support for this. On other systems Vim will start a shell for you. This also has the functionality of being able to execute shell commands. But it's a new shell, not the one that you started Vim from. When you are running the GUI you can't go back to the shell where Vim was started. CTRL−Z will minimize the Vim window instead. ============================================================================== *21.2* Executing shell commands To execute a single shell command from Vim use ":!{command}". see a directory listing: For example, to :!ls :!dir The first one is for Unix, the second one for MS−Windows. Vim will execute the program. When it ends you will get a prompt to hit . This allows you to have a look at the output from the command before returning to the text you were editing. The "!" is also used in other places where a program is run. Let's take a look at an overview: :!{program} :r !{program} :w !{program} :[range]!{program} execute {program} execute {program} and read its output execute {program} and send text to its input filter text through {program} Notice that the presence of a range before "!{program}" makes a big difference. Without it executes the program normally, with the range a number of text lines is filtered through the program. .\usr_doc.txt Page 99 Executing a whole row of programs this way is possible. better at it. You can start a new shell this way: But a shell is much :shell This is similar to using CTRL−Z to suspend Vim. shell is started. The difference is that a new When using the GUI the shell will be using the Vim window for its input and output. Since Vim is not a terminal emulator, this will not work perfectly. If you have trouble, try toggling the 'guipty' option. If this still doesn't work well enough, start a new terminal to run the shell in. For example with: :!xterm& ============================================================================== *21.3* Remembering information; viminfo After editing for a while you will have text in registers, marks in various files, a command line history filled with carefully crafted commands. When you exit Vim all of this is lost. But you can get it back! The viminfo file is designed to store status information: Command−line and Search pattern history Text in registers Marks for various files The buffer list Global variables Each time you exit Vim it will store this information in a file, the viminfo file. When Vim starts again, the viminfo file is read and the information restored. The 'viminfo' option is set by default to restore a limited number of items. You might want to set it to remember more information. This is done through the following command: :set viminfo=string The string specifies what to save. The syntax of this string is an option character followed by an argument. The option/argument pairs are separated by commas. Take a look at how you can build up your own viminfo string. First, the ' option is used to specify how many files for which you save marks (a−z). Pick a nice even number for this option (1000, for instance). Your command now looks like this: :set viminfo='1000 The f option controls whether global marks (A−Z and 0−9) are stored. If this option is 0, none are stored. If it is 1 or you do not specify an f option, the marks are stored. You want this feature, so now you have this: :set viminfo='1000,f1 The < option default, all thousands of starting Vim controls how many lines are saved for each of the registers. By the lines are saved. If 0, nothing is saved. To avoid adding lines to your viminfo file (which might never get used and makes slower) you use a maximum of 500 lines: :set viminfo='1000,f1,<500 Other options you might want to use: : number of lines to save from the command line history @ number of lines to save from the input line history / number of lines to save from the search history r removable media, for which no marks will be stored (can be used several times) ! global variables that start with an uppercase letter and .\usr_doc.txt h % c n Page 100 don't contain lowercase letters disable 'hlsearch' highlighting when starting the buffer list (only restored when starting Vim without file arguments) convert the text using 'encoding' name used for the viminfo file (must be the last option) See the 'viminfo' option and |viminfo−file| for more information. When you run Vim multiple times, the last one exiting will store its information. This may cause information that previously exiting Vims stored to be lost. Each item can be remembered only once. GETTING BACK TO WHERE YOU STOPPED VIM You are halfway editing a file and it's time to leave for holidays. You exit Vim and go enjoy yourselves, forgetting all about your work. After a couple of weeks you start Vim, and type: '0 And you are right back where you left Vim. So you can get on with your work. Vim creates a mark each time you exit Vim. The last one is '0. The position that '0 pointed to is made '1. And '1 is made to '2, and so forth. Mark '9 is lost. The |:marks| command is useful to find out where '0 to '9 will take you. GETTING BACK TO SOME FILE If you want to go back to a file that you edited recently, but not when exiting Vim, there is a slightly more complicated way. You can see a list of files by typing the command: :oldfiles 1: ~/.viminfo 2: ~/text/resume.txt 3: /tmp/draft Now you would like to edit the second file, which is in the list preceded by "2:". You type: :e #<2 Instead of ":e" you can use any command that has a file name argument, the "#<2" item works in the same place as "%" (current file name) and "#" (alternate file name). So you can also split the window to edit the third file: :split #<3 That #<123 thing is a bit complicated when you just want to edit a file. Fortunately there is a simpler way: :browse oldfiles 1: ~/.viminfo 2: ~/text/resume.txt 3: /tmp/draft −− More −− You get the same list of files as with |:oldfiles|. If you want to edit "resume.txt" first press "q" to stop the listing. You will get a prompt: Type number and (empty cancels): Type "2" and press to edit the second file. More info at |:oldfiles|, |v:oldfiles| and |c_#<|. .\usr_doc.txt Page 101 MOVE INFO FROM ONE VIM TO ANOTHER You can use the ":wviminfo" and ":rviminfo" commands to save and restore the information while still running Vim. This is useful for exchanging register contents between two instances of Vim, for example. In the first Vim do: :wviminfo! ~/tmp/viminfo And in the second Vim do: :rviminfo! ~/tmp/viminfo Obviously, the "w" stands for "write" and the "r" for "read". The ! character is used by ":wviminfo" to forcefully overwrite an existing file. When it is omitted, and the file exists, the information is merged into the file. The ! character used for ":rviminfo" means that all the information is used, this may overwrite existing information. Without the ! only information that wasn't set is used. These commands can also be used to store info and use it again later. You could make a directory full of viminfo files, each containing info for a different purpose. ============================================================================== *21.4* Sessions Suppose you are editing along, and it is the end of the day. You want to quit work and pick up where you left off the next day. You can do this by saving your editing session and restoring it the next day. A Vim session contains all the information about what you are editing. This includes things such as the file list, window layout, global variables, options and other information. (Exactly what is remembered is controlled by the 'sessionoptions' option, described below.) The following command creates a session file: :mksession vimbook.vim Later if you want to restore this session, you can use this command: :source vimbook.vim If you want to start Vim and restore a specific session, you can use the following command: vim −S vimbook.vim This tells Vim to read a specific file on startup. The 'S' stands for session (actually, you can source any Vim script with −S, thus it might as well stand for "source"). The windows that were open are restored, with the same position and size as before. Mappings and option values are like before. What exactly is restored depends on the 'sessionoptions' option. The default value is "blank,buffers,curdir,folds,help,options,winsize". blank buffers curdir folds help options winsize keep empty windows all buffers, not only the ones in a window the current directory folds, also manually created ones the help window all options and mappings window sizes Change this to your liking. example, use: To also restore the size of the Vim window, for :set sessionoptions+=resize SESSION HERE, SESSION THERE .\usr_doc.txt Page 102 The obvious way to use sessions is when working on different projects. Suppose you store your session files in the directory "~/.vim". You are currently working on the "secret" project and have to switch to the "boring" project: :wall :mksession! ~/.vim/secret.vim :source ~/.vim/boring.vim This first uses ":wall" to write all modified files. Then the current session is saved, using ":mksession!". This overwrites the previous session. The next time you load the secret session you can continue where you were at this point. And finally you load the new "boring" session. If you open help windows, split and close various windows, and generally mess up the window layout, you can go back to the last saved session: :source ~/.vim/boring.vim Thus you have complete control over whether you want to continue next time where you are now, by saving the current setup in a session, or keep the session file as a starting point. Another way of using sessions is to create a window layout that you like to use, and save this in a session. Then you can go back to this layout whenever you want. For example, this is a nice layout to use: +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ | VIM − main help file | | | |Move around: Use the cursor keys, or "h| |help.txt================================| |explorer | | |dir |~ | |dir |~ | |file |~ | |file |~ | |file |~ | |file |~ | |~/=========|[No File]===================| | | +−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+ This has a help window at the top, so that you can read this text. The narrow vertical window on the left contains a file explorer. This is a Vim plugin that lists the contents of a directory. You can select files to edit there. More about this in the next chapter. Create this from a just started Vim with: :help CTRL−W w :vertical split ~/ You can resize the windows a bit to your liking. Then save the session with: :mksession ~/.vim/mine.vim Now you can start Vim with this layout: vim −S ~/.vim/mine.vim Hint: To open a file you see listed in the explorer window in the empty window, move the cursor to the filename and press "O". Double clicking with the mouse will also do this. UNIX AND MS−WINDOWS Some people have to do work on MS−Windows systems one day and on Unix another day. If you are one of them, consider adding "slash" and "unix" to 'sessionoptions'. The session files will then be written in a format that can .\usr_doc.txt be used on both systems. Page 103 This is the command to put in your vimrc file: :set sessionoptions+=unix,slash Vim will use the Unix format then, because the MS−Windows Vim can read and write Unix files, but Unix Vim can't read MS−Windows format session files. Similarly, MS−Windows Vim understands file names with / to separate names, but Unix Vim doesn't understand \. SESSIONS AND VIMINFO Sessions store many things, but not the position of marks, contents of registers and the command line history. You need to use the viminfo feature for these things. In most situations you will want to use sessions separately from viminfo. This can be used to switch to another session, but keep the command line history. And yank text into registers in one session, and paste it back in another session. You might prefer to keep the info with the session. You will have to do this yourself then. Example: :mksession! ~/.vim/secret.vim :wviminfo! ~/.vim/secret.viminfo And to restore this again: :source ~/.vim/secret.vim :rviminfo! ~/.vim/secret.viminfo ============================================================================== *21.5* Views A session stores the looks of the whole of Vim. When you want to store the properties for one window only, use a view. The use of a view is for when you want to edit a file in a specific way. For example, you have line numbers enabled with the 'number' option and defined a few folds. Just like with sessions, you can remember this view on the file and restore it later. Actually, when you store a session, it stores the view of each window. There are two basic ways to use views. The first is to let Vim pick a name for the view file. You can restore the view when you later edit the same file. To store the view for the current window: :mkview Vim will decide where to store the view. you get the view back with this command: When you later edit the same file :loadview That's easy, isn't it? Now you want to view the file without the 'number' option on, or with all folds open, you can set the options to make the window look that way. Then store this view with: :mkview 1 Obviously, you can get this back with: :loadview 1 Now you can switch between the two views on the file by using ":loadview" with and without the "1" argument. You can store up to ten views for the same file this way, one unnumbered and nine numbered 1 to 9. A VIEW WITH A NAME The second basic way to use views is by storing the view in a file with a name .\usr_doc.txt Page 104 you choose. This view can be loaded while editing another file. Vim will then switch to editing the file specified in the view. Thus you can use this to quickly switch to editing another file, with all its options set as you saved them. For example, to save the view of the current file: :mkview ~/.vim/main.vim You can restore it with: :source ~/.vim/main.vim ============================================================================== *21.6* Modelines When editing a specific file, you might set options specifically for that file. Typing these commands each time is boring. Using a session or view for editing a file doesn't work when sharing the file between several people. The solution for this situation is adding a modeline to the file. This is a line of text that tells Vim the values of options, to be used in this file only. A typical example is a C program where you make indents by a multiple of 4 spaces. This requires setting the 'shiftwidth' option to 4. This modeline will do that: /* vim:set shiftwidth=4: */ Put this line as one of the first or last five lines in the file. When editing the file, you will notice that 'shiftwidth' will have been set to four. When editing another file, it's set back to the default value of eight. For some files the modeline fits well in the header, thus it can be put at the top of the file. For text files and other files where the modeline gets in the way of the normal contents, put it at the end of the file. The 'modelines' option specifies how many lines at the start and end of the file are inspected for containing a modeline. To inspect ten lines: :set modelines=10 The 'modeline' option can be used to switch this off. Do this when you are working as root on Unix or Administrator on MS−Windows, or when you don't trust the files you are editing: :set nomodeline Use this format for the modeline: any−text vim:set {option}={value} ... : any−text The "any−text" indicates that you can put any text before and after the part that Vim will use. This allows making it look like a comment, like what was done above with /* and */. The " vim:" part is what makes Vim recognize this line. There must be white space before "vim", or "vim" must be at the start of the line. Thus using something like "gvim:" will not work. The part between the colons is a ":set" command. It works the same way as typing the ":set" command, except that you need to insert a backslash before a colon (otherwise it would be seen as the end of the modeline). Another example: // vim:set textwidth=72 dir=c\:\tmp: use c:\tmp here There is an extra backslash before the first colon, so that it's included in the ":set" command. The text after the second colon is ignored, thus a remark can be placed there. For more details see |modeline|. ============================================================================== .\usr_doc.txt Next chapter: |usr_22.txt| Page 105 Finding the file to edit Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_22.txt* Page 106 For Vim version 7.4. Last change: 2012 Nov 15 VIM USER MANUAL − by Bram Moolenaar Finding the file to edit Files can be found everywhere. So how do you find them? Vim offers various ways to browse the directory tree. There are commands to jump to a file that is mentioned in another. And Vim remembers which files have been edited before. |22.1| |22.2| |22.3| |22.4| The file browser The current directory Finding a file The buffer list Next chapter: |usr_23.txt| Editing other files Previous chapter: |usr_21.txt| Go away and come back Table of contents: |usr_toc.txt| ============================================================================== *22.1* The file browser Vim has a plugin that makes it possible to edit a directory. Try this: :edit . Through the magic of autocommands and Vim scripts, the window will be filled with the contents of the directory. It looks like this: " ============================================================================ " Netrw Directory Listing (netrw v109) " Sorted by name " Sort sequence: [\/]$,\.h$,\.c$,\.cpp$,*,\.info$,\.swp$,\.o$\.obj$,\.bak$ " Quick Help: :help −:go up dir D:delete R:rename s:sort−by x:exec " ============================================================================ ../ ./ check/ Makefile autocmd.txt change.txt eval.txt~ filetype.txt~ help.txt.info You can see these items: 1. 2. 3. 4. 5. 6. The name of the browsing tool and its version number The name of the browsing directory The method of sorting (may be by name, time, or size) How names are to be sorted (directories first, then *.h files, *.c files, etc) How to get help (use the key), and an abbreviated listing of available commands A listing of files, including "../", which allows one to list the parent directory. If you have syntax highlighting enabled, the different parts are highlighted so as to make it easier to spot them. You can use Normal mode Vim commands to move around in the text. For example, move the cursor atop a file and press ; you will then be editing that file. To go back to the browser use ":edit ." again, or use ":Explore". CTRL−O also works. Try using while the cursor is atop a directory name. The result is that the file browser moves into that directory and displays the items found there. Pressing on the first directory "../" moves you one level .\usr_doc.txt Page 107 higher. Pressing "−" does the same thing, without the need to move to the "../" item first. You can press to get help on the things you can do in the netrw file browser. This is what you get: 9. Directory Browsing netrw−browse netrw−dir netrw−list netrw−help MAPS netrw−maps .............Help.......................................|netrw−help| .............Browsing...................................|netrw−cr| ............Deleting Files or Directories..............|netrw−delete| −................Going Up...................................|netrw−−| a................Hiding Files or Directories................|netrw−a| mb...............Bookmarking a Directory....................|netrw−mb| gb...............Changing to a Bookmarked Directory.........|netrw−gb| c................Make Browsing Directory The Current Dir....|netrw−c| d................Make A New Directory.......................|netrw−d| D................Deleting Files or Directories..............|netrw−D|............Edit File/Directory Hiding List............|netrw−ctrl−h| i................Change Listing Style.......................|netrw−i| ............Refreshing the Listing.....................|netrw−ctrl−l| o................Browsing with a Horizontal Split...........|netrw−o| p................Use Preview Window.........................|netrw−p| P................Edit in Previous Window....................|netrw−p| q................Listing Bookmarks and History..............|netrw−q| r................Reversing Sorting Order....................|netrw−r| (etc) The key thus brings you to a netrw directory browsing contents help page. It's a regular help page; use the usual |CTRL−]| to jump to tagged help items and |CTRL−O| to jump back. To select files for display and editing: (with the cursor is atop a filename) o v p P t Open the file in the current window. Horizontally split window and display file Vertically split window and display file Use the |preview−window| Edit in the previous window Open file in a new tab |netrw−cr| |netrw−o| |netrw−v| |netrw−p| |netrw−P| |netrw−t| The following normal−mode commands may be used to control the browser display: i s r Controls listing style (thin, long, wide, and tree). The long listing includes size and date information. Repeatedly pressing s will change the way the files are sorted; one may sort on name, modification time, or size. Reverse the sorting order. As a sampling of extra normal−mode commands: c R D mb gb Change Vim's notion of the current directory to be the same as the browser directory. (see |g:netrw_keepdir| to control this, too) Rename the file or directory under the cursor; a prompt will be issued for the new name. Delete the file or directory under the cursor; a confirmation request will be issued. Make bookmark/goto bookmark One may also use command mode; again, just a sampling: :Explore [directory] :NetrwSettings Browse specified/current directory A comprehensive list of your current netrw settings with help linkage. The netrw browser is not limited to just your local machine; one may use urls such as: (that trailing / is important) .\usr_doc.txt Page 108 :Explore ftp://somehost/path/to/dir/ :e scp://somehost/path/to/dir/ See |netrw−browse| for more. ============================================================================== *22.2* The current directory Just like the shell, Vim has the concept of a current directory. Suppose you are in your home directory and want to edit several files in a directory "VeryLongFileName". You could do: :edit VeryLongFileName/file1.txt :edit VeryLongFileName/file2.txt :edit VeryLongFileName/file3.txt To avoid much of the typing, do this: :cd VeryLongFileName :edit file1.txt :edit file2.txt :edit file3.txt The ":cd" command changes the current directory. directory is with the ":pwd" command: You can see what the current :pwd /home/Bram/VeryLongFileName Vim remembers the last directory that you used. Example: Use "cd −" to go back to it. :pwd /home/Bram/VeryLongFileName :cd /etc :pwd /etc :cd − :pwd /home/Bram/VeryLongFileName :cd − :pwd /etc WINDOW LOCAL DIRECTORY When you split a window, both windows use the same current directory. When you want to edit a number of files somewhere else in the new window, you can make it use a different directory, without changing the current directory in the other window. This is called a local directory. :pwd /home/Bram/VeryLongFileName :split :lcd /etc :pwd /etc CTRL−W w :pwd /home/Bram/VeryLongFileName So long as no ":lcd" command has been used, all windows share the same current directory. Doing a ":cd" command in one window will also change the current directory of the other window. For a window where ":lcd" has been used a different current directory is remembered. Using ":cd" or ":lcd" in other windows will not change it. When using a ":cd" command in a window that uses a different current directory, it will go back to using the shared directory. .\usr_doc.txt Page 109 ============================================================================== *22.3* Finding a file You are editing a C program that contains this line: #include "inits.h" You want to see what is in that "inits.h" file. of the file and type: Move the cursor on the name gf Vim will find the file and edit it. What if the file is not in the current directory? Vim will use the 'path' option to find the file. This option is a list of directory names where to look for your file. Suppose you have your include files located in "c:/prog/include". This command will add it to the 'path' option: :set path+=c:/prog/include This directory is an absolute path. No matter where you are, it will be the same place. What if you have located files in a subdirectory, below where the file is? Then you can specify a relative path name. This starts with a dot: :set path+=./proto This tells Vim to look in the directory "proto", below the directory where the file in which you use "gf" is. Thus using "gf" on "inits.h" will make Vim look for "proto/inits.h", starting in the directory of the file. Without the "./", thus "proto", Vim would look in the "proto" directory below the current directory. And the current directory might not be where the file that you are editing is located. The 'path' option allows specifying the directories where to search for files in many more ways. See the help on the 'path' option. The 'isfname' option is used to decide which characters are included in the file name, and which ones are not (e.g., the " character in the example above). When you know the file name, but it's not to be found in the file, you can type it: :find inits.h Vim will then use the 'path' option to try and locate the file. same as the ":edit" command, except for the use of 'path'. This is the To open the found file in a new window use CTRL−W f instead of "gf", or use ":sfind" instead of ":find". A nice way to directly start Vim to edit a file somewhere in the 'path': vim "+find stdio.h" This finds the file "stdio.h" in your value of 'path'. necessary to have one argument |−+c|. The quotes are ============================================================================== *22.4* The buffer list The Vim editor uses the term buffer to describe a file being edited. Actually, a buffer is a copy of the file that you edit. When you finish changing the buffer, you write the contents of the buffer to the file. Buffers not only contain file contents, but also all the marks, settings, and other stuff that goes with it. HIDDEN BUFFERS .\usr_doc.txt Page 110 Suppose you are editing the file one.txt and need to edit the file two.txt. You could simply use ":edit two.txt", but since you made changes to one.txt that won't work. You also don't want to write one.txt yet. Vim has a solution for you: :hide edit two.txt The buffer "one.txt" disappears from the screen, but Vim still knows that you are editing this buffer, so it keeps the modified text. This is called a hidden buffer: The buffer contains text, but you can't see it. The argument of ":hide" is another command. ":hide" makes that command behave as if the 'hidden' option was set. You could also set this option yourself. The effect is that when any buffer is abandoned, it becomes hidden. Be careful! When you have hidden buffers with changes, don't exit Vim without making sure you have saved all the buffers. INACTIVE BUFFERS When a buffer has been used once, Vim remembers some information about it. When it is not displayed in a window and it is not hidden, it is still in the buffer list. This is called an inactive buffer. Overview: Active Hidden Inactive Appears in a window, text loaded. Not in a window, text loaded. Not in a window, no text loaded. The inactive buffers are remembered, because Vim keeps information about them, like marks. And remembering the file name is useful too, so that you can see which files you have edited. And edit them again. LISTING BUFFERS View the buffer list with this command: :buffers A command which does the same, is not so obvious to list buffers, but is much shorter to type: :ls The output could look like this: 1 #h "help.txt" 2 %a + "usr_21.txt" 3 "usr_toc.txt" line 62 line 1 line 1 The first column contains the buffer number. You can use this to edit the buffer without having to type the name, see below. After the buffer number come the flags. Then the name of the file and the line number where the cursor was the last time. The flags that can appear are these (from left to right): u Buffer is unlisted |unlisted−buffer|. Current buffer. Alternate buffer. Buffer is loaded and displayed. Buffer is loaded but hidden. Buffer is read−only. Buffer is not modifiable, the 'modifiable' option is off. Buffer has been modified. % # a h = − + EDITING A BUFFER You can edit a buffer by its number. name: :buffer 2 That avoids having to type the file .\usr_doc.txt Page 111 But the only way to know the number is by looking in the buffer list. use the name, or part of it, instead: You can :buffer help Vim will find the best match for the name you type. If there is only one buffer that matches the name, it will be used. In this case "help.txt". To open a buffer in a new window: :sbuffer 3 This works with a name as well. USING THE BUFFER LIST You can move around in the buffer list with these commands: :bnext :bprevious :bfirst :blast go go go go to to to to next buffer previous buffer the first buffer the last buffer To remove a buffer from the list, use this command: :bdelete 3 Again, this also works with a name. If you delete a buffer that was active (visible in a window), that window will be closed. If you delete the current buffer, the current window will be closed. If it was the last window, Vim will find another buffer to edit. You can't be editing nothing! Note: Even after removing the buffer with ":bdelete" Vim still remembers it. It's actually made "unlisted", it no longer appears in the list from ":buffers". The ":buffers!" command will list unlisted buffers (yes, Vim can do the impossible). To really make Vim forget about a buffer, use ":bwipe". Also see the 'buflisted' option. ============================================================================== Next chapter: |usr_23.txt| Editing other files Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_23.txt* Page 112 For Vim version 7.4. Last change: 2006 Apr 24 VIM USER MANUAL − by Bram Moolenaar Editing other files This chapter is about editing files that are not ordinary files. With Vim you can edit files that are compressed or encrypted. Some files need to be accessed over the internet. With some restrictions, binary files can be edited as well. |23.1| |23.2| |23.3| |23.4| |23.5| DOS, Mac and Unix files Files on the internet Encryption Binary files Compressed files Next chapter: |usr_24.txt| Inserting quickly Previous chapter: |usr_22.txt| Finding the file to edit Table of contents: |usr_toc.txt| ============================================================================== *23.1* DOS, Mac and Unix files Back in the early days, the old Teletype machines used two characters to start a new line. One to move the carriage back to the first position (carriage return, ), another to move the paper up (line feed, ). When computers came out, storage was expensive. Some people decided that they did not need two characters for end−of−line. The UNIX people decided they could use only for end−of−line. The Apple people standardized on . The MS−DOS (and Microsoft Windows) folks decided to keep the old . This means that if you try to move a file from one system to another, you have line−break problems. The Vim editor automatically recognizes the different file formats and handles things properly behind your back. The option 'fileformats' contains the various formats that will be tried when a new file is edited. The following command, for example, tells Vim to try UNIX format first and MS−DOS format second: :set fileformats=unix,dos You will notice the format in the message you get when editing a file. You don't see anything if you edit a native file format. Thus editing a Unix file on Unix won't result in a remark. But when you edit a dos file, Vim will notify you of this: "/tmp/test" [dos] 3L, 71C For a Mac file you would see "[mac]". The detected file format is stored in the 'fileformat' option. which format you have, execute the following command: To see :set fileformat? The three names that Vim uses are: unix dos mac USING THE MAC FORMAT On Unix, is used to break a line. It's not unusual to have a character halfway a line. Incidentally, this happens quite often in Vi (and Vim) scripts. On the Macintosh, where is the line break character, it's possible to have a character halfway a line. The result is that it's not possible to be 100% sure whether a file .\usr_doc.txt Page 113 containing both and characters is a Mac or a Unix file. Therefore, Vim assumes that on Unix you probably won't edit a Mac file, and doesn't check for this type of file. To check for this format anyway, add "mac" to 'fileformats': :set fileformats+=mac Then Vim will take a guess at the file format. Vim guesses wrong. Watch out for situations where OVERRULING THE FORMAT If you use the good old Vi and try to edit an MS−DOS format file, you will find that each line ends with a ^M character. (^M is ). The automatic detection avoids this. Suppose you do want to edit the file that way? Then you need to overrule the format: :edit ++ff=unix file.txt The "++" string is an item that tells Vim that an option name follows, which overrules the default for this single command. "++ff" is used for 'fileformat'. You could also use "++ff=mac" or "++ff=dos". This doesn't work for any option, only "++ff" and "++enc" are currently implemented. The full names "++fileformat" and "++encoding" also work. CONVERSION You can use the 'fileformat' option to convert from one file format to another. Suppose, for example, that you have an MS−DOS file named README.TXT that you want to convert to UNIX format. Start by editing the MS−DOS format file: vim README.TXT Vim will recognize this as a dos format file. UNIX: Now change the file format to :set fileformat=unix :write The file is written in Unix format. ============================================================================== *23.2* Files on the internet Someone sends you an e−mail message, which refers to a file by its URL. example: For You can find the information here: ftp://ftp.vim.org/pub/vim/README You could start a program to download the file, save it on your local disk and then start Vim to edit it. There is a much simpler way. Move the cursor to any character of the URL. Then use this command: gf With a bit of luck, Vim will figure out which program to use for downloading the file, download it and edit the copy. To open the file in a new window use CTRL−W f. If something goes wrong you will get an error message. It's possible that the URL is wrong, you don't have permission to read it, the network connection is down, etc. Unfortunately, it's hard to tell the cause of the error. You might want to try the manual way of downloading the file. Accessing files over the internet works with the netrw plugin. with these formats are recognized: ftp:// uses ftp Currently URLs .\usr_doc.txt rcp:// scp:// http:// Page 114 uses rcp uses scp uses wget (reading only) Vim doesn't do the communication itself, it relies on the mentioned programs to be available on your computer. On most Unix systems "ftp" and "rcp" will be present. "scp" and "wget" might need to be installed. Vim detects these URLs for each command that starts editing a new file, also with ":edit" and ":split", for example. Write commands also work, except for http://. For more information, also about passwords, see |netrw|. ============================================================================== *23.3* Encryption Some information you prefer to keep to yourself. For example, when writing a test on a computer that students also use. You don't want clever students to figure out a way to read the questions before the exam starts. Vim can encrypt the file for you, which gives you some protection. To start editing a new file with encryption, use the "−x" argument to start Vim. Example: vim −x exam.txt Vim prompts you for a key used for encrypting and decrypting the file: Enter encryption key: Carefully type the secret key now. You cannot see the characters you type, they will be replaced by stars. To avoid the situation that a typing mistake will cause trouble, Vim asks you to enter the key again: Enter same key again: You can now edit this file normally and put in all your secrets. When you finish editing the file and tell Vim to exit, the file is encrypted and written. When you edit the file with Vim, it will ask you to enter the same key again. You don't need to use the "−x" argument. You can also use the normal ":edit" command. Vim adds a magic string to the file by which it recognizes that the file was encrypted. If you try to view this file using another program, all you get is garbage. Also, if you edit the file with Vim and enter the wrong key, you get garbage. Vim does not have a mechanism to check if the key is the right one (this makes it much harder to break the key). SWITCHING ENCRYPTION ON AND OFF To disable the encryption of a file, set the 'key' option to an empty string: :set key= The next time you write the file this will be done without encryption. Setting the 'key' option to enable encryption is not a good idea, because the password appears in the clear. Anyone shoulder−surfing can read your password. To avoid this problem, the ":X" command was created. It asks you for an encryption key, just like the "−x" argument did: :X Enter encryption key: ****** Enter same key again: ****** LIMITS ON ENCRYPTION The encryption algorithm used by Vim is weak. It is good enough to keep out the casual prowler, but not good enough to keep out a cryptology expert with .\usr_doc.txt Page 115 lots of time on his hands. Also you should be aware that the swap file is not encrypted; so while you are editing, people with superuser privileges can read the unencrypted text from this file. One way to avoid letting people read your swap file is to avoid using one. If the −n argument is supplied on the command line, no swap file is used (instead, Vim puts everything in memory). For example, to edit the encrypted file "file.txt" without a swap file use the following command: vim −x −n file.txt When already editing a file, the swapfile can be disabled with: :setlocal noswapfile Since there is no swapfile, recovery will be impossible. more often to avoid the risk of losing your changes. Save the file a bit While the file is in memory, it is in plain text. Anyone with privilege can look in the editor's memory and discover the contents of the file. If you use a viminfo file, be aware that the contents of text registers are written out in the clear as well. If you really want to secure the contents of a file, edit it only on a portable computer not connected to a network, use good encryption tools, and keep the computer locked up in a big safe when not in use. ============================================================================== *23.4* Binary files You can edit binary files with Vim. Vim wasn't really made for this, thus there are a few restrictions. But you can read a file, change a character and write it back, with the result that only that one character was changed and the file is identical otherwise. To make sure that Vim does not use its clever tricks in the wrong way, add the "−b" argument when starting Vim: vim −b datafile This sets the 'binary' option. The effect of this is that unexpected side effects are turned off. For example, 'textwidth' is set to zero, to avoid automatic formatting of lines. And files are always read in Unix file format. Binary mode can be used to change a message in a program. Be careful not to insert or delete any characters, it would stop the program from working. Use "R" to enter replace mode. Many characters in the file will be unprintable. To see them in Hex format: :set display=uhex Otherwise, the "ga" command can be used to see the value of the character under the cursor. The output, when the cursor is on an , looks like this: <^[> 27, Hex 1b, Octal 033 There might not be many line breaks in the file. the 'wrap' option off: To get some overview switch :set nowrap BYTE POSITION To see on which byte you are in the file use this command: g CTRL−G The output is verbose: Col 9−16 of 9−16; Line 277 of 330; Word 1806 of 2058; Byte 10580 of 12206 .\usr_doc.txt Page 116 The last two numbers are the byte position in the file and the total number of bytes. This takes into account how 'fileformat' changes the number of bytes that a line break uses. To move to a specific byte in the file, use the "go" command. For example, to move to byte 2345: 2345go USING XXD A real binary editor shows the text in two ways: as it is and in hex format. You can do this in Vim by first converting the file with the "xxd" program. This comes with Vim. First edit the file in binary mode: vim −b datafile Now convert the file to a hex dump with xxd: :%!xxd The text will look like this: 0000000: 1f8b 0808 39d7 173b 0203 7474 002b 4e49 0000010: 4b2c 8660 eb9c ecac c462 eb94 345e 2e30 0000020: 373b 2731 0b22 0ca6 c1a2 d669 1035 39d9 ....9..;..tt.+NI K,.`.....b..4^.0 7;'1.".....i.59. You can now view and edit the text as you like. Vim treats the information as ordinary text. Changing the hex does not cause the printable character to be changed, or the other way around. Finally convert it back with: :%!xxd −r Only changes in the hex part are used. the right are ignored. Changes in the printable text part on See the manual page of xxd for more information. ============================================================================== *23.5* Compressed files This is easy: You can edit a compressed file just like any other file. The "gzip" plugin takes care of decompressing the file when you edit it. And compressing it again when you write it. These compression methods are currently supported: .Z .gz .bz2 compress gzip bzip2 Vim uses the mentioned programs to do the actual compression and decompression. You might need to install the programs first. ============================================================================== Next chapter: |usr_24.txt| Inserting quickly Copyright: see |manual−copyright| vim:tw=78:ts=8:ft=help:norl: .\usr_doc.txt *usr_24.txt* Page 117 For Vim version 7.4. Last change: 2006 Jul 23 VIM USER MANUAL − by Bram Moolenaar Inserting quickly When entering text, Vim offers various ways to reduce the number of keystrokes and avoid typing mistakes. Use Insert mode completion to repeat previously typed words. Abbreviate long words to short ones. Type characters that aren't on your keyboard. |24.1| |24.2| |24.3| |24.4| |24.5| |24.6| |24.7| |24.8| |24.9| |24.10| Making corrections Showing matches Completion Repeating an insert Copying from another line Inserting a register Abbreviations Entering special characters Digraphs Normal mode commands Next chapter: |usr_25.txt| Editing formatted text Previous chapter: |usr_23.txt| Editing other files Table of contents: |usr_toc.txt| ============================================================================== *24.1* Making corrections The key was already mentioned. It deletes the character just before the cursor. The key does the same for the character under (after) the cursor. When you typed a whole word wrong, use CTRL−W: The horse had fallen to the sky CTRL−W The horse had fallen to the If you really messed up a line and want to start over, use CTRL−U to delete it. This keeps the text after the cursor and the indent. Only the text from the first non−blank to the cursor is deleted. With the cursor on the "f" of "fallen" in the next line pressing CTRL−U does this: The horse had fallen to the CTRL−U fallen to the When you spot a mistake a few words back, you need to move the cursor there to correct it. For example, you typed this: The horse had follen to the ground You need to change "follen" to "fallen". would type this to correct it: With the cursor at the end, you4blraA get out of Insert mode four words back move on top of the "o" replace with "a" restart Insert mode 4b l ra A Another way to do this: afour words back move on top of the "o" .\usr_doc.txt Page 118 delete the "o" insert an "a" go to end of the line aThis uses special keys to move around, while remaining in Insert mode. This resembles what you would do in a modeless editor. It's easier to remember, but takes more time (you have to move your hand from the letters to the cursor keys, and the key is hard to press without looking at the keyboard). These special keys are most useful when writing a mapping that doesn't leave Insert mode. The extra typing doesn't matter then. An overview of the keys you can use in Insert mode: to start of the file a whole screenful up to start of line one word left one word left one word right one word right to end of the line a whole screenful down to end of the file There are a few more, see |ins−special−special|. ============================================================================== *24.2* Showing matches When you type a ) it would be nice to see with which ( it matches. Vim do that use this command: To make :set showmatch When you now type a text like "(example)", as soon as you type the ) Vim will briefly move the cursor to the matching (, keep it there for half a second, and move back to where you were typing. In case there is no matching (, Vim will beep. Then you know that you might have forgotten the ( somewhere, or typed a ) too many. The match will also be shown for [] and {} pairs. You don't have to wait with typing the next character, as soon as Vim sees it the cursor will move back and inserting continues as before. You can change the time Vim waits with the 'matchtime' option. For example, to make Vim wait one and a half second: :set matchtime=15 The time is specified in tenths of a second. ============================================================================== *24.3* Completion Vim can automatically complete words on insertion. You type the first part of a word, press CTRL−P, and Vim guesses the rest. Suppose, for example, that you are creating a C program and want to type in the following: total = ch_array[0] + ch_array[1] + ch_array[2]; You start by entering the following: total = ch_array[0] + ch_ At this point, you tell Vim to complete the word using the command CTRL−P. Vim searches for a word that starts with what's in front of the cursor. In this case, it is "ch_", which matches with the word ch_array. So typing CTRL−P gives you the following: total = ch_array[0] + ch_array After a little more typing, you get this (ending in a space): .\usr_doc.txt Page 119 total = ch_array[0] + ch_array[1] + If you now type CTRL−P Vim will search again for a word that completes the word before the cursor. Since there is nothing in front of the cursor, it finds the first word backwards, which is "ch_array". Typing CTRL−P again gives you the next word that matches, in this case "total". A third CTRL−P searches further back. If there is nothing else, it causes the editor to run out of words, so it returns to the original text, which is nothing. A fourth CTRL−P causes the editor to start over again with "ch_array". To search forward, use CTRL−N. Since the search wraps around the end of the file, CTRL−N and CTRL−P will find the same matches, but in a different sequence. Hint: CTRL−N is Next−match and CTRL−P is Previous−match. The Vim editor goes through a lot of effort to find words to complete. default, it searches the following places: 1. 2. 3. 4. 5. 6. By Current file Files in other windows Other loaded files (hidden buffers) Files which are not loaded (inactive buffers) Tag files All files #included by the current file OPTIONS You can customize the search order with the 'complete' option. The 'ignorecase' option is used. when searching for matches. When it is set, case differences are ignored A special option for completion is 'infercase'. This is useful to find matches while ignoring case ('ignorecase' must be set) but still using the case of the word typed so far. Thus if you type "For" and Vim finds a match "fortunately", it will result in "Fortunately". COMPLETING SPECIFIC ITEMS If you know what you are looking for, you can use these commands to complete with a certain type of item: CTRL−X CTRL−X CTRL−X CTRL−X CTRL−X CTRL−X CTRL−X CTRL−X CTRL−F CTRL−L CTRL−D CTRL−I CTRL−K CTRL−T CTRL−] CTRL−V file names whole lines macro definitions (also in included files) current and included files words from a dictionary words from a thesaurus tags Vim command line After each of them CTRL−N can be used to find the next match, CTRL−P to find the previous match. More information for each of these commands here: |ins−completion|. COMPLETING FILE NAMES Let's take CTRL−X CTRL−F as an example. This will find file names. It scans the current directory for files and displays each one that matches the word in front of the cursor. Suppose, for example, that you have the following files in the current directory: main.c sub_count.c sub_done.c Now enter Insert mode and start typing: The exit code is in the file sub sub_exit.c .\usr_doc.txt Page 120 At this point, you enter the command CTRL−X CTRL−F. Vim now completes the current word "sub" by looking at the files in the current directory. The first match is sub_count.c. This is not the one you want, so you match the next file by typing CTRL−N. This match is sub_done.c. Typing CTRL−N again takes you to sub_exit.c. The results: The exit code is in the file sub_exit.c If the file name starts with / (Unix) or C:\ (MS−Windows) you can find all files in the file system. For example, type "/u" and CTRL−X CTRL−F. This will match "/usr" (this is on Unix): the file is found in /usr/ If you now press CTRL−N you go back to "/u". Instead, to accept the "/usr/" and go one directory level deeper, use CTRL−X CTRL−F again: the file is found in /usr/X11R6/ The results depend on what is found in your file system, of course. matches are sorted alphabetically. The COMPLETING IN SOURCE CODE Source code files are well structured. That makes it possible to do completion in an intelligent way. In Vim this is called Omni completion. some other editors it's called intellisense, but that is a trademark. In The key to Omni completion is CTRL−X CTRL−O. Obviously the O stands for Omni here, so that you can remember it easier. Let's use an example for editing C source: { struct foo *p; p−> The cursor is after "p−>". Now type CTRL−X CTRL−O. Vim will offer you a list of alternatives, which are the items that "struct foo" contains. That is quite different from using CTRL−P, which would complete any word, while only members of "struct foo" are valid here. For Omni completion to work you may need to do some setup. At least make sure filetype plugins are enabled. Your vimrc file should contain a line like this: filetype plugin on Or: filetype plugin indent on For C code you need to create a tags file and set the 'tags' option. That is explained |ft−c−omni|. For other filetypes you may need to do something similar, look below |compl−omni−filetypes|. It only works for specific filetypes. Check the value of the 'omnifunc' option to find out if it would work. ============================================================================== *24.4* Repeating an insert If you press CTRL−A, the editor inserts the text you typed the last time you were in Insert mode. Assume, for example, that you have a file that begins with the following: "file.h" /* Main program begins */ You edit this file by inserting "#include " at the beginning of the first line: #include "file.h" /* Main program begins */ .\usr_doc.txt Page 121 You go down to the beginning of the next line using the commands "j^". now start to insert a new "#include" line. So you type: You i CTRL−A The result is as follows: #include "file.h" #include /* Main program begins */ The "#include " was inserted because CTRL−A inserts the text of the previous insert. Now you type "main.h" to finish the line: #include "file.h" #include "main.h" /* Main program begins */ The CTRL−@ command does a CTRL−A and then exits Insert mode. way of doing exactly the same insertion again. That's a quick ============================================================================== *24.5* Copying from another line The CTRL−Y command inserts the character above the cursor. This is useful when you are duplicating a previous line. For example, you have this line of C code: b_array[i]−>s_next = a_array[i]−>s_next; Now you need to type the same line, but with "s_prev" instead of "s_next". Start the new line, and press CTRL−Y 14 times, until you are at the "n" of "next": b_array[i]−>s_next = a_array[i]−>s_next; b_array[i]−>s_ Now you type "prev": b_array[i]−>s_next = a_array[i]−>s_next; b_array[i]−>s_prev Continue pressing CTRL−Y until the following "next": b_array[i]−>s_next = a_array[i]−>s_next; b_array[i]−>s_prev = a_array[i]−>s_ Now type "prev;" to finish it off. The CTRL−E command acts like CTRL−Y except it inserts the character below the cursor. ============================================================================== *24.6* Inserting a register The command CTRL−R {register} inserts the contents of the register. This is useful to avoid having to type a long word. For example, you need to type this: r = VeryLongFunction(a) + VeryLongFunction(b) + VeryLongFunction(c) The function name is defined in a different file. Edit that file and move the cursor on top of the function name there, and yank it into register v: "vyiw "v is the register specification, "yiw" is yank−inner−word. Now edit the file where the new line is to be inserted, and type the first letters: r = .\usr_doc.txt Page 122 Now use CTRL−R v to insert the function name: r = VeryLongFunction You continue to type the characters in between the function name, and use CTRL−R v two times more. You could have done the same with completion. Using a register is useful when there are many words that start with the same characters. If the register contains characters such as or other special characters, they are interpreted as if they had been typed from the keyboard. If you do not want this to happen (you really want the to be inserted in the text), use the command CTRL−R CTRL−R {register}. ============================================================================== *24.7* Abbreviations An abbreviation is a short word that takes the place of a long one. For example, "ad" stands for "advertisement". Vim enables you to type an abbreviation and then will automatically expand it for you. To tell Vim to expand "ad" into "advertisement" every time you insert it, use the following command: :iabbrev ad advertisement Now, when you type "ad", the whole word "advertisement" will be inserted into the text. This is triggered by typing a character that can't be part of a word, for example a space: What Is Entered I saw the a I saw the ad I saw the ad What You See I saw the a I saw the ad I saw the advertisement The expansion doesn't happen when typing just "ad". That allows you to type a word like "add", which will not get expanded. Only whole words are checked for abbreviations. ABBREVIATING SEVERAL WORDS It is possible to define an abbreviation that results in multiple words. example, to define "JB" as "Jack Benny", use the following command: For :iabbrev JB Jack Benny As a programmer, I use two rather unusual abbreviations: :iabbrev #b /**************************************** :iabbrev #e ****************************************/ These are used for creating boxed comments. The comment starts with #b, draws the top line. I then type the comment text and use #e to draw the bottom line. Notice that the #e abbreviation begins with a space. In other words, first two characters are space−star. Usually Vim ignores spaces between abbreviation and the expansion. To avoid that problem, I spell space as characters: <, S, p, a, c, e, >. which the the seven Note: ":iabbrev" is a long word to type. ":iab" works just as well. That's abbreviating the abbreviate command! FIXING TYPING MISTAKES It's very common to make the same typing mistake every time. For example, typing "teh" instead of "the". You can fix this with an abbreviation: :abbreviate teh the .\usr_doc.txt Page 123 You can add a whole list of these. mistake. Add one each time you discover a common LISTING ABBREVIATIONS The ":abbreviate" command lists the abbreviations: :abbreviate i #e i #b i JB i ad ! teh ****************************************/ /**************************************** Jack Benny advertisement the The "i" in the first column indicates Insert mode. These abbreviations are only active in Insert mode. Other possible characters are: c ! Command−line mode both Insert and Command−line mode :cabbrev :abbreviate Since abbreviations are not often useful in Command−line mode, you will mostly use the ":iabbrev" command. That avoids, for example, that "ad" gets expanded when typing a command like: :edit ad DELETING ABBREVIATIONS To get rid of an abbreviation, use the ":unabbreviate" command. have the following abbreviation: Suppose you :abbreviate @f fresh You can remove it with this command: :unabbreviate @f While you type this, you will notice that @f is expanded to "fresh". worry about this, Vim understands it anyway (except when you have an abbreviation for "fresh", but that's very unlikely). To remove all the abbreviations: Don't :abclear ":unabbreviate" and ":abclear" also come in the variants for Insert mode (":iunabbreviate and ":iabclear") and Command−line mode (":cunabbreviate" and ":cabclear"). REMAPPING ABBREVIATIONS There is one thing to watch out for when defining an abbreviation: The resulting string should not be mapped. For example: :abbreviate @a adder :imap dd disk−door When you now type @a, you will get "adisk−doorer". That's not what you want. To avoid this, use the ":noreabbrev" command. It does the same as ":abbreviate", but avoids that the resulting string is used for mappings: :noreabbrev @a adder Fortunately, it's unlikely that the result of an abbreviation is mapped. ============================================================================== *24.8* Entering special characters The CTRL−V command is used to insert the next character literally. In other .\usr_doc.txt Page 124 words, any special meaning the character has, it will be ignored. example: For CTRL−V Inserts an escape character. Thus you don't leave Insert mode. the space after CTRL−V, it's only to make this easier to read). (Don't type Note: On MS−Windows CTRL−V is used to paste text. Use CTRL−Q instead of CTRL−V. On Unix, on the other hand, CTRL−Q does not work on some terminals, because it has a special meaning. You can also use the command CTRL−V {digits} to insert a character with the decimal number {digits}. For example, the character number 127 is the