From: http://www.ibm.com/developerworks/cn/linux/l-tip-vim3/index.html
3.1. Vim script Basics
In the. vimrc file, and in the plug-in and syntax files mentioned in Chapter 2, the language used is the Vim script language. The syntax of this script language is a bit like BASIC, and the expression is a bit like C, which is easy to understand. This chapter does not intend to give a very systematic introduction to it (for a complete understanding, see ": help usr_41.txt"), but only introduces some basic knowledge, especially understanding customization. basic knowledge required by vimrc.
The Vim script is equivalent to a command that can be executed directly in command mode, but does not need to enter the colon (if a colon is used, no error will occur ). Therefore, commands such as setting options and creating keyboard mappings are directly available. Of course, as a scripting language, in addition to the commands that are input on a common keyboard, we also need more complex functions, especially variables, expressions, conditions, and cyclic statements and functions.
3.1.1. Variables
In Vim, assign values to variables (create variables) using the following syntax ):
Let variable name = Value |
There are two types of variables: integer and string, which cannot be used before the first value assignment. In addition to regular letters, underscores, and numbers, variable names can also use special prefixes:
- "B:" -- only variables valid for the current buffer;
- "W:" -- only variables valid for the current window being edited.
- "G:" -- global variable (the prefix must be used to access the global variable in the function. If the prefix is not added, it is considered as a local variable in the function );
- "S:" -- the variable name is valid only in the current script;
- "A:" -- function parameters;
- "V:" -- Special variables predefined in Vim (see ": help vim-variable ").
The following three prefixes are used to access special values. Because the behavior is similar to the variable (which can be read and modified), they are also discussed here:
- "$" -- Access environment variables;
- "&" -- Access Vim options;
- "@" -- Access register.
When the variable is no longer used, you can use "unlet variable name" to delete the variable.
3.1.2. Expression
Similar to C, variables and constants can be used, parentheses can be used, and functions can be called ("function name (...) "), supports addition (" + "), subtraction ("-"), multiplication (" * "), Division ("/"), and modulo (" % "), logical operations ("&", "|", and "! "), Supports the ternary conditional expression ("? B: c "). String operations are certainly better than C. You can use "." To concatenate strings. You can use "=" and "<=" to compare the string size. You can use "= ~" And "! ~" Matches regular expressions. You can add "#" or "?" After the comparison operator. To force case-sensitive or non-sensitive comparisons (affected by the Vim option ignorecase by default ). To display the result of an expression, you can use ": echo expression" to display it on the status bar, or use "Ctrl-R = expression" in insert mode to insert it into the text of the buffer zone.
Like many other languages that have grown up in Unix, Vim's string constants can be enclosed in double quotes or single quotes. If single quotes are used, any character in single quotes is a part of a string, which cannot contain single quotes. If you use double quotation marks, you can use "\" to generate a code-changing sequence (For details, refer to ": help expr-quote"). For example, "\ n" indicates a line break, "\" "represents double quotation marks," \ "represents the backslash itself, and so on.
Note that double quotation marks can represent both string constants and comments. The "at the beginning of the line, and the" that appears in the expression, all indicate that the parts after "" Are comments.
3.1.3. Condition and loop statements
The condition statement format is as follows:
If expression statement endif |
Or
If expression statement else statement endif |
Or
If expression statement elseif expression statement endif |
The statement format is as follows:
While expression statement endwhile |
Both conditions and loop statements can be nested. These are relatively simple and will not be explained in detail.
3.1.4. Functions
When using a function in an expression, it is similar to the method in C. You can directly use the function name with brackets and write parameters in brackets (optional ). When a function is called without a return value, it is slightly different. You need to use the "call" command, followed by the function name and brackets (the parameters may be included in the brackets ).
The following syntax is used to define a function:
Function Name (parameter list) Statement endfunction |
If a function with the same name already exists, Vim will report an error unless "!" is added after "function".
If the parameter does not contain "... ", the number of parameters is fixed, and the function caller must provide the same number of parameters as the definition (Add" a: "before using the parameter name in the function definition for access ). If the parameter contains "... ", the number of parameters is not fixed. In addition to using the parameter name to access the passed parameters, you can also use" a: 0 "to know the number of parameters to be passed, and use": 1 "," a: 2 ", and so on.
You can use the "return" statement to return a value in the middle of the function.
Vim defines more than one hundred functions. For a detailed list, see ": help function-list ".
Back to Top
3.2. My. vimrc
As a specific example of a Vim script, I will explain the most practical situation, my. vimrc file. File .vimrc.html (Please download it locally to open it) is an HTML file generated by my. vimrc file following these steps:
1. Open the. vimrc file in Vim;
2. Run the ": colorscheme koehler" command (the default color scheme may not work well in the browser)
3. Execute the command ": %! Nl-w4-s ''(section 1.11)
4. Execute the command ": TOhtml" (section 1.13)
5. Execute the command ": w"
You can paste the text in the browser to Vim, and then use the following replacement command ": % s/^ \ + [0-9] \ +/" to delete the previous row number, to restore the original. vimrc file.
Next we will explain it one by one and include links to the materials required to understand its content. We recommend that you directly read The. vimrc file and read the following explanation when you have any questions.
Row 1st: Comment (the last section of section 3.1.2), which contains a pattern line (section 1.4 and section 1.5 ).
Line 1: first, determine whether the system supports "autocmd". If yes, execute the content from line 2 to line 6 (Section 2nd, ": help has", and ": help feature-list ").
Row 3rd: Pure annotation (I will skip the annotation line later and will not describe it ).
Line 2: Clear all automatic commands (": help autocmd-remove") to facilitate debugging. You can use "source ~ /. Vimrc "to view the modified results (": help source ").
Row 3: For Files suffixed with ". asm", Microsoft Macro explorer format (": help masm-syntax") is used ").
Row 7th: paired with the if Statement of row 2nd.
Row 8th-10: When the graphic interface is used (": help feature-list"), make sure that all file types appear under the "Syntax" ("Syntax") menu, instead of displaying a menu item "Show filetypes in menu ". By default, Vim can be started a little faster.
Row 11th-13: When a graphical interface is used and the environment variable LANG does not contain "." (that is, there is no required encoding), set Vim's internal encoding to a UTF-8.
Row 3: No need to maintain compatibility with vi (": help 'compute '").
Row 15th: runs the. vimrc file provided by Vim by default. It contains the most common functions such as opening the syntax to highlight the display.
Row 16th: Enable auto indent (section 1.4 ).
Row 17th: No backup file is generated by default (": help 'backup '").
Row 18th: The time mark in the input parentheses will temporarily jump to the matching brackets without affecting the input (": help 'showmatch '").
Row 19th: lines and splices of Chinese characters (section 1.12 ).
Row 20th: automatically recognized file types include Unicode files with BOM characters, UTF-8-encoded files, and GBK-encoded files.
Row 21st: sets the status line so that it can display the file encoding information, "gbk" and "big5" (": help 'statusline'") in step 2 '").
Figure 2
Lines 22nd-24: If Vim supports the mouse, enable the mouse support (Section 1.3 ).
Lines 25th-29: Determine whether Vim contains multi-byte Language Support (multi_byte feature), and the version number (": help v: version") is greater than 6.1 (including the ambiwidth option ).
Lines 26th-28: If the Vim language (": help v: lang"; is affected by the Environment Variable LANG) is Chinese (zh), Japanese (ja), or Korean (ko) set the width (ambiwidth option, section 1.2) of the Unicode character with fuzzy width to double ).
31st-36 rows: Change the upper and lower direction key behavior mode: Generally, these keys are used in logical rows, so it may be inconvenient to move the cursor if the row is long; these keyboard mappings change the scope of these keys to the screen line ("help gk "), the ing "Ctrl-j" and "Ctrl-k" are also added to those who are used to "j" and "k" to screen rows. The commands used for the preceding four mappings are "noremap", which acts on normal mode, visual mode, and command execution. The commands used for the subsequent two mappings are "inoremap", which only acts on the insert mode, use Ctrl-O to temporarily execute a common mode command (': help I _CTRL-O ").
Row 38th-41: In the insert mode of Vim, you can use "Ctrl-R =" to calculate the value of the integer expression, but Vim itself does not have the ability to calculate the floating-point expression. These four mappings provide the computing power of floating-point expressions: "\ ma" (assuming that the Leader character is the default "\", see ": help <Leader> ") the calculation result can be placed on the next line (the expression to be calculated is the current row or the content selected in visual mode ), use "\ mr" to replace the expression to be calculated with the calculated result (also the content selected for the current row or in visual mode ). These mappings assume that a command "calcu" can be used to calculate the content of an expression. This command can be simply implemented using the following shell script:
#! /bin/shecho "$*" | sed -e $'s/\r$//' -e 's/sin *(/s(/g' -e 's/cos *(/c(/g' -e 's/atan * (/a(/g' -e 's/log *(/l(/g' -e 's/exp *(/e(/g' | bc -l |
This script converts the expression to a form acceptable to bc [1] (converts "sin (x)" to "s (x)", and so on ), and the standard input sent to bc through the standard output.
This ing is complex and is not explained here-the central idea is to select the expression to be calculated and put it in the unknown register, then press Ctrl-R to paste it to the command line, use calcu for calculation, and then paste the result back to the buffer being edited. The last one is the most complex, to replace the original expression, remember the start and end positions of the selected content. You may want to see ": help gv", ": help v_o", and ": help m ",": help' ", and review section 1.11. Note that "<silent>" (": help map-<silent>") is used in the ing, which prevents explicit execution on the command line.
Row 43rd-44: allows users to use F2 to cancel the highlighted display of Search/replacement. Here, a ing is used for the normal mode (nmap) and an insert mode (imap ). As mentioned above, "Ctrl-O" can run a command in Normal Mode in insert mode.
Lines 46th-47: These two mappings are used for the taglist plug-in. Use F9 to directly open (or close) The taglist window.
Lines 49th-50: Used in the quick revision window (section 1.10). You can use F11 (and F12) to view the next (previous) error (or grep item ).
Lines 52nd-65: Some Vim settings for running in text mode. For details, see the following description.
Rows 54th-56: Set the variable Tlist_Inc_Winwidth to 0 to prevent the taglist plug-in from changing the terminal window size (in some cases, the system may be unstable ). When "has ('eval')" is used, this statement is run only in Vim versions with relatively complete functions and at least expressions supported.
58th-64 lines: enable the text mode menu in the system with the wildmenu feature (": help 'wildmenu.
Row 59th: Open the wildmenu option and start the command line with the menu item prompt to automatically complete.
Row 60th: ensure that the Character Sequence '<C-Z>' is understood as Ctrl-Z rather than the separated five characters (': help' cpoptions '").
Row 61st: sets the Automatic completion prompt using Ctrl-Z to activate.
Lines 62nd-63: Map F10 in normal mode and insert mode to an execution menu item, and automatically prompt the menu content. Note that the default menu is still not loaded automatically. The main purpose of using this feature is to use the CVS menu in text mode Vim. Figure 16 shows the result of pressing the F10 key and then the Tab key.
Figure 16
Lines 66th-161: Use the autocmd feature. Use "has" to prevent this part of content from running in Vim versions that do not support automatic commands.
Lines 67th-129: defines the functions used by the following automatic commands. For details, refer to the following automatic commands. Note that a "!" is used after each "function". (": Help E122"): To facilitate debugging, let "source ~ /. Vimrc "can run correctly without reporting the function-defined errors.
Row 131st-133: as long as the environment variable VIM_HATE_SPACE_ERRORS is not set to zero, set the value of the variable c_space_errors to 1. The result is a blank character that is "Incorrect" in the C/C ++ Code (the blank character at the end of the line and the space that follows the tab characters) will be highlighted. In the code shown in Figure 17, two spaces are added at the end of the row of line 1, and spaces are added before the first tab of Line 2. The Vim prompt #935 contains some additional instructions. For more information, see the description of row 160th.
Figure 17
Row 3: The English spelling variant is the Canadian style, that is, the spelling "abridgement" (instead of "abridgment") and "color" (instead of "color ") "realize" (rather than "realize"), "theater" (rather than "theater"), and so on, are more in line with the spelling style in Chinese English textbooks, it is also suitable for writing "international" English.
Row 138th: Use the keyboard ing "\ a" to view the character attributes under the cursor, which is mainly used to debug the Vim syntax file. Figure 18 shows that the syntax "group" of the Characters Under the cursor is vimOption, PreProc (preprocessing symbol) is used in the color scheme, and the foreground color is purple (RGB: # a020f0 ). If you are interested, view the specific content of Vim script #383.
Figure 18
Row 140th: When the function cannot be found (": help FuncUndefined"), it is automatically run in the runtime environment (in Linux, it is generally ~ /. Vim) read the. vim file with the same name as the function in the autoload directory. This is the recommended Installation Method for script #383 (the SyntaxAttr. vim file is placed in the autoload directory and loaded only during execution ).
Row 142nd: Set the options for C/C ++ files (section 1.4 ).
Row 143rd: Set the indentation and Tab width of the patch file to the same as that of the C/C ++ file (section 1.4 ).
Row 144th: cancels the indentation automatically generated by Vim on the HTML tag, but enable the auto indent option (section 1.4 ).
Row 3: For files whose log type is changed, set the row width to 76 characters (section 145th ).
Row 3: When the file suffix is ". gb, it is considered a GBK-encoded file, before reading the file (": help BufReadPre ") call the SetFileEncodings function to save the content of the original fileencodings option in a variable in this buffer zone (section 3.1.1), and then set fileencodings to gbk, that is, the file content is interpreted as a GBK character sequence.
Row 148th: similar to the above example, the file with the suffix ". big5" is treated as a Big5 encoded file. before reading the file, set fileencodings to big5 and only try to interpret the file content as a Big5 character sequence.
Line 2: similar to the above, the file suffixed with ". nfo" is treated as a CP437 encoding (that is, an English dos oem character set encoding) file. See Figure 19 for the effect.
Figure 19
Row 150th: after reading the. gb,. big5, or. nfo file (": help BufReadPost"), call the RestoreFileEncodings function to restore the original value of fileencodings.
Row 151st:. the CheckFileEncoding function is called to check whether the file has been modified and fileencoding has a value when the file is displayed (": help BufWinEnter. If the conditions are met, it indicates that the file has modified fileencoding in the mode line. Therefore, this encoding (": help ++ enc") is used to force the file again ("!"). Read the file to ensure that the file is correctly decoded. The Vim prompt #911 contains some additional instructions.
Row 153rd: in case of an HTML file, if Vim determines the encoding Type and uses "<meta http-equiv =" Content-Type "content =" text/HTML; charset = encoding ">" indicates that the encoding is inconsistent. You can use the encoding specified in the webpage to re-read the file. The ConvertHtmlEncoding function converts the encoding names used in some webpages to the correct encoded names that can be processed by Vim. The function DetectHtmlEncoding writes down the current cursor position after determining whether the file type is HTML, search the preceding HTML code line to find out the character set encoding. After the encoding is not equal to the current file encoding (fileencoding) when the current file encoding is null or equal to the file encoding determined by the system, use this encoding to forcibly re-read the file and ignore any errors ("silent! "). This automatic command can be written as nested (": help autocmd-nested") to ensure that the syntax is highlighted and the cursor position of the last opened file is correctly maintained. The Vim prompt #1074 contains some additional instructions.
Lines 155th-156: Make sure that all files in the/usr/include/c ++ and/usr/include/g ++-3 directories are treated as C ++ files, no matter what file type Vim originally identified (": help BufEnter "). Many Standard C ++ header files (such as "algorithm") do not have a file suffix. By default, Vim is not treated as a C ++ file.
Row 158th: Row 142nd sets the tab width of the C/C ++ file to 4 (personal setting). However, the source code of the system generally uses the GNU coding standard and the tab width is 8. This row sets all files under the/usr directory to use the GNU coding specification (section 1.4 ).
Row 160th: before writing a file (": help BufWritePre"), call the RemoveTrailingSpace function: as long as the environment variable VIM_HATE_SPACE_ERRORS is not set to zero, for files of the C, C ++, and Vim script types, the blank characters at the end of all rows are automatically cleared. The "normal m'" indicates the current cursor position, "normal'' "restores the memory cursor position.
So far, I have introduced the basic knowledge of Vim, many practical skills and some of the most commonly used Vim plug-ins, and introduced the basic knowledge of scripts through the custom. vimrc file. If you need to further study Vim or want to raise specific questions about Vim, you may wish to participate in the Vim email discussion list from the Vim website, which will benefit a lot. The author also hopes that this article has completed the task of guiding readers to learn and understand the advanced features of Vim.