diff options
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | tests/runewidth.ha | 9 | ||||
| -rw-r--r-- | tests/strwidth.ha | 6 | ||||
| -rw-r--r-- | tui/widget/widget.ha | 6 | ||||
| -rw-r--r-- | tui/width.ha | 32 |
5 files changed, 51 insertions, 3 deletions
@@ -4,3 +4,4 @@ /list_nostyle /scrolllist /il +/runewidth diff --git a/tests/runewidth.ha b/tests/runewidth.ha new file mode 100644 index 0000000..5e570a5 --- /dev/null +++ b/tests/runewidth.ha @@ -0,0 +1,9 @@ +use tui; + +@test +fn runewidth() void = { + assert(tui::runewidth('f') == 1); + assert(tui::runewidth('ๅคง') == 2); + assert(tui::runewidth('ใ') == 2); + assert(tui::runewidth('๐') == 2); +}; diff --git a/tests/strwidth.ha b/tests/strwidth.ha new file mode 100644 index 0000000..e3863d6 --- /dev/null +++ b/tests/strwidth.ha @@ -0,0 +1,6 @@ +use tui; + +@test +fn strwidth() void = { + assert(tui::strwidth("ๅคงใ๐f") == 7); +}; diff --git a/tui/widget/widget.ha b/tui/widget/widget.ha index be6c255..3e6cf8d 100644 --- a/tui/widget/widget.ha +++ b/tui/widget/widget.ha @@ -198,7 +198,7 @@ export fn print(w: *widget) void = { w.state.clear = false; }; -// Applies styling (style) to the given string. +// Applies styling (style) to the given string slice. fn applystyles(st: (*style | void), s: []str) []str = { return match (st) { case let st: *style => @@ -234,11 +234,11 @@ fn truncate_to_size(w: *widget) []str = { const line = w.buf.lines[i]; let item = match (w.sz) { case let sz: tty::ttysize => - const s = if (len(line) > sz.columns) strings::sub(line, 0z, sz.columns) else line; + const s = if (tui::strwidth(line) > sz.columns) strings::sub(line, 0z, sz.columns) else line; yield strings::rpad(s, ' ', sz.columns); case void => const wsz = tty::winsize(w.state.out)!; - const s = if (len(line) > wsz.columns) strings::sub(line, 0z, wsz.columns) else line; + const s = if (tui::strwidth(line) > wsz.columns) strings::sub(line, 0z, wsz.columns) else line; yield strings::dup(s); }; append(lines, item)!; diff --git a/tui/width.ha b/tui/width.ha new file mode 100644 index 0000000..6f9631c --- /dev/null +++ b/tui/width.ha @@ -0,0 +1,32 @@ +use strings; + +export fn runewidth(r: rune) uint = { + let ru = r: u32; + // emoticons: https://en.wikipedia.org/wiki/Emoticons_(Unicode_block) + if (ru >= '\U0001F600' && ru <= '\U0001F64F') { + return 2; + }; + // hiragana: https://en.wikipedia.org/wiki/Hiragana_%28Unicode_block%29 + if (ru >= '\U00003040' && ru <= '\U0000309F') { + return 2; + }; + // katakana: https://en.wikipedia.org/wiki/Katakana_(Unicode_block) + if (ru >= '\U000030A0' && ru <= '\U000030FF') { + return 2; + }; + // CJK: https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) + if (ru >= '\U00004E00' && ru <= '\U00009FFF') { + return 2; + }; + return 1; +}; + +export fn strwidth(s: str) uint = { + const runes = strings::torunes(s); + defer free(runes); + let sum = 0u; + for (let r .. runes) { + sum += runewidth(r); + }; + return sum; +}; |
