rust-lang / rust-mode

Emacs configuration for Rust
Apache License 2.0
1.11k stars 179 forks source link

Improve the usability of `rust-dbg-wrap-or-unwrap` #498

Closed micl2e2 closed 1 year ago

micl2e2 commented 1 year ago

While the original implementation of rust-dbg-wrap-or-unwrap works in many cases, it has following problems:

Issue1. Insertion happens indiscriminately.

For example:

before:

*<---cursor is here
let a = 1;

after:

dbg!(
let) a = 1;

Issue2. Not handling the cursor position after dbg!() insertion.

Insertion of dbg!() indicates that user's intention to debug an expression. if the return value is significant(case 1), the original expression must be surrounded by another expression, which means not handling the cursor position is totally fine, but if dbg!'s return value is insignificant(case 2), the subsequent action the user will take must be adding an trailing semicolon, for the original implementation in such cases, users must reach the end of line first(C-e or similar) and then add a semicolon.

In fact, in practice, the second case is far more common than the first one, we can do some rough statistics on the source files of rust-lang/rust:

rg 'dbg!\(.*\).*[^;]$' | wc -l  # 61 the first case
rg 'dbg!\(.*\).*;$' |  wc -l  # 270 the second case

The point is that, whether users insert trailing semicolon or not, moving cursor to the end of dbg!() automatically after insertion not only does no harms, but it likely saves one keystroke for most cases.

Overall, these patches do nothing more than fixing the issues mentioned above and cutting some unnecessary branches. For the first issue , the result after fixed will be

dbg!()
let a = 1;

Other known issues:

  1. Similar to the original implementaion, the current rust-dbg-wrap-or-unwrap still relies on forward/backward-sexp to move forward/backward the cursor. In some cases where the cursor is inside pattern match arms or a complex structure or similar, C-c C-d may break the code.
psibi commented 1 year ago

Thanks for the PR. Can you add some tests for the different cases here ?

micl2e2 commented 1 year ago

Thanks for the PR. Can you add some tests for the different cases here ?

Sure, I'm working on this.

micl2e2 commented 1 year ago

Hi! @psibi I've added tests for new cases(two), as well as existing cases(three). And I've splited changes into relatively small commits, which might be helpful for the review. If these commits are too verbose and need to be squashed or rearranged, please let me know.

psibi commented 1 year ago

Thank you!