hledger for VS Code - User Guide

August 3, 2026 · View on GitHub

Complete documentation for the hledger VS Code extension.

Quick Links:


Introduction

The hledger VS Code extension provides full IDE support for hledger plain text accounting files. It transforms your journal editing experience with intelligent auto-completion, automatic formatting, syntax highlighting, and integration with the hledger command-line tool.

Supported File Types

The extension activates for files with these extensions:

  • .journal
  • .hledger
  • .ledger
  • Files named journal or .journal (without extension)
  • .rules — hledger CSV import rules files (language ID: hledger-rules)

Installation

  1. Open VS Code
  2. Press Ctrl+Shift+X (or Cmd+Shift+X on macOS) to open Extensions
  3. Search for "hledger"
  4. Click Install

Alternative Sources

File Associations

The extension automatically associates with .journal, .hledger, .ledger, and .rules files. If files aren't recognized:

  1. Click the language indicator in the bottom-right corner of VS Code
  2. Select "hledger" (for journal files) or "hledger-rules" (for rules files) from the list

Or add to your settings.json:

{
  "files.associations": {
    "*.journal": "hledger",
    "*.hledger": "hledger",
    "*.ledger": "hledger",
    "*.rules": "hledger-rules"
  }
}

CSV Import Rules Files (.rules)

The extension fully supports hledger CSV import rules files (.rules). These files use a different syntax from journal files and are registered as a separate language (hledger-rules).

Features available in .rules files:

  • Syntax highlighting (comments, directives, field assignments, if/end blocks)
  • LSP diagnostics, completion, and navigation via the Language Server
  • Hover information on directives and field names
  • Go to Definition and Find References for included files
  • Folding ranges for if/end blocks

Features not available in .rules files (journal-only):

  • Tab amount alignment
  • CLI commands (balance, stats, income statement)
  • Inline ghost text completion
  • Format on type

Getting Started

Basic Workflow

  1. Create or open a .journal file
  2. Start typing - auto-completion activates automatically
  3. Press Enter after transaction dates - LSP adds posting indent (requires editor.formatOnType: true)
  4. Press Tab after account names - LSP positions cursor at amount column
  5. Save file - automatic formatting aligns amounts

Example Transaction

2025-01-15 * Grocery Store
    Expenses:Food:Groceries        \$45.50
    Assets:Bank:Checking          -\$45.50

Completion Workflow

  1. Type 2025 at line start → Date completions appear
  2. After date, type Gro → Payee completions (based on history)
  3. Press Enter → Cursor indents for posting
  4. Type Exp → Account completions
  5. Press Tab → Cursor moves to amount column
  6. Type $45.50 → Amount entered
  7. Press Enter → New posting line with indent

Auto-Completion

The extension provides context-aware completions that activate automatically as you type. No keyboard shortcuts needed - just start typing.

Account Completion

Trigger: Type on an indented line (posting context) or type : anywhere

Features:

  • Frequency-based sorting: Most-used accounts appear first
  • Hierarchical navigation: Type : to drill into sub-accounts
  • Abbreviation matching: Type initials to find accounts
    • ef matches Expenses:Food
    • abc matches Assets:Bank:Checking
  • Fuzzy matching: Partial matches work too
  • Usage count display: Shows how often each account is used

Example:

Typing "exp:foo" shows:
  Expenses:Food (used 150 times)
  Expenses:Food:Groceries (used 89 times)
  Expenses:Food:Restaurants (used 45 times)

Payee Completion

Trigger: After date and optional status on transaction line

Features:

  • Sorted by usage frequency
  • Fuzzy matching supported
  • Multi-language support (Cyrillic, Asian characters, etc.)

Example:

2025-01-15 Amaz    ; typing "Amaz" suggests "Amazon", "Amazon Prime", etc.

Date Completion

Trigger: Type a digit (0-9) at line start

Suggestions:

SuggestionDescription
TodayCurrent date
YesterdayPrevious day
Last week7 days ago
Month startFirst of current month
Last monthFirst of previous month
Last usedMost recent date in journal

Format: Dates use YYYY-MM-DD format by default.

Commodity Completion

Trigger: Type @ after an amount, or in amount context

Features:

  • Common currency symbols: $, , £, ¥,
  • Currency codes: USD, EUR, GBP
  • Custom commodities from your journal
  • Marks default commodity if set

Tag Completion

Trigger: Type ; to start a comment, then type tag content

Two modes:

  1. Tag name completion: Suggests existing tag names

    ; project:    ; typing suggests: project, category, etc.
    
  2. Tag value completion: After tag name and :, suggests values

    ; project:home    ; typing after : suggests values used with "project" tag
    

Transaction Template Completion

Trigger: When typing payee name (if enabled)

Features:

  • Suggests complete transaction structures based on history
  • Shows accounts and amounts from similar past transactions
  • Snippet support for cursor positioning
  • Prioritizes recent transaction patterns

Example: When you type "Amazon", you might see:

Amazon → Template:
    Expenses:Shopping    $XX.XX
    Assets:Credit Card

Inline Completion (Ghost Text)

Inline completions show suggestions as "ghost text" - semi-transparent text that appears ahead of your cursor.

How It Works

  1. Start typing a payee name on a new transaction line
  2. After typing minimum characters (default: 2), ghost text appears
  3. Press Enter to accept the suggestion
  4. Press Escape or continue typing to dismiss

Payee Inline Completion

Shows the remainder of matching payee names:

2025-01-15 Amaz|on Prime     ; "on Prime" shown as ghost text

Template Inline Completion

Shows complete posting structure as ghost text:

2025-01-15 Amazon Prime|
    Expenses:Shopping    \$12.99    ; shown as ghost text
    Assets:Credit Card

Configuration

SettingDescriptionDefault
hledger.features.inlineCompletionEnable/disable inline completionstrue

LSP Dependency

Inline completions require the Language Server (LSP) to be running. The Language Server is automatically installed on first activation. When the LSP is unavailable:

  • Ghost text suggestions will not appear
  • No error is shown - the feature silently waits for LSP availability
  • Once LSP starts, inline completions work automatically

Smart Editing

On-Type Formatting (LSP)

When the Language Server is running and editor.formatOnType is enabled in VS Code settings, the LSP handles formatting as you type:

TriggerBehavior
Enter after transaction date lineAdds posting indent
Enter after posting linePreserves indent for next posting
Enter on empty indented lineRemoves indent (outdents)
Tab after account namePositions cursor at amount alignment column

To enable, add to your settings.json:

{
  "editor.formatOnType": true
}

Fallback: When the LSP is not running, onEnterRules from the language configuration provide basic indentation behavior.

Completion Triggers

CharacterTriggers
0-9Date completion (at line start)
:Account hierarchy navigation
@Commodity completion
;Tag/comment completion
SpaceContext-aware completion

Formatting

The extension provides automatic formatting to keep your journals clean and readable.

Enable Format on Save

Add to your settings.json:

{
  "editor.formatOnSave": true
}

What Gets Formatted

ElementFormatting Applied
AmountsAligned at consistent column (start, right-edge, or decimal point)
CommentsRight-aligned
Posting indentationNormalized to 4 spaces
Account-amount spacingStandardized using 2+ spaces

Preserved Elements

The formatter preserves:

  • Balance assertions (= \$100)
  • Balance assignments (:= \$100)
  • Virtual postings (parentheses and brackets)
  • Commodity format (prefix $100 vs postfix 100 USD)
  • Sign placement (-\$100, $-100, -100 USD)
  • Metadata and tags
  • Empty lines and structure

Multi-Currency Support

The formatter handles multiple currencies intelligently:

2025-01-15 International Purchase
    Expenses:Shopping            \$45.00
    Expenses:Travel             €120.00
    Assets:Bank:USD             -\$45.00
    Assets:Bank:EUR            -€120.00

Amount Formatting by Commodity

When you have commodity directives in your journal, amounts are automatically formatted according to their format specification on save.

Automatic Formatting: Enable editor.formatOnSave in VS Code settings to format amounts automatically when saving the file.

; Commodity directives define the format
commodity RUB 1 000,00  ; space as group separator, comma as decimal
commodity \$1,000.00     ; comma as group separator, period as decimal

; Default commodity for postings without explicit currency
D RUB 1 000,00

2025-01-15 Supermarket
    ; Before save: "1000 RUB" → After save: "1 000,00 RUB"
    Expenses:Food                          1 000,00 RUB
    ; Before save: "1000" (no commodity) → After save: "1 000,00" (uses D directive)
    Assets:Cash                           -1 000,00

Behavior:

  • With explicit commodity: formats number and keeps symbol (e.g., 1000 RUB1 000,00 RUB)
  • Without commodity: uses D directive format, formats only the number (e.g., 10001 000,00)
  • All amounts in a posting are formatted: main amount, cost notation (@ 95.50 USD), balance assertion (= 5000 RUB)
  • Virtual postings ((), []) are fully supported
  • No format defined: amount is not modified
  • Amounts are aligned according to hledger.formatting.amountAlignmentMode and hledger.formatting.amountAlignmentColumn (default: auto)

Manual Formatting

  • Format Document: Ctrl+Shift+I (or Cmd+Shift+I on macOS)
  • Format Selection: Select text, then use same command

Syntax Highlighting

The extension provides two levels of syntax highlighting:

  1. TextMate Grammar (always available): Basic syntax highlighting using VS Code's built-in TextMate engine. Works without the Language Server.
  2. Semantic Tokens (requires LSP): Rich, context-aware highlighting provided by the Language Server. Offers more accurate and detailed highlighting.

Automatic Fallback: When the Language Server is not running or semantic tokens are disabled, VS Code automatically uses TextMate grammar highlighting. Basic syntax highlighting is always available.

Recommended Setup:

  • Language Server running + Semantic tokens enabled (default) = Best experience

Enable/Disable Semantic Highlighting

Semantic highlighting is enabled by default:

{
  "hledger.features.semanticTokens": true
}

Semantic Token Types

The LSP server uses standard semantic token types:

Standard TypeTextMate ScopeDark+ Colorhledger Elements
namespaceentity.name.namespaceCyan (#4EC9B0)Account names (including virtual accounts)
typeentity.name.typeCyan (#4EC9B0)Currency/commodity codes
functionentity.name.functionYellow (#DCDCAA)Payee names
numberconstant.numericGreen (#B5CEA8)Dates and amounts
decoratorentity.name.tagBlue (#569CD6)Tag names
keywordkeyword.controlPurple (#C586C0)Directives (include, account, etc.)
stringstring.quotedOrange (#CE9178)Transaction codes, tag values, text
operatorkeyword.operatorLight (#D4D4D4)Status markers (*, !), operators
commentcomment.lineGreen (#6A9955)Comments and notes
regexpstring.regexpRed (#D16969)Regex patterns (rules files)
parametervariable.parameterLight blue (#9CDCFE)Field names (rules files)

Virtual accounts are distinguished from regular accounts by the abstract modifier ("namespace.abstract:hledger": "#color").

Note: Some elements share the same token type: dates and amounts are both number, comments and notes are both comment, transaction codes and tag values are both string. They cannot be styled independently.

How highlighting works:

  1. TextMate Scopes (highest priority) - Standard scopes like entity.name.namespace, constant.numeric that themes understand
  2. VS Code Type (fallback) - Semantic token type used when theme doesn't customize the scope
  3. Theme defaults (lowest priority) - Built-in theme colors

The extension uses standard TextMate scopes that are recognized by all VS Code themes, ensuring consistent highlighting without custom theme configuration.

Color Customization

You can customize colors in two ways:

Override colors specifically for hledger tokens. This works with any theme and doesn't affect other languages:

{
  "editor.semanticTokenColorCustomizations": {
    "rules": {
      "namespace:hledger": "#0EA5E9",
      "function:hledger": "#EF4444",
      "number:hledger": "#F59E0B",
      "type:hledger": "#A855F7",
      "decorator:hledger": "#EC4899"
    }
  }
}

Option 2: Per TextMate Scope (Global)

Customize the underlying TextMate scopes. This affects ALL languages that use these scopes:

{
  "editor.tokenColorCustomizations": {
    "textMateRules": [
      {
        "scope": "entity.name.function",
        "settings": { "foreground": "#DCDCAA" }
      },
      {
        "scope": "constant.numeric",
        "settings": { "foreground": "#B5CEA8" }
      },
      {
        "scope": "entity.name.namespace",
        "settings": { "foreground": "#4EC9B0" }
      }
    ]
  }
}

⚠️ Warning: TextMate scope customization applies to all languages, not just hledger.

Default Theme Colors

The extension uses standard TextMate scopes that are automatically styled by VS Code themes:

  • Dark+: Accounts (cyan), payees (yellow), amounts/dates (green), directives (purple)
  • Light+: Similar semantic colors with adjusted brightness for light backgrounds

No additional configuration is needed for standard themes to work correctly.

Rules File Highlighting

.rules files (CSV import rules) use a TextMate grammar for syntax highlighting — not LSP semantic tokens. The grammar assigns standard TextMate scopes to each element:

ElementTextMate ScopeTypical ColorDescription
Comments (#, ;, *)comment.lineGreenLine comments
Directives (skip, fields, separator, etc.)keyword.control.directivePurpleConfiguration directives
Directive valuesstring.unquoted.valueOrangeValues after directives
if / end keywordskeyword.control.if / keyword.control.endPurpleConditional block markers
Regex patternsstring.regexpOrange/RedMatch patterns in if-blocks
Field names (account1, description, etc.)entity.name.tagBlueField assignment names
Field valuesstring.unquoted.valueOrangeValues assigned to fields

Note: Colors in the "Typical Color" column are approximate and vary by theme.

Customizing Rules File Colors

Add textMateRules in your VS Code settings. Use the .hledger-rules suffix to target only rules files without affecting other languages:

{
  "editor.tokenColorCustomizations": {
    "textMateRules": [
      {
        "scope": "entity.name.tag.hledger-rules",
        "settings": { "foreground": "#268BD2" }
      },
      {
        "scope": "keyword.control.directive.hledger-rules",
        "settings": { "foreground": "#6C71C4" }
      },
      {
        "scope": "string.regexp.hledger-rules",
        "settings": { "foreground": "#DC322F" }
      }
    ]
  }
}

Tip: Using the full scope with .hledger-rules suffix ensures your customizations apply only to .rules files — no side effects on other languages.


Diagnostics & Validation

The extension validates your journal files and shows warnings/errors.

What Gets Validated

TypeDescription
Account validationChecks for undefined accounts
Commodity validationChecks for undeclared commodities (when commodity directives exist)
Amount formatValidates complex amount patterns
Tag formatValidates tag syntax
Transaction balanceChecks that transactions balance to zero

Transaction Balance Validation

The extension checks that all transactions balance correctly:

  • Each commodity balances separately - All postings with the same commodity must sum to zero
  • One inferred amount allowed - At most one posting can omit its amount
  • Virtual postings handled:
    • (account) - Unbalanced virtual postings are ignored
    • [account] - Balanced virtual postings must balance among themselves
  • Cost notation supported - @ and @@ price conversions are properly handled
  • Balance assertions - = \$500, == \$500, := \$500 are recognized

When a transaction doesn't balance, the error appears on the transaction date line with details about the imbalance (e.g., "Transaction is unbalanced in USD; difference is 10.50").

Troubleshooting Balance Errors

"Transaction has N postings without amounts"

  • hledger allows only one posting to omit its amount (inferred from others)
  • Solution: Add explicit amounts to all but one posting

"Transaction is unbalanced in X; difference is Y"

  • The sum of all postings for commodity X doesn't equal zero
  • Common causes:
    • Typo in amount
    • Missing posting
    • Incorrect cost notation (@ vs @@)
  • For small differences (e.g., $0.01), check decimal precision in your amounts

Cost notation (@ vs @@)

  • @ = unit price: 10 AAPL @ \$150 means each unit costs $150 (total: $1500)
  • @@ = total price: 10 AAPL @@ \$1500 means all units together cost $1500

Disable balance checking If you prefer to use hledger CLI for validation, you can disable balance checking:

{
  "hledger.diagnostics.checkBalance": false
}

Tolerance configuration For cryptocurrencies with 8+ decimal places, increase tolerance to avoid false positives:

{
  "hledger.diagnostics.balanceTolerance": 1e-8
}

Validated Amount Patterns

The extension recognizes all valid hledger amount formats:

  • Basic: -\$10.00, $-10.00, $10.00
  • Unicode currencies: ₽100.00, €50.00, £25.00
  • Grouped numbers: 1,000.00, 1.000,00, 1 000.00
  • Scientific notation: 1E-6, 1E3
  • Quoted commodities: 3 "green apples"
  • Balance assertions: = \$500, == \$500
  • Balance assignment: := \$500
  • Amount with assertion: $100 = \$500
  • Amount with cost: 10 AAPL @ \$150

Disable Validation

If diagnostics are not needed:

{
  "hledger.diagnostics.enabled": false
}

Transaction Status Toggle

Toggle transaction and posting status markers (! pending, * cleared) using keyboard shortcuts.

How It Works

  • Cursor on transaction header (line starting with date): toggles the transaction status
  • Cursor on posting line (indented line): toggles the posting status

Status Cycle

Pressing the cycle shortcut rotates through: unmarked! (pending) → * (cleared) → unmarked

Examples

; Before: cursor on transaction header, press Cmd+K S
2024-01-15 Grocery Store
    expenses:food    \$50.00
    assets:checking

; After: status set to pending
2024-01-15 ! Grocery Store
    expenses:food    \$50.00
    assets:checking

; Press Cmd+K S again: status set to cleared
2024-01-15 * Grocery Store
    expenses:food    \$50.00
    assets:checking

; Press Cmd+K S again: status removed
2024-01-15 Grocery Store
    expenses:food    \$50.00
    assets:checking

Individual posting status:

; Cursor on posting line, press Cmd+K 2 to set cleared
2024-01-15 Transaction
    * assets:checking    $-100
    expenses:food         \$100

Keyboard Shortcuts

ShortcutAction
Cmd+K S / Ctrl+K SCycle status (unmarked → ! → * → unmarked)
Cmd+K 0 / Ctrl+K 0Set to unmarked (remove status)
Cmd+K 1 / Ctrl+K 1Set to pending (!)
Cmd+K 2 / Ctrl+K 2Set to cleared (*)

All shortcuts can be customized via VS Code Keyboard Shortcuts (Cmd+K Cmd+S).


CLI Integration

Run hledger commands directly from VS Code and insert results into your journal.

Prerequisites

  • hledger must be installed and in your PATH
  • Or configure explicit path in settings

Available Commands

Access via Command Palette (Ctrl+Shift+P or Cmd+Shift+P):

CommandDescriptionhledger command
HLedger: Insert Balance SheetBalance sheet with assets/liabilitieshledger bs
HLedger: Insert Income StatementRevenue and expense summaryhledger incomestatement
HLedger: Insert Statistics ReportFile statistics and metricshledger stats

Example Output

; hledger bs - 2025-01-15
; ==================================================
; Balance Sheet 2025-01-15
;              ||  2025-01-15
; =============++=============
;  Assets      ||
; -------------++-------------
;  Assets:Bank || 2450.00 USD
; -------------++-------------
;              || 2450.00 USD
; ==================================================

Journal File Resolution

The extension determines which journal file to use in this priority:

  1. LEDGER_FILE environment variable - If set and valid
  2. hledger.cli.journalFile setting - If configured
  3. Current open file - As fallback

Security

Paths from environment variables and settings are validated to prevent command injection:

  • Shell metacharacters (;, &, |, `, $, etc.) are rejected
  • Inaccessible paths show error messages
  • Current file paths (from VS Code) are trusted

Configuration

SettingDescriptionDefault
hledger.cli.pathPath to hledger executableAuto-detected
hledger.cli.journalFileMain journal file pathUses env or current file

Context Menu

Right-click in the editor to access the HLedger submenu with quick access to CLI reports.

Available Commands

CommandDescription
Insert Balance SheetInsert hledger bs output as comment
Insert Income StatementInsert hledger is output as comment
Insert StatisticsInsert hledger stats output as comment

Usage

  1. Open a .journal, .hledger, or .ledger file
  2. Right-click in the editor
  3. Select HLedger from the context menu
  4. Choose the desired report

The context menu only appears for hledger files and provides the same functionality as the Command Palette commands, but with faster access.

Navigation commands (Go to Definition, Go to References, Rename Symbol) are available through VS Code's standard context menu when the Language Server is active.


CSV/TSV Import

Import bank statements and transaction data from tabular files.

Commands

CommandDescription
HLedger: Import Selected Tabular DataImport selected text as CSV/TSV
HLedger: Import Tabular Data from FileImport entire active file

Supported Delimiters

The extension auto-detects:

  • Tab-separated (TSV)
  • Comma-separated (CSV)
  • Semicolon-separated
  • Pipe-separated (|)

Column Detection

The extension recognizes columns by header names (English and Russian):

Column TypeRecognized Headers
DateDate, Дата
Description/PayeeDescription, Payee, Merchant, Описание
AmountAmount, Sum, Сумма
DebitDebit, Expense
CreditCredit, Income
CategoryCategory, Категория
AccountAccount
MemoMemo, Note
ReferenceReference, ID
BalanceBalance
CurrencyCurrency

Account Resolution

The import feature tries to match payees to accounts using multiple strategies:

PriorityStrategyConfidenceDescription
1Journal history (exact)95%Exact payee match from existing transactions
2Journal history (fuzzy)85%Similar payee names
3Category (exact)80%Direct category column match
4Category (partial)75%Partial category match (contains/contained by)
5Merchant pattern70%Regex patterns for common merchants
6Amount sign50%Positive=income, negative=expense
7Default accounts0%Configured defaults

Date Format Handling

Setting ValueFormat
autoAuto-detect (default)
YYYY-MM-DD2025-01-15
YYYY/MM/DD2025/01/15
DD/MM/YYYY15/01/2025
MM/DD/YYYY01/15/2025
DD.MM.YYYY15.01.2025
DD-MM-YYYY15-01-2025

Import Settings

SettingDescriptionDefault
hledger.import.dateFormatExpected date formatauto
hledger.import.defaultDebitAccountAccount for expensesexpenses:unknown
hledger.import.defaultCreditAccountAccount for incomeincome:unknown
hledger.import.defaultBalancingAccountBalancing posting accountTODO:account
hledger.import.invertAmountsInvert amount signsfalse
hledger.import.useJournalHistoryLearn from existing transactionstrue

Language Server (LSP)

The extension uses a Language Server Protocol (LSP) backend for most features. The LSP server provides completions, real-time diagnostics, formatting, semantic highlighting, and other capabilities.

Without Language Server

The Language Server is required and auto-installed on first activation. If the LSP is unavailable (e.g., auto-install was declined or binary was removed), the following fallback features remain:

  • Syntax highlighting: Basic TextMate grammar highlighting (automatic fallback)
  • Basic indentation: onEnterRules from language configuration provide basic Enter key indentation
  • CLI integration: balance, stats, income statement commands (works locally)
  • CSV/TSV import: Import functionality (works locally)

Features unavailable without LSP:

  • On-type formatting (smart Enter/Tab with editor.formatOnType)
  • Inline completions (ghost text)
  • Auto-completion (accounts, payees, dates, etc.)
  • Diagnostics and validation
  • Document formatting
  • Code navigation (Go to Definition, Find References, Rename Symbol)
  • Document Highlight (highlight all occurrences of a symbol)
  • Selection Range (smart expand/shrink selection)
  • Range Formatting (format selected text)
  • Hover information
  • Folding ranges
  • Workspace symbols
  • CodeLens balance indicators

Installation

The Language Server is automatically installed on first activation. If prompted, accept the installation to enable all features. The binary is stored in VS Code's global storage directory.

If downloads require a proxy, set VS Code's http.proxy. Its non-empty value is used for both HTTP and HTTPS release downloads. When http.proxy is empty, the extension uses HTTP_PROXY and HTTPS_PROXY from the environment; NO_PROXY still bypasses the proxy for matching hosts. Reload VS Code after changing proxy settings so the Language Server download transport is recreated.

A Get Started walkthrough is available via Command Palette → HLedger: Get Started. It guides you through Language Server installation, opening a journal file, and importing from CSV.

To manually reinstall or update:

  1. Open Command Palette (Ctrl+Shift+P or Cmd+Shift+P)
  2. Run HLedger: Install/Update Language Server
  3. Wait for the download to complete

Status Bar

The extension shows an LSP status indicator in the VS Code status bar (bottom-right). The indicator reflects the current state of the Language Server:

IconStateDescription
$(server)RunningLSP is active and providing features
$(sync~spin)Starting / DownloadingLSP is starting up or being downloaded
$(warning)ErrorLSP encountered an error (click to restart)
$(cloud-download)Not InstalledLSP binary not found
$(debug-stop)StoppedLSP is stopped

Click the status bar item to restart the Language Server.

Output Channel

Extension logs are available in the Output panel under HLedger channel (View → Output → HLedger). When hledger.lsp.debug is enabled, additional debug-level messages are logged. This is useful for diagnosing issues without opening Developer Tools.

LSP Commands

CommandDescription
hledger.lsp.updateInstall or update the language server binary
hledger.lsp.showVersionShow installed version and status
hledger.lsp.restartRestart the language server

Note: CLI commands (hledger.cli.balance, hledger.cli.stats, hledger.cli.incomestatement), hledger.editor.alignAmount and hledger.editor.insertInferredAmount only appear in the Command Palette when a .journal/.hledger/.ledger file is active. Import and LSP commands are always available.

LSP Settings

SettingTypeDefaultDescription
hledger.lsp.pathstring""Custom path to hledger-lsp binary. If empty, uses auto-downloaded binary
hledger.lsp.debugbooleanfalseEnable debug logging for the LSP server (output visible in HLedger output channel)
hledger.lsp.checkForUpdatesbooleantrueCheck for Language Server updates on extension activation

LSP Feature Settings

Control which Language Server features are enabled:

SettingTypeDefaultDescription
hledger.features.hoverbooleantrueEnable hover information
hledger.features.completionbooleantrueEnable autocompletion
hledger.features.formattingbooleantrueEnable document formatting
hledger.features.diagnosticsbooleantrueEnable diagnostics
hledger.features.semanticTokensbooleantrueEnable semantic tokens
hledger.features.codeActionsbooleantrueEnable code actions
hledger.features.foldingRangesbooleantrueEnable transaction folding
hledger.features.documentLinksbooleantrueEnable links for include directives
hledger.features.workspaceSymbolbooleantrueEnable workspace symbol search
hledger.features.inlineCompletionbooleantrueEnable inline ghost text completions
hledger.features.codeLensbooleanfalseEnable balance check indicators on transactions
hledger.features.inlayHintsbooleantrueEnable inlay hints (requires a server restart)

LSP Completion Settings

SettingTypeDefaultDescription
hledger.completion.snippetsbooleantrueEnable snippet completions for payees
hledger.completion.fuzzyMatchingbooleantrueEnable fuzzy matching
hledger.completion.showCountsbooleantrueShow usage counts in completions
hledger.completion.maxResultsnumber50Maximum number of completion items (5-200)
hledger.completion.includeNotesbooleantrueInclude notes in payee completions

LSP Diagnostics Settings

SettingTypeDefaultDescription
hledger.diagnostics.undeclaredAccountsbooleantrueReport undeclared accounts
hledger.diagnostics.undeclaredCommoditiesbooleantrueReport undeclared commodities
hledger.diagnostics.unbalancedTransactionsbooleantrueReport unbalanced transactions

LSP Formatting Settings

SettingTypeDefaultDescription
hledger.formatting.indentSizenumber4Number of spaces for posting indentation (2-8)
hledger.formatting.alignAmountsbooleantrueAlign amounts in postings

CLI Integration Settings (LSP)

SettingTypeDefaultDescription
hledger.cli.enabledbooleantrueEnable CLI integration
hledger.cli.timeoutnumber30000Timeout for commands in milliseconds (1000-300000)

Limits Settings

SettingTypeDefaultDescription
hledger.limits.maxFileSizeBytesnumber10485760Maximum file size (1MB-100MB, default: 10MB)
hledger.limits.maxIncludeDepthnumber50Maximum include directive depth (1-100)

Backward Compatibility

The new settings maintain backward compatibility with existing settings:

Old SettingNew SettingNotes
autoCompletion.enabledfeatures.completionNew takes precedence if both set
diagnostics.enabledfeatures.diagnosticsNew takes precedence if both set
diagnostics.checkBalancediagnostics.unbalancedTransactionsNew takes precedence if both set

Using Custom Binary

If you prefer to use your own hledger-lsp binary:

  1. Install hledger-lsp manually
  2. Configure the path in settings:
    {
      "hledger.lsp.path": "/path/to/hledger-lsp"
    }
    

Supported Platforms

Auto-download supports:

  • macOS (Intel and Apple Silicon)
  • Linux (x64 and ARM64)
  • Windows (x64)

Configuration Reference

Auto-Completion Settings

SettingTypeDefaultDescription
hledger.autoCompletion.enabledbooleantrueEnable automatic completion
hledger.autoCompletion.maxResultsnumber25Maximum completion items (5-50)
hledger.autoCompletion.maxAccountResultsnumber30Maximum account items (5-50)
hledger.autoCompletion.transactionTemplates.enabledbooleantrueEnable transaction template suggestions

Inline Completion Settings

SettingTypeDefaultDescription
hledger.features.inlineCompletionbooleantrueEnable ghost text completions

Inlay Hint Settings

Inlay hints are read-only annotations the Language Server renders inside the line. They are not part of the file and are never saved.

SettingTypeDefaultDescription
hledger.features.inlayHintsbooleantrueEnable inlay hints (requires a server restart)
hledger.inlayHints.inferredAmountsbooleanfalseShow the amount hledger infers for a posting left without one
hledger.inlayHints.runningBalancesbooleanfalseShow the running account balance after each posting
hledger.inlayHints.costExpansionbooleanfalseShow the total cost of postings that carry a per-unit price

Inferred amount hints are off by default. A hint takes up room in the rendered line, so while you are typing an amount it shifts the rest of the line to the right. To write the inferred amount into the file instead, use HLedger: Insert Inferred Amount (Cmd+K = / Ctrl+K =), which works whether or not the hints are shown.

CLI Integration Settings

SettingTypeDefaultDescription
hledger.cli.pathstring""Path to hledger (auto-detected if empty)
hledger.cli.journalFilestring""Main journal file path

Diagnostics Settings

SettingTypeDefaultDescription
hledger.diagnostics.enabledbooleantrueEnable validation diagnostics
hledger.diagnostics.checkBalancebooleantrueCheck that transactions balance correctly
hledger.diagnostics.balanceTolerancenumber1e-10Tolerance for balance validation. Useful for high-precision accounting with cryptocurrencies

Formatting Settings

SettingTypeDefaultDescription
hledger.formatting.amountAlignmentColumnnumber0Fixed mode-specific target column for amount alignment (0 = auto)
hledger.formatting.minAlignmentColumnnumber0Minimum column floor for amount alignment (0 = auto). Enforces a minimum column across files; shifts further right if account names require it
hledger.formatting.amountAlignmentModestring"right"Alignment mode: "left" (start), "right" (right edge), or "decimal" (decimal point)
hledger.formatting.amountAlignmentTargetstring"cost"For cost-notation postings (@/@@), which amount anchors alignment: "cost" (cost amount) or "posting" (posting amount)

Note: The amountAlignmentColumn setting specifies a fixed target for the selected mode. With 0, the LSP detects alignment from the file's content and preserves hand-formatted layout. Use minAlignmentColumn instead when you want a floor (minimum column) rather than a fixed target — the column can still grow to fit long account names.

The amountAlignmentMode setting controls how amounts are aligned within that column:

  • "left" — amount starts align at the target column
  • "right" (default) — amounts align by their right edge
  • "decimal" — amounts align by the decimal point (mantissa alignment, matching hledger print default)

The amountAlignmentTarget setting applies to postings that carry cost notation, e.g. 2.36 EUR @@ 3.12 USD:

  • "cost" (default) — the cost (second) amount is aligned (hledger 1.x behavior)
  • "posting" — the posting (first) amount is aligned and the cost annotation trails freely (hledger 2.x print behavior)
{
  "hledger.formatting.amountAlignmentMode": "decimal",
  "hledger.formatting.amountAlignmentTarget": "posting"
}

Import Settings

SettingTypeDefaultDescription
hledger.import.dateFormatenumautoExpected date format in imports
hledger.import.defaultDebitAccountstringexpenses:unknownDefault expense account
hledger.import.defaultCreditAccountstringincome:unknownDefault income account
hledger.import.defaultBalancingAccountstringTODO:accountDefault balancing account
hledger.import.invertAmountsbooleanfalseInvert amount signs
hledger.import.useJournalHistorybooleantrueUse journal history for account matching

Language Server Settings

SettingTypeDefaultDescription
hledger.lsp.pathstring""Custom path to hledger-lsp binary
hledger.lsp.debugbooleanfalseEnable debug logging for LSP
hledger.lsp.checkForUpdatesbooleantrueCheck for LSP updates on activation

LSP Feature Settings

SettingTypeDefaultDescription
hledger.features.hoverbooleantrueEnable hover information
hledger.features.completionbooleantrueEnable autocompletion
hledger.features.formattingbooleantrueEnable document formatting
hledger.features.diagnosticsbooleantrueEnable diagnostics
hledger.features.semanticTokensbooleantrueEnable semantic tokens
hledger.features.codeActionsbooleantrueEnable code actions
hledger.features.foldingRangesbooleantrueEnable transaction folding
hledger.features.documentLinksbooleantrueEnable links for include directives
hledger.features.workspaceSymbolbooleantrueEnable workspace symbol search
hledger.features.inlineCompletionbooleantrueEnable inline ghost text completions
hledger.features.codeLensbooleanfalseEnable balance check indicators on transactions
hledger.features.inlayHintsbooleantrueEnable inlay hints (requires a server restart)

LSP Completion Settings

SettingTypeDefaultDescription
hledger.completion.snippetsbooleantrueEnable snippet completions for payees
hledger.completion.fuzzyMatchingbooleantrueEnable fuzzy matching
hledger.completion.showCountsbooleantrueShow usage counts in completions
hledger.completion.maxResultsnumber50Maximum number of completion items (5-200)
hledger.completion.includeNotesbooleantrueInclude notes in payee completions

LSP Diagnostics Settings

SettingTypeDefaultDescription
hledger.diagnostics.undeclaredAccountsbooleantrueReport undeclared accounts
hledger.diagnostics.undeclaredCommoditiesbooleantrueReport undeclared commodities
hledger.diagnostics.unbalancedTransactionsbooleantrueReport unbalanced transactions

LSP Formatting Settings

SettingTypeDefaultDescription
hledger.formatting.indentSizenumber4Posting indentation (2-8 spaces)
hledger.formatting.alignAmountsbooleantrueAlign amounts in postings
hledger.formatting.amountAlignmentModestring"right""left" (start), "right" (right edge), or "decimal" (decimal point)
hledger.formatting.minAlignmentColumnnumber0Minimum column floor for amount alignment (0 = auto)
hledger.formatting.amountAlignmentTargetstring"cost"Cost-notation anchor: "cost" or "posting"

CLI Settings (Extended)

SettingTypeDefaultDescription
hledger.cli.enabledbooleantrueEnable CLI integration
hledger.cli.timeoutnumber30000Command timeout in milliseconds

Limits Settings

SettingTypeDefaultDescription
hledger.limits.maxFileSizeBytesnumber10485760Maximum file size (default: 10MB)
hledger.limits.maxIncludeDepthnumber50Maximum include directive depth

Commands Reference

All commands accessible via Command Palette (Ctrl+Shift+P or Cmd+Shift+P):

CommandTitleDescription
hledger.cli.balanceHLedger: Insert Balance SheetInsert balance sheet as comment
hledger.cli.statsHLedger: Insert Statistics ReportInsert file statistics as comment
hledger.cli.incomestatementHLedger: Insert Income StatementInsert income statement as comment
hledger.import.fromSelectionHLedger: Import Selected Tabular DataImport selected CSV/TSV
hledger.import.fromFileHLedger: Import Tabular Data from FileImport active file as CSV/TSV
hledger.lsp.updateHLedger: Install/Update Language ServerInstall or update LSP binary
hledger.lsp.showVersionHLedger: Show Language Server VersionShow LSP version info
hledger.lsp.restartHLedger: Restart Language ServerRestart the LSP server
hledger.editor.alignAmountHLedger: Align Amount to ColumnAlign amount at cursor via LSP
hledger.editor.insertInferredAmountHLedger: Insert Inferred AmountWrite the inferred balancing amount at the amount column
hledger.editor.cycleStatusHLedger: Cycle Transaction/Posting StatusCycle status: unmarked → ! → * → unmarked
hledger.editor.setStatusUnmarkedHLedger: Set Status to UnmarkedRemove status marker
hledger.editor.setStatusPendingHLedger: Set Status to Pending (!)Set pending status
hledger.editor.setStatusClearedHLedger: Set Status to Cleared (*)Set cleared status
hledger.getStartedHLedger: Get StartedOpen the Get Started walkthrough

Keyboard Shortcuts

Default Keybindings

KeyActionCondition
EnterAccept completionWhen completion widget is visible
EnterAccept inline suggestionWhen ghost text is visible
TabAlign amount to columnWhen no suggestions/snippets active
Cmd+K = / Ctrl+K =Insert inferred amountOn a posting hledger can infer an amount for
Cmd+K S / Ctrl+K SCycle transaction/posting statusIn hledger files
Cmd+K 0 / Ctrl+K 0Set status to unmarkedIn hledger files
Cmd+K 1 / Ctrl+K 1Set status to pending (!)In hledger files
Cmd+K 2 / Ctrl+K 2Set status to cleared (*)In hledger files
Ctrl+SpaceManual completion triggerAlways

On-type formatting (Enter/Tab) is handled by the Language Server when editor.formatOnType is enabled.

Status Bar Hints

When editing an hledger file, the status bar shows a quick reference for the most useful keybindings:

⌘K S: status · Tab: align · Enter: suggest

This hint is visible only in hledger files and requires no configuration.

Completion Trigger Characters

These characters automatically trigger completions:

CharacterTriggersContext
0-9Date completionAt line start
:Account hierarchyAfter account name segment
@Commodity completionAfter amount
;Tag completionAnywhere (starts comment)

Performance Tips

Large Files

For journals with thousands of transactions:

  1. Split into multiple files using include:

    include 2024-01.journal
    include 2024-02.journal
    include 2025-01.journal
    
  2. Project-based caching handles large files efficiently:

    • Files are parsed incrementally
    • Only changed files are reparsed
    • Cache validates using file modification times

Include Directives

Best practices:

  • Organize by year or month
  • Keep active/current transactions in main file
  • Archive old transactions in included files
  • Maximum nesting depth: 50 levels (configurable up to 100 via hledger.limits.maxIncludeDepth)

Cache Behavior

The extension caches:

  • Parsed accounts, payees, tags, commodities
  • Usage frequency counts
  • File modification times

Cache invalidation:

  • Automatic on file save
  • Automatic on file changes (filesystem watcher)
  • Manual: Reload VS Code window

Disable Features for Performance

If experiencing slowness:

{
  "hledger.features.semanticTokens": false,
  "hledger.features.diagnostics": false,
  "hledger.diagnostics.checkBalance": false,
  "hledger.autoCompletion.transactionTemplates.enabled": false
}

Additional Resources


This documentation is for hledger VS Code extension. For the most up-to-date version, see the GitHub repository.