Tuesday, July 22, 2025

Re: Calling a vim9script function with a range

On 2025-07-21, 'Russell Shaw' via vim_use <vim_use@googlegroups.com> wrote:
> Hi,
>
> In "Comment()", how can i tell if the mapping "\c" was called with a visual
> range or not ?
>
> I want to call "Comment()" only once, without resorting to a legacy function,
> and without resorting to an intermediate ex command.
>
> I want access to the first and last visual lines, or else the current line (for
> non-visual, first==last).
>
> ---------------------------------
> vim9script
>
> def g:Comment()
> echo "a"
> enddef
>
> map \c :<C-U>call Comment()<CR>
> ---------------------------------

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.


--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/vim_use/105ouan%2410kj%241%40ciao.gmane.io.

No comments: