Sunday, July 4, 2021

Re: Help converting function to Vim9 script

> The MetaPost plugin in Vim contains the following definition to replace
> the n-th occurrence of `beginfig(...)` with `beginfig(n)`:
>
> function! s:fix_beginfigs()
> let i = 1
> g/^beginfig(\d*);$/s//\='beginfig('.i.');'/ | let i = i + 1
> endfunction
>
> command -nargs=0 FixBeginfigs call s:fix_beginfigs()
>
> On attempting to convert it to Vim9 script, I came up with this:
>
> def FixBeginfig()
> i = 1
> g/^beginfig(\d*);$/s//\='beginfig(' .. i .. ');'/ | i += 1
> enddef
>
> command! -buffer -nargs=0 -bar FixBeginfigs call <sid>FixBeginfig()
>
> But this results in 'Undefined variable: i', likely because the command
> is not evaluated in Vim9 script context.
>
> Any idea what would be the best way to convert the snippet above?

Well, this works:

def Fix_beginfigs()
g:index = 1
g/^beginfig(\d*);$/s//\='beginfig(' .. g:index .. ');'/ | g:index = g:index + 1
unlet g:index
enddef

However, using a legacy function would not be worse. The global command
does most of the work, what function it's in doesn't really matter.

--
From "know your smileys":
(:-# Said something he shouldn't have

/// Bram Moolenaar -- Bram@Moolenaar.net -- http://www.Moolenaar.net \\\
/// \\\
\\\ sponsor Vim, vote for features -- http://www.Vim.org/sponsor/ ///
\\\ help me help AIDS victims -- http://ICCF-Holland.org ///

--
--
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 on the web visit https://groups.google.com/d/msgid/vim_use/202107042130.164LU1792626692%40masaka.moolenaar.net.

No comments:

Post a Comment