如何将 Vim 中每行开头的空格数减半? [英] How to halve the number of whitespace at the beginning of each line in Vim?

查看:22
本文介绍了如何将 Vim 中每行开头的空格数减半?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何在 Vim 中做相反的映射:

Can someone tell me how to do the opposite of this mapping in Vim:

nnoremap <leader>iw :let _s=@/<Bar>:let _s2=line(".")<Bar>:%s/^\s*/&&/ge<Bar>:let @/=_s<Bar>:nohl<Bar>exe ':'._s2<CR>

作为说明:此映射使每行开头的空白字符数(&& 部分)加倍.仅影响第一个常规字符之前的空格.当前搜索字符串保持原样(通过 _s 变量).在此转换后(通过 _s2 变量)恢复光标位置.

As a clarification: This mapping doubles (the && part) the number of whitespace characters at the beginning of each line. Only the whitespace before the first regular character is affected. Current search string is kept in tact (via the _s variable). The cursor position is restored after this transformation (via the _s2 variable).

所以,基本上,我正在寻找一种映射,如果它们一个接一个地执行,就会撤销这个映射.

So, basically, I’m searching for a mapping that will undo this one if they are executed one after another.

我无法弄清楚如何将这个新操作限制为仅适用于第一个常规字符之前的空格.

I’m having trouble in figuring out how to limit this new operation to work only on whitespace before the first regular character.

推荐答案

下面的替换命令反其效果对应的前导空格加倍.

The following substitute command inverses the effect of its counterpart that doubles the leading whitespace.

:%s/^\(\s*\)\1/\1/

为此命令构建的映射需要遵循相同的模式作为问题中使用的模式(替换除外当然要执行).为了减少定义中的重复,一可以将状态保持代码拆分成一个小函数:

A mapping to be constructed for this command needs to follow the same pattern as the one used in the question (except for the substitution to execute, of course). To reduce repetition in the definitions, one can separate the state-preserving code into a small function:

nnoremap <silent> <leader>>    :call PinnedCursorDo('%s/^\s*/&&/')<cr>
nnoremap <silent> <leader><lt> :call PinnedCursorDo('%s/^\(\s*\)\1/\1/')<cr>

function! PinnedCursorDo(cmd)
    let [s, c] = [@/, getpos('.')]
    exe a:cmd
    let @/ = s
    call setpos('.', c)
endfunction

这篇关于如何将 Vim 中每行开头的空格数减半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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