Maintaining Auto-Indentation

TypeScript

I have been tasked with maintaining the auto-indentation in the editor. The auto-indent feature automatically adjusts indentation when users type, paste, move, or indent lines. It is controlled by the editor.autoIndent setting and defined in the EditorAutoIndentStrategy enum.

Strategy Levels

The setting accepts five levels, each building on the previous:

LevelValueBehavior
None0No automatic indentation
Keep1Keeps the indentation of the current line when pressing Enter
Brackets2Honors indentation from brackets (e.g., indent after {)
Advanced3Uses language-defined indentationRules (increase/decrease patterns)
Full4Uses both indentationRules and onEnterRules for full language-aware indentation

The default is Advanced.

Key Features

  • On-Type Indent (cursorTypeEditOperations.ts:31) — The AutoIndentOperation class computes proper indentation when typing characters like closing brackets. It only activates at the Full level and when tokenization is cheap.

  • On-Paste Indent (indentation.ts:370) — The AutoIndentOnPaste contribution re-indents pasted code to match the surrounding context. Controlled separately by editor.autoIndentOnPaste (boolean) and requires auto-indent level Full. There’s also autoIndentOnPasteWithinString for pasting within strings.

  • On-Enter Indent (autoIndent.ts:311) — getIndentForEnter() determines beforeEnter and afterEnter indentation using the language’s onEnterRules and indentationRules.

  • Inherited Indent (autoIndent.ts:82) — getInheritIndentForLine() walks preceding lines to determine the correct inherited indentation, respecting shouldIncrease, shouldDecrease, and shouldIndentNextLine patterns.

  • Good Indent (autoIndent.ts:227) — getGoodIndentForLine() computes the ideal indentation for a line based on language rules and context, combining inherited indentation with enter actions.

Language Integration

Auto-indent relies on two language configuration constructs:

  • indentationRules — Regex patterns (increaseIndentPattern, decreaseIndentPattern, indentNextLinePattern, unIndentedLinePattern) that describe how indentation should change.
  • onEnterRules — Rules that specify what should happen when Enter is pressed (e.g., indent, outdent, insert text). Both are processed through ProcessedIndentRulesSupport in indentationLineProcessor.ts, which handles mixed-language lines by filtering tokens to only consider the relevant language.

Key Files

FilePurpose
autoIndent.tsCore indent computation algorithms
cursorTypeEditOperations.tsOn-type auto-indent operation
indentation.tsAutoIndentOnPaste contribution and indent commands
editorOptions.ts:1434Setting definition and parsing
indentationLineProcessor.tsToken-aware indent rule processing