Что такое vim в linux
Vim is a terminal text editor. It is an extended version of vi with additional features, including syntax highlighting, a comprehensive help system, native scripting (Vim script), a visual mode for text selection, comparison of files ( vimdiff(1) ), and tools with restricted capabilities such as rview(1) and rvim(1) .
Installation
Install one of the following packages:
- vim — with Python, Lua, Ruby and Perl interpreters support but without GTK/X support.
- gvim — which also provides the same as the above vim package with GTK/X support.
- The vim package is built without Xorg support; specifically the +clipboard feature is missing, so Vim will not be able to operate with the primary and clipboardselection buffers. The gvim package provides also the CLI version of Vim with the +clipboard feature.
- The unofficial repository herecura also provides a number of Vim/gVim variants: vim-cli , vim-gvim-common , vim-gvim-gtk3 , vim-rt and vim-tiny .
Usage
For a basic overview on how to use Vim, follow the vim tutorial by running either vimtutor (for the terminal version) or gvimtutor (for the graphical version).
Vim includes a broad help system that can be accessed with the :h subject command. Subjects include commands, configuration options, key bindings, plugins etc. Use the :h command (without any subject) for information about the help system and jumping between subjects.
Configuration
Vim’s user-specific configuration file is located in the home directory:
/.vimrc , and Vim files of current user are located inside
/.vim/ . The global configuration file is located at /etc/vimrc . Global Vim files such as defaults.vim and archlinux.vim are located inside /usr/share/vim/ .
For gVim, the user-specific configuration file is located at
/.gvimrc and the global configuration file is located at /etc/gvimrc .
-
Commonly expected behavior such as syntax highlighting is enabled in defaults.vim , which is loaded when no
/.vimrc is present. Add let skip_defaults_vim=1 to /etc/vimrc to disable loading of defaults.vim completely. [1]. Alternatively, to enable defaults.vim even when
Clipboard
Vim commands such as :yank or :put normally operate with the unnamed register «» . If the +clipboard feature is available and its value includes unnamed , then Vim yank, delete, change and put operations which would normally go to the unnamed register will use the clipboard register «* instead, which is the PRIMARY buffer in X.
To change the default register, you can :set clipboard=unnamedplus to use the «+ register instead. The «+ clipboard register corresponds to the CLIPBOARD buffer in X. It should be noted that the clipboard option can be set to a comma-delimited value. If you :set clipboard=unnamedplus,unnamed , then yank operations will also copy the yanked text to the «* register in addition to the «+ register (however, delete, change and put operations will still only operate on the «+ register).
For more information, see :help ‘clipboard’ . There are other values which can be set for the clipboard feature. You can use :help clipboard-unnamed to take you to the help topic for the first valid value which can be set for this feature, followed by help for all other valid values.
- Custom shortcuts for copy and paste operations can be created. See e.g. [2] for binding Ctrl+c , Ctrl+v and Ctrl+x .
- The X clipboard gets flushed when vim exits. To make the vim selection persistent within X clipboard, you need a clipboard manager. Alternatively, you can add autocmd VimLeave * call system(«echo -n $'» . escape(getreg(), «‘») . «‘ | xsel —input —clipboard») to your .vimrc (requires the xsel package).
Syntax highlighting
To enable syntax highlighting for many programming languages:
Indentation
alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />This article or section needs expansion. alt=»Tango-view-fullscreen.png» width=»48″ height=»48″ />
The indent file for specific file types can be loaded with:
Visual wrapping
The wrap option is on by default, which instructs Vim to wrap lines longer than the width of the window, so that the rest of the line is displayed on the next line. The wrap option only affects how text is displayed, the text itself is not modified.
The wrapping normally occurs after the last character that fits the window, even when it is in the middle of a word. More intelligent wrapping can be controlled with the linebreak option. When it is enabled with set linebreak , the wrapping occurs after characters listed in the breakat string option, which by default contains a space and some punctuation marks (see :help breakat ).
Wrapped lines are normally displayed at the beginning of the next line, regardless of any indentation. The breakindent option instructs Vim to take indentation into account when wrapping long lines, so that the wrapped lines keep the same indentation of the previously displayed line. The behaviour of breakindent can be fine-tuned with the breakindentopt option, for example to shift the wrapped line another four spaces to the right for Python files (see :help breakindentopt for details):
Using the mouse
Vim has the ability to make use of the mouse, but it only works for certain terminals:
-
/urxvt-based terminal emulators
- Linux console with gpm (see Console mouse support for details)
To enable this feature, add this line into
The mouse=a option is set in defaults.vim .
Traverse line breaks with arrow keys
By default, pressing Left at the beginning of a line, or pressing Right at the end of a line, will not let the cursor traverse to the previous, or following, line.
The default behavior can be changed by adding set whichwrap=b,s,<,>,[,] to your
Merging files
Vim includes a diff editor (a program that shows differences between two or more files and aids to conveniently merge them). Use vimdiff to run the diff editor — just specify some couple of files to it: vimdiff file1 file2 . Here is the list of vimdiff-specific commands.
Action | Shortcut |
---|---|
next change | ]c |
previous change | [c |
diff obtain | do |
diff put | dp |
fold open | zo |
fold close | zc |
rescan files | :diffupdate |
Tips and tricks
Line numbers
To show the line number column, use :set number . By default absolute line numbers are shown, relative numbers can be enabled with :set relativenumber . Setting both enables hybrid line numbers—the current line is absolute, while the others are relative.
Jumping to a specific line is possible with :line number or line numbergg . Jumps are remembered in a jump list, see :h jump-motions for details.
Spell checking
Vim has the ability to do spell checking, enable by entering:
By default, only English language dictionaries are installed (in /usr/share/vim/vim82/spell/ ). More dictionaries can be found in the official repositories by searching for vim-spell . Additional dictionaries can be found in the Vim’s FTP archive. Additional dictionaries can be put in the folder
/.vim/spell/ and enabled with the command: :setlocal spell spelllang=en_us (replacing the en_us with the name of the needed dictionary).
Action | Shortcut |
---|---|
next spelling | ]s |
previous spelling | [s |
spelling suggestions | z= |
spelling good, add | zg |
spelling good, session | zG |
spelling wrong, add | zw |
spelling wrong, session | zW |
spelling repeat all in file | :spellr |
-
To enable spelling in two languages (for instance English and German), add set spelllang=en,de into your
/.vimrc or /etc/vimrc , and then restart Vim. Alternatively, one can simply insert the line autocmd BufRead,BufNewFile *.txt setlocal spell into their
Saving runtime state
Normally, exiting vim discards all unessential information such as opened files, command line history, yanked text etc. Preserving this information can be configured in the following ways.
viminfo files
The viminfo file may also be used to store command line history, search string history, input-line history, registers’ content, marks for files, location marks within files, last search/substitute pattern (to be used in search mode with n and & within the session), buffer list, and any global variables you may have defined. For the viminfo modality to be available, the version of vim you installed must have been compiled with the +viminfo feature.
Configure what is kept in your viminfo file, by adding (for example) the following to your
where each parameter is preceded by an identifier:
See the official viminfo documentation for particulars on how a pre-existing viminfo file is modified as it is updated with current session information, say from several buffers in the current session you are in the process of exiting.
Session files
Session files can be used to save the state of any number of particular sessions over time. One distinct session file may be used for each session or project of your interest. For that modality to be available, the version of vim you installed must have been compiled with the +mksession feature.
Within a session, :mksession[!] [my_session_name.vim] will write a vim-script to my_session_name.vim in the current directory, or Session.vim by default if you choose not to provide a file name. The optional ! will clobber a pre-existing session file with the same name and path.
A vim session can be resumed either when starting vim from terminal:
Or in an already opened session buffer by running the vim command:
Exactly what is saved and additional details on session files options are extensively covered in the vim documentation. Commented examples are found here.
Saving cursor position
Replace vi command with Vim
Create an alias for vi to vim .
Alternatively, if you want to be able to type sudo vi and get vim , install vi-vim-symlink AUR which will remove vi and replace it with a symlink to vim . You could also create this symlink yourself and place it somewhere higher in your path than /usr/bin to have it take precedence.
DOS/Windows carriage returns
If there is a ^M at the end of each line then this means you are editing a text file which was created in MS-DOS or Windows. This is because in Linux only a single line feed character (LF) used for line break, but in Windows/MS DOS systems they are using a sequence of a carriage return (CR) and a line feed (LF) for the same. And this carriage returns are displayed as ^M .
To remove all carriage returns from a file do:
Note that there ^ is a control letter. To enter the control sequence ^M press Ctrl+v,Ctrl+m .
Alternatively install the package dos2unix and run dos2unix file to fix the file.
Empty space at the bottom of gVim windows
When using a window manager configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color.
The solution is to adjust how much space gVim reserves at the bottom of the window. Put the following line in
Vim as a pager
Using scripts Vim can be used as a terminal pager, so that you get various vim features such as color schemes.
Vim comes with the /usr/share/vim/vim90/macros/less.sh script, for which you can create an alias. Note that this script does not support any command-line flags mentioned in less(1) § OPTIONS .
Alternatively there is also the vimpager Vim script. To change the default pager, export the PAGER environment variable. Note that not all command-line flags are supported; the list of supported flags is available on GitHub.
Highlighting search results
In order to highlight the first string that will be matched in a search while typing the search, add the following line to your
In order to highlight all strings that will be matched in a search while typing the search, and after the search has been executed, add the following line to your
- Setting hlsearch will keep all matches highlighted until a further search is made. This behaviour may be undesired, so to temporarily disable the highlighting until the next search, run :nohlsearch . If you find yourself running this command often, consider binding it to a key.
- This behaviour will also be observed when matching regex during other commands that involve them like s or g .
Plugins
Adding plugins to Vim can increase your productivity by extending Vim’s features. Plugins can alter Vim’s UI, add new commands, enable code completion support, integrate other programs and utilities with Vim, add support for additional languages and more.
Installation
Using the built-in package manager
Vim 8 added the possibility to load third-party plugins natively. This functionality can be used by storing third-party packages in the
/.vim/pack folder. The structure of this folder differs slightly from that of typical plugin managers which will usually have a single directory per plugin. What follows is a typical installation procedure and directory structure (using Tim Pope’s vim-surround plugin as an example):
It is important to note that
/.vim/pack/tpope is a package directory which is loosely defined as directory containing one or more plugins in the Vim documentation. Plugin repositories should not be downloaded to this directory though. The name of the package directory is also arbitrary. You can choose to keep all your plugins in a single package directory or, as in our example, use the author’s GitHub name, tpope .
The package directory can contain the following subfolders:
- start — plugins from this subfolder will be loaded automatically when Vim starts. This is the most frequently used location.
- opt — plugins from this subfolder can be loaded on-demand by issuing :packadd command inside Vim.
Now change into the start folder and checkout the plugin repository:
This creates an additional subfolder,
/.vim/pack/tpope/start/surround , where the plugin files are placed.
Next, update the help index if the plugin contains help files:
The plugin will now be loaded automatically when starting Vim. No changes to
/.vimrc are required, barring plugin-specific options.
Using a plugin manager
A plugin manager is a plugin that installs, manages and updates Vim plugins. This can be useful if you are also using Vim on platforms other than Arch Linux and want a consistent method of updating plugins.
-
is a minimalist Vim plugin manager with many features like on-demand plugin loading and parallel updating, available as vim-plugAUR or vim-plug-gitAUR . is available as vundleAUR or vundle-gitAUR . is a simple plugin for managing Vim’s runtimepath, available as vim-pathogenAUR or vim-pathogen-gitAUR . is a plugin manager replacing NeoBundle, available as vim-deinAUR or vim-dein-gitAUR .
From Arch repositories
The vim-plugins group provides various plugins. Use pacman -Sg vim-plugins command to list available packages which you can then install with pacman.
Notable plugins
cscope
Cscope is a tool for browsing a project. By navigating to a word/symbol/function and calling cscope (usually with shortcut keys) it can find: functions calling the function, the function definition, and more.
Copy the cscope default file where it will be automatically read by Vim:
/.vim/plugin/cscope_maps.vim in order to enable cscope shortcuts in Vim 7.x:
Create a file which contains the list of files you wish cscope to index (cscope can handle many languages but this example finds .c, .cpp and .h files, specific for C/C++ project):
Create database files that cscope will read:
Default keyboard shortcuts:
Feel free to change the shortcuts.
Taglist
Taglist provides an overview of the structure of source code files and allows you to efficiently browse through source code files in different programming languages.
Useful options to be put in
Troubleshooting
gVim is slow
Vim’s GTK 3 GUI may be slower than the GTK 2 version (see FS#51366). gvim-gtk2 AUR can be installed as a workaround.
Introduction
Back in 2007, I had a rough beginning as a design engineer at a semiconductor company in terms of software tools. Linux command line, Vim and Perl were all new to me. I distinctly remember progressing from dd (delete current line) to d↓ (delete current line as well as the line below) and feeling happy that it reduced time spent on editing. Since I was learning on the job, I didn’t know about count prefix or the various ways I could’ve deleted all the lines from the beginning of the file to the line containing a specific phrase. Or even better, I could’ve automated editing multiple files if I had been familiar with sed or progressed that far with Perl.
I also remember that we got a two-sided printed cheatsheet that we kept pinned to our cabins. That was one of the ways I kept adding commands to my repertoire. But, I didn’t have a good insight to Vim’s philosophy and I didn’t know how to apply many of the cheatsheet commands. At some point, I decided to read the Vim book by Steve Oualline and that helped a lot, but it was also too long and comprehensive for me to read it all. My memory is hazy after that, and I don’t recall what other resources I used. However, I’m sure I didn’t effectively utilize built-in help. Nor did I know about stackoverflow or /r/vim until after I left my job in 2014.
Still, I knew enough to conduct a few Vim learning sessions for my colleagues. That came in handy when I got chances to teach Vim as part of scripting course for college students. From 2016 to 2018, I started maintaining my tutorials on Linux command line, Vim and scripting languages as GitHub repos. As you might guess, I then started polishing these materials and published them as ebooks. This is an ongoing process, with Vim Reference Guide being the twelfth ebook.
Why Vim?
You’ve probably already heard that Vim is a text editor, powerful one at that. Vim’s editing features feel like a programming language and you can customize the editor using scripting languages. Apart from plethora of editing commands and support for regular expressions, you can also incorporate external commands. To sum it up, most editing tasks can be managed from within Vim itself instead of having to write a script.
Now, you might wonder, what is all this need for complicated editing features? Why does a text editor require programming capabilities? Why is there even a requirement to learn how to use a text editor? Isn’t it enough to have the ability to enter text, use Backspace/Delete/Home/End/Arrow/etc, menu and toolbar, some shortcuts, a search and replace feature and so on? A simple and short answer — to reduce repetitive manual task.
- Lightweight and fast
- Modal editing helps me to think logically based on the type of editing task
- Composing commands and the ability to record them for future use
- Settings customization and creating new commands
- Integration with shell commands
There’s a huge ecosystem of plugins, packages and colorschemes as well, but I haven’t used them much. I’ve used Vim for a long time, but not really a power user. I prefer using GVim, tab pages, mouse, arrow keys, etc. So, if you come across tutorials and books suggesting you should avoid using them, remember that they are subjective preferences.
Here are some more opinions by those who enjoy using Vim:
Should everybody use Vim? Is it suitable for all kinds of editing tasks? I’d say no. There are plenty of other well established text editors and new ones are coming up all the time. The learning curve isn’t worth it for everybody. If Vim wasn’t being used at job, I probably wouldn’t have bothered with it. Don’t use Vim for the wrong reasons article discusses this topic in more detail.
Installation
-
— user manual for installation on different platforms, common issues, upgrading, uninstallation, etc — building from source, using distribution packages, etc
Ice Breaker
- gvim ip.txt opens a file named ip.txt for editing
- You can also use vim if you prefer terminal instead of GUI, or if gvim is not available
- Vim is a modal editor. You have to be aware which mode you are in and use commands or type text accordingly
- When you first launch Vim, it starts in Normal mode (primarily used for editing and moving around)
- Pressing i key is one of the ways to enter Insert mode (where you type the text you want to save in a file)
- After you’ve entered the text, you need to save the file. To do so, you have to go back to Normal mode first by pressing the Esc key
- Then, you have to go to yet another mode! Pressing : key brings up the Command-line mode and awaits further instruction
- wq is a combination of write and quit commands
- use wq ip.txt if you forgot to specify the filename while launching Vim, or perhaps if you opened Vim from Start menu instead of a terminal
If you launched GVim, you’ll likely have Menu and Tool bars, which would’ve helped with operations like saving, quitting, etc. Nothing wrong with using them, but this book will not discuss those operations. In fact, you’ll learn how to configure Vim to hide them in the Customizing Vim chapter.
Don’t proceed any further if you aren’t comfortable with the above steps. Take help of youtube videos if you must. Master this basic procedure and you will be ready for Vim awesomeness that’ll be discussed in the coming sections and chapters.
Material presented here is based on GVim (GUI), which has a few subtle differences compared to Vim (TUI). See this stackoverflow thread for more details.
Options and details related to opening Vim from the command line will be discussed in the CLI options chapter.
Built-in tutor
- gvimtutor command that opens a tutorial session with lessons to get started with Vim
- don’t worry if something goes wrong as you’ll be working with a temporary file
- use vimtutor if gvim is not available
- pro-tip: go through this short tutorial multiple times, spread over multiple days
Next step is :h usr_02.txt, which provides enough information about editing files with Vim.
Built-in help
- You can access built-in help in several ways:
- type :help from Normal mode (or just the :h short form)
- GVim has a Help menu
- press F1 key from Normal mode
- Task oriented explanations, from simple to complex. Reads from start to end like a book
- Precise description of how everything in Vim works
- See also vi.stackexchange: guideline to use help
Here’s a neat table from :h help-context:
You can go through a copy of the documentation online at https://vimhelp.org/. As shown above, all the :h hints in this book will also be linked to the appropriate online help section.
Vim learning resources
As mentioned in the Preface chapter, this Vim Reference Guide is more like a cheatsheet instead of a typical book for learning Vim. In addition to built-in features already mentioned in the previous sections, here are some resources you can use:
-
— learn Vim in a way that will stay with you for life — everything you need to know about Vim — short introduction that covers a lot — article series for beginners to expert users
Books
-
— interactive tutorial — learn Vim by playing a game — master Vim from the comfort of your web browser — interactive lessons designed to help you get better at Vim faster
See my Vim curated list for a more complete list of learning resources, cheatsheets, tips, tricks, forums, etc.
Modes of Operation
- Insert mode
- Normal mode
- Visual mode
- Command-line mode
This section provides a brief description for these modes. Separate chapters will discuss their features in more detail.
Insert mode
This is the mode where the required text is typed. There are also commands available for moving around, deleting, autocompletion, etc.
Pressing the Esc key takes you back to Normal mode.
Normal mode
This is the default mode when Vim is opened. This mode is used to run commands for operations like cut, copy, paste, recording, moving around, etc. This is also known as the Command mode.
Visual mode
Visual mode is used to edit text by selecting them first. Selection can either be done using mouse or using visual commands.
Pressing the Esc key takes you back to the Normal mode.
Command-line mode
This mode is used to perform file operations like save, quit, search, replace, execute shell commands, etc. Any operation is completed by pressing the Enter key after which the mode changes back to the Normal mode. The Esc key can be used to ignore whatever is typed and return to the Normal mode.
The space at the end of the file used for this mode is referred to as Command-line area. It is usually a single line, but can expand for cases like auto completion, shell commands, etc.
Identifying current mode
- In Insert mode, you get a blinking | cursor
- also, — INSERT — can be seen on the left hand side of the Command-line area
Vim philosophy and features
-
(this stackoverflow thread also has numerous Vim tips and tricks)
- dG delete from the current line to the end of the file
- where d is the delete command awaiting further instruction
- and G is a motion command to move to the last line of the file
- where y is the yank (copy) command awaiting further instruction
- 3p paste the copied content three times
- 5x delete the character under the cursor and 4 characters to its right (total 5 characters)
- 3 followed by Ctrl + a add 3 to the number under the cursor
- diw delete a word regardless of where the cursor is on that word
- ya> copy all characters within <> including the <> characters
- /searchpattern search the given pattern in the forward direction
- :g/call/d delete all lines containing call
- :g/cat/ s/animal/mammal/g replace animal with mammal only for the lines containing cat
- :3,8! sort sort only lines 3 to 8 (uses external command sort )
- :set incsearch highlights current match as you type the search pattern
- colorscheme murphy use a dark theme
- set tabstop=4 width for the tab character (default is 8 )
- nnoremap <F5> :%y+<CR> map F5 key to copy everything to system clipboard in Normal mode
- inoreabbrev teh the automatically correct teh to the in Insert mode
There are many more Vim features that’d help you with text processing and customizing the editor to your needs, some of which you’ll get to know in the coming chapters.
-
command supports vim-like navigation, qutebrowser (keyboard-driven browser with vim-like navigation), etc, VSCodeVim, etc
Vim’s history
See Where Vim Came From if you are interested in knowing Vim’s history that traces back to the 1960s with qed , ed , etc.
Как освоить 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<char> — (Delete To <character>) удалить текст от позиции курсора до следующего вхождения указанного символа.
Если вас интересуют другие команды Vim — посмотрите это замечательное и довольно длительное видео, демонстрирующее прохождение уроков vimtutor , которое записал Вим Дизель (шучу — это всё тот же Люк). Тут собрано множество полезнейших советов по Vim.
Итоги
Вероятно, сейчас вы уже достаточно хорошо освоили Vim и значительно повысили свою скорость работы с кодом. И вы наконец сможете похвастаться перед пользователями Reddit или перед коллегами своими отточенными навыками редактирования текстов, когда в ходе работы вам не приходится убирать руки с основной части клавиатуры. Когда вы достигнете подобного уровня, вы можете развиваться в сфере Vim и дальше. Например — в следующих направлениях:
How to use vim for Beginners
In this tutorial, we are going to take a look at look at how we can use the vim and why it is better than the other text editors. Also, we will learn how to use it on Android Devices.
Let’s get started!
What is vim? and why it is a better text editor?
Vim is an acronym for Vi IMproved. It is a free and open-source text editor written by Bram Moolenaar. It was first released in 1991 for UNIX variants and its main goal was to provide enhancement to the Vi editor, which was released way back in 1976.
Vim is highly customizable and extensible, making it an attractive tool for users that demand a large amount of control and flexibility over their text editing environment. There are many plugins available that will extend or add new functionality to Vim, such as linters, integration of git, showing colors in CSS.
What we are going to learn
- How to start vim
- Vim Modes
- Creating new file
- View file in read-only mode
- Edit existing file
- Vim help manual
- How to installed and run Vim on Android
How to Start and Close vim
Using Vim from terminal will be identical on Windows as well as Linux platform. Perform the following steps to start and quit Vim from terminal
It will open Vim in the terminal as follows
to close this, press Esc key followed by colon : and q . In Vim q command stands for quit. This command will be shown in the bottom left corner of the editor itself
Vim Modes
Vim supports multiple modes. This section discusses some of the important modes which will be used on a day-to-day basis.
Command Mode
This is the default mode in which Vim starts. We can enter editor commands in this mode. We can use a variety of commands in this mode like copy, paste, delete, replace and many more. We’ll discuss these commands in later sections.
NOTE − Here onwards, any Vim command without colon indicates that we are executing that command in command mode.
Insert Mode
You can use this mode to enter/edit text. To switch from default command to insert mode press i key. It will show the current mode in the bottom left corner of the editor.
We can enter any text once we are in insert mode. Below image shows this
Use the Escape Esc key to switch back to command mode from this mode.
Command Line Mode
This mode is also used to enter commands. Commands in this mode starts with colon : . For instance, in the previous section quit command was entered in this mode. We can go to this mode either from command or insert mode.
- To switch from command mode to this mode just type colon :
- To switch from insert mode to this mode press Esc and type colon :
In below image colon at bottom left indicates line mode.
NOTE − Here onwards, any Vim command starting with colon indicates that we are executing that command in command line mode.
Visual Mode
In this mode, we can visually select text and run commands on selected sections.
- To switch from command mode to visual mode type v
- To switch from any other mode to visual mode first switch back to command mode by pressing Esc , then type v to switch to visual mode
In below image bottom left corner shows visual mode.
Create new file
Perform the below steps to create and save new file
Execute the following command to open Vim
Type following command in Vim
Enter some text and Switch back to command mode
Now message.txt file will be created. To quit Vim
Open file in read-only mode
Use –R option to open file in read-only mode
In below image bottom left corner shows read-only mode
Alternatively, you can use view command to achieve the same result.
Edit existing file
Perform below steps to edit existing file
Switch to insert mode and enter some text there.
Quit editor without saving changes
Save changes and quit editor using following command
Vim is a feature-rich editor hence remembering everything about it will be difficult. But there is no need to worry, we can always ask for help. Fortunately, this help is provided by Vim itself.
Access help manual
The help manual is shipped with the Vim editor itself and it is really comprehensive. To access help execute below command
Help on specific topic
Help manual will show entire help about Vim. But what if, we are only interested in certain topics. Vim provides command for that as well with following syntax
In the above command replace <topic-name> with the topic in which you are interested. For instance to access help about vim mode, execute following command
Access online help
Vim also provides online help. To access online help
- Visit vim-help URL
- Additionally, you can also refer vim-docs documentation
How to install and run Vim on Android
- Install termux app from google play store
- After installation open the app and type $ pkg update && pkg upgrade
- After that has been done type $ pkg install vim
That it now you have vim installed in your Android Device enjoy!
Conclusion
In this tutorial, we learned how we can use the vim text editor to edit text files and we also learned how to use vim’s built-in help manual.
I hope you like this article. If you did, please share it with your friends!