Saltar a contenido

Vim Cheatsheet

Sinopsis

Vim es un editor de texto altamente configurable construido para hacer crear y cambiar cualquier tipo de texto muy eficiente. Es una versión mejorada del editor vi distribuida con la mayoría de los sistemas UNIX.

Mandos de movimiento

h, j, k, l    # Left, down, up, right
w             # Next word
b             # Previous word
e             # End of word
0             # Beginning of line
^             # First non-blank character
$             # End of line
gg            # Go to first line
G             # Go to last line
:n            # Go to line n
Ctrl+f        # Page down
Ctrl+b        # Page up
Ctrl+d        # Half page down
Ctrl+u        # Half page up

Saltando

%             # Jump to matching bracket
*             # Find next occurrence of word under cursor
#             # Find previous occurrence of word under cursor
n             # Next search result
N             # Previous search result
``            # Jump back to previous position
'.            # Jump to last edit

Modos

Mode Switching

i             # Insert mode (before cursor)
a             # Insert mode (after cursor)
I             # Insert at beginning of line
A             # Insert at end of line
o             # Open new line below
O             # Open new line above
v             # Visual mode
V             # Visual line mode
Ctrl+v        # Visual block mode
:             # Command mode
Esc           # Return to normal mode

Edición de Comandos

Edición básica

x             # Delete character under cursor
X             # Delete character before cursor
dd            # Delete line
D             # Delete from cursor to end of line
dw            # Delete word
d$            # Delete to end of line
d0            # Delete to beginning of line
yy            # Copy (yank) line
yw            # Copy word
y$            # Copy to end of line
p             # Paste after cursor
P             # Paste before cursor
u             # Undo
Ctrl+r        # Redo
.             # Repeat last command

Edición avanzada

cc            # Change entire line
cw            # Change word
c$            # Change to end of line
r             # Replace single character
R             # Replace mode
s             # Substitute character
S             # Substitute line
~             # Toggle case
>>            # Indent line
<<            # Unindent line
J             # Join lines

Búsqueda y sustitución

Búsqueda

/pattern      # Search forward
?pattern      # Search backward
n             # Next match
N             # Previous match
*             # Search for word under cursor (forward)
#             # Search for word under cursor (backward)
:noh          # Clear search highlighting

Sustitución

:s/old/new/           # Replace first occurrence in line
:s/old/new/g          # Replace all occurrences in line
:%s/old/new/g         # Replace all occurrences in file
:%s/old/new/gc        # Replace with confirmation
:5,10s/old/new/g      # Replace in lines 5-10

Operaciones de archivo

Administración de archivos

:w            # Save file
:w filename   # Save as filename
:q            # Quit
:q!           # Quit without saving
:wq           # Save and quit
:x            # Save and quit (same as :wq)
ZZ            # Save and quit (normal mode)
ZQ            # Quit without saving (normal mode)
:e filename   # Edit file
:r filename   # Read file into current buffer

Buffer Management

:ls           # List buffers
:b n          # Switch to buffer n
:bn           # Next buffer
:bp           # Previous buffer
:bd           # Delete buffer
:split        # Horizontal split
:vsplit       # Vertical split
Ctrl+w h/j/k/l # Navigate between splits
Ctrl+w w      # Switch between splits

Modo visual

Selección visual

v             # Character-wise visual mode
V             # Line-wise visual mode
Ctrl+v        # Block-wise visual mode
o             # Move to other end of selection
gv            # Reselect last visual selection

Operaciones visuales

d             # Delete selection
y             # Yank (copy) selection
c             # Change selection
>             # Indent selection
``<             # Unindent selection
=             # Auto-indent selection
u             # Lowercase selection
U             # Uppercase selection

Objetos de texto

Selección de objetos de texto

iw            # Inner word
aw            # A word (including spaces)
is            # Inner sentence
as            # A sentence
ip            # Inner paragraph
ap            # A paragraph
i"            # Inner quotes
a"            # A quotes (including quotes)
i(            # Inner parentheses
a(            # A parentheses (including parens)
it            # Inner tag (HTML/XML)
at            # A tag (HTML/XML)

Ejemplos de uso

diw           # Delete inner word
ciw           # Change inner word
yi"           # Yank text inside quotes
da(           # Delete text including parentheses

Macros

Grabación y Reproducción de Macros

qa            # Start recording macro in register 'a'
q             # Stop recording
@a            # Play macro from register 'a'
@@            # Repeat last macro
5@a           # Play macro 5 times

Ejemplos Macro

# Record a macro to add semicolon at end of line
qa            # Start recording
A;            # Go to end of line and add semicolon
Esc           # Return to normal mode
q             # Stop recording
@a            # Play macro

Registros

Utilizando Registros

"ay           # Yank into register 'a'
"ap           # Paste from register 'a'
:reg          # Show all registers
:reg a        # Show register 'a'
"0p           # Paste from yank register (register 0)
"+y           # Yank to system clipboard
"+p           # Paste from system clipboard

Marcas

Ajuste y uso de marcas

ma            # Set mark 'a' at current position
'a            # Jump to mark 'a'
`a            # Jump to exact position of mark 'a'
:marks        # Show all marks
''            # Jump to previous position
'.            # Jump to last edit position

Folding

Mandos plegados

zf            # Create fold
zo            # Open fold
zc            # Close fold
za            # Toggle fold
zR            # Open all folds
zM            # Close all folds
zd            # Delete fold

Configuración

Basic .vimrc Ajustes

" Enable syntax highlighting
syntax on

" Show line numbers
set number

" Enable mouse support
set mouse=a

" Set tab width
set tabstop=4
set shiftwidth=4
set expandtab

" Enable auto-indentation
set autoindent
set smartindent

" Show matching brackets
set showmatch

" Highlight search results
set hlsearch

" Incremental search
set incsearch

" Case insensitive search
set ignorecase
set smartcase

" Enable file type detection
filetype on
filetype plugin on
filetype indent on

" Set color scheme
colorscheme desert

" Show status line
set laststatus=2

" Enable clipboard
set clipboard=unnamedplus

Configuración avanzada

" Leader key
let mapleader = ","

" Custom key mappings
nnoremap <leader>``w :w<CR>
nnoremap <leader>q :q<CR>
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

" Auto-completion
set wildmenu
set wildmode=list:longest

" Backup and swap files
set backup
set backupdir=~/.vim/backup
set directory=~/.vim/swap

" Persistent undo
set undofile
set undodir=~/.vim/undo

Plugins

Plugin Managers

" Vim-Plug (add to .vimrc)
call plug#begin('~/.vim/plugged')
Plug 'preservim/nerdtree'
Plug 'vim-airline/vim-airline'
Plug 'tpope/vim-fugitive'
call plug#end()

" Install plugins: :PlugInstall
" Update plugins: :PlugUpdate

Plugins populares

" File explorer
Plug 'preservim/nerdtree'
:NERDTree

" Status line
Plug 'vim-airline/vim-airline'

" Git integration
Plug 'tpope/vim-fugitive'
:Git status

" Fuzzy finder
Plug 'ctrlpvim/ctrlp.vim'
Ctrl+p

" Auto-completion
Plug 'ycm-core/YouCompleteMe'

" Syntax checking
Plug 'vim-syntastic/syntastic'

Command Line

Ex Comandos

:help         # Open help
:help topic   # Help on specific topic
:version      # Show version
:set          # Show all options
:set option   # Show specific option
:set option=value # Set option value
:!command     # Execute shell command
:r !command   # Read command output into buffer

Mandos útiles

:retab        # Convert tabs to spaces
:sort         # Sort lines
:sort u       # Sort and remove duplicates
:%!xxd        # Hex dump
:%!xxd -r     # Reverse hex dump
:g/pattern/d  # Delete lines matching pattern
:v/pattern/d  # Delete lines not matching pattern

Características avanzadas

Múltiples archivos

:args *.txt   # Open multiple files
:next         # Next file
:prev         # Previous file
:first        # First file
:last         # Last file
:argdo %s/old/new/g # Execute command on all files

Período de sesiones

:mksession session.vim  # Save session
:source session.vim     # Load session
vim -S session.vim      # Start with session

Diff Mode

vimdiff file1 file2     # Start diff mode
:diffthis               # Make current window part of diff
:diffoff                # Turn off diff mode
]c                      # Next difference
[c                      # Previous difference
do                      # Diff obtain (get change)
dp                      # Diff put (put change)

Consejos y trucos

Consejos de productividad

# Quick file switching
Ctrl+^        # Switch to alternate file

# Quick line duplication
yyp           # Duplicate current line

# Quick word completion
Ctrl+n        # Next completion
Ctrl+p        # Previous completion

# Quick bracket matching
%             # Jump to matching bracket

# Quick indentation
=G            # Auto-indent from cursor to end
gg=G          # Auto-indent entire file

Comandos de ahorro de tiempo

# Change case
guu           # Lowercase line
gUU           # Uppercase line
g~~           # Toggle case of line

# Join lines with space
J             # Join current line with next

# Increment/decrement numbers
Ctrl+a        # Increment number under cursor
Ctrl+x        # Decrement number under cursor

# Quick substitution
&             # Repeat last substitution

Solución de problemas

Cuestiones comunes

# Stuck in insert mode
Esc           # Return to normal mode

# Can't save file
:w!           # Force write
:w filename   # Save with different name

# Accidental recording
q             # Stop recording macro

# Clear search highlighting
:noh          # No highlight

# Reset to defaults
:set all&     # Reset all options

Recursos

  • Documentación oficial: :help_
  • Vim Wiki: vim.fandom.com
  • Tutorial interactivo: vimtutor
  • ** Recursos en línea**: vim.org