Skip to content

Fix #127: Format keeps the cursor, Format Selection changes only the selection - #146

Merged
albilu merged 4 commits into
albilu:masterfrom
swlim9999:pr/127-format-selection
Nov 14, 2026
Merged

albilu merged 4 commits into
albilu:masterfrom
swlim9999:pr/127-format-selection

Conversation

@swlim9999

Copy link
Copy Markdown
Contributor

Fixes #127. First of the per-issue PRs discussed in #145.

What changes (one file, PythonReformatTask.java):

  • Format Selection uses range formatting whenever the selection isn't the whole document (before, only when it didn't start at offset 0).
  • A selection ending at column 0 of a line no longer pulls that line in; edits outside the selected lines are dropped.
  • Server edits are applied as the minimal changed text, so unchanged code keeps its position, and the cursor/selection stay on their lines instead of jumping to the end of the file.
  • LSP positions past the end of a line or the document are clamped (the old code could remove text up to a wrong limit).
  • Small: the log messages used String.format with {0}, and the interrupt flag is now restored.

How to test

  1. Open a Python file with badly formatted code in several places, e.g. x=1 on line 3 and y=2 on line 10.
  2. Put the cursor in the middle of the file, run Source → Format (Alt+Shift+F): the code is formatted and the cursor stays on its line.
  3. Select only lines 2–4 and run Format again on a fresh copy: only x = 1 changes, line 10 stays y=2.
  4. Select lines ending at the start of the next line (triple-click/drag to column 0): that next line isn't changed.

Built with RELEASE310 and RELEASE290; tested by hand in NetBeans 30/31 on Linux. I also have unit tests for this in my branch, but since the repo has no test setup they aren't included. I can send them as a separate PR if you want a test suite.

Written with AI assistance (Claude Opus), reviewed and tested by me.

🤖 Generated with Claude Code

…y the selection

- Range formatting is used whenever the context is not the whole document
  (previously only when it did not start at offset 0).
- The range sent to the server ends before a line the selection only
  touches at column 0; edits are limited to the selected whole lines.
- Server edits are applied as the minimal changed text (common prefix and
  suffix are kept), so unchanged code keeps its positions, and the caret
  and selection stay on their lines instead of jumping to the end.
- LSP positions past a line or the document are clamped instead of
  removing text up to an incorrect limit.
- Fixed the log messages (String.format with "{0}") and restore the
  interrupt flag when interrupted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution and helping move this project forward

@albilu albilu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution. The ordinary single-caret Black case now keeps the cursor on its original line, and the tested Black/autopep8 selection-boundary and EOF cases behave correctly.

Requesting changes before merging because two reproduced issues remain in the new code:

  1. P1 — YAPF Format Selection can delete selected code. The per-edit selection filter can accept a deletion while rejecting the corresponding insertion. Please handle related edits together so selection filtering cannot apply only half of a replacement.
  2. P2 — Caret restoration drops additional carets. Calling EditorCaret.setDot() to restore the last caret removes the other carets. Please preserve all caret/selection entries through the NetBeans multicaret APIs.

The inline comments include reproductions and expected behavior. Since you mentioned having tests in your branch, please include focused regression tests for these two cases in this PR, with the minimal test setup needed to run them. The tests should assert that selected statements are preserved and correctly formatted, unselected code remains unchanged, and multiple carets/selections survive formatting. Please also retain coverage for the original single-caret cursor-jump fix.

Validation: JDK 21 / RELEASE310 compilation passed. A temporary harness exercised 27 formatter-response cases using actual Black, autopep8 and YAPF output, plus NetBeans BaseDocument/EditorCaret checks under a virtual display on both the UI and background threads. The relevant behavior was compared with base commit b5201d4. This was harness validation; a full interactive IDE session was not performed.

Reviewed head: 0ac67dfd522dd1eff9ff6f1aa98b6f4aefa4fc80.

…lbilu#146)

- Formatter edits are applied to a copy of the text as LSP specifies
  (ranges refer to the original text, inserts at one position keep their
  order), and the result is compared with the original. Changed lines are
  split only where the code before the split is the same in both
  versions, and each part is applied or rejected as a whole. YAPF's
  separate deletions and insertions can no longer delete selected code,
  and whole-document YAPF formatting no longer reorders or drops lines.
- If a rejected part re-indents code, no part does, so a block is never
  left half re-indented.
- All carets are read with EditorCaret.getCarets() and restored with
  replaceCarets(), each at the same code as before (setDot() kept only
  the last caret, and EditorCaret merges carets that meet in replaced
  text).
- Regression tests built from real yapf, autopep8 and Black responses;
  JUnit test dependency and a headless surefire setting in the pom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@swlim9999

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Both points are fixed in cde1b6a, and the PR now includes tests:

  • Test setup (pom.xml): JUnit 4.13.2 with test scope, and java.awt.headless=true for surefire. mvn -B clean install -P dev as in builds.yml runs them, and they pass for RELEASE290 and RELEASE310, also without a display.
  • PythonReformatTaskTest: 13 tests built from real responses of python-lsp-server 1.15.0 with yapf 0.43.0, autopep8 2.0.4 and python-lsp-black 2.0.0. 10 of them fail on the previous head.

Also found while testing: with YAPF, whole-document Format reorders or drops lines, on master too. x=1\ny=2\n becomes empty, and # header\nx=1+2\nz = 3\n becomes # header\nz = 3\nx = 1 + 2\n, because the edits were applied one by one to the changing document. Applying them to the original text fixes this (insertsAtTheSamePositionKeepTheirOrder).

Other validation: a harness applied 648 real formatter responses (9 sample files × yapf, autopep8 and Black × the whole document and every line range). Whole-document results matched the formatter output, unselected lines never changed, results compiled whenever the input and the formatter output did, and 2,187 caret positions stayed at the same code. Caret restoration was also checked while holding the document lock, on the UI thread and on a background thread. I haven't done an interactive IDE session.

One test detail: EditorCaret updates the system selection and only catches SecurityException there, while the headless toolkit throws HeadlessException. The test editor's getToolkit() therefore throws a SecurityException.

@albilu albilu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the findings and adding the regression tests. Rechecked cde1b6a: both original reproductions now pass. YAPF selection formatting preserves the selected statement and surrounding code, and the original multicaret case retains both caret positions.

All 13 tests pass with JDK 21 on both RELEASE290 and RELEASE310. Independent harness checks also covered 363 real formatter responses (39 whole-document responses and 324 selection responses).

Keeping changes requested for one newly reproduced P2 issue in FormatterEdits.map(), detailed inline: Black can remove parentheses, and counting non-whitespace characters then maps a cursor in unchanged code to the end of a later line. The previous PR revision keeps the cursor correctly in this case, so this is a regression in the follow-up commit.

Please update the mapping to account for inserted/removed non-whitespace characters and add a regression test for the supplied Black example, including the background-thread path. Validation used actual NetBeans document/caret classes under a virtual display; no full interactive IDE session was performed.

…u#146)

Black removes optional parentheses, so counting non-whitespace characters
moved a cursor in unchanged code to a later line. Inside a change, the
code tokens of both versions are now aligned (Myers diff), and a caret
stays before the same token, or after the last kept token before it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@swlim9999

Copy link
Copy Markdown
Contributor Author

Thanks for the recheck. The P2 is fixed in 6b3978b (details inline), with three regression tests for your Black example, including the background-thread path. The 16 tests pass with JDK 21 on RELEASE290 and RELEASE310, also without a display.

Harness: I added three parenthesis-heavy sources to the formatter harness: your example, if (a): / return (((a))) / for (i) in (range(3)):, and quote changes. That makes 840 real responses from black 26.10.1, python-lsp-black 2.0.0, yapf 0.43.0 and autopep8 via python-lsp-server 1.15.0. Every caret offset of each whole-document response was mapped (2,919 positions):

  • Caret order was never reversed.
  • 1,962 carets before code that a token diff shows as kept stayed before that code.
  • 888 carets in whitespace stayed between the same kept code.

The only disagreements with the harness's own difflib alignment are cases with more than one valid alignment: which of two ) in (range(3)) was removed, and ' changed to ". In these the caret stays at the replaced quote. Whole-document results still match the formatter output, and selection results leave the unselected lines unchanged. I haven't done an interactive IDE session.

Distinguish incomplete token alignment from deleted tokens and fall back to a clamped line and column within the replacement. Cover large Black quote normalization, multiple carets and selections, background formatting, and shortened lines.

@albilu albilu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing the review findings and adding the regression coverage. I verified the YAPF selection fix, preservation of multiple carets/selections, and the Black parenthesis-removal fix.

I added a small follow-up commit, 108378f, for one remaining edge case found during verification: Black's quote normalization in a 600-item list exceeds the bounded token-alignment limit. The incomplete alignment was being treated as deleted code, moving the cursor from offset 4705 to 15 and collapsing multiple carets.

The follow-up distinguishes an incomplete alignment from deleted tokens and falls back to the same line and column within the replacement, clamping to the available text. Exact token mapping remains in use when alignment completes. Three regression tests cover multiple carets/selections on both the UI and background threads, plus clamping on a shortened line.

Validation: all 19 tests pass with JDK 21 on both RELEASE290 and RELEASE310. The independent harness also passes 39 whole-document and 324 selection cases from real formatter responses. NetBeans document/caret checks under a virtual display confirm that the 600-item case now keeps offset 4705 on both execution paths. This was automated editor validation, not a full interactive IDE session.

The requested code changes are resolved, and I found no remaining code blocker in the reviewed head, 108378f. Approving; merge will follow once the required build and CodeQL checks pass.

@albilu
albilu merged commit ef137aa into albilu:master Nov 14, 2026
4 checks passed
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.

When you format a file, the cursor jumps to the end of the file

2 participants