如何在 Vim 中构建用于过滤文本块的多命令? [英] How to construct a multi-command for filtering out blocks of text in Vim?

查看:72
本文介绍了如何在 Vim 中构建用于过滤文本块的多命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的关于在 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 标签应该:

  1. 搜索#tag.
  2. 所有相应的文本块粘贴到新的垂直缓冲区中.
  3. 在新缓冲区中的文本块之间添加一个空行.
  1. Search for the #tag.
  2. Paste all corresponding Text Blocks into a new vertical buffer.
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆