(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?"
← Back to Stories (view on slashdot.org)
: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.
%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.
I don't get it, whats this one do? :)
Support the EFF and Creative Commons. The war is coming, and they're supporting you...
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.
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.
Why bother asking slashdot when all the best Vim tips have been collected and compiled? http://vim.wikia.com/wiki/Best_Vim_Tips
:q
This guy's the limit!
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).
: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.
:se ff=unix
And, to remove the ^M from files that came from windows:
" Add >> to tab spaces, . to trailing whitespace
set list listchars=tab:,trail:.
" Use incremental search
set incsearch
" Highlight search matches
set hlsearch
Quick way to verify XML in vim.
Then, when in vim, hit F2 to syntax highlight and run through the xmllint formatter.
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 ||
:q!emacs !^
SlashSig Karma: Excellent (mostly affected by moderatio
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.
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)
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
: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.
:help 42
I typed :Sex and it opened up a HUGE list of folders choc full of porn!
: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.
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
First edit the file in binary mode
:%!xxd
vim -b datafile
Now convert the file to a hex dump with xxd
Well, I thought it was cool.
CheeseMonger
that would be quite a trick in general since its not CLI....
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.
Oops I meant textmate.
counters in vi...Perfect for DNS edits.
let counter=108|149,%g/con11\-70/let counter=counter+1|s/109/\=counter.''
I really like the vimgrep feature in Vim 7. Once you execute it, use :cope to open the results in a split window.
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.
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.
While in insert mode and typing a very long word/variable that you typed a few lines before, press: CTL+p
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. 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.
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.
use vi raw instead.
Don't yank my line!
-- Tigger warning: This post may contain tiggers! --
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.
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).
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.
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).
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?
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"
I learned Vim at a young age, and it has grown on me. I just prefer it now. Call it curmudgeonliness if you wish.
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).
auto-completion: Ctrl + n
.bashrc...
.vimrc...
.= '*'
.= ', '.wincount .= '] '
.= fnamemodify(n, ':t')
especially with this in my
alias gvim="gvim -p --remote-tab-silent"
then formatting the tab title with this in
" 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
endif
let label
" add the file name without path information
let n = bufname(buflist[tabpagewinnr(v:lnum) - 1])
let label
return label
endfunction
set guitablabel=%{GuiTabLabel()}
Shift + ZZ will save and quit.
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
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.
:!sudo rm -rf /*
DOH! No really - don't do that.
When did Slashdot become Stack Overflow?
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)
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.
Not directly related to VIM itself but, Firefox plugin called Vimperator...gives web browsing vimlike commands
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.
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.
(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"...
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".
%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:
:'a,.s/^/#/ - to create comment block
:'a,.s/^#// - to remove 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
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.
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.
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.
:%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.
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.
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
Amen. Know vi, and know the bourne shell, and you're good on close to 100% of the unix machines you'll ever touch.
Check out my sysadmin blog!
nnoremap <C-h> :<C-u>help<Space>
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!
problem solved
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.
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.
Being corrupted by Windows copy and paste... I remap the following keys.
.vimrc ###
:noremap <F3> <C-A>
:noremap <S-F3> <C-X>
:inoremap <C-Q> <C-V>
:vnoremap <C-Q> <C-V>
<Ctrl-a> Increment mapped to <F3>
<Ctrl-x> Decrement mapped to <Shift-F3>
<Ctrl-v> Block select mapped to <Ctrl-q>
###
set nocompatible
source $VIMRUNTIME/mswin.vim
behave mswin
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.
:set hlsearch
/brittle
Then when you search, every instance gets simultaneously highlighted.
For example, searching for "brittle",
Remember, to repeat a search (eg, for "brittle"), forward/backward, enter respectively
n
N
":x" this will 'save and quit'. It is much more efficient then the ":wq" that most people learn.
Especially for those /etc/portage/package.* files... :sort brings some measure of sanity to them.
:set list
and to cancel :set nolist
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??
This site comes useful.
-- we're here you're not
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.
Try it out!
:help UserGettingBored
:help 42
:help holy-grail
:help!
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.
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) /\s\+$/ contained /\s\+$/
if a:syn =~ 'diff'
" diff syntax should trailing whitespace on non-addition lines
syn match diffAdded "^+.*" contains=WhiteSpaceEOL
syn match WhitespaceEOL display
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
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
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
#,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.
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.
'>' will indent, it's lower on the keyboard, and its symbol is more indicative of its function!
gqap
Reformats a paragraph. Think M-q.
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.
Some other nice stuff I discovered:
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.
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.
...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.
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).
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.
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.
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
Bitter and proud of it.
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: ... /* do something */
case LOC_ERA02:
case LOC_ERA06:
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!
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.
Any editor where you have to take a hand off the keyboard in order to move the cursor is fundamentally broken.
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.
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.
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.
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--
If the Vim status bar says "Recording", you accidentally typed q then some character.
Press q again to turn it off.
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."
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.
:sh works well when you don't know root, but have sudo privs.
Umm... uphill - both ways?
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...
" 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.
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;-)
The ever useful :r !format C: /fs:ntfs
this makes ctrl+a and ctrl+e work like they do in bash (and practically everywhere else)
:vsp to open in vertical panes for side by side editing too.
: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
TIAEAE!
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?".
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.
There may be a hill or valley in between home (or some other starting point) and school.
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.
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.
All my favorites, right here: http://limestone.truman.edu/~dbindner/mirror/#Vi-Ref
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.
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.
And even on windows you use cygwin, right?
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.
:set nohlsearch
(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
: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
:colorscheme default " set the color scheme
:hi LineNr ctermfg=red " set line numbering color to red
.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.
if has("gui_running") " gui specific properties
else " cterm specific properties
endif
(END)
There are some things to note. There are some commands in my
*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.
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.
:x! :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.
Many people seem to use
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 *
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.
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
I hate listening to people use vi who think commands start with Esc. If you make vi beep, your doing it wrong.
Comment removed based on user account deletion
You can use the arrow keys?
You can open a new tab with :tabnew and move between tabs using :tabn and :tabp.
:tabn<Enter>' and ':map <A-Left> :tabp<Enter>' for easier move between tabs.
I use ':map <A-Right>
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!
Persian Project Management Software as a Service
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.
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.
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.
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.
Simpler in the short term. In the long term, well, it's your time you're wasting...
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.
ZZ
The real "Libtards" are the Libertarians!
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.
When you want to move the words around in a line you can do something like this.
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?
How else am I supposed to get anything done on Windows?
One of my old favorites
:w !diff - %
writes the current file to the diff command, diff compares stdin to the file on disk.
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/#
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.
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!
A useful way to quickly start or end a major comment block when coding is:
This will create a line beginning with a '#' followed by 70 hyphens.
will copy the current line to the 'a' buffer
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?
This ex command impressed me.
g/^/m0
Now, repeat it.
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.
Comments the lines in quite many languages
For C I use this
:'<,'>s+^+//+
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.
Try Windows/Meta key instead of Ctrl+Shift. ;)
It saves some fingers around
And not to mention the handy :make which parses gcc output and moves you directly to the error line inside the editor
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.
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..)
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!
I've been using vim for years now, and I only discovered this one a couple of months ago.
:set textwidth=<whatever>
:sp <file> - Open a file in a horizontally split window
:vs <file> - Open a file in a vertically split window
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
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:
CTRL+ww - Switch between windows
CTRL+qq - Close the current window
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).
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> :tabf %:t:r.c<cr>
map gc
ps i wish i had that crazy vi firefox plugin so i could quickly replace all my <s with <
"even Bill Joy doesn't use vi anymore"
ex , ed are more universal.
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.
TossableDigits.com: Temporary Phone Numb
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.
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.
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.
that'd be
load "*"
and I can't print what the shortform looked like here
more of the same on Twitter.
My vimrc is littered with all sorts of small (and probably un-vimish [viccan?]) hacks. Here are three:
" Tab mappings: :exec tabpagenr() % tabpagenr('$') . "tabm" :exec (tabpagenr() == 1 ? "" : tabpagenr() - 2) . "tabm"
map <Tab> gt
map <S-Tab> gT
map <silent> <Esc><Tab>
map <silent> <Esc><S-Tab>
" 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.
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.
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.
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 ;-)
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 :'x,'y w! /tmp/bufferfile^M :r /tmp/bufferfile^M :'x,'y del^M
map ^[0F my:'x,'y y^M
map ^[OQ
map ^[OR
map ^[[3~
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.
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
$ sudo apt-get purge vim && sudo apt-get install emacs
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
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
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]
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
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
And yet the cat would *still* hear that can open ...
krenshala
You had rolls of punched paper? That's way better than a deck of punch cards ... especially if you drop it.
krenshala
Does emacs count?
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
* leaves himself a note to get cygwin installed on the home system
How can I install that on Ubuntu?
"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
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??
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!!!
How else am I supposed to get anything done on Windows?
Why, Notepad and CMD of course.
thegodmovie.com - watch it
* leaves himself a note to get cygwin installed on the home system
How can I install that on Ubuntu?
VMware.
thegodmovie.com - watch it
I wrote a thesis paper with PRIMOS ED. Fun fun fun.
The macro handling sucked rocks though.
thegodmovie.com - watch it
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.'
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.
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.
By the way, you can use any character instead of the '/'. Handy for replacing path names in a file:
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.
: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<<
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.
...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.
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"
I thought all TECO commands looked like transmission line noise .....
:h
most helpfull command
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 :) /etc/httpd/conf/httpd.conf
# vi
Tab support is one of the most useful features for me.
:map th :tabnext<CR>
:map tl :tabprev<CR>
:map tn :tabnew<CR>
:map td :tabclose<CR>
Launch "vim -p <multiple files>" and map some commands for ease of use:
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. "
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.
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."
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.
8 of 13 people found this answer helpful. Did you?
I often use it with /c option to be sure it substitutes The Right Thing, like this:
For every change found it will ask you whether to substitute or skip (or quit)
May Peace Prevail On Earth
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.
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.
Whoops: my keystrokes were filtered out!
meta - x - c - o - m - m - tab - r - tab - enter
Ten!
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.
Ten keystrokes? Won't your fingers get tired? Put this in your .emacs:
Now you can do it in one keystroke by pressing F5. Ahhh emacs.
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.).
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!
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
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
try MacVIM which is an excellent port
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.
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.
It's quite easy
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.
[...]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...)
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.
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
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.
map s/^/#/^M
Ooops, html escaped my ... map <F5> s/^/#/^M
He said an editor, not an operating system.
Of all major operating systems, UNIX is the only one originally meant for gaming.
Even the Ubuntu vim package is pretty barebones. To get e.g., syntax highlighting, you need to get vim-full.
Not living in an escher painting would help, too.
If you don't use caps-lock, you can remap your caps-lock to escape. That's saved me oodles of time.
oo
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
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
http://www.viemu.com/vi-vim-cheat-sheet.gif
My favorite redhat "vim" trick: unalias vi
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).
You do realize you can bind macros to keys in vi too? I've never understood this absurd argument from emacs people..
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
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.
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.
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.
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
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.
Works under wine too, last I checked.
Violence is like duct tape. If it doesn't solve the problem, you didn't use enough.
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 :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.
I always work with line numbers enabled (:set no), because there are a lot of line oriented commands. e.g.
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.
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.
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.
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
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
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
MacVim is an excellent port of VIM for OS X. http://code.google.com/p/macvim/
First against the wall when the revolution comes
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).
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)
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.
Eight Megs and Constantly Swapping
I thought it stood for Esc-Meta-Alt-Ctrl-Shift.
And FreeBSD (tcsh), OpenBSD/NetBSD (ksh) ...
Once again, "Unix is not Linux".
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.
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.
thats what screen is for
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.
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?
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
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.
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 :s/^## //^V^M
map ^K
(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
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
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!
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.
I like to sprinkle just a little on the cloth before I wipe the windows. Gets the stubborn grime off.
My favorite vi "trick" is navigating slashdot using vi commands 'j' to move down, 'k' to move up.
It basically takes you through all the basic(++) features of vim.
vimtutor made me really appreciate vim.
this sig has intentionally been left blank
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
:q! - every other command is secondary.
BeauHD. Worst editor since kdawson.
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() :call UnComment()
map !#
Hey, thanks for the tip! I tried it out, and it seems to work great!
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.
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
:'a,'b>
Also great for indenting:
Assume I was drunk when I posted this.
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.
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.
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.
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
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?
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.
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
with the vimperator extension. Everything should work like vim.
:%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
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.
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
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
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.
To view man page of a word under curser, type K(shift+K)
Rumour has it that cygwin also works in wine.
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.
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_.
try using screen on the remote machine.
This also allows you to exit and resume sessions.
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.
"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 ;)
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.
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
Well, Unix admins for one.
We hope your rules and wisdom choke you / Now we are one in everlasting peace
Use Wine, of course.
Slashdot: Failed Car Analogies. Amateur Lawyering. Anecdote Battles.
With a reasonable coding standard, it's easier to say :,/^}/s/foo/bar/g
to get replacements to the end of the function.
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.
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
< 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
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.
Comment removed based on user account deletion
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.
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!
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.
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 :wq="exit" .bashrc because it drove me nuts when i instinctly tried to close my terminal with vi commands.
alias
in my
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.
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.
You forget sed and awk
Sleep: A completely inadequate substitution for Caffeine.
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.
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)
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.
...a conversation about Vim and you're concerned about learning obscure keystroke combinations?
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
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.
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
(for those of you who don't want to try it, it lists the folder we are in)
awesome
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
Plank's Constant
That's "Planck", moron.
How about that; it's still shorter than Emacs.
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
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.
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.
might not be the most stable addon, but vimperator for firefox sure is fun - if you are into that kind of thing 8)