Introduction
I love the Vim editor, I have been using it in my work (for writing code) for more than four years and I want to share my experience of using it.
This article is not a set of “magic commands” and recipes (cookbook, as such sets are called in English), although they are also present here, but rather an attempt to describe how the general principles of ergonomic interfaces can be applied in the practice of using Vim to make it a convenient and efficient working environment with texts.
This article is also not a tutorial for novice Vim users, although they (and also Emacs users) may be interested, because some of the principles mentioned are quite general and apply not only to text editing systems, but in general wherever we are talking about using a computer to edit anything. Nevertheless, I assume that the reader is familiar with the basic concepts used in Vim (modes, registers, buffers, commands) and I do not dwell on their detailed description.
')
By default, Vim is very old-fashioned, and this setting implies that the user will think in metaphors of fifty years ago when working with text, as if it were the dawn of the UNIX era. However, the Vim design allows you to make several settings, after which the system will look quite decent and will work very efficiently, combining the useful features of the ancient Unix text tools, and modern WYSIWIG processors, while bypassing as much as possible limitations. That's about these settings and techniques for their use and will be discussed.
Working with content on the model “noun - verb”
Jeff Raskin, a renowned authority in the field of interface ergonomics, in his classic work “Interface: New Directions in Computer Systems Design” mentions two models of working with content - “verb - noun”, when an action is first given, and then the content is chosen. you need to apply, and “noun - verb”, when the contents are first allocated, and then some operation is applied to it. In most cases, it is the “noun-verb” model that is preferred. In this case, it is definitely the case. I will add that some of the techniques that will be discussed were invented by me independently of Ruskin at the time when I did not know about the existence of his book, through trial and error - I tried different ways of performing actions, and after a while I was forming idea of ​​what is convenient and what is not.
In this case, the content on which operations are performed is editable text. Selected content, respectively, is usually the selected text.
In Vim, however, the notion of selected content is split. As it can be:
- A block of text selected in visual selection mode (usually gray)
- Text that matches the regular expression in the / (register of current search). In other words, this is text that is highlighted in yellow when the hlsearch option is on.
The first case is widely known, and I will not dwell on it in detail. In the visual mode, a block of text is highlighted in gray, then the command is applied to it (say, “Translate to upper case”). Everything, as in other editors.
Highlighted - looked - fulfilled
The second case is more interesting. In the “noun - verb” model, it allows you to make a noun text that matches the regular expression in the register /. At the same time, when the option: hlsearch is on, this text is highlighted in yellow. This allows you to develop a style of working with text that can be described as “highlighted - looked - (replaced IT | deleted IT | copied containing IT lines | executed what command you need)”, where IT is the text corresponding to the regular expression in the register /. This style gives a completely new level of convenience when performing operations like “replace all occurrences of one word with another” due to the fact that all occurrences of the replaced word are immediately visible in the text. After switching to this style, it is almost impossible to return to the old style of mass replacement (by “old style” I understand, for example, the implementation of the command “Replace all” in the text editor Far manager, which actually replaces everything with the risk of replacing where It is not necessary, or requests confirmation of each replacement, creating unnecessary annoying hesitations at work). When using a preliminary visual backlight, the risk of making an error when making mass replacements and similar operations is minimized.
Then I will describe several settings that, when using the “highlight - looked - performed” style, turned out to be very convenient for me.
Lines from my _vimrc configuration file:
" ,
nnoremap * *N
" : Ctrl-F8
nnoremap <C-F8> :nohlsearch<CR>
I will explain what they do. Vim has a built-in * (asterisk, invoked by simply pressing Shift + 8 in normal mode), which places the current word (the cursor is on) in the search register /, searches for the next occurrence of this word in the text and moves the cursor to this next occurrence. In addition, the occurrences of this word are highlighted (in fact, again, the text corresponding to the regular expression in the search register, but in practice in this case it means just the occurrence of the current word). In my opinion, this command is not implemented correctly. I consider it a mistake to jump to the next occurrence of the word, because this jump knocks out the context, leading to a change of text on the screen (the next entry may be anywhere, and the text may change to a completely unfamiliar). Therefore, I use the first mapping, which changes the semantics of the command * to “highlight the current word, but do not change the position of the cursor”. The second mapping is used to assign a hot key that resets the backlight (for ergonomic reasons, it should be close to key 8, where the * command is located, because the “highlight” - “reset the backlight” commands are often used in pairs, for example, how to “highlight all occurrences of the variable on which I am now standing with the cursor.” After the local task, for which the variables are highlighted, is solved, it is better to reset the highlighting so that it does not distract attention from further work. Rich in the actual operation time interval between "highlight" and "reset illumination" can be reduced to one second). After the word is highlighted, you can use the n and N commands to jump forward / backward through its occurrences, if necessary.
" *
vnoremap * y :execute ":let @/=@\""<CR> :execute "set hlsearch"<CR>
This is the same as the * command for words, but applied to a fragment selected in visual mode. It is used when it is necessary to highlight not a word (framed by spaces), but an arbitrary fragment, which, say, may contain a space in the middle.
Using the “highlight - looked - executed” style together with the visual mode turned out to be a very convenient practice. Such a combination of selection styles is used when solving problems of the type “in this function, rename the variable foo to bar” and the like. Such (and similar) tasks are solved by a sequence of actions:
- Highlight foo with *
- Switch to the visual selection mode and select the current function.
- Give the replacement command: '<,'> s // bar / g
The characters '<,'>, meaning the beginning and end of the current selected block, and defining the range of use of the command: s, Vim substitutes automatically when returning any command from the visual selection mode. The first command argument is also omitted: s, since there is no need to type it - when it is omitted, Vim uses the contents of the current search register as this argument. That is exactly what is highlighted in yellow.
Thus, visibility is achieved. The contents of the register / highlighted in yellow, so we see that we will replace. The block selected in the mode of visual selection is highlighted in gray, so we see WHERE we will replace it. It remains to issue the command: s, in which to indicate WHAT to replace.
A separate emphasis deserves the already mentioned feature of Vim (unfortunately, it is not immediately clear that it is available, and you can learn about its existence either by stumbling upon its description in the documentation either on the Internet or using the “spear” method), which is that commands used for bulk text operations, such as: s (substitute, replacing one pattern with another),: d (delete, deleting lines containing a pattern),: g (global, performing an arbitrary operation on strings containing a pattern ) use the contents of the register / as their rgumenta, when he dropped by their call. It is very convenient, and you get used to this behavior instantly. Actually, it is this “feature” that makes it possible to edit the text in the “highlight - looked - executed” mode, which is so well compatible with the peculiarities of human perception that it is used everywhere in computer interfaces - we select files in the file manager (they are highlighted) We look at the sample, perform with them any operation. The same thing happens in graphic and other editors. Actually, after a short period of getting used to editing in this style, it becomes unclear how it can be done differently.
Some recipes from my “Vim cookbook”
Then I will give a few commands and techniques for using Vim, which I consider useful for myself, but, in principle, using them or not using them is a matter of taste and personal preferences, as well as gained experience using Vim. It is possible that for some of the tasks described below, there are more effective ways to solve it.
: g // t $ - copy lines containing the highlighted value to the end of the file. If, for example, you need to quickly understand how a global variable (sic! - and what to do, they are found in legacy code) is used in the module.
: g // d - delete lines containing the highlighted value
: g! // d - delete lines that do NOT contain the highlighted value
A list of useful, but rarely used commands with a nontrivial syntax, which themselves will not be remembered from frequent use, it is better to write in the cheat sheet. For example, you can record such and similar things:
Replace each entry of several empty lines with one empty line (so that there is an equal gap in one line between paragraphs):
: v /./,/./- j
Remove blank lines (in visual mode)
: '<,'> g / ^ $ / d
Spread consecutive lines (the opposite of the previous action, each line will be a paragraph)
It is necessary when formatting text under 76 characters, from the format as it is saved by Word, when each paragraph becomes a line in a text file.
: '<,'> s / $ / \ r / g
The following chords have shown their usefulness (fragment from _vimrc)
"Alt-1 edit current word
nnoremap <M-1> ciw
"Alt-5 change the tail of the current word
nnoremap <M-5> cw
Using Vim to work with code and programming
I will give a few tricks that are useful when working with code. Actually, it was created for working with the Vim code (unlike Emacs, which is considered to be a more versatile editor suitable for working with any text, and not just with the code. However, this is a famous theme for holy wars).
It is convenient to use the label] to insert a block of code inside the operator brackets and its subsequent alignment (indenting). Here it is meant that after inserting a block inside operator brackets, using the p command, it is necessary to select the inserted block again to align its position inside the brackets in accordance with the accepted formatting rules. To do this, select the inserted block. This can be easily done if you get up on the first line of the inserted block, switch to the visual selection of lines (command V), and give the command to go to a special label indicating the last line of the block you just inserted: '] (apostrophe, then close bracket) .
Matchit plugin to navigate through statement brackets. No comments must have. At the command%, the cursor jumps between {and} in languages ​​with a C-like syntax, between begin and end in Pascal, etc. The plugin is included in the standard Vim distribution.
Auto-completion by Ctrl-N. Of course, as good as in IDE-environments that support parsing and precompilation will not work, but if there is no such IDE, or reluctance to install, then it will be fine.
The ctags tag generator and the commands for moving the Ctrl-] tags (go to the function under the cursor) and Ctrl-T (go back). Again, in comparison with IDE, it turns out to be simple and sometimes oak, but working code navigation (and the code can be quite a lot, half a million lines are quite pulling, and they are said to pull much more).
You can use: r! Grep <arguments for grep> and then Ctrl-W gf to search and / or replace by an array of code (for refactoring). The command: r! Grep inserts grep in the current location (where the cursor is). The gf (go [to] file) command opens the file on the name of which the cursor is in a new window (or tab). If the file name is tricky (say, the file path contains spaces), then you can select the full path to the file in the visual selection mode, and after that give the gf command (or Ctrl-W gf).
Using Vim in the Windows operating system
Since my main OS is Windows, I perform some additional Vim settings so that the hot keys behave consistently. The standard distribution includes the settings file mswin.vim, which is included at the beginning of the _vimrc initialization file:
set nocompatible
source $VIMRUNTIME/mswin.vim
behave mswin
The inclusion of this file leads to the fact that copying and pasting into the buffer (Ctrl-C and Ctrl-V) commands begin to work in the standard way for Windows, which is fully justified.
I use tabs to edit multiple files. To open a file in Vim (add a tab with a file / files if Vim is already open), I use the command for the Far menu:
"C:\Program Files\Vim\vim73\gvim.exe" --remote-tab-silent !&
(! & Is a special macro of Far'a, meaning “current or selected files”). Actually, the command line interface here is:
"C:\Program Files\Vim\vim73\gvim.exe" --remote-tab-silent file1 [file2] ...
To switch between tabs, I use the standard Windows-based Ctrl-Tab (Shift-Ctrl-Tab) combination. Also, practice has shown that you need the ability to move tabs left and right so that several files that are edited at the same time can be shifted so that they are in adjacent tabs. For this, I use the following settings:
" CTRL-Tab is Next tab
nnoremap <C-Tab> :tabnext<CR>
" CTRL-Shift-Tab is Previous tab
nnoremap <CS-Tab> :tabprevious<CR>
" use Alt-Left and Alt-Right to move current tab to left or right
nnoremap <silent> <A-Left> :execute 'silent! tabmove ' . (tabpagenr()-2)<CR>
nnoremap <silent> <A-Right> :execute 'silent! tabmove ' . tabpagenr()<CR>
" CTRL-F4 is :tabclose
nnoremap <C-F4> :tabclose<CR>
When working in insert mode, it is more convenient for me to use standard system layout switching (which is usually Alt-Shift, and I have Caps), rather than Vim built in, which is Ctrl- ^. Although, perhaps, this is a purely personal preference.
The cursor between the windows (in terms of Vim, that is, the text areas created by the commands: split or: vsplit) I move the Tab key, which, again, is standard for Windows:
" Tab is Next window
nnoremap <Tab> <CW>w
" Shift-Tab is Previous window
nnoremap <S-Tab> <CW>W
Hint, unobvious for new users of Vim: in order to insert a useful command from the cheat sheet into the Vim command line from the Windows clipboard, you must, while in command return mode (which we switch to after pressing the colon), press Ctrl-R (the cursor changes shape to a quotation mark), then press Shift-8 (in this context it means “insert the contents of the register in which the Windows clipboard is located”).
It is convenient to split windows (windows in Vim terminology) by using the shortcut Ctrl-W s and Ctrl-W v, close by Ctrl-W c (this is faster than typing the commands: split and: vsplit)
Conclusion
We have reviewed some of the principles and techniques, the use of which in the editor Vim allows you to improve the efficiency of text editing. Perhaps this article interested someone who did not work with Vim, but wanted (or wanted) to try, or those who may have already seen Vim, but did not start using it because of the unusual and unusual nature of its interface. Indeed, Vim is not the easiest to use tool and its learning curve is not the most gentle. However, time-tested design and immense flexibility make it one of the most effective text editing tools that has not lost its relevance today. Moreover, it develops and new versions are released. The most effective use of Vim is achieved by using the right approaches, some of which (as I see it) I tried to highlight in this article.
I would advise novice users who want to learn how to use Vim to go the way I walked myself - complete the included tutorial, and then gradually read the chapters of the User Manual from the help system (it’s very good there, available at the command: help) in order, try to use the commands described there and, of course, use Vim in daily activities.
Thanks for attention.