terrortylor / nvim-comment

A comment toggler for Neovim, written in Lua
MIT License
479 stars 23 forks source link

Return cursor to previous location after commenting paragraph #45

Open dwoznicki opened 2 years ago

dwoznicki commented 2 years ago

After toggling comments for a paragraph (or in any visual mode), I'd like to have some way of returning my cursor to the previous location. Currently, executing a comment toggle with either gcip or vip:CommentToggle<cr> appears to place the cursor at the beginning of the commented block and erase all marks within the commented block.

Here's how I can recreate this.

In my init.vim, I have the following lines.

" ff: toggle comment for current line
nnoremap <silent> ff :CommentToggle<cr>

I can place my cursor on the first "n" in "nnoremap" and create a mark by running mt. I can check that my mark exists my running :marks. I see something like so.

:marks
mark line  col file/text
mark line  col file/text
 '    321    0 " ff: toggle comment for current line.
 l    321    0 " ff: toggle comment for current line.
 p    328    0 -invalid-
 t    322   10 nnoremap <silent> ff :CommentToggle<cr>
 y    325   10 nnoremap <silent> fp mtvip:CommentToggle<cr>`t

I can then comment these two lines by running gcip. I can then run :marks again, and see that the t mark is no longer present.

:marks
mark line  col file/text
 p    328    0 -invalid-
 y    325   10 nnoremap <silent> fp mtvip:CommentToggle<cr>`t

Note that undoing the comment also recreates the mark.

So finding a way to preserve marks after block commenting would do the trick, because then I could do something like

mtvip:CommentToggle<cr>`t

to comment a paragraph and go back to my t mark.

Thanks.

terrortylor commented 2 years ago

sure will take a look when I've next got time, had a quick play and didn't get anywhere... although couldn't replicate the marks going missing.

dwoznicki commented 2 years ago

Ah, yeah you're right. I can't recreate the marks going missing when I run sequence

mt
gcip
`t

But I can recreate it when I run :CommentToggle. In fact, it looks like executing :CommentToggle on a line deletes all marks on that line. I don't see this behavior when using the standard command mappings.

terrortylor commented 2 years ago

Hey sorry for the long pause. So marks going missing is fixed, this is due to the nvim api function call.

In regards to the returning cursor, I'm not sure we can do this. So testing with vip we see that the cursor immediately moves to the end of the selection. What I tested was hooking into this behaviour but no mark is set before the selection takes place. Trying to capture the cursor position before the operator pending mapping is initiated also doesn't seem to yield any meaningful info... anyhow I'll keep at it as now you've raised it it's bugging me.