explorer.vim to frowse directories
CSV Files
Columnise a csv file for display only. This may crop wide columns:
:let width = 20
:let fill=' ' | while strlen(fill) < width | let fill=fill.fill | endwhile
Highlight a particular csv column (put in .vimrc)
function! CSVH(x)
execute 'match Keyword /^\([^,]*,\)\{'.a:x.'}\zs[^,]*/'
execute 'normal ^'.a:x.'f,'
endfunction
command! -nargs=1 Csv :call CSVH(<args>)
:Csv 5 highlight fifth column
Another method is the following to work with CVS files: mmfield.vim navigating CSV files (I love it!). However, I changed the script a bit:
function MMsetfield()
let need_field = input('Jump to field? ')
execute 'match Keyword /^\([^,]*,\)\{'.need_field.'}\zs[^,]*/'
execute 'normal ^'.need_field.'f,'
endfunction
Diff'ing
Load a file in VIM and do a
:diffsplit {filename}
OR:
:vert diffsplit {filename}
Nice!!! Try scrolling around!!! Or on the commandline you could do a:
vimdiff file1 file2 [file3]
All right. Some more:
:diffthis makes the current window part of the diff.
:diffpatch {patchfile} patch the current buffer with the diff found in {patchfile}.
:set diffopt=filler,context:3 sets the context to 3 lines.
Moving in diffs works as follows:
[c jump backwards to the previous start of a hange.
]c jump forward to the next start of a hange.
To also change the buffer according to changes in the other buffer, set the cursor on a difference and use:
:diffg to apply the change from the other buffer.
:diffp to apply the change to the other buffer.
:set scrollbind simulataneously scroll the windows, use before splitting the windows.
The Network File Editor
gf now also works on URLs (starting with: scp:// http:// ftp:// rcp://).
:Nread scp://machine#port/path lets you open a remote file
:Nwrite scp://machine#port/path writes the file remotely.
:Nwrite machine uid pass path writes the file via FTP remotely.
The http protocol is using wget to get the file.
:w ftp://machine/path also works.
gvim ftp://209.51.134.122/public_html/index.html
Store your settings for ftp in the file .netrc:
machine login {userid} password "{password}"
default login {userid} password "{password}"
Command line window
First things first. On the command prompt: (:) you can use TAB for completion, but only if you are in non-compatibility mode (:set nocompatible). Use CTRL-N or CTRL-P or CTRL-A for more options when selecting files. The nicest option is the CTRL-E which gives a list of all the possibilities and lets you select the one you want.
Now, to open the command line window, which is nothing else than the history of commands which are editable like a file, you open as follows:
q:
Hardcopy
Once upon a time, I wrote a script which made it possible to print out just a part of a file. Now finally it is part of the VIM distro:
:[range]ha sends the range to the printer.
:[range]ha > {filename} sends the range to a file (as postscript!!!)
There are a couple of variables you can set to setup headers, the font and so on. Also the papersize and such can be set via the printoptions variable.
LaTeX:
I know, there is WinWord and other beautiful editors to write reports, articles and such, but for my term project, I was encouraged to have a look at LaTex. And for that purpose, I was also checking for some macros which could be handy to use in VIM. Here are a couple of macros I use: (Some of them I got off the web and changed them: http://www.vmunix.com/vim/howto/latex.html)
" ,rl = run latex (on current file)
map ,rl :!latex %<CR>
" ,cps = create ps file (from dvi file of current file)
map ,cps :!dvips %<.dvi -o %<.ps<CR>:!ghostview %<.ps<CR>
" ,vdvi = view dvi file
map ,vdvi :!xdvi %<.dvi &<CR>
ab ... \ldots
imap {\em}i {\em}i
imap {\bf}i {\bf}i
imap {\tt}i {\tt}i
imap \verb++i \verb++i
map! \chapter{ \chapter{}<ESC>i
map! \section{ \section{}<ESC>i
map! \subsection{ \subsection{}<ESC>i
map! \subsubsection{ \subsubsection{}<ESC>i
map! \begin{itemize}
\item \begin{itemize}<CR>\item <CR>\end{itemize}<ESC>kA
map! \begin{enumerate}
\item \begin{enumerate}<CR>\item <CR>\end{enumerate}<ESC>kA
augroup TeX
"autocmd FileType tex source $VIM/TeX/texmacro.vim
autocmd FileType tex :set nonumber
augroup END
A nice Function
A function to save word under cursor to a file
function! SaveWord()
normal yiw
exe ':!echo '.@0.' >> word.txt'
endfunction
map ,p :call SaveWord()
----------------------------------------
# function to delete duplicate lines
function! Del()
if getline(".") == getline(line(".") - 1)
norm dd
endif
endfunction
My .vimrc File
If anybody is interested, here is my .vimrc file!
And this one is for Windows.
VIM Version 6 Features
That it is worth upgrading to version 6 of VIM, can be seen at the following list of new features. They are really worth trying out!
Deleting Paragraphs
I searched for a solution to this problem for a long time. I had a file that was organized in paragraphs. I wanted to delete all the ones that did not contain the word true. I finally found a solution using perl:
:amenu Mo1./.Delete-Matching-Paras:1,$!perl :1,$! perl -0000lne 'print if m/true/'
This solution also shows how to generate menu entries for GVIM.
More things I just discovered
At the bottom of this page, I already outline some things that are really handy and I never really realized. I just found some more things:
Ctrl-R Ctrl-A Enters the text from the editor in you commend line (command mode).
Ctrl-R Ctrl-F Enters the file under the cursor into the editor in you commend line (command mode).
Ctrl-R Ctrl-P Enters the file under the cursor into the editor in you commend line (command mode).
set wildmode=list:longest This is really something you want! Tab-completion the right way!
:r !ls | wc Insert output from a command into the text.
:r !date-join
V select a line
= use equalprg to format selected text (set equalprog=fmt)
Folding
Finally you can fold text. Folding is the process of basically hiding some parts of the text in order to get a quick and easy overview of the rest of it.
There are several modes of operation. Let's start with the manual:
zf'a creates a fold from the current line to the line where mark 'a' was set.
5zF creates a fold for 5 lines.
{range}fo creates a fold for the given range.
zd deletes the fold under the cursor.
zE deletes all the folds of a window.
zo open one folder under the cursor.
zc close one fold under the cursor.
zA on a closed fold, it opens it, on a open one it's the reverse.
There is also the notion of foldlevels, which I do not want to mention close here. Do a :help fold to get more information on folding.
]z moves to the start of the current open fold.
[z moves to the end of the curent open fold.
zj moves to the next fold.
zk moves to the previous fold.
Further you can colorize the folds, by using:
highlight Folded guibg=grez guifg=blue you get the idea...
Further there is the possibility to fold according to the indent, an expression, the syntax or diff.
Diff'ing
Load a file in VIM and do a
:diffsplit {filename}
OR:
:vert diffsplit {filename}
Nice!!! Try scrolling around!!!
Or on the commandline you could do a:
vimdiff file1 file2 [file3]
All right. Some more:
:diffthis makes the current window part of the diff.
:diffpatch {patchfile} patch the current buffer with the diff found in {patchfile}.
:set diffopt=filler,context:3 sets the context to 3 lines.
Moving in diffs works as follows:
[c jump backwards to the previous start of a hange.
]c jump forward to the next start of a hange.
To also change the buffer according to changes in the other buffer, set the cursor on a difference and use:
:diffg to apply the change from the other buffer.
:diffp to apply the change to the other buffer.
Vertically Split Windows
Finally also the VI community can get vertically split windows:
CTRL-W v
Moving around is done pretty intuitively:
CTRL-l
and
CTRL-h
If you want to bind the two windows together, use:
:set scrollbind
before you split the window.
CTRL-W CTRL-I Search for first occurance of what is under the cursor in the current window.
CTRL-W CTRL-F Open new window with filename of word under cursor.
There are many many things you can do with tags and windows. But see :help split for more information on that.
NEW Plugins
All files in ~/.vim/plugin are automatically loaded as plugins for vim.
Standardplugins are:
netrw.vim for editing files over a network!
gzip.vim to edit gzipped files
explorer.vim to frowse directories
mmfield.vim navigating CSV files (I love it!). However, I changed the script a bit:
function MMsetfield()
let need_field = input('Jump to field? ')
execute 'match Keyword /^\([^,]*,\)\{'.need_field.'}\zs[^,]*/'
execute 'normal ^'.need_field.'f,'
endfunction
To see a list of all loaded plugins, use:
:scriptnames
The File Browser
:E starts the browser (!case sensitive!)
Just select a file with the cursor and press ENTER to open it. Press ? to get a help.
:E {directory} starts the browser in a specific directory.
:Se starts the browser in a split window.
The Network File Editor
gf now also works on URLs (starting with: scp:// http:// ftp:// rcp://).
:Nread scp://machine#port/path lets you open a remote file
:Nwrite scp://machine#port/path writes the file remotely.
:Nwrite machine uid pass path writes the file via FTP remotely.
The http protocol is using wget to get the file.
:w ftp://machine/path also works.
Store your settings for ftp in the file .netrc:
machine login {userid} password "{password}"
default login {userid} password "{password}"
Command line window
First things first. On the command prompt: (:) you can use TAB for completion, but only if you are in non-compatibility mode (:set nocompatible). Use CTRL-N or CTRL-P or CTRL-A for more options when selecting files. The nicest option is the CTRL-E which gives a list of all the possibilities and lets you select the one you want.
Now, to open the command line window, which is nothing else than the history of commands which are editable like a file, you open as follows:
q:
Hardcopy
Once upon a time, I wrote a script which made it possible to print out just a part of a file. Now finally it is part of the VIM distro:
:[range]ha sends the range to the printer.
:[range]ha > {filename} sends the range to a file (as postscript!!!)
There are a couple of variables you can set to setup headers, the font and so on. Also the papersize and such can be set via the printoptions variable.
Older Things I never realized
:bro w opens a window to browse for a new filename under which you wanna save the current file.
:bro set opens a window to browse in the settings, with descriptions to each option.
:mksession {filename} writes the entire vim window-settings into a file, which can be :sourceed in another session to restore the setting again.
:qall quits all the windows you have open.
:grep {what} {filename} greps in the files and opens the first one which matches. To go to the next match, use :cnext and :clist to see a list...
:grepadd does not create a new list of found matches, but adds to the old one.
:center does exactly what you think it does.
CTRL-X CTRL-L in edit mode completes a line with the text of a line which starts in the same way.
CTRL-N in edit mode completes a line with a word used in the text already.
gf position the cursor over a filename in the text and this will open the file.
:find {filename} finds the file in the path and edits it.
:%!sort | uniq -c pipes the whole file into sort and does a uniq after it.
v marks text while you move around. Afterward, just use the one-key edit commands to do stuff. For example y yanks the marked text. Pretty neat once you get the heck of it.
CTRL-v similar to "v", you mark a block, not normal text. Try it!
K on a word in commad mode, will show you the man page of the command underneath the cursor.
The SHORTCUTS:
Some hints to the shortcuts below: <BR>
{CR} means that you press ENTER
{lc} is just one lowercase character!
NAME
vi, - screen-oriented (visual) display editor based on ex
START
vi +/startingword 'file'
vi -n don't create swap file
COMMAND SUMMARY
Positioning within file
^F forward screen
^B backward screen
^D scroll down half screen
^U scroll up half screen
h left
j down
k up
l right
H top line on screen
L last line on screen
M middle line on screen
^ first non white-space character
0 beginning of line
$ end of line
w forward a word
b back a word
e end of word
f{char} forward to {char}
t{char} forward till before {char}
dt{char} delete up to {char}
) to next sentence
} to next paragraph
( back a sentence
{ back a paragraph
G end of file
$ end of line
+ move to first non-white char on next line
[( back to unclosed (
[{ back to unclosed {
[* back to unclosed comment (/*)
]) forward to unclosed )
]} forward to unclosed }
}* forward to unclosed comment (*/)
^E scroll window down 1 line
^Y scroll window up 1 line
^o jump back to where you came from
i insert
I insert at beginning of line
a append
A append at end of line
x delete a character
dw delete a word
dd delete a line
3dd delete 3 lines
d'a delete until mark a
d/[w] delete up to [w]ord
d30G delete from cursor to line 30
D delete rest of line (d$)
r replace character under cursor
o open new line below current line
O open new line above current line
~ change case
gu[w] change work to lowercase
gU[w] change work to uppercase
u undo previous change
U restore current line
^R redo change
. repeat last change
J join lines
c[w] change a [word]
C change rest of line (c$)
ZZ exit vi, saving changes
^G show current file and line
!/[w]{CR} sort sorts the input form cursor to [w]ord
!Gawk '{print $1}' from currentline to end replace every line
with first word of that line
:'linenumber' jumps to 'linenumber'
:[+/-] offset
:$ end of File
Tags
^] jump to tag under cursor
:ts [tag] list matching tags and select one to jump to
^T jump back from tag
:tags print tag-list
Multiple files
:n edit next file in arglist
:n 'args' specify new arglist
:e filename of file to edit
:e # opens last file
:e! reedit, discard changes
:r 'file' insert a file
:wn save file and edit next one
Shell escape
:sh run shell, then return
:!'cmd' run 'cmd', then return
Marking and returning
m{lc} mark current position with the ASCII lowercase letter
'{lc} move cursor to mark {lc}
'' jump back to line (where you came from)
:marks show the active marks
Yank and Put
:reg show the content of all registers
"{lc}yy yank the current line in buffer {lc}
3yy yank 3 lines
3yl yank 3 characters
p put back text after cursor
]p put back text after curser, but adjust indent
"{lc}p put from buffer {lc}
"{lc}y yank to buffer {lc}
"{lc}d delete into buffer {lc}
"1p paste the first deleted text
"2p paste the second deleted text …
y'{lc} yank until {lc}-mark
'{lc},'{lc}w write the text between the marks in a file
yyp duplicate a line
"zy'm copy from mark m to cursor
"zd'm cut from mark m to cursor
"zP Paste
Y yank lines (yy)
". contains the last inserted text
"% contains the current filename
Search and Replace
:s/{what}/{with} do it on the active line
:1,10s/{what}/{with} do it from line 1 to 10
:.,+5s/{what}/{with} do it from current to plus five lines
:.,$s/{what}/{with} do it current line to the end
:%s/{what}/{with} do it on the entire buffer
.../g do it on the entire line, not just on first occurance
.../c ask for confirm evey time
:g/{occures}/s/{what}/{with} every line with {occurres} do it
:g!/{occures}/s/{what}/{with} every line without ...
:s@{what}@{with} use another deliminator:
:%s/h.t/host/g use reg-ex for search (.=one char)
use \ as escape caracter!
Use \{ and \} to specify beginning of a
word and ending of a word
/{ctrl-v}{ctrl-seq} Search for a Control Sequence!
% find matching paranthesis
# search identifier under cursor backward
* search identifier under cursor forward
gd get local declaration of identifier
gD get globacl declaration of identifier
n repeat last search
N reverse last search
:ab {text} {with} when typing {text} it sets {with}
:una {text} delete the abbreviation
:map Shows the mappings
:ab Show all abbreviations
Splitting windows
^W n create new empty window
^W s split current window
^W - decrease current window size
^W + increase current window size
^W c close current window
^W k move cursor to window above
^W j move cursor to window below
^W ] split window and jump to tag
^W r rotate windows
^W v vertically split window
^W l move around to the right
^W h move around to the left
z{nr} set current window height to nr
Several
Numbers before a command: Repeats the command n times.
:syntax on Enables syntax highlihting
:set Show all modified options
:set all Shows all the set commands to customize VI.
q{a-z} Record typed characters into register {a-z}
q Stop recording
@{a-z} execute the recording
ga show ASCII value of character under curos
:[range]p [n] print n lines, starting with range
:g/pattern/[cmd] execute Ex command cmd on line with pattern
.vimrc / .exrc -- Vi Configuration File in the home directory
set tabstop=4
set shiftwidth=4
set nowrapscan
set ignorecase
set nocompatibel sets a non compatible mode to VI
set bs=2 Backspace over everything in insertmode
set ai always set autoindent on
set hlsearch highlight the last search pattern
set backup Keep backup copy
set backupdir Backup Directory
set backuptext Set extension for backup file
set number Shows the linenumbers during editing
set showmatch Shows the matching bracket during editing
map <F3> oSOMETEXT maps F3 to insert SOMETEXT
Make
:mak Make (keeps an errorlog, goes to first error)
:cc {nr} Jump to error number
:cn Next error
:cp Show previos error
:cl Show all errors that contain a filename
:cl! Show all errors
CTAGS
CTags can be used to create an index of all methods in a source tree. When editing a file, it
is then possible to jump to method declarations cia ^[. CTags works not only for C, but also
for a lot of other languages (Java, Perl, C, …)
Example:
cd sourcedir ; rm -f tags ; touch tags
find . \(-name SCCS -prune -name '*.java' -o -name '*.java' \) -exec ctags -u {}