


(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?"
You have a tendency to feel you are superior to most computers.
best one ever (Score:5, Funny)
:r! emacs /I partly kid I like Vi
Ha Ha Ha (Score:2)
Re: (Score:2, Funny)
/bin/bash: emacs: command not found
Re:best one ever (Score:5, Funny)
Password:
# test -f
# cat <<EOF >/bin/emacs
#!/bin/bash
echo emacs: command not found
EOF
# exit
$ logout
Re: (Score:3, Informative)
Re: (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.
Re:Just using VIM (Score:5, Funny)
Re:Just using VIM (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).
Re:Just using VIM (Score:5, Informative)
Re:Just using VIM (Score:5, Interesting)
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.
Re:Just using VIM (Score:4, Informative)
It's quite easy
Re:Just using VIM (Score:5, Insightful)
Re:Just using VIM (Score:5, 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.
Re:Just using VIM (Score:5, Funny)
Re: (Score:3, Funny)
* leaves himself a note to get cygwin installed on the home system
How can I install that on Ubuntu?
Re:Just using VIM (Score:5, Funny)
* leaves himself a note to get cygwin installed on the home system
How can I install that on Ubuntu?
VMware.
Re:Just using VIM (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).
Re:Just using VIM (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.
Re: (Score:2)
Re:Just using VIM (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.
Re: (Score:3, 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
Re: (Score:2)
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.
Re:Just using VIM (Score:4, 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 :-)
Re: (Score:3, 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
Re: (Score:2, Funny)
Re: (Score:2)
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 br
Re:Just using VIM (Score:5, 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.
Re:Just using VIM (Score:4, Insightful)
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.
Re:Just using VIM (Score:4, Funny)
Replacement (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.
Re:Replacement (Score:5, 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
Re:Replacement (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. :'a,'bs/^#//
Reverse it with:
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)
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.
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.
Re: (Score:2)
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)
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
Re:Replacement (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:
Re: (Score:3, Informative)
# change foo to bar for all occurrences in the rest of :s/foo/bar/g
# the file from where the cursor is
No, that only works on the current line. perhaps :.,$s/foo/bar/g
Re: (Score:2)
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
Re: (Score:3, 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.
Filter Lines (Score:5, 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.
Re: (Score:2)
Re: (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.
:1,$!fmt
In particular, a whole page gets pasted as one line.
So, I enter
or like the author (shift-v or ctrl-v) then
!fmt
Couple off-hand (Score:5, 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.
Re: (Score:2)
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]
Vim tips (Score:5, Informative)
Re: (Score:3, Informative)
ClownColors!!!! (Score:3, Interesting)
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 purp
Re:Vim tips (Score:5, Informative)
very useful (especially for noobs) (Score:5, Funny)
Re:very useful (especially for noobs) (Score:4, Funny)
nano
Re: (Score:2)
= and * (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).
retab (Score:5, Informative)
And, to remove the ^M from files that came from windows:
Re: (Score:2)
:se ff=unix
nice, I just posted :set fileformat=unix|dos, didn't know there was a short form for that :o)
Whitespace + Searching (Score:2)
" 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)
+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.
my most frequent vi trick (Score:2)
:q!emacs !^
Need a way to un-highlight (Score:5, 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.
will not search past the top or bottom.
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.
will turn on/off hidden characters, and show end of lines. Great for finding tabs or spaces at the end of a line.
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)
Re: (Score:3, Informative)
If you're pasting something, and don't want Vim's autoindent to screw up the formatting use: :set paste
Re: (Score:2)
Much easier is to use :a! (or :i!), paste your text and then end the paste with a line containing just .
Re: (Score:2)
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=
Re: (Score:2)
You can accomplish the same thing more simply with :set hlsearch!<CR>
map <F4>
% - jump between braces, ifdefs, etc (Score:2, Informative)
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)
split (Score:2)
:sp to split the screen
to toggle between
made my life a lot easier
Re: (Score:2)
er ctrl-w-w
(forgot about tags)
WTF?? (Score:5, Funny)
I typed :Sex and it opened up a HUGE list of folders choc full of porn!
Re:WTF?? (Score:5, Funny)
delete a block of lines larger than the screen (Score:4, Informative)
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)
Stupid vi tricks? (Score:3, 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.
Re:Stupid vi tricks? (Score:5, 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?
Re:Stupid vi tricks? (Score:5, Funny)
Stupid vi tricks? (Score:2)
by argent (18001)
I believe you and your fancy VIM are on this man's lawn.
Use '=' and 'gq' together... (Score:2)
Re: (Score:2)
: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
Buy the book (Score:2)
Re: (Score:2)
Anyone else misread the URL as "...Steve Ovaltine..."?
I need more sleep :-(
1,.d (Score:2)
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
Some of my favorites (Score:2)
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.
Thos
Most powerful of them all... (Score:2)
:!sudo rm -rf /*
DOH! No really - don't do that.
gg=G (Score:2)
Stack Overflow (Score:5, Insightful)
When did Slashdot become Stack Overflow?
Perhaps two of the weirdest: Ctrl-A and Ctrl-X (Score:3, Informative)
(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"...
dos2unix equivalent (Score:2)
%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.
Re: (Score:2)
Re: (Score:2)
Especially useful for PERL (Score:2, Informative)
move cursor to the start of the comment block
ma - creates a mark called "a"
scroll down to the end of the 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.
beep beep (Score:2)
Tab Size (Score:2)
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
I think I see a pattern in these stories (Score:3, Funny)
Reference card (Score:3, Informative)
All my favorites, right here: http://limestone.truman.edu/~dbindner/mirror/#Vi-Ref [truman.edu]
Getting copy/paste to work (Score:3, 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'.
$ ssh -v -X remotemachine
debug1: Requesting X11 forwarding with authentication spoofing.
debug1: Remote: No xauth program; cannot forward with spoofing.
Re::Sex (Score:5, Funny)
You're asking on the wrong site. No one on Slashdot has ever tried it.
Re::Sex (Score:5, Funny)
Re::Sex (Score:5, Informative)
:help sex
e.g. it give you a file exploring pane above the buffer you are currently using.
Re::Sex (Score:5, Funny)
If only my parents had told me earlier.
Re: (Score:3, Funny)
support :sex education!
Re: (Score:2)
dG in command mode also deletes from current position to the end of the file (in vim, at least)
Re: (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 $@;
Re: (Score:3, Informative)
If you use "your" to mean "you're", you're doing it (using the English language) incorrectly.
The keyboard is the same. (Score:3, 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