PDA

View Full Version : VIM: The (un)official thread



MK27
04-24-2009, 07:38 AM
I noticed in this other thread (http://cboard.cprogramming.com/linux-programming/114837-c-cplusplus-ide.html) a lot of people of people mentioned vim, and usage problems with vim. I'm not going to do a complete review, but I will say I really believe it is the greatest piece of software of all time.

It's also the most poorly documented, so what I did want to do was start a new thread here in the "Product Review" board where people could ask stuff like "How can I see the value of a defined variable?" (the answer is here (http://cboard.cprogramming.com/c-programming/112469-quick-vim-use-question.html); "escape mode)

I'm sure there are some other programming software products around that could have an even more popular thread, but I'm not going to start any of them ;)

Here's the wikipedia entry for the curious:
http://en.wikipedia.org/wiki/Vim_(text_editor)
And the actual homepage is welcome home : vim online (http://www.vim.org).

I recommend against the use of the GUI. There is nothing wrong with it, but it is unnecessary and the functionality cannot be improved upon with tradition pull down menus and tabs (learn to use a keyboard, you are a computer programmer!). Plus, there is nothing like being able to use your absolute favourite tool even when you don't have a graphical desktop, and not have to remember how to get things done without a mouse to click and point things at. If you are new to the whole concept, two commands which work in escape mode that you might want to get to know are
:split
This splits the window in half horizontally, and if you include a filename loads it. You can also split the window unevenly (try ":help split"). To move back and forth, use ctrl-ww.
:e #
This will reload the last file, handy for flipping back and forth.

Vim is standard on almost all unix derived operating systems including linux, and available for all of them (including MAC OS). There is even a windows and DOS version. However, the package included with your linux distro probably leaves a lot to be desired. It is easy to compile from source, however (choose the "huge" option to get the most functionality). A quick test of your installation is to try "vim --remote": you should be able to type:
vim --remote mycode.c
to send a file to the currently running (or first) instance of vim in any terminal anywhere on your desktop. This is very handy since you can add this command to your filebrowser, and just have one fullscreen, non-GUI vim in a terminal somewhere. If it doesn't work, your install doesn't have all the vim features and you should uninstall it and build from the source.

Here's a simple ~/.vimrc that demonstrates some basic and essential configuration (the double quote " starts a comment):


" .vimrc
" syntax highlighting, line numbering, etc on by default
:syntax enable
set number
set nowrap
set bs=indent,eol,start " allow backspacing over everything in insert mode

" you probably want all the syntax colors to work in your terminal
" here's how to set them for contrast
" numbers and color names are interchangable
hi Statement ctermfg=7
hi LineNr ctermbg=0 ctermfg=4
hi Comment ctermbg=7 ctermfg=darkblue
hi PreProc cterm=bold
hi Type ctermfg=6
hi Identifier ctermfg=2
hi Number cterm=underline ctermfg=6
hi Conditional cterm=bold ctermfg=3
hi Repeat cterm=bold ctermfg=1
hi Constant ctermfg=3
hi StatusLine cterm=bold ctermfg=green ctermbg=darkmagenta
hi StatusLineNC ctermfg=darkgray ctermbg=white

" key bindings (these just print things in appropriate places to save typing)
" cmap works in escape (aka command) mode, eg, for when loading a file
:cmap <F2> /root/code/
" imap works in insert (aka editing) mode
:imap <F2> printf("\n"); fflush(stdout);
:imap <F3> 12345678901234567890
" that last one is for counting string lengths...


If you have any questions about using vim, or some reason why it is not the greatest piece of software of all time, post those here :)

zacs7
04-24-2009, 09:45 AM
> I recommend against the use of the GUI.
Going against what the authors recommend? Why? They suggest gvim because of the 256 native colour support, along with various other things (encoding, the terminal doesn't get in the way etc).

I'd suggest using gvim and turning off the menu / toolbar. That way it's exactly the same if you SSH into another box and cannot pipe X (who would anyway?). And it allows you to enjoy 256 colours in the mean time.

Otherwise, +1 for spreading vi/m. And down with Emacs!

MK27
04-24-2009, 09:55 AM
I wouldn't use it just for the colors, 16 seems enough for text (there's not that many syntax categories anyway), and you can make those 16 colors any combination of millions via the terminal (at least, most modern X terminals -- which also allow tabbing).

Also, I really like a transparent background, which you can't get with the GUI. You know, no window borders, all see-thru: that classic linux power user look. Regarding "the terminal getting in the way", you may have to short circuit the esc key shortcut if there is one, but that's a fairly simple point and click task witht the terminal interface.

I guess I should have added: Just don't use xterm!

Emacs is definitely a creepy beast. But I never got into it.

birnam
04-27-2009, 01:49 AM
On large documents I've noticed a significant performance hit with gvim vs terminal vim when interacting with the mouse on blocks of text, and with scrolling. The extra colors can look really sharp, true, but as far as I can see the only true benefit to gvim is integration with system open/save dialogs -- and NERDTree is a great replacement for that even.

Terminal Vim has tabs, splitscreen, and everything else. You can even turn on mouse control and be able to select dynamically, point/click to locate the cursor, resize the split windows, click an 'X' to close a tab, etc.

It seems like every day I learn something new or a new way to do something in Vim. Programming auto-complete dropdowns, using ctags and taglist, etc.

I don't know about best, but Vim is certainly in the upper echelon of best applications of all time.

MK27
04-27-2009, 09:37 AM
It seems like every day I learn something new or a new way to do something in Vim. Programming auto-complete dropdowns, using ctags and taglist, etc.

I don't know about best, but Vim is certainly in the upper echelon of best applications of all time.

I was in denial for a long time, then I realized it only has a few pieces of competition in my life: the web browser (any web browser, it's quite a feat), the kernel (under appreciated), gcc (also under appreciated), and the perl interpreter. I wouldn't include libraries and APIs, etc, and there are lots of super cool graphics things out there but I don't use them that much.

Anyway, all the things birnam mentions are pretty cool in so far as I am familiar with them. The i-mode ctrl-x autocompletion/autoreplace stuff is almost psychotic (if you have an IQ of like 160, it must be amazingly handy), which is why I thought I'd mention something essential to newbies that I didn't think of in the OP:
:u vim undo!
:redo vim redo!
because it ain't hard to do crazy things by accident (I think they have run out of ctrl-alt-meta-shift combinations).

glo
04-28-2009, 08:24 AM
Being a Windows user, I was also raised with a silver mouse in my hand. Applications offering sleek GUI, animated tool-tips and decorated buttons are all around the place. These applications take eye-candy further and further, but forget one important thing: Efficiency.
As Mad_Guy fanatically put it time and again, it all boils down to efficiency. VIM allows you just that, so I'll leave you to youtube VIM and see it in action rather than describe it in words.
VIM is complete, yet minimalistic in nature. Gives you full control over your code, yet can automate all the boring chores. Takes time and effort to learn, yet pays off once you get to know it.

Note: You should know proper touch-typing to actually be efficient.

zacs7
04-29-2009, 07:09 AM
Speaking of which, a little "question"

Use ESC, Ctrl + C, Ctrl + [ or rebind capslock for Insert -> Normal mode?

Wraithan
04-29-2009, 09:29 AM
Though I am no longer using VIM, I did use it for a long time and used capslock to go back to normal mode.

MK27
04-29-2009, 11:06 AM
Speaking of which, a little "question"

Use ESC, Ctrl + C, Ctrl + [ or rebind capslock for Insert -> Normal mode?

Use ESC to leave "insert" mode and go into "command" (aka escape or normal) mode; use the Insert key to leave command mode and re-enter "insert" mode. Works for me anyway.

If you are totally new to vim understanding those two modes (there are some other non-essential ones) is task #1.

Here's my tips o' the day: You can read in (that is, have them processed, not read them into the text display) script files (like the sample .vimrc from my OP) with
:source ~/vimscripts/somescript
That includes ~/.vimrc itself, so you can reconfigure without restarting. In addition to just loading a set of imap/cmap macros, there is a whole language for vim scripts including loops, arrays, etc (and more internal functions than I want to count)*.

You can set a "bookmark" to the current line while in command mode by pressing "m" and then another (upper or lower case) character, eg, "X". To return to that position, use ` (the backtick) and the same character. As long as the file remains in place, vim will remember your bookmarks between invocations; so for example if you have "mX" previously set in some other file, if you don't reset it, "`X" will take you to that line in that file. I have noticed the functionality with this is not perfect (eg, you can lose bookmarks if you mod the file enough) but it generally works. You can get a list of all your existing bookmarks with:
:marks

Here's a quite extensive and well written "Vim Reference" that is independent of the official documentation -- organized differently, etc, so it provides a good contrast (and is definately better indexed):
VIM Reference Guide (http://www.dc.turkuamk.fi/docs/soft/vim/vim.html)
Remember, you can try consulting vim itself on some topic (eg, "recording") with:
:help recording

:) :) :)

* this is actually how the syntax highlighting files are made. In addition to the hundred or so standard, included ones, there are also syntax files available for lots of C (etc) API's that can be added onto the top of the base language (eg, there's one for gtk and openGL). Those can be googled; one place to start is vim.org itself:
http://www.vim.org/scripts/

laserlight
04-29-2009, 11:16 AM
Use ESC, Ctrl + C, Ctrl + [ or rebind capslock for Insert -> Normal mode?
Interesting. I have only ever used ESC for that, but what advantage would the other methods have? Wouldn't rebinding capslock made it inconvenient for those rare cases where you actually want to use it to eh, shout?


use the Insert key to leave command mode and re-enter "insert" mode.
I tend to use i for that, but then I am only a pedestrian vi user.

Wraithan
04-29-2009, 11:31 AM
Capslock is closer in than ESC, I use several capslock keybindings and have the capslock function itself disabled. IF I NEED TO SHOUT I CAN JUST TYPE WITHOUT ONE OF MY PINKIES AND HOLD DOWN SHIFT.

zacs7
04-29-2009, 03:47 PM
Interesting. I have only ever used ESC for that, but what advantage would the other methods have? Wouldn't rebinding capslock made it inconvenient for those rare cases where you actually want to use it to eh, shout?


Sure, but caps lock is on the home row, and escape is certainly not. I usually use ctrl + c. But that's rather... emacs'y. If you need to shout, just bind escape to caps lock, and caps lock to escape.

Oh and you forgot to mention, turn of vi compatibility mode, because even the bugs are mimicked.

Here's my .vimrc if anyone cares.


" zac's vimrc
" Wed Feb 11 07:28:14 UTC 2005

" func
set nocompatible " non vi compatible
set nobackup " no backup files (~)
set history=64 " command line history

" searching
set incsearch " incremental searching
set ignorecase " case insenitive search
set smartcase " if search has uppercase letters then search is case-sensitive

" behaviour
" backspace over everything in indent mode
set backspace=start,indent,eol
set mouse="" " no mouse support in X11
set confirm " always :confirm on exit
" complete options
set completeopt=menu,longest,preview

" appearance
set number " line numbers
set ruler " ruler
set showcmd " display incomplete commands
set showmatch " show the matching bracket for the last )
set nowrap " no wrapping
syn on " syntax highlighting
set showtabline=2 " tab bar at the top

" indenting
set tabstop=3 " tab = 3 spaces
set expandtab " space tabs
set cindent
set autoindent
set smartindent

" colour scheme
colorscheme delek

quzah
05-01-2009, 03:39 PM
The thing everyone wants to know when they run it for the first time:

:q
Quit

:w
Save

:wq
Save and quit.

:q!
Quit without saving.


Quzah.

bithub
05-01-2009, 04:48 PM
In addition to quzah's post, here are some other commands that everyone should know:

i or a
Enter insert mode. i will place the cursor before the currently selected character, and a will place the cursor after.

ESC
Go back to command mode. You may need to press esc twice if you are in some states (like the text search state).

/
Search for text

*
Search for occurences of the word that is currently under the cursor.

n
Go to the next search result.

N
Go to the previous search result.

==
Correctly indent the current line.

=G
Indent the from the cursor location to the end of the file. This command is great for when you paste some non-indented (or poorly indented) code into a vim buffer.

MK27
05-02-2009, 06:54 AM
==
Correctly indent the current line.

=G
Indent the from the cursor location to the end of the file. This command is great for when you paste some non-indented (or poorly indented) code into a vim buffer.
>> will add a tab to the beginning of the current line while in escape mode. If you preface with a number, eg, "5>>" the next five lines will be indented.
<<works the opposite way.

Multiple use of either one will, surprise surprise, add or remove more tab stops. Ie, you can shift entire blocks right or left this way.

MK27
05-09-2009, 10:15 AM
Hey I just noticed that vim won last year's LinuxQuestions.org's "Member's Choice Awards" for Best Text Editor (http://www.linuxquestions.org/questions/2008-linuxquestions.org-members-choice-awards-83/text-editor-of-the-year-695658/) by a whopping margin (400 to 2nd place gedit at 155, out of a field of 15!*). Much surprised.

Also surprised: Midnight Commander, the *second* best piece of software of all time, placed 3rd in "File Manager". Under "Best Programming Langauge", Python beat C++ 226 to 129...

*IDE's were in a seperate catagory, but the winner there (Eclipse) only recieved 129 votes.

Snafuist
05-09-2009, 10:17 AM
:s/<regexp>/<replace>/g
Replaces <regexp> with <replace> globally.

:v
:V
Start selecting text per character/per line.


:y
..."yank", i.e. copy the selected text...

:p
:P
...and paste at the current cursor position or the next one.

:r
Enter replace-mode for exactly one character. Handy for fixing typos.

:help uganda
Make Bram Moolenaar happy.

Greets,
Philip

PS: what is an emac and why do I need several of them to edit text?

MK27
05-10-2009, 09:49 AM
:v
:V
Start selecting text per character/per line.


Sorry, Snafusist, but this is wrong; a command prefaced by a colon is an "ex"tended command that appears at the bottom allowing you to add extensions. ":v" is a real ex command not to be confused with just pushing "v" while in ex mode, which I think is what you meant. "v" enters VISUAL mode where you can select text (personally, I prefer yy & yw).

I won't try and describe ":v" since I never use it except to say that is a variant of ":g", which is incredibly useful. Let's say you have a block of text containing some printf lines that all have some character or sequence in them (eg, "+") that you want to replace all instances of (with "->"), but you don't want to replace "+" globally. You could go line to line and just repeat the command
:s/+/->/
which since you won't have to type that more than once, is pretty easy. Now say there are twenty of them, on every other line (and the line in between has a + you want to leave). That's ":g"
:11,46g/printf/s/+/->/
"11,46" limits the command to lines 11-46 (otherwise global). "printf" -- only lines containing printf. The next part (beginning with "s") can be any other command (except, unfortunately, another g, but you can make up for that with a little regexp know-how in your pattern) -- in this case the substitution.
:v is a slightly useless seeming variation you'll have to look up yourself ;)



:r
Enter replace-mode for exactly one character. Handy for fixing typos.


This is why I like using the actual "Insert" key to enter "insert" mode: because if you press Insert in insert mode, you can switch in and out of "replace" (just like most other places in the universe).

Shakti
05-21-2009, 09:24 AM
To get code completion to work with vim:
http://blogs.gnome.org/lharris/2008/07/20/code-completion-with-vim-7/

When you are done with that i suggest you run
:h omnicppcomplete
in vim and check through chapter 4 to see what options you can change. For instance to have prototypes show up in the dropdown list you add this line to your .vimrc file:
let OmniCpp_ShowPrototypeInAbbr=1

To get rid of the preview window add this to .vimrc
set completeopt=menuone,menu,longest

If you dont have any colorscheme by default i suggest you add this to .vimrc
colorscheme default

This however has some uglyass colors for the dropdown (magenta and a completely white line) so i added these lines to the default.vim file in /usr/share/vim/vim71/colors/
let colors_name = "default"
hi Pmenu ctermbg=3 ctermfg=0
hi PmenuSel ctermbg=3 ctermfg=1
hi PmenuSbar ctermbg=7
hi PmenuThumb ctermbg=0 cterm=NONE

Ive included a screenshot of my vim with these settings. To see a list of colors you can use go here:
Vim documentation: syntax (http://www.vim.org/htmldoc/syntax.html#:highlight)
And scroll down to cterm-colors section.

Kennedy
08-06-2009, 03:42 PM
Maybe you folks already know this, but maybe you don't. One of the coolest things I found lately is CTRL-SHIFT-v for block select. Comes in really handy from time to time.

NOTE: this is NOT the same thing as v or V as those are character and line select.

bithub
08-06-2009, 03:46 PM
Maybe you folks already know this, but maybe you don't. One of the coolest things I found lately is CTRL-SHIFT-v for block select. Comes in really handy from time to time.

NOTE: this is NOT the same thing as v or V as those are character and line select.

Hmm, I've never heard of that, and it didn't work in my version of VIM. I usually use v-% to select a block.

Kennedy
08-06-2009, 03:50 PM
Hmm, I've never heard of that, and it didn't work in my version of VIM. I usually use v-% to select a block.You have to be in command mode (didn't say that part). Try that again. I'm using
VIM - Vi IMproved 7.2 (2008 Aug 9, compiled Sep 17 2008 01:21:50)


EDIT: What I've been using it to do is to block copy my enums to put into switch case statements. I can dup case : then paste it in between the case and :.

bithub
08-06-2009, 04:36 PM
I was in command mode, so that's not it. I'm using VIM 7.0, so I guess it may be a version issue. I also have set up quite a few custom commands in my vimrc, so one of those may be conflicting with (and messing up) the ctrl-shift-v. At any rate, I think v-% does the same thing (unless I misunderstand what you mean by block select), so I'm not missing out on anything.

Kennedy
08-13-2009, 09:20 PM
What is v-%???? When I do that all that happens is that it smart selects a block of code. What I'm talking about is something like this:
1234567
1234567
1234567
1234567then do a ctrl-shift-v on the 3, press right arrow then down the colum, then d to delete just 3 and 4 from each line. . . get it?

MK27
08-16-2009, 11:16 AM
They are different:

v-% is VISUAL
ctrl-v is VISUAL BLOCK

Here's my new found vim feature. I'm always using either remote from file browser to load (see first post in this thread) or :e. The problem with :e is there is only macro, #, which is the last file edited. I'd really prefer a list of all the files I have been editing this session. So it turns out

:b

will do that; regardless of how the file was loaded, if you now type the first few characters of it's short name, you can get a tab completion of the full path and return loads the file same as :e.

Another new found thing:

:set wildmenu

This will give you a horizontal bar of possibilities when using tab completion with any command (or no command, eg, :br tab will give you a bar of possibilities beginning with br). Without wildmenu on, tab completion starts with the first cantidate...

And another: you can add your own commands to abbreviate others with options, etc, using :command. So here's a nice one for the .vimrc:

command SpellOn setlocal spell spelllang=en_us
command SpellOff setlocal nospell

As usual there is more advanced syntax for including parameters, etc. So now, with wildmenu on, you just type :Sp, hit tab, and you will get a choice between SpellOn and SpellOff.

Maz
08-30-2009, 02:14 PM
Well, my most used vim things.

1. run ctags -R in root of your source folders.
2. edit vimrc so vim can find the tags file ( set tags=./tags;../../../../ )

Now, when you want to find the implementation of some function, definition, enum, ..., ... just save file, move cursor on name, and press ctrl+altgr+]
Then ctrl+t will bring you back.
Autocompletion with ctrl+n

What I also do, :new <filename> to split the window and open new file to splitted part. ctrl+ww will change active window.
Running shell commands
:!command
Running shell commands and reading output to file (I use this to correct compile bugs by splitting window when source file is open, and runnin make in empty window.)
:r!command

fronty
08-31-2009, 06:48 AM
a command prefaced by a colon is an "ex"tended command that appears at the bottom allowing you to add extensions. ":v" is a real ex command not to be confused with just pushing "v" while in ex mode, which I think is what you meant. "v" enters VISUAL mode where you can select text (personally, I prefer yy & yw).
Er, command that begins is with colon is a ex command, which means that the command means same thing in ex and in vi. That means, entering v in ex prompt means same thing as entering :v in vi. So you can not confuse command v and "just pushing v while in ex mode", because they are the same thing.

Or, that's the case in nvi which I use (current version of original vi, read about lawsuits if you want to hear more). I believe the situation is the same in vim and other clones.

EDIT: Yay, emacs lost pitifully in linuxquestions poll. 8)

MK27
08-31-2009, 11:40 AM
That means, entering v in ex prompt means same thing as entering :v in vi. So you can not confuse command v and "just pushing v while in ex mode", because they are the same thing.

Or, that's the case in nvi which I use (current version of original vi, read about lawsuits if you want to hear more). I believe the situation is the same in vim and other clones.

I don't use vi, but what I said in that post is true for vim. :v and v ARE NOT THE SAME. I even documented the difference between them. Did you think my explanation of the :v command (which is different than VISUAL, just try it*) referred to some kind of hallucination of something that does not exist?

* you could also just look at "help v" and "help :v" for the difference.

tabstop
08-31-2009, 12:09 PM
I don't use vi, but what I said in that post is true for vim. :v and v ARE NOT THE SAME. I even documented the difference between them. Did you think my explanation of the :v command (which is different than VISUAL, just try it*) referred to some kind of hallucination of something that does not exist?

* you could also just look at "help v" and "help :v" for the difference.

He means that what you are calling "ex mode" is called "command mode" and that what is actually called "ex mode" is something else.

fronty
09-01-2009, 11:17 AM
You are free to try v in ex and :v in vi. I think you will notice that commands that begin with : in vi are same as ex commands. :/

ex commands are commands of line editor ex. ex's prompt is colon, hence vi's command line commands begin with colon (with some exceptions). If you enter a command that begins with colon in visual mode, you are really executing ex's command with same name and syntax and meaning. In fact ex and vi are the same program, it just has two user interfaces, line editor interface and screen editor interface. Visual mode has some commands that aren't present in line editor mode and they share some commands.

EDIT: And by visual mode I mean screen editor mode, the mode you can enter with ex command vi.

MTK
12-03-2009, 11:29 AM
I occasionally play around with vim, and it has a lot of commands that I like that don't exist on other editors (especially "o"), though it still puts me off that I have to switch modes to reposition the cursor. And I do remap my caps lock key to ESC, it is much faster to press and strains my hand less, and I would say that Caps Lock is 99% nuisance and 1% helpful anyway.

I also think that GVIM is better when possible (I don't use the mouse and menus, I like it because I find the shape-changing cursor very handy).

stevesmithx
01-15-2010, 05:46 AM
I've been using vim for a few days now. Darn good editor for touch typists. Every key seems to have a feature in normal mode. Initially I was annoyed by this, as i would accidentally turn some feature ON (like macro instead of exiting (by typing 'q' instead of ':q') but later as I understood them, I was really surprised at how easy and productive vim can be.

My previous post seems to be deleted during the restoration of server backup. Anyways here is the link to the google video where Bram Moolenaar delivers a lecture on effective text editing using Vim.
7 Habits For Effective Text Editing 2.0 (http://video.google.com/videoplay?docid=2538831956647446078) that i posted previously.

Another good article article on why you should use vi:
Why, oh WHY, do those #?@! nutheads use vi? (http://www.viemu.com/a-why-vi-vim.html)

wildcard_seven
04-20-2011, 06:43 PM
I gave it up. I had a sudden realization that Vim had become just as big as the programming. Training myself on the commands, trying out plugins, developing the dexterity to not hit a stray key and end up saying, "WTF" aloud.

I'd much rather just be a little bit slower, but worrying a lot more about what I'm doing than how speedy and badass I am while doing it. I'm using a barebones IDE named Geany on Ubuntu for when I need that type of thing currently.