Skip to content

feat: add trailing_comment_spacing option to preserve comment alignment#1129

Open
sobh wants to merge 1 commit into
JohnnyMorganz:mainfrom
sobh:feat/preserve-trailing-comment-spacing
Open

feat: add trailing_comment_spacing option to preserve comment alignment#1129
sobh wants to merge 1 commit into
JohnnyMorganz:mainfrom
sobh:feat/preserve-trailing-comment-spacing

Conversation

@sobh

@sobh sobh commented Jun 20, 2026

Copy link
Copy Markdown

Disclaimer: This PR was authored with AI assistance.

Summary

Adds a new trailing_comment_spacing configuration option that controls whether the formatter compresses whitespace before trailing inline comments to a single space, or preserves the original spacing.

This is useful for codebases that align trailing comments for readability:

-- Before (with Compress, the default/existing behavior):
local x = 1 -- x value
local y = 2 -- y value
local longname = 3 -- long name

-- After (with Preserve):
local x = 1        -- x value
local y = 2        -- y value
local longname = 3 -- long name

Configuration

Possible values:

  • Compress: (default) — matches StyLua's original behavior of replacing all whitespace before a trailing comment with a single space.
  • Preserve: keeps the original spacing as written in the source.

stylua.toml:

trailing_comment_spacing = "Preserve"

CLI:

stylua --trailing-comment-spacing Preserve src/

EditorConfig:

[*.lua]
stylua_trailing_comment_spacing = preserve

Changes

  • Add TrailingCommentSpacing enum to stylua_lib
  • Modify format_token and load_token_trivia in src/formatters/general.rs to preserve original whitespace before trailing comments when configured
  • Wire up CLI flag (--trailing-comment-spacing)
  • Wire up EditorConfig property (stylua_trailing_comment_spacing)
  • Document the option in the README options table
  • Document all EditorConfig property mappings in the README
  • Add snapshot tests

Testing

  • All existing tests pass (185 total)
  • Added 2 new snapshot tests covering aligned comments and varying spacing
  • Manually verified with both CLI flag and stylua.toml configuration

…ment

Add a new configuration option `trailing_comment_spacing` that controls
how whitespace before trailing inline comments is handled:

- `Compress` (default): always use a single space before comments
- `Preserve`: keep the original spacing before comments

This allows users to maintain aligned comments without the formatter
collapsing the spacing.

Configurable via stylua.toml, CLI flag, and EditorConfig.
Also document all supported EditorConfig property mappings in the README.
@sobh sobh force-pushed the feat/preserve-trailing-comment-spacing branch from 3b7f239 to 57e31a1 Compare June 20, 2026 14:48
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