Search code examples
perlunicodetext-formatting

Compute the width of a string in monspaced font


In order to properly format some text in a terminal (where I assume usage of a monospaced font), I need to compute the “length” of strings. The tricky part is that I need the length it will use on display (in number of fixed-width characters).

I originally used the length function, but it returns the number of codepoints. I also tried to count the number of graphemes using:

sub width {
    my $str = shift;
    my $count = 0;
    while ($str =~ /\X/g) {
        $count++;
    }
    return $count;
}

(Credits to Tom Christiansen).

But this is still not what I need, as some graphemes are double-width with my font (SF Mono Regular), e.g. emojis and Asian characters.


Solution

  • After further research, I found the Text::CharWidth CPAN module, which provides the mbswidth function, doing exactly what I need.

    use Text::CharWidth qw(mbswidth);
    
    mbswidth ("😀😉"); # returns 4
    mbswidth ("あら"); # returns 4