- VIM for beginners
- Level 0 — Сonquer The Fear
- Touch typing
- VIM Intro
- Level 1 — Survive
- Level 2 — Confidence
- Getting insert mode
- Normal mode
- VIM language
- Be persistent
- Level 3 — Mastering
- VIM is not an IDE
- VIM plugins
- Mappings
- VIM features
- Configuration
- Как освоить Vim?
- Что такое Vim?
- Как научиться работать в Vim?
- ▍1. Используйте vimtutor
- ▍2. Постоянно пользуйтесь Vim
- ▍3. Интегрируйте с Vim всё что сможете
- ▍4. Перенастройте клавишу Caps Lock (но это необязательно)
- ▍5. Глубже изучите Vim
- Итоги
VIM for beginners
Like any developer, you are constantly developing. You are learning new technologies by reading books, watching online lessons, attending some courses, and so on and so forth. You know that if you stop learning, you become uncompetitive. But have you ever thought about your performance? How do you improve that? If you don’t know how to answer than welcome under the cut.
Level 0 — Сonquer The Fear
Touch typing
This post is not about touch typing. Nevertheless, this is the first answer to the question above. To understand the rest of this article you have to manage touch typing.
VIM Intro
In this post, I will tell you how to improve your coding speed, how to navigate in code faster and how to get rid of your computer mouse. We will talk about VIM (the best text editor known to the human kind). In unskilful hands, it is just an awkward text editor, and no one knows how to exit from it. But actually, it is highly configurable text editor (or plugin to almost any IDE) which is built to allow you to manage your code in the most efficient way. VIM is not just a text editor. Not to seem crazy, but imagine that you do not code, you speak with a computer. So your coding process may be built in the following monologue:
- here I will type: string text = file.ReadAll();
- create an empty line above this one
- move all lines with TODO comments to the end of this file
- navigate to the function GetDirectoryFiles and copy all its content
- navigate to that «if» statement and replace its content with the text from the buffer
- center this line in the middle of the screen
But if you want to dance, you have to pay the piper. To «speak» with VIM you have to learn the language which has its own nouns, verbs, adjectives, etc. That is why VIM does not have shortcuts, it has sentences (e.g. change inner tag). When you learn the basics of this language you will be able to combine your own sentences depending on what you are going to do. Afterwhile you will understand that you don’t need your mouse anymore.
It is not easy to start learning this language because all its components should become your habit. And it is a painful challenge to yourself which can take at least 2 weeks, so think twice before you start. But if you overcome it, you will open a new world of your code managing.
The primary benefit of quick data entry is not the time saved in data entry per second, but the increased chance that your hands can keep up with your brain.
Level 1 — Survive
The most distinctive feature of VIM is that it has modes. We can define the main four of them:
- Normal mode — here you can type text commands and do navigation. To enter this mode press ESC
- Insert mode — in this mode you can type text as in other editors. To enter this mode press i
- Visual mode — here you can select text. To enter this mode press v
- Command mode — editor commands (like save, open, etc.). To enter this mode press :
Also, you have to learn basic navigation which works in a normal mode. Forget about arrows because they are slow to work with. When you are typing, your fingers are usually placed in the middle of your keyboard. Left hand on asdf and right hand on jkl;. And usually, you are navigating in your code up/down and rarely left/right (later we will speak about navigation within the line). So navigation in VIM is the following:
- down — j (looks like a down arrow)
- up — k
- left — h
- right — l
To get used to the basic movement you can play VIM Adventures game. Actually, this is all you have to know to get started. So, install vim plugin on your favorite IDE and practice. Keep in mind, it is gonna be hard.
Level 2 — Confidence
Ok, you decided to learn VIM and this is awesome. Let’s make sure you are doing it right. Your fingers got used to hjkl navigation and you also know how to change modes from one to another. If it is true, so you are ready.
Getting insert mode
You know you can enter this mode by pressing i on a keyboard. Let’s think that i stands for insert as insert text before the cursor. You can also press a which stands for append as append text after the cursor. It is easy to intensify these commands by changing the case, so the result would be the following: I inserts text before the first non-blank in the line and A appends text at the end of the current line.
To make your future work more pleasant you have to know command o which appends a new blank line after the current and O which does the same but before the current line.
These are the most often used insert mode-switching commands in VIM. If you adjust to hjkl navigation it will take a couple of days to get used to these commands. The more you sweat in training, the less you bleed in war.
Normal mode
Before we start to learn VIM language we should also improve our navigation skills. In this question command f (stands for find) will help us. This command is used to navigate within the current line. You type f and a letter to which you want to move the cursor. fP moves the cursor from the current position to the first occurrence of letter P. You can power up this command to F which does the same but changes the search direction.
VIM language
Now it is the time to become a crazy geek. You should «speak» with VIM in the normal mode. Firstly, let’s consider some constructions of VIM language:
Nouns:
w — word
s — sentence
p — paragraph
b — (block/parentheses)
t — tag
< , >, ( , ) , [ , ] — braces
» , ‘ — quotes
Verbs:
- v — visualize
- c — change (delete text and switch VIM into insert mode)
- d — delete and copy (delete text and does not change VIM mode)
- y — yank (means copy)
Adverbs:
- i — inside
- a — around
- t — till
- f — till (inclusive)
Pay attention that these commands may work by itself not as you expect. Moreover, when you create a VIM sentence, it should be sufficient and all constructions should be on their place, otherwise, you will get another result. Now let’s create some easy VIM sentences as an example:
- ciw — change inside word — deletes the whole word under cursor and switches to insert mode, unlike cw which deletes a word from cursor to the end of this word.
- cis — change inside sentence.
- ci» — change inside » brace — deletes all text between » braces.
- da> — delete around > brace — deletes all text inside curly braces including them.
- vip — visual inside paragraph — selects all paragraph.
- ctp — change till p — delete everything from here to the letter p.
To expand your VIM language right now I suggest you learn new VIM construction — number modifier. Let’s consider the following code:
And you want to remove all code inside <> of foo function. Using number modifier it is easy to do. Just type 2ci< — change inside curly braces 2 times.
Number modifier works not only in sentences but it works almost everywhere:
- 5j — moves the cursor down 5 times.
- 2fK — moves the cursor to the second occurrence of litter k in the line.
- 2iHello — insert Hello 2 times.
Be persistent
As you learn VIM you will find some new language constructions and expand your VIM language. Day by day it would be easier to «speak» with VIM. All the commands and language constructions are tightly coupled and created to maximize your performance, and it is proved by more than 20 years of VIM existence.
Level 3 — Mastering
You are on the way to become a VIM master. As you may found, this is not so easy to learn VIM. When you feel the power in your hands using VIM, you will want something more and this is what this part about. All topics are discovered superficially in order to let you decide what you want.
VIM is not an IDE
Yeah, VIM is not an IDE despite that you can setup it to perform almost all IDE functions. I am sure you won’t leave your favorite Visual Studio or WebStorm and that is why I prepared the list of plugins for your IDE and not only.
- VSVim for VisualStudio
- VS VIM for VSCode
- IdeaVim for WebStorm, IntelliJ IDEA (and other Jetbrains products)
- Sublime text has Vintage mode out of the box
- Vim mode for Atom
- XVim for XCode
- Hardcore! Do not repeat this at home! Google Chrome also has extensions for VIM-like navigation. (find it in Chrome Store)
Still, you have to keep in mind that the maximum performance can be achieved by using just VIM. Basically, it is suitable for small js/html/css projects, editing configuration files or just as a replacement of your notepad++ 🙂
VIM plugins
VIM has thousands of plugins for any caprice. Here you can find almost everything you want from file explorer and git integration to the build systems.
One of my favorite plugins is EasyMotion. It was created to speed up your navigation in VIM. EasyMotion is very sophisticated and deeply integrated within VIM philosophy. For example, if you just want to navigate to a specific line behind the current one, you can do this by pressing j key several times. In comparison, with EasyMotion you can press leader key (in my case TAB ) and j to highlight all the lines behind with different letters. All that has left to do is to press the letter which represents the line you need.
In my case, I pressed TAB key and ju to navigate to the appropriate line. It was the easiest example and as usual, in the world of VIM, you can craft almost any command according to your needs.
Mappings
This feature I decided to consider separately. You may think about mapping as key bindings for all modes. That is to say, you can bind some pattern to perform some actions in different modes.
So let’s look at the easy and real example. Almost every person who works in VIM does not change the mode from insert to normal by pressing ESC . We are doing it by pressing jj or jk because we have the following mapping: :imap jj ESC >. imap stands for insert mode mapping and means that it works only in insert mode.
You can map everything you want to do and this will save your time in future. Read more about mapping here.
VIM features
There are a lot of things to learn in VIM besides the features mentioned above. You definitely should pay attention to the following list:
- global commands
- search and replace
- macros and registers
- buffers
- tabs
- indents and foldings
- autocommands
They may exist in other development tools, but this is VIM. Day by day you will wonder how brilliant all these things are constructed. Check it out to make sure.
Configuration
There are a lot of VIM settings which have to be stored somewhere in order to use the same settings for all editors with VIM plugin. And this is the responsibility of the .vimrc file. By default, in Windows 10 this file is located in C:\Users\%username% . Here you can set up all mappings, autocommands, plugins, color scheme, and all other settings. I’ve found pretty good article how to set up your own .vimrc file so you can practice by yourself.
Note: Don’t put any lines in your .vimrc that you don’t understand
Источник
Как освоить Vim?
Осваивать Vim — это, пожалуй, страшно. Или, точнее, очень страшно. Речь идёт об изучении совершенно необычного подхода к редактированию кода, не говоря уже о работе с простым текстом. Многие несправедливо обвиняют тех, кто выбирает Vim, в том, что они впустую тратят время.
Я со всей уверенностью могу заявить о том, что Vim позволил мне повысить эффективность в деле написания программ. Работать стало удобнее (ниже я расскажу об этом более подробно). Я никому не хочу навязывать Vim, но очень рекомендую освоить этот редактор всем, кто занимается программированием, работает в сфере Data Science, в общем — тем, кто так или иначе пишет и редактирует некий код.
Если вам очень хочется узнать о том, стоит ли вам использовать Vim, и о том, кто и для чего им реально пользуется — взгляните на этот материал (кстати, не позвольте его названию, «Не пользуйтесь Vim», ввести себя в заблуждение). Ещё можете посмотреть это видео, которое, кстати, подготовил сам Люк Смит.
А теперь, учитывая всё вышесказанное, предлагаю поговорить о том, что такое, на самом деле, Vim!
Что такое Vim?
Отвечая на этот вопрос, я хочу ещё раз повторить то, что было сказано в самом начале статьи: «Vim — это редактор, реализующий совершенно необычный подход к редактированию кода, не говоря уже о работе с простым текстом».
В Vim имеется несколько «режимов работы», переключение между ними приводит к изменению функционала клавиатурных клавиш (например, клавиша W в режиме вставки, что неудивительно, позволяет ввести букву w, а вот в нормальном режиме она позволяет перемещать курсор вперёд на одно слово). При таком подходе клавиатура используется и для ввода символов, и для перемещения по тексту. Другими словами — при работе в Vim не нужна мышь.
Это очень хорошо в тех случаях, когда нужно постоянно «переключаться» между редактированием и просмотром кода. Обычно программисты именно так и работают. Если вы раньше никогда не пользовались Vim для работы с программным кодом, то вы даже не замечаете того, как много времени тратится на то, чтобы снять руку с клавиатуры и потянуться к мыши (или к трекпаду), затем — на то, чтобы переместить курсор туда, куда нужно, и наконец на то, чтобы вернуть руку на клавиатуру и приступить к вводу текста (в общем — тратится очень много времени).
Конечно, на то, чтобы привыкнуть к Vim, нужно некоторое время. И это — не прямая замена какой-нибудь IDE или редактора вроде VS Code. Но можно сказать, что Vim позволяет тому, кто умеет им пользоваться, значительно ускорить работу с кодом. Кроме того, интересно то, что его более простым аналогом является Vi — стандартный текстовый редактор большинства Unix-подобных систем, работающий в терминале.
Как научиться работать в Vim?
▍1. Используйте vimtutor
Меня не удивляет то, что в каждом руководстве по Vim рекомендуется начинать изучать этот текстовый редактор с vimtutor . Поэтому я, без зазрения совести, поступлю так же. Нет нужды играть ни в какие «Vim-игры» (хотя они и довольно интересны), или прибегать к программам, помогающим запоминать бесчисленные клавиатурные сокращения. Надо просто установить vimtutor и, когда найдётся 10-15 минут свободного времени, прорабатывать этот официальный учебник по Vim. И не пытайтесь сразу же запомнить все клавиатурные сокращения Vim; вы запомните их постепенно, снова и снова проходя уроки vimtutor .
Хочу отметить, что Windows-пользователям я рекомендую использовать WSL (Windows Subsystem for Linux, подсистему Windows для Linux) и для прохождения vimtutor , и, в целом, для работы с Vim. Лично я в Windows с Vim не работал, поэтому не могу обещать того, что при работе с ним в этой ОС всё будет точно так же, как в Linux.
▍2. Постоянно пользуйтесь Vim
Практика — это путь к совершенству. Это — главный принцип, которого стоит придерживаться при изучении чего-то нового. Изучение Vim — не исключение. Поэтому, пока вы изучаете Vim с помощью vimtutor , пользуйтесь этим редактором для решения реальных задач.
Используйте Vim как можно чаще. Нужно просмотреть текстовый файл? Запустите Vim. Хотите что-то по-быстрому изменить в Python-скрипте? Примените Vim. Делаете какие-то заметки? Делайте их с помощью Vim. В общем, полагаю, вы меня поняли. И каждый раз, когда работаете в Vim, всегда задавайтесь вопросом о том, какова наиболее эффективная последовательность нажатий на клавиши (то есть — наиболее короткая последовательность), позволяющая решить текущую задачу.
И попутно постарайтесь сократить использование мыши.
▍3. Интегрируйте с Vim всё что сможете
Используйте клавиатурные привязки Vim везде, где это возможно. Начните делать всё, что сможете, «в стиле Vim». Например, если вы пользуетесь браузером, основанным на Chromium (Chrome, Brave, Edge), или браузером Firefox, подумайте об установке расширения Vimium, которое позволяет пользоваться в браузере клавиатурными сокращениями Vim, отвечающими за перемещение по документу (H, J, K, L и так далее).
Если вы пользуетесь для работы с кодом некоей IDE — найдите плагин или расширение для добавления Vim-привязок в соответствующую среду. Например, пользователи PyCharm (или любой IDE от JetBrains) могут воспользоваться ideavim. А пользователи VS Code (в 2021 году этот инструмент уже ближе к IDE, чем к обычным текстовым редакторам) могут прибегнуть к расширению VSCodeVim.
В Jupyterlab можно включить привязки Vim для встроенного текстового редактора путём установки jupyterlab-vim, что позволит полностью эмулировать Vim в ячейках блокнотов.
Постарайтесь органично интегрировать Vim в свою рабочую среду и несколько недель поработайте по-новому. Я могу говорить о том, что после нескольких VSCode-сессий в стиле Vim мне стало гораздо удобнее пользоваться этим редактором. А ещё — я очень рад избавлению от мыши!
▍4. Перенастройте клавишу Caps Lock (но это необязательно)
Самая бесполезная клавиша, расположенная в самом лучшем месте клавиатуры. Именно так можно охарактеризовать клавишу Caps Lock. Поэтому советую превратить Caps Lock в Escape. Если вы интересуетесь Vim, то уже должны знать о том, что клавиша Escape используется в Vim для переключения режимов. Я очень советую тем, кто стремится к максимальной эффективности, воспользоваться вышеописанной модификацией.
Пользователи Windows и WSL могут использовать uncap — программу, которая превращает клавишу Caps Lock в Escape.
Пользователям macOS в плане переназначения клавиш повезло — они могут решить эту задачу, прибегнув к системным настройкам.
Если вы работаете в Linux — настроить всё как надо вам помогут StackOverflow и Google. Лично я (заслуженный пользователь Arch Linux) использую утилиту setxkbmap , с помощью которой делаю из Caps Lock ещё одну клавишу Escape. А потом включаю автозапуск утилиты при запуске системы:
▍5. Глубже изучите Vim
После того, как вы привыкнете к Vim и немного его освоите, придёт время для более глубокого освоения этого редактора ради дальнейшего повышения эффективности своего труда. Ниже я, основываясь на собственном опыте, привожу список самых полезных (и, пожалуй, уникальных для Vim) команд, применимых в нормальном режиме работы:
- ZZ — сохранить документ и выйти из Vim. Красивая команда.
- zz, zt, zb — прокрутка текста, перемещающая строку с курсором, соответственно, в центральную, в верхнюю или в нижнюю часть области просмотра.
- Ctrl+u, Ctrl+d — прокрутка области просмотра вверх или вниз на полстраницы.
- ciw — (Change Inside Word) удаление текущего слова и автоматический переход в режим вставки.
- C — удалить текст от позиции курсора до конца строки и перейти в режим вставки.
- dt — (Delete To ) удалить текст от позиции курсора до следующего вхождения указанного символа.
— (тильда, на стандартной клавиатуре вводится клавишей, находящейся под Escape) переключение регистра (верхний/нижний) текущего или выделенного символа.
Освоение подобного списка команд может показаться неподъёмной задачей. Но помните о том, что стоит стремиться к изучению нового через практику, а не через запоминание. Эти команды Vim, если взглянуть на них с другой точки зрения, показывают то, что этот редактор способен дать нам мощнейшие возможности, доступные без применения мыши или контекстных меню.
Если вас интересуют другие команды Vim — посмотрите это замечательное и довольно длительное видео, демонстрирующее прохождение уроков vimtutor , которое записал Вим Дизель (шучу — это всё тот же Люк). Тут собрано множество полезнейших советов по Vim.
Итоги
Вероятно, сейчас вы уже достаточно хорошо освоили Vim и значительно повысили свою скорость работы с кодом. И вы наконец сможете похвастаться перед пользователями Reddit или перед коллегами своими отточенными навыками редактирования текстов, когда в ходе работы вам не приходится убирать руки с основной части клавиатуры. Когда вы достигнете подобного уровня, вы можете развиваться в сфере Vim и дальше. Например — в следующих направлениях:
- Можно установить Neovim и поэкспериментировать с ним (это — отрефакторенный форк Vim, рассчитанный на высокий уровень расширяемости и на поддержку графического интерфейса).
- Можно перенести функционал Vim в терминал или интерпретатор командной строки, воспользовавшись vim-airline.
- Можно попробовать некоторые из популярных Vim-плагинов.
Желаю всем, кто дочитал до этого места, наслаждаться будущим, наполненным благами Vim (и освободиться от власти мыши или трекпада).
Источник