vim-prettier icon indicating copy to clipboard operation
vim-prettier copied to clipboard

Fix cursor jumping to top when redo

Open byeokim opened this issue 2 years ago • 0 comments

Summary

This resolves #226.

Issue: When pressing u after :Prettier, the cursor stays. (#207) However when pressing Ctrl-r after u the cursor won't stay but will jump to the top of the file.

Cause: I'm not sure, but it seems that the cursor position information is lost during :Prettier operation.

:Prettier essentially deletes all the contents of the current buffer and writes pre-prettier'ed contents into that buffer.

https://github.com/prettier/vim-prettier/blob/5e6cca21e12587c02e32a06bf423519eb1e9f1b2/autoload/prettier/utils/buffer.vim#L17-L28

When changes happen, Vim stores snapshots including cursor positions before those changes are applied. Then when the user presses Ctrl-r, Vim reads the cursor position stored in the snapshot. If the cursor position is in the redo block, the current cursor will move to that cursor position. However if the cursor position is outside the redo block, the current cursor will move to "the first line that actually changed".

In vim-prettier's case the cursor position is not in the redo block because all the lines upon one of which the cursor position was located are deleted. Thus the current cursor will move to the top of the file which is the first of the lines where the changes occurred.

Fix: Change the order of :Prettier process:

  • Before: delete the original contents and write pre-prettier'ed contents.
  • After: write pre-prettier'ed contents and delete the original contents.

Test Plan

For both Vim 8.2 and Neovim 0.6 check if the cursor jumps to the top of the file.

  1. Create an empty JavaScript file test.js
  2. Add 10 lines of const a = 1; and indent one of these lines:
    • the first line. (This is the first test case)
    • the last line. (This is the second test case)
    • line 3, i.e. somewhere between the first and the last. (This is the third test case)
  3. :Prettier
  4. u
  5. Ctrl-r

byeokim avatar Jan 04 '22 06:01 byeokim