Skip to content

Use formatWithCursor() API to preserve cursor position after formatting #3939

@ntotten

Description

@ntotten

Problem

The extension currently uses Prettier's format() API, which causes the cursor to jump after formatting. This is a common user complaint and differs from the expected behavior of maintaining editing context.

Proposed Solution

Use Prettier's formatWithCursor() API instead of format(). This API accepts a cursorOffset option and returns both the formatted text and the adjusted cursor offset.

Current Implementation

// PrettierEditService.ts:format() (around line 622)
const formatted = await prettierInstance.format(text, options);

Proposed Implementation

const cursorOffset = document.offsetAt(editor.selection.active);
const result = await prettierInstance.formatWithCursor(text, { 
  ...options, 
  cursorOffset 
});
// Use result.formatted for the text
// Use result.cursorOffset to restore cursor position

Impact

  • User Experience: Major improvement - cursor stays in place during format-on-save
  • Effort: Medium - requires changes to how provideEdits() returns edits and potentially using VS Code's WorkspaceEdit with cursor positioning

Relevant Files

  • src/PrettierEditService.ts - format() and provideEdits() methods
  • src/types.ts - PrettierInstance interface may need formatWithCursor added

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions