I have something like this in my vimrc:
vim9script
nnoremap <silent> Q :set opfunc=libtext#ToggleComment<cr>g@
vnoremap <silent> Q <scriptcmd> libtext.ToggleComment(visualmode(), true)<cr>
Then, in autoload/libtext.vim:
export def ToggleComment(visualMode: string, visual: bool = false)
# Comment/uncomment a region of text. See also :help map-operator.
#
# visualMode: one of "line", "char", or "block". See :help g@.
# visual: whether the function is called directly when in Visual mode (true)
# as opposed to being called via opfunc (false).
var first: number
var last: number
if visual
var lnum1 = line("v")
var lnum2 = line(".")
if lnum1 < lnum2
first = lnum1
last = lnum2
else
first = lnum2
last = lnum1
endif
else
first = line("'[")
last = line("']")
endif
# Do something with getline(first, last)
enddef
Depending on your goal, you may also want to look at Vim's comment
plugin at $VIMRUNTIME/pack/dist/opt/comment.
Hope this help,
Life.