Intelligent cursor restoration after auto-formatting #131
Replies: 5 comments 5 replies
-
This is a nice idea! I think it can be done as followed:
|
Beta Was this translation helpful? Give feedback.
-
There's a macro in 0.5.0 for this: The following works for me in Python (provided that (require 'tree-sitter-extras)
(define-advice format-all-buffer (:around (f &rest args) tree-sitter-save-excursion)
(if tree-sitter-mode
(tree-sitter-save-excursion
(apply f args))
(apply f args))) I think it's better to combine this with the diff-based approach mentioned in the issue you linked, though. |
Beta Was this translation helpful? Give feedback.
-
@raxod502, who wrote |
Beta Was this translation helpful? Give feedback.
-
Yes, there are basically two good options for handling this issue:
If you've got the resources available to do the first approach, it'll probably work better. The reason I think the second approach is good is because the first approach requires a lot of work for each language / formatter, whereas the second approach works for all languages and formatters. The disadvantages of the second approach are:
|
Beta Was this translation helpful? Give feedback.
-
It's since been pointed out to me that Emacs 26 and later ship a function which takes care of all this stuff for you: radian-software/apheleia#38 |
Beta Was this translation helpful? Give feedback.
-
I've never used tree-sitter so let me know if this is not possible or doesn't make much sense.
Restoring buffer position after applying styling fixes can be difficult. My frequent use case is with the
black
formatter using https://github.com/lassik/emacs-format-all-the-code on save.Black makes a guarantee that the AST is unmodified after formatting, so it seems to me that combining tree-sitter with this the user could be placed on the same tree node as they were before the format. This would make it so that autoformatting would leave your cursor in the same logical place as it was before, even if the number of lines of code was radically changed.
Beta Was this translation helpful? Give feedback.
All reactions