quarta-feira, 25 de fevereiro de 2009

VIM: Code Folding (comandos mais utilizados)

zR -> abre todos os foldings
zM -> fecha todos os foldings
za -> abre (quando fechando) / fecha (quando aberto) um folding.

VIM: movendo-se entre os arquivos de um projeto.

Para ir para um arquivo referenciado posicione o curso sobre a referência, e tecle:

gf (goto file)

Para retornar, tecle:

Ctrl + o

ou

:e#

Para abrir o arquivo em uma nova janela:

Ctrl + w, f

Para abrir o arquivo em uma nova aba:

Ctrl + w, gf

segunda-feira, 23 de fevereiro de 2009

VIM: ajustar compatibilidade com mouse (xterm).

Adicione ao .vimrc:

set nocompatible
set mouse=a

VIM: Backspace.

Adicione ao .vimrc:

set backspace=indent,eol,start

VIM: Janela com saida de execução/compilação.

Adicionar ao script do PyChecker:

if ( !hasmapto('PythonGrep(python)') && (maparg('') == '') )
map :call PythonGrep('python')
map! :call PythonGrep('python')
else
if ( !has("gui_running") || has("win32") )
echo "Python Error: No Key mapped.\n".
\ " is taken and a replacement was not assigned."
endif
endif

domingo, 22 de fevereiro de 2009

VIM: verificador de sintaxe python.

Instalar PyChecker:

sudo python setup.py install

Em seguida, instalar PyLint:

sudo python setup.py install

Adicionar ao .vimrc:

function PythonGrep(tool)
set lazyredraw
" Close any existing cwindows.
cclose
let l:grepformat_save = &grepformat
let l:grepprogram_save = &grepprg
set grepformat&vim
set grepformat&vim
let &grepformat = '%f:%l:%m'
if a:tool == "pylint"
let &grepprg = 'pylint --output-format=parseable --reports=n'
elseif a:tool == "pychecker"
let &grepprg = 'pychecker --quiet -q'
else
echohl WarningMsg
echo "PythonGrep Error: Unknown Tool"
echohl none
endif
if &readonly == 0 | update | endif
silent! grep! %
let &grepformat = l:grepformat_save
let &grepprg = l:grepprogram_save
let l:mod_total = 0
let l:win_count = 1
" Determine correct window height
windo let l:win_count = l:win_count + 1
if l:win_count <= 2 | let l:win_count = 4 | endif windo let l:mod_total = l:mod_total + winheight(0)/l:win_count | \ execute 'resize +'.l:mod_total " Open cwindow execute 'belowright copen '.l:mod_total nnoremap c :cclose
set nolazyredraw
redraw!
endfunction

if ( !hasmapto('PythonGrep(pylint)') && (maparg('') == '') )
map :call PythonGrep('pylint')
map! :call PythonGrep('pylint')
else
if ( !has("gui_running") || has("win32") )
echo "Python Pylint Error: No Key mapped.\n".
\ " is taken and a replacement was not assigned."
endif
endif

if ( !hasmapto('PythonGrep(pychecker)') && (maparg('') == '') )
map :call PythonGrep('pychecker')
map! :call PythonGrep('pychecker')
else
if ( !has("gui_running") || has("win32") )
echo "Python Pychecker Error: No Key mapped.\n".
\ " is taken and a replacement was not assigned."
endif
endif

Criar o plugin pychecker.vim e adicionar:

" Vim compiler file
" Compiler: Pychecker for Python
if exists("current_compiler")
finish
endif
let current_compiler = "pychecker"
if exists(":CompilerSet") != 2 " older Vim always used :setlocal
command -nargs=* CompilerSet setlocal
endif

CompilerSet makeprg=pychecker\ --quiet\ %
CompilerSet efm=%f:%l:%m


Fonte: http://vim.wikia.com/wiki/Integrate_Pylint_and_Pychecker_support

VIM: Code Folding.

Instale o plugin python_fold.

Seguem algumas teclas de atalho:

  • zj moves the cursor to the next fold.
  • zk moves the cursor to the previous fold.
  • zo opens a fold at the cursor.
  • zO open all folds under the cursor recursively.
  • zm fold more
  • zM closes all open folds.
  • zc close one fold under the cursor.
  • zC close all folds under the cursor recursively.
  • zr reduce folding:
  • zR decreases the foldlevel to zero — all folds will be open.
  • za when on a closed fold: open it. When on an open fold: close it.
  • zA when on a closed fold: open it recursively. When on an open fold: close it recursively
  • [z move to start of open fold.
  • ]z move to end of open fold.
Fonte:http://undefined.org.ua/blog/2008/01/19/moy-vim/?lang=en

VIM: NERDTree para explorar sistema de arquivos.

Adicione o plugin NERDTree.

Para usá-lo no VIM, faça:

:NERDTree

Para desabilitar:

:NERDTreeClose

Para as teclas de atalho, digite ?.

VIM: Adicionar e remover python breakpoints.

Adicione ao .vimrc:

python << EOF
import vim
def SetBreakpoint():
import re
nLine = int( vim.eval( 'line(".")'))

strLine = vim.current.line
strWhite = re.search( '^(\s*)', strLine).group(1)

vim.current.buffer.append(
"%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
{'space':strWhite, 'mark': '#' * 30}, nLine - 1)

for strLine in vim.current.buffer:
if strLine == "import pdb":
break
else:
vim.current.buffer.append( 'import pdb', 0)
vim.command( 'normal j1')

vim.command( 'map :py SetBreakpoint()')

def RemoveBreakpoints():
import re

nCurrentLine = int( vim.eval( 'line(".")'))

nLines = []
nLine = 1
for strLine in vim.current.buffer:
if strLine == 'import pdb' or strLine.lstrip()[:15] == 'pdb.set_trace()':
nLines.append( nLine)
nLine += 1

nLines.reverse()

for nLine in nLines:
vim.command( 'normal %dG' % nLine)
vim.command( 'normal dd')
if nLine < nCurrentLine:
nCurrentLine -= 1

vim.command( 'normal %dG' % nCurrentLine)

vim.command( 'map :py RemoveBreakpoints()')
EOF

Teclando F7 e Shift+F7 é possível inserir e remover os breakpoints.

Para compilar/executar o código basta:

:!python %

Fonte: http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/

VIM: Python Snippets.

Baixar e instalar o plugin imap.vim.

Adicionar ao .vimrc:

"Python
autocmd BufNewFile,BufRead *.py inorea
cfun =IMAP_PutTextWithMovement("def <++>(<++>):\n<++>\nreturn <++>")
autocmd BufRead,BufNewFile *.py inorea
cclass =IMAP_PutTextWithMovement("class <++>:\n<++>")
autocmd BufRead,BufNewFile *.py inorea
cfor =IMAP_PutTextWithMovement("for <++> in <++>:\n<++>")
autocmd BufRead,BufNewFile *.py
inorea cif =IMAP_PutTextWithMovement("if <++>:\n<++>")
autocmd BufRead,BufNewFile *.py
inorea cifelse =IMAP_PutTextWithMovement("if <++>:\n<++>\nelse:\n<++>")

Ps. Utilizar Ctrl+j para percorrer os campos <++> do snippet.

VIM: TagList.

Baixar o plugin aqui.

Em seguida, instalar em ~/.vim/plugin.

Ir para o diretório do projeto e executar o seguinte comando:

ctags -R *.py

Abrir o VIM e executar o seguinte comando:

:TlistToggle

Se preferir, adicione um atalho para este comando no .vimrc:

nnoremap F8 :TlistToggle

Para adicionar mais arquivos ao TagList, use:

:TlistAddFiles
ou
:TlistAddFilesRecursive

As teclas +, - e * expande, fecha e expande tudo na árvore de arquivos do TagList, respectivamente.

Para finalizar, adicione a linha abaixo ao .vimrc para que ao fechar o arquivo o TagList seja fechado também.

let Tlist_Exit_OnlyWindow = 1


Fonte: http://bgmerrell.blogspot.com/2008/02/first-of-all-let-me-introduce-ctags-and.html

VIM: Compilando com suporte a python.

Inicialmente, você deve baixar os fontes aqui.

Em seguida, escolha uma pasta e descompacte. Configure com o seguite comando:

./configure --enable-pythoninterp --enable-gui=no --prefix=/Users/garme/devel/vim --without-x

Faça:

make && make install

Se preferir, crie um atalho para a aplicação assim:

ln -s /Users/garme/devel/vim/bin/vim /usr/bin/vimpy

sábado, 21 de fevereiro de 2009

VIM: Pydoc.

Para acessar toda a documentação python no VIM é necessário baixar o plugin pydoc.vim. Para usá-lo basta:

:Pydoc

ou

:PydocSearch

VIM: Python completition.

Adicione a linha abaixo no seu .vimrc:

autocmd FileType python set omnifunc=pythoncomplete#Complete

Ps. Seu VIM obrigatoriamente tem que ter sido compilado com suporte ao python.

Agora basta utilizar a sequencia abaixo para completar o código:

Ctrl + x, Ctrl + o

VIM: Saltando entre seu código e as classas da python lib.

Execute o seguinte comando:

$ ctags -R -f ~/.vim/tags/python.ctags /usr/lib/python2.5/

Em seguida acrescente a seguinte linha ao seu .vimrc:

set tags+=$HOME/.vim/tags/python.ctags


Agora você poderá utilizar:

Ctrl + ] para saltar para o método/propriedade sob o curso na python lib
Ctrl + t para voltar


Fonte: http://blog.sontek.net/2008/05/11/python-with-a-modular-ide-vim/

VIM: .vimrc

Segue meu .vimrc:


set nocompatible " This is vim, not vi (Put this line first!)
"colorscheme koehler " Optional, but I like a black background
set smartcase " Only do case sensitive match on Upper Case
syntax on " Syntax highlight on
set showcmd " Show the command you have typed in
set showmatch " Show matching brackets or parentheses
set wildmenu " Show possible command tab completions
set ruler " Show useful information on the command line
set incsearch " Incremental searching
"set hlsearch " Highlight search results. Clear with :nohl
set nohlsearch
set expandtab " Expand tabs to spaces
set tabstop=2 " 4 spaces is one tab
set shiftwidth=2 " Should be the same as tabstop
set softtabstop=2 " Makes the spaces feel like real tabs
set smarttab " Backspace over expandtab
set noautoindent " Don't use this, use smartindent
set smartindent " Smarter indentation on new lines
filetype on " Try to figure out the right filetype
filetype plugin on " Filetype specific plugins
filetype indent on " Filetype specific intenting
set number " Set number lines


"Python
autocmd BufNewFile,BufRead *.py inorea cfun =IMAP_PutTextWithMovement("def<++>(<++>):\n<++>\nreturn <++>")
autocmd BufRead,BufNewFile *.py inorea cclass =IMAP_PutTextWithMovement("class<++>:\n<++>")
autocmd BufRead,BufNewFile *.py inorea cfor =IMAP_PutTextWithMovement("for<++> in <++>:\n<++>")
autocmd BufRead,BufNewFile *.py inorea cif =IMAP_PutTextWithMovement("if<++>:\n<++>")
autocmd BufRead,BufNewFile *.py inorea celse =IMAP_PutTextWithMovement("if<++>:\n<++>\nelse:\n<++>")
autocmd BufRead,BufNewFile *.py inorea cwhile =IMAP_PutTextWithMovement("while<++>:\n<++>")
autocmd BufRead,BufNewFile *.py inorea cfrom =IMAP_PutTextWithMovement("from<++> import <++>")


" comment lines out with #
map cl :'<,'>s/^/#/g
" " uncomment lines commented with #
map cu :'<,'>s/^#//g
" " toggle line numbers
" map :set nu!
" " open new tab
" map :tabnew
" " tab navigation
" map gT
" map gt
" " close all tabs without saving
" map :tabdo q
" " close all tabs with saving
" map :tabdo wq


Ps. Dica de snipplets: http://vim.wikia.com/wiki/Snippets_for_JavaScript,_HTML_and_Python

sexta-feira, 20 de fevereiro de 2009

VIM: Scroll up e Scroll down.

ctrl + y = up
ctrl + e = down

Dica: ver trechos de código acima/abaixo sem mover o cursor.

quinta-feira, 19 de fevereiro de 2009

VIM: Inserindo texto em linhas diferentes, mas na mesma coluna.

Para adicionar algum texto em uma determinada coluna em diferentes linhas basta:
1. teclar crtl + v (entra no modo visual para que possa marcar as linhas na posição desejada)
2. teclar I (entra no modo de insersão)
3. digitar algo
4. teclar esc.

Pronto! =)

Dica: comentar blocos de código.