Overview
TheVim.defineOperator() function creates custom Vim operators. Operators in Vim act on motions or text objects (like d for delete, y for yank, or c for change). After defining an operator, you can use it with any motion or in visual mode.
Signature
Parameters
The name of the operator. This name is used to reference the operator in keymaps.
The function to execute when the operator is invoked. Receives:
cm(CodeMirror) - The editor instanceargs(OperatorArgs) - Operator arguments including:repeat(number) - Repeat countlinewise(boolean) - Whether operation is linewiseforward(boolean) - Direction of operationregisterName(string) - Target register
ranges(Range[]) - Array of selection ranges, each with:anchor(Pos) - Start positionhead(Pos) - End position
oldAnchor(Pos) - Original anchor position before operationnewHead(Pos) - New head position after operation
Pos object for the new cursor position, or void to keep current position.Return Value
This function does not return a value.
Examples
Hard Wrap Operator
Define ahardWrap operator that wraps text at a specified width:
Sort Operator
Define an operator to sort lines:Case Toggle Operator
Define an operator that toggles text case:Usage
After defining an operator, you can use it with:- Motions:
<operator><motion>(e.g.,gqipfor hard wrap inner paragraph) - Visual mode: Select text and press the operator keys
- Line-wise: Double the operator key (e.g.,
gqgqfor current line) - Counts: Prefix with a count (e.g.,
3gqjfor 3 lines down)
Notes
- Operators must be added to the keymap using
Vim.mapCommand()before they can be used - The
rangesarray typically contains one range, but may have multiple in visual block mode - Return a
Posobject to set the cursor position after the operation - If you don’t return a value, the cursor remains at its current position
- Operators work with all built-in motions and text objects
See Also
- Vim.defineMotion() - Define custom motions
- Vim.defineAction() - Define custom actions
- Vim.mapCommand() - Add commands to keymap

