Vim regexp help: change spaces to “ ”

2019-04-16 09:51发布

问题:

I've had this problem many times: I have a source code, but if I copy / paste it into Wordpress and enclose it with <code> </code> 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 the line by &nbsp;.

I.e.

    extend: 'Ext.panel.Panel',

becomes

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

回答1:

I would propose the following three solutions addressing the issue that are listed below in order of my personal preference.

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

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

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

    :%s/\v(^ *)@<= /\&nbsp;/g
    
  2. Two-staged substitution that splits a line just after 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
    


回答2:

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

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



回答3:

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

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