Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
vim_faq.txt  Frequently Asked QuestionsLast updated on: 11 October 2025  VIMFAQ by: Christian Brabandt <cb@256bit.org>Frequently Asked Questionsvim-faqVim-FAQThis VimFAQis created from the questions and answers posted to thevim@vim.org user mailinglist and the comp.editors newsgroup. There areseveral ways to solvea problem in Vim. ThisFAQ gives one of those severalpossibilities. You can explore the other ways using the information andlinks given in this FAQ. The credit for the answers in thisFAQ goes toPeppe, Benji, Charles Campbell and numerous others. An online version ofthisFAQis availableathttps://vimhelp.org/vim_faq.txt.htmlfaq-indexINDEXfaq-general-informationSECTION 1 - GENERAL INFORMATIONfaq-1.1   Whatis Vim?faq-1.2   Who wrote Vim?faq-1.3   Is Vim compatible with Vi?faq-1.4   What are some of the improvements of Vim over Vi?faq-1.5   Is Vim free?faq-resourcesSECTION 2 - RESOURCESfaq-2.1   Where canI learn more about Vim?faq-2.2   Is therea mailinglist available?faq-2.3   Is there an archive available for the Vim mailing lists?faq-2.4   Where canI get the Vim user manual in HTML/PDF/PS format?faq-2.5I havea "xyz" (some) problem with Vim. HowdoI determine ifitisa problem with my setup or with Vim?faq-2.6   Where canI report bugs?faq-2.7   Where can theFAQ be found?faq-2.8   What ifI don't find an answer in this FAQ?faq-2.9I havea patch for implementinga Vim feature. WheredoI send the  patch?faq-2.10I havea Vim tip or developeda new Vim  syntax/indent/filetype/compilerplugin or developeda newscript  ora colorscheme. Is therea public website whereI can upload  this?faq-availabilitySECTION 3 - AVAILABILITYfaq-3.1   Whatis the latest version of Vim?faq-3.2   Where canI find the latest version of Vim?faq-3.3   What platforms doesit run on?faq-3.4   Where canIdownload the latest version of the Vim runtime files?faq-helpSECTION 4 - HELPfaq-4.1   HowdoI use thehelp files?faq-4.2   HowdoI search fora keyword in the Vimhelp files?faq-4.3I am getting an error message E123, what didIdo wrong?faq-4.4   Where canI read about thevarious modes in Vim?faq-4.5   HowdoI generate the Vimhelptags file after addinga new Vimhelp file?faq-4.6   CanI use compressed versions of thehelp files?faq-editing-a-fileSECTION 5 - EDITING A FILEfaq-5.1   HowdoI loada file in Vim for editing?faq-5.2   HowdoI save the current file in another name (save as) and edita new file?faq-5.3   HowdoI change the current directory to the directory of the  current file?faq-5.4   HowdoI writea file without the line feed (EOL)at theend of  the file?faq-5.5   HowdoI configure Vim to opena fileat the last edited location?faq-5.6   When editinga file in Vim, whichis being changed by an external  application, Vim opensa warningwindow (like the confirm dialog)  each timea changeis detected. HowdoI disable this warning?faq-5.7   HowdoI edita file whose nameis under the cursor?faq-5.8   HowdoI reload/re-edit the current file?faq-5.9   HowdoI autosavea file periodically?faq-5.10  HowdoI opena file in read-only mode?faq-5.11  HowdoI opena file for editing without saving the modifications  to the current file?faq-5.12  HowdoI reduce the loading time for very large files in Vim?faq-editing-multiple-filesSECTION 6 - EDITING MULTIPLE FILESfaq-6.1   HowdoI open multiple filesat once from within Vim?faq-6.2   HowdoI switch between multiple files/buffers in Vim?faq-6.3   HowdoI open several files in Vim, with each file ina separate  window/tabpage?faq-6.4   HowdoI configure Vim toautoload several filesat once similar  to "work-sets" or "projects"?faq-6.5   Isit possible to open multiple top levelwindows ina single  instance of Vim similar to Nedit or emacs?faq-6.6   HowdoI browse/explore directories from within Vim?faq-6.7   HowdoI edit files overanetwork using ftp/scp/rcp/http?faq-backupSECTION 7 - BACKUPfaq-7.1   WhenI edit and save files, Vim createsa file with the same nameas the original file anda "~" characterat the end. HowdoI stop  Vim from creating this file (or) HowdoI disable the Vimbackup  file feature?faq-7.2   WhenI edit and save files, Vim createsa file with the same nameas the original file anda ".un~" extensionat the end. HowdoI  stop Vim from creating this file (or) HowdoI disable the Vim  undofile feature.faq-7.3   HowdoI configure Vim to store all thebackup files ina  particular directory?faq-7.4   WhenI savea file with Vim, the file permissions are changed.  HowdoI configure Vim to savea file withoutchanging the file  permissions?faq-buffersSECTION 8 - BUFFERSfaq-8.1I have made some modifications toa buffer. HowdoI edit another  buffer without saving the modified buffer and also without losing  the modifications?faq-8.2   HowdoI configure Vim to auto-savea modified buffer when  switching to another buffer?faq-8.3   HowdoI replace the buffer in the currentwindow witha blank  buffer?faq-8.4   Is therea keyboard shortcut to loada buffer by the buffer  number?faq-8.5   HowdoI open all the currentbuffers in separate windows?faq-8.6   HowdoI close (delete)a buffer withoutexiting Vim?faq-8.7   WhenI use the command:%bd to delete all the buffers, not all  thebuffers are deleted. Why?faq-8.8   HowdoI display the buffer number of the current buffer/file?faq-8.9   HowdoI deletea buffer without closing thewindow in which the  bufferis displayed?faq-8.10  HowdoI map the<Tab> key to cycle through and open all the  buffers?faq-windowsSECTION 9 - WINDOWSfaq-9.1   Whatis the difference betweena Vimwindow anda buffer?faq-9.2   HowdoI increase the width ofa Vim window?faq-9.3   HowdoI zoom into or out ofa window?faq-9.4   HowdoI execute anex command on all the openbuffers or openwindows or all the files in the argument list?faq-motionSECTION 10 - MOTIONfaq-10.1  HowdoI jump to the beginning (first line) orend (last line) ofa file?faq-10.2  Ininsert mode, whenI press the<Esc> key togo to command mode,  the cursor moves one character to the left (except when the  cursoris on the first character of the line). Isit possible to  change this behavior to keep the cursorat the same column?faq-10.3  HowdoI configure Vim to maintain the horizontal cursor position  whenscrolling with the <Page Up>, <Page Down>, etc keys?faq-10.4  Some lines ina file are more than the screen width and they are  all wrapped. WhenI use the j,k keys to move from one line to  the next, the cursoris moved to the next line in the file  instead of the next line on the screen. HowdoI move from one  screen line to the next?faq-10.5  Whatis the definition ofa sentence,paragraph andsection in  Vim?faq-10.6  HowdoI jump to beginning orend ofa sentence,paragraph ora  section?faq-10.7I have lines ina file thatextends beyond the right extent of the  screen. HowdoI move the Vimview to the right to see the text  off the screen?faq-10.8  HowdoI scroll two or morebuffers simultaneously?faq-10.9  WhenI use my arrow keys, Vim changes modes, inserts weird  characters in my document but doesn't move the cursor properly.  What's going on?faq-10.10 HowdoI configure Vim to move the cursor to theend of the  previous line, when the left arrow keyis pressed and the cursoris currentlyat the beginning ofa line?faq-10.11 HowdoI configure Vim to stay only ininsert mode (modeless  editing)?faq-10.12 HowdoI display some context lines whenscrolling text?faq-10.13 HowdoIgo back to previous cursor locations?faq-searching-textSECTION 11 - SEARCHING TEXTfaq-11.1  AfterI searched fora text witha pattern, all the matched text  stays highlighted. HowdoI turn off the highlighting  temporarily/permanently?faq-11.2  HowdoI entera carriage return character ina search pattern?faq-11.3  HowdoI search for the character "^M"?faq-11.4  How canI search/replace characters that displayas "~R", "~S",  etc.?faq-11.5  HowdoI highlight all the non-printable characters ina file?faq-11.6  HowdoI search for whole words ina file?faq-11.7  HowdoI search for the currentword under the cursor?faq-11.8  HowdoI search foraword without regard to thecase (uppercase  or lowercase)?faq-11.9  HowdoI search for words that occur twice consecutively?faq-11.10 HowdoIcount the number of timesa particularword occurs ina  buffer?faq-11.11 HowdoI place the cursorat theend of the matchedword when  searching fora pattern?faq-11.12 HowdoI search for an empty line?faq-11.13 HowdoI search fora line containing onlya single character?faq-11.14 HowdoI search and replaceastring in multiple files?faq-11.15I am using the:s substitute command ina mapping. Whena  search forapattern fails, the map terminates.I would like the  map to continue processing the next command, even if the  substitute command fails. HowdoIdo this?faq-11.16 HowdoI search for the n-th occurrence ofa character ina  line?faq-11.17 HowdoI replaceatab (or any other character) witha hard  return (newline) character?faq-11.18 HowdoI search fora character by its ASCII value?faq-11.19 HowdoI search for long lines?faq-11.20 HowdoI display all the lines in the current buffer that  containa specified pattern?faq-11.21 HowdoI search fora textstring that spans multiple lines?faq-11.22 HowdoI search forapattern only withina range of lines  ina buffer?faq-11.23 HowdoI clear the last searched pattern?faq-11.24 Why does thispattern "a.\{-}p\@!" not match?faq-11.25 How canI use "/" withina pattern, without escaping it?faq-11.26 How canI operate ona search match?faq-changing-textSECTION 12 - CHANGING TEXTfaq-12.1  HowdoI delete all the trailing whitespace characters (SPACE  and TAB)at theend of all the lines ina file?faq-12.2  HowdoI replace all the occurrences of multiple consecutivespace characters toa single space?faq-12.3  HowdoI reducea range of empty lines into one line only?faq-12.4  HowdoI delete all blank lines ina file? HowdoI remove all  the lines containing onlyspace characters?faq-12.5  HowdoI copy/yank the current word?faq-12.6  HowdoIyank text from one position to another position withina  line, without yanking the entire line?faq-12.7  WhenIyank some text intoa register, howdoI append the text  to the current contents of the register?faq-12.8  HowdoIyanka completesentence that spans over more than one  line?faq-12.9  HowdoIyank all the lines containingapattern intoa buffer?faq-12.10 HowdoI delete all the lines ina file thatdo not containa  pattern?faq-12.11 HowdoI adda line before each line with "pattern" in it?faq-12.12 Is therea way to operate ona line if the previous line  containsa particular pattern?faq-12.13 HowdoI executea command on all the lines containinga  pattern?faq-12.14 CanI copy the character above the cursor to the current cursor  position?faq-12.15 HowdoIinserta blank line above/below the current line  without enteringinsert mode?faq-12.16 HowdoIinsert the name of the current file into the current  buffer?faq-12.17 HowdoIinsert the contents ofa Vim register into the current  buffer?faq-12.18 HowdoI move the cursor past theend of line andinsert some  charactersat some columns after theend of the line?faq-12.19 How to replace theword under the cursor (say: junk) with  "foojunkbar" in Vim?faq-12.20 HowdoI replacea particular text in all the files ina  directory?faq-12.21I have some numbers ina file. HowdoI increment or decrement  the numbers in the file?faq-12.22 HowdoI reuse the last used searchpattern ina:substitute  command?faq-12.23 HowdoI change thecase ofastring using the:substitute  command?faq-12.24 HowdoI enter characters that are not present in the keyboard?faq-12.25 Is therea command to remove any or all digraphs?faq-12.26 Ininsert mode, whenI press thebackspace key,it erases only  the characters entered in this instance ofinsert mode. HowdoI  erase previously entered characters ininsert mode using thebackspace key?faq-12.27I havea file which has lines longer than 72 characters  terminated with "+" and wrapped to the next line. How canI  quickly join the lines?faq-12.28 HowdoI pastecharacterwise yanked text into separate lines?faq-12.29 HowdoI change thecase (uppercase, lowercase) ofaword ora character ora block of text?faq-12.30 HowdoI enter ASCII characters that are not present in the  keyboard?faq-12.31 HowdoI replace non-printable characters ina file?faq-12.32 HowdoI remove duplicate lines froma buffer?faq-12.33 HowdoI prefix all the lines ina file with the corresponding  line numbers?faq-12.34 HowdoI exchange (swap) two characters or words or lines?faq-12.35 HowdoI change the characters usedasword delimiters?faq-completion-in-insert-modeSECTION 13 - COMPLETION IN INSERT MODEfaq-13.1  HowdoI complete words or lines ininsert mode?faq-13.2  HowdoI complete file names ininsert mode?faq-13.3I am usingCTRL-P/CTRL-N to complete words ininsert mode. HowdoI complete words that occur after the just completed word?faq-text-formattingSECTION 14 - TEXT FORMATTINGfaq-14.1  HowdoI formata textparagraph so thata new lineis insertedat theend of each wrapped line?faq-14.2  HowdoI format long lines ina file so that each line containsless than "n" characters?faq-14.3  HowdoI join short lines to the forma paragraph?faq-14.4  HowdoI format bulleted and numbered lists?faq-14.5  HowdoI indent lines ininsert mode?faq-14.6  HowdoI format/indent an entire file?faq-14.7  HowdoI increase or decrease the indentation of the current  line?faq-14.8  HowdoI indenta block/group of lines?faq-14.9  WhenI indent lines using the> or< key, the standard 8-tabstops  are used instead of the current'tabstop' setting. Why?faq-14.10 HowdoI turn off the automatic indentation of text?faq-14.11 HowdoI configure Vim to automatically set the'textwidth'  option toa particular value whenI edit mails?faq-14.12 Is therea way to make Vim auto-magically break lines?faq-14.13I am seeinga lot of ^M symbols in my file.I tried setting the'fileformat' option to'dos' and then'unix' and then'mac'.None of these helped. How canI hide these symbols?faq-14.14 WhenI paste some text intoa Vim buffer from another  application, the alignment (indentation) of the new textis  messed up. HowdoI fix this?faq-14.15 When thereisa very long wrapped line (wrapis "on") anda line  doesn't fit entirely on the screenitis not displayedat all.  There are blank lines beginning with "@" symbol instead of  wrapped line. IfI scroll the screen to fit the line the "@"  symbols disappear and the lineis displayed again. What Vim  settingcontrol this behavior?faq-14.16 HowdoI convert all thetab characters ina file tospace  characters?faq-14.17 What Vimoptions canI use to edit text that will latergo toaword processor?faq-14.18 HowdoI join lines without adding or removing anyspace  characters?faq-visual-modeSECTION 15 - VISUAL MODEfaq-15.1  HowdoIdo rectangular block copying?faq-15.2  HowdoI delete or changea column of text ina file?faq-15.3  HowdoI apply an ex-command ona set of visually selected lines?faq-15.4  HowdoI execute anex command ona column of text selected inVisual block mode?faq-15.5  HowdoI select the entire file in visual mode?faq-15.6  WhenI visually selecta set of lines and press the> key to  indent the selected lines, the visual mode ends. How canI  reselect the region for further operation?  (or) HowdoI  re-select the last selected visual area again?faq-15.7  HowdoI jump to the beginning/end ofa visually selected region?faq-15.8  WhenI select text with mouse and then press: to enter anex  command, the selected textis replaced with the: character. HowdoI execute anex command ona text selected using the mouse  similar to the text selected using the visual mode?faq-15.9  WhenI selecta block of text using the mouse, Vim goes into  selection mode instead ofVisual mode. Why?faq-command-line-modeSECTION 16 - COMMAND-LINE MODEfaq-16.1  HowdoI use the name of the current file in the command mode or  anex command line?faq-16.2  HowdoI edit the text in the Vim command-line effectively?faq-16.3  HowdoI switch fromVi mode toEx mode?faq-16.4  HowdoI copy the output from an ex-command intoa buffer?faq-16.5  WhenI press the<Tab> key to complete the name ofa file in the  command mode, if there are more than one matching file names,  then Vim completes the first matching file name and displaysalist of all matching filenames. HowdoI configure Vim to only  display thelist of all the matching filenames and not complete  the first one?faq-16.6  HowdoI copy text froma buffer to the command line and from the  command line toa buffer?faq-16.7  HowdoIputa command onto the commandhistory without executing  it?faq-16.8  HowdoI increase the height of the command-line?faq-viminfoSECTION 17 - VIMINFOfaq-17.1  WhenI invoke Vim,I get errormessages about illegal characters  in theviminfo file. What shouldIdo to get rid of these  messages?faq-17.2  HowdoI disable theviminfo feature?faq-17.3  HowdoI save and use Vim marks/commands across Vim sessions?faq-remote-editingSECTION 18 - REMOTE EDITINGfaq-18.1  HowdoI opena file with existing instance of gvim? What  happened to the Vim 5.x OpenWithVim.exe and SendToVim.exe files?faq-18.2  HowdoI senda command toa Vim server to write allbuffers to  disk?faq-18.3  Where canI get the documentation about the Vim remote server  functionality?faq-optionsSECTION 19 - OPTIONSfaq-19.1  HowdoI configure Vim ina simple way?faq-19.2  HowdoItoggle the value of an option?faq-19.3  HowdoI set an option that affects only the current  buffer/window?faq-19.4  HowdoI usespace characters fora Vim option value?faq-19.5  CanI add (embed) Vim option settings to the contents ofa file?faq-19.6  HowdoI display the line numbers of all the lines ina file?faq-19.7  HowdoI change the width of the line numbers displayed using the'number' option?faq-19.8  HowdoI display (view) all the invisible characters like space,  tabs and newlines ina file?faq-19.9  HowdoI configure Vim to always display the current line and  column number?faq-19.10 HowdoI display the current Vim mode?faq-19.11 HowdoI configure Vim to show pending/partial commands on the  status line?faq-19.12 HowdoI configure the Vim status line to display different  settings/values?faq-19.13 HowdoI configure Vim to display status line always?faq-19.14 HowdoI makea Vim setting persistent across different Vim  invocations/instances/sessions?faq-19.15 WhydoI hearabeep (why does mywindow flash) about 1 second  afterI hit the Escape key?faq-19.16 HowdoI make the "c" and "s" commands displaya "$" instead ofdeleting the characters I'm changing?faq-19.17 HowdoI remove more than one flag usinga single:set command  froma Vim option?faq-mapping-keysSECTION 20 - MAPPING KEYSfaq-20.1  HowdoI know whata keyis mapped to?faq-20.2  HowdoIlist all the user-defined key mappings?faq-20.3  HowdoI unmapa key?faq-20.4I am not able to createamapping for the<xxx> key. Whatis  wrong?faq-20.5  Why doesmapping the <C-...> key not work?faq-20.6  HowdoI map the numeric keypad keys?faq-20.7  HowdoI createamapping that works only in visual mode?faq-20.8  HowdoI createamapping that works only in normal andoperator  pending mode (but not in visual mode)?faq-20.9  Ina Vim script, howdoI know which keys to use for my mappings,  so that the mapped key will not collide with an already used key?faq-20.10 HowdoI map theescape key?faq-20.11 HowdoI mapa key to perform nothing?faq-20.12I want to use the<Tab> key to indenta block of text and<Shift-Tab> key to unindenta block of text. HowdoI map the keys  todo this?  This behavioris similar to textpad, visual studio,  etc.faq-20.13 In my mappings the special characters like<CR> are not  recognized. How canI configure Vim to recognize special  characters?faq-20.14 HowdoI use the "|" to separate multiple commands ina map?faq-20.15 IfI havea mapping/abbreviation whose endingis the beginning of  another mapping/abbreviation, howdoI keep the first from  expanding into the second one?faq-20.16 Why doesit takea second or more for Vim to processa key,  sometimes whenI pressa key?faq-20.17 HowdoI mapa key to run an external command usinga visually  selected text?faq-20.18 HowdoI map theCTRL-I key while still retaining the  functionality of the<Tab> key?faq-20.19 HowdoI definea map to accepta count?faq-20.20 How canI make my normal modemapping work from withinInsert  Mode?faq-abbreviationsSECTION 21 - ABBREVIATIONSfaq-21.1  HowdoI auto correct misspelled words?faq-21.2  HowdoI create multi-line abbreviations?faq-21.3  When myabbreviations are expanded, an additionalspace characteris addedat theend of the expanded text. HowdoI avoid this  character?faq-21.4  HowdoIinsert the current date/time stamp into the file?faq-21.5  HowdoI prevent an abbreviation from expanding ininsert mode?faq-record-and-playbackSECTION 22 - RECORD AND PLAYBACKfaq-22.1  HowdoI repeat an editing operation (insertion, deletion, paste,  etc)?faq-22.2  HowI record and repeata set of key sequences?faq-22.3  HowdoI edit/modifya recorded set of key sequences?faq-22.4  HowdoI write recorded key sequences toa file?faq-22.5I am using register0 to record my key sequences (i.e. q0 ....  q). In the recorded key sequences,I am yanking some text.  After  the first replay of the recorded key sequence,I am no longer  able to playit back.faq-autocommandsSECTION 23 - AUTOCOMMANDSfaq-23.1  HowdoI executea command whenI try to modifya read-only file?faq-23.2  HowdoI executea command every time when enteringa buffer?faq-23.3  HowdoI executea command every time when enteringa window?faq-23.4  From an autocmd, how canI determine the name of the file or the  buffer number for which theautocommandis executed?faq-23.5  HowdoI automatically save all the changedbuffers whenever Vim  loses focus?faq-23.6  HowdoI execute/runa function when Vim exits todo some  cleanup?faq-syntax-highlightSECTION 24 - SYNTAX HIGHLIGHTfaq-24.1  HowdoI turn off/onsyntax highlighting?faq-24.2  HowdoI change the background and foreground colors used by Vim?faq-24.3  HowdoI change the highlight colors to suita dark/light  background?faq-24.4  HowdoI change the color of the line numbers displayed when the  `:set number` commandis used?faq-24.5  HowdoI change the background color used fora Visually selected  block?faq-24.6  HowdoI highlight the special characters (tabs, trailing spaces,end of line, etc) displayed by the'list' option?faq-24.7  HowdoI specifya colorscheme in my .vimrc/.gvimrc file, so that  Vim uses the specified colorscheme every time?faq-24.8  Vimsyntax highlightingis broken. WhenI am editinga file, some  parts of the fileis notsyntax highlighted orsyntax highlighted  incorrectly.faq-24.9  Is therea built-in function to syntax-highlight the  corresponding matching bracket?faq-24.10 HowdoI turn off theC commentsyntax highlighting?faq-24.11 HowdoI add my ownsyntax extensions to the standardsyntax  files supplied with Vim?faq-24.12 HowdoI replacea standardsyntax file that comes with the Vimdistribution with my ownsyntax file?faq-24.13 HowdoI highlight all the characters aftera particular column?faq-24.14 HowdoI converta source file (.c, .h, etc) with the Vimsyntax  highlighting intoa HTML file?faq-24.15 HowdoIlist the definition of all the current highlight  groups?faq-24.16 How canI embed onesyntax highlighting language into another  one?faq-vim-script-writingSECTION 25 - VIM SCRIPT WRITINGfaq-25.1  HowdoIlist the names of all the scripts sourced by Vim?faq-25.2  HowdoI debug Vim scripts?faq-25.3  HowdoI locate the script/plugin which setsa Vim option?faq-25.4I am getting some error/informationalmessages from Vim (possibly  when runninga script), themessages are cleared immediately. HowdoI display themessages again?faq-25.5  HowdoI save and restoreaplugin specific information across  Vim invocations?faq-25.6  HowdoI startinsert mode froma Vim function?faq-25.7  HowdoI change the cursor position from withina Vim function?faq-25.8  HowdoI check the value of an environment variable in the.vimrc  file?faq-25.9  HowdoI check whether an environment variableis set or not froma Vim function?faq-25.10 HowdoI call/use the Vim built-in functions?faq-25.11I am using some normal mode commands in my Vim script. HowdoI  avoid using the user-defined mappings for these normal mode  commands and use the standard Vim functionality for these normal  mode commands?faq-25.12 HowdoI geta visually selected text intoa Vim variable or  register?faq-25.13I have some text ina Vim variable "myvar".I would like to use  this variable ina:s substitute command to replacea text  "mytext". HowdoIdo this?faq-25.14A Vim variable (bno) containsa buffer number. HowdoI use this  variable to open the corresponding buffer?faq-25.15 HowdoI store the value ofa Vim option intoa Vim variable?faq-25.16I have copied and inserted some text intoa buffer froma Vim  function. HowdoI indent the inserted text from the Vim  function?faq-25.17 HowdoI get the character under the cursor froma Vim script?faq-25.18 HowdoI get the name of the current file without the extension?faq-25.19 HowdoI get the basename of the current file?faq-25.20 HowdoI get the output froma Vim function into the current  buffer?faq-25.21 HowdoI call external programs froma Vim function?faq-25.22 HowdoI get the return status ofa program executed using the:! command?faq-25.23 HowdoI determine whether the current bufferis modified or  not?faq-25.24I would like to use the carriage return character ina normal  command froma Vim script. HowdoI specify the carriage return  character?faq-25.25 HowdoI split long lines ina Vim script?faq-25.26 WhenI try to "execute" my function using the `:execute Myfunc()`  command, the cursoris moved to the top of the current buffer.  Why?faq-25.27 HowdoI source/execute the contents ofa register?faq-25.28 After callinga Vim function ora mapping, whenI press the "u"  key toundo the last change, Vim undoes all the changes made by  the mapping/function. Why?faq-25.29 How canI calla function defined with s: (script local  function) from another script/plugin?faq-25.30 Isit possible to un-sourcea sourced script? In other words,  reverse all the commands executed by sourcinga script.faq-pluginsSECTION 26 - PLUGINSfaq-26.1  HowdoI set differentoptions for different types of files?faq-26.2I have downloadeda Vimplugin orasyntax file ora indent file,  ora color scheme orafiletypeplugin from the web. Where shouldI copy these files so that Vim will find them?faq-26.3  HowdoI extend an existingfiletype plugin?faq-26.4  HowdoI turn off loading the Vim plugins?faq-26.5  HowdoI turn on/off loading thefiletype plugins?faq-26.6  HowdoI override settings made ina file typeplugin in the  globalftplugin directory for all the file types?faq-26.7  HowdoI disable the Vim directory browser plugin?faq-26.8  HowdoI set thefiletype option for files with names matchinga  particularpattern or depending on the file extension?faq-editing-program-filesSECTION 27 - EDITING PROGRAM FILESfaq-27.1  HowdoI enable automatic indentation for C/C++ files?faq-27.2  HowdoI configure the indentation used for C/C++ files?faq-27.3  HowdoI turn off the automatic indentation feature?faq-27.4  HowdoI change the number ofspace characters used for the  automatic indentation?faq-27.5I am editingaC program using Vim. HowdoI display the  definition ofamacro ora variable?faq-27.6I am editingaC program using Vim. HowdoI jump to the  beginning orend ofa code block from within the block?faq-27.7  When editing C++ files and wheninserting new lines above or  belowa comment (//) line, Vim automatically inserts the C++  comment character (//)at the beginning of the line. HowdoI  disable this?faq-27.8  HowdoI add the comment character "#" toa set of linesat the  beginning of each line?faq-27.9  HowdoI edita header file with the same nameas the  correspondingC source file?faq-27.10 HowdoI automaticallyinsert comment leaders while typing  comments?faq-quickfixSECTION 28 - QUICKFIXfaq-28.1  HowdoI build programs from Vim?faq-28.2  WhenI run the make command in VimI get theerrors listedas the  compiler compiles the program. Whenit finishes thislist  disappears andI have to use the:clist command to see the error  message again. Is there any other way to see these error  messages?faq-28.3  How canI performa command for each item in the  quickfix/location list?faq-foldingSECTION 29 - FOLDINGfaq-29.1  HowdoI extend the Vimfolding support?faq-29.2  WhenI enablefolding by setting the'foldmethod' option, all thefolds are closed. HowdoI prevent this?faq-29.3  HowdoIcontrol how manyfolds will be opened whenI start  editinga file?faq-29.4  HowdoI open and closefolds using the mouse?faq-29.5  HowdoI change the text displayed fora closed fold?faq-29.6  HowdoI store and restore manually createdfolds across  different Vim invocations?faq-29.7I have enabledsyntax based folding. Whyis Vim so slow?faq-vim-with-external-applicationsSECTION 30 - VIM WITH EXTERNAL APPLICATIONSfaq-30.1  CanI runa shell insidea Vim window?faq-30.2  HowdoI pass theword under the cursor to an external command?faq-30.3  HowdoI get the output ofa shell command intoa Vim buffer?faq-30.4  HowdoI pipe the contents of the current buffer to an external  command and replace the contents of the buffer with the output  from the command?faq-30.5  HowdoI sortasection of my file?faq-30.6  HowdoI use Vimasa pager?faq-30.7  HowdoIviewUnix man pages from inside Vim?faq-30.8  HowdoI change thediff command used by the Vimdiff support?faq-30.9  HowdoI use the Vimdiff mode without folding?faq-gui-vimSECTION 31 - GUI VIMfaq-31.1  HowdoI create buffer specific menus?faq-31.2  HowdoI change the font used byGUI Vim?faq-31.3  WhenstartingGUI Vim, howdoI specify the location of the GVIM  window?faq-31.4  HowdoI adda horizontal scrollbar in GVim?faq-31.5  HowdoI make the scrollbar appear in the left side by default?faq-31.6  HowdoI remove the Vim menubar?faq-31.7I am usingGUI Vim. WhenI press the<Alt> key anda letter, the  menustarting with thatletteris selected.I don't want this  behaviorasI want to map the<Alt>-<key> combination. HowdoIdo  this?faq-31.8  Isit possible to scroll the text by dragging the scrollbar so  that the cursor stays in the original location?faq-31.9  HowdoI getgvim to start browsing files ina particular  directory when using the:browse command?faq-31.10 For some questions, like whena fileis changed outside of Vim,  Vim displaysaGUIdialog box. HowdoI replace thisGUIdialog  box witha consoledialog box?faq-31.11I am trying to useGUI Vimas the editor for my xxx application.  When the xxx application launchesGUI Vim to edita file, thecontrol immediately returns to the xxx application. HowdoI  startGUI Vim, so that thecontrol returns to the xxx  application only afterI quit Vim?faq-31.12 Why does the "Select Font"dialog doesn't show all the fonts  installed in my system?faq-31.13 HowdoI use the mouse in Vim command-line mode?faq-31.14 WhenI use the middle mouse button to scroll text,it pastes the  last copied text. HowdoI disable this behavior?faq-31.15 HowdoI change the location and size ofaGUI Vim window?faq-31.16 When splitting the Vimwindow vertically, Vim changes  the position.faq-vim-on-unixSECTION 32 - VIM ON UNIXfaq-32.1I am running Vim ina xterm. WhenI press theCTRL-S key, Vim  freezes. What shouldIdo now?faq-32.2I am seeing weird screen update problems in Vim. What canIdo to  solve this screen/display update problems?faq-32.3I am using the terminal/console version of Vim. In insertmode,  WhenI press thebackspace key, the character before the cursoris not erased. HowdoI configure Vim todo this?faq-32.4I am using Vim ina xterm. WhenI quit Vim, the screen contents  are restored back to the original contents. HowdoI disable  this?faq-32.5  WhenI start Vim,it takes quitea few seconds to start. HowdoI  minimize thestartup time?faq-32.6  How canI make the cursor ingvim inunix stop blinking?faq-32.7  HowdoI change the menu font onGTK Vim?faq-32.8  HowdoI preventCTRL-Z from suspending Vim?faq-32.9  WhenI kill the xterm running Vim, the Vim process continues to  run and takes upa lot of CPU (99%) time. Whyis this happening?faq-32.10 HowdoI get the Vimsyntax highlighting to work inaUnix  terminal?faq-vim-on-ms-windowsSECTION 33 - VIM ON MS-WINDOWSfaq-33.1  In MS-Windows,CTRL-V doesn't start the blockwise visual mode.  What happened?faq-33.2  WhenI press theCTRL-Y key,it acts like theCTRL-R key. HowdoI configure Vim to treatCTRL-YasCTRL-Y?faq-33.3  HowdoI startGUI Vim ina maximizedwindow always?faq-33.4  After doing some editing operations, Vim freezes. The cursor  becomes an empty rectangle.I am not able enter any characters.  Whatis happening?faq-33.5I am using Windows XP, the display speed of maximized GVimis  very slow. What canIdo to speed the display updates?faq-33.6  What are the recommended settings for using Vim with cygwin?faq-33.7I am trying to use GNUdiff with Vimdiff mode. WhenI run thediff from command line,it works. WhenI try to use thediff with  Vimit doesn't work. What shouldIdo now?faq-33.8  Isit possible to use Vimas an external editor forMS-Windows  Outlook email client?faq-33.9I am using Vim to edit HTML files. HowdoI startinternet  explorer with the current file to preview the HTML file?faq-33.10I would like to use Vim with MicrosoftVisual Studio. HowdoIdo this?faq-33.11 WheredoI place the_vimrc and_gvimrc files?faq-33.12 Every timeI savea file, Vim warns about the file being changed  outside of Vim. Why?faq-printingSECTION 34 - PRINTINGfaq-34.1  HowdoI printa file along with line numbers for all the lines?faq-34.2  HowdoI printa file with the Vimsyntax highlighting colors?faq-building-vim-from-sourceSECTION 35 - BUILDING VIM FROM SOURCEfaq-35.1  HowdoI build Vim from the sources onaUnix system?faq-35.2  HowdoIinstall Vim in myhome directory ora directory other  than the default installation directory in Unix?faq-35.3  HowdoI build Vim from the sources onaMS-Windows system?faq-35.4  The Vim help, syntax, indent files are missing from my Vim  installation. HowdoIinstall these files?faq-35.5I have built Vim from the source and installed the Vim package  using "makeinstall". DoI need to keep the Vim source directory?faq-35.6  HowdoI determine the Vim features which are enabledat compile  time?faq-35.7  CanI build Vim without theGUI support?faq-35.8  When building Vim onaUnix system,I am getting "undefinedreference to term_set_winsize" error. HowdoI resolve this  error?faq-35.9  Vim configure keeps complaining about the lack of gtk-config  while trying to useGTK 2.03. Thisis correct, since inGTK 2  they moved to using the generic pkg-config.I can get pkg-config  tolist thevarious includes and libs for gtk, but for some  reason the configurescript still isn't picking this up.faq-35.10I did successfullydownload the sources and compiled Vim on  Unix. But feature... still does not work. Whatis wrong and  how canI fix it?faq-variousSECTION 36 - VARIOUSfaq-36.1  HowdoI edit binary files with Vim?faq-36.2  HowdoI disable the visual error flash and the error beep?faq-36.3  HowdoI display the ascii value ofa character displayed ina  buffer?faq-36.4  CanI use zeroasacount fora Vim command?faq-36.5  HowdoI disable the Vim welcome screen?faq-36.6  HowdoI avoid the "hit enter to continue" prompt?faq-36.7  HowdoI invoke Vim from command line to runa group of commands  ona group of files?faq-36.8  HowdoI usea normal mode command frominsert mode without  leaving theinsert mode?faq-36.9  HowdoI start Vim ininsert mode?faq-36.10 HowdoI use Copy and Paste with Vim?faq-36.11 Why shouldn'tI modify the files in the system runtime  directory?faq-unicodeSECTION 37 - UNICODEfaq-37.1  Isit possible to createUnicode files using Vim?faq-37.2  Which Vim settings are particularly important for editingUnicode  files?faq-37.3  Whatis the'encoding' option?faq-37.4  How does Vim name thevariousUnicode encodings?faq-37.5  How does Vim specify the presence or absence ofa byte-order  mark?faq-37.6  Whatis the'fileencoding' option?faq-37.7  Whatis the'fileencodings' option?faq-37.8  Whatis the'termencoding' option?faq-37.9  Whatis the'bomb' option?faq-37.10 Where canI find an example ofa typical use of all these  options?faq-37.11 How canIinsertUnicode characters intoa file using Vim?faq-37.12 How canI know whichdigraphs are defined and for which  characters?=============================================================================faq-1SECTION 1 - GENERAL INFORMATIONfaq-1.11.1. Whatis Vim?Vim stands forVi IMproved. It used to beVi IMitation, but there are somany improvements thata name change was appropriate. Vimisa text editorwhich includes almost all the commands from theUnix program "Vi" anda lotof new ones. All commands can be given with the keyboard. This has theadvantage that you can keep your fingers on the keyboard and your eyes onthe screen. For those who want it, thereis mouse support andaGUI versionwith scrollbars and menus.Vimis an editor, notaword processor.Aword processoris used mainlytodo layout of text. This means positioning it,changing the wayitappears on output. More often than not, the final documentis meant tobe printed or typeset or what have you, in order to presentit inapleasing manner to others. Examples ofword processors are MicrosoftWord, FrameMaker, and OpenOffice Writer.An editoris simply for entering text. Any typesetting or laying out of thedocumentis secondary. With an editor, one's main concernis entering text,not making the text look good. Examples of editors other than Vim andViare Emacs, TextMate, Ultraedit and gedit. And Notepad.For more information, read:introfaq-1.21.2. Who wrote Vim?Most of Vimis based on Stevie and was written byBram Moolenaar, withcontributions from too many people to mention here.For more information, read:authorcreditsfaq-1.31.3. Is Vim compatible with Vi?Yes. Vimis very much compatible with Vi.  You can use the "-C"command-line flag to start Vim inVi compatible mode:    $ vim -CYou can also use:    $ vim -u NONEYou can also set the'compatible' option to enableVi compatibility:    :set compatibleIf you want to make sure, to start Vim ina'nocompatible' mode tooriginal Vi, supply the-N command line argument:    $ vim -NFor more information, read:-C-N'compatible'compatible-defaultfaq-1.41.4. What are some of the improvements of Vim over Vi?A short summary of the improvements of Vim overviis listed below.  Thelist shows that Vimisa thoroughly modern and feature-packed editor.Standard features of modern editors are implemented, and thereis an equalemphasis on general power-user features and features for programmers.Features to modernise Vi:  Multi-level undo     Allows you to set the number of times you canundo your changes ina     file buffer. You can alsoredo an undone change.     Alsostarting with version 7.3 Vim can permanently store yourundo     information, so that you canundo your changes which you have done     ina previous editing session.  Tabs, Multiple windows and buffers     Each file can be displayed in its own window. You can move easily from     onewindow to another. Each file opened duringa Vim session also has     an associated buffer and you can easily jump from one to the other.     Also like any modern GUI, Vim supports opening several files in tabs.     You cando batch processing for tabs, buffers,windows and the     argumentlist.  Flexible insert mode     Vim allows you to use the arrow keys while ininsert mode to move     around in the file. No more hitting<Esc>, moving around, then hitting     `i' or `a'.  Macros     Vim hasa facility which allows you to recorda sequence of typed     characters and repeat them any number of times.  Visual mode     You can highlight sections of text and execute operations on thissection of text only.  Block operators     Allow selection and highlighting of rectangular blocks of text in     orderdo execute specific operations on them.  Online help system     You can easily findhelp on any aspect of using Vim. Helpis displayed     in its own window.  Command-line editing and history     History allows you to use the arrow keys to repeat or search fora     command that has already been typed. Allows you to match the beginning     ofa command with the beginning of another similar command in thehistory buffer. You can also edita command to correct typos or changea few values.  Command line completion.     Using the<Tab> key, you can complete commands, options, filenames,     etc.as needed.  Horizontal scrolling.     Long lines can be scrolled horizontally (with or without the GUI).  Unicode and internationalization improvements.     Vimis able to edit files inunicode encoding and uses internally anutf-8 encoding. Additionally Vim can display text right to left     oriented.Advanced user features:  Text formatting     With two keystrokes, you can format large sections of text, without     the use of external programs.  Completion in Insert mode     Vim provides several different possibilities to complete your text.     For example Vim can complete words while you are typing, by matching     the currentword with other similar words in the file.  Jump tags     Just like in aninternet browser, you can jump back to previous parts     of the text you were editing, and then forward again.  Your brainis     thus free to edit instead of navigate.  Automatic commands     Commands automatically executed when reading orwritinga file,     jumping to another buffer, etc.  Viminfo     Allows storing of the command line history, marks andregisters ina     file to be read on startup.  Therefore, you can recall old search     patterns, macros, etc., ina new Vim session.  Mouse support     The mouseis supported in an xterm and for MS-DOS. It can be used to     position the cursor, select the visual area, pastea register, etc.  Graphical User Interface (GUI)     There are several different graphical user interfaces available.     Also, it's veryeasy to add your own menus.  Of course, console vimis     still supported, and very widely used.  Scripting language     Vim hasa powerful scripting language so new commands can be created.     You can also use Perl, Python, TCL,Lua andRuby to achieve the same     thing!  Plugins     Extra functionality implemented via vim commands (regular commands or     the scripting language) thatis automatically loaded on startup.     Examples: file explorer,network editing, enhanced autocompletion,syntax checks.     More are being developed and shared on VimOnline all the time.  Syntax highlighting for many programming languagesSyntax highlighting (including concealing items) for hundreds of     programming languagesis supported. Support for others can be     added.  Extended regular expressions     Vim supports extended regular expressions which are similar in     functionality to that ofPerl regular expressions.  Integrated Spell checking     Spell checking has been integrated into Vim.  Diff mode     Vim can highlight the differences between two, three or four files.     Identical lines will be folded away and hidden.  Encryption using the blowfish algorithm     Vim allows to encrypt your files using the symmetric block cipherblowfishas wellas the swap file.  Extensive customizable     Vim can be tuned and customized to work like you want by setting     options. You can define your own commands, macros and even plugins     to extend its capabilities  Packages     Packages have been added to keep the installation of the growing     number of plugins manageable. Thisisa convenient way to get one     or more plugins, drop them ina directory and keep them updated.     Vim will load them automatically, or only when desired.Programming performance features:  Edit-compile-edit speedup     You can compile within Vim and automatically jump to the location oferrors in the source code.  Indenting for many programming languages     C, C++, Java, Perl, XML and many other languages can be automatically     indented by vim while you type.  Support for others can be added.  Searching for words in include files     Vim allows you to search fora match of theword under the cursor in     the current and included files.  Advanced text objects     Instantly select, delete, copy, indent, format, change case, or...     to all the text between( and ), or{ and }, or< and >, or[ and     ].  Ora word, sentence, or paragraph.  Very powerful.  Folding     Certain parts of the text can be "folded" away.  The best exampleis     the body ofa function.  You can get an overview of the code, and then     open the fold of the function whose detail you need to see.  ctags and cscope integration     Using these two powerful programs, you can jump toa definition ofa     function froma calling instance of it, and use other tricks to     navigate source code.  Integration of several programming languages     If you find the internal scripting language not powerful enough, you     can extend Vim using Lua, Ruby, Tcl,Perl andPython 2 and 3.  Asynchronous I/O support     Vim uses jobs and channels to talk to other programs     asynchronously. This allows to have e.g.a compiler run in the     background and open thequickfixlistas soonasitis finished to     fix warnings and errors.  Timers     Timers are asynchronous and can fire once or repeatedly to invokea     function todo any work.For more information, read:vi-differencesfaq-1.51.5. Is Vim free?Vimis Charityware. There are no restrictions on using orcopying Vim, buttheauthor encourages you to makea donation to charity.A documentexplaining how todo sois included in the distribution.For more information, read:copyright=============================================================================faq-2SECTION 2 - RESOURCESfaq-2.12.1. Where canI learn more about Vim?You can post your Vim questions to the vim@vim.org mailing list.  You canpost your Vimdevelopment related questions to the vim-dev@vim.org mailinglist. Vim does not havea newsgroup of its own. But the appropriatenewsgroup to post tois comp.editors."VimOnline"isa web page that servesasa de facto homepage for vim,although the main purpose ofitis to gathertips and scripts fromeverywhere.  Get involved!  The URLishttps://www.vim.orgFinally, read theVi FAQ:http://www.faqs.org/faqs/editor-faq/vi/part1/index.htmlFinally, there are also some communities, where you can discuss featuresor ask questions:https://vi.stackexchange.comhttps://vim.reddit.comFor more information, read:mail-listinternetfaq-2.22.2. Is therea mailinglist available?There are several:    NAME              DESCRIPTION    ----------------  ---------------------------------------------vim-announce      Announcements of new releases    vim               General discussionvim-dev           Patches, bug reports,development discussionsvim-macMacintosh discussion    vim-fr            General discussion in FrenchOf these, only vim andvim-dev are of general interest.vim-announceisread-only to most people, and itsmessages are sent to the other listsaswell. The remaining four are very low volume.    ACTION            EMAIL SEND TO    ----------------  --------------------------    To subscribe:<NAME>-subscribe@vim.org    To unsubscribe:<NAME>-unsubscribe@vim.org    To get help:<NAME>-help@vim.orgThe available mailing lists are also mentioned here:https://www.vim.org/maillist.phpfaq-2.32.3. Is there an archive available for the Vim mailing lists?Yes. Visithttps://groups.yahoo.com/, where nameis one of:vimannounce, vim, vimdev, vim-fr, vim-mac, vim-vms.Alternatively, visit www.gmane.org to find out about GMANE, which allowsyou to access the mailing listsas though they were newsgroups.  Thisoffers some convenience to those who wish to browse thehistory or casuallyobserve the current threads.faq-2.42.4. Where canI get the Vim user manual in HTML/PDF/PS format?You candownload the HTML/PDF/PS format of the Vim user manual from:https://vimdoc.sourceforge.net/Note, the user manual from that pageis currently pretty outdated. It'sbest to either use the documentation that comes with vim or use theonline versionathttps://vimhelp.orgYou can finda pdf version of the full English help, including thisfaq(in letter, A4 and Ipad format) at:https://nathangrigg.com/vimhelp/This documentis cross-referenced, so you can use the hyperlinkfunctionality.faq-2.52.5.I havea "xyz" (some) problem with Vim. HowdoI determine ifitisa     problem with my setup or with Vim?/ HaveI founda bug in Vim?First, you need to find out, whether the erroris in the actual runtimefiles or anyplugin thatis distributed with Vim or whetheritisasimple side effect of any configuration option from your.vimrc or.gvimrc. So first, start vim like this:    vim -u NONE -U NONE -N -i NONEThis starts Vim in nocompatible mode (-N), without reading yourviminfofile (-i NONE), without reading any configuration file (-u NONE for notreading.vimrc file and-U NONE for not readinga.gvimrc file) or evenplugin.In this invocation, try to reproduce your problem. If the errorpersists, the chanceis good you've founda bug in Vim (see alsoQuestion 2.6.faq-2.6)If the error does not occur whenstarting Vim this way, then the problemis either related to someplugin of yours or some setting in one of yourlocal setup files. You need to find out, what triggers the error, youtrystarting Vim this way:    vim -u NONE -U NONE -NIf the error occurs, the problemis your .viminfo file. Simply deletetheviminfo file then. If the error does not occur, try:    vim -u ~/.vimrc --noplugin -N -i NONEThis will simply use your.vimrcas configuration file, but not load anyplugins. If the error occurs this time, the erroris possibly caused bysome configuration option inside your.vimrc file. Depending on thelength of yourvimrc file,it can be quite hard to trace the originwithin that file.The best wayis to add:finish command in the middle of your .vimrc.Then restart again using the same command line. If the error stilloccurs, the bugmust be caused because ofa setting in the first half ofyour .vimrc. Ifit doesn't happen, the problematic settingmust be inthe second half of your .vimrc. So move the:finish command to themiddle of that half, of which you know that triggers the error and moveyour way along, until you find the problematic option. If your.vimrcis350 lines long, you needata maximum 9 tries to find the offending line(in practise, this can often be further reduced, since often linesdepend on each other).If the problem does not occur, when only loading your.vimrc file, theerrormust be caused byaplugin or another runtime file (indentautoload orsyntax script). Check the output of the:scriptnames commandto see what files have been loaded and for each one try to disable eachone by one and see which one triggers the bug. Often files that areloaded by vim, havea simple configuration variable to disable them, butyou need to check inside each file separately.You can also use the-V command line argument to get more debuginformation to analyze the problem:    $ vim -V2logfileYou can increase the value passed to the-V argument to get more debuginformation. By also specifyinga logfile name, this makes sure, thedebugmessages don't appear on the screen and won't disturb you whentrying to reproduce the problem.For more information, read:-u-U-N-V'verbose':verbose:set-verbosefaq-2.62.6. Where canI report bugs?First collect the required information using the following command:    :source $VIMRUNTIME/bugreport.vimNow send the resulting text from the above command to the bugs@vim.orge-mail address. Thereis alsoa public bug tracker availableathttps://github.com/vim/vim/issues.A copy of each message therewill be forwarded to the Vim Development list.The Vim Development mailinglist (see Question 2.2faq-2.2)isa good place todiscuss general bugs.  If the bug you findis withsyntax highlighting,a runtime file, or some other "added feature" (i.e. not directlyprogrammed into vim), attempt to inform the maintainer of that feature.His e-mail address will be mentionedat the top of the correspondingruntime file.For more information, read:bug-reportsfaq-2.72.7. Where can theFAQ be found?TheFAQ can be foundathttps://vimhelp.org/vim_faq.txt.html.It will be auto-generated from the source thatis managed in the githubrepositoryhttps://www.github.com/chrisbra/vim_faq (Patches are welcome).The repository also includes thefaq in different formats, e.g. manpage,pdf file, html file, plain text version anda version in vimhelp format.A slightly older version (which doesn't seem to get updated anymore) canstill be foundat VimOnline (https://www.vim.org/).faq-2.82.8. What ifI don't find an answer in this FAQ?ThisFAQ covers mainly Vim-specific questions. You may find moreinformation suitable for mostVi clones by reading theVi FAQ. Itis postedregularly on comp.editors. You can also finda copyathttp://www.faqs.org/faqs/editor-faq/vi/part1/index.htmlAlso, since Vim has gathered so many features in the last few years,successfully documenting the frequently asked questions hereisanear-impossible task. To makeit possible, please email the maintainer ifyou havea good question.A good questionis one that you've tried toanswer yourself (remember, Vim has great documentation) but struggled.faq-2.92.9.I havea patch for implementinga Vim feature. Where canI send this     patch?You can send your patches to the Vim developer mailinglistvim-dev@vim.org.For more information, read:vim-devfaq-2.102.10.I havea Vim tip or developeda new Vim syntax/indent/filetype/      compilerplugin or developeda newscript ora colorscheme.      Is therea public website whereI can upload this?Yes. You can use the Vim Online website to upload your plugins/scripts,colorschemes, etc. The siteisathttps://www.vim.orgNowadays people also seem to share their plugins/runtime filesatgithub.Tips can also be shared in the Wiki which you can findathttp://vim.wikia.com=============================================================================faq-3SECTION 3 - AVAILABILITYfaq-3.13.1. Whatis the latest version of Vim?The latest version of Vimis 8.2 released on 12th December 2019.The releasehistory of different versions of Vimis below:    VERSION         RELEASE DATE    --------------  --------------------    Version 9.1     2nd January, 2024    Version 9.0     28th June, 2022    Version 8.2     12th December, 2019    Version 8.1     17th May, 2018    Version 8.0     12th September, 2016    Version 7.4     10th August, 2013    Version 7.3     15th August, 2010    Version 7.2     9th August, 2008    Version 7.1     12th May, 2007    Version 7.0     8th May, 2006    Version 6.4     15th October, 2005    Version 6.3     8th June, 2004    Version 6.2     1st June, 2003    Version 6.1     24th March, 2002    Version 6.0     27th September, 2001    Version 5.8     31st May, 2001    Version 5.7     24th June, 2000    Version 5.6     16th January, 2000    Version 5.5     21st September, 1999    Version 5.4     26th July, 1999    Version 5.3     31st August, 1998    Version 5.2     24th August, 1998    Version 5.1     7th April, 1998    Version 5.0     19th February, 1998    Version 4.6     13th March, 1997    Version 4.5     17th October, 1996    Version 4.2     5th July, 1996    Version 4.0     29th May, 1996    Version 3.0     12th August, 1994    Version 2.0     21st December, 1993    Version 1.27    23rd April, 1993    Version 1.17    21st April, 1992    Version 1.14    2nd November, 1991If you are interested in the old release history, check out thevim-history git repository:https://github.com/vim/vim-historyand especially for the release history:https://github.com/vim/vim-history#release-historyFor more information, read:new-9new-8changed-9.1changed-8.2changed-8.1faq-3.23.2. Where canI find the latest version of Vim?You candownload the sources for the latest version of Vim from theGithub repository. The URL for this siteishttps://github.com/vim/vimA mercurial mirroris also available:https://www.vim.org/hgweb/vim/Some users keep updated repositories for distributing latest binaryversions of Vim. You can find those repositories here:http://vim.wikia.com/wiki/Where_to_download_Vimfaq-3.33.3. What platforms doesit run on?AllUnix platforms.All Windows platforms (10 and later).Amiga, Macintosh, MachTen, VMS, IBM z/OS.ForMS-DOS support has been removed with the latest releases of Vim.16-bit DOS: latest supported version 7.132-bit DOS: latest supported version 7.3Windows XP and Visat: latest supported version 9.0faq-3.43.4. Where canIdownload the latest version of the Vim runtime files?You candownload the latest version of the Vim runtime files (syntax files,filetype plugins, compiler files, color schemes, documentation, indentationfiles and keymaps) from the Vim github repositoryhttps://github.com/vim/vim/tree/master/runtimeAnother way of downloading the runtime filesis this:    wget https://github.com/vim/vim/archive/master.tar.gz -O- |    tar zfx - vim-master/runtime/ --strip-components=1See also:https://www.vim.org/runtime.php=============================================================================faq-4SECTION 4 - HELPfaq-4.14.1. HowdoI use thehelp files?Help can be found for allfunctions of Vim. In order to use it, use the:help command.  This will bring you to the mainhelp page. On that firstpage, you will find explanations on how to move around. Basically, you movearound in thehelp pages the same way you would ina read-only document.You can jump to specific subjects by using tags. This can be done in twoways:   * Use theCTRL-] command while standing on the name ofa command     or option. This only works when thetagisa keyword.<Ctrl-LeftMouse> andg<LeftMouse> work just likeCTRL-].   * use the `:tag<subject>` command. This works with all characters.UseCTRL-T to jump back to previous positions in thehelp files. Use:q to close thehelp window.If you want to jump toa specific subject on thehelp pages, use`:help{subject}`. If you don't know what to look for, try `:help index`to getalist of all available subjects. Use the standard search keys tolocate the information you want.You can abbreviate the:help commandas:h.For searching the help, see the next Question 4.2.faq-4.2For more information, read:online-helpfaq-4.24.2. HowdoI search fora keyword in the Vimhelp files?a)  You can press theCTRL-D key after typing thehelp keyword to getalist of all thehelp keywords containing the supplied pattern. You can    also use themeta characters like *, \+, etc to specify thehelp    search pattern:    :help init<C-D>    :help str*()<C-D>    :help '*indent<C-D>b)  You can press the<Tab> key after typingapartialhelp keyword to expand    to the matching keyword. You can continue to press the<Tab> key to see    other keyword matches.c)  From thehelp window, you can use the:tag command to search for    keywords. For example,    :tselect /window    This command willlist all thehelp keywords containing the text    "window". You can select one from thelist and jump to it.d)  You can use the:helpgrep command to search for the given text in    all thehelp files. Thequickfixwindow will be opened with all the    matching lines.For more information, read:help-summaryc_CTRL-Dc_<Tab>:tselect:help:helpgrepfaq-4.34.3.I am getting an error message E123, what didIdo wrong?You can get more information about the error and the error message using:E123For more information, read:error-messagesfaq-4.44.4. Where canI read about thevarious modes in Vim?You can get information about the different modes in Vim by readingvim-modesfaq-4.54.5. HowdoI generate the Vimhelptags file after addinga new Vimhelp     file?You can use the:helptags command to regenerate the Vimhelptag filefrom within Vim. For example:    :cd $VIMRUNTIME/doc    :helptags .To update all "doc" directories in your'runtimepath', you can use:helptags ALLFor more information, read::helptagsadd-local-helpfaq-4.64.6. CanI use compressed versions of thehelp files?Yes. You cancompress thehelp files and still be able toview them withVim.  This makes accessing thehelp filesa bit slower and requires the"gzip" utility. Follow these steps tocompress and use the Vimhelp files:- Compress all thehelp files using "gzip doc/*.txt".- Edit the "doc/tags" file and change the ".txt" to ".txt.gz" using        :%s=\(\t.*\.txt\)\t=\1.gz\t=- Add the following line to your vimrc:        set helpfile={dirname}/help.txt.gzWhere{dirname}is the directory where thehelp files are.  The gzip.vimplugin supplied with the standard Vimdistribution will take care ofdecompressing the files.  Youmust make sure that$VIMRUNTIMEis set towhere the other Vim files are, when they are not in the same locationasthe compressed "doc" directory.Note, that the:helpgrep command does not work with compressedhelp pages.For more information, read:gzip-helpfile'helpfile'gzip$VIMRUNTIME=============================================================================faq-5SECTION 5 - EDITING A FILEfaq-5.15.1. HowdoI loada file in Vim for editing?There are several ways to loada file for editing. The simplestis touse the:e (:edit) command:    :e <filename>You can also use the:n (:next) command to load files into Vim:    :n <filename(s)>You can also use the:args command to load files into Vim:    :args <filename(s)>For more information, read:usr_07.txtedit-files:edit:next_f:args_ffaq-5.25.2. HowdoI save the current file in another name (save as) and edita     new file?You can use the:saveas command to save the current file in another name:    :saveas <newfilename>Alternatively, you can also use the following commands:    :w <newfilename>    :edit #You can also use the:file command, followed by:w command:    :file <newfilename>    :wFor more information, read:07.7:saveas:file_f:wfaq-5.35.3. HowdoI change the current directory to the directory of the current     file?You can use the following command to change the current directory to thedirectory of the current file:    :cd %:p:hTo automatically change the current directory to the directory of thecurrent file, simply set the option'autochdir'.    :set autochdirFor more information, read::cd:lcdfilename-modifiersautocommand'acd'getcwd()faq-5.45.4. HowdoI writea file without the line feed (EOL)at theend of the     file?You can turn off the'eol' option and turn on the'binary' option to writea file without the EOLat theend of the file:    :set binary    :set noeol    :wAlternatively, you can use:    :set noeol    :w ++binIf you rather only like Vim not to write missing EOLs, you can reset the'fixeol' option. This needsa Vim newer 7.4.785, so you should wrap thisin an if condition in your.vimrc like this:    if exists('+fixeol')        set nofixeol    endifThis has the advantage of avoiding the many side effects that the'binary' option has.For more information, read:'endofline''fixeol''binary'23.4faq-5.55.5. HowdoI configure Vim to opena fileat the last edited location?Vim stores the cursor position of the last edited location for each bufferin the'"' register. You can use the following autocmd in your.vimrc or.gvimrc file to opena fileat the last edited location:    au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") |                         \ exe "normal! g`\"" | endifAlternatively, you can simply source thevimrc_example.vim file, whichisdistributed with Vim.For more information, read:'quotelast-position-jumpvimrc_example.vimfaq-5.65.6. When editinga file in Vim, whichis being changed by an external     application, Vim opensa warningwindow (like the confirm dialog) each     timea changeis detected. HowdoI disable this warning?You can set the Vim'autoread' option to automatically read the file againwhenitis changed outside of Vim:    :set autoreadYou can also use the following autocommand:    autocmd FileChangedShell *          \ echohl WarningMsg |          \ echo "File has been changed outside of vim." |          \ echohl NoneFor more information, read:'autoread'FileChangedShelltimestamp:checktimefaq-5.75.7. HowdoI edita file whose nameis under the cursor?You can use thegf command to edita file whose nameis under the cursor.You can use theCTRL-Wf command to edit the file ina newwindow andfinally you can useCTRL-Wgf top opena newtab page that contains thefile name under the cursor.For more information, read:gfCTRL-W_fCTRL-W_gf'isfname''path''suffixesadd''includeexpr'faq-5.85.8. HowdoI reload/re-edit the current file?You can use the:edit command, without specifyinga file name, toreloadthe current file.  If you have made modifications to the file, you can use:edit! to force thereload of the current file (you will lose yourmodifications, but depending on your'undoreload' settings, thosechanges might be saved into theundo history).For more information, read::edit:edit!'confirm''undoreload'faq-5.95.9. HowdoI autosavea file periodically?Vim doesn't support auto-savinga file periodically.For more information, read:'updatetime'CursorHoldswap-filefaq-5.105.10. HowdoI opena file in read-only mode?You can opena file in read-only mode using the:view command:    :view <filename>This command sets the'readonly' option for the opened buffer. You can alsouse the "-R" command-line option to opena file in read-only mode:    $ vim -R <filename>You can also use the symbolic link executable "view" to opena file inread-only mode from the command-line:    $ view <filename>For more information, read:07.6'readonly''modifiable':view:sviewview-R-Mfaq-5.115.11. HowdoI opena file for editing without saving the modifications to      the current file?You can opena file for editing without saving the modifications to thecurrent file and without losing the changes using one of the followingmethods:    :split <new_filename>    :new <new_filename>You can also set the'hidden' option and edita new file:    :set hidden    :e <new_filename>If you want todiscard the changes made to the current file and loadanother file for editing, then you can use the following command:    :e! <new_filename>For more information, read::edit!_f'hidden':split:newfaq-5.125.12. HowdoI reduce the loading time for very large files in Vim?You can use the following settings to reduce the loading time forvery large files in Vim:    :set lazyredraw    :set noswapfile    :set undolevels=-1    :set eventignore=all    :set nohidden    :set syntax=offNote that the above settings will disable many Vim features including thefollowing: Swap files support for crash recovery,undo support,syntaxhighlighting,filetype detection and otherautocommand based features.Thereis also the LargeFileplugin availableathttps://www.vim.org/scripts/script.php?script_id=1506which automatically sets these options, when working with large files(itis configurable, whatis considered to bea large file, by default,itis 100MB).=============================================================================faq-6SECTION 6 - EDITING MULTIPLE FILESfaq-6.16.1. HowdoI open multiple filesat once from within Vim?Makea difference between args, buffers, tabs and windows. They are alldifferent things in VIM.argsisalist of arguments. Buffers are place to edit text, almostalways attached toa file but not necessarily. Windowisa place forabuffer andtabis set of windows, better name would be "layout".There are several ways to open multiple filesat once from within Vim. Youcan use the:next command to specifya group of files:    :next f1.txt f2.txt    :next *.cYou can use the:args command to specifya group of filesas arguments:    :args f1.txt f2.txt    :args *.cAfter loading the files, you can use the:next and:prev command toswitch between the files.To execute command for all files inargument-list use:argdoFor more information, read:07.2:next:args_fargument-listfaq-6.26.2. HowdoI switch between multiple files/buffers in Vim?Tolist allbuffers use:ls, tolistbuffers without file attached to(also knownas unlisted buffers, ex. scratch buffer and help-window) use:ls!There are several ways to switch between multiple files. You can use the:buffer command to switch between multiple files. You can also shortencommandas:b and use only part of the filename. For example,    :buffer file1    :buffer file2    :b e2You can also use<TAB> after:b for autocompletion. Try also:bfollowed byCTRL-D to see all available buffers. This works also for:e.You can also use theCTRL-^ key to switch between buffers. By specifyingacount before pressing the key, you can edit the buffer with that number.Without the count, you can edit the alternate buffer by pressingCTRL-^You can also use the `:e #` command to edita particular buffer:    :e #5To closea buffer use:bd -command.To execute command for all files inbuffer-list use:bufdoFor more information, read:edit-files:bufferCTRL-^alternate-file22.407.3faq-6.36.3. HowdoI open several files in Vim, with each file ina separate     window/tab?You can use the-o and-O Vim command line arguments to open multiple filesin separate horizontally or vertically split Vim windows. For example:    $ vim -o3 f1.txt f2.txt f3.txtThe above command will open the files f1.txt, f2.txt and f3.txt in threeseparate horizontally split Vim windows.    $ vim -O3 f1.txt f2.txt f3.txtThe above command will open the files f1.txt, f2.txt and f3.txt in threeseparate vertically split Vim windows.    $ vim -p f1.txt f2.txt f3.txtThe above command will open the files f1.txt, f2.txt and f3.txt in threeseparatetab windows. The option'tabpagemax' defines, how many tabpagescan be openedat the same time, by defaultitis set to 10.For more information, read:-o-O-pstartup-options'tabpagemax'faq-6.46.4. HowdoI configure Vim toautoload several filesat once similar to     "work-sets" or "projects"?You can use the:mksession and the:mkview commands toautoload severalfiles in Vim.The:mksession command createsa Vimscript that restores the currentediting session. You can use the:source command to source the fileproduced by the mksession command.The:mkview command createsa Vimscript that restores the contents ofthe current window. You can use the:loadview command to load theviewfor the current file.For more information, read:21.421.5views-sessions'sessionoptions':mksession:sourcev:this_session:mkview:loadview'viewdir'buffersfaq-6.56.5. Isit possible to open multiple top levelwindows ina single instance     of Vim similar to Nedit or Emacs?No. Itis currently not possible to open multiple top-levelwindows inasingle instance of Vim. This featureis in thetodo list.faq-6.66.6. HowdoI browse/explore directories from within Vim?You can use thenetrw.vim plugin, supplied with the standard Viminstallation, to browse/explore directories from within Vim. You can startthe file explorer using one of the following commands:    :e <directory>    :Explore    :Sexplore    :Vexplore    :TexploreFrom the file explorer, you can browse through directories, rename, deleteand edit files.For more information, read:netrw.vim22.1faq-6.76.7. HowdoI edit files overanetwork using ftp/scp/rcp/http?You can use thenetrw.vim plugin, supplied with the standard Vim package,to edit files overanetwork using ftp/scp/rcp/http. Using this plugin, Vimwill transparently load and save the files over ftp/scp/rcp/http. Forexample, to edita file over ftp, you can use the following command:    $ vim ftp://machine/pathFor more information, read:netrw.vim=============================================================================faq-7SECTION 7 - BACKUPfaq-7.17.1. WhenI edit and save files, Vim createsa file with the same nameas     the original file anda "~" characterat the end. HowdoI stop Vim     from creating this file? (or) HowdoI disable the Vimbackup file     feature?You have set the'backup' option, so Vim createsabackup file when savingthe original file. You can stop Vim from creating thebackup file, byclearing the option:    :set nobackupNote that, by default this optionis turned off. You have explicitlyenabled the'backup' option in one of theinitialization files. You mayalso have to turn off the'writebackup' option:    :set nowritebackupFor more information, read:07.4backup-table'backup''writebackup''backupskip''backupdir''backupext''backupcopy'backupfaq-7.27.2. WhenI edit and save files, Vim createsa file with the same nameas     the original file anda "un~" extensionat the end. HowdoI stop Vim     from creating this file (or) HowdoI disable the Vim undofile feature?Vim 7.3 containsas new feature persistent undo, that is,undo informationwon't be lost when quitting Vim and be stored ina file that ends with".un~" You have set the'undofile' option, so Vim creates anundo file whensaving the original file. You can stop Vim from creating thebackup file,by clearing the option:    :set noundofileNote that, by default this optionis turned off. You have explicitlyenabled the'undofile' option in one of theinitialization files. If youwant your undofiles to be stored only ina particular directory, you canpoint the'undodir' option toa directory that will contain all youraggregated undofiles.For more information, read:'undodir''undofile'undo-persistencefaq-7.37.3. HowdoI configure Vim to store all thebackup files ina particular     directory?You can configure Vim to store all thebackup files ina particulardirectory using the'backupdir' option. For example, to store all thebackup files in the ~/backup directory, you can use the following command:    :set backupdir=~/backupFor more information, read:07.4'backupdir'backupfaq-7.47.4. WhenI savea file with Vim, the file permissions are changed.     HowdoI configure Vim to savea file withoutchanging the file     permissions?This may happen, if the'backupcopy' optionis set to "no" or "auto".Notethat the default value for this optionis set in sucha way that this willcorrectly work in most of the cases. If the default doesn't work for you,try setting the'backupcopy' option to "yes" to keep the file permissionwhen savinga file:    :set backupcopy=yesThis applies, only if you have configured Vim to makeabackup wheneveroverwritinga file. By default, Vim will notbackup files.For more information, read:'backupcopy'backup'backup''writebackup'=============================================================================faq-8SECTION 8 - BUFFERSfaq-8.18.1.I have made some modifications toa buffer. HowdoI edit another     buffer without saving the modified buffer and also without losing the     modifications?You can set the'hidden' option to edita file without losing modificationsto the current file:    :set hiddenBy setting the'hidden' option, you can also save the modificationhistory(undo-history) for the buffer. Otherwise,as you switch between files, theundo-history will be lost (unless you use persistent undofiles).For more information, read:'hidden'hidden-quit:hidefaq-8.28.2. HowdoI configure Vim to auto-savea modified buffer when switching     to another buffer?You can set the'autowrite' option to auto-savea modified buffer whenswitching to another buffer:    :set autowriteFor more information, read:'autowrite''autowriteall''hidden'faq-8.38.3. HowdoI replace the buffer in the currentwindow witha blank buffer?You can use the:enew command to load an empty buffer in place of thebuffer in the current window.For more information, read::enewfaq-8.48.4. Is therea keyboard shortcut to loada buffer by the buffer number?You can use theCTRL-^ command to loada buffer by specifying the buffernumber. For example, to load buffer number 5, you have to use the 5CTRL-^command.For more information, read:CTRL-^faq-8.58.5. HowdoI open all the currentbuffers in separate windows?You can use the:ball or:sball commands to open all thebuffersin the buffer list:    :ballIf you want allbuffers to be opened in new tabs, simply prefix the:tabcommand:    :tab :sballFor more information, read::ballfaq-8.68.6. HowdoI close (delete)a buffer withoutexiting Vim?You can use any of:bdelete,:bwipeout or:bunload commands todeletea buffer withoutexiting Vim. For example:    :bdelete file1For more information, read::bdelete:bwipeout:bunloadfaq-8.78.7. WhenI use the command:%bd to delete all the buffers, not all thebuffers are deleted. Why?In the:%bd command, the "%" range will be replaced with thestarting andending line numbers in the current buffer. Instead of using "%"as therange, you should specify numbers for the range. For example, to delete allthe buffers, you can use the command:1,9999bd.For more information, read::bd(This behaviour has been fixed with patch 7.4.530)faq-8.88.8. HowdoI display the buffer number of the current buffer/file?You can use 2<CTRL-G> command to display the buffer number for the currentfile/buffer.Note the use ofcount before theCTRL-G command. If thecountis greater than 1, then Vim will display the buffer number.You can also use the following command to display the current buffernumber:    :echo bufnr("%")You can also include the "%n" field to the'statusline' option to displaythe current buffer number on the statusline.For more information, read:CTRL-Gbufnr():echo'statusline'faq-8.98.9. HowdoI deletea buffer without closing thewindow in which the     bufferis displayed?You can use the following command to open the next buffer and deletethe current buffer.    :bnext | bdelete #For more information, read::bnext:bdelete:buffersfaq-8.108.10. HowdoI map the<Tab> key to cycle through and open all the buffers?You can use the following two map commands, to map the<Ctrl-Tab> key to openthe next buffer and the<Ctrl-Shift-Tab> key to open the previous buffer:    :nnoremap <C-Tab> :bnext<CR>    :nnoremap <S-C-Tab> :bprevious<CR>Note, this might not work in theterminal version of Vim.For more information, read::bnext:bprevious=============================================================================faq-9SECTION 9 - WINDOWSfaq-9.19.1. Whatis the difference betweena Vimwindow anda buffer?A Vim bufferisa file loaded into memory for editing. The original fileremains unchanged until you write the buffer to the file.A Vimwindowisaviewport ontoa buffer. You can use multiplewindows on one buffer orseveralwindows on different buffers.For more information, read:usr_08.txt22.4windows-introQ_wifaq-9.29.2. HowdoI increase the width ofa Vim window?You can increase the width ofa Vimwindow using one of the followingcommands:    :vert resize +N    :vert resize -N    :vert resize NYou can also useCTRL-W< orCTRL-W> orCTRL-W | commands.For more information, read::vertical-resizeCTRL-W_>CTRL-W_<window-resizefaq-9.39.3. HowdoI zoom into or out ofa window?You can zoom intoawindow (close all thewindows except the currentwindow) using the "<CTRL-W>o" command or the:onlyex command.You can use the "<CTRL-W>_" command or the:resizeex command to increasethe currentwindow height to the highest possible without closing otherwindows.You can use the "<CTRL-W>|" command or the `:vertical resize`ex command toincrease the currentwindow width to the highest possible without closingother windows.You can use the "<CTRL-W>=" command to make the height and width of all thewindows equal.You can also set the followingoptions to get better results with the abovecommands:Method 1:Set the'winminheight' option to 0:    :set winminheight=0By default, this optionis set to 1.This option controls the minimum height of an inactivewindow (whenitisnot the current window).  When the'winminheight' optionis set to 0, onlythe status line will be displayed for inactive windows.Method 2:Set the'noequalalways' option and set the'winheight' option toa largevalue (like 99999):    :set noequalalways    :set winheight=99999Now, the activewindow will always open to its maximum size, while theotherwindows will stay present, but shrunken to justa status line.With any of the above mentioned methods, you cannot restore thewindowlayout after zooming intoa window.  If you want to restore the Vimwindowlayout after zooming intoa window, you can use the ZoomWin plugin. You candownload thisplugin from the Vim online website at:https://www.vim.org/scripts/script.php?script_id=508For more information, read:CTRL-W_owindow-resize'winminheight''equalalways''winheight'08.3faq-9.49.4. HowdoI execute anex command on all the openbuffers or openwindows     or all the files in the argument list?You can use the:bufdo command to execute anex command on all the openbuffers.  You can use the:windo command to execute anex command on allthe open windows.  You can use the:argdo command to execute anexcommand on all the files specified in the argument list. And finally youcan use the:tabdo command to execute anex command in all opentab pages.For more information, read::windo:bufdo:argdo:tabdo26.3=============================================================================faq-10SECTION 10 - MOTIONfaq-10.110.1. HowdoI jump to the beginning (first line) orend (last line) ofa     file?You can use "G" command to jump to the last line in the file and the "gg"command to jump to the first line in the file.For more information, read:Gggfaq-10.210.2. Ininsert mode, whenI press the<Esc> key togo to command mode, the     cursor moves one character to the left (except when the cursoris on     the first character of the line). Isit possible to change this     behavior to keep the cursorat the same column?No. Itis not possible to change this behavior. The cursoris alwayspositioned ona valid character (unless you have virtual-edit modeenabled). So, if you are appending text to theend ofa line, when youreturn to command mode the cursormust drop back onto the last characteryou typed. For consistency sake, the cursor drops back everywhere, even ifyou are in the middle ofa line.You can use theCTRL-O orCTRL-\CTRL-O command ininsert mode to executeasingleex command and return back toinsert mode without moving the cursorcolumn.For more information, read:'virtualedit'i_CTRL-Oi_CTRL-\_CTRL-Ofaq-10.310.3. HowdoI configure Vim to maintain the horizontal cursor position whenscrolling with the <Page Up>, <Page Down>, etc keys?You can reset the'startofline' option to keep the cursorat the samehorizontal location whenscrolling text:    :set nostartoflineFor more information, read:'startofline'faq-10.410.4. Some lines ina file are more than the screen width and they are all     wrapped. WhenI use the j,k keys to move from one line to the next,     the cursoris moved to the next line in the file instead of the next     line on the screen. HowdoI move from one screen line to the next?You can use thegj andgk commands to move from one screen line to thenext/previous screen line. Thej andk commands move the cursor from onefile line to the next file line. You can also avoid the line wrapping byresetting the'wrap' option:    :set nowrapFor more information, read:gjgk'wrap'You can use the following mappings:    :map <Up> gk    :imap <Up> <C-o>gk    :map <Down> gj    :imap <Down> <C-o>gj    :noremap j gj    :noremap k gkfaq-10.510.5. Whatis the definition ofa sentence,paragraph andsection in Vim?Asentenceis definedas endingata ".", "!" or "?" followed by either theend ofa line, or byaspace (or two) or tab. Which characters and thenumber of spaces needed to constituteasentence endingis determined bythe'joinspaces' and'cpoptions' options.Aparagraph begins after each empty line, and alsoat each ofa set ofparagraph macros, specified by the pairs of characters in the'paragraphs'option.Asection begins aftera form-feed (<C-L>) in the first column andat eachofa set ofsection macros, specified by the pairs of characters in the'sections' option.For more information, read:sentence'joinspaces''cpoptions'paragraphsectionwordfaq-10.610.6. HowdoI jump to beginning orend ofa sentence,paragraph ora     section?You can use the following motion commands to jump to the beginning orendofasentence oraparagraph ora section:      motion  position    where      ------  ---------   -----------------(       beginning   currentsentence)end         currentsentence{       beginning   currentparagraph}end         currentparagraph[]end         previoussection[[      beginning   currentsection][end         currentsection]]      beginning   nextsectionEach of these motions can be preceded bya number which will extend thejump forward (or backward).For more information, read:object-motionsfaq-10.710.7.I have lines ina file thatextends beyond the right extent of the     screen. HowdoI move the Vimview to the right to see the text off     the screen?You can use one of the following commands to horizontally scroll the screento the left or right:    cmd  scroll to    ---  --------------------------zl   scroll to the leftzh   scroll to the rightzL   scroll halfa screenwidth to the leftzH   scroll halfa screenwidth to the rightzs   scroll to position the cursorat the start of the screenze   scroll to position the cursorat theend of the screenYou can use theg0 command to move the cursor to the first character of thescreen line and theg$ command to move the cursor to the last character ofthe screen line withoutscrolling the screen.For more information, read:scroll-horizontalfaq-10.810.8. HowdoI scroll two or morebuffers simultaneously?You can set the'scrollbind' option for each of thebuffers to scroll themsimultaneously.For more information, read:'scrollbind'scroll-binding'scrollopt''cursorbind'faq-10.910.9. WhenI use my arrow keys, Vim changes modes, inserts weird characters     in my document but doesn't move the cursor properly. What's going on?There area couple of things that could be going on: either you are usingVim overa slow connection or Vim doesn't understand the key sequence thatyour keyboardis generating.If you are working overa slow connection (suchasa 2400 bps modem), youcan try to set the'timeout' or'ttimeout' option. These options, combinedwith the'timeoutlen' and'ttimeoutlen' options, may fix the problem.The preceding procedure will not work correctly if yourterminal sends keycodes that Vim does not understand. In this situation, your best optionisto map your key sequence toa matching cursormovement command and savethese mappings ina file. You can then:source the file whenever you workfrom that terminal.For more information, read:'timeout''ttimeout''timeoutlen''ttimeoutlen':mapvt100-cursor-keysfaq-10.1010.10. HowdoI configure Vim to move the cursor to theend of the previous      line, when the left arrow keyis pressed and the cursoris currentlyat the beginning ofa line?You can add the "<" flag to the'whichwrap' option to configure Vim to movethe cursor to theend of the previous line, when the left arrow keyispressed and the cursoris currentlyat the beginning ofa line:    :set whichwrap+=<Similarly, to move the cursor the beginning of the next line, when theright arrow keyis  pressed and the cursoris currentlyat theend ofaline, add the ">" flag to the'whichwrap' option:    :set whichwrap+=>The above will work only in normal and visual modes. To use this ininsertand replace modes, add the "[" and "]" flags respectively.For more information, read:'whichwrap'05.7faq-10.1110.11. HowdoI configure Vim to stay only ininsert mode (modeless      editing)?You can set the'insertmode' option to configure Vim to stay only ininsertmode:    :set insertmodeBy setting this option, you can use Vimasa modeless editor. If you pressthe<Esc> key, Vim will notgo to the normal mode. To executea singlenormal mode command, you can pressCTRL-O followed by the normal modecommand.  To execute more than one normal command, you can useCTRL-Lfollowed by the commands. To return toinsert mode, press the<Esc> key. Todisable this option, reset the'insertmode' option:    :set noinsertmodeYou can also start vim using the "evim" command or you can use "vim-y" touse Vimasa modeless editor.You can also start Vim ininsert mode using the:startinsertex command.For more information, read:'insertmode':startinsert:stopinserti_CTRL-Oi_CTRL-Levimevim-keysfaq-10.1210.12. HowdoI display some context lines whenscrolling text?You can set the'scrolloff' option to displaya minimal number of screenlines (context) above and below the cursor.    :set scrolloff=10For more information, read:'scrolloff''sidescrolloff'faq-10.1310.13. HowdoIgo back to previous cursor locations?You cango back to the cursor location before the latest jump using the''or`` command. You can use theCTRL-O command togo back to older cursorpositions and theCTRL-I command togo to the newer cursor positions in thejump list.For more information, read:03.10mark-motionsjump-motions=============================================================================faq-11SECTION 11 - SEARCHING TEXTfaq-11.111.1. AfterI searched fora text witha pattern, all the matched text      stays highlighted. HowdoI turn off the highlighting      temporarily/permanently?The'hlsearch' option controls whether all the matches for the lastsearchedpattern are highlighted or not. By default, this optionis notenabled. If this optionis set ina system-widevimrc file, then you canturn off the search highlighting by using the following command:    :set nohlsearchTo temporarily turn off the search highlighting, use    :nohlsearchYou can also clear the search highlighting, by searching forapattern thatis not in the current file (for example, search for thepattern "asdf").You can use this mapping, to clear the search highlighting whenredrawing thewindow pressingCTRL-L    :nnoremap <silent> <C-L> <C-L>:nohls<CR>For more information, read:'hlsearch':nohlsearchfaq-11.211.2. HowdoI entera carriage return character ina search pattern?You can either use "\r" or<CTRL-V><CTRL-M> to entera carriage returncharacter ina pattern. In Vim scripts,itis better to use "\r" for thecarriage return character.For more information, read:sub-replace-specialfaq-11.311.3. HowdoI search for the character ^M?You can enter the ^M character ina search command by first pressing theCTRL-V key and then pressing theCTRL-M key.    /^V^MYou can also use the "\r" character. In Vim scripts, "\r"is preferred.For more information, read:c_CTRL-Vusing_CTRL-V/\rfaq-11.411.4. How canI search/replace characters that displayas "~R", "~S", etc.?You can use the "ga" command to display the ASCII value/code for thespecial character. For example, let us say the ASCII valueis 142. Then youcan use the following command to search for the special character:    /^V142where, ^Vis entered by pressingCTRL-V.For more information, read:gausing_CTRL-V24.8faq-11.511.5. HowdoI highlight all the non-printable characters ina file?You can use the following commands and searchpattern to highlight all thenon-printable characters ina file:    :set hlsearch    /\(\p\|$\)\@!.For more information, read:/\p/bar/$/\(/\@!'hlsearch'faq-11.611.6. HowdoI search for whole words ina file?You can search for whole words ina file using the \< and \> atoms. Forexample:    /\<myword\>The \< atom matches the beginning of theword and the \> atom matches theend of the word.For more information, read:/\</\>faq-11.711.7. HowdoI search for the currentword under the cursor?You can press the * key to search forward for the currentword under thecursor.  To search backward, you can press the# key.Note that only wholekeywords will be searched using these commands.For more information, read:star#gstarg#03.8search-commandsfaq-11.811.8. HowdoI search foraword without regard to thecase (uppercase or      lowercase)?To always ignorecase while searching fora pattern, set the'ignorecase'option:    :set ignorecaseTo ignorecase only when searchinga particular pattern, use the special \cdirective:    /\c<pattern>For more information, read:'ignorecase'/ignorecase/\cfaq-11.911.9. HowdoI search for words that occur twice consecutively?You can use one of the following search commands to locate words that occurtwice consecutively:     /\(\<\w\+\)\_s\+\1\>     /\(\<\k\+\)\_s\+\1\>The main differenceis the use of "\w" and "\k", where the latteris basedon the'iskeyword' option which may include accented and other languagespecific characters.For more information, read:/\1/\(/\)/\</\>/\w/\k/\+/\_x'iskeyword'faq-11.1011.10. HowdoIcount the number of timesa particularword occurs ina       buffer?You can use the following set of commands tocount the number of timesaparticularword occurs ina buffer:    :let cnt=0    :g/\<your_word\>/let cnt=cnt+1    :echo cntThis only counts the number of lines where theword occurs. You can alsouse the following command:    :%s/\<word\>/&/gnTocount the number of alphabetic words ina file, you can use    :%s/\a\+/&/gnTocount the number of words made up of non-space characters, you can use    :%s/\S\+/&/gnFor more information, read:count-itemsword-countv_g_CTRL-G12.5:s_flagsfaq-11.1111.11. HowdoI place the cursorat theend of the matchedword when       searching fora pattern?You can use the "e" offset to the search command to place the cursorat theend of the matched word. For example    /mypattern/eFor more information about search offsets, read:search-offset/faq-11.1211.12. HowdoI search for an empty line?You can search for an empty line using:    /^$    or    /^\s*$The latter also matches lines, that consist only of white space, while theformer only matchestrue empty lines. For more information, read:/^/$/\s/starsearch-commandsfaq-11.1311.13. HowdoI search fora line containing onlya single character?You can search fora line containing onlya single character using:    /^\s*\a\s*$For more information, read:/^/\a/\s/star/$faq-11.1411.14. HowdoI search and replaceastring in multiple files?You can use the:argdo,:bufdo,:windo or:tabdo commands to executeanex command on multiple files. For example:    :argdo %s/foo/bar/g|updFor more information, read::argdo:bufdo:windo:tabdofaq-11.1511.15.I am using the:s substitute command ina mapping. Whena search       forapattern fails, the map terminates.I would like the map to       continue processing the next command, even if the substitute command       fails. HowdoIdo this?You can use the "e" flag to the substitute command to continue processingother commands ina map, whenapatternis not found.For more information, read::s_flagsfaq-11.1611.16. HowdoI search for the n-th occurrence ofa character ina line?To search for the n-th occurrence ofa character ina line, you can prefixthe "f" command witha number. For example, to search for the 5thoccurrence of the character@ ina line, you can use the command 5f@. Thisassumes the cursorisat the beginning of the line- and that this firstcharacteris not the one your are looking for.For more information, read:fFtT;,faq-11.1711.17. HowdoI replaceatab (or any other character) witha hard return       (newline) character?You can replaceatab (or any other character) witha hard return (newline)character using the following command:    :s/\t/\r/Note that in the above command, if you use \n instead of \r, then thetabcharacters will not be replaced bya new-line character.For more information, read:sub-replace-specialNL-used-for-NulCR-used-for-NLfaq-11.1811.18. HowdoI search fora character by its ASCII value?You can search fora character by its ASCII value by pressingCTRL-Vfollowed by the decimal or hexadecimal oroctal value of that character inthe search "/" command.  To determine the ASCII value ofa character youcan use the:ascii or the "ga" command.For example, to search for the ASCII character with value 188, you canuse one of the following search commands:    /<CTRL-V>188    /<CTRL-V>o274    /<CTRL-V>xBC    /<CTRL-V>u00bcYou can also search for the character with the decimal/octal/hex numberusinga collation[] like this:    /[\d188]    /[\o274]    /[\xbc]    /[\u00bc]Alternatively, you can use the special atom \%d \%o \%x \%u:    /\%d188    /\%o274    /\%xbc    /\%u00bcOr you usedigraphs to enter the character. For example enter:    /CTRL-K14to search for the above character.For more information, read:i_CTRL-V_digit:asciiga/\]/\%ddigraphsfaq-11.1911.19. HowdoI search for long lines?You can search for long lines or lines containing more thana specificnumber of characters using the Vim regular-expressions in the searchcommand. For example, to search for all the lines containing more than 80characters, you can use one of the following commands:    /^.\{80}.\+$    /^.*\%>80c.*$    /^.*\%>80v.*$For more information, read:/\{/\%c/\%vfaq-11.2011.20. HowdoI display all the lines in the current buffer that containa       specified pattern?You can use the following command to display all the lines in the currentbuffer that containa specified pattern:    :g/<pattern>/pFor example, the following command will display all the lines in thecurrent buffer that contain "vim":    :g/vim/pSince:pis the default command to be executed for theex command:g, youcan also use:    :g/vimIf you also want the corresponding line numbers, then you can use thefollowing command:    :g/<pattern>/#For more information, read::global:print:numberfaq-11.2111.21. HowdoI search fora textstring that spans multiple lines?You can search fora textstring that spans multiple lines using the \_xregularexpression atom. For example, to search for the textstring "HelloWorld", you can use the following search command:    /Hello\_sWorldThis will match theword "Hello" followed bya newline character and thentheword "World"at the beginning of the next line. This will also matchtheword "Hello" immediately followed byaspace character and then theword "World". When searching for the "Hello World" string, to include thespace charactersat theend and beginning of the line, you can use thefollowing search command:    /Hello\_s\+WorldFor more information, read:27.8pattern-atoms/\_pattern-searchesfaq-11.2211.22. HowdoI search forapattern within the specified range of lines       ina buffer?You can search forapattern withina range of lines using the \%>land \%<l regularexpression atoms.For example, to search for theword "white" between the lines 10 and 30 ina buffer, you can use the following command:    /white\%>9l\%<31lFor more information, read:/\%lfaq-11.2311.23. HowdoI clear the last searched pattern?The last searchedpatternis stored in the "/" register. You can clearthis register using the following command:    :let @/=""To clear the last searchpattern whenevera bufferis unloaded, you can usethe following command:    :autocmd BufUnload * let @/ = ""For more information, read:@/:let-@autocmd-searchpatlast-patternfaq-11.2411.24. Why does thispattern "a.\{-}p\@!" not match?"\{-}" doesn't just mean "as fewas possible",it means "as fewaspossible to make the wholepattern succeed". Ifit didn't match the "p",the wholepattern would fail (because of the "p\@!") soit does matchthe "p". Itisa longer match, butitis the shortest match that makesthe wholepattern succeed.If you wanted "as fewas possible regardless" you would use "\@>", whichbasically dividesapattern up so that the pieces either side behaveindependently. If thepattern were "a.\{-}\@>p\@!" then ".\{-}" wouldalways match nothing because that's the smallest match that can succeedwhen there are not other restrictions. The wholepattern then wouldbehave the sameas "ap\@!", i.e.it would match any "a" not followed bya "p").This means,it matchesas fewas possible "a"s without trying to keepgoing until Vim finds the longest match. This means,it will still match"ap".faq-11.2511.25. How canI use "/" withina pattern, without escaping it?When using/ to search fora pattern, you need toescape all "/" withinthe pattern, because they would otherwise terminate the pattern. So youcan't directly search for /usr/share/doc/ but need to search for\/usr\/share\/doc\/The easiest solution around that, would be to use "?" to startabackward search and afterwards use/<CR> to use the lastsearch-patternin forward direction.If you havea Vim, that has the eval-feature built in (which needsatleasta normal built or higher), you can also directly paste thepatterninto the search register::let@/= '/usr/share/doc/'Then use "n" to jump to the next occurrence.See also thehelpat@//<CR>faq-11.2611.26. How canI operate ona search match?The "gn" command makesiteasy to operate on regions of text that matchthe current search pattern. By default,it will search forward for thelast used searchpattern and visually select the match. If the cursorisalready on the match,it will be visually selected. If you used the "gn"command after anoperator (e.g. "c" to change text),it will be appliedon the match.IfVisual modeis active before using gn, the visual selection will beextended until theend of the next match.The "gN" commands works similar but searches backwards.This allows to repeat simple operations on each match. For example, youmight want to change each occurence of apples by peaches. So you searchusing "/apple" then you can use "cgnpeach<Esc>" to replace the currentmatch by peach. Now you can use the dot "." command toredo thereplacement for the rest of the buffer.See also thehelpatgngN=============================================================================faq-12SECTION 12 - CHANGING TEXTfaq-12.112.1. HowdoI delete all the trailing whitespace characters (SPACE and      TAB)at theend of all the lines ina file?You can use the:substitute command on the entire file to search andremove all the trailing whitespace characters:    :%s/\s\+$//For more information, read::%:s/\s/\+/$faq-12.212.2. HowdoI replace all the occurrences of multiple consecutivespace      characters toa single space?You can use the following command to replace all the occurrences ofmultiple consecutivespace characters toa single space:    :%s/ \{2,}/ /gAlternatively use:    :%s/  \+/ /gFor more information, read::%:s/\{:s_flagsfaq-12.312.3. HowdoI reducea range of empty lines into one line only?You can use the following command to reducea range of empty lines into oneline only:    :v/./.,/./-1joinThe explanation for this commandis below:    part            description    -----           --------------------------    :v/./           Execute the following command for all lines not                    containinga character (empty lines).     .,             Use the current lineas the start of the range of                    lines.     /./            Use the line containinga characteras the last line.     -1             Adjust the range of lines toend with the line before                    the last line.j              Join the lines in the range.Note that this will give an error message if the empty lines areat theendof the file. To correct this, you have to adda temporary lineat theendof the file, execute the command and then remove the temporary line.For more information, read::v:joincmdline-rangescollapsefaq-12.412.4. HowdoI delete all blank lines ina file? HowdoI remove all the      lines containing onlyspace characters?To remove all blank lines, use the following command:    :g/^$/dTo remove all lines with onlywhitespace (spaces or tabs) in them, use thefollowing command:    :g/^\s\+$/dTo remove all the lines with only whitespace, if anything, use thefollowing command:    :g/^\s*$/dfaq-12.512.5. HowdoI copy/yank the current word?You can use the "yiw" (yank innerword without whitespace) command or the"yaw" (yankaword with whitespace) command to copy/yank the currentword.For more information, read:04.604.8iwyanktext-objectsobjectsfaq-12.612.6. HowdoIyank text from one position to another position withina      line, without yanking the entire line?You can specifya motion command with theyankoperator (y) toyank textfrom one position to another position withina line. For example, toyankfrom the current cursor position till the nextletter x, use yfx or Fx ortx or Tx. Toyank till the nth column, usen|. Toyank till the nextoccurrence ofa "word", use /word. Todoayank till the nth column onanother line, firstmark the position using the "ma" command,go to thestart of theyank position, and thenyank till themark using y`a (note thedirection of the quote)For more information, read:yankmotion.txt04.6faq-12.712.7. WhenIyank some text intoa register, howdoI append the text to      the current contents of the register?When you specify the register for some operation, if you use the upper-casefor the register name, then the new text will be appended to the existingcontents. For example, if you have some text in the register "a". If youwant to append some new text to this, you have to use the "A" registername. If you use thelowercase register name, then the contents of theregister will be overwritten with the new text.For more information, read:quotequote_alpha10.1faq-12.812.8. HowdoIyanka completesentence that spans over more than one line?Toyanka completesentence that spans over more than one line you have touse theyankoperator followed bya motion command. For example:        y)From inside thesentence you can use "yi)" toyank the sentence.For more information, read:yank{motion}object-motions04.6faq-12.912.9. HowdoIyank all the lines containingapattern intoa buffer?You can use the:global command toyank all the lines containing thepattern intoa register and then paste the contents of the register intothe buffer:    :let @a=''    :g/mypattern/y AThe first command, clears the contents of the register "a". The secondcommand copies all the lines containing "mypattern" into the register "a".Note that the capitalletter "A"is used to append the matched lines. Nowyou can paste the contents of register "a" toa buffer using "ap command.If you only want to collect all matches, you can usea differentapproach. For that run the:s command with the flags "gn" so thatitwon't actually  change the buffer("n" flag) but select each match("g"flag). Combining this with the "\=" part in the replacement part, youcan copy each match to e.g.a list. Altogether this looks like this:    :let list=[]    :%s/pattern/\=add(list, submatch(0))/gnNow all matches will be in thelist and you can post process themaswanted.For more information, read::g:y:let-registerquote_alphaputregisters:registerssub-replace-\=faq-12.1012.10. HowdoI delete all the lines ina file thatdo not containa       pattern?You can use:v command to delete all the lines thatdo not containapattern:    :v/pattern/dor    :g!/pattern/dFor more information, read::v:gfaq-12.1112.11. HowdoI adda line before each line with "pattern" in it?You can use the following command to adda line before each line with"pattern" in it:    :g/pattern/normal! Oi<line of text goes here>Alternatively you canyank the line using theY command and theninsert theline using the following command:    :g/pattern/put!For more information, read::g:putinsert0faq-12.1212.12. Is therea way to operate ona line if the previous line containsa       particular pattern?You can use the:global command to operate ona line, if the previousline containsa particular pattern:    :g/<pattern>/+{cmd}For more information, read::g:rangefaq-12.1312.13. HowdoI executea command on all the lines containinga pattern?You can use the:global (:g) command to executea command on all thelines containinga pattern.    :g/my pattern/dIf you want to usea non-Ex command, then you can use the:normalcommand:    :g/my pattern/normal {command}Unless you want the normal mode commands to be remapped, consider usinga:normal! command instead (note the "!").For more information, read::global:v:normalfaq-12.1412.14. CanI copy the character above the cursor to the current cursor       position?InInsert mode, you can copy the character above the cursor to the currentcursor position by typingCTRL-Y. The same can be done with thecharacters below the cursor by typingCTRL-E.For more information, read:i_CTRL-Yi_CTRL-Efaq-12.1512.15. HowdoIinserta blank line above/below the current line without       enteringinsert mode?You can use the:putex command toinsert blank lines. For example, try    :put =''    :put! =''For more information, read::putfaq-12.1612.16. HowdoIinsert the name of the current file into the current buffer?There are several ways toinsert the name of the current file into thecurrent buffer. Ininsert mode, you can use the<C-R>% or the<C-R>=expand("%") command. In normal mode, you can use the `:put =@%`command.For more information, read:i_CTRL-Rexpand()!!faq-12.1712.17. HowdoIinsert the contents ofa Vim register into the current       buffer?Ininsert mode, you can use the<CTRL-R><register> command toinsert thecontents of<register>. For example, use<CTRL-R>a toinsert the contentsof register "a" into the current buffer.In normal mode, you can use the `:put<register>` command toinsert thecontents of<register>. For example, use the `:put d` command toinsertthe contents of register "d" into the current buffer.For more information, read:i_CTRL-Ri_CTRL-R_CTRL-Ri_CTRL-R_CTRL-Oi_CTRL-R_CTRL-P:putfaq-12.1812.18. HowdoI move the cursor past theend of line andinsert some       charactersat some columns after theend of the line?You can set the'virtualedit' option to move the cursor past theend-of-line andinsert characters ina column after the end-of-line. Tostart the virtual mode, use    :set virtualedit=allFor more information, read:'virtualedit'faq-12.1912.19. How to replace theword under the cursor (say: junk) with      "foojunkbar" in Vim?There are several ways todo this. If thewordis the first suchword onthe line, use the following command:    :exe "s/".expand("<cword>")."/foo&bar/"To match specifically you could usea more complex substitution like this:    :exe 's/\<'.expand("<cword>").'\%>'.(col(".")-1).'c\>/foo&bar/'You can also use the command: ciwfoo<C-R>"bar<Esc>For more information, read::substituteexpand()col()/\%cfaq-12.2012.20. HowdoI replacea particular text in all the files ina directory?You can use the:argdo command to execute the substitute command on allthe files specifiedas arguments:    :args *    :argdo %s/<your_text>/<replacement_text>/ge | updateFor more information, read::args_f:argdo:s_flagsfaq-12.2112.21.I have some numbers ina file. HowdoI increment or decrement the       numbers in the file?You can use theCTRL-A key to increment the number and theCTRL-X key todecrement the number. You can also specify the number toincrement/decrement from the number by specifyingacount to the key. Thisworks for decimal,octal and hexadecimal numbers. You can change the baseused by Vim for this operation by modifying the'nrformats' option.For more information, read:26.2CTRL-ACTRL-X'nrformats'faq-12.2212.22. HowdoI reuse the last used searchpattern ina:substitute       command?To reuse the last used searchpattern ina:substitute command, don'tspecifya new search pattern:    :s/pattern/newtext/    :s//sometext/In the second:s command,asa searchpatternis not specified, thepattern specified in the first:s command "pattern" will be used.If you want to change the searchpattern but repeat the substitutionpattern you can use the special right hand side, you can use the tildecharacter:    :s/newpattern/~/For more information, read::s:&:~&sub-replace-specialfaq-12.2312.23. HowdoI change thecase ofastring using the:substitute       command?You can use special characters in the replacementstring fora:substitute command to change thecase of the matched string. Forexample, to change thecase of thestring "MyString" to all uppercase, youcan use the following command:    :%s/MyString/\U&/gTo change thecase to lowercase, you can use the following command:    :%s/MyString/\L&/gTo change thecase of the first character in all the words in the currentline to uppercase, you can use the following command:    :s/\<\(.\)\(\k*\)\>/\u\1\L\2/gFor more information, read:sub-replace-special:substitute/\U/\L/\ufaq-12.2412.24. HowdoI enter characters that are not present in the keyboard?You can usedigraphs to enter characters that are not present in thekeyboard. You can use the:digraphs command to display all the currentlydefined digraphs. You can adda newdigraph to thelist using the:digraphs command.For more information, read:digraphs'digraph'24.9faq-12.2512.25. Is therea command to remove any or all digraphs?No. Thedigraphs tableis definedat compile time. You can only add newones. Addinga command to removedigraphsis on thetodo list.faq-12.2612.26. Ininsert mode, whenI press thebackspace key,it erases only the       characters entered in this instance ofinsert mode. HowdoI erase       previously entered characters ininsert mode using thebackspace       key?Thisis traditionalvi behaviour. You can set the'backspace' option toerase previously entered characters ininsert mode:    :set backspace=indent,eol,startFor more information, read:'backspace'i_backspacingfaq-12.2712.27.I havea file which has lines longer than 72 characters terminated       with "+" and wrapped to the next line. How canI quickly join the       lines?You can use the:global command to search and join the lines:    :g/+$/jThis will, however, only join every second line.A couple of more complexexamples which will join all consecutive lines witha "+"at theend are:    :g/+$/,/\(^\|[^+]\)$/j    :g/+$/mark a | .,/\(^\|[^+]\)$/s/+$// | 'a,.jFor more information, read::g:j:markfaq-12.2812.28. HowdoI pastecharacterwise yanked text into separate lines?You can use the:put command to pastecharacterwise yanked text into newlines:    :put =@"For more information, read::putquote_=faq-12.2912.29. HowdoI change thecase (uppercase, lowercase) ofaword ora       character ora block of text?You can use the "~" command to switch thecase ofa character.You can change thecase of theword under the cursor touppercase using the"gUiw" or "viwU" command and tolowercase using the "guiw" or "viwu"command.You can switch thecase (uppercase to lowercase and vice versa) of theword under the cursor using the "viw~" or "g~iw" command.You can use the "gUgU" command to change the current line touppercase andthe "gugu" command to change the current line to lowercase.You can use the "g~g~" command to switch thecase of the current line. Youcan use the "g~{motion}" or "{Visual}~" commands to switch thecase ofablock of text.If you set'tildeop' the "~" command behaves like anoperator and expectsa motion command to act on. If you have    :set tildeopand you want to change thecase from the current cursor position to theendof line, simply use "~$".For more information, read:case'tildeop'faq-12.3012.30. HowdoI enter ASCII characters that are not present in the       keyboard?You can enter ASCII characters that are not present in the keyboard bypressingCTRL-V and then the ASCII character number. You can also usedigraphs to enter special ASCII characters.For more information, read:i_CTRL-V_digitdigraphs45.5faq-12.3112.31. HowdoI replace non-printable characters ina file?To replacea non-printable character, you have to first determine the ASCIIvalue for the character. You can use the:asciiex command or the "ga"normal-mode command to display the ASCII value of the character under thecursor.You can enter the non-printable character by enteringCTRL-V followed bythe decimal number 1-255 (with no leading zero), or byx anda hex number00-FF, or by anoctal number 0-0377 (with leading zero), or byu anda hexnumber 0-FFFF, or byU anda hex number 0-7FFFFFFFAnother alternativeis to use the:digraphsex command to display thedigraphs for all characters, together with their value in decimal andalpha. You can entera non-printable character by enteringCTRL-K followedby two alphanumeric characters (a digraph).For more information, read::asciii_CTRL-Vi_CTRL-V_digit:digraphsfaq-12.3212.32. HowdoI remove duplicate lines froma buffer?You can use the following user-defined command to remove all the duplicatelines froma buffer::command -range=% Uniq<line1>,<line2>g/^\%<<line2>l\(.*\)\n\1$/dAdd the above command to your.vimrc file and invoke:Uniq to remove allthe duplicate lines.faq-12.3312.33. HowdoI prefix all the lines ina file with the corresponding line       numbers?You can prefix the lines ina file with the corresponding line number inseveral ways. Some of them are listed below:    :%s/^/\=line('.'). ' '    :%s/^/\=printf('%5d ', line('.'))/    :%s/^/\=strpart(line('.').'.     ', 0, 5)    :%s/^/\=strpart('   ', strlen(line('.'))).line('.').'. 'The last two commands will pad the line numbers withspace characters.  Thelast command will right align the numbers and the command before that willleft align the numbers.If you don't want to number consecutive lines but rather non-consecutiveregions, you can also use this idiom:    :let i = 1    :g/TODO/s/^/\=printf('%2d.',i)|let i+=1This first initializes the variablei with 1. In the next line,a:gcommandis used to performa substitute command only on lines, thatmatch "TODO". After the substitute command has taken place, the variablei will be incremented by 1.For more information, read:sub-replace-specialline()expr6strpart()printf():execute:globalfaq-12.3412.34. HowdoI exchange (swap) two characters or words or lines?You can exchange two characters with the "xp" command sequence. The "x"will delete the character under the cursor and "p" will paste the justdeleted character after the character under the cursor. This will resultin exchanging the two characters.You can exchange two words with the "deep" command sequence (start with thecursor in the blankspace before the first word).You can exchange two lines with the "ddp" command sequence. The "dd" willdelete the current line and "p" will paste the just deleted line after thecurrent line. This will result in exchanging the two lines.All of the above operations will change the " unnamed register.You can use the `:m +`ex command to exchange two lines withoutchanging theunnamed register.For more information, read:xpdddelinewise-registerquotequote:movefaq-12.3512.35. HowdoI change the characters usedasword delimiters?Vim uses the characters specified by the'iskeyword' optionasworddelimiters. The default setting for this optionis "@,48-57,_,192-255".For example, to add ":"asaword delimiter, you can use    :set iskeyword+=:To remove "_"asaword delimiter, you can use    :set iskeyword-=_For more information, read:'iskeyword'word=============================================================================faq-13SECTION 13 - COMPLETION IN INSERT MODEfaq-13.113.1. HowdoI complete words or lines ininsert mode?Ininsert mode, you can complete words using theCTRL-P andCTRL-N keys.TheCTRL-N command searches forward for the next matching keyword.TheCTRL-P command searches backwards for the next matching keyword.Ininsert mode, you can use theCTRL-XCTRL-L command sequence to completelines that starts with the same charactersas in the current line beforethe cursor. To get the next matching line, press theCTRL-P orCTRL-N keys.There area lot of other keys/ways available to complete words ininsertmode.Vim supports completion of the following items:    CTRL-X CTRL-L    whole lines    CTRL-X CTRL-N    keywords in the current file    CTRL-X CTRL-K    words from a dictionary    CTRL-X CTRL-T    words from a thesaurus    CTRL-X CTRL-I    current and included files    CTRL-X CTRL-]    tags    CTRL-X CTRL-F    file names    CTRL-X CTRL-D    macro definitions (also in included files)    CTRL-X CTRL-V    Vim command line    CTRL-X CTRL-U    User defined completion    CTRL-X CTRL-O    Omni completionUser defined completions and omni completions are often set byfiletypeplugins.For more information, read:24.3ins-completionfaq-13.213.2. HowdoI complete file names ininsert mode?Ininsert mode, you can use theCTRL-XCTRL-F command sequence to completefilenames that start with the same charactersas in the current line beforethe cursor.For more information, read:compl-filenamefaq-13.313.3.I am usingCTRL-P/CTRL-N to complete words ininsert mode. HowdoI      complete words that occur after the just completed word?You can useCTRL-XCTRL-N andCTRL-XCTRL-P keys to complete words that arepresent after the just completed word.For more information, read:i_CTRL-X_CTRL-Pi_CTRL-X_CTRL-Nins-completion=============================================================================faq-14SECTION 14 - TEXT FORMATTINGfaq-14.114.1. HowdoI formata textparagraph so thata new lineis insertedat      theend of each wrapped line?You can use the "gq" command to formata paragraph. This will format thetext according to the current'textwidth' setting. An alternative would beto use the "gw" command that formats like "gq" but does not move thecursor.Note that thegqoperator can be used witha motion command to operate onarange of text. For example:    gqgq - Format the current line    gqap - Format current paragraph    gwap - Format current paragraph (and don't move cursor)    gq3j - Format the current and the next 3 linesFor more information, read:gqgwformattingusr_25.txtmotion.txtfaq-14.214.2. HowdoI format long lines ina file so that each line containsless      than "n" characters?You can set the'textwidth' option tocontrol the number of characters thatcan be present ina line. For example, to set the maximum width ofa lineto 70 characters, you can use the following command:    set textwidth=70Now to break the long lines ina file to the length defined by the'textwidth' option, you can use    :g/./normal gqqFor more information, read:'textwidth'gqfaq-14.314.3. HowdoI join short lines to forma paragraph?First, make sure the'textwidth' optionis set toa high value:    :set textwidth=99999Next, join the short lines to formaparagraph using the command:    1GgqGThe above command will operate on the entire file. Todo theformatting onall paragraphs ina specific range, use:    :'a,'bg/\S/normal gq}For more information, read:gqGgqqfaq-14.414.4. HowdoI format bulleted and numbered lists?You can configure Vim to format bulleted and numbered lists using the'formatoptions' option. For example, you can format thelist of thefollowing format:- thisisa test. thisisa test. thisisa test. thisisa test.  thisisa test.into this format:- thisisa test. thisisa test. thisisa test. thisisa test.    thisisa test.You can use the "n" flag in the'formatoptions' to align the text.    :set fo+=nWith this option, whenformatting text, Vim will recognize numbered lists.For this option to work, the'autoindent' option alsomust be set.For more information, read:'formatoptions'fo-tableformat-commentsfaq-14.514.5. HowdoI indent lines ininsert mode?Ininsert mode, you can press theCTRL-T key toinsert one shiftwidth ofindentat the start of the current line. Ininsert mode, you can use theCTRL-D key to delete on shiftwidth of indentat the start of the currentline. You can also use theCTRL-O>> andCTRL-O<< commands to indent thecurrent line ininsert mode.For more information, read:i_CTRL-Ti_CTRL-Di_0_CTRL-Di_CTRL-O>><<faq-14.614.6. HowdoI format/indent an entire file?You can format/indent an entire file using the gg=G command, where    gg - Goto the beginning of the file    =  - apply indentation    G  - till end of fileFor more information, read:gg=G'formatprg'C-indentingfaq-14.714.7. HowdoI increase or decrease the indentation of the current line?You can use the ">>" and "<<" commands to increase or decrease theindentation of the current line.For more information, read:shift-left-right>><<'shiftwidth'faq-14.814.8. HowdoI indenta block/group of lines?You can visually select the group of lines and press the> or< key toindent/unindent the lines. You can also use the following ex-command toindent the lines    :10,20>For more information, read:shift-left-rightv_>v_<:<:>faq-14.914.9. WhenI indent lines using the> or< key, the standard 8-tabstops are      used instead of the current'tabstop' setting. Why?The number of spaces used when lines are indented using the ">"operatoriscontrolled by the'shiftwidth' option. The'tabstop' settingis onlyused, when the'shiftwidth' optionis zero.    :set shiftwidth=4For more information, read:'shiftwidth'>>'softtabstop'faq-14.1014.10. HowdoI turn off the automatic indentation of text?By default, the automatic indentation of textis not turned on. Check theconfiguration files (.vimrc, .gvimrc) for settings related to indentation.Make sure the `:filetype indent on` commandis not present. Ifitispresent, remove it. Also, depending on your preference, you may also wantto check the value of the'autoindent','smartindent','cindent' and'indentexpr'options and turn them offas needed.For more information, read::filetype-indent-off'autoindent''smartindent''cindent''indentexpr'faq-14.1114.11. HowdoI configure Vim to automatically set the'textwidth' option       toa particular value whenI edit mails?You can use the "FileType"autocommand to set the'textwidth' option:    autocmd FileType mail set tw=<your_value>For more information, read::autocmdFileTypeusr_43.txtfaq-14.1214.12. Is therea way to make Vim auto-magically break lines?Yes. Set the'textwidth' option to the preferred length fora line. ThenVim will auto-magically break the newly entered lines. For example:    :set textwidth=75For more information, read:'textwidth'ins-textwidth'formatoptions'fo-tableformattingfaq-14.1314.13.I am seeinga lot of ^M symbols in my file.I tried setting the'fileformat' option to "dos" and then "unix" and then "mac".None of       these helped. How canI hide these symbols?Whena fileis loaded in Vim, the format of the fileis determinedasbelow:- If all the linesend witha new line (<NL>), then the fileformatis  "unix".- If all the linesend witha carriage return (<CR>) followed bya new line  (<NL>), then the fileformatis "dos".- If all the linesend with carriage return (<CR>), then the fileformatis  "mac".If the file has some lines ending with<CR> and some lines ending with<CR>followed bya<NL>, then the fileformatis set to "unix".You can change the format of the current file, by savingit explicitly indos format:    :w ++ff=dosTo display the format of the current file, use    :set fileformat?The above behavioris also controlled by the'fileformats' option. You cantry the following commands:    :set fileformats+=unix    :e <your_file>    :set fileformat=unix    :wTo remove the carriage return (<CR>) characterat theend of all the linesin the current file, you can use the following command:    :%s/\r$//To force Vim to usea particular file format, when editinga file, you canuse the following command:    :e ++ff=dos filenameFor more information, read:'fileformats''fileformat'file-formatsDOS-format-writeUnix-format-writeMac-format-writedos-file-formats23.1++fffaq-14.1414.14. WhenI paste some text intoa Vim buffer from another application,      the alignment (indentation) of the new textis messed up. HowdoI      fix this?When you paste text intoaGUI Vim using the mouse, Vimis able todetect that you are pasting text. So all the indentation relatedsettings (like autoindent, smartindent, cindent, etc.) are ignored andthe textis pasted literally.When pasting text intoa Vim running inaterminal (like xterm) usingthe mouse, Vim may not be able to detect that you are pasting text. Thisdepends on several things: the capability of theterminal to pass themouse events to Vim, Vimis compiled to handle mouse events and accessthe clipboard, the DISPLAY variableis set properly, the Vim'mouse'optionis set correctly.If Vimis able to detect that you are pasting text using the mouse, thenthe pasted text will be inserted literally.If Vimis not able to detect that you are pasting using the mouse, thenit will see the pasted textas though you literally typed the text.After the first line from the pasted textis inserted, when Vimencounters the newline character, because of the indentation settings,the next line will start indented. The spacesat the beginning of thesecond line in the pasted text will be inserted leading to additionalindentation. This will be repeated for subsequent lines. So the pastedtext will be inserted with staircase indentation.You can fix this problem inaterminal Vim in several ways:1. Build Vim with the+mouse and+xterm_clipboard compile-time options.   The normal or big or huge build of Vim includes these options.  Set   the'mouse' option to either "a" or include "i".  When pasting text   using the mouse, don't press the Shift key. This will work only if   Vim can access theX display. For more information, read the   following Vimhelp topics:+feature-list'mouse'<MiddleMouse>x11-selectionxterm-clipboard1.1 Some Linux distributions build theirterminal vimpackages    withoutX support.  This makes no sense and leaves many users    with the impression that Vim interminal mode doesn't support    some operations suchas properly pasting text witha mouse.    If your distribution includes gvim, which it almost certainly    does these days, the solutions to this include the following.a)  Start Vimas            gvim -v    b)  Put this alias in your shell's configuration file, e.g.        ~/.bashrc:            alias vim='gvim -v'    c)  Put the following command ina file named "vim" andput that        file in your ~/bin directory:            gvim -v "$@"    d)  Link the distribution'sgvim to ~/bin/vim with the following        command, which needs to be executed only once.            ln -s $(which gvim) ~/bin/vim    For c) and d), make sure that ~/bin precedes /usr/bin in your    PATH.2. Paste the text using theCTRL-RCTRL-O * command.  This will paste   the text literally without any automatic indentation. If you want to   paste the text and then fix the indentation, then you can useCTRL-RCTRL-P *. These commands will work only if Vim can access theX   display. For more information, read the following Vimhelp topics:i_CTRL-R_CTRL-Oi_CTRL-R_CTRL-Pquotestar3. Set the'paste' option before pasting the text. This option will   disable the effect of all the indentation related settings. Make   sure to turn off this option using `:set nopaste` after pasting the   text. Otherwise the Vim indentation feature will not work.  Do not   permanently set the'paste' option in your.vimrc file. If you are   going to repeat these steps often, then you can set the'pastetoggle' option toa key. When you press the specified key,   the'paste' option will be toggled. You can press the key once   before pasting the text and the press the key once after pasting   the text.Note that when the'paste' optionis set, all the   mappings andabbreviations are disabled.  For more information,   read the following Vimhelp topics:'paste''pastetoggle'You can also refer to the following topics in the user manual:04.709.3faq-14.1514.15. When thereisa very long wrapped line (wrapis "on") anda line      doesn't fit entirely on the screenitis not displayedat all. There      are blank lines beginning with "@" symbol instead of wrapped line. IfI scroll the screen to fit the line the "@" symbols disappear and the      lineis displayed again. What Vim settingcontrol this behavior?You can set the'display' option to "lastline" to displayas muchaspossible of the last line inawindow instead of displaying the "@"symbols.    :set display=lastlineFor more information, read:'display'faq-14.1614.16. HowdoI convert all thetab characters ina file tospace       characters?You can use the:retab command to update all thetab characters in thecurrent file with the current setting of'expandtab' and'tabstop'. Forexample, to convert all the tabs to white spaces, use    :set expandtab    :retabFor more information, read::retab'expandtab''tabstop'25.3faq-14.1714.17. What Vimoptions canI use to edit text that will latergo toaword       processor?You can set the followingoptions to edit text that will latergo intoaword processor:    :set wrap    :set linebreak    :set textwidth=0    :set showbreak=>>>You can use the "gk" and "gj" commands to move one screen line up and down.For more information, read:'wrap''linebreak''textwidth''showbreak'gkgjfaq-14.1814.18. HowdoI join lines without adding or removing anyspace characters?By default, when you join lines using the "J" or:join command, Vim willreplace the line break, leading whitespace and trailing whitespace withasinglespace character. If there arespace charactersat theend ofa lineora line starts with the ")" character, then Vim will not addaspacecharacter.To join lines without adding or removing anyspace characters, you can usethegJ or:join! commands.For more information, read:gJ:joinJ10.5'joinspaces''cpoptions''formatoptions'=============================================================================faq-15SECTION 15 - VISUAL MODEfaq-15.115.1. HowdoIdo rectangular block copying?You cando rectangular blockcopying in Vim using the blockwise visualmode. To start blockwise visual mode use theCTRL-V key. Move the cursorusing any of the motion commands and then use theyoperator toyank tovisually selected text.IfCTRL-V does not workas expected,it may have been remapped toCTRL-Q bythemswin.vimscript whichis often sourced byavimrc on Windows machinesto mimic some common short cuts from other programs.For more information, read:04.4blockwise-visualvisual-modeQ_vifaq-15.215.2. HowdoI delete or changea column of text ina file?You can use the Vim block-wise visual mode to select the column of text andapply anoperator (delete, change, copy, etc) on it.For more information, read:visual-blockvisual-operatorsfaq-15.315.3. HowdoI apply an ex-command ona set of visually selected lines?When you selecta range of lines in visual mode, the< registeris set tothe start of the visual region and the> registeris set to theend of thevisual region. You can use theseregisters to specify the range for anexcommand. After visually selecting the lines, press ":" togo to the commandmode.  Vim will automaticallyinsert the visual range '<,'>. You can runany ex-command on the visual range.For more information, read:v_:'<'>faq-15.415.4. HowdoI execute anex command ona column of text selected inVisual      block mode?All theex commands operate on whole lines only. If you try to executeanex command ona column of text selected in visual block mode, Vimwill operate on all the selected lines (instead of the selectedcolumns). You can use the vis.vim or NrrwRgnpluginscript fromhttps://www.vim.org scripts archive todo this.For more information, read:cmdline-ranges10.3cmdline-linesfaq-15.515.5. HowdoI select the entire file in visual mode?You can select the entire file in visual mode using ggVG.    gg - go to the beginning of the file.    V  - Start linewise visual mode    G  - goto the end of the file.For more information, read:gglinewise-visualGfaq-15.615.6. WhenI visually selecta set of lines and press the> key to indent      the selected lines, the visual mode ends. How canI reselect the      region for further operation?  (or) HowdoI re-select the last      selected visual area again?You can use the "gv" command to reselect the last selected visual area. Youcan also use the marks'< and'> to jump to the beginning or theend of thelast selected visual area.For more information, read:gv'<'>faq-15.715.7. HowdoI jump to the beginning/end ofa visually selected region?You can use the "o" command to jump to the beginning/end ofa visuallyselected region.For more information, read:v_ofaq-15.815.8. WhenI select text with mouse and then press: to enter anex      command, the selected textis replaced with the: character. HowdoI      execute anex command ona text selected using the mouse similar to      the text selected using the visual mode?This will happen if you have configured Vim to use select mode instead ofVisual mode by setting the'selectmode' option. Check the value of thisoption:    :set selectmode?This modeis knownas selectmode andis similar to the visual mode. Thisoptionis also automatically set when you use the "behave mswin" command.Select mode looks like visual mode, butitis similar to the selection modein MS-Windows.For more information, read:Select-mode'selectmode'09.4:behavefaq-15.915.9. WhenI selecta block of text using the mouse, Vim goes into      selection mode instead ofVisual mode. Why?The'selectmode' option controls whetherSelect mode will be started whenselectinga block of text using the mouse. To startVisual mode whenselecting text using mouse, remove the "mouse" value from the'selectmode'option:    :set selectmode-=mouseNote that by default, the'selectmode' option will be set to empty, so thatalways visual modeis used.For more information, read:'selectmode'Select-mode:behavefaq-15.1015.10. HowdoI visually select the last copy/pasted text?You can use the'[ and'] marks to visually select the last copy/pastedtext. The'[markis set to the beginning of the last changed/yanked textand the']markis set to theend of the last changed/yanked text. Tovisually select this block of text use the command '[v']For more information, read:'[']`av=============================================================================faq-16SECTION 16 - COMMAND-LINE MODEfaq-16.116.1. HowdoI use the name of the current file in the command mode or anex command line?In the command line, the "%" character represents the name of the currentfile. In some commands, you have to useexpand("%") to get the filename:    :!perl %Another exampleis to load the latex generated pdf file from the file youare currently editing:    :!xpdf %<.pdfFor more information, read::_%cmdline-specialexpand()faq-16.216.2. HowdoI edit the text in the Vim command-line effectively?You can use the command-linewindow for editing Vim command-line text. Toopen the Vim command-linewindow use the "q:" command in normal mode. Incommand-line mode, use theCTRL-F key. In this window, the command linehistory will be displayed. You can use normal Vim keys/commands to edit anyprevious/new command line. To executea command line, press theenter/return key.Ina similar vain, the searchhistory can be edited with "q/" and "q?"commands.For more information, read:cmdline-windowfaq-16.316.3. HowdoI switch fromVi mode toEx mode?You can use theQ command to switch fromVi mode toEx mode. To switch fromEx mode back to theVi mode, use the:vi command.For more information, read:QgQEx-mode:vifaq-16.416.4. HowdoI copy the output from an ex-command intoa buffer?To copy the output from an ex-command intoa buffer, you have to first getthe command output intoa register. You can use the:redir command to getthe output intoa register. For example,    :redir @a    :g/HelloWord/p    :redir ENDNow the register "a" will contain the output from theex command:g/HelloWord/p. Now you can paste the contents of the register "a" intoabuffer. You can also send or append the output of an ex-command intoa fileusing the:redir command.You can prefix the:global command with:silent, to avoid having thelines printed to the screen.To redirect the output from an ex-command toa file, you can use thefollowing set of commands:    :redir > myfile    :g/HelloWord/p    :redir ENDFor more information, read::redir:silentfaq-16.516.5. WhenI press the<Tab> key to complete the name ofa file in the      command mode, if there are more than one matching file names, then      Vim completes the first matching file name and displaysalist of all      matching filenames. HowdoI configure Vim to only display thelist      of all the matching filenames and not complete the first one?You can modify the'wildmode' option to configure the way Vim completesfilenames in the command mode. In this case, you can set the'wildmode'option to "list":    :set wildmode=listFor more information, read:'wildmode'faq-16.616.6. HowdoI copy text froma buffer to the command line and from the      command line toa buffer?To copy text froma buffer to the command line, after yanking the text fromthe buffer, use "<CTRL-R>0" in the command line to paste the text. You canalsoyank the text toa specific register and useCTRL-R<register> topaste the text to the command line.  You can useCTRL-RCTRL-W to paste theword under the cursor in the command line.To copy text from the command line intoa buffer, you can paste thecontents of the: register using the ":p command. The most recentlyexecuted command lineis stored in the: register.Another approach forcopying and pasting text to and from the command lineis to open the command linewindow usingq: from normal mode orCTRL-F fromthe command-line mode. In the command linewindow you can use all the Vimcommands to edit the command line.For more information, read:c_CTRL-Rquote_:cmdline-windowfaq-16.716.7. HowdoIputa command onto the commandhistory without executing it?Toputa command onto the commandhistory without executing it, press the<Esc> key to cancel the command.An alternative solution,is to use thehistadd() function like this:    :call histadd(':', 'echo strftime("%c")')For more information, read:c_<Esc>histadd()faq-16.816.8. HowdoI increase the height of the command-line?You can increase the height of the command-line bychanging the'cmdheight'option:    :set cmdheight=2For more information, read:'cmdheight'hit-enter05.7=============================================================================faq-17SECTION 17 - VIMINFOfaq-17.117.1. WhenI invoke Vim,I get errormessages about illegal characters in      theviminfo file. What shouldIdo to get rid of these messages?You can remove the $HOME/.viminfo or the $HOME/_viminfo file to get rid ofthese error messages.For more information, read:viminfo-errorsviminfo-file-nameviminfo21.3faq-17.217.2. HowdoI disable theviminfo feature?By default, theviminfo featureis disabled. If theviminfo featureisenabled bya system-widevimrc file, then you can disable theviminfofeature by setting the'viminfo' option to an emptystring in your local.vimrc file:    :set viminfo=""For more information, read:'viminfo'faq-17.317.3. HowdoI save and use Vim marks/commands across Vim sessions?You can save and restore Vim marks across Vim sessions using theviminfofile. To use theviminfo file, make sure the'viminfo' optionis not empty.To save and restore Vim marks, the'viminfo' option should not contain the"f" flag or should havea value greater than zero for the "f" option.You can also use theviminfo file to synchronize the commandlinehistoryacross different sessions using:wvimfo and:rviminfo commands togetherwith theFocusGained andFocusLost autocommands:    augroup viminfo        au!        au FocusLost   * wviminfo        au FocusGained * rviminfo    augroup endNote, this will only work reliably, when Vim can detect theFocusLostandFocusGainedautocommands correctly. This meansit should work withGVim but might depend on yourterminal for konsole vim.For more information, read:21.3viminfo'viminfo':wviminfo:rviminfoFocusLostFocusGained=============================================================================faq-18SECTION 18 - REMOTE EDITINGfaq-18.118.1. HowdoI opena file with existing instance of gvim? What happened to      the Vim 5.x OpenWithVim.exe and SendToVim.exe files?Starting with Vim6, the OLE version of OpenWithVim.exe and SendToVim.exeVim utilities are replaced by the newclient-server feature. To open thefile j.txt with an existing instance of Gvim (MyVim), use:    $ gvim --servername MyVim --remote-silent j.txtTolist the server names of all the currently running Vim instances, use    $ vim --serverlistTo get more information aboutclient-server feature, readclient-serverfaq-18.218.2. HowdoI senda command toa Vim server to write allbuffers to disk?You can use the Vim remote server functionality todo this:    $ gvim --servername myVIM --remote-send "<C-\><C-N>:wall<CR>"For more information, read:client-serverCTRL-\_CTRL-N:wallfaq-18.318.3. Where canI get the documentation about the Vim remote server      functionality?You can get more information about the Vim remote server functionality byreadingclient-server=============================================================================faq-19SECTION 19 - OPTIONSfaq-19.119.1. HowdoI configure Vim ina simple way?You can use the:options command to open the Vim option window:    :optionsThiswindow can be used for viewing and setting all the options.For more information, read::optionsfaq-19.219.2. HowdoItoggle the value of an option?You can prefix the option with "inv" totoggle the value of the option:    :set invignorecase    :set invhlsearchYou can also suffix the option with "!" totoggle the value:    :set ignorecase!    :set hlsearch!For more information, read:set-optionfaq-19.319.3. HowdoI set an option that affects only the current buffer/window?Some of the Vimoptions can havea local or global value.A local valueapplies only toa specific buffer or window.A global value applies to allthebuffers or windows.Whena Vim optionis modified using the:set command, both the global andlocal values for the option are changed. You can use the:setlocalcommand to modify only the local value for the option and the:setglobalcommand to modify only the global value.You can use the:setlocal command to set an option that will affect onlythe current file/buffer:    :setlocal textwidth=70Note that not alloptions can havea local value. You can use:setlocalcommand to set an option locally toa buffer/window only if the optionisallowed to havea local value.You can also use the following command to set an option locally:    :let &l:{option-name} = <value>For more information, read::setlocallocal-optionsfaq-19.419.4. HowdoI usespace characters fora Vim option value?To usespace characters ina Vim option value, you have toescape thespacecharacter. For example:    :set tags=tags\ /usr/tagsFor more information, read:option-backslashfaq-19.519.5. CanI add (embed) Vim option settings to the contents ofa file?You can use modelines to add Vim option settings to the contents ofa file.For example, inaC file, you can add the following line to the top or thebottom of the file:    /* vim:sw=4: */This will set the'shiftwidth' option to 4, when editing thatC file.For this to work, the'modeline' option should be set. By default, the'modeline' optionis set. An alternative exampleis given in this documentin the first line.The'modelines' settingsspecifies the number oflines that will be checked for the Vim set commands.For more information, read:21.6modelineauto-setting'modeline''modelines'faq-19.619.6. HowdoI display the line numbers of all the lines ina file?You can set the'number' option to display the line numbers for all thelines.    :set numberFor more information, read:'number'faq-19.719.7. HowdoI change the width of the line numbers displayed using the'number' option?You can set the minimum number of columns to be used for line numbering bysetting the'numberwidth' option:    :set numberwidth=3This set's the width for the line number to 3 digits, whichis enough, ifyour buffer containsless than 999 lines. However, if your current buffercontains more lines than 999, the'numberwidth' will be adjusted accordingly,so that the maximum line number will fit on the screen.faq-19.819.8. HowdoI display (view) all the invisible characters like space, tabs      and newlines ina file?You can set the'list' option to see all the invisible characters in yourfile.    :set listWith this option set, you canviewspace characters, tabs, newlines,trailingspace characters and wrapped lines.To not display the invisible characters (whichis the default), you have toreset the'list' option:    :set nolist    (or)    :set list!The `:set list!` command willtoggle the current setting of theboolean'list' option.You can modify the'listchars' option to configure how and which invisiblecharacters are displayed. For example, with the following command all thetrailingspace characters will be displayed witha "." character.    :set listchars=trail:.For more information, read:'listchars''list'faq-19.919.9. HowdoI configure Vim to always display the current line and column      number?You can set the'ruler' option to display current column and line number inthe status line:    :set rulerFor more information, read:'ruler'faq-19.1019.10. HowdoI display the current Vim mode?You can set the'showmode' option to display the current Vim mode. InInsert,Replace andVisual modes, Vim will display the current mode on thelast line.    :set showmodeFor more information, read:'showmode'faq-19.1119.11. HowdoI configure Vim to show pending/partial commands on the       status line?You can set the'showcmd' option to display pending/partial commands in thestatus line:    :set showcmdFor more information, read:'showcmd'faq-19.1219.12. HowdoI configure the Vim status line to display different       settings/values?You can set the'statusline' option to display different values/settings inthe Vim status line.For more information, read:'statusline''laststatus''rulerformat''ruler'faq-19.1319.13. HowdoI configure Vim to display status line always?You can set the'laststatus' option to 2 to display the status line always.    :set laststatus=2For more information, read:'laststatus'faq-19.1419.14. HowdoI makea Vim setting persistent across different Vim       invocations/instances/sessions?To makea Vim option setting persistent across different Vim instances, addyour setting to the.vimrc or.gvimrc file. You can also use the:mkvimrccommand to generateavimrc file for the current settings.For more information, read:save-settingsvimrcgvimrcvimrc-intro:mkvimrcinitializationfaq-19.1519.15. WhydoI hearabeep (why does mywindow flash) about 1 second afterI hit the Escape key?Thisis normal behavior. If yourwindow flashes, then you've got the visualbell on. Otherwise, you should heara beep.Vim needsa timeout to tell the difference betweena simpleescape and,say,a cursor key sequence.  When you pressa key in normal mode (and evenininsert mode) and that keyis the beginning ofa mapping, Vim waitsacertain amount of time to see if the rest of themapping sequence follows.If themapping sequenceis completed beforea given timeout period, themapping for that sequence of keysis applied. If you interrupt the mapping,the normal actions associated with the keys are executed.For example, if you haveamapping definedas `:imap vvv Vimis great!!`and you type "vvv" quickly, the "Vimis great!!" will be inserted into yourtext. But if you type "vvv" then thatis what willput into your text.Thisis alsotrue if you type "vvv" too slowly where "too slowly"is longerthan the value for the timeout option. Setting the timeout option toalarger value canhelp alleviate problems that appear when using functionkeys overa slow line.For more information, read:'ttimeout'faq-19.1619.16. HowdoI make the "c" and "s" commands displaya "$" instead ofdeleting the characters I'm changing?To make the "c" and "s" commands displaya "$" instead ofdeleting thecharacters, add the$ flag to the'cpoptions' option:    :set cpoptions+=$For more information, read:'cpoptions'faq-19.1719.17. HowdoI remove more than one flag usinga single:set command       froma Vim option?You can remove more than one flag froma Vim option usinga single:setcommand, by specifying the flags in exactly the same orderas they appearin the option. For example, if you use the following command to remove the"t" and "n" flags from the'formatoptions' option:    :set formatoptions-=tnThe "t" and "n" flags will be removed from the'formatoptions' option, onlyif the'formatoptions' option contains these flags in this order: "tn".Otherwise,it will not remove the flags. To avoid this problem, you canremove the flags one by one:    :set formatoptions-=t formatoptions-=nFor more information, read::set-==============================================================================faq-20SECTION 20 - MAPPING KEYSfaq-20.120.1. HowdoI know whata keyis mapped to?To see whata keyis mapped to, use the following commands:    :map <key>    :map! <key>You can also check the mappings ina particular mode using one of the:cmap,:nmap,:vmap,:imap,:omap, etc commands.To find out, where the key has been mapped, prefix the:verbose command:    :verbose :map <key>For more information, read:map-listingmap-overviewfaq-20.220.2. HowdoIlist all the user-defined key mappings?You canlist all the user-defined key mappings using:    :mapFor more information, read:map-listingfaq-20.320.3. HowdoI unmapa previously mapped key?You can unmapa previously mapped key using the:unmap command:    :unmap <key>    :unmap! <key>For mode specific mappings, you can use one of the these commands:    :nunmap    :vunmap    :ounmap    :iunmap    :lunmap    :cunmapThe following command will fail to unmapa buffer-local mapped key:    :unmap <key>To unmapa buffer-local mapped key, you have to use the<buffer> keyword inthe unmap command:    :unmap <buffer> <key>    :unmap! <buffer> <key>For more information, read::unmapmap-modes:map-localmapleaderfaq-20.420.4.I am not able to createamapping for the<xxx> key. Whatis wrong?1) First make sure, the keyis passed correctly to Vim. To determine if   thisis the case,put Vim inInsert mode and then hitCTRL-V (orCTRL-Q if yourCTRL-Vis remapped to the paste operation (e.g. on   Windows if you are using themswin.vimscript file) followed by your   key.   If nothing appears in the buffer (and assuming that you have'showcmd' on, ^V remains displayed near the bottom right of the Vim   screen), then Vim doesn't get your key correctly and thereis nothing   to be done, other than selectinga different key for yourmapping or   using GVim, which should recognise the key correctly.2) Possibly, Vim gets your key, but seesitas no different than   something else. Say you want to map<Ctrl-Right>, then inInsert mode   hitCTRL-K followed by<Ctrl-Right>. If Vim displays<C-Right>it has   correctly seen the keystroke and you should be able to mapit (by   using<C-Right>as your{lhs}). Ifit displays<Right>it has seen   the keystroke butas if you hadn't held<Ctrl> down: this means your   temrinal passes<Ctrl-Right>as ifit were just<Right>. Anything else   means the key has been misidentified.3) If the keyis seen, but notas itself and notas some recognizable   key, then thereis probably an error in theterminal library for the   currentterminal (termcap orterminfo database). In thatcase        :set term?   will tell you whichtermcap orterminfo Vimis using. You can try to   tell vim, what termcode to use in that terminal, by adding the   following to your vimrc:        if &term == <termname>            set <C-Right>=<keycode>        endif   where<termname> above should be replaced by the value of'term'   (withquotes around it) and<keycode> by what you get when hittingCTRL-V followed by<Ctrl-Right> inInsert mode (with nothing around   it).<C-Right> should be left as-is (9 characters). Don't forget that   ina:set command, whitespaceis not allowed between the equal sign   and the value, and any space, double quote, verticalbar orbackslash   presentas part of the valuemust be backslash-escaped.   Now you should be able to see the keycode corresponding to the key   and you can createamapping for the key using the following command:        :map <C-Right>  <your_command_to_be_mapped>For more information, read:map-keys-fails:map-special-keyskey-codesfaq-20.520.5. Why doesmapping the <C-...> key not work?The only<Ctrl>-<printable-key> chords which Vim can reliably detect(because they are defined in the ASCII standard) are the following:        CTRL-@                 0x00            NUL        CTRL-A to CTRL-Z       0x01 to 0x1A        CTRL-a to CTRL-z       0x01 to 0x1A        CTRL-[                 0x1B            ESC        CTRL-\                 0x1C        CTRL-]                 0x1D        CTRL-^                 0x1E        CTRL-_                 0x1F        CTRL-?                 0x7F            DELMost of these, however, already havea function in Vim (and some arealiases of other keys:CTRL-H and<BS>,CTRL-I and<Tab>,CTRL-M and<Enter>,CTRL-[ and<Esc>,CTRL-? and<Del>).The "safest" keys to use in Vim for the{lhs} ofamapping are theFkeys, with or without Shift:<F2> to<F12> and<S-F1> to<S-F12>. (SomeOSes, including mine, intercept<Ctrl-Fn> and<Alt-Fn>, which never reach anapplication program suchas vim or gvim).You can try other combinations of<Ctrl>+ any key, but they may eithernot work everywhere (e.g. theterminal might not pass that key to Vim,or they might have unintended side effects (e.g.mapping<C-I> meansalso to map<Tab>).Thisisa known issue, that has been discussed and might be implementedin the future to enable Vim to distinguish betweenvarious keys even inconsole mode. (e.g.https://groups.google.com/d/msg/vim_dev/2bp9UdfZ63M/sajb9KM0pNYJ)faq-20.620.6. HowdoI map the numeric keypad keys?First make sure that the numeric keypad keys are passed to Vim. Next, youcan use the following command to map the numeric keypad keys:    :map <kSomething>  <your_command>where,<kSomething> can be kHome, kEnd, kPageUp, kPageDown, kPlus, kMinus,kDivide, kMultiply, kEnter, etc.For more information, read:key-codesterminal-optionsfaq-20.720.7. HowdoI createamapping that works only in visual mode?You can create mappings that work only in specific modes (normal, command,insert, visual, etc). To createamapping that works only in the visualmode, use the:vmap command:    :vmap <F3> <your mapping here>Thismapping will work in visual and select mode. If you want the map towork only in visual mode (excluding select mode), use:    :xmap <F3> <your mapping here>and to have themapping only work in select mode (but not visual mode),use:    :smap <F3> <your mapping here>For more information, read::vmap:xmap:smapmap-modes40.1faq-20.820.8. HowdoI createamapping that works only in normal andoperator   pending mode (but not in visual mode)?Using:map createsamapping that works in normal, visual+select mode andoperator pending mode. You can use:nmap to have themapping only work innormal mode and:vmap to have themapping only be defined for visual andselect mode or use:omap to have themapping only defined inoperatorpending mode.But if you want to haveamapping defined, that works in bothoperatorpending mode and normal mode, but not in visual and select mode, you needto first define themapping using:map and afterwards delete themappingfor visual and select mode::map<f3> <yourmapping here>:vunmap<f3>faq-20.920.9. Ina Vim script, howdoI know which keys to use for my mappings, so      that the mapped key will not collide with an already used key?Vim uses most of the keys in the keyboard. You can use the<leader> prefixin maps to define keys which will not overlap with Vim keys. For example:    :map <leader>S <C-W>s    :map <leader>j <C-W>j    :map <leader>k <C-W>kwhere by default<leader> gets substituted withabackslash (\), so theuser would enter        \s        \j        \kto invoke the above map commands. The user can change themapleadervariable to be whatever they wanted:    :let mapleader = ","Whenwritingaplugin or other script, more often than not,itis advisableto use:noremap instead of:map to avoid side effects from user definedmappings.For more information, read:<Leader><LocalLeader>write-pluginfaq-20.1020.10. HowdoI map theescape key?You can map the Escape key to some other key using the:map command. Forexample, the following command maps theescape key toCTRL-O.    :map <C-O> <Esc>faq-20.1120.11. HowdoI mapa key to perform nothing?You can mapa key to<Nop> to perform nothing when the keyis pressed. Forexample, with the following mappings, the<F7> key willdo nothing whenpressed.    :map <F7> <Nop>    :map! <F7> <Nop>For more information, read:<Nop>:map:map!map-modesfaq-20.1220.12.I want to use the<Tab> key to indenta block of text and<Shift-Tab>       key to unindenta block of text. HowdoI map the keys todo this?       This behavioris similar to textpad, visual studio, etc.Use the following mapping:    :inoremap <S-Tab> <C-O><lt><lt>    :nnoremap <Tab> >>    :nnoremap <S-Tab> <lt><lt>    :vnoremap <Tab> >    :vnoremap <S-Tab> <lt>Note, that the<S-Tab>mapping will work only if Vim receives the correctkey sequence. Thisis mostly thecase withGUI Vim.For more information, read::inoremap:nnoremap:vnoremap<S-Tab>i_CTRL-O>><<<lt>faq-20.1320.13. In my mappings the special characters like<CR> are not recognized.       How canI configure Vim to recognize special characters?Check the value of the'cpoptions' option:    :set cpoptions?If this option contains the "<" flag, then special characters will not berecognized in mappings. Remove the "<" flag from'cpoptions' option:    :set cpo-=<Also, check the value of the'compatible' option:    :set compatible?The'compatible' optionmust be reset:    :set nocompatibleFor more information, read:'cpoptions''compatible'faq-20.1420.14. HowdoI use the "|" to separate multiple commands ina map?You canescape the "|" character usingbackslash (\) to use "|" ina map.    :map _l :!ls \| more<CR>You can also try the following command:    :map _l :!ls <bar> more<CR>There are also other ways todo this.For more information, read:map_barfaq-20.1520.15. IfI havea mapping/abbreviation whose endingis the beginning of       another mapping/abbreviation, howdoI keep the first from expanding       into the second one?Instead of using the `:map lhs rhs` command, use the `:noremap lhs rhs`command. For abbreviations, use "noreabbrev lhs rhs". The "nore" prefixprevents themapping or abbreviation from being expanded again.For more information, read::noremap:noreabbrevfaq-20.1620.16. Why doesit takea second or more for Vim to processa key,       sometimes whenI pressa key?Make sure you have not definedamapping for this key using the followingcommand:    :map <key>Ifamappingis defined for this key and the mapped key contains more thanone character, then Vim will wait for the next character to be pressed todetermine whetheritis the mapped key or not. For example, if you havemapped "ab", then if you press "a", Vim will wait for the next key to bepressed. If the next keyis "b", Vim will execute the mapped sequence.Otherwise, Vim will proceed with the normal processing of "a" followed bythe next key. If the'timeout' optionis set (whichis the default), thenVim will timeout after waiting for the period specified with the'timeoutlen' option (defaultis 1 second).For more information, read:map-typing'timeoutlen''ttimeoutlen''timeout''ttimeout'vt100-cursor-keysslow-fast-terminalfaq-20.1720.17. HowdoI mapa key to run an external command usinga visually       selected text?You can the:vmap command to mapa key in the visual mode. In the mappedcommand sequence, you have to firstyank the text. The yanked textisavailable in the'"' register. Now, you can use the contents of thisregister to run the external command. For example, to run the externalcommand "perldoc" ona visually selected text, you can use the followingmapping:    :vmap <F7> y:!exec "!perldoc '" . @" . "'"<CR>If you want themapping to work in the visual mode, but not with thehighlighted text, you can use the following command:    :vmap <F7> :<C-U>!perldoc <cword><CR>The abovemapping will use theword under the cursor instead of thehighlighted text.Note the use of the<C-U> before invoking the "perldoc"external command. The<C-U>is used to erase the range of text selected inthe visual mode and displayed on the command line. If the visual rangeisnot removed using<C-U>, then the output from the external command willreplace the visually selected text.For more information, read::vmapquote_quote:let-registerc_CTRL-U:!cmdfaq-20.1820.18. HowdoI map theCTRL-I key while still retaining the functionality       of the<Tab> key?TheCTRL-I key and the<Tab> key produce the same keycode, so Vim cannotdistinguish between theCTRL-I and the<Tab> key. When you map theCTRL-Ikey, the<Tab> keyis also mapped (and vice versa). The same restrictionapplies for theCTRL-[ key and the<Esc> key.For more information, read:keycodesfaq-20.1920.19. HowdoI definea map to accepta count?Use the@= command to use an expression. For example,    nnoremap = @='3l'Now you can specifyacount to the "=" command.complex-repeatfaq-20.2020.20. How canI make my normal modemapping work from withinInsert       Mode?Mappings in normal mode can be executed afterCTRL-O frominsert modeaswell but if there are more commands included in themapping{rhs}, only thefirst one will be executed in normal mode and the rest of{rhs} will beprinted literally ininsert mode. One of ways to workaround this problemisto make{rhs} be one command, via wrappingit to the function. For example:    function GetFontNameOfFirstChar()    normal! 0    echo getfontname()    endfunction:nmap<F9>:call GetFontNameOfFirstChar()<CR>A more technical and detailed solution to this problem follows and canbe foundathttps://groups.google.com/group/vim_dev/msg/75f1f2dfc00908bbNot every normal mode-mappingis automatically suitable for execution viaCTRL-O from withininsert mode; you need to explicitly design your mappingsfor that purpose.TheCTRL-O command allows execution of one normal mode command fromwithininsert mode, then returns toinsert mode. Ifa normal modemappingconcatenates multiple normal mode commands, this breaks down in temporarynormal mode and literally inserts the second part of the command into thebuffer instead. To support execution of normal mode mappings from withininsert mode, these strategies can be used:1) Instead of concatenating multiple normal mode commands, use one:normal    mapping:    :nnoremap <silent> zC :<C-U>normal! zCVzC<CR>2) Concatenate multipleEx commands via<Bar> on the rhs:    :nnoremap zC :<C-U>call MyMap1()<Bar>call MyMap2()<CR>3) Shadow normal mode mappings byinsert mode mappings that    re-enter normal mode, then invoke the normal mode mapping:    :nnoremap <silent> <SID>MyMap2 :<C-U>call MyMap2()<CR>    :inoremap <silent> <script> <SID>MyMap2 <C-\><C-O><SID>MyMap2    :nnoremap <silent> <script> zC <SID>MyMap1<SID>MyMap24)Normal mode mappings that consist of multipleEx command lines (and    whereEx commands cannot be concatenated via<Bar>) replace:<C-U>    with<SID>NM; the<SID>NMmapping enters normal mode for oneex command    line:    :nnoremap <silent> <SID>NM :<C-U>    :inoremap <silent> <SID>NM <C-\><C-O>:    :nnoremap <silent> <script> zC <SID>MyMap1<SID>NMcall MyMap2()<CR>5)  If none of the aboveis possible,at least force normal mode for    subsequent commands viaCTRL-\CTRL-N to avoid accidental insertion    of the remainder of the mapping.    :nnoremap zC zC<C-\><C-N>VzCzzFor more information, read:i_CTRL-Omap_bari_CTRL-\_CTRL-OCTRL-\_CTRL-N=============================================================================faq-21SECTION 21 - ABBREVIATIONSfaq-21.121.1. HowdoI auto correct misspelled words?You can auto correct misspelled words using abbreviations. For example, thefollowing abbreviation can be used to correct "teh" with "the":    :abbreviate teh theVim supportsabbreviations ininsert mode, replace mode and command-linemode.For more information, read:24.7abbreviationsQ_abfaq-21.221.2. HowdoI create multi-line abbreviations?You can create multi-lineabbreviations by embedding the "<CR>"key code in the text:    iabbrev #c --------------<CR>-- Date:<CR>--<CR>---------With the above abbreviation, when you type #c,it will be expanded tothe following text:---------------- Date:-----------For more information, read:abbreviationsfaq-21.321.3. When myabbreviations are expanded, an additionalspace characteris      addedat theend of the expanded text. HowdoI avoid this character?To avoid an additionalspace characterat theend of the expanded text, youcan expand the abbreviation by pressing theCTRL-] key.  The abbreviationwill be expanded without addingaspace characterat the end.Another alternativeis to use the following function and command:    function! Eatchar(pat)        let c = nr2char(getchar())        return (c =~ a:pat) ? '' : c    endfunction    command! -nargs=+ Iabbr execute "iabbr" <q-args> . "<C-R>=Eatchar('\\s')<CR>"Now, define yourabbreviations using the new "Iabbr" command instead of thebuiltin:iabbrev command. With this command, after expanding theabbreviated text, the next typedspace character will be discarded.For more information, read:abbreviationsfaq-21.421.4. HowdoIinsert the current date/time stamp into the file?You can use thestrftime() function toinsert the current data/time stampina file. For example, you can use the following abbreviation:    iabbrev dts <C-R>=strftime("%y/%m/%d %H:%M")<CR>With this abbreviation, when you type dts ininsert mode,it will beexpanded to the date/time stamp.Some other forms of the above abbreviation are listed below:    iabbrev mdyl <C-R>=strftime("%a %d %b %Y")<CR>    iabbrev mdys <C-R>=strftime("%y%m%d")<CR>    iabbrev mdyc <C-R>=strftime("%c")<CR>    iabbrev hml  <C-R>=strftime("%d/%m/%y %H:%M:%S")<CR>    iabbrev hms  <C-R>=strftime("%H:%M:%S")<CR>For more information, read:strftime()i_CTRL-Rfaq-21.521.5. HowdoI prevent an abbreviation from expanding ininsert mode?You can prevent an abbreviation from expanding ininsert mode by typingCTRL-V before the character after the abbreviated word.For more information, read:abbreviations=============================================================================faq-22SECTION 22 - RECORD AND PLAYBACKfaq-22.122.1. HowdoI repeat an editing operation (insertion, deletion, paste,      etc)?You can repeat the last editing operation using the "." command. This willrepeat the last simple change likea insert, delete, change, paste, etc.For more information, read:04.3single-repeatQ_refaq-22.222.2. HowI record and repeata set of key sequences?You can use the "q" command in normal mode to recorda set of key sequencesand storeit ina register. For example, in the normal mode you can pressqfollowed bya register name{0-9a-bA-Z"} to start the recording.  Toend/stop therecording pressq again. You can playback/repeat the recordedkey sequences by pressing@ followed by the register name. e.g. @a.Another approachis to start Vim with the "-w" command-line argument.    $ vim -w <file_name>Vim will record all the characters typed in the session in thespecified file "file_name". You can use the recorded file with the "-s"command line argument to playit back:    $ vim -s <file_name>For more information, read:10.1recording-w-sfaq-22.322.3. HowdoI edit/modifya recorded set of key sequences?The recorded key sequences are stored ina register. You can paste thecontents of the register intoa Vim buffer, edit the pasted text and againyank the text into the register. You can also use the:let command tomodify the register. For example:    :let @a = "iHello World\<Esc>"For more information, read:recording10.1:let-register<>'cpoptions'faq-22.422.4. HowdoI write recorded key sequences toa file?The recorded key sequences are stored ina register. You can paste thecontents of the register intoa Vim buffer. Now you can save the bufferintoa file. You can also modify the pasted text and againyank into theregister to modify the recorded key sequence. For example, if you recordaset of key sequences using qa ..... q. The recorded key sequences arestored in the register "a". You can paste the contents of register "a"using "ap.For more information, read:recording10.1faq-22.522.5.I am using register0 to record my key sequences (i.e. q0 .... q).      In the recorded key sequences,I am yanking some text. After the      first replay of the recorded key sequence,I am no longer able to      playit back.Register0 contains the text from the lastyank operation. In your recordedkey sequence, when theyankis performed, register0is overwritten withthe yanked text. So yourrecording stored in register0is lost. You haveto use some other register.For more information, read:registers=============================================================================faq-23SECTION 23 - AUTOCOMMANDSfaq-23.123.1. HowdoI executea command whenI try to modifya read-only file?You can use theFileChangedROautocommand event to executea command whenaread-only fileis modified. For example, you can use this event to checkoutaread-only file:    :autocmd FileChangedRO * call MyCheckoutFunction()For more information, read:FileChangedROfaq-23.223.2. HowdoI executea command every time when enteringa buffer?You can use theBufEnterautocommand event to executea command every timewhen enteringa buffer. For example:    :autocmd BufEnter *.c set formatoptions=croqtFor more information, read:BufEnterfaq-23.323.3. HowdoI executea command every time when enteringa window?You can use theWinEnterautocommand event to executea command every timewhen enteringa window. For example:    :autocmd WinEnter *.c call MyFunction()For more information, read:WinEnterfaq-23.423.4. From an autocmd, how canI determine the name of the file or the      buffer number for which theautocommandis executed?You can use the special words<afile> or<abuf> in an autocmd to get thename of the file or the buffer number for which theautocommandisexecuted.For more information, read::<afile>:<abuf>:<amatch>faq-23.523.5. HowdoI automatically save all the changedbuffers whenever Vim      loses focus?You can define anautocommand for theFocusLost event which will save allthe modifiedbuffers whenever Vim loses focus:    :autocmd FocusLost * wallFor more information, read:FocusLost:wallfaq-23.623.6. HowdoI execute/runa function when Vim exits todo some cleanup?You can useVimLeave autocmd event to executea function just before Vimexits. For example,    :autocmd VimLeave * call MyCleanupFunction()For more information, read:VimLeave=============================================================================faq-24SECTION 24 - SYNTAX HIGHLIGHTfaq-24.124.1. HowdoI turn off/onsyntax highlighting?By default, the Vimsyntax highlightingis turned off. To enable thesyntaxhighlighting, you can use one of the following commands:    :syntax enable    or    :syntax onTo disable thesyntax highlighting, you can use the following command:    :syntax offFor more information, read:06.106.4:syntax-enable:syntax-on:syn-clearfaq-24.224.2. HowdoI change the background and foreground colors used by Vim?Vim uses the "Normal" highlight group for the background and foregroundcolors. To change the foreground/background colors, you have to modify the"Normal" highlight group. For example, to set the background color to blueand foreground color to white, you can use    :highlight Normal ctermbg=blue ctermfg=white guibg=blue guifg=whiteIf you are using theMotif or the Athena version of theGUI Vim, then youcan modify the foreground and background resource names in the.Xdefaultsfiles to change the colors:    Vim.foreground:     Black    Vim.background:     WheatYou can also use the "-foreground" and "-background" command-line argumentsto specify the foreground and background colors. These arguments aresupported only in theMotif or Athena versions:    $ gvim -foreground Black -background WheatFor more information, read::highlight.Xdefaults-guifaq-24.324.3. HowdoI change the highlight colors to suita dark/light background?You can set the'background' option to either "dark" or "light" to changethe highlight colors to suita dark/light background:    :set background=darkFor more information, read:'background'06.2faq-24.424.4. HowdoI change the color of the line numbers displayed when the      `:set number` commandis used?The line numbers displayed use the LineNr highlighting group. To displaythe current colors used, use    :hi LineNrTo change the color modify the LineNr highlight group. For example:    :hi linenr guifg=red guibg=blackThis will give red numbers ona black background in GVIM.For more information, read::highlightfaq-24.524.5. HowdoI change the background color used fora Visually selected      block?You can modify the "Visual" highlight group to change the color used foravisually selected block:    :highlight Visual guibg=redFor more information, read::highlighthl-Visualfaq-24.624.6. HowdoI highlight the special characters (tabs, trailing spaces,end      of line, etc) displayed by the'list' option?You can modify the "NonText" and "SpecialKey" highlight groups to highlightthe special characters displayed by the'list' option:    :highlight NonText guibg=red    :highlight SpecialKey guibg=greenThe "NonText" highlighting groupis used for "eol", "extends" and"precedes" settings in the'listchars' option.  The "SpecialKey"highlighting groupis used for the "tab" and "trail" settings.For more information, read:'listchars'hl-NonTexthl-SpecialKeyfaq-24.724.7. HowdoI specifya colorscheme in my .vimrc/.gvimrc file, so that Vim      uses the specified colorscheme every time?You can specify the color scheme using the:colorscheme command in your.vimrc or.gvimrc file:    colorscheme eveningFor more information, read::colorschemefaq-24.824.8. Vimsyntax highlightingis broken. WhenI am editinga file, some      parts of the fileis notsyntax highlighted orsyntax highlighted      incorrectly.Vim doesn't read the whole file to parse the text forsyntax highlighting.It starts parsing wherever you are viewing the file. That savesa lot oftime, but sometimes the colors are wrong.A simple fixis refreshing thescreen using theCTRL-L key. Or scroll backa bit and then forward again.You can also use the command:    :syntax sync fromstartNote that this might considerably slow down the screen refreshing.For more information, read::syn-sync:syn-sync-firstfaq-24.924.9. Is therea built-in function to syntax-highlight the corresponding      matching bracket?Yes. Vim includes thematchparen Pluginas standardplugin thatis enabledby default. Whenever the cursor moves over an item defined with the'matchpairs' option, Vim will highlight the corresponding bracket using theMatchParen highlighting group.However, if the corresponding parenthesisis not visible in the currentwindow, the cursor won't jump to it.Thematchitplugin providesa similar function, that lets the cursorjump to related items (e.g. "if", "else", "endif" items) and skipsmatches in comments. This uses the% command to jump to correspondingitems. Though both plugins provide similarfunctions they are unrelatedand work differently.For more information, read:matchparen'matchpairs'matchit-installmatchit-introfaq-24.1024.10. HowdoI turn off theC commentsyntax highlighting?You can use the following command to turn offC commentsyntaxhighlighting:    :highlight clear commentFor more information, read:ft-c-syntaxfaq-24.1124.11. HowdoI add my ownsyntax extensions to the standardsyntax files       supplied with Vim?You should not modify thesyntax files supplied with Vim to add yourextensions. When youinstall the next version of Vim, you will lose yourchanges. Instead you should createa file under the ~/.vim/after/syntaxdirectory with the same nameas the originalsyntax file and add youradditions to this file.For more information, read:mysyntaxfile-add'runtimepath'faq-24.1224.12. HowdoI replacea standardsyntax file that comes with the Vimdistribution with my ownsyntax file?You can replacea standardsyntax file that comes with the Vimdistributionby creatinga file with the same nameas the originalsyntax file andplacingit in the vim runtimesyntax (~/.vim/syntax) directory. Forexample, to replace thec.vimsyntax file inaUnix system, place the newc.vim in the ~/.vim/syntax directory. InaMS-Windows system, place the newsyntax file in the $HOME/vimfiles/syntax or $VIM/vimfiles/syntax directory.For more information, read:mysyntaxfile-replace44.11mysyntaxfilefaq-24.1324.13. HowdoI highlight all the characters aftera particular column?You can use the:match command to highlight all the characters afteraparticular column:    :match Todo '\%>75v.\+'This will highlight all the characters after the 75th column.You can also set the'colorcolumn' option to highlighta particularcolumn::set colorcolumn=+2which highlights 2 columns after the current'textwidth' setting(alternatively, you can use the exact column number).For more information, read::match/\%v/\+/.'colorcolumn'faq-24.1424.14. HowdoI converta source file (.c, .h, etc) with the Vimsyntax       highlighting intoa HTML file?You can use the2html.vimscript to converta source file intoa HTML filewith the Vimsyntax highlighting. Use the following command:    :TOhtmlFor more information, read:convert-to-HTML:TOhtmlfaq-24.1524.15. HowdoIlist the definition of all the current highlight groups?You canlist the definition of all the current highlight groups using the:highlight (without any arguments)ex command.For more information, read::highlightfaq-24.1624.16. How canI embed onesyntax highlighting language into another one?Itis possible to include onesyntax highlighting into another one,however most of the currently deployedsyntax highlighting scripts arenot prepared to be included into anothersyntax script.You can however create your own customscript to define your ownregions, which will be highlighted witha different language.See the wiki fora comprehensive solution:http://vim.wikia.com/wiki/Different_syntax_highlighting_within_regions_of_a_fileFor more information, read::syn-includesh-awk=============================================================================faq-25SECTION 25 - VIM SCRIPT WRITINGfaq-25.125.1. HowdoIlist the names of all the scripts sourced by Vim?You can use the:scriptnames command tolist the names of all the scriptssourced by Vim:    :scriptnamesFor more information, read::scriptnamesfaq-25.225.2. HowdoI debug Vim scripts?Vim has built-in support fora primitive debugger to debug Vim plugins andscripts. Using this debugger you can set breakpoints and step through theplugin functions.For more information, read:debug-scripts-Dfaq-25.325.3. HowdoI locate the script/plugin which setsa Vim option?You can use the:verbose command to locate the plugin/script which lastmodifieda Vim option. For example:    :verbose set textwidth?For more information, read::set-verbose:verbosefaq-25.425.4.I am getting some error/informationalmessages from Vim (possibly      when runninga script), themessages are cleared immediately. HowdoI display themessages again?You can use the:messages command to display the previous messages.    :messagesFor more information, read::messages:echoerr:echomsgmessage-historyfaq-25.525.5. HowdoI save and restoreaplugin specific information across Vim      invocations?Vim will save and restore globalvariables that start with anuppercaseletter and don't containa lowercase letter. For this to work, the'viminfo' optionmust contain the "!" flag. Vim will store thevariables intheviminfo file.For more information, read:'viminfo'viminfo-filevariablesfaq-25.625.6. HowdoI startinsert mode froma Vim function?You can use the:startinsert command to start theinsert mode from insidea Vim function.For more information, read::startinsertfaq-25.725.7. HowdoI change the cursor position from withina Vim function?You can use thecursor() function to position the cursor.        call cursor(lnum, col)Alternatively, use thesetpos() function:        call setpos('.', [bufnum, lnum, col, off])which set's the cursor in the buffer bufnum to line lnum, column col andoffset for'virtualedit'. You can use thegetpos() function, to returnalist with these values, that can then be fed back to thesetpos() function.If you want to save and restore the viewpoint ona window, use thewinsaveview() andwinrestview() function calls.You can also use the following command to change the cursor position:        exe "normal! " . lnum . "G" . col . "|"For more information, read:cursor()bargetpos()setpos()winsaveview()winrestview()faq-25.825.8. HowdoI check the value of an environment variable in the.vimrc      file?You can use prefix the environment variable name with the "$" character touseit froma Vim script/function.  You can refer to the value of anenvironment variable using the $env_var syntax:    if $EDITOR == 'vi'    endifFor more information, read:expr-envfaq-25.925.9. HowdoI check whether an environment variableis set or not froma      Vim function?You can use theexists() function to check for the existence of anenvironment variable.    if exists("$MY_ENV_VAR")    endifFor more information, read:exists()expr-envfaq-25.1025.10. HowdoI call/use the Vim built-in functions?You can use the:call command to invokea Vim built-in function:    :call cursor(10,20)You can use the:echo command to echo the value returned bya function:    :echo char2nr('a')You can use the:let command to assign the value returned bya functiontoa variable:    :let a = getline('.')To store the return value froma function intoa Vim register, you can usethe following command:    :let @a = system('ls')The above command will store the output of the "ls" command intothe register "a".For more information, read::call:echo:let:let-registeruser-functionsusr_41.txtfaq-25.1125.11.I am using some normal mode commands in my Vim script. HowdoI       avoid using the user-defined mappings for these normal mode commands       and use the standard Vim functionality for these normal mode       commands?You can use the:normal! command in yourscript to invokea normal-modecommand. This will use the standard functionality of the normal modecommand and will not use the user-defined mapping.For more information, read::normalfaq-25.1225.12. HowdoI get the current visually selected text intoa Vim variable       or register?You can get the current visually selected text intoa Vim variable byyanking the text into Vim register and then assigning the contents of theregister into the variable:    :normal! gvy    :let myvar = @"The above command copies the visually selected text into the variable"myvar".You can also use the command:    :normal! gv"*yIn the above command,gv reselects the last visually selected text and therest of the command copies the selected text into the * (clipboard)register. Alternatively, you can set the "a" flag in the'guioptions'option to automatically copya visually selected text into the * register.Todo thisas part ofa visual map, you can usea command similar to theone shown below:    :vmap <F3> "*y:call ...For more information, read:gv:normal:let-@quotestarclipboardregistersfaq-25.1325.13.I have some text ina Vim variable "myvar".I would like to use this       variable ina:s substitute command to replacea text "mytext".       HowdoIdo this?You can use the:execute command to evaluate the variable:    :execute '%s/mytext/' . myvar . '/'For more information, read::executeYou can also use "\=" in the substitute command to evaluate the variable:    :%s/mytext/\=myvar/For more information, read:sub-replace-specialfaq-25.1425.14.A Vim variable (bno) containsa buffer number. HowdoI use this       variable to open the corresponding buffer?The:buffer command will not accepta variable name. It accepts onlyabuffer number or buffer name. You have to use the:execute command toevaluate the variable into the corresponding value. For example:    :execute "buffer " . bnoFor more information, read::executefaq-25.1525.15. HowdoI store the value ofa Vim option intoa Vim variable?You can prefix the option name with the "&" character and assign the optionvalue toa Vim variable using the:let command. For example, to store thevalue of the'textwidth' option into the Vim variable "old_tw", you can usethe following command:    :let old_tw = &twTo explicitly save buffer local options, use the prefix "l:"    :let old_tw = &l:twIf you want to explicitly select the global option, use the "g:" prefix tothe option name.Todo the opposite, to set the'textwidth' option with the value stored inthe "old_tw" variable, you can use the following command:    :let &tw = old_twFor more information, read:expr-option:let-optionfaq-25.1625.16.I have copied and inserted some text intoa buffer froma Vim       function. HowdoI indent the inserted text from the Vim function?You can use the following command to format the just inserted text:    :normal '[=']For more information, read:'[']=:normalfaq-25.1725.17. HowdoI get the character under the cursor froma Vim script?You can use thegetline() function and usestringindex[] to get thecharacter:    :echo getline(".")[col(".") - 1]In the above command, getline(".") returns  the text in the current line.The indexing of thestring startsat zero, and you can geta singlecharacter inastring by itsindex with the "string[index]" notation. Thecol(".") returns the column of the cursor position; the adjustmentis toget the right character of the string. However, this does NOT work withmultibyte charactersas this command only returns the byte index.Alternatively, you can use the following sequence of commands to get thecharacter under the cursor:    normal! vy    let ch=@"Note, that the above commands will change the'< and'> marks.For more information, read:getline()col()expr-[]faq-25.1825.18. HowdoI get the name of the current file without the extension?You can get the name of the current file without the extension using:    :echo expand("%:r")With some commands, you can use the file name modifiers directly:    :cd %:p:h    :!gcc -o %:r.o %    :!xpdf %<.pdfFor more information, read:filename-modifiersexpand()cmdline-specialfnamemodify()faq-25.1925.19. HowdoI get the basename of the current file?You can use the ":t" filename modifier to get the basename of the currentfile:    :echo expand("%:t")For more information, read:filename-modifiersfaq-25.2025.20. HowdoI get the output froma Vim function into the current buffer?You caninsert the return value froma function using the following commandininsert mode:    <C-R>=MyFunc()Note, that this will onlyinsert the return value of the function.For more information, read:i_CTRL-Ri_CTRL-R_CTRL-Ri_CTRL-R_CTRL-Oexpressionfaq-25.2125.21. HowdoI call external programs froma Vim function?There are several ways to call external programs froma Vim function. Youcan use the builtinsystem() function to invoke external programs and getthe result:    :let output = system("ls")You can also use "!" ex-command to run an external command.For more information, read:system():!10.9faq-25.2225.22. HowdoI get the return status ofa program executed using the:!       command?You can use the predefined Vimv:shell_error variable to get the returnstatus of the last run shell command.For more information, read:v:shell_errorfaq-25.2325.23. HowdoI determine whether the current bufferis modified or not?You can check the value of the'modified' option to determine whether thecurrent bufferis modified:    :set modified?Froma Vim script, you can check the value of the'modified' option:    if &modified        echo "File is modified"    endifFor more information, read:'modified'faq-25.2425.24.I would like to use the carriage return character ina normal       command froma Vim script. HowdoI specify the carriage return       character?You can use the:execute command to specify the special (control)character ina normal mode command:    :execute "normal \<CR>"    :execute "normal ixxx\<Esc>"For more information, read::executeexpr-quotefaq-25.2525.25. HowdoI split long lines ina Vim script?You can split long lines ina Vimscript byinserting thebackslashcharacter("\")at the start of the next line. For example,    set comments=sr:/*,mb:*,el:*/,                \://,                \b:#,                \:%,                \n:>,                \fb:-For more information, read:line-continuationfaq-25.2625.26. WhenI try to "execute" my function using the `:execute Myfunc()`       command, the cursoris moved to the top of the current buffer.       Why?The:execute command runs theex command specified by the argument.In thecase of the following command:    :execute Myfunc()The call to Myfunc() will return 0. The:execute command will runtheex command:0, which moves the cursor to the top of the file.To calla Vim function, you should use the:call command instead of the:execute command:    :call Myfunc()For more information, read::call:execute:echouser-functions41.541.6cmdline-linesfaq-25.2725.27. HowdoI source/execute the contents ofa register?If you have yankeda set of Vim commands intoa Vim register (for exampleregister "a"), then you can source the contents of the register using oneof the following commands:    :@aor:exe @aFor more information, read::@faq-25.2825.28. After callinga Vim function ora mapping, whenI press the "u"       key toundo the last change, Vim undoes all the changes made by       the mapping/function. Why?When you calla function ora mapping, all the operations performed by thefunction/mapping are treatedas one single operation. When youundo thelast operation by pressing "u", all the changes made by thefunction/mapping are reversed.For more information, read:undo-redo:map-undofaq-25.2925.29. How canI calla function defined with s: (script local function)       from another script/plugin?The s: prefix fora Vim function nameis used to createascript localfunction.Ascript local function can be called only from within thatscript and cannot be called from other scripts. To definea function inascript/plugin, so thatit can be called from other plugins/scripts, definethe function without the s: prefix.For more information, read:script-variablescript-local:scriptnamesfaq-25.3025.30. Isit possible to un-sourcea sourced script? In other words, reverse       all the commands executed by sourcinga script.No. Itis not possible to reverse orundo all the commands executed bysourcinga script.For more information, read::source=============================================================================faq-26SECTION 26 - PLUGINSfaq-26.126.1. HowdoI set differentoptions for different types of files?You can createfiletype plugins to set differentoptions for differenttypes of files. You should first enablefiletype plugins using the command:    :filetype plugin onAfiletypepluginisa vimscript thatis loaded whenever Vim opens orcreatesa file of that type.  For example, to ensure that the'textwidth'optionis set to 80 when editingaC program (filetype "c"), create one ofthe following files:        ~/.vim/ftplugin/c.vim (Unix)        %HOME%\vimfiles\ftplugin\c.vim (Windows)with the following text in it:        setlocal textwidth=80You can also useautocommands to set specificoptions when editing specifictype of files. For example, to set the'textwidth' option to 75 for only*.txt files, you can use the following autocmd:    autocmd BufRead *.txt setlocal textwidth=80For more information, read:filetype-pluginadd-filetype-plugin:autocmd40.3faq-26.226.2.I have downloadeda Vimplugin orasyntax file ora indent file, ora color scheme orafiletypeplugin from the web. Where shouldI copy      these files so that Vim will find them?You can place the Vim runtime files (plugins,syntax files, indent files,color schemes,filetype plugins, etc) under one of the directoriesspecified in the'runtimepath' option. To determine the current value ofthe'runtimepath' option, use the following command:    :set runtimepathForUnix systems, thisis usually the "$HOME/.vim" directory. ForMS-Windowssystems, thisis usually the $VIM\vimfiles or $HOME\vimfiles directory.Depending on the type of the runtime file, you have to placeit underaspecific directory under the above runtime directory. The names of thedirectories are listed below:    name        description    ----------  ------------------    colors/     color scheme files    compiler/   compiler files    doc/        documentation    ftplugin/filetype plugins    indent/     indent scripts    keymap/     keymapping files    lang/       menu translations    plugin/plugin scripts    syntax/syntax files    tutor/      files forvimtutorFor more information, read:your-runtime-dir'runtimepath':runtimefaq-26.326.3. HowdoI extend an existingfiletype plugin?You can extend an existingfiletypeplugin by creatinga file in theafter/ directory in any of the'runtimepath' directories.- for small changes to be done after (and in addition to) whatis  already done by theftplugin installed with Vim, use an after-directory,as follows (replacing foobar by the'filetype' of the concerned  files):- For changes private to one user:- on Windows:            $HOME/vimfiles/after/ftplugin/foobar.vim- on Unix-like OSes:            $HOME/.vim/after/ftplugin/foobar.vim- For changes affecting all users on the system:        $VIM/vimfiles/after/ftplugin/foobar.vim- whenreplacing the wholefiletype-plugin bya different version, or  when installinga newftplugin for somefiletype not yet supported by  Vim out of the box: use the same paths without the after/ in them. In  thatcase you should place near the start of yourplugin an "if...  finish... endif... let" block like the one in the plugins distributed  with Vim.All the above paths are given in Vim terminology (whichis similar toUnix terminology, butis understood even by Vim for Windows); they don'texist by default, so the first time you need them you will have tocreate them using mkdir (on any OS including DOS/Windows) or md (onDOS/Windows only).$VIM and, on DOS/Windows, $HOME,do not necessarilyexist outside Vim. If$HOME has no value (or no valid value) inside Vim,you can use$VIM instead; but on any but possibly very old versions ofWindows, $HOMEDRIVE and $HOMEPATH are defined by the system, and if$HOMEis undefinedat Vim startup, Vim will setit by expanding$HOMEDRIVE$HOMEPATH before sourcing your vimrc. To know which values Vimuses, you can type (ina running Vim):    :echo $VIM    :echo $HOMEIf you placed the file in the after/ftplugin runtime directory, then Vimwill first source the existingfiletypeplugin file and then will sourcethe new file.  If you placed the file in the $VIMRTUNTIME/ftplugin runtimedirectory, then Vim will first source the new file and then will source theexistingfiletypeplugin file.For more information, read:ftplugin-overrulefiletype-pluginadd-filetype-plugin'runtimepath'faq-26.426.4. HowdoI turn off loading the Vim plugins?You can reset the'loadplugins' option to turn off loading the plugins:    :set noloadpluginsYou can also specify the "--noplugin" command line argument to stop loadingthe plugins:    $ vim --nopluginFor more information, read:'loadplugins'--nopluginload-pluginsfaq-26.526.5. HowdoI turn on/off loading thefiletype plugins?By default, Vim will not load thefiletype plugins. You can configure Vimto loadfiletype plugins using the command:    filetype plugin onYou can turn off loading thefiletype plugins using:    filetype plugin offFor more information, read::filetype-plugin-on:filetype-plugin-off:filetypefaq-26.626.6. HowdoI override settings made ina file typeplugin in the globalftplugin directory for all the file types?You can use anautocommand triggered on theFileType event:    au Filetype * set formatoptions=xyzThis shouldat least be after "filetype on" in your vimrc. Bestis toputit in your "myfiletypefile" file, so that it's always last.If you want to overridea setting fora particular filetype, then createafile with the same nameas the originalfiletypeplugin in the~/.vim/after/ftplugin directory For example, to overridea setting in thec.vimfiletype plugin, createac.vim file in the ~/.vim/after/ftplugindirectory and add your preferences in this file.For more information, read:ftplugin-overruleftpluginsmyfiletypefilefaq-26.726.7. HowdoI disable the Vim directory browser plugin?To disable the directory browsing Vim plugin, add the following line toyour.vimrc file:    let g:loaded_netrw = 1For more information, read:netrwfaq-26.826.8. HowdoI set thefiletype option for files with names matchinga      particularpattern or depending on the file extension?You can set the'filetype' option for files with names matchingaparticularpattern using an autocmd. For example, to set the'filetype'option to "c" for all files with extension ".x", you can use the followingautocmd:    autocmd! BufRead,BufNewFile *.x     setfiletype cA better alternative to the above approachis to createa filetype.vim filein the ~/.vim directory (or in one of the directories specified in the'runtimepath' option) and add the following lines:    " my filetype file    if exists("did_load_filetypes")        finish    endif    augroup filetypedetect        au! BufRead,BufNewFile *.x       setfiletype c    augroup ENDFor more information, read:new-filetype43.2:setfiletype=============================================================================faq-27SECTION 27 - EDITING PROGRAM FILESfaq-27.127.1. HowdoI enable automatic indentation for C/C++ files?You can enablefile-type based indentation using:    :filetype indent onIf you want to only enable automaticC indentation, then use:    :set cindentFor more information, read:'cindent'C-indentingfiletypefaq-27.227.2. HowdoI configure the indentation used for C/C++ files?You can configure the VimC indentation by modifying the value of the'cinoptions','cinkeys' and'cinwords' options.For more information, read:'cindent''cinoptions''cinkeys''cinwords'C-indentingcinoptions-values'smartindent'faq-27.327.3. HowdoI turn off the automatic indentation feature?By default, the automatic indentationis not turned on. Youmust haveconfigured Vim todo automatic indentation in either.vimrc or.gvimrcfiles. You can disable automatic indentation using either,    :filetype indent offor    :set nocindentAlso, check the setting for the following options:    :set autoindent?    :set smartindent?    :set indentexpr?For more information, read:'cindent':filetype-indent-off'autoindent''smartindent''indentexpr'faq-27.427.4. HowdoI change the number ofspace characters used for the automatic      indentation?You can modify the'shiftwidth' option to change the number ofspacecharacters used for the automatic indentation:    :set shiftwidth=4For more information, read:'shiftwidth'faq-27.527.5.I am editingaC program using Vim. HowdoI display the definition      ofamacro ora variable?You can use the "[d" command to display the definition ofa macro, "[i"command to display the definition ofa variable, "gd" to goto the localdeclaration ofa variable and "gD" togo to the global Declaration.For more information, read:[d[igdgDinclude-search29.429.5faq-27.627.6.I am editingaC program using Vim. HowdoI jump to the beginning orend ofa code block from within the block?You can use "[{" command to jump to the beginning of the code block and "]}"to jump to theend of the code block from inside the block.For more information, read:[{]}various-motionsfaq-27.727.7. When editing C++ files and wheninserting new lines above or belowa      comment (//) line, Vim automatically inserts the C++ comment      character (//)at the beginning of the line. HowdoI disable this?This automatic insertion of the comment leader (//) when new linesare addedis controlled by three flags in the'formatoptions'option:  "c", "r" and "o".  "c" enables auto-wrapping of commentlines when typingextends beyond the right margin.  "r" enables theautomatic insertion of the comment leader when<Enter>is pressedwhile editinga comment line.  "o" enables the automatic insertionof the comment leader whena new lineis opened above or below anexisting comment line by typingO oro inNormal mode.You can stop Vim from automaticallyinserting the comment leaderwhen typing<Enter> withina comment or when openinga new line byremoving the "r" and "o" flags from'formatoptions'.:set formatoptions-=r:set formatoptions-=oThe defaultfiletypeplugin forC and C++ files($VIMRUNTIME/ftplugin/c.vim) adds the "r" and "o" flags to the'formatoptions' option.  If you want to override this for C++ files,then you can add the above lines to the~/.vim/after/ftplugin/cpp.vim file.For more information, read:'formatoptions'30.6format-commentsfiletype-pluginsftplugin-overrulefaq-27.827.8. HowdoI add the comment character "#" toa set of linesat the      beginning of each line?First, select the first character in all the lines using visual block mode(CTRL-V). Press "I" to startinserting charactersat the beginning of theline. Enter the comment character and then stop theinsert mode by pressing<Esc>. Vim will automaticallyinsert the entered charactersat thebeginning of all the selected lines.For more information, read:visual-blockblockwise-operatorsv_b_Ifaq-27.927.9. HowdoI edita header file with the same nameas the correspondingC      source file?You can use the following command to edita header file with the same nameas the correspondingC source file:    :e %:t:r.hYou can use the following command to edit the file ina new split window:    :sp %:t:r.hIn the above commands, the percent sign expands to the name of the currentfile.  The:t modifier extracts the tail (last component) of thefilename. The:r modifier extracts the root of the filename.  The .hisappended to the resulting name to get the header filename.Another approachis to use the following command:    :sfind %:t:r.hThis command will search for the header file in the directories specifiedin the'path' option.For more information, read:cmdline-specialfilename-modifiers:sfind'path'faq-27.1027.10. HowdoI automaticallyinsert comment leaders while typing comments?To automaticallyinsert comment leaders while typing comments, add the "r"and "o" flags to the'formatoptions' option.    :set formatoptions+=roYou may also want to add the "c" flag to auto-wrap comments using the'textwidth' option setting and the "q" flag to format comments with the"gq" command:    :set formatoptions=croqFor more information, read:30.6format-comments'comments'fo-table=============================================================================faq-28SECTION 28 - QUICKFIXfaq-28.128.1. HowdoI build programs from Vim?You can use the:make command to build programs from Vim. The:makecommand runs the program specified by the'makeprg' option.For more information, read:30.1:make_makeprg'makeprg''makeef':makequickfixfaq-28.228.2. WhenI run the make command in VimI get theerrors listedas the      compiler compiles the program. Whenit finishes thislist disappears      andI have to use the:clist command to see the error message again.      Is there any other way to see these error messages?You can use the:copen or:cwindow command to open thequickfixwindowthat contains the compiler output. You can select different error linesfrom thiswindow and jump to the corresponding line in the source code.For more information, read::copen:cwindowquickfixfaq-28.328.3. How canI performa command for each item in the quickfix/location      list?Starting from Vim 7.4.858 Vim provides the new commands:cfdo,:cdo,:lfdo and:ldo. They work by iterating over all items in thequickfixlist and performinga command on each. The difference is, that the:lfdoand:ldo commands iterate over the locationlist entries, while the:cfdo and:cdo commands operate on the items in thequickfix list. Also,the:cfdo and:lfdo operate on all different files, while the:cdo and:ldo commands operate on each item in the quickfix/location list.For example you could vimgrep allC files in the current directory forasearchstring "Foobar":    :vimgrep /Foobar/ *.candas this populates yourquickfix list, you could simply replace alloccurences by using:    :cdo :%s/Foobar/Foobaz | updFor more information, read::cfdo:cdo=============================================================================faq-29SECTION 29 - FOLDINGfaq-29.129.1. HowdoI extend the Vimfolding support?You can use the'foldexpr' option to fold usinga user specified function.For example, to fold subroutines of the following form intoa single line:    sub foo {      my $barf;      $barf = 3;      return $barf;    }You can use the following commands:    set foldmethod=expr    set foldexpr=MyFoldExpr(v:lnum)    fun! MyFoldExpr(line)        let str = getline(a:line)        if str =~ '^sub\>'            return '1'        elseif str =~ '^}'            return '<1'        else            return foldlevel(a:line - 1)        endif    endfunFor more information, read:'foldexpr'fold-exprfaq-29.229.2. WhenI enablefolding by setting the'foldmethod' option, all thefolds are closed. HowdoI prevent this?You can set the'foldlevelstart' option toa particular value to close onlyfolds above the specified value.    :set foldlevelstart=99For more information, read:'foldlevelstart''foldlevel'fold-foldlevelfaq-29.329.3. HowdoIcontrol how manyfolds will be opened whenI start editinga      file?You can modify the'foldlevelstart' option tocontrol the number offoldsthat will be opened when you start editinga file. To start editing withall thefolds closed:    :set foldlevelstart=0To start editing with all thefolds opened, you can use    :set foldlevelstart=999For more information, read:'foldlevelstart'faq-29.429.4. HowdoI open and closefolds using the mouse?You can click on the+ and- characters displayedat the leftmost column toopen and close fold. For this to work, you have to set the'foldcolumn'toa value greater than zero:    :set foldcolumn=2For more information, read:'foldcolumn'faq-29.529.5. HowdoI change the text displayed fora closed fold?You can use the'foldtext' option to change the text displayed fora closedfold.For more information, read:'foldtext'fold-foldtext'fillchars'faq-29.629.6. HowdoI store and restore manually createdfolds across different      Vim invocations?You can use the:mkview command to store manually created folds. Later,you can use the:loadview command to restore the folds. For this to work,the'viewoptions'must contain "folds".For more information, read:28.4:mkview:loadview'viewoptions''viewdir':mksession'sessionoptions'faq-29.729.7.I have enabledsyntax based folding. Whyis Vim so slow?Syntax basedfoldingis currently rather slow in Vim and will possiblyslow down Vim considerably. Thereis an issue in thetodolist to fixthis, but thetodolistis rather long andit may takea while untilthis will be fixed.You can find the issue in thetodo list, if you readtodo.txtfollowed bya search for "folding with'foldmethod'"A workaroundis to temporarily set the foldmethod to manual while ininsert mode. Thisis described in the wiki at:http://vim.wikia.com/wiki/Keep_folds_closed_while_inserting_text=============================================================================faq-30SECTION 30 - VIM WITH EXTERNAL APPLICATIONSfaq-30.130.1. CanI runa shell insidea Vim window?Since Version 8.1 Vim comes withaterminalwindow included. It allowsto runa shell inside an ordinary Vimwindow (e.g. split) asynchronouslyand interact with the shell using the normal Vim commands.When the focusis in theterminal window, typed keys will be sent tothejob andis calledterminal mode. You can click outside of theterminalwindow to move keyboard focus elsewhere, alternatively one canuseCTRL-W to novigate between different Vim windows. To feedCTRL-W into theterminal, one needs to useCTRL-W.To map keys specifically forterminal mode, use the new:tmapcommand. After typingCTRL-W theterminalwindow will switch toTerminal-Normal mode (this can be used to move the cursor around, scrollthe window, etc. Just like normal mode).To interact between theterminal and Vim, Vimimplements severalinterfaces using term_sendkeys(),terminal-api and theclient-servermechanism.For more information, read:terminalmapmode-tTerminal-Normalterminal-communicationfaq-30.230.2. HowdoI pass theword under the cursor to an external command?You can use the special keyword<cword> to pass theword under the cursorto an external command. For example:    :!dict <cword>For more information, read::<cword>faq-30.330.3. HowdoI get the output ofa shell command intoa Vim buffer?You can use the `:r !` command to get the output ofa shell command intoaVim buffer. For example, toinsert the output of the "ls" shell command,you can use the following command:    :r !lsToinsert the output of the shell command above the first line use thefollowing command:    :0r !lsFor more information, read::r!faq-30.430.4. HowdoI pipe the contents of the current buffer to an external      command and replace the contents of the buffer with the output from      the command?You can use the:! command to pipe the contents of the current buffer to anexternal command and replace the contents of the buffer with the outputfrom the command. For example, to sort the contents of the current buffer,using theUnix sort command, you can use the following command:    :%!sortTo sort only lines 10-20, you can use the following command    :10,20!sortAlso, if you want to pipea buffer to an external command but notput theresults back in the buffer, you can use    :w !sortThe above command will pipe the entire buffer to the sort command.  Note,that thespace between the "w" and the "!"is critical.  To pipe onlyarange of lines, you can use    :10,20w !sortThe above command will pipe the lines 10-20 to the sort command.For more information, read::range!10.9:w_cfaq-30.530.5. HowdoI sortasection of my file?You use the:sort command like this:   :5,100sortUsing the:sort command provides many options, you can sort numerical onthe first found decimal number using:   :%sortnOr you can specify to sort on the text,startingat virtual column 8:   :%sort/.*\%8v/Alternatively can pipeasection of the file to theUnix "sort" utility tosort the file. For example:    :5,100!sortYou can also usea visual block, and use the "!sort" command on theselected block.See also::sortfilterfaq-30.630.6. HowdoI use Vimasa pager?You can use Vimasapager using the $VIMRUNTIME/macros/less.sh shellscript, suppliedas part of the standard Vim distribution. This shellscript uses the $VIMRUNTIME/macros/less.vim Vimscript to provideless likekey bindings.For more information, read:lessfaq-30.730.7. HowdoIviewUnix man pages from inside Vim?You canviewUnix man pages, inside Vim, using theman.vimplugin suppliedas part of the standard Vim distribution. To use this plugin, add thefollowing line to yourstartupvimrc file:    runtime ftplugin/man.vimYou can also press theK key to run the program specified by the'keywordprg' option with the keyword under the cursor. By default,'keywordprg'is set to run man on the keyword under the cursor.For more information, read:ft-man-pluginK'keywordprg'faq-30.830.8. HowdoI change thediff command used by the Vimdiff support?By default, the Vimdiff support uses the'diff' command. You can changethis bychanging the'diffexpr' option.For more information, read:diff-diffexpr'diffexpr'faq-30.930.9. HowdoI use the Vimdiff mode without folding?You can use the following command-line to start Vim with two filenamesand use thediff mode without folding:    $ vim -o file1 file2 "+windo set diff scrollbind scrollopt+=hor nowrap"If you like vertically split windows, then replace "-o" with "-O".For more information, read:vimdiff=============================================================================faq-31SECTION 31 - GUI VIMfaq-31.131.1. HowdoI create buffer specific menus?Adding support for buffer specificmenusis in the Vim TODO list. In themean time, you can try Michael Geddes's plugin, buffermenu.vim:https://www.vim.org/scripts/script.php?script_id=246faq-31.231.2. HowdoI change the font used byGUI Vim?You can change the'guifont' option to change the font used byGUI Vim.  Todisplay the current value of this option, you can use    :set guifont?You can add the displayed font name to the.vimrc file to use the fontacross Vim sessions. For example, add the following line to the.vimrc fileto use Andale Mono font.    set guifont=Andale_Mono:h10:cANSIFor Win32,GTK and Photon version of Vim, you can use the following commandto bringupadialog which willhelp you inchanging the guifont:    :set guifont=*You can also use the-font Vim command line option to specify the font usedfor normal text.For more information, read:'guifont''guifontset''guifontwide'font-sizes-font-boldfont-italicfont-menufont-menufontsetfaq-31.331.3. WhenstartingGUI Vim, howdoI specify the location of the GVIM      window?You can use the "-geometry" command line argument to specify the locationof theGUI Vim window. For example:    $ gvim -geometry 80x25+100+300For more information, read:31.4-geomfaq-31.431.4. HowdoI adda horizontal scrollbar in GVim?You can enable the horizontal scrollbar by modifying the'guioptions'option:    :set guioptions+=bFor more information, read:'guioptions'gui-horiz-scrollfaq-31.531.5. HowdoI make the scrollbar appear in the left side by default?You can add the "l" flag to the'guioptions' option to make the scrollbarappear in the left side.    :set guioptions+=l    :set guioptions-=rFor more information, read:'guioptions'gui-scrollbarsfaq-31.631.6. HowdoI remove the Vim menubar?You can remove the Vim menubar by removing the "m" flag from the'guioptions' option:    :set guioptions-=mFor more information, read:'guioptions'faq-31.731.7.I am usingGUI Vim. WhenI press the<Alt> key anda letter, the menustarting with thatletteris selected.I don't want this behaviorasI want to map the<Alt>-<key> combination. HowdoIdo this?You can use the'winaltkeys' option to disable the use of the<Alt> key toselecta menu item:    :set winaltkeys=noFor more information, read:'winaltkeys':simaltfaq-31.831.8. Isit possible to scroll the text by dragging the scrollbar so that      the cursor stays in the original location?The way Vimis designed, the cursor position has to be ina visible spot innormal, visual, select andinsert mode. This cannot be changed withoutmodifying Vim. When the scrollbaris used, the cursor will be moved so thatitis always visible. Another approach to solving this problemis to usethe Vim marks. You canmark the current cursor position using ma. Thenscroll toa different part of the text and jump back to the old positionusing `a. You can also try the following suggestion from the Vim Onlinewebsite:http://vim.wikia.com/wiki/VimTip320For more information, read:mark-motionsfaq-31.931.9. HowdoI getgvim to start browsing files ina particular directory      when using the:browse command?You can set the'browsedir' option to the default directory to use for the:browse command.    :set browsedir='<your_dir>'For more information, read:'browsedir'faq-31.1031.10. For some questions, like whena fileis changed outside of Vim, Vim       displaysaGUIdialog box. HowdoI replace thisGUIdialog box witha consoledialog box?You can set the "c" flag in the'guioptions' option to configure Vim to useconsole dialogs instead ofGUI dialogs:    :set guioptions+=cFor more information, read:'guioptions'faq-31.1131.11.I am trying to useGUI Vimas the editor for my xxx application.       When the xxx application launchesGUI Vim to edita file, thecontrol immediately returns to the xxx application. HowdoI startGUI Vim, so that thecontrol returns to the xxx application only       afterI quit Vim?You have to startGUI Vim with the "-f" (foreground) command line option:    $ gvim -fBy default,GUI Vim will disconnect from the program that started Vim. Withthe '-f' option,GUI Vim will not disconnect from the program that startedit.For more information, read:gui-fork-ffaq-31.1231.12. Why does the "Select Font"dialog doesn't show all the fonts       installed in my system?Vim supports only fixed width (mono-spaced) fonts. Proportional fonts arenot supported.  In the "Select Font" dialog, only fixed width fonts will bedisplayed.For more information, read:font-sizes'guifont'faq-31.1331.13. HowdoI use the mouse in Vim command-line mode?You can set the "c" flag in the'mouse' option to use mouse in the Vimcommand-line mode:    :set mouse+=cFor more information, read:mouse-usinggui-mouse09.2faq-31.1431.14. WhenI use the middle mouse button to scroll text,it pastes the       last copied text. HowdoI disable this behavior?You can map the middle mouse button to<Nop> to disable the middle mousebutton:    :map  <MiddleMouse> <Nop>    :map! <MiddleMouse> <Nop>For more information, read:gui-mouse-mapping<Nop>faq-31.1531.15. HowdoI change the location and size ofaGUI Vim window?You can use the:winpos command to change the Vimwindow position. Tochange the size of the window, you can modify the'lines' and'columns'options.For example, the following commands will position theGUI Vimwindowat theX,Y co-ordinates 50,50 and set the number of lines to 50 and the number ofcolumns to 80.    :winpos 50 50    :set lines=50    :set columns=80The arguments to the:winpos command specify the pixel co-ordinates of theVim window. The'lines' and'columns'options specify the number of linesand characters to use for the height and the width of thewindowrespectively.For more information, read:31.4:winpos'lines''columns'GUIEnterfaq-31.1631.16. When splitting the Vimwindow vertically, Vim changes the position.Thisisa known problem. When you are splitting the Vim window, Vim willtry to drawa scrollbar. Since this changes thegui window, Vim tries toresize its mainwindow to keep the same position and this will cause Vimto move its position. This happens on Windows witha multi-window setup orawindow that was "snapped" toa certain position.A workaournd to this problem is, to removegui scrollbars, e.g.    :set guioptions-=L=============================================================================faq-32SECTION 32 - VIM ON UNIXfaq-32.132.1.I am running Vim ina xterm. WhenI press theCTRL-S key, Vim      freezes. What shouldIdo now?Manyterminal emulators and realterminal drivers use theCTRL-S key tostop the data from arriving so that you can stopa fastscrolling displayto lookatit (also allowed older terminals to slow down the computer sothatit did not get buffer overflows).  You can start the output again bypressing theCTRL-Q key.When you press theCTRL-S key, theterminal driver will stop sending theoutput data. Asa result of this,it will look like Vimis hung. If youpress theCTRL-Q key, then everything will be back to normal.You can turn off theterminal driver flowcontrol using the "stty" command:    $ stty -ixon -ixoffor, you can change the keys used for theterminal flow control, using thefollowing commands:    $ stty stop <char>    $ stty start <char>faq-32.232.2.I am seeing weird screen update problems in Vim. What canIdo to      solve this screen/display update problems?You have to usea properterminal emulator like xterm with correctTERMsettings (TERM=xterm) anda correct terminfo/termcap file.For more information, read:'term'faq-32.332.3.I am using the terminal/console version of Vim. In insertmode, WhenI      press thebackspace key, the character before the cursoris not      erased. HowdoI configure Vim todo this?You have to make sure that Vim gets the correct keycode for the backpspacekey. You can try using the command:    :fixdelMake sure theTERM environment variableis set to the correctterminalname. You can try using the "stty" command:    $ stty erase ^Hwhere, you have to enter the ^H character by pressing theCTRL-V key andthen theCTRL-H key. Also check the value of your'backspace' setting.For more information, read::fixdelLinux-backspaceNetBSD-backspace'backspace'faq-32.432.4.I am using Vim ina xterm. WhenI quit Vim, the screen contents are      restored back to the original contents. HowdoI disable this?The xterm hasa capability called "alternate screen".  If this capabilityis present, vim switches to that alternate screen uponstartup and back onexit, thus restoring the original screen contents.  To disable thisfeature, add the following line to your.vimrc file:    :set t_ti= t_te=For more information, read:'restorescreen'xterm-screensfaq-32.532.5. WhenI start Vim,it takes quitea few seconds to start. HowdoI      minimize thestartup time?This may be related to Vim opening theX display for setting the xtermtitle and using theX clipboard. Make sure the DISPLAY variableis set topoint to the correct host. Try using the command line:    $ vim -XThis will prevent Vim from opening theX display. With this command-lineoption, theXclipboard cannot be used and also Vim will not be able tochange the xterm title.You can also set the'clipboard' option to    :set clipboard=exclude:.*This has the same effectas using the-X command-line argument.For more information, read:-X'clipboard'If theclipboardis not the cause of the slow startup,it might beaplugin that slows down Vim. In that case, you can use the--startuptimeargument to debug this further. You can do:    $ vim --startuptime vim_startup.logand the timing will be written to the file vim_startup.log. For evenmore advanced profiling, you can use theprofiling feature, thatisavailable in huge builds of Vim. Todo so, call Vim like this:    $ vim --cmd 'profile start profile.log' \      --cmd 'profile func *' \      --cmd 'profile file *' \      -c 'profdel func *' \      -c 'profdel file *' \      -c 'qa!'After running this, you will havea file profile.log in your currentdirectory. To further analyse this, open the file profile.log and run:    " Open profile.log file in vim first    :let timings=[]    :g/^SCRIPT/call add(timings, [getline('.')[len('SCRIPT  '):], matchstr(getline(line('.')+1), '^Sourced \zs\d\+')]+map(getline(line('.')+2, line('.')+3), 'matchstr(v:val, ''\d\+\.\d\+$'')'))    :enew    :call setline('.', ['count total (s)   self (s)  script']+map(copy(timings), 'printf("%5u %9s   %8s  %s", v:val[1], v:val[2], v:val[3], v:val[0])'))For more information, read:--startuptimeprofilingfaq-32.632.6. How canI make the cursor ingvim inunix stop blinking?You can modify the'guicursor' option, to stop the cursor from blinking.For example:    :set guicursor=a:blinkon0For more information, read:'guicursor'faq-32.732.7. HowdoI change the menu font onGTK Vim?You can modify the ~/.gtkrc file to change the menu font onGTK Vim. Forexample:    style "default"    { font ="smooth09" }    class "*" style "default"The last line changes the font of all widgets.For more information, read:gui-gtkfaq-32.832.8. HowdoI preventCTRL-Z from suspending Vim?You can mapCTRL-Z to prevent the suspending. Here are some suggestions:- MakeCTRL-Zdo nothing:    :map <C-Z> <Nop>- MakeCTRL-Z starta shell:    :map <C-Z> :shell<CR>- MakeCTRL-Z give an error message:    :map <C-Z> :"suspending disabled<CR>For the last example, the doublequoteis necessary in order to keep themessage on the status line.faq-32.932.9. WhenI kill the xterm running Vim, the Vim process continues to run      and takes upa lot of CPU (99%) time. Whyis this happening?When Vimis built with support forPython interface, you will have thisproblem. Thisisa known problem with thepython thread library and Vim.  Tosolve this problem, usea Vim binary built without thePython interface.For more information, read:+pythonpythonfaq-32.1032.10. HowdoI get the Vimsyntax highlighting to work inaUnix terminal?The easiest and simplest way to get Vimsyntax highlightingis to use theGUI version of Vim (GVIM). To getsyntax highlighting to work in theconsole/terminal version of Vim, you have to runaterminal emulator (likeXfree86 xterm orrxvt or dtterm) that supports color.Note that ifaterminal emulator supportschanging the background and foreground colors,that does not mean thatit also supports ANSIescape sequences forchangingthe color. You candownload the latest version of Xfree86 xterm fromhttps://invisible-island.net/xterm/xterm.htmlYou candownload the latest version ofrxvt fromhttps://rxvt.orgYou have toinstall the terminfo/termcap file that supports colors for theterminal emulator. Also, set theTERM environment variable to the correctname of the term that supports colors.You can use thecolortest.vimscript supplied with the Vim runtimepackage to test the color setup. To use this script, follow these steps:    :e $VIMRUNTIME/syntax/colortest.vim    :source %For more information, read:06.2terminal-colorstermcap-colorsstartup-terminalxterm-colorcolortest.vim=============================================================================faq-33SECTION 33 - VIM ON MS-WINDOWSfaq-33.133.1. In MS-Windows,CTRL-V doesn't start the blockwise visual mode. What      happened?Themswin.vimscript provides key mappings andoptions to make Vim behavelikeaMS-Windows application. One of the keys mappedisCTRL-V whichisused for pasting text inMS-Windows applications. This will disable the useofCTRL-V to start the blockwise visual mode. Themswin.vimscript mapsCTRL-Q for staring the blockwise visual mode. So you can useCTRL-Q insteadofCTRL-V.For more information, read:CTRL-VCTRL-V-alternativeCTRL-Q10.5faq-33.233.2. WhenI press theCTRL-Y key,it acts like theCTRL-R key. HowdoI      configure Vim to treatCTRL-YasCTRL-Y?Themapping of theCTRL-Y key to theCTRL-R keyis done by themswin.vimscript. Themswin.vimscript mapsCTRL-Y to make Vim behave likea standardMS-Windows application. Thisis explained in `:helpCTRL-Y`. You can eithercomment out the line inmswin.vim that maps theCTRL-Y key or you canremove the line in your.vimrc file that sources themswin.vim script.faq-33.333.3. HowdoI startGUI Vim ina maximizedwindow always?You can use the:simalt command to maximize the Vim window. You can usetheGUIEnter autocmd to maximize the Vimwindow on startup:    autocmd GUIEnter * simalt ~xFor more information, read::simaltGUIEntergui-win32-maximizedfaq-33.433.4. After doing some editing operations, Vim freezes. The cursor becomes      an empty rectangle.I am not able enter any characters. Whatis      happening?Most probably, you used the mouse wheel to scroll the text in Vim. Thereisa known problem in using intellimouse mouse wheel with Vim. To avoid thisproblem, disable Universalscrolling support for Vim.For more information, read:intellimouse-wheel-problemsfaq-33.533.5.I am using Windows XP, the display speed of maximized GVimis very      slow. What canIdo to speed the display updates?This may be due to the fact that you have enabled 'Smooth edges of screenfonts' in the display properties. Try turning off font smoothing or trychanging the smoothingmethod to "Standard".faq-33.633.6. What are the recommended settings for using Vim with cygwin?You may want to set the following shell related Vim settings:    :set shellcmdflag=-c    :set shellquote=    :set shellslash          " Use the forward slash for expansion.    :set shellxquote=\"    :set shell=d:\cygwin\bin\bash.exe " Use the bash shell    :set shellpipe=2>&1| tee    :set shellredir=>%s 2>&1faq-33.733.7.I am trying to use GNUdiff with Vimdiff mode. WhenI run thediff      from command line,it works. WhenI try to use thediff with Vimit      doesn't work. What shouldIdo now?Thereisa problem with using GNUdiff with Vim. You can try using theGNU diff.exe built by Ron Aaron from the following link:http://www.mossbayeng.com/~ron/vim/builds.html(This page no longer exists.)faq-33.833.8. Isit possible to use Vimas an external editor forMS-Windows      Outlook email client?You can use the "cubiclevim" COM Add-In to use Vimas an external editorforMS-Windows Outlook email client. Visit the following URL for moreinformation:https://sourceforge.net/projects/cubiclevim/Note, that currently this works only with MS-Office 2000 and XP.Also theplugin OutlookVim might be wortha look:https://www.vim.org/scripts/script.php?script_id=3087faq-33.933.9.I am using Vim to edit HTML files. HowdoI startinternet explorer      with the current file to preview the HTML file?You can use the following command:    :!start c:\progra~1\intern~1\iexplore.exe file://%:p<CR>faq-33.1033.10.I would like to use Vim with MicrosoftVisual Studio. HowdoIdo       this?You have todownload and use the OLE version of Vim (for example:gvim61ole.zip). This file also contains instructions on how to use Vim withVisual Studio.For more information, read:MSVisualStudiofaq-33.1133.11. WheredoI place the_vimrc and_gvimrc files?You can place the_vimrc and_gvimrc files under the directory pointed toby the VIM environment variable. If you are sharing this system with otherusers, then you can place the files ina directory and set the HOMEenvironment variable to this directory.For more information, read:$HOME-use_vimrcfaq-33.1233.12. Every timeI savea file, Vim warns about the file being changed       outside of Vim. Why?If you get the following warning message, every time you savea file:    WARNING: The file has been changed since reading it!!!    Do you really want to write to it (y/n)?then this problem could be related toa bug inMS-Windows on the daydaylight saving time starts.  Vim remembers thetimestamp of the file afterit was written.  Just before the next write thetimestampis obtained againto check if the file was changed outside of Vim.  This works correctly,except on the day daylight saving time starts.This problem willgo away the next day after the day the daylight savingtime starts.For more information, read:W11=============================================================================faq-34SECTION 34 - PRINTINGfaq-34.134.1. HowdoI printa file along with line numbers for all the lines?You can set the'printoptions' option and use the:hardcopy command toprint your file:    :set printoptions=number:y    :hardcopyFor more information, read:'printoptions':hardcopyfaq-34.234.2. HowdoI printa file with the Vimsyntax highlighting colors?You can use the:hardcopy command to printa file with the Vimsyntaxhighlighting colors. You can also convert your file toa HTML file usingthe2html.vimscript and print the HTML file.For more information, read:syntax-printing2html.vim:hardcopyprinting=============================================================================faq-35SECTION 35 - BUILDING VIM FROM SOURCEfaq-35.135.1. HowdoI build Vim from the sources onaUnix system?ForaUnix system, follow these steps to build Vim from the sources:- Download the source from the git repository:https://github.com/vim/vim/releases/- Alternatively,download the source from the mercurial repository:https://bitbucket.org/vim-mirror/vim/downloads/- Run the "make" command to configure and build Vim with the default  configuration.- Run "makeinstall" command toinstall Vim in the default directory.To enable/disablevarious Vim features, before running the "make" commandyou can run the "configure" command with different flags to include/excludethevarious Vim features. Tolist all the availableoptions for the"configure" command, use:    $ configure --helpFor more information, read:installfaq-35.235.2. HowdoIinstall Vim in myhome directory ora directory other      than the default installation directory in Unix?Toinstall Vim ina directory other than the default installationdirectory, you have to specify the directory using the --prefix optionwhile running the configure script.    $ ./configure --prefix=/users/xyzYou can enable/disablevarious Vim feature by supplying different argumentsto the configure script. For more information about all these options, run:    $ ./configure --helpFor more information, read:install-homeinstallfaq-35.335.3. HowdoI build Vim from the sources onaMS-Windows system?ForaMS-Windows system, Vim can be built using either theVisual C++compiler or the Borland C++ compiler or the Ming GCC compiler or the cygwingcc compiler. Follow these steps to build Vim from the sources forMS-Windows:-download the source from the git repository:https://github.com/vim/vim/releases/- Depending on the installed compiler, you can use the corresponding      makefile to build the Vim sources. ForVisual C++ use the      Make_mvc.mak makefile, for borland C++ use the Make_bc5.mak makefile,      for ming GCC use the Make_ming.mak makefile, for cygwin gcc use the      Make_cyg.mak makefile.Depending on whether you want to build theGUI version of Vim or theconsole version of Vim, you have to pass different arguments to themakefiles. After successfully building the sources, you can copy thevim.exe or gvim.exe file to the desired directory along with the files fromthe runtime archive.For more information, read:installfaq-35.435.4. The Vim help, syntax, indent files are missing from my Vim      installation. HowdoIinstall these files?The Vim help, syntax, indent and other runtime files are part of the Vimruntime package. You need todownload andinstall the Vim runtime package.For example, for MS-Windows, the name of the Vim 6.1 runtime packageisvim61rt.zip.For more information, read:installfaq-35.535.5.I have built Vim from the source and installed the Vim package using      "makeinstall". DoI need to keep the Vim source directory?No. Once you have built and installed Vim in some directory other than theoriginal source directory (for example, /usr/bin or /usr/local/bin), thenyou can remove the source directory.faq-35.635.6. HowdoI determine the Vim features which are enabledat compile      time?You can use the:version command to determine the Vim features that areenabledat compile time. The features that are enabled will be prefixedwitha "+". The features that are not enabled will be prefixed witha "-".If you want to test fora feature ina script, you can use thehas()function:    if has("menu")        " Set up some menus    endifFor more information, read::version+feature-listhas()faq-35.735.7. CanI build Vim without theGUI support?Yes. You can build Vim by optionally enabling/disabling many of thefeatures including GUI.For more information, read:installfaq-35.835.8. When building Vim onaUnix system,I am getting "undefinedreference      to term_set_winsize" error. HowdoI resolve this error?You will get this error when the build processis not able to locate thetermlib,termcap or ncurses library. You have toinstall the ncurses-devpackage to resolve this error.faq-35.935.9. Vim configure keeps complaining about the lack of gtk-config while      trying to useGTK 2.03. Thisis correct, since inGTK 2 they moved to      using the generic pkg-config.I can get pkg-config tolist thevarious includes and libs for gtk, but for some reason the configurescript still isn't picking this up.Use the following shellscript named gtk-config:    #!/bin/sh    pkg-config gtk+-2.0 $1 $2faq-35.1035.10.I did successfullydownload the sources and compiled Vim on        Unix. But feature... still does not work. Whatis wrong and        how canI fix it?You should first check, that you are actually running yourself compiledVim and not the system's provided version. So first check your $PATHsetting.Depending on your compile options, some features might not be included inyour build of Vim. You can use the:version command to determine the Vimfeatures that are enabledat compile time. The features that are enabledwill be prefixed witha "+". The features that are not enabled will beprefixed witha "-".The easiest way to include all featuresis to build the huge version. Todothis, you have to specify the --with-features option while running theconfigure script:    $ ./configure --with-features=hugeNevertheless,a feature could still be disabledat compile time, if theconfigurescript can't find the required libraries for those features (e.g.forclipboard integration, your Vim needs to be linked against theX11development libraries).There are several ways toinstall the required libraries:1) Ona Debian based distribution, you can use the package manager "apt"   toinstall all required dependencies. As superuser, run the command:$ apt-get build-dep vim-gtk   This makes sure all required libraries needed to compile the vim-gtk   package will be installed. (This requires, that your sourceslist   contains deb-src entries. See yourdistribution manual on how to   enable this, if the above command did not work.)2) In openSUSE you can use the package manager "zypper" toinstall all   required libraries. This requires, that thereisa source version of   the package installable froma configured repository (which by   defaultis not the case). Use:$ zypper search-t srcpackage vim   to find out, whether or not there existsa source version in the   repository. If thereis none, you'll need to adda source repository.   For openSUSE11.2 you could use, e.g.$ zypper arhttp://download.opensuse.org/source/distribution/11.2/repo/oss/src-11.2   (one line)   Once you havea source version available in your repositories, use   this command toinstall all needed requirements:$ zypper source-install --build-deps-only vim3) Ona Fedora/RedHat based system, you can use$ yum-builddep vim-enhanced4) Run configure with youroptions and watch for missing libraries:$ ./configure --with-features=huge 2>&1 |tee logfile   This will run configure and record the output into the file "logfile".   You need to check the logfile for missing dependencies. Consider this   output:    checking --disable-gtktest argument... gtk test enabled    checking for pkg-config... /usr/bin/pkg-config    checking for GTK - version >= 2.2.0... no    Here you can see, that the gtk libraries are missing and therefore    noGTKgui version can't be build. So you need toinstall theGTK    library in your system, with your package manager or by compilingit    yourself. Then run the configurescript again and check, thatit    finds the library.In theory, those provided dependencies by yourdistribution might stilllack some libraries, that are needed for features, that simply are notenabled in yourdistribution and therefore those commands in 1-3 won'tinstall it. At the very least, this providesa jumping point and you needto track down the required missingpackages usingmethod 4 from above. Butusually, this works good enough for most people and you won't have tobother with the fourth method.For more information, read::version+feature-list=============================================================================faq-36SECTION 36 - VARIOUSfaq-36.136.1. HowdoI edit binary files with Vim?You can set the followingoptions to edit binary files in Vim:    :set binary    :set display=uhexYou can also use the "-b" command-line option to edita binary file:    $ vim -b <binary_file_name>You can also use the xxd utility (part of the Vim distribution) to editbinary files.For more information, read:23.4edit-binaryhex-editing-b'binary''endofline''display'faq-36.236.2. HowdoI disable the visual error flash and the error beep?You can disable both the visual error flash and the errorbeep using thefollowing command:    :set visualbell t_vb=For more information, read:'visualbell''errorbells't_vbfaq-36.336.3. HowdoI display the ascii value ofa character displayed ina      buffer?You can use the "ga" command to display the ascii value ofa displayedcharacter.For more information, read:ga:asciifaq-36.436.4. CanI use zeroasacount fora Vim command?You cannot use zeroasacount fora Vim command,as "0"isa command onits own, moving to the first column of the line.For more information, read:0countfaq-36.536.5. HowdoI disable the Vim welcome screen?You can disable the Vim welcome screen, by adding the "I" flag to the'shortmess' option:    :set shortmess+=IFor more information, read::intro'shortmess'faq-36.636.6. HowdoI avoid the "hit enter to continue" prompt?Vim will prompt you with the "hit enter to continue" prompt, if there aresomemessages on the screen for you to read and the screenis about to beredrawn.  You can add the "T" flag to the'shortmess' option to truncateall messages. This willhelp in avoiding thehit-enter prompt:    :set shortmess+=TYou can also increase the command height by setting the'cmdheight' option:    :set cmdheight=2For more information, read:hit-enteravoid-hit-enter'shortmess''cmdheight'faq-36.736.7. HowdoI invoke Vim from command line to runa group of commands ona      group of files?There are several ways to invoke Vim from command line to runa group ofcommands ona group of files. You can usea set of  "-c" command lineoptions to specifya group of commands:    $ vim -c "<ex_command_1>" -c "<ex_command_2>" *.txtEach of the ex-command specified with the "-c" command line optionisexecuted one by one sequentially. You can also usea single "-c" commandline option and the "|" character to separate theex commands:    $ vim -c "<ex_command_1> | <ex_command_2>" *.txtIn the above command, if anex command fails, then all the remainingexcommands will not be executed.For example, to replace "ABC" with "DEF" ina file from the command-line,you can use the following command:    $ vim -c "%s/ABC/DEF/ge | update" myfile.txtTo replace "ABC" with "DEF" in multiple files from the command-line,you can use the following command:    $ vim -c "argdo %s/ABC/DEF/ge | update" *.txtYou can store the group of commands intoa file and use the "-s" commandline option to run the commands ona set of files. For example, if thegroup of commands are stored in the file mycmds.txt, then you can use thefollowing command:    $ vim -s mycmds.txt *.plFor more information, read:-c-sfaq-36.836.8. HowdoI usea normal mode command frominsert mode without leaving      theinsert mode?You can usea normal command frominsert mode, without leaving theinsertmode, by first pressing theCTRL-O key and then follow that witha singlenormal mode command.To execute more than one normal mode command, press theCTRL-L key,followed by any number of normal mode commands and then press<Esc> to getback to theinsert mode. (This only works, when the'insertmode' optionis set).For more information, read:i_CTRL-Oi_CTRL-Lfaq-36.936.9. HowdoI start Vim ininsert mode?You can start Vim ininsert mode using the:startinsertex command.    $ vim +startinsert myfile.txtThe above command will open the file "myfile.txt" and startinsert modewith the cursor in front of the first character on the first line.  To openthe file and start appending after the last character on the last line,you can use the following command:    $ vim + +startinsert! myfile.txtFor more information, read::startinsertfaq-36.1036.10. HowdoI use Copy and Paste with Vim?You should first check the output of the:version command and makesure that +xterm-clipboardis present.When running Vim in an xterm, you can either let Vimcontrol the mouseor let xtermcontrol the mouse. Thisis configured by the'mouse' option.If the'mouse' optionis not set (or set to the default value), then Vim willnotcontrol the mouse. You cannot move the Vim text cursor using themouse. When you select some text using the mouse, xterm will copyit to theX11 cut buffer. When you press both the mouse buttons,xterm will paste the text from the cut buffer.If the'mouse' optionis set to "a" or some other value, then Vim controlsthe mouse. The mode (normal orinsert or visual, etc) in which Vimcontrols the mouseis configured by the'mouse' option. You can movethe Vim text cursor using the mouse. When you select some text,the'clipboard' option settingis used to determine whether to transferthe selected text to theclipboard or not. The default settingis totransfer the selected text to the clipboard. If you want to use thexterm selection mechanism in this mode, then you can press the<Shift> key. If you press<Shift> key when selecting text using themouse, then Vim doesn'tcontrol the mouse and xterm controls themouse.In theGUI mode, Copy and Paste should just work, depending on the'mouse'setting. For more information, read:'clipboard'x11-selectionclipboard'go-a''mouse'xterm-copy-paste09.3faq-36.1136.11. Why shouldn'tI modify the files in the system runtime directory?Just be careful about modifying files under $VIMRUNTIME, which usuallyis /usr/share/vim/vimXX (Unix) or C:\Program Files\vim\vimXX(Windows) and XX being the version for whichit applies, e.g. 73 for Vim7.3.One should generally avoid modifying those files because they may bereplaced during an upgrade of your Vim installation and your changeswill be lost.  Also, if you upgrade toa new major or minor revision ofVim (e.g., from 7.3 to 7.4), the new version of Vim will usea different$VIMRUNTIME directory and while your changes won't be lost, they will beignored.Consequently, takea lookatfiletypesfor an explanation of several ways to modify Vim's response todifferentfiletypes and where toput those modifications so thatthey will not be overwritten.=============================================================================faq-37SECTION 37 - UNICODEAuthor: Tony Mechelynck <antoine.mechelynck AT belgacom.net>faq-37.137.1. Isit possible to createUnicode files using Vim?Yes. It may be more orless complicated depending on the keyboard and fontsavailable to you, butitis always possible to encode any possibleUnicodecodepoint (and some illegal ones) intoa file. To createaUnicode fileusing Vim, you should have compiled Vim with the "+multi_byte" compile-timeoption.  You can get more information aboutUnicode from the followingsites:http://www.unicode.orghttps://www.cl.cam.ac.uk/~mgk25/unicode.htmlFor more information, read:multibyteusr_45.txtfaq-37.237.2. Which Vim settings are particularly important for editingUnicode      files?The most important are thevarious "encoding" options, i.e.,'encoding','fileencoding','fileencodings' and'termencoding'. Theboolean option'bomb'is also significant.For more information, read:'encoding''fileencoding''fileencodings''termencoding''bomb'faq-37.337.3. Whatis the'encoding' option?Basically, the'encoding' option defines how Vim will represent your datainternally.  However, allUnicode encodings are represented internallyasutf-8 and converted (if necessary) when reading and writing.For more information, read:'encoding'faq-37.437.4. How does Vim name thevariousUnicode encodings?Utf-8is calledutf-8 or utf8; utf-16is called ucs-2 or ucs2; utf-32iscalled ucs-4 or ucs4. Also, you may specify endianness (except forutf-8which does not vary for endianness) by appending le for little-endian or befor big-endian. If you createa file with an encoding of ucs-2 or ucs-4without specifying endianness, Vim will use whatis typical of yourmachine.For more information, read:encoding-namesencoding-valuesencoding-tablefaq-37.537.5. How does Vim specify the presence or absence ofa byte-order mark?When readinga file, if the'fileencodings' option includes "ucs-bom", Vimwill check fora byte-order mark. Whenwritinga file, if the'bomb' optionis set, Vim will writea byte-ordermark on files whose encoding warrantsit.For more information, read:'fileencodings''bomb'faq-37.637.6. Whatis the'fileencoding' option?The'fileencoding' option defines the particular encoding which Vim willuse to writea file. If empty, then the value of the'encoding' optionisthe default.For more information, read:'fileencoding'faq-37.737.7. Whatis the'fileencodings' option?The'fileencodings' option defines the heuristics used by Vim when openingan existing file. Itisa comma separatedlist of encodings.A specialname, "ucs-bom"is used to indicate that Vim should check for the presenceofa byte-order mark; however,it will not be recognised ifit comes after"utf-8".  Normally, "ucs-bom" (if present) should be first in the list.When Vim opensa file,it checksit against the encodings listed in'fileencodings'. The first one that matchesis used. If thereis no match,then Vim sets'fileencoding' to thenull string, i.e., the value of'encoding' will be used.For more information, read:'fileencodings''encoding'faq-37.837.8. Whatis the'termencoding' option?The'termencoding' option defines how your keyboard encodes the data youtype.  If empty, Vim assumes thatit has the same valueas'encoding'.Usuallyit should be set to something that matches your locale.For more information, read:'termencoding'localefaq-37.937.9. Whatis the'bomb' option?When readinga file with "ucs-bom" present in the'fileencodings' option,Vim will set the'bomb' option on or off depending on the presence orabsence ofa byte-ordermarkat the start of the file. When writing, Vimwill writea byte-ordermark if the'bomb' optionis set. You may set orunsetit manuallydo make Vim write, or not write, the b.o.m.For more information, read:'bomb'faq-37.1037.10. Where canI find an example ofa typical use of all these options?Thereisa "tip", with explains them in different words with an example,athttp://vim.wikia.com/wiki/VimTip246faq-37.1137.11. How canIinsertUnicode characters intoa file using Vim?Several methods are available:- Characters present on your keyboard can be typed in the usual way, even  those which requirea "dead-key" prefix, like (for instance) the  circumflex on French keyboards.- Characters for whichadigraphis defined can be typedas two characters  prefixed byCTRL-K.- If you have set the'digraph' option, you can enter the characters for  whichadigraphis definedas<char1><BS><char2>.- Any character can be entered by usingaCTRL-V prefix (orCTRL-Q ifCTRL-Vis remapped to paste from the clipboard).For more information, read:digraphs'digraph'i_CTRL-V_digitfaq-37.1237.12. How canI know whichdigraphs are defined and for which characters?First set the'encoding' option properly (for instance, to utf-8), then usethe:digraphs command tolist the currently defined digraphs.Alternatively, thehelp file contains the complete set of all digraphs.So you can easily search thatlist there.For more information, read::digraphs'encoding'digraph-table vim:tw=78:ts=8:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2026 Movatter.jp