如何用 Vim substitute() 和 &commentstring 注释整行
How to comment the whole line with Vim substitute() and &commentstring
我一直在尝试编写一个 vim 脚本来读取 shell 命令 (figlet
) 的输出并对其每一行进行注释。我想使用 &commentstring
变量,因为我希望此脚本适用于任何文件类型。
到目前为止,我只获得了不一致的结果。这是一个例子:
- 提示用户输入 his/her 首字母并将其传递给 shell 命令
figlet
以在文件顶部打印 ascii 艺术:
let g:initials = input('Authors initials: ')
execute '0r! figlet -W ' . toupper(g:initials)
输出如下(例如g:initials = JT):
_ _____
| | |_ _|
_ | | | |
| |_| | | |
\___/ |_|
- 获取输出的行数:
let s:line_count = system("figlet -W " . g:signit_initials . "| wc -l")
- 使用vim函数
substitute()
对每一行进行注释:
let s:i = 1
while s:i < s:line_count
execute 'silent' . s:i . 's/^.*$/\=substitute(&commentstring, "%s", "\t" . getline(".") . "\t", "")'
let s:i += 1
endwhile
输出如下:
/* _ _____ */
/* | | |_ _|*/
/* _ | | | | */
/* | |_| | | | */
/* ___/ |_| */
如您所见,它在最后一行之前运行良好,我不明白为什么。也许有更好的方法来解决这个问题。无论如何,如果有人能就如何解决这个小问题向我提供帮助,我将非常感激。
it works well until the last line and I dont understand why
最后一行包含一个反斜杠。并根据 :h sub-replace-special
进行修改。所以,至少,你必须用另一个来逃避它。有点像 escape(getline('.'), '\')
。但是,对于这种特殊情况,我宁愿选择 printf
,因为它看起来更简单、更自然:printf(&cms, "\t"..getline(".").."\t")
也不需要“while”循环,因为许多命令和函数都接受行范围:它更有效,也更容易编写。
Maybe there is a better way to aproach this.
IMO 这看起来更好:
call append(0, map(systemlist("figlet -W "..toupper(g:initials)),
\ {_, v -> printf(&cms, "\t" .. v .. "\t")}))
我一直在尝试编写一个 vim 脚本来读取 shell 命令 (figlet
) 的输出并对其每一行进行注释。我想使用 &commentstring
变量,因为我希望此脚本适用于任何文件类型。
到目前为止,我只获得了不一致的结果。这是一个例子:
- 提示用户输入 his/her 首字母并将其传递给 shell 命令
figlet
以在文件顶部打印 ascii 艺术:
let g:initials = input('Authors initials: ')
execute '0r! figlet -W ' . toupper(g:initials)
输出如下(例如g:initials = JT):
_ _____
| | |_ _|
_ | | | |
| |_| | | |
\___/ |_|
- 获取输出的行数:
let s:line_count = system("figlet -W " . g:signit_initials . "| wc -l")
- 使用vim函数
substitute()
对每一行进行注释:
let s:i = 1
while s:i < s:line_count
execute 'silent' . s:i . 's/^.*$/\=substitute(&commentstring, "%s", "\t" . getline(".") . "\t", "")'
let s:i += 1
endwhile
输出如下:
/* _ _____ */
/* | | |_ _|*/
/* _ | | | | */
/* | |_| | | | */
/* ___/ |_| */
如您所见,它在最后一行之前运行良好,我不明白为什么。也许有更好的方法来解决这个问题。无论如何,如果有人能就如何解决这个小问题向我提供帮助,我将非常感激。
it works well until the last line and I dont understand why
最后一行包含一个反斜杠。并根据 :h sub-replace-special
进行修改。所以,至少,你必须用另一个来逃避它。有点像 escape(getline('.'), '\')
。但是,对于这种特殊情况,我宁愿选择 printf
,因为它看起来更简单、更自然:printf(&cms, "\t"..getline(".").."\t")
也不需要“while”循环,因为许多命令和函数都接受行范围:它更有效,也更容易编写。
Maybe there is a better way to aproach this.
IMO 这看起来更好:
call append(0, map(systemlist("figlet -W "..toupper(g:initials)),
\ {_, v -> printf(&cms, "\t" .. v .. "\t")}))