Dough Git

commit

Add other langs

commit
9a04e44ef8d21af58b3cdc60629a91bb5864e726
author
Clove <[email protected]>
date
2026-11-23 21:41

diff --git a/Cargo.lock b/Cargo.lock
index 373bb74..aef33f2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -19,7 +19,7 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
 
 [[package]]
 name = "c4d"
-version = "1.0.0"
+version = "1.0.1"
 dependencies = [
  "jpcl",
  "proc-macro2",
diff --git a/Cargo.toml b/Cargo.toml
index 05e1f99..d52260b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
 
 [package]
 name = "c4d"
-version = "1.0.0"
+version = "1.0.1"
 edition = "2024"
 rust-version = "1.85"
 description = "Local source-code formatting and accessibility checks"
@@ -15,6 +15,7 @@ include = [
     "/data/default.jp",
     "/LICENSE",
     "/README.md",
+    "/SUPPORTED.md",
 ]
 
 [dependencies]
diff --git a/README.md b/README.md
index 88a65f2..08b472c 100644
--- a/README.md
+++ b/README.md
@@ -2,340 +2,19 @@
 
 # code4dyslexia
 
-`c4d` is a local formatter and naming checker for developers with dyslexia. The
-same file and settings produce the same output. The executable needs no AI,
-API keys, network access, or language-server process.
-
-The [dyslexia-friendly-code skill](https://github.com/doughmination/dyslexia-friendly-code)
-inspired consistent indentation, spacing between logical blocks, and optional
-checks for common naming conventions. C4D leaves line wrapping, comment
-placement, file headers, identifier similarity, and renaming to the author.
-Those choices can depend on intent, public interfaces, or a reader's preferences.
-
-## Install
-
-Install the published alpha from crates.io by specifying its version explicitly.
+`c4d` is a local code formatter and naming checker for developers with dyslexia.
 
 ```sh
-cargo install c4d --version 1.0.0-alpha-1 --locked
+cargo install c4d --locked
 ```
 
-Cargo skips prereleases when you omit the version. To install the current
-checkout instead, run this from the repository root.
+From a checkout, use `cargo install --path . --locked`.
 
 ```sh
-cargo install --path . --locked
-c4d version
-```
-
-Cargo may fetch dependencies on the first build. For a machine with a populated
-Cargo cache, add `--offline` to install without the network. Cargo installs the
-native executable in `~/.cargo/bin` by default. Alternatively, build with
-`cargo build --release --locked` and run `target/release/c4d`.
-
-## Commands
-
-```sh
-c4d version
 c4d check .
+c4d format --check .
 c4d format .
-c4d format --check src/main.rs tests/
 c4d config show
-c4d config show src/main.rs --language rust
-```
-
-| Command | Behaviour |
-| --- | --- |
-| `version` | Prints the installed version. Also available as `-V` and `--version`. |
-| `check` | Reports naming and formatting issues with file, line, and column. |
-| `format` | Applies whitespace rules and adds path headers when enabled. |
-| `format --check` | Lists files that would change without writing. |
-| `config show` | Prints effective settings as JPCL, with the source of each value in comments. |
-
-Paths default to the current directory. `check` and `format` accept multiple
-files and directories. Use `--` before input paths starting with a dash.
-Successful interactive scans print a summary, including when no supported files are found.
-Exit code `0` means the command succeeded, `1` means a check found issues,
-and `2` means usage, configuration, syntax, or I/O errors. Explicit skips are
-reported on stderr and do not count as issues. A formatting run operates
-file by file, so an error can occur after other files have been written.
-
-## Configuration
-
-`c4d config show` creates `~/.c4d/config.jp` from the bundled defaults if it
-is missing. Existing global settings keep their contents.
-
-Use `~/.c4d/config.jp` for global settings and
-`<project-root>/.c4d/config.jp` for project settings. C4D looks upward from
-each source directory for the nearest project file and stops at the Git root
-if it finds one first. A nested project config takes the project layer for
-files in its subtree.
-
-Each setting inherits independently. From lowest to highest precedence
-
-1. Built-in defaults
-2. Global settings
-3. Global language override
-4. Project settings
-5. Project language override
-
-Omit a key to inherit it. Set a formatting option to `0` to disable that
-transformation, or a naming option to `disabled` to turn off its check.
-Formatting sizes are integers from 0 to 100. Invalid configuration reports the
-file and, for JPCL syntax errors, the parser's line and column.
-
-The official [JPCL parser](https://github.com/jpcl-lang/jpcl) accepts bare
-setting values, `[section]` headers, nested objects, line comments beginning
-with `~~`, and block comments wrapped in `~*` and `*~`.
-The following [default file](data/default.jp) is embedded in the executable.
-
-```jpcl
-~* Default configuration for code4dyslexia
-   (c) MIT - Clove Twilight 2026
-   https://github.com/doughmination/code4dyslexia
-*~
-
-[terminal]
-color: default
-
-[formatting]
-~~ Set any of these to 0 to disable them
-indentSize: 4
-newLineSize: 2
-~~ Enable to add a file path comment automatically
-filePathHeader: false
-
-[cases]
-~* Accepted values:
-   flatcase - acoolfunction
-   camelCase - aCoolFunction
-   PascalCase - ACoolFunction
-   snake_case - a_cool_function
-   SCREAMING_SNAKE_CASE - A_COOL_FUNCTION
-   disabled - Disables checks
-*~
-functions: disabled
-variables: disabled
-classes: disabled
-
-~~ Uncomment the override block to customise individual languages
-
-~*
-[overrides]
-typescript: {
-    formatting: {
-        newLineSize: 3
-    }
-    cases: {
-        functions: camelCase
-    }
-}
-*~
-```
-
-The commented TypeScript example is valid JPCL and can be inspected when
-enabled. Language overrides for an adapter that has yet to be implemented
-have no effect on file processing. To configure the Rust adapter, use the
-`rust` language identifier.
-
-```jpcl
-[overrides.rust.formatting]
-newLineSize: 3
-
-[overrides.rust.cases]
-functions: snake_case
-```
-
-## Terminal colours
-
-Choose a theme in global or project JPCL settings.
-
-```jpcl
-[terminal]
-color: catppuccin
-```
-
-| Theme | Appearance |
-| --- | --- |
-| `default` or `normal` | Standard terminal colours. This is the default. |
-| `pastel` | Soft teal, lilac, and rose accents. |
-| `catppuccin` | Green, yellow, and red from [Catppuccin Mocha](https://catppuccin.com/palette/#mocha). |
-| `protanopia`, `protanomaly`, `deuteranopia`, `deuteranomaly` | Blue and amber accents for red–green colour vision differences. |
-| `tritanopia`, `tritanomaly` | Green and pink accents for blue–yellow colour vision differences. |
-| `achromatopsia`, `blue-cone-monochromacy`, `monochrome` | Bold and underlined labels without colour. |
-| `plain` | Plain text. |
-
-Themes style rule names and formatting status labels. Those labels remain
-readable in plain text. Redirected output, configuration output, `TERM=dumb`, and a non-empty
-`NO_COLOR` environment variable all produce plain text. The RGB themes work
-best in a true-colour terminal. To choose a theme for Rust specifically,
-set `color` under `[overrides.rust.terminal]`.
-
-## Supported sources
-
-C4D supports UTF-8 Rust (`.rs`), Go (`.go`), Python (`.py` and `.pyi`),
-JSON (`.json`), and JSON with comments (`.jsonc`). Their configuration
-identifiers are `rust`, `go`, `python`, `json`, and `jsonc`. Extensions are
-case-insensitive. TypeScript and JavaScript files are skipped.
-
-### Rust
-
-The Rust adapter uses [syn](https://docs.rs/syn/2.0.117/syn/) for the syntax tree and
-[proc-macro2](https://docs.rs/proc-macro2/1.0.106/proc_macro2/struct.Span.html)
-for source token spans.
-
-#### Rust formatting
-
-- `indentSize` controls leading spaces on lines that begin with a token.
-  Each active multiline brace, bracket, or parenthesis group contributes
-  one level. Nested groups opened on the same line share a level. A line
-  that begins with a closing delimiter uses the enclosing level.
-- `newLineSize` counts newline sequences between sibling items or statements
-  already on separate lines, where at least one sibling is a logical block.
-  Logical blocks include functions, structs, enums, unions, impls, traits,
-  modules, and extern blocks. At statement level they also include standalone
-  blocks and control-flow expressions such as `if`, `match`, and loops.
-  C4D edits gaps made entirely of whitespace and uses the first newline
-  sequence in the gap. A size of `2` gives one empty line.
-- By default, formatting edits only leading indentation and qualifying gaps. Literals,
-  comments, macro arguments, and attribute contents keep their bytes.
-  Files containing explicit `line!()` or `column!()` calls retain all source
-  positions. Checks still report naming issues in those files.
-
-The syntax check is based on the parser available in the pinned version of
-`syn`. It does not type-check, resolve names, evaluate configuration
-attributes, or expand macros. Some macro-expanded code and compiler features
-are opaque to the tool. Formatting can shift source locations observed
-indirectly through macros, compiler diagnostics, or caller metadata.
-
-#### File path headers
-
-Enable this option in `.c4d/config.jp` to have `c4d format` add a comment
-such as `// src/main.rs`. The option defaults to `false`.
-
-```jpcl
-[formatting]
-filePathHeader: true
 ```
 
-C4D uses the path relative to the project root, or the working directory
-when there is no project root. Files outside both use their basename.
-The comment goes after a byte-order mark or shebang when present.
-An exact matching path in the leading comments counts as an existing header.
-`c4d check` reports missing headers and `c4d format --check` previews them.
-Files with explicit `line!()` or `column!()` calls also skip header insertion.
-
-#### Rust naming
-
-| Option | Rust declarations checked |
-| --- | --- |
-| `functions` | Named functions and method signatures |
-| `variables` | Pattern bindings, including function parameters, and named const and static items |
-| `classes` | Structs, enums, unions, and traits |
-
-All checks are disabled by default. With a check enabled, names are matched
-against that convention's ASCII letters, digits, and underscore pattern.
-A Rust raw identifier prefix `r#` is ignored for matching. Diagnostics
-never change the identifier.
-
-### JSON and JSONC
-
-C4D validates files before applying whitespace edits. JSON uses strict JSON
-syntax. JSONC also accepts line comments, block comments, and trailing commas.
-The extension selects the syntax. A `.json` file containing comments reports
-a syntax error.
-
-- `indentSize` sets the leading spaces per open object or array. A line that
-  starts with a closing delimiter uses the enclosing level.
-- `newLineSize` applies between siblings on separate lines when either value
-  is an object or array. A gap containing a comment is left intact.
-- Strings, number spellings, duplicate keys, key order, and comment contents
-  keep their original bytes. The JSON adapters skip file path headers and
-  naming checks.
-
-### Python
-
-Python formatting requires CPython 3.11 or newer as `python3` on PATH.
-C4D uses it to parse and tokenize source without executing it. The installed
-Python version determines which syntax is supported. The adapter accepts
-UTF-8 source with LF or CRLF line endings.
-
-- `indentSize` sets spaces per indentation level on logical statement lines.
-  Continuation lines, comments, and multiline string contents keep their
-  original spacing.
-- `newLineSize` sets the spacing between statements in the same suite when
-  either is a compound statement such as a definition, loop, or conditional.
-  Gaps containing comments keep their existing spacing.
-- `filePathHeader` adds a `# path/to/file.py` comment after any shebang and
-  encoding declaration.
-- Naming checks cover function and class definitions, parameters, and simple
-  name bindings. Checks report diagnostics without renaming anything.
-
-Before writing, C4D reparses the proposed result and compares the two syntax
-trees. Formatting can still shift source line numbers used by tracebacks or
-inspection tools.
-
-### Go
-
-Go formatting requires Go 1.21 or newer as `go` on PATH. C4D starts one
-helper per invocation using Go's standard parser and scanner. The helper
-builds locally with the installed toolchain and uses its normal build cache.
-C4D parses the source without building or executing the Go files you pass in.
-
-- `indentSize` sets spaces per open brace, bracket, or parenthesis. Lines
-  beginning with a closing delimiter use the enclosing level.
-- `newLineSize` applies between sibling declarations or statements on
-  different lines when one is a logical block. These include functions,
-  type declarations, grouped declarations, loops, conditionals, switches,
-  selects, and standalone blocks. Gaps with comments keep their spacing.
-- `filePathHeader` inserts a standalone `// path/to/file.go` comment above
-  the source. Files with Go line directives keep their position and spacing.
-- Naming checks cover functions and methods, named types, named parameters
-  and results, const and var declarations, and names on the left of `:=`.
-
-Before writing, C4D reparses the result and compares token kinds and spellings,
-including implicit semicolons. Literals and existing comments keep their
-bytes. Syntax checking uses Go's parser and skips package type checking.
-
-### Discovery
-
-Directories are traversed in name order. The tool skips symlinks, non-source
-files, and common dependency, cache, and build directories such as `.git`,
-`node_modules`, `target`, `vendor`, and `dist`. It also skips invalid UTF-8,
-files with NUL bytes, generated suffixes such as `.generated.rs`, and
-recognised generated markers in the leading comments. Add unusual generated
-paths to `.c4dignore`.
-
-C4D reads ancestor and nested `.gitignore` and `.c4dignore` files. It supports
-ordinary Git-style path patterns, including anchors, directory-only patterns,
-wildcards, character ranges, escaped leading markers, and negation. Global
-Git excludes and `.git/info/exclude` are outside this first release.
-
-Writes replace a changed file atomically and preserve its permission bits.
-On Unix, C4D rejects files with multiple hard links. It checks for changes to
-the source immediately before replacement. Avoid concurrent formatting and
-editing of the same file.
-
-## Contributing
-
-Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`,
-and `cargo test --locked` before submitting a change. The Python and Go integration
-tests use `python3` and `go` respectively. When adding a language,
-register its adapter in `src/language.rs` and add representative fixtures
-covering syntax-sensitive whitespace, literals, comments, and repeat runs.
-Keep transformations constrained to the spans that the adapter can verify.
-
-## Publishing
-
-1. Verify the package with `cargo publish --locked --dry-run`. For the first
-   release, authenticate locally and run `cargo publish --locked` from a clean
-   checkout.
-2. Set up [crates.io Trusted Publishing](https://crates.io/docs/trusted-publishing)
-   for `doughmination/code4dyslexia`. Use the workflow filename `publish.yml`
-   and the GitHub environment `crates-io`.
-3. For later versions, push the version bump in `Cargo.toml` and `Cargo.lock`.
-   In GitHub Actions, open **Publish c4d to crates.io**, choose **Run workflow**,
-   and select the branch you want to publish. The workflow tests that branch
-   and publishes the version in its manifest via an OIDC token.
-
-[MIT licence](LICENSE).
+[Supported languages and settings](SUPPORTED.md) · [MIT licence](LICENSE)
diff --git a/SUPPORTED.md b/SUPPORTED.md
new file mode 100644
index 0000000..8a45ac6
--- /dev/null
+++ b/SUPPORTED.md
@@ -0,0 +1,306 @@
+<!-- SUPPORTED.md -->
+
+# Supported languages and settings
+
+## Configuration
+
+`c4d config show` creates `~/.c4d/config.jp` from the bundled defaults if it
+is missing. Existing global settings keep their contents.
+
+Use `~/.c4d/config.jp` for global settings and
+`<project-root>/.c4d/config.jp` for project settings. C4D looks upward from
+each source directory for the nearest project file and stops at the Git root
+if it finds one first. A nested project config takes the project layer for
+files in its subtree.
+
+Each setting inherits independently. From lowest to highest precedence
+
+1. Built-in defaults
+2. Global settings
+3. Global language override
+4. Project settings
+5. Project language override
+
+Omit a key to inherit it. Set a formatting option to `0` to disable that
+transformation, or a naming option to `disabled` to turn off its check.
+Formatting sizes are integers from 0 to 100. Invalid configuration reports the
+file and, for JPCL syntax errors, the parser's line and column.
+
+The official [JPCL parser](https://github.com/jpcl-lang/jpcl) accepts bare
+setting values, `[section]` headers, nested objects, line comments beginning
+with `~~`, and block comments wrapped in `~*` and `*~`.
+The following [default file](data/default.jp) is embedded in the executable.
+
+```jpcl
+~* Default configuration for code4dyslexia
+   (c) MIT - Clove Twilight 2026
+   https://github.com/doughmination/code4dyslexia
+*~
+
+[terminal]
+color: default
+
+[formatting]
+~~ Set any of these to 0 to disable them
+indentSize: 4
+newLineSize: 2
+~~ Enable to add a file path comment automatically
+filePathHeader: false
+
+[cases]
+~* Accepted values:
+   flatcase - acoolfunction
+   camelCase - aCoolFunction
+   PascalCase - ACoolFunction
+   snake_case - a_cool_function
+   SCREAMING_SNAKE_CASE - A_COOL_FUNCTION
+   disabled - Disables checks
+*~
+functions: disabled
+variables: disabled
+classes: disabled
+
+~~ Uncomment the override block to customise individual languages
+
+~*
+[overrides]
+typescript: {
+    formatting: {
+        newLineSize: 3
+    }
+    cases: {
+        functions: camelCase
+    }
+}
+*~
+```
+
+The commented TypeScript example is valid JPCL and can be inspected when
+enabled. Language overrides for an adapter that has yet to be implemented
+have no effect on file processing. To configure the Rust adapter, use the
+`rust` language identifier.
+
+```jpcl
+[overrides.rust.formatting]
+newLineSize: 3
+
+[overrides.rust.cases]
+functions: snake_case
+```
+
+## Terminal colours
+
+Choose a theme in global or project JPCL settings.
+
+```jpcl
+[terminal]
+color: catppuccin
+```
+
+| Theme | Appearance |
+| --- | --- |
+| `default` or `normal` | Standard terminal colours. This is the default. |
+| `pastel` | Soft teal, lilac, and rose accents. |
+| `catppuccin` | Green, yellow, and red from [Catppuccin Mocha](https://catppuccin.com/palette/#mocha). |
+| `protanopia`, `protanomaly`, `deuteranopia`, `deuteranomaly` | Blue and amber accents for red–green colour vision differences. |
+| `tritanopia`, `tritanomaly` | Green and pink accents for blue–yellow colour vision differences. |
+| `achromatopsia`, `blue-cone-monochromacy`, `monochrome` | Bold and underlined labels without colour. |
+| `plain` | Plain text. |
+
+Themes style rule names and formatting status labels. Those labels remain
+readable in plain text. Redirected output, configuration output, `TERM=dumb`, and a non-empty
+`NO_COLOR` environment variable all produce plain text. The RGB themes work
+best in a true-colour terminal. To choose a theme for Rust specifically,
+set `color` under `[overrides.rust.terminal]`.
+
+## Supported sources
+
+Extensions are case-insensitive. Use the language identifier under `[overrides]`.
+
+| Language | Extensions | Tool needed |
+| --- | --- | --- |
+| Rust | `.rs` | Built in |
+| JSON | `.json` | Built in |
+| JSONC | `.jsonc` | Built in |
+| Python | `.py`, `.pyi` | CPython 3.11+ |
+| Go | `.go` | Go 1.21+ |
+| TypeScript | `.ts`, `.mts`, `.cts` | Node.js and the TypeScript 6 compiler package |
+| JavaScript | `.js`, `.mjs`, `.cjs` | Node.js and the TypeScript 6 compiler package |
+| Lua | `.lua` | `luac` on PATH |
+
+### Rust
+
+The Rust adapter uses [syn](https://docs.rs/syn/2.0.117/syn/) for the syntax tree and
+[proc-macro2](https://docs.rs/proc-macro2/1.0.106/proc_macro2/struct.Span.html)
+for source token spans.
+
+#### Rust formatting
+
+- `indentSize` controls leading spaces on lines that begin with a token.
+  Each active multiline brace, bracket, or parenthesis group contributes
+  one level. Nested groups opened on the same line share a level. A line
+  that begins with a closing delimiter uses the enclosing level.
+- `newLineSize` counts newline sequences between sibling items or statements
+  already on separate lines, where at least one sibling is a logical block.
+  Logical blocks include functions, structs, enums, unions, impls, traits,
+  modules, and extern blocks. At statement level they also include standalone
+  blocks and control-flow expressions such as `if`, `match`, and loops.
+  C4D edits gaps made entirely of whitespace and uses the first newline
+  sequence in the gap. A size of `2` gives one empty line.
+- By default, formatting edits only leading indentation and qualifying gaps. Literals,
+  comments, macro arguments, and attribute contents keep their bytes.
+  Files containing explicit `line!()` or `column!()` calls retain all source
+  positions. Checks still report naming issues in those files.
+
+The syntax check is based on the parser available in the pinned version of
+`syn`. It does not type-check, resolve names, evaluate configuration
+attributes, or expand macros. Some macro-expanded code and compiler features
+are opaque to the tool. Formatting can shift source locations observed
+indirectly through macros, compiler diagnostics, or caller metadata.
+
+#### File path headers
+
+Enable this option in `.c4d/config.jp` to have `c4d format` add a comment
+such as `// src/main.rs`. The option defaults to `false`.
+
+```jpcl
+[formatting]
+filePathHeader: true
+```
+
+C4D uses the path relative to the project root, or the working directory
+when there is no project root. Files outside both use their basename.
+The comment goes after a byte-order mark or shebang when present.
+An exact matching path in the leading comments counts as an existing header.
+`c4d check` reports missing headers and `c4d format --check` previews them.
+Files with explicit `line!()` or `column!()` calls also skip header insertion.
+
+#### Rust naming
+
+| Option | Rust declarations checked |
+| --- | --- |
+| `functions` | Named functions and method signatures |
+| `variables` | Pattern bindings, including function parameters, and named const and static items |
+| `classes` | Structs, enums, unions, and traits |
+
+All checks are disabled by default. With a check enabled, names are matched
+against that convention's ASCII letters, digits, and underscore pattern.
+A Rust raw identifier prefix `r#` is ignored for matching. Diagnostics
+never change the identifier.
+
+### JSON and JSONC
+
+C4D validates files before applying whitespace edits. JSON uses strict JSON
+syntax. JSONC also accepts line comments, block comments, and trailing commas.
+The extension selects the syntax. A `.json` file containing comments reports
+a syntax error.
+
+- `indentSize` sets the leading spaces per open object or array. A line that
+  starts with a closing delimiter uses the enclosing level.
+- `newLineSize` applies between siblings on separate lines when either value
+  is an object or array. A gap containing a comment is left intact.
+- Strings, number spellings, duplicate keys, key order, and comment contents
+  keep their original bytes. The JSON adapters skip file path headers and
+  naming checks.
+
+### Python
+
+Python formatting requires CPython 3.11 or newer as `python3` on PATH.
+C4D uses it to parse and tokenize source without executing it. The installed
+Python version determines which syntax is supported. The adapter accepts
+UTF-8 source with LF or CRLF line endings.
+
+- `indentSize` sets spaces per indentation level on logical statement lines.
+  Continuation lines, comments, and multiline string contents keep their
+  original spacing.
+- `newLineSize` sets the spacing between statements in the same suite when
+  either is a compound statement such as a definition, loop, or conditional.
+  Gaps containing comments keep their existing spacing.
+- `filePathHeader` adds a `# path/to/file.py` comment after any shebang and
+  encoding declaration.
+- Naming checks cover function and class definitions, parameters, and simple
+  name bindings. Checks report diagnostics without renaming anything.
+
+Before writing, C4D reparses the proposed result and compares the two syntax
+trees. Formatting can still shift source line numbers used by tracebacks or
+inspection tools.
+
+### Go
+
+Go formatting requires Go 1.21 or newer as `go` on PATH. C4D starts one
+helper per invocation using Go's standard parser and scanner. The helper
+builds locally with the installed toolchain and uses its normal build cache.
+C4D parses the source without building or executing the Go files you pass in.
+
+- `indentSize` sets spaces per open brace, bracket, or parenthesis. Lines
+  beginning with a closing delimiter use the enclosing level.
+- `newLineSize` applies between sibling declarations or statements on
+  different lines when one is a logical block. These include functions,
+  type declarations, grouped declarations, loops, conditionals, switches,
+  selects, and standalone blocks. Gaps with comments keep their spacing.
+- `filePathHeader` inserts a standalone `// path/to/file.go` comment above
+  the source. Files with Go line directives keep their position and spacing.
+- Naming checks cover functions and methods, named types, named parameters
+  and results, const and var declarations, and names on the left of `:=`.
+
+Before writing, C4D reparses the result and compares token kinds and spellings,
+including implicit semicolons. Literals and existing comments keep their
+bytes. Syntax checking uses Go's parser and skips package type checking.
+
+### TypeScript and JavaScript
+
+Install the trusted `typescript@6` package where Node can resolve it, or
+set `C4D_TYPESCRIPT` to the absolute path to its `lib/typescript.js`. For
+example, with the package installed in the current project:
+
+```sh
+C4D_TYPESCRIPT="$PWD/node_modules/typescript/lib/typescript.js" c4d check .
+```
+
+The identifiers are `typescript` and `javascript`. Both adapters support
+indentation, spacing between logical statement blocks, path headers, and
+naming diagnostics for functions, methods, classes, variables, and parameters.
+The adapter reparses edits and compares syntax tree structure and token text
+to protect template contents and automatic semicolon insertion. It parses
+source without running it or type-checking it. JSX and TSX are outside this
+initial adapter.
+
+### Lua
+
+The `lua` adapter uses `luac -p` to validate source without executing it.
+The installed compiler determines the Lua version accepted. C4D adjusts
+indentation around block keywords and delimiters and can insert a
+`-- path/to/file.lua` header after a shebang. It preserves existing comments,
+long strings, and line endings, and validates the result before writing.
+Lua blank-line spacing and naming diagnostics are pending.
+
+### Discovery
+
+Directories are traversed in name order. The tool skips symlinks, non-source
+files, and common dependency, cache, and build directories such as `.git`,
+`node_modules`, `target`, `vendor`, and `dist`. It also skips invalid UTF-8,
+files with NUL bytes, generated suffixes such as `.generated.rs`, and
+recognised generated markers in the leading comments. Add unusual generated
+paths to `.c4dignore`.
+
+C4D reads ancestor and nested `.gitignore` and `.c4dignore` files. It supports
+ordinary Git-style path patterns, including anchors, directory-only patterns,
+wildcards, character ranges, escaped leading markers, and negation. Global
+Git excludes and `.git/info/exclude` are outside this first release.
+
+Writes replace a changed file atomically and preserve its permission bits.
+On Unix, C4D rejects files with multiple hard links. It checks for changes to
+the source immediately before replacement. Avoid concurrent formatting and
+editing of the same file.
+
+## Contributing
+
+Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`,
+and `cargo test --locked` before submitting a change. The Python and Go integration
+tests use `python3` and `go` respectively. The ECMAScript and Lua integration
+tests run when Node can load TypeScript and `luac` is available, respectively. When adding a language,
+register its adapter in `src/language.rs` and add representative fixtures
+covering syntax-sensitive whitespace, literals, comments, and repeat runs.
+Keep transformations constrained to the spans that the adapter can verify.
+
+[MIT licence](LICENSE).
diff --git a/src/ecmascript_adapter.cjs b/src/ecmascript_adapter.cjs
new file mode 100644
index 0000000..6b158ce
--- /dev/null
+++ b/src/ecmascript_adapter.cjs
@@ -0,0 +1,207 @@
+// src/ecmascript_adapter.cjs
+
+const fs = require("node:fs");
+const ts = require(process.env.C4D_TYPESCRIPT || "typescript");
+
+const anchors = new Set([
+        ts.SyntaxKind.OpenBraceToken,
+        ts.SyntaxKind.OpenBracketToken,
+        ts.SyntaxKind.OpenParenToken,
+    ]);
+const closers = new Set([
+        ts.SyntaxKind.CloseBraceToken,
+        ts.SyntaxKind.CloseBracketToken,
+        ts.SyntaxKind.CloseParenToken,
+    ]);
+
+function logical(node) {
+    return ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)
+    || ts.isInterfaceDeclaration(node) || ts.isEnumDeclaration(node)
+    || ts.isModuleDeclaration(node) || ts.isBlock(node)
+    || ts.isIfStatement(node) || ts.isIterationStatement(node, false)
+    || ts.isSwitchStatement(node) || ts.isTryStatement(node);
+}
+
+function inspect(tree) {
+    const shape = [];
+    const tokens = [];
+
+    function walk(node) {
+        if (ts.isJSDoc(node)) return;
+
+        const children = node.getChildren(tree);
+        shape.push(node.kind);
+
+        if (children.length) {
+            for (const child of children) walk(child);
+        } else if (node.kind !== ts.SyntaxKind.EndOfFileToken) {
+            shape.push(node.getText(tree));
+            tokens.push(node);
+        }
+
+        shape.push(-1);
+    }
+
+    walk(tree);
+    return { shape: JSON.stringify(shape), tokens };
+}
+
+function analyze(request) {
+    const { source, path } = request;
+    const scriptKind = /\.[cm]?ts$/i.test(path) ? ts.ScriptKind.TS : ts.ScriptKind.JS;
+    const parse = (text) => ts.createSourceFile(path, text, ts.ScriptTarget.Latest, false, scriptKind);
+    const tree = parse(source);
+    const bytes = (position) => Buffer.byteLength(source.slice(0, position));
+
+    if (tree.parseDiagnostics.length) {
+        const error = tree.parseDiagnostics[0];
+        return {
+            error: ts.flattenDiagnosticMessageText(error.messageText, "\n"),
+            offset: bytes(error.start || 0),
+        };
+    }
+
+    const { tokens, shape } = inspect(tree);
+    const edits = [];
+    const names = [];
+    const starts = tree.getLineStarts();
+    const line = (offset) => tree.getLineAndCharacterOfPosition(offset).line;
+    const bom = source.startsWith("\uFEFF") ? 1 : 0;
+    const edit = (start, end, replacement, key, message) => {
+        edits.push({ start, end, replacement, rule: `formatting.${key}`, message });
+    };
+
+    if (request.indent) {
+        let depth = 0;
+        let previous = -1;
+
+        for (const token of tokens) {
+            const start = token.getStart(tree);
+            const row = line(start);
+
+            if (closers.has(token.kind)) depth = Math.max(0, depth - 1);
+
+            if (row !== previous) {
+                const prefixStart = Math.max(bom, starts[row]);
+                const prefix = source.slice(prefixStart, start);
+                const width = depth * request.indent;
+                const wanted = " ".repeat(width);
+
+                if (prefix !== wanted && /^[ \t]*$/.test(prefix)) {
+                    edit(prefixStart, start, wanted, "indentSize", `Expected ${width} space(s) of indentation`);
+                }
+            }
+
+            previous = row;
+
+            if (anchors.has(token.kind)) depth++;
+        }
+    }
+
+    function checkName(name, group) {
+        if (!name) return;
+
+        if (ts.isIdentifier(name)) {
+            names.push([name.getStart(tree), group, name.text]);
+        } else if (ts.isBindingPattern(name)) {
+            for (const element of name.elements) {
+                if (ts.isBindingElement(element)) checkName(element.name, group);
+            }
+        }
+    }
+
+    function visit(node) {
+        if (request.names) {
+            if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) {
+                checkName(node.name, "functions");
+            } else if (ts.isClassLike(node)) {
+                checkName(node.name, "classes");
+            } else if (ts.isVariableDeclaration(node) || ts.isParameter(node)) {
+                checkName(node.name, "variables");
+            }
+        }
+
+        if (request.newlines && (ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node)
+                || ts.isCaseClause(node) || ts.isDefaultClause(node))) {
+            for (let index = 1; index < node.statements.length; index++) {
+                const left = node.statements[index - 1];
+                const right = node.statements[index];
+
+                if (!logical(left) && !logical(right)) continue;
+
+                const end = starts[line(right.getStart(tree))];
+                const gap = source.slice(left.end, end);
+
+                if (!/^[ \t\r\n]+$/.test(gap)) continue;
+
+                const breaks = gap.match(/\r\n|\r|\n/g);
+
+                if (breaks && breaks.length !== request.newlines) {
+                    edit(left.end, end, breaks[0].repeat(request.newlines), "newLineSize",
+                        `Expected ${request.newlines} newline character(s) between logical blocks`);
+                }
+            }
+        }
+
+        ts.forEachChild(node, visit);
+    }
+
+    visit(tree);
+
+    if (request.header) {
+        const comment = "// " + path;
+        const firstBreak = source.match(/\r\n|\r|\n/);
+        const shebang = source.startsWith("#!", bom);
+        const position = shebang ? (firstBreak ? firstBreak.index + firstBreak[0].length : source.length) : bom;
+        const leading = source.slice(position).match(/^(?:\s|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)*/)[0];
+
+        if (!leading.split(/\r\n|\r|\n/).some((line) => line.trim() === comment)) {
+            const ending = firstBreak?.[0] || "\n";
+            edit(position, position, (shebang && !firstBreak ? ending : "") + comment + ending,
+                "filePathHeader", `Expected file path header ${comment}`);
+        }
+    }
+
+    edits.sort((left, right) => left.start - right.start || left.end - right.end
+        || Number(right.rule.endsWith("Header")) - Number(left.rule.endsWith("Header")));
+    let cursor = 0;
+    const chunks = [];
+
+    for (const change of edits) {
+        if (change.start < cursor) return { error: "Formatting produced overlapping edits" };
+
+        chunks.push(source.slice(cursor, change.start), change.replacement);
+        cursor = change.end;
+    }
+
+    chunks.push(source.slice(cursor));
+    const formatted = chunks.join("");
+
+    if (edits.length) {
+        const proposed = parse(formatted);
+
+        if (proposed.parseDiagnostics.length || inspect(proposed).shape !== shape) {
+            return { error: "Formatting would change the JavaScript or TypeScript syntax tree" };
+        }
+    }
+
+    const positions = [...new Set([...edits.map((entry) => entry.start), ...names.map(([start]) => start)])]
+    .sort((left, right) => left - right);
+    const offsets = new Map();
+    let previous = 0;
+    let offset = 0;
+
+    for (const position of positions) {
+        offset += Buffer.byteLength(source.slice(previous, position));
+        offsets.set(position, offset);
+        previous = position;
+    }
+
+    return {
+        formatted,
+        issues: edits.map(({ start, rule, message }) => ({ offset: offsets.get(start), rule, message })),
+        names: names.map(([start, group, name]) => [offsets.get(start), group, name]),
+    };
+}
+
+process.stdout.write(JSON.stringify(analyze(JSON.parse(fs.readFileSync(0, "utf8")))));
diff --git a/src/ecmascript_source.rs b/src/ecmascript_source.rs
new file mode 100644
index 0000000..14c5198
--- /dev/null
+++ b/src/ecmascript_source.rs
@@ -0,0 +1,40 @@
+// src/ecmascript_source.rs
+
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+use crate::adapter_protocol::{decode, request, runtime};
+use crate::config::Effective;
+use crate::language::{Analysis, Diagnostic};
+
+const ADAPTER: &str = include_str!("ecmascript_adapter.cjs");
+
+pub fn analyze<'source>(
+    source: &'source str,
+    path: &str,
+    settings: &Effective,
+    naming: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+    let mut child = Command::new("node")
+    .args(["-e", ADAPTER])
+    .env_remove("NODE_OPTIONS")
+    .stdin(Stdio::piped())
+    .stdout(Stdio::piped())
+    .stderr(Stdio::piped())
+    .spawn()
+    .map_err(|error| runtime(format!("JavaScript and TypeScript support needs Node.js: {error}")))?;
+
+    let write = child.stdin.take().expect("piped Node input")
+    .write_all(request(source, path, settings, naming).to_string().as_bytes());
+    let result = child.wait_with_output().map_err(|error| runtime(error.to_string()))?;
+
+    if !result.status.success() {
+        let stderr = String::from_utf8_lossy(&result.stderr);
+        let message = stderr.lines().find(|line| line.starts_with("Error:")).unwrap_or(stderr.trim());
+        return Err(runtime(format!("JavaScript/TypeScript parser failed. Set C4D_TYPESCRIPT to an absolute path to TypeScript 6's typescript.js. {message}")));
+    }
+
+    write.map_err(|error| runtime(error.to_string()))?;
+    let response = serde_json::from_slice(&result.stdout).map_err(|error| runtime(error.to_string()))?;
+    decode(source, settings, &response)
+}
diff --git a/src/language.rs b/src/language.rs
index 3dd1e17..d211f97 100644
--- a/src/language.rs
+++ b/src/language.rs
@@ -59,6 +59,24 @@ pub static LANGUAGES: &[Language] = &[
         generated_header: crate::rust_source::generated_header,
         analyze: crate::go_source::analyze,
     },
+    Language {
+        id: "typescript",
+        extensions: &["ts", "mts", "cts"],
+        generated_header: crate::rust_source::generated_header,
+        analyze: crate::ecmascript_source::analyze,
+    },
+    Language {
+        id: "javascript",
+        extensions: &["js", "mjs", "cjs"],
+        generated_header: crate::rust_source::generated_header,
+        analyze: crate::ecmascript_source::analyze,
+    },
+    Language {
+        id: "lua",
+        extensions: &["lua"],
+        generated_header: crate::lua_source::generated_header,
+        analyze: crate::lua_source::analyze,
+    },
 ];
 
 pub fn detect(path: &Path) -> Option<&'static Language> {
diff --git a/src/lua_source.rs b/src/lua_source.rs
new file mode 100644
index 0000000..9fb44c6
--- /dev/null
+++ b/src/lua_source.rs
@@ -0,0 +1,205 @@
+// src/lua_source.rs
+
+use std::borrow::Cow;
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+use crate::adapter_protocol::runtime;
+use crate::config::Effective;
+use crate::language::{Analysis, Diagnostic};
+
+fn validate(source: &str) -> Result<(), Diagnostic> {
+    let mut child = Command::new("luac")
+        .args(["-p", "-"])
+        .stdin(Stdio::piped())
+        .stdout(Stdio::null())
+        .stderr(Stdio::piped())
+        .spawn()
+        .map_err(|error| runtime(format!("Lua support needs luac on PATH: {error}")))?;
+    let write = child.stdin.take().expect("piped Lua input").write_all(source.as_bytes());
+    let output = child.wait_with_output().map_err(|error| runtime(error.to_string()))?;
+    if !output.status.success() {
+        let message = String::from_utf8_lossy(&output.stderr);
+        let (offset, message) = message.split_once("stdin:").and_then(|(_, tail)| {
+            let (line, text) = tail.split_once(':')?;
+            let previous = line.trim().parse::<usize>().ok()?.saturating_sub(1);
+            let offset = source.split_inclusive('\n').take(previous).map(str::len).sum();
+            Some((offset, text.trim()))
+        }).unwrap_or((0, message.trim()));
+        return Err(Diagnostic {
+            offset,
+            rule: "syntax",
+            message: message.to_owned(),
+        });
+    }
+    write.map_err(|error| runtime(error.to_string()))
+}
+
+fn long_end(source: &str) -> Option<usize> {
+    let rest = source.strip_prefix('[')?;
+    let equals = rest.bytes().take_while(|&byte| byte == b'=').count();
+    let body = rest.get(equals..)?.strip_prefix('[')?;
+    let closer = format!("]{}]", "=".repeat(equals));
+    Some(body.find(&closer).map_or(source.len(), |end| equals + 2 + end + closer.len()))
+}
+
+fn short_end(source: &str, quote: u8) -> usize {
+    let bytes = source.as_bytes();
+    let mut cursor = 1;
+    while cursor < bytes.len() {
+        match bytes[cursor] {
+            byte if byte == quote => return cursor + 1,
+            b'\\' => cursor += 2,
+            _ => cursor += 1,
+        }
+    }
+    bytes.len()
+}
+
+fn word(byte: u8) -> bool {
+    byte.is_ascii_alphanumeric() || byte == b'_'
+}
+
+fn header_offset(source: &str) -> usize {
+    let bom = usize::from(source.starts_with('\u{feff}')) * '\u{feff}'.len_utf8();
+    if source[bom..].starts_with('#') {
+        source[bom..].find('\n').map_or(source.len(), |offset| bom + offset + 1)
+    } else {
+        bom
+    }
+}
+
+pub fn generated_header(source: &str, path: &str) -> bool {
+    let expected = format!("-- {path}");
+    source[header_offset(source)..].lines().map(str::trim)
+        .take_while(|line| line.is_empty() || line.starts_with("--"))
+        .filter(|line| *line != expected)
+        .any(|line| {
+            let lower = line.to_ascii_lowercase();
+            ["@generated", "auto-generated", "automatically generated", "do not edit"]
+                .iter().any(|marker| lower.contains(marker))
+        })
+}
+
+pub fn analyze<'source>(
+    source: &'source str,
+    path: &str,
+    settings: &Effective,
+    _: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+    validate(source)?;
+    let code_start = header_offset(source);
+    let mut edits = Vec::new();
+    let mut issues = Vec::new();
+
+    if settings.file_path_header() {
+        let comment = format!("-- {path}");
+        let present = source[code_start..].lines().map(str::trim)
+            .take_while(|line| line.is_empty() || line.starts_with("--"))
+            .any(|line| line == comment);
+        if !present {
+            let ending = if source.split_once('\n').is_some_and(|(line, _)| line.ends_with('\r')) {
+                "\r\n"
+            } else {
+                "\n"
+            };
+            let separator = if code_start == source.len() && source.starts_with('#') && !source.ends_with('\n') {
+                ending
+            } else {
+                ""
+            };
+            edits.push((code_start, code_start, format!("{separator}{comment}{ending}")));
+            issues.push(Diagnostic {
+                offset: code_start,
+                rule: "formatting.filePathHeader",
+                message: format!("Expected file path header {comment}"),
+            });
+        }
+    }
+
+    let width = settings.indent_size();
+    let mut depth = 0usize;
+    let mut cursor = code_start;
+    let mut line_start = code_start;
+    let mut first = true;
+    let bytes = source.as_bytes();
+    while width != 0 && cursor < bytes.len() {
+        let start = cursor;
+        let remaining = &source[start..];
+        if matches!(bytes[start], b'\n' | b'\r') {
+            cursor += 1;
+            line_start = cursor;
+            first = true;
+            continue;
+        }
+        if bytes[start].is_ascii_whitespace() {
+            cursor += 1;
+            continue;
+        }
+        if let Some(rest) = remaining.strip_prefix("--") {
+            cursor += 2 + long_end(rest).unwrap_or_else(|| rest.find(['\r', '\n']).unwrap_or(rest.len()));
+            first = false;
+            continue;
+        }
+
+        let (length, closes, opens) = match bytes[start] {
+            quote @ (b'\'' | b'"') => (short_end(remaining, quote), false, false),
+            b'[' => long_end(remaining).map_or((1, false, true), |end| (end, false, false)),
+            b'{' | b'(' => (1, false, true),
+            b'}' | b')' | b']' => (1, true, false),
+            byte if word(byte) => {
+                let length = remaining.bytes().take_while(|byte| word(*byte)).count();
+                let token = &remaining[..length];
+                (
+                    length,
+                    matches!(token, "end" | "until" | "else" | "elseif"),
+                    matches!(token, "then" | "do" | "function" | "repeat" | "else"),
+                )
+            }
+            _ => (remaining.chars().next().expect("remaining Lua text").len_utf8(), false, false),
+        };
+        if closes {
+            depth = depth.saturating_sub(1);
+        }
+        if first {
+            let prefix = &source[line_start..start];
+            let wanted = depth * width;
+            if prefix.bytes().all(|byte| matches!(byte, b' ' | b'\t'))
+                && (prefix.len() != wanted || prefix.contains('\t'))
+            {
+                edits.push((line_start, start, " ".repeat(wanted)));
+                issues.push(Diagnostic {
+                    offset: line_start,
+                    rule: "formatting.indentSize",
+                    message: format!("Expected {wanted} space(s) of indentation"),
+                });
+            }
+        }
+        first = false;
+        if opens {
+            depth += 1;
+        }
+        cursor += length;
+    }
+
+    if edits.is_empty() {
+        return Ok(Analysis {
+            formatted: Cow::Borrowed(source),
+            issues,
+        });
+    }
+
+    let mut formatted = String::with_capacity(source.len());
+    let mut previous = 0;
+    for (start, end, replacement) in edits {
+        formatted.push_str(&source[previous..start]);
+        formatted.push_str(&replacement);
+        previous = end;
+    }
+    formatted.push_str(&source[previous..]);
+    validate(&formatted)?;
+    Ok(Analysis {
+        formatted: Cow::Owned(formatted),
+        issues,
+    })
+}
diff --git a/src/main.rs b/src/main.rs
index 77c294a..c2a4c5c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,12 +6,16 @@ mod config;
 
 mod discovery;
 
+mod ecmascript_source;
+
 mod go_source;
 
 mod json_source;
 
 mod language;
 
+mod lua_source;
+
 mod python_source;
 
 mod rust_source;
diff --git a/tests/cli.rs b/tests/cli.rs
index 7c22053..e726d25 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -330,8 +330,8 @@ fn discovery_obeys_ignore_rules_and_skips_non_sources() {
         "target/module.rs",
         "node_modules/module.rs",
         "file.generated.rs",
-        "code.ts",
-        "code.lua",
+        "code.rb",
+        "code.java",
         ".git/hidden.rs",
         "../external/outside.rs",
     ];
@@ -386,7 +386,7 @@ fn discovery_obeys_ignore_rules_and_skips_non_sources() {
         &[
             "format",
             "ignored/special.rs",
-            "code.ts",
+            "code.rb",
             "target/module.rs",
         ],
         0,
@@ -500,8 +500,8 @@ fn explicit_false_overrides_inherited_headers_and_existing_comments_remain() {
 fn unsupported_language_fixtures_are_preserved_byte_for_byte() {
     let workspace = Workspace::new();
     let examples: &[(&str, &[u8])] = &[
-        ("example.ts", include_bytes!("fixtures/example.ts")),
-        ("example.js", include_bytes!("fixtures/example.js")),
+        ("example.rb", b"puts 1\n"),
+        ("example.java", b"class Example {}\n"),
     ];
 
     workspace.write(
@@ -769,3 +769,96 @@ fn go_preserves_line_directives_and_refuses_invalid_syntax() {
     assert!(String::from_utf8_lossy(&result.stdout).contains(" syntax"));
     assert_eq!(workspace.read("broken.go"), invalid);
 }
+
+#[test]
+fn ecmascript_adapters_preserve_asi_and_template_literals() {
+    let parser = Command::new("node")
+    .args(["-e", "require(process.env.C4D_TYPESCRIPT || 'typescript')"])
+    .output();
+
+    if !parser.is_ok_and(|output| output.status.success()) {
+        return;
+    }
+
+    let workspace = Workspace::new();
+    workspace.write(
+        ".c4d/config.jp",
+        "[formatting]\nfilePathHeader: true\n[overrides.typescript.cases]\nfunctions: camelCase\n",
+    );
+    let js = concat!(
+        "#!/usr/bin/env node\n",
+        "function buildMessage() {\n",
+        " const template = `first\n  keep spaces \u{e9}\nlast`\n",
+        " return\n",
+        " template\n",
+        "}\n",
+        "console.log(buildMessage())\n",
+    );
+    workspace.write("message.mjs", js);
+    let ts = "function Bad_Name(value: number) {\n return value;\n}\nclass Example {}\n";
+    workspace.write("example.mts", ts);
+    let diagnostics = workspace.cli(&["check", "."], 1);
+    assert!(String::from_utf8_lossy(&diagnostics.stdout).contains("example.mts:1:10 cases.functions"));
+
+    let run_js = || {
+        let output = Command::new("node")
+        .arg(workspace.project.join("message.mjs"))
+        .output()
+        .unwrap();
+        assert!(output.status.success());
+        output.stdout
+    };
+    let before = run_js();
+    workspace.cli(&["format", "."], 0);
+    let formatted = workspace.read("message.mjs");
+    assert!(formatted.starts_with("#!/usr/bin/env node\n// message.mjs\n"));
+    assert!(formatted.contains("`first\n  keep spaces \u{e9}\nlast`"));
+    assert!(formatted.contains("    return\n    template"));
+    assert_eq!(run_js(), before);
+    assert!(workspace.read("example.mts").contains("    return value;\n}\n\nclass"));
+    workspace.cli(&["format", "--check", "."], 0);
+
+    let invalid = "const invalid = ;\n";
+    workspace.write("invalid.ts", invalid);
+    workspace.cli(&["format", "invalid.ts"], 2);
+    assert_eq!(workspace.read("invalid.ts"), invalid);
+}
+
+#[test]
+fn lua_indentation_preserves_long_literals_comments_and_shebang() {
+    if !Command::new("luac").arg("-v").output().is_ok_and(|output| output.status.success()) {
+        return;
+    }
+
+    let workspace = Workspace::new();
+    workspace.write(
+        ".c4d/config.jp",
+        "[formatting]\nfilePathHeader: true\n[overrides.lua.formatting]\nindentSize: 2\n",
+    );
+    let source = concat!(
+        "#!/usr/bin/env lua\r\n",
+        "local function message(ready)\r\n",
+        " if ready then\r\n",
+        "  --[=[ a comment\r\n  end ]=]\r\n",
+        "  return [=[first\r\n  keep these spaces\r\nlast]=]\r\n",
+        " elseif not ready then\r\n",
+        "  return 'waiting'\r\n",
+        " end\r\n",
+        "end\r\n",
+    );
+    workspace.write("example.LUA", source);
+    workspace.cli(&["format", "--check", "."], 1);
+    workspace.cli(&["format", "."], 0);
+    let formatted = workspace.read("example.LUA");
+    assert!(formatted.starts_with("#!/usr/bin/env lua\r\n-- example.LUA\r\n"));
+    assert!(formatted.contains("  if ready then\r\n  --[=[ a comment\r\n  end ]=]"));
+    assert!(formatted.contains("    return [=[first\r\n  keep these spaces\r\nlast]=]"));
+    assert!(formatted.contains("  elseif not ready then\r\n    return 'waiting'\r\n  end"));
+    assert!(!formatted.replace("\r\n", "").contains('\n'));
+    workspace.cli(&["format", "--check", "."], 0);
+
+    let invalid = "local function incomplete()\n";
+    workspace.write("broken.lua", invalid);
+    workspace.cli(&["format", "broken.lua"], 2);
+    assert_eq!(workspace.read("broken.lua"), invalid);
+}
diff --git a/tests/fixtures/example.js b/tests/fixtures/example.js
index 2378341..e422ea1 100644
--- a/tests/fixtures/example.js
+++ b/tests/fixtures/example.js
@@ -1,5 +1,6 @@
+// tests/fixtures/example.js
 /* tests/fixtures/example.js */
 
 export function describeStatus(ready) {
-  return `Status: ${ready ? "ready" : "waiting"}`;
+    return `Status: ${ready ? "ready" : "waiting"}`;
 }
diff --git a/tests/fixtures/example.ts b/tests/fixtures/example.ts
index 57fe12a..26afd00 100644
--- a/tests/fixtures/example.ts
+++ b/tests/fixtures/example.ts
@@ -1,7 +1,9 @@
+// tests/fixtures/example.ts
 /* tests/fixtures/example.ts */
 
 export type Status = "ready" | "waiting";
 
+
 export function describeStatus(ready: boolean): Status {
-  return ready ? "ready" : "waiting";
+    return ready ? "ready" : "waiting";
 }