Vim replaces Unicode character

I have seen hints on how to search for unicode characters in vim using: help regexp and \% u, but I have not been able to figure out how to replace the text with a unicode hex character.

A special situation is that DefaultKeyBindings.dict needs comments that will print the character displayed on that line in the comment.

Start:

blah blah...\U2234  

      

Command:

:s/\v.*\\U(\d{4})/& \/\*\\\\%u\1 \*\/  

      

Result:

blah blah...\U2234 /*\%u2234 */  

      

Purpose:

blah blah...\U2234 /* ∴ */

      

+3


source to share


2 answers


You need to convert the string representation of the Unicode hex value to the actual character represented by it. This is a task for nr2char()

, which can be embedded in a substitution via :help sub-replace-expression

:

:substitute+\v.*\\U(\d{4})\zs+\='/* '.nr2char(str2nr(submatch(1),16)).' */'+

      



Protip: use a different separator (I chose +

over /

), then you don't need to run.

+8


source


You can use an expression in the substitution text with \=

. Combine this with a feature nr2char()

for a workable solution. Here starts:

s^.*\\U\(\d\{4}\)^\=submatch(0).' // '.nr2char(printf('%d','0x'.submatch(1)))

      

This will convert the string

Bla bla ... \U2234

      



to

Bla bla ... \U2234 // ∴

      

I am using printf()

to convert from hex to decimal as required by the function nr2char()

. I'm sure this can be improved.

Note that this needs to be set 'encoding'

to UTF-8, see :h nr2char()

.

+3


source







All Articles