如何在 vimscript 中替换选定的文本

How to replace selected text in vimscript

我有一些文件的特定部分带有未格式化的 xml 代码。我需要编写一个选择文本并调用 xmllint 的 vimscript 函数。

我知道我可以在命令行上执行此操作:'<,'>!xmllint --format -

但我确实需要在 vimscript 函数中做同样的事情,但我不知道如何制作类似 normal! 的视觉调用。

我试过了,但它不能正常工作:

function! MyFormat()
    ... stuff done here
    let startl = line("'<")
    let endl = line("'>")
    let line = getline(startl, endl)
    let r = system('echo "' . join(line, "") . '" | xmllint --format -')

    call setline('.', r)
endfunction

Vim 脚本中的每一行都是一个 Ex 命令。既然你已经有一个有效的 Ex 命令,你不妨使用它。

function! MyFormat()
    " ... stuff done here
    '<,'>!xmllint --format -
    " ... more stuff done here
endfunction

但是,同样,数据缺失,所以这可能有效……或无效,是否足够……或无效,等等。