Slashdot Mirror


(Useful) Stupid Vim Tricks?

haroldag writes "I thoroughly enjoyed the recent post about Unix tricks, so I ask Slashdot vim users, what's out there? :Sex, :b#, marks, ctags. Any tricks worth sharing?"

702 comments

  1. best one ever by shawn(at)fsu · · Score: 4, Funny

    :r! emacs /I partly kid I like Vi

    --
    500 dollar reward for tip(s) leading to the arrest of the person(s) who stole my sig.
    1. Re:best one ever by Anonymous Coward · · Score: 2, Funny

      /bin/bash: emacs: command not found

    2. Re:best one ever by smcameron · · Score: 3, Informative

      For all your vi/Emacs flamewar needs, try http://wordwarvi.sourceforge.net/ Full disclosure, I'm the author of that game.

    3. Re:best one ever by Repton · · Score: 1

      Just don't forget to run M-x viper-mode!

      --
      Repton.
      They say that only an experienced wizard can do the tengu shuffle.
    4. Re:best one ever by rpresser · · Score: 4, Funny

      $ sudo bash
      Password:
      # test -f /bin/emacs  && mv /bin/emacs /bin/emacs.NEVER
      # cat <<EOF >/bin/emacs
      #!/bin/bash
      echo emacs: command not found
      EOF
      # exit
      $ logout

    5. Re:best one ever by Anonymous Coward · · Score: 0

      notepad

    6. Re:best one ever by Anonymous Coward · · Score: 0

      If your writing anything in vi try the following, instant productivity boost :wq
      $ emacs

    7. Re:best one ever by Antique+Geekmeister · · Score: 1

      And, of course, emacs is normally in /usr/bin, which is for larger user utilities. (Some systems symlink /bin to /usr/bin, but certainly not all)

      But try running 'emacs -e psychonalyze-pinhead', or 'emacs -e tower-of-hanoi' if you have a full GNU emacs installation.

    8. Re:best one ever by satan666 · · Score: 1

      (export MYEMAC=$(which emacs 2>/dev/null);[[ -f $MYEMAC ]] && { mv ${MYEMAC} ${MYEMAC}.NEVER; echo -e "#\x21/bin/bash\necho \"emacs: command not found\"" >${MYEMAC}; chmod 755 $MYEMAC; });exit

      Just for the record, that is the proper command.

    9. Re:best one ever by SL+Baur · · Score: 1

      Dropping things like this:

      :!kill -6 $$

      in random directories in files named ".exrc" used to be great sport.

      I see sadly, that VIM actually starts up from that as "~/.exrc".

      (kill -9 still works, but is not as fun ...)

    10. Re:best one ever by prestomation · · Score: 1

      /bin/bash: emacs: command not found

      :(

    11. Re:best one ever by nocomment · · Score: 1

      who links /bin to /usr/bin? That's dumb. Especially if the system makes /usr it's own partition. Boot into single user mode to see why.

      --
      /* oops I accidentally made a comment, sorry */
      /* http://allyourbasearebelongto.us */
    12. Re:best one ever by SlashDev · · Score: 1

      echo mv `type emacs |cut -f3 -d' '` /`type emacs | cut -f2 -d'/'`/mv.NEVER cat `type emacs |cut -f3 -d' '` #!/bin/bash echo emacs: command not found EOF # exit $ logout

      --

      TOP DSLR Cameras Reviews of the top DSLRs
    13. Re:best one ever by Anonymous Coward · · Score: 0

      Er...
      # chmod 755 /bin/emacs

    14. Re:best one ever by ilikejam · · Score: 1

      Solaris does.

      [dave@sol10 ~]$ ls -l /
      total 1070
      lrwxrwxrwx 1 root root 9 Sep 4 2007 bin -> ./usr/bin

      --
      C-x C-s C-x k
    15. Re:best one ever by houghi · · Score: 1

      # test -f /bin/vi && cp /bin/vi /bin/emacs

      --
      Don't fight for your country, if your country does not fight for you.
    16. Re:best one ever by Anonymous Coward · · Score: 0

      I like the color highlight of /usr/share/vim/vim71/macros/less.sh

    17. Re:best one ever by Anonymous Coward · · Score: 0

      $ sudo bash
      Password:
      # test -f /bin/emacs && mv /bin/emacs /bin/emacs.NEVER
      # cat <<EOF >/bin/emacs
      #!/bin/bash
      echo emacs: command not found
      EOF
      # exit
      $ logout

      Ehh, that won't work.........

      You need to mark the file as executable
      so just add "chmod +x /bin/emacs"

    18. Re:best one ever by Anonymous Coward · · Score: 0

      $ sudo bash
      Password:
      # test -f /bin/emacs && mv /bin/emacs /bin/emacs.NEVER
      # cat <<EOF >/bin/emacs
      #!/bin/bash
      echo emacs: command not found

      Slightly improved version:

      echo emacs: command not found 2>&1

    19. Re:best one ever by Anonymous Coward · · Score: 0

      # # test -f /bin/emacs && mv /bin/emacs /bin/emacs.NEVER

      FTFY

    20. Re:best one ever by MessageDrivenBean · · Score: 1

      You forgot "chmod a+x /bin/emacs".

      --
      Quisque verborum suorum optimus interpres...
    21. Re:best one ever by rpresser · · Score: 1

      IT DOESN'T MATTER. Practically everyone has /bin before /usr/bin in their path. My script tests /bin/emacs just to make sure it's not clobbering anything for good. Then it creates an emacs-hiding script in /bin, where it will be found before /usr/bin.

      I would have thought that by paying attention that would be obvious.

      Vim also has a tower-of-hanoi simulator script. And a Turing machine simulator script, for Pete's sake. So what?

    22. Re:best one ever by Antique+Geekmeister · · Score: 1

      Not everyone has /bin before /usr/bin. In particular, many folks have /usr/local/bin before either, and emacs is often installed there in UNIX systems that don't come with Emacs (though these are getting rarer).

      The point is that you cannot just assume that a binary that you didn't insall and you didn't package manage is in a particular location on someone else's system. In addition, even if emacs is linked to in /bin/emacs, the next update of the emacs package is likely to replace it and put it right back where you tried to hide it from.

      What you are doing is exactly what NVidia did to the OpenGL libraries in their Linux installer, and it's a source of real package management problems. It's what someone does on their home environment, and leaves as a booby trap for others to cope with. If you don't want emacs, don't install it, or make changes that affect your personal environment, not everyone else's. For example, having $HOME/bin early in your PATH allows you to put a script there called 'emacs' that says "don't use this!", but doesn't step on package management or other people's use of the server.

    23. Re:best one ever by Antique+Geekmeister · · Score: 1

      I'm afraid not. The AT&T style UNIX's didn't support the '-e' option for the 'echo' command. Use printf instead.

    24. Re:best one ever by Anonymous Coward · · Score: 0

      $ sudo bash
      Password:
      # test -f /bin/emacs && mv /bin/emacs /bin/emacs.NEVER
      # cat <<EOF >/bin/emacs
      #!/bin/bash
      echo emacs: command not found
      EOF
      # exit
      $ logout

      You forgot to:

      chmod +x /bin/emacs

    25. Re:best one ever by Anonymous Coward · · Score: 0

      "All the world is a VAX."

      #!/bin/bash is slightly dumb when you do not urgently require bash features; #!/bin/it is utterly stupid when you only use standard shell features.

    26. Re:best one ever by Anonymous Coward · · Score: 0

      doh! missed the chmod... shame on you.

  2. Replacement by lunchlady55 · · Score: 2, Interesting

    %s/FROM/TO/g

    replaces every instance of FROM to TO in the document.

    % = every line. Drop that to just affect the current line
    g = every instance within the line. Drop that to change only the first occurrence in the line.

    also - use CTRL-v CTRL-m to get a newline - will look like ^M but match newlines.

    1. Re:Replacement by acreman · · Score: 1

      In addition to %s/FROM/TO/g you can do X,Ys/FROM/TO/g This will do the same but only between line number X and line number Y.

    2. Re:Replacement by Reality+Master+101 · · Score: 4, Informative

      Also, you can do use "ma" to mark the beginning line, "mb" to mark the ending line, and then:

      :'a,'bs/FROM/TO/g

      --
      Sometimes it's best to just let stupid people be stupid.
    3. Re:Replacement by iggya · · Score: 5, Informative

      One of vi's best features is the '.' command to repeat what you last did. You can do 'dd' to delete a line, then press '.' (dot) to do it again. Or '100.' to do it 100 times. Typing in numbers before a command repeats the command. Typing in '100ihello[esc]' will insert 'hello' 100 times. Then typing dot will give you 100 more.

      On a modern vi you can press up-arrow after pressing colon to get your previous colon command back for editing.

      Some examples of changing things on various lines:

      # add 'gronk' to the end of every line
      # 1 is line 1, $ is the last line
      :1,$ s/$/gronk/
      # put 'bing' at the start of lines 5-10
      :5,10 s/^/bing/
      # change foo to bar for all occurrences in the rest of
      # the file from where the cursor is
      :s/foo/bar/g

    4. Re:Replacement by Anonymous Coward · · Score: 1, Informative

      Don't forget you can precede your search-replace statement with a line range, like

      %10,20s/From/To/

      %.,$s/F/T/

    5. Re:Replacement by pluther · · Score: 1

      CTRL-v CTRL-m will match Windows-style newline characters.

      This is useful when you have a file created on a Windows machine and transferred to Unix, so: :%s/CTRL-v CTRL-m//g will strip out all the Windows newlines.

      To match a Unix newline, use $ instead.

      --
      If the masses can keep you down, you're not the Ubermensch.
    6. Re:Replacement by pluther · · Score: 5, Informative

      Very cool. I didn't know how to mark a range like that before.

      And, while we're having fun with search and replace, ^ will match the beginning of a line, so if you mark as above, and then change the command to: :'a,'bs/^/#/

      you will have commented out a section of your code without having to insert a comment character independently on each line.
      Reverse it with: :'a,'bs/^#//

      to remove the comments.

      Also, you don't have to use the / command as a separator. Anything typed after s will become the separator, so if you want to, say, change all your Windows paths to Unix paths, instead of starting with: :%s/\\/\//g

      which, while undeniably cool, can be more easily written as: :%s;\\;/;g

      which is a little easier to read.

      Two other interesting bits:

      u all by itself will undo the last command. Handy when you're testing your commands before posting them to Slashdot.

      Also, Slashdot's editor will remove the newlines before any line that starts with a :
      In my examples, I put each command on it's own line, but Slashdot keeps appending them to the previous line. Weird.

      --
      If the masses can keep you down, you're not the Ubermensch.
    7. Re:Replacement by MrKaos · · Score: 3, Interesting

      Also, you can do use "ma" to mark the beginning line, "mb" to mark the ending line, and then:

      :'a,'bs/FROM/TO/g

      And if you add a c (confirm) to the end

      :'a,'bs/FROM/TO/gc

      you will get a Y/N to replace that instance or not, in case you don't want to replace every occurrence. if you search like this :'a,'b g/FINDME/ s/FROM/TO/gc

      vi will ask for confirmation to replace FROM to TO only on line between a and b markers on lines with the string FINDME on it.

      :.,$ g/FINDME/p will search from your current cursor position (.) to the end of the document ($) and get /regular expression/ print (i.e grep) inside of vi.

      456G

      go to the 456 line (G for the last line)

      These are a few of my favourite things. Vi plugin for Eclipse and Visual Studio actually makes them have a worthwhile editor, I couldn't imagine not having all the effort I invested into using vi available in some of the "editors" available today.

      --
      My ism, it's full of beliefs.
    8. Re:Replacement by mrons · · Score: 2, Informative

      Also g/foo/s/bar/baz/g

      For all the lines that match foo, replace bar with baz

      With this form, the equivalent of %s/bar/baz/g is g/bar/s//baz/g

      Another useful :g command is g/foo/d to delete all lines with foo

    9. Re:Replacement by emerald_glitter · · Score: 1

      ... where X,Ys/FROM/TO/g can be something like -10,.s/FROM/TO/g (previous 10 lines & current) or .,+5s/FROM/TO/g (this line and next 5). Also, $ = last line so you can do something line .,$s/FROM/TO/g for everything from the current line to the end of the file.

    10. Re:Replacement by Sancho · · Score: 1

      You can leave off the first number to, in order to start from the current line:

      :,Ys/FROM/TO/g

      Or, to replace until the end of the file:

      :,$s/FROM/TO/g

    11. Re:Replacement by Abcd1234 · · Score: 2, Informative

      I much rather use Visual mode for this, as I hate having to remember line numbers. Just hit 'V', highlight the region, and then type ':s/FROM/TO/g'. Vim does the rest.

    12. Re:Replacement by nabsltd · · Score: 1

      Thank you.

      I'm a vi guy, and I just haven't spent much time learning the new features offered by vim. I always wondered what "visual mode" was.

      Although vim has good online help, I'm generally too busy actually using it to learn about it.

    13. Re:Replacement by James+McGuigan · · Score: 1

      :456
      456gg
      456G

      All do the same thing, goto line 456

    14. Re:Replacement by iggya · · Score: 1

      You can use colon-number to go to a line in a file. Open a file and type ':777' to go to line 777, or the last line if there are less than 777 lines.

      To quickly duplicate a line, put the cursor on that line, and type 'yyp', which means yank line, and then 'put' the yanked thing into the buffer.

      You can use slash to search for things in a file. For example, you might search for a puppy: /puppy.

      Suppose you had a config file for a webserver, and you wanted to change the webserver root. Here is the starting file:

      # blah blah blah
      server.document-root = "/var/www/"
      # blah blah blah

      You search for the line with the webserver root (using slash /root), and duplicate the line (yyp). Then comment out the first line by going up a line and inserting a hash at the start (k i # escape). Go to the bit you want to change (/var n). Here you type /var, which searches for var. It gets the var on the commented out line. Then you type 'n', which gives you the next match forward, or the next match in reverse if you use ? to search backwards. So now you should have your cursor at the start of var. You want to change three words, 'var', '/', and 'www', so you do (3cw home/web escape). Happy with the results, use ":x" to write and exit. That saves one keystroke over the prolix ":wq". The file now looks like this:

      # blah blah blah
      #server.document-root = "/var/www/"
      server.document-root = "/home/web/"
      # blah blah blah

      Job done quickly and easily, thanks to vi!

    15. Re:Replacement by James+McGuigan · · Score: 1

      Selecting a range in visual mode will actually set markers, thus you can select a range and do multiple :'s/FROM/TO/g replacements without having to reselect your lines.

      Its useful when you do a replacement (:'<,'>s/FROM/TO/g), find its not quite right, undo (u), reload the last command from history (:<up>), correct it and retry.

    16. Re:Replacement by Mr+Z · · Score: 1

      You can use V to do visual highlight also, and just start typing :s/FROM/TO/g to do the replace. If you hit : followed by up arrow, you can go through previous commands you did on a visual-selected range. This makes repeating commands on multiple blocks easy.

    17. Re:Replacement by poached · · Score: 1

      I can't really get vim to work within visual studios. Do you have any tips or a link to a tutorial to getting that to work? From what I understand, the plugin will open a NEW window, not embedded in the VS window?

    18. Re:Replacement by E+IS+mC(Square) · · Score: 1

      That's what I do most of the time. Also, depending on if you do "shift v" or "ctrl v", you can go to Line mode or Block mode respectively. (ctrl q instead of ctrl v in case of gvim for windows)

    19. Re:Replacement by whoever57 · · Score: 1

      Also, you can do use "ma" to mark the beginning line, "mb" to mark the ending line, and then:

      Or, you can use "V" (in command mode) to mark a range: Hit "V" (at the bottom of the screen, it will show "-- VISUAL LINE --") move the cursor to the end of the range, then hit ":" and type the rest of the command (the range will be indicated by "'<,'>").

      --
      The real "Libtards" are the Libertarians!
    20. Re:Replacement by Samah · · Score: 1

      Vi plugin for Eclipse and Visual Studio actually makes them have a worthwhile editor...

      Which Vi plugin for Eclipse do you use? I had a go at one or two a while ago and just couldn't get them working properly. They seemed pretty buggy too. It's a pity because I'd love the functionality, depending on how well it integrated with existing code completion and what not.

      --
      Homonyms are fun!
      You're driving your car, but they're riding their bikes there.
    21. Re:Replacement by Anonymous Coward · · Score: 0

      :1,$ s/$/gronk/
      simpler: :%s/$/gronk/

    22. Re:Replacement by scm · · Score: 1

      You actually only need one mark (e.g. the start) and then move the cursor to the end and do:

      :'a,.s/FROM/TO/g

      in this context '.' means "where the cursor is"

    23. Re:Replacement by MrKaos · · Score: 1
      I'm pretty sure it was viemu. I'm doing my dev work in eclipse now, but I do remember that the VS vi plugin was pretty good, actually seems a little better than the vi plugin I am using for eclipse.

      Oh yeah and another vi thing I remembered that if you position the cursor over a word and press # it will load that word into the search buffer so you can do a n/N for the next or previous occurrence (which I've just discovered dosen't work in my vi plugin )-:

      --
      My ism, it's full of beliefs.
    24. Re:Replacement by isorox · · Score: 2, Informative

      # change foo to bar for all occurrences in the rest of
      # the file from where the cursor is :s/foo/bar/g

      No, that only works on the current line. perhaps :.,$s/foo/bar/g

    25. Re:Replacement by Randle_Revar · · Score: 1

      :%s/CTRL-v CTRL-m//g

      which is great, but if you have it, it is easier to use fromdos or todos from the tofrodos package

    26. Re:Replacement by PylonHead · · Score: 1

      have commented out a section of your code without having to insert a comment character independently on each line.

      I usually just go to the start of the first line, hit ctrl-v to start block visual mode, go to the start of the last line and hit I#<esc>

      That's capital i, pound, then the escape key.

      --
      # (/.);;
      - : float -> float -> float =
    27. Re:Replacement by Anonymous Coward · · Score: 0

      Also, Slashdot's editor will remove the newlines before any line that starts with a :
      In my examples, I put each command on it's own line, but Slashdot keeps appending them to the previous line. Weird.

      Weird indeed, but you can use an html line break

    28. Re:Replacement by sdhoigt · · Score: 1

      Which VI plugin for Eclipse are you talking about?

      I haven't found a decent open source one. I'm hopeful that one exists.

      SD

    29. Re:Replacement by Bo6us00 · · Score: 1

      The "mark" facility is one of the most powerful things in Vim. The m[a-z] syntax drops a marker at the current position of the cursor. So you have the full alphabet at your disposal for markers, not just a & b.

      The " ' " (the single quote char) with a mark letter is how you address a mark. This can be combined with many Vim commands. Example: drop a marker-h (mh) at the function you are working on, then no matter where you move to in the file, typing "'h" will take you to the "home" function you are working on.

      To yank a series of lines, drop a marker-a (ma) at the beginning of the series of lines. Move down to the bottom of where you wish to yank. Hit "y'a" and you will yank all the lines from marker-a to your current position and can then "place" them (I call it drop them) with the p or P commands.

      There are plenty of other marker capabilities and many other cool things in Vim. Steve Qualline's great book "VI iMproved", http://www.amazon.com/iMproved-VIM-Landmark-Steve-Oualline/dp/0735710015/ref=pd_bbs_sr_3?ie=UTF8&s=books&qid=1226030977&sr=8-3, is a great read and well worth the money for it. For those that can not afford it, it is also available as an online PDF ftp://ftp.vim.org/pub/vim/doc/book/vimbook-OPL.pdf

    30. Re:Replacement by playerone · · Score: 2, Informative

      Some examples of changing things on various lines:

      # add 'gronk' to the end of every line
      # 1 is line 1, $ is the last line :1,$ s/$/gronk/

      In vim (unsure if its new or in the original vi) a % means do this on all lines.

      eg: :%s/^/foo/

      places "foo" at the start of every line.

      --
      --Question Authority--
    31. Re:Replacement by laddiebuck · · Score: 1

      For just commenting out blocks of code, you can highlight with V and replace with :s, or even simpler, just hit Ctrl-V, select, then I. It will insert at each line in the "left side" of the rectangle.

    32. Re:Replacement by knutal · · Score: 1

      A related tool is to record a sequence of commands in the registers and then execute them. The following records some commands in register 1. (Start with q1 and end with q)

      q1
      "do some actions"
      q

      @1 will then execute contents of register 1. 10@1 will execute them 10 times and so on

      See also "complex-repeat" in vim help

    33. Re:Replacement by Provocateur · · Score: 1

      Thanks for that last one; I didn't know about u to undo. My undo has always been :q! since I don't really code, just edit text or config files with vi :-)

      However I use vi as my chat client once in a while heh. Talk about minimalist.

      --
      WARNING: Smartphones have side effects--most of them undocumented.
    34. Re:Replacement by xouumalperxe · · Score: 1

      Not weird at all. The posts are being processed as HTML. a newline is just a whitespace, and is rendered as such. The preferred way to post code in /. would be wrapping it in <ecode> tags.

    35. Re:Replacement by SCHecklerX · · Score: 1

      !}fmt

      Runs the current paragraph through the fmt command.

    36. Re:Replacement by Anonymous Coward · · Score: 0

      A much easier way to do multi-line comments is using visual block mode (Ctrl-v) to select the first character of the lines you want to comment out. 'I#' to insert before the highlighted locations. When you hit , its all commented!

    37. Re:Replacement by Anonymous Coward · · Score: 0

      Anything typed after s will become the separator

      Oh! Very nice. Thanks!

    38. Re:Replacement by Anonymous Coward · · Score: 0

      I use marks all the time these days. You can use them to mark locations and then jump back to that location at a later time. You can use them to copy or delete sections of text without even having to use : commands. For example:

      ma -- marks current line with mark a.
      'a -- Jumps to line previously marked as a.
      d'a -- deletes from current line to mark a.
      y'a -- copies from current line to mark a.

      :set report=0 -- Will now give you a status indicator (like '1 line yanked') when you copy or delete a single line of text or more. If you only want to be told when you delete 5 or more lines of text then set report=4.

      Another useful trick is to use the multiple buffers available rather than just the default buffer. This allows you to paste in more than one set of copied data or alternate between two sets of copied data. You specify a buffer via the " and can specify any buffer a-z:

      "ayy -- Copy the current line into buffer a.
      "ap -- Paste the buffer in a at current location.
      "bdd -- Delete the current line and put it into buffer b.
      "a3yw -- Copy the 3 words starting at cursor and put them in buffer a.
      "ay/text -- copy everything up to "text" into buffer a.

      You can also use the numbered buffers "1 - "0 to paste the most recently deleted lines (doesn't seem to work with words). This is handy if you realized that you deleted a line unintentionally a few commands ago and don't want to undo what you've done in the meantime:

      "1p -- Paste most recent deletion.
      "2p -- Paste 2nd most recent deletion.

    39. Re:Replacement by yukk · · Score: 1

      You can go direct to stuff from the command line too.
      vi +777 file.foo to start editing at line 777
      or
      vi +/badcode file.c to start editing at the first occurance of "badcode" or whatever text you want.

      --
      The trouble with the rat race is that even if you win, you're still a rat." Lily Tomlin
    40. Re:Replacement by Anonymous Coward · · Score: 1, Funny

      Young fools. You don't anything know about sed, do you? You can use sed "s/foo/bar/g" < file in another session of Screen. Of course, sed is a far too arcane tool for people who like to play music in an editor. Crappy music, by the way.

    41. Re:Replacement by ClubStew · · Score: 1

      Why bother with setting marks, though? In normal mode, just type "v" to enter visual mode and select the lines (well, characters, but the end result next would act on the lines) then without leaving visual mode type :s/foo/bar/g. ViM will automatically use "'s/foo/bar/g" which replaces "foo" with "bar" over the visually selected lines. Not sure this works that way in Vi, but I prefer ViM.

    42. Re:Replacement by ioshhdflwuegfh · · Score: 1

      Also, you can do use "ma" to mark the beginning line, "mb" to mark the ending line, and then:

      :'a,'bs/FROM/TO/g

      In reality, this is fine only if you marked by a and b a piece of code that you frequently comment/uncomment, although I never use it that way. Basically, if you're using marks you don't want to or can't waste them on marking beginning and ending of a block of code. If you don't use them, then this use of them might seem cool to n00bs, but it is still quite keystroke expensive.

    43. Re:Replacement by ioshhdflwuegfh · · Score: 1

      Very cool. I didn't know how to mark a range like that before.

      And, while we're having fun with search and replace, ^ will match the beginning of a line, so if you mark as above, and then change the command to: :'a,'bs/^/#/

      you will have commented out a section of your code without having to insert a comment character independently on each line.
      Reverse it with: :'a,'bs/^#//

      to remove the comments.

      That's cool / That's fun / Now let's see how it's in vi done.

      1. We go to the beginning line of the block. You have to go to the beginning line of your block to put the mark. But instead of putting it, thus wasting both mark and strokes, just do the change. Just do it: I#<esc>
      2. Instead of moving aimlessly around in order to reach the ending line of the block and put mark b there, we change the code by repeating: <Ret>.<Ret>. as many times as there are lines to be changed.
      3. When you reach the last line that you need to change, you're done.
      4. Then figure out faster ways of doing it depending on the part of the code you're changing,

    44. Re:Replacement by Atario · · Score: 1

      Open a bunch of files in separate windows (which I generally do with the context menu in Explorer, your mileage may vary), then do

      :windo <command>

      to do the <command> on every file you opened.

      --
      "A great democracy must be progressive or it will soon cease to be a great democracy." --Theodore Roosevelt
    45. Re:Replacement by Anonymous Coward · · Score: 0

      goto beginning of block
      press 0 to go to the beginning of the line
      Ctrl-V to start block highlight
      goto end of block
      Shift-i to insert
      # to insert a '#' char
      ESC to get out of insert

      block commented.
      Shift-i in general is handy.

    46. Re:Replacement by dwater · · Score: 1

      not sure how they can justify the 'plain old text' description...

      --
      Max.
    47. Re:Replacement by dwater · · Score: 1

      you didn't mention what the plugin was for eclipse...are you using eclim, or something else?

      --
      Max.
    48. Re:Replacement by dwater · · Score: 1

      > why bother...?

      because it can be faster...it all depends on the cursor movement you need/want to use (and what you're used to too, I guess).

      --
      Max.
    49. Re:Replacement by MrKaos · · Score: 1

      you didn't mention what the plugin was for eclipse

      Indeed, I didn't. It's viplugin. It has some quirks including;

      marks work but lose their position when you ad or remove lines (c)hanging a (w)ord when using a middle paste dosen't remember the change when you iterate a search and then do a . (repeat last command)

      you can't paste into a command buffer (annoying)

      some of the vi functions I mentioned don't work

      It mostly works which is weird considering the vi plugin for vs works better.

      --
      My ism, it's full of beliefs.
    50. Re:Replacement by dwater · · Score: 1

      thanks.

      The VS plugin isn't of any use if you don't use Microsoft Windows. I'm using Linux, so a vi plugin for eclipse is just what I'm after :)

      Thanks, I'll give it a try.

      --
      Max.
    51. Re:Replacement by dublin · · Score: 1

      Surprisingly, I recently used vi's "." command as the easiest way to create a file that had to have exactly 40,000 zeroes in it.

      I started out putting a loop around /dev/zero, but quickly realized that was going to take bloody forever. Vi did it in about 10 seconds.

      --
      "The future's good and the present is nothing to sneeze at." - Roblimo's last ./ post
  3. :Sex by dyingtolive · · Score: 1

    I don't get it, whats this one do? :)

    --
    Support the EFF and Creative Commons. The war is coming, and they're supporting you...
    1. Re::Sex by Anonymous Coward · · Score: 5, Funny

      You're asking on the wrong site. No one on Slashdot has ever tried it.

    2. Re::Sex by TrekkieTechie · · Score: 5, Funny

      I'll tell you when you're older.

    3. Re::Sex by tsalmark · · Score: 1

      Try it, You'll like it.

    4. Re::Sex by Noksagt · · Score: 4, Informative

      :help sex

      :Sexplore[!] [dir]... Split&Explore directory of current file *:Sexplore*

      e.g. it give you a file exploring pane above the buffer you are currently using.

    5. Re::Sex by pimpimpim · · Score: 5, Funny
      it give you a file exploring pane above the buffer you are currently using.

      If only my parents had told me earlier.

      --
      molmod.com - computing tips from a molecular modeling
    6. Re::Sex by Anonymous Coward · · Score: 0

      Strange...

      I got

      E149: Sorry, no help for sex

    7. Re::Sex by Anonymous Coward · · Score: 0

      :sex
      Not an editor command.

      I guess I have to upgrade to get that feature?

      --
      (I'm kidding. I know it's case sensitive.)

    8. Re::Sex by Randle_Revar · · Score: 2, Funny

      support :sex education!

    9. Re::Sex by ooglek · · Score: 1

      Wow, that post was actually extremely useful! You'd think after 16 years of using VIM I'd have tried ":help sex" but no.

    10. Re::Sex by Errtu76 · · Score: 1

      I'll try to remember this one when my daughter one day will ask me, thanks!

    11. Re::Sex by Anonymous Coward · · Score: 0

      jr@monkey:~$ man Sex
      No manual entry for Sex

      Aw.

  4. Filter Lines by saberworks · · Score: 4, Interesting

    Use visual mode (shift-v) to highlight lines, then shell out to external programs to filter them, such as perltidy. To do that, with lines highlighted, type !perltidy (assuming you have it on your machine). This lets you filter specific lines instead of the whole file.

    1. Re:Filter Lines by TheRaven64 · · Score: 1

      I've not done this with perltidy, but a visual mode selection followed by !sort is really useful for sorting lines. xxd instead of sort is great if you find yourself looking at some binary data too - you can use vim as your hex editor.

      --
      I am TheRaven on Soylent News
    2. Re:Filter Lines by oever · · Score: 1

      !cat
      !uniq
      !sort
      !sort -n
      !ls
      !bash

      It all works. This is brilliant! I've using vim for years and did not know this.

      --
      DNA is the ultimate spaghetti code.
    3. Re:Filter Lines by Jameson+Burt · · Score: 2, Interesting

      In vim, I often enter
      :set paste
      then highlight text from a browser
      and paste that text (middle mouse button)
      into my vim session.
      The "set paste" prevents the lines from indenting further and further to the right.

      After pasting, many lines are too long.
      In particular, a whole page gets pasted as one line.
      So, I enter
      :1,$!fmt
      or like the author (shift-v or ctrl-v) then

            !fmt

    4. Re:Filter Lines by billster0808 · · Score: 1

      I've just got it set as an alias:
      alias vimxxd='vim -R +"%!xxd" +"set ft=xxd" +"set nomod"'
      vimxxd opens it up in hex mode.

    5. Re:Filter Lines by Architect_sasyr · · Score: 1

      !bash

      And if you're running vi under someones "sudo" access account, that'll get you a root shell. I use ':sh' personally, mostly to drop to a shell when I'm in the middle of editing something and I just want to quickly check the name of a file.

      --
      Me failed English...
      FreeBSD over Linux. If my comments seem odd, this may explain...
    6. Re:Filter Lines by James+McGuigan · · Score: 2, Informative

      These are useful with prefixes: :r!pwd (read `pwd` into to document) :%!sort (sort all lines) :'$lt;'>!sort | uniq (sort last visual selection, notice the pipe)

      Another useful thing you can do is to bind a filter to a script, in your .vimrc, so you can yy pp a line, and get an instant commented debug line.

      map :.! ~/scripts/javascript-debug.pl==

      #!/usr/bin/perl
      while() {
              ($line = $_ ) =~ s/^\s+|\s+$//g;
              ($quote = $line) =~ s/'/\\'/g;
              print "console.log('DEBUG: $quote ', $line);\n";
      }

      Note: My normal script has half a dozen regexps in the middle, for stripping out semicolons, function declarations, return statements, such that what gets printed is almost always a valid code statememnt. However slashdot can't tell my regexps apart from line line-noise and kept complaining about too many junk characters.

      However its possible to write similar scripts for various languages, and for other simple tasks such as wrapping a for statement around an array variable.

    7. Re:Filter Lines by oever · · Score: 1

      What's wrong with ctrl-z and 'fg'?

      --
      DNA is the ultimate spaghetti code.
    8. Re:Filter Lines by TheRaven64 · · Score: 1
      That drops you out in the parent terminal. Imagine someone did:

      $ sudo vim

      If you do control-z then you will be in their shell. If you do !sh then you will get a root shell.

      --
      I am TheRaven on Soylent News
    9. Re:Filter Lines by Mr+Bill · · Score: 1

      You can easily create shortcuts for these as well, if you use them often

      nnoremap <silent> ,t :%!perltidy -q<Enter>
      vnoremap <silent> ,t :!perltidy -q<Enter>

      That hooks the command ,t to perltidy. If you don't highlight anything and type ,t in command mode it will filter the whole file. If you highlight some lines and hit ,t it will only filter the selected lines.

      And if you put that in .vim/ftplugin/perl.vim then those commands will only work when editing perl files.

    10. Re:Filter Lines by Architect_sasyr · · Score: 1

      No no he means for breaking out to read lines.

      Nothing wrong with it, except that sometimes my terminal intercepts ^Z before it gets to the SSH connection, sometimes it gets stopped at the other end. I've been known to use so-called 'hack' shells that don't permit job control. I can see where GP is going though, it's just easier to build the functionality into a piece of software and know it works every time rather than rely on the systems around it.

      --
      Me failed English...
      FreeBSD over Linux. If my comments seem odd, this may explain...
    11. Re:Filter Lines by zojas · · Score: 1
      or even simpler, in command mode, just hit ! then do any cursor movement. then it will give you a prompt to type the shell command. the stuff that the cursor would have moved over is then filtered through the shell command.

      this works for cursor movements like }, 5j, 'b, G, anything you can dream up.

      I don't even bother with visual mode.

    12. Re:Filter Lines by ooglek · · Score: 1
      Then after you've highlighted what you want, you can then type other commands.

      shift-v
      j j j j j
      :s/foo/bar/g

      replaces foo with bar in only the 5 lines you've highlighted.

    13. Re:Filter Lines by Splab · · Score: 1

      You can assign the paste option for a specific button:
      set pastetoggle=
      Just hit F9 in insert mode and it switches to paste, hit it again to get out.

      And if you want to wrap a long line you can use gq, this will wrap to your current textwidth setting - also, if you got a couple of short lines you want nicely wrapped you can mark them with visual and use gq, vim will then collapse them to whatever fits within textwidth.

    14. Re:Filter Lines by olyar · · Score: 1

      I do the same with :set noai

      (as in no autoindent)

      Used to drive me nuts before I learned that one.

      --
      Custom, hands-free Linux installs. Instalinux
    15. Re:Filter Lines by Anonymous Coward · · Score: 0

      Like most vi commands you use use any movement command in conjunction with the !cmd filter to filter arbitrary amounts of text. The format is !Mcmd where M is the movement you want to make and cmd is the filter program. Or :a,b !cmd where a,b are the lines you want to filter (can use % or marks too of course). For example:

      !}fmt -- I use this to format a paragraph that has lines that go past 80 characters using the 'fmt' utility.

      !Gcmd -- Filter from current line to end of file.

      :10,20 !fmt -- Format lines 10 - 20 only.

    16. Re:Filter Lines by MikeBabcock · · Score: 1

      v, highlight some lines, then ':fold -s -w72' for E-mail formatting, for example.

      --
      - Michael T. Babcock (Yes, I blog)
    17. Re:Filter Lines by dwater · · Score: 1

      Fold, eh? That's interesteding. I've always used 'fmt'. It seems like the behaviour is similar - I wonder if there are any differences to make me want to type the extra chars for the fold command?
      Doing the 'fold -s -w30' and 'fmt -w30' on identical texts shows that they indeed do something different...hrm.

      --
      Max.
    18. Re:Filter Lines by MikeBabcock · · Score: 1

      I don't use fmt on a regular basis, but I know that "fold -s -w72" will break on whitespace at 72 columns, thus preserving words, without otherwise modifying layout.

      --
      - Michael T. Babcock (Yes, I blog)
    19. Re:Filter Lines by nneonneo · · Score: 1

      Or just
      :%!sort
        to sort the entire file.

  5. Couple off-hand by Reality+Master+101 · · Score: 4, Interesting

    Not horribly exciting ones, but useful:

    xp - reverse next two characters
    dL - Delete to end of page, in other words, everything visible.
    C - Often overlooked: chop off end of line and go into insert mode.

    --
    Sometimes it's best to just let stupid people be stupid.
    1. Re:Couple off-hand by Sancho · · Score: 1

      I much more frequently use c instead of C. With the lowercase-version, you can select where to end your edit. Great for modifying things in quotes:

      c/"[enter]

    2. Re:Couple off-hand by slackito · · Score: 1

      Don't forget:

      ci" - change all the text between quotes, from anywhere in the text

      It also works with parenthesis and brackets :D

    3. Re:Couple off-hand by Deadplant · · Score: 1

      I've been doing d/" then having to enter insert mode with another keystroke. thanks for the tip!

    4. Re:Couple off-hand by Lalakis · · Score: 1

      Thanks! I did :help object-select and now I feel enlightened!
      cit (correct inner tag!!!)
      :)

    5. Re:Couple off-hand by zojas · · Score: 1
      to generalize that a bit...

      you said: dL to delete to the bottom of the visible screen. you can also do d followed by any cursor movement and the text the cursor would have moved over will be deleted. dw, dW, de, dE, d'b, dG, d$, d^, those are all handy.

      C is a shortcut for c$. c is like d, in that you can follow it with any cursor movement command, for example cw, cW, ce, cE, cG, cL, c}, c'b, cj, whatever.

      you may be sensing a pattern here. lots of vim commands actually will operate over any cursor movement range specified.

    6. Re:Couple off-hand by EricWright · · Score: 1

      I use dgg (delete to top of buffer) and dG (delete to bottom of buffer) ALL the time. It's great for splitting PL/SQL packages into a spec file and body file.

    7. Re:Couple off-hand by nwf · · Score: 1

      And, of course, you can prefix them with a number to repeat that action "n" times, e.g. 20dw to delete 20 words.

      I use S a lot to replace the entire current line. and z. to center the current line in the middle of the screen.

      --
      I don't know, but it works for me.
    8. Re:Couple off-hand by zojas · · Score: 1

      and don't forget z.'s twin sisters: z- to put the current line at the bottom of the screen, and z ENTER to put the current line at the top of the screen.

    9. Re:Couple off-hand by Anonymous Coward · · Score: 0

      And, of course, you can prefix them with a number to repeat that action "n" times, e.g. 20dw to delete 20 words.

      Or if you're more comfortable d20w will do the same thing. Well, not quite the same thing. 20dw will delete 1 word 20 times, and d20w will delete 20 words once. You can also combine them: 2d3w will delete 3 words twice (or 6dw)

    10. Re:Couple off-hand by SplinterOfChaos · · Score: 1

      I use ct a lot. (That's change 'till ). Really helpful for changing specific elements, like one argument of a function ( ct, ).

    11. Re:Couple off-hand by include($dysmas) · · Score: 2, Informative

      I/A - insert at start /end of line

      P/p - paste before / after cursor

      "*y / "*p - yank & paste to / from the windows clipboard

      vat/vit select around/inside a text block like html tags

      vi" select inside speech marks

      ciB correct inside curly brackets pair

      the list goes on, the point is to treat each key as an atom of a command, and learn how they can be combined.

      !python % - run current file through python

      ggVG= - reindent current buffer

      ^wv/s - split window

      ^6 - switch to last touched buffer

    12. Re:Couple off-hand by memphis.barbecue · · Score: 1

      Vim became my UNIX command-line editor of choice when I realized you could compare documents side-by-side in it:

      (horizontally)
      vi -o [document] [seconddocument] [ad infinitum]

      (vertically)
      vi -O [document] [seconddocument] [ad infinitum]

      and you could switch back and forth between them using CTRL-W. But that's probably common knowledge.

      As for voting, I tried to figure out which of my pets I could write-in. But alas, none of them met the 35 year-old requirement.

    13. Re:Couple off-hand by Anonymous Coward · · Score: 0

      here's some more:

      d$ or D - delete to end of line
      de - delete to end of current word

      replace the d in the above commands with a c and you'll go into insert mode after the deletion.

      you can also use a number to delete/replace. e.g.
      2ce will delete the next words and then go into insert mode.

      And the most useful key in vim .... . - repeat what you just did.

    14. Re:Couple off-hand by LordByronStyrofoam · · Score: 1

      Use D instead of dL and save a keystroke.

      --
      Slashdot's name? When my compiler sees /. it generates a warning about a badly formed comment.
    15. Re:Couple off-hand by Reality+Master+101 · · Score: 1

      D goes to the end of line, dL goes to the end of the page. It's useful when you want to delete a bunch of stuff, so it's any easy way to delete a lot of lines at a time, but you never delete anything out of view. Repeating it allows you to suck up a lot of text quickly.

      --
      Sometimes it's best to just let stupid people be stupid.
    16. Re:Couple off-hand by dwater · · Score: 1

      > dL - Delete to end of page, in other words, everything visible.

      That's only true if your current position is the top of the page, since it actually deletes from the current line to the bottom of the page.

      'dL's sister command is 'dH', which is delete to the top of the currently visible text.

      --
      Max.
    17. Re:Couple off-hand by dwater · · Score: 1

      ...and 'z+' which is like a 'page down' since it puts the line below....or something (it's not doing what I thought it did when I try it).

      --
      Max.
    18. Re:Couple off-hand by dwater · · Score: 1

      > I use dgg (delete to top of buffer) and dG (delete to bottom of buffer) ALL the time

      Wow! You must have a lot of empty files!

      ..or perhaps just one file, since you have no time to write it and move to the next...and you're just being extremely zealous at keeping it empty.

      --
      Max.
    19. Re:Couple off-hand by L33tGreg · · Score: 1

      ct" (no enter) saves you a keystroke. t/T/f/F are often overlooked movement commands.

  6. Vim tips by icsEater · · Score: 5, Informative

    Why bother asking slashdot when all the best Vim tips have been collected and compiled? http://vim.wikia.com/wiki/Best_Vim_Tips

    1. Re:Vim tips by fishbowl · · Score: 1

      I've been trying to figure out how to do this forever:

      Say I have an identifier throughout my code where it's both siteCode and SiteCode depending on context.

      Say I want to change all occurrences of siteCode to siteIdentifier and SiteCode to SiteIdentifier, in a single search/replace. I may be missing something obvious, and this might be a simple DFA (and therefore regex), but I've never found it, and quite often find myself doing substitutions twice.

      --
      -fb Everything not expressly forbidden is now mandatory.
    2. Re:Vim tips by Amazing+Quantum+Man · · Score: 4, Informative

      :%s/\<\([Ss]\)iteCode\>/\1iteIdentifier/g

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    3. Re:Vim tips by Amazing+Quantum+Man · · Score: 1

      Note that the escaped angle brackets are to limit search to whole word search, so that embedded search targets are not found.
      The key is \([Ss]\), which stores the first character for the later \1 substitution.

      --
      Fascism starts when the efficiency of the government becomes more important than the rights of the people.
    4. Re:Vim tips by retzkek · · Score: 1

      This should do the trick (I like using question marks for the delimiter instead of slashes):
      :%s?\([sS]ite\)Code?\1Identifier?g

    5. Re:Vim tips by shani · · Score: 1

      :%s/\([sS]ite\)Code/\1Identifier/g

    6. Re:Vim tips by amirulbahr · · Score: 1

      s/([Ss]ite)Code/$1Identifier/

    7. Re:Vim tips by fishbowl · · Score: 1

      Thanks, good answer. Even trickier would be a regex to deal with the arbitrary internal uppercase character. This problem comes up pretty often in generated binding code. I suspect that when we get away from specific strings for substitution, the problem ceases to be context-free. But I really do have a lot of situations where I want to do replacements like the one your regex solves. I didn't know how escaped anglebrackets worked, despite being a vim user since probably 1993.

      Thanks!

      --
      -fb Everything not expressly forbidden is now mandatory.
    8. Re:Vim tips by TimJL · · Score: 3, Informative

      I'd like to pimp my own cheat sheet here: http://tjl2.com/sysadmin/vim-cheat-sheet.html I love Vim!

    9. Re:Vim tips by Anonymous Coward · · Score: 0

      To have that page posted?

    10. Re:Vim tips by searlea · · Score: 1

      I'm guessing you're after :%s/\<\(site\)code\>/\1Identifier/gi

      (the 'i' flag makes the search-replace case-insensitive)

    11. Re:Vim tips by andy753421 · · Score: 1

      Use \zs to avoid \(\) and \1 can also be nice.. :%s/\<[Ss]ite\zbCode\>/Identifier/

    12. Re:Vim tips by doti · · Score: 1

      Why bother asking slashdot when all the best Vim tips have been collected and compiled?

      Because one never learn all Vim tricks at once.
      You can't go to the wiki and read it all. Well, you can, but it won't stick.

      This is an opportunity to learn (and teach), for those who don't have a daily routine of reading one tip per day.

      Speaking of which, a tip-of-the-day plugin for Vim would be nice. It could even get live data (netrw) from the wiki.

      --
      factor 966971: 966971
  7. very useful (especially for noobs) by gEvil+(beta) · · Score: 5, Funny

    :q

    --
    This guy's the limit!
    1. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 4, Funny

      surely:

      :q!
      nano

    2. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      very useful (especially for noobs) :q

      I tried it a few times but couldn't get it to work. I was getting frustrated and yelled it, and whaddya know, it worked... :q!

    3. Re:very useful (especially for noobs) by gEvil+(beta) · · Score: 1

      You're assuming they managed to get into Insert mode first. : p (that's a smiley, not a command)

      --
      This guy's the limit!
    4. Re:very useful (especially for noobs) by freedumb2000 · · Score: 1

      Safer is: Esc-Esc-Esc-Esc-Esc-Esc-:q-:q!-nano

    5. Re:very useful (especially for noobs) by apathy+maybe · · Score: 1

      actually

      [ESC] :q!

      Quit and don't save.

      --
      I wank in the shower.
    6. Re:very useful (especially for noobs) by James+McGuigan · · Score: 1

      Better still :!nano %

      This will open the currently open file in nano, without having to leave vim. Ctrl-X in nano will take you back to vim.

    7. Re:very useful (especially for noobs) by stand · · Score: 1

      This is the all-time funniest comment I've read on Slashdot.

      --
      Four fifths of all our troubles in this life would disappear if we would just sit down and keep still. -C. Coolidge
    8. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      not half as useful for noobs as :q!

    9. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      :q

      :q!

    10. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      Thanks for the tip! I was going:

      ^c ^c, ^c^c, q alt-f4 ^d, q q q ESC ESC ESCESCESC nfskfsdfljlj,STUPIDFUCKINGMACHINE^c^c, ^z
      $ killall vim

    11. Re:very useful (especially for noobs) by SplinterOfChaos · · Score: 1

      :wq! I wonder who'll reply with the slightly better version... (:wqa?)

    12. Re:very useful (especially for noobs) by mgiuca · · Score: 1

      That was the only vim command I knew for 3 years.

      In hindsight it was the least useful.

    13. Re:very useful (especially for noobs) by anilg · · Score: 1

      Oh these are nothing. I found a secret webpage that lists all kinds of dark vi secrets.. get them here!!

      --
      http://dilemma.gulecha.org - My philospohical short film.
    14. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      surely: :q!

      nano

      I find I have to tell people to do that a lot when they're trying to log out. They keep on typing in "ex it"

    15. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      :q!

    16. Re:very useful (especially for noobs) by bluelip · · Score: 1

      Better make that :q!

      Otherwise, they may not be able to get out if changes were made.

      --

      Yep, I never spell check.
      More incorrect spellings can be found he
    17. Re:very useful (especially for noobs) by Anonymous Coward · · Score: 0

      :q

      :qa!

  8. = and * by Lalakis · · Score: 3, Informative

    There are far too many "essential" commands in vim, but if I had to pick the two that make the most difference, I would pick * and =. * searches for the word under the cursor and = indents the selected text (most useful for programming).

    1. Re:= and * by retzkek · · Score: 1

      And # to search backwords for the word under the cursor.

    2. Re:= and * by Isomer · · Score: 1

      * and # are pretty cool, but for vim so is [i and [^i (show the first occurance of the keyword under the cursor in the minibuffer, recursing through #includes, and ^i is "jump to"). Also ^Wi for opening it in a new window.

    3. Re:= and * by totally+bogus+dude · · Score: 1

      I often find gq in visual mode to be useful, particularly when replying to emails. It re-wraps the selected text block.

      In command mode, press v, then use the cursors to select the area, then enter gq

      You can use :set textwidth=68 to set how many columns you want it to wrap to.

    4. Re:= and * by kybred · · Score: 1
      I use * and # all the time with 'hls' (highlight search). This highlights all the occurrences of the search item that are visible on the screen, so, for instance, you can see all the places a variable is used easily.

      gVim Rocks!

    5. Re:= and * by drunkennewfiemidget · · Score: 1

      Holy crap. I use VIM exclusively and have for years, and I had no idea = existed. I've been hammering > and repeatedly for some time.

      Thank you so very much.

    6. Re:= and * by locofungus · · Score: 1

      gg=G

      To reindent the entire file.

      Tim.

      --
      God said, "div D = rho, div B = 0, curl E = -@B/@t, curl H = J + @D/@t," and there was light.
    7. Re:= and * by dwater · · Score: 1

      I knew '#' for a long time, and got annoyed that it always searched backwards. '*' searches forwards and was a minor revelation.

      However, what I just loved was doing a '*' or '#' on a word, then ':s//sometext/' - vim automatically puts the searched for text in the '//' that you want to replace. Works with any search actually.

      --
      Max.
    8. Re:= and * by dwater · · Score: 1

      '=' doesn't indent as such (it might not be deemed 'necessary')...it formats. The difference being that it totally depends on other formatting settings. I forget which...

      --
      Max.
    9. Re:= and * by Lalakis · · Score: 1

      '=' doesn't indent as such (it might not be deemed 'necessary')...it formats. The difference being that it totally depends on other formatting settings. I forget which...

      Well, it indents in the sense of indent(1). It's useful for programming. For simple text you might want to look at gq.

  9. retab by DigitalCrackPipe · · Score: 4, Informative

    :ret over highlighted text will reformat using the tabbing rules set up in your .vimrc files. Quite handy when you have legacy code and new code mixed together leaving a big mess when opened in a viewer with different settings.
    And, to remove the ^M from files that came from windows:
    :se ff=unix

    1. Re:retab by jakel2k · · Score: 1

      ==
      indents the line. Add a number in front to indent the next N lines. Works well in C/C++... sucks in HTML files.

    2. Re:retab by maharg · · Score: 1

      :se ff=unix

      nice, I just posted :set fileformat=unix|dos, didn't know there was a short form for that :o)

      --

      $ strings FTP.EXE | grep Copyright
      @(#) Copyright (c) 1983 The Regents of the University of California.
    3. Re:retab by itomato · · Score: 1

      ':set ts=N' will also work, though for the tab spacing you specify.

      ':set et' will expand the TABs into spaces (for satisfying your crufty cow-orkers)

    4. Re:retab by James+McGuigan · · Score: 1

      :set filetype=perl :set filetype=html :set filetype=javascript

      These are good for fixing your syntax highlighting if the extension doesn't match the filetype, or are editing code imbedded within a larger file.

      You can also use this to select between per filetype vimrc files (different bindings, different tab settings etc).

      ~/.vim/ftplugin/perl.vim
      ~/.vim/ftplugin/html.vim
      ~/.vim/ftplugin/javascript.vim

    5. Re:retab by Anonymous Coward · · Score: 0

      Sometimes you can get files with mixed endings, in which case: :%s/^M$//

      will fix it, and the file will be in unix line-ending mode.

      Note that ^M means a literal ^M, which can be entered by Ctrl-V Ctrl-M.

    6. Re:retab by fabs64 · · Score: 1

      Also helpful:

      gg=G reformat whole file
      n== reformat n lines from cursor down

    7. Re:retab by ooglek · · Score: 1
      Or to reformat the whole file with proper indent rules for that filetype:

      gg=G

    8. Re:retab by Anonymous Coward · · Score: 0

      :ret over highlighted text will reformat using the tabbing rules set up in your .vimrc files.

      I just use '=' in command mode on highlighted text for auto-reformat.

    9. Re:retab by Anonymous Coward · · Score: 0

      gg=G retabs the entire file.

    10. Re:retab by IpalindromeI · · Score: 1

      Most :set variables have short forms. You can find them by asking for help:

      :help fileformat

      --

      --
      Promoting critical thinking since 1994.
    11. Re:retab by dwater · · Score: 1

      you might also consider 'set sw=N' to have your auto indent use the same indent increments.

      --
      Max.
  10. Whitespace + Searching by kevin_conaway · · Score: 1

    " Add >> to tab spaces, . to trailing whitespace

    set list listchars=tab:,trail:.

    " Use incremental search

    set incsearch

    " Highlight search matches

    set hlsearch

    1. Re:Whitespace + Searching by the_greywolf · · Score: 1

      After a suggestion from someone else, I started using this:

      set list listchars=tab:>trail:-

      It's more readable, IMO.

      --
      grey wolf
      LET FORTRAN DIE!
    2. Re:Whitespace + Searching by kangasloth · · Score: 2, Interesting

      +1 to visually distinguishable tabs. I still want a bit "whiter" whitespace though, something that settles a little more easily into the background. I've lately settled on the following, in combination with DejaVu Sans Mono. Unicode support mileage with other fonts varies.

      if &encoding =~ "utf-8"
      set list listchars=tab:&#9476;&#9472;,trail:&#183;
      else
      set list listchars=tab:._,trail:-
      endif

      ... not that I can actually show what those look like since it appears that slashcode doesn't approve of box drawing characters. At least not "BOX DRAWINGS LIGHT TRIPLE DASH HORIZONTAL" and "BOX DRAWINGS LIGHT HORIZONTAL". You'll have to decode those HTML entities yourself, oh intrepid reader. I could probably get "MIDDLE DOT" through, but I guess I'm just not that committed.

  11. When dealing with XML by Anonymous Coward · · Score: 0

    Quick way to verify XML in vim.

    cat >> ~/.vimrc <<EOF
    noremap <F2> :set syntax=xml<CR>:%!xmllint --format - <CR>
    EOF

    Then, when in vim, hit F2 to syntax highlight and run through the xmllint formatter.

  12. Re:Just using VIM by jDeepbeep · · Score: 3, Funny

    is itself a stupid trick. Emacs sucks too. Please welcome you to 21 century - use textedit!

    No thank you. edlin works just great for me.

    --
    Reply to That ||
  13. my most frequent vi trick by wdr1 · · Score: 1

    :q!emacs !^

    --
    SlashSig Karma: Excellent (mostly affected by moderatio
    1. Re:my most frequent vi trick by dwater · · Score: 1

      Do people really think such comments are funny?

      One person I know who uses emacs commented that it was possible to write 'vi' in emacs. My reply was along the lines of, "What a waste of time. Just use 'vi'".
      Some people are really poor at making a point. It was only a little later that I realised he meant to indicate the power/flexibility of emacs - as a 'vi' user who's never used emacs, it didn't occur to me right away.

      --
      Max.
  14. Need a way to un-highlight by bugnuts · · Score: 4, Informative

    Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit <esc>u but haven't found anything for vim.

    The tricks I use in vi/vim are mostly the arcane flags.

    :set nows

    will not search past the top or bottom.

    :set sw=4

    will make a nice indentation shiftwidth, especially for using the indent command (>). Works great for programming, especially with autoindent (:set ai). But when programming with autoindent, you often need to unindent one shiftwidth... do that by typing control-D at the beginning of the line. You can go to the very beginning of an autoindented line with 0 control-D.

    :set list
    :set nolist

    will turn on/off hidden characters, and show end of lines. Great for finding tabs or spaces at the end of a line.

    :set nu

    will turn on line numbering.

    Of course, if you want actual line numbers in your file, in *nix you'd use
    :%!cat -n

    %

    when pressed over a parenthesis, finds the matching parenthesis or brackets

    Now, I want someone to write a lisp interpreter based in vi macros. That way we can port emacs to vi.

    1. Re:Need a way to un-highlight by Lalakis · · Score: 1

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"?

      :nohl

    2. Re:Need a way to un-highlight by Mad+Merlin · · Score: 2, Informative

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit u but haven't found anything for vim.

      :noh

    3. Re:Need a way to un-highlight by Hatta · · Score: 2, Informative

      If you're pasting something, and don't want Vim's autoindent to screw up the formatting use: :set paste

      --
      Give me Classic Slashdot or give me death!
    4. Re:Need a way to un-highlight by Cristofori42 · · Score: 1

      while :noh is the "correct" way to do it, I find it a lot faster personally to type "/asfe". I suppose the best solution would be to just map it to an F key or something.

      --
      "Is that dad? Either that or Batman's really let himself go."
    5. Re:Need a way to un-highlight by hedronist · · Score: 1

      I have the following in my .vimrc file:

      map <F4> :let &hlsearch=!&hlsearch<CR>/<BS>

      This allows <F4> to toggle highlighting on and off. The <CR> ends the :let command, the / starts a new search (and therefore clears the command line), and the <BS> makes the / go away.

      A little circumlocutious, but it works for me.

      The following are also useful for search highlighting:

      set hls
      highlight Search term=standout ctermfg=4 ctermbg=7
      highlight MatchParen ctermfg=1 ctermbg=8

    6. Re:Need a way to un-highlight by theokayplus · · Score: 1

      To unhighlight a search term, use :nohl. I have it bound to a key in my .vimrc:
      map <F1> :nohl <CR>

    7. Re:Need a way to un-highlight by Mad+Merlin · · Score: 1

      If you're pasting something, and don't want Vim's autoindent to screw up the formatting use: :set paste

      Much easier is to use :a! (or :i!), paste your text and then end the paste with a line containing just .

    8. Re:Need a way to un-highlight by Frizzle+Fry · · Score: 1

      You can accomplish the same thing more simply with
      map <F4> :set hlsearch!<CR>

      --
      I'd rather be lucky than good.
    9. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :noh

      (no highlight)

    10. Re:Need a way to un-highlight by zunger · · Score: 1

      On X at least (I haven't checked this recently on other OS's), you can paste directly from the clipboard into vi, without any screwy autoindenting, with "*p (vim uses * as a buffer which represents the clipboard).

    11. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"?

      Use :nohlsearch, abbreviated to :noh.

      Within Vim, type :help :noh for details.

    12. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :set nohl

    13. Re:Need a way to un-highlight by 31415926535897 · · Score: 1

      :set nohl

    14. Re:Need a way to un-highlight by Denis+Lemire · · Score: 1

      Nice! I usually use straight vanilla Vi (nvi actually). Whenever I get stuck on a Linux machine with Vim it annoys me with everything staying highlighted... I usually end up doing another search for f*ck, sh*t or some other curse word that isn't in the current file to get rid of the highlight...

      This :nohl solution you speak of is far more elegant.

      It's especially annoying because I use the search command often in combination with the 'c' command to change a string from the courser to the first occurrence of a character...

      This is useful for changing a string variable in your code (amongst many other things)...

      ie) a perl string like so $mystring="This is my long strong"

      Can be changed by moving the cursor just after the first " and entering c/"

      In Vim this leaves every " in my code left as highlighted which makes my eyes bleed.

    15. Re:Need a way to un-highlight by asc99c · · Score: 1

      Auto-indent isn't great for a C-style language - you are better off using cindent. This removes most of the needs to unindent - when you type a bracket, it will automatically unindent it to the correct place. It's also useful setting up a quick keymapping to disable indentation:

      :set noai
      :set cindent
      :set pastetoggle=<F12>

      With this, when you need to paste a few lines of code (operating system cut and paste, not vim paste), you just hit F12 before you paste to disable all auto-indent, and F12 after to re-enable.

    16. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"?

      Try :noh

    17. Re:Need a way to un-highlight by asc99c · · Score: 1

      Just about every version of gvim correctly interprets operating system cut and paste. Certainly the windows and Linux versions work fine as well. However I think many people (myself included) generally use normal command line vim through an ssh or telnet session.

    18. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit <esc>u but haven't found anything for vim.

      Another alternative:

      :set @/=''

      will clear the last search pattern without turning off highlighting.

    19. Re:Need a way to un-highlight by Linknoid · · Score: 1

      :noh

    20. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      To get rid of highlighted searches

      :nohlsearch

      If you never want it, add


      set nohlsearch

      to ~/.vimrc

    21. Re:Need a way to un-highlight by Lalakis · · Score: 1

      ie) a perl string like so $mystring="This is my long strong"

      Can be changed by moving the cursor just after the first " and entering c/"

      Try ct" (correct till ") - it is easier and more straight forward. Also of use is cf" (correct forward "). The last one also deletes the ".

    22. Re:Need a way to un-highlight by Cyrano+de+Maniac · · Score: 1

      In answer to your first question, yes. The canonical way is ":noh". However, that's a pain in the butt. I've mapped it to Ctrl-N by putting this in my .vimrc:

      " Control-N clears any search highlighting
      map <C-n> :nohlsearch<CR>

      --
      Cyrano de Maniac
    23. Re:Need a way to un-highlight by Denis+Lemire · · Score: 1

      That rocks! Thanks!

      The sweetest part about Vi and the like, is you've never really mastered it completely. I've been using it for probably 10 years and still find the odd new gem like this every once in a while.

    24. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :noh

      will turn off highlighting for the current match (next search will be highlighted) :set nohlsearch

      will turn off highlighting for good (put it in .vimrc if that's what you want)

    25. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      To un-highTry using :nohls

    26. Re:Need a way to un-highlight by yuriks · · Score: 1

      To remove the highlighting, just run :nohl

    27. Re:Need a way to un-highlight by lyongyorf · · Score: 1

      I map :nohl to the escape key:
      :map <esc> :nohl<cr>
      Leaving "search highlight mode" seems analogous to leaving insert mode. I used to type /asdf<CR> to reset the highlighting. However, I found this jarring because I also use incremental search.

    28. Re:Need a way to un-highlight by Mr+Bill · · Score: 1

      When pasting I always find myself in insert mode when I remember I need to :set paste. So I have some hooks that allow me to turn it on while in insert mode:

      :map <F10> :set paste<CR>
      :map <F11> :set nopaste<CR>
      :imap <F10> <C-O>:set paste<CR>
      :imap <F11> <nop>
      :set pastetoggle=<F11>

      F10 to turn on paste mode and F11 to turn it off, and it works in command mode and insert mode. That is straight out of the vim help files if you type :help pastetoggle.

    29. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      You can un-highlight until the next search with :noh (full version :nohlsearch)
      I've got a :map :noh in my .vimrc, works lovely.

    30. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :nohl

    31. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :noh

      get rid of search highlighting
      :%s/^M//g

      get rid of DOS newlines. you get the caretM by typing ctrl-v ctrl-m
      :%s/\s\+$//g

      just replace all ending spaces with nothing

      Yes it sucks to clean up after someone using an IDE in windows. I feel your pain.

      if you're in command mode

      ==
      indents the line

      =%
      indents to the matching brace

      =4j
      indents five lines

      =... you get the picture

    32. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :noh turns off highlighting.

    33. Re:Need a way to un-highlight by zojas · · Score: 1

      to turn off the highlight, just do :noh

    34. Re:Need a way to un-highlight by lsm2006 · · Score: 1

      :noh turns off search result highlighting

    35. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :nohl is what you were looking for.

    36. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      I map it to comma. Works well.

    37. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :noh to remove highlighting

    38. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :nohl will turn off highlighting

    39. Re:Need a way to un-highlight by RhettR · · Score: 1

      :nohls

    40. Re:Need a way to un-highlight by baboon · · Score: 1

      map <leader>\ :let @/=""<bar>echo "Search pattern cleared"<cr>

      Assuming your leader is still \, just double-tap a \\ to clear.  I think someone on the VIM gave me this one.

    41. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :nohls

    42. Re:Need a way to un-highlight by laddiebuck · · Score: 1

      :set hls! turns it off entirely. I'm afraid I don't know how to turn it off after a particular search result -- but someone probably will post here later. :)

    43. Re:Need a way to un-highlight by hellgate · · Score: 1

      In .vimrc:

      :nnoremap <CR> :nohlsearch<CR>/<BS>

      Hitting return clears search highlighting.

    44. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"?

      :set nohls

      I'd recommend binding it to a key, as it's such a frequent action.

    45. Re:Need a way to un-highlight by kjhambrick · · Score: 1

      Are you looking for ?

      :set nohls

      -- kjh (included in my .vimrc)

    46. Re:Need a way to un-highlight by omuls+are+tasty · · Score: 1

      Hm, I've always been using + as the clipboard buffer. And yes, it actually works ;) Anyone knows what the difference is?

    47. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      To unhighlight a search pattern, I define a function and map a key to call it in .vimrc

      " Define a function to toggle higlighted search
      function Toggle_HLS()
              if &hls == 0
                      let &hls=1
              else
                      let &hls=0
              endif
      endfunction
      map :call Toggle_HLS()

    48. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      use :noh (no-highlight)

    49. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :set nohls (highlight search) turns it off

      I have a control key combination bound to ":set invhls" which toggles it on and off. Very useful.

    50. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      "Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit u but haven't found anything for vim."

      :noh

    51. Re:Need a way to un-highlight by peter_gzowski · · Score: 1

      In your .vimrc:

      nmap :set hlsearch!

      You can map it to whatever key you want. It will toggle search highlighting.

      --
      "Now gluttony and exploitation serves eight!" - TV's Frank
    52. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      yep. that'll do it. I expanded that idea by adding this to the .vimrc:

      "This unsets the "last search pattern" register by hitting return
      nnoremap :noh

    53. Re:Need a way to un-highlight by vontrotsky · · Score: 1

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit u but haven't found anything for vim.
      You can use :nohlsearch to turn off highlighting. And addin

      nmap <Tab>/ :nohlsearch<CR>

      to your .vimrc file will let you turn of the highlighting with Tab /

    54. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      :nohls will stop the highlighting until the next search. Not much better than /klwjerw, though.

    55. Re:Need a way to un-highlight by LunarCrisis · · Score: 1

      I my experience this works in the console versions as well, when you have mouse support enabled though the terminal and vim.

      --
      Mr. Period: Nine is the one that's right by ten!
      Nine: One day I will kill him. Then, I will be Ten.
    56. Re:Need a way to un-highlight by boomer_rehfield · · Score: 1

      sheeeeeeeezzzz..... I always thought that was a bug or something was screwed up somewhere....I've wasted a few years of my life unindenting pasted code. :cry

      --
      Carpe Canem - Seize the Dog
    57. Re:Need a way to un-highlight by boss_hog · · Score: 1

      :set nohighlight
      or
      :set nohl
      :set hl to turn it back on after turning it off.
      I have them bound to function keys via :map.

    58. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      You could turn off search highlighting: :set nohls

      or you could erase the current entry in your search history: :let @/ = ''

    59. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      Am I just a vim noob? After doing a search and loving the nice highlighting, is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"? In less(1), you'd hit u but haven't found anything for vim.

      :noh

      Too much typing

      put this in your .vimrc file

      map \ :noh<CR>

      Now when you hit the \ key it will remove the search highlighting.

    60. Re:Need a way to un-highlight by dwater · · Score: 1

      > it will automatically unindent it to the correct place

      It totally depends on the definition of 'correct'; it is often defined by the organisation for which you work. For example (although this is C++ rather than C, the same point applies) Qt has a particular 'style', and Symbian another, even though they're both C++.

      However, it is possible to write your own indent rules. See here for an example (which is actually broken, but anyway) :

      http://vim.wikia.com/wiki/Indenting_for_Qt_C%2B%2B

      and it's likely worthwhile spending some time developing the rules, esp. if there are more than just one of you using vim.

      --
      Max.
    61. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      To handle the paste problem, I use :r!cat

      after pasting add a newline then ^d and another newline.

      I love this because it is so orthogonal to the use of :r and !command..

      I just tried it and it worked... been using it for years now.

    62. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      Try putting this in ~/.vimrc

      nmap :nohlsearch:redraw!

      When you press CTRL-L it'll clear the current search highlight & redraw the screen. Works well for me :)

    63. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      I fail at HTML.
      Here's the correct command:
      nmap <C-l> :nohlsearch<CR>:redraw!<CR>

    64. Re:Need a way to un-highlight by Onymous+Coward · · Score: 1

      What Frizzle Fry said. And plus you don't need to clear the command line; don't output the information in the first place:

      map <silent> <F4> :set hlsearch!

    65. Re:Need a way to un-highlight by foxharp · · Score: 1

      :set sw=4

      will make a nice indentation shiftwidth, especially for using the indent command (>). Works great for programming, especially with autoindent (:set ai). But when programming with autoindent, you often need to unindent one shiftwidth... do that by typing control-D at the beginning of the line. You can go to the very beginning of an autoindented line with 0 control-D.

      if you're going to do a lot of coding, please don't get in the habit of using "sw" to change your indent. it results in a mixture of spaces and tabs on ever line which, while it sometime seems practical, is incredibly unpopular. i made this mistake long ago, and now have lots of code that annoys other people, and annoys me when other people edit it. (yes, i could convert it all, and sometimes i do, bit by bit.) it's better, if you want 4 column indents, to set your tabstop to 4, and use tabs for indenting. (set ts=4). in vile, you could use "set c-tabstop 4" to do this just for c-mode files. i assume there's a similar buffer-type specific setting for vim. (i'm not a vim user.)

    66. Re:Need a way to un-highlight by not_a_product_id · · Score: 1
      "After doing a search and loving the nice highlighting, is there a way to unhighlight the search term"

      If you're asking what I think you're asking ;-) you could try:

      let @/=""

      I think the idea is that since the / is your search you're setting it to be empty ("")

      --

      ---
      We spoke for about a half an hour. I don't recall a thing we said. - Colorblind James Experience

    67. Re:Need a way to un-highlight by mhandis · · Score: 1

      :noh

      No Highlighting

    68. Re:Need a way to un-highlight by Anonymous Coward · · Score: 0

      is there a way to unhighlight the search term without doing a "/lkasjdfkjdfdf"?

      :nohl

    69. Re:Need a way to un-highlight by IpalindromeI · · Score: 1

      I always use "+, too. Apparently, "+ and "* are equivalent in Windows. Under X, "* uses the PRIMARY X selection (visually selected stuff), whereas "+ uses the CLIPBOARD selection (used when you do a Cut or Copy from an app's menu).

      --

      --
      Promoting critical thinking since 1994.
  15. % - jump between braces, ifdefs, etc by tippe · · Score: 2, Informative
    Also:

    v, V and ctrl-V (various visual selection modes for copy-paste)

    zf, zo, zc: fold creation, open, close (hides sections of your code)

    ~: (toggle case)

    u, ctrl-r: undo, redo

    "vimdiff" or "vim -d": (visual diff of two files)

  16. So many by dedazo · · Score: 1

    gF: Open the file under the cursor, for #include statements and even classes for languages like C# or Python (if they're in the same directory). Very nifty.

    %: Match the brace under the cursor.

    Some of my favs are the text object commands in visual mode, like placing the cursor inside a string literal and doing vi" to select the inner portion of the string and then c to start changing it without having to re-type the quotes. viB selects the current inner brace block, vaB the outer block (including braces), good for refactoring and so on.

    * Start an auto search for the word under the cursor.

    ~: Swap the case of the char under the cursor.

    So many...

    --
    Web2.0: I love when people Flickr my cuil and digg my boingboing until my google is reddit and I start to yahoo
    1. Re:So many by IpalindromeI · · Score: 1

      like placing the cursor inside a string literal and doing vi" to select the inner portion of the string and then c to start changing it without having to re-type the quotes

      ci"

      --

      --
      Promoting critical thinking since 1994.
  17. split by gsn · · Score: 1

    :sp to split the screen
      to toggle between
    made my life a lot easier

    --
    Reality must take precedence over public relations, for nature cannot be fooled.
    1. Re:split by gsn · · Score: 1

      er ctrl-w-w
      (forgot about tags)

      --
      Reality must take precedence over public relations, for nature cannot be fooled.
    2. Re:split by James+McGuigan · · Score: 1

      :split <filename> (open new file in split) :vsplit % (open current file in vertical split) :only (close other splits)
      Ctrl-W Arrow (move around)
      Ctrl-W 10+ (increase split size by 10 lines)
      Ctrl-W 20- (decrease split size by 20 lines)
      Ctrl-W = (make all splits equal) :tabnew :tabnext :tabprev (vim 7 tabs)

    3. Re:split by James+McGuigan · · Score: 1

      Also use :diffsplit <filename> to diff one file with another.

      Use :diffget and :diffput to shift changes between the two files

      Get the VCSCommand vim plugin (one of the most useful plugins, but there are many more), and do :VCSVimDiff r200 and get an interactive diff with your repository (svn,cvs,git) or things like :VCSBlame, :VCSCommit, :VCSLog, :VCSRevert etc

      If you have two files open you can on diff mode using :diffthis and :diffoff

    4. Re:split by the_greywolf · · Score: 1

      ^W-v and ^W-s :vsp and :sp

      If you're using Vim 7, :help tab-page

      My terminal is wide (170+ chars), so I vsplit a lot.

      --
      grey wolf
      LET FORTRAN DIE!
  18. Props to Douglas Adams by Anonymous Coward · · Score: 0

    :help 42

  19. WTF?? by monkeySauce · · Score: 5, Funny

    I typed :Sex and it opened up a HUGE list of folders choc full of porn!

    1. Re:WTF?? by snspdaarf · · Score: 4, Funny

      Congratulations! You found the Easter egg!

      --
      Why, without your clothes, you're naked, Miss Dudley!
    2. Re:WTF?? by s0m3body · · Score: 1

      Stop Using It In Your Homedir !

    3. Re:WTF?? by Anonymous Coward · · Score: 0

      I tried it. =( Didn't work for me.

    4. Re:WTF?? by JuicyBrain · · Score: 1

      All right !

      Now, to see it try :%d

  20. :q by Anonymous Coward · · Score: 0

    :q

    every first time user needs to know how to get out of it when nothing he tries works. reminds me of that bash.org post.

  21. Why asking... by GerardAtJob · · Score: 1

    RTFM : http://www.vim.org/htmldoc/help.html Damn... :q!kill -9 !^ ty.. now that the frustration is gone I'm feeling so much better... pls post interesting news :)

    --
    I can't call that English ;-)
  22. Viewing hexdumps of binary files in vim. by CheeseMonger · · Score: 0, Interesting

    First edit the file in binary mode
    vim -b datafile
    Now convert the file to a hex dump with xxd
    :%!xxd
    Well, I thought it was cool.

    --
    CheeseMonger
  23. Re:Just using VIM by Anonymous Coward · · Score: 0

    that would be quite a trick in general since its not CLI....

  24. Re:Just using VIM by Anonymous Coward · · Score: 0

    depends what you're doing. i find textedit useful for some things but for most of my work I use vim and find it much more efficient. too bad there's a rather large learning curve.

  25. Re:Just using VIM by Anonymous Coward · · Score: 0

    Oops I meant textmate.

  26. let counter= by Anonymous Coward · · Score: 0

    counters in vi...Perfect for DNS edits.

    let counter=108|149,%g/con11\-70/let counter=counter+1|s/109/\=counter.''

  27. Vim 7's vimgrep feature by Anonymous Coward · · Score: 0

    I really like the vimgrep feature in Vim 7. Once you execute it, use :cope to open the results in a split window.

  28. Re:Just using VIM by Anonymous Coward · · Score: 1, Informative

    I know the emacs vs. vi holy war is a funny old meme, but why not just use a modern-style editor? We have these powerful graphical desktops with very standard interfaces. I'm sure the old classics give you a lot of power (Actually, I don't know that much about vim, but I understand you can run Eliza, NetHack, or a Lisp interpreter in emacs), but who wants to learn a bunch of obscure commands and meta-keystrokes? If you just need to edit some text, there are simpler solutions. Me, I use Kate.

  29. Deleting lines by Anonymous Coward · · Score: 0

    One of my favorite Vi commands... dunno where I even found it: :.,$d

    Delete everything from this line down... Comes in handy when chopping a file down to size.

    1. Re:Deleting lines by sarabob · · Score: 1

      dG in command mode also deletes from current position to the end of the file (in vim, at least)

    2. Re:Deleting lines by Frizzle+Fry · · Score: 1

      VGd will accomplish the same thing with less keystroks.

      --
      I'd rather be lucky than good.
    3. Re:Deleting lines by Sancho · · Score: 1

      I find it easier to type dG. Same effect, fewer keystrokes.

    4. Re:Deleting lines by __1200333 · · Score: 1

      I prefer dG - seems a lot simpler to use and remember (gg takes you to the top, G takes you to the bottom, etc...)

    5. Re:Deleting lines by svennieboy · · Score: 1

      I usually just use dG (saves on keystrokes).

      --
      -- Slackware linux... because wizards are for wussies
    6. Re:Deleting lines by pimpimpim · · Score: 1
      with less keystroks

      it seems like you sure are an expert on efficient use of keystrokes ;)

      --
      molmod.com - computing tips from a molecular modeling
    7. Re:Deleting lines by Anonymous Coward · · Score: 0

      One of my favorite Vi commands... dunno where I even found it: :.,$d

      Shorter form:
      dG

  30. keyword completion by Anonymous Coward · · Score: 0

    While in insert mode and typing a very long word/variable that you typed a few lines before, press: CTL+p

    1. Re:keyword completion by Anonymous Coward · · Score: 0

      While in insert mode and typing a very long word/variable that you typed a few lines before, press: CTL+p

      Or CTRL-N.
      Note, it is not just the lines in the buffer you are editing, but it pulls that list from all open files you are currently editing (assuming :set hidden).

  31. delete a block of lines larger than the screen by prgrmr · · Score: 3, Informative

    move up to the top line of the block to be delete

    mm (sets a marker "m")

    move down to the last line in the block

    d`m (deletes to marker "m", and that's the grave below the tilde, not the back-quote)

    1. Re:delete a block of lines larger than the screen by oever · · Score: 1

      Or go to visual mode with 'v' or 'V', scroll down and press 'd'.

      --
      DNA is the ultimate spaghetti code.
    2. Re:delete a block of lines larger than the screen by HeXetic · · Score: 1

      Uh, maybe you're using a different keyboard than me, but for those of us on the standard US PC-104 clicker, the "grave below the tilde" *is* the back-quote (also known as the back-tick).

      --
      http://www.chmodoplusr.com/
    3. Re:delete a block of lines larger than the screen by Kent+Recal · · Score: 1

      Much easier:

      Go to the start-position (from where to delete)
      Press v
      Move down to the end position
      Press d

    4. Re:delete a block of lines larger than the screen by Anonymous Coward · · Score: 0

      if the block is enclosed in braces {} you can delete the whole block without marks thusly:

      daB

    5. Re:delete a block of lines larger than the screen by Deadplant · · Score: 1

      or if you know the number of lines
      d10 down arrow

      or d/regex to delete until regex match

    6. Re:delete a block of lines larger than the screen by James+McGuigan · · Score: 2, Informative

      Use Ctrl-v and you can select a column of chars. You can copy, delete and paste them.

      I have used this technique, along with vertical alignment of code, to quickly copy/paste a huge spreadsheet of expected results, into very exhaustive unit test code.

    7. Re:delete a block of lines larger than the screen by Anonymous Coward · · Score: 0

      This is just a specific case of a very powerful "combo" system that exists because things like 'd' (delete) and 'c' (change) allowing an arbitrary "movement" command after them to define the extent of the text that the operation should operate upon. Usually, repeating the operation letter means "the current line", which is why 'dd' deletes the current line and 'cc' removes the current line and puts you into insert mode.

      So, once you learn some of the interesting "movement" commands, such as:

      f<letter> ("find" (move to) next instance of <letter> in the current line)
      w (move to the next 'word')
      0 (move to the start of the line)
      $ (move to the end of the line)
      `<letter> (move to the position 'marked' with the letter) - your example
      '<letter> (that's the single-quote version - move to the start of the LINE 'marked' with the letter) ... and then appreciate that most "movement" commands which make sense to have one, can be preceded by a count of how many times to perform the command (so '2fx' places the cursor at the 2nd 'x' in the line from the current position, '3/foo' places the cursor at the 3rd instance of "foo" in the file from the current position etc etc), you realise you can do all sorts of funky things with those 'c' and 'd' commands:

      c2w (Change two words)
      d4w (delete four words)
      d5/foo (delete from the current position up to the 5th instance of 'foo' in the file).

      etc.

      And for the purists, AFAIR this is all pure 'vi' (pronounced 'vee eye' ;)) too - no vim extensions.

    8. Re:delete a block of lines larger than the screen by mebrahim · · Score: 1

      I use visual mode (actually visual-line) for that purpuse. Try shift+v!

    9. Re:delete a block of lines larger than the screen by Anonymous Coward · · Score: 0

      Um, the "grave below the tilde" IS the back quote. You have another back quote on your keyboard?

    10. Re:delete a block of lines larger than the screen by Anonymous Coward · · Score: 0

      if you are lucky enough to have vim why not just 'shift-v' and visually select the lines you want to be deleted and then type 'd'.

  32. Most time-saving features by Anonymous Coward · · Score: 1, Interesting

    1. Tags. No learning curve. Generate tags with !ctags -R *.c *.h (if you are looking at a C code base). Ctrl-] on any function name, structure name/field, etc. to jump to the declaration point. Ctrl-T to come back. Tag stack is maintained. Then, :ta to jump to the tag. Auto completion for the tag name makes it a breeze. Ctrl-], Ctrl-T, and :ta are enough to save 50% of your time.

    2. Ctrl-P and Ctrl-N for very smart auto-completion can save another 30-50% of your time.

    3. Record a sequence of key strokes and replay them. Hit 'q', , 'q', , 'q' . Then, hit @f to repeat those actions. @@ to repeat the previous @ command. So one can do: @f, then, @@, @@, wherever they want to apply the changes.

    4. Hitting 'gf' on a header file will take you to the header file (not to your girlfriend). Hit Ctrl-O to come back.

    5. Use j,k,l,; to move up, down, left, and right. Learn touch typing.

  33. Stupid vi tricks? by argent · · Score: 2, Funny

    VIM is a "stupid vi trick".

    Every time I update OS X no I have to dike it out and put the REAL "vi" back.

    1. Re:Stupid vi tricks? by mario_grgic · · Score: 4, Insightful

      Ah, add "set compatible" to your .vimrc file and you have 99% vi behavior.

      Why would you use plain vi, when vim is so much better?

      --
      As the island of our knowledge grows, so does the shore of our ignorance.
    2. Re:Stupid vi tricks? by Anonymous Coward · · Score: 5, Funny

      Stupid vi tricks? (Score:2)
      by argent (18001)

      I believe you and your fancy VIM are on this man's lawn.

    3. Re:Stupid vi tricks? by ld+a,b · · Score: 0

      That 1% matters the most to us.
      If I am faced with a fresh install of Ubuntu and vim comes up when I type vi, I solve the bug quickly by using the :!sudo apt-get install nvi && vim command. I don't know if that qualifies as a vim trick, though.

      --
      10 little-endian boys went out to dine, a big-endian carp ate one, and then there were -246.
    4. Re:Stupid vi tricks? by CoolVibe · · Score: 1

      *ahem* :)

  34. best trick by WillAffleckUW · · Score: 1

    use vi raw instead.

    Don't yank my line!

    --
    -- Tigger warning: This post may contain tiggers! --
  35. Use '=' and 'gq' together... by wanerious · · Score: 1

    A good partner to the indenting keystroke "=" is "gq", to automatically format highlighted text that is messy from copy/pastes. I use the pair all the time to save headaches.

    1. Re:Use '=' and 'gq' together... by Qzukk · · Score: 1

      :set paste! to avoid the headache in the first place. :set pt=<f1> to avoid the headache of typing :set paste! every time you want to switch in and out of paste mode

      --
      If I have been able to see further than others, it is because I bought a pair of binoculars.
    2. Re:Use '=' and 'gq' together... by wanerious · · Score: 1

      Well, I really meant the cutting/pasting within the document, like joining a few lines together with repeated 'J's and then doing a 'gq' on the unsightly text. But point taken.

  36. Re:Just using VIM by tchuladdiass · · Score: 5, Insightful

    If you are on a single box, that is fine. But when you have to admin about 500 servers, spread out across the country, and sometimes over a dial-up link, you often don't have a graphical environment available. Even on the local network, I often ssh from one box to the next, and forget to forward my X11 connections. Since vi is always available, that is what I use.

    The other thing is that I appreciate having only minimal hand movement to get around a file and make changes. Much like people used to love the Word Star diamond, the same thing with vi's ctrl-f, ctrl-b, h, j, k, l, etc. And since I've been using it for about 20 years, these commands are second nature to me. Not to mention the search/replace supporting regular expressions (something a lot of gui word processors don't have).

  37. Buy the book by pauljlucas · · Score: 1

    There's lots of good stuff in here.

    --
    If you reply, do so only to what I explicitly wrote. If I didn't write it, don't assume or infer it.
    1. Re:Buy the book by game+kid · · Score: 1

      Anyone else misread the URL as "...Steve Ovaltine..."?

      I need more sleep :-(

      --
      You can hold down the "B" button for continuous firing.
    2. Re:Buy the book by AchiIIe · · Score: 1

      You don't need to buy the book. Steve has made the book freely available, and since then Bram has incorporated the book into the vim manual.

      See Bram Moolenar's google talk on VIM (7 habits for effective editing)
      > http://video.google.com/videoplay?docid=2538831956647446078

      --
      Nature journal lied in Britannica vs Wikipedia Ask to retrac
    3. Re:Buy the book by Constantine+XVI · · Score: 1

      No... you need to drink your Ovaltine!

      --
      "I think an etch-a-sketch with an ethernet port would beat IE7 in web standards compliance."
  38. Re:Just using VIM by tolan-b · · Score: 5, Insightful

    Try using most GUI editors on a remote server over ssh. Kate may be an exception with KDE's nice network abstraction I don't know (I use Gnome), but to be honest for me the main utility of vi is that I know it's going to be there in any Linux enviroment (and I suspect Unix in general).

  39. Ha Ha Ha by Greyfox · · Score: 1
    Back in the mid 90s I had a job auditing source code for Data General. I mostly did the C standard library, but a co-worker of mine got the vi source. The original AT&T vi source. He found a comment in there, dated sometime in the 70s, saying that the programmer didn't like the way the terminal was handled in this particular chunk of code and making a note to fix it one of these days. But my co-worker was also quite impressed with vi and started using it after that. I, being an emacs proponent (To this very day) suggested to him that he could run emacs with the emacs vi emulation and get the best of both worlds.

    Amusingly he did check out the emacs vi emulation to see how well it conformed to the operation of actual vi. I don't recall what his verdict was, though. And for a few years after that I was quite sensitive to the places where vim behaves differently from vi. I still prefer a no-frills vi when I'm using vi, even though I use emacs from most heavy editing tasks.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    1. Re:Ha Ha Ha by mattack2 · · Score: 1

      I admittedly can't find it at the moment, but do you notice the differences even if you tell vim not to use any vim specific features? (it's not -v, at least according to the man page.. that says it only matters if the executable is called 'ex')

      I probably only use 4-5 (at most) features of vim over vi, with a few more rarely (split windows relatively rarely except for looking through the help just now).

    2. Re:Ha Ha Ha by DiegoBravo · · Score: 1

      Well, since a long time I'm used to the Vim syntax highligthing/identation when I write some piece of C (of course in Java the IDE is in another league.) I found annoying when Vim is not configured with that support.

    3. Re:Ha Ha Ha by Greyfox · · Score: 1
      Yeah, I usually use emacs these days, but vim rubs me the wrong way. I usually end up uninstalling it and installing nvi instead. nvi advertises as bug-for-bug compatible with the original vi. I don't recall exactly what has bothered me about vim in the past other than the syntax highlighting. That's always struck me as an unnatural thing for vi to do. I believe that most of the things that bother me about the editor can be fixed with a little tweaking of the editor's config file, though.

      I've run across a couple of UNIX configurations that have had emacs or... pico... defined as the default editor. Whoever made those choices should be stabbed in the face. When I want to edit my crontab file, nothing but vi will do. And pico is an abomination anyway and should never be included by default with ANY operating system. I'm seriously, freaking WORDPAD is better than pico. But I digress...

      --

      I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

    4. Re:Ha Ha Ha by Anonymous Coward · · Score: 1, Informative

      You can get the traditional vi here:
      http://ex-vi.sourceforge.net/

    5. Re:Ha Ha Ha by eneville · · Score: 1

      I put all my favourite vim tricks here: http://www.s5h.net/vim.html, I used it all day every day.

    6. Re:Ha Ha Ha by metamatic · · Score: 1

      I don't recall exactly what has bothered me about vim in the past other than the syntax highlighting. That's always struck me as an unnatural thing for vi to do.

      Why did you turn it on, then? (Given that it's off by default.)

      --
      GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
    7. Re:Ha Ha Ha by marnues · · Score: 1

      It's off by default if you install it from source. I don't think I've ever seen a Linux package that doesn't enable it by default though. And good for that. Vim is my IDE of choice. If only Eclipse supported different editors and I could just drop it in. It'd be better than the vi Eclipse hack (albeit a good one).

  40. 1,.d by TheCarp · · Score: 1

    Thats right, first post, just delete all the lines before this one.

    The ability to do any operation on a subset of lines, itself, is so useful. I was working with a n00b showing him some tips to polish up a script that he wrote. Of course he used the same string like 20 different times, and it contained a version number.

    So I showed him how to break it out into a variable at the top then moved to the next line and :.,$s/foobar35/$dirname/g

    Or when dealing with a log file with lots of useless information using :g/pattern/d to remove all of the lines that don't have any use can really make the problem just pop right out at you

    -Steve

    --
    "I opened my eyes, and everything went dark again"
  41. Re:Just using VIM by eosp · · Score: 1

    I learned Vim at a young age, and it has grown on me. I just prefer it now. Call it curmudgeonliness if you wish.

  42. some useful things by Anonymous Coward · · Score: 0

    Ctrl-v ...for block select.

    Ctrl-n ...(or Ctrl-p) to autocomplete words. /string\c ...to search case insensitive (because of \c).

    U | u ...with text selected to (de)capitalize text.

    u ...to undo last changes

    Ctrl-R ...to redo last changes

    Also, after selecting text (with V): copy (yy), paste (p), delete (d).

  43. Tabs! by solipsist0x01 · · Score: 1

    auto-completion: Ctrl + n

    especially with this in my .bashrc...

    alias gvim="gvim -p --remote-tab-silent"

    then formatting the tab title with this in .vimrc...

    " Customize the information in the tab lables
    function! GuiTabLabel()
        " add the tab number
        let label = '['.tabpagenr()

        " modified since the last save?
        let buflist = tabpagebuflist(v:lnum)
        for bufnr in buflist
            if getbufvar(bufnr, '&modified')
                let label .= '*'
                break
            endif
        endfor

        " count number of open windows in the tab
        let wincount = tabpagewinnr(v:lnum, '$')
        if wincount > 1
            let label .= ', '.wincount
        endif
        let label .= '] '

        " add the file name without path information
        let n = bufname(buflist[tabpagewinnr(v:lnum) - 1])
        let label .= fnamemodify(n, ':t')

        return label
    endfunction

    set guitablabel=%{GuiTabLabel()}

  44. One tip: by dealmaster00 · · Score: 1

    Shift + ZZ will save and quit.

  45. Some of my favorites by Vornzog · · Score: 1

    In your .vimrc:

    Reformat the current paragraph (great for editing text):
    nnoremap Q gqap
    vnoremap Q gq

    Incremental searching:
    set incsearch

    Insert a comment character on multiple rows - use this to do a visual select and comment out a code block:
    (ctrl-v) -> visually select a column
    (shift-i) -> go to insert mode
    (your favorite character here - I like #)
    esc, esc

    Find a good set of fold rules and syntax highlighting for your favorite programming language. This has become an essential part of the way I work.

    Those are some of my favorites. I discover something new about once a week, despite having used vim for years now.

    --

    -V-

    Who can decide a priori? Nobody.
    -Sartre

  46. Re:Just using VIM by eln · · Score: 5, Funny

    Young whippersnappers. When I was "at a young age", it was called vi, and it didn't have any of this fruity syntax highlighting, and if you wanted to navigate around a document you had to use h,j,k,l, not those hand-holding arrow keys.

    Remember the old dig at emacs, "Eight Megs and Constantly Swapping?" Well back then, an 8 MB program actually did mean constant swapping!

    I've been in this business for too damn long.

  47. Most powerful of them all... by javab0y · · Score: 1

    :!sudo rm -rf /*

    DOH! No really - don't do that.

  48. gg=G by MonoSynth · · Score: 1
    • gg=G to reindent a whole file
    • Ctrl-L to redraw the screen (to fix broken syntax highlighting)
    • Fortunately Esc doesn't do strange things in Firefox
  49. Stack Overflow by JPLemme · · Score: 4, Insightful

    When did Slashdot become Stack Overflow?

  50. Re:Just using VIM by careysb · · Score: 2, Funny

    When I was your age I wrote thousands of lines of C code using EDLIN. (P.s. this was on a *nix box not DOS) (P.p.s Also walked to school 5 miles, up-hill, barefoot, in the snow, both ways)

  51. Re:Just using VIM by 32771 · · Score: 1

    Well it is not just editing some text anymore for me. It is more software development where you would want something like eclipse.

    For some odd reason I'm still using XEmacs. You don't have to use the mouse if you don't want to. Indentation works nicer under XEmacs than with eclipses Emacs mode. It is just not the same, even though eclipses project management is nice.
    Lets not start with search and replace - I don't need a silly window for that.

    Fortunately there is still ecb and cedet to improve emacs code browsing a bit.

    Now if somebody could tell me whether there is a ddd plugin for eclipse I might give up on emacs and switch over.

    --
    Je me souviens.
  52. Vimperator by Anonymous Coward · · Score: 1, Informative

    Not directly related to VIM itself but, Firefox plugin called Vimperator...gives web browsing vimlike commands

    1. Re:Vimperator by Anonymous Coward · · Score: 0

      This is so damn awesome, I think I've gotten some of my friends who normally use Emacs to use it :)

    2. Re:Vimperator by agentultra · · Score: 1

      i love my vimperator.

      i actually find it annoying and difficult to use any other browser without it.

  53. Re:Just using VIM by jaredmauch · · Score: 2, Insightful

    Yes, please tell me about your years spent on Ultrix, Altos and other boxes. You modern kidz and your GUI. The main reason why I use OSX is because I can ssh *and* run Microsoft office at the same time. If you don't understand syntax like

    run *kermit

    load * (Oh, the magical keys on the c64)

    and having to spend time at bps rates lower than 9600 when performing tasks, you clearly don't appreciate the speed increases over the years the same as some of us. I remember going from 300->1200->2400bps. Now I spent my time tracking IEEE HSSG for 100Gb/s interfaces, because I will likely have a need to bundle them.

    I get really sad when I see wasteful memory and cpu bloat. Perhaps these will become scarce resources again with the mobile trend, and people will do a better job watching their consumption. Oh well.

  54. Re:Just using VIM by Sancho · · Score: 4, Insightful

    I use Vim primarily because I can perform almost any task without moving my fingers from the standard typing position. I certainly feel much more efficient being able to (for example) use j/k/l/h for movement than moving my hand over to the arrow keys, or worst, to the mouse. That's one of many tasks which simply becomes natural over time (in fact, when I'm typing in a web form, I frequently find myself trying to use Vi shortcuts) and which really make things go more smoothly for me. Even when I'm on a full desktop, I prefer using Vim. I only wish the OS X port of gvim worked better.

    The reason that I don't use EMACS is because of the finger gymnastics you have to perform for even the simplest of tasks. Of course, one could complain similarly about Vi--having to switch to command mode is something that gets just about every single newbie.

  55. Perhaps two of the weirdest: Ctrl-A and Ctrl-X by sdt · · Score: 2, Informative

    (in vim only), Ctrl-A and Ctrl-X find the next number on the line starting at the cursor, and then increment or decrement it respectively.

    Apart from being weird, these are surprisingly useful sometimes, e.g. toggling "#if 0" to "#if 1"...

    1. Re:Perhaps two of the weirdest: Ctrl-A and Ctrl-X by Waffle+Iron · · Score: 1

      I use those all the time. It is strange how often they are useful. My only complaint with them is that if the number has leading zeros, then it assumes octal (07 -> 10), and if it's preceded by a dash, it assumes negative numbers. This can be an annoyance when tweaking dates like 2008-06-07.

    2. Re:Perhaps two of the weirdest: Ctrl-A and Ctrl-X by asc99c · · Score: 1

      I use them all the time also.

      :set nf="hex"

      nf controls the number formats recognised by vim - the default is "octal,hex". You can also add alpha and it will increment letters alphabetically, but I like it to automatically find the next number and increment that.

    3. Re:Perhaps two of the weirdest: Ctrl-A and Ctrl-X by mebrahim · · Score: 1

      Wow! Now I know why most of my codes weren't working. You should have told me this sooner.

    4. Re:Perhaps two of the weirdest: Ctrl-A and Ctrl-X by StarFire_FIN · · Score: 1

      I find ctrl-a and ctrl-x to be very useful. In fact, I have a nifty script in my .vimrc that uses ctrl-a.

      " this function repeats the given command for the given amount of times
      function! Repeat(times, cmd)
      let i = a:times
      if i <= 0
      let i = 1
      endif
      while i > 0
      execute a:cmd
      let i = i - 1
      endwhile
      endfunction

      " define CTRL-Z to copy this line to the next line, but increment the number
      " under the cursor for that line. sets the 'q' mark and overwrites the unnamed
      " register with the line that has the number incremented.
      nmap <C-Z> :<C-U>call Repeat(v:count, "normal mqyyp`qj<C-A>yy")<CR>

      Very useful when you have a line of code with a number on it, and you need to replicate that many times and increment the number. Like with case statements:

      case DEFINED_123_CONSTANT_0:

      It accepts numeric arguments, so you can move your cursor past the '123' and then press 4ctrl-z and you get:

      case DEFINED_123_CONSTANT_0:
      case DEFINED_123_CONSTANT_1:
      case DEFINED_123_CONSTANT_2:
      case DEFINED_123_CONSTANT_3:
      case DEFINED_123_CONSTANT_4:

      I've found this useful very, very often.

  56. Often ignored: ex mode by kyrmit09 · · Score: 1

    Hi, the ex-mode isn't as straight forward as the commands for vi but comes in handy at times. A rough and tumble way to view methods in a perl module ":g/sub/p", or public java methods in a java class ":g/^public/p". Also helpful to filter all the stack dumps from the jboss (or other java related ) logfile to get some non generic error messages ":v/\tat/p".

  57. dos2unix equivalent by CyberSnyder · · Score: 1

    %s/(then press ctrl-v crtl-m)//

    I never knew how to get the ^M on the command line and found it a week or two ago after doing unix since '93.

    1. Re:dos2unix equivalent by maharg · · Score: 1

      you can also :set fileformat=unix or :set fileformat=dos appropriately

      --

      $ strings FTP.EXE | grep Copyright
      @(#) Copyright (c) 1983 The Regents of the University of California.
    2. Re:dos2unix equivalent by 4D6963 · · Score: 1

      doesn't vim have the ability to convert between the different kinds of line breaks?

      --
      You just got troll'd!
    3. Re:dos2unix equivalent by ThePhilips · · Score: 1

      :set ff=unix will not work with files with broken encoding. :%s/^V^M//g with :set ff={dos,unix} makes sure that all lines would have proper ending.

      --
      All hope abandon ye who enter here.
    4. Re:dos2unix equivalent by ThePhilips · · Score: 1

      The trick helps to correct files with broken encoding.

      :set ff=... would work properly afterward.

      --
      All hope abandon ye who enter here.
  58. Especially useful for PERL by ickyb0d · · Score: 2, Informative

    To create a comment block:

    move cursor to the start of the comment block
    ma - creates a mark called "a"
    scroll down to the end of the comment block

    :'a,.s/^/#/ - to create comment block
    :'a,.s/^#// - to remove comment block

    basically puts # at the start of every line from mark a to your current cursor position. You can get creative and use this method for tons of things, indenting, substituting words within a given scope, comment blocks, etc.

    1. Re:Especially useful for PERL by doti · · Score: 1

      So you like Perl. How about this one:


      autocmd! FileType perl FileTypePerl
      command! FileTypePerl setlocal makeprg=perl\ -c\ %
      \ | setlocal keywordprg=perldoc\ -f
      \ | setlocal cindent
      \ | setlocal errorformat=
      \%-G%.%#had\ compilation\ errors.,
      \%-G%.%#syntax\ OK,
      \%m\ at\ %f\ line\ %l.,
      \%+A%.%#\ at\ %f\ line\ %l\\,%.%#,
      \%+C%.%#

      After putting this in your vimrc, :make will run "perl -c" to check the syntax, and Vim will interpret the errors just like with gcc. (":help quickfix" if don't know this yet.)

      --
      factor 966971: 966971
  59. Re:Just using VIM by Anonymous Coward · · Score: 0

    The reason I started using Emacs is simply ESS. It provides a common interface and interactive use to the most common statistical analysis programs. From there, I saw the light. I now use it for just about everything, I actually get excited about using it. I could never work at a job that didn't allow me to use Emacs. The power is simply amazing (I love that I can do EVERYTHING in it). Give it a try, a real try... you'll never go back.

  60. beep beep by maharg · · Score: 1

    to make vi[m] beep, just press Esc Esc ;o) Also :e! restores to the previously saved version

    --

    $ strings FTP.EXE | grep Copyright
    @(#) Copyright (c) 1983 The Regents of the University of California.
    1. Re:beep beep by CableModemSniper · · Score: 1

      Oo, :e!. I've been using :e! %. Good one.

      --
      Why not fork?
  61. Re:Just using VIM by el+momia · · Score: 5, Informative

    :%s/foo/bar/g go through all the file and replace foo by bar :12,20s/foo/bar/ from line 12 to 20 replace foo for bar :s/foo/bar/g in the current line replace foo for bar the g after the last / means to replace all the occurrences of foo vby bar and not only the first one.

  62. Re:Just using VIM by eln · · Score: 1

    9600 bps was especially thrilling, since it was the first time I had a modem where the modem actually displayed text faster than I could read it. With 2400 (and especially 1200 and 300) I would have to read, pause waiting for more text to come through, read, pause, etc.

    When 14.4k came along, I could actually MUD without buffering a screen of commands at once while the modem caught up to me.

  63. Tab Size by Maltheus · · Score: 1

    The first thing I do on any new account is set the tab size to a reasonable 4 character width:

    echo "set tabstop=4" >> ~/.vimrc

    1. Re:Tab Size by ThePhilips · · Score: 1

      You should also then :set sw=&ts too (set shiftwidth (sw) to size of tabstop (ts)). That way file would be properly indented with tabs. e.g. you can then set ts=2 or ts=3 or ts=8 and file would change its look accordingly.

      In past, when I worked with some micro-softies, I had a shortcut like :map :normal ":set sw=".(12-&ts)." ts=".(12-&ts) (can't be sure about syntax, lazy to check). Pressing F8 was toggling tabsize between 4 and 8 spaces (12 - 8 = 4; 12 - 4 = 8; etc). Was really handy.

      --
      All hope abandon ye who enter here.
  64. Re:Just using VIM by Bandman · · Score: 4, Insightful

    Amen. Know vi, and know the bourne shell, and you're good on close to 100% of the unix machines you'll ever touch.

  65. :help by Anonymous Coward · · Score: 0

    nnoremap <C-h> :<C-u>help<Space>

  66. ctrl-a, ctrl-x to increase/decrease integer value by Anonymous Coward · · Score: 0

    assuming you are working with C, you can use ctrl-a and ctrl-x to raise or lower the integer immediatly below the cursor.

    It even works for hex.

    so

    int a = (ctrl-a) becomes
    int a = 6

    Awesome!

  67. $ emacs -n by Anonymous Coward · · Score: 0

    problem solved

  68. Re:Just using VIM by Waffle+Iron · · Score: 1

    Of course, one could complain similarly about Vi--having to switch to command mode is something that gets just about every single newbie.

    I solved that by adding imap <M-f> <ESC> to my .vimrc file. If your keyboard has a short spacebar, hitting Alt+F can be done almost subconsciously without moving fingers off the home row. I find it much better than reaching for the ESC key.

  69. oh dear by maharg · · Score: 1

    I just typed 1G to try and get to the top of this webpage.

    --

    $ strings FTP.EXE | grep Copyright
    @(#) Copyright (c) 1983 The Regents of the University of California.
    1. Re:oh dear by crunch_ca · · Score: 1

      I take it you don't have vimperator installed.

    2. Re:oh dear by Anonymous Coward · · Score: 0

      If you're using Firefox, the vimperator plugin will let you do just that: https://addons.mozilla.org/en-US/firefox/addon/4891

    3. Re:oh dear by asc99c · · Score: 1

      Wow - I love it! Never even thought such a thing might exist. Although firefox by default has the forward slash for a quick search anyway, which I think is probably the most used vim command I'd use in Firefox.

    4. Re:oh dear by doti · · Score: 1

      best firefox plugin evar.

      --
      factor 966971: 966971
  70. copy-paste by jakel2k · · Score: 1

    Being corrupted by Windows copy and paste... I remap the following keys.

    <Ctrl-a> Increment mapped to <F3>
    <Ctrl-x> Decrement mapped to <Shift-F3>
    <Ctrl-v> Block select mapped to <Ctrl-q>


    ### .vimrc ###

    :noremap <F3> <C-A>
    :noremap <S-F3> <C-X>
    set nocompatible
    source $VIMRUNTIME/mswin.vim
    behave mswin
    :inoremap <C-Q> <C-V>
    :vnoremap <C-Q> <C-V>

  71. Some basic but useful commands by Maexxus · · Score: 2, Insightful

    Very basic commands, but the ones I use the most are:
    o - Open a new line in insert mode
    cw - Delete word and enter insert mode (change word)
    dw - Delete word
    d$/c$ - Delete/Change to end of line
    dd - Delete Line and Yank
    yy - Yank Line
    p - Paste

    These simple commands alone make Vi/Vim very fast for editing.

    1. Re:Some basic but useful commands by rastos1 · · Score: 1

      yy - Yank Line
      p - Paste

      In fact there can be much more fun with buffers. You can have one for every letter:

      Yanking:
      "{buffername}{cursor movement}
      such as:
      "ay2w - to buffer a yank 2 words
      "by5j - to buffer b yank 5 lines down starting at cursor position
      also:
      "cdw - delete a word and put it in buffer c

      Pasting:
      "{buffername}{p|P}
      such as:
      "bp - paste content of buffer b after current cursor position
      "aP - past content of buffer a at current cursor position

      And the best thing is that it worked already in 1996 when I met vi. However I'm missing good (read short) documentation of vi basics. The documentation has grown too much with descriptions on code folding, syntax highlight, autocompletion, etc. etc. - and a newbie has no chance to find simple commands for moving around the screen (such as H - top "home" of screen, L - bottom "low" of screen, Ctrl-f - forward one page, Ctrl-u up one page, ... ) in that. Also :map used to be good one - before all keystrokes and keystroke-combinations got assigned to something :-)

    2. Re:Some basic but useful commands by Onymous+Coward · · Score: 1

      d$/c$ - Delete/Change to end of line

      D and C will do the same.

  72. :set hlsearch -- highlights all searched by Jameson+Burt · · Score: 1

    :set hlsearch
    Then when you search, every instance gets simultaneously highlighted.
    For example, searching for "brittle",
    /brittle

    Remember, to repeat a search (eg, for "brittle"), forward/backward, enter respectively
    n
    N

  73. Most used command by cranesan · · Score: 1

    ":x" this will 'save and quit'. It is much more efficient then the ":wq" that most people learn.

    1. Re:Most used command by ZzzzSleep · · Score: 1

      "ZZ" is even faster, and can be done easily with one hand.

  74. Sort by k33l0r · · Score: 1

    :sort

    Especially for those /etc/portage/package.* files... :sort brings some measure of sanity to them.

  75. see hidden chars , tabs , ^M etc. by deadly · · Score: 1

    :set list

    and to cancel :set nolist

  76. Why should I learn vi?? by Anonymous Coward · · Score: 0

    Hi,

    this is not a troll question, but really, why should I learn it??

    I do my development work in Visual Studio / Netbeans / Jdeveloper.

    These tools are not just editors, they support platform / technology specific features and I can't imagine doing stuff with anything but the tool (e.g. editing .Net DataSet with vi).

    For configuration files etc I just use nano.

    So, where exactly is the place for vi / emacs today and what benefits do they bring??

    1. Re:Why should I learn vi?? by ThePhilips · · Score: 1

      I do my development work in Visual Studio / Netbeans / Jdeveloper.

      So, where exactly is the place for vi / emacs today and what benefits do they bring??

      You are used to IDEs - go with Emacs. [ Disclaimer: huge VIM fan and Emacs hater. ]

      VIM shines when you need to do some work in more or less "batch" mode. Senseless coding comes to mind. Shortcuts are relatively short, but there is a gotcha: VIM has two major modes (insert vs. normal) and shortcuts differ in the modes. (Actually, VIM has officially IIRC 6 modes: visual (selection), insert, replace, normal, ex, command - or something like this). Since VIM was born from console, after some practice you can work in it with closed eyes. (Hint: if you do visual programming - VIM isn't for you).

      Emacs integrates all things together wrapping (and often replacing) whole OS by its own "modes." ("Mode" in Emacs is a sort of "plug-in" or "specialized shell"). It has everything, starting from version control mode to tetris clone to web browser. If you would manage to comprehend rather incomprehensible documentation, Emacs could be very good tool for everything. Added bonus: among countless utilities it also includes text editor. Kidding. Emacs is by all means full fledged text processor.

      Essential difference between the two: Emacs is very interactive, while VIM is batch oriented. You can do everything without ever leaving Emacs, while VIM easily integrates with shell (and you would need to use it for many things). Configuring Emacs is hurdle and like IDEs is often impossible (mainly due to complexity of configuration). VIM has relatively good documentations and configuring it is rather simple.

      Both differ from traditional M$ borne IDEs is that they do not employ button clicking interfaces and can provide most utility to touch typists. Everything (like *everything*) can be done from keyboard.

      Since both provide unparalleled configuration flexibility (read: scriptable), it's possible to make out of them highly efficient workhorse for any particular workload. Without button-clicking. In the end that means if you do not wish to make out of them the "workhorse" - customizing work environment isn't your thing - probably you can save learning time by staying with whatever editor you already know and skipping both Emacs and VIM.

      P.S. I myself have fond memories of working with Turbo/Borland Pascal/C++ IDEs. My fingers still remember all the shortcuts of decade ago. Yet, recently I had a chance to compare how I did things in past (in Borland IDEs under Windows) and I do things now (in VIM under *nix). After 15 minutes correcting quarter of file in Borland C++ Builder editor, I have rebooted into my Debian and within a minute had rest finished in VIM. Yes, I really like how Borland's IDE looks and works. Yet, in VIM and Linux, I can do my work magnitudes faster.

      --
      All hope abandon ye who enter here.
    2. Re:Why should I learn vi?? by grumbel · · Score: 1

      So, where exactly is the place for vi / emacs today and what benefits do they bring??

      In practical terms: very little, if any.

      On the more theoretical side of things: When using vi or Emacs you use one editor for all your text-work, so all you shortcuts and commands will work no matter if you are programming java, editing xorg.conf, sending mail or doing stuff over ssh on a computer that is thousand miles away.

      However if you are already familiar with an IDE for the language you program in, I seriously doubt that switching to Emacs or vi would have any benefit, in fact there might be plenty of features that you will be missing after the switch.

  77. graphical cheatsheet by yacoob · · Score: 1

    This site comes useful.

    --
    -- we're here you're not
  78. Re:Just using VIM by potHead42 · · Score: 1

    There's also the standard mappings Ctrl-[, which does exactly the same as Escape, and Ctrl-C, which differs slightly (some autocommands won't be called) but works perfectly fine for me in most cases.

  79. Famous Easter Eggs by pasde · · Score: 0

    Try it out!

    :help UserGettingBored
    :help 42
    :help holy-grail
    :help!

  80. my tips... by naChoZ · · Score: 1

    Here's some that I a lot...

    Visual *block* mode
    Instead of just regular visual mode 'v', you can use CTRL-v for visual block mode. I tend to use this as a quick way to comment out lines. type [0] for beginning of line, then [CTRL-v], arrow down, [Shift-i], [#], then [Esc] and it will stick a # at the beginning of the every line in the visual block. But one of the nice things is that you don't have to be at the beginning of a line. You can indent everything after column 40, for example, across your selected lines and it will move everything after your visual block. It's also very handle for visually selecting a single column of text in a file and then using the [x] to delete it.

    << and >>
    In normal mode, hitting the key [>] twice will indent the whole current line (or visually selected area) to the next tabstop.

    [v][i][p]
    This visually selects the current paragraph in its entirety (a paragraph being lines of text separated by a blank line). One that I type all the time is [v][i][p][=] because I have my "equalprog" value set to perltidy and this reformats my current block of code. I just prefer not to run perltidy across a whole file of my code at once. I also use this one a lot with shell commands like !sort.

    And a couple for your ~/.vimrc:

    map zz za
    I use folds a lot and I just find it more convenient to hit zz to open/close the current fold.

    nmap :wincmd w
    If you use split windows a lot, this let's you just hit the Tab key while in normal mode to switch through regions.

    Geez, I just noticed my ~/.vimrc file is up to 29K...

    --
    "I can be self-referential if I want to," said Tom, swiftly.
  81. Here's a few good ones by Cyrano+de+Maniac · · Score: 1

    Here's a few good ones from my .vimrc file.

    First one, for those of you who've been lambasted by maintainers/etc when submitting Linux/whatever patches because your code had extra whitespace at the end of the line. This highlights such whitespace by turning the background color red on those characters:

    " Highlight trailing whitespace
    highlight WhitespaceEOL ctermbg=red guibg=red

    function WhitespaceHighlight(syn)
            if a:syn =~ 'diff'
            " diff syntax should trailing whitespace on non-addition lines
            syn match diffAdded "^+.*" contains=WhiteSpaceEOL
                    syn match WhitespaceEOL display /\s\+$/ contained
            elseif a:syn =~ '^\v(asm|c|config|cpp|ia64|crontab|fortran|html|man|pascal|perl|postscript|procmail|python|sh|csh|tcsh|zsh|spec|tcl|vim)$'
            " bug: Innards of C comments aren't highlighted
            syn match WhitespaceEOL display /\s\+$/
            endif
    endfunction

    autocmd Syntax * call WhitespaceHighlight(expand(""))

    The next one is for those of you who've edited read-only files, only to realize at the end of the editing session that you can't write to it. This set of entries makes read-only buffers non-modifiable (i.e. editing commands don't work), and selects different colorschemes based on whether the current buffer is modifiable or not (a visual trigger -- in my case a black background means not editable, dark blue means I can edit it).

    " Color schemes
    let rwcolor="darkblue"
    let rocolor="elflord"

    " Make sure automatic color schemes always know they have dark backgrounds
    " ColorScheme event appeared no later than version 7.1. Probably 7.0
    if (v:version >= 700)
            autocmd ColorScheme * set background=dark
    endif

    " Change modifiability and color scheme based on read-only status of
    " current buffer
    function Modifiable()
            " Make readonly files non-modifiable, so we don't make a
            " bunch of changes only to realize we can't save them
            if &readonly
                    set nomodifiable
            else
                    set modifiable
            endif

            " Set the colorscheme based on the readonly/modifiable
            " status of the file. This gives a visual cue as to
            " when modifying is disallowed.
            if has("gui_running")
                    if &modifiable
                            let g:colors_name=g:rwcolor
                    else
                            let g:colors_name=g:rocolor
                    endif
                    if (v:version >= 700)
                            doautocmd ColorScheme
                    else
                            " This has the same effect, but is kludgy
                            " and may miss some of the side-effects.
                            " It does the job for our purposes.
                            set background=dark
                    endif
            endif
    endfunction

    autocmd BufEnter * call Modifiable()

    --
    Cyrano de Maniac
    1. Re:Here's a few good ones by Cyrano+de+Maniac · · Score: 1

      Hmm. Apparently /. stripped out some of the code due to it looking like HTML. In the whitespace highlighting recipe, the last line should be:

      autocmd Syntax * call WhitespaceHighlight(expand("<amatch>"))

      --
      Cyrano de Maniac
    2. Re:Here's a few good ones by James+McGuigan · · Score: 3, Informative

      Actually I fix this one within .bashrc, and create a wrapper function around vim, that detects if the file is editable or not, and asks if you want to prefix an sudo.

      argc () {
              count=0;
              for arg in "$@"; do
                      if [[ ! "$arg" =~ '-' ]]; then count=$(($count+1)); fi;
              done;
              echo $count;
      }

      vi () { if [[ `argc "$@"` > 1 ]]; then /usr/bin/vim $@;
                      elif [ $1 = '' ]; then /usr/bin/vim;
                      elif [ ! -f $1 ] || [ -w $1 ]; then /usr/bin/vim $@;
                      else
                              echo -n "File is readonly. Edit as root? (Y/n): "
                              read -n 1 yn; echo;
                              if [ "$yn" = 'n' ] || [ "$yn" = 'N' ];
                                  then /usr/bin/vim $*;
                                  else sudo /usr/bin/vim $*;
                              fi
                      fi
                  }

    3. Re:Here's a few good ones by Cyrano+de+Maniac · · Score: 1

      OK, now do ":split someother.file" that has different r/w attributes.

      I win. ;)

      --
      Cyrano de Maniac
  82. Re:Just using VIM by Minozake · · Score: 4, Insightful

    The learning curve is worth it, though. If you need to edit text quite a bit, it makes sense to make it efficient.

    I personally recommend trying to learn Vim alongside with another editor, or using a GUI frontend like GVim.

    Replace Vim or GVim with any editor of your choice.

    --
    http://sourcemage.org/ - Have fun :)
  83. #,n,N by itomato · · Score: 1

    #,n,N

    The hash will find additional occurances of the keyword under cursor, 'n' will do the same (find 'n'ext instance), while 'N' will search in the opposing direction.

  84. Re:Just using VIM by Sancho · · Score: 1

    Neat shortcut. I tend to use ctrl-c, which functions similarly, but it's the context switch from insert mode into command mode that throws people, not the specific keystroke.

  85. '' will also indent by itomato · · Score: 1

    '>' will indent, it's lower on the keyboard, and its symbol is more indicative of its function!

    1. Re:'' will also indent by James+McGuigan · · Score: 1

      if you are in insert mode,
      >> will indent,
        will unindent, and
      == will auto-indent

    2. Re:'' will also indent by James+McGuigan · · Score: 1

      << will unindent

    3. Re:'' will also indent by dwater · · Score: 1

      I think you mean, "*Unless* you're in insert mode", since *in* insert mode, typing '>>' will insert two '>' chars.

      --
      Max.
  86. Reformatting and macros by jzu · · Score: 1

    gqap
    Reformats a paragraph. Think M-q.

    :map [list of one-key-commands]
    Binds a key (q being a favorite of mine) to a macro. Knowing h, j, k, l, 0, $ commands is a requisite, C-v allows control chars like line feed and escape.

  87. f and t by potHead42 · · Score: 1
    I use the f and t motion commands all the time since discovering them. For example, ct) will remove all text from the current cursor position up to the next ), and switch to insert mode. This is incredibly useful for replacing arguments in function calls, or attributes in HTML tags.

    Some other nice stuff I discovered:
    • :set wildmenu, shows all possible completions in a menu above the command line when pressing Tab
    • :set scrolloff=5, automatically keeps 5 lines visible when moving the cursor to the top/bottom
    • o / O, starts a new line in insert mode below/above the current line
    • C-e / C-y, scrolls the buffer without moving the cursor
    • runtime macros/matchit.vim, extends the % command to match more stuff, like HTML tags
    • the vimdiff shell command, which starts Vim in its awesome diff mode. use the :diffget and :diffput commands to merge changes
    1. Re:f and t by James+McGuigan · · Score: 1

      if you like vimdiff, then did you know about :diffsplit <filename>, :diffthis, :diffoff

      Or the VCSCommand plugin for doing vimdiff against a CVS/SVN/GIT repository :VCSVimDiff

    2. Re:f and t by potHead42 · · Score: 1

      I sometimes use :diffthis, but usually I'm faster when just calling vimdiff ;) But thanks for the VCSCommand link, that could be really useful indeed.

  88. Re:Just using VIM by Anonymous Coward · · Score: 5, Funny

    Not really a vim trick, but I always liked to create a file in the / directory named README. The file just contained one line: "ERROR: can not open file README" When someone cats it, they get the error message. Pretty cute until they vi it and figure it out.

  89. Re:Just using VIM by mattack2 · · Score: 1

    If I have to do a *lot* of widespread editing over multiple source files (especially a massive search/replace), I will do it in GUI tools, usually Xcode.

    But if I just want to fix a typo that stopped my last compile, or do a few-line bug fix, I'll do it in vim, because it's faster for me.

  90. I think I see a pattern in these stories by Xeth · · Score: 2, Funny

    ...and I've already gotten through half of my 20-page "(Useful) Stupid Emacs Tricks" post.

    --
    If your theory is different from practice, then your theory is wrong.
  91. Re:Just using VIM by _Sprocket_ · · Score: 1

    Like other posters have alluded to, I first picked up vi because if you learn it you're set on almost any *nix command line you will ever touch. I've done a fair amount of *nix work over the years so I've developed some (limited compared to some of the vi nuts I've known) familiarity with it.

    But these days, I use vim mostly on my own desktop where I have a ful GUI going on. It's not because I don't want GUI flash. My vim sessions are running in shiny translucent windows that (as best as I can make it) look like glass. And with it I can do things like shift-v,highlight block of text,s/^/# to comment out a block or s/^#// to uncomment it. When I do find myself using a GUI editor, I'm always wanting to use vi commands. You use the tools you're most familiar with, I guess.

    I could always use gvim. But its not as shiny as my gnome terminal. And then there's the times I'm SSH'd out to some colo and want to use the vi/vim tricks I'm accustomed to (instead of reaching for a pull-down menu).

  92. Re:Just using VIM by Evil+Pete · · Score: 1

    And more often than you would believe the remote connection is slow even via ssh. So abbreviated commands are a lifesaver ... this is when you are glad you are using vi.

    --
    Bitter and proud of it.
  93. Re:Just using VIM by mattack2 · · Score: 1

    Then :set showmode

    for the newbies. (Maybe this is the default? I don't see it in my .vimrc or .exrc)

    Though one of the good things about vim is that you can move around while still in insert mode, which I think removes a decent amount of the stigma from it.

  94. Changing case by Evil+Pete · · Score: 1

    Found this completely by accident. Shift-tilde (~) changes the case of the letter under the cursor and moves to the next character. Still have need to use this occasionally.

    And let's not forget the marking of blocks (I know it's fundamental but sometimes you can forget it). e.g

    ma --- mark the start of block 'a'
    move to end of block
    yank, delete whatever the block
    y'a or d'a

    --
    Bitter and proud of it.
  95. Auto-increment numbers and macros by asc99c · · Score: 1

    Ctrl-A auto-increments the next number.
    qq q records a macro that can be run with @q

    Combined these are very useful. I often find myself having to put stuff into case statements like:

    case LOC_ERA01:
    case LOC_ERA02: ...
    case LOC_ERA06: /* do something */
        break;

    Now I just write the first line and run
    'qq yy p Ctrl-A q 4@q'

    The thing I love about vim is how naturally I run those sorts of macros. It's just taken me ages to actually think of how to do it but it all seems to come naturally as you type.

    Just a note for the vim newbies. I went to Uni in 2002 and trained up in coding with Eclipse and Visual Studio. I'd never used vim or any other modal editor. After uni, I was sent to site for a few weeks on business without access to anything other than vim. It took a long while to get it, but now I'm a complete convert.

    Eclise and Visual Studio are IDEs. Vim is a much better editor. Thankfully, both IDEs have a vim editor plugin to combine the best of both worlds. I'd never survive these days without a modal editor!

    1. Re:Auto-increment numbers and macros by allenthelee · · Score: 0

      You can actually record a macro on other keys as well, i.e.,

      qq 1 starts recording a macro that can then be run via @1

    2. Re:Auto-increment numbers and macros by asc99c · · Score: 1

      q1 (not qq1) starts recording a macro called 1.

      Just noticed my original post came out wrong, damn HTML tags! It should have said qq <commands> q.

      The first q is record macro, and the second is the macro name (I just find q is the easiest name), and the final one is to stop recording.

  96. entering vim by Deadplant · · Score: 1

    you can open a directory instead of a file.

    vim /var/log/
    then navigate to the file you want to edit.
    can be useful sometimes.

    1. Re:entering vim by ThePhilips · · Score: 1

      Or right in VIM - :E - would list files in :pwd.

      --
      All hope abandon ye who enter here.
    2. Re:entering vim by andrikos · · Score: 1

      You can even open tarballs and edit them "in-place"!

  97. Graphical Editor Environments by FreeBSD+evangelist · · Score: 1
    I know the emacs vs. vi holy war is a funny old meme, but why not just use a modern-style editor? We have these powerful graphical desktops with very standard interfaces.

    Any editor where you have to take a hand off the keyboard in order to move the cursor is fundamentally broken.

    1. Re:Graphical Editor Environments by ChameleonDave · · Score: 1

      Any editor where you have to take a hand off the keyboard in order to move the cursor is fundamentally broken.

      It's fortunate that Kate is not one of those then.

  98. reformatting text by mattack2 · · Score: 1

    That reminds me of one of the things I use most in vim, and forgot about until I read this thread. I use alpine (http://www.washington.edu/alpine/) as my email program, and vim as my external editor.

    gq
    will reformat text, keeping the quoting properly done.

    e.g., there are a bunch of replies in a thread, and it ends up something like this (after you've trimmed unnecessary quoted text of course!)
    >>really really really really really really really really long line from older message
    >long long long long long line from newer message

    so it'll often end up too wide (wider than 80 cols.. heh). So go to the beginning of the 'really really' line, and hit
    gq
    and it'll end up reformatted to your current window's width.. This in a very tiny window I made to show this example:
    >>really really really really really
    >>really really really long line from
    >>older message
    >long long long long long line from
    >newer message

    There are more sophisticated options for gq, like for the whole paragraph, etc., but I usually just do it line by line as I'm editing/trimming the quotation.

  99. Re:Just using VIM by Anonymous Coward · · Score: 0

    I still use h,j,k,l. Those arrow keys are like, on the other side of the keyboard.

    Its Awesome that j and k work in Google Reader. Its like the wasd for non-games.

  100. A few of mine by Pheersome · · Score: 1

    For vim compiled with X support, "* is the register corresponding to the X clipboard. So, "*p dumps the X clipboard into your file in a much more elegant way than i and middle-click.

    Some large motions (:123, gg, G, probably others) set the ' mark. So, gg to go to the top of the file (say, add a #include or an import), then '' to go back to where you were. On a somewhat related note, ^I and ^O will traverse the list of places you've jumped to -- handy for finding your way back to where you were before you jumped to five or six different places via a search.

    Somebody mentioned . earlier. If you're not using . religiously, you're using vim wrong.

    High on my wishlist for vim tricks is a way to put delimiters on either side of a motion that supports . to repeat it. E.g.: say I have a few words and I want to parenthesize each of them. Put the cursor at the start of the first word, [some keys](, lparen and rparen magically appear around the word, move to the next word, hit ., parens appear around that word, etc.

    --
    Better to light a candle than to curse the darkness.
    1. Re:A few of mine by Kerrigann · · Score: 1

      It's not quite the same... but you can always record a macro to do what you're talking about.

      Place the cursor on the start of a word, qa to start recording to 'a', then i(ea) to add parens, then q to end recording.

      Now @a does what you're describing.

      (Apologies if I'm insulting your intelligence and you already knew this and just wanted a way to do it with '.')

    2. Re:A few of mine by Kerrigann · · Score: 1

      Sorry to reply to myself, didn't look too closely at the preview and it ate my <esc>

      the macro would be i(<esc>ea)<esc>

  101. Re:Just using VIM by playerone · · Score: 1

    Because if you do a lot of text editing they are much quicker and more efficient to use. The biggest thing I notice on a day to day basis is with a "mode" editor such as vi you can block comment out 20 lines of code with a single command rather than comment down across comment down across comment... Syntax highlighting is also a huge bonus. I know that some other "gui" editors have this sort of thing now as well but its pretty standard on vi/emacs style editors. The power you refer to is what makes them more useful than your standard gui modeless editor.

    --
    --Question Authority--
  102. "Recording" by Michael+Wardle · · Score: 1

    If the Vim status bar says "Recording", you accidentally typed q then some character.

    Press q again to turn it off.

  103. Re:Just using VIM by Constantine+XVI · · Score: 5, Interesting

    main utility of vi is that I know it's going to be there in any Linux enviroment (and I suspect Unix in general).

    vi is part of the Single UNIX Specification, so anything passing itself off as UNIX must include vi. Even without the spec, it's much, much more universal than emacs, and more powerful than pico/nano.

    --
    "I think an etch-a-sketch with an ethernet port would beat IE7 in web standards compliance."
  104. Re:Just using VIM by Anonymous Coward · · Score: 0

    I've a ripe 19 year old whose been using vi(m) for about 3 years and I most definitely use the h,j,k,l! Anyone who doesn't is not taking advantage of the most useful feature. Using the arrow keys defeats the entire purpose, why not just use the mouse then? I like the shortcuts so much I've set my workspace hotkeys to ctrl + shift + h,j,k,l and move window to workspace to ctrl + shift + alt + h,j,k,l

    More applications should take advantage of this awesome idea.

  105. shelling out by onedeadeddie · · Score: 2, Informative

    :sh works well when you don't know root, but have sudo privs.

  106. Re:Just using VIM by Anonymous Coward · · Score: 0

    Umm... uphill - both ways?

  107. Hi, I'm Kerrigan and I'm a vim addict.. by Kerrigann · · Score: 2, Interesting

    I've used vim for years... to the point that it is forever ingrained in the way I think and code. I can't even think of the last thing I edited *not* in vim (besides this post :). I consider myself to be *kinda okay* at using it...

    Here are three of my *cannot live without* vim features...

    1. Highlight text with visual mode and 'gq' to format it according to the currently set formatting rules. I know full-fledged IDEs have this feature, but I can't think of anything outside of vim or emacs that can do this from a thousand miles away in a terminal.

    2. "smarttab" mode and the 'retab' command. I've worked in lots of places with very disparate IDEs and environments and everyone seems to produce code with slightly different tabstops and tab consistency. 'smarttab' and 'expandtab' tell vim to output spaces instead of tabs for consistency in viewing across editors, but to treat consecutive spaces as virtual tabs for the purposes of deleting or selecting. 'retab' changes tabs across the entire file to match the currently set convention. *Very Useful* for editing python :)

    3. This is the biggest one... macro recording and programmatic repeat. 'q' starts recording a keystroke macro, which thanks to vim can be something as complicated as... "go to start of line, replace text up to first ( with blah, go to second ',' and capitalize the first letter of that word" etc... Then, you can either use the :global command to search a file for lines matching a pattern and execute that macro on each line, or even easier, use V (visual line select mode) to select groups of lines, then execute the macro on all of those, or a subset of those with global. I always do this via the :normal command, which allows you to execute a keystroke based command through command-line mode. So, 'qa^f(cbfoobarf)a const' would replace a function call name with 'foobar' and add a const to the declaration. Select a group of lines with V, then type :normal @a to call the macro on every line. I think there might be a better way to call macros from command-line mode, but that's the only one that I know.

    I have actually whined and cried and begged to put vim on everything larger than a toaster where I work so that I don't go crazy. Vim has saved me countless hours of programming time over the years, and I highly recommend trying to learn some of its deeper features.

    Plus, all the other editors I use have this weird habit of putting ':wq's and 'dd's in my text...

    1. Re:Hi, I'm Kerrigan and I'm a vim addict.. by lucas+teh+geek · · Score: 1

      Plus, all the other editors I use have this weird habit of putting ':wq's and 'dd's in my text...

      yeah, I hate it how they do that!:wq

      --
      TIAEAE!
    2. Re:Hi, I'm Kerrigan and I'm a vim addict.. by rdebath · · Score: 1

      Why does everyone seem to use :wq instead of :x ?!

    3. Re:Hi, I'm Kerrigan and I'm a vim addict.. by include($dysmas) · · Score: 1

      use ZZ

    4. Re:Hi, I'm Kerrigan and I'm a vim addict.. by IpalindromeI · · Score: 1

      Because once you learn that :w is write, and :q is quit, it's easier for many people to remember that write and quit is the combination of the two than to remember a separate, unrelated command. Then it becomes a habit.

      --

      --
      Promoting critical thinking since 1994.
  108. Registers by afranke · · Score: 1

    " and a letter before a command will save the content into a register named by the letter. For instance, "add will cut the line and save it into register a. If you want to paste this, just do "ap. You can even append things in a register by using the capital letter. "Add will append one more line to the one we cut earlier and now "ap will paste these two lines. See :help reg for more info on this topic.

  109. Re:Just using VIM by Anonymous Coward · · Score: 0

    I've a ripe 19 year old whose been using vi(m) for about 3 years...

    And just what are you doing with this ripe 19 year old that you have;-)

  110. :r by Anonymous Coward · · Score: 0

    The ever useful :r !format C: /fs:ntfs

  111. a few from my ~/.vimrc by lucas+teh+geek · · Score: 1

    this makes ctrl+a and ctrl+e work like they do in bash (and practically everywhere else)

    :map <C-a> 0
    :map <C-e> $
    :cmap <C-a> <home>
    :cmap <C-e> <end>
    :imap <C-e> <ESC>$i<right>
    :imap <C-a> <ESC>0i

    These make it so when a line has wrapped, jk navigation moves one line on the screen, instead of one line in the file
    nnoremap j gj
    nnoremap k gk
    vnoremap j gj
    vnoremap k gk
    nnoremap <Down> gj
    nnoremap <Up> gk
    vnoremap <Down> gj
    vnoremap <Up> gk
    inoremap <Down> <C-o>gj
    inoremap <Up> <C-o>gk

    this gives you a current-row and current-column highlight, so you never lose your cursor
    set cursorcolumn
    set cursorline
    hi cursorcolumn ctermbg=red

    and finally, I think nobody should use vim without learning how to use split panes.
    :sp filename.txt -- opens the file in a new horizontal pane
    ^ww -- changes between the panes.
    ^w+ -- grows the current pane one line
    ^w- -- shrinks it one line
    ^w= --makes all panes the same size.

    you can also use :vsp to open in vertical panes for side by side editing too.

    --
    TIAEAE!
  112. Re:Just using VIM by Anonymous Coward · · Score: 0

    We have these powerful graphical desktops

    There's also the puzzling fact that a lot of emacs and vim non-users seem to think they don't have GUIs. Now, vim got "gvim" relatively recently, but emacs has had a bitmapped GUI for an extremely long time, most people run it in GUI mode. (Apple shipped a crappy nongui build of emacs with macosx though).

    http://www.gnu.org/software/emacs/tour/ - Emacs, a gui application with multiple windows and toolbars and menubar and stuff.

    People have really strange ideas about emacs. It's like when you ask a windozer about linux and they go "oh yeah, it's that thing like MS-DOS, right?".

  113. Re:Just using VIM by Anonymous Coward · · Score: 1, Funny

    When I was your age I wrote thousands of lines of C code using EDLIN. (P.s. this was on a *nix box not DOS) (P.p.s Also walked to school 5 miles, up-hill, barefoot, in the snow, both ways)

    That's nothing. When I was half your age I wrote code over a dial up connection without a modem. Made the tones with my voice! Mind you we lived in a cardboard box at the time, in the middle of the road.

  114. Re:Just using VIM by thzinc · · Score: 1

    There may be a hill or valley in between home (or some other starting point) and school.

  115. Vim rocks, but on Windows... by scott_karana · · Score: 1

    As awesome as Vim is, whenever I'm on a Windows platform I find its GUI abhorent, but at the same time I can't see myself using it on the commandline.
    So I use WinVi instead. While it has FAR less features, if I need to bang out some gorgeous regex replace in a native editor, WinVi got my back.

    1. Re:Vim rocks, but on Windows... by rdebath · · Score: 1

      You mean vim or gvim?

      Personally I think the gvim GUI is fine; those tear off menus are sweet.

      My only real problem with vim is that sometimes it seems a little overweight but I can never point to something I think should go ... I suppose that means it's zaftig :-)
       

  116. Re:Just using VIM by Count+Fenring · · Score: 0, Offtopic

    You can even get a shiny, aquafied version of GNU Emacs! http://aquamacs.org/.

    I will say that Emacs takes more configuring than most modern single language IDEs. On the other hand, I've spent high multiples of the time I've spent on Emacs just trying to get some of Eclipses more popular plugins to work.

  117. Reference card by YoungHack · · Score: 2, Informative
  118. Re:Just using VIM by Obfuscant · · Score: 1
    Young whippersnapper. When I was young it was called "teco", and the game to play with every new user was to type their name to see what it did.

    I remember the day we got the 'vi' macros for teco. Woot woot. Hot stuff.

    Actually, when I was young it was called an IBM keypunch. Those were the days.

  119. Re:Just using VIM by daybot · · Score: 1

    I get really sad when I see wasteful memory and cpu bloat. Perhaps these will become scarce resources again with the mobile trend, and people will do a better job watching their consumption. Oh well.

    Maybe it's happening already. I'm amazed at how small some of the richer iPhone applications are, and how much they can do with limited RAM.

  120. Re:Just using VIM by czaby · · Score: 1

    And even on windows you use cygwin, right?

  121. Re:Just using VIM by Anonymous Coward · · Score: 1, Funny

    When I was your age I wrote thousands of lines of C code using EDLIN. (P.s. this was on a *nix box not DOS) (P.p.s Also walked to school 5 miles, up-hill, barefoot, in the snow, both ways)

    That's nothing. When I was half your age I wrote code over a dial up connection without a modem. Made the tones with my voice! Mind you we lived in a cardboard box at the time, in the middle of the road.

    We used to DREAM of even having a phone to make tones with. We had to tap out our code with a telegraph machine, in binary, from memory. And as there were twelve of us living in OUR cardboard box, we had to take turns and STILL get eight hours of work done in a day.

  122. :set nohlsearch by Crackez · · Score: 1

    :set nohlsearch

  123. Probably too much for one post... by liebeskind · · Score: 1

    (Please excuse the terrible way that I have to post this - normally the comments are above the command, but slashdot was freaking out...) Here is my .vimrc file:
    :com Openvimrc :tabnew ~/.vimrc " custom command to edit the _vimrc file from anywhere
    :nnoremap <C-J> 5j " custom key mapping: CTRL-J -> move down 5 lines
    :nnoremap <C-K> 5k " custom key mapping: CTRL-K -> move up 5 lines
    :nmap <C-t> :tabnew<cr> " custom key mapping: CTRL-T -> open new tab
    :nmap <C-tab> :tabnext<cr> " custom key mapping: CTRL-TAB -> move to next tab
    :nmap <C-S-tab> :tabprevious<cr> " custom key mapping: CTRL-SHIFT-TAB -> move to previous tab
    :autocmd BufEnter * lcd %:p:h " auto set the current working directory to be the same as the buffer's
    :filetype on " toggle filetype detection
    :filetype plugin on " toggle filetype plugins
    :set number " turn on line numbering
    :set tabstop=4 " indentation level
    :set expandtab " convert tab key to spaces
    :set shiftwidth=4 " indent/outdent
    :set shiftround " always indent/outdent to nearest tabstop
    :syntax on " turn on syntax highlighting
    :au BufWinEnter * let w:m1=matchadd('ErrorMsg','\%81v.*',-1) " lines that are > 80 characters are error highlighted by default
    :com SetLengthWarning :let w:m1=matchadd('ErrorMsg','\%81v.*',-1) " custom command to set > 80 character highlighting
    :com UnsetLengthWarning :call matchdelete(w:m1) " custom command to unset > 80 character highlighting
    :set backspace=indent,eol,start " allow backspace over everything
    :set noerrorbells visualbell t_vb= " kill the bells
    if has("gui_running") " gui specific properties
    :set guioptions-=T " hide the GUI toolbar
    :set guioptions-=m " hide the GUI menu
    :colorscheme inkpot " set the color scheme
    :set guifont=Anonymous:h13 " set the GUI font
    :set lines=46 columns=100 " set the window size
    else " cterm specific properties
    :colorscheme default " set the color scheme
    :hi LineNr ctermfg=red " set line numbering color to red
    endif

    (END)
    There are some things to note. There are some commands in my .vimrc which will highlight text that has crossed the 80 character threshold. In order for those commands to work, vim7.2 or greater must be installed. Also, tab support was not added until vim7.0 I think. My gvim font is from http://www.ms-studio.com/FontSales/anonymous.html>. If you want some excellent colorschemes, check out http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/>. Finally, I just discovered this a couple of days ago http://technotales.wordpress.com/2007/10/03/like-slime-for-vim/>: an awesome vim trick to use with irb.

  124. Re:Just using VIM by MadnessASAP · · Score: 1

    *Silence*

    Becuase a *Whoosh* in space can't make a sound.

    --
    I may agree with what you say, but I will defend to the death your right to face the consequences of saying it.
  125. Re:Just using VIM by czaby · · Score: 1

    Actually in the old days we did whistle into the phone to see if the modem on the other end responds at all. It was a primitive but sometimes useful diagnostic method.

  126. Write and Quit by thogard · · Score: 1

    :x!
    Many people seem to use :wq! when :x! has done the same thing for decades but gets rid of the issue of what if the write fails, does it still quit and is the ! tied to the w or the q? ZZ will also do the same thing.

    1. Re:Write and Quit by 1s44c · · Score: 1

      :x!
      Many people seem to use :wq! when :x! has done the same thing for decades but gets rid of the issue of what if the write fails, does it still quit and is the ! tied to the w or the q? ZZ will also do the same thing.

      You are right that most people insist on using :wq! when :x! obsoleted it in 1978.

      However there is a difference, :x will not write the file where it has not changed, :wq! will write the file in any case.

  127. something I stumbled upon a few years ago by ErisCalmsme · · Score: 1

    I had a folder (*cough* I mean directory) named reports. Inside that folder (yeah, directory) I had a file named reports.php

    I did this: vim reports [tab] [enter] expecting my shell to complete the filename and open it. (I forgot that the reports.php file was in the reports fo^H^H dir) What happened was that Vim said "reports is a directory" and showed me all this stuff... I thought I broke it! But the reality is that vim has a built in file browser. It's very handy! Try it!

    PS yes I know that a directory is a file too along with everything else.........

    PPS the best vim tip ever: vimtutor
    just do it.

    --
    Chaos is Divine *
  128. Obligatory by ThePhilips · · Score: 1

    My first and foremost thing in .vimrc is ":imap <Insert> <Nop> ".

    I hate when out of casual habit I press Ins in insert mode and VIM sends me to replace mode.

    Obviously, habit of pressing 'i' or <Insert> all the time comes from the funny effects typing plain text causes in normal (command) mode.

    --
    All hope abandon ye who enter here.
  129. Re:Just using VIM by michaelamdavies · · Score: 2, Funny

    Eeee, I used to dream of living in a hole in't ground. We used to live at bottom of lake, hand coding assembly language in hex, rotating bits with a hand crank and communicating it using signal flags or semaphore. And then sysadmins and punch card operators would come and chop us into little bits with paper tape readers and dance on our line printer reams. And you tell young people this today, and they just don't believe you

  130. Esc ends commands, not starts them by thogard · · Score: 1

    I hate listening to people use vi who think commands start with Esc. If you make vi beep, your doing it wrong.

    1. Re:Esc ends commands, not starts them by mattack2 · · Score: 2, Informative

      If you use "your" to mean "you're", you're doing it (using the English language) incorrectly.

    2. Re:Esc ends commands, not starts them by thogard · · Score: 0, Troll

      Languages evolve and the ' is going away so you can get over it now or later.

    3. Re:Esc ends commands, not starts them by drunkennewfiemidget · · Score: 1

      .. you were kidding, right?

    4. Re:Esc ends commands, not starts them by mattack2 · · Score: 1

      So the 'e' is going away too, huh? ("your" and "you're" have more than just a ' difference.)

    5. Re:Esc ends commands, not starts them by Anonymous Coward · · Score: 0

      Of course. The "your doing it wrong" is a sure way to bring out the language trolls. Of course this whole thread should be moderated off topic.

    6. Re:Esc ends commands, not starts them by dwater · · Score: 1

      I think he means that the whole word 'are' is going away...which makes me wonder what will happen on pirates' day a few years from now.

      --
      Max.
  131. Comment removed by account_deleted · · Score: 1

    Comment removed based on user account deletion

  132. Re:Just using VIM by denvergeek · · Score: 0

    You can use the arrow keys?

  133. Tabs and more by mebrahim · · Score: 1

    You can open a new tab with :tabnew and move between tabs using :tabn and :tabp.
    I use ':map <A-Right> :tabn<Enter>' and ':map <A-Left> :tabp<Enter>' for easier move between tabs.
    A very useful trick I learned recently is Ctrl+r in normal mode which lets me paste a register (which is already yanked or deleted).
    When I open a file which Vim doesn't detect its format, I use ':set ft=cpp' to let it know!

    1. Re:Tabs and more by IpalindromeI · · Score: 1

      Ctrl-PgUp and Ctrl-PgDn move between tabs, too.

      --

      --
      Promoting critical thinking since 1994.
  134. Re:Just using VIM by Anonymous Coward · · Score: 0

    I know the emacs vs. vi holy war is a funny old meme, but why not just use a modern-style editor?

    I used to. Then I was forced by circumstances to learn Emacs, and I found to my surprise that, once you get past the initial learning curve, it's more flexible and powerful than anything else I've ever tried.

    We have these powerful graphical desktops with very standard interfaces.

    Standard and horribly inefficient interfaces, that waste convenient keyboard shortcuts like Control+A on commands like "select all" that most people never use, forcing you to move your hands away from home row to perform incredibly common actions like "move to start of line".

    Besides, once you've learned Emacs, that becomes your standard interface. Many standard Unix programs, such as bash and gdb, emulate Emacs by default and have an optional vi mode. Others, such as GNOME, Firefox, etc, use inefficient Windows-style shortcuts by default but have an option to emulate Emacs. And Emacs itself is a good choice for many common tasks such as email.

    I'm sure the old classics give you a lot of power (Actually, I don't know that much about vim, but I understand you can run Eliza, NetHack, or a Lisp interpreter in emacs)

    It's not just "you can run a Lisp interpreter in Emacs". Emacs is a Lisp interpreter. You can use the editor to edit the editor itself, while it's running. For non-techies, it's a nightmare scenario, and I would definitely not recommend Emacs to my grandmother. For a programmer, though, it's great.

    but who wants to learn a bunch of obscure commands and meta-keystrokes?

    I didn't, once. That was before I realised how useful some of those obscure commands are. For example, just having a simple shortcut to repeat a command or keystroke an arbitrary number of times: before I used Emacs, I'd have said it was a useless feature, whereas now I couldn't live without it.

    Besides, what do you have in your "modern" editor? Only a handful of shortcut keys are standardised, so to do anything beyond the very basic load/save/clipboard/move-cursor-around, you either have to learn a whole bunch of obscure keystrokes, or you have to navigate poorly-structured menus or click on cryptic icons. Whatever editor you use, you have to go through a learning process in order to use it effectively. Emacs and vi don't attempt to hide that learning process from you. Every other complex editor is lying to you by pretending to be easier to use.

    If you just need to edit some text, there are simpler solutions.

    Simpler in the short term. In the long term, well, it's your time you're wasting...

  135. Re:Just using VIM by Anonymous Coward · · Score: 0

    Luxury! We had to carve the code into stone tablets with our teeth. Then submit them by steamship only to find, six months later, that it wouldn't compile because of a missed semicolon!

    Of course emacs has a mode for this now.

  136. Or for the more confident: by whoever57 · · Score: 1

    ZZ

    --
    The real "Libtards" are the Libertarians!
  137. Re:Just using VIM by Adam+Hazzlebank · · Score: 5, Interesting

    The one I find really useful is .,+20s/foo/bar/g

    Replace all occurrences in the next 20 lines from the current line only. Great when your editing code and you've realised you used the wrong variable name in that method for example.

  138. regular expression groups by naveenkumar.s · · Score: 2, Informative

    When you want to move the words around in a line you can do something like this.

    hello world
    ~
    ~
    :%s/\(.*\) \(.*\)/\2 \1/

    world hello

  139. highlight and indent multiple times? by mbannonb · · Score: 1

    I highlight (ctrl-V) and use 'j' to select lines of text and then I hit '>' to indent the highlighted text.

    However, the highlighting disappears and I usually want to indent more than once.

    How do I keep that highlighting so that I can indent multiple times?

    1. Re:highlight and indent multiple times? by DeathCarrot · · Score: 1
      gv restores your previous selection - yeah not as convenient as keeping the highlighting in the first place, but it works.

      Alternatively, instead of just > you could use 2> or 3> to indent 2 or 3 times.

    2. Re:highlight and indent multiple times? by Jimmy_B · · Score: 1

      Just press '.' (repeat last command) and it will indent the same range of text.

    3. Re:highlight and indent multiple times? by andrikos · · Score: 1

      If you want to indent e.g. 5 times, try 5> ;)

    4. Re:highlight and indent multiple times? by Anonymous Coward · · Score: 0

      Add the following two mappings :vnoremap > >gv
      and :vnoremap gv

    5. Re:highlight and indent multiple times? by mbannonb · · Score: 1

      awesome, thanks!!!

  140. Re:Just using VIM by Anonymous Coward · · Score: 5, Funny

    How else am I supposed to get anything done on Windows?

  141. what's the diff by cbunix23 · · Score: 1

    One of my old favorites

    :w !diff - %

    writes the current file to the diff command, diff compares stdin to the file on disk.

  142. emacs "occur" vim style by Anonymous Coward · · Score: 0

    I switched to vim some years back (I was an emacs biggot)

    One thing emacs had was "occur"

    You can do the same with this: :g/pattern/#

  143. Re:Just using VIM by Timex · · Score: 1

    Feh.

    If you didn't end every command line with "$$", it wasn't TECO. (I first saw it on a DEC PDP 11/70.)

    Kids...

    --
    When politicians are involved, everyone loses.
  144. I've got a question actually by lucas+teh+geek · · Score: 1

    lets say I start editing a file (lets just say /etc/hosts for simplicity) as a normal user then I go to save it and realise I dont have enough privileges to write it, is there some way to escalate vim's privileges without quitting?

    --
    TIAEAE!
    1. Re:I've got a question actually by ecdown · · Score: 1

      Usually I do the following: 1) Ctrl-z 2) change file permissions 2a) sudo root 2b) chmod 666 file 3) fg 4) :w! Then I usually reset the file permissions.

    2. Re:I've got a question actually by dwater · · Score: 1

      I think the real answer to the question is 'no'.

      I can't think of any technical reason why it couldn't do it though. Perhaps there's a security reason.

      --
      Max.
    3. Re:I've got a question actually by SkimTony · · Score: 1

      If I've only made a few edits, I usually just quit and re-edit using sudo. If I have made a lot of edits, I usually save-as with a different filename, and then rename/move the files involved once I can escalate my privileges.

      :w filename
      will write the current buffer as the new filename.

    4. Re:I've got a question actually by muddysteel · · Score: 1

      Nope, ya can't! However, for argument's sake, let's say you forgot to 'sudo vi /etc/hosts' for a moment, I would do the following (assuming *nix):
      ^Z (to suspend my vim session)
      sudo chmod g+w /etc/hosts (assuming i'm a member of the group who can write this file)
      fg (resume gvim session)
      :w! (force the write)
      :q
      sudo chmod g-w /etc/hosts
      cheers!

  145. highlighted comment lines by plzdontspamme · · Score: 1

    A useful way to quickly start or end a major comment block when coding is:

    i#<space><Esc>70i-<Esc>

    This will create a line beginning with a '#' followed by 70 hyphens.

    "ayy

    will copy the current line to the 'a' buffer

    "aP

    will paste the line stored in buffer 'a'. Of course, you can use any letter or number to save to a buffer, which is one of the great things about vi--36 buffers!

    P.S. Is there a way to change the settings in Firefox so vi commands will work when editing text in text boxes?

  146. Reordering a file by terremoto · · Score: 1

    This ex command impressed me.

    g/^/m0

    Now, repeat it.

  147. I kid you not by pomke · · Score: 1

    During a lull in work a year or so ago I hacked up a simple commandline reader for the ambient light sensor on the macbook pro. I then wrote a small bit of vim script to move through a range of themes based on the ambient lighting, so dark text on white in bright sunlight, through to darker themes for late night hacking.

    1. Re:I kid you not by Anonymous Coward · · Score: 0

      Awesome sounding. Do you have it posted anywhere? Or could you? :)

  148. Re:Just using VIM by andrikos · · Score: 2, Informative
    Ctrl+V (Visual mode), select the lines I want, press : (which adds '<,'> automatically) and executing the command:
    :'<,'>s/^/#/
    Comments the lines in quite many languages

    For C I use this
    :'<,'>s+^+//+

  149. Re:Just using VIM by uvajed_ekil · · Score: 1

    Young whippersnappers. When I was "at a young age," it was called stone, and it didn't have any of the fruity ease of use features that other mediums like clay tablets and papyrus have. We had to learn to be precise and exact, because once we typed something there was no way to "navigate" or fix mistakes. I was fine with the drawbacks, because I always knew wherever I was there would be stone, which is not true with clay, papyrus, pulp paper, or systems of tubes.

    --
    This is a hacked account, for which the owner can not be held responsible.
  150. Re:Just using VIM by andrikos · · Score: 1

    Try Windows/Meta key instead of Ctrl+Shift.
    It saves some fingers around ;)

  151. Re:Just using VIM by andrikos · · Score: 1

    And not to mention the handy :make which parses gcc output and moves you directly to the error line inside the editor

  152. Re:Just using VIM by andrikos · · Score: 1
    % over a character like {}, (), [] takes you to the other end of the block.

    You can also combine it in something like d% to delete a whole block.

    On the "block part" again something I find really handy is also d/pattern, where pattern the place until which to delete.

  153. Re:Just using VIM by mattack2 · · Score: 1

    I would use that *if* I could ignore specific kinds of warnings (e.g. deprecation warnings). We use _and_ implement deprecated stuff, and the last time I asked, there was no way to get vim to ignore a certain type of warnings. (You can't turn off this specific type of warning from gcc, and we wouldn't want to generally..)

  154. Hit Ctrl-C instead of Esc by thelenm · · Score: 1

    Here's one that no one seems to know for some reason. You can hit Ctrl-C instead of Esc for switching from insert mode into command mode. I find it much more convenient.

    --
    Use Ctrl-C instead of ESC in Vim!
    1. Re:Hit Ctrl-C instead of Esc by Onymous+Coward · · Score: 1

      <C-[> is also escape. (That's Control-left bracket.)

  155. Wrapping Text by mr_visible · · Score: 1

    I've been using vim for years now, and I only discovered this one a couple of months ago.

    If you want to wrap text to a width of 80 characters, select it using visual mode and type: gq

    You can change the width to something other than 80 characters by doing a

    :set textwidth=<whatever>

    It's very useful for long comments, as it manages to keep the leading comment characters, at least when when I'm editing perl. It actually can do more than just simply wrapping text, see 'formatoptions'.

    Oh and split window editing is useful:

    :sp <file> - Open a file in a horizontally split window
    :vs <file> - Open a file in a vertically split window
    CTRL+ww - Switch between windows
    CTRL+qq - Close the current window

  156. Re:Just using VIM by SL+Baur · · Score: 0, Offtopic

    For some odd reason I'm still using XEmacs.

    Because we're very good at what we do?

    Any real Emacs-based editor has the *huge* advantage that you can both tweak behavior very easily and you also can make extensions very easily.

    I've been an Emacs user for over 2 decades now. I haven't seen anything remotely close to making me want to switch[1].

    Of course, I'm biased ...

    [1] If XEmacs were to become suddenly unavailable, I'd use Stallman-Emacs (or grab an old copy of XEmacs 21.1).

  157. add code block, and diff vs source control by yerex · · Score: 1

    i have a few useful things in my vimrc

    this one, when you visually select a peice of C code and type {, it adds new lines before and after with { and } on them, and indents the code inside. very useful for enclosing existing code in an if.

    vmap { <Esc> '<ko{<Esc> '>o}<Esc> :'<,'> normal ==

    My other useful trick, is to diff the file against source control and highlight changed code, then ]c and [c jump forward and backward to sections of code that have been changed.

    This one is extremely useful as I am often adding a few things here and there to very large files. It updates the diff as you type too.

    function P4diff()
          silent execute '!p4 print -o %.p4rev %\#have'
          diffsplit %.p4rev
          hide
          set nofoldenable
          set foldcolumn=0
    endfunction

    map <C-P><C-D> :call P4diff()

    gf will open the filename under the cursor.
    i like it to be in a new tab, so i have:
    map gf <C-W>gf

    and i have a couple to open the .h or .c file corresponding to the current file

    map gh :tabf %:t:r.h<cr>
    map gc :tabf %:t:r.c<cr>

    ps i wish i had that crazy vi firefox plugin so i could quickly replace all my <s with &lt;

  158. Re:Just using VIM by Anonymous Coward · · Score: 0

    "even Bill Joy doesn't use vi anymore"

    ex , ed are more universal.

  159. Automatically format and indent your file! 4 chars by ooglek · · Score: 1

    I love to use the formatting that is included. Set your filetype and syntax correctly, then type:

    gg=G

    Now your indent preferences, as well as the filetype specific indenting rules are applied to your whole file. Great for getting a piece of code that has horrible standards, just gg=G and you've formatted your file according to your tabstop requirements.

    What I just now learned is how it all works.

    gg -> Go to the first line of the file.
    = -> runs 'equalprg' and if empty, either 'lisp' 'cindent' or 'indentexpr' are run.
    G -> Do something from where you are now to the end of the file.

    Will not work if you've set equalprg to something else.

  160. Place holders.. by McNally · · Score: 1

    I've read through the whole thread so far and haven't seen any mention of the tremendous power available using the grouping operators '\(' and '\)' in regular expression search and replace. You can do some really amazing line transformations using these in the match part of the substitute and the \1, \2, etc. patterns in the replace.

    Let's say you've got a text table of comma separated weather data, for example:

    75,Sunny,5mph,SW
    65,PartCloudy,10mph,W

    and you want to switch the field order so the second field comes first after the replace. Very easy when you know that grouping the match expressions in \( and \) allows you to re-use them in the substitute pattern (\1 is the first grouped match expression, \2 is the second, etc..)

    :%s/\([0-9]*\),\([A-Za-z]*\),\(.*\)/\2,\1,\3/

    will switch the sample text above to:

    Sunny,75,5mph,SW
    PartCloudy,65,10mph,W

    OK, that's a really simple example and could easily have been accomplished by piping the block to awk (for example) but trust me, once you start finding places to use this powerful feature of regex search and replace you'll wonder how you ever lived without it.

    1. Re:Place holders.. by Nicolay77 · · Score: 1

      Well, this /. post is about Vim tricks.

      I can do what you describe in Editplus in Windows.

      --
      We are Turing O-Machines. The Oracle is out there.
  161. Re:Just using VIM by Eivind · · Score: 1

    This is true, but on poor links I've found it MUCH superior to run the editor locally and simply edit the files on the server using sshfs or fish.

    That way there's only network-traffic at all on initial read of the file and on file-save operations. I find a second of file-save lag a lot more acceptable than having the editor itself lag on me as is the case with remote-editing over a poor link, even in vi.

    If you do that, you can run a gargantuan graphical editor over a 9600bps modem-link, it doesn't matter.

  162. Re:Just using VIM by alexdw · · Score: 1

    You can reset your specific "make" command in vim, and you can also tweak the error format. This page shows an example of that:

    http://vim.wikia.com/wiki/Make_support_for_NEC_V850_CA850_compilers

    There is also more information here:
    http://vim.wikia.com/wiki/Errorformat_and_makeprg

    --
    Deliver yesterday, code today, think tomorrow.
  163. minor correction by Metaphorically · · Score: 1

    that'd be

    load "*"

    and I can't print what the shortform looked like here

    --
    more of the same on Twitter.
    1. Re:minor correction by Anonymous Coward · · Score: 0

      You mean holding down run-stop and hitting the "restore" key like it needed to DIE ?

  164. vimrc cruft by twifkak · · Score: 1

    My vimrc is littered with all sorts of small (and probably un-vimish [viccan?]) hacks. Here are three:

    " Tab mappings:
    map <Tab> gt
    map <S-Tab> gT
    map <silent> <Esc><Tab> :exec tabpagenr() % tabpagenr('$') . "tabm"
    map <silent> <Esc><S-Tab> :exec (tabpagenr() == 1 ? "" : tabpagenr() - 2) . "tabm"

    " Undo close tab:
    let s:last_closed = []
    augroup UndoClose
        au!
        au BufUnload * call add(s:last_closed, expand("<afile>"))
    augroup END
    command! UndoClose exec (tabpagenr()-1) . "tabe " . remove(s:last_closed, -1)

    " Source current selection as vimscript:
    map gS "sy:@s<CR>

    --
    I know you were joking, but I want my Karma, so I'm going to reiterate your post in a serious tone.
  165. Re:Just using VIM by Alpha830RulZ · · Score: 1

    When I was young, we wrote code on the paper teletype, and stored our programs on those rolls of punched paper. What is this editing thing you speak of?

    And I really did walk two miles to school, through the snow, uphill both ways (through a good sized valley), so that I could do said programming. Though we were well off, so I did have shoes.

    --
    I was taught to respect my elders. The trouble is, it's getting harder and harder to find some.
  166. Re:Just using VIM by onefriedrice · · Score: 1

    Even better, vi actually is vim on most (all?) unix I've worked with lately. Not even sure the last time I saw the real vi, but vim is way better anyway.

    --
    This author takes full ownership and responsibility for the unpopular opinions outlined above.
  167. Re:Just using VIM by pez · · Score: 1, Flamebait

    man that's so much easier than the Emacs equivalent....

    M-x comment-region RET

    (which, of course, like everything else in Emacs is easily bound to a key if you ever find yourself doing it often)

    *** rushes off to snarkily reply to every vi suggestion with the easier and more sane Emacs equivalent ;-)

  168. Mapping; function keys by herve_masson · · Score: 1

    You can map special keyboard key sto mark begining or end of a block, and a few others keys to save/load/delete the block.

    INSERT => mark begnining of block
    END => mark end of block (and yand the block)
    F2 => save block into a buffer file
    F3 => insert buffer file at current position
    DELETE => remove block

    Here is what I do in .exrc to map those keys:

    map ^[OH mx
    map ^[0F my:'x,'y y^M
    map ^[OQ :'x,'y w! /tmp/bufferfile^M
    map ^[OR :r /tmp/bufferfile^M
    map ^[[3~ :'x,'y del^M

    You need to type CRTL-V before hitting the function key to get its escape sequence properly set in the file. You also can use special names for function keys ( I believe?) instead of storing your terminal-dependant sequences. ^M is a single character (hex code 0x0d) which you can type using CTRL-V followed by the ENTER key.

    1. Re:Mapping; function keys by yukk · · Score: 1

      You could use memory buffers:
      "1 to "9 to store your blocks instead of temp files.
      e.g. 'x"1y'y To pull your block into buffer 1
      and "1p to insert it. Delete could be 'xd'y but these are just style things.

      --
      The trouble with the rat race is that even if you win, you're still a rat." Lily Tomlin
    2. Re:Mapping; function keys by Anonymous Coward · · Score: 0

      Yes, you can do that, but you lose the possibility to insert the saved text into another instance of vi, that's why I'm using files.

  169. Re:Just using VIM by petard · · Score: 3, Interesting

    Sigh. I'm sure I'm not the only one here... I distinctly remember purchasing my first 9600bps modem. (A real Hayes, no less! I sent them a large manilla SASE and they shipped me the AT command manual for no charge.) I spent a few months mowing every lawn I could to raise the funds for it. Exactly a week after I got it installed and found a couple local BBSes I could connect to at 9600, Hayes shipped the very first 14400bps modem.

    Apart from the nature and amount of labor involved in raising funds, that's been a pattern for so many equipment purchases since. That was the very first time I bought something so close to the release of the new shiny, though :-)

    --
    .sig: file not found
  170. My favorite vim trick on Debian by devloop · · Score: 1

    $ sudo apt-get purge vim && sudo apt-get install emacs

  171. Re:Just using VIM by krenshala · · Score: 1

    so, you prefer about 24 keystrokes instead of 14?

    every time i see someone say, "you should use emacs and do it this way ..." they list somethign that is at best the same number of keystrokes and at worst two to three times as many as the vi(m) command they claim is inferior.

    of course, what you are familiar with makes a difference as well, so please don't think i'm trying to say you shouldn't use emacs. ;)

    --

    krenshala

  172. Re:Just using VIM by krenshala · · Score: 1

    vim for windows works pretty good ... thought not quite as useful as having cygwin installed.

    * leaves himself a note to get cygwin installed on the home system

    --

    krenshala

  173. Tabs by Anonymous Coward · · Score: 0

    If you are running version 7 you can now have tabs with :tabnew

    Lots of info here: http://www.linux.com/articles/59533 [linux.com]

  174. Re:Just using VIM by krenshala · · Score: 1

    I've tried to blot the memory from my mind: was the PDP 11/70 the one with the 128kb 11 inch floppy drive for booting? If so, I *hated* that machine!

    --

    krenshala

  175. Re:Just using VIM by krenshala · · Score: 1

    You had stone? In my day we had to paint on cave walls with plant juice. we'd use ashes instead but most of us didn't have any fire.

    --

    krenshala

  176. Re:Just using VIM by krenshala · · Score: 1

    And yet the cat would *still* hear that can open ...

    --

    krenshala

  177. Re:Just using VIM by krenshala · · Score: 1

    You had rolls of punched paper? That's way better than a deck of punch cards ... especially if you drop it.

    --

    krenshala

  178. Re:Just using VIM by laejoh · · Score: 0

    Replace Vim or GVim with any editor of your choice.

    Does emacs count?

  179. Re:Just using VIM by krenshala · · Score: 2, Insightful

    This reminds me of the not-quite-a-joke: A programmer will spend 30 days writing a script that saves him 30 seconds ... every time he uses it. Using vim (or emacs, for those that insist ;) is the same way; you spend time up front to learn how it works only to save truly stupendous amounts of time later when the "obscure commands and meta-keystrokes" you now know saves you minutes to hours per file.

    --

    krenshala

  180. Re:Just using VIM by geminidomino · · Score: 2, Funny

    * leaves himself a note to get cygwin installed on the home system

    How can I install that on Ubuntu?

  181. Re:Just using VIM by poolmeister · · Score: 1

    "Amen. Know vi, and know the bourne shell, and you're good on close to 100% of the unix machines you'll ever touch.

    Apart from HP-UX & AIX which use the Korn shell by default.

    --
    CN=poolmeister.OU=lurkers.CN=slashdot
  182. Live CD by furbearntrout · · Score: 1

    Bart's, Knoppix, Ubuntu/Suse live installers. Whatever you can get to boot. Thank God for NTFS-Fuse.

    --
    Crap. What did the new CSS do with the "Post anonymously" option??
  183. vim ISN'T USEFUL by Jaryn · · Score: 0, Flamebait

    vim ISN'T USEFUL.

    It was useful 30 years ago when a screen was a single display of 80 by 25 characters and the mouse didn't exist.

    The fact that we're talking about 'stupid vim tricks' that nobody else knows about, in order to complete what should be a simple task, means that the program is ridiculously outdated and a poor solution. Using insane strings of characters to.. do a find/replace.. is.. insane and doesn't save time. Use notepad++ or kate or.. anything instead. everything and your grandmother support regexp. vim isn't useful!

    /okay, maybe it's useful.

    /when hax0ring files over the intertubes

    /but it's still dumb.

    /not troll-really!!!

  184. Re:Just using VIM by rrohbeck · · Score: 1

    How else am I supposed to get anything done on Windows?

    Why, Notepad and CMD of course.

  185. Re:Just using VIM by rrohbeck · · Score: 4, Funny

    * leaves himself a note to get cygwin installed on the home system

    How can I install that on Ubuntu?

    VMware.

  186. Re:Just using VIM by rrohbeck · · Score: 1

    I wrote a thesis paper with PRIMOS ED. Fun fun fun.
    The macro handling sucked rocks though.

  187. Re:Just using VIM by Anonymous Coward · · Score: 0

    like Control+A on commands like "select all" that most people never use

    Good grief. Get out of the basement, man. Or step out of the cubicle and go visit the other non-IT departments with PCs on their desks. Ask them what the keyboard shortcut to 'select all', and you're going to be surprised. You'll be hearing them mumbling afterwards, 'He works in our IT department? We're in trouble.'

  188. search / auto-complete / un-indent by Anonymous Coward · · Score: 0

    for programming in VIM i think # and * in normal mode - are a great help (search word back/forward)

    also the ^P and ^N in insert mode (auto complete - search back/forward)

    finally - there is the 0^D command in insert mode (un-indent current line) and it's even a vintage "VI" command.

  189. Re:Just using VIM by shadanan · · Score: 1

    Actually, believe it or not, Ubuntu and CentOS both come with vi by default. Vim needs to be installed either by apt-get or yum. On CentOS, the package is called vim-enhanced. On Ubuntu, you have to apt-get vim.

  190. Re:Just using VIM by dutchd00d · · Score: 2, Interesting

    By the way, you can use any character instead of the '/'. Handy for replacing path names in a file:

    :%s#/bin/ls#/usr/bin/ls#g

  191. argdo by Anonymous Coward · · Score: 0

    From the manual:

    Example:
    :args *.c
    :argdo set ff=unix | update

    This sets the 'fileformat' option to "unix" and writes the file if is now changed.
    This is done for all *.c files.

  192. :map [F1] /[Ctrl-V][Ctrl-M]z[Ctrl-V][Ctrl-M]$ by rdebath · · Score: 1

    :map [Ctrl-V][F1] /[Ctrl-V][Ctrl-M]z[Ctrl-V][Ctrl-M]$

    I like this one, after this every time you hit F1 vi will search for the next match and put it at the top of the screen.

    Of course there are loads of others, some my faves ...

    the standard c2w or c2t[Space]
    with the second of those you have c; to almost do it again.
    how about d0 or c0
    H and L are probably the least well known of the most useful movements.

    Of course the ones that make people with lessor editors hate you are 15>> and 15<<

  193. Unlimited undo, and of course, suspend... by fgaliegue · · Score: 1

    u to undo, C-r to redo. :w your file, C-z to suspend, try, fg to re-edit, use undo: GREAT for testing configuration files/scripts. :w /other/file/name, of course.

    Stripping out ALL comments and empty lines from files where comments begin with hashes: :g/^\s*\(#\|$\)/d

    The /c modifier to :s.

    The 26 registers, a to z. The 26 marks, a to z.

    Mark a, mark b. Substitute only on lines between a and b: :'a,'bs/what/ever/

    I love vim.

    1. Re:Unlimited undo, and of course, suspend... by dwater · · Score: 1

      > Stripping out ALL comments and empty lines from files where comments begin with hashes: :g/^\s*\(#\|$\)/d

      Curious....why do you use \( and \) in that?

      --
      Max.
    2. Re:Unlimited undo, and of course, suspend... by fgaliegue · · Score: 1

      > Curious....why do you use \( and \) in that?

      [and \|]

      Because for some reason, vim sticks to the vi regex dialect in many ways, at a time where (, ), |, +, ?, { and } were literals (unlike in more modern regex dialects).

      You MUST put a backslash in front of all of those in order to make them have their "regex" meaning.

    3. Re:Unlimited undo, and of course, suspend... by dwater · · Score: 1

      Ah, I get it. It's because you're using an OR '\|'.

      It looked strange to me because I was familiar with using '\(' and '\)' for marking text to be later included in the substituted text (eg '\1'), but this command doesn't have such a thing.

      I wonder if you can later use the '\1' for anything, or does it just disappear?

      --
      Max.
    4. Re:Unlimited undo, and of course, suspend... by fgaliegue · · Score: 1

      > Ah, I get it. It's because you're using an OR '\|'.

      In fact, an alternative ;) And you do NOT have to use an alternative inside parentheses. You may use it standalone, eg, 'cat\|dog'

      As to grouping operators, \( and \) in vim, nothing prevents you from using them without ever using the captured text. And AFAIK, grouping does not preserve contents across regexes either.

      Maybe vim has some special syntax to capture groupings in, say, registers, but if so I don't know of it.

    5. Re:Unlimited undo, and of course, suspend... by IpalindromeI · · Score: 1

      Start regexes with \v and never waste your \'s again.

      --

      --
      Promoting critical thinking since 1994.
  194. Re:Just using VIM by mcrbids · · Score: 1

    ...and having to spend time at bps rates lower than 9600 when performing tasks, you clearly don't appreciate the speed increases over the years the same as some of us.

    I started telecommunications at 1200 bps, so I think I can appreciate the benefits of speed. I remember using a crossover serial cable with Artisoft's LANtastic over a 19,200 BPS interface on DOS 3.x. I remember waiting 20 minutes to load a program while the cassette tape played...

    I get really sad when I see wasteful memory and cpu bloat. Perhaps these will become scarce resources again with the mobile trend, and people will do a better job watching their consumption. Oh well.

    Here's where we differ. Look to the cost of this "bloat", because that's the only real factor that matters. Today's "bloated" 20 GB Operating System is much, much cheaper than Windows 3.0 was on a 10 MB hard drive, simply because the disk space used by Windows 3.0 cost around $100 while the disk space used by Windows Vista costs about $5.

    That's not "bloat" - that's putting your money where it counts - features rather than being "lean" which offers little actual value.

    --
    I have no problem with your religion until you decide it's reason to deprive others of the truth.
  195. The keyboard is the same. by rdebath · · Score: 2, Insightful

    The keyboard hasn't changed in the 100 years and that is the main bottleneck. Vi is the most efficient keyboard interface to a text file I know of.

    Emacs is nicer to use at first and is just as efficient for very simple and very complex edits but it's poorer in the middle. The trade off (both ways) is what gives the nice "community spirit".

    The editors you mention don't even have the concept of complex edits and frequently require you to drag you hands away from the home keys, not just to the further reaches of the keyboard (like emacs) but right off the keyboard. This is the sort of thing that can break your concentration (ie WTF has happened to that ****ing mouse)

    BTW: Regex S&R is one of the simplest of the "complex edits"
     

  196. Re:Just using VIM by sfm · · Score: 1

    I thought all TECO commands looked like transmission line noise .....

  197. help by Anonymous Coward · · Score: 0

    :h
    most helpfull command

  198. making vi sane by Anonymous Coward · · Score: 0

    we live in 2008+ why is vim not the default?!
    # echo "alias vi=vim" >> ~/.bashrc

    default navy blue on black, what were they thinking?!
    # echo "colorscheme murphy" >> ~/.vimrc

    check out the purdy colours :)
    # vi /etc/httpd/conf/httpd.conf

  199. tab support by merer · · Score: 1

    Tab support is one of the most useful features for me.
    Launch "vim -p <multiple files>" and map some commands for ease of use:
    :map th :tabnext<CR>
    :map tl :tabprev<CR>
    :map tn :tabnew<CR>
    :map td :tabclose<CR>

    1. Re:tab support by ilovegeorgebush · · Score: 1

      I find mapping to Function keys much better:
      :map :tabn etc.

  200. Re:Just using VIM by wiz_80 · · Score: 1

    You had plant juice? In my day we had to cut off our own limbs to paint with blood on the cave walls, and then walk home, uphill, in the snow.

    Young 'uns these days, don't know how good they've got it.

    --
    " There is a rational explanation for everything. There is also an irrational one. "
  201. Clever deleting by Boawk · · Score: 2, Informative

    Everyone is aware of commands such as dw which will delete a word. Many are aware that the valid generalization of that command is d<movement>. Few people are aware that <movement> means pretty much anything which moves your cursor. For example, d/sometext<return>. Use your imagination; anything which moves your cursor.

    1. Re:Clever deleting by Onymous+Coward · · Score: 1

      "Feel free, my friend. Whatever moves your cursor."

  202. Re:Just using VIM by Terrasque · · Score: 1

    In the folder browser in gnome, just type in ssh://server/path - and use gedit to open the file.

    It downloads the file, edits locally, and saves to the server. Simple and easy.

    --
    It's The Golden Rule: "He who has the gold makes the rules."
  203. Getting copy/paste to work by cerberusss · · Score: 2, Informative

    Vim works wonderful together with X. Besides the graphical version (gvim), it's also possible to start vim in a terminal like xterm, konsole or gnome-terminal. With the right options, it's still aware of the X clipboard, the mouse, et cetera. However it's quite a pain in the ass to find out what's wrong when it doesn't work. Here's a guide for using and fixing it.

    vim has one default clipboard, but has an extra one under any a-z character. The two X clipboards are available too, but under a special character. To paste the X clipboards, paste either the + or * clipboard:

    This is the X clipboard for which you just select something with the mouse: [Escape]"+p

    The star buffer contains the X clipboard for which you selected with the mouse, then right-clicked and selected 'copy', or pressed a shortcut like CTRL-C or similar: [Escape]"*p

    If this doesn't work, check the following things:


    • Vim is started in compatibility mode. Solution: don't use 'vi' to start, use 'vim'. On RedHat and CentOS, it's not enough to start 'vim', use 'vimx'. If this program is not present, be sure to install the package 'vim-X11'.
    • Vim is not compiled with the right options. To check: 'vim --version | grep xterm', and the output must show '+xterm_clipboard'.
    • You used SSH to log into a remote machine and X11 is not forwarded. To check: start a simple X program like 'xclock'. Solution: start ssh with option '-X'.
    • You used SSH with -X and X11 is still not forwarded. To check whether the system administrator has configured the SSH daemon to deny X11 forwarding, add the -v option, and check whether the following line shows up and the request is not denied. If this is the problem, ask your sysadmin to add the line 'X11Forwarding true' to /etc/ssh/sshd_config.
          $ ssh -v -X remotemachine ...
          debug1: Requesting X11 forwarding with authentication spoofing. ...
    • You used SSH with -X and X11 is still not forwarded. Use the -v option as above, and check for the following line. If it appears, ask your sysadmin to install the xauth program.
          debug1: Remote: No xauth program; cannot forward with spoofing.
    --
    8 of 13 people found this answer helpful. Did you?
    1. Re:Getting copy/paste to work by Anonymous Coward · · Score: 0

      Don't forget that the mouse is off by default.
      type ":set mouse=a" to turn it on. Before figuring this out, I never use the visual mode.

      Note that using VIM from putty, you don't need x11 forwarding for the mouse. Putty sends the mouse anyways. However, for the clipboard, you probably need to install Xming, unless someone can suggest a simpler way.

    2. Re:Getting copy/paste to work by dwater · · Score: 1

      I'm curious why you start all your commands with 'escape'?

      --
      Max.
    3. Re:Getting copy/paste to work by cerberusss · · Score: 1

      Hmyeah not really necessary if you assume you're in command mode.

      --
      8 of 13 people found this answer helpful. Did you?
    4. Re:Getting copy/paste to work by dwater · · Score: 1

      It's at least traditional to express key sequences from 'command' (is that the correct name?) mode...eg 'i' takes you to insert mode, 'a' takes you to append mode. I would have called the mode ':' takes you to 'command mode', but perhaps that is wrong....looking in :help I see it's called 'command-line mode', and what you call 'command mode' is actually 'normal mode' :) So, there is no 'command mode' as such, though the mode ':' takes you to is closest, I think.

      Anyway....

      --
      Max.
    5. Re:Getting copy/paste to work by cerberusss · · Score: 1
      --
      8 of 13 people found this answer helpful. Did you?
    6. Re:Getting copy/paste to work by IpalindromeI · · Score: 1

      According to :help quoteplus, you got the target X clipboards backward:

      There are three documented X selections: PRIMARY (which is expected to
      represent the current visual selection - as in Vim's Visual mode), SECONDARY
      (which is ill-defined) and CLIPBOARD (which is expected to be used for
      cut, copy and paste operations).

      Of these three, Vim uses PRIMARY when reading and writing the "* register
      (hence when the X11 selections are available, Vim sets a default value for
      'clipboard' of "autoselect"), and CLIPBOARD when reading and writing the "+
      register. Vim does not access the SECONDARY selection.

      So "* is when you selected something with the mouse. And "+ is when you used a Copy or Cut command.

      --

      --
      Promoting critical thinking since 1994.
  204. Re:Just using VIM by SolitaryMan · · Score: 1

    I often use it with /c option to be sure it substitutes The Right Thing, like this:

    :%s/foo/bar/gc

    For every change found it will ask you whether to substitute or skip (or quit)

    --
    May Peace Prevail On Earth
  205. Command recording by Bazer · · Score: 1

    qA - start recording to the 'A' buffer.
    Do some magic on a record/block/line.
    Hit q to stop recording.
    Typing @A will repeat all your magic between qA and q.
    If you'll end the recording session with a move to the next record/line/block that needs to be processed then you can just type 1000@A and be done with it.

  206. Re:Just using VIM by gstone · · Score: 1

    Except it's not 24 keystrokes. Here is my count:

    Ten!

    However,I assume there _must_ be an easier way to comment a region in vim? I am an emacs person, but I have seen my colleague insert a % at the front of a line and have this repeated down a block. It looks like significantly less than 14 keystrokes, and of course is much more flexible.

     

  207. Re:Just using VIM by gstone · · Score: 1

    Whoops: my keystrokes were filtered out!

    meta - x - c - o - m - m - tab - r - tab - enter

    Ten!

  208. My personal favourites by andrewmc · · Score: 1
    A few of my own favourites:
    • :windo :bufdo :tabdo and :argdo. Absolutely magic if you've a large number of files to work with. (:help :windo)
    • "gq" for reformatting (:help gq)
    • Digraphs for common characters not on your keyboard (:help digraphs). Press ctrl-K followed by the two characters to type them in, e.g. ctrl-k, p, * prints a Greek pi(:help i_CTRL-K). Use :digraphs to list them all.
    • For other characters, "ga" for finding out the ascii/unicode value of the character under the cursor (:help ga), and it's converse: ctrl-v, u, to type them in. (:help utf-8-typing)

    Yes, I do work with a large number of odd characters in my work :). But when you get used to typing them, you start using them everywhere. Just because you can.

  209. Re:Just using VIM by Anonymous Coward · · Score: 0

    Ten keystrokes? Won't your fingers get tired? Put this in your .emacs:

    (global-set-key [f5] 'comment-region)

    Now you can do it in one keystroke by pressing F5. Ahhh emacs.

  210. VimOutliner by Anonymous Coward · · Score: 0

    I recently discovered the VimOutliner plugin. It allows for creating outlines and adds checkbox capabilities so you can use it as a TODO list manager (including automatic percentage calculation).

    It uses plain text format, so it is easily stored in version control and can be read and modified by other text editors as well (just in case), but also viewed in your SCM frontend (Trac, gitweb, hgweb etc.).

  211. Re:Just using VIM by MoogMan · · Score: 1

    Luxury! In my day, there were no such thing as multi line editing. We used ex to edit line by line, and we were lucky!

  212. Move on the line by Anonymous Coward · · Score: 0

    The trick that did the difference was :

    f,F,t,T

    if you type fa you go to the first a after the cursor on the line. Very usefull.

    second : C-V to be able to comment/decomment many lines

  213. Re:Just using VIM by vhogemann · · Score: 1

    Well,

    Kate is able to edit files over ssh, ftp, sftp, and probably other dozens of network protocols supported by KDE.

    --
    ---- You know how some doctors have the Messiah complex - they need to save the world? You've got the "Rubik's" complex
  214. Re:Just using VIM by Anonymous Coward · · Score: 2, Informative

    try MacVIM which is an excellent port

  215. Re:Just using VIM by Anonymous Coward · · Score: 0

    AMEN Brother.. We were lucky to have 8MB on the system and vi was a luxury item. Don't forget the day's of ed.

  216. Re:Just using VIM by yogikoudou · · Score: 1

    I've been in this business for too damn long.

    Damn! You have a 5-digit prime ID and you did the "get off my lawn with your fancy emacs" joke. I bow before you.

  217. Re:Just using VIM by WoLpH · · Score: 3, Informative

    It's quite easy

    1. ^V for block select
    2. Select the lines you want (10j for the next 10 lines)
    3. I for insert mode
    4. Type the # or whatever you want to prefix
    5. <esc>
  218. Re:Just using VIM by Anonymous Coward · · Score: 0

    yes uphill boot ways, which just means he's a dumbass: all he had to do to walk downhill both ways was take the morning route in the evening and vica versa.

  219. Re:Just using VIM by etwills · · Score: 1

    [...]it was called vi, and it didn't have any of this fruity syntax highlighting, and if you wanted to navigate around a document you had to use h,j,k,l, not those hand-holding arrow keys

    When I came to Unix, although I had a DOS PC by then, my main computer had been a ZX Spectrum. The transition from 5, 6, 7, 8 (for left, down, up, right) to h...l was completely natural.

    (I'd be interested if anywhere documents it as something other than coincidence...)

  220. Re:Just using VIM by Timex · · Score: 1

    It was an 8-inch floppy, but yes.

    I was greatly amused when the Admin bought a Mac (now known as the "Mac Classic"). The Mac was more powerful than the mainframe! :D

    Oddly, I still look back fondly at the days when I trampled through RSTS/E... I think I still have an emulator around here somewhere. :\

    --
    When politicians are involved, everyone loses.
  221. Re:Just using VIM by shish · · Score: 1

    but who wants to learn a bunch of obscure commands and meta-keystrokes? If you just need to edit some text, there are simpler solutions

    Why learn to cook when you can eat at McDonald's for every meal? :P

    --
    I mod down anyone who says "I will be modded down for this", regardless of the rest of their comment
  222. Re:Just using VIM by jaredmauch · · Score: 1

    The problem I have is that these programmers translate to routing equipment that I use eg: Juniper and Cisco platforms where the memory and cpu continue to be at a premium. While they develop on the latest c2d cpus, the devices that make up the core of the internet actually are more like SR71000 CPU at 600Mhz with 1GB of ram, or a 2ghz pentium mobile processor, or even 300Mhz MPC 755 processors.

    While most people don't consider these an embeded platform, the constraints that exist here have real impacts as there's not always protected memory (cisco). You would be sad to see what they charge for memory and flash cards.

  223. Re:Just using VIM by ROBOKATZ · · Score: 1

    map s/^/#/^M

  224. Re:Just using VIM by ROBOKATZ · · Score: 1

    Ooops, html escaped my ... map <F5> s/^/#/^M

  225. Re:Just using VIM by ppc_digger · · Score: 4, Funny

    He said an editor, not an operating system.

    --
    Of all major operating systems, UNIX is the only one originally meant for gaming.
  226. Re:Just using VIM by ROBOKATZ · · Score: 1

    Even the Ubuntu vim package is pretty barebones. To get e.g., syntax highlighting, you need to get vim-full.

  227. Re:Just using VIM by ROBOKATZ · · Score: 1

    Not living in an escher painting would help, too.

  228. Re:Just using VIM by kyofunikushimi · · Score: 1

    If you don't use caps-lock, you can remap your caps-lock to escape. That's saved me oodles of time.

    --
    oo
  229. Switch ESC and Caps Lock by omuls+are+tasty · · Score: 1

    KDE can do it, don't know if other environments can. AFAIK the very reason why the Esc key was originally chosen for entering the normal mode was that it was located where the Caps Lock is now.

    Saves me a helluva lot of time. The only problem is that now I keep WRITING THINGS IN CAPITAL LETTERS ON OTHERS' COMPUTERS

  230. Re:Just using VIM by petermgreen · · Score: 1

    One thing i've always thought would be nice would be a ssh client with a built in text editor. It should be able to be far more responsive on laggy connections than editing on the server since it won't have to resend everything each time it redraws the screen and would allow the full comfort of a gui editor.

    BTW does anyone else find it annoying that none of the free software ssh clients seem to be able to open a new terminal without opening a complete new ssh connection and re-authenticating.

    --
    note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  231. vim cheat sheet by zbharucha · · Score: 2, Informative
  232. For purists like me... by CatsupBoy · · Score: 1

    My favorite redhat "vim" trick: unalias vi

  233. Re:Just using VIM by Smeagel · · Score: 1

    Yes - there's a commentify module. You can bind it to any key, I use ctrl-c. Then you can combine it with anything you want (ctrl-c on a selection comments them all, pressing 10 before ctrl-c comments 10 lines, lots of other options, holing control and hitting c 5-times to quickly comment as you go).

  234. Re:Just using VIM by Smeagel · · Score: 4, Insightful

    You do realize you can bind macros to keys in vi too? I've never understood this absurd argument from emacs people..

  235. Re:Just using VIM by DG · · Score: 2, Funny

    Young whippersnapper.

    You think *you* had it tough? We had to figure out all the fundamental constants of the universe and then tough off the Big Bang and wait for limbs and blood to **evolve** before we could paint on the cave walls.

    You "we inherited an inhabited universe" guys had it *so* easy compared to us. Did *you* ever work out the ideal value of Plank's Constant by trial end error? I don't think so.

    Meh. Kids today.

    DG

    --
    Want to learn about race cars? Read my Book
  236. Re:Just using VIM by Smeagel · · Score: 1

    You could always mount using shfs (ssh file system) and edit it that way - making sure to keep your temporary file in a local place.

  237. Re:Just using VIM by Remus+Shepherd · · Score: 1

    Ah, EDLIN. I wrote a relational database in DOS 3.1 using EDLIN. Looking back at those days, I must have been Superboy to complete such herculean tasks. Or maybe Bizzaro-boy, because it was stupid of me to even attempt them.

    --
    Genocide Man -- Life is funny. Death is funnier. Mass murder can be hilarious.
  238. Lies! by argent · · Score: 1

    Ah, add "set compatible" to your .vimrc file and you have 99% vi behavior.

    Lies! Oh, the sad day when I believed those lies, and tried to make peace with vim.

    I've had up to 20 lines in my vimrc suggested by well meaning idiots like you and still found myself going back to real vi.

    Why would you use plain vi, when vim is so much better?

    Because the latest version of vi, nvi, is even better.

    1. Re:Lies! by mario_grgic · · Score: 1

      Well, I still have not heard anything from you that would explain why vi is working better for you than VIM?

      I happen to work for a company that makes plain vanilla implementation of vi as part of our Toolkit (a UNIX subsystem for Windows)

      http://en.wikipedia.org/wiki/MKS_Toolkit

      and funny thing is, we all prefer to use VIM here. I guess we must all be idiots.

      --
      As the island of our knowledge grows, so does the shore of our ignorance.
    2. Re:Lies! by Nicolay77 · · Score: 1

      As someone who's learning vim, and coming from windows, and totally hating it, can you please sell me the idea about nvi?

      At this point, I really need something to make my work easier.

      --
      We are Turing O-Machines. The Oracle is out there.
    3. Re:Lies! by argent · · Score: 1

      I still have not heard anything from you that would explain why vi is working better for you than VIM?

      You're not going to. That's a discussion I've had too many times over the years and, well, vim users and the vim developers always end up going either "why on earth would you want to do that" or "if you add this obscure option to your vimrc, I'm sure it'll work". Since I don't *need* to use vim, and I don't *need* to convert you, I'm not going to go through all that again. Just take it as a given that I like vim so much that I ported another vi-like editor (elvis) to the Amiga because vim ticked me off so much maintaining a port was less of a hassle for me.

      But, setting that aside... MKS, eh. So they're still around.

      I've used MKS toolkit now and then. Back in the '90s it was the bomb. I loved it. It made Windows survivable.

      But it soon felt, well, a little dated... and pretty soon Interix and Cygwin pushed it quite out of mind. Yes, I know Cygwin's a security hole waiting to happen... I caught Korn's lecture on that at Usenix... but people still use it because it's maintained and upgraded and not still trying to catch up with 4.2BSD.

      And because it's free, of course. But things like shipping "a plain vanilla version of vi" in MKS instead of picking up nvi really doesn't help. And it's BSD licensed, so there's really no reason you can't pick it up...

      http://www.bostic.com/vi/

  239. Re:Just using VIM by usrbinallen · · Score: 1

    Eclipse has a vi compatability plugin for $15 (or maybe Euros). Well worth it if you do Java. I wonder if it works in the eclipse++ IDEs?

    --
    Not everything that can be counted counts, and not everything that counts can be counted. Albert Einstein
  240. A useful vi Plugin for Eclipse by chelsel · · Score: 1

    If you use Eclipse, then you have to checkout http://www.satokar.com/viplugin/ it's a vi editor plugin for Eclipse. I've been using it for a year and their most recent version is very, very stable.

  241. Re:Just using VIM by The+Mighty+Buzzard · · Score: 1

    Works under wine too, last I checked.

    --
    Violence is like duct tape. If it doesn't solve the problem, you didn't use enough.
  242. Tabbed Editing, folds, and more by oddRaisin · · Score: 1

    vim is one of those tools that does way more than you'd ever reasonably expect. It's crazy the stuff that's out there. Here are some useful ones I can't live without.

    Tabbed Editing

    You can edit multiple files in tabs with vim. 'vim -p file1 file2' will open the listed files in tabs. While in vim ":tabe filename" will open the given file in a new tab. I have [ and ] mapped to :tabp (previous) and :tabn (next) for moving around.

    Folds

    I like folds for cleaning up my source code visually. Just add a comment that has {{{ in it at the beginning of the block and another comment with }}} in it at the end of the block. Press zc somewhere inside the block and presto! You've got a line instead of blocks of code. You can put a summary of the block of code in the fold marker comment at the beginning of the block which will show up when folded.

    Word completion
    Pressing control-n while typing will have vim pop up a list of options. For common languages it's smart enough to offer suggestions for function and variable names, as well as library functions.

    Printing a section of code
    I always work with line numbers enabled (:set no), because there are a lot of line oriented commands. e.g. :10,100!sort (sort lines 10 through 100). One of these commands is :10,100hardcopy, which will print just those lines. :hardcopy by itself will print the entire file.

    So many more. You can have integrated spell checking (:set spelllang=en_us , :set spell , z= will offer suggestions for misspelled words). Bookmarks, :g//, :v//, and that's just the core. There are hundreds of great plugins (and themes) out there.

  243. Tilde by thrykol · · Score: 1

    Surprisingly useful is ~ in command mode. It will change the case of your text. Throw a number in front and that many characters will have their case changed.

  244. Re:Just using VIM by Thuktun · · Score: 1

    Similarly you can press m-a (or some other letter) to mark a place with the label 'a'. Then you can :'a,.s/foo/bar/g to replace foo with bar from label 'a' to the current line.

    You can also !}foo to run command foo on the paragraph following the current position. This is great for running sort on a collection of lines to be sorted or fmt to format the paragraph within line widths.

    Most of these are just RTFM, though.

  245. Split view, edit, next, ff ftw by Anonymous Coward · · Score: 1, Informative

    Ctrl-w + s for split horizontal, Ctrl-W + v for split vertical. Ctrl-w then moves between the panes, and in each pane you can split it again to your hearts content. Also :edit to edit a new file, if you open multiple files like vim *.txt then :next will move to the next file.

    Very useful :![cmd] to execute a command back on the shell, like :!tail /var/some/log to check errors while fixing them in your code.

    Also nice to see a little firefox kickback to VIM - in firefox hit / to search through the document, shortcute for ctrl-f/splat-f

  246. Re:Just using VIM by yukk · · Score: 1

    Why learn to cook when you can eat at McDonald's for every meal? :P

    Well, that's the problem isn't it. It's The American Way these days.

    --
    The trouble with the rat race is that even if you win, you're still a rat." Lily Tomlin
  247. Re:Just using VIM by Anonymous Coward · · Score: 1

    if you use visual mode (v) to highlight the function you can then use: :s/foot/bar/g and will only change occurences in the highlighted code.

    Useful if you're worried about the replace spilling into the next section of code

  248. MOD Parent up by slagheap · · Score: 1

    MacVim is an excellent port of VIM for OS X. http://code.google.com/p/macvim/

    --
    First against the wall when the revolution comes
  249. Re:Just using VIM by What'sInAName · · Score: 1

    You are close. on Ubuntu at least (I don't know about CentOS) vim-tiny is installed by default, and to get "real" vim, you just install "vim". I only say this because if you have an Ubuntu server install (i.e. bare-bones, without X), and you install vim-full, you will get, in addition to "real" vim, the GUI version of vim. That implies of course that you are going to get a whole boatload of packages (such as X), which you probably don't want (or you would have installed it in the first place).

  250. Re:Just using VIM by MikeBabcock · · Score: 1

    Back in the day when I was first using DOS 3.x, I was shown how to edit CONFIG.SYS and AUTOEXEC.BAT by 'type'ing the contents (cat equivalent) and then retyping it with "COPY CON AUTOEXEC.BAT"

    When I figured out edlin, I was in heaven lol.

    --
    - Michael T. Babcock (Yes, I blog)
  251. Re:Just using VIM by Brassrat70s · · Score: 2, Insightful

    years ago i had a (fortunately) mild case of carpal-tunnel syndrome. After a cortisone shot, I stopped using emacs - no more CTRL-THIS and CTRL-THAT - and haven't looked back. The advantage of a mode-based editor is that you can get by with simple single keystrokes which are much less stressful to you hands.

  252. Re:Just using VIM by narooze · · Score: 1

    Eight Megs and Constantly Swapping

    I thought it stood for Esc-Meta-Alt-Ctrl-Shift.

  253. Re:Just using VIM by Undead+NDR · · Score: 1

    Apart from HP-UX & AIX which use the Korn shell by default.

    And FreeBSD (tcsh), OpenBSD/NetBSD (ksh) ...

    Once again, "Unix is not Linux".

  254. Have a :ball with these by Anonymous Coward · · Score: 0

    Open up a whole bunch of buffers and: :bufdo :%s/foo/bar/g

    That one is like sed, but if your already in the editor and already have the files open, this makes a lot of sense.

    Another one: :g/^\s*$/d

    Macros:
    gq then do stuff then @ to replay the stuff

    Reindent:
    gg=G

    Reformat:
    gggqG

    <c-v> to select blocks of text

    Search for the word under the cursor:
    * and/or #

    I forget most of them I use on a daily basis, I just do stuff without thinking about the commands anymore.

    The best vim tip of all: use xkeycaps to map capslock to esc.

  255. Command mode by Kernel+Kludge · · Score: 1

    I just use ctrl-[ (open bracket, a.k.a. ASCII ESC). Works well on all keyboards and ctrl is a much more common keystroke so the finger memory is already there. 'Course I also map ctrl to be left of A where it was before the IBM PC/AT screwed it up. ;-)

    I'm similarly lazy with backspace (ctrl-H) and tab (ctrl-I). I seem to do fine with newline.

    Modal editing is a common complaint. It's just a different paradigm and a very small time investment can get most folks past it.

  256. Re:Just using VIM by nihaopaul · · Score: 1

    thats what screen is for

  257. Re:Just using VIM by Sancho · · Score: 1

    Definitely. I've been lucky with my hands so far, so I hadn't thought of that aspect, but that's a good point, too.

  258. Completion by tokuchan · · Score: 1

    Here is a neat one:

    First, compute the set of tags for your project. You can use ctags *.c *.h, for example, but other programs may also be able to produce a tags file. The format of the tags file is fairly simple. Each line is the tag, followed by a tab, then the relative path to the file containing that tag, followed by a tab, then a regular expression matching the line on which that tag is found. If the tag occurs more than once, just insert new copies of the line with different regexes.

    Now for the neat, Vimmy part. When typing in insert mode, press Crtl-N and you will get a completion window that lists all of your tags. Pretty neat, huh?

  259. Re:Just using VIM by Lobster+Quadrille · · Score: 1

    Yes, but when you've got a shell session open already, who wants to open Kate (okay, on my system she's always open), punch in the credentials, and navigate to the file you want to change. It's an awful lot easier to jut type "vi filename".

    Don't get me wrong, I love Kate, but vi is fast. Wicked, wicked fast.

    --
    "The cup is in turn designed for holding hot or cold liquids, and has an open rim and closed base." --US Patent #5425497
  260. Re:Just using VIM by ElectricRook · · Score: 1

    With "modern" editors, one always ends up driving the mouse. To me, driving a mouse for a living, is about as cool as driving a truck for a living... Except that when driving a truck, one cannot hear the toad in the next box clearing his throat every 20 seconds, and the scenery does in fact change.

    --
    - High Tech workers, please say NO to Union Carpenters, their Union sees fit to control our compensation.
  261. Sysadmin easy comments by swordgeek · · Score: 1

    I've got two essential lines in my .exrc (yes, this is for real vi, but works in all derivatives):

    map K :s/^/## /^V^M
    map ^K :s/^## //^V^M

    (note that the ^K ^V and ^M are control characters, the ^ in the substitution patterns are literal carats)

    Shift-K comments lines. Ctrl-K uncomments them. As an admin, I use this all the time. When I've done some more involved programming in C, I changed it to C-style comment substitution just as successfully.

    Most useful two extra keys in my arsenal.

    --

    "People who do stupid things with hazardous materials often die." -- Jim Davidson on alt.folklore.urban
  262. Re:Just using VIM by Lobster+Quadrille · · Score: 1

    No, the alligators feed on the downhill route.

    --
    "The cup is in turn designed for holding hot or cold liquids, and has an open rim and closed base." --US Patent #5425497
  263. How about recording? by jivemonkey · · Score: 2, Informative

    In vim/gvim, I think the most useful thing I have ever used is the recording capability. It works great for editing HTML. If you have 10 lines that look very similar (such as a list of navigation links), start recording, edit the first line making sure that you end your statement with 'j' so that it moves to the next line, then finish recording and you can execute that recording for the next 9 lines.

    To start recording, type 'q' and then a number such as '1'. This will record your next keystrokes into memory bank 1. When you're done typing, just hit 'q' to finish recording.

    So, if you had

    <h1>Foo</h1>
    <h1>Foo</h1>
    <h1>Foo</h1>
    <h1>Foo</h1>

    and you wanted

    <h1>Foo Bar</h1>
    <h1>Foo Bar</h1>
    <h1>Foo Bar</h1>
    <h1>Foo Bar</h1>

    you would hit 'q1' to begin recording in bank 1, '^' to start at the beginning, 'l' (as in ell) 6 times to move six characters to the right, 'a' to insert after the last 'o' of "Foo", ' Bar' to insert the string, 'esc' 'j' to finish and move down one line, 'q' to finish recording, then '3@1' to execute the operation in bank 1 three times.

    I can't count the number of times I have used this functionality! Makes coding immensely easier.

    --
    Got a problem? Call a monkey!
  264. Vim (not vi) annoyances? by Kernel+Kludge · · Score: 1

    Moving to vim is still on my to-do list. You see, I've been using nvi for a very long time and I'm rather used to its implementation of various extensions. What I desire most is vim's tab-complete-everything, search history and superior UTF-8 handling.

    But what are your vim vs. other vi annoyances?

    The only big thing I can think of off the top of my head is the undo stack's incompatability with original BSD vi. "uu" in BSD vi and nvi undo and "un-undo" a change. In vim, this undoes the last two operations. Nvi implements the undo stack with ".", the perfectly vi-like repeat command. Thus "u." undoes the last two operations. I'm sure with some practice I can overcome this incompatability, but it's an unnecessary and most un-vi-like UI gaffe IMHO. Advice?

    I rather prefer nvi's simpler if less powerful split screen capability for the fewer keystrokes alone. I don't need half a dozen buffers open at once so the clever management benefits me little. I use cscope for complex navigation. An inconsequential quibble — power to Teh Vim!

    I also like the way nvi lets me fully manage my own command history just like any other edit buffer. I can prune, sort, etc. my history. Vim is rather inflexible on this point.

  265. Stupid Vim tricks? by Anonymous Coward · · Score: 0

    I like to sprinkle just a little on the cloth before I wipe the windows. Gets the stubborn grime off.

  266. navigating slashdot by Anonymous Coward · · Score: 0

    My favorite vi "trick" is navigating slashdot using vi commands 'j' to move down, 'k' to move up.

  267. vimtutor by sirius_bbr · · Score: 1

    It basically takes you through all the basic(++) features of vim.

    vimtutor made me really appreciate vim.

    --
    this sig has intentionally been left blank
  268. The esc key is far, just like the arrows by danieltdp · · Score: 1

    I use Vim primarily because I can perform almost any task without moving my fingers from the standard typing position. I certainly feel much more efficient being able to (for example) use j/k/l/h for movement than moving my hand over to the arrow keys, or worst, to the mouse.

    So you are trying to convince us that its easier to reach ESC and navigate with j/k/l/h instead of just reach the arrow key? Sorry, I don't buy that. The arrows are as far as ESC and besides you are adding keypresses to the process too. I won't event start with the further i to get back into insert mode.

    Vi is fucking awesome, but not for the reasons you present

    --
    -- dnl
    1. Re:The esc key is far, just like the arrows by Sancho · · Score: 1

      Well, I don't use ESC. I use ctrl-c. It takes you out of insert mode, though it has other semantic differences that I don't remember off of the top of my head. Regardless, I haven't noticed the differences, and I could certainly remap the keys if it ever became an issue.

      ctrl-c is a really short movement for my left hand--just one row down from home position. You can also use ctrl-[, but it's a little more cumbersome for me. At this point, it's all muscle memory. Brain wants me to move the caret around, left hand hits ctrl-c. Brain wants to start typing, right hand hits i.

  269. The only one you need to know: by kuzb · · Score: 1

    :q! - every other command is secondary.

    --
    BeauHD. Worst editor since kdawson.
  270. Block comments by Anonymous Coward · · Score: 0

    I used to have this s/^/#/ mapped to a macro and s/^#// mapped to a second macro. This allowed me to comment/uncomment blocks of code in two keystrokes. What I always hated, though, was that when I was searching for all occurrences of a pattern and (un)commenting them, the macro execution over-rode my most recently used search pattern.

    I finally resolved this issue last year when I wrote a couple of Vim functions. Put this in your .vimrc and away you go.

    let g:commentChar="#" ; this can be reset using auto commands so the functions work cross-language

    function! Comment()
            let l:line = g:commentChar.getline(".")
            call setline(".",l:line)
    endfunction

    function! UnComment()
            let l:line = getline(".")
            let l:pos = stridx(l:line,g:commentChar)
            if l:pos > -1
                    let l:line = strpart(l:line,0,l:pos).strpart(l:line,l:pos+strlen(g:commentChar))
            endif
            call setline(".",l:line)
    endfunction

    map ## :call Comment()
    map !# :call UnComment()

  271. Re:Just using VIM by Sancho · · Score: 1

    Hey, thanks for the tip! I tried it out, and it seems to work great!

  272. custom motions really make the difference by agentultra · · Score: 1

    I use a lot of custom motions on top of the stock vim ones. My two most often used are:

    http://www.vim.org/scripts/script.php?script_id=1905

    and

    http://vim.sourceforge.net/scripts/script.php?script_id=30

    It's the motions that really make editing with vim a pleasure.

    No more tapping "l" through someones longCamelCaseClassName to change it. 2,wc,w jumps in 2 words, removes the third and drops you into insert mode.

    Similarily, v]fd deletes a function in python. ]] jumps to the next class definition.

    More motions are better. They help you edit the text structurally rather than as a stream of characters.

  273. Re:Just using VIM by jcuervo · · Score: 1

    Those are both pretty informative. I just go to the first line, set a mark (say, "ma" to set mark "a"), go to the last line ("mb" for mark "b"), then :'a,'bs/foo/bar/g

    Also great for indenting: :'a,'b>

    --
    Assume I was drunk when I posted this.
  274. Re:Just using VIM by Anonymous Coward · · Score: 0

    I'm amazed how few people know the visual mode of vim. I think it was introduced in version 3 maybe earlier.

    What you do is type v from command mode, then move around (its like selecting with a mouse in a GUI editor). You can then do: :s/foo/bar/g (actually vim fills in :'<,'>s/foo/bar/g, where '< is the begining of the visual selection, and '> is the end, same vane as the line numbers).

    and that will work on the "highlighted" portions of the code.

    This works with commandline filters as well.

    Line numbers went out with BASIC.

  275. Re:Just using VIM by robo45h · · Score: 1

    You're failing to consider the following: VIM (and Emacs, but I'm a vi person) have very powerful built-in capabilities that allow you to do things like make very specific global changes, using regular expressions, etc. Most basic text editors lack this. I frequently watch people doing silly things like putting pound-sign (#) characters as comments at the beginning of, say, 10 lines to comment out a section of a script or config file. They're doing it in Windows Notepad or something similar one line at a time. Come on; that's trivial in vi to do very quickly. And that's just the beginning of what you can do. Such a complete waste of time and productivity due to poor tools (provided natively) and poor choices (not getting and learning better tools).

    As for Kate -- that exmplifies another thing you've failed to consider. Kate's not available everywhere. In fact, since my present personal website server runs Ubuntu under Gnome, I've never seen Kate to my knowledge. Meanwhile, VIM (or vi) is available everywhere. It's navtive to all versions of Unix and Linux. So if you're a Unix / Linux system admin, it's available on HP-UX, Solaris, AIX, Red Hat, Ubuntu, SuSe, etc. No matter where you end up, it's there, and it works and it's powerful. Plus, VIM/GVIM can be easily added to other systems like Windows. And it's free.

    Another important aspect, as others have pointed out, is that vi is not required to run as a GUI (though GVIM is available if you want it); you can run it in a terminal window like ssh or telnet. Kate can't do that. Period.

    The vi learning curve admittedly sucks. But I was forced to deal with that in 1985 on systems where that was the only real choice. Since I'm over the hump, it's not an issue for me.

  276. Re:Just using VIM by robo45h · · Score: 1

    In the deep, distant past, I don't think you could bind macros to keys in vi. So it's an old argument that's no longer valid.

  277. Re:Just using VIM by hrimhari · · Score: 1

    Been some time since I last touched a Solaris OS, but have you checked VI in there? Last time I did, it wouldn't even support the arrow keys and had some strange limitations regarding VI commands. The h, j, k, l thing isn't in my blood as much as other VI stuff.

    When you say "most (all?) unix", do you mean Linux/*BSD only or also HP-UX and Solaris?

    Did you install the OS yourself or could it be that somebody else replaced the native VI with VIM?

    --
    http://dilbert.com/2010-12-13
  278. Re:Just using VIM by amorsen · · Score: 1

    There's not much point in using slow processors on routers, and lots of reasons not to. Cisco and Juniper should wake up -- BGP isn't done in hardware, and it can be quite CPU intensive.

    --
    Finally! A year of moderation! Ready for 2019?
  279. Commenting by mr_stinky_britches · · Score: 1

    For commenting, I usually just use the NERD Commenter plugin. Easier to use than constant regular expressions.

    \\cc - comment selected (highlighted) block.

    \\cu - uncomment selected block.

    --
    Censorship is obscene. Patriotism is bigotry. Faith is a vice. Slashdot 2.0 sucks.
  280. ClownColors!!!! by tempest69 · · Score: 2, Interesting

    Why bother asking slashdot when all the best Vim tips have been collected and compiled? http://vim.wikia.com/wiki/Best_Vim_Tips

    Because..drum roll.. Vim has a syntax file for your favorite language..

    You can customize if for your coding style... especially for things that you make wiked mistakes on..
    for example:

    if (x=y){do some code;}

    any c programmer will see the mistake pretty quick.
    but once it's in thousands of lines of code,, its a bear to find.
    with clown colors you set the color of the = to bright purple, and the parens to yellow. set == to orange.. so that your eye catches a painful clash when you type something stupid..

    for the common typos that I make.. I set it to INVERSE... so retrun x; get fixed before get to the next line.

    some of the common variable names I use get colorized so that I can recognize the specific variables...

    So a common for loop that you code without blinking has a "color signature" that lets you know it's your normal.
    fantastic crutch..

    Storm

  281. use vim commands to browse in Firefox by lee1 · · Score: 1

    with the vimperator extension. Everything should work like vim.

    1. Re:use vim commands to browse in Firefox by dwater · · Score: 1

      I've been using vimperator for a little while. It takes a lot of getting used to, but I think it's a revelation in web browsing.

      http://vimperator.org/trac/wiki/Vimperator

      I wish I could edit in text areas like this one using vim, but it doesn't seem to do that - perhaps there's an option I haven't found yet.

      --
      Max.
    2. Re:use vim commands to browse in Firefox by lee1 · · Score: 1

      There are extensions that are supposed to allow you to use your editor of choice for this, but I've never gotten them to work. I just write the comments in vim and paste them in.

  282. Applying commands globally by LSU_ADT_Geek · · Score: 1
    Deleting empty lines from a file:

    :%g:^\s*$:d

    This becomes powerful because now there is a way you can delete multiple lines from a file and not just empty lines. If I am cleaning up a file, I will mark lines I want to keep with some special character I don't expect to find at the beginning of the line and delete any lines that don't begin with it.

    Splitting the screen into multiple windows

    :sp [path to file to open in new window]

    Control + W, direction key - to move between windows; direction key relative horizontal or vertical split

    Control + W, equal sign - to resize windows to be same size

    Control + W, underscore - to maximize current window

    Word completion in Insert mode

    Control + P - This will attempt to complete the word based upon the most recent word in history this matches. It will also show a list of the potential words further in the history it could use if you continue to hit Control + P

  283. Re:Just using VIM by Anonymous Coward · · Score: 0

    The one I find really useful is .,+20s/foo/bar/g

    Replace all occurrences in the next 20 lines from the current line only. Great when your editing code and you've realised you used the wrong variable name in that method for example.

    Or, you could just select the entire method in normal mode:

    f{V%

    And then perform the same replacement:
    :'<,'>s/foo/bar/g

    The nice thing is that everything up to the "s" is inserted for you.

  284. Re:Just using VIM by Mr.+Firewall · · Score: 1

    Young whippersnappers. When I was "at a young age", we had to code with our bare hands, in Assembler, at 110 baud both ways. It was called vi, and it didn't have any of this fruity syntax highlighting, and if you wanted to navigate around a document you had to use h,j,k,l, not those hand-holding arrow keys. And we LIKED it!

    There, fixed that for you.

    --
    In times of universal deceit, telling the truth gets you modded -1 Troll
  285. VIM: A software development IDE by DigitalPenguinDude · · Score: 1

    No one seems to be mentioning the fact that vim is a basic software development IDE and can integrate with tools like cscope. See: http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html

  286. Re:Just using VIM by jeebusroxors · · Score: 1

    Solaris is still vi. You can use arrows but you may have problems. I never looked into why that was.

    And hjkl is great. You can edit and move without moving your hands. Tough to get used to though. I just visualized hl as left and right arrows (obvious). for up and down, the first thing you're going to do in a file is move down, and like a good little typist, your index finger should be on j, which is the easiest to find, and easiest to manipulate(??). *shrug* That's what worked for me.

  287. man page using K by Anonymous Coward · · Score: 0

    To view man page of a word under curser, type K(shift+K)

  288. Re:Just using VIM by Anonymous Coward · · Score: 0

    Rumour has it that cygwin also works in wine.

  289. Hangups - vi and dvorak by SkimTony · · Score: 1

    I use vi(m) on MacOS X, linux, and Windows, though I admit to using the arrow keys because j,k,l,h are tough to keep track of when typing in dvorak. I will also admit to being confused when confronted with a new linux install that has something like "nano" set as the editor - it always takes me a little while to figure out how to write out the file.

  290. Re:Just using VIM by pez · · Score: 1

    The point, my friend, is that 10 strokes of easily-remembered commands is far superior to remembering *both* :'s+^+//+

    *and* :'s+^+//+

    Which the OP first suggested.

    And in case you're counting, that first sequence is 20+ keystrokes of gobbldygook, while Emacs' is not only 10 (Yay! Tab completion!) but it also _makes sense_.

  291. Re:Just using VIM by supernova_hq · · Score: 1

    try using screen on the remote machine.

    This also allows you to exit and resume sessions.

  292. Re:Just using VIM by corbettw · · Score: 1

    Or .,$s/foo/bar/g. Change everything from the current line to the end of the file.

    --
    God invented whiskey so the Irish would not rule the world.
  293. Re:Just using VIM by Ugtar · · Score: 1

    "in fact, when I'm typing in a web form, I frequently find myself trying to use Vi shortcuts"

    There's a cure for that ailment. There's a firefox addon called itsalltext that lets you assign a shortcut to text areas and edit them with the editor of your choosing. This response, of course, was written in vim ;)

  294. Re:Just using VIM by ioshhdflwuegfh · · Score: 1

    Ooops, html escaped my <F5>... map <F5> s/^/#/^M

    If really necessary to bind this to anything, I'd use: qcI#<esc><Ret>q. It's less typing overall and I haven't bound any F-key to such a trivial task.

  295. Re:Just using VIM by petermgreen · · Score: 1

    Screen is handy but it requires learning obscure keystroke combinations and for many uses is IMO nowhere near as convinant as being able to pop

    Also as well as popping up another termainal the official non-free ( back when I last used it there was a freely downloadable version for non-commerical use but I can't seem to find that anymore ) windows ssh client can open a file transfer window just as easilly.

    --
    note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  296. Re:Just using VIM by amRadioHed · · Score: 1

    but who wants to learn a bunch of obscure commands and meta-keystrokes?

    Well, Unix admins for one.

    --
    We hope your rules and wisdom choke you / Now we are one in everlasting peace
  297. Re:Just using VIM by Matt+Perry · · Score: 1

    How can I install that on Ubuntu?

    Use Wine, of course.

    --
    Slashdot: Failed Car Analogies. Amateur Lawyering. Anecdote Battles.
  298. Re:Just using VIM by drew_eckhardt · · Score: 1

    With a reasonable coding standard, it's easier to say :,/^}/s/foo/bar/g

    to get replacements to the end of the function.

  299. Re:Just using VIM by Anonymous Coward · · Score: 0

    FWIW, Gmail uses _some_ of the same key-bindings as vi. Just type "?" from any screen in Gmail. Learning this pretty much made me a Gmail loyalist.

  300. Re:Just using VIM by xarak · · Score: 1

    Me personally, I use regexp's in ed, sed, Perl &c for batch handling large number of files. I find it handy to keep the same(ish) syntax. But that's just what I do.

    --
    Atheism is a non-prophet organisation
  301. Re:Just using VIM by Mr2cents · · Score: 1

    < is for indenting to the left, > is to the right and = is auto-formatting. With code it will indent it to your liking (the default indentation can be modified throug settings), with text it will perform word-wrapping.

    Here are my favorites:

    in insert mode, you can press CTRL-p to do auto-completion (searches for possible completions in the text, or CTRL-x-f for filename completion (like pressing tab in bash).

    Another nice one is CTRL-a and CTRL-x in normal mode. It will increment/decrement the number under the cursor, and it will work with decimal, octal and hex numbers.

    In normal mode, macro's can save your day sometimes. For example:

    1) Go to insert mode, type 1, and go back to normal mode.
    2) qq (this will start recording macro 'q' - qy would have assigned it to macro 'y')
    3) yyp (yank-yank-paste, yy yanks a line (other term for copy), and pastes it on the next line)
    4) CTRL-A to increment that number
    5) q to stop recording macro

    Invocing a macro is done using '@'. @q executes macro q, @@ executes the last executed macro again, 10@q executes macro q ten times, ..

    (Too bad nobody uses line-numbered basic interpreters any more, for this macro would have saved them a lot of time 8-).

    --
    "It's too bad that stupidity isn't painful." - Anton LaVey
  302. Re:Just using VIM by jcuervo · · Score: 1

    I always wondered about macros. Usually I'd miss the ":" key or something, see " - recording - ", and go "wtf?". (Thanks!)

    --
    Assume I was drunk when I posted this.
  303. Comment removed by account_deleted · · Score: 1

    Comment removed based on user account deletion

  304. Open file at specific line by Adam+Hazzlebank · · Score: 1

    I find it useful to fire up vim with vi myprog.c +20 where 20 is a line number. Takes you straight to that line number, useful when fixing compilation errors.

  305. Re:Just using VIM by LarsG · · Score: 1

    I don't have much experience with BGP, but running ipsec on a Cisco 160x wasn't exactly fast either.

    --
    If J.K.R wrote Windows: Puteulanus fenestra mortalis!
  306. How to make peace with vi. by argent · · Score: 1

    If you're coming from Windows, then I don't think you're going to find any version of vi more like what you're used to than any other, and you'll never understand why I maintained the Amiga port of a vi clone for years. But I can give you a few suggestions to make vi easier to understand.

    The main thing to unlearn is the whole business of "insert mode". VI is not a modal editor, it doesn't have an "insert mode". It's normally described that way, even by the authors, but that's not how it works.

    VI is like a stripped down version of TECO. If you don't know what TECO is or was, it doesn't matter.

    What matters is that TECO was designed for printing terminals, it did not provide immediate feedback to commands. You'd enter:

    IThis is some text I'm inserting

    TECO would respond with:

    IThis is some text I'm inserting$$

    If you wanted to see what the line you were editing you'd use another command to display the line. When you're working at 75 baud on a printing terminal this kind of interface was important.

    Now, vi is a lot less powerful than TECO, but it has one feature that makes it a lot friendlier than TECO. And that is, when you enter:

    IThis is some text I'm inserting

    It shows you what the file looks like it while you're entering the command.

    That's what makes people think of that as being an "insert mode" that you end by hitting "escape".

    Really, what you're doing is executing an "insert command", and getting immediate feedback as you're entering it. If you stick to treating it like a "command", and always terminate the command with the final escape. You're always in "command mode" because "command mode" is the only mode there is.

    The actions are the same, but the way you think about them suddenly makes them make a lot more sense.

    Plus, things like applying modifiers to commands work well, too.

    So, if you want to create a line with all the tabstops marked with a "|", you'd enter:

    9a|

    Repeat 9 times, append "|".

    Admittedly, applying counts to inserts isn't at the top of anyone's list, but it's not a specific feature of the editor, it's just a side effect of the way the command structure works, and a nice illustration of the difference between the idea of "insert mode" and "there's no modes, there's an insert command".

    Whether you're using vim or nvi this viewpoint should serve you well.

  307. Re:Just using VIM by GangsterAlgot · · Score: 1

    That's one of many tasks which simply becomes natural over time (in fact, when I'm typing in a web form, I frequently find myself trying to use Vi shortcuts) and which really make things go more smoothly for me.

    Don't mention it, i had to put
    alias :wq="exit"
    in my .bashrc because it drove me nuts when i instinctly tried to close my terminal with vi commands.

  308. Re:Just using VIM by elp · · Score: 1

    The Korn shell and Bash were both improvements on the old Bourne shell. They are pretty much identical for most practical purposes. FreeBSD always has /bin/sh installed on the box even if its not the default, and it behaves like a korn shell. Besides most sysadmins just install bash anyway.

    Linux is just a flavor of UNIX to everyone except the zealots.

  309. Re:Just using VIM by elp · · Score: 1

    Wow, how distant a past are we talking? Function key macros in vi were heavily used on the old SCO 3.2 box I started on back in the early 90s.
     
    Oh man that was such an awful piece of crap! We only had dumb terminals because the TCP/IP licence was almost as much as the operating system i.e. more than my first car.

  310. Re:Just using VIM by squallbsr · · Score: 1

    You forget sed and awk

    --
    Sleep: A completely inadequate substitution for Caffeine.
  311. Re:Just using VIM by squallbsr · · Score: 1

    Mainly because Cocoa is still an API at the lower levels of C and Objective-C. Its not like this newfangled .NET or Java stuff that requires you to load <exageration>8 billion megs</exageration> of code to run Hello World!

    --
    Sleep: A completely inadequate substitution for Caffeine.
  312. vimperator!!! by tsreyb · · Score: 1

    This is my favorite vim trick: install vimperator into firefox. It brings vim to your browsing experience. Throw your mouse away! I *LOVE* vimperator!!! Get it at ..

    http://vimperator.org/trac/wiki/Vimperator

    (beware: my only gripe with vimperator is it, by default, completely hides firefox's menus (!). There is a simple way to bring them back. Look for this info in the docs before you install it)

  313. Re:Just using VIM by Anonymous Coward · · Score: 0

    I found recently more intuitive way to do this. Instead of calculating the number of lines you want to apply the replace logic; use the visual mode.

    Hit v and select all the lines you want your change to affect. Then hit :

    This will automaticallly create a command line :'

    Now you can append to this :'s/foo/bar/g

    Try it, it's quicker.

  314. Re:Just using VIM by wolftone · · Score: 1

    ...a conversation about Vim and you're concerned about learning obscure keystroke combinations?

  315. Re:Just using VIM by Anonymous Coward · · Score: 0

    Actually, there's a way to use your Vim shortcuts while browsing your forums. Try Vimperator for your firefox browser. http://vimperator.org/trac/wiki/Vimperator

  316. Re:Just using VIM by JadeNB · · Score: 1

    Sigh. I'm sure I'm not the only one here... I distinctly remember purchasing my first 9600bps modem. (A real Hayes, no less! I sent them a large manilla SASE and they shipped me the AT command manual for no charge.) I spent a few months mowing every lawn I could to raise the funds for it. Exactly a week after I got it installed and found a couple local BBSes I could connect to at 9600, Hayes shipped the very first 14400bps modem.

    No, no, surely we don't get geek credit for starting with a 9600 baud modem. My first was a 2400 baud (US Robotics, maybe?), and I even used (but never owned) a 300 baud modem. I remember how blazing fast 14400 baud seemed when I first got my hands on it.

  317. Re:Just using VIM by petard · · Score: 1

    No, no, surely we don't get geek credit for starting with a 9600 baud modem. My first was a 2400 baud (US Robotics, maybe?), and I even used (but never owned) a 300 baud modem. I remember how blazing fast 14400 baud seemed when I first got my hands on it.

    Heh. We probably started about the same time... the first modem I purchased was a 2400 baud modem ("Prometheus" I think), and I used but never owned a 1200 baud model. 9600 was just particularly memorable because it was obsoleted *so* immediately after what was, for me, a substantial purchase.

    --
    .sig: file not found
  318. Mine did too! Re:WTF?? by Anonymous Coward · · Score: 0

    (for those of you who don't want to try it, it lists the folder we are in)

  319. Re:Just using VIM by WgT2 · · Score: 1

    awesome

  320. Re:Just using VIM by dublin · · Score: 1

    Wow, you're making *me* feel old. As a college sophomore ('81-'82), I managed to scam an unused ADM-3A terminal from my Dad's company and found a departing grad student to sell me his 300 baud acoustically-coupled modem for the princely sum of $85.00.

    For those that have never seen one, they were designed so once any "standard" phone handset (no Trimlines!) was plugged into the two rubber cups, it would happily warble letters onto your screen at the blistering speed of 30 characters/sec. Do the math: to re-fill the screen took just over a minute!

    Anyway, this thing was the most popular item in the dorm. In semesters I didn't need it, I rented the terminal/modem setup out for $50/semester, so I actually made a little beer and pizza money.

    I ran across the modem and terminal the other day, and I just can't part with either one. I figure if Skynet takes over, the resistance will be using 300 baud modems, since nothing modern will know how to talk to it anymore. ;-) Of course, I'll have to find something with an RS-232 interface to plug it into...

    --
    "The future's good and the present is nothing to sneeze at." - Roblimo's last ./ post
  321. Re:Just using VIM by Anonymous Coward · · Score: 0

    Plank's Constant

    That's "Planck", moron.

  322. Re:Just using VIM by WgT2 · · Score: 1

    How about that; it's still shorter than Emacs.

  323. Re:Just using VIM by dfj225 · · Score: 1

    You may be interested in the MacVim port.

    http://code.google.com/p/macvim/

    I found these recently and have been enjoying it ever since.

    For me, the biggest differences are:
    1) Better font support
    2) Uses standard OS X keyboard shortcuts (cmd+v, cmd+w, etc)
    3) Better performance for drawing the window (noticeable when scrolling).

    --
    SIGFAULT
  324. Re:Just using VIM by Sancho · · Score: 1

    Scrolling speed was the main thing that made the gVim port simply unusable to me. Someone else pointed me to MacVim, and I checked it out. It's great!

    Thanks for the second recommendation, though.

  325. Re:Just using VIM by MrResistor · · Score: 1

    And for an added bonus, I recall that wine works under cygwin (though I haven't tried it personally).

    --
    Under capitalism man exploits man. Under communism it's the other way around.
  326. Re:Just using VIM by Anonymous Coward · · Score: 0

    might not be the most stable addon, but vimperator for firefox sure is fun - if you are into that kind of thing 8)