Vim
VIM je napredan tekst editor koji de-facto pruža snagu UNIX editora VI uz više značajki i naprednih opcija. VIM nije jednostavan editor kao nano ili pico, potrebno je nešto vremena da ga se nauči i podosta vremena da ga se savlada.
Sadržaj
Značajke
- Vim je vrlo moćan za napredno editiranje
- Brojne ekstenzije i načini konfiguriranja
- jednostavan no opet robustan
- upravljanje sintaksama
Installacija
Arch Linux
pacman -S vim
odnosno
pacman -S gvim
za gui sučelje.
Debian
apt-get install vim vim-rt
Gentoo
emerge vim
Fedora
yum install vim-X11 vim-common vim-enhanced vim-minimal
OpenSuse
zypper install vim
Imajte na umu ukoliko imate upogonjen X da je možda pametnije instalirati gvim pa čak i ukoliko koristite samo vim jer gvim dolazi sa vimom u kojega je ukompajlirana opcija --with-x=yes
pa je omogućeno copy/paste via X.
Korištenje
Ovo je kratak pregled kako koristiti Vim. Alternativno, uvijek možete koristiti vimtutor kako bi se pobliže upoznali sa Vim-om. Vim ima 4 osnovna načina rada:
- Command mode: tipkovničke kratice se intrepretiraju kao naredbe
- Insert mode: editiranje teksta
- Visual mode: uz pomoć tipkovničkih kratica dijelovi teksta se selektiraju, režu ili kopiraju
- Ex mode: mod za unos dodatnih naredaba (e.g. spremanje, zamjena teksta...)
Osnovno editiranje
Ako pokrenete Vim sa
vim nekadatoteka.txt
vidjet će te da se otvorio prazan crni terminal koji kaže kako ta datoteka ne postoji, a ukoliko postoji vidjet će te što se nalazi u njoj. Tu datoteku nećete moći uređivati jer se nalazite u command modu, te je Vim-u trenutno moguće davati naredbe samo preko tipkovnice. Jedna od naredaba je ona za ulazak u insert mod, tipka I. Za izlazak iz insert moda koristi se tipka esc. Dokument spremamo na sljedeći način:
nakon što smo uredili datoteku izađemo pomoću tipke esc te unesemo :w! ~/nekadatoteka.txt, pritisnemo enter te nakon uspješno spremljene tekstualne datoteke unesemo :q i pritisnemo enter za izlazak.
Kretanje dokumentom
Postoji nekoliko načina pomicanja kursora u Vim-u.
Mišem
U Vimu možete slično kao i u Terminalu mišem postaviti kursor na željeno mjesto, kao i obavljati jednostavnije radnje poput obilježavanja teksta.
U .vimrc postavite
set mouse=a
Snimite i ponovno pokrenite Vim.
Ako nemate .vimrc, kreirajte ga u svom home folderu.
Tipkama
Kretati dokumentom se možete i tipkama, točnije strelicama. No to nije vim način pa krenimo na Vim način. U Vim-u se prema dolje krećete sa j, prema gore idete sa k, h je lijevo, a l (L) je desno. ^ stavlja kursor na početak reda dok ga & stavlja na kraj reda. Za riječ naprijed koristi se w, a za povratak je b. Veći skokovi su mogući s { i }. { miče na početak paragrafa dok je } za pomak na kraj paragrafa. H se koristi za pomak na header dokumenta, M za pomak na sredinu, L za zadnji dio, dok gg ide na samo početak dokumenta, a G na sam kraj. control-D omogućava listanje dokumenta po stranama.
Brisanje
Naredba x briše jedan znak dok X briše jednu riječ. 6x briše 6 znakova, 3x r znaka 9X briše 9 riječi. Naredba . ponavlja prethodnu naredbu. d kaže Vim-u da želite nešto obrisati pa je potrebno nakon što pritisnete d i definirati akciju, npr. dW ili d^ ako želite obrisati liniju. Naredba cw trenutno briše riječ na kojoj je kursor te automatski ulazi u insert mod kako bi je mogli zamjeniti. Za zamjenu jednog znaka koristi se r.
Undo i rendo
Vim ima svojevrstan clipboard (buffer) pa je u za undone i Ctrl+r rendo.
Visual mod
Pritiskom na v ulazite u vizual mod. Ovdje se možete slobodno kretati tekstom, pritiskom na y baciti komad teksta u buffer ili koristiti c za cut naredbu i p za paste naredbu nakon kursora i P za paste ispred kursora. V je vizual mod za liniju u kojoj se trenutno nalazite, a ctrl+v za odlomak.
Naredbe search i replace
Za traženje riječi ili znakova unutar teksta potrebno je odabrati / te unijeti znak ili riječ koju tražite, npr. /linux te /& će tražiti u tekstu riječ linux odnosno znak &. Za sljedeći pronađen uzorak se koristi n. Za traženje i zamjenu se koristi substitute :s/ naredba. Sintaksa je sljedeća: [range]:g//[cmd] .
Na primjer:
:g/^#/d Delete all lines that begins with # :g/^$/d Delete all lines that are empty
Spremanje i izlazak
Za spremanje i / ili izlazak iz dokumenta koriste se tzv. Ex naredbe. Njihova karakteristika je što se ispred njih nalazi : . Za spremanje dokumenta koristi se :w odnosno iza :w se doda ime ukoliko taj dokument još ne postoji :w nekadatoteka.txt. Za izlazak se koristi :q ili :q! ukoliko želite spremiti promjene. :x za spremanje i izlazak. Postoji još jedna naredba za spremanje i potom izlazak iz dokumenta <shift>zz .
Dodatne naredbe
- Pritisak na s obrisat će znak pod kursorom, te vas baciti u insert mod. S briše cijelu liniju i baca u insert mod
- o stvara novu liniju između linija i stavlja i insert mod, O stvara liniju iznad trenutne linije i stavlja u insert mod.
- yy stavlja cijelu liniju u buffer
- cc mijenja trenutnu liniju s novom
- * pomiče trenutnu riječ, a n je traži
Konfiguracija
Vim-ova konfiguracijska datoteka je smještena u korisnikovom /home direktoriju ~/.vimrc. Napredni korisnici nastoje imati pregledan i uređen ~/.vimrc. Globalna konfiguracijska datoteka je /etc/vimrc dok su fallback varijable definirane u /usr/share/vim/ .
Backupiranje datoteka
Vim nativno stvara za svaki editirani dokument backup u istom direktoriju u kojem se nalazi datoteka te ga nazove filename~. Kako bi spriječili da ne dođe do brkanja potrebno je definirati backup direktorij za Vim:
set backupdir=~/.vim/backup,/tmp
No također je moguće backup i isključiti:
set nobackup set nowritebackup set noswapfile ! (additionally disable swap files)
Zamotavanje pretraživanje
set wrapscan
Spell check
set spell
Nakon ovoga Vim će raditi spell check (doduše površno ali još uvijek kvalitetnije nego MS Office spell checker). Kada pronađe krivo napisanu riječ na nju će automatski baciti kursor, te je potrebno pritisnuti z= kako bi se pokazale predložene ispravke. Nativno dolazi s provjerom za engleski jezik. Za ostale jezike potrebno je skinuti rječnike te ih instalirati. Oni se mogu naći u arhivi na [1]. Nakon skidanja potrebnog rječnika, npr. hr_HR.diff main.aap potrebno ga je prebaciti u ~/.vim/spell te pokrenuti
:setlocal spell spelllang=LL
Primjer za ~/.vimrc
|name=~/.vimrc |content= " .vimrc " See: http://vimdoc.sourceforge.net/htmldoc/options.html for details " For multi-byte character support (CJK support, for example): "set fileencodings=ucs-bom,utf-8,cp936,big5,euc-jp,euc-kr,gb18030,latin1 set tabstop=4 " Number of spaces that a <Tab> in the file counts for. set shiftwidth=4 " Number of spaces to use for each step of (auto)indent. set expandtab " Use the appropriate number of spaces to insert a <Tab>. " Spaces are used in indents with the '>' and '<' commands " and when 'autoindent' is on. To insert a real tab when " 'expandtab' is on, use CTRL-V <Tab>. set smarttab " When on, a <Tab> in front of a line inserts blanks " according to 'shiftwidth'. 'tabstop' is used in other " places. A <BS> will delete a 'shiftwidth' worth of space " at the start of the line. set showcmd " Show (partial) command in status line. set number " Show line numbers. set showmatch " When a bracket is inserted, briefly jump to the matching " one. The jump is only done if the match can be seen on the " screen. The time to show the match can be set with " 'matchtime'. set hlsearch " When there is a previous search pattern, highlight all " its matches. set incsearch " While typing a search command, show immediately where the " so far typed pattern matches. set ignorecase " Ignore case in search patterns. set smartcase " Override the 'ignorecase' option if the search pattern " contains upper case characters. set backspace=2 " Influences the working of <BS>, <Del>, CTRL-W " and CTRL-U in Insert mode. This is a list of items, " separated by commas. Each item allows a way to backspace " over something. set autoindent " Copy indent from current line when starting a new line " (typing <CR> in Insert mode or when using the "o" or "O" " command). set textwidth=79 " Maximum width of text that is being inserted. A longer " line will be broken after white space to get this width. set formatoptions=c,q,r,t " This is a sequence of letters which describes how " automatic formatting is to be done. " " letter meaning when present in 'formatoptions' " ------ --------------------------------------- " c Auto-wrap comments using textwidth, inserting " the current comment leader automatically. " q Allow formatting of comments with "gq". " r Automatically insert the current comment leader " after hitting <Enter> in Insert mode. " t Auto-wrap text using textwidth (does not apply " to comments) set ruler " Show the line and column number of the cursor position, " separated by a comma. set background=dark " When set to "dark", Vim will try to use colors that look " good on a dark background. When set to "light", Vim will " try to use colors that look good on a light background. " Any other value is illegal. set mouse=a " Enable the use of the mouse. filetype plugin indent on syntax on }}
i napredniji
" = :: =========================================================== :: = " Filename: /home/lutherus/.vimrc " Filesize: 13459 Bytes on 461 Lines " Purpose: My personal vim configuration file " Author: lutherus " License: License? uhm, this is a config file; do with it what ever you want! " Created: 26.11.2004 18:20 CET (+0100) " Modified: 28.04.2011 13:01 CET (+0100) " Version: VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Dec 2 2010 10:44:11) " = :: =========================================================== :: = " = :: = Esentiallies ===================================== {{{1 = :: = if version < 700 echomsg "Your Vim is somewhat out of date, thus" echomsg "update your Editor or don't use this ~/.vimrc" finish endif set all& set nocompatible " set textwidth=0 " Don't wrap set textwidth=72 " see formatoptions and :h fo-table set encoding=utf-8 "autocmd! " = :: = Variables ======================================== {{{1 = :: = " - :: - 2html.vim Setup ---------------------------------- {{{2 - :: - let g:html_use_css = 1 let g:html_use_xhtml = 1 unlet g:html_use_xhtml let g:html_number_lines = 1 let g:html_ignore_folding = 1 let g:html_hover_unfold = 0 unlet g:html_hover_unfold let g:html_use_encoding = "UTF-8" " - :: - Spell check Setup -------------------------------- {{{2 - :: - let g:spellfile_url = 'http://ftp.vim.org/pub/vim/runtime/spell' let g:SpellLangList = [ "nospell", "de_20", "de_19", "en_us" ] language messages C " - :: - BufExplorer Setup -------------------------------- {{{2 · :: - let g:bufExplorerDefaultHelp = 0 " Do not show default help. let g:bufExplorerDetailedHelp = 0 let g:bufExplorerShowRelativePath = 1 " Show relative paths. let g:bufExplorerSplitRight = 1 " Split right. let g:bufExplorerSplitVertical = 1 " Split vertically. let g:bufExplorerUseCurrentWindow = 1 " Open using current window. " - :: - MiniBufExplorer Setup ---------------------------- {{{2 - :: - let g:miniBufExplVSplit = 20 " - :: - Miscellaneous ------------------------------------ {{{2 - :: - let g:BKUPDIR=expand("~/.vim/bkup") let g:SWPDIR=expand("~/.vim/swap//") let loaded_matchparen = 1 let mapleader="," let g:tex_flavor = "latex" " :h ft-tex-plugin let g:loadFileHeaderPlugin = 0 " = :: = File Format, Backup & Swapfile Settings ========== {{{1 = :: = filetype plugin indent on if filewritable(BKUPDIR) == 2 set backup let &backupdir=BKUPDIR else set nobackup endif if filewritable(SWPDIR) == 2 let &directory=SWPDIR " See `:h dir` and the 'Variables' section in this file for explanation set swapfile set updatecount=150 set updatetime=7500 endif set viminfo='25 set vi+=<0 set vi+=:75 set vi+=@75 set vi+=h set vi+=n~/.vim/viminfo set history=75 " = :: = Read, Write Permissions ========================== {{{1 = :: = set noautoread " don't automatically read files if they changed outside vim set noautowrite " don't automatically write files on ':next, :rewind, :last, ...' set noautowriteall " like autowrite, but also used for ':edit, :quit, :exit, ...' set secure " = :: = Display Settings ================================= {{{1 = :: = set showcmd " Show (partial) command in the last line of the screen. set showmode " Display current Modus ( --INSERT --, --REPLACE--, ... ) set report=0 " Show _always_ hints about new/changed/deleted Lines set ruler " Show the line and column number of the cursor position set laststatus=2 " Show _always_ the statusline "set statusline=[%n]%r%m%-25.25(%y[%{&ff}][%{&fenc}]%)%-40.40(%F%)%<%=[%03.3c,%04.4l]\ (%3P) set statusline=[%n]%m[%03.3c,%04.4l]%r%-25.25(%y[%{&ff}][%{&fenc}]%)%-40.40(%F%)%<%=(%3P) set cmdheight=1 " Number of screen lines to use for the command-line. set helpheight=0 " Minimal initial height of the help window set scrolloff=2 " Keep (at least) 2 screen lines above/below the cursor set display=lastline " Display much as possible of the last line "set linespace=2 " Number of pixel lines to use between characters set cursorline " Highlight the screen line of the cursor set shortmess=a " a=filmnrwx set shm+=I " Start without the intro message set shm+=s " Suppress 'search hit BOTTOM, continuing at TOP' message set shm+=tT " Truncate long filenames/messages set shm+=oO " Overwrite some status messages "set shm+=A " get rid off the „ATTENTION“ message when a swap file is found set warn " Warning when a shell cmd is used while the buffer has been changed. set nolist " Show special chars defined by 'listchars' " Notice the the toggle (function) keys in the " mapping section below. set listchars=tab:×· set lcs+=trail:← set lcs+=eol:$ set lcs+=extends:» set lcs+=precedes:« set lcs+=nbsp:¬ set nowrap " wrap lines longer than windowwidth set linebreak set breakat=\ \ !;:,.? set showbreak=\:\:\ »\ set sidescroll=1 " min. number of columns to scroll horizontally. set sidescrolloff=2 " min. number of columns to keep to the left/right of the cursor set wrapmargin=0 " Chars from the right window border where wrapping starts set noerrorbells " Shut up! set novisualbell " Don't flicker! set t_vb= " Holy ..., be quite! " = :: = Window Settings ================================== {{{1 = :: = set splitbelow set splitright " = :: = Completion Settings ============================== {{{1 = :: = set wildmenu set wildmode=full set wildignore+=*.ps set wig+=*.dvi set wig+=*.toc set wig+=*.swp set wig+=*~ set suffixes+=.pdf set su+=.aux " = :: = Tabstop Settings ================================= {{{1 = :: = set tabstop=4 " ??? set shiftwidth=4 " ??? set expandtab set shiftround " ??? "set smartindent "set softtabstop=4 " = :: = Motion Settings ================================== {{{1 = :: = set whichwrap=<,>,~,[,] set backspace=eol,start,indent set esckeys " Use cursor keys in Insert Mode set virtualedit=block " only in Visual Block Mode set nostartofline " keep the cursor in the same column " = :: = Mouse Settings =================================== {{{1 = :: = set mouse=a nmap <MiddleMouse> <Nop> set selectmode=mouse " = :: = Folding Settings ================================= {{{1 = :: = set foldmethod=marker set foldenable " = :: = Search Settings ================================== {{{1 = :: = set magic set wrapscan set ignorecase set smartcase set nohlsearch set incsearch " = :: = Printer Settings ================================= {{{1 = :: = set printheader=%<%F%h%m%=Page\ %N set printfont=terminus:h11 set printoptions=paper:A4 set popt+=syntax:n set popt+=jobsplit:y set popt+=number:y set popt+=header:2 set popt+=wrap:y set popt+=duplex:off set popt+=collate:y " = :: = Syntax Highlighting ============================== {{{1 = :: = syntax on colorscheme darkburn " = :: = Format Settings ================================== {{{1 = :: = set noautoindent " ??? (complex) set nosmartindent " ??? (complex) set nocindent " ??? (complex) set nocopyindent " ??? (complex) " set formatoptions=tcq " vim standard " set fo+=r " insert comment leader after hitting enter " set fo+=n " recognize numbered lists " set fo+=1 " don't break a line after a one-letter word " set formatoptions=tcq " vim standard set fo-=t " Don't auto-wrap text using textwidth "set formatlistpat=^\s*\d\+[\]:.)}\t ]\s* " vim standard set nojoinspaces " don't insert spaces after '.,?!' with <J> set switchbuf=usetab,newtab " = :: = Miscellaneous settings =========================== {{{1 = :: = set hidden set ttyfast set nolazyredraw set modeline set modelines=3 set notitle " = :: = Mappings ========================================= {{{1 = :: = " - :: - Comments in VISUAL MODE -------------------------- {{{2 - :: - " U visual modu markirati više znakova " :let @/="" obriši cijeli redak " ili uzmi :set hlsearch " vmap # :s/^/# <CR>:let @/=""<CR> vmap " :s/^/" /<CR>:let @/=""<CR> vmap % :s/^/% /<CR>:let @/=""<CR> vmap / :s/^/\/\/ /<CR>:let @/=""<CR> vmap ; :s/^/; /<CR>:let @/=""<CR> vmap ! :s/^/! /<CR>:let @/=""<CR> " und hier löscht man die Kommentarzeichen wieder vmap - :s/^[#"%\/;!]*<SPACE>//<CR>:let @/=""<CR> " - :: - Function Keys ------------------------------------ {{{2 - :: - nmap <F1> :help <C-R>=expand("<cword>")<CR><CR> map <F2> <ESC>:setlocal hlsearch! <bar> set hlsearch?<CR> imap <F2> <C-O>:setlocal hlsearch!<CR> map <F3> <ESC>:setlocal wrap! <bar> set wrap?<CR> imap <F3> <C-O>:setlocal wrap!<CR> map <F4> <ESC>:setlocal list! <bar> set list?<CR> imap <F4> <C-O>:setlocal list!<CR> map <F5> <ESC>:setlocal number! <bar> set number?<CR> imap <F5> <C-O>:setlocal number!<CR> map <F6> <ESC>:setlocal foldenable! <bar> set foldenable?<CR> imap <F6> <C-O>:setlocal foldenable!<CR> map <F7> <ESC>:setlocal cursorline! <bar> set cursorline?<CR> map <F8> <ESC>:call ToggleColorColumne()<CR> map <F9> <ESC>:call ToggleSpellLang()<CR> imap <F9> <C-O>:call ToggleSpellLang()<CR> set pastetoggle=<F12> " - :: - Misc Mappings ------------------------------------ {{{2 - :: - map S O#<ESC>a<SPACE>=<SPACE>::<SPACE><ESC>60a=<ESC><CR><ESC>0k9lR nmap + <C-W>+ nmap - <C-W>- nmap <S-LEFT> 10<C-W>< nmap <S-RIGHT> 10<C-W>> nmap <LEADER>e :Texplore<CR> nmap <LEADER>E :Sexplore<CR> nmap <LEADER>tn :tabnew<SPACE> nmap <LEADER>tc :tabclose<CR> nmap :W :w nmap :Q :q nmap <LEADER>HI :so $VIMRUNTIME/syntax/hitest.vim nmap <LEADER>sv :so ~/.vimrc<CR> map <LEADER>tm <esc>:r!date +\%R<CR> map <LEADER>dt <esc>:r!date +'\%A, \%d.\%B \%Y \%k:\%M'<CR> nmap <LEADER>s <esc>:%s/ *$//g<CR> nmap <LEADER>S <esc>:%s/ *$//g<CR> nmap <LEADER>m <PLUG>MiniBufExplorer nmap <LEADER>c <PLUG>CMiniBufExplorer nnoremap j gj nnoremap k gk nnoremap Q gq " = :: = Abbreviations ==================================== {{{1 = :: = ca hitest so $VIMRUNTIME/syntax/hitest.vim iab hrul = :: =========================================================== :: = iab teh the iab -today- <esc>:r!date \+'\%c'<CR>kJA<esc> " = :: = Autocommands ===================================== {{{1 = :: = augroup zsh autocmd! autocmd BufNewFile,BufRead ~/zsh/*.zsh setlocal ft=zsh augroup END augroup note autocmd! autocmd BufNewFile,BufRead /tmp/sartoo-1000/notes/* setlocal tw=72 fo+=t augroup END augroup html autocmd! " autocmd BufNewFile,BufRead *.html setlocal wrap linebreak matchpairs+=<:> autocmd FileType html,xhtml setlocal fo-=t fo-=c autocmd FileType html,php,css source ~/.vim/html.vim augroup END augroup mutt autocmd! autocmd BufNewFile,BufRead ~/.mutt/*.muttrc setlocal ft=muttrc augroup END augroup mail autocmd! " autocmd FileType mail setlocal spell spelllang=de_de " Das meiste erledigt `ftplugin/mail.vim´ autocmd BufNewFile,BufRead /tmp/*/mutt-* setlocal comments=n:>,fb:- tw=72 ts=8 sw=8 sts=0 et " Entferne leere Kommentarzeilen aus den Mails, also sowas mag ich " nicht in meinen Mails: " > blabla " > " >> weiteres blablb autocmd BufRead /tmp/*/mutt-* normal :g/^> -- $/,/^$/-1d<CR><C-L>gg " in der muttrc wird vim so aufgerufen: set editor="/usr/bin/vim -c '+/^Subject:' augroup END augroup tex autocmd! autocmd BufNewFile *.tex 0r ~/documents/templates/skel.tex autocmd BufNewFile,BufRead ~/*.tex setlocal tw=80 augroup END autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif autocmd BufNewFile ~/*.bwb setlocal ft=txt wrap linebreak expandtab list cursorline autocmd BufNewFile ~/*.bwb 0r ~/.vim/templates/bwb.tmp autocmd BufNewFile ~/*.bwb retab " autocmd! FileType vo_base colorscheme 256-sartoo " = :: = Functions ======================================== {{{1 = :: = func! ToggleSpellLang() if !exists("b:SpellLang") let b:SpellLang = 0 endif let b:SpellLang = b:SpellLang + 1 if b:SpellLang >= len(g:SpellLangList) let b:SpellLang = 0 setlocal nospell endif if b:SpellLang > 0 setlocal spell setlocal nohls let &spelllang=g:SpellLangList[b:SpellLang] endif echo "language:" g:SpellLangList[b:SpellLang] endfunc func! ToggleColorColumne() if !exists("b:ColCol") let b:ColCol = 0 endif if b:ColCol == 0 setlocal colorcolumn=+2 let b:ColCol = 1 echo "set Colorcolumn" else setlocal colorcolumn= let b:ColCol = 0 echo "unset Colorcolumn" endif endfunc " :help :abbreviate-local 14k func Eatchar(pat) let c = nr2char(getchar(0)) return (c =~ a:pat) ? '' : c endfunc " = :: = Plugins ========================================== {{{1 = :: = runtime! ftplugin/man.vim filetype plugin indent on set grepprg=grep\ -nH\ $* let g:tex_flavor = "latex"
Uspoređivanje dokumenata
Vim ima ugrađen diff editor (program koji prepoznaje razlike između dva dokumenta). Korištenje počinje sa vimdiff file1 file2 ; te se dalje koristi nešto od navedenog
]c : - sljedeća razlika [c : - prethodna razlika Ctrl+w +w - promjena prozora do - diff obtain dp - diff put zo - otvara preklopljen text zc - zatvara preklopljen text :diffupdate - reskeniranje razlika
Resursi
Službeni
Tutoriali
- vi Tutorial and Reference Guide
- Graphical vi-vim Cheat Sheet and Tutorial
- Vimcasts - screencasts in .ogg format.
- Tutorial Videos - Tutorial videos, covering the basics up to advanced topics.
- Vim Introduction and Tutorial