Repository navigation
feat: add layout-preserving formatting for Lua files - #12
Merged
Merged
Conversation
`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>
6 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
This is the next
plan.mdstep after #8: Formatting (textDocument/formatting,/rangeFormattingand/onTypeFormatting). Quick fixes and JSDoc are still missing.The server now formats
.luafiles. 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:
.menufiles.luaonly in this step. VS Code reports that.menufiles have no formatter. Follow-up.FormattingOptions:tabSize,insertSpaces,insertFinalNewline,trimFinalNewlines.Rules
Indentation. One level is a tab, or
tabSizespaces withinsertSpaces.function,do(also ofwhile/for),then,else,repeat,(,[,{f(function()indents its body once.end,until,else,elseif,),],}(one or more)end)→ the level of thef(function()line;}, {→ the level of thef({lineif a and/b then,local x = a +/b,obj/:m())then/doon a line of their ownSpacing within a line. These rules come from an ordered table in
inlineSpace; the first match wins.::name::,;/ after them([, before)][[would start a long string.{, before}{}stays empty.and:-and#-, because--would start a comment.(of a call or a function's parameters, the[of an indexf"x",f{…})=, names)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.
endhasn'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 completesend,else,elseif,untilor 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.
initializedwith a Lua-only selector:{ language: 'lua', scheme }{ scheme, pattern: '**/*.[lL][uU][aA]' }, for editors with other language IDsfileanduntitled.nullfor.menudocuments.Logging of refusals.
infodebugerrorDeviation 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 wholeifstatement, 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:
Chunk.statementStarts: every statement start the parser began, including abandoned ones. It is additive, with a unit test, and no other consumer changes.Commits (one concern each; please review them one by one)
refactor(server): record where the parser begins each statementChunk.statementStarts(above) + testfeat(server): compute layout-preserving formatting edits for Luasrc/server/formatting/format.ts(pure), 22 unit tests, including properties checked with the official compilerfix(server): refuse invalid tab sizes and skip lexing for on-type keys in names/reviewfindings (below)feat(server): add document, range and on-type formatting for Lua filesdocs: document formattingEach commit type-checks and passes the unit tests on its own (checked in a temporary worktree: 426 → 464 → 465 → 473 → 473).
Project
/reviewfindings and what was doned e f l ) ] }arrive for every such key typed inside a name (field,self), and each one lexed the whole documentinfoline about the syntax errordebugtabSizewithinsertSpacesmade' '.repeat()allocate a huge string. LSP only saysuinteger.invalid-options, logged) unless it is an integer from 1 to 100: the bounds of VS Code'seditor.tabSize(minimum: 1, maximum: 100in its settings schema, checked in the 1.145.0 build). Values are refused rather than clamped to a guessed bound.f"a""b",f{}{},t[1]"x") not pinnedThe review also checked:
vscodeimport insrc/serverorsrc/shared;engines.vscodechange, and no ID renamed;How it was tested
Locally (Linux/WSL2):
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 runvscode.executeFormatDocumentProvider,…FormatRangeProviderand…FormatOnTypeProvideron the new original fixtureformat.lua, and check that a.menufile gets no formatter.package, thennotices -- --check, thenvsce package+vsce ls. The VSIX has 42 files, unchanged.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):
Timings (local, tree cached as in the server; mean of 10 runs):
\nmid-filedending a nameendwas really typed)Size (both built locally from the same tree;
mainin a temporary worktree):maindist/server/server.jsdist/client/extension.jsscripts/release/vsix.mts)Limitations
.menufiles 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.=. The space before a trailing comment is kept as written.editor.formatOnSave,editor.formatOnType,editor.defaultFormatter).Checklist
npm run check-types,npm run lintandnpm run test:unitpassnpm test(integration) passes, if activation, commands, settings or the LSP wiring changedvscode.l10n.t()/package.nls.json, andnpm run check-l10npasses (no new user-facing strings; the log messages are server logs, like the existing ones)CHANGELOG.mdanddocs/CHANGELOG.vsix.mdhave entries under[Unreleased](if users notice the change)🤖 Generated with Claude Code