Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
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:
  • 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? http://vim.wikia.com/wiki/Best_Vim_Tips [wikia.com]
  • Re:Replacement (Score:5, Informative)

    by Reality Master 101 ( 179095 ) <<moc.liamg> <ta> <101retsaMytilaeR>> 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:

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

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

  • by tippe ( 1136385 ) on Thursday November 06, 2008 @05:01PM (#25666427)
    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)

  • Re:Replacement (Score:5, Informative)

    by iggya ( 1401047 ) on Thursday November 06, 2008 @05:03PM (#25666479)

    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

  • by Mad Merlin ( 837387 ) on Thursday November 06, 2008 @05:05PM (#25666499) Homepage

    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

  • Re:Replacement (Score:1, Informative)

    by Anonymous Coward on Thursday November 06, 2008 @05:05PM (#25666511)

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

    %10,20s/From/To/

    %.,$s/F/T/

  • Re:Just using VIM (Score:1, Informative)

    by Anonymous Coward on Thursday November 06, 2008 @05:13PM (#25666633)

    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.

  • by Hatta ( 162192 ) on Thursday November 06, 2008 @05:16PM (#25666673) Journal

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

  • 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)
  • Re::Sex (Score:5, Informative)

    by Noksagt ( 69097 ) on Thursday November 06, 2008 @05:44PM (#25667061) Homepage

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

  • Re:Replacement (Score:5, Informative)

    by pluther ( 647209 ) <pluther@uCHEETAHsa.net minus cat> 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.

  • Vimperator (Score:1, Informative)

    by Anonymous Coward on Thursday November 06, 2008 @05:59PM (#25667245)

    Not directly related to VIM itself but, Firefox plugin called Vimperator...gives web browsing vimlike commands

  • Re:Replacement (Score:2, Informative)

    by mrons ( 2769 ) on Thursday November 06, 2008 @05:59PM (#25667249)

    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

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

    (in vim only), Ctrl-A and Ctrl-X [vim.org] 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"...

  • by ickyb0d ( 975453 ) on Thursday November 06, 2008 @06:03PM (#25667317)
    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.
  • Re:Just using VIM (Score:5, Informative)

    by el momia ( 1400135 ) on Thursday November 06, 2008 @06:06PM (#25667363)
    :%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.
  • Re:Replacement (Score:3, Informative)

    by Abcd1234 ( 188840 ) on Thursday November 06, 2008 @06:06PM (#25667365) Homepage

    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.

  • Re:Vim tips (Score:5, Informative)

    by Amazing Quantum Man ( 458715 ) on Thursday November 06, 2008 @06:34PM (#25667791) Homepage

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

  • Re:best one ever (Score:3, Informative)

    by smcameron ( 1245020 ) on Thursday November 06, 2008 @06:36PM (#25667821)
    For all your vi/Emacs flamewar needs, try http://wordwarvi.sourceforge.net/ [sourceforge.net] Full disclosure, I'm the author of that game.
  • Re:Filter Lines (Score:2, Informative)

    by James McGuigan ( 852772 ) on Thursday November 06, 2008 @07:01PM (#25668195) Homepage

    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.

  • by James McGuigan ( 852772 ) on Thursday November 06, 2008 @07:32PM (#25668667) Homepage

    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.

  • shelling out (Score:2, Informative)

    by onedeadeddie ( 1398557 ) on Thursday November 06, 2008 @07:49PM (#25668915)

    :sh works well when you don't know root, but have sudo privs.

  • Re:Vim tips (Score:3, Informative)

    by TimJL ( 1401875 ) on Thursday November 06, 2008 @07:54PM (#25668969)
    I'd like to pimp my own cheat sheet here: http://tjl2.com/sysadmin/vim-cheat-sheet.html [tjl2.com] I love Vim!
  • by James McGuigan ( 852772 ) on Thursday November 06, 2008 @08:03PM (#25669079) Homepage

    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
                }

  • Reference card (Score:3, Informative)

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

    All my favorites, right here: http://limestone.truman.edu/~dbindner/mirror/#Vi-Ref [truman.edu]

  • Re:Replacement (Score:3, Informative)

    by isorox ( 205688 ) on Thursday November 06, 2008 @08:58PM (#25669761) Homepage Journal

    # 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

  • by naveenkumar.s ( 825789 ) on Thursday November 06, 2008 @09:20PM (#25669985)

    When you want to move the words around in a line you can do something like this.

    hello world
    ~
    ~
    :%s/\(.*\) \(.*\)/\2 \1/

    world hello

  • by mattack2 ( 1165421 ) on Thursday November 06, 2008 @10:22PM (#25670573)

    If you use "your" to mean "you're", you're doing it (using the English language) incorrectly.

  • Re:Just using VIM (Score:2, Informative)

    by andrikos ( 1114853 ) on Thursday November 06, 2008 @10:54PM (#25670845)
    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+^+//+

  • Re:Replacement (Score:2, Informative)

    by playerone ( 903173 ) on Friday November 07, 2008 @01:03AM (#25671963)

    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.

  • Re:Ha Ha Ha (Score:1, Informative)

    by Anonymous Coward on Friday November 07, 2008 @04:59AM (#25672989)

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

  • Clever deleting (Score:2, Informative)

    by Boawk ( 525582 ) on Friday November 07, 2008 @05:10AM (#25673043)
    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.
  • by cerberusss ( 660701 ) on Friday November 07, 2008 @05:11AM (#25673051) 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.
  • Re:Just using VIM (Score:2, Informative)

    by Anonymous Coward on Friday November 07, 2008 @06:45AM (#25673505)

    try MacVIM which is an excellent port

  • Re:Just using VIM (Score:4, Informative)

    by WoLpH ( 699064 ) on Friday November 07, 2008 @07:07AM (#25673655)

    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>
  • Re:Couple off-hand (Score:2, Informative)

    by include($dysmas) ( 729935 ) on Friday November 07, 2008 @07:39AM (#25673861)

    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

  • vim cheat sheet (Score:2, Informative)

    by zbharucha ( 1331473 ) on Friday November 07, 2008 @10:03AM (#25674829)
  • by Anonymous Coward on Friday November 07, 2008 @11:00AM (#25675465)

    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

  • How about recording? (Score:2, Informative)

    by jivemonkey ( 776115 ) on Friday November 07, 2008 @12:19PM (#25676539) Homepage

    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.

"Gravitation cannot be held responsible for people falling in love." -- Albert Einstein

Working...