Vim это простой редактор текста, встроенный почти во все операционные системы Linux.
Руководство на русском языке
$ vimtutor ru
Первоначальная настройка
1.Установка
apt update apt install vim
2.Создание папки для тем
mkdir -p .vim/colors cd .vim/colors
3.Установка тем
gruvbox
wget https://raw.githubusercontent.com/morhetz/gruvbox/master/colors/gruvbox.vim
molokai
wget https://raw.githubusercontent.com/tomasr/molokai/master/colors/molokai.vim
better-molokai Лучшая тема, с исправленным цветом комментариев
wget https://raw.githubusercontent.com/ELouisYoung/vim-better-molokai/master/colors/better-molokai.vim
4.Цвет 256
echo 'export TERM=xterm-256color' >> $HOME/.bashrc
5.vimrc
Копировать содержимое .vimrc в .vimrc файл.
Режимы работы
- Normal mode (Нормальный режим) - режим по умолчанию, когда мы можем вводить команды i,a,r,u,ZZ,ZQ. При запуске Vim, вы находитесь в этом режиме.
- Command mode (Режим команд) - используется для выполнения команд. Для переключения надо в нормальном режиме набрать :
- Insert mode (Режим вставки) - используется для ввода текста. Для перехода в этот режим, нажмите клавишу "i"
- Replace mode(Режим замены) - используется для замены существующего текста. Для перехода в этот режим, нажмите клавишу "R"
- Visual mode (Режим визуального выделения) - используется для выделения текста для копирования, вырезания или изменения. Для перехода в этот режим, нажмите клавишу "v"
- Binary mode (Двоичный режим) - когда можно редактировать файл в двоичном/шестнадцатиричном режиме vim -b
Полезные статьи
Цвета в терминале
В .bashrc обязательно должен быть указан поддерживаемый тип терминала, т.к. по умолчанию set t_Co = 8
export TERM='xterm-256color' #или echo 'export TERM=xterm-256color' >> $HOME/.bash_profile
или в .vimrc
set t_Co=256
Темы для VIM
Посмотреть путь к VIM
:echo $VIMRUNTIME
Путь к темам
cd /usr/share/vim/vim*/colors/
Можно или скопировать тему в папку с темами или в локальную ~/.vim/colors
gruvbox
wget https://raw.githubusercontent.com/morhetz/gruvbox/master/colors/gruvbox.vim
molokai
wget https://raw.githubusercontent.com/tomasr/molokai/master/colors/molokai.vim
better-molokai Лучшая тема, с исправленным цветом комментариев
wget https://raw.githubusercontent.com/ELouisYoung/vim-better-molokai/master/colors/better-molokai.vim
Установить нормальный цвет комментариев
:hi Comment ctermfg=102 или :color desert
Установить бело-красный цвет выделения
:hi Visual ctermfg=230 ctermbg=196
Редактирование
Вставка/Удаление
Клавиша | Описание |
---|---|
Y | копировать в буфер |
D | удалить, вырезать в буфер |
P | вставить из буфера |
Режим выделения
Клавиша | Описание |
---|---|
v | выделить блок |
V | выделить строку |
Ctrl+V | выделить вертикальный блок |
Копирование
Клавиша | Описание | |
---|---|---|
yy | Копировать текущую строку | |
3yy | Скопировать 3 строки начиная со строки, где установлен курсор | |
y$ | Копировать всё от курсора до конца строки | |
y | Копировать с начала строки до курсора | |
yiw | Копировать текущее слово |
Вырезание
Клавиша | Описание |
---|---|
dd | вырезать текущую строку |
3dd | вырезать 3 строки начиная от курсора |
d$ | вырезать всё от курсора до конца строки |
Вставка
Клавиша | Описание |
---|---|
P | вставить до курсора |
p | вставить после курсора |
Сортировка
- Выделить блок V+стрелки
- Нажать :
- В строке :'<,'> написать sort
:'<,'>sort
Удалить дубликаты
:%sort u
Цифровая сортировка
:%sort n
Перемещение строки
"Ctrl-j – Move current line down "Ctrl-k – Move current line up nnoremap <c-j> :m .+1<CR>== nnoremap <c-k> :m .-2<CR>== inoremap <c-j> <Esc>:m .+1<CR>==gi inoremap <c-k> <Esc>:m .-2<CR>==gi vnoremap <c-j> :m '>+1<CR>gv=gv vnoremap <c-k> :m '<-2<CR>gv=gv
- yyp Дублирование текущей строки
- yapP Дублирование текущего параграфа
Посмотреть текущие настройки
Команда | Описание |
---|---|
set all | |
set! all | построчно |
set syntax? | Посмотреть конкретную настройку |
Комментарии
Закомментировать блок
- нажать Esc и перейти в командный режим
- нажать ctrl+v и перейти в визуальный режим
- используя стрелки ↑/↓ выбрать строки
- нажать Shift+i (большая I) и перейти в режим вставки
- вставить символ комментария % или #
- Два раза нажать EscEsc
Раскомментировать блок
- нажать Esc и перейти в командный режим
- нажать ctrl+v и перейти в визуальный режим
- используя стрелки выделить блок символов комментария #
- нажать x или d для удаления
Нарисовать строку из комментариев
В командном режиме набрать 10i# и ESC. В строке появится строка из 10 символов #
Скрыть комментарии
:set fdm=expr :set fde=getline(v:lnum)=~'^\\s#'?1:getline(prevnonblank(v:lnum))=~'^\\s#'?1:getline(nextnonblank(v:lnum))=~'^\\s*#'?1:0
Навести курсор на блок
Команда | Описание |
---|---|
zo | Раскрыть блок |
zc | Закрыть блок |
zi | Выключить блоки глобально |
Автоматическое форматирование кода
gg =G
- gg - переместить курсор в начало файла
- G переместить в конец файла
- = - проставить отступы
Полезные сочетания клавиш
ESC — переключение в командный режим
Настройки
Ярлык | Описание |
---|---|
Ctrl+G/set number! | включить отображение номеров строк |
set nonumber! | включить отображение номеров строк |
Номер строки+Enter | Перемещение к номеру строки |
color desert | Установить тему |
Команды режима ввода
Ярлык | Описание |
---|---|
i | Вставить перед курсором |
a | Вставить после курсора |
I | Вставить в начале строки |
A | Вставить в конце строки |
Основные команды перемещения(в командном режиме)
Ярлык | Описание |
---|---|
h/j/k/l | Переместить на один символ влево/вниз/вверх/вправо |
w | Переместить на одно слово вправо |
b | Переместить на одно слово влево |
w | переместить курсор на начало следующего слова |
b | переместить курсор на начало предыдущего слова |
e | переместить курсор на конец текущего слова |
W | Переместить на одно не пустое слово вправо |
B | Переместить на одно не пустое слово влево |
e | Переместить к концу текущего слова |
E | Перемещение к концу текущего не пустого слова |
O, 0, home | Перемещение к началу строки |
^ | Перемещение к первому не пустому символу в начале строки |
$$, end | Перемещение к концу строки |
% | Перемещение к соответствующей открывающей/закрывающей скобке |
Номер строки+Enter | Перемещение к номеру строки |
m | на половину ширины экрана |
g | на нижнюю строку |
e | до конца слова |
- | на строку вверх и на первый непустой символ |
+, Enter | на строку вниз и на первый непустой символ |
G | на последнюю строку |
H | на первую строку экрана |
M | на среднюю строку экрана |
L | на последнюю строку экрана |
w | на слово вперед |
b | на слово назад |
( | на предложение назад (до точки) |
) | на предложение вперед (до точки) |
{ | на абзац назад (до пустой строки) |
} | на абзац вперед (до пустой строки) |
:ju | список переходов |
0 - переместить курсор в начало строки
$ - переместить курсор в конец строки
gg - переместить курсор в начало файла
G - переместить курсор в конец файла
Редактирование текста i - вставить текст перед курсором
a - вставить текст после курсора
o - вставить новую строку после текущей строки и перейти в режим вставки
dd - вырезать текущую строку
yy - скопировать текущую строку
p - вставить скопированный или вырезанный текст после курсора
u - отменить последнее действие
Ctrl + r - повторить отмененное действие
Сохранение и выход из редактора :w - сохранить файл
:q - выйти из Vim
:wq - сохранить файл и выйти
Выход и работа с файлами
Ярлык | Описание |
---|---|
q | выход из vim |
q! | закрыть файл без сохранения |
qa! | закрыть все файлы без сохранения |
ZZ/wq/x | записать и выйти из vim |
wqa | закрыть все файлы с сохранением |
w !sudo tee % | Записать файл используя sudo |
Поиск и замена
Ярлык | Описание |
---|---|
/ подстрока | поиск подстроки |
? подстрока | обратный поиск подстроки |
n,N | поиск следующего совпадения/предыдущего совпадения |
/,? | повторить предыдущий, обратный поиск |
%s/что заменить/на что заменить/g | Заменить одно на другое |
0,10s/from/to/gc | Заменить в первых десяти строках from на to, c - опция подтверждения |
Удаление (командный режим)
Ярлык | Описание |
---|---|
d | |
dw | удаление слова |
d/паттерн | удаление от текущей позиции до паттерна |
D | Удаление до конца строки |
d, Shift+G | удаление до конца файла |
Выделение (командный режим)
Ярлык | Описание |
---|---|
yy | Выделение строки |
Вставка (командный режим)
Ярлык | Описание |
---|---|
Del, x | удаление символа под курсором |
X | удаление символа перед курсором |
u, :u | отмена последнего действия |
U | отменить все изменения, повлиявшие на текущую строку |
~ | перевести в верхний или нижний регистр в зависимости от текущего символа под курсором |
C | удалить от курсора и до конца строки с переходом в режим ввода |
D | удалить от текущего символа до конца строки |
dd | вырезать строку, на которой стоит курсор. Перед любой командой можно ввести числовой модификатор, который укажет сколько раз выполнить команду. Например: 3dd - удалит три строки начиная с текущей |
yy | копирует строку. Также можно использовать числовой модификатор |
p | вставить после текущей строки |
P | вставить перед текущей строкой |
<< — сдвиг влево текущей строки; >> — сдвиг вправо текущей строки; J — объединение текущей строки с последующей.
Работа с окнами (split)
Команда | Описание |
---|---|
split | Разбить окно на два |
3split | Разбить окно на три |
vsplit | Разбить по вертикали |
vim -o file1 file2 file3 | загрузит сразу три файла |
vim -O file1 file2 file3 | загрузит сразу три файла и разобьёт окна вертикально |
:vertical all | Сделать все окна вертикальными |
Ctrl+F | Скроллинг вперёд |
Ctrl+B | Скроллинг назад |
Ctrl+v | Переключение отображения сайд бай сайд |
Ctrl+n Ctrl+N | Разбивка окна вертикально |
Переключение между окнами
Ctrl+W + Vim команды перемещения | |
Ctrl+W + j | перемещение вниз |
Ctrl+W + k | перемещение наверх |
Ctrl+W + h | перемещение лево |
Ctrl+W + l | перемещение вправо |
Ctrl+W + t | перемещение на первое окно |
Ctrl+W + b | перемещение на последнее окно |
Ctrl+K и Ctrl+J | переключают окна местами |
Ctrl+H и Ctrl+L | переключают окна местами вертикально |
!ls | посмотреть файлы на диске |
q | |
wqall | записать все окна и выйти |
Ctrl + W + Plus and Ctrl + W + Minus keys will increase and decrease the size of the current window by one line.
Vim Commands Cheat Sheet
How to Exit
:q[uit] | Quit Vim. This fails when changes have been made. |
:q[uit]! | Quit without writing. |
:cq[uit] | Quit always, without writing. |
:wq | Write the current file and exit. |
:wq! | Write the current file and exit always. |
:wq {file} | Write to {file}. Exit if not editing the last |
:wq! {file} | Write to {file} and exit always. |
:[range]wq[!] | [file] Same as above, but only write the lines in [range]. |
ZZ | Write current file, if modified, and exit. |
ZQ | Quit current file and exit (same as ":q!"). |
Editing a File
:e[dit] | Edit the current file. This is useful to re-edit the current file, when it has been changed outside of Vim. |
:e[dit]! | Edit the current file always. Discard any changes to the current buffer. This is useful if you want to start all over again. |
:e[dit] {file} | Edit {file}. |
:e[dit]! {file} | Edit {file} always. Discard any changes to the current buffer. |
gf | Edit the file whose name is under or after the cursor. Mnemonic: "goto file". |
Inserting Text
a | Append text after the cursor [count] times. |
A | Append text at the end of the line [count] times. |
i | Insert text before the cursor [count] times. |
I | Insert text before the first non-blank in the line [count] times. |
gI | Insert text in column 1 [count] times. |
o | Begin a new line below the cursor and insert text, repeat [count] times. |
O | Begin a new line above the cursor and insert text, repeat [count] times. |
Inserting a file
:r[ead] [name] | Insert the file [name] below the cursor. |
:r[ead] !{cmd} | Execute {cmd} and insert its standard output below the cursor. |
Deleting Text
<Del> or x | Delete [count] characters under and after the cursor |
X | Delete [count] characters before the cursor |
d{motion} | Delete text that {motion} moves over |
dd | Delete [count] lines |
D | Delete the characters under the cursor until the end of the line |
{Visual}x or {Visual}d | Delete the highlighted text (for {Visual} see Selecting Text). |
{Visual}CTRL-H or {Visual} | When in Select mode: Delete the highlighted text |
{Visual}X or {Visual}D | Delete the highlighted lines |
:[range]d[elete] | Delete [range] lines (default: current line) |
:[range]d[elete] {count} | Delete {count} lines, starting with [range] |
Changing (or Replacing) Text
r{char} | replace the character under the cursor with {char}. |
R | Enter Insert mode, replacing characters rather than inserting |
~ | Switch case of the character under the cursor and move the cursor to the right. If a [count] is given, do that many characters. |
~{motion} | switch case of {motion} text. |
{Visual}~ | Switch case of highlighted text |
Substituting
:[range]s[ubstitute]/{pattern}/{string}/[c][e][g][p][r][i][I] [count] | For each line in [range] replace a match of {pattern} with {string}. |
:[range]s[ubstitute] [c][e][g][r][i][I] [count] :[range]&[c][e][g][r][i][I] [count] | Repeat last :substitute with same search pattern and substitute string, but without the same flags. You may add extra flags |
The arguments that you can use for the substitute commands: [c] Confirm each substitution. Vim positions the cursor on the matching string. You can type: 'y' to substitute this match 'n' to skip this match to skip this match 'a' to substitute this and all remaining matches {not in Vi} 'q' to quit substituting {not in Vi} CTRL-E to scroll the screen up {not in Vi} CTRL-Y to scroll the screen down {not in Vi}. [e] When the search pattern fails, do not issue an error message and, in particular, continue in maps as if no error occurred. [g] Replace all occurrences in the line. Without this argument, replacement occurs only for the first occurrence in each line. [i] Ignore case for the pattern. [I] Don't ignore case for the pattern. [p] Print the line containing the last substitute.
Copying and Moving Text
"{a-zA-Z0-9.%#:-"} | Use register {a-zA-Z0-9.%#:-"} for next delete, yank or put (use uppercase character to append with delete and yank) ({.%#:} only work with put). |
:reg[isters] | Display the contents of all numbered and named registers. |
:reg[isters] {arg} | Display the contents of the numbered and named registers that are mentioned in {arg}. |
:di[splay] [arg] | Same as :registers. |
["x]y{motion} | Yank {motion} text [into register x]. |
["x]yy | Yank [count] lines [into register x] |
["x]Y | yank [count] lines [into register x] (synonym for yy). |
{Visual}["x]y | Yank the highlighted text [into register x] (for {Visual} see Selecting Text). |
{Visual}["x]Y | Yank the highlighted lines [into register x] |
:[range]y[ank] [x] | Yank [range] lines [into register x]. |
:[range]y[ank] [x] {count} | Yank {count} lines, starting with last line number in [range] (default: current line), [into register x]. |
["x]p | Put the text [from register x] after the cursor [count] times. |
["x]P | Put the text [from register x] before the cursor [count] times. |
["x]gp | Just like "p", but leave the cursor just after the new text. |
["x]gP | Just like "P", but leave the cursor just after the new text. |
:[line]pu[t] [x] | Put the text [from register x] after [line] (default current line). |
:[line]pu[t]! [x] | Put the text [from register x] before [line] (default current line). |
Undo/Redo/Repeat
u | Undo [count] changes. |
:u[ndo] | Undo one change. |
CTRL-R | Redo [count] changes which were undone. |
:red[o] | Redo one change which was undone. |
U | Undo all latest changes on one line. {Vi: while not moved off of it} |
. | Repeat last change, with count replaced with [count]. |
Moving Around
Basic motion commands: k h l j
h or | [count] characters to the left (exclusive). |
l or or | [count] characters to the right (exclusive). |
k or or CTRL-P | [count] lines upward |
j or or CTRL-J or or CTRL-N | [count] lines downward (linewise). |
0 | To the first character of the line (exclusive). |
<Home> | To the first character of the line (exclusive). |
^ | To the first non-blank character of the line |
$ or <End> | To the end of the line and [count - 1] lines downward |
g0 or g<Home> | When lines wrap ('wrap on): To the first character of the screen line (exclusive). Differs from "0" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost character of the current line that is on the screen. Differs from "0" when the first character of the line is not on the screen. |
g^ | When lines wrap ('wrap' on): To the first non-blank character of the screen line (exclusive). Differs from "^" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the leftmost non-blank character of the current line that is on the screen. Differs from "^" when the first non-blank character of the line is not on the screen. |
g$ or g<End&gr; | When lines wrap ('wrap' on): To the last character of the screen line and [count - 1] screen lines downward (inclusive). Differs from "$" when a line is wider than the screen. When lines don't wrap ('wrap' off): To the rightmost character of the current line that is visible on the screen. Differs from "$" when the last character of the line is not on the screen or when a count is used. |
f{char} | To [count]'th occurrence of {char} to the right. The cursor is placed on {char} (inclusive). |
F{char} | To the [count]'th occurrence of {char} to the left. The cursor is placed on {char} (inclusive). |
t{char} | Till before [count]'th occurrence of {char} to the right. The cursor is placed on the character left of {char} (inclusive). |
T{char} | Till after [count]'th occurrence of {char} to the left. The cursor is placed on the character right of {char} (inclusive). |
; | Repeat latest f, t, F or T [count] times. |
, | Repeat latest f, t, F or T in opposite direction [count] times. |
- <minus> | [count] lines upward, on the first non-blank character (linewise). |
+ or CTRL-M or <CR> | [count] lines downward, on the first non-blank character (linewise). |
_ <underscore> | [count] - 1 lines downward, on the first non-blank character (linewise). |
<C-End> or G | Goto line [count], default last line, on the first non-blank character. |
<C-Home> or gg | Goto line [count], default first line, on the first non-blank character. |
<S-Right> or w | [count] words forward |
<C-Right> or W | [count] WORDS forward |
e | Forward to the end of word [count] |
E | Forward to the end of WORD [count] |
<S-Left> or b | [count] words backward |
<C-Left> or B | [count] WORDS backward |
ge | Backward to the end of word [count] |
gE | Backward to the end of WORD [count] |
These commands move over words or WORDS.
A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, ). This can be changed with the 'iskeyword' option.
A WORD consists of a sequence of non-blank characters, separated with white space. An empty line is also considered to be a word and a WORD.
( | [count] sentences backward |
) | [count] sentences forward |
{ | [count] paragraphs backward |
} | [count] paragraphs forward |
]] | [count] sections forward or to the next '{' in the first column. When used after an operator, then the '}' in the first column. |
][ | [count] sections forward or to the next '}' in the first column |
[[ | [count] sections backward or to the previous '{' in the first column |
[] | [count] sections backward or to the previous '}' in the first column |
Screen movement commands
z. | Center the screen on the cursor |
zt | Scroll the screen so the cursor is at the top |
zb | Scroll the screen so the cursor is at the bottom |
Marks
m{a-zA-Z} | Set mark {a-zA-Z} at cursor position (does not move the cursor, this is not a motion command). |
m' or m` | Set the previous context mark. This can be jumped to with the "''" or "``" command (does not move the cursor, this is not a motion command). |
:[range]ma[rk] {a-zA-Z} | Set mark {a-zA-Z} at last line number in [range], column 0. Default is cursor line. |
:[range]k{a-zA-Z} | Same as :mark, but the space before the mark name can be omitted. |
'{a-z} | To the first non-blank character on the line with mark {a-z} (linewise). |
'{A-Z0-9} | To the first non-blank character on the line with mark {A-Z0-9} in the correct file |
`{a-z} | To the mark {a-z} |
`{A-Z0-9} | To the mark {A-Z0-9} in the correct file |
:marks | List all the current marks (not a motion command). |
:marks {arg} | List the marks that are mentioned in {arg} (not a motion command). For example: |
Searching
/{pattern}[/] | Search forward for the [count]'th occurrence of {pattern} |
/{pattern}/{offset} | Search forward for the [count]'th occurrence of {pattern} and go {offset} lines up or down. |
/<CR> | Search forward for the [count]'th latest used pattern |
//{offset}<CR> | Search forward for the [count]'th latest used pattern with new. If {offset} is empty no offset is used. |
?{pattern}[?]<CR> | Search backward for the [count]'th previous occurrence of {pattern} |
?{pattern}?{offset}<CR> | Search backward for the [count]'th previous occurrence of {pattern} and go {offset} lines up or down |
?<CR> | Search backward for the [count]'th latest used pattern |
??{offset}<CR> | Search backward for the [count]'th latest used pattern with new {offset}. If {offset} is empty no offset is used. |
n | Repeat the latest "/" or "?" [count] times. |
N | Repeat the latest "/" or "?" [count] times in opposite direction. |
Selecting Text (Visual Mode)
To select text, enter visual mode with one of the commands below, and use motion commands to highlight the text you are interested in. Then, use some command on the text.
The operators that can be used are: ~ switch case d delete c change y yank > shift right < shift left ! filter through external command = filter through 'equalprg' option command gq format lines to 'textwidth' length
v | start Visual mode per character. |
V | start Visual mode linewise. |
<Esc> | exit Visual mode without making any changes |
How to Suspend
CTRL-Z | Suspend Vim, like ":stop". Works in Normal and in Visual mode. In Insert and Command-line mode, the CTRL-Z is inserted as a normal character. |
:sus[pend][!] or :st[op][!] | Suspend Vim. If the '!' is not given and 'autowrite' is set, every buffer with changes and a file name is written out. If the '!' is given or 'autowrite' is not set, changed buffers are not written, don't forget to bring Vim back to the foreground later! |
Daniel Gryniewicz / dang@fprintf.net