Follow Slashdot stories on Twitter


Forgot your password?
Software Operating Systems Unix

(Useful) Stupid Vim Tricks? 702

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?"
This discussion has been archived. No new comments can be posted.

(Useful) Stupid Vim Tricks?

Comments Filter:
  • by shawn(at)fsu ( 447153 ) on Thursday November 06, 2008 @04:38PM (#25666113) Homepage

    :r! emacs /I partly kid I like Vi

    • 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
    • Re: (Score:2, Funny)

      by Anonymous Coward

      /bin/bash: emacs: command not found

    • Re: (Score:3, Informative)

      by smcameron ( 1245020 )
      For all your vi/Emacs flamewar needs, try [] Full disclosure, I'm the author of that game.
  • Replacement (Score:2, Interesting)

    by lunchlady55 ( 471982 )


    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.

    • Re:Replacement (Score:5, Informative)

      by Reality Master 101 ( 179095 ) <RealityMaster101 AT gmail DOT com> on Thursday November 06, 2008 @04:51PM (#25666299) Homepage Journal

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


      • Re:Replacement (Score:5, Informative)

        by pluther ( 647209 ) <pluther.usa@net> on Thursday November 06, 2008 @05:46PM (#25667095) Homepage

        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.

      • Re:Replacement (Score:4, Interesting)

        by MrKaos ( 858439 ) on Thursday November 06, 2008 @05:55PM (#25667195) Journal

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


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


        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.


        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.

    • by pluther ( 647209 )

      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.

    • Re: (Score:2, Informative)

      by mrons ( 2769 )

      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

  • Filter Lines (Score:5, Interesting)

    by saberworks ( 267163 ) on Thursday November 06, 2008 @04:48PM (#25666243)

    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.

    • 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.
    • Re: (Score:2, Interesting)

      by Jameson Burt ( 33679 )

      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
      or like the author (shift-v or ctrl-v) then


  • Couple off-hand (Score:5, Interesting)

    by Reality Master 101 ( 179095 ) <RealityMaster101 AT gmail DOT com> on Thursday November 06, 2008 @04:48PM (#25666245) Homepage Journal

    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.

    • by Sancho ( 17056 ) *

      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:


  • Vim tips (Score:5, Informative)

    by icsEater ( 1093717 ) on Thursday November 06, 2008 @04:50PM (#25666271)
    Why bother asking slashdot when all the best Vim tips have been collected and compiled? []
  • by gEvil (beta) ( 945888 ) on Thursday November 06, 2008 @04:51PM (#25666303)
  • = and * (Score:3, Informative)

    by Lalakis ( 308990 ) on Thursday November 06, 2008 @04:53PM (#25666323) Homepage

    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).

  • retab (Score:5, Informative)

    by DigitalCrackPipe ( 626884 ) on Thursday November 06, 2008 @04:54PM (#25666337)
    :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
    • by maharg ( 182366 )

      :se ff=unix

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

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

    set list listchars=tab:,trail:.

    " Use incremental search

    set incsearch

    " Highlight search matches

    set hlsearch

    • Re: (Score:3, Interesting)

      by kangasloth ( 114799 )

      +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;
      set list listchars=tab:._,trail:-

      ... not that I can actually show what those look like since it appears that slashcode doesn't ap

  • :q!emacs !^

  • by bugnuts ( 94678 ) on Thursday November 06, 2008 @04:58PM (#25666385) Journal

    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.

    • Re: (Score:3, Informative)

      by Mad Merlin ( 837387 )

      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.


    • Re: (Score:3, Informative)

      by Hatta ( 162192 )

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

      • 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 .

    • 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=

  • 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)

  • by gsn ( 989808 )

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

  • WTF?? (Score:5, Funny)

    by monkeySauce ( 562927 ) on Thursday November 06, 2008 @05:03PM (#25666473) Journal

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

  • by prgrmr ( 568806 ) on Thursday November 06, 2008 @05:19PM (#25666723) Journal
    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)
  • by argent ( 18001 ) <peter&slashdot,2006,taronga,com> on Thursday November 06, 2008 @05:23PM (#25666771) Homepage Journal

    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.

  • 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.
    • by Qzukk ( 229616 )

      :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

  • There's lots of good stuff in here [].
  • by TheCarp ( 96830 ) *

    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

  • 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.


  • :!sudo rm -rf /*

    DOH! No really - don't do that.

    • 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
  • Stack Overflow (Score:5, Insightful)

    by JPLemme ( 106723 ) on Thursday November 06, 2008 @05:53PM (#25667185)

    When did Slashdot become Stack Overflow?

  • by sdt ( 7606 ) on Thursday November 06, 2008 @06:02PM (#25667295) Homepage

    (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"...

  • %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.

  • 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.
  • to make vi[m] beep, just press Esc Esc ;o) Also :e! restores to the previously saved version
  • 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

  • by Xeth ( 614132 ) on Thursday November 06, 2008 @06:51PM (#25668041) Journal
    ...and I've already gotten through half of my 20-page "(Useful) Stupid Emacs Tricks" post.
  • Reference card (Score:3, Informative)

    by YoungHack ( 36385 ) on Thursday November 06, 2008 @08:26PM (#25669359)

    All my favorites, right here: []

  • by cerberusss ( 660701 ) on Friday November 07, 2008 @05:11AM (#25673051) Homepage Journal

    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.

To avoid criticism, do nothing, say nothing, be nothing. -- Elbert Hubbard