<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Plan Zero Blog &#187; Tutorials</title>
	<atom:link href="http://blog.planzero.org/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.planzero.org</link>
	<description>Mind dump</description>
	<lastBuildDate>Sat, 05 Sep 2009 17:29:18 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>An introduction to the vi editor</title>
		<link>http://blog.planzero.org/2009/08/an-introduction-to-the-vi-editor/</link>
		<comments>http://blog.planzero.org/2009/08/an-introduction-to-the-vi-editor/#comments</comments>
		<pubDate>Wed, 26 Aug 2009 18:34:37 +0000</pubDate>
		<dc:creator>Plan Zero</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://blog.planzero.org/?p=231</guid>
		<description><![CDATA[<p>Back in 2006 I wrote an article on the vi text editor. While I&#8217;m in the process of rearranging my site, the time seems right to republish the article. Read and enjoy!</p>
<h3>The history of vi</h3>
<p>The vi text editor originated at the University of California in Berkeley. Created by Bill Joy in 1976 as a replacement for the frustrating ed line&#8230;</p>]]></description>
			<content:encoded><![CDATA[<p>Back in 2006 I wrote an article on the vi text editor. While I&#8217;m in the process of rearranging my site, the time seems right to republish the article. Read and enjoy!</p>
<h3>The history of vi</h3>
<p>The vi text editor originated at the University of California in Berkeley. Created by Bill Joy in 1976 as a replacement for the frustrating ed line editor, it was designed to be usable over a 300 or 1200 baud modem, and as such quickly evolved into a powerful yet light text editing application, cramming functionality into every keystroke.</p>
<p>In a 1999 <a href="http://www.theregister.co.uk/2003/09/11/bill_joys_greatest_gift/">interview</a> talking about what inspired him to write vi, Bill Joy explains:</p>
<blockquote><p>… we got frustrated with the editor we were using which was named ed. ed is certainly frustrating. We got this code from a guy named George Coulouris … called em &#8211; Editor for Mortals &#8211; since only immortals could use ed to do anything. So we modified em and created en. I don&#8217;t know if there was an eo or an ep but finally there was ex. [laughter] I remember en but I don&#8217;t know how it got to ex. So I had a terminal at home and a 300 baud modem so the cursor could move around and I just stayed up all night for a few months and wrote vi.</p></blockquote>
<h3>Why vi?</h3>
<p>Despite its age, vi is still an important tool today. This is demonstrated by the fact that every unix/linux distribution released over the last twenty years is likely to have a copy installed by default. Since the original release of vi, many derivatives have been written (such as vim, vile and elvis), with usability and functionality added along the way. Because of this, vi is probably one of the most evolved and stable text editors in the world.</p>
<p>Many of the more recent vi clones are also intelligent enough to know about the type of document you are editing, and will help you out by automatically indenting your text (in the case of HTML or C, for example) or by highlighting the syntax to make your work much clearer. In the great Unix tradition, features that bug you or help you can be turned on and off at your preference, and spending a few minutes customising vi to your liking can save you hours of work in the long run.</p>
<h3>Operation modes</h3>
<p>Most common text editors have just one mode, and use a menu system or multiple key combinations to allow you to perform functions on your document, such as saving or searching and replacing text. The vi editor has two modes: <em>insert mode</em>, in which text is edited and entered, and <em>command mode</em>, where editing functions and document navigation take place. If this seems strange, don&#8217;t let it put you off; you&#8217;ll get used to the concept fairly quickly!</p>
<p>In <em>command mode</em>, you can tell vi to use any number of functions, from pasting text to quitting or opening up a shell. Most commands in vi are short, and many are single letters. Command mode is also where you enter <em>insert mode</em>. In <em>insert mode</em>, you can only enter text. Nothing more, with the exception of using the backspace key to go back and correct mistakes in the newly entered text. In <em>insert mode</em> you cannot copy and paste, search or save your document.</p>
<p>You will find yourself using both modes extensively in vi, and once you get the hang of using the two modes properly, you will see that you can edit documents much faster than you ever could using your current text editor. Personally, I use vi for almost all of my console-based text editing and coding, including to write this tutorial :-)</p>
<h3>Using modes and adding text</h3>
<p>Okay, enough theory, on to the useful stuff!</p>
<p>When you first fire up vi (by opening up a shell and typing <code>vi</code>), you will be presented with a screen that looks something like this:</p>
<p><code>~<br />
~<br />
~<br />
~<br />
~<br />
~</code></p>
<p>Each tilde represents a line with no content. The tildes are used to distinguish between a line with no content whatsoever, and a blank line; i.e. one with a newline character (what you get when you press<code>enter</code>) but no visible text. When vi first starts up, you will be in <em>command mode</em>. It is important to note that commands in vi are case sensitive &#8211; a lower case i does not do the same thing as an upper case I at all!</p>
<p>To enter some text into the document, start off by typing <code>i</code>, which will put you into <em>insert mode</em>. Everything that you type from now on will be taken as text to be entered into the document. Try typing a few words and practice using the backspace key to modify and type over some of the text.</p>
<p>From <em>insert mode</em>, pressing the escape key will put you back into <em>command mode</em>. Play around with changing modes a few times until you get the hang of it. Now, to quit vi, make sure that you are in <em>command mode</em>, then type <code>:q</code> (colon q) and press enter. This probably won&#8217;t quit as expected, but will give you a warning about the document being unsaved. As we don&#8217;t want to save this document, we can force vi to enact a command without warnings by using the force command. Try typing: <code>:q!</code> (colon q exclamation mark) and pressing enter. The vi editor should now oblige and drop you back to the shell.</p>
<h3>Navigating around</h3>
<p>For those who are used to using the mouse to navigate around documents, you may find navigation in vi a little tricky at first, however the power of the vi navigation commands far outweigh the advantages of using a mouse. To try out some of the navigation methods, it may be best to open a file which already has some content, or to create one to mess around with. You can open an existing file by running <code>vi [filename]</code>, or just fire up vi, enter <em>insert mode</em> and type a few lines of random words.</p>
<p>The navigation keys in vi are as follows:</p>
<ul>
<li>h &#8211; left</li>
<li>j &#8211; down</li>
<li>k &#8211; up</li>
<li>l &#8211; right</li>
</ul>
<p>Easy to remember, huh? Although most modern clones of vi will allow you to use the arrow keys to move around your document in addition to the keys above, it is always good to learn the &#8220;proper&#8221; navigation keys just in case you are stuck using a version of vi that doesn&#8217;t support these more familiar keys. The other advantage of learning and using the keys above is that you spend less time moving your hands away from the centre of the keyboard, thus increasing typing speed. Give it a go!</p>
<p>One of the more useful navigation methods in vi is the search function. When in <em>command mode</em>, simply type <code>/<search pattern></code> (forward slash, then the text you wish to search for) then enter and you will be taken directly to the first match forwards from your current position. To repeat the search forwards, simply type <code>/</code> and hit enter. Searching backwards is also easy; type <code>?</code> instead of <code>/</code> in either of the previous commands. Note that all searches are case sensitive by default; if you want to turn this off, try <code>:set ic</code> before searching.</p>
<p>Something to note when using this search method is that certain characters have special meaning to vi. For example, the full stop character . means match any character. This means that when performing the search /192.168, the string 192.168.1.125 will be matched, but so will 1920168. You can escape these special characters by using a back slash (\). So, to find our first pattern and not the second, we would use /192\.168. For more information, search for regular expressions on <a href="http://en.wikipedia.org/wiki/Regular_expression">Wikipedia</a> or check out Starmerj&#8217;s indispensable <a href="http://web.mit.edu/semenko/Public/regexp.html">RegExp Crib Sheet</a>.</p>
<h3>Editing text</h3>
<p>To recap, when you first start up vi you are put into <em>command mode</em>. From here, you can enter <em>insert mode</em> by typing <code>i</code> and typing away to your heart&#8217;s content. But are there other ways of entering <em>insert mode</em>? And what about editing what you&#8217;ve written? From <em>command mode</em>, you have many options.</p>
<p>As we have already found out, typing <code>i</code> will put us into <em>insert mode</em> at the cursor position. There are also a few other ways of entering <em>insert mode</em>. For example, if you type <code>I</code>, you will enter <em>insert mode</em> at the beginning of the current line. By typing a you will start from the character to the right of the cursor, and by typing A you will start editing at the end of the current line. You can also open an blank line for text below the cursor by typing <code>o</code> and above the cursor by typing <code>O</code>. Give it a try!</p>
<p>You can delete text character by character by placing the cursor in front of the text to be deleted and typing <code>x</code>. To delete text in the other direction (similar to using the backspace key), type <code>X</code>. You can delete a whole line by typing dd, whilst typing dw will delete the next word, and the <code>D</code> command will delete from the cursor to the end of the line.</p>
<p>Deleted too much text? No problem! Just type <code>u</code> to undo the last action, or <code>U</code> to restore the current line. Some clones of vi support multiple levels of undo, so typing <code>u</code> multiple times will take you further back in the history of the document. Make sure you are familiar with the working of these undelete commands, as you will find yourself using them often!</p>
<h3>Copying and pasting</h3>
<p>The vi editor has advanced copy and paste support. Should you need the functionality, vi also makes available multiple named buffers for performing complex copy and paste actions, such as swapping segments of code around without the need to go to and fro multiple times.</p>
<p>As you may have guessed, there are several commands for copying text with vi. Typing <code>yw</code> will copy a word, <code>yy</code> will copy the current line, and <code>y<motion></code> will copy from the cursor to the target motion. For example, to copy from the cursor position to the word <em>blue</em> further down the document, you can type <code>y/blue</code> and press enter, which uses the search syntax as described in the Navigating Around section to move the cursor to its final position. You can use almost any navigation command here!</p>
<p>Pasting the copied text couldn&#8217;t be easier; simply type <code>p</code> to place the text before the cursor, and <code>P</code> to place the text after the cursor. You can, of course, paste copied text multiple times, so this is a handy way of duplicating data.</p>
<p>Using named buffers isn&#8217;t much different from normal copying and pasting &#8211; to copy text into a named buffer, type <code>x[action]</code> where x is the buffer name (a-z), and action is one of the copy actions above, such as yy. To paste text from a named buffer, just type <code>xp</code> or <code>xP</code>, again where x is the name of the buffer. After a little practice, you&#8217;ll be able to copy and paste <em>sans souris</em> in your sleep :-)</p>
<h3>Saving files</h3>
<p>Now that you know how to open documents, add and edit text and navigate around, it&#8217;s probably a good time to learn how to save your masterpiece.</p>
<p>If you started up vi with a filename as a parameter (i.e. vi [filename]), simply typing <code>:w</code> will save the document as filename. If there is a problem writing to the file (such as the file being read-only) and you have the correct permissions, you can force an override by using the ! (exclamation mark) character, like this <code>:w!</code>.</p>
<p>If you want to save another copy of the current document (for example, as a backup), or if you started vi without a filename parameter, you can write to a specifically named file by typing <code>:w [filename]</code>. You can also save typing by using the magic % place-the-current-filename-here variable. For example, typing <code>:w %.bak</code> will save the current document as it&#8217;s current filename with the extension .bak.</p>
<p>To save and quit vi with one command, type either <code>:x</code> or <code>:wq</code>; they both have the same effect. Personally, I prefer the latter, as I find it too easy to confuse <code>:q</code> and <code>:x</code> otherwise. You can also use <code>ZZ</code> (no colon!) to save the current text and exit vi. Again, you can attempt to override any errors by using an exclamation mark at the end of the save command.</p>
<h3>More navigation</h3>
<p>As you may have noticed, there are often many ways of getting a job done in vi. Navigation is no exception, and here to prove it are a few more elegant ways of navigating around your document.</p>
<p>You will no doubt at some point want to edit large files. If scrolling through it line-by-line doesn&#8217;t appeal to your sense of fun, help is at hand! To scroll forwards one screen type <code>ctrl-F</code> and to go backwards one screen type <code>ctrl-B</code>. You can scroll half-pages by typing <code>ctrl-D</code> to go forwards, or <code>ctrl-U</code> to go backwards. To show one more line at the top of the screen, type <code>ctrl-Y</code>, and for one more line at the bottom type <code>ctrl-E</code>.</p>
<p>It&#8217;s also sometimes handy to be able to reposition the page in relation to the cursor. Typing <code>z</code> and then pressing enter will reposition the line with the cursor to the top of the screen. <code>z.</code> will reposition to the middle of the screen, and z- to the bottom of the screen. These functions can be a bit disorientating at first, but don&#8217;t let that put you off!</p>
<p>Yet another handy navigation feature, especially when programming, is the ability to jump to a specific line number within your text. You can do this by typing <code>:[line number]</code> (colon followed by the line number) and pressing enter. For example, typing <code>:32</code> will jump to the beginning of line 32 of your code or text.</p>
<h3>Seek and&#8230; replace</h3>
<p>Did I mention that you can enter <em>insert mode</em> in over-type mode by typing <code>R</code>, or that you can replace a single character by typing <code>r[character]</code>? Well, now you know. But that isn&#8217;t what this part of the tutorial is about.</p>
<p>The search and replace mechanism in vi uses <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expressions</a> and can be made to do some complicated things, such as replacing the second o in the first seven matches of the word potato, or replacing any word containing two Ps with the word parrot. As with the closely related search function mentioned in the Navigating around section, all search operations are case sensitive. Type <code>:set ic</code> to turn this off if it irritates you.</p>
<p>I won&#8217;t delve into the world of regular expressions fully here, as there is far too much to cover in this small space. Suffice it to say that if you can think of an operation involving replacement of text, you can probably do it in vi with a single regexp command.</p>
<p>Basic search and replace operations are fairly easy; typing <code>:s/foo/bar</code> will substitute the word foo with the word bar on the current line. You can specify which portion of the document to search by using <code>:1,4s/foo/bar</code>, which will replace any occurrences on lines 1-4 of the document. If you want to do a search and replace operation globally, <code>:%s/chicken/dog</code> will replace chicken with dog wherever it is written throughout the document, and is the same as typing <code>:1,$s/chicken/dog</code>, where the $ means last line.</p>
<p>If you&#8217;re a bit nervous about accidentally replacing too much text in your document, you can ask vi to prompt you before each replacement is made by adding the <code>/c</code> flag to the end of your search expression, like this <code>:%s/abuot/about/c</code>. To aid with clarity, you can also get vi to print back a copy of each line after it has been modified by adding the <code>/p</code> flag.</p>
<p>Finally, beware of special characters! As mentioned in the Navigating around section, some characters have a special meaning to vi. You can find out more on Wikipedia, or by using your favourite search engine. Just search for regular expressions, regex or regexp!</p>
<h3>Fin</h3>
<p>As I hope this tutorial has shown, vi is an immensely powerful text editor which has an wide range of uses to this day. With a little work and a lot of patience, you too can find the joy of vi! The door has been opened a crack; through it you have seen the tip of the iceberg.</p>
<p>Where you go from here is a choice I leave to you&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.planzero.org/2009/08/an-introduction-to-the-vi-editor/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
