This document covers Vim's event-driven programming system through user-defined functions and autocommands. User functions provide reusable logic encapsulation, while autocommands enable automatic execution of commands in response to editor events. Together, they form the foundation for extending Vim's behavior and automating workflows.
For information about built-in functions, see 5.3 Built-in Functions Reference. For script execution and sourcing, see 5.5 Script Execution and Control. For expression evaluation, see 5.2 Expression Evaluation System.
Functions in Vim9 script are defined using the def keyword for compiled functions or function for legacy-style functions. The basic syntax distinguishes between different scope levels.
Function Definition Syntax
Sources: doc/usr_41.jax287-310
Function Scope Hierarchy
Sources: doc/usr_41.jax222-257 doc/usr_41.jax286-310
In Vim9 script, function definitions use explicit type annotations and the def keyword for compiled execution:
def g:GetCount(): number counter += 1 return counter enddef The function can access script-local variables defined outside the function scope. Script-local variables persist after script execution completes.
Key characteristics:
def keyword introduces compiled Vim9 functionsvar) are accessible within functionsg: prefix are globally accessibleSources: doc/usr_41.jax287-310
Parameter Types and Defaults
Sources: doc/usr_41.jax315-340 doc/usr_41.jax669-710
Autoload Functions
Autoload functions enable lazy loading of functionality. They follow a specific naming convention that maps to file paths:
autoload#module#SubModule#FunctionName └─ Loads from: autoload/module/SubModule.vim Lambda Functions and Closures
Lambda functions provide inline function definitions with closure support:
var Incrementer = (x) => x + 1 var list = [1, 2, 3] var result = map(list, (idx, val) => val * 2) Closures capture variables from their enclosing scope, maintaining references to those variables even after the outer function returns.
Function References (Funcref)
Function references allow passing functions as values:
var funcref = funcref('FunctionName') var result = funcref() " Call the function Sources: doc/usr_41.jax669-710 doc/usr_41.jax922-923
Autocommands execute commands automatically in response to specific events. The system provides hooks into nearly every aspect of Vim's operation.
Autocommand Execution Flow
Sources: doc/autocmd.jax74-173
Autocommand Definition Syntax
The :autocmd command defines autocommands with the following structure:
:autocmd [group] {event} {pattern} [++once] [++nested] {command} Components:
[group]: Optional group name for organization and bulk operations{event}: Event type that triggers execution (e.g., BufRead, InsertEnter){pattern}: File pattern to match (e.g., *.txt, <buffer>)[++once]: Execute once then remove (one-shot autocommand)[++nested]: Allow nested autocommand triggering{command}: Command(s) to execute when triggeredSources: doc/autocmd.jax74-119
Vim recognizes numerous event types organized by functional category:
Major Event Categories
Sources: doc/autocmd.jax274-457
Common Event Types
| Event | When Triggered | Common Use Cases |
|---|---|---|
BufNewFile | Editing new file | Template insertion, skeleton files |
BufReadPost | After reading file | Filetype detection, option setting |
BufWritePre | Before saving | Auto-formatting, trailing space removal |
FileType | 'filetype' set | Language-specific configuration |
VimEnter | Startup complete | Plugin initialization |
InsertCharPre | Before char insert | Character transformation |
TextYankPost | After yank/delete | Highlight yanked region |
CursorHold | Idle for 'updatetime' | Preview, auto-save |
Sources: doc/autocmd.jax284-457
Patterns determine which files trigger an autocommand:
Pattern Types
Sources: doc/autocmd.jax91-92
Groups provide organization and enable bulk operations on related autocommands:
Group Operations
Pattern for safe reloading in vimrc:
augroup vimrc autocmd! " Clear all vimrc autocommands au BufNewFile,BufRead *.html so <sfile>:h/html.vim augroup END Sources: doc/autocmd.jax136-157
Buffer-local autocommands use special pattern syntax to restrict execution to specific buffers:
Buffer Pattern Syntax
<buffer>: Current buffer at definition time<buffer=N>: Specific buffer number NThis enables buffer-specific behavior without pattern matching:
autocmd <buffer> BufWrite * call FormatBuffer() Sources: doc/autocmd.jax91-92
Context Variables and Expansion
During autocommand execution, special variables and expansions provide context:
| Symbol | Expands To | Example |
|---|---|---|
<afile> | Filename matching pattern | readme.txt |
<abuf> | Buffer number | 3 |
<amatch> | Matched portion of pattern | *.txt matches as txt |
<sfile> | Script file defining autocmd | /path/to/vimrc |
% | Current buffer name | May differ from <afile> |
Special Considerations
<sfile> expands at definition time, not execution time<script> with :execute in functions for reliable paths% and <afile> may differ when autocommand executes in different buffer contextSources: doc/autocmd.jax122-133
The primary integration pattern calls user-defined functions from autocommands, separating event detection from business logic:
Function Call Pattern
Recommended Pattern
Sources: doc/autocmd.jax49-70
Common Integration Patterns
Sources: doc/autocmd.jax49-70
The ++nested flag allows autocommands to trigger other autocommands:
Nesting Behavior
Without ++nested, autocommands do not trigger during autocommand execution, preventing infinite recursion. Use ++nested carefully to enable legitimate cascading behavior.
Sources: doc/autocmd.jax84-89
The ++once flag creates self-removing autocommands:
autocmd BufRead *.txt ++once call FirstTimeOnly() After execution, the autocommand is automatically removed. Useful for initialization that should occur only on first file load.
Sources: doc/autocmd.jax87-89
The autocmd_add() function provides programmatic autocommand creation from Vim script:
Function Signature
autocmd_add(list<dict<any>>): bool Each dictionary specifies one autocommand:
| Key | Type | Description |
|---|---|---|
group | string | Autocommand group name |
event | string or list | Event(s) to trigger on |
pattern | string or list | File pattern(s) to match |
cmd | string | Command to execute |
once | bool | Remove after first execution |
nested | bool | Allow nested triggering |
replace | bool | Replace existing autocmds in group |
Example Usage
Sources: doc/autocmd.jax104-106 doc/usr_41.jax1040-1043
The autocmd_delete() function removes autocommands programmatically:
Function Signature
autocmd_delete(list<dict<any>>): bool Dictionary keys match autocmd_add(). Omitted keys act as wildcards:
Sources: doc/autocmd.jax177-179 doc/usr_41.jax1042
The autocmd_get() function retrieves defined autocommands:
Function Signature
autocmd_get(dict<any> = {}): list<dict<any>> Returns list of dictionaries describing matching autocommands. Empty dictionary returns all autocommands:
Each returned dictionary contains:
group: Group nameevent: Event typepattern: File patterncmd: Command stringSources: doc/autocmd.jax234-235 doc/usr_41.jax1043
Recommended Structure
Pattern: Separation of Concerns
Sources: doc/autocmd.jax49-70
Errors in autocommands halt execution. Use try-catch for robustness:
Alternatively, use :silent! to suppress errors (though this hides issues):
autocmd BufWrite * silent! call FormatBuffer() Sources: doc/autocmd.jax34-47
CursorMoved and TextChanged Events
These events fire frequently. Keep handlers lightweight:
Disable During Bulk Operations
Use :noautocmd prefix to disable autocommands for commands:
:noautocmd edit file.txt :noautocmd bufdo substitute/pattern/replacement/g Sources: doc/autocmd.jax771-784 doc/autocmd.jax1021
The FuncUndefined event enables on-demand function definition:
When MyPlugin_Something() is called but undefined, the autocommand loads the implementation. However, autoload functions (autoload#module#Function) are preferred for this pattern.
Sources: doc/autocmd.jax948-959
Typical Event Sequence
Understanding the event sequence ensures handlers execute at the appropriate time:
BufReadPre: Before reading file (modify options before load)BufRead: After reading file, before modelines (detect filetype)BufWinEnter: After buffer shown in window (UI setup)BufLeave: Before switching away (cleanup, save state)BufUnload: Before removing from memory (save data)Sources: doc/autocmd.jax254-270 doc/autocmd.jax460-597
The :execute and :normal commands enable dynamic command generation in autocommands:
Dynamic Command Execution
Normal Mode Commands
The ! in normal! prevents user mappings from interfering.
Sources: doc/various.jax205-254 doc/autocmd.jax620-631
The user function and autocommand system provides comprehensive event-driven automation:
Key Components:
autocmd_add(), autocmd_delete(), autocmd_get() for programmatic managementIntegration Pattern:
Event → Pattern Match → Group Filter → Function Call → Implementation Logic This architecture separates event detection (what triggers) from implementation (what executes), enabling testable, maintainable, and reusable code.
Sources: doc/autocmd.jax1-70 doc/usr_41.jax669-710
Refresh this wiki
This wiki was recently refreshed. Please wait 4 days to refresh again.