How to replace leading spaces (only) with " " in Vim?
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
, so that, for example,
extend: 'Ext.panel.Panel',
becomes
extend: 'Ext.panel.Panel',
:%s/^ \+/\=repeat(" ",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.
A substitution using the preceding-atom matching syntax (see
:help \@<=
)::%s/\%(^ *\)\@<= /\ /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(^ *)@<= /\ /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/ /\ /g|j!
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
::exe "g/^ \\+/norm!v//e\rr\r" | %s/\r/\ /g
Using a look-behind assertion to replace spaces precedeed by only spaces at the beginning of a line:
%s/\(^ *\)\@<= /\ /g
精彩评论