Skip to content

fix: don't format a file which is excluded from formatting - #1817

Merged
angelozerr merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/formatting-exclusions
Nov 2, 2026
Merged

angelozerr merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/formatting-exclusions

Conversation

@lagergren

Copy link
Copy Markdown
Collaborator

When Reformat code runs before a commit, LSP4IJ lets a language server format a file which matches a Do not format pattern of Settings > Editor > Code Style > Formatter. In #1647 this is the application.properties of a Quarkus project, which the Quarkus Tools language server formats although *.properties is excluded.

IntelliJ checks these patterns with a LanguageFormattingRestriction, ExcludedFileFormattingRestriction, and asks the restrictions only in LanguageFormatting.forContext(), for its own formatter. The commit's ReformatCodeProcessor skips an excluded file only when the file's formatting service is the CoreFormattingService (AbstractLayoutCodeProcessor.canBeFormatted()). AbstractLSPFormattingService.canFormat() doesn't ask the restrictions, so for a file of a language server, the LSP formatting service is chosen and formats it. Reformat Code on a directory in the Project view goes through the same check. Reformat Code in the editor checks the patterns itself, with CodeStyle.isFormattingEnabled() in FileInEditorProcessor, which is why it didn't format the file when tried in the issue.

Fixes #1647.

Changes

  • AbstractLSPFormattingService.canFormat() returns false for a file which a LanguageFormattingRestriction doesn't allow to format (isFormatterAllowed), as LanguageFormatting.forContext() does for IntelliJ's own formatter. IntelliJ's formatter then takes the file and leaves it as it is. The check runs after the check that the file has a language server, so other files don't pay for it.
  • The check uses isFormatterAllowed, not isAutoFormatAllowed: IntelliJ asks LanguageFormatting.isAutoFormatAllowed() itself before it formats on save.
  • Server-side on-type formatting (textDocument/onTypeFormatting) doesn't go through the formatting service and is not changed.

Tests

New ExcludedFileFormattingTest reformats test.ts with ReformatCodeProcessor, the processor that Reformat code before a commit runs, here for one file with runWithoutProgress(). Each test sets a "Do not format" glob pattern in temporary code style settings:

  • testExcludedFileIsNotFormatted: with the pattern *.ts, the file is left as it is, and the language server gets no textDocument/formatting.
  • testFileWhichIsNotExcludedIsFormatted: with the pattern *.properties, the file is formatted, with one textDocument/formatting.

Without the canFormat() change, the first fails (the file is formatted to const a = 1;) and the second passes. With it, both pass. The formatting tests (com.redhat.devtools.lsp4ij.features.formatting.* and LanguageServerFileEnablementTest, 80 tests) pass.

Locally, the full suite passes (1,005 tests, 3 skipped) except the 7 known macOS failures ("File accessed outside allowed roots"), which fail on main too. Not checked in a running IDE.

"Reformat code" before a commit let a language server format a file
which matches a "Do not format" pattern of Settings > Editor > Code
Style > Formatter. IntelliJ checks these patterns with a
LanguageFormattingRestriction, ExcludedFileFormattingRestriction, and
asks the restrictions only in LanguageFormatting.forContext(), for its
own formatter: the commit's ReformatCodeProcessor skips an excluded file
only when the file's formatting service is the CoreFormattingService.
Reformat Code in the editor checks the patterns itself, which is why it
did not format the file.

AbstractLSPFormattingService.canFormat() now returns false for a file
which a LanguageFormattingRestriction does not allow to format, so
IntelliJ's own formatter takes the file and leaves it as it is.

ExcludedFileFormattingTest reformats a file with ReformatCodeProcessor:
an excluded file is not formatted and the language server gets no
formatting request; a file which is not excluded is formatted. Without
the fix, the first test fails.

Fixes redhat-developer#1647
@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 468b1712-dd7c-4519-84e5-f323e9a740ff
Commits

Reviewing files that changed from the base of the PR and between cec834e and 52a2d1f.

Files selected for processing: 2
  • src/main/java/com/redhat/devtools/lsp4ij/features/formatting/AbstractLSPFormattingService.java
  • src/test/java/com/redhat/devtools/lsp4ij/features/formatting/ExcludedFileFormattingTest.java

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Formatting now respects the IDE’s “Do not format” file exclusions when using a language server. Files matching an exclusion remain unchanged during reformatting, while files not excluded continue to be formatted as usual.

The formatting service now checks registered language formatting restrictions before it checks language-server formatting support. Tests cover excluded files, which remain unchanged without formatting requests, and allowed files, which receive formatting edits.

Changes: Formatting restrictions

Layer / File(s) Summary
Apply formatting restrictions
src/main/java/com/redhat/devtools/lsp4ij/features/formatting/AbstractLSPFormattingService.java
canFormat returns false when a registered LanguageFormattingRestriction disallows formatting the file.
Verify excluded-file formatting
src/test/java/com/redhat/devtools/lsp4ij/features/formatting/ExcludedFileFormattingTest.java
Tests verify that a matching exclusion pattern prevents formatting requests and edits, while a nonmatching pattern allows formatting.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to 52a2d

The change prevents LSP formatting for excluded files while retaining formatting for allowed files. No actionable merge-blocking issue remains; merge after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely states the main change: preventing formatting of files excluded by formatting rules.
Description check Passed The description directly explains the formatting issue, the implementation, affected behavior, tests, and validation results.
Linked Issues check Passed Linked issue #1647 requires that IntelliJ does not format files excluded by a "Do not format" pattern during commit, for .properties files when LSP4IJ is active. At the reviewed head, `AbstractLSPFo…
Out of Scope Changes check Passed The PR changes two files. (1) AbstractLSPFormattingService.java adds the isFormatterAllowed check in canFormat() and a private helper that reads LanguageFormattingRestriction.EP_NAME. This cha…
Full details: Linked Issues check

Explanation

Linked issue #1647 requires that IntelliJ does not format files excluded by a "Do not format" pattern during commit, for .properties files when LSP4IJ is active. At the reviewed head, AbstractLSPFormattingService.canFormat() returns false when any LanguageFormattingRestriction (via isFormatterAllowed) forbids formatting the file. The check runs after the language server availability check. This closes the path where the LSP formatting service formatted excluded files during commit-time Reformat Code. The new ExcludedFileFormattingTest covers this path with ReformatCodeProcessor: a *.ts exclusion leaves test.ts unchanged and sends no textDocument/formatting, and a non-matching *.properties pattern still formats the file with one request. Scope note: the PR description says the tests pass (1,005 tests, 3 skipped, with 7 known macOS failures) and that the change was not checked in a running IDE. I did not run the tests. The result rests on the code and test source at head. The coding requirement is met by the code evidence. No non-coding requirements apply.

Full details: Out of Scope Changes check

Explanation

The PR changes two files. (1) AbstractLSPFormattingService.java adds the isFormatterAllowed check in canFormat() and a private helper that reads LanguageFormattingRestriction.EP_NAME. This change implements the linked issue #1647 requirement directly. The PR states that textDocument/onTypeFormatting and isAutoFormatAllowed behavior are not changed. The file at head shows no other modifications in the reviewed code. (2) ExcludedFileFormattingTest.java is a new test for the same behavior. Tests support the objective and are in scope. No unrelated changes were found. I could not read the whole-PR text diff, because changed blobs were missing from the checkout. The scope assessment uses the file content at head and the PR summary, so the file list is taken from the PR summary and not from a diff read.

Full details: Docstring Coverage

Explanation

Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 2 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

@codecov

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 37.63%. Comparing base (cec834e) to head (52a2d1f).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##             main    #1817     +/-   ##
=========================================
  Coverage   37.62%   37.63%             
=========================================
  Files         786      786             
  Lines       30019    30023      +4     
  Branches     4546     6002   +1456     
=========================================
+ Hits        11296    11300      +4     
  Misses      16772    16772             
  Partials     1951     1951             

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lagergren

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@angelozerr angelozerr added bug Something isn't working formatting labels Nov 2, 2026
@angelozerr angelozerr added this to the 0.30.0 milestone Nov 2, 2026
@angelozerr angelozerr moved this to In Progress in Java Tooling Nov 2, 2026
@angelozerr
angelozerr merged commit 20cf6c6 into redhat-developer:main Nov 2, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Java Tooling Nov 2, 2026
@angelozerr

Copy link
Copy Markdown
Contributor

Thanks!

angelozerr pushed a commit that referenced this pull request Nov 4, 2026
* docs: describe the 0.30.0 LSP and DAP changes that the docs miss

Several changes merged for 0.30.0 changed behavior that the docs
describe, or added behavior that they don't. LSPSupport.md still said
that pull diagnostics don't support related documents, which #1723
changed.

LSP:
- LSPSupport.md, Pull Diagnostics: previousResultId, and the
  relatedDocuments of either kind of report (#1723, #1735), in place
  of "It doesn't support the related documents."
- LSPSupport.md, Inline Completion: the trigger kind and the selected
  completion item (#1715).
- LSPSupport.md, Signature Help: the retrigger, the active parameter
  of each signature, and signatures without parameters (#1712, #1734).
- LSPSupport.md, Formatting: a file without an open editor (#1707).
- LSPSupport.md, new Did Change Watched Files section: the directories
  outside the project that watchers name, and the watchers of a stopped
  server (#1742). The support list links to it.
- UserGuide.md, Formatting: the Do not format patterns (#1817).
- UserDefinedLanguageServer.md, Configuration tab: null properties
  (#1710, #1847) and invalid JSON (#1828).
- DeveloperGuide.md, Workspace Configuration: null members of
  createSettings() (#1710, #1847).

DAP, dap/UserGuide.md:
- Exception breakpoint: the hint built from exceptionInfo (#1761). The
  screenshot of the stop at the exception moves back after the example
  it shows; the Smart Step Into section had come between them.
- Large variables: a page with fewer children than asked for is the
  last one (#1851).

Validation: each statement was checked against the code at d1a281d:
DocumentContentSynchronizer.refreshPullDiagnostic,
LSPInlineCompletionProvider.createParams, LSPParameterInfoHandler,
ClientCapabilitiesFactory, AbstractLSPFormattingService.canFormat,
LSPFormattingSupport, FileSystemWatchRoots, LanguageServerPanel
.validateJsonFields, JsonSettingsTypeAdapterFactory,
DAPClient.getExceptionHint and DAPVariableChildren. The other changes
merged for 0.30.0 are already documented, by their own PRs, #1784 and
#1810, or change nothing that the docs describe.

Limits: docs only, no new screenshots, no build run.

* docs: say that the JSON fields of a language server are read leniently

CodeRabbit noted that "must be valid JSON" is stricter than what
LSP4IJ accepts. The dialog's check (LanguageServerPanel.jsonError,
JsonParser.parseString) and the readers at run time
(SettingsHelper.parseJson, JsonParser.parseReader for the
initialization options, experimental and installer, Gson.fromJson for
the client configuration and workspace folders) all read leniently.

The paragraph now says which JSON is accepted and which isn't.

Validation: probed Gson 2.15.0's JsonParser.parseString and
Gson.fromJson. Both accept // and /* */ and # comments, unquoted names
and single-quoted strings, and both reject a trailing comma, a missing
brace and an unescaped backslash, such as in C:\Users.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working formatting

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

In intellij, commit format can't be filtered by file type

2 participants