*insert.txt* For Vim version 9.1. Last change: 2024 Aug 25 VIM REFERENCE MANUAL by Bram Moolenaar *Insert* *Insert-mode* Inserting and replacing text *mode-ins-repl* Most of this file is about Insert and Replace mode. At the end are a few commands for inserting text in other ways. An overview of the most often used commands can be found in chapter 24 of the user manual |usr_24.txt|. 1. Special keys |ins-special-keys| 2. Special special keys |ins-special-special| 3. 'textwidth' and 'wrapmargin' options |ins-textwidth| 4. 'expandtab', 'smarttab' and 'softtabstop' options |ins-expandtab| 5. Replace mode |Replace-mode| 6. Virtual Replace mode |Virtual-Replace-mode| 7. Insert mode completion |ins-completion| 8. Insert mode commands |inserting| 9. Ex insert commands |inserting-ex| 10. Inserting a file |inserting-file| Also see 'virtualedit', for moving the cursor to positions where there is no character. Useful for editing a table. ============================================================================== 1. Special keys *ins-special-keys* In Insert and Replace mode, the following characters have a special meaning; other characters are inserted directly. To insert one of these special characters into the buffer, precede it with CTRL-V. To insert a character use "CTRL-V CTRL-@" or "CTRL-V 000". On some systems, you have to use "CTRL-V 003" to insert a CTRL-C. Note: When CTRL-V is mapped you can often use CTRL-Q instead |i_CTRL-Q|. If you are working in a special language mode when inserting text, see the 'langmap' option, |'langmap'|, on how to avoid switching this mode on and off all the time. If you have 'insertmode' set, and a few other keys get another meaning. See |'insertmode'|. char action ~ ----------------------------------------------------------------------- *i_CTRL-[* *i_* or CTRL-[ End insert or Replace mode, go back to Normal mode. Finish abbreviation. Note: If your key is hard to hit on your keyboard, train yourself to use CTRL-[. If Esc doesn't work and you are using a Mac, try CTRL-Esc. Or disable Listening under Accessibility preferences. *i_CTRL-C* CTRL-C Quit insert mode, go back to Normal mode. Do not check for abbreviations. Does not trigger the |InsertLeave| autocommand event. *i_CTRL-@* CTRL-@ Insert previously inserted text and stop insert. *i_CTRL-A* CTRL-A Insert previously inserted text. *i_CTRL-H* *i_* *i_BS* or CTRL-H Delete the character before the cursor (see |i_backspacing| about joining lines). See |:fixdel| if your key does not do what you want. *i_* *i_DEL* Delete the character under the cursor. If the cursor is at the end of the line, and the 'backspace' option includes "eol", delete the ; the next line is appended after the current one. See |:fixdel| if your key does not do what you want. *i_CTRL-W* CTRL-W Delete the word before the cursor (see |i_backspacing| about joining lines). See the section "word motions", |word-motions|, for the definition of a word. *i_CTRL-U* CTRL-U Delete all entered characters before the cursor in the current line. If there are no newly entered characters and 'backspace' is not empty, delete all characters before the cursor in the current line. If C-indenting is enabled the indent will be adjusted if the line becomes blank. See |i_backspacing| about joining lines. *i_CTRL-I* *i_* *i_Tab* or CTRL-I Insert a tab. If the 'expandtab' option is on, the equivalent number of spaces is inserted (use CTRL-V to avoid the expansion; use CTRL-Q if CTRL-V is mapped |i_CTRL-Q|). See also the 'smarttab' option and |ins-expandtab|. *i_CTRL-J* *i_* or CTRL-J Begin new line. *i_CTRL-M* *i_* or CTRL-M Begin new line. *i_CTRL-K* CTRL-K {char1} [char2] Enter digraph (see |digraphs|). When {char1} is a special key, the code for that key is inserted in <> form. For example, the string "" can be entered by typing (two keys). Neither char is considered for mapping. CTRL-N Find next keyword (see |i_CTRL-N|). CTRL-P Find previous keyword (see |i_CTRL-P|). CTRL-R {register} *i_CTRL-R* Insert the contents of a register. Between typing CTRL-R and the second character, '"' will be displayed to indicate that you are expected to enter the name of a register. The text is inserted as if you typed it, but mappings and abbreviations are not used. If you have options like 'textwidth', 'formatoptions', or 'autoindent' set, this will influence what will be inserted. This is different from what happens with the "p" command and pasting with the mouse. Special registers: '"' the unnamed register, containing the text of the last delete or yank '%' the current file name '#' the alternate file name '*' the clipboard contents (X11: primary selection) '+' the clipboard contents '/' the last search pattern ':' the last command-line '.' the last inserted text *i_CTRL-R_-* '-' the last small (less than a line) delete register. This is repeatable using |.| since it remembers the register to put instead of the literal text to insert. *i_CTRL-R_=* '=' the expression register: you are prompted to enter an expression (see |expression|) Note that 0x80 (128 decimal) is used for special keys. E.g., you can use this to move the cursor up: CTRL-R ="\" Use CTRL-R CTRL-R to insert text literally. When the result is a |List| the items are used as lines. They can have line breaks inside too. When the result is a Float it's automatically converted to a String. When append() or setline() is invoked the undo sequence will be broken. See |registers| about registers. CTRL-R CTRL-R {register} *i_CTRL-R_CTRL-R* Insert the contents of a register. Works like using a single CTRL-R, but the text is inserted literally, not as if typed. This differs when the register contains characters like . Example, where register a contains "ab^Hc": > CTRL-R a results in "ac". CTRL-R CTRL-R a results in "ab^Hc". < Options 'textwidth', 'formatoptions', etc. still apply. If you also want to avoid these, use CTRL-R CTRL-O, see below. The '.' register (last inserted text) is still inserted as typed. After this command, the '.' register contains the text from the register as if it was inserted by typing it. CTRL-R CTRL-O {register} *i_CTRL-R_CTRL-O* Insert the contents of a register literally and don't auto-indent. Does the same as pasting with the mouse ||. When the register is linewise this will insert the text above the current line, like with `P`. The '.' register (last inserted text) is still inserted as typed. After this command, the '.' register contains the command typed and not the text. I.e., the literals "^R^O" and not the text from the register. Does not replace characters in |Replace-mode|! CTRL-R CTRL-P {register} *i_CTRL-R_CTRL-P* Insert the contents of a register literally and fix the indent, like |[|. The '.' register (last inserted text) is still inserted as typed. After this command, the '.' register contains the command typed and not the text. I.e., the literals "^R^P" and not the text from the register. Does not replace characters in |Replace-mode|! *i_CTRL-T* CTRL-T Insert one shiftwidth of indent at the start of the current line. The indent is always rounded to a 'shiftwidth' (this is vi compatible). *i_CTRL-D* CTRL-D Delete one shiftwidth of indent at the start of the current line. The indent is always rounded to a 'shiftwidth' (this is vi compatible). *i_0_CTRL-D* 0 CTRL-D Delete all indent in the current line. *i_^_CTRL-D* ^ CTRL-D Delete all indent in the current line. The indent is restored in the next line. This is useful when inserting a label. *i_CTRL-V* CTRL-V Insert next non-digit literally. For special keys, the terminal code is inserted. It's also possible to enter the decimal, octal or hexadecimal value of a character |i_CTRL-V_digit|. The characters typed right after CTRL-V are not considered for mapping. Note: When CTRL-V is mapped (e.g., to paste text) you can often use CTRL-Q instead |i_CTRL-Q|. When |modifyOtherKeys| is enabled then special Escape sequence is converted back to what it was without |modifyOtherKeys|, unless the Shift key is also pressed. *i_CTRL-Q* CTRL-Q Same as CTRL-V. Note: Some terminal connections may eat CTRL-Q, it doesn't work then. It does work in the GUI. CTRL-SHIFT-V *i_CTRL-SHIFT-V* *i_CTRL-SHIFT-Q* CTRL-SHIFT-Q Works just like CTRL-V, unless |modifyOtherKeys| is active, then it inserts the Escape sequence for a key with modifiers. CTRL-X Enter CTRL-X mode. This is a sub-mode where commands can be given to complete words or scroll the window. See |i_CTRL-X| and |ins-completion|. *i_CTRL-E* CTRL-E Insert the character which is below the cursor. *i_CTRL-Y* CTRL-Y Insert the character which is above the cursor. Note that for CTRL-E and CTRL-Y 'textwidth' is not used, to be able to copy characters from a long line. *i_CTRL-_* CTRL-_ Switch between languages, as follows: - When in a rightleft window, revins and nohkmap are toggled, since English will likely be inserted in this case. - When in a norightleft window, revins and hkmap are toggled, since Hebrew will likely be inserted in this case. CTRL-_ moves the cursor to the end of the typed text. This command is only available when the 'allowrevins' option is set. Please refer to |rileft.txt| for more information about right-to-left mode. Only if compiled with the |+rightleft| feature. *i_CTRL-^* CTRL-^ Toggle the use of typing language characters. When language |:lmap| mappings are defined: - If 'iminsert' is 1 (langmap mappings used) it becomes 0 (no langmap mappings used). - If 'iminsert' has another value it becomes 1, thus langmap mappings are enabled. When no language mappings are defined: - If 'iminsert' is 2 (Input Method used) it becomes 0 (no Input Method used). - If 'iminsert' has another value it becomes 2, thus the Input Method is enabled. When set to 1, the value of the "b:keymap_name" variable, the 'keymap' option or "" appears in the status line. The language mappings are normally used to type characters that are different from what the keyboard produces. The 'keymap' option can be used to install a whole number of them. *i_CTRL-]* CTRL-] Trigger abbreviation, without inserting a character. *i_* Toggle between Insert and Replace mode. ----------------------------------------------------------------------- *i_backspacing* The effect of the , CTRL-W, and CTRL-U depend on the 'backspace' option (unless 'revins' is set). This is a comma-separated list of items: item action ~ indent allow backspacing over autoindent eol allow backspacing over end-of-line (join lines) start allow backspacing over the start position of insert; CTRL-W and CTRL-U stop once at the start position When 'backspace' is empty, Vi compatible backspacing is used. You cannot backspace over autoindent, before column 1 or before where insert started. For backwards compatibility the values "0", "1", "2" and "3" are also allowed, see |'backspace'|. If the 'backspace' option does contain "eol" and the cursor is in column 1 when one of the three keys is used, the current line is joined with the previous line. This effectively deletes the in front of the cursor. *i_CTRL-V_digit* With CTRL-V the decimal, octal or hexadecimal value of a character can be entered directly. This way you can enter any character, except a line break (, value 10). There are five ways to enter the character value: first char mode max nr of chars max value ~ (none) decimal 3 255 o or O octal 3 377 (255) x or X hexadecimal 2 ff (255) u hexadecimal 4 ffff (65535) U hexadecimal 8 7fffffff (2147483647) Normally you would type the maximum number of characters. Thus to enter a space (value 32) you would type 032. You can omit the leading zero, in which case the character typed after the number must be a non-digit. This happens for the other modes as well: As soon as you type a character that is invalid for the mode, the value before it will be used and the "invalid" character is dealt with in the normal way. If you enter a value of 10, it will end up in the file as a 0. The 10 is a , which is used internally to represent the character. When writing the buffer to a file, the character is translated into . The character is written at the end of each line. Thus if you want to insert a character in a file you will have to make a line break. Also see 'fileformat'. *i_CTRL-X* *insert_expand* CTRL-X enters a sub-mode where several commands can be used. Most of these commands do keyword completion; see |ins-completion|. Two commands can be used to scroll the window up or down, without exiting insert mode: *i_CTRL-X_CTRL-E* CTRL-X CTRL-E scroll window one line up. When doing completion look here: |complete_CTRL-E| *i_CTRL-X_CTRL-Y* CTRL-X CTRL-Y scroll window one line down. When doing completion look here: |complete_CTRL-Y| After CTRL-X is pressed, each CTRL-E (CTRL-Y) scrolls the window up (down) by one line unless that would cause the cursor to move from its current position in the file. As soon as another key is pressed, CTRL-X mode is exited and that key is interpreted as in Insert mode. ============================================================================== 2. Special special keys *ins-special-special* The following keys are special. They stop the current insert, do something, and then restart insertion. This means you can do something without getting out of Insert mode. This is very handy if you prefer to use the Insert mode all the time, just like editors that don't have a separate Normal mode. You may also want to set the 'backspace' option to "indent,eol,start" and set the 'insertmode' option. You can use CTRL-O if you want to map a function key to a command. The changes (inserted or deleted characters) before and after these keys can be undone separately. Only the last change can be redone and always behaves like an "i" command. char action ~ ----------------------------------------------------------------------- cursor one line up *i_* cursor one line down *i_* CTRL-G cursor one line up, insert start column *i_CTRL-G_* CTRL-G k cursor one line up, insert start column *i_CTRL-G_k* CTRL-G CTRL-K cursor one line up, insert start column *i_CTRL-G_CTRL-K* CTRL-G cursor one line down, insert start column *i_CTRL-G_* CTRL-G j cursor one line down, insert start column *i_CTRL-G_j* CTRL-G CTRL-J cursor one line down, insert start column *i_CTRL-G_CTRL-J* cursor one character left *i_* cursor one character right *i_* cursor one word back (like "b" command) *i_* cursor one word back (like "b" command) *i_* cursor one word forward (like "w" command) *i_* cursor one word forward (like "w" command) *i_* cursor to first char in the line *i_* cursor to after last char in the line *i_* cursor to first char in the file *i_* cursor to after last char in the file *i_* cursor to position of mouse click *i_* move window one page up *i_* move window one page up *i_* move window one page down *i_* move window one page down *i_* move window three lines down *i_* move window one page down *i_* move window three lines up *i_* move window one page up *i_* move window six columns left *i_* move window one page left *i_* move window six columns right *i_* move window one page right *i_* CTRL-O execute one command, return to Insert mode *i_CTRL-O* CTRL-\ CTRL-O like CTRL-O but don't move the cursor *i_CTRL-\_CTRL-O* CTRL-L when 'insertmode' is set: go to Normal mode *i_CTRL-L* CTRL-G u close undo sequence, start new change *i_CTRL-G_u* CTRL-G U don't start a new undo block with the next *i_CTRL-G_U* left/right cursor movement, if the cursor stays within the same line ----------------------------------------------------------------------- Note: If the cursor keys take you out of Insert mode, check the 'noesckeys' option. The CTRL-O command sometimes has a side effect: If the cursor was beyond the end of the line, it will be put on the last character in the line. In mappings it's often better to use (first put an "x" in the text, will then always put the cursor on it). Or use CTRL-\ CTRL-O, but then beware of the cursor possibly being beyond the end of the line. Note that the command following CTRL-\ CTRL-O can still move the cursor, it is not restored to its original position. The CTRL-O command takes you to Normal mode. If you then use a command enter Insert mode again it normally doesn't nest. Thus when typing "aa" and then takes you back to Normal mode, you do not need to type twice. An exception is when not typing the command, e.g. when executing a mapping or sourcing a script. This makes mappings work that briefly switch to Insert mode. The shifted cursor keys are not available on all terminals. Another side effect is that a count specified before the "i" or "a" command is ignored. That is because repeating the effect of the command after CTRL-O is too complicated. An example for using CTRL-G u: > :inoremap u This redefines the backspace key to start a new undo sequence. You can now undo the effect of the backspace key, without changing what you typed before that, with CTRL-O u. Another example: > :inoremap u This starts a new undo block at each line break. It also expands abbreviations before this. An example for using CTRL-G U: > inoremap U inoremap U inoremap col('.') == match(getline('.'), '\S') + 1 ? \ repeat('U', col('.') - 1) : \ (col('.') < match(getline('.'), '\S') ? \ repeat('U', match(getline('.'), '\S') + 0) : \ repeat('U', col('.') - 1 - match(getline('.'), '\S'))) inoremap repeat('U', col('$') - col('.')) inoremap ( ()U This makes it possible to use the cursor keys in Insert mode, without starting a new undo block and therefore using |.| (redo) will work as expected. Also entering a text like (with the "(" mapping from above): Lorem ipsum (dolor will be repeatable by using |.| to the expected Lorem ipsum (dolor) Using CTRL-O splits undo: the text typed before and after it is undone separately. If you want to avoid this (e.g., in a mapping) you might be able to use CTRL-R = |i_CTRL-R|. E.g., to call a function: > :imap =MyFunc() When the 'whichwrap' option is set appropriately, the and keys on the first/last character in the line make the cursor wrap to the previous/next line. The CTRL-G j and CTRL-G k commands can be used to insert text in front of a column. Example: > int i; int j; Position the cursor on the first "int", type "istatic j ". The result is: > static int i; int j; When inserting the same text in front of the column in every line, use the Visual blockwise command "I" |v_b_I|. ============================================================================== 3. 'textwidth' and 'wrapmargin' options *ins-textwidth* The 'textwidth' option can be used to automatically break a line before it gets too long. Set the 'textwidth' option to the desired maximum line length. If you then type more characters (not spaces or tabs), the last word will be put on a new line (unless it is the only word on the line). If you set 'textwidth' to 0, this feature is disabled. The 'wrapmargin' option does almost the same. The difference is that 'textwidth' has a fixed width while 'wrapmargin' depends on the width of the screen. When using 'wrapmargin' this is equal to using 'textwidth' with a value equal to (columns - 'wrapmargin'), where columns is the width of the screen. When 'textwidth' and 'wrapmargin' are both set, 'textwidth' is used. If you don't really want to break the line, but view the line wrapped at a convenient place, see the 'linebreak' option. The line is only broken automatically when using Insert mode, or when appending to a line. When in replace mode and the line length is not changed, the line will not be broken. Long lines are broken if you enter a non-white character after the margin. The situations where a line will be broken can be restricted by adding characters to the 'formatoptions' option: "l" Only break a line if it was not longer than 'textwidth' when the insert started. "v" Only break at a white character that has been entered during the current insert command. This is mostly Vi-compatible. "lv" Only break if the line was not longer than 'textwidth' when the insert started and only at a white character that has been entered during the current insert command. Only differs from "l" when entering non-white characters while crossing the 'textwidth' boundary. Normally an internal function will be used to decide where to break the line. If you want to do it in a different way set the 'formatexpr' option to an expression that will take care of the line break. If you want to format a block of text, you can use the "gq" operator. Type "gq" and a movement command to move the cursor to the end of the block. In many cases, the command "gq}" will do what you want (format until the end of paragraph). Alternatively, you can use "gqap", which will format the whole paragraph, no matter where the cursor currently is. Or you can use Visual mode: hit "v", move to the end of the block, and type "gq". See also |gq|. ============================================================================== 4. 'expandtab', 'smarttab' and 'softtabstop' options *ins-expandtab* If the 'expandtab' option is on, spaces will be used to fill the amount of whitespace of the tab. If you want to enter a real , type CTRL-V first (use CTRL-Q when CTRL-V is mapped |i_CTRL-Q|). The 'expandtab' option is off by default. Note that in Replace mode, a single character is replaced with several spaces. The result of this is that the number of characters in the line increases. Backspacing will delete one space at a time. The original character will be put back for only one space that you backspace over (the last one). *ins-smarttab* When the 'smarttab' option is on, a inserts 'shiftwidth' positions at the beginning of a line and 'tabstop' positions in other places. This means that often spaces instead of a character are inserted. When 'smarttab' is off, a always inserts 'tabstop' positions, and 'shiftwidth' is only used for ">>" and the like. *ins-softtabstop* When the 'softtabstop' option is non-zero, a inserts 'softtabstop' positions, and a used to delete white space, will delete 'softtabstop' positions. This feels like 'tabstop' was set to 'softtabstop', but a real character still takes 'tabstop' positions, so your file will still look correct when used by other applications. If 'softtabstop' is non-zero, a will try to delete as much white space to move to the previous 'softtabstop' position, except when the previously inserted character is a space, then it will only delete the character before the cursor. Otherwise you cannot always delete a single character before the cursor. You will have to delete 'softtabstop' characters first, and then type extra spaces to get where you want to be. ============================================================================== 5. Replace mode *Replace* *Replace-mode* *mode-replace* Enter Replace mode with the "R" command in normal mode. In Replace mode, one character in the line is deleted for every character you type. If there is no character to delete (at the end of the line), the typed character is appended (as in Insert mode). Thus the number of characters in a line stays the same until you get to the end of the line. If a is typed, a line break is inserted and no character is deleted. Be careful with characters. If you type a normal printing character in its place, the number of characters is still the same, but the number of columns will become smaller. If you delete characters in Replace mode (with , CTRL-W, or CTRL-U), what happens is that you delete the changes. The characters that were replaced are restored. If you had typed past the existing text, the characters you added are deleted. This is effectively a character-at-a-time undo. If the 'expandtab' option is on, a will replace one character with several spaces. The result of this is that the number of characters in the line increases. Backspacing will delete one space at a time. The original character will be put back for only one space that you backspace over (the last one). ============================================================================== 6. Virtual Replace mode *vreplace-mode* *Virtual-Replace-mode* Enter Virtual Replace mode with the "gR" command in normal mode. {not available when compiled without the |+vreplace| feature} Virtual Replace mode is similar to Replace mode, but instead of replacing actual characters in the file, you are replacing screen real estate, so that characters further on in the file never appear to move. So if you type a it may replace several normal characters, and if you type a letter on top of a it may not replace anything at all, since the will still line up to the same place as before. Typing a still doesn't cause characters later in the file to appear to move. The rest of the current line will be replaced by the (that is, they are deleted), and replacing continues on the next line. A new line is NOT inserted unless you go past the end of the file. Interesting effects are seen when using CTRL-T and CTRL-D. The characters before the cursor are shifted sideways as normal, but characters later in the line still remain still. CTRL-T will hide some of the old line under the shifted characters, but CTRL-D will reveal them again. As with Replace mode, using etc will bring back the characters that were replaced. This still works in conjunction with 'smartindent', CTRL-T and CTRL-D, 'expandtab', 'smarttab', 'softtabstop', etc. In 'list' mode, Virtual Replace mode acts as if it was not in 'list' mode, unless "L" is in 'cpoptions'. Note that the only situations for which characters beyond the cursor should appear to move are in List mode |'list'|, and occasionally when 'wrap' is set (and the line changes length to become shorter or wider than the width of the screen). In other cases spaces may be inserted to avoid following characters to move. This mode is very useful for editing separated columns in tables, for entering new data while keeping all the columns aligned. ============================================================================== 7. Insert mode completion *ins-completion* In Insert and Replace mode, there are several commands to complete part of a keyword or line that has been typed. This is useful if you are using complicated keywords (e.g., function names with capitals and underscores). Completion can be done for: 1. Whole lines |i_CTRL-X_CTRL-L| 2. keywords in the current file |i_CTRL-X_CTRL-N| 3. keywords in 'dictionary' |i_CTRL-X_CTRL-K| 4. keywords in 'thesaurus', thesaurus-style |i_CTRL-X_CTRL-T| 5. keywords in the current and included files |i_CTRL-X_CTRL-I| 6. tags |i_CTRL-X_CTRL-]| 7. file names |i_CTRL-X_CTRL-F| 8. definitions or macros |i_CTRL-X_CTRL-D| 9. Vim command-line |i_CTRL-X_CTRL-V| 10. User defined completion |i_CTRL-X_CTRL-U| 11. omni completion |i_CTRL-X_CTRL-O| 12. Spelling suggestions |i_CTRL-X_s| 13. keywords in 'complete' |i_CTRL-N| |i_CTRL-P| Additionally, |i_CTRL-X_CTRL-Z| stops completion without changing the text. All these, except CTRL-N and CTRL-P, are done in CTRL-X mode. This is a sub-mode of Insert and Replace modes. You enter CTRL-X mode by typing CTRL-X and one of the CTRL-X commands. You exit CTRL-X mode by typing a key that is not a valid CTRL-X mode command. Valid keys are the CTRL-X command itself, CTRL-N (next), and CTRL-P (previous). To get the current completion information, |complete_info()| can be used. Also see the 'infercase' option if you want to adjust the case of the match. *complete_CTRL-E* When completion is active you can use CTRL-E to stop it and go back to the originally typed text. The CTRL-E will not be inserted. *complete_CTRL-Y* When the popup menu is displayed you can use CTRL-Y to stop completion and accept the currently selected entry. The CTRL-Y is not inserted. Typing a space, Enter, or some other unprintable character will leave completion mode and insert that typed character. When the popup menu is displayed there are a few more special keys, see |popupmenu-keys|. Note: The keys that are valid in CTRL-X mode are not mapped. This allows for `:map ` to work (assuming "<" is not in 'cpo'). The key that ends CTRL-X mode (any key that is not a valid CTRL-X mode command) is mapped. Also, when doing completion with 'complete' mappings apply as usual. *E565* Note: While completion is active Insert mode can't be used recursively and buffer text cannot be changed. Mappings that somehow invoke ":normal i.." will generate an E565 error. The following mappings are suggested to make typing the completion commands a bit easier (although they will hide other commands; this requires "<" is not in 'cpo'): > :inoremap :inoremap :inoremap :inoremap As a special case, typing CTRL-R to perform register insertion (see |i_CTRL-R|) will not exit CTRL-X mode. This is primarily to allow the use of the '=' register to call some function to determine the next operation. If the contents of the register (or result of the '=' register evaluation) are not valid CTRL-X mode keys, then CTRL-X mode will be exited as if those keys had been typed. For example, the following will map to either actually insert a if the current line is currently only whitespace, or start/continue a CTRL-N completion operation: > function! CleverTab() if strpart( getline('.'), 0, col('.')-1 ) =~ '^\s*$' return "\" else return "\" endif endfunction inoremap =CleverTab() Completing whole lines *compl-whole-line* *i_CTRL-X_CTRL-L* CTRL-X CTRL-L Search backwards for a line that starts with the same characters as those in the current line before the cursor. Indent is ignored. The matching line is inserted in front of the cursor. The 'complete' option is used to decide which buffers are searched for a match. Both loaded and unloaded buffers are used. CTRL-L or CTRL-P Search backwards for next matching line. This line replaces the previous matching line. CTRL-N Search forward for next matching line. This line replaces the previous matching line. CTRL-X CTRL-L After expanding a line you can additionally get the line next to it by typing CTRL-X CTRL-L again, unless a double CTRL-X is used. Only works for loaded buffers. Completing keywords in current file *compl-current* *i_CTRL-X_CTRL-P* *i_CTRL-X_CTRL-N* CTRL-X CTRL-N Search forwards for words that start with the keyword in front of the cursor. The found keyword is inserted in front of the cursor. CTRL-X CTRL-P Search backwards for words that start with the keyword in front of the cursor. The found keyword is inserted in front of the cursor. CTRL-N Search forward for next matching keyword. This keyword replaces the previous matching keyword. CTRL-P Search backwards for next matching keyword. This keyword replaces the previous matching keyword. CTRL-X CTRL-N or CTRL-X CTRL-P Further use of CTRL-X CTRL-N or CTRL-X CTRL-P will copy the words following the previous expansion in other contexts unless a double CTRL-X is used. If there is a keyword in front of the cursor (a name made out of alphabetic characters and characters in 'iskeyword'), it is used as the search pattern, with "\<" prepended (meaning: start of a word). Otherwise "\<\k\k" is used as search pattern (start of any keyword of at least two characters). In Replace mode, the number of characters that are replaced depends on the length of the matched string. This works like typing the characters of the matched string in Replace mode. If there is not a valid keyword character before the cursor, any keyword of at least two characters is matched. e.g., to get: printf("(%g, %g, %g)", vector[0], vector[1], vector[2]); just type: printf("(%g, %g, %g)", vector[0], ^P[1], ^P[2]); The search wraps around the end of the file, the value of 'wrapscan' is not used here. Multiple repeats of the same completion are skipped; thus a different match will be inserted at each CTRL-N and CTRL-P (unless there is only one matching keyword). Single character matches are never included, as they usually just get in the way of what you were really after. e.g., to get: printf("name = %s\n", name); just type: printf("name = %s\n", n^P); or even: printf("name = %s\n", ^P); The 'n' in '\n' is skipped. After expanding a word, you can use CTRL-X CTRL-P or CTRL-X CTRL-N to get the word following the expansion in other contexts. These sequences search for the text just expanded and further expand by getting an extra word. This is useful if you need to repeat a sequence of complicated words. Although CTRL-P and CTRL-N look just for strings of at least two characters, CTRL-X CTRL-P and CTRL-X CTRL-N can be used to expand words of just one character. e.g., to get: México you can type: M^N^P^X^P^X^P CTRL-N starts the expansion and then CTRL-P takes back the single character "M", the next two CTRL-X CTRL-P's get the words "é" and ";xico". If the previous expansion was split, because it got longer than 'textwidth', then just the text in the current line will be used. If the match found is at the end of a line, then the first word in the next line will be inserted and the message "Word from other line" displayed, if this word is accepted the next CTRL-X CTRL-P or CTRL-X CTRL-N will search for those lines starting with this word. Completing keywords in 'dictionary' *compl-dictionary* *i_CTRL-X_CTRL-K* CTRL-X CTRL-K Search the files given with the 'dictionary' option for words that start with the keyword in front of the cursor. This is like CTRL-N, but only the dictionary files are searched, not the current file. The found keyword is inserted in front of the cursor. This could potentially be pretty slow, since all matches are found before the first match is used. By default, the 'dictionary' option is empty. For suggestions where to find a list of words, see the 'dictionary' option. 'ignorecase', 'smartcase' and 'infercase' apply. CTRL-K or CTRL-N Search forward for next matching keyword. This keyword replaces the previous matching keyword. CTRL-P Search backwards for next matching keyword. This keyword replaces the previous matching keyword. Completing words in 'thesaurus' *compl-thesaurus* *i_CTRL-X_CTRL-T* CTRL-X CTRL-T Works as CTRL-X CTRL-K, but in a special way. It uses the 'thesaurus' option instead of 'dictionary'. If a match is found in the thesaurus file, all the remaining words on the same line are included as matches, even though they don't complete the word. Thus a word can be completely replaced. CTRL-T or CTRL-N Search forward for next matching keyword. This keyword replaces the previous matching keyword. CTRL-P Search backwards for next matching keyword. This keyword replaces the previous matching keyword. In the file used by the 'thesaurus' option each line in the file should contain words with similar meaning, separated by non-keyword characters (white space is preferred). Maximum line length is 510 bytes. For an example, imagine the 'thesaurus' file has a line like this: > angry furious mad enraged Placing the cursor after the letters "ang" and typing CTRL-X CTRL-T would complete the word "angry"; subsequent presses would change the word to "furious", "mad" etc. Other uses include translation between two languages, or grouping API functions by keyword. An English word list was added to this github issue: https://github.com/vim/vim/issues/629#issuecomment-443293282 Unpack thesaurus_pkg.zip, put the thesaurus.txt file somewhere, e.g. ~/.vim/thesaurus/english.txt, and the 'thesaurus' option to this file name. Completing keywords with 'thesaurusfunc' *compl-thesaurusfunc* If the 'thesaurusfunc' option is set, then the user specified function is invoked to get the list of completion matches and the 'thesaurus' option is not used. See |complete-functions| for an explanation of how the function is invoked and what it should return. Here is an example that uses the "aiksaurus" command (provided by Magnus Groß): > func Thesaur(findstart, base) if a:findstart return searchpos('\<', 'bnW', line('.'))[1] - 1 endif let res = [] let h = '' for l in systemlist('aiksaurus ' .. shellescape(a:base)) if l[:3] == '=== ' let h = '(' .. substitute(l[4:], ' =*$', ')', '') elseif l ==# 'Alphabetically similar known words are: ' let h = "\U0001f52e" elseif l[0] =~ '\a' || (h ==# "\U0001f52e" && l[0] ==# "\t") call extend(res, map(split(substitute(l, '^\t', '', ''), ', '), {_, val -> {'word': val, 'menu': h}})) endif endfor return res endfunc if exists('+thesaurusfunc') set thesaurusfunc=Thesaur endif Completing keywords in the current and included files *compl-keyword* The 'include' option is used to specify a line that contains an include file name. The 'path' option is used to search for include files. *i_CTRL-X_CTRL-I* CTRL-X CTRL-I Search for the first keyword in the current and included files that starts with the same characters as those before the cursor. The matched keyword is inserted in front of the cursor. CTRL-N Search forwards for next matching keyword. This keyword replaces the previous matching keyword. Note: CTRL-I is the same as , which is likely to be typed after a successful completion, therefore CTRL-I is not used for searching for the next match. CTRL-P Search backward for previous matching keyword. This keyword replaces the previous matching keyword. CTRL-X CTRL-I Further use of CTRL-X CTRL-I will copy the words following the previous expansion in other contexts unless a double CTRL-X is used. Completing tags *compl-tag* *i_CTRL-X_CTRL-]* CTRL-X CTRL-] Search for the first tag that starts with the same characters as before the cursor. The matching tag is inserted in front of the cursor. Alphabetic characters and characters in 'iskeyword' are used to decide which characters are included in the tag name (same as for a keyword). See also |CTRL-]|. The 'showfulltag' option can be used to add context from around the tag definition. CTRL-] or CTRL-N Search forwards for next matching tag. This tag replaces the previous matching tag. CTRL-P Search backward for previous matching tag. This tag replaces the previous matching tag. Completing file names *compl-filename* *i_CTRL-X_CTRL-F* CTRL-X CTRL-F Search for the first file name that starts with the same characters as before the cursor. The matching file name is inserted in front of the cursor. Alphabetic characters and characters in 'isfname' are used to decide which characters are included in the file name. Note: the 'path' option is not used here (yet). CTRL-F or CTRL-N Search forwards for next matching file name. This file name replaces the previous matching file name. CTRL-P Search backward for previous matching file name. This file name replaces the previous matching file name. Completing definitions or macros *compl-define* The 'define' option is used to specify a line that contains a definition. The 'include' option is used to specify a line that contains an include file name. The 'path' option is used to search for include files. *i_CTRL-X_CTRL-D* CTRL-X CTRL-D Search in the current and included files for the first definition (or macro) name that starts with the same characters as before the cursor. The found definition name is inserted in front of the cursor. CTRL-D or CTRL-N Search forwards for next matching macro name. This macro name replaces the previous matching macro name. CTRL-P Search backward for previous matching macro name. This macro name replaces the previous matching macro name. CTRL-X CTRL-D Further use of CTRL-X CTRL-D will copy the words following the previous expansion in other contexts unless a double CTRL-X is used. Completing Vim commands *compl-vim* Completion is context-sensitive. It works like on the Command-line. It completes an Ex command as well as its arguments. This is useful when writing a Vim script. *i_CTRL-X_CTRL-V* CTRL-X CTRL-V Guess what kind of item is in front of the cursor and find the first match for it. Note: When CTRL-V is mapped you can often use CTRL-Q instead of |i_CTRL-Q|. CTRL-V or CTRL-N Search forwards for next match. This match replaces the previous one. CTRL-P Search backwards for previous match. This match replaces the previous one. CTRL-X CTRL-V Further use of CTRL-X CTRL-V will do the same as CTRL-V. This allows mapping a key to do Vim command completion, for example: > :imap User defined completion *compl-function* Completion is done by a function that can be defined by the user with the 'completefunc' option. See below for how the function is called and an example |complete-functions|. *i_CTRL-X_CTRL-U* CTRL-X CTRL-U Guess what kind of item is in front of the cursor and find the first match for it. CTRL-U or CTRL-N Use the next match. This match replaces the previous one. CTRL-P Use the previous match. This match replaces the previous one. Omni completion *compl-omni* Completion is done by a function that can be defined by the user with the 'omnifunc' option. This is to be used for filetype-specific completion. See below for how the function is called and an example |complete-functions|. For remarks about specific filetypes see |compl-omni-filetypes|. More completion scripts will appear, check www.vim.org. Currently there is a first version for C++. *i_CTRL-X_CTRL-O* CTRL-X CTRL-O Guess what kind of item is in front of the cursor and find the first match for it. CTRL-O or CTRL-N Use the next match. This match replaces the previous one. CTRL-P Use the previous match. This match replaces the previous one. Spelling suggestions *compl-spelling* A word before or at the cursor is located and correctly spelled words are suggested to replace it. If there is a badly spelled word in the line, before or under the cursor, the cursor is moved to after it. Otherwise the word just before the cursor is used for suggestions, even though it isn't badly spelled. NOTE: CTRL-S suspends display in many Unix terminals. Use 's' instead. Type CTRL-Q to resume displaying. *i_CTRL-X_CTRL-S* *i_CTRL-X_s* CTRL-X CTRL-S or CTRL-X s Locate the word in front of the cursor and find the first spell suggestion for it. CTRL-S or CTRL-N Use the next suggestion. This replaces the previous one. Note that you can't use 's' here. CTRL-P Use the previous suggestion. This replaces the previous one. Completing keywords from different sources *compl-generic* *i_CTRL-N* CTRL-N Find next match for words that start with the keyword in front of the cursor, looking in places specified with the 'complete' option. The found keyword is inserted in front of the cursor. *i_CTRL-P* CTRL-P Find previous match for words that start with the keyword in front of the cursor, looking in places specified with the 'complete' option. The found keyword is inserted in front of the cursor. CTRL-N Search forward for next matching keyword. This keyword replaces the previous matching keyword. CTRL-P Search backwards for next matching keyword. This keyword replaces the previous matching keyword. CTRL-X CTRL-N or CTRL-X CTRL-P Further use of CTRL-X CTRL-N or CTRL-X CTRL-P will copy the words following the previous expansion in other contexts unless a double CTRL-X is used. Stop completion *compl-stop* *i_CTRL-X_CTRL-Z* CTRL-X CTRL-Z Stop completion without changing the text. FUNCTIONS FOR FINDING COMPLETIONS *complete-functions* This applies to 'completefunc', 'thesaurusfunc' and 'omnifunc'. The function is called in two different ways: - First the function is called to find the start of the text to be completed. - Later the function is called to actually find the matches. On the first invocation the arguments are: a:findstart 1 a:base empty The function must return the column where the completion starts. It must be a number between zero and the cursor column "col('.')". This involves looking at the characters just before the cursor and including those characters that could be part of the completed item. The text between this column and the cursor column will be replaced with the matches. If the returned value is larger than the cursor column, the cursor column is used. Negative return values: -2 To cancel silently and stay in completion mode. -3 To cancel silently and leave completion mode. Another negative value: completion starts at the cursor column On the second invocation the arguments are: a:findstart 0 a:base the text with which matches should match; the text that was located in the first call (can be empty) The function must return a List with the matching words. These matches usually include the "a:base" text. When there are no matches return an empty List. Note that the cursor may have moved since the first invocation, the text may have been changed. In order to return more information than the matching words, return a Dict that contains the List. The Dict can have these items: words The List of matching words (mandatory). refresh A string to control re-invocation of the function (optional). The only value currently recognized is "always", the effect is that the function is called whenever the leading text is changed. If you want to suppress the warning message for an empty result, return |v:none|. This is useful to implement asynchronous completion with |complete()|. Other items are ignored. For acting upon end of completion, see the |CompleteDonePre| and |CompleteDone| autocommand event. For example, the function can contain this: > let matches = ... list of words ... return {'words': matches, 'refresh': 'always'} < *complete-items* Each list item can either be a string or a Dictionary. When it is a string it is used as the completion. When it is a Dictionary it can contain these items: word the text that will be inserted, mandatory abbr abbreviation of "word"; when not empty it is used in the menu instead of "word" menu extra text for the popup menu, displayed after "word" or "abbr" info more information about the item, can be displayed in a preview or popup window kind single letter indicating the type of completion icase when non-zero case is to be ignored when comparing items to be equal; when omitted zero is used, thus items that only differ in case are added equal when non-zero, always treat this item to be equal when comparing. Which means, "equal=1" disables filtering of this item. dup when non-zero this match will be added even when an item with the same word is already present. empty when non-zero this match will be added even when it is an empty string user_data custom data which is associated with the item and available in |v:completed_item|; it can be any type; defaults to an empty string hl_group an additional highlight group whose attributes are combined with |hl-PmenuSel| and |hl-Pmenu| or |hl-PmenuMatchSel| and |hl-PmenuMatch| highlight attributes in the popup menu to apply cterm and gui properties (with higher priority) like strikethrough to the completion items kind_hlgroup an additional highlight group specifically for setting the highlight attributes of the completion kind. When this field is present, it will override the |hl-PmenuKind| highlight group, allowing for the customization of ctermfg and guifg properties for the completion kind All of these except "icase", "equal", "dup" and "empty" must be a string. If an item does not meet these requirements then an error message is given and further items in the list are not used. You can mix string and Dictionary items in the returned list. The "menu" item is used in the popup menu and may be truncated, thus it should be relatively short. The "info" item can be longer, it will be displayed in the preview window when "preview" appears in 'completeopt' or in a popup window when "popup" appears in 'completeopt'. In the preview window the "info" item will also remain displayed after the popup menu has been removed. This is useful for function arguments. Use a single space for "info" to remove existing text in the preview window. The size of the preview window is three lines, but 'previewheight' is used when it has a value of 1 or 2. *complete-popup* When "popup" is in 'completeopt' a popup window is used to display the "info". Then the 'completepopup' option specifies the properties of the popup. This is used when the info popup is created. The option is a comma-separated list of values: height maximum height of the popup width maximum width of the popup highlight highlight group of the popup (default is PmenuSel) align "item" (default) or "menu" border "on" (default) or "off" Example: > :set completepopup=height:10,width:60,highlight:InfoPopup When the "align" value is "item" then the popup is positioned close to the selected item. Changing the selection will also move the popup. When "align" is "menu" then the popup is aligned with the top of the menu if the menu is below the text, and the bottom of the menu otherwise. After the info popup is created it can be found with |popup_findinfo()| and properties can be changed with |popup_setoptions()|. *complete-popuphidden* If the information for the popup is obtained asynchronously, use "popuphidden" in 'completeopt'. The info popup will then be initially hidden and |popup_show()| must be called once it has been filled with the info. This can be done with a |CompleteChanged| autocommand, something like this: > set completeopt+=popuphidden au CompleteChanged * call UpdateCompleteInfo() func UpdateCompleteInfo() " Cancel any pending info fetch let item = v:event.completed_item " Start fetching info for the item then call ShowCompleteInfo(info) endfunc func ShowCompleteInfo(info) let id = popup_findinfo() if id call popup_settext(id, 'async info: ' .. a:info) call popup_show(id) endif endfunc < *complete-item-kind* The "kind" item uses a single letter to indicate the kind of completion. This may be used to show the completion differently (different color or icon). Currently these types can be used: v variable f function or method m member of a struct or class t typedef d #define or macro When searching for matches takes some time call |complete_add()| to add each match to the total list. These matches should then not appear in the returned list! Call |complete_check()| now and then to allow the user to press a key while still searching for matches. Stop searching when it returns non-zero. *E840* The function is allowed to move the cursor, it is restored afterwards. The function is not allowed to move to another window or delete text. An example that completes the names of the months: > fun! CompleteMonths(findstart, base) if a:findstart " locate the start of the word let line = getline('.') let start = col('.') - 1 while start > 0 && line[start - 1] =~ '\a' let start -= 1 endwhile return start else " find months matching with "a:base" let res = [] for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec") if m =~ '^' .. a:base call add(res, m) endif endfor return res endif endfun set completefunc=CompleteMonths < The same, but now pretending searching for matches is slow: > fun! CompleteMonths(findstart, base) if a:findstart " locate the start of the word let line = getline('.') let start = col('.') - 1 while start > 0 && line[start - 1] =~ '\a' let start -= 1 endwhile return start else " find months matching with "a:base" for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec") if m =~ '^' .. a:base call complete_add(m) endif sleep 300m " simulate searching for next match if complete_check() break endif endfor return [] endif endfun set completefunc=CompleteMonths < INSERT COMPLETION POPUP MENU *ins-completion-menu* *popupmenu-completion* Vim can display the matches in a simplistic popup menu. The menu is used when: - The 'completeopt' option contains "menu" or "menuone". - The terminal supports at least 8 colors. - There are at least two matches. One if "menuone" is used. The 'pumheight' option can be used to set a maximum height. The default is to use all space available. The 'pumwidth' option can be used to set a minimum width. The default is 15 characters. There are three states: 1. A complete match has been inserted, e.g., after using CTRL-N or CTRL-P. 2. A cursor key has been used to select another match. The match was not inserted then, only the entry in the popup menu is highlighted. 3. Only part of a match has been inserted and characters were typed or the backspace key was used. The list of matches was then adjusted for what is in front of the cursor. You normally start in the first state, with the first match being inserted. When "longest" is in 'completeopt' and there is more than one match you start in the third state. If you select another match, e.g., with CTRL-N or CTRL-P, you go to the first state. This doesn't change the list of matches. When you are back at the original text then you are in the third state. To get there right away you can use a mapping that uses CTRL-P right after starting the completion: > :imap < *popupmenu-keys* In the first state these keys have a special meaning: and CTRL-H Delete one character, find the matches for the word before the cursor. This reduces the list of matches, often to one entry, and switches to the second state. Any non-special character: Stop completion without changing the match and insert the typed character. In the second and third state these keys have a special meaning: and CTRL-H Delete one character, find the matches for the shorter word before the cursor. This may find more matches. CTRL-L Add one character from the current match, may reduce the number of matches. any printable, non-white character: Add this character and reduce the number of matches. In all three states these can be used: CTRL-Y Yes: Accept the currently selected match and stop completion. CTRL-E End completion, go back to what was there before selecting a match (what was typed or longest common string). Select a match several entries back, but don't insert it. Select a match several entries further, but don't insert it. Select the previous match, as if CTRL-P was used, but don't insert it. Select the next match, as if CTRL-N was used, but don't insert it. or Stop completion without changing the match and insert the typed character. The behavior of the key depends on the state you are in: first state: Use the text as it is and insert a line break. second state: Insert the currently selected match. third state: Use the text as it is and insert a line break. In other words: If you used the cursor keys to select another entry in the list of matches then the key inserts that match. If you typed something else then inserts a line break. The colors of the menu can be changed with these highlight groups: Pmenu normal item |hl-Pmenu| PmenuSel selected item |hl-PmenuSel| PmenuSbar scrollbar |hl-PmenuSbar| PmenuThumb thumb of the scrollbar |hl-PmenuThumb| There are no special mappings for when the popup menu is visible. However, you can use an Insert mode mapping that checks the |pumvisible()| function to do something different. Example: > :inoremap =pumvisible() ? "\C-N>" : "\Down>" You can use of in mapping to have the popup menu used when typing a character and some condition is met. For example, for typing a dot: > inoremap . MayComplete() func MayComplete() if (can complete) return ".\\" endif return '.' endfunc See |:map-| for more info. FILETYPE-SPECIFIC REMARKS FOR OMNI COMPLETION *compl-omni-filetypes* The file used for {filetype} should be autoload/{filetype}complete.vim in 'runtimepath'. Thus for "java" it is autoload/javacomplete.vim. C *ft-c-omni* Completion of C code requires a tags file. You should use Universal/ Exuberant ctags, because it adds extra information that is needed for completion. You can find it here: Universal Ctags: https://ctags.io Exuberant Ctags: http://ctags.sourceforge.net Universal Ctags is preferred, Exuberant Ctags is no longer being developed. For Exuberant ctags, version 5.6 or later is recommended. For version 5.5.4 you should add a patch that adds the "typename:" field: ftp://ftp.vim.org/pub/vim/unstable/patches/ctags-5.5.4.patch A compiled .exe for MS-Windows can be found at: http://ctags.sourceforge.net/ https://github.com/universal-ctags/ctags-win32 If you want to complete system functions you can do something like this. Use ctags to generate a tags file for all the system header files: > % ctags -R -f ~/.vim/systags /usr/include /usr/local/include In your vimrc file add this tags file to the 'tags' option: > set tags+=~/.vim/systags When using CTRL-X CTRL-O after a name without any "." or "->" it is completed from the tags file directly. This works for any identifier, also function names. If you want to complete a local variable name, which does not appear in the tags file, use CTRL-P instead. When using CTRL-X CTRL-O after something that has "." or "->" Vim will attempt to recognize the type of the variable and figure out what members it has. This means only members valid for the variable will be listed. When a member name already was complete, CTRL-X CTRL-O will add a "." or "->" for composite types. Vim doesn't include a C compiler, only the most obviously formatted declarations are recognized. Preprocessor stuff may cause confusion. When the same structure name appears in multiple places all possible members are included. CSS *ft-css-omni* Complete properties and their appropriate values according to CSS 2.1 specification. HTML *ft-html-omni* XHTML *ft-xhtml-omni* CTRL-X CTRL-O provides completion of various elements of (X)HTML files. It is designed to support writing of XHTML 1.0 Strict files but will also work for other versions of HTML. Features: - after "<" complete tag name depending on context (no div suggestion inside of an a tag); '/>' indicates empty tags - inside of tag complete proper attributes (no width attribute for an a tag); show also type of attribute; '*' indicates required attributes - when attribute has limited number of possible values help to complete them - complete names of entities - complete values of "class" and "id" attributes with data obtained from