Public
snipts » vim
showing 1-20 of 41 snipts for vim
-
∞ 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
-
∞ Mi vimrc Linux
" Modo no compatible set nocompatible " Cambio de mapleader let mapleader = "," " Indentación y tabuladores: Se usarán 2 espacios " en vez de un tabulador set tabstop=2 set smarttab set shiftwidth=2 set autoindent set expandtab set backspace=start,indent,eol " 80 caracteres por linea set textwidth=80 " Ficheros que no pueden usar espacios en vez " de tabs autocmd FileType make set noexpandtab " Números de línea, sintaxis y búsquedas " resaltadas set number set ruler set ignorecase set hlsearch set incsearch syntax on filetype on filetype plugin on filetype indent on " Cambiamos los directorios para los ficheros swap " y los backpus (~) set directory=/tmp set backupdir=/tmp " Quitamos la campana set visualbell " Diccionario en ficheros .txt, .tex " au BufNewFile,BufRead *.txt set spell spelllang=es " au BufNewFile,BufRead *.tex set spell spelllang=es " Codificación a UTF-8 set encoding=utf-8 " Buffer set hidden " Mayor matching runtime macros/matchit.vim " Mejor 'completion': Como en bash set wildmenu set wildmode=list:longest,full " Mayor marco para el scroll set scrolloff=3 " Muestra los comandos y los paréntesis, etc " que se acaban de escribir set showcmd set showmatch " Color Scheme if has('gui_running') " colorscheme zenburn colorscheme soruby set guifont=Courier10Pitch else set background=dark end "" Comandos personalizados " Guardar con CTRL-S nmap <C-s> :w<CR> imap <C-s> <Esc>:w<CR>a " Controlar el Folding con espacio nnoremap <space> za " movimientos nmap <C-h> <C-w>h nmap <C-j> <C-w>j nmap <C-k> <C-w>k nmap <C-l> <C-w>l " Brackets inoremap ( ()<Left> inoremap { {}<Left> inoremap [ []<Left> inoremap < <><Left> inoremap " ""<Left> inoremap ' ''<Left> " Markdown augroup mkd autocmd BufRead *.mkd set ai formatoptions=tcroqn2 comments=n:> augroup END "" Plugins " NERD_commenter let NERDSpaceDelims=1 let NERDShutUp=1 " NERDTree nmap <F5> :NERDTree<CR> "NERDTree Toggle nnoremap <Leader>nt :NERDTreeToggle<CR> " XMLEdit autocmd BufNewFile,BufRead *.xml source ~/.vim/ftplugin/xml.vim " FuzzyFinder nnoremap <Leader>fb :FuzzyFinderBuffer<CR> nnoremap <Leader>ff :FuzzyFinderFile<CR> " Latex-Suite let g:tex_flavor='latex' " let g:Tex_ViewRule_pdf='Skim' " let g:Tex_ViewRule_ps='Preview' " let g:Tex_ViewRule_dvi='Skim' let g:Tex_DefaultTargetFormat='pdf' let g:Tex_AutoFolding=0 let g:Tex_Diacritics=1 let g:Tex_MultipleCompileFormats='dvi,pdf' " Para usar Xetex en vez de Latex let g:Tex_CompileRule_pdf='xelatex $*' " taglist let Tlist_Ctags_Cmd='/usr/bin/ctags' nnoremap <Leader>tl :TlistToggle<CR> " vcscommand " let VCSCommandSVNExec='/usr/local/bin/svn' " let VCSCommandMapPrefix='<Leader>vc'
-
∞ 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} -
∞ mapeamentos para contar ocorrências de palavra e buscar palavra sob o cursor
" 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 colocar palavra sob o cursor na busca nnoremap <Leader>s :%s/\<<C-r><C-w>\>/
-
∞ findmate plugin for vim
"Name: findMate "Author: Manuel Aguilar y Victor Guardiola "Version: 0.1 "Description: Este plugin es buscador de archivos en todo un arbol de "dirctorios " function! FindMate(name) let l:_name = substitute(a:name, "\\s", "*", "g") let l:list=system("find . -iname '*".l:_name."*' -not -name \"*.class\" -and -not -name \"*.swp\" -and -not -name \".*\" | perl -ne 'print \"$.\\t$_\"'") let l:num=strlen(substitute(l:list, "[^\n]", "", "g")) if l:num < 1 echo "'".a:name."' not found" return endif if l:num != 1 echo l:list let l:input=input("Which ? (<enter>=nothing)\n") if strlen(l:input)==0 return endif let items = split(l:input, ' ', 1) for item in items if strlen(substitute(l:item, "[0-9]", "", "g"))>0 echo "Not a number" return endif if l:item<1 || l:item>l:num echo "Out of range" return endif let l:line=matchstr("\n".l:list, "\n".l:item."\t[^\n]*") let l:line=substitute(l:line, "^[^\t]*\t./", "", "") execute ":sp ".l:line endfor else let l:line=substitute(l:list, "^[^\t]*\t./", "", "") execute ":sp ".l:line endif endfunction command! -nargs=1 FindMate :call FindMate("<args>") map ,, :FindMate
-
∞ how get char under cursor an put in cmd 's' on vim
"ayl ................. copia para o registro 'a' o caractere sob o cursor :%s/<c-r>a/"/g ....... substitui o conteúdo do registro a por aspas simples
-
∞ desert custom theme
" Vim color file " Maintainer: Hans Fugal <hans@fugal.net> " Last Change: $Date: 2004/06/13 19:30:30 $ " Last Change: $Date: 2004/06/13 19:30:30 $ " URL: http://hans.fugal.net/vim/colors/desert.vim " Version: $Id: desert.vim,v 1.1 2004/06/13 19:30:30 vimboss Exp $ " cool help screens " :he group-name " :he highlight-groups " :he cterm-colors set background=dark if version > 580 " no guarantees for version 5.8 and below, but this makes it stop " complaining hi clear if exists("syntax_on") syntax reset endif endif let g:colors_name="customdesert" hi Normal guifg=White guibg=grey5 " highlight groups hi Cursor guibg=khaki guifg=slategrey "hi CursorIM "hi Directory "hi DiffAdd "hi DiffChange "hi DiffDelete "hi DiffText "hi ErrorMsg hi VertSplit guibg=#c2bfa5 guifg=grey50 gui=none hi Folded guibg=grey30 guifg=gold hi FoldColumn guibg=grey8 guifg=tan hi IncSearch guifg=slategrey guibg=khaki "hi LineNr hi ModeMsg guifg=goldenrod hi MoreMsg guifg=SeaGreen hi NonText guifg=LightBlue guibg=grey8 hi Question guifg=springgreen hi Search guibg=peru guifg=wheat hi SpecialKey guifg=yellowgreen hi StatusLine guibg=#c2bfa5 guifg=black gui=none hi StatusLineNC guibg=#c2bfa5 guifg=grey50 gui=none hi Title guifg=indianred hi Visual gui=none guifg=khaki guibg=olivedrab "hi VisualNOS hi WarningMsg guifg=salmon "hi WildMenu "hi Menu "hi Scrollbar "hi Tooltip " syntax highlighting groups hi Comment guifg=SkyBlue hi Constant guifg=#ffa0a0 hi Identifier guifg=palegreen hi Statement guifg=khaki hi PreProc guifg=indianred hi Type guifg=darkkhaki hi Special guifg=navajowhite "hi Underlined hi Ignore guifg=grey40 "hi Error hi Todo guifg=orangered guibg=yellow2 " color terminal definitions hi SpecialKey ctermfg=darkgreen hi NonText cterm=bold ctermfg=darkblue hi Directory ctermfg=darkcyan hi ErrorMsg cterm=bold ctermfg=7 ctermbg=1 hi IncSearch cterm=NONE ctermfg=yellow ctermbg=green hi Search cterm=NONE ctermfg=grey ctermbg=blue hi MoreMsg ctermfg=darkgreen hi ModeMsg cterm=NONE ctermfg=brown hi LineNr ctermfg=3 hi Question ctermfg=green hi StatusLine cterm=bold,reverse hi StatusLineNC cterm=reverse hi VertSplit cterm=reverse hi Title ctermfg=5 hi Visual cterm=reverse hi VisualNOS cterm=bold,underline hi WarningMsg ctermfg=1 hi WildMenu ctermfg=0 ctermbg=3 hi Folded ctermfg=darkgrey ctermbg=NONE hi FoldColumn ctermfg=darkgrey ctermbg=NONE hi DiffAdd ctermbg=4 hi DiffChange ctermbg=5 hi DiffDelete cterm=bold ctermfg=4 ctermbg=6 hi DiffText cterm=bold ctermbg=1 hi Comment ctermfg=darkcyan hi Constant ctermfg=brown hi Special ctermfg=5 hi Identifier ctermfg=6 hi Statement ctermfg=3 hi PreProc ctermfg=5 hi Type ctermfg=2 hi Underlined cterm=underline ctermfg=5 hi Ignore cterm=bold ctermfg=7 hi Ignore ctermfg=darkgrey hi Error cterm=bold ctermfg=7 ctermbg=1 "vim: sw=4



MySQL Cookbook