Originally Published: Thursday, 17 August 2000 Author: Jim Jones
Published to: learn_articles_firststep/General Page: 1/1 - [Printable]

Easing Into Editors: Vim

Most work done in Linux is facilitated through the use of one of its many editors. You could be writing a quick note, trying to get that darned X windows configuration file tweaked just so, or programming the next great Open Source widget. This series will take you through the fundamentals of working with files in the myriad of editors available to the Linux user. This first installment will deal with one of the "standard" editors found on most Linux systems, vim.

   Page 1 of 1  

Introduction:

When you get down to brass tacks, most work done in Linux is facilitated through the use of one of its many editors. You could be writing a quick note, trying to get that darned X windows configuration file tweaked just so, or programming the next great Open Source widget. All of it done, in one way or another in one of Linux's many editors. For added complexity, you are probably new to Linux. You haven't written notes outside of post-its, much less having any idea what an "X windows configuration file" might be (it tells Linux how to set up the X windows system, a Graphical User Interface or GUI, for the display hardware of the computer Linux is running on), nor have you programmed anything other than your coffee maker. That's all right. This series will take you through the fundamentals of working with files in the myriad of editors available to the Linux user. This first installment will deal with one of the "standard" editors found on most Linux systems, vim.

From There to Here:

First, a little history. The vi editor (precursor to clones like elvis, ni and, of course, vim) sprang, in very Greek fashion, from the head of the standard Unix editor of the time called ex and its precursor, ed. While no one ever claimed that Unix or Unix-like text editors were non-esoteric, vim's precursors were difficult to use with even that in mind. The ed and ex editors were line-oriented editors (allowing the user to only see whichever line they were currently working with). This made it difficult to edit a line in context with its surroundings. The ex editors advantage was that it had a visual display mode that you could get to by giving the ex editor the vi command. This became such a popular feature of the editor that people would set it so that ex started up in "visual mode" by default.

The vim editor is one of the most popular clones of the original vi editor. Vim stands for "vi improved". Vim's biggest improvement over its ancestors is its support for color syntax highlighting of program code. This feature improves programming productivity by giving visual cues to a word or command's significance with respect to the language being used by the programmer. Other people (like myself, for instance) like vim because it is less picky about the the current mode it is in (more on this later) when editing a file.

However, even with these improvements, it should be noted that vim is not particularly well suited for text layout or formatting. Its sole job is to work with text in a format independent way and it does a darn good job at it. Thus making it one of the most popular editors (and a Unix/Linux standard) that is found on virtually every system out in the known world.

A Few Words About Modes:

The vim editor operates in one of three modes at any one time. Each mode, including input mode, command mode, and status line mode (aka last line mode), is used for specific operations within the editor. In vim, command mode is used to issue short commands (of 1 to a couple characters each) which allow you to manipulate the text or editor environment in a number of ways. Input mode, is used for inputting text into the editor's work buffer (basically the "workspace" of vim before it is committed to the hard drive through a "save" operation). Finally, status line mode is used for issuing longer, more complex commands to the editor. These commands are echoed back to the user in the status line of the editor (demarcated by a ":" at the bottom of the screen) and are executed when the user hits the enter key.

Switching between modes is relatively easy and quite necessary to make use of the full complement of vim's tools and abilities. To change to command mode, you generally just have to hit the Esc key. The only visual cue that you are in command mode is that there is no visual cue (strange, I know, but the other modes do have cues which end up making "nothing" a telling sign in and of itself). You can get into input mode by entering one of the editing commands (sounds easy, huh? Relax, its not that bad). Three of the most common editing commands include i and I, a and A, and o and O (more on this later, of course). You generally know you are in input mode because -- INSERT -- is printed in the status line across the bottom of the editor. Finally, getting into status line mode is a two step process. Hit the Esc Key (basically enter command line mode) and then enter a colon (:). You know you are in status line mode because your actions are restricted to a single line along the bottom of the editor that is preceded by a :.

I think that covers the basics and the background. Now, let's get down to the nitty gritty.

Starting the vim Editor:

First, let's start up vim in a terminal session. The syntax for creating a file (or working with a file already in existence) is:

$ vim filename

For our purposes, we will be working with a file name fstep.vim, so we type:

$ vim fstep.vim

This will open the vim editor for working with the fstep.vim file. You should see something that looks something like this: | | ~ ~ ~ ...cut for the sake of space... ~ ~ ~ "fstep.vim" [New File] 0,0-1 All Don't worry about the tildes (~). They just mark the area past the end of the file and will be "pushed" down as you enter text into the work buffer.

Other vim startup options include: starting vim in read only mode ($ vim -R fstep.vim), which is useful for viewing long configuration files without the fear of accidentally changing them; starting it in recovery mode ($ vim -r fstep.vim) which recovers recent edits after a crash; starting it up with the cursor placed at the end of the file ($ vim + fstep.vim); and starting vim at a line number ($ vim +n fstep.vim) or at a particular word or phrase ($ vim +/pattern fstep.vim).

Now let's look at adding some text to fstep.vim.

Adding Text in vim:

Let's add the party line definition of Linux to our file. We'll borrow the initial definition from the FirstStep section of Linux.com (http://www.linux.com/firststep/#whatislinux). In case you haven't seen it, here's what it says:

Linux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share. Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development.

We can do this by entering input mode via the i, a, or o commands. The i edit command opens input mode before the current cursor position. This is handy for inserting new text before text previously in your file. The a edit command opens input mode after the current cursor position. This can be handy for adding text after text previously in your file. Finally, the o edit command opens input mode in a new line above the current cursor position. Generally you will use mostly the i and a commands for inputting text. It should also be noted that the uppercase brethren of these commands, I, A, and O open input mode before the beginning, after the end or above the current line the cursor is positioned on.

To add the Linux definition to fstep.vim, type i and then begin entering the definition. You could type it out by hand or just "mark" (or "highlight") the definition above and then use the X windows mouse paste operation (use the middle mouse button on a three button mouse or click the left and right mouse buttons at the same time) in the window that has your vim session going. You should end up with something that looks a little like this: Linux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share. Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development.| | ~ ~ ~ ...cut for the sake of space... ~ ~ ~ -- INSERT -- See, that wasn't so hard. Now, before we go any further, let's commit this change to the hard drive by issuing a save or write command to the editor. First, you need to get into status line mode (Esc Key then :). From there, type w to commit the work buffer to disk. While we are at it, other save operations include saving the contents of the work buffer and quitting the editor. In true Linux form, many variations exist for this operation, so here goes. You could try ZZ, x or wq. Don't let it be said that Linux stifles your creativity in this respect. Other save options allow you to save all, or part, of the file to a new file name. The 10,20w newfile command will write the contents of lines 10 through 20 (or any other set you want) to a new file. The 10,20w>> filename command will append the contents of lines 10 through 20 (or any other set you want) to a file that already exists. Finally, the more often used w newfile saves the entire contents of the work buffer to a new file.

We've done pretty much so far, but now we need to cover some of the mechanics that you will use to actually edit a file. Editing, of course, requires being able to move to the trouble spot and excise or repair whatever "damage" exists (very much like a surgeon, to be sure). In the next section we will cover cursor movement.

Moving the Cursor in vim:

Basic cursor movement in vim is pretty straight forward. While in command mode (press the Esc key a couple times if you are not sure), you can move anywhere in your file by just using the UP, DOWN, LEFT, and RIGHT arrow keys on the keyboard. If, for some reason you do not have these keys available to you (perhaps they were removed by a sadistic office manager), vim comes to your aid with directional key mappings for left (the h key), for down (the j key), for up (the k key) and for right (the l key). In most cases, especially for small edits on relatively small documents, this form of navigation will suit you fine. However, larger documents may require a bit more involvement.

Larger documents may require extensive editing, for which movements of one space at a time simply won't do. For these, we require a broader set of movement tools. Need I say that vim shall provide? Vim has conventions for moving forward or backward one word at a time (w and W, respectively), forward and backward one sentence at a time ( ) and (, respectively) and the same for paragraphs ( } and {, respectively. It also maintains conventions for moving ahead and back one screen of information at a time (Ctrl + F and Ctrl + B, respectively), one half screen at at time (Ctrl + D and Ctrl + U, respectively) and to a particular text pattern forward or backward from the cursor's position (/pattern and ?pattern, respectively). Again, there are many more options, but these few should serve you in most situations until you learn all the other commands.

Let's cover a few commands for cutting, pasting and removing text and then we'll apply what we've learned to fstep.vim.

Some Editing Commands for vim:

Most anyone who has worked with any processor is aware that copying and pasting text is a pretty standard feature across applications and some operating systems. Many know that the standard keyboard shortcut for copying is Ctrl + C and for pasting is Ctrl + V. Unfortunately, that is not how it is with vim. In fact, vim doesn't even use the same terminology. That's okay, though, because it the commands accomplish the same thing and are easy to use and remember once you learn them.

To "copy" text in vim, you perform a "yank" command. Vim's version of pasting is achieved through a "put" command. You can yank the current line that the cursor is placed on by typing yy while in command mode. This "copies" the current line into a memory buffer for later use. Variations of the yank command include yanking a word (yw), a sentence (y)) and a paragraph (y}) at a time. You can even yank all the text between the current position of a cursor to a specific text pattern (y/pattern). If that doesn't blow your mind, I am not sure what will.

To "paste" your "yanked" text (this is starting to sound odd), simply move your cursor to the point you want to "put" the new text and type p. Being flexible, vim also lets you "put" the text before the cursor's position by typing P instead.

To get rid of text, vim offers a host of tools almost identical in nature to the yank command set. To delete text in vim, you use several variations of the d command. You can delet the current line you are working with by typing dd while in command mode. Other variations of delete allow you to delete a word (dw) at a time, a sentence (d)) at a time and a paragraph (d}) at a time. You can even delete all the text between the current position of a cursor to a specific text pattern (d/pattern), just like in yank. For added precision, delete even allows you to delete the next number of characters that you specify by typing dnumber-of-characters and then hitting the Enter key. Finally, another useful delete command can be had by typing x, which deletes the character currently under the cursor.

Now, let's apply some what we've learned

An Example in vim:

We're going to change the first line of our example into two seperate sentences (this is already sounding like a standardized test). When we last left fstep.vim, it looked like this: Linux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share. Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development.| | ~ ~ ~ ...cut for the sake of space... ~ ~ ~ -- INSERT -- You should notice two things. First, we are still in input mode as denoted by the -- INSERT -- tag in the status line at the bottom of the editor's workspace. Second, the cursor (denoted in the example by | |)is at the end of the paragraph.

In order to edit the first sentence we are going to have to get the cursor up there. First, hit the Esc key to exit input mode and enter command mode. You're screen should now look a little like this: Linux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share. Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development.| | ~ ~ ~ ...cut for the sake of space... ~ ~ ~ 5,13 All Now, we need to move the cursor (| |) to the beginning of the paragraph by typing {. You should now see the cursor over the "L" in "Linux" like so: |L|inux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share. Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development. ~ ~ ~ ...cut for the sake of space... ~ ~ ~ 5,13 All Now use the arrow keys (or other movement commands we've discussed) to move the cursor over both commas in this sentence and delete them with the x command. Using your insert and other commands in conjunction change:

Linux, the most popular Unix variant for PCs, is the only operating system not from Microsoft that is gaining significant market share.

into

Linux is the most popular Unix variant for PCs. It is the only operating system not from Microsoft that is gaining significant market share.

When you are all done it should look something like this: Linux is the most popular Unix variant for PCs. It is the only operating system not from Microsoft that is gaining significant market share.Created by Linus Torvalds and developed collaboratively over the Internet, Linux is the great success story of Open Source software development. ~ ~ ~ ...cut for the sake of space... ~ ~ ~ 5,13 All You can quit and save your changes by typing :wq.

That's it for now. I hope you will give vim a chance in your future explorations with Linux. It is handy to know since it (or one of its clones) is installed by default on almost every Linux and Unix system out there and can come in handy in a pinch. While this is by no means an exhaustive look at the editor, it should give you enough commands to get you started and keep you from pulling your hair out. For further information on vim you can type :help from inside the editor or check out the Vim Color Editor HOW-TO. The best advice I can give to mastering vim is to go slowly and keep at it. If you learn a little something new each time you use it, mastery will be just around the corner.

Raised by wolves in the northern forests of Germany during his father's stint in the US army, Jim decided to throw off the "easy life" of a lean and mean wild child in order to explore the theoretical possibilities of actually graduating college with a computer science/art degree and no money. Having survived that adventure by the skin of his loans, he is now slowly working towards his lifetime goal of becoming one heck of a geek. Writing for Linux.com is the next step in that evolution. Email: cascadefx@linux.com





   Page 1 of 1