在 vim 中插入文本加上模式计数

Inserting text plus the count of a pattern in vim

我正在尝试编写一个小函数,以帮助我使用 Stata 调试代码。我想要的只是 vim 计算一行以 di "here 开头的次数,然后将 di "here XX" 插入缓冲区的当前行,其中 XX 是次数。

这是我的:

fun! ADD_Here()
    let n=[0] | bufdo %s/^di\ \"here\zs/\=map(n,'v:val+1')[1:]/ge
    put='di \"here ' . n[0] . '\"'
endfun
nmap <leader>d :<C-U>call ADD_Here()<CR>

这几乎完全按预期工作,它执行所有计数并插入文本,但它总是将第二个插入放在第一个插入的正下方,然后是第三个插入在第二个下方,等等。我该如何修改它它在当前行插入?

出于引用目的,我得到了 let n=[0]... 语句的代码 here

:[line]put 总是将文本放在行 [line] 下方,如果没有 [line].

则放在当前行下方

使用call setline('.', 'di \"here ' . n[0] . '\"')更改当前行。

通过在计数发生之前存储当前行号,在计数之后移动到该行,使用 setline 函数插入带有唯一关键字的文本来解决这个问题(感谢@romani 带来这个功能引起我的注意),然后用 n[0] 中存储的计数替换该关键字。我还在 setline 函数之前添加了 exec 'normal O' 命令以在当前行上方插入一个换行符,这样当前行就不会被调试文本替换。

    fun! ADD_Here()
        "Store the current line number in a variable
        let cline = line('.') 

        "Store the count of lines beginning with 'di "here' in a list
        let n=[0] | bufdo %s/^di\ \"here\zs/\=map(n,'v:val+1')[1:]/ge     

        "The above command moves the current line if n[0]>0, so go back to the saved value
        exec cline

        "Create a blank line above the current line and move to it
        exec 'normal O'

        "Insert text with a unique keyword '__stata_debug__' on the current line
        call setline('.','di "here __stata_debug__"')

        "Replace the unique keyword with the count of lines beginning with 'di "here'
        exec '%s/__stata_debug__/'.n[0].'/g'
    endfun
    "Map to function to <leader>d
    nmap <leader>d :<C-U>call ADD_Here()<CR>