On 15/04/09 13:22, Yukihiro Nakadaira wrote:
>
> Y. Hida wrote:
>> Is there a way figure out how wide a string containing double-width
>> characters are when displayed? I'm trying to right-justify some strings
>> in foldtext.
>
> /\%v pattern is useful for it.
>
>
> function! StrWidth(str, ...)
> let vcol = get(a:000, 0, 0)
i.e. if a:0 > 0 | let vcol = a:1 | else | let vcol = 0 | endif
> let w = 0
> for c in split(a:str, '\zs')
> let w += CharWidth(c, w + vcol)
> endfor
> return w
> endfunction
>
> function! CharWidth(c, ...)
> let vcol = get(a:000, 0, 0)
> if a:c == ""
> return 0
> elseif a:c == "\t"
> return TabWidth(vcol)
> elseif a:c =~ '^.\%2v' " single char
> return 1
> elseif a:c =~ '^.\%3v' " double char, ^X
> return 2
> elseif a:c =~ '^.\%5v' "<XX>
> return 4
> else " other?
<XXXX> e.g. <feff>
In theory even <XXXX> wouldn't suffice for unprintable and zero-width
characters aobve U+FFFF but I cannot find an example.
From the examples above,
elseif a:c =~ '^.\%7v'
return 6
and we could skip the last "else".
> endif
> return 0
> endfunction
>
> function! TabWidth(vcol)
> return&tabstop - (a:vcol %&tabstop)
> endfunction
Here's another proposal, which can meet every possibility, and doesn't
loop over all characters (faster for long strings), but at the cost of
opening a temporary window (IOW, it requires has('windows))
function VirtLen(string)
new
0put =a:string
let rv = virtcol('$') - 1
q!
return rv
endfunction
Note that if the argument string includes nulls or newlines, only the
virtual length of the part after the last of them will be returned. If
you deem this unacceptable, replace the ":put" line by
0put =substitute(a:string, '\n', '\r', 'g')
Best regards,
Tony.
--
Basic, n.:
A programming language. Related to certain social diseases in
that those who have it will not admit it in polite company.
--~--~---------~--~----~------------~-------~--~----~
You received this message from the "vim_use" maillist.
For more information, visit http://www.vim.org/maillist.php
-~----------~----~----~----~------~----~------~--~---