Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,32 @@ the extension live in [`docs/CHANGELOG.vsix.md`](docs/CHANGELOG.vsix.md).
- Fields are `property`, or `method` after `:`; library and EEex-Docs members (`string.format`,
`C:AddGold`) as documented. Assignment targets have `modification`, declared names
`declaration`, labels are `label`.
- Formatting of `.lua` files (`textDocument/formatting`, `/rangeFormatting` and
`/onTypeFormatting`), layout-preserving: only the white space between tokens and comments
changes. `.menu` files are not formatted (no formatter is offered for them).
- Line breaks are kept exactly as written; strings, long strings and long comments are never
touched. Trailing white space is removed (also after a `--` comment) and blank lines are
emptied.
- Indentation by the constructs open at the start of each line (`function`, `do`, `then`,
`else`, `repeat`, `(`, `[`, `{`), counted once per line that opens them (`f(function()` indents
its body once); a line that starts with `end`, `until`, `else`, `elseif`, `)`, `]` or `}` is
indented like the line that opened the construct; a line that continues a statement gets one
more level. One level is a tab, or `tabSize` spaces with `insertSpaces`; a `tabSize` that is
not an integer from 1 to 100 (the bounds of VS Code's `editor.tabSize`) is refused and logged.
- Spacing within a line: one space around binary operators, `=` and keywords and after `,`/`;`;
none inside `()`/`[]`, around `.`/`:`, after unary `-`/`#` or before the parentheses of a call
or function; `{ a }` and `{}`; string and table call arguments (`f"x"`, `f{…}`) stay joined or
apart as written; the space before a trailing comment is kept.
- `insertFinalNewline` and `trimFinalNewlines` are honored for document formatting when the
client sends `true`. No new settings.
- A file with a syntax error is not formatted (the reason is logged); range and on-type
formatting only refuse errors before the end of the lines they change.
- On-type: after a line break the finished line is formatted (a blank new line keeps the
editor's indentation); after the last character of `end`, `else`, `elseif`, `until`, `)`,
`]` or `}` that starts a line, the line is re-indented. VS Code needs `editor.formatOnType`.
- Every result is lexed again and must have the same tokens and comments, or nothing changes.
- Registered dynamically for Lua documents only (language `lua`, or `*.lua` in any letter case)
when the client supports it, so `.menu` files have no formatter; static otherwise.
- Error-tolerant Lua 5.2 parser and scope analysis (`src/server/syntax/`), checked against the
official compiler by a differential test; it publishes no diagnostics of its own.
- Localization of the manifest, UI strings and the language server's hover labels into all 14 VS
Expand Down
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
|---|---|
| Name | `IE Lua Language Server` |
| Publisher | `infinity-engine-tools` |
| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors |
| Purpose | Lua 5.2 language support (diagnostics, hover, completion, semantic tokens, formatting of `.lua` files, document and workspace symbols, folding, and same-file definition, references and rename now; more LSP features planned) for Infinity Engine EE `.lua` files and the Lua embedded in `.menu` files, usable from VS Code and other LSP editors |
| Language | TypeScript (strict) |
| Bundler | esbuild (two bundles: client + language server) |
| Minimum VS Code | `^1.91.0` (see `engines.vscode` in `package.json`; required by `vscode-languageclient` ≥ 10) |
Expand All @@ -35,6 +35,7 @@
│ │ ├── hover/ # Hover targets, library knowledge and rendering (pure, no LSP imports)
│ │ ├── completion/ # Completion candidates (pure, no LSP imports)
│ │ ├── semanticTokens/ # Name classification for semantic tokens (pure, no LSP imports)
│ │ ├── formatting/ # Layout-preserving Lua formatting edits (pure, no LSP imports)
│ │ ├── l10n.ts # Server messages in the client's locale (tables in l10n/server/)
│ │ ├── syntax/ # Lua 5.2 lexer, parser, scopes, symbols, folding (pure, no LSP imports)
│ │ ├── validation/ # Pure analysis logic (no LSP imports) — unit-tested directly
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ server (port 6009).
| `src/server/hover/` | What a hover describes and its text (pure; library data from `data/lua52/` and `data/eeex/`) |
| `src/server/completion/` | What completion offers at the cursor (pure; reuses the hover's knowledge and text) |
| `src/server/semanticTokens/` | What each name is, for semantic highlighting (pure; follows the hover's rules) |
| `src/server/formatting/` | Layout-preserving formatting edits for Lua (pure; every result re-lexed and checked) |
| `src/server/syntax/` | Error-tolerant Lua 5.2 parser, scope analysis, document symbols and folding (pure; checked against the official compiler by `test/unit/server/syntax/differential.test.ts`) |
| `src/server/workspace/` | Index of the workspace's Lua and `.menu` files, and `files.exclude` matching as VS Code applies it (file system injected, unit-tested with an in-memory one) |
| `src/shared/` | Types and constants used by both sides |
Expand Down
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the

> [!NOTE]
> This is an early version. It currently provides **syntax diagnostics**, **hover**,
> **completion**, **semantic highlighting**, **document symbols**, **workspace symbols**, **folding**,
> and **go to definition**, **find references** and **rename** within a file; cross-file navigation,
> formatting and more are planned.
> **completion**, **semantic highlighting**, **formatting** (Lua files), **document symbols**,
> **workspace symbols**, **folding**, and **go to definition**, **find references** and **rename**
> within a file; cross-file navigation, formatting of `.menu` files and more are planned.

## Features

Expand Down Expand Up @@ -60,6 +60,12 @@ Lua language support for the **Infinity Engine Enhanced Edition** games and the
"rules": { "*.global": { "bold": true } }
}
```
- **Format Document and Format Selection** for Lua files: indentation, spacing within a line and
trailing white space are fixed, while your line breaks stay where they are and strings and
comments are never changed (apart from trailing white space after a `--` comment). Tabs or spaces follow your editor settings (*Editor: Tab Size*,
*Editor: Insert Spaces*). Turn on *Editor: Format On Type* to have `end`, `else` and closing
brackets re-indented as you type them, or *Editor: Format On Save*. Files with a syntax error
are left unchanged. `.menu` files are not formatted yet.
- **Go to Definition, Find All References and Rename Symbol** for variables within a file. Locals
follow Lua's scoping rules; globals are followed across all the Lua of a `.menu` file. Rename
refuses, and says why, when it could change what the code does: a name already in use nearby,
Expand Down
5 changes: 5 additions & 0 deletions docs/CHANGELOG.vsix.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ versions with an **even** middle number (for example 1.**2**.0) are stable relea
VS Code's default theme, parameters, local and global variables, functions, table fields and
the functions the game provides can be colored differently, in Lua files and the Lua of `.menu`
files. Themes can style globals with the `global` modifier.
- **Format Document and Format Selection** for Lua files. Fixes indentation and spacing without
moving your line breaks, and never changes strings or the text of comments. It uses your
editor's tab and indentation settings, and with *Editor: Format On Type* it re-indents `end`,
`else` and closing brackets as you type them. Files with syntax errors are left as they are;
`.menu` files are not formatted yet.
- **Available in 14 languages**, following your VS Code display language.
- **Works in other editors too**: setup guides for Sublime Text, Neovim, Emacs, JetBrains
IDEs, Helix, Zed, Kate, Notepad++ and Geany are on the project page.
15 changes: 14 additions & 1 deletion docs/editors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ node /path/to/server.js --stdio
| Hover | `textDocument/hover` | Markdown or plain text, whichever the editor prefers (`hover.contentFormat`); the server's own words follow the editor's `locale`. See below. |
| Completion | `textDocument/completion`, `completionItem/resolve` | Triggered by `.` and `:`. Documentation is sent on resolve, in the editor's preferred `completionItem.documentationFormat`. See below. |
| Semantic tokens | `textDocument/semanticTokens/full`, `/full/delta`, `/range` | Names only (keywords, strings and comments are left to the editor's highlighting). See below. |
| Formatting | `textDocument/formatting`, `/rangeFormatting`, `/onTypeFormatting` | `.lua` files only. Keeps your line breaks; uses the editor's tab size and spaces/tabs option. See below. |
| Workspace symbols | `workspace/symbol` | Every `*.lua` and `*.menu` file under the workspace folders, plus open files. See below. |

Workspace symbols need an editor that sends **workspace folders** when it starts the server;
Expand Down Expand Up @@ -104,6 +105,18 @@ Semantic tokens classify every name in the Lua with standard token types (`names
functions. How the names are colored depends on the editor and its color scheme; an editor that
ignores the `global` modifier still gets the token type.

Symbols, folding, hover, completion, semantic tokens and navigation always reflect the current text, whatever `validate.mode` is.
Formatting changes only the white space between tokens and comments: indentation, spacing
within a line and trailing white space. Line breaks stay where you put them, and strings and
comments are never changed, apart from trailing white space after a `--` comment. It follows the
`tabSize` and `insertSpaces` the editor sends, and `insertFinalNewline` / `trimFinalNewlines`
when the editor sends them. A file with a syntax error is not formatted (the reason goes to the
server log). On-type formatting re-indents a line when you type the last character of `end`,
`else`, `elseif`, `until`, `)`, `]` or `}` at its start, and formats the line you leave with
Enter, if your editor sends on-type formatting requests (some send them only when an option is
turned on; see its documentation). When the editor supports dynamic registration, formatting is
offered for Lua documents only (language `lua`, or `*.lua` in any letter case), so `.menu` files
have no formatter; other editors get no edits for `.menu` files.

Symbols, folding, hover, completion, semantic tokens, formatting and navigation always reflect the current text, whatever `validate.mode` is.
Navigation works on variables: table fields (`t.x`) and `goto` labels are not followed, and in a
`.menu` file globals are shared by all its Lua, while locals stay in their own block or script.
180 changes: 180 additions & 0 deletions src/server/features/formatting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import type {
Connection,
DocumentSelector,
FormattingOptions as LspFormattingOptions,
ServerCapabilities,
TextDocumentClientCapabilities,
TextDocuments,
TextEdit,
} from 'vscode-languageserver/node';
import { DocumentFormattingRequest, DocumentOnTypeFormattingRequest, DocumentRangeFormattingRequest } from 'vscode-languageserver/node';
import type { TextDocument } from 'vscode-languageserver-textdocument';
import { DOCUMENT_SCHEMES } from '../../shared/protocol.ts';
import type { ParsedDocumentCache } from '../documentCache.ts';
import {
formatDocument,
formatOnType,
formatRange,
ON_TYPE_FIRST_TRIGGER,
ON_TYPE_MORE_TRIGGERS,
MAX_TAB_SIZE,
MIN_TAB_SIZE,
type FormatResult,
type FormattingOptions,
} from '../formatting/format.ts';
import type * as Ast from '../syntax/ast.ts';

export interface FormattingDeps {
readonly cache: ParsedDocumentCache;
}

/**
* The documents formatting is offered for: Lua files, by language ID (VS Code) or by
* extension in any letter case (editors with other language IDs). Not .menu files,
* which are not formatted yet, so VS Code keeps reporting that they have no formatter.
*/
export const LUA_SELECTOR: DocumentSelector = DOCUMENT_SCHEMES.flatMap((scheme) => [
{ language: 'lua', scheme },
{ scheme, pattern: '**/*.[lL][uU][aA]' },
]);

const ON_TYPE_OPTIONS = { firstTriggerCharacter: ON_TYPE_FIRST_TRIGGER, moreTriggerCharacter: [...ON_TYPE_MORE_TRIGGERS] };

/** Which formatting requests the client registers dynamically (with `LUA_SELECTOR`); the others are advertised statically. */
export interface FormattingRegistration {
readonly document: boolean;
readonly range: boolean;
readonly onType: boolean;
}

export function dynamicRegistration(capabilities: TextDocumentClientCapabilities | undefined): FormattingRegistration {
return {
document: capabilities?.formatting?.dynamicRegistration === true,
range: capabilities?.rangeFormatting?.dynamicRegistration === true,
onType: capabilities?.onTypeFormatting?.dynamicRegistration === true,
};
}

/**
* Server capabilities for the requests the client does not register dynamically.
* A static capability cannot carry a document selector, so these handlers answer
* `null` for .menu documents.
*/
export function staticCapabilities(dynamic: FormattingRegistration): Pick<
ServerCapabilities,
'documentFormattingProvider' | 'documentRangeFormattingProvider' | 'documentOnTypeFormattingProvider'
> {
return {
...(dynamic.document ? {} : { documentFormattingProvider: true }),
...(dynamic.range ? {} : { documentRangeFormattingProvider: true }),
...(dynamic.onType ? {} : { documentOnTypeFormattingProvider: ON_TYPE_OPTIONS }),
};
}

/** Registers the dynamically registered requests; call after `initialized`. */
export function registerDynamically(connection: Connection, dynamic: FormattingRegistration): void {
const failed = (request: string) => (error: unknown) => {
connection.console.warn(`Could not register ${request}; it is unavailable: ${String(error)}`);
};
if (dynamic.document) {
connection.client.register(DocumentFormattingRequest.type, { documentSelector: LUA_SELECTOR }).catch(failed('document formatting'));
}
if (dynamic.range) {
connection.client.register(DocumentRangeFormattingRequest.type, { documentSelector: LUA_SELECTOR }).catch(failed('range formatting'));
}
if (dynamic.onType) {
connection.client
.register(DocumentOnTypeFormattingRequest.type, { documentSelector: LUA_SELECTOR, ...ON_TYPE_OPTIONS })
.catch(failed('on-type formatting'));
}
}

/** The LSP options the formatter honors; the others (`trimTrailingWhitespace`, …) do not change its result. */
export function formatterOptions(options: LspFormattingOptions): FormattingOptions {
return {
tabSize: options.tabSize,
insertSpaces: options.insertSpaces,
insertFinalNewline: options.insertFinalNewline,
trimFinalNewlines: options.trimFinalNewlines,
};
}

/**
* What the server logs about a request it did not answer with edits. Refusals of
* explicit requests are `info`; refusals of on-type requests, sent at every key the
* user types while the code is incomplete, are `debug`.
*/
export type FormattingLog = (level: 'debug' | 'info' | 'error', message: string) => void;

/**
* Runs `format` on the Lua chunk of `document` and converts its result to LSP edits.
* `null` for .menu documents, refused requests and failures, which are logged.
*/
export function formattingEdits(
document: TextDocument,
cache: ParsedDocumentCache,
format: (text: string, tree: Ast.Chunk) => FormatResult,
log: FormattingLog,
refusalLevel: 'debug' | 'info' = 'info',
): TextEdit[] | null {
const parsed = cache.get(document);
const chunk = parsed.chunks[0];
if (parsed.kind !== 'lua' || chunk === undefined) return null;
const result = format(document.getText(), chunk.tree);
if (!result.ok) {
if (result.reason === 'syntax-error') {
log(refusalLevel, `Not formatting ${document.uri}: it has a syntax error before the end of the formatted lines.`);
} else if (result.reason === 'invalid-options') {
log('error', `Not formatting ${document.uri}: with insertSpaces, tabSize must be an integer from ${MIN_TAB_SIZE} to ${MAX_TAB_SIZE}.`);
} else {
log('error', `Not formatting ${document.uri}: the result would not lex to the same tokens. Please report this with the file.`);
}
return null;
}
return result.edits.map((edit) => ({
range: { start: document.positionAt(edit.start), end: document.positionAt(edit.end) },
newText: edit.newText,
}));
}

/** `textDocument/formatting`, `/rangeFormatting` and `/onTypeFormatting` (see src/server/formatting/format.ts). */
export function register(connection: Connection, documents: TextDocuments<TextDocument>, deps: FormattingDeps): void {
const log: FormattingLog = (level, message) => {
if (level === 'debug') connection.console.debug(message);
else if (level === 'info') connection.console.info(message);
else connection.console.error(message);
};
/** Shared by the three handlers: synchronous after the lookup, so a cancellation can only arrive after the response. */
const answer = (
uri: string,
cancelled: boolean,
format: (document: TextDocument, text: string, tree: Ast.Chunk) => FormatResult,
refusalLevel: 'debug' | 'info' = 'info',
): TextEdit[] | null => {
try {
const document = documents.get(uri);
if (!document || cancelled) return null;
return formattingEdits(document, deps.cache, (text, tree) => format(document, text, tree), log, refusalLevel);
} catch (error) {
connection.console.error(`Formatting ${uri} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
return null;
}
};

connection.onDocumentFormatting(({ textDocument, options }, token) =>
answer(textDocument.uri, token.isCancellationRequested, (_document, text, tree) => formatDocument(text, tree, formatterOptions(options))),
);
connection.onDocumentRangeFormatting(({ textDocument, range, options }, token) =>
answer(textDocument.uri, token.isCancellationRequested, (document, text, tree) =>
formatRange(text, tree, formatterOptions(options), document.offsetAt(range.start), document.offsetAt(range.end)),
),
);
connection.onDocumentOnTypeFormatting(({ textDocument, position, ch, options }, token) =>
answer(
textDocument.uri,
token.isCancellationRequested,
(document, text, tree) => formatOnType(text, tree, formatterOptions(options), document.offsetAt(position), ch),
'debug',
),
);
}
Loading