Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
cowsay: fix width of multibyte characters
--- cowsay.orig 2015-12-01 18:05:41.636619759 +0900
+++ cowsay 2015-12-01 18:11:36.999132910 +0900
@@ -11,6 +11,7 @@ use Text::Wrap qw(wrap fill $columns);
use File::Basename;
use Getopt::Std;
use Cwd;
+use Text::CharWidth qw(mbswidth);
if (${^UTF8LOCALE}) {
binmode STDIN, ':utf8';
@@ -110,7 +111,7 @@ sub maxlength {
my ($l, $m);
$m = -1;
for my $i (@_) {
- $l = length $i;
+ $l = mbswidth $i;
$m = $l if ($l > $m);
}
## maxlength patch from Jeronimo Pellegrini (Closes: #165218)
@@ -120,10 +121,15 @@ sub maxlength {
return $m;
}
+sub colstr {
+ (my $str, my $columns) = @_;
+ $str . ' ' x ($columns - mbswidth $str)
+}
+
sub construct_balloon {
my $max = &maxlength(@message);
my $max2 = $max + 2; ## border space fudge.
- my $format = "%s %-${max}s %s\n";
+ my $format = "%s %s %s\n";
my @border; ## up-left, up-right, down-left, down-right, left, right
if ($0 =~ /think/i) {
$thoughts = 'o';
@@ -142,12 +148,12 @@ sub construct_balloon {
## no trailing spaces (#276144)
push(@balloon_lines,
" " . ("_" x $max2) . "\n" ,
- sprintf($format, $border[0], $message[0], $border[1]),
+ sprintf($format, $border[0], colstr($message[0], $max), $border[1]),
(@message < 2 ? "" :
- map { sprintf($format, $border[4], $_, $border[5]) }
+ map { sprintf($format, $border[4], colstr($_, $max), $border[5]) }
@message[1 .. $#message - 1]),
(@message < 2 ? "" :
- sprintf($format, $border[2], $message[$#message], $border[3])),
+ sprintf($format, $border[2], colstr($message[$#message], $max), $border[3])),
" " . ("-" x $max2) . "\n"
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.