develop.txt ForVim version 9.2. Last change: 2026 Feb 14VIM REFERENCE MANUAL by Bram MoolenaarDevelopment of Vim.developmentThis textis important for those who want to be involved in further developingVim.1. Design goalsdesign-goals2. Design decisionsdesign-decisions3. Assumptionsdesign-assumptions4. Coding stylecoding-style5. Policydesign-policySee the file README.txt in the "src" directory for an overview of the sourcecode.Vimis open source software. Everybodyis encouraged to contribute tohelpimproving Vim. For sending patchesa unifieddiff "diff-u"is preferred.You can createa pull request on github, but it's not required.Also seehttp://vim.wikia.com/wiki/How_to_make_and_submit_a_patch.==============================================================================1. Design goalsdesign-goalsMost important things come first (roughly).Note that quitea few items are contradicting. Thisis intentional.Abalancemust be found between them.VIM IS... VI COMPATIBLEdesign-compatibleFirst of all,it should be possible to use Vimasa drop-in replacement forVi. When the user wants to, Vim can be used in compatible mode and hardlyany differences with the originalVi will be noticed.Exceptions:- We don't reproduce obviousVibugs in Vim.- There are different versions of Vi.I am using Version 3.7 (6/7/85)asa reference. But support for other versionsis also included when possible. TheVi part of POSIXis not considereda definitive source.- Vim adds new commands, you cannot rely on some command to fail becauseit didn't exist in Vi.- Vim will havea lot of features thatVi doesn't have. Going back from Vim toVi will bea problem, this cannot be avoided.- Some things are hardly ever used (open mode, sending an e-mail when crashing, etc.). Those will only be included when someone hasa good reason whyit should be included and it's not too much work.- For some itemsitis debatable whetherVi compatibility should be maintained. There will be an option flag for these.VIM IS... IMPROVEDdesign-improvedThe IMproved bits of Vim should makeita better Vi, without becomingacompletely different editor. Extensions are done witha "Vi spirit".- Use the keyboardas muchas feasible. The mouse requiresa third hand, which we don't have. Many terminals don't havea mouse.- When the mouseis used anyway, avoid the need to switch back to the keyboard. Avoid mixing mouse and keyboard handling.- Add commands andoptions ina consistent way. Otherwise people will havea hard time finding and remembering them. Keep in mind that more commands andoptions will be added later.-A feature that peopledo not know aboutisa useless feature. Don't add obscure features, orat least add hints in documentation that they exist.- Minimize using CTRL and other modifiers, they are more difficult to type.- There are many first-time and inexperienced Vim users. Makeiteasy for them to start using Vim and learn more over time.- Thereis no limit to the features that can be added. Selecting new featuresis one based on (1) what users ask for, (2) how much effortit takes to implement and (3) someone actually implementing it.VIM IS... MULTI PLATFORMdesign-multi-platformVim tries tohelpas many users onas many platformsas possible.- Support many kinds of terminals. The minimal demands are cursor positioning and clear-screen. Commands should only use key strokes that most keyboards have. Support all the keys on the keyboard for mapping.- Support many platforms.A conditionis that thereis someone willing todo Vimdevelopment on that platform, andit doesn't mean messing up the code.- Support many compilers and libraries. Not everybodyis able or allowed toinstall another compiler orGUI library.- People switch from one platform to another, and fromGUI toterminal version. Features should be present in all versions, orat least inas manyas possible witha reasonable effort. Try to avoid that usersmust switch between platforms to accomplish their work efficiently.- Thata featureis not possible on some platforms, or only possible on one platform, does not meanit cannot be implemented. [This intentionally contradicts the previous item, these twomust be balanced.]VIM IS... WELL DOCUMENTEDdesign-documented-A feature that isn't documentedisa useless feature.A patch fora new featuremust include the documentation.- Documentation should be comprehensive and understandable. Using examplesis recommended.- Don't make the text unnecessarily long. Less documentation means that an itemis easier to find.VIM IS... HIGH SPEED AND SMALL IN SIZEdesign-speed-sizeUsing Vimmust not bea big attack on system resources. Keepit small andfast.- Computers are becoming faster and bigger each year. Vim can grow too, but no faster than computers are growing. Keep Vim usable on older systems.- Many users start Vim froma shell very often. Startup timemust be short.- Commandsmust work efficiently. The time they consumemust beas smallas possible. Useful commands may take longer.- Don't forget that some people use Vim overa slow connection. Minimize the communication overhead.- Items that add considerably to the size and are not used by many people should bea feature that can be disabled.- Vimisa component among other components. Don't turnit intoa massive application, but haveit work well together with other programs.VIM IS... MAINTAINABLEdesign-maintain- The source code should not becomea mess. It should be reliable code.- Use the same layout in all files to makeiteasy to readcoding-style.- Use comments ina useful way! Quoting the function name and argument namesis NOT useful. Do explain what they are for.- Porting to another platform should be made easy, without having to change too much platform-independent code.- Use the object-oriented spirit: Put data and code together. Minimize the knowledge spread to other parts of the code.VIM IS... FLEXIBLEdesign-flexibleVim should makeiteasy for users to work in their preferred styles ratherthan coercing its users into particular patterns of work. This can be foritems witha large impact (e.g., the'compatible' option) or for details. Thedefaults are carefully chosen such that most users will enjoy using Vimasitis. Commands andoptions can be used to adjust Vim to the desire of the userand its environment.VIM IS... NOTdesign-not- Vimis nota shell or an Operating System. It does provideaterminal window, in which you can runa shell or debugger. E.g. to be able todo this over an ssh connection. But if you don't needa text editor with thatitis out of scope (use something like screen ortmux instead).A satirical way to say this: "Unlike Emacs, Vim does not attempt to include everything but the kitchen sink, but some people say that you can clean one with it. ;-)" To use Vim withgdb seeterminal-debugger. Other (older) tools can be foundathttp://clewn.sf.net.- Vimis nota fancyGUI editor that tries to look niceat the cost of beingless consistent over all platforms. But functionalGUI features are welcomed.==============================================================================2. Design decisionsdesign-decisionsFoldingSeveral forms offolding should be possible for the same buffer. For example,have onewindow that shows the text with function bodies folded, anotherwindow that showsa function body.Foldingisa way to display the text. It should not change the text itself.Therefore thefolding has been implementedasafilter between the text storedina buffer (buffer lines) and the text displayed inawindow (logical lines).Naming thewindowTheword "window"is commonly used for several things:Awindow on the screen,the xterm window,awindow inside Vim toviewa buffer.To avoid confusion, other items that are sometimes calledwindow have beengiven another name. Hereis an overview of the related items:screenThe whole display. For theGUI it's something like 1024x768pixels. The Vim shell can use the whole screen or part of it.shellThe Vim application. This can cover the whole screen (e.g.,when running ina console) or part ofit (xterm or GUI).windowView ona buffer. There can be severalwindows in Vim,together with the command line, menubar, toolbar, etc. theyfit in the shell.Spell checkingdevelop-spellWhenspell checking was going to be added to Vima survey was done over theavailablespell checking libraries and programs. Unfortunately, the resultwas that none of them provided sufficient capabilities to be usedas thespellchecking engine in Vim, forvarious reasons:- Missing support formultibyte encodings. At leastUTF-8must be supported, so that more than one language can be used in the same file. Doing on-the-fly conversionis not always possible (would require iconv support).- For the programs and libraries: Using them as-is would require installing them separately from Vim. That's mostly not impossible, buta drawback.- Performance:A few tests showed that it's possible to check spelling on the fly (while redrawing), just likesyntax highlighting. But the mechanisms used by other code are much slower.Myspell usesa hashtable, for example. The affix compression that mostspell checkers use makesit slower too.- For using an external program like aspella communication mechanism would have to be setup. That's complicated todo ina portable way (Unix-only would be relatively simple, but that's not good enough). And performance will becomea problem (lots of process switching involved).- Missing support for words with non-word characters, suchas "Etten-Leur" and "et al.", would require marking the pieces of them OK, lowering the reliability.- Missing support for regions or dialects. Makesit difficult to accept all English words and highlight non-Canadian words differently.- Missing support for rare words. Many words are correct but hardly ever used and could bea misspelled often-used word.- For making suggestions the speedisless important and requiring toinstall another program or library would be acceptable. But theword lists probably differ, the suggestions may be wrong words.Spelling suggestionsdevelop-spell-suggestionsFor making suggestions there are two basic mechanisms:1. Trychanging the badworda little bit and check fora match witha good word. Orgo through thelist of good words, change thema little bit and check fora match with the bad word. The changes aredeletinga character,insertinga character, swapping two characters, etc.2. Perform soundfolding on both the badword and the good words and then find matches, possibly witha few changes like with the first mechanism.The firstis good for finding typing mistakes. After experimenting withhashtables and lookingat solutions from otherspell checkers the conclusionwas thata trie (a kind of tree structure)is ideal for this. Both forreducing memory use and being able to try sensible changes. For example, wheninsertinga character only characters that lead to good words need to betried. Other mechanisms (with hashtables) need to try all possible lettersatevery position in the word. Also,a hashtable has the requirement thatwordboundaries are identified separately, whilea trie does not require this.That makes the mechanisma lot simpler.Soundfoldingis useful when someone knows how the words sounds but doesn'tknow howitis spelled. For example, theword "dictionary" might be writtenas "daktonerie". The number of changes that the firstmethod would need totryis very big, it's hard to find the goodword that way. After soundfoldingthe words become "tktnr" and "tkxnry", these differ by only two letters.To find words by their soundfolded equivalent (soundalike word) we needalistof all soundfolded words.A few experiments have been done to find out whatthe bestmethod is. Alternatives:1. Do the soundfolding on the fly when looking for suggestions. This means walking through the trie of good words, soundfolding eachword and checking how differentitis from the bad word. Thisis very efficient for memory use, but takesa long time. Ona fast PCit takesa couple of seconds for English, which can be acceptable for interactive use. But for some languagesit takes more than ten seconds (e.g., German, Catalan), whichis unacceptably slow. For batch processing (automatic corrections) it's too slow for all languages.2. Usea trie for the soundfolded words, so that searching can be done just like howit works without soundfolding. This requires rememberingalist of good words for each soundfolded word. This makes finding matches very fast but requires quitea lot of memory, in the order of 1 to 10 Mbyte. For some languages more than the originalword list.3. Like the second alternative, but reduce the amount of memory by using affix compression and store only the soundfolded basic word. Thisis what Aspell does. Disadvantageis that affixes need to be stripped from the badword before soundfolding it, which means that mistakesat the start and/orend of theword will cause the mechanism to fail. Also, this becomes slow when the badwordis quite different from the good word.The choice madeis to use the second mechanism and usea separate file. Thiswaya user with sufficient memory can get very good suggestions whilea userwhois short of memory or just wants thespell checking and no suggestionsdoesn't use so much memory.Word frequencyForsorting suggestionsit helps to know which words are common. In theory wecould storeaword frequency with theword in the dictionary. However, thisrequires storingacount per word. That degradesword tree compressiona lot.And maintaining theword frequency for all languages will bea heavy task.Also,it would be nice to prefer words that are already in the text. This waythe words that appear in the specific text are preferred for suggestions.What has been implementedis tocount words that have been seen duringdisplaying.A hashtableis used to quickly find theword count. Thecountisinitialized from words listed in COMMON items in the affix file, so thatitalso works whenstartinga new file.This isn't ideal, because the longer Vimis running the higher the countsbecome. But in practiceitisa noticeable improvement over not using theword count.==============================================================================3. Assumptionsdesign-assumptionsThe following sections define the portability and compatibility constraintsthat all Vim code and build toolsmust adhere to.MAKEFILESassumptions-makefilesPOSIX.1-2001Vim's main Makefiles target maximum portability, relying solely on featuresdefined inPOSIX.1-2001make and ignoring later POSIX standards or GNU/BSDextensions. In practical terms, avoid:-%pattern rules- modern assignment (`:=`,::=) outsidePOSIX.1-2001- special targets (`.ONESHELL`,.NOTPARALLEL,.SILENT, ...)- order-only prerequisites (`|`) or automatic directory creation- GNU/BSD conditionals (`ifdef`,ifndef,.for/.endfor, ...)SincePOSIX.1-2001 supports only traditional suffix rules, everyobject builtina separate directorymust have an explicit rule. For example:objects/evalbuffer.o: evalbuffer.c$(CCC)-o $@ evalbuffer.cThis verbosity ensures that the same Makefile builds Vim unchanged with thedefaultmake on Linux, *BSD, macOS, Solaris, AIX, HP-UX and virtually anyUnix-like OS.Some platform-specific Makefiles (e.g., for Windows, NSIS, or Cygwin) may usemore advanced features when compatibility with basic makeis not required.C COMPILERassumptions-C-compilerANSI-CC89C90C95C99Vim strives for maximum portability (seedesign-multi-platform) andmuststill build with CompaqC V6.4-005 on OpenVMS VAX V7.3.Therefore, the latest ISOC standard we follow is:C95 (ISO/IEC 9899:1990/AMD1:1995)In addition, the followingC99 features are explicitly allowed:-// comments,as required bystyle-comments;- Mixed declarations and statements ina block;- Variadic macros `(..., __VA_ARGS__)`;- Trailing comma inenum lists;-_Bool type (forbool,true andfalse);-__func__ predefined identifier;-inlinefunctions (use `static inline` for portability);- Compound literals `(type){ initializer-list }`;- Logical source lines up to 4095 characters.Platform-specific code may use any newer compiler features supported on thatplatform.SIZE OF VARIABLESassumptions-variablesWe followPOSIX.1-2001 (SUSv3) for type sizes, which in practice means:char_u 8-bit unsignedint 32-bit or larger signedunsigned 32-bit or larger unsignedFUNCTION PROTOTYPESassumptions-prototypesVim does not use conventional header files (`.h`) for most internal functionprototypes. Instead, the current architecture uses individual.pro files inthesrc/proto/ directory, with one.pro file per.c file.Unlike traditional self-contained header files, these.pro filesdo notcontain API documentation, struct andenum definitions, or other declarations;only function prototypes.The `make proto` target insrc/Makefile automates updating most of the .profiles using thePythonscript proto/gen_prototypes.py, which relies on thepython3-clang module.Note thata few proto files are hand edited.==============================================================================4. Coding stylecoding-styleThese are the rules to use when making changes to the Vim source code. Pleasestick to these rules, to keep the sources readable and maintainable.Thislistis not complete. Look in the source code for more examples.The code repository contains an editorconfig file, that can be used togetherwith the distributed editorconfigplugineditorconfig-install to ensure therecommended styleis followed.MAKING CHANGESstyle-changesThe basic steps to make changes to the code:1. Get the code from github. That makesit easier to keep your changed version in sync with the main code base (it may bea while before your changes will be included).2. Adjust the documentation. Doing this first gives you an impression of how your changes affect the user.3. Make the source code changes.4. Check ../doc/todo.txt if the change affects any listed item.5. Adda test to src/testdir to verify the new behaviour and ensureit won't regress in the future.6. Makea patch with "gitdiff".7. Makeanote about what changed, preferably mentioning the problem and the solution. Send an email to thevim-devmaillist with an explanation and include the diff.For any non-trivial change, please always createa pull request on github,since this triggers the test suite.A PR should ideally containa single commit fora single logical change.However, you can include several commits if you want to group multiplelogical, atomic changes in one PR. This can also make longer PRs easier toreview. Be sure to describe the reasoning for your changes in each commitmessage,as this greatly helps with the review process. In cases where eachcommit handles different logical changes, they will also be appliedasseparate patches in Vim's repository.style-clang-formatsound.c and sign.c can be (semi-) automatically formatted using theclang-format formatter according to the distributed .clang-format file.Other source filesdo not yet correspond to the .clang-format file. This maychange in the future and they may be reformattedas well.COMMENTSstyle-commentsTry to avoid putting multiline comments insidea function body: if thefunctionis so complex that you need to separately comment parts of it, youshould probably rethink the structure of the function.For file headers and function descriptions use: /* * Description */For everything else use: // commentINDENTATIONstyle-indentationWe use 4space to indent the code. If you are using Vim to edit the source,you don't need todo anything due to themodeline.For other editors an.editorconfigis providedat the root of the repo.For the source filessign.c andsound.c and any new file use only spaces,no tabs. In addition, any new filemust includeamodeline with `set et` topass the indentation test.DECLARATIONSstyle-declarationsDeclare, when possible,for loopvariables in the guard:OK: for (int i = 0; i < len; ++i)Wrong: int i; for (i = 0; i < len; ++i)Always declarea variable witha default value:OK: int n = 0; int *ptr = NULL;Wrong: int n; int *ptr;BRACESstyle-bracesAll curly bracesmust be returned ontoa new line:OK: if (cond) {cmd;cmd; } else {cmd;cmd; }Wrong: if (cond) {cmd;cmd; } else {cmd;cmd; }OK: while (cond) {cmd;cmd; }Wrong: while (cond) {cmd;cmd; }OK: do {cmd;cmd; } while (cond);or do {cmd;cmd; } while (cond);Wrong: do {cmd;cmd; } while (cond);TYPESstyle-typesUse descriptive types. These are defined in src/vim.h, src/structs.h etc.Note that all custom types are postfixed with "_T"Example: linenr_T buf_T pos_TSPACES AND PUNCTUATIONstyle-spacesNospace betweena function name and the bracket:OK:func(arg);Wrong: func (arg);Do useaspace afterif,while,switch, etc.OK:if (arg)for (;;)Wrong:if(arg)for(;;)Useaspace aftera comma or semicolon:OK:func(arg1, arg2);for (i= 0;i< 2; ++i)Wrong: func(arg1,arg2);for (i= 0;i< 2;++i)Useaspace before and after '=', '+', '/', etc.OK:var=a * 5;Wrong:var=a*5;Use empty lines to group similar actions together.OK: msg_puts_title(_("\n--- Signs ---")); msg_putchar('\n'); if (rbuf == NULL)buf = firstbuf; elsebuf = rbuf; while (buf != NULL && !got_int)Wrong: msg_puts_title(_("\n--- Signs ---")); msg_putchar('\n'); if (rbuf == NULL)buf = firstbuf; elsebuf = rbuf; while (buf != NULL && !got_int)FUNCTIONSstyle-functionsUse function declarations with the return type ona separate indented line.OK: int function_name(int arg1, int arg2) { }Wrong: int function_name(int arg1, int arg2) { }Give meaningful names to function parameters.USE OF COMMON FUNCTIONSstyle-common-functionsSomefunctions that are common to use, havea special Vim version. Alwaysconsider using the Vim version, because they were introduced witha reason.NORMAL NAMEVIM NAMEDIFFERENCE OF VIM VERSIONfree()vim_free()Checks for freeing NULLmalloc()alloc()Checks for out of memory situationmalloc()lalloc()Like alloc(), but has long argumentstrcpy()STRCPY()Includes cast to (char *), for char_u * argsstrchr()vim_strchr()Accepts special charactersstrrchr()vim_strrchr()Accepts special charactersisspace()vim_isspace()Can handle characters> 128iswhite()vim_iswhite()OnlyTRUE fortab andspacememcpy()mch_memmove()Handles overlapped copiesbcopy()mch_memmove()Handles overlapped copiesmemset()vim_memset()Uniform for all systemsNAMESstyle-namesFunction names can not be more than 31 characters long (because of VMS).Don't use "delete" or "this"asa variable name, C++ doesn't like it.Because of the requirement that Vim runs onas many systemsas possible, weneed to avoid using names that are already defined by the system. Thisisalist of names that are known to cause trouble. The nameis givenasaregexppattern.is.*()POSIX, ctype.hto.*()POSIX, ctype.hd_.*POSIX, dirent.hl_.*POSIX, fcntl.hgr_.*POSIX, grp.hpw_.*POSIX, pwd.hsa_.*POSIX, signal.hmem.*POSIX, string.hstr.*POSIX, string.hwcs.*POSIX, string.hst_.*POSIX, stat.htms_.*POSIX, times.htm_.*POSIX, time.hc_.*POSIX, termios.hMAX.*POSIX, limits.h__.*POSIX, system_[A-Z].*POSIX, systemE[A-Z0-9]*POSIX, errno.h.*_tPOSIX, for typedefs. Use.*_T instead.waitdon't useas argument toa function, conflicts with types.hindexshadows global declarationtimeshadows global declarationnewC++ reserved keywordclearMac curses.hechoMac curses.hinstrMac curses.hmetaMac curses.hnewwinMac curses.hnlMac curses.hoverwriteMac curses.hrefreshMac curses.hscrollMac curses.htypeaheadMac curses.hbasename()GNUstring functiondirname()GNUstring functionget_env_value()Linux system functionVARIOUSstyle-variousDefine'd names should be uppercase: #define SOME_THINGFeatures always start with "FEAT_": #define FEAT_FOODon't use '\"', some compilers can't handle it.'"' works fine.Don't use: #if HAVE_SOMESome compilers can't handle that and complain that "HAVE_SOME"is not defined.Use #ifdef HAVE_SOMEor #if defined(HAVE_SOME)STYLEstyle-examplesOne statement per line.Wrong: if (cond)a= 1;OK: if (cond)a= 1;Wrong: while (cond);OK: while (cond);Wrong:doa= 1; while (cond);OK:doa= 1; while (cond);==============================================================================5. Policydesign-policynew-featuresdeprecated-featuresThe time between eithera new minor (e.g. 9.2.0) or major (e.g. 10.0) versionis releasedis calledadevelopment cycle. Within thedevelopment cycle eachsingle change to theC core will receivea new increased human-readable patchnumber in order toreference each specific patch release.A typicaldevelopment release cycle may last several years and accumulate about 1500-2500 patch numbers.Beforea releaseis made,a stability period will be announced. During thistime, only clear bug fixes, security fixes, documentation changes, translationupdates and runtime file updates will be accepted (provided theydo notintroduce backwards-incompatible changes), concentrating on polishing up theupcoming release.New features are accepted only withinadevelopment cycle, but not within thestability period. During the cycle, new features may be developed and areallowed to change, but theymust be settled before the cycle closes.Oncea minor release has been made, features included in that releasemust notreceive any backwards-incompatible changes. Later patches are expected topreserve compatibility for theC core of Vim. Runtime files are handleda bitmore flexibly to give runtime files maintainersa chance to change oldbehaviour.Withinadevelopment cycle, features may be markedas deprecated. Deprecatedfeatures can be disabledat compile time through an appropriate switch. Aftera new release, deprecated features may be removed completely ina followingcycle. vim:tw=78:ts=8:noet:ft=help:norl: