Skip to content

feat: add layout-preserving formatting for Lua files - #12

Merged
4Luke4 merged 5 commits into
mainfrom
feat/formatting
Nov 4, 2026
Merged

4Luke4 merged 5 commits into
mainfrom
feat/formatting

Conversation

@4Luke4

@4Luke4 4Luke4 commented Nov 4, 2026

Copy link
Copy Markdown
Owner

What and why

This is the next plan.md step after #8: Formatting (textDocument/formatting, /rangeFormatting and /onTypeFormatting). Quick fixes and JSDoc are still missing.

The server now formats .lua files. It changes only the white space between tokens and comments: indentation, spacing within a line, and trailing white space. Line breaks stay exactly where they were written. Strings, long strings and the text of comments are never changed. Every result is lexed again and compared token by token before it is returned (see Safety).

Decisions taken with the maintainer before implementation:

Question Decision
Next feature Formatting
Style Layout-preserving. Keep the user's line breaks; re-indent by block structure; normalize spacing within a line; remove trailing white space.
.menu files .lua only in this step. VS Code reports that .menu files have no formatter. Follow-up.
Requests Document, range and on-type formatting
Settings None new. Only the LSP FormattingOptions: tabSize, insertSpaces, insertFinalNewline, trimFinalNewlines.

Rules

Indentation. One level is a tab, or tabSize spaces with insertSpaces.

Line Level
Inside function, do (also of while/for), then, else, repeat, (, [, { One more than the line that opened it. Several constructs opened on one line count once: f(function() indents its body once.
Starts with end, until, else, elseif, ), ], } (one or more) The level of the line that opened the last of them: end) → the level of the f(function() line; }, { → the level of the f({ line
Continues a statement inside a block (if a and / b then, local x = a + / b, obj / :m()) One more level. Inside brackets the bracket's level applies instead.
then / do on a line of their own The statement's level. Their block is indented from the statement, also after a continuation line.
Inside a multi-line string or long comment Untouched

Spacing within a line. These rules come from an ordered table in inlineSpace; the first match wins.

# Between Space
1 Before a comment / after a comment As written, at least one / one
2 Inside ::name:: None
3 Before , ; / after them None / one
4 After ( [, before ) ] None. One between a bracket and a long string, because [[ would start a long string.
5 After {, before } One; {} stays empty
6 Around . and : None
7 After unary - and # None. One before another -, because -- would start a comment.
8 Before the ( of a call or a function's parameters, the [ of an index None
9 Before a string or table call argument (f"x", f{…}) Kept as written: joined stays joined, apart becomes one space
10 Anything else (keywords, binary operators, =, names) One

Unary vs binary -, call arguments and labels come from the neighboring tokens. Each of these rules is exact for valid Lua 5.2 (manual §9). They don't use tree nodes, because those can be lost when the parser abandons a statement (next section).

Syntax errors.

  • Document formatting is refused on any error.
  • Range and on-type formatting are refused only for errors that start before the end of the lines they change. A line's layout depends only on the text up to it, so a block whose end hasn't been typed yet does not block formatting.

On-type triggers.

  • \n: formats the line just finished. A blank new line keeps the editor's own indentation.
  • d e f l ) ] }: re-indents the line when the character completes end, else, elseif, until or a closing bracket that is the line's first token.

Safety. The edited text is lexed again. It must have the same tokens (type and value), the same comments (-- comments compared without trailing white space), the same errors, and the same line breaks up to its last token or comment. Otherwise nothing is returned, and the refusal is logged as an error (unsafe).

Registration.

  • When the client supports dynamic registration, each request is registered after initialized with a Lua-only selector:
    • { language: 'lua', scheme }
    • { scheme, pattern: '**/*.[lL][uU][aA]' }, for editors with other language IDs
    • each of them for file and untitled.
  • Otherwise the capability is static, and the handler answers null for .menu documents.

Logging of refusals.

Refusal Level
Syntax error, explicit request info
Syntax error, on-type request (sent at every key while the code is incomplete) debug
Invalid options, unsafe result error

Deviation from the approved plan: a parser addition

The plan built the formatter on the existing tree. When I tested if a then … elseif <eof>, the parser abandoned the whole if statement, so its inner statements and unary operators disappeared from the tree. Range and on-type formatting would then have indented and spaced the lines before the error wrongly.

Two changes fix this:

  1. Commit 1 records Chunk.statementStarts: every statement start the parser began, including abandoned ones. It is additive, with a unit test, and no other consumer changes.
  2. The spacing facts were moved from tree nodes to the token context (above).

Commits (one concern each; please review them one by one)

# Commit What it changes
1 refactor(server): record where the parser begins each statement Chunk.statementStarts (above) + test
2 feat(server): compute layout-preserving formatting edits for Lua src/server/formatting/format.ts (pure), 22 unit tests, including properties checked with the official compiler
3 fix(server): refuse invalid tab sizes and skip lexing for on-type keys in names Fixes for the project /review findings (below)
4 feat(server): add document, range and on-type formatting for Lua files Handlers, static/dynamic registration, fixture, feature unit tests, 4 integration tests, both changelogs
5 docs: document formatting README, editors guide, CONTRIBUTING, CLAUDE.md

Each commit type-checks and passes the unit tests on its own (checked in a temporary worktree: 426 → 464 → 465 → 473 → 473).

Project /review findings and what was done

Finding Severity Outcome
On-type requests for d e f l ) ] } arrive for every such key typed inside a name (field, self), and each one lexed the whole document Should fix Fixed (commit 3). The line up to the cursor must be exactly a closer before anything is lexed: 0.15 ms on a 78 KB file.
Every Enter in incomplete code logged an info line about the syntax error Should fix Fixed (commit 4): on-type refusals are logged at debug
An absurd tabSize with insertSpaces made ' '.repeat() allocate a huge string. LSP only says uinteger. Nit Fixed (commit 3). Refused (invalid-options, logged) unless it is an integer from 1 to 100: the bounds of VS Code's editor.tabSize (minimum: 1, maximum: 100 in its settings schema, checked in the 1.145.0 build). Values are refused rather than clamped to a guessed bound.
Call-argument chains (f"a""b", f{}{}, t[1]"x") not pinned Nit Fixed: tests added

The review also checked:

  • no vscode import in src/server or src/shared;
  • no client, command, setting, dependency, build or engines.vscode change, and no ID renamed;
  • every advertised capability has a handler;
  • all three handlers check cancellation before their synchronous work and never throw.

How it was tested

Locally (Linux/WSL2):

  • Passed: check-types; lint (0 warnings); test:unit (473 passing, up from 425); check-l10n; lua-manual -- --check.
  • npm test (xvfb-run): 47 passing on both VS Code 1.91.0 and stable (4 new). The tests run vscode.executeFormatDocumentProvider, …FormatRangeProvider and …FormatOnTypeProvider on the new original fixture format.lua, and check that a .menu file gets no formatter.
  • Packaging: package, then notices -- --check, then vsce package + vsce ls. The VSIX has 42 files, unchanged.
  • commitlint passes on all 5 commits and on the title.

Corpus check on 133 real Lua files found on the machine (4.0 MB, mods and game scripts; read in place, nothing copied or committed):

Invariant Result
Unsafe result (tokens or comments would change) 0
Not idempotent (formatting the result again changes it) 0
Compiled with the official Lua 5.2.4 compiler (WASM) before, not after 0
Range formatting over the whole text ≠ document formatting 0
Refused for syntax errors 41, exactly the files the official compiler rejects (0 disagreements between the parser and the compiler)

Timings (local, tree cached as in the server; mean of 10 runs):

File Format Document On-type \n mid-file On-type d ending a name
10 KB 0.41 ms 0.64 ms 0.03 ms
78 KB 8.7 ms 6.8 ms 0.15 ms
977 KB 101 ms 90 ms — (121 ms when an end was really typed)

Size (both built locally from the same tree; main in a temporary worktree):

Measure main This branch
dist/server/server.js 676,056 B 685,124 B (+9,068)
dist/client/extension.js 437,728 B unchanged
VSIX 321,829 B 325,543 B (+3,714)
Installed size (scripts/release/vsix.mts) 1,234,681 B 1,244,800 B (+10,119)

Limitations

  • .menu files are not formatted. Their Lua sits in `…` blocks, whose last character the engine drops, and in quoted property strings. Formatting it safely is a separate step.
  • Very large files. Around 1 MB, a request takes ~90–120 ms: two lexes of the file (~28 ms each) plus the layout pass. That is above the 50 ms guideline; files up to ~100 KB stay around 10 ms. Range and on-type requests stop the layout pass at the end of their lines, but still lex the whole file twice (once to format, once for the safety check).
  • Layout-preserving by design. No line wrapping, joining or splitting, no quote normalization, no alignment of =. The space before a trailing comment is kept as written.
  • No new settings. Turn formatting off as with any formatter (editor.formatOnSave, editor.formatOnType, editor.defaultFormatter).
  • Syntax errors. A file with a syntax error is not formatted by Format Document. The reason goes to the output channel (info level).

Checklist

  • npm run check-types, npm run lint and npm run test:unit pass
  • npm test (integration) passes, if activation, commands, settings or the LSP wiring changed
  • New logic has unit tests; new commands/settings have an integration test (no new commands or settings; formatting has integration tests)
  • User-facing strings use vscode.l10n.t() / package.nls.json, and npm run check-l10n passes (no new user-facing strings; the log messages are server logs, like the existing ones)
  • CHANGELOG.md and docs/CHANGELOG.vsix.md have entries under [Unreleased] (if users notice the change)
  • No setting key or command ID was renamed (breaking change), or it is called out above

🤖 Generated with Claude Code

4Luke4 and others added 5 commits November 4, 2026 22:46
`Chunk.statementStarts` lists the offset of the first token of every
statement the parser began, in source order. It includes statements that an
error made the parser abandon, which are missing from `body`: after
`if a then … elseif <eof>` the whole `if` statement is dropped, but the
statements typed inside it are still known.

Range and on-type formatting need this to indent the lines before a syntax
error that is still being typed. Nothing else changes; a unit test pins the
abandoned-statement case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`formatting/format.ts` (pure) computes the edits for document, range and
on-type formatting of a Lua 5.2 chunk. Only the white space between tokens and
comments changes: line breaks are kept exactly (characters and count), and the
inside of strings, long strings and long comments is never touched.

- Indentation by the constructs open at the start of each line (`function`,
  `do`, `then`, `else`, `repeat`, brackets), once per line that opens them, so
  `f(function()` indents its body once; a line led by closers takes the level
  of the line that opened them (`end)`, `}, {`); a line continuing a statement
  in a block gets one more level, and `then`/`do` open from the statement.
- Spacing within a line from an ordered rule table (spaces around binary
  operators, `=` and keywords; none inside `()`/`[]`, around `.`/`:`, after
  unary `-`/`#`, before call parentheses; `{ a }`; string and table call
  arguments joined or apart as written; space kept before trailing comments).
  The rules use token neighbors only, exact for valid Lua 5.2, so they hold
  before a syntax error that makes the parser abandon a statement.
- Trailing white space removed; `insertFinalNewline`/`trimFinalNewlines`
  honored for document formatting when the client sends `true`.
- Document formatting is refused on any lexical or syntax error; range and
  on-type formatting only on errors that start before the end of the lines
  they change (a line's layout depends only on the text up to it).
- Safety check: the result is lexed again and must have the same tokens,
  comments, errors and line breaks before its last token, or nothing is
  returned (`unsafe`). This guards e.g. `- -x` and `t[ [[s]] ]`.

Checked beyond the unit tests on 133 local Lua files (4 MB, not committed):
no unsafe result, idempotent, everything the official Lua 5.2.4 compiler
accepted still compiles, range over the whole text equals document
formatting, and the 41 refusals are exactly the files the compiler rejects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s in names

Two findings of the project review of the formatter:

- `insertSpaces` with a `tabSize` that is not an integer from 1 to 100 is now
  refused (`invalid-options`) instead of floored and clamped to 0. The bounds
  are those of VS Code's `editor.tabSize` setting (`minimum: 1, maximum: 100`
  in its settings schema, checked in the 1.145.0 build); LSP only says
  `uinteger`, and an absurd value made `' '.repeat()` allocate a huge string.
- On-type requests for `d`, `e`, `f`, `l`, `)`, `]`, `}` arrive for every such
  key typed inside a name (`field`, `self`). The line up to the cursor must now
  be exactly a closer before the document is lexed: 0.15 ms instead of a full
  lex for a 78 KB file.

Also pins call-argument chains (`f"a""b"`, `f{}{}`, `t[1]"x"`) in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Serves `textDocument/formatting`, `/rangeFormatting` and `/onTypeFormatting`
with the edits of `formatting/format.ts`, converted to LSP ranges.

- Lua only. When the client supports dynamic registration of a request, it is
  registered after `initialized` with a selector for language `lua` and for
  `**/*.[lL][uU][aA]` (other editors' language IDs), for the `file` and
  `untitled` schemes, so VS Code keeps reporting that `.menu` files have no
  formatter. Otherwise the capability is static, and the handler answers
  `null` for `.menu` documents.
- On-type triggers: `\n`, then `d e f l ) ] }` (the last characters of `end`,
  `else`, `elseif`, `until` and the closing brackets).
- Options: `tabSize`, `insertSpaces`, `insertFinalNewline`,
  `trimFinalNewlines`. No new settings.
- Refusals answer `null` and are logged: syntax errors at info level for
  explicit requests and at debug level for on-type ones (sent on every key
  while code is incomplete); invalid options and unsafe results as errors.
- Cancellation is checked before the synchronous work; nothing throws.

Tests: unit tests for the conversion, the `.menu` refusal, the logging levels,
the static/dynamic split and the selector; integration tests for the three
requests on the new original fixture `format.lua`, and for no formatter on a
`.menu` file. Both changelogs have entries under [Unreleased].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
README (feature list and status note), the editors guide (feature table and
what formatting does over LSP), CONTRIBUTING (layout) and CLAUDE.md (purpose
and layout).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@4Luke4
4Luke4 merged commit c65b397 into main Nov 4, 2026
@4Luke4
4Luke4 deleted the feat/formatting branch November 4, 2026 22:06
@4Luke4 4Luke4 mentioned this pull request Nov 5, 2026
6 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant