Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Learn vi/vim in 50 lines and 15 minutes

by tachyon (Chancellor)
on Mar 04, 2004 at 00:05 UTC ( [id://333737]=perltutorial: print w/replies, xml ) Need Help??

So you need a perl editor. vi/vim (vi-improved) has its advantages. You will find it on virtually any *nix and you can get it for Win32. I syntax higlights perl, C and everything else pretty well. And it is simple to get the basics. So let's begin. We only have 15 minutes, and time is a wastin ;-)

To edit a file with vi/vim do:

vi file.txt vim file.txt

vim is better and on many systems if you type vi you actually get vim. Use vim if you possibly can rather than plain old vi. If you did that let's go on..... Vi is a tie died hippy modal editor possibly developed by guys who did too much LSD. But once you get you head around the wierdness it works well. It has 4 MODES.

  • Nav.
  • Match.
  • Colon.
  • Insert(Edit).

You are only in one MODE at a time. When you are in a MODE what you type causes different stuff to happen. Escape (ESC at top left of keyboard) will get you out of whatever mode you are in. You will learn to love ESC. Press it lots if needed. It does respond to lots of stabs!!! You will end up back in nav mode which is where you begin. So without further ado let's begin....

NAV MODE

Default is nav mode. This is where you start and where you end up with lots of ESC ESC ESC if you get lost. Arrow keys work as expected. In short h j k l move the cursor as well. Direction not entirely intuitive but you get used to it. Try it. You need to be able to feel it rather than have me say this key moves you this way.

Almost all vi commands will take a prefix integer argument. For example typing 12j is the same as typing jjjjjjjjjjjj. In this case you will execute 12 j commands, each one of which moves the cursor down one line, so you will jump down 12 lines. Useful when you mean it, potentially painful if you don't. Examples 5h - left 5 chars, 10j - down 10 lines, 3k - up 3 lines, 7l - right 7 chars. We will use NN to represent an integer argument to a command.

gg goes to top of file. NNgg goes to line NN. NN means an integer +OK? G goes to bottom of file dd deletes current line under cursor. NNdd deletes NN lines yy 'yanks' ie copies the current line and NNyy yanks NN lines. p pastes the current buffer at the end of the line the cursor is +on. Both dd and yy fill the buffer. ^ goes to begining of line like REs. Literal ^ not control BTW $ goes to end of line like REs u undo, NNu undo last NN changes. Ctrl+r redo, NNCtrl+r redo last NN undo-s x deletes char under cursor. NNx deletes NN chars to RHS of curso +r. r type r and the next char you type will replace the char under t +he cursor. handy for s/'/"/ and the like. J Joins the cursor line to the line below ie remove \n from cur l +ine. Note j is nav J is join..... Note Backspace will more you backwards (ie navigates but no deletion i +n nav mode) but DEL deletes as normal (ie no navigation stuff disappears). GOK.

MATCH MODE

Type a / or a ? and you enter match mode. You will see either a / or a ? at the bottom left of your editor window. Then type almost any perl RE and hit enter. Note there is no trailing / or ? required. The cursor will move to the first match. Hit n to go to the next or NNn to go the the NNth match moving forward.

Type a ? and then almost any perl RE and hit enter - works the same as / but heads towards top of file, so n gets you the match before....

As always ESC gets you back to nav mode.

COLON MODE

Type SHIFT+: to enter colon mode. That is shift and the colon key together. Hit ESC key to exit colon mode and get back to nav. Colon appears at bottom left of window. You have 3 main chars you can type (w q !)

:w writes file :w! writes file even if read only :q quit :q! quit and don't mess with me. ie if I have made changes ignore them and exit with no write (good for f ups) :wq write quit (usually what you want) :wq! write quit don't question my wisdom! There are also lots of neatish widgets, here's three :shell gives you a shell to do stuff. type exit to return to vi. :!command gives you a shell immediately below colon. ie !./script while you are editing 'script' it will exec +it. hit enter to return to vi as prompted, else type more com +mands..... :%perldo s/this/that/ execs that perl s///

INSERT MODE

You have 2 chars a and i and the shift key adds A and I. From nav mode typing the following enters insert mode at the following position relative to the cursor:

a Insert after the current cursor pos A Insert after the end of current line i Insert before the current cursor pos I Insert at the begining of the current line

In insert mode when you type 'stuff' it appears at the cursor. Arrows work as normal for navigation if needed. hjkl of course don't navigate you they just type letters. To use the undo key 'u' you need to hit ESC to escape into nav mode, then type undo which will undo all your insert mode edits. If you need to delete just a bit use arrows, backspace and delete as normal.

There is a lot more power than what I have shown you but if you take the time to learn those 20 odd keystrokes you will be able to use vi and perhaps learn more.....happy beeping.

Updates

Added J as suggested by dragonchild and %perldo s/// as suggested by Caron. Recommended vim explicitly per Abigail-II halley made it read better.

Replies are listed 'Best First'.
•Re: Learn vi/vim in 50 lines and 15 minutes
by merlyn (Sage) on Mar 04, 2004 at 00:18 UTC
    You forgot:

    BEEP MODE

    In beep mode, no matter what character you try to press, vim beeps at you. Beginners enter this mode all the time; experts enter it only once every few minutes. Entering beep mode is nearly always unintentional; exiting beep mode is usually just as accidental. If you work in an office, and use vim, you should consider reducing the volume of your machine, or getting a set of headphones so as not to annoy the emacs users nearby.
    {grin}

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      #!/bin/sh # beepoff turns off the beep # Console setterm -blength 0 # X xset b off # Optional for Emacs users # find / -name '*emacs*' -exec rm -f {} \;
      /me laughs maniacally. (!!!!!, no less)

      --
      Allolex

        I know this is ancient history, but surely:

        - find / -name '*emacs*' -exec rm -f {} \; + find / -name '*emacs*' -print | perl -nle unlink

        there could be a lot of emacs files on there..

        --
        Simon.

Re: Learn vi/vim in 50 lines and 15 minutes
by dragonchild (Archbishop) on Mar 04, 2004 at 01:14 UTC
    You forgot a number of very important commands and distinctions:
    1. vi's regex language is very different than Perl's. It's much more akin to the shell command grep's. Specifically, there is no + and you only have back-references.
    2. Aliases:
      • Colon Mode:
        • :x is :wq
        • :NN moves you to the NNth line. :$ moves you to the bottom of the file.
        • :!asdf executes asdf in the shell.
        • :map X asdfasdf will map the key X to the key sequence asdfasdf. These are macros, to be used in Nav Mode. My favorites are:
          • v - :!perl -wc %^V^M (That's Ctrl-V, Ctrl-M.) - compile the current file in Perl.
          • V - :!%^V^M - Execute the current file.
          • q - :e #^V^M - Switch you to the last buffer. (Read up if you want to know what these are.)
      • Nav Mode
        • 0 is ^
        • z-z moves the screen to center on your line. z-Enter moves the screen so that your line is on the top. (There's on that does it for the bottom, but I never remember it.)
        • o inserts a new line below where you are and puts you in Insert Mode at the beginning of it. O does it for above.
        • w goes the beginning of the next word. b to the prior. e to the end of the current word.
        • J takes the next line and puts it at the end of the current line.

    The reason to use vi is that, once you understand it, it's is extremely efficient to edit in. I found that my productivity in sheer editing is almost as fast as I think. (Which, granted, isn't that fast, but still!)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Good post... a minor nit, though. You can use + in Vim regexes, but you have to precede it with a backslash. Vim regexes and Perl regexes are not the same (knowing when to use backslashes often throws me off), but I think they're much more similar than they are different.

      -- Mike

      --
      XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
      -- grantm, perldoc XML::Simpler

        OK so I lied (it was just a little one!) It really uses the abortive GNU regex syntax that is just different enough from Perl to s!+t you if you really know perl REs.....it is like grep. My usual greps are called re and re! linked into /usr/bin. They look like:

        [root@devel3 root]# cat /usr/bin/re #!/usr/bin/perl die "Usage re [RE]\nFull Perl grep on STDIN\n" unless @ARGV == 1; my $re = qr/$ARGV[0]/; while(<STDIN>) { print if m/$re/; } [root@devel3 root]# cat /usr/bin/re! #!/usr/bin/perl die "Usage re [RE]\nFull Perl grep on STDIN\n" unless @ARGV == 1; my $re = qr/$ARGV[0]/; while(<STDIN>) { print if ! m/$re/; } [root@devel3 root]# cat some.file | re "some perl re"

        cheers

        tachyon

      Sure there are shortcuts. Only had 50 lines!. All good points. :NN is 4 strokes as is NNgg. :$ is 3 strokes but G is only two.

      cheers

      tachyon

Re: Learn vi/vim in 50 lines and 15 minutes
by atcroft (Abbot) on Mar 04, 2004 at 01:04 UTC
Re: Learn vi/vim in 50 lines and 15 minutes
by Caron (Friar) on Mar 04, 2004 at 07:53 UTC
Re: Learn vi/vim in 50 lines and 15 minutes
by Abigail-II (Bishop) on Mar 04, 2004 at 14:48 UTC
    To edit a file with vi do:
    vi file.txt
    This is a bit misleading. On many systems, if you do vi file.txt, you do indeed edit the file with vi, and not with vim. You discuss vim, and while vim has many similarities with vi, not everything you discuss will work in vi. For instance, not on every system will the arrow keys work as expected in vi. There's no syntax highlighting in vi, nor does vi have any perl hooks.
    It has 4 MODES.
    That's just an opinion. One could also argue that vi only has command mode. But some commands take arbitrary long arguments. ;-).

    Abigail (using vi since 1984)

      alias vi=vim

      Never leave home without it.

      ------------ :Wq Not an editor command: Wq

      Yep, this is where I jump right in and say that I was taught and believe that vi has 2 modes, command and insert. In command mode you have an ed sub mode (:). In command mode you can use the / or ? command to search. The only reason I would use /usr/bin/vi would be an emergency.

      On the positive side I wish there had been a web tutorial like this when I was cursing and crying in front of the beeping flashing monster with the intimidating tilde teeth. (they really do look like teeth on a HP-Term in a panic trying to figure out how to use it to do homework.) That was when I learned about O'Reilly.

      Love, --Brig Update: Fixed 2 typos
Re: Learn vi/vim in 50 lines and 15 minutes
by flyingmoose (Priest) on Mar 04, 2004 at 17:33 UTC
    A few thoughts/observations/comments on vi in general, for anyone scared about it or debating not learning it.

    • vi/vim is cool because it is everywhere. If you walk up to some obscure ancient UNIX box, probably all it will have is vi. This means your editor (pico, nano, emacs, etc) -- will not exist. This is life.
    • Enjoy the simple speedups like :/foo/ to search for foo, or :520 to go to line 520, or ":set nu" to show line numbers, or ":$" to jump to EOF. In most GUI tools (nedit, SlickEdit, etc) you'd have to expend far more calories to make these things happen. In more primative tools (pico, nano, etc) some of these things require far more keystrokes and some of them aren't even doable.
    • There greatest thing about vi/vim is you don't have to leave the keyboard and everything can be typed very quickly. This minimizes wrist strain (especially with mises) or finger-cramps-or-breakage (Escape-Meta-Alt-Control-Shift) in EMACS.
    • For those using pico, nano, consider yourself being taunted and envision yourself riding a bike with training wheels. Endeavor to be cool like the other kids.
    • You might have tried "vi" and had problems. Maybe the arrow keys were unsupported, maybe backspace was broken. You'll find vim is vastly superior to old-schoool vi. You still launch vim with "vi", but it's less broken. Scream in terror when you approach a SCO box and it has "vi" and not "vim". Consider upgrading however possible.
    • there are oodles of commands and options. You don't need to learn them all. insert mode will take you far, you don't need all of them -- especially when using vim (AIOCS).
    • There is no escape from beep mode. -- and merlyn, on my laptop, the infernal thing beeps using my PC speaker. -- you should treat beep mode as shock training. It's annoying you because you did something wrong, and it is encouraging you to type valid commands so you don't sound stupid in front of your other friends. Yep, beep mode is a good thing -- and it will make you faster through subconcious training
    • If you encounter any EMACS zealots while complaining about vi, they are there to convert you, so you should run away as fast as possible. Tell them EMACS would be for you if only you had twenty fingers. Or maybe "EMACS is a great operating system, but it really needs a good text editor".
    • run :h holy-grail when you get a chance and see the nine-billion options
      There is no escape from beep mode.
      Oh, sure there is. At least, on many vi-clones, and, IIRC, even on plain old vi. (But maybe not in vim).

      In my vi clone, it's as simple as :set noerrorbells, and that will turn off visual and audio bells.

      Abigail

        psst...you weren't supposed to tell them that. No, seriously, for newbies I think the bells are good instructional aids. I used to want them off, but they seem to be helping. I would only turn them if covertly coding in the bushes (say you are on a sting operation and have to take notes) and you don't want anyone to know where you are hiding.
        Or do it in your terminal... I use xterms on Solaris (/usr/openwin/bin/xset -b)
Re: Learn vi/vim in 50 lines and 15 minutes
by diotalevi (Canon) on Mar 04, 2004 at 00:55 UTC
    So what am I doing to get into merlyn's beep mode? I'd end up there all the time when I tried using vim and if I hit escape enough times ( which was always more than I thought I had to - I think six or seven times was about right ) I'd get back to "nav" mode. Heck, nano is nicer than that!

    I also never figured out how to backspace a newline off and had to resort to typing everything from the next line onto the end of the previous line again because newlines at the end can't be deleted.

    Also, also, really long lines just truncate (visually only, mind you) so I'd have to cursor over to see the entire thing and only the bit that fit into the 80 character window.

    So why is this so popular anyway?

    A late addition... I had another thought - is this like Umberto Eco's intention with the first two hundred pages of The Name of the Rose? I recall it was something along the lines of keeping all the readers who weren't willing to slog through two hundred pages of book just to get to the good bits out. Is that vim's mode?

      So why is this so popular anyway?

      Because it's extremely fast and powerful once you know what you're doing. I can edit at least 3-5 times as quickly using Vim as anything else I've tried. Maybe more, I haven't benchmarked it. :-)

      And with Vim just about everything is customizable so if you don't like the way something works by default, you can configure it how you want it. For example, your truncated lines example: use :set wrap and presto, line-wrapping. And the help documentation (:help) in Vim is very good. It's how I've learned almost everything I know about Vim.

      Oh, and for getting rid of newlines between lines, I think you were missing the 'J' command (join two lines). Or maybe :set backspace=eol, which allows you to backspace over newlines in Insert mode.

      -- Mike

      --
      XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
      -- grantm, perldoc XML::Simpler

      I also never figured out how to backspace a newline off

      Ah INSERT MODE backspace key works for me and will backspace you to the begining of the file if you hold it down long enough.... Here is your post after I did G A Backspace + Hold it down and wait.....

      ~ ~ ~ ~ -- INSERT --

      :-)

      J will join lines ie remove newlines too. J will remove the newline at the end of the cursor line effectively joining the next line to it.....

      As noted in NAV mode DEL deletes stuff. BACKSPACE just works like left arrow or h and navigates you. GOK!

      cheers

      tachyon

        Ah INSERT MODE backspace key works for me and will backspace you to the begining of the file if you hold it down long enough

        It'll backspace over line breaks if you "set backspace=eol".

        I have backspace set to "indent, eol, start" in my .vimrc. indent allows me to backspace over autoindented lines, eol allows backspacing over line breaks, and start allows backspacing past the starting insertion point.

        <sarcasm>A list of all available options can be found with the obvious and intuitive command ":he Q_op"</sarcasm>, in case a vi/vim beginner is looking.

      I thought it was funny and a bit sad that "ESC ESC ESC" was mentioned in the vi tutorial. The only advantage of "ESC ESC ESC" over "ESC" is that it beeps at you after exiting insert mode.

      You enter "beep mode" by typing ESC (an odd number of times) when you aren't in insert mode (but this doesn't happen to me since I use a Real® OS where function keys don't send ESC sequences).

      If you type ESC, then there is a pause while vi waits to see if it is the start of an escape sequence or is just a plain ESC. If you type something else during this period, vi looks if the sequence is an ESC sequence for a function key (or other special key), probably finds that it isn't, and so then processes the ESC as a single keystroke (which produces a beep since there is no function for ESC when in 'nav mode').

      So beep mode is caused by people hitting ESC *one* too many times and then cycling through hitting ESC more times to try to figure out what mode they are in. If you simply wait several seconds, the beep mode passes.

      Note also that any vi produced in the last decade can show you when you are in insert mode so you don't have to hit ESC trying to figure out whether you are in insert mode or not.

      - tye        

Re: Learn vi/vim in 50 lines and 15 minutes
by halley (Prior) on Mar 09, 2004 at 17:30 UTC
    I use vi when root or remote, emacs for anything else. And that's the way I've used Un*x computers for nearly two decades, so it's not likely I'll change any time soon.

    Technical documentation note: you started talking about NNmove in the middle of a paragraph, and leave it up to the user to infer that NN represents some decimal number typed as digits. New general concepts deserve careful introduction.

    Start a paragraph with something like, "To do anything a number of times, such as move the cursor eleven lines, just precede the usual command with a number; typing "1 1 k" is equivalent to typing "kkkkkkkkkkk" while in nav mode.

    --
    [ e d @ h a l l e y . c c ]

      Fair point, I got carried away with brief. I have broken it out into a para with an explanation along your line. Thanks. Hopefully someone will find it useful.

      cheers

      tachyon

Re: Learn vi/vim in 50 lines and 15 minutes
by nimdokk (Vicar) on Mar 04, 2004 at 16:41 UTC
    This could be useful, might have to point some folks here at work to it for learning vi a bit more. It can drive me nuts somedays watching my co-workers use vi and do stuff the long way when there is a shortcut that will get them there faster. You just can't teach a rhino to dance, it wastes your time and annoys the rhino, and no one likes an annoyed rhino ;-)


    "Ex Libris un Peut de Tout"
Re: Learn vi/vim in 50 lines and 15 minutes
by Anonymous Monk on Mar 04, 2004 at 16:44 UTC
    Bill Joy, Creater or VI interview cirta 1984:

    REVIEW: What is it that Interleaf offers you that EMACS doesn't?
    JOY: I can just look at my screen, and when I print it off, it's the same as it looks on the screen. It is formatted, and I'm tired of using vi. I get really bored. There have been many nights when I've fallen asleep at the keyboard trying to make a release. At least now I can fall asleep with a mouse in my hand. I use the Xerox optica mouse instead of the other one because it is color coordinated with my office. Did you notice? I prefer the white mouse to the black mouse. You've got to have some fun, right? This business of using the same editor for 10 years - it's like living in the same place for 10 years. None of us does it. Everyone moves once a year, right?

    citation: http://www.cs.pdx.edu/~kirkenda/joy84.html

      This is up here to say that VI is not the end all of editors. BUT if you use UNIX you do need to know it (or the even older ed on which it was based) This old article went on to state it was on a lot of UNIX boxes, But not all. In fact Bill stated that he was using CAT to write software and VI to edit.

      "All real programmer needs is a hex editor" - Anon

Re: Learn vi/vim in 50 lines and 15 minutes
by runrig (Abbot) on Mar 04, 2004 at 18:41 UTC
    I've been doing all of my 'on the fly' SQL in vim or vi. On Windows, I use this in vim, and on AIX (where currently there is only vi installed, and I only access Informix databases), I use a different shortcut to send SQL to Informix's 'dbaccess'. For the vi version, I use the following two statements in my .exrc file (and they say perl is line noise :-) :
    map #1 ma/^}/^M:?^{?,.t.^Mk:?^{?+1,.!dbvi^M'a map #2 ma:/^{/;/^}/d^M'a
    I have a shell script named 'dbvi' (which filters the input before sending it to dbaccess or elsewhere), and when the cursor is in any block delimited by braces, it sends the contents of the block to the shell script, and the results appear following the current block. E.g. Hitting F1 in the first block produces the next block:
    { select * from some_table } { <results of query> }
    Hitting F2 in the current block deletes the following block. I did have to mess with terminfo to get the F-keys to work. In the vim version, I open new windows, so I don't have to deal with this block stuff...
Re: Learn vi/vim in 50 lines and 15 minutes
by hesco (Deacon) on Jan 02, 2007 at 00:14 UTC
    I made the switch to vim in 2003, maybe 2004 for its syntax highlighting. The last step was figuring out how to do cut and paste longer than a single line at a time (dd, p).

    During the transition, I would close the file in vim, open it in nano for block moves, then return to vim. I called a friend who introduced me to my first shell and he helped me break my nano habit (except for a rare machine I've encountered where the J command did not work to kill the \n at the end of a line). He introduced me to markers. The m key will set a marker, named after the next letter you feed it. Go to the start of your block you want to move, type `ma`. Then move to the end of your block and use `d'a` and it will delete from the current position back to the marker you set. Move the cursor again and use the `p` key to paste your block where you want it.

    I found this far less annoying than using `dd` and `p` to move one line at a time.

    From a combination of nodes here, the vim website and elsewhere, I have now accumulated the following .vimrc file which creates a useful development environment for me. The first thing I do after being given shell access to a new server, right after changing my password, is to scp my .vimrc from my usual servers to the new environment.

    My .vimrc follows:

    I write nearly everything in vim these days, love letters, code, memos, reports. Between vim and mailx (catdoc, antiword, xpdf's pdftotext and munpack) I rarely need to leave a console. Perhaps a couple of times a month I'll open Abiword or OpenOffice to "pretty up" a document for printing. But I also once wrote a perl script to massage a plain text press release thorugh LaTeX into a pdf file, so I didn't have to open a gui editor just to distribute a press release (something I had to do several times a week in a previous job).

    When I introduce new folks to a linux environment, as I'm telling them not to fear the shell prompt, I urge them to learn a text editor. I tell them that nano may be more intuitive and easier to learn (with its on screen menu), but that vim is far more powerful, that if they spend any time writing (as I do) that they will appreciate having mounted the learning curve.

    By now I am so attuned to working in vim, that I sometimes find spurious :wq or i's in my documents composed in other editors or on webforms like this one.

    -- Hugh

    :wq

    if( $lal && $lol ) { $life++; }
Re: Learn vi/vim in 50 lines and 15 minutes
by mikasue (Friar) on Apr 13, 2006 at 16:33 UTC
    I must say that I read that Learning VI book and it wasn't nearly as informative as this tutorial! Thanks for writing it.
      Ahh, finally relief from errorbells. Below combo worked great for me for VIM 7.0 on Windows to stop audible bells and visual bells (screen flash): set visualbell set vb t_vb= Now I can finally turn up my speaker volume and get audible reminders from Outlook and stop missing meetings!
Re: Learn vi/vim in 50 lines and 15 minutes
by zentara (Archbishop) on Mar 04, 2004 at 15:30 UTC
    No matter how many times I tried to switch to vi/vim, I always come back to midnight commander's "mcedit".

    I'm not really a human, but I play one on earth. flash japh
      No. Try not. Do... or do not. There is no try.
Re: Learn vi/vim in 50 lines and 15 minutes
by Anonymous Monk on Jun 18, 2009 at 02:28 UTC
    thank you for putting this online. short and useful, great for quick start!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perltutorial [id://333737]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (6)
As of 2024-03-19 11:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found