Latest 100 public
snipts » vim
showing 1-20 of 42 snipts for vim
-
∞ reads a dump of file, formatted as C source
xxd -i `which xxd`
-
∞ scp in vimrc
let g:netrw_cygwin= 0 let g:netrw_scp_cmd = "C:\\path\\to\\putty's\\scp\\pscp.exe -pw yourpasswd" let g:netrw_sftp_cmd = "C:\\path\\to\\putty's\\sftp\\pftp.exe -pw yourpasswd" let g:netrw_list_cmd = "plink username@hostname -pw yourpasswd ls -Fa"
-
∞ configure vim file
" Arquivo de configuração do vim " vim:nolist:enc=utf-8: " Criado: Qua 02/Ago/2006 hs 09:19 " Last Change: Qua 30 Jun 2010 17:10:32 BRT " Autor: Sergio Luiz Araujo Silva " Codificação: utf-8 " Download: http://dotfiles.org/~voyeg3r/.vimrc " Licence: Licença: Este arquivo é de domínio público " Garantia: O autor não se responsabiliza por eventuais danos " causados pelo uso deste arquivo. " ( O O )"{{{ " +===========oOO==(_)==OOo==============+ " | | " | °v° Sergio Luiz Araujo Silva | " | /(_)\ Linux User #423493 | " | ^ ^ voyeg3r ? gmail.com | " +======================================+ " " Referências: " * http://aurelio.net/vim/vimrc-ivan.txt " " :set runtimepath=~/vimruntime,/mygroup/vim,$VIMRUNTIME " :echo g:colors_name " " sobre o plugin taglist " http://www.caiomoritz.com/2008/02/09/o-poder-da-exuberant-ctags-aliada-ao-vim/ " " let s:wordUnderCursor = expand("<cword>") " :%s/expand("<cword>")//gn"}}} " if v:lang =~ "utf8$" || v:lang =~ "UTF-8$" set fileencodings=utf-8,latin1 endif " Settings for :TOhtml let html_number_lines=1 let html_use_css=1 let use_xhtml=1 map ,f <esc>:FuzzyFinderFile<cr> map ,b <esc>:FuzzyFinderBookmark<cr> map ,a <esc>:FuzzyFinderAddBookmark<cr> map ,d <esc>:FuzzyFinderDir<cr> map ,m <esc>:FuzzyFinderMruFile<cr> nmap ,i [I:let nr = input("Which one: ")<Bar>exe "normal " . nr ."[\t"<CR> amenu &Projetos.toggle <Plug>ToggleProject<cr> " -------------------- " Project " -------------------- "map <A-S-p> :Project<CR> "map <A-S-o> :Project<CR>:redraw<CR>/ "nmap <silent> <F3> <Plug>ToggleProject let g:proj_window_width = 30 let g:proj_window_increment = 50 " habilitar e desabilitar o plugin nmap <silent> ,p <Plug>ToggleProject<cr> " mapeamento para mostrar linhas que contenhasm determinada palavra map ,/ [I:let nr = input("Which one: ")<Bar>exe "normal " . nr ."[\t"<CR> " mapeamento para mostrar linhas duplicadas map ,sd <esc>:g/^\(.*\)\n\ze\%(.*\n\)*\1$/#<cr> " para que as modelines funcionem com file encoding au BufReadPost * let b:reloadcheck = 1 au BufWinEnter * if exists('b:reloadcheck') | unlet b:reloadcheck | if &mod != 0 && &fenc != "" | exe 'e! ++enc=' . &fenc | endif | endif " contagem de ocorrências de uma palavra (case insensitive) nmap <F4> <esc>mz:%s/\c\<\(<c-r>=expand("<cword>")<cr>\)\>//gn<cr>`z nmap <s-F4> <esc>mz:%s/\c\(<c-r>=expand("<cword>")<cr>\)//gn<cr>`z " mapeamento para o wikispaces " https://addons.mozilla.org/pt-BR/firefox/addon/4125 imap ,w [[code format=""]]<enter><+conteudo+><enter>[[code]]<esc><right>D<esc>kkf"a nmap ,w [[code format=""]]<enter><+conteudo+><enter>[[code]]<esc><right>D<esc>kkf"a " mapeamento para colocar palavra sob o cursor na substituição nnoremap <Leader>s :%s/\<<C-r><C-w>\>/ " registro de alterações de arquivo " ChangeLog entry convenience " Função para inserir um status do arquivo " cirado: data de criação, alteração, autor etc fun! InsertChangeLog() normal(1G) call append(0, "Arquivo: ") call append(1, "Criado: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(2, "Last Change: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(3, "autor: <+digite seu nome+>") call append(4, "site: <+digite o endereço de seu site+>") normal gg endfun " Cria um cabeçalho para scripts bash fun! InsertHeadBash() normal(1G) call append(0, "#!/bin/bash") call append(1, "# Criado em:" . strftime("%a %d/%b/%Y hs %H:%M")) call append(2, "# Last Change: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(3, "# vim:ft=sh:fdm=syntax:nu:") call append(4, "# Instituicao: <+nome+>") call append(5, "# Proposito do script: <+descreva+>") call append(6, "# Autor: <+seuNome+>") call append(7, "# site: <+seuSite+>") normal gg endfun map ,sh :call InsertHeadBash()<cr>A au BufNewFile,BufRead *.sh if getline(1) == "" | normal ,sh au! VimEnter * match ErrorMsg /^\t\+/ au! VimEnter * match ErrorMsg / $/ augroup filetypedetect au BufNewFile,BufRead *.txt setf txt augroup END augroup filetypedetect au BufNewFile,BufRead *.sh setf sh augroup END fun! BufNewFile_PY() normal(1G) call append(0, "#!/usr/bin/env python") call append(1, "# # -*- coding: UTF-8 -*-") call append(2, "# Criado em:" . strftime("%a %d/%b/%Y hs %H:%M")) call append(3, "# Last Change: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(4, "# vim:ft=python:nolist:nu:") call append(5, "# Instituicao: <+nome+>") call append(6, "# Proposito do script: <+descreva+>") call append(7, "# Autor: <+seuNome+>") call append(8, "# site: <+seuSite+>") normal gg endfun autocmd BufNewFile *.py call BufNewFile_PY() map ,py :call BufNewFile_PY()<cr>A " calculadora científica usando python :command! -nargs=+ Calc :py print <args> :py from math import * map ,c :Calc nmap <c-s-c> :call LastChange()<cr> nmap <c-m-c> :call InsertChangeLog()<cr> " Automatically give executable permission to scripts starting " with #!/usr/bin/perl and #!/bin/sh au BufNewFile,BufWritePost * if getline(1) =~ "^#!/bin/[a-z]*sh" || \ getline(1) =~ "^#!/usr/bin/.*python" | silent execute "!chmod u+x %" | endif filetype on filetype plugin on set ofu=syntaxcomplete#Complete "# omini completion for python autocmd FileType python set omnifunc=pythoncomplete#Complete autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS autocmd FileType html set omnifunc=htmlcomplete#CompleteTags autocmd FileType css set omnifunc=csscomplete#CompleteCSS autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags autocmd FileType php set omnifunc=phpcomplete#CompletePHP autocmd FileType c set omnifunc=ccomplete#Complete if has("autocmd") autocmd FileType php set complete-=k/home/USUARIO/.vim/doc/funclist.txt complete+=k/home/USUARIO/.vim/doc/funclist.txt endif " adiciona omnifunc para demais formatos if has("autocmd") && exists("+omnifunc") autocmd Filetype * \ if &omnifunc == "" | \ setlocal omnifunc=syntaxcomplete#Complete | \ endif endif " Like bufdo but restore the current buffer. function! BufDo(command) let currBuff=bufnr("%") execute 'bufdo ' . a:command execute 'buffer ' . currBuff endfunction com! -nargs=+ -complete=command Bufdo call BufDo(<q-args>) "numerar linhas - use o plugin nlist que está instalado ou instale via web " instalei o plugin nlist para numerar linhas por isso comentei este trecho "command! -nargs=* -range Nlist <line1>,<line2>call Nlist(<f-args>) "function! Nlist(...) range " if 2 == a:0 " let start = a:1 " let append = a:2 " elseif 1 == a:0 " let start = a:1 " let append = " " " else " let start = 1 " let append = " " " endif " " " try to work like getline (i.e. allow the user to pass in . $ or 'x) " if 0 == (start + 0) " let start = line(start) " endif " " exe a:firstline . "," . a:lastline . 's/^/\=line(".")-a:firstline+start.append/' "endfunction " advanced incrementing (really useful) " put following in _vimrc let g:I=0 function! INC(increment) let g:I =g:I + a:increment return g:I endfunction " eg create list starting from 223 incrementing by 5 between markers a,b ":let I=223 ":'a,'bs/^/\=INC(5)/ " create a map for INC "cab viminc :let I=223 \| 'a,'bs/$/\=INC(5)/ " rola janela alternativa fun! ScrollOtherWindow(dir) if a:dir == "down" let move = "\<C-E>" elseif a:dir == "up" let move = "\<C-Y>" endif exec "normal \<C-W>p" . move . "\<C-W>p" endfun nmap <silent> <M-Down> :call ScrollOtherWindow("down")<CR> nmap <silent> <M-Up> :call ScrollOtherWindow("up")<CR> set foldlevel=2 set vb t_vb= set listchars=tab:\|\ ,extends:>,precedes:<,trail:-,nbsp:% " set foldcolumn=2 --> exibe um sinal de mais ao lado dos folder " ao rolar a janelas ele manterá uma linha a mais " visível na tela, faça um experimento " ele manterá as linhas próximas visíveis set scrolloff=2 nnoremap <leader>w :set wrap! wrap?<cr> " mostra +++ no começo de linhas longas sem wrap set showbreak=+++ nnoremap <leader>l :set list! list?<cr> ":help options linha 4321 "au BufNewFile,BufRead *.txt source ~/.vim/syntax/txt.vim " testa de há modo gráfico if &t_Co > 2 || has("gui_running") syntax on set hlsearch colorscheme ir_black hi LineNr guifg=pink ctermfg=lightMagenta "hi LineNr guifg=green ctermfg=lightGreen endif let hr= str2nr(strftime("%H")) if 0 <= hr && hr <= 3 colors ir_black elseif 4 <= hr && hr <= 7 colors tango-morning elseif 8 <= hr && hr <= 14 colors mustang elseif 15 <= hr && hr <= 20 colors digerati else colors digerati endif function! <SID>SwitchColorSchemes() if exists("g:colors_name") if g:colors_name == 'google' colorscheme xoria256 elseif g:colors_name == 'xoria256' colorscheme darkbone elseif g:colors_name == 'darkbone' colorscheme colorful elseif g:colors_name == 'colorful' colorscheme zenburn elseif g:colors_name == 'zenburn' colorscheme python elseif g:colors_name == 'python' colorscheme tango-morning elseif g:colors_name == 'tango-morning' colorscheme guepardo elseif g:colors_name == 'guepardo' colorscheme rubyblue elseif g:colors_name == 'rubyblue' colorscheme pacific elseif g:colors_name == 'pacific' colorscheme tango elseif g:colors_name == 'tango' colorscheme softblue elseif g:colors_name == 'softblue' colorscheme vividchalk elseif g:colors_name == 'vividchalk' colorscheme professional elseif g:colors_name == 'professional' colorscheme neverness elseif g:colors_name == 'neverness' colorscheme mustang elseif g:colors_name == 'mustang' colorscheme underwater-mod elseif g:colors_name == 'underwater-mod' colorscheme whitebox elseif g:colors_name == 'whitebox' colorscheme summerfruit elseif g:colors_name == 'summerfruit' colorscheme maroloccio elseif g:colors_name == 'maroloccio' colorscheme wombat elseif g:colors_name == 'wombat' colorscheme chrysoprase elseif g:colors_name == 'chrysoprase' colorscheme quagmire elseif g:colors_name == 'quagmire' colorscheme digerati elseif g:colors_name == 'digerati' colorscheme vylight elseif g:colors_name == 'vylight' colorscheme vitamins elseif g:colors_name == 'vitamins' colorscheme rdark elseif g:colors_name == 'rdark' colorscheme eclm_wombat elseif g:colors_name == 'eclm_wombat' colorscheme native elseif g:colors_name == 'native' colorscheme inkpot elseif g:colors_name == 'inkpot' colorscheme vibrantink elseif g:colors_name == 'vibrantink' colorscheme ir_black elseif g:colors_name == 'ir_black' colorscheme google endif endif endfunction "map <silent> <F6> :call <SID>SwitchColorSchemes()<CR> <BAR> :set t_Co=256 <BAR> :echo g:colors_name<cr> map <silent> <F6> <esc>:call <SID>SwitchColorSchemes()<CR><bar>:echo g:colors_name<cr> set anti gfn=Inconsolata\ 12,\ Envy\ Code\ R\ 10 "set anti gfn=BPmono\ 11 "set anti gfn=Inconsolata\ 13 "set anti gfn=Pragmata\ 10,Monaco\ 9,\ Envy\ Code\ R\ 10 "set anti gfn=Liberation\ Mono\ 9 "set guifont=Bitstream\ Vera\ Sans\ Mono\ 9 "set ve=all " cura para acesso remoto set et set notimeout set ttimeout set timeoutlen=100 set autowrite " salvamento automático set shiftwidth=4 set softtabstop=4 set viminfo=%,'50,\"100,/100,:100,n set undolevels=1000 " undoing 1000 changes should be enough :-) set updatecount=100 " write swap file to disk after each 20 characters set updatetime=6000 " write swap file to disk after 6 inactive seconds set noerrorbells " don't make noise set incsearch " habilita busca incremental set ts=4 " Paradas de tabulação com 4 espaços set nocompatible set ignorecase set smartcase "Se começar uma busca em maiúsculo ele habilita o case set expandtab set smarttab set noerrorbells set visualbell set nu ai sm js set showcmd showmode "set showmatch set ruler set hls set ts=4 set backup set backupdir=~/.backup,~/tmp,.,/tmp set backupext=.backup set mousemodel=popup set mouse=nvc set ttyfast " Uppercase first letter of sentences ":%s/[.!?]\_s\+\a/\U&\E/g " Define o número de linhas deslocadas com os comandos " ^U (Ctrl+U) e ^D (Ctrl+D) setlocal scroll=2 syn match ipaddr /\(\(25\_[0-5]\|2\_[0-4]\_[0-9]\|\_[01]\?\_[0-9]\_[0-9]\?\)\.\)\{3\}\(25\_[0-5]\|2\_[0-4]\_[0-9]\|\_[01]\?\_[0-9]\_[0-9]\?\)/ hi link ipaddr Identifier "validador de e-mail (observe que estou buscando no começo da linha) " ^\<[^ @][A-Za-z0-9_.-]\+@\([A-Za-z0-9_-]\+\.\)\+[A-Za-z]\{2,4}\>\(?[A-Za-z0-9%&=+.,@*_-]\+\)\= map ,d <esc>my:%s/\(^\n\{2,}\)/\r/g<cr>`y nno <S-F11> <esc>:set hls! hls?<cr> " Para inserir o simbolo use ^v ^M ou ^v Enter if has("user_commands") " remove from the file com! RemoveCtrlM :%s/\%x0d/\r/g " change to directory of current file com! CD cd %:p:h endif " o atalho <leader>m já está mapeado para FuzzyFinderMruFile "noremap <Leader>m mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm " no caso do sed faça: "sed -i 's/\x0D$//' * " Para apagar caracteres de final de linha do DOS manualmente faça: ":%s/\%x0d//g " plugin potwiki " leia: http://sergioaraujo.pbwiki.com/potwiki au Filetype potwiki set sts=4 highlight PotwikiWord guifg=darkcyan highlight PotwikiWordNotFound guibg=Red guifg=Yellow " snippets let g:snips_author = 'Sérgio Luiz Araújo Silva' " para exibir os snippets disponíveis (inserção) <c-r><tab> "let snippetsEmy_key = "<C-Space>" " place holders snippets " File Templates " -------------- " ^J jumps to the next marker " iabbr <buffer> for for <+i+> in <+intervalo+>:<cr><tab><+i+> function! LoadFileTemplate() "silent! 0r ~/.vim/templates/%:e.tmpl syn match vimTemplateMarker "<+.\++>" containedin=ALL hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold endfunction function! JumpToNextPlaceholder() let old_query = getreg('/') echo search("<+.\\++>") exec "norm! c/+>/e\<CR>" call setreg('/', old_query) endfunction autocmd BufNewFile * :call LoadFileTemplate() nnoremap <C-J> :call JumpToNextPlaceholder()<CR>a inoremap <C-J> <ESC>:call JumpToNextPlaceholder()<CR>a " " http://aurelio.net/doc/vim/txt.vim coloque em ~/.vim/syntax au BufNewFile,BufRead *.txt source ~/.vim/syntax/txt.vim " CTRL-X CTRL-F file names " CTRL-X CTRL-L whole lines " CTRL-X CTRL-D macro definitions (also in included files) " CTRL-X CTRL-I current and included files " CTRL-X CTRL-K words from a dictionary " CTRL-X CTRL-T words from a thesaurus " CTRL-X CTRL-] tags " CTRL-X CTRL-V Vim command line " CTRL-X CTRL-O códigos au FileType * exe('setl dict+='.$VIMRUNTIME.'/syntax/'.&filetype.'.vim') " numerar linhas ":let i=1 | g/^/s//\=i."\t"/ | let i=i+1 map ,n <esc>:let i=1 <bar> g/^/s//\=i."\t"/ <bar> let i=i+1<cr> map <F2> <esc>:NERDTreeToggle<cr> nnoremap <F3> :set invpaste paste?<cr> "imap <F3> <C-O><F3><cr><cr> imap <F3> <esc>:set invpaste paste?<cr>a<cr> set pastetoggle=<F3> "usa o tab em modo insert para completar palavras function! InsertTabWrapper(direction) let col = col('.') - 1 if !col || getline('.')[col - 1] !~ '\k' return "\<tab>" elseif "backward" == a:direction return "\<c-p>" else return "\<c-n>" endif endfunction let g:AutoComplPop_CompleteoptPreview = 1 "mapeia para completar comandos e busca com tab "cmap <tab> <Plug>CmdlineCompleteForward "Fechamento automático de parênteses, chaves e colchetes imap { {}<left> imap ( ()<left> imap [ []<left> " pular fora dos parênteses, colchetes e chaves, mover o cursor " no modo de inserção imap <c-l> <Esc><right>a "Para ir para a próxima linha usando l ou h set whichwrap=h,l,~,[,] "set matchpairs+=<:> filetype plugin indent on set dictionary+=/home/sergio/docs/conf/dict/.words.txt set infercase set noequalalways set wildmenu set wildmode=list:longest,full inoremap <tab> <c-r>=InsertTabWrapper ("forward")<cr> inoremap <s-tab> <c-r>=InsertTabWrapper ("backward")<cr> " pydiction "if has("autocmd") " autocmd FileType python set complete+=k/.vim/dict/pydiction isk+=.,( "endif " has("autocmd") "let g:pydiction_location = 'vimfiles/ftplugin/pydiction/complete-dict' let g:pydiction_location = '~/.vim/after/ftplugin/pydiction/complete-dict' "Complementação de palavras if v:version >= 700 set completeopt+=longest set completeopt=longest,menuone set spell spelllang=pt map <silent> <C-M-i> :setlocal invspell<CR> imap <silent> <C-M-i> <ESC>:setlocal invspell<CR>i endif setlocal complete=.,w,k,b,u,t,i set complete-=k complete+=k set nospell " usando <c-i> ativa spell set spellsuggest=8 map <s-F7> <esc>:set spell!<cr> " status bar format " O trecho abaixo formata a barra de status com algumas opções interessantes! " mostra o código ascii do caractere sob o cursor e outras coisas mais set statusline=%<%F%h%m%r%h%w%y\ \ft:%{&ft}\ \ff:%{&ff}\ Modificado:\ \%{strftime(\"%a\ %d/%B/%Y\ \%H:%M:%S\",getftime(expand(\"%:p\")))}%=\ \#%n\ \ \LIN:%04l\ COL:%04v\ \TOTAL:%04L\ HEX:%03.3B\ ASCII:%03.3b\ %P set laststatus=2 " Sempre exibe a barra de status nmap n nzz nmap N Nzz nmap * *zz nmap # #zz nmap g* g*zz nmap g# g#zz " recarregar o vimrc " Source the .vimrc or _vimrc file, depending on system if &term == "win32" || "pcterm" || has("gui_win32") map ,v :e $HOME/_vimrc<CR> nmap <F12> :<C-u>source ~/_vimrc <BAR> echo "Vimrc recarregado!"<CR> else map ,v :e $HOME/.vimrc<CR> nmap <F12> :<C-u>source ~/.vimrc <BAR> echo "Vimrc recarregado!"<CR> endif " Highlight redundant whitespace and tabs. highlight RedundantWhitespace ctermbg=red guibg=red match RedundantWhitespace /\s\+$\| \+\ze\t/ map <F7> <esc>mz:%s/\s\+$//g<cr>`z fun! LastChange() mark z if getline(1) =~ ".*Last Change:" || \ getline(2) =~ ".*Last Change:" || \ getline(3) =~ ".*Last Change:" || \ getline(4) =~ ".*Last Change:" || \ getline(5) =~ ".*Last Change:" exec "1,5s/\s*Last Change: .*$/Last Change: " . strftime("%c") . "/" endif exec "'z" endfun nmap <F9> <esc>:w<cr> imap <F9> <C-O><C-S> " salva com <F5> e altera o time stamp chamando a função " LastChange() definina acima map <F5> <esc>:call LastChange() <BAR> w<cr> " abre o histórico de comandos "ao salvar modificar o change log no começo do arquivo cab wq call LastChange() <BAR> wq<cr> "============ Fim da Data Automática =================== " Abreviações " " Estas linhas sao para não dar erro " na hora de salvar arquivos cab W w cab Wq wq cab wQ wq cab WQ wq cab Q q iab tambem também iab teh the iab them then iab latex \LaTeX\ iab ,m <voyeg3r@gmail.com> ab slas Sérgio Luiz Araújo Silva ab vc você iab teh the iab a. ª iab analize análise iab angulo ângulo iab apos após iab apra para iab aqeule aquele iab aqiulo aquilo iab arcoíris arco-íris iab aré até iab asim assim iab aspeto aspecto iab assenção ascenção iab assin assim iab assougue açougue iab aue que iab augum algum iab augun algum iab ben bem iab beringela berinjela iab bon bom iab cafe café iab caichote caixote iab capitões capitães iab cidadães cidadãos iab ckaro claro iab cliche clichê iab compreenssão compreensão iab comprensão compreensão iab comun comum iab con com iab contezto contexto iab corrijir corrigir iab coxixar cochichar iab cpm com iab cppara para iab dai daí iab danca dança iab decer descer iab definitamente definitivamente iab deshonestidade desonestidade iab deshonesto desonesto iab detale detalhe iab deven devem iab díficil difícil iab distingeu distingue iab dsa das iab dze dez iab ecessão exceção iab ecessões exceções iab eentão e então iab emb bem iab ems sem iab emu meu iab en em iab enbora embora iab equ que iab ero erro iab erv ver iab ese esse iab esselência excelência iab esu seu iab excessão exceção iab Excesões exceções iab excurção excursão iab Exenplo exemplo iab exeplo exemplo iab exijência exigência iab exijir exigir iab expontâneo espontâneo iab ezemplo exemplo iab ezercício exercício iab faciu fácil iab fas faz iab fente gente iab ferias férias iab geito jeito iab gibóia jibóia iab gipe jipe iab ha há iab hezitação hesitação iab hezitar hesitar iab http:\\ http: iab iigor igor iab interesado interessado iab interese interesse iab Irria Iria iab isot isto iab ítens itens iab ja já iab jente gente iab linguiça lingüiça iab linux GNU/Linux iab masi mais iab maz mas iab con com iab mema mesma iab mes mês iab muinto muito iab nao não iab nehum nenhum iab nenina menina iab noã não iab no. nº iab N. Nº iab o. º iab obiter obter iab observacao observação iab ons nos iab orijem origem iab ospital hospital iab poden podem iab portugu6es português iab potuguês português iab precisan precisam iab própio próprio iab quado quando iab quiz quis iab recizão rescisão iab sanque sangue iab sao são iab sen sem iab sensivel sensível iab sequéncia seqüência iab significatimente significativam iab sinceranete sinceramente iab sovre sobre iab susseder suceder iab tanbem também iab testo texto iab téxtil têxtil iab tydo tudo iab una uma iab unico único iab utilise utilize iab vega veja iab vivaotux http://vivaotux.blogspot.com iab vja veja iab voc6e você iab wue que iab xave chave iab 1a. 1ª iab 2a. 2ª iab 3a. 3ª iab 4a. 4ª iab 5a. 5ª iab 6a. 6ª iab 7a. 7ª iab 8a. 8ª iab 9a. 9ª iab 10a. 10ª iab 11a. 11ª iab 12a. 12ª iab 13a. 13ª iab 14a. 14ª iab 15a. 15ª " caso o teclado esteja desconfigurado use: "iab 'a á "iab 'A Á "iab 'e é "iab 'E É "iab 'i í "iab 'I Í "iab 'o ó "iab 'O Ó "iab ~a ã "iab ~A Ã "iab ^a â "iab ^A Â "iab `a à "iab `A À "iab ,c ç "iab ,C Ç "iab ^e ê "iab ^E Ê "iab ^o ô "iab ^O Ô "iab ~o õ "iab ~O Õ "iab 'u ú "iab 'U Ú if exists('+autochdir') set autochdir else autocmd BufEnter * silent! lcd %:p:h:gs/ /\\ / endif "autocmd BufEnter * lcd %:p:h autocmd BufReadPost * \ if line("'\"") > 0 && line("'\"") <= line("$") | \ exe "normal g`\"" | \ endif " autocomandos para python augroup python au! BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class au! BufRead,Bufnewfile *.py im :<CR> :<CR><TAB> "autocmd FileType python set textwidth=79 autocmd FileType python filetype indent on let python_highlight_all=1 let python_highlight_builtins=0 let python_highlight_builtins=1 let python_highlight_exceptions=1 let python_highlight_numbers=1 let python_highlight_space_errors=1 augroup end " setando o path do python python << EOF import os import sys import vim for p in sys.path: # Add each directory in sys.path, if it exists. if os.path.isdir(p): # Command 'set' needs backslash before each space. vim.command(r"set path+=%s" % (p.replace(" ", r"\ "))) EOF " fim da seção do path do python augroup html " au! <--> Remove all html autocommands au! au BufNewFile,BufRead *.html,*.shtml,*.htm set ft=html "au BufNewFile,BufRead,BufEnter *.html,*.shtml,*.htm so ~/.vim/skel/skel.html au BufNewFile *.html 0r ~/.vim/skel/skel.html "au BufNewFile *.html,*.shtml,*.htm /body/+ au BufNewFile,BufRead *.html,*.shtml,*.htm set noautoindent au BufNewFile,BufRead *.html,*.shtml,*.htm set nolist augroup end map <M-right> :wn<cr> map <M-left> :wp<cr> " carregamento do plugin closetag au Filetype html,xml,xsl source ~/.vim/plugin/closetag.vim augroup css au Bufnewfile,BufRead *.css set ft=css au BufNewFile *.css 0r ~/.vim/skel/template.css "autocmd FileType css set omnifunc=csscomplete#CompleteCSS augroup end " (window)Define o número de linhas deslocadas com os comandos " ^B (Ctrl+B) e ^F (Ctrl+F) setlocal window=5 " " fazer rolagem no documento " tem que estar em modo normal! map <C-Down> <c-d> map <C-Up> <c-u> " " define a cor para o menu contextual dos complementos highlight Pmenu ctermbg=13 guibg=Gray highlight PmenuSel ctermbg=7 guibg=DarkBlue guifg=White highlight PmenuSbar ctermbg=7 guibg=DarkGray highlight PmenuThumb guibg=Black " " MinusculasMaiusculas: converte a primeira letra de cada frase p/MAIUSCULAS map ,mm :set noic<cr> \:%s/\(\(\([.!?]\s*\\|^\s*\)\n^\\|[.?!-] \)\s*"\?\s*\)\([a-zàáéóú]\)/\1\U\4/g<cr> " " Coloca em maiúsculo a primeira letra de cada sentença map ,u :%s/\([.!?]\)\(\_s\+\)\(\a\)/\1\2\U\3/g<cr> " " um destaque especial para MinhasNotas highlight MinhasNotas ctermbg=Yellow ctermfg=red guibg=Yellow guifg=red match MinhasNotas /[Nn]otas\?:\?/ " "Auto formatação para parágrafos map <F8> gqap " " mapeamento para abrir e fechar folders em modo normal usando " a barra de espaços -- zR abre todos os folders nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR> "nmap <space> : " o mapeamento abaixo coloca e retira a numeração " o sistema alterna a numeração para ativa ou desativada map <F11> <esc>:set invnu<cr> map <S-F12> <esc>:dig<cr> " mostra os digrafos do tipo Word® " for txt, autoformat and wrap text at 70 chars. autocmd BufNewFile,BufRead *.txt set wrapmargin=70 textwidth=70 map <BS> X " vim:foldmethod=marker:tw=78:ts=3
-
∞ Stick this in your .vimrc if your designers leave tabs in their css.
:autocmd FileType css set noexpandtab
-
∞ Save a file edited in VIm without the needed permissions
:w !sudo tee %
-
∞ vim: Remotely write vi buffer to remote host
:Nwrite scp://user@host//home/cmwise/Desktop/xx.java
-
∞ parser2.php
<?php require_once('XML/Parser.php'); error_reporting(E_ALL); define('OUT_PATH', 'out/'); define('TAGS_PATH', 'out/tags'); $entities = array( '<' => '<', '>' => '>', '&' => '&', '"' => '"', ''' => '"', ); $tags = array(); function load_entities($path) { global $entities; $data = file_get_contents($path); preg_match_all('/<!ENTITY\s+(\S+)\s+(["\'])(.*?)\\2>/sm', $data, $regs, PREG_SET_ORDER); //print_r($regs); foreach ($regs as $r) { $entities['&' . $r[1] . ';'] = $r[3]; } } function array_top($arr) { $c = count($arr); if ($c == 0) return null; return $arr[$c-1]; } class Parser extends XML_Parser { var $_elStack = array(); var $_cdata = ''; var $manual = array(); var $paratext = ''; var $methodname = ''; var $methodtype = ''; function Parser() { $this->folding = false; $this->XML_Parser(); } function format_function_ref($func) { return '|' . $func . '|'; } function format_param_ref($param) { return '{' . $param . '}'; } function format_text($text) { return wordwrap( preg_replace('/\s+/', ' ', trim($text)), 78 ); } function format_tag($tag) { $tmp = sprintf("%78s", '*php:' . $tag . '*'); $this->tag = '/^' . $tmp . '$/'; return $tmp; } function format_title($title, $desc) { return $this->format_text(preg_replace('/\s+/', ' ', trim($title . ' -- ' . $desc))); } function format_help_tag($title) { global $tags; if (isset($tags[$title])) { $i = '#' . ++$tags[$title]; } else { $tags[$title] = 1; $i = ''; } return sprintf("%78s", '*' . $title . $i . '*'); } /* function format_description($name, $desc) { $name = '*php:' . $name . '()*'; return sprintf("%78s\n%s", $name, wordwrap('' . trim(ucwords($desc)), 78)); } */ function format_proto($type, $name, $param) { $text = ' ' . $type . ' ' . $name .'('; $opt = 0; $c = count($param); for ($i=0; $i<$c; $i++) { $p = $param[$i]; if ($p[2]) { if ($i > 0) { $text .= ' '; } $text .= '['; $opt++; } if ($i > 0) { $text .= ', '; } $text .= $p[0] . ' ' . $p[1]; } for ($i=0; $i<$opt; $i++) { $text .= ']'; } $text .= ')~'; return $text; } function format_code($text) { /* return ' ' . str_repeat( '..', 34) . "\n : " . preg_replace('/\r?\n/', "\n : ", trim($text)); */ return preg_replace( '/^\s*<\?php\s*$/m', '<?php >', preg_replace( '/^\s+\?>/m', '?>', ' ' . trim( preg_replace( '/\r?\n/', "\n ", $text ) ) ) ); } function startHandler($xp, $elem, &$attribs) { if ($this->_cdata) { $top = array_top($this->_elStack); $el = $top[0]; $attr = $top[1]; $this->handleElement($el, $attr, $this->_cdata, false); } array_push($this->_elStack, array($elem, $attribs)); $this->_cdata = ''; } function endHandler($xp, $elem) { $top = array_top($this->_elStack); $el = $top[0]; $attr = $top[1]; $this->handleElement($el, $attr, $this->_cdata, true); array_pop($this->_elStack); $this->_cdata = ''; } function cdataHandler($xp, $data) { $this->_cdata .= $data; } function inElement($name) { $c = count($this->_elStack); //print_r($this->_elStack); for ($i=$c-1; $i>=0; $i--) { if ($this->_elStack[$i][0] == $name) { return true; } } return false; } function handleElement($name, $attr, $data, $final) { if ($this->inElement('refnamediv')) { if ($name == 'refname') { $this->refname = trim($data); } elseif ($this->inElement('refpurpose')) { $this->refpurpose = isset($this->refpurpose) ? $this->refpurpose . $data : $data; } if (($name == 'refnamediv') && $final) { //$this->paragraphlist[] = $this->format_help_tag($this->refname); $this->paragraphlist[] = $this->format_title($this->refname, $this->refpurpose); } } elseif ($this->inElement('methodsynopsis')) { if ($this->inElement('methodparam')) { if ($name == 'type') { $this->paramtype = trim($data); } elseif ($name == 'parameter') { $this->paramname = trim($data); } elseif (($name == 'methodparam') && $final) { $this->paramlist[] = array( isset($this->paramtype) ? trim($this->paramtype) : '', trim($this->paramname), isset($attr['choice']) && ($attr['choice'] == 'opt') ); } } elseif ($name == 'type') { $this->methodtype = trim($data); } elseif ($name == 'methodname') { $this->methodname = trim($data); } elseif (($name == 'methodsynopsis') && $final) { $this->proto = $this->format_proto( $this->methodtype, $this->methodname, isset($this->paramlist) ? $this->paramlist : array()); $this->paragraphlist[] = $this->proto; } } elseif ($this->inElement('programlisting') || $this->inElement('screen') || $this->inElement('literallayout')) { if (!ctype_space($this->paratext)) { $this->paragraphlist[] = $this->format_text($this->paratext); $this->paratext = ''; } $this->paragraphlist[] = $this->format_code($data); } elseif ($this->inElement('para') || $this->inElement('simpara') || $this->inElement('example')) { if ($name == 'function') { $this->paratext .= $this->format_function_ref($data); } elseif ($name == 'parameter') { $this->paratext .= $this->format_param_ref($data); } elseif (($name == 'para' || $name == 'simpara' || $name == 'example') && $final) { if (!ctype_space($data)) { $this->paratext .= $data; } if (!ctype_space($this->paratext)) $this->paragraphlist[] = $this->format_text($this->paratext); $this->paratext = ''; } else { $this->paratext .= $data; } } } } function process_all($path) { if ($dir = opendir($path)) { while ($fname = readdir($dir)) { $fname2 = $path . '/' . $fname; if (is_dir($fname2) && ($fname != '.') && ($fname != '..') && ($fname != 'CVS')) { process_all($fname2); echo "recursing into $fname2\n"; } elseif (preg_match('#[\/\\\\]\w+[\/\\\\]functions[\/\\\\]([a-zA-Z0-9\._-]+)\.xml$#', $fname2, $regs)) { process_file($fname2, OUT_PATH . $regs[1] . '.txt'); } } closedir($dir); } } function process_file($in, $out) { global $entities; echo "processing $in\n"; $p =& new Parser(); $data = file_get_contents($in); $data = strtr($data, $entities); $data = strtr($data, $entities); /* $data = strtr($data, array( '&true;' => 'TRUE', '&false;' => 'FALSE', '&null;' => 'NULL', '<' => '<', '>' => '>', '&' => '&', '"' => '"', ''' => '"', '°' => '°', '&return.success;' => 'Returns TRUE on success or FALSE on failure.', '&warn.undocumented.func;' => '', '¬e.gd.2;' => 'This function requires GD 2.0.1 or later.', '&php.ini;' => 'php.ini', '&url.mysql.docs.error;' => 'http://dev.mysql.com/doc/mysql/en/Error-returns.html', '&example.outputs;' => 'The above example will output something similar to:' )); */ $data = preg_replace('/\&([^;]+;)/', '&\\1', $data); $res = $p->setInputString($data); $res = $p->parse(); $fp = fopen($out, 'wb') or die("Could not open $out!"); fwrite($fp, implode("\n\n", $p->paragraphlist)); fwrite($fp, "\n\nvim:ft=help:\n"); fclose($fp); if ($p->refname) { /* if (!empty($p->proto)) $tag = '/^' . $p->proto . '$/'; else $tag = '1'; */ $tag = '/^' . $p->refname; $fp = fopen(TAGS_PATH, 'ab') or die("Could not open tags!"); fwrite($fp, $p->refname . "\t" . basename($out) . "\t" . $tag . "\n"); fclose($fp); } } $fp = fopen(TAGS_PATH, 'wb') or die("Could not open tags!"); //fwrite($fp, "!_TAG_FILE_FORMAT 2\n"); //fwrite($fp, "!_TAG_FILE_SORTED 1\n"); fclose($fp); load_entities('phpdoc/doc-base/entities/global.ent'); load_entities('phpdoc/en/language-defs.ent'); load_entities('phpdoc/en/language-snippets.ent'); load_entities('phpdoc/en/livedocs.ent'); load_entities('phpdoc/en/contributors.ent'); //print_r($entities['&example.outputs;']); //print_r($entities); process_all('phpdoc/en/reference'); //process_all('d:/htdocs/livedocs/phpdoc/en/reference'); echo "sorting tags\n"; system('sort ' . TAGS_PATH. ' -o ' . TAGS_PATH); ?>
-
∞ auto indent for python files
" indent.vimrc autocmd BufRead * python setIndentation() python << EOF def setIndentation(): import vim maxSearch = 1000 # max number of lines to search through indentSpaces = None cb = vim.current.buffer indentCount = { ' ' : 0, '\t' : 0 } justSawDefOrClassLine = 0 for i in xrange(0, min(maxSearch, len(cb))): line = cb[i] if not line: continue # count spaces after a class or def line if justSawDefOrClassLine: justSawDefOrClassLine = 0 if line[0] == ' ': indentSpaces = 0 for c in line: if c != ' ': break indentSpaces = indentSpaces + 1 if line[:4] == 'def ' or line[:6] == 'class ': justSawDefOrClassLine = 1 # add to tab versus space count if line[0] in ' \t': indentCount[line[0]] = indentCount.get(line[0], 0) + 1 # more lines started with space if indentCount[' '] > indentCount['\t']: vim.command('set smarttab tabstop=8 expandtab') if indentSpaces: vim.command('set ts=%d sw=%d' % ( indentSpaces, indentSpaces )) # more lines started with tab else: vim.command('set softtabstop=3 ts=3 sw=3') EOF
-
∞ função para incrementar números no vim
" site: http://rayninfo.co.uk/vimtips.html " advanced incrementing (really useful) " put following in _vimrc let g:I=0 function! INC(increment) let g:I =g:I + a:increment return g:I endfunction " eg create list starting from 223 incrementing by 5 between markers a,b :let I=223 :'a,'bs/^/\=INC(5)/ " create a map for INC cab viminc :let I=223 \| 'a,'bs/$/\=INC(5)/
-
∞ function vim+python for commit every time you save file
" requires vim-python and python-git function! CommitFile() python << EOF import vim, git curfile = vim.current.buffer.name if curfile: try: repo = git.Repo(curfile) repo.git.add(curfile) repo.git.commit(m='Update') except (git.InvalidGitRepositoryError, git.GitCommandError): pass EOF endfunction au BufWritePost * call CommitFile()
-
∞ Replacing stuff in vim
:%s/old/new/g :%s/domainbeats\1.com/domainbeats\.com/g :%s/home\/content\/t\/r\/i\/foo/home\/73941\/domains\/bar\.com\/html/g
-
∞ .vimrc atual
"--------------------------------------------------------------------------- " Use VIM padrão é muito melhor " Valores padrão para algumas opções são adequados ao Vim, não Vi. "--------------------------------------------------------------------------- set nocompatible "--------------------------------------------------------------------------- " Numerando as linhas do arquivo, isto é, qualquer arquivo carregado é " Editado com a numeração de linhas ligada "--------------------------------------------------------------------------- set number "--------------------------------------------------------------------------- " Ligando configurações de cor, isto é, faz com que o vim busque no " diretório /usr/share/vim/vim62/syntax os arquivos de configuração de " cores de acordo com o tipo de arquivo que é aberto "--------------------------------------------------------------------------- syntax on "--------------------------------------------------------------------------- " Se você tem certos textos que sempre tem que ficar digitando, como " seu nome completo, seu email, seu endereço, faça abreviações, que são " completadas automaticamente enquanto você as digita. " Use abreviações para textos normais, para comandos use mapeamentos. "-------------------------------------------------------------------------- iab linux GNU/Linux iab gnome GNOME iab kde KDE iab latex LaTeX "--------------------------------------------------------------------------- " Salvar e/ou sair de um arquivo, é comum na pressa digitar o `w` ou `q` " em maiúsculas, pois você ainda não soltou o dedo do shift que apertou " para fazer os dois pontos :, mas isso tem solução, basta usarmos " abreviações para a linha de comando (Cab) "--------------------------------------------------------------------------- cab W w cab Wq wq cab wQ wq cab WQ wq cab Q q "--------------------------------------------------------------------------- " Embaralha a tela para evitar bisbilhoteiros "--------------------------------------------------------------------------- map <F4> ggVGg? "--------------------------------------------------------------------------- " Permite Identar Bloco de Código " No modo visual, selecionar o bloco " TAB para identar > e shift+TAB para identar < "--------------------------------------------------------------------------- vnoremap < <gv vnoremap > >gv vmap <TAB> > vmap <S-TAB> < imap <S-TAB> <ESC><<i "--------------------------------------------------------------------------- " Copiar em modo visual " possibilita colar em outra janela " Vim/GVim com o uso do Y para copiar, guarda em um buffer dele. "--------------------------------------------------------------------------- vmap <F5> "+y "---------------------------------------------------------------------------- " Esquema de cores para utilizar no vim "---------------------------------------------------------------------------- colorscheme elflord "--------------------------------------------------------------------------- " Antes de sobrescrever um arquivo mantém um backup do mesmo " Por exemplo, após salvar um arquivo de nome Alfa.txt, o vim cria uo " outro arquivo chamado Alfa.txt~ com a configuração anterior do arquivo " antes do mesmo ser alterado "--------------------------------------------------------------------------- set backup "--------------------------------------------------------------------------- " Usar a pasta pessoal de backup " É onde será escrito o arquivo *~ " Nessa configuração, primeiro usa o diretório ~/.vim/.backup, " se não existir usa o diretório corrente "--------------------------------------------------------------------------- set backupdir=~/.vim/backup/ "--------------------------------------------------------------------------- " Para aumentar a esperteza e memorização do vim, podemos ter um arquivo " ~/.viminfo que guardará dados úteis como seu histórico de pesquisas /, " linha de comando :, marcas `, registradores, entre outros. Então com o " viminfo é possível copiar uma linha qualquer (yy), sair do arquivo, " abrir um OUTRO arquivo e colar (p) aquela linha copiada anteriormente. " Você pode inclusive nesse intervalo desligar a máquina e ficar um mês " de férias, que ao voltar o vim ainda saberá qual foi a linha copiada. " " A segunda linha é uma gambiarra para que ao abrir um arquivo, o cursor " já fique na posição que estava na última vez que ele foi editado. o " viminfo guarda a posição de TODOS os arquivos que você editou. " " http://www.vivaolinux.com.br/script/Um-.vimrc-massudo. (necessário '.' no final). "--------------------------------------------------------------------------- set viminfo='10,\"30,:20,%,n~/.viminfo au BufReadPost * if line("'\"")|execute("normal `\"")|endif "--------------------------------------------------------------------------- " Permite apagar identações, final e início de linhas " com backspace no modo de inserção. " " http://maratona.tiagomadeira.com/links-vimrc-e-apostila-da-ufmg/ "--------------------------------------------------------------------------- set backspace=indent,eol,start "--------------------------------------------------------------------------- " Auto identação "--------------------------------------------------------------------------- set ai "---------------------------------------------------------------------------- " tabstop: número de colunas para o comando <TAB> " A tecla TAB no vim vem padronizada com 8 espaços, sendo assim, quando " editar um código em c, c++, pascal ou outra linguagem qualquer o texto " do código torna-se algo meio confuso, principalmente quando o código é " longo e possui inúmeros escopos. Para tanto, podemos mudar o tamanho do " TAB, isto é do número de espaços gerados pelo mesmo, utilizando o comando " 'set tabstop=4' que transforma o tamanho do TAB de 8 para 4. "---------------------------------------------------------------------------- set ts=4 "---------------------------------------------------------------------------- " Dica para programadores: Comentários num programa são " excelentes, mas na hora da sua manutenção, eles podem " atrapalhar, pois você queria ver só o código. " " Para resolver este problema, vamos fazer um truque no vim. Que tal se " pintarmos os comentários de preto para que fiquem invisíveis? Podemos " fazer isso redefinindo o componente da cor da sintaxe. ah! e quem usa " fundo branco vai ter que trocar 'black' por 'white'. " " Ainda criamos uma função vim pra fazer o serviço. " a CommOnOff() oculta/mostra os comentários, alternando. Resumão do " que ela faz é: se a variável global 'hiddcomm' não existir, a cria e " oculta os comentários. Se já existir, restaura os comentários. Por fim " definimos um mapeamento esperto no F11 para chamar nossa função. " http://www.vivaolinux.com.br/script/Um-.vimrc-massudo. (necessário '.' no final). "---------------------------------------------------------------------------- fu! CommOnOff() if !exists('g:hiddcomm') let g:hiddcomm=1 | hi Comment ctermfg=black guifg=black else unlet g:hiddcomm | hi Comment ctermfg=cyan guifg=cyan term=bold endif endfu map <F11> :call CommOnOff()<cr> "---------------------------------------------------------------------------- " Faz resultados da busca aparecerem no meio da tela "---------------------------------------------------------------------------- nmap n nzz nmap N Nzz nmap * *zz nmap # #zz nmap g* g*zz nmap g# g#zz" "---------------------------------------------------------------------------- " Busca colorida em amarelho/fundo preto "---------------------------------------------------------------------------- hi Search ctermbg=yellow ctermfg=black "---------------------------------------------------------------------------- " Ignora os tipos de arquivos abaixo "---------------------------------------------------------------------------- set wildignore=*.o,*.obj,*.bak,*.exe "---------------------------------------------------------------------------- " Para completar com TAB da mesma forma que o bash faz "---------------------------------------------------------------------------- set wildmode=longest,list "---------------------------------------------------------------------------- " Opções espertas de busca "---------------------------------------------------------------------------- set is hls ic scs magic
-
∞ Round decimals
# Extends Float class to make it possible rounding wiht more decimals Float.class_eval do alias_method :original_round, :round def round(decs = 0) if decs == 0 self.original_round elsif decs > 0 decs = decs.to_i (self * 10 ** decs).original_round.to_f / 10 ** decs else raise ArgumentError, "You can't pass negative arguments" end end end ############################ # Test require 'test/unit' require 'round' # Unit Tests class RoundTest < Test::Unit::TestCase def test_round_1_decimal assert_equal 12.6, 12.56.round(1) assert_equal 12.5, 12.53.round(1) end def test_no_decimals assert_equal 5.0, 5.4.round, "Debe ser 5" assert_equal 6, 5.5.round assert_equal 5, 5.0.round assert_equal 5.class, 5.12.round.class, "Should return a Fixnum class" end def test_negative assert_equal -12.15, -12.153.round(2) assert_equal -12.6, -12.59.round(1) end def test_exception_negative_value assert_raise ArgumentError do 12.532.round(-1) end end end
-
∞ Vim: Replace innerHTML inside next (HTML)-Tag
cit
-
∞ snippet LaTeX para snipMate
# \begin{}...\end{} snippet begin \begin{${1:env}} ${2} \end{$1} # Tabular snippet tab \begin{table}[htb] \begin{center} \caption{${1:Legenda}} \label{tb:${2:nome}} \newcommand{\mc}[3]{\multicolumn{#1}{#2}{#3}} \newcommand{\mr}[3]{\multirow{#1}{#2}{#3}} \begin{tabular}{${2:ll}} \hline ${3} & \\ \cline{2-3} & \\ \hline & \\ & \\ \hline \end{tabular} \end{center} \end{table} ${4} # Subfigure : uma sobre a outra snippet subfig \begin{figure}[htp] \begin{center} \subfigure[]{\label{fig:${1:nomea}} \includegraphics[width=${2:12cm}]{${3:fig/arquivo}}} ${4:\\} \subfigure[]{\label{fig:${5:nomeb}} \includegraphics[width=${6:12cm}]{${7:fig/arquivo}}} \end{center} \caption{${8:Legenda}} \label{fig:${9:nome}} \end{figure} ${10} # More one subfig snippet sfigadd \subfigure[]{\label{fig:${1:nomea}} \includegraphics[width=${2:12cm}]{${3:fig/arquivo}}} ${4:\\} # Figure snippet fig \begin{figure}[htp] \centering \includegraphics[width=${1:12cm}]{${2:fig/arquivo}}} \caption{${3:Legenda}} \label{fig:${4:nome}} \end{figure} ${5} # Equation snippet eqn \begin{equation} ${1} \label{eq:} \end{equation} snippet eqa \begin{eqnarray} ${1} &=& ${2} \label{eq:} \end{eqnarray} # Unnumbered Equation snippet eqd $ ${1} $ # Enumerate snippet enum \begin{enumerate} \item ${1} \end{enumerate} # Itemize snippet itemize \begin{itemize} \item ${1} \end{itemize} # Quote snippet quote \begin{quote} ${1} \end{quote} # Description snippet desc \begin{description} \item[${1}] ${2} \end{description} # Chapter snippet cha \chapter{${1:chapter name}} \label{ch:${2}} ${3} # Section snippet sec \section{${1:section name}} % bsec \label{sec:${2}} ${3} % endsec # Sub Section snippet sub \subsection{${1:subsection name}} \label{sub:${2}} ${3} # Sub Sub Section snippet subs \subsubsection{${1:subsubsection name}} \label{subsub:${2}} ${3} # Paragraph snippet par \paragraph{${1:paragraph name}} \label{par:${2:$1}} ${3} # Sub Paragraph snippet subp \subparagraph{${1:subparagraph name}} \label{subpar:${2}} ${3} # Item snippet itd \item${1:[description]} ${2} # For references, pt-br snippet refcha capítulo~\ref{${1:fig:}} ${2} snippet reffig figura~\ref{${1:fig:}} ${2} snippet reftab tabela~\ref{${1:tab:}} ${2} snippet refsec seção~\ref{${1:sec:}} ${2} snippet refpag página~\pageref{${1}} ${2} # For references, en snippet refchaen chapter~\ref{${1:fig:}} ${2} snippet reffigen figure~\ref{${1:fig:}} ${2} snippet reftaben table~\ref{${1:tab:}} ${2} snippet refsecen section~\ref{${1:sec:}} ${2} snippet refpagen page~\pageref{${1}} ${2} # For bib snippet citen ${1:nome}~\cite{${2}} ${3} snippet cite ~\cite{${1}} ${2} # Verbartim snippet verbatim \begin{verbartim} ${1} \end{verbartim} ${2} snippet verb \verb|${1}| ${2} snippet lrp \left(${1} \right) snippet lrc \left[${1} \right] snippet lrb \left\lbrace ${1}\right\rbrace snippet lra \left\langle ${1} \right\rangle snippet ldot \left. snippet rdot \right. -
∞ Arquivo .vimrc
" **************************************************************************** " * File: .vimrc " * Author: J. F. Mitre <jfmitre (at) gmail.com> " * Url: <URL:http://jfmitre.com, http://notasemcfd.blogspot.com> " * Last Update: Qua 03 Jun 2009 15:31:23 BRT " * Created: Sex 22 Mai 2009 10:01:22 BRT " * Installation: - As dotfile drop the file into your $HOME/ folder. " * - In Command line put $vim -U .vimrc. " * License: GNU General Public License v3 " * <http://www.gnu.org/licenses/gpl.html> " * Version: 2.0 " * Notes: Based on the file .vimrc (1.0) made by Ivan Carlos da Silva Lopes " * .vimrc made by Aurelio Marinho Jarga (verde) and " * .vimrc made by Sérgio Luiz Araújo Silva (voyeg3r) " * " **************************************************************************** " Configuração do Ambiente de Edição {{{ " ---------------------------------------------------------------------------- " Use VIM padrão é muito melhor " Valores padrão para algumas opções são adequados ao Vim, não Vi. " ---------------------------------------------------------------------------- set nocompatible " ---------------------------------------------------------------------------- " Definindo o bash para o GNU/Linux " ---------------------------------------------------------------------------- if has("unix") let &shell="bash" set clipboard=autoselect endif " ---------------------------------------------------------------------------- " Numerando as linhas do arquivo, isto é, qualquer arquivo carregado é " Editado com a numeração de linhas ligada " ---------------------------------------------------------------------------- set number " ---------------------------------------------------------------------------- " Permite remover e adicionar o número de linhas " ---------------------------------------------------------------------------- map <C-F11> :set nu!<cr> imap <C-F11> <Esc>:set nu!<cr> " ---------------------------------------------------------------------------- " Exibe o modo atual de operações do VI (Inserção ou comandos) " Mostra o modo que você esta. " ---------------------------------------------------------------------------- set showmode " ---------------------------------------------------------------------------- " Recua cada linha para o mesmo nível da linha superior " ---------------------------------------------------------------------------- set autoindent " ---------------------------------------------------------------------------- " Aqui definimos uma chave para a alternância entre os modos: " " -- INSERT (paste) -- e -- INSERT -- " " O primeiro não segue o padrão de linha indentada enquanto o segundo " é o modo normal de trabalho. Digitar <F2> alterna entre os dois modos " ---------------------------------------------------------------------------- set pastetoggle=<F2> " ---------------------------------------------------------------------------- " régua: mostra a posição do cursor " ---------------------------------------------------------------------------- set ruler " ---------------------------------------------------------------------------- " Caso o arquivo seja modificado FORA do vim ele é atualizado DENTRO do vim " ---------------------------------------------------------------------------- set autoread " ---------------------------------------------------------------------------- " tabstop: número de colunas para o comando <TAB> " A tecla TAB no vim vem padronizada com 8 espaços, sendo assim, quando " editar um código em c, c++, pascal ou outra linguagem qualquer o texto " do código torna-se algo meio confuso, principalmente quando o código é " longo e possui inúmeros escopos. Para tanto, podemos mudar o tamanho do " TAB, isto é do número de espaços gerados pelo mesmo, utilizando o comando " 'set tabstop=3' que transforma o tamanho do TAB de 8 para 3. " ---------------------------------------------------------------------------- set ts=3 " ---------------------------------------------------------------------------- " Tabs são convertidos para espaços por padrão " ---------------------------------------------------------------------------- set expandtab " set noexpandtab " ---------------------------------------------------------------------------- " ShiftWidth: número de colunas deslocadas pelo comando > ou < " ---------------------------------------------------------------------------- set sw=3 " ---------------------------------------------------------------------------- " SHortMessages: encurta as mensagem da régua " ---------------------------------------------------------------------------- " set shm=filmnrwxt " ---------------------------------------------------------------------------- " ShowMatch: Toda vez que você fecha um parêntese, colchete " ou chave, o Vi mostra onde este foi aberto. Caso não haja " nenhum aberto para este, deixa em vermelho parênteses ou " chaves que não têm um par. " ---------------------------------------------------------------------------- set sm " ---------------------------------------------------------------------------- " mostra os comandos sendo executados " ---------------------------------------------------------------------------- set showcmd " ---------------------------------------------------------------------------- " Configurações de filetype " Check :filetype para status atual " ---------------------------------------------------------------------------- filetype on filetype plugin on " filetype indent on " ---------------------------------------------------------------------------- " reporta ações com linhas no rodapé " ---------------------------------------------------------------------------- set report=0 " ---------------------------------------------------------------------------- " Usando <BkSpc> para deletar linha " ---------------------------------------------------------------------------- set backspace=eol,start,indent " ---------------------------------------------------------------------------- " Tecla Backspace volta 4 espaços quando estiver numa indentação. " ---------------------------------------------------------------------------- set softtabstop=3 " ---------------------------------------------------------------------------- " Permite mover com as setas para áreas onde não tem texto. " ---------------------------------------------------------------------------- " set ve=all " ---------------------------------------------------------------------------- " (window) Define o número de linhas deslocadas com os comandos " ^B (Ctrl+B) e ^F (Ctrl+F) " ---------------------------------------------------------------------------- set window=10 " ---------------------------------------------------------------------------- " Define o número de linhas deslocadas com os comandos " ^U (Ctrl+U) e ^D (Ctrl+D) " ---------------------------------------------------------------------------- set scroll=5 " ---------------------------------------------------------------------------- " Em caso de se cometer um comando inválido aciona-se um alarme visual " visual-bells " ---------------------------------------------------------------------------- " set visualbell " ---------------------------------------------------------------------------- " Em caso de se cometer um comando inválido aciona-se um alarme sonoro " error-bells " ---------------------------------------------------------------------------- " Para habilitar " set eb " Para desabilitar set noerrorbells " ---------------------------------------------------------------------------- " Habilita o salvamento automático (parcial ou completo) " ---------------------------------------------------------------------------- " set autowrite " set autowriteall " ---------------------------------------------------------------------------- " Envia mais caracteres ao terminal, melhorando o redraw de janelas. " ---------------------------------------------------------------------------- set ttyfast " ---------------------------------------------------------------------------- " Antes de sobrescrever um arquivo mantém um backup do mesmo " " Por exemplo, após salvar um arquivo de nome Alfa.txt, o vim cria uo " outro arquivo chamado Alfa.txt~ com a configuração anterior do arquivo " antes do mesmo ser alterado " ---------------------------------------------------------------------------- set bk " ---------------------------------------------------------------------------- " Usar a pasta pessoal de backup " É onde será escrito o arquivo *~ " Nessa configuração, primeiro usa o diretório ~/.vim/.backup, se não existir " usa o diretório corrente " ---------------------------------------------------------------------------- set backupdir=~/.vim/.backup/,. " ---------------------------------------------------------------------------- " Habilita a mudança de coluna quando movimenta-se através das linhas " ---------------------------------------------------------------------------- " set startofline " ---------------------------------------------------------------------------- " Diretórios onde o VIM busca por arquivos " ---------------------------------------------------------------------------- set path=.,./include/,/usr/include/,/usr/local/bin/,~/.vim/scripts/ " ---------------------------------------------------------------------------- " Uma configuração interessante da barra de status é defini-la com tamanho de " duas linhas e fundo com cor azul e fonte branca. " ---------------------------------------------------------------------------- " Mostra duas linhas set laststatus=2 " Fundo azul e fonte branca (foi adicionando ao meu código de cores nativas) " highlight StatusLine ctermfg=blue ctermbg=white " ---------------------------------------------------------------------------- " Configurando o formato da régua " Novos arquivos possuem uma data de modificação em um certo dia muito tempo " no passado. Ignore. " ---------------------------------------------------------------------------- " set statusline=%t%m%r%h%w " \%=[FORMATO=%{&ff}] " \[TIPO=%Y] " \[ASCII=%03b] " \[HEX=%02B] " \[\ XY=%04v,%04l] " \[%03P] " set statusline=%<%F%h%m%r%h%w%y\ ft:%{&ft}\ ff:%{&ff}\ " \Modificado:\ %{strftime(\"%a\ %d/%B/%Y\ %H:%M:%S\", " \getftime(expand(\"%:p\")))}%=\ coluna:%04v\ linha:%04l\ " \total:%04L\ hex:%03.3B\ ascii:%03.3b\ %03P\ set statusline=%<%F%h%m%r%h%w%y\ ft:%{&ft}\ ff:%{&ff}\ \Modificado:\ %{strftime(\"%c\",getftime(expand(\"%:p\")))} \%=\ coluna:%04v\ linha:%04l\ \total:%04L\ hex:%03.3B\ ascii:%03.3b\ %03P\ " ---------------------------------------------------------------------------- " Mostra o nome do arquivo na parte superior do prompt " ---------------------------------------------------------------------------- set title " ---------------------------------------------------------------------------- " Alguns tipos de arquivos devem ser ignorados pelo Vim. " ---------------------------------------------------------------------------- set wildignore=*.o,*.obj,*.bak,*.exe,*.dll,*.com,*.class,*.au,*.wav,*.ps,\ \*.avi,*.wmv,*.flv,*.djvu,*.pdf,*.chm,*.dvi,*.svn/,*~ " ---------------------------------------------------------------------------- " Definindo e trabalhando com histórico da linha de comando " ---------------------------------------------------------------------------- set cedit=<Esc> " ---------------------------------------------------------------------------- " (history) Define o tamanho do arquivo de histórico, onde <valor> é o " número de linhas de comandos a serem armazenados (5000). " ---------------------------------------------------------------------------- set hi=5000 " ---------------------------------------------------------------------------- " Guarda posição do cursor e histórico da linha de comando : " ---------------------------------------------------------------------------- set viminfo='100,\"1000,:40,%,n~/.viminfo au BufReadPost * if line("'\"")|execute("normal `\"")|endif autocmd BufReadPost * \ if line("'\"") > 0 && line("'\"") <= line("$") | \ exe "normal g`\"" | \ endif " ---------------------------------------------------------------------------- " Tamanho da barra de título " ---------------------------------------------------------------------------- set titlelen=78 " ---------------------------------------------------------------------------- " Exibe a barra de título no formato configurado " " Exemplo1: " --------- " formato:"nome="NomeArq.EXT [se alterado mostrar +] " set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:~:.:h\")})%)%(\ %a%) " " Exemplos2: " ---------- " set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:p\")})%)%(\ %a%) " ---------------------------------------------------------------------------- " -------------------------- [Formato] --------------------------------------- " [Nome=nome] buffer={current} [Total de linhas=999] ' " ---------------------------------------------------------------------------- " Se editar múltiplos arquivos " ---------------------------------------------------------------------------- " [Nome=nome] buffer={current} [{current} of {max})] [Total de linhas=999] ' " ---------------------------------------------------------------------------- " set titlestring=%<Nome=%t%m%r%h%w " \%= " \BUFFER=%n " \%(\ %a%) " \%28([Total\ de\ linhas=%L]%) set titlestring=%<%F%h%m%r%h%w\ \ \ \ \ \ coluna:%04v\ \ \ \ linha:%04l\ de\ %04L\ \ \ \ %03P\ " ---------------------------------------------------------------------------- " Define qual é o tamanho da margem direita para a quebra de linhas " automáticas, wrapmargin " ---------------------------------------------------------------------------- set wm=10 " ---------------------------------------------------------------------------- " Quando esta opção encontra-se ativa o VIM lê o arquivo, e qualquer " comando de configuração que estiver nas cinco primeiras linhas e cinco " ultimas do arquivo, serão executados. Um exemplo disso são os arquivos " do help, onde as últimas linhas a apresentam a seguinte sintaxe: " 'vim:tw=78:ts=8:ft=help:norl:' " A opção nomodeline assegura que esse recurso estará desabilitado " ---------------------------------------------------------------------------- " set modeline set nomodeline " ---------------------------------------------------------------------------- " Utilizando a barra de espaço para mover uma página " ---------------------------------------------------------------------------- " noremap <Space> <PageDown> " ---------------------------------------------------------------------------- " }}} " Configurações de cores, fonte, visual, etc {{{ " ---------------------------------------------------------------------------- " Ligando configurações de cor, isto é, faz com que o vim busque no " diretório /usr/share/vim/vim62/syntax os arquivos de configuração de " cores de acordo com o tipo de arquivo que é aberto " ---------------------------------------------------------------------------- syntax on " ---------------------------------------------------------------------------- " Sintaxe para fundo escuro (dark) ou claro (light) " ---------------------------------------------------------------------------- set background=dark " set background=light " ---------------------------------------------------------------------------- " Mapeamento para trocar o tipo de background " Pode fazer com que a função SwitchColorSchemes() pare de funcionar " dependendo do tema que estiver sendo usado ao acionar esse mapeamento " Para quem não usa temas, não há qualquer problema. " ---------------------------------------------------------------------------- map <S-F6> <ESC>:set background=light<CR> map <C-S-F6> <ESC>:set background=dark<CR> " ---------------------------------------------------------------------------- " Função para trocar o tema de cores " A primeira linha refere-se ao esquema padrão " ---------------------------------------------------------------------------- colorscheme native function! <SID>SwitchColorSchemes() if g:colors_name == 'native' colorscheme automation elseif g:colors_name == 'automation' colorscheme moria elseif g:colors_name == 'moria' colorscheme desert elseif g:colors_name == 'desert' colorscheme colorful elseif g:colors_name == 'colorful' colorscheme navajo-night elseif g:colors_name == 'navajo-night' colorscheme bmichaelsen elseif g:colors_name == 'bmichaelsen' colorscheme impact elseif g:colors_name == 'impact' colorscheme ir_black elseif g:colors_name == 'ir_black' set background=dark colorscheme native endif endfunction map <F6> :call <SID>SwitchColorSchemes()<CR>:echo g:colors_name<CR> " ---------------------------------------------------------------------------- " Define a cor para o menu contextual dos complementos " ---------------------------------------------------------------------------- " highlight Pmenu ctermbg=13 guibg=Gray " highlight PmenuSel ctermbg=7 guibg=DarkBlue guifg=White " highlight PmenuSbar ctermbg=7 guibg=DarkGray " highlight PmenuThumb guibg=Black " ---------------------------------------------------------------------------- " Cor da numeração lateral " ---------------------------------------------------------------------------- " hi LineNr guifg=pink ctermfg=lightMagenta hi LineNr guifg=green ctermfg=lightGreen " ---------------------------------------------------------------------------- " Destaca a linha e coluna sobre o cursor e define a cor " Não há como especificar a cor e conseguir algo bom para todos os ambientes " ---------------------------------------------------------------------------- set cursorline " hi CursorLine ctermbg=blue cterm=none " hi CursorLine ctermbg=black cterm=none " set cursorcolumn " hi CursorColumn ctermbg=4 " ---------------------------------------------------------------------------- " Configuração de fonte (tamanho e nome) para o GVim " ---------------------------------------------------------------------------- if has("gui_running") if has("gui_gtk2") " Para GTK2 " Ajustando o tamanho da fonte de acordo com o tamanho da resolução " Adicionando no ~/.bashrc as linhas : " #-------------------------------------------------------------------- " # Definindo variável de screen para o vim " #-------------------------------------------------------------------- " export SCREENSIZE=$(xdpyinfo | grep 'dim'\ " | sed -e 's/x.*//g' -e 's/^.*[a-z]: *//g') " #-------------------------------------------------------------------- " A beleza dessas linhas é que elas observam o tamanho da resolução do " computador cliente, e não do host. Apenas o tamanho horizontal é " utilizado como referência, ou seja, 1280x1024, apenas 1280 é " verificado para determinar o tamanho da fonte. Isso não funciona bem " em monitores cujo o maior tamanho seja o vertical. if exists("$SCREENSIZE") " se existe a variável $SCREENSIZE if ($SCREENSIZE > 1300) " se $SCREENSIZE é maior que 1300 set guifont=monospace\ 14 elseif ($SCREENSIZE < 850) " se $SCREENSIZE é menor que 850 set guifont=monospace\ 8 else " se $SCREENSIZE é maior que 850 e menor que 1300 set guifont=monospace\ 10 endif " Existe SCREENSIZE, e com base nele define-se guifont else " caso a variável $SCREENSIZE não exista, use... set guifont=monospace\ 10 endif " Define tamanho se existe ou não $SCREENSIZE elseif has("x11") " Para GTK1 set guifont=*-lucidatypewriter-medium-r-normal-*-*-180-*-*-m-*-* elseif has("gui_win32") " Para Windows set guifont=Luxi_Mono:h12:cANSI else " Para todos as outras gui use ... set guifont=monospace\ 12 endif " Conclui a verificação do tipo de interface gráfica endif " Conclui sobre a existência de uma interface gráfica " ---------------------------------------------------------------------------- " }}} " Configurações de Dobras (folders) {{{ " ---------------------------------------------------------------------------- " Ajuda: " zf ................ operador para criar folders " zfis .............. cria um folder da sentença atual " zd ................ delete folder " zo ................ abrir dobra sob o cursor " zc ................ fechar dobra sob o cursor " zv ................ visualizar linha sob o cursor " zR ................ abre todos os folders " zM ................ fecha todos os folders " ---------------------------------------------------------------------------- " Método das dobras " ---------------------------------------------------------------------------- set foldmethod=marker " ---------------------------------------------------------------------------- " Dobra padrão " Quando cria-se ou deleta-se uma dobra, são esses caracteres que são " adicionados ou removidos do texto. " ---------------------------------------------------------------------------- set fmr={{{,}}} " ---------------------------------------------------------------------------- " Mapeamento para dobras " ---------------------------------------------------------------------------- " Abrindo uma dobra map + zo " Fechando um certa dobra map - zc " Abrindo todo mundo map ++ zR " Fechando todo mundo map -- zM " ---------------------------------------------------------------------------- " folderlevel define quantos níveis de dobras ficam abertos por padrão " ---------------------------------------------------------------------------- set foldlevel=0 " ---------------------------------------------------------------------------- " Barra de espaço abre e fecha folders " ---------------------------------------------------------------------------- nnoremap <space> @=((foldclosed(line(".")) < 0) ? 'zc' : 'zo')<CR> " ---------------------------------------------------------------------------- " }}} " Configurando a busca {{{ " ---------------------------------------------------------------------------- " Ativa o recurso de colorir, dando realce a pesquisa de palavra(s) " que estiver em andamento. O hlsearch abreviado chama-se hls " ---------------------------------------------------------------------------- set hlsearch " ---------------------------------------------------------------------------- " O método de busca pode ser incrementado com a adição do comando " incsearch". A pesquisa torna-se diferenciada e dinâmica em tempo de " pesquisa, isto é, antes do usuário entrar com o comando <enter> a fim " de buscar os resultados, os mesmos já aparecerão em sua tela. " ---------------------------------------------------------------------------- set incsearch " ---------------------------------------------------------------------------- " Se começar uma busca em maiúsculo ele habilita o case " ---------------------------------------------------------------------------- " set smartcase " ---------------------------------------------------------------------------- " Que tal trocar a cor do texto ? " daquela seleção que aparece quando você procura algo com o comando " / ? " é fácil, basta definir a cor do componente da sintaxe. Ah sim, a " opção hls (veja acima) deve estar ativa. " você pode colocar as cores que quiser, em inglês. Note que é " ctermBG e FG, de background e foreground (fundo e letra). E veja " também que o IncSearch (busca enquanto você digita) é invertido! " ---------------------------------------------------------------------------- " hi Search ctermbg=yellow ctermfg=red " hi IncSearch ctermbg=green ctermfg=cyan " ---------------------------------------------------------------------------- " No vim temos diversas opções para modificar seu comportamento " através do comando set. para ver todas as opções disponíveis, faça " :set all. Diversas opções já vêem ligadas por padrão, então " vamos mais opções de busca " IncrementedSearch, HighLightedSearch, IgnoreCase e SmartCaSe " ---------------------------------------------------------------------------- set ic scs " ---------------------------------------------------------------------------- " Limpando o registro de buscas " ---------------------------------------------------------------------------- nno <S-F11> <Esc>:let @/=""<CR> " ---------------------------------------------------------------------------- " }}} " Abreviações, correções e jeitinhos para o modo de inserção {{{ " ---------------------------------------------------------------------------- " Mapeando abreviações para o modo de inserção " ---------------------------------------------------------------------------- iab linux GNU/Linux iab gnome GNOME iab kde KDE iab latex LaTeX " ---------------------------------------------------------------------------- " Mapeando correções para o modo de inserção " ---------------------------------------------------------------------------- iab tambem também iab vc você iab assenção ascenção iab assougue açougue iab corrijir corrigir iab definitamente definitivamente iab deshonestidade desonestidade iab díficil difícil iab distingeu distingue iab ecessão exceção iab ecessões exceções iab excessão exceção iab Excesões exceções iab excurção excursão iab exijir exigir iab nao não iab noã não iab portugu6es português iab portugês português iab portugues português iab dividos divididos iab lisensa licença iab licenssa licença iab licensa licença iab Licensa Licença iab drives drivers iab drive driver iab Drive Driver iab Drives Drivers " ---------------------------------------------------------------------------- " caso o teclado esteja desconfigurado use: " ---------------------------------------------------------------------------- " iab 'a á " iab 'A Á " iab 'e é " iab 'E É " iab 'i í " iab 'I Í " iab 'o ó " iab 'O Ó " iab ~a ã " iab ~A Ã " iab ^a â " iab ^A Â " iab `a à " iab `A À " iab ,c ç " iab ,C Ç " iab ^e ê " iab ^E Ê " iab ^o ô " iab ^O Ô " iab ~o õ " iab ~O Õ " iab 'u ú " iab 'U Ú" " }}} " Configurando o dicionário e corretor ortográfico {{{ " ---------------------------------------------------------------------------- " Utilizando o dicionário do aspell " ---------------------------------------------------------------------------- cmap ckBR w!<CR>:!aspell check %<CR>:e! %<CR> cmap ckEN w!<CR>:!aspell --lang=en check %<CR>:e! %<CR> " ---------------------------------------------------------------------------- " Verificação automática do arquivo (spell check interno ao vim) " Para baixar o dicionário: http://www.broffice.org/verortografico/baixar " Descompacte e no diretório abra o vim. Nele execute: " :mkspell pt pt_BR " cp pt*.spl ~/.vim/spell/ " Adicione no .vimrc as linhas: " ---------------------------------------------------------------------------- set spelllang=pt map <S-F8> :set spelllang=en<CR> map <C-S-F8> :set spelllang=pt<CR> set nospell nnoremap <C-F8> :set spell! spell?<CR> " ---------------------------------------------------------------------------- " Para habilitar a identificação automática das palavras erradas, por tipo de " arquivo, use: " ---------------------------------------------------------------------------- " autocmd BufNewFile,BufRead *.txt setl spell spl=pt " ---------------------------------------------------------------------------- " Plugin vimspell. Somente foi implementado devido ao funcionamento pouco " correto do plugin interno do vim. " URL: http://www.vim.org/scripts/script.php?script_id=465 " ---------------------------------------------------------------------------- " Para desabilitar o vimspell (habilite apenas quando for usar). let loaded_vimspell = 1 " Configurando a coloração de sintaxe highlight link SpellErrors Error " Usando o aspell (opções: aspell e ispell) let spell_executable = "aspell" " Restrigindo os idiomas disponíveis " Para o aspell let spell_language_list = "pt_BR,en" " Para o ispell " let spell_language_list = "brazilian,english" " Não quero auto correção ativa. Aguarde eu chamar o programa let spell_auto_type = "none" " ---------------------------------------------------------------------------- " Dicionário para procurar o auto-complemento de palavras " ---------------------------------------------------------------------------- set dictionary=~/.vim/dict/words.dic " ---------------------------------------------------------------------------- " Auto-complemento de palavras " ---------------------------------------------------------------------------- " Exemplo de como usar o dicionário com mapeamento: " (1) dentro do modo de inserção -- INSERT -- " (2) posicione o cursor sob a palavra a ser completada " (3) ligar dicionário ao pressionar a seqüência "<C-D>" imap <C-D> <c-x><c-k> " (4) busca palavra no arquivo corrente "<F8>" imap <F8> <c-x><c-i> " (5) o <C-N> trava meu computador, assim, eliminarei ele imap <C-N> <C-P> " ---------------------------------------------------------------------------- " Quando completar uma palavra seguir a seguinte seqüência de " busca, sendo primeiro em 1, segundo em 2, ... " " 1 - no buffer atual (.) " 2 - buffer de outra janela (w) " 3 - outros buffers carregados (b) " 4 - buffers não carregados (u) " 5 - arquivo de tags (t) " 6 - arquivo de include (i) " 7 - dicionário (K) " ---------------------------------------------------------------------------- " set complete=.,w,b,u,t,i,k "(*default*) set complete=k,.,w,t,i,b,u " set complete=.,w,k,t,i " ---------------------------------------------------------------------------- " Completa a palavra ignorando se é maiúscula ou minúscula " Não é uma idéia muito boa, se o propósito envolver completar códigos. " ---------------------------------------------------------------------------- " set infercase " ---------------------------------------------------------------------------- " Marca como erro duas palavras idênticas separadas por espaço " ---------------------------------------------------------------------------- syntax match DoubleWordErr "\c\<\(\a\+\)\_s\+\1\>" hi def link DoubleWordErr Error " ---------------------------------------------------------------------------- " }}} " Configurações do taglist {{{ " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=273 " ---------------------------------------------------------------------------- " Inclua: " --langdef=tex " --langmap=tex:.tex " --regex-tex=/\\subsubsection[ \t]*\*?\{[ \t]*([^}]*)\}/- \1/s,subsubsection/ " --regex-tex=/\\subsection[ \t]*\*?\{[ \t]*([^}]*)\}/+\1/s,subsection/ " --regex-tex=/\\section[ \t]*\*?\{[ \t]*([^}]*)\}/\1/s,section/ " --regex-tex=/\\chapter[ \t]*\*?\{[ \t]*([^}]*)\}/\1/c,chapter/ " --regex-tex=/\\label[ \t]*\*?\{[ \t]*([^}]*)\}/\1/l,label/ " --regex-tex=/\\ref[ \t]*\*?\{[ \t]*([^}]*)\}/\1/r,ref/ " " no arquivo ~/.ctags para permitir ajustar o ctags para o LaTeX. " URL: http://vim.wikia.com/wiki/Use_Taglist_with_LaTeX_files " ---------------------------------------------------------------------------- " Auto Update da lista de tags " ---------------------------------------------------------------------------- let Tlist_Auto_Update = 1 " ---------------------------------------------------------------------------- " Habilitando o menu tags no gvim " ---------------------------------------------------------------------------- let Tlist_Show_Menu = 1 " ---------------------------------------------------------------------------- " Ajustando o tamanho da janela do taglist " ---------------------------------------------------------------------------- let Tlist_WinWidth = 30 let Tlist_WinHeight = 30 " ---------------------------------------------------------------------------- " Fechamento automático das dobras que estão inativas " ---------------------------------------------------------------------------- let Tlist_File_Fold_Auto_Close = 1 " ---------------------------------------------------------------------------- " Se ao fechar, apenas o taglist estiver aberto, fechar o vim " ---------------------------------------------------------------------------- let Tlist_Exit_OnlyWindow = 1 " ---------------------------------------------------------------------------- " Abreviações para linha de comando " ---------------------------------------------------------------------------- cab ctg TlistToggle cab ctgo TlistOpen cab ctgs Tlist cab ctgadd TlistAddFiles cab ctgaddall TlistAddFilesRecursive cab ctgup TlistUpdate cab ctglock TlistLock cab ctgsync TlistSync cab ctgsave TlistSessionSave cab ctgopen TlistSessionLoad " ---------------------------------------------------------------------------- " }}} " Configurações do PotWiki {{{ " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=1018 " ---------------------------------------------------------------------------- " Definindo o caminho padrão para o wiki " ---------------------------------------------------------------------------- let potwiki_home = "$HOME/.vim/.wiki/HomePage" " ---------------------------------------------------------------------------- " Habilitando o autosalvamento para o wiki " ---------------------------------------------------------------------------- let potwiki_autowrite = 1 " ---------------------------------------------------------------------------- " Personalizando as cores do wiki " ---------------------------------------------------------------------------- highlight PotwikiWord guifg=darkcyan highlight PotwikiWordNotFound guibg=Red guifg=Yellow " ---------------------------------------------------------------------------- " }}} " Configurações do NERDTree {{{ " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=1658 " ---------------------------------------------------------------------------- " Veja ~/.vim/doc/NERDTree.txt para mais informações " ---------------------------------------------------------------------------- " Abreviando a inicialização dele " ---------------------------------------------------------------------------- cab ntree NERDTree map <F5> :NERDTree<CR> imap <F5> <ESC>:NERDTree<CR> " ---------------------------------------------------------------------------- " Configurando o arquivo que registrará os bookmarks " ---------------------------------------------------------------------------- let NERDTreeBookmarksFilee="~/.vim/.NERDTreeBookmarks" " ---------------------------------------------------------------------------- " Ativando os Bookmarks ao iniciar " ---------------------------------------------------------------------------- let NERDTreeShowBookmarks=1 " ---------------------------------------------------------------------------- " Ajustando o tamanho da janela para melhor aproveitamento do espaço " ---------------------------------------------------------------------------- let NERDTreeWinSize=45 " ---------------------------------------------------------------------------- " }}} " Configurações para o snipMate {{{ " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=2540 " ---------------------------------------------------------------------------- " Os snippets utilizados por esse .vimrc e que são diferentes da versão de " instalação, podem ser encontrados em: " URL: http://snipt.net/jfmitre/tag/snippet " ---------------------------------------------------------------------------- " O snipMate deve usar tabulação para funcionar " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.snippets set noexpandtab " ---------------------------------------------------------------------------- " Não quero usar folder nos arquivos do snipMate " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.snippets set foldlevel=2 " ---------------------------------------------------------------------------- " }}} " Configuração para GNU GPG {{{ " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=661 " ---------------------------------------------------------------------------- " Definindo a variável GPG_TTY no .vimrc " O correto é acrescentar ao .bashrc: " export GPG_TTY="tty" " ---------------------------------------------------------------------------- let $GPG_TTY = "tty" " ---------------------------------------------------------------------------- " Não crie arquivo de backup de arquivos encriptados " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.gpg,*.asc,*.pgp setlocal nobk \ | setlocal noswf " ---------------------------------------------------------------------------- " Utilizando o mesmo esquema de cores que foi criado para arquivos .txt " Vide 'Funções, mapeamentos e abreviações para edição de texto em geral' " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.gpg,*.asc,*.pgp source ~/.vim/data/txt.vim " ---------------------------------------------------------------------------- " Facilitando o acesso ao meu arquivo de senhas, abre o mesmo em uma nova tab " Para navegar entre tabs: " :tabnext, :tabprev, :tabfirst, :tablast ou :tab n " O mapeamento abaixo refere-se a <C-7> " ---------------------------------------------------------------------------- map <ESC>:tabnew ~/.passwords.gpg<CR> " ---------------------------------------------------------------------------- " }}} " Para melhor uso do vim e seus plugins {{{ " ---------------------------------------------------------------------------- " Utilizando abreviações em linha de comando " Para tanto vamos utilizar o comando Cab " ---------------------------------------------------------------------------- cab W w cab Wq wq cab wQ wq cab WQ wq cab Q q " ---------------------------------------------------------------------------- " Melhorando o trabalho com várias janelas " ---------------------------------------------------------------------------- imap <C-W> <ESC><C-W> " Teclas de copiar, colar e recortar tipo: <C-C>, <C-V> e <C-X> " ---------------------------------------------------------------------------- " copy - copiar " ---------------------------------------------------------------------------- vmap <C-C> y " ---------------------------------------------------------------------------- " paste - colar " ---------------------------------------------------------------------------- nmap <C-V> p imap <C-V> <C-O>p " ---------------------------------------------------------------------------- " cut - cortar " ---------------------------------------------------------------------------- vmap <C-X> x " ---------------------------------------------------------------------------- " undo - desfazer " ---------------------------------------------------------------------------- noremap <C-Z> u inoremap <C-Z> <C-O>u " ---------------------------------------------------------------------------- " select all - selecionar tudo " ---------------------------------------------------------------------------- map <C-a> <esc>ggvG " ---------------------------------------------------------------------------- " Faz o shift-insert comportar-se semelhante ao Xterm " Sendo assim você seleciona um bloco de texto com o mouse " e cola com o botão do meio do mouse " ---------------------------------------------------------------------------- map <S-Insert> <MiddleMouse> map! <S-Insert> <MiddleMouse> " ---------------------------------------------------------------------------- " Atalhos para o plugin Calendar " ---------------------------------------------------------------------------- " URL: http://www.vim.org/scripts/script.php?script_id=52 " ---------------------------------------------------------------------------- cab C Calendar cab CH CalendarH " ---------------------------------------------------------------------------- " Embaralha a tela para evitar bisbilhoteiros " ---------------------------------------------------------------------------- map <F4> ggVGg? " ---------------------------------------------------------------------------- " Alterna o modo de quebra de linha " ---------------------------------------------------------------------------- map <leader>b :set wrap! <bar> ec &wrap ? 'wrap' : 'nowrap'<cr> " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para edição de texto em geral {{{ " ---------------------------------------------------------------------------- " Definindo tamanho da linha, isto é, coluna onde a linha deve ser "quebrada" " com a inserção de fim de linha (<EOL>, abreviação de end-of-line). " Existe a recomendação majoritária de ter textos com quebra inferior ou igual " a 80. Contudo, 90 é uma boa escolha para uma formatação genérica. " Especifique outros valores de acordo com interesse " ---------------------------------------------------------------------------- set textwidth=90 " ---------------------------------------------------------------------------- " Se uma linha ultrapassar o valor estipulado em textwidth ela será " mostrada em destaque colocá-la em uma função de liga desliga junto " com uma que mostre as linhas e colunas de um arquivo em destaque " ---------------------------------------------------------------------------- au BufNewFile,BufRead * exec 'match Error /\%>' . &textwidth . 'v.\+/' " ---------------------------------------------------------------------------- " Fazer a primeiria letra depois de uma pontuação tornar-se maiúscula " ---------------------------------------------------------------------------- " :%s/[.!?]\_s\+\a/\U&\E/g " ---------------------------------------------------------------------------- " Para remover linhas em branco duplicadas " ---------------------------------------------------------------------------- " map ,d my:%s/\(^\n\{2,}\)/\r/g`y " ---------------------------------------------------------------------------- " Adição de um cabeçalho genérico " ---------------------------------------------------------------------------- fun! InsertUpdateData() normal(1G) call append(0, " File: ") call append(1, " Author: J. F. Mitre <http://jfmitre.com>") " Escreve a data na forma: DD/MM/AA hs HH:MM " call append(2, " Created: " . strftime("%a %d/%b/%Y hs %H:%M")) " Escreve a data na forma: Semana DD MES AAAA HH:MM:SS TIMEZONE call append(2, " Created: " . strftime("%c")) " Escreve a data na forma: DD/MM/AA hs HH:MM " call append(3, " Last Update: " . strftime("%a %d/%b/%Y hs %H:%M")) " Escreve a data na forma: Semana DD MES AAAA HH:MM:SS TIMEZONE call append(3, " Last Update: " . strftime("%c")) call append(4, " Notes: ") normal($) endfun cmap ,cl call InsertUpdateData()<CR>A " ---------------------------------------------------------------------------- " Dando destaque para notas " http://vivaotux.blogspot.com/2009/01/ " \ uniformizao-de-espaamento-nos-cdigos.html " ---------------------------------------------------------------------------- highlight MinhasNotas ctermbg=blue ctermfg=yellow guibg=blue guifg=yellow match MinhasNotas /[Nn]otas\? \?:/ " ---------------------------------------------------------------------------- " a função (strftime) é predefinida pelo sistema " ---------------------------------------------------------------------------- iab YDATE <C-R>=strftime("%a %d/%b/%Y hs %H:%M")<CR> iab HDATE <C-R>=strftime("%a %d/%b/%Y hs %H:%M")<CR> " ---------------------------------------------------------------------------- " Adicionando o suporte a calculadora no vim " ---------------------------------------------------------------------------- command! -nargs=+ Calc :py print <args> py from math import * " ---------------------------------------------------------------------------- " Fechamento automático para parênteses " ---------------------------------------------------------------------------- inoremap ( ()<esc>i inoremap { {}<esc>i inoremap [ []<esc>i " ---------------------------------------------------------------------------- " Função para atualizar a data da última modificação " Verifica se existe uma data nas 5 primeiras linhas do documento " Se não existe, escreve na primeira linha " Se existe, atualiza a informação " Essa função gera uma mensagem de erro em documento com menos de 5 linhas " ---------------------------------------------------------------------------- fun! LastUpdate() mark z if getline(0) =~ ".*Last Update:" || \ getline(1) =~ ".*Last Update:" || \ getline(2) =~ ".*Last Update:" || \ getline(3) =~ ".*Last Update:" || \ getline(4) =~ ".*Last Update:" || \ getline(5) =~ ".*Last Update:" " Atualiza apenas o que estiver nas 5 primeiras linhas exec "1,5s/\s*Last Update: .*$/Last Update: " . strftime("%c") . "/" " Atualiza apenas a linha que contém o cursor " exec "s/\s*Last Update: .*$/Last Update: " . strftime("%c") . "/" else " call append(0, " Last Update: " . strftime("%a %d/%b/%Y hs %H:%M")) call append(0, " Last Update: " . strftime("%c")) endif exec "'z" endfun " ---------------------------------------------------------------------------- " Abreviação para a função acima " ---------------------------------------------------------------------------- cmap data call LastUpdate()<CR> " ---------------------------------------------------------------------------- " Man: Páginas de manual são na verdade textos em NROFF " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.man set ft=nroff " ---------------------------------------------------------------------------- " MostraTab: mostra TAB no inicio e espaços no fim das linhas " ---------------------------------------------------------------------------- map ,mt /^\t\+\\|\s\+$<cr> " ---------------------------------------------------------------------------- " PalavrasRepetidas: procura palavras repetidas no texto " ---------------------------------------------------------------------------- map ,pr /\<\(\w*\) \1\><cr> " ---------------------------------------------------------------------------- " Numerar linhas dentro do arquivo " :let i=1 | g/^/s//\=i."\t"/ | let i=i+1 " ---------------------------------------------------------------------------- map ,n :let i=1 g/^/s//\=i."\t"/ let i=i+1 " ---------------------------------------------------------------------------- " Destaca uma linha no texto com o código de erro " ---------------------------------------------------------------------------- nnoremap <Leader>k mk:exe 'match Search /<Bslash>%'.line(".").'l/'<CR> " ---------------------------------------------------------------------------- " Justifica: justifica os textos com o justificador em sed " ---------------------------------------------------------------------------- vmap ,je :!sed.alinha-justify<cr> " ---------------------------------------------------------------------------- " Digitar ";l" retira espaços em branco de final de arquivo " ---------------------------------------------------------------------------- map ;l :%s/\s*$//g<cr> " ---------------------------------------------------------------------------- " Mail: Configurações especiais para arquivos de e-mail " ---------------------------------------------------------------------------- au FileType Mail set fo=ctq tw=65 et " ---------------------------------------------------------------------------- " Identação de textos e códigos com o TAB no modo visual " URL: http://gustavodutra.com/post/72/ " \ dicas-de-movimentacao-e-identacao-no-gvim/ " ---------------------------------------------------------------------------- vnoremap < <gv vnoremap > >gv vmap <TAB> > vmap <S-TAB> < imap <S-TAB> <ESC><<i " ---------------------------------------------------------------------------- " Permite abrir um arquivo mencionado com o caminho dentro de outro arquivo " Funciona em cabeçalhos de programação " ---------------------------------------------------------------------------- nmap gf :new %:p:h/<cfile><CR> " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para aquivos .txt {{{ " ---------------------------------------------------------------------------- " Quebra os arquivos de texto na coluna 79 " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.txt setl tw=79 " ---------------------------------------------------------------------------- " Usa uma source para edição de arquivo .txt " Source txt.vim do Aurelio Marinho Jarga " URL: http://aurelio.net/vim/txt.vim " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.txt source ~/.vim/data/txt.vim " ---------------------------------------------------------------------------- " Os arquivo README, NEWS e ToDo também são arquivos de texto " ---------------------------------------------------------------------------- au BufNewFile,BufRead *{R,r}{E,e}{A,a}{D,d}{M,m}{E,e} setl ft=txt tw=79 au BufNewFile,BufRead *{R,r}{E,e}{A,a}{D,d}{M,m}{E,e} \ source ~/.vim/data/txt.vim au BufNewFile,BufRead *{N,n}{E,e}{W,w}{S,s} setl ft=txt tw=79 au BufNewFile,BufRead *{N,n}{E,e}{W,w}{S,s} source ~/.vim/data/txt.vim au BufNewFile,BufRead *{T,t}{O,o}{D,d}{O,o} setl ft=txt tw=79 au BufNewFile,BufRead *{T,t}{O,o}{D,d}{O,o} source ~/.vim/data/txt.vim " }}} " Funções, mapeamentos e abreviações para programação e edição de dotfiles {{{ " ---------------------------------------------------------------------------- " Função que mapeia <F9> para mostrar/ocultar comentários " ---------------------------------------------------------------------------- fu! CommOnOff() if !exists('g:hiddcomm') let g:hiddcomm=1 | hi Comment ctermfg=black guifg=black else unlet g:hiddcomm | hi Comment ctermfg=cyan guifg=cyan term=bold endif endfu map <F9> :call CommOnOff()<cr> " ---------------------------------------------------------------------------- " Função para comentar vários arquivos de acordo com o tipo " URL: http://vim.wikia.com/wiki/Comment_Lines_according_to_a_given_filetype " ---------------------------------------------------------------------------- fu! CommentLines() "let Comment="#" " shell, tcl, php, perl exe ":s@^@".g:Comment."@g" exe ":s@$@".g:EndComment."@g" endfu " mapeando a função no modo visual com a combinação 'co' vmap co :call CommentLines()<CR>a " definindo os comentários por tipo de arquivo (a primeira linha é um padrão) au BufRead,BufNewFile * let Comment="# " | let EndComment="" au BufRead,BufNewFile *.inc,*.ihtml,*.html,*.tpl,*.class \ let Comment="<!-- " | let EndComment=" -->" au BufRead,BufNewFile *.sh,*.pl,*.tcl let Comment="# " | let EndComment="" au BufRead,BufNewFile *.js set | let Comment="// " | let EndComment="" au BufRead,BufNewFile *.cc,*.php,*.cxx,*.cpp \ let Comment="// " | let EndComment="" au BufRead,BufNewFile *.c,*.h let Comment="/* " | let EndComment=" */" au BufRead,BufNewFile *.f90,*.f95 let Comment="! " | let EndComment="" au BufRead,BufNewFile *.f let Comment="C " | let EndComment="" au BufRead,BufNewFile *.tex,*.bib let Comment="% " | let EndComment="" au BufRead,BufNewFile *.vim,.vimrc let Comment="\" " | let EndComment="" " ---------------------------------------------------------------------------- " }}} " Para editar o vimrc {{{ " ---------------------------------------------------------------------------- " Permite recarregar e editar o ~/.vimrc " ---------------------------------------------------------------------------- " Para recarregar o .vimrc manualmente imap ,u <ESC>:source ~/.vimrc<CR> " Para permitir que ele seja automaticamente carregado ao ser salvo " autocmd! bufwritepost .vimrc source % " Para editar o .vimrc imap ,v <ESC>:e ~/.vimrc<CR> " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para Makefiles {{{ " ---------------------------------------------------------------------------- " O Makefile deve usar Tabs " ---------------------------------------------------------------------------- au BufNewFile,BufRead *[mM]akefile setlocal noexpandtab " ---------------------------------------------------------------------------- " Esses arquivos também são tipo scripts " ---------------------------------------------------------------------------- au BufNewFile,BufRead *[mM]akefile* setlocal ft=make " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para LaTeX {{{ " ---------------------------------------------------------------------------- " Identificando o .tex como código LaTeX " ---------------------------------------------------------------------------- let g:tex_flavor='latex' " ---------------------------------------------------------------------------- " Registrando tamanho de coluna em arquivo LaTeX " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal tw=79 " ---------------------------------------------------------------------------- " Dicionário que é a lista dos nomes dos snippets utilizados pelo snipMate " quando o LaTeX é utilizado " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal dictionary=~/.vim/dict/latex.dic " ---------------------------------------------------------------------------- " Dicionário relativo as tags do arquivo de bibliografia. " Digite <F7> (ou sua tecla personalizada) para criar o arquivo ./bib.dic " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal dictionary+=./bib.dic " ---------------------------------------------------------------------------- " Dicionário completo de comandos. Adaptado do dicionário do Kile. " URL: http://sites.google.com/site/bemylifeeasy/Home/tex.zip " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal dictionary+=~/.vim/dict/tex/*.cwl \ iskeyword+=\\,.,{,},[,],*,=,/,(,),>,< " ---------------------------------------------------------------------------- " Alguns comandos para LaTeX (para o modo de inserção) " Ative a complementação de chaves para melhor aproveitamento " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex imap ,bf \textbf{ \ | imap ,it \textit{ \ | imap ,tt \texttt{ \ | imap ,fn \footnote{ \ | imap ,se \section{ \ | imap ,ch \chapter{ \ | imap ,un \underline{ \ | iab latex \LaTeX " ---------------------------------------------------------------------------- " Gerando um dicionário de bibliografia " O script (em bash) catbib varre todos os .bib do diretório corrente e " cria o arquivo ./bib.dic que é parte da lista de dicionários acima " " Código do script: catbib " #!/bin/bash " # File: catbib " # Author: J. F. Mitre <http://jfmitre.com> " # Created: Qui 28/Mai/2009 hs 23:15 " # Last Update: Dom 31 Mai 2009 13:17:25 BRT " # Notes: write an bib.dic with labels for \cite{} " " TEMP=`ls *.bib 2>/dev/null` " if [ ! -z $TEMP ]; then " #if there is/are *.bib, then " grep @ *.bib |sed -e '/STRING/d' \ " -e '/ /d' \ " -e 's/^.*{//g' >bib.dic 2>/dev/null " fi " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex,*.bib \ map <F7> <ESC>:!~/.vim/scripts/catbib<CR> " ---------------------------------------------------------------------------- " Correlacionando as aspas estilo LaTeX " e mapeando a função "" para ser ``'' se digitar '"<space>"', ou seja, " aspas, espaço, aspas, será incluído as aspas comuns. " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal matchpairs+=`:' \ | inoremap "" ``''<esc><left><left>a " ---------------------------------------------------------------------------- " Gerenciando folders em LaTeX (apenas seções são folders) " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex setlocal foldmarker=%\ bsec,%\ endsec \ | setlocal foldlevel=0 " ---------------------------------------------------------------------------- " Construindo e gerenciando um 'projeto' com o taglist " Não deixa de ser abreviações criadas anteriormente, mas aqui possui um " propósito mais definido, com um nome mais claro. " ---------------------------------------------------------------------------- cab texctg TlistAddFilesRecursive ./ *.tex cab texp Tlist " ---------------------------------------------------------------------------- " Filtrando e abrindo log para melhor avaliação do resultado da compilação " modifique vsplit para split caso prefira dividir a tela horizontalmente. " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.tex,*.bib \ map <S-F7> <ESC>:!~/.vim/scripts/latexfilter &>./filter.log<CR> \<ESC>:vsplit ./filter.log<CR> " ---------------------------------------------------------------------------- " Carregando sintaxe para destacar erros no código LaTeX " Ela será aplicada apenas ao arquivo filter.log criado no item anterior " ---------------------------------------------------------------------------- au BufNewFile,BufRead filter.log syn clear | syn case ignore \ | syn match logError '.*Error.*' \ | syn match logWarning '.*Warning.*' \ | syn match logOverUnderFull '.*[Over|Under].*[v|h]box.*' \ | syn match logFile '.*\.\/.*\....$' \ | syn match logNoFile1 '.*No\ file.*' \ | syn match logNoFile2 '.*File.*does.not.*' \ | hi logOverUnderFull ctermfg=LightGrey cterm=bold \ | hi logWarning ctermfg=Red cterm=bold \ | hi logFile ctermfg=Green cterm=bold \ | hi logError ctermfg=yellow ctermbg=Red \ | hi logNoFile1 ctermfg=Blue \ | hi logNoFile2 ctermfg=Blue " ---------------------------------------------------------------------------- " Templates em LaTeX " ---------------------------------------------------------------------------- " Documento para escrever relatórios e textos em geral. au BufNewFile,BufRead *.tex cmap TEXD r ~/.vim/headers/documento.tex<CR> " Escrever pequenos resumos de uma página au BufNewFile,BufRead *.tex cmap TEXD r ~/.vim/headers/resumo.tex<CR> " Escrever cartas au BufNewFile,BufRead *.tex cmap TEXL r ~/.vim/headers/carta.tex<CR> " Apresentação com o Prosper au BufNewFile,BufRead *.tex cmap TEXP r ~/.vim/headers/prosper.tex<CR> " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para programação em shell script {{{ " ---------------------------------------------------------------------------- " BashTemp: linha de criação do arquivo temporário com o mktemp " ---------------------------------------------------------------------------- " map ,bt IA_TMP=`mktemp /tmp/$(basename $0).XXXXXX` " ---------------------------------------------------------------------------- " O arquivo .sh é na verdade um arquivo bash " ---------------------------------------------------------------------------- au FileType sh let b:is_bash=1 " ---------------------------------------------------------------------------- " Esss arquivos também são tipo scritps " ---------------------------------------------------------------------------- au BufNewFile,BufRead .alias*,.funcoes* set ft=sh " ---------------------------------------------------------------------------- " Cria um cabeçalho para scripts bash " ---------------------------------------------------------------------------- fun! InsertHeadBash() normal(1G) call append(0, "#!/bin/bash") call append(1, "# File: <name>") call append(2, "# Author: J. F. Mitre <http://jfmitre.com>") call append(3, "# Created: " . strftime("%c")) call append(4, "# Last Update: " . strftime("%c")) call append(5, "# Notes:") normal($) endfun cmap ,sh call InsertHeadBash()<CR>A " ---------------------------------------------------------------------------- " Se for um arquivo .sh e ele estiver vazio, insira o cabeçalho " ---------------------------------------------------------------------------- " au BufNewFile,BufRead *.sh if getline(1) == "" | normal ,sh au BufNewFile,BufRead *.sh if getline(1) == "" | call InsertHeadBash() " }}} " Funções, mapeamentos e abreviações para programação em Python {{{ " ---------------------------------------------------------------------------- " Cria uma cabeçalho para programas em Python " ---------------------------------------------------------------------------- fun! BufNewFile_PY() normal(1G) call append(0, "#!/usr/bin/env python") call append(1, "# # -*- coding: UTF-8 -*-") call append(2, "# Author: J. F. Mitre <http://jfmitre.com>") call append(3, "# Created: " . strftime("%c")) call append(4, "# Last Update: " . strftime("%c")) call append(5, "# File: <name>") call append(6, "# Notes: ") normal gg endfun cmap ,py call BufNewFile_PY()<CR>A " ---------------------------------------------------------------------------- " Arquivos Python devem ter tabulação " ---------------------------------------------------------------------------- au FileType python set noexpandtab " ---------------------------------------------------------------------------- " Se for um arquivo .py e ele estiver vazio, insira o cabeçalho " ---------------------------------------------------------------------------- au BufNewFile,BufRead *.py if getline(1) == "" | call BufNewFile_PY() " ---------------------------------------------------------------------------- " Indentação inteligente para python " ---------------------------------------------------------------------------- au! FileType python set smartindent \ cinwords=if,elif,else,for,while,try,except,finally,def,class " ---------------------------------------------------------------------------- " Pydoc, plugin que integra o Pydoc com o vim " URL: http://www.vim.org/scripts/script.php?script_id=910 " Uso: no modo normal, digite \pw com o cursor sobre o verbete " ---------------------------------------------------------------------------- " Para desabilitar o highlight na busca por ajuda " let g:pydoc_highlight = 0 " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações para programação para web {{{ " ---------------------------------------------------------------------------- " Relaciona o caractere < com o caractere > em arquivo HTML " ---------------------------------------------------------------------------- au FileType html set matchpairs+=<:> " ---------------------------------------------------------------------------- " Auto complete < com > em arquivo HTML " ---------------------------------------------------------------------------- au FileType html inoremap < <><esc>i " ---------------------------------------------------------------------------- " Dicionário para snippets de arquivo HTML " ---------------------------------------------------------------------------- au FileType html set dictionary=~/.vim/dict/html.dic " ---------------------------------------------------------------------------- " Convertendo arquivo do vim para página em HTML (sintaxe colorida) " ---------------------------------------------------------------------------- map <leader>2html <ESC>:so $VIMRUNTIME/syntax/2html.vim<CR> " ---------------------------------------------------------------------------- " }}} " Funções, mapeamentos e abreviações programação em FORTRAN {{{ " ---------------------------------------------------------------------------- " Leia a parte relativa a FORTRAN em: http://www.vim.org/htmldoc/syntax.html " ---------------------------------------------------------------------------- " Define qual é a extensão do arquivo " ---------------------------------------------------------------------------- let s:extfname = expand("%:e") " ---------------------------------------------------------------------------- " Dependendo da extensão, é FORTRAN 77 ou FORTRAN 90/95 " Para cada caso é definido formato fixo ou formato livre do código " Considerar ou não considerar a tabulação " E para o caso de formato fixo, definir o exato tamanho permitido " ---------------------------------------------------------------------------- if s:extfname ==? "f90" let fortran_free_source=1 unlet! fortran_fixed_source let fortran_have_tabs=1 elseif s:extfname ==? "f95" let fortran_free_source=1 unlet! fortran_fixed_source let fortran_have_tabs=1 elseif s:extfname ==? "f" let fortran_fixed_source=1 unlet! fortran_free_source set tw=72 endif " ---------------------------------------------------------------------------- " Mais precisão na definição de sintaxe do código " ---------------------------------------------------------------------------- let fortran_more_precise=1 " ---------------------------------------------------------------------------- " Usar ou não usar folders no código " ---------------------------------------------------------------------------- " let fortran_fold=1 " let fortran_fold_conditionals=1 " let fortran_fold_multilinecomments=1 " ---------------------------------------------------------------------------- " }}} " Referências {{{ " ---------------------------------------------------------------------------- " " * vimbook - tirei muitas dicas dali, mais do que isso, aprendi coisas " para adaptar e escrever outras. Aliás, essa foi a força " motriz para a iniciativa dessa configuração. " URL: http://vivaotux.blogspot.com/2009/01/nosso-livro-sobre-o-vim.html " " * aurelio.net - referência clássica, mesmo que eu não tivesse visitado a " página do camarada (e eu visitei), eu teria absorvido " através de terceiros. " URL: http://aurelio.net/ " " * vivaotux - muitas dicas sobre vim (plugins e outras coisas). " URL: http://vivaotux.blogspot.com/ " " * Vim (Página oficial) - a documentação existente nesse site é fantástica. " URL: http://www.vim.org/ " " * Alguns arquivos vimrc: " " * http://aurelio.net/vim/vimrc-ivan.txt " * http://aurelio.net/doc/vim/vimrc-voyeg3r.txt " * http://dotfiles.org/~voyeg3r/.vimrc " * http://aurelio.net/doc/dotfiles/vimrc.txt " * http://www.stripey.com/vim/vimrc.html " * http://www.8t8.us/configs/vimrc.txt " * http://snipt.net/voyeg3r/my-vimrc " ---------------------------------------------------------------------------- " }}}
-
∞ options to wrap and list
" opções para mostrar espaços e tabulações set listchars=tab:\|\ ,extends:>,precedes:<,trail:-,nbsp:% map <leader>l :set list! list?<cr> " alterna o modo de quebra visual de linha map <leader>b :set wrap! wrap?<cr> " mostra +++ no começo de linhas longas sem wrap set showbreak=+++
-
∞ my vimrc file
set autoindent set smartindent " Basics { set nocompatible " explicitly get out of vi-compatible mode set background=dark " we plan to use a dark background syntax on " syntax highlighting on " } " Vim UI { set cursorcolumn " highlight the current column set cursorline " highlight current line set incsearch " BUT do highlight as you type you search phrase set laststatus=2 " always show the status line set lazyredraw " do not redraw while running macros set linespace=0 " don't insert any extra pixel lines betweens rows set list " we do what to show tabs, to ensure we get them out of my files set listchars=tab:>-,trail:- " show tabs and trailing whitespace set matchtime=5 " how many tenths of a second to blink matching brackets for set nohlsearch " do not highlight searched for phrases set nostartofline " leave my cursor where it was set novisualbell " don't blink set number " turn on line numbers set numberwidth=5 " We are good up to 99999 lines set report=0 " tell us when anything is changed via :... set ruler " Always show current positions along the bottom set scrolloff=10 " Keep 5 lines (top/bottom) for scope set shortmess=atI " shortens messages to avoid 'press a key' prompt set showcmd " show the command being typed set showmatch " show matching brackets set sidescrolloff=10 " Keep 5 lines at the size " statusline demo: ~\myfile[+] [FORMAT=format] [TYPE=type] [ASCII=000] [HEX=00] [POS=0000,0000][00%] [LEN=000] set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [ASCII=\%03.3b]\ [HEX=\%02.2B]\ [POS=%04l,%04v][%p%%]\ [LEN=%L] " } " Text Formatting/Layout { set completeopt=menu,longest " improve the way autocomplete works set expandtab " no real tabs please! set formatoptions=rq " Automatically insert comment leader on return, and let gq work set ignorecase " case insensitive by default set nowrap " do not wrap line set shiftround " when at 3 spaces, and I hit > ... go to 4, not 5 set smartcase " if there are caps, go case-sensitive " Indent Related { set shiftwidth=4 " unify set softtabstop=4 " unify set tabstop=4 " real tabs should be 4, but they will show with set list on " } " } function! ToggleSyntax() if exists("g:syntax_on") syntax off else syntax enable endif endfunction nmap <silent> ;s :call ToggleSyntax()<CR>
-
∞ Change each 'foo' to 'bar' for all lines between line 5 and line 12.
:5,12s/foo/bar/g
-
∞ snipts para html
snippet skel <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <link rel="stylesheet" href="${1:meuestilo.css}"> <!-- comentario --> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <head> <title> ${2:titulo-da-pagina} </title> </head> <body> ${3:corpo-do-documento} </body> </html> # Some useful Unicode entities # Non-Breaking Space snippet nbs # ? snippet left ← # ? snippet right → # ? snippet up ↑ # ? snippet down ↓ # ? snippet return ↩ # ? snippet backtab ⇤ # ? snippet tab ⇥ # ? snippet shift ⇧ # ? snippet control ⌃ # ? snippet enter ⌅ # ? snippet command ⌘ # ? snippet option ⌥ # ? snippet delete ⌦ # ? snippet backspace ⌫ # ? snippet escape ⎋ # Generic Doctype snippet doctype HTML 4.01 Strict <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" "http://www.w3.org/TR/html4/strict.dtd"> snippet doctype HTML 4.01 Transitional <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"" "http://www.w3.org/TR/html4/loose.dtd"> snippet doctype HTML 5 <!DOCTYPE HTML> snippet doctype XHTML 1.0 Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> snippet doctype XHTML 1.0 Strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> snippet doctype XHTML 1.0 Transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> snippet doctype XHTML 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> # HTML Doctype 4.01 Strict snippet docts <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"" "http://www.w3.org/TR/html4/strict.dtd"> # HTML Doctype 4.01 Transitional snippet doct <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"" "http://www.w3.org/TR/html4/loose.dtd"> # HTML Doctype 5 snippet doct5 <!DOCTYPE HTML> # XHTML Doctype 1.0 Frameset snippet docxf <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> # XHTML Doctype 1.0 Strict snippet docxs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> # XHTML Doctype 1.0 Transitional snippet docxt <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> # XHTML Doctype 1.1 snippet docx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> snippet html <html> ${1} </html> snippet xhtml <html xmlns="http://www.w3.org/1999/xhtml"> ${1} </html> snippet body <body> ${1} </body> snippet head <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"`Close()`> <title>${1:`substitute(Filename('', 'Page Title'), '^.', '\u&', '')`}</title> ${2} </head> snippet title <title>${1:`substitute(Filename("", "Page Title"), "^.", "\u&", "")`}</title>${2} snippet script <script type="text/javascript" charset="utf-8"> ${1} </script>${2} snippet scriptsrc <script src="${1}.js" type="text/javascript" charset="utf-8"></script>${2} snippet style <style type="text/css" media="${1:screen}"> ${2} </style>${3} snippet base <base href="${1}" target="${2}"`Close()`> snippet r <br`Close()[1:]`> snippet div <div id="${1:name}"> ${2} </div> # Embed QT Movie snippet movie <object width="$2" height="$3" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"> <param name="src" value="$1"`Close()`> <param name="controller" value="$4"`Close()`> <param name="autoplay" value="$5"`Close()`> <embed src="${1:movie.mov}" width="${2:320}" height="${3:240}" controller="${4:true}" autoplay="${5:true}" scale="tofit" cache="true" pluginspage="http://www.apple.com/quicktime/download/" `Close()[1:]`> </object>${6} snippet fieldset <fieldset id="$1"> <legend>${1:name}</legend> ${3} </fieldset> snippet form <form action="${1:`Filename('$1_submit')`}" method="${2:get}" accept-charset="utf-8"> ${3} <p><input type="submit" value="Continue →"`Close()`></p> </form> snippet h1 <h1 id="${1:heading}">${2:$1}</h1> snippet input <input type="${1:text/submit/hidden/button}" name="${2:some_name}" value="${3}"`Close()`>${4} snippet label <label for="${2:$1}">${1:name}</label><input type="${3:text/submit/hidden/button}" name="${4:$2}" value="${5}" id="${6:$2}"`Close()`>${7} snippet link <link rel="${1:stylesheet}" href="${2:/css/master.css}" type="text/css" media="${3:screen}" charset="utf-8"`Close()`>${4} snippet mailto <a href="mailto:${1:joe@example.com}?subject=${2:feedback}">${3:email me}</a> snippet meta <meta name="${1:name}" content="${2:content}"`Close()`>${3} snippet opt <option value="${1:option}">${2:$1}</option>${3} snippet optt <option>${1:option}</option>${2} snippet select <select name="${1:some_name}" id="${2:$1}"> <option value="${3:option}">${4:$3}</option> </select>${5} snippet table <table border="${1:0}"> <tr><th>${2:Header}</th></tr> <tr><th>${3:Data}</th></tr> </table>${4} snippet textarea <textarea name="${1:Name}" rows="${2:8}" cols="${3:40}">${4}</textarea>${5}


