如何在 Vim 中构建用于过滤文本块的多命令? [英] How to construct a multi-command for filtering out blocks of text in Vim?
问题描述
快速解释:我有用 #tags
标记的文本块,并用空行分隔.我想过滤掉包含特定标签的所有块.我在这里得到了正则表达式的帮助(谢谢!),所以我构建了以下命令:
A quick explanation: I have blocks of text tagged with #tags
and separated by a blank line. I want to filter out all blocks that include a specific tag. I was helped with regex here (thanks!), so I constructed the following command:
command -nargs=1 TagSearch g/^\(.\+\n\)\{-}.*#<args>.*/y a | vnew | put a | %s/^#.*<args>.*\n/&\r
因此,做一个 :TagSearch 标签
应该:
- 搜索
#tag
. - 将所有相应的文本块粘贴到新的垂直缓冲区中.
- 在新缓冲区中的文本块之间添加一个空行.
- Search for the
#tag
. - Paste all corresponding Text Blocks into a new vertical buffer.
- Add a blank line between the Text Blocks in the new buffer.
Q1:当我单独执行每个步骤时,一切正常.但是多命令只将第一个匹配的文本块粘贴到新缓冲区中.为什么?
Q1: When I do each step separately, everything works. But the multi-command only pastes the first matching text block into the new buffer. Why?
Q2:如何让命令接受多个参数(以防我想一次搜索多个 #tags
)?谢谢!
Q2: How could I make the command accept multiple arguments (in case I want to search for several #tags
at once)? Thanks!
推荐答案
可以使用以下实现.
command! -nargs=* -bar TagSearch call CollectParagraphs([<f-args>])
function! CollectParagraphs(tags) range
let tags = len(a:tags) > 0 ? a:tags : [expand('<cword>')]
let pats = map(copy(tags), '"\\.\\*#" . escape(v:val, "\\")')
let v = winsaveview()
let [sr, @/; lines] = [@/, '\V' . join(pats, '\&')]
g//call extend(lines, getline(search('\n\n\zs', 'bnW'), line("'}")))
let @/ = sr
call winrestview(v)
exe 'vnew' escape(join(tags), ' %#|\')
set buftype=nofile bufhidden=hide noswapfile
call setline(1, lines)
endfunction
这篇关于如何在 Vim 中构建用于过滤文本块的多命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!