如何用“ "替换前导空格(仅)在 Vim 中? [英] How to replace leading spaces (only) with " " in Vim?

查看:42
本文介绍了如何用“ "替换前导空格(仅)在 Vim 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我遇到过很多次了:我有一段源代码,但是如果我将其复制并粘贴到 Wordpress 中并用 <code>...</code> 标签括起来,则开头的空格会被压缩"合二为一.

I’ve had this problem many times: I have a piece of source code, but if I copy and paste it into Wordpress and enclose it with the <code>...</code> tags, the beginning spaces are "compressed" into one.

因此,我想知道如何通过 &nbsp; 更改行开头的所有空格,例如,

Thus I’d like to know how I could change all the spaces only at the beginning of the line by &nbsp;, so that, for example,

    extend: 'Ext.panel.Panel',

变成

&nbsp;&nbsp;&nbsp;&nbsp;extend: 'Ext.panel.Panel',

推荐答案

我可以通过三种方法来实现所需的编辑看,下面按我个人喜好的顺序列出.

There are three approaches to implement the desired edit that I can see, listed below in the order of my personal preference.

  1. 使用前置原子匹配语法的替换(见 :help \@<=):

 :%s/\%(^ *\)\@<= /\&nbsp;/g

如果命令的简洁性很重要,可以缩短它使用非常神奇"的模式(见 :help \v)通过改变非捕获组 (:help \%() 到捕获组:

If brevity of the command is crucial, one can shorten it using the "very magic" mode (see :help \v) by changing the non-capturing group (:help \%() to a capturing one:

 :%s/\v(^ *)@<= /\&nbsp;/g

  • 一个两阶段的替换,在前导之后分割一行空格,替换这些空格,然后重新加入该行:

  • A two-staged substitution that splits a line just after the leading spaces, replaces those spaces, and rejoins that line:

     :g/^/s/^ \+/&\r/|-s/ /\&nbsp;/g|j!
    

  • 另一种两步替换,替换每个前导文本中未出现的某些符号的空格,并更改那个符号到 &nbsp;:

     :exe "g/^ \\+/norm!v//e\rr\r" | %s/\r/\&nbsp;/g
    

  • 这篇关于如何用“&amp;nbsp;"替换前导空格(仅)在 Vim 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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