Global

  • :h[elp] termo - abrir ajuda para termo
  • :sav[eas] ficheiro - gravar como
  • :clo[se] - fechar painel actual
  • :ter[minal] - open a terminal window
  • K - abrir página do manual para o termo onde está o cursor
Tip Run vimtutor in a terminal to learn the first Vim commands.

Movimento do cursor

  • h - mover o cursor para a esquerda
  • j - mover o cursor para baixo
  • k - mover o cursor para cima
  • l - mover o cursor para a direita
  • gj - move cursor down (multi-line text)
  • gk - move cursor up (multi-line text)
  • H - ir para o topo do ecrã
  • M - ir para o meio do ecrã
  • L - ir para o fundo do ecrã
  • w - ir para o início da próxima palavra
  • W - ir para o início da próxima palavra (podendo conter pontuação)
  • e - ir para o fim da próxima palavra
  • E - ir para o fim da próxima palavra (podendo conter pontuação)
  • b - ir para o início da palavra anterior
  • B - ir para o início da palavra anterior (podendo conter pontuação)
  • ge - jump backwards to the end of a word
  • gE - jump backwards to the end of a word (words can contain punctuation)
  • % - ir para o carácter correspondente (pares reconhecidos originalmente: '()', '{}', '[]' - use :h matchpairs no vim para mais informação
  • 0 - ir para o início da linha
  • ^ - ir para o primeiro carácter da linha que não seja espaço
  • $ - ir para o fim da linha
  • g_ - ir para o último carácter da linha que não seja espaço
  • gg - ir para a primeira linha do documento
  • G - ir para a última linha do documento
  • 5gg or 5G - ir para a linha 5
  • gd - move to local declaration
  • gD - move to global declaration
  • fx - ir para a próxima ocorrência do caracter 'x'
  • tx - ir para o carácter anterior à próxima ocorrência do caracter 'x'
  • Fx - ir para a ocorrência anterior do caracter 'x'
  • Tx - ir para depois da ocorrência anterior do caracter 'x'
  • ; - repetir movimento f, t, F ou T
  • , - repetir movimento f, t, F ou T, no sentido contrário
  • } - ir para o próximo parágrafo (ou função/bloco, ao editar código)
  • { - ir para o parágrafo anterior (ou função/bloco, ao editar código)
  • zz - centrar o cursor no ecrã
  • zt - position cursor on top of the screen
  • zb - position cursor on bottom of the screen
  • Ctrl + e - move screen down one line (without moving cursor)
  • Ctrl + y - move screen up one line (without moving cursor)
  • Ctrl + b - retroceder um ecrã completo
  • Ctrl + f - avançar um ecrã completo
  • Ctrl + d - avançar meio ecrã
  • Ctrl + u - retroceder meio ecrã
Tip Para repetir um movimento do cursor adicione um prefixo numérico. Por exemplo, 4j move o cursor 4 linhas para baixo.

Modo de inserção - inserir/acrescentar texto

  • i - inserir antes do cursor
  • I - inserir no início da linha
  • a - inserir depois do cursor
  • A - inserir no fim da linha
  • o - inserir uma nova linha por baixo da actual
  • O - inserir uma nova linha por cima da actual
  • ea - inserir no fim da palavra
  • Ctrl + h - delete the character before the cursor during insert mode
  • Ctrl + w - delete word before the cursor during insert mode
  • Ctrl + j - begin new line during insert mode
  • Ctrl + t - indent (move right) line one shiftwidth during insert mode
  • Ctrl + d - de-indent (move left) line one shiftwidth during insert mode
  • Ctrl + n - insert (auto-complete) next match before the cursor during insert mode
  • Ctrl + p - insert (auto-complete) previous match before the cursor during insert mode
  • Ctrl + rx - insert the contents of register x
  • Ctrl + ox - Temporarily enter normal mode to issue one normal-mode command x.
  • Esc or Ctrl + c - sair do modo de inserção

Edição

  • r - substituir um único carácter
  • R - replace more than one character, until ESC is pressed.
  • J - juntar a linha seguinte com a linha actual
  • gJ - join line below to the current one without space in between
  • gwip - reflow paragraph
  • g~ - switch case up to motion
  • gu - change to lowercase up to motion
  • gU - change to uppercase up to motion
  • cc - substituir a linha toda
  • c$ or C - substituir até ao fim da linha
  • ciw - change (replace) entire word
  • cw or ce - substituir até ao fim da palavra actual
  • s - apagar um carácter e substituir texto
  • S - apagar um carácter e substituir até ao fim da linha (igual ao cc)
  • xp - transpor duas letras (cortar e colar)
  • u - anular
  • U - restore (undo) last changed line
  • Ctrl + r - refazer
  • . - repetir o último comando

Marcação de texto (modo visual)

  • v - começar modo visual, marcar linhas e executar um comando (como o y - copiar)
  • V - começar modo visual de linha
  • o - ir alternadamente para o fim/início da área marcada
  • Ctrl + v - iniciar modo visual de bloco
  • O - ir alternadamente para o fim/início do bloco na linha actual
  • aw - marcar uma palavra
  • ab - marcar bloco dentro de (), incluindo ()
  • aB - marcar bloco dentro de {}, incluindo {}
  • at - a block with <> tags
  • ib - marcar bloco dentro de (), excluindo ()
  • iB - marcar bloco dentro de {}, excluindo {}
  • it - inner block with <> tags
  • Esc or Ctrl + c - sair do modo visual
Tip Instead of b or B one can also use ( or { respectively.

Comandos no modo visual

  • > - deslocar texto para a direita
  • < - deslocar texto para a esquerda
  • y - copiar texto marcado
  • d - apagar texto marcado
  • ~ - alternar maiúsculas/minúsculas
  • u - change marked text to lowercase
  • U - change marked text to uppercase

Registos

  • :reg[isters] - mostrar conteúdo dos registos
  • "xy - copiar para o registo 'x'
  • "xp - colar conteúdo do registo 'x'
  • "+y - yank into the system clipboard register
  • "+p - paste from the system clipboard register
Tip Os registos são guardados em ~/.viminfo e serão carregados novamente quando reiniciar o vim
Tip Special registers:

0 - last yank
" - unnamed register, last delete or yank
% - current file name
# - alternate file name
* - clipboard contents (X11 primary)
+ - clipboard contents (X11 clipboard)
/ - last search pattern
: - last command-line
. - last inserted text
- - last small (less than a line) delete
= - expression register
_ - black hole register

Marcas

  • :marks - lista das marcas
  • ma - definir a marca 'a' na posição actual
  • `a - ir para a posição da marca 'a'
  • y`a - copiar texto da posição actual até à marca 'a'
  • `0 - go to the position where Vim was previously exited
  • `" - go to the position when last editing this file
  • `. - go to the position of the last change in this file
  • `` - go to the position before the last jump
  • :ju[mps] - list of jumps
  • Ctrl + i - go to newer position in jump list
  • Ctrl + o - go to older position in jump list
  • :changes - list of changes
  • g, - go to newer position in change list
  • g; - go to older position in change list
  • Ctrl + ] - jump to the tag under cursor
Tip To jump to a mark you can either use a backtick (`) or an apostrophe ('). Using an apostrophe jumps to the beginning (first non-blank) of the line holding the mark.

Macros

  • qa - começar a gravar a macro 'a'
  • q - parar de gravar a macro
  • @a - correr a macro 'a'
  • @@ - correr novamente a última macro executada

Cortar/copiar e colar

  • yy - copiar uma linha
  • 2yy - copiar duas linhas
  • yw - copiar os caracteres até ao início da próxima palavra
  • yiw - yank (copy) word under the cursor
  • yaw - yank (copy) word under the cursor and the space after or before it
  • y$ or Y - copiar até ao fim da linha
  • p - colar depois do cursor
  • P - colar antes do cursor
  • gp - put (paste) the clipboard after cursor and leave cursor after the new text
  • gP - put (paste) before cursor and leave cursor after the new text
  • dd - cortar uma linha
  • 2dd - cortar duas linhas
  • dw - cortar até ao início da próxima palavra
  • diw - delete (cut) word under the cursor
  • daw - delete (cut) word under the cursor and the space after or before it
  • :3,5d - delete lines starting from 3 to 5
Tip You can also use the following characters to specify the range:
e.g.

:.,$d - From the current line to the end of the file
:.,1d - From the current line to the beginning of the file
:10,$d - From the 10th line to the beginning of the file

  • :g/{pattern}/d - delete all lines containing pattern
  • :g!/{pattern}/d - delete all lines not containing pattern
  • d$ or D - cortar até ao fim da linha (igual ao D)
  • x - cortar o carácter actual

Indent text

  • >> - indent (move right) line one shiftwidth
  • << - de-indent (move left) line one shiftwidth
  • >% - indent a block with () or {} (cursor on brace)
  • <% - de-indent a block with () or {} (cursor on brace)
  • >ib - indent inner block with ()
  • >at - indent a block with <> tags
  • 3== - re-indent 3 lines
  • =% - re-indent a block with () or {} (cursor on brace)
  • =iB - re-indent inner block with {}
  • gg=G - re-indent entire buffer
  • ]p - paste and adjust indent to current line

Sair

  • :w - gravar ficheiro, mas sem sair
  • :w !sudo tee % - gravar o ficheiro actual com sudo
  • :wq or :x or ZZ - gravar e sair
  • :q - sair (não sai se houver alterações por gravar)
  • :q! or ZQ - sair sem gravar alterações
  • :wqa - write (save) and quit on all tabs

Procurar e substituir

  • /pattern - procurar por próxima ocorrência de padrão
  • ?pattern - procurar por ocorrência anterior de padrão
  • \vpattern - padrão 'muito mágico': caracteres não-alfanuméricos são interpretados como símbolos especiais de expressões regulares (sem necessidade de escape)
  • n - repetir procura na mesma direcção
  • N - repetir procura na direção oposta
  • :%s/old/new/g - substituir todas as ocorrências de 'old' por 'new' no documento
  • :%s/old/new/gc - substituir todas as ocorrências de 'old' por 'new' no documento, com confirmação
  • :noh[lsearch] - remover destaque das ocorrências encontradas

Procurar em múltiplos ficheiros

  • :vim[grep] /pattern/ {`{file}`} - procurar por padrão em múltiplos ficheiros
e.g. :vim[grep] /foo/ **/*
  • :cn[ext] - ir para a próxima ocorrência
  • :cp[revious] - ir para a ocorrência anterior
  • :cope[n] - abrir uma janela com a lista de ocorrências encontradas
  • :ccl[ose] - close the quickfix window

Separadores

  • :tabnew or :tabnew {page.words.file} - abrir um ficheiro num novo separador
  • Ctrl + wT - mover a janela dividida actual para o seu próprio separador
  • gt or :tabn[ext] - ir para o próximo separador
  • gT or :tabp[revious] - ir para o separador anterior
  • #gt - ir para o separador número '#'
  • :tabm[ove] # - mover o separador actual para a posição '#' (começa no zero)
  • :tabc[lose] - fechar o separador actual e todas as suas janelas
  • :tabo[nly] - fechar todos os separadores excepto o actual
  • :tabdo command - correr commando para todos os separadores (por exemplo, :tabdo q - fecha todos os separadores abertos)

Trabalhar com múltiplos ficheiros

  • :e[dit] ficheiro - editar um ficheiro numa nova área de memória temporária
  • :bn[ext] - ir para a próxima área de memória temporária
  • :bp[revious] - ir para a área de memória temporária anterior
  • :bd[elete] - apagar uma área de memória temporária (fechar um ficheiro)
  • :b[uffer]# - go to a buffer by #
  • :b[uffer] file - go to a buffer by file
  • :ls or :buffers - listar as áreas de memória temporárias abertas
  • :sp[lit] ficheiro - abrir um ficheiro numa nova área de memória temporária e dividir a janela
  • :vs[plit] ficheiro - abrir um ficheiro numa nova área de memória temporária e dividir a janela verticalmente
  • :vert[ical] ba[ll] - edit all buffers as vertical windows
  • :tab ba[ll] - edit all buffers as tabs
  • Ctrl + ws - dividir a janela
  • Ctrl + wv - dividir janela verticalmente
  • Ctrl + ww - alternar janelas
  • Ctrl + wq - sair de uma janela
  • Ctrl + wx - exchange current window with next one
  • Ctrl + w= - make all windows equal height & width
  • Ctrl + wh - mover o cursor para a janela da esquerda (divisão vertical)
  • Ctrl + wl - mover o cursor para a janela da direita (divisão vertical)
  • Ctrl + wj - mover o cursor para a janela de baixo (divisão horizontal)
  • Ctrl + wk - mover o cursor para a janela de cima (divisão horizontal)
  • Ctrl + wH - make current window full height at far left (leftmost vertical window)
  • Ctrl + wL - make current window full height at far right (rightmost vertical window)
  • Ctrl + wJ - make current window full width at the very bottom (bottommost horizontal window)
  • Ctrl + wK - make current window full width at the very top (topmost horizontal window)

Diff

  • zf - manually define a fold up to motion
  • zd - delete fold under the cursor
  • za - toggle fold under the cursor
  • zo - open fold under the cursor
  • zc - close fold under the cursor
  • zr - reduce (open) all folds by one level
  • zm - fold more (close) all folds by one level
  • zi - toggle folding functionality
  • ]c - jump to start of next change
  • [c - jump to start of previous change
  • do or :diffg[et] - obtain (get) difference (from other buffer)
  • dp or :diffpu[t] - put difference (to other buffer)
  • :diffthis - make current window part of diff
  • :dif[fupdate] - update differences
  • :diffo[ff] - switch off diff mode for current window
Tip The commands for folding (e.g. za) operate on one level. To operate on all levels, use uppercase letters (e.g. zA).
Tip To view the differences of files, one can directly start Vim in diff mode by running vimdiff in a terminal. One can even set this as git difftool.