1

写作时,有时我必须连续替换几个不同的单词,比如 a1 -> a2、b1->b2、c1->c2 等等。

为此,我手动编辑命令历史记录,因此我从

:s/a1/a2/gc

用 b1 和 b2 替换 a1 和 a2 后,进行替换并继续下一项。

我想要的工作流程是这样的:

:let in = ['a1', 'b1', 'c1']
:let out = ['a2', 'b2', 'c2']
:call ReplaceAllWithConfirmation(in, out)

其中 ReplaceAllWithConfirmation 将是一个执行替换但每次都要求我确认的函数。

这可能吗?

谢谢!

4

3 回答 3

3

您不需要编写函数。只需运行以下命令:

:%s/[a-c]1/\={'a1':'a2','b1':'b2','c1':'c2'}[submatch(0)]/gc

后面可以有表达式\=

于 2012-09-29T00:08:27.107 回答
2

使用 Tim Pope 的Abolish plugin,您的示例将是

%Subvert/{a,b,c}1/{}2/g
于 2012-09-29T10:24:40.767 回答
0

在我提出问题后,我想出了这个功能和映射,几乎可以满足我的需求。这不像其他两个答案那样优雅,但它可以适应执行一系列由在每个命令之间暂停的列表指定的一般命令,所以我在这里写。

function! MyLatexReplaceText(...)
  if a:0 > 0
    if a:0 != 2
      echom "provide two lists to the function"
      return ''
    endif
    let g:replace_list_in = a:1
    let g:replace_list_out = a:2
    let g:replace_ncur = 0
  endif
  if a:0 == 0 && !exists("g:replace_ncur")
    let g:replace_list_in = ['a1', 'b1', 'c1']
    let g:replace_list_out = ['a2', 'b2', 'c2']
    let g:replace_ncur = 0
  endif
  if g:replace_ncur == len(g:replace_list_in)
    let g:replace_cmd = ":echom 'reached end of list'\<CR>"
    let g:replace_ncur = -1
  else
    let range_ = "'<,'>"
    let extra_flags = 'gc'
    let g:replace_cmd = ':' .range_ . "s/" .  g:replace_list_in[g:replace_ncur] 
          \ . "/" . g:replace_list_out[g:replace_ncur] . "/" . extra_flags
          \ . "\<CR>"
    call histadd("cmd", g:replace_cmd)
  endif
  let g:replace_ncur += 1
  return g:replace_cmd
endfunction
nnoremap <silent><expr> <Leader>ns MyLatexReplaceText()
于 2012-09-29T17:38:15.953 回答