Vim practical technology (2)

Source: Internet
Author: User
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 bunch of well-known registers. You can use "(see": Help "") or "Ctrl-R" (see ": help I _CTRL-R "and": Help c_CTRL-R ") plus register name (letters, numbers, and some special characters, see": Help registers ";" "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: "*" The accessed register is 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 =". 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.

Search, replace, and regular expression

Everyone knows that Vim uses "/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. In this section, we do not intend to fully elaborate on VIM Regular Expressions (you may be able to write a special booklet ), here, we will give some useful examples and some practical skills.

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 for (variable name, function name, etc.), such as "test", and then press "*", vim automatically generates a search for "\ <Test \>" (see ": Help/\ <" and ": Help/\>"), that is, 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 techniques include "#" (matching words under the cursor up), "g *" (matching words under the cursor down partially), etc. Please check it yourself (": help # ", etc ).

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:

nmap 
      
        :nohlsearch
       
      

The preceding command indicates that pressing the F2 key in normal mode is equivalent to inputting ": nohlsearch" followed by a carriage return, that is, canceling 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 (use "\ $" to indicate a simple "$" character ); the content to be replaced is blank. Because a row only needs to be replaced once at most, no special logo is required. This is relatively simple.
  • Remove all blank lines: ": % S/\ (\ s * \ n \) \ +/\ r /". "\ (", "\)", "\ N", "\ r", and "*" are added "*". "*" Indicates matching the previous character (\ s) zero or multiple times (the more the better, use "\ *" to indicate a "*" 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 the continuous linefeed (including the possible consecutive blank characters before the linefeed) with a single linefeed. The only 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 the historical generation. For more information, see ": Help NL-used-for-NUL ".
  • Remove all "//" Comments: ": % s! \ S *//.*!! ". First, you can note that the separator here is changed "! ", The reason is that the"/"character is used in the mode or string. If other separators are not used, you must use the"/"character as" \/"each time "\/", the above command must be written as ": % S/\ s *\/\/. * // ", low readability. The command itself is quite simple. People who have used regular expressions 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. "\_. "Match All characters including line breaks;" \ {-} "indicates that the previous character can appear zero or multiple times, but 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 ".

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" (search for matching words and complete them) and "Ctrl-x Ctrl-l" (search for matching rows and complete them) and "Ctrl-x Ctrl-F" (search for matching file names and complete). 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:

#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? 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 you need to keep the last "," 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.

File redirection and tags

As you know, double-click the keyword in the Vim Help window or type "Ctrl-]" to jump to the help topic related to this keyword. However, the "Jump to matching keyword" function is not limited to help files. If you have 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 search for and identify supported file formats in files, 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", enter a number to jump to the specified tag)
  • : Tjump [keyword] (similar to ": tselect", but when there is only one matching item, Jump 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 the function is the same 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 an 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 in the/home/My/proj1 and/home/My/proj2 locations.

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 preceding 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 '".

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 ") You can 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 enter to jump to the error. For example, see)

  • : CClose (close 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 modify these options in Unix/Linux, we will not detail them here.

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 how to use it ":! 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 ":! "The command also has some tips to use.

The most formal method for executing external commands, as mentioned above, is ":! ". For example, to display all the files in the current directory, run the following command :":! Ls ". Vim will list the files in a final window, and then prompt us to press the key to return to vim. In fact, this method is more practical for commands that do not need to be output like "CP" and "RM", and is not very useful 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 ":! "The command also has a very 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. Linux generally carries the gnu nl, which can be completed in a very flexible way-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 ":! "(": '<,'>! ", Indicating that the command range is selected text), or use": %! "(The command range is the text in the 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.

Set 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 (no more than 80 columns) in emails and source code ). Vim has special support capabilities in handling wide texts. 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:

It was nearing midnight and the Prime
Minister was sitting alone in his
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}" (format a segment), "gq5j" (format 5 rows), and "gqg" (format to the end of the file ).

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 comments start character;
  • R: In insert mode, when you press enter in the comment, insert the appropriate comment start character;
  • Q: You can use the "GQ" command to format comments;
  • 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 effective 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 a ">" or other character used to reference the original text in an email (controlled by the comments option. For details, 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.

Other Tips

You may find these useful:

  • % (Jump to matching brackets)
  • . (Repeat the last modification command)
  • '. (Jump to the last modified location)
  • ZQ (exit unconditionally)
  • ZZ (save 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 change to uppercase)
  • : Tohtml (generate HTML code based on the vim syntax highlighted; you can also use the menu "syntax-convert to HTML" in the GUI 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.