我正在尝试编写一个 beautify.vim 脚本,使类似 C 的代码符合我可以轻松阅读的标准。
我的文件只包含全部以 %s/...
开头的替换命令
但是,当我尝试以 :source beautify.vim
或 :runtime beautify.vim
的方式在我的文件打开的情况下运行脚本时,它运行但是所有替代命令都声明未找到它们的模式(模式通过手动输入进行测试并且应该有效)。
有没有办法让 vim 在当前缓冲区的上下文中运行命令?
美化.vim:
" add spaces before open braces
sil! :%s/\%>1c\s\@<!{/ {/g
" beautify for
sil! :%s/for *( *\([^;]*\) *; *\([^;]*\) *; *\([^;]*\) *)/for (\1; \2; \3)/
" add spaces after commas
sil! :%s/,\s\@!/, /g
在我的测试中,第一个 :s 命令应该匹配(它在手动应用时匹配)。
最佳答案
我最近刚写了一个类似的美化脚本,但我以我认为更灵活的方式实现了它;另外,我试图想出一种机制来避免替换字符串中的内容。
" {{{ regex silly beautifier (avoids strings, works with ranges)
function! Foo_SillyRegexBeautifier(start, end)
let i = a:start
while i <= a:end
let line = getline(i)
" ignore preprocessor directives
if match(line, '^\s*#') == 0
let i += 1
continue
endif
" ignore content of strings, splitting at double quotes characters not
" preceded by escape characters
let chunks = split(line, '\(\([^\\]\|^\)\\\(\\\\\)*\)\@<!"', 1)
let c = 0
for c in range(0, len(chunks), 2)
let chunk = chunks[c]
" add whitespace in couples
let chunk = substitute(chunk, '[?({\[,]', '\0 ', 'g')
let chunk = substitute(chunk, '[?)}\]]', ' \0', 'g')
" continue like this by calling substitute() on chunk and
" reassigning it
" ...
let chunks[c] = chunk
endfor
let line = join(chunks, '"')
" remove spaces at the end of the line
let line = substitute(line, '\s\+$', '', '')
call setline(i, line)
let i += 1
endw
endfunction
" }}}
然后我定义了一个映射,它在正常模式下影响整个文件,在可视模式下只影响选定的行。当文件中有一些您不想触及的精心格式化的部分时,这很好。
nnoremap ,bf :call Foo_SillyRegexBeautifier(0, line('$'))<CR>
vnoremap ,bf :call Foo_SillyRegexBeautifier(line("'<"), line("'>"))<CR>
关于vim - 如何运行改变当前缓冲区的 vim 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5136516/