-
-
Notifications
You must be signed in to change notification settings - Fork 505
Use formatWithCursor() to preserve cursor position #3945
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ntotten
wants to merge
1
commit into
main
Choose a base branch
from
feature/format-with-cursor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+130
−8
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ import { | |
| DocumentFilter, | ||
| languages, | ||
| Range, | ||
| Selection, | ||
| TextDocument, | ||
| TextEdit, | ||
| TextEditor, | ||
|
|
@@ -22,6 +23,8 @@ import { | |
| ExtensionFormattingOptions, | ||
| ModuleResolverInterface, | ||
| PrettierBuiltInParserName, | ||
| PrettierCursorOptions, | ||
| PrettierCursorResult, | ||
| PrettierFileInfoResult, | ||
| PrettierInstance, | ||
| PrettierModule, | ||
|
|
@@ -104,6 +107,11 @@ interface ISelectors { | |
| languageSelector: ReadonlyArray<DocumentFilter>; | ||
| } | ||
|
|
||
| interface FormatResult { | ||
| formatted: string; | ||
| cursorOffset: number; | ||
| } | ||
|
|
||
| export default class PrettierEditService implements Disposable { | ||
| private formatterHandler: undefined | Disposable; | ||
| private rangeFormatterHandler: undefined | Disposable; | ||
|
|
@@ -448,21 +456,58 @@ export default class PrettierEditService implements Disposable { | |
| options: ExtensionFormattingOptions, | ||
| ): Promise<TextEdit[]> => { | ||
| const startTime = new Date().getTime(); | ||
| const result = await this.format(document.getText(), document, options); | ||
|
|
||
| // Get cursor offset from active editor if available and not doing range formatting | ||
| const editor = window.activeTextEditor; | ||
| const isRangeFormatting = | ||
| options.rangeStart !== undefined && options.rangeEnd !== undefined; | ||
| let cursorOffset: number | undefined; | ||
|
|
||
| if (editor && editor.document === document && !isRangeFormatting) { | ||
| cursorOffset = document.offsetAt(editor.selection.active); | ||
| } | ||
|
|
||
| const result = await this.format( | ||
| document.getText(), | ||
| document, | ||
| options, | ||
| cursorOffset, | ||
| ); | ||
| if (!result) { | ||
| // No edits happened, return never so VS Code can try other formatters | ||
| return []; | ||
| } | ||
| const duration = new Date().getTime() - startTime; | ||
| this.loggingService.logInfo(`Formatting completed in ${duration}ms.`); | ||
| const edit = this.minimalEdit(document, result); | ||
| const edit = this.minimalEdit(document, result.formatted); | ||
| if (!edit) { | ||
| // Document is already formatted, no changes needed | ||
| this.loggingService.logDebug( | ||
| "Document is already formatted, no changes needed.", | ||
| ); | ||
| return []; | ||
| } | ||
|
|
||
| // Schedule cursor repositioning after VS Code applies the edit | ||
| // We use setImmediate to run after the current event loop completes | ||
| if ( | ||
| editor && | ||
| editor.document === document && | ||
| !isRangeFormatting && | ||
| result.cursorOffset >= 0 | ||
| ) { | ||
| setImmediate(() => { | ||
| // Verify the editor is still active and document hasn't changed | ||
| if ( | ||
| window.activeTextEditor === editor && | ||
| editor.document === document | ||
| ) { | ||
| const newPosition = document.positionAt(result.cursorOffset); | ||
| editor.selection = new Selection(newPosition, newPosition); | ||
| } | ||
| }); | ||
| } | ||
|
Comment on lines
+491
to
+509
|
||
|
|
||
| return [edit]; | ||
| }; | ||
|
|
||
|
|
@@ -505,14 +550,17 @@ export default class PrettierEditService implements Disposable { | |
| /** | ||
| * Format the given text with user's configuration. | ||
| * @param text Text to format | ||
| * @param path formatting file's path | ||
| * @returns {string} formatted text | ||
| * @param doc TextDocument being formatted | ||
| * @param options Formatting options | ||
| * @param cursorOffset Optional cursor offset for cursor preservation | ||
| * @returns FormatResult with formatted text and new cursor offset, or undefined if formatting failed | ||
| */ | ||
| private async format( | ||
| text: string, | ||
| doc: TextDocument, | ||
| options: ExtensionFormattingOptions, | ||
| ): Promise<string | undefined> { | ||
| cursorOffset?: number, | ||
| ): Promise<FormatResult | undefined> { | ||
| const { fileName, uri, languageId } = doc; | ||
|
|
||
| this.loggingService.logInfo(`Formatting ${uri}`); | ||
|
|
@@ -631,18 +679,53 @@ export default class PrettierEditService implements Disposable { | |
| this.loggingService.logInfo("Prettier Options:", prettierOptions); | ||
|
|
||
| try { | ||
| // Use formatWithCursor if we have a cursor offset to preserve cursor position | ||
| if (cursorOffset !== undefined) { | ||
| const cursorOptions: PrettierCursorOptions = { | ||
| ...prettierOptions, | ||
| cursorOffset, | ||
| }; | ||
|
|
||
| // Check if formatWithCursor is available (it should be for all modern Prettier versions) | ||
| if ("formatWithCursor" in prettierInstance) { | ||
| try { | ||
| const result: PrettierCursorResult = | ||
| await prettierInstance.formatWithCursor(text, cursorOptions); | ||
| this.statusBar.update(FormatterStatus.Success); | ||
| return { | ||
| formatted: result.formatted, | ||
| cursorOffset: result.cursorOffset, | ||
| }; | ||
| } catch (cursorError) { | ||
| // formatWithCursor can fail with some plugins that don't implement locStart/locEnd | ||
| // Fall back to regular format() in this case | ||
| this.loggingService.logDebug( | ||
| "formatWithCursor failed, falling back to format()", | ||
| cursorError, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Fallback to regular format() if no cursor offset or formatWithCursor not available/failed | ||
| const formattedText = await prettierInstance.format( | ||
| text, | ||
| prettierOptions, | ||
| ); | ||
| this.statusBar.update(FormatterStatus.Success); | ||
|
|
||
| return formattedText; | ||
| return { | ||
| formatted: formattedText, | ||
| cursorOffset: -1, // Indicate that cursor position is unknown | ||
| }; | ||
| } catch (error) { | ||
| this.loggingService.logError("Error formatting document.", error); | ||
| this.statusBar.update(FormatterStatus.Error); | ||
|
|
||
| return text; | ||
| return { | ||
| formatted: text, | ||
| cursorOffset: cursorOffset ?? -1, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
setImmediatefunction is not available in browser environments, but this extension supports both Node.js and browser contexts (as indicated by the "browser" field in package.json). This will cause a runtime error when the extension runs in vscode.dev or other browser-based VS Code instances.Consider using
setTimeout(() => {...}, 0)instead, which works in both Node.js and browser environments and provides similar behavior of deferring execution to the next event loop tick.