Vi survival guide

319 views
226 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
319
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Vi survival guide

  1. 1. http://www.nuxified.org/vi_survival_guidevi survival guide 18. May 20061. IntroductionIf you are trying to work at a command line in pretty much The students discovered they could use terminal escape codesany Operating System, no matter if a Linux such as Ubuntu or so that the terminal moved the cursor to the bottom, and theyFedora Core, or another UNIX-like system like Mac OS X or dubbed it "open mode." Short commands could be typed in.FreeBSD; or even if in Microsoft Windows, you will most def- There were later derivatives of the ed tool called em and en;initely need a text editor sooner or later. If you are using a students were experimenting with reprogramming each oneUNIX-like system, like GNU/Linux variants, there are many and borrowing each others features. Eventually the mosttext editors that may or may not be installed. Luckily there is popular became Bills project, vi. When the VAX came about,one de-facto standard: vi is included in almost every GNU/ the terminal escape codes became standardized as VT100Linux or UNIX distribution. "Vi" is a truncation of the word (Vax Terminal 100). VT100 carried over into the BSD Unix"visual" and has (contrary to popular belief) nothing to do with and is still there today, implemented, for example, in thethe Roman number six. Many people are not fond of vi, but Linux console and xterm. These codes were utilized inthey are often forced into using it when it is the only known moving the cursor around in the editor; in scrolling sections;option. You may prefer easier editors like gedit (Gnome), kate in blocking off certain sections so that they do not scroll; and(KDE), emacs or ne (command line) -- but they may not be in other cursor movements. What is most important to notepresent when working at a given command line. Therefore it is about vis history is that there was very limited memory andbest to know the basics of vi and to understand it a little better. disk space, so commands seemed to be more efficient if theyWhat you will learn in this guide is basic survival in vi. Unlike were short keystrokes, rather than typing out words. Menuswhat you may have heard regarding the invention of C, the vi and even a mouse werent invented yet at XEROX PARC center,editor was not an idea of some kind of sick joke. -- It was so short keystroke commands seemed to fit the ticket. Danfor real and it served a real purpose. -- I am writing this in vi. Bricklins Visicalc program would later hinge off of that aspect and use keystrokes which brought up menus -- an approachVi is old, 1976 to be exact -- only 6 years after 1970-01-01, that led to the success of Lotus 1-2-3. So short keystrokes itwhich is the second number zero, the Big Bang, the Christmas became. Each of us who use Linux should get to know how toDay of UNIX system clocks. In the age of information and survive in using these keystrokes. Like many things in Unixthe internet, 30 years is a century. -- Remembering vis age and Linux, when enough people know about a command andmay help you accept it, if you do not particularly like vi. depend on it, it becomes one of the defacto items that, likeMany people, however, do like that they can memorize the vi it or leave it, just have to be rolled in, or people will complain.keystrokes and feel at home with vi for quick tasks; and theydo like vis tiny footprint in disk space and RAM. They like it 2. Basic crash courseboth as the old reliable standard and as a powerful editing Lets start with the most basic vi knowledge -- what you willtool as well. need to use vi when vi is the only choice. Vi is different from most editors in that it has several so-called « modes ». When viVi has an interesting history. It was created in 1976 in a starts up, it is in NORMAL mode where every key has someBerkeley University dorm room at Evans Hall by Bill Joy and special function. Pressing x, for example, deletes the characterfriends. Joy was the one who fleshed out most of it, using the under the cursor. Beginners will start off preferring vis INSERTPascal language. He designed it for a version of Unix he was mode: you enter it by pressing i from NORMAL mode. Hereworking on at Berkeley called BSD Unix (Berkeley Software letters are letters, backspace is backspace etc -- like in any edi-Distribution Unix: the base for such modern Unices as the popular tor. This is a safe mode for beginners, since (unlike in NORMALFreeBSD). Bill Joy eventually moved on to Sun Microsystems mode) ordinary keys dont do non-ordinary things. When youas one of its original founding members, and he has since have made the changes you want, switch back to NORMALmoved on to other projects. Before Bill Joy wrote vi, students mode by pressing <ESC>. You can always return to INSERTat the university were using an editor called ed. The ed tool, mode by pressing i. -- You will now want to do some specialstill as widespread as vi, unfortunately, is much harder to use. things such as saving. Here are commands you should know:Vi_Survival_Guide page 1 of 6
  2. 2. :w <ENTER> write file [save to disk] 3.1.1. Movement :wq <ENTER> write file and quit Even in NORMAL mode, you can use the arrow keys, but that :w FILENAME <ENTER> write file as FILENAME means moving your hand from the letters to the arrow keys. :e FILENAME <ENTER> edit file FILENAME On laptop keyboards, it is especially inconvienient. Instead, vi offers the following movement keys: :q <ENTER> quit from vi editor :q! <ENTER> quit witdout saving k up3. Other Modes h left l rightBy now you should be able to survive in vi for a quick config j downfile edit, code hack or simple ASCII art. But vi is a lot morethan insert mode. These keys are under a touch typists right hand. The keys can3.1. A guide to NORMAL mode be memorized in different ways. h and l are the furthest left and right (respectively) in the set of four. The letter j looks likeNormal mode is, as you may have guessed, the vi mode. You its pointing downward. The j key often has a little stud orcan do almost anything from inside NORMAL mode. bump at the bottom (to locate the key by feel when touch typing).Here are some more movement keys. -- Some are especially useful combined with other commands (see next section): Inside the line $ moves to the end of the line 0 moves to the beginning of the line ^ moves to the first non-whitespace character -- i.e. to the beginning of an indented line. Movement via words (where a word is a sequence of alphanumeric OR punctuation signs) w next word e end of current word b previous word Movement via words (where a word is a sequence of non-blank characters) W next word E end of current word B previous word Other Jumps H jump to top of screen L jump to bottom of screen { jump to previous paragraph } jump to next paragraph fx jump to next occurence of character x (where x is any character, of course) tx jump right before next occurence of character x (till x) (again, x in anything) Fx jump to previous occurence of character x (again, x in anything) Tx jump right after previous occurence of character x (back till x) (again, x in anything) G jump to EOF (End of file) LINE G jump to line number LINEVi_Survival_Guide page 2 of 6
  3. 3. 3.1.2. Modifying, Deleting, Copying, PastingObviously, you are in vi to edit text. You could also be in vi to hear beeps when you press some wierd keys, butthen you probably wouldnt be reading a guide to vi. You have already learned about INSERT mode, but there ismore to it that just i ! To "just" get into INSERT mode, you can use the following commands:i places you in INSERT mode before the current character.I places you in INSERT mode at the beginning of the line. Same as ^i places you in INSERT mode after the current character. Same as i <RIGHT-ARROW>a (or li when not at the end of the line)A places you in INSERT mode at the end of the line. Same as $ao places you in INSERT mode in a new line below the current one. Same as $i <ENTER>O places you in INSERT mode in a new line above the current one. Same as kovi also offers simple command for single-character deleting and editing:x delete character under cursor. like <DEL> in INSERT mode.X deletes the previous character. like Backspace in INSERT mode.rx replace the character under the cursor with character x (where x is any character)Now lets go over to some more larger-scale editing in NORMAL mode, as you seriously dont want to use x orX to delete a paragraph of text, for example. This is also [where] the movement commands from section 3.1.1.become really useful.d{motion} delete all text up to the destination of movement {motion}c{motion} delete all text up to the destination of movement {motion} and enter INSERT mode (to change the text)y{motion} copy (yank in vi-speak) all text up to the destination of movement {motion} p paste (or put) the last deleted, changed or yanked text after the current position P paste (or put) the last deleted, changed or yanked text before the current positionFor better comprehension, a few examples are in order.dw delete up to the beginning of the next word{c} change current paragraphywP duplicate wordThere are also a few special cases, namely:dd deleted current linecc change current lineyy yank current lineWhen you delete, change or yank a line [i.e. copy it: «yank » is a mnemonic for the y key], the p and P keys alsooperate line-wise: p places the yanked line after the current line, while P places it before the current line.Vi_Survival_Guide page 3 of 6
  4. 4. 3.1.3. Repetition features in vi: how to avoid doing mindlessly repetitive tasks with special keystrokes.[Mindless] repetition [of editing tasks] is annoying and senseless. Vi has some features to make editing [jobs]easier in this respect. First of all comes the command « . » (yes, thats a period.). The period key repeats the lastcommand. If, for instance, your last command was dd, then tapping period . deletes another [one more] line.Counts are another very useful feature. It lets you repeat a command a specific number of times. The syntax is:{number}{command} do {command} {number} of times.Counts also works for motions that are part of a command. A few examples:10j move 10 lines down3yy yank three linesc3w change 3 wordsNow for some commands that every editor supports, including Notepad: u undo last command (including INSERT mode sessions)<Ctrl+r> redo last undone commandUnlike with Notepad, vi supports undo and re-do multiple times.3.2. Ex mode"Ex mode" is a command-line-like mode. In ex mode you can type certain longer commands, which are thenexecuted by typing <ENTER>. There are several ways to use ex mode (see below). Single ex commands are pre-ceded by a colon : . A series of ex commands may be done by entering the ex mode [inside vis NORMAL mode].Note: certain vi clones, vile in particular, support some common vi ex modes without supporting certain others.]:{ex-mode command} execute one ex mode command gQ enter ex modeSound familiar? -- The save, edit and quit commands in section 2 are actually ex mode commands. Here aresome important ex mode commands (colon itself not shown). The parts below inside square brackets are optional.w[rite] [FILENAME] write file to FILENAME (if given)w[rite]! FILENAME write file to FILENAME, overwriting if it exists. e[dit] FILENAME edit FILENAME e[dit]! FILENAME edit FILENAME without saving q[uit] quit q[uit]! quit without saving ! COMMAND execute shell command COMMAND vi[sual] exit ex modeVi_Survival_Guide page 4 of 6
  5. 5. 4. Searching and replacing s/foo/bar/ replace the first occurence of foo on the current line with barSearching and replacing are two very important features replace all occurences of foo s/foo/bar/gwhen editing text files; just think of how easy it is to lose a on the current line with barline in a large config file or on an enormous screen. Ill perform s/foo/bar/[g] on every %s/foo/bar/[g] line in the file.start with the simpler of the two: searching. The commands perform s/foo/bar/[g] on everyare issued in NORMAL mode. X,Ys/foo/bar/ line between line # X and # Y. search (forwards) for strings that match APPENDIX. VIM -- Vi IMproved /REGEX the regular expression /REGEX/. search for strings that match the regular There are many vi clones and dereviatives out there. In ?REGEX fact, when you open "vi", you will probably not see the expression /REGEX/ , but go backwards. original vi, but a clone like nvi or vim [or vile]. VIM is n go to the next occurence in the search process probably by far the most advanced clone. It has numerous N go to the previous occurence [ last one back ] features that are interesting for programmers, among other people. I will explain below two features which are, in my eyes, the most interesting additions found in Vim. (SyntaxThis may sound dreadfully complicated to you. You may highlighting in Vim is enabled with the ex command syntax on:)be thinking along the lines, "Regular expressions ... Huh?". Vim has (1) VISUAL MODE and (2) MULTIPLE WINDOW capability.Well, dont panic. -- Regular expressions are a standardizedway of expressing patterns to search for. -- The syntax is APPENDIX.1. VISUAL modenot easy to understand, and it is beyond the scope of this doc-ument. So that you get the idea, Ill give a few examples: Yes, another mode. In this Vim mode, you can select text[0-9]{1,3} matches any one- to three-digit number, and and perform operations which usually take a movement asjoe matches the three letters joe (lowercase) , and nothing argument. For example: selecting text and pressing d willelse. If youre not dealing with special characters, you can delete the text. As usual, you enter VISUAL mode fromforget about regex [ for the time being ] . NORMAL mode; but unlike the other modes, VISUAL has multiple sub-modes (three of them).Now to replacing. -- The syntax for replacing is inheritedfrom [ s ]ed , [ from i.e. programs ed and sed ] . These are ex- v Enter normal VISUAL modemode commands and like before use regular expressions: V Enter VISUAL LINE modethis time with bracket substitution, since it is replacing. <Ctrl+v> Enter VISUAL BLOCK mode---------------------------------------------------------------------------------normal VISUAL modeThis is pretty much like selecting in most graphical editors: you select character-wise. Let me show you an example:Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:VISUAL LINE modeThis is a little bit niftier. It selects line-wise, not character-wise. Doing d on VISUAL LINE selected text is likedoing dd on all the lines.Vi_Survival_Guide page 5 of 6
  6. 6. Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:VISUAL BLOCK modeThis is the niftiest of selection modes. You select blocks (duh). I cannot convey this better than with an example --Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is: Some text text text just to show the readers what VISUAL mode is all about. As I said this is:APPENDIX.2. Multiple WindowsVim has support for splitting the screen into multiple windows (but not the overlapping windows you know from popularGUIs). Vims multiple windows are parts of a split screen (like on GNU Emacs and GNU screen ). With vims multiple win-dows you can, for example, do editing in one part of the screen while you are looking at a different file (or at a diff-erent part of the same file) at the same time [in i.e. a single instance of Vim]. Try out vim to see what multiple windowsare about! Here I will list only the most important window-related commands. Use the ex command help usr_08in vim to get to the relevant section in the on-line [help-] docs [ bundled with Vim ]. [ Vi-clone vile has multiple windows.]Window-related ex commands split horizontally split the current window and display the current buffer (=file) in the new window vsplit vertically split the current window and display the current buffer in the new window new horizontally split the current window and create a new buffer in the new window. vnew vertically split the current window and create a new buffer in the new window. only destroy all other windows. only! destroy all other windows, discarding unsaved changes q destroy the current window. qa destroy all windows (exiting vim) qa! destroy all windows (exiting vim), discarding unsaved changesWindow-related NORMAL commands<ctrl+w> h move one window left<ctrl+w> j move one window down<ctrl+w> k move one window up<ctrl+w> l move one window rightFinal WordsAs you have seen, vi is a complicated, unusual editor with many annoyances to the normal user. Surprisingly, the vi editingmodel has greatly improved productivity of many. If you do a lot of editing (e.g. programming), vi can increase your efficiency.If you do decide seriously to learn vi or vim, try to use vi exclusively, at least for a time. And, above all, stay away fromINSERT mode as much as you can. -- Over-using INSERT mode wont help in the slightest if you want to really use vi.Vi_Survival_Guide page 6 of 6

×