开发者

How to replace leading spaces (only) with " " in Vim?

开发者 https://www.devze.com 2023-03-24 02:33 出处:网络
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 “compre

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.

Thus I’d like to know how I could change all the spaces only at the beginning of th开发者_如何学Pythone line by &nbsp;, so that, for example,

    extend: 'Ext.panel.Panel',

becomes

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


:%s/^ \+/\=repeat("&nbsp;",strlen(submatch(0)))

But it wouldn't surprise me if there's a shorter substitute command. Come on Vimgolfers!


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

  1. A substitution using the preceding-atom matching syntax (see :help \@<=):

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

    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
    
  2. 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!
    
  3. Another two-step substitution that replaces each of the leading spaces by certain symbol that does not occur in the text, and changes that symbol to &nbsp;:

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


Using a look-behind assertion to replace spaces precedeed by only spaces at the beginning of a line:

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

精彩评论

暂无评论...
验证码 换一张
取 消