0

I want to write a command that replaces all of a line's spaces with figure spaces, and I want the code to not use those literal characters so it is more legible than :s/ / /g

So, naturally, I try various iterations like:

:s/\x20/\u2007/g      " matches a hex char then "20", adds uppercase "2007"
:s/\%u20/\%u2007/g
:s/[\x20]/\\%u2007/g
:s/[\x20]/^Vu2007/g                " that's a literal <Ctrl-V>
:s/\%u20/\=printf("%c", 0x2007)/g  " gives me ^G instead
:s/\%u20/\="\<Char-0x2007>"/g      " gives me <e2><80><fe>X<87> instead

None of these work, though all of the patterns do indeed match spaces.

I see lots of tricks around for how to enter Unicode characters in Insert mode, but none about how to do so in a replacement string.

In researching this question, I found How to translate Unicode escape sequences to the Unicode character, which gives me the following functional solution:

:s/\%u20/\=nr2char(0x2007)/g

Is there really no cleaner way to do this? I assume that's unnecessarily costly.

1 Answer 1

2

I'm surprised you didn't see an error message telling you that there was no match. Your problem is \x20 which was matching nothing. Your pattern was effectively:

[0-9A-Fa-f]20

\x matches a hex digit atom. See :h /\x. What you're thinking of are string special characters (:h expr-quote), which aren't expanded in patterns.

This is what you want:

execute ":s/ /\u2007/g"

or

:s/ /\="\u2007"/g

or

:s/\%u20/\="\u2007"/g

Just use a literal space as the pattern.

3
  • That was a typo; /[\x20]/ works. I'll adjust the question. This is still "executing" "\u2007" though, isn't it? Wouldn't that therefore have a (admittedly very small) extra cost beyond a literal figure space?
    – Adam Katz
    Mar 3, 2017 at 23:49
  • 1
    Are you talking about performance cost? Vim's script is literally the same as you typing it in the command line. There's no bytecode cache--it's always "executed". So yes, \="\u2007" evaluates a string and returns it during execution before substitution. It's also the simplest way for you to have an opaque representation of that character.
    – Tommy A
    Mar 4, 2017 at 4:38
  • That's the answer I was looking for. Thanks.
    – Adam Katz
    Mar 6, 2017 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.