Vim practical technology, Part 1: Practical Skills

Source: Internet
Author: User
Tags windows support
Vim: vim. wikis. comwikiVim_Tips_Wikiblog.jobbole.com206040.Vim is one of the most important open-source editors (Emacs). Vim is favored by many developers with its powerful functions and customization capabilities. However, it may be because Vim is too powerful.

A vim Daquan: http://vim.wikia.com/wiki/Vim_Tips_Wiki http://blog.jobbole.com/20604/ 0. Vim introduction as one of the most important open-source editor of the world (another is Emacs), Vim with its powerful functions and customizable ability is favored by many developers. However, it may be because Vim is too powerful.

A vim book: http://vim.wikia.com/wiki/Vim_Tips_Wiki

Http://blog.jobbole.com/20604/

0. Vim Introduction

As one of the most important editors in the open-source world (Emacs), Vim is favored by many developers with its powerful functions and customization capabilities. However, it may be because Vim is so powerful that it is not easy to make good use of Vim. The author has gradually mastered some practical technologies in years of practical use and will introduce them to you here. -- This article does not attempt to give a comprehensive and systematic introduction to Vim, but it is not just a few moments away. Instead, it hopes to attract everyone's interest by introducing some important features and providing relevant reference information, in-depth exploration of its capabilities, and truly make good use of this powerful work.

Next we will give a basic introduction to Vim and some reference information to help readers who are not familiar with Vim understand and view further information.

Unlike most other editors, after entering Vim, the characters entered by default are not inserted into the edited file. The Vim mode is very important. You need to know that Vim has the following modes:

● Normal Mode: the default editing mode. Unless otherwise specified, all the commands mentioned are directly entered in normal mode; you can use the Esc key on the keyboard to return to normal mode in any other mode.

● Command mode: used to execute long and complex commands. In normal mode, enter ":" (General command), "/" (Forward search), or "?" (Reverse search) to Enter this mode. In command mode, Enter the Enter key.

● Insert mode: used for text input. In normal mode, type "I" (insert) or "a" (append) you can enter the insert mode (there are also some commands, such as "c", you can also enter the insert mode, but these commands have other functions ).

● Visual mode: used to select text blocks. You can enter "v" (lower case) in normal mode to select text blocks by character, and enter "V" (upper case) or press Ctrl-V to select by Square.

● Select mode: similar to the normal Windows Editor, select text blocks. After you select a text block in either visual or selection mode, you can use Ctrl-G to switch to another mode. This mode is rarely used in Linux and will not be described in this article.

Vim has a complete help document. In the standard release of Vim 6.4, there are more than one hundred chapter help files containing nearly 0.6 million English words. Enter Vim and enter ": help (the command entered in command mode ends with the Enter key, which is not described below) to access. When introducing the features in this article, the detailed content described in this document will only be briefly described and the application examples will be provided, and commands for accessing the corresponding Vim document will be provided.

The general release version usually carries a simple 30-minute Vim tutorial. A newbie can start learning by entering the "vimtutor" command on the command line of the operating system. In addition to the simple description above, this article does not introduce the most basic Vim commands. A newbie of Vim should familiarize himself with Vim through the tutorial before continuing to read it.

We recommend that all Vim users frequently access the main Vim site [1]. In addition to the basic release, installation, and download information, the most useful content is that users can upload their own Vim scripts and write tips that they think are useful ), for use by other Vim users. At the time of writing this section, there were more than one thousand three hundred scripts on the Vim site, and the number of prompts just exceeded one thousand. For scripts with serial numbers nn, is the URL directly accessed a http://www.vim.org/scripts/script.php? Script_id = nn; for the prompt that the serial number is nn, the URL directly accessed is http://www.vim.org/tips/tip.php? Tip_id = nn.

Unless otherwise stated, the content discussed in this article applies to Vim version 6 (from 6.0 to 6.4 ). We recommend that you carefully upgrade Vim users to Vim 6.4, preferably compile and upgrade all the patch packages by yourself. Related information is available on the website. We will not repeat it here.

1. Practical Skills

1.1 installation

If you install Vim directly from the Linux release, note that by default, the system does not necessarily install a complete Vim for you. For example, in Red Hat (and later Fedora Core) releases, Vim is split into four packages: vim-common (public part), vim-minimal (minimum installation ), vim-enhanced (complete installation except X Window support), and vim-X11 (X Window graphical interface support ). The minimal installation cannot fully demonstrate the advantages of Vim. It is usually used as a substitute for vi and lacks many important features such as multi-byte language support, mouse support, and script support. If X Window is installed, gvim in the graphic interface has more features than vim in the text mode. We recommend that you install Vim as much as possible.

If you are willing to make a little effort to compile Vim yourself, you can better customize Vim. -- If you find any error, you can fix it by yourself, or at least locate the error to Bram (author of Vim) it can solve problems faster. Figure 1 shows part of the result of executing ": version" in Vim. We can see that Vim has many different features that can be turned on or off during compilation. If you compile it yourself, you can choose to enable the required features and disable unnecessary features to get a powerful and quick Vim custom version.

Figure 1

1.2 Chinese support

Vim supports the world's major languages, including Chinese. If you use Vim to edit Chinese characters, but Chinese characters cannot be correctly displayed, there are two possibilities: the use of Vim is incomplete and does not support multi-byte languages (multi_byte features ); second, a configuration error occurs.

Speaking of multi-language support, there are two basic concepts: one is the language encoding of files, but the internal encoding of the environment. In older operating systems, regardless of Linux or Windows, these two encodings are the same, meaning that only one type of encoded file can be processed at a time: either only Western-style encoding (Latin1, that is, ISO-8859-1 [5]), or can only process Chinese encoding (GB2312 [2]). In the new operating system, the two can be different. In Linux, it is common that the internal encoding of the Environment uses UTF-8 [6], while the UTF-8 can be encoded in the same language for Lossless conversion, this ensures the multi-language processing capability of the system. Vim follows the Unix/Linux tradition in this regard, while the internal encoding makes the UTF-8, can simultaneously process do not agree with the language encoding files.

The settings related to language encoding are listed below:

● Environment variable LANG (language used );

● Environment variable LC_CTYPE (internal encoding used );

● Vim option encoding (Vim internal encoding );

● Vim option termencoding (the encoding used by Vim to interact with the screen/keyboard );

● Vim option fileencoding (the encoding of the file currently edited by Vim during storage );

● Vim option fileencodings (the encoding used by Vim when opening the file );

● Vim option ambiwidth (Processing Method for "unspecified width" characters; introduced after Vim 6.1.455 ).

If your environment only needs to process simplified Chinese, the simplest way is to use simplified Chinese for all settings. You only need to: Set LANG = zh_CN.GB2312, do not set LC_CTYPE (same as LANG by default), do not set Vim options related to encoding (the default is determined by LANG and LC_CTYPE ), you do not need to set the Vim option ambiwidth. That is to say, we set the language to the Chinese (zh) used by China (CN) and the encoding to GB2312 (Note: Vim does not recognize the national standard GB18030 [3] internally, so only GB2312 can be set here; see the discussion on UTF-8 below ).

However, if we use UTF-8 for all internal encoding in Linux, there will be some additional benefits, one of which is that Vim supports editing a variety of different encoding files at the same time in this case, for example, simplified Chinese and Traditional Chinese (see figure 2). In addition, Vim can also support GBK [4] and GB18030 through encoding conversion. In this way, a large number of Vim options for language encoding are available. The following describes the options and recommendation settings (if applicable ):

Figure 2

● Encoding = UTF-8: regardless of the file encoding, regardless of how it is displayed and input, the internal use of Vim encoding is a UTF-8; this is the foundation of international support.

● Termencoding: depends on the actual terminal or X Window settings. For example, if you select Simplified Chinese to log on to X Window or are using CXTERM [10], this option should be set to GB2312; if you log on to X Window using the default language (LANG = en_US.UTF-8), or use PuTTY [11] to remotely access the Linux machine and set the character encoding in (Window-Translation in configuration) if it is set to UTF-8, this option should be set to UTF-8. Note that using PuTTY to remotely connect to Linux in Windows indicates that, only when using UTF-8, puTTY can reliably display and input Chinese characters (the display font must be set to a Chinese font ).

● Fileencoding: When a file is loaded, this option is set to the file encoding recognized by Vim. Therefore, the file encoding will not change during storage. The following fileencodings and fileencodings can use hundreds of encodings supported by libiconv (if the iconv feature is included in the compilation process ), related to the Chinese are gb2312, gbk, gb18030, hz-gb-2312, iso-2022-cn, big5, cp936, cp950 and so on. If you do not want to use the UTF-8 as the file encoding when creating a new file, you may need to set this option manually, such as ": set fileencoding = gb2312 ". It should be noted that using "set" to set this option will change the default encoding of the new file in the future, and using "setlocal" will only affect the current file (refer to ": help setlocal ").

● Fileencodings = ucs-bom, UTF-8, chinese: Vim first checks whether the file starts with a bom (byte order mark) character of Unicode [7] [8]. if yes, the rest of the file is interpreted as the corresponding Unicode sequence; otherwise, try to interpret the file content as a sequence of UTF-8; otherwise, the file is interpreted as simplified chinese (chinese is an alias for a cross-platform simplified chinese character set, which is equivalent to gb2312 and euc-cn in Linux; you can also use gb2312, gbk, or gb18030 encoding as needed ). Note that this order cannot be reversed, and it is meaningless to add other encodings such as big5 and latin1 later, because Vim cannot identify errors in 8-bit encoding, therefore, the encoding of these encoded columns will never be used.

● Ambiwidth = double: indicates all the characters with "uncertain width" [9]. It refers to some characters in the Unicode Character Set that are used in both eastern and western languages, for example, ellipsis, broken signs, book names, and full-angle quotation marks. In Western text, the character width is generally equivalent to ordinary ASCII characters, while in Eastern text, the character width is usually equivalent to two times of ordinary ASCII characters, therefore, the width is "unknown" -- the width is set to double (Chinese character width ). This value is valid only when encoding is set to UTF-8 or a Unicode encoding. Note that if you use Vim through the terminal, you need to make the terminal display these characters as double-width. For example, in the case of XTERM [12], the option "-cjk" should be used, that is, the command "uxterm-cjk" should be used to start the Unicode X terminal that displays these characters in double width; if you use PuTTY for remote connection, select "Treat CJK ambiguous characters as wide" in the configured Window-Translation (see figure 3 ).

Figure 3

The options to be set are usually placed in the Vim resource configuration file of the user, that is, in ~ /Add the following to the vimrc file:

1

2

3

4

setencoding=utf-8

setfileencoding=chinese

setfileencodings=ucs-bom,utf-8,chinese

setambiwidth=double

If you want to learn more about these options, you can use ": help'options'" to view related information in the help document. You can also find the abbreviations of these options (and commands) in this article for ease of understanding. Except for some commands that are rarely spelled, such as ": e (dit)" and ": s (ubstitute), etc., generally use complete spelling without instructions or abbreviations. For the configuration file. vimrc, you can use ": help. vimrc" to view relevant information.

When using an internal encoding UTF-8, to edit a file other than fileencodings that is not automatically recognized, you can run the following command: ": e ++ enc = encoding file name ". For details, see ": help ++ enc ".

1.3. Mouse support

Both the text interface and the Vim Interface Support the mouse. However, in the text interface, the mouse support is not activated by default. This means that when you use the mouse on a terminal, all functions are the same as when Vim is not used and are not affected by Vim. To activate the mouse support in the text interface, you only need to execute the ": set mouse = a" statement.

After mouse support is enabled, Vim mainly supports the following mouse operations:

● Click to move the cursor to the clicked position;

● Double-click the help keyword to display help information related to the keyword;

● Double-click the word at the selected position on the plain text;

● Drag the mouse to select the text;

● Scroll the text in the current buffer with the mouse wheel;

● When editing multiple windows, you can drag the position of the window column.

For more information, see ": help 'mouse", ": help mouse-using", and ": help scroll-mouse-wheel ".

It is particularly worth mentioning that the mouse can also be used for remote access to the Linux system. If you use the X Window System, you don't have to say it. However, when you use SSH for remote connection, most terminal client programs in Linux, for example, XTERM, GNOME-Terminal [13], later versions of Konsole [14], and PuTTY in Windows support the use of the mouse: you only need to simply start Vim and execute ": set mouse = a" (of course, you can also remove the starting colon from the preceding statement and put it in. in the vimrc file ).

1.4. spaces, tabs, and indentation

Indentation is one of the most basic concepts for writing code. As for whether indentation uses spaces, tabs, or whether indentation exactly uses a Tab, many programmers, especially programmers who are developed in Windows, are easily confused. Fortunately, Vim has very complete support for these concepts and is sufficient to cope with various complex situations. The following are the main Vim options:

● Shiftwidth (number of indented spaces );

● Tabstop (Tab width );

● Expandtab (whether to use spaces to replace indentation and Tab keys; Use noexpandtab to cancel settings );

● Softtabstop (soft Tab width. If it is set to a non-zero value, the number of cells moved by the Tab key and Backspace time mark is equal to this value, but the actually inserted characters are still controlled by tabstop and expandtab );

● Autoindent (automatic indent, that is, the indent value of each line is equal to that of the previous line; Use noautoindent to cancel the setting );

● Cindent (using C language indentation, the indentation is automatically adjusted based on special characters such as "{", "}", ":", and whether the statement ends; it is automatically set when editing C/C ++ and other types of files; Use nocindent to cancel the settings );

● Cinoptions (for details about how to indent C language, see ": help cinoptions-values ");

● Paste ).

Below are some common combinations:

● Shiftwidth = 4 tabstop = 4: many Windows programmers will get used to this setting to make indentation equal to the tab width.

● Shiftwidth = 4 tabstop = 8: Many Unix programmers still use the commonly used four-cell indent, but the tab width is the Standard 8.

● Cinoptions => 4, N-2, {2, ^-2,: 2, = 2, g0, h2, p5, t0, + 2, (0, u0, w1, m1 shiftwidth = 2 tabstop = 8: Standard GNU encoding style settings, which make many minor adjustments to Vim's default C indent style, for example, "{" and "}" in the if statement must be indented after "if", but the "{" and "}" in the function definition are still aligned with the function name. Open-source software often uses this indent style.

When editing the code, a useful command is to adjust the code indent, which can easily increase or reduce several levels of indentation, and automatically use the correct spaces or tabs according to the options. You only need to use "V" to select the line of code you want to adjust, and then type "<" (or ">") to increase (or decrease) the first level of indentation; if you type a number before you type "<" (or ">"), you can specify the indentation level to increase (or decrease.

The last related command we want to discuss is ": retab ". When the expandtab option is set, this option converts all tabs into spaces. If the expandtab option is not set, use ": retab !" The blank characters can be converted to tabs (which may be converted by mistake and used with caution). You can use ": retab n" to reset tabstop to n, convert the consecutive blank characters containing tabs into appropriate combinations of tabs and spaces to ensure that the rows containing tabs do not look changed. For more information, see ": help: retab ".

1.5. modeline)

No one wants to manually enter a lot of Tab and indent settings every time. However, it does not seem to be a good idea to put it in the. vimrc file: What if I edit more than one style of code? -- Consider, if you participate in open-source software projects, can you ensure that all the projects you participate in, as well as the software items and code styles in your company are the same? -- Vim is the first editor I have used to record code style settings in files. This feature is called a mode line in Vim. In fact, what it does is to set relevant Vim options according to the Vim command in the file when opening the file. The following is a pattern line embedded in the C source code:

1

/* vim: settabstop=4 shiftwidth=4 expandtab: */

The Mode row has several forms. This article only introduces this form (other forms are similar, please refer to ": help modeline "): the "/*" at the beginning and the "*/" at the end of the line tell the C compiler that this is a line of comment, not part of the code. Vim can use the following "vim: "identifies the start of the mode line (a blank character must appear at the beginning or front of the line); followed by a string of Vim options separated by" set "and spaces;": "indicates that the mode row ends.

This method is very simple and powerful. In addition, for the sake of security, the options in the mode line only affect the current file (": help modeline-local"), and cannot do anything other than the setting options.

1.6. Register

The editor usually has a clipboard to store the copied and cut content. A similar concept in Vim is called register ). Besides an anonymous register, Vim also has a large number of well-known registers. You can use "" (see ": help" ") or" Ctrl-R "(see": help I _CTRL-R and: help c_CTRL-R plus Register names (letters, numbers, and some special characters, see: help registers; "unknown" register name is ""). For example, you copied a row using "ayy", deleted the row using "dd", and moved the cursor to the position to be reset, you can use "aP" to paste the previously copied content. Manual Editing is not very useful for well-known registers, but when you want Vim to automatically complete work in a macro-like way, well-known registers become indispensable and important functions. We will also use it below.

When using the X Window System, there are two special registers that need to be noted: "" * "refers to the primary selection area (primary selection) of X ), the "+" access register is the X clipboard (clipboard ). If you want to copy text between Vim and other X applications, you can try these two registers.

There is also a special "register": "= ". In the insert mode or command mode, type "Ctrl-R =" and Vim will prompt you to enter an expression. The normal Integer Operation is fully valid here. If you want to perform floating point operations, see the techniques in section 3.2.

1.7. Search, replace, and regular expressions

Everyone knows that Vim uses the "/mode" (or "? ": S/mode/string/Flag" is used for the search. The "Mode" is a regular expression. If you are not familiar with regular expressions, you can use them while learning them. In this section, we do not intend to fully elaborate on Vim's regular expressions (you may be able to write a special booklet ), some useful examples and some practical skills are provided.

Let's start with a little search. One of the most useful shortcuts in searching is "*" (matching words under the cursor down completely ). Move the cursor to the word you want to search (variable name, function name, etc.), such as "test", and then press "*", Vim will automatically generate a pair of "\ "(See": help/\ <"and": help/\> "), that is, to search for the complete word" test ". Don't underestimate this technique. It often greatly improves the search speed. In fact, this is the No. 1st technique published on the Vim website, and it is also the most rated skill. Similar tips include "#" (matching words under the cursor up), "g *" (matching words under the cursor down partially), etc. Please check it yourself (": help ).

Vim brightens successfully matched text during search and replacement. After the search and replacement tasks have been completed, Such brightening sometimes hinders display. Vim provides a dedicated Command to cancel this highlight (until the user again uses the search or replacement command): ": nohlsearch ". We recommend that you create a key mapping and add it to. vimrc, for example:

1

nmap:nohlsearch

The preceding command indicates that pressing the F2 key in normal mode is equivalent to entering ": nohlsearch" followed by a carriage return, that is, canceling the search highlight.

Let's look at several practical examples of search replacement.

● Remove the spaces at the end of all rows: "% s/\ s \ + $ //". "%" Indicates replacement within the entire file range, and "\ s" indicates blank characters (spaces and tabs ), "\ +" matches the previous character once or multiple times (the more the better), and "$" matches the end of the line ("\ $" indicates a simple "$" character ); the content to be replaced is blank. Because a row only needs to be replaced once at most, no special flag is required. This is relatively simple.

● Remove all blank lines: "% s/\ (\ s * \ n \) \ +/\ r /". "\ (", "\)", "\ N", "\ r", and "*" are added. "*" Indicates matching the first character ("\ s" Here) zero or multiple times (the more the better; "\ *" indicates a simple "*" character ), "\ n" indicates a linefeed, "\ r" indicates a carriage return, and "\ (" and "\)" groups expressions to make them an integral whole. Therefore, the complete meaning of this expression is to replace a continuous line break (including any consecutive blank characters before the line break) with a single line break. The only special difference is that "\ n" is used in the mode, but "\ n" is not used in the replaced content, but "\ r" is only used ". The reason is caused by history. for details, see ": help NL-used-for-Nul ".

● Remove all "//" Comments: ": % s! \ S *//.*!!". First, you can note that the separator here is changed to "!", The reason is that the "/" character is used in the mode or character string. If other separators are not used, you must write "\/" each time you use the "/" character. the above command must be written as ": % s/\ s *\/\/. * // ", which is less readable. The command itself is quite simple. People who have used regular expressions probably know that "." matches any character except line breaks.

● Remove all "/**/" Comments: ": % s! \ S */\ * \ _. \ {-} \ */\ s *! ! G ". This is a little complicated. We have used a few less commonly used Vim regular expression features. "\ _. "Matches all characters including line breaks." \ {-} "indicates that the previous character can appear zero or multiple times. However, if the entire regular expression can match successfully, the smaller the number of matched characters, the better. The mark "g" indicates that a row can be matched and replaced multiple times. The replacement result is a space to ensure that expressions like "int/* space not necessary around und comments */main ()" are still valid after replacement.

We hope that the above simple examples will interest you in using Vim regular expressions to efficiently complete tasks. For more information, see ": help regexp ".

1.8. Automatic completion and path setting

Vim supports Automatic completion of words. For example, if you use a long variable name named aLongVariable, you do not need to complete the input. Most likely, you just need to type "aL" and press "Ctrl-P" (search for matching words and complete them) you can get the complete variable name (if you do not get the expected result, press Ctrl-P for a few times, or enter a few more characters, such as "aLongV "). Similar Commands include "Ctrl-N" (backward searching for matching words and completing) and "Ctrl-X Ctrl-L" (searching for matching rows and completing), "Ctrl-X Ctrl-F" (search for matching file names and complete), etc. For details, see ": help ins-completion ".

If you are not familiar with these functions, but do not think it is strange, the following example may surprise you. Open a blank C file (vim test. c) and enter:

1

2

3

4

#include

int main()

{

pri

Do not press enter in the last line. Enter "Ctrl-P" directly after "pri". You will see "printf. Yes, although there is no "printf" in the file, Vim knows where to look for it! When the keyword match is complete, if the current file and other open files do not have the desired results, vim will automatically go to the "# include" file for further search (why is it "# include? For more information, see ": help 'include '". The directory to be searched is determined by the option path. The default value is "., /usr/include, "indicates that the directories to be searched are respectively the directory where the files are located,/usr/include, and the current directory. Depending on the actual situation, you may need. set this option in the vimrc file and add the project-related include directory. Note that the last "," should be retained unless you do not need to search in the current directory.

After a proper path is set, you can use the "gf" command to conveniently jump to the file represented by the file name under the cursor. In the above example, move the cursor to any character of "stdio. h" and type "gf", Vim will automatically open the/usr/include/stdio. h file. Use Ctrl-O (see: help CTRL-O) to return to the original file.

As you know, double-click the keyword in the Vim Help window or press Ctrl-] to jump to the help topic related to this keyword. However, the "Jump to matching keyword" function is not limited to help files. As long as there is a suitable tags file (see ": help tags-file-format"), we can also use this convenient function in the source code, jump to the "tag" that matches the keyword (usually the definition location of a function, type, variable or macro in the source code ).

To generate a tags file, we usually use Exuberant Ctags [15]. This tool is available in general Linux releases. Ctags has a large number of options. Here we only briefly describe how to use the basic functions in a typical multi-file, multi-layer Directory Project: you only need to enter "ctags-R. ", Ctags can automatically find and identify supported file formats in the file, and generate tags files. Currently, Exuberant Ctags supports up to 33 programming languages [16], including C, C ++, Java, Perl, and PHP commonly used in Linux. With the tags file, the following Vim commands can be used conveniently (for more information, see ": help tags-and-searches "):

●: Tag keyword (jump to the tag that matches the keyword)

●: Tselect [keyword] (display the tag list that matches the "keyword" and enter a number to jump to the specified tag)

●: Tjump [keyword] (similar to ": tselect", but when there is only one matching item, it jumps directly to the tag without displaying the list)

●: Tn (jump to the next matched tag)

●: Tp (jump to the last matched tag)

● Ctrl-] (jump to the tag that matches the keyword under the cursor. Except for the "keyword", it is automatically obtained from the cursor position and has the same function as ": tags ".

● G] (similar to "Ctrl-]", but the command used is ": tselect ")

● G Ctrl-] (similar to "Ctrl-]", but the command used is ": tjump ")

● Ctrl-T (jump back to the position before the previous jump using the above command)

These commands work well when we work in the project root directory. However, if we enter the layer in the multi-layer directory and run Vim to open the file, the execution result of these commands is usually changed to the error message "E433: No tags file ". This is because by default, Vim only searches for the tags file in the directory where the file is located and in the current directory. We generated a tags file in the root directory of the project, and Vim could not find the file. There are several solutions. I think it is generally easier to add a path setting for each project in the. vimrc file. Assume that we have two projects at/home/my/proj1 and/home/my/proj2 respectively. Then we can use:

1

2

au BufEnter /home/my/proj1/* setlocal tags+=/home/my/proj1/tags

au BufEnter /home/my/proj2/* setlocal tags+=/home/my/proj2/tags

The Vim option tags is used to control the check tags file. The default value is "./tags, tags", that is, the tags file in the directory where the file is located and in the current directory. The above two lines of automatic commands tell Vim to add the project's tags file path to the content in the tags option when opening files in the project directory. For more information, see ": help 'tags '".

1.10. Make and grep

Make [17] And grep [18] are basic tools in the Unix world. Naturally, Vim has special support for them. This support is mainly implemented by accessing a special quick fix window. Enter the relevant make or grep commands (for example, ": grep foo *. c) to put the execution result of the command into this window, and jump to the first Error Based on the returned result (make; When grep is used, the match is successful ). The following are common "quick revision" commands:

●: Cn (displays the next error)

●: Cp (display the previous error)

● Cl (list all errors and their numbers)

●: Cc (jump to the error of the specified number)

●: Copen (open the quick revision window and show all errors. You can double-click the error or press the Enter key to jump to the error. For example, see Figure 4)

Figure 4

●: Cclose (Closing the quick revision window)

This feature of Vim can also work with programs other than make and grep (in fact, on Windows XP, the ": grep" command generally calls "findstr/n "). The specific program called is controlled by the options makeprg ("make" by default in Linux) and grepprg ("grep-n $ */dev/null" by default in Linux, the options errorformat and grepformat control how to parse the returned content. Since you do not need to change the content of these options in Unix/Linux, we will not detail them here.

1.11. Execute External commands

In a command like ": make", Vim automatically calls an external program. Of course, you can also execute external programs by yourself: it is estimated that many people already know that ":! Command "You can execute an external command in Vim. However, it is estimated that most people do not know, and there are other commands that can execute External commands, even if ":!" There are also some tips in the command.

The most formal method for executing external commands, as mentioned above, is ":!". For example, if we want to display all the files in the current directory, we can directly execute: ":! Ls ". Vim will list the files in a terminal window, and then prompt us to press the key to return to Vim. In fact, this method is more practical for commands that require no output such as "cp" and "rm", but not for commands that focus on output like "ls.

If you want to insert the execution result of an external command to the buffer currently edited, you can use ": r !". For example, we use ": r! Ls to insert the execution result of the ls command to the row where the cursor is located in the buffer. This may be particularly useful when using macros.

Vim's ":!" The command also has a particularly powerful technique to use. In this example, we need to insert a number before each row of a file. What should we do? -- Vim macros or scripts can be used to complete this task, but this is not the most efficient and flexible way of working. Generally, the GNU nl in Linux can be used in a flexible way to complete this task-to number all non-empty rows, you only need to ": %! Nl "; do you want to number all rows that contain empty rows? OK, ": %! Nl-ba ".

I will explain it a little bit. After selecting a text line in visual mode, type ":!". (": '<,'>!" Appears on the command line !", Indicates that the command range is selected text), or use ": % !" (The command range is the text in the entire buffer zone.) When executing the following command, Vim uses the text lines in the Command range as the standard input for subsequent command execution, replace the text lines in the current buffer with the standard output after command execution. This is how the above command line works.

1.12. Fixed-width text Layout

In traditional Unix environments, the definition of a text file is a combination of lines with a certain length limit [19]. Although Vim has no actual limit on the line length, some tools have such restrictions. For maximum compatibility and convenience in display and print processing, we recommend that you do not exceed 72 columns (up to 80 columns) in emails and source code ). Vim has special support in processing fixed-width text. The following is a result of entering the first sentence of Harry Potter and the Half-Blood Prince after setting the row width (use the textwidth option) to 40 in Vim:

1

2

3

4

5

6

It was nearing midnight and the Prime

Minister was sitting alone inhis

office, reading a long memo that was

slipping through his brain without

leaving the slightest trace of meaning

behind.

Only English letters and spaces are used for input. The linefeed is automatically inserted by Vim. What should I do if I add or delete some characters in a row before the operation? It is easy to move the cursor to the beginning of the text to be re-formatted. Use the "gq" command followed by a cursor movement command to determine the re-formatting range. For example, "gq}", "gq5j", and "gqG ).

In addition to the textwidth option, the formatoptions option determines the basic options related to Text Formatting. common values include:

● T: automatically fold rows based on textwidth;

● C: automatically fold the line in the comments (in the program source code) and insert the appropriate comment start character;

● R: In insert mode, when you press enter in a comment, insert a suitable comment start character;

● Q: You can use the "gq" command to format the comment;

● N: identifies the number list. The indentation of the next line of the number row is determined by the blank space after the number (in conflict with "2", "autoindent" is required ");

● 2: Use the indentation of the second line to format the text;

● L: when the length of the current row exceeds textwidth, It is not automatically reformatted;

● M: It can be broken at multi-byte characters and is especially valid for Chinese characters (otherwise, it can only be broken at spaces );

● M: When splicing two rows (re-formatting, or manually using the "J" command), if the end of the first line or the start of the last line is multi-byte characters, no space is inserted, very suitable for Chinese

The annotations mentioned above can be "//" and "/*" in C/C ++. it can also be the ">" or other characters used to reference the original text in an email (controlled by the comments option; see ": help 'comments '"). Vim can intelligently process these characters, which is sufficient for daily source code editing and email editing. When using some mail clients that are not powerful enough to process plain text, I usually use Vim to edit emails (especially English emails) and paste the results back to the mail editing window for sending.

In Vim, the default value of formatoptions is "tcq. add a line "set formatoptions + = mM" to the vimrc file to ensure that Vim can fold lines between Chinese characters without spaces, in most cases, you can correctly reformat Chinese characters.

1.13. Other Tips

You may find these useful:

● % (Jump to the matching brackets)

●. (Repeat the last modification command)

● '. (Jump to the last modified location)

● ZQ (exit unconditionally

● ZZ (Disk logout)

● Ga (display the internal code of the character under the cursor under the currently used encoding)

● Guw (words under the cursor become lowercase)

● GUw (words under the cursor are capitalized)

●: TOhtml (generate HTML code based on the Vim Syntax highlighted; you can also use the "Syntax-Convert to HTML" menu in the graphic interface to achieve the same effect)

When you are bored, you can try again (haha !) :

●: Help!

●: Help 42

●: Help holy-grail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.