chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
Generated
+3295
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"iter"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func ensure_char_in_range(value uint32) uint32 {
|
||||
// Branchless: if (value > MAX_UNICODE) value = 0
|
||||
diff := int64(value) - UNICODE_LIMIT
|
||||
// The right shift gives all ones for negative diff and all zeros for positive diff
|
||||
mask := uint32(diff >> 63)
|
||||
return value & mask
|
||||
}
|
||||
|
||||
func CharPropsFor(ch rune) CharProps {
|
||||
q := ensure_char_in_range(uint32(ch))
|
||||
return charprops_for(q)
|
||||
}
|
||||
|
||||
func IteratorOverGraphemes(text string) iter.Seq[string] {
|
||||
var s GraphemeSegmentationResult
|
||||
start_pos := 0
|
||||
return func(yield func(string) bool) {
|
||||
for pos, ch := range text {
|
||||
if s = s.Step(CharPropsFor(ch)); s.Add_to_current_cell() == 0 {
|
||||
if !yield(text[start_pos:pos]) {
|
||||
return
|
||||
}
|
||||
start_pos = pos
|
||||
}
|
||||
}
|
||||
if start_pos < len(text) {
|
||||
yield(text[start_pos:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func SplitIntoGraphemes(text string) []string {
|
||||
ans := make([]string, 0, len(text))
|
||||
for t := range IteratorOverGraphemes(text) {
|
||||
ans = append(ans, t)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (s *GraphemeSegmentationResult) Reset() {
|
||||
*s = 0
|
||||
}
|
||||
|
||||
func (s GraphemeSegmentationResult) Step(ch CharProps) GraphemeSegmentationResult {
|
||||
key := grapheme_segmentation_key(s, ch)
|
||||
return graphemesegmentationresult_for(key)
|
||||
}
|
||||
|
||||
func Runewidth(code rune) int {
|
||||
return CharPropsFor(code).Width()
|
||||
}
|
||||
|
||||
func IsEmojiPresentationBase(code rune) bool {
|
||||
return CharPropsFor(code).Is_emoji_presentation_base() == 1
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
_ "embed"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestSplitIntoGraphemes(t *testing.T) {
|
||||
var m = map[string][]string{
|
||||
" \u0308 ": {" \u0308", " "},
|
||||
"abc": {"a", "b", "c"},
|
||||
}
|
||||
for text, expected := range m {
|
||||
if diff := cmp.Diff(expected, SplitIntoGraphemes(text)); diff != "" {
|
||||
t.Fatalf("Failed to split %#v into graphemes: %s", text, diff)
|
||||
}
|
||||
}
|
||||
tests, err := kitty.LoadGraphemeBreakTests()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, x := range tests {
|
||||
text := strings.Join(x.Data, "")
|
||||
actual := SplitIntoGraphemes(text)
|
||||
if diff := cmp.Diff(x.Data, actual); diff != "" {
|
||||
t.Fatalf("Failed test #%d: split %#v into graphemes (%s): %s", i, text, x.Comment, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type parser_state uint8
|
||||
type csi_state uint8
|
||||
type csi_char_type uint8
|
||||
|
||||
var bracketed_paste_start = []byte{'2', '0', '0', '~'}
|
||||
|
||||
const (
|
||||
normal parser_state = iota
|
||||
esc
|
||||
csi
|
||||
st
|
||||
st_or_bel
|
||||
esc_st
|
||||
c1_st
|
||||
bracketed_paste
|
||||
)
|
||||
|
||||
const (
|
||||
parameter csi_state = iota
|
||||
intermediate
|
||||
)
|
||||
|
||||
const (
|
||||
unknown_csi_char csi_char_type = iota
|
||||
parameter_csi_char
|
||||
intermediate_csi_char
|
||||
final_csi_char
|
||||
)
|
||||
|
||||
type EscapeCodeParser struct {
|
||||
state parser_state
|
||||
utf8_state, utf8_codep utils.UTF8State
|
||||
csi_state csi_state
|
||||
current_buffer []byte
|
||||
bracketed_paste_buffer []utils.UTF8State
|
||||
current_callback func([]byte) error
|
||||
|
||||
ReplaceInvalidUtf8Bytes bool
|
||||
|
||||
// Callbacks
|
||||
HandleRune func(rune) error
|
||||
HandleEndOfBracketedPaste func() error
|
||||
HandleCSI func([]byte) error
|
||||
HandleOSC func([]byte) error
|
||||
HandleDCS func([]byte) error
|
||||
HandlePM func([]byte) error
|
||||
HandleSOS func([]byte) error
|
||||
HandleAPC func([]byte) error
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) InBracketedPaste() bool { return self.state == bracketed_paste }
|
||||
|
||||
func (self *EscapeCodeParser) ParseString(s string) error {
|
||||
return self.Parse(utils.UnsafeStringToBytes(s))
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) ParseByte(b byte) error {
|
||||
switch self.state {
|
||||
case normal, bracketed_paste:
|
||||
prev_utf8_state := self.utf8_state
|
||||
switch utils.DecodeUtf8(&self.utf8_state, &self.utf8_codep, b) {
|
||||
case utils.UTF8_ACCEPT:
|
||||
err := self.dispatch_char(self.utf8_codep)
|
||||
if err != nil {
|
||||
self.reset_state()
|
||||
return err
|
||||
}
|
||||
case utils.UTF8_REJECT:
|
||||
self.utf8_state = utils.UTF8_ACCEPT
|
||||
if prev_utf8_state != utils.UTF8_ACCEPT {
|
||||
// reparse this byte with state set to UTF8_ACCEPT
|
||||
return self.ParseByte(b)
|
||||
}
|
||||
if self.ReplaceInvalidUtf8Bytes {
|
||||
err := self.dispatch_char(utils.UTF8State(0xfffd))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
err := self.dispatch_byte(b)
|
||||
if err != nil {
|
||||
self.reset_state()
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) Parse(data []byte) error {
|
||||
for _, b := range data {
|
||||
err := self.ParseByte(b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) Reset() {
|
||||
self.reset_state()
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) write_ch(ch byte) {
|
||||
self.current_buffer = append(self.current_buffer, ch)
|
||||
}
|
||||
|
||||
func csi_type(ch byte) csi_char_type {
|
||||
if (0x30 <= ch && ch <= 0x3f) || ch == '-' {
|
||||
return parameter_csi_char
|
||||
}
|
||||
if 0x40 <= ch && ch <= 0x7E {
|
||||
return final_csi_char
|
||||
}
|
||||
if 0x20 <= ch && ch <= 0x2F {
|
||||
return intermediate_csi_char
|
||||
}
|
||||
return unknown_csi_char
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) reset_state() {
|
||||
self.current_buffer = self.current_buffer[:0]
|
||||
self.bracketed_paste_buffer = self.bracketed_paste_buffer[:0]
|
||||
self.state = normal
|
||||
self.utf8_state = utils.UTF8_ACCEPT
|
||||
self.utf8_codep = utils.UTF8_ACCEPT
|
||||
self.current_callback = nil
|
||||
self.csi_state = parameter
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) dispatch_esc_code() error {
|
||||
if self.state == csi && bytes.Equal(self.current_buffer, bracketed_paste_start) {
|
||||
self.reset_state()
|
||||
self.state = bracketed_paste
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
if self.current_callback != nil {
|
||||
err = self.current_callback(self.current_buffer)
|
||||
}
|
||||
self.reset_state()
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) invalid_escape_code() {
|
||||
self.reset_state()
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) dispatch_rune(ch utils.UTF8State) error {
|
||||
if self.HandleRune != nil {
|
||||
return self.HandleRune(rune(ch))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) bp_buffer_equals(chars []utils.UTF8State) bool {
|
||||
if len(self.bracketed_paste_buffer) != len(chars) {
|
||||
return false
|
||||
}
|
||||
for i, q := range chars {
|
||||
if self.bracketed_paste_buffer[i] != q {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) dispatch_char(ch utils.UTF8State) error {
|
||||
if self.state == bracketed_paste {
|
||||
dispatch := func() error {
|
||||
if len(self.bracketed_paste_buffer) > 0 {
|
||||
for _, c := range self.bracketed_paste_buffer {
|
||||
err := self.dispatch_rune(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
self.bracketed_paste_buffer = self.bracketed_paste_buffer[:0]
|
||||
}
|
||||
return self.dispatch_rune(ch)
|
||||
}
|
||||
handle_ch := func(chars ...utils.UTF8State) error {
|
||||
if self.bp_buffer_equals(chars) {
|
||||
self.bracketed_paste_buffer = append(self.bracketed_paste_buffer, ch)
|
||||
if self.bracketed_paste_buffer[len(self.bracketed_paste_buffer)-1] == '~' {
|
||||
self.reset_state()
|
||||
if self.HandleEndOfBracketedPaste != nil {
|
||||
if err := self.HandleEndOfBracketedPaste(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
return dispatch()
|
||||
}
|
||||
}
|
||||
switch ch {
|
||||
case 0x1b:
|
||||
return handle_ch()
|
||||
case '[':
|
||||
return handle_ch(0x1b)
|
||||
case '2':
|
||||
return handle_ch(0x1b, '[')
|
||||
case '0':
|
||||
return handle_ch(0x1b, '[', '2')
|
||||
case '1':
|
||||
return handle_ch(0x1b, '[', '2', '0')
|
||||
case '~':
|
||||
return handle_ch(0x1b, '[', '2', '0', '1')
|
||||
default:
|
||||
return dispatch()
|
||||
}
|
||||
} // end self.state == bracketed_paste
|
||||
|
||||
switch ch {
|
||||
case 0x1b:
|
||||
self.state = esc
|
||||
case 0x90:
|
||||
self.state = st
|
||||
self.current_callback = self.HandleDCS
|
||||
case 0x9b:
|
||||
self.state = csi
|
||||
self.current_callback = self.HandleCSI
|
||||
case 0x9d:
|
||||
self.state = st_or_bel
|
||||
self.current_callback = self.HandleOSC
|
||||
case 0x98:
|
||||
self.state = st
|
||||
self.current_callback = self.HandleSOS
|
||||
case 0x9e:
|
||||
self.state = st
|
||||
self.current_callback = self.HandlePM
|
||||
case 0x9f:
|
||||
self.state = st
|
||||
self.current_callback = self.HandleAPC
|
||||
default:
|
||||
return self.dispatch_rune(ch)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *EscapeCodeParser) dispatch_byte(ch byte) error {
|
||||
switch self.state {
|
||||
case esc:
|
||||
switch ch {
|
||||
case 'P':
|
||||
self.state = st
|
||||
self.current_callback = self.HandleDCS
|
||||
case '[':
|
||||
self.state = csi
|
||||
self.csi_state = parameter
|
||||
self.current_callback = self.HandleCSI
|
||||
case ']':
|
||||
self.state = st_or_bel
|
||||
self.current_callback = self.HandleOSC
|
||||
case '^':
|
||||
self.state = st
|
||||
self.current_callback = self.HandlePM
|
||||
case '_':
|
||||
self.state = st
|
||||
self.current_callback = self.HandleAPC
|
||||
case 'D', 'E', 'H', 'M', 'N', 'O', 'Z', '6', '7', '8', '9', '=', '>', 'F', 'c', 'l', 'm', 'n', 'o', '|', '}', '~':
|
||||
default:
|
||||
// we drop this dangling Esc and reparse the byte after the esc
|
||||
self.reset_state()
|
||||
return self.ParseByte(ch)
|
||||
}
|
||||
case csi:
|
||||
self.write_ch(ch)
|
||||
switch self.csi_state {
|
||||
case parameter:
|
||||
switch csi_type(ch) {
|
||||
case intermediate_csi_char:
|
||||
self.csi_state = intermediate
|
||||
case final_csi_char:
|
||||
return self.dispatch_esc_code()
|
||||
case unknown_csi_char:
|
||||
self.invalid_escape_code()
|
||||
}
|
||||
case intermediate:
|
||||
switch csi_type(ch) {
|
||||
case parameter_csi_char, unknown_csi_char:
|
||||
self.invalid_escape_code()
|
||||
case final_csi_char:
|
||||
return self.dispatch_esc_code()
|
||||
}
|
||||
}
|
||||
case st_or_bel:
|
||||
if ch == 0x7 {
|
||||
return self.dispatch_esc_code()
|
||||
}
|
||||
fallthrough
|
||||
case st:
|
||||
if ch == 0x1b {
|
||||
self.state = esc_st
|
||||
} else if ch == 0xc2 {
|
||||
self.state = c1_st
|
||||
} else {
|
||||
self.write_ch(ch)
|
||||
}
|
||||
case esc_st:
|
||||
if ch == '\\' {
|
||||
return self.dispatch_esc_code()
|
||||
} else {
|
||||
self.state = st
|
||||
self.write_ch(0x1b)
|
||||
if ch != 0x1b {
|
||||
self.write_ch(ch)
|
||||
}
|
||||
}
|
||||
case c1_st:
|
||||
if ch == 0x9c {
|
||||
return self.dispatch_esc_code()
|
||||
} else {
|
||||
self.state = st
|
||||
self.write_ch(0xc2)
|
||||
self.write_ch(ch)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEscapeCodeParsing(t *testing.T) {
|
||||
type test_parse_collection struct {
|
||||
actual, expected string
|
||||
}
|
||||
var d test_parse_collection
|
||||
|
||||
add := func(prefix string, b []byte) error {
|
||||
d.actual += "\n" + prefix + ": " + string(b)
|
||||
return nil
|
||||
}
|
||||
|
||||
var test_parser = EscapeCodeParser{
|
||||
HandleCSI: func(b []byte) error { return add("CSI", b) },
|
||||
HandleOSC: func(b []byte) error { return add("OSC", b) },
|
||||
HandleDCS: func(b []byte) error { return add("DCS", b) },
|
||||
HandleSOS: func(b []byte) error { return add("SOS", b) },
|
||||
HandlePM: func(b []byte) error { return add("PM", b) },
|
||||
HandleAPC: func(b []byte) error { return add("APC", b) },
|
||||
HandleRune: func(b rune) error { return add("CH", []byte(string(b))) },
|
||||
}
|
||||
|
||||
reset_test_parser := func() {
|
||||
test_parser.Reset()
|
||||
d = test_parse_collection{}
|
||||
}
|
||||
|
||||
check_test_result := func(raw string) {
|
||||
if d.actual != d.expected {
|
||||
t.Fatalf("parsing: %#v actual != expected: %#v != %#v", raw, string(d.actual), string(d.expected))
|
||||
}
|
||||
}
|
||||
|
||||
test := func(raw string, expected string) {
|
||||
reset_test_parser()
|
||||
d.expected = "\n" + expected
|
||||
test_parser.Parse([]byte(raw))
|
||||
check_test_result(raw)
|
||||
}
|
||||
|
||||
test("\x1b[31m\xc2\x9bm", "CSI: 31m\nCSI: m")
|
||||
test("\x1b[-31m\xc2\x9bm", "CSI: -31m\nCSI: m")
|
||||
test("ab\nc", "CH: a\nCH: b\nCH: \n\nCH: c")
|
||||
test("a\x1b[200m\x1b[mb\x1b[5:3;2;4~", "CH: a\nCSI: 200m\nCSI: m\nCH: b\nCSI: 5:3;2;4~")
|
||||
test("\x1b[200~a\x1b[201m\x1b[201~\x1b[x", "CH: a\nCH: \x1b\nCH: [\nCH: 2\nCH: 0\nCH: 1\nCH: m\nCSI: x")
|
||||
test("a\x1bPb\x1b\x1bc\x1b\\d", "CH: a\nDCS: b\x1bc\nCH: d")
|
||||
test("a\x1b_b\x1b\x1b\x1bc\x1b\\d", "CH: a\nAPC: b\x1b\x1bc\nCH: d")
|
||||
test("\x1b]X\x07\x1b]X\x1b\x07\x1b\\", "OSC: X\nOSC: X\x1b\x07")
|
||||
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type current_cell struct {
|
||||
head, tail, width int
|
||||
}
|
||||
|
||||
type forward_iterator struct {
|
||||
width_iter *WCWidthIterator
|
||||
current_cell current_cell
|
||||
cell_num, pos int
|
||||
}
|
||||
|
||||
type reverse_iterator struct {
|
||||
cells []string
|
||||
pos int
|
||||
}
|
||||
|
||||
func (self *forward_iterator) reset() {
|
||||
self.width_iter.Reset()
|
||||
self.current_cell = current_cell{}
|
||||
self.pos = 0
|
||||
self.cell_num = 0
|
||||
}
|
||||
|
||||
type CellIterator struct {
|
||||
text, current string
|
||||
forward_iter forward_iterator
|
||||
reverse_iter reverse_iterator
|
||||
}
|
||||
|
||||
func NewCellIterator(text string) *CellIterator {
|
||||
ans := &CellIterator{text: text}
|
||||
ans.forward_iter.width_iter = CreateWCWidthIterator()
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *CellIterator) GotoStart() *CellIterator {
|
||||
self.forward_iter.reset()
|
||||
self.reverse_iter.pos = -1
|
||||
self.current = ""
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *CellIterator) GotoEnd() *CellIterator {
|
||||
self.current = ""
|
||||
self.reverse_iter.pos = len(self.reverse_iter.cells)
|
||||
self.forward_iter.pos = len(self.text)
|
||||
self.forward_iter.cell_num = len(self.text) + 1
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *CellIterator) Current() string { return self.current }
|
||||
|
||||
func (self *CellIterator) forward_one_rune() bool {
|
||||
for self.forward_iter.pos < len(self.text) {
|
||||
rune_count_before := self.forward_iter.width_iter.rune_count
|
||||
self.forward_iter.width_iter.ParseByte(self.text[self.forward_iter.pos])
|
||||
self.forward_iter.pos++
|
||||
if self.forward_iter.width_iter.rune_count != rune_count_before {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *CellIterator) Forward() (has_more bool) {
|
||||
if self.reverse_iter.cells != nil {
|
||||
if self.reverse_iter.pos < len(self.reverse_iter.cells) {
|
||||
self.reverse_iter.pos++
|
||||
}
|
||||
if self.reverse_iter.pos >= len(self.reverse_iter.cells) {
|
||||
self.current = ""
|
||||
return false
|
||||
}
|
||||
self.current = self.reverse_iter.cells[self.reverse_iter.pos]
|
||||
return true
|
||||
}
|
||||
fi := &self.forward_iter
|
||||
cc := &fi.current_cell
|
||||
for {
|
||||
width_before := fi.width_iter.current_width
|
||||
pos_before := fi.pos
|
||||
if !self.forward_one_rune() {
|
||||
break
|
||||
}
|
||||
change_in_width := fi.width_iter.current_width - width_before
|
||||
cc.tail = fi.pos
|
||||
if cc.width > 0 && change_in_width > 0 {
|
||||
self.current = self.text[cc.head:pos_before]
|
||||
cc.width = change_in_width
|
||||
cc.head = pos_before
|
||||
fi.cell_num++
|
||||
return true
|
||||
}
|
||||
cc.width += change_in_width
|
||||
}
|
||||
if cc.tail > cc.head {
|
||||
self.current = self.text[cc.head:cc.tail]
|
||||
cc.head = fi.pos
|
||||
cc.tail = fi.pos
|
||||
cc.width = 0
|
||||
fi.cell_num++
|
||||
return true
|
||||
}
|
||||
self.current = ""
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *CellIterator) Backward() (has_more bool) {
|
||||
ri := &self.reverse_iter
|
||||
if ri.cells == nil {
|
||||
current_cell_num := self.forward_iter.cell_num
|
||||
cells := make([]string, 0, len(self.text))
|
||||
self.GotoStart()
|
||||
for self.Forward() {
|
||||
cells = append(cells, self.current)
|
||||
}
|
||||
ri.pos = min(max(-1, current_cell_num-1), len(cells))
|
||||
ri.cells = cells
|
||||
}
|
||||
if ri.pos > -1 {
|
||||
ri.pos--
|
||||
}
|
||||
if ri.pos < 0 {
|
||||
self.current = ""
|
||||
return false
|
||||
}
|
||||
self.current = ri.cells[ri.pos]
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type truncate_error struct {
|
||||
pos, width int
|
||||
}
|
||||
|
||||
func (self *truncate_error) Error() string {
|
||||
return fmt.Sprint("Truncation at:", self.pos, " with width:", self.width)
|
||||
}
|
||||
|
||||
type truncate_iterator struct {
|
||||
w WCWidthIterator
|
||||
|
||||
pos, limit int
|
||||
limit_exceeded_at *truncate_error
|
||||
}
|
||||
|
||||
func (self *truncate_iterator) handle_csi(csi []byte) error {
|
||||
if len(csi) > 1 && csi[len(csi)-1] == 'b' { // repeat previous char escape code
|
||||
num_string := utils.UnsafeBytesToString(csi[:len(csi)-1])
|
||||
n, err := strconv.Atoi(num_string)
|
||||
if err == nil && n > 0 {
|
||||
width_before_repeat := self.w.current_width
|
||||
for ; n > 0; n-- {
|
||||
self.w.handle_rune(self.w.prev_ch)
|
||||
if self.w.current_width > self.limit {
|
||||
return &truncate_error{pos: self.pos, width: width_before_repeat}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.pos += len(csi) + 2
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *truncate_iterator) handle_st_terminated_escape_code(body []byte) error {
|
||||
self.pos += len(body) + 4
|
||||
return nil
|
||||
}
|
||||
|
||||
func KeepOnlyCSI(text string, output io.Writer) {
|
||||
var w WCWidthIterator
|
||||
w.parser.HandleCSI = func(data []byte) (err error) {
|
||||
_, err = output.Write([]byte{'\x1b', '['})
|
||||
if err == nil {
|
||||
_, err = output.Write(data)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func create_truncate_iterator() *truncate_iterator {
|
||||
var ans truncate_iterator
|
||||
ans.w.parser.HandleRune = ans.handle_rune
|
||||
ans.w.parser.HandleCSI = ans.handle_csi
|
||||
ans.w.parser.HandleOSC = ans.handle_st_terminated_escape_code
|
||||
ans.w.parser.HandleAPC = ans.handle_st_terminated_escape_code
|
||||
ans.w.parser.HandleDCS = ans.handle_st_terminated_escape_code
|
||||
ans.w.parser.HandlePM = ans.handle_st_terminated_escape_code
|
||||
ans.w.parser.HandleSOS = ans.handle_st_terminated_escape_code
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *truncate_iterator) handle_rune(ch rune) error {
|
||||
width := self.w.current_width
|
||||
self.w.handle_rune(ch)
|
||||
if self.limit_exceeded_at != nil {
|
||||
if self.w.current_width <= self.limit { // emoji variation selectors can cause width to decrease
|
||||
return &truncate_error{pos: self.pos + len(string(ch)), width: self.w.current_width}
|
||||
}
|
||||
return self.limit_exceeded_at
|
||||
}
|
||||
if self.w.current_width > self.limit {
|
||||
self.limit_exceeded_at = &truncate_error{pos: self.pos, width: width}
|
||||
}
|
||||
self.pos += len(string(ch))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *truncate_iterator) parse(b []byte) (ans int, width int) {
|
||||
err := self.w.parser.Parse(b)
|
||||
var te *truncate_error
|
||||
if err != nil && errors.As(err, &te) {
|
||||
return te.pos, te.width
|
||||
}
|
||||
if self.limit_exceeded_at != nil {
|
||||
return self.limit_exceeded_at.pos, self.limit_exceeded_at.width
|
||||
}
|
||||
return len(b), self.w.current_width
|
||||
}
|
||||
|
||||
func TruncateToVisualLengthWithWidth(text string, length int) (truncated string, width_of_truncated int) {
|
||||
if length < 1 {
|
||||
return text[:0], 0
|
||||
}
|
||||
t := create_truncate_iterator()
|
||||
t.limit = length
|
||||
t.limit_exceeded_at = nil
|
||||
t.w.current_width = 0
|
||||
truncate_point, width := t.parse(utils.UnsafeStringToBytes(text))
|
||||
return text[:truncate_point], width
|
||||
}
|
||||
|
||||
func TruncateToVisualLength(text string, length int) string {
|
||||
ans, _ := TruncateToVisualLengthWithWidth(text, length)
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type WCWidthIterator struct {
|
||||
prev_ch rune
|
||||
prev_width, current_width int
|
||||
seg GraphemeSegmentationResult
|
||||
can_combine bool
|
||||
parser EscapeCodeParser
|
||||
rune_count uint
|
||||
}
|
||||
|
||||
func CreateWCWidthIterator() *WCWidthIterator {
|
||||
var ans WCWidthIterator
|
||||
ans.parser.HandleRune = ans.handle_rune
|
||||
ans.parser.HandleCSI = ans.handle_csi
|
||||
ans.parser.HandleOSC = ans.handle_st_terminated
|
||||
ans.parser.HandleDCS = ans.handle_st_terminated
|
||||
ans.parser.HandlePM = ans.handle_st_terminated
|
||||
ans.parser.HandleSOS = ans.handle_st_terminated
|
||||
ans.parser.HandleAPC = ans.handle_st_terminated
|
||||
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) Reset() {
|
||||
self.prev_ch = 0
|
||||
self.prev_width = 0
|
||||
self.current_width = 0
|
||||
self.rune_count = 0
|
||||
self.can_combine = false
|
||||
self.seg = 0
|
||||
self.parser.Reset()
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) handle_csi(csi []byte) error {
|
||||
if len(csi) > 1 && csi[len(csi)-1] == 'b' {
|
||||
num_string := utils.UnsafeBytesToString(csi[:len(csi)-1])
|
||||
n, err := strconv.Atoi(num_string)
|
||||
if err == nil && n > 0 {
|
||||
for range n {
|
||||
err = self.handle_rune(self.prev_ch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.can_combine = false
|
||||
self.seg = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) handle_st_terminated(data []byte) error {
|
||||
self.can_combine = false
|
||||
self.seg = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) handle_rune(ch rune) error {
|
||||
self.rune_count += 1
|
||||
cp := CharPropsFor(ch)
|
||||
self.seg = self.seg.Step(cp)
|
||||
if self.can_combine && self.seg.Add_to_current_cell() == 1 {
|
||||
switch ch {
|
||||
case 0xfe0f:
|
||||
if CharPropsFor(self.prev_ch).Is_emoji_presentation_base() == 1 && self.prev_width == 1 {
|
||||
self.current_width += 1
|
||||
self.prev_width = 2
|
||||
}
|
||||
case 0xfe0e:
|
||||
if CharPropsFor(self.prev_ch).Is_emoji_presentation_base() == 1 && self.prev_width == 2 {
|
||||
self.current_width -= 1
|
||||
self.prev_width = 1
|
||||
}
|
||||
default:
|
||||
// Thai/Lao SARA AM: a SpacingMark with non-zero width widens a narrow base cell
|
||||
if cp.Grapheme_break() == uint8(GBP_SpacingMark) && cp.Width() > 0 && self.prev_width == 1 {
|
||||
self.current_width += 1
|
||||
self.prev_width = 2
|
||||
}
|
||||
}
|
||||
} else {
|
||||
width := cp.Width()
|
||||
switch width {
|
||||
case -1:
|
||||
case 0:
|
||||
self.prev_width = 0
|
||||
case 2:
|
||||
self.prev_width = 2
|
||||
default:
|
||||
self.prev_width = 1
|
||||
}
|
||||
self.current_width += self.prev_width
|
||||
self.can_combine = true
|
||||
}
|
||||
self.prev_ch = ch
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) ParseByte(b byte) (ans int) {
|
||||
self.parser.ParseByte(b)
|
||||
return self.current_width
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) Parse(b []byte) (ans int) {
|
||||
self.current_width = 0
|
||||
self.parser.Parse(b)
|
||||
return self.current_width
|
||||
}
|
||||
|
||||
func (self *WCWidthIterator) CurrentWidth() int {
|
||||
return self.current_width
|
||||
}
|
||||
|
||||
func Stringwidth(text string) int {
|
||||
w := CreateWCWidthIterator()
|
||||
return w.Parse(utils.UnsafeStringToBytes(text))
|
||||
}
|
||||
|
||||
func StripEscapeCodes(text string) string {
|
||||
out := strings.Builder{}
|
||||
out.Grow(len(text))
|
||||
|
||||
p := EscapeCodeParser{}
|
||||
p.HandleRune = func(ch rune) error {
|
||||
out.WriteRune(ch)
|
||||
return nil
|
||||
}
|
||||
p.ParseString(text)
|
||||
return out.String()
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package wcswidth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
func TestNonZeroWidthSpacingMarks(t *testing.T) {
|
||||
// The cell a SpacingMark with non-zero width combines into is widened, both here and
|
||||
// in kitty's C code. Only U+0E33 and U+0EB3 have that combination of properties, which
|
||||
// docs/text-sizing-protocol.rst specifies, so guard against a Unicode data refresh
|
||||
// silently changing the set.
|
||||
expected := map[rune]bool{0x0e33: true, 0x0eb3: true}
|
||||
for r := rune(0); r <= MAX_UNICODE; r++ {
|
||||
cp := CharPropsFor(r)
|
||||
if cp.Grapheme_break() == uint8(GBP_SpacingMark) && cp.Width() > 0 {
|
||||
if !expected[r] {
|
||||
t.Fatalf("U+%04X is an unexpected non-zero width SpacingMark of width: %d", r, cp.Width())
|
||||
}
|
||||
delete(expected, r)
|
||||
}
|
||||
}
|
||||
for r := range expected {
|
||||
t.Fatalf("U+%04X is no longer a non-zero width SpacingMark", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWCSWidth(t *testing.T) {
|
||||
|
||||
wcswidth := func(text string, expected int) {
|
||||
if w := Stringwidth(text); w != expected {
|
||||
t.Fatalf("The width for %#v was %d instead of %d", text, w, expected)
|
||||
}
|
||||
}
|
||||
wcwidth := func(text string, widths ...int) {
|
||||
for i, q := range []rune(text) {
|
||||
if w := Runewidth(q); w != widths[i] {
|
||||
t.Fatalf("The width of the char: U+%x was %d instead of %d", q, w, widths[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
wcwidth("a1\000コニチ ✔", 1, 1, 0, 2, 2, 2, 1, 1)
|
||||
wcswidth("a\033[2mb", 2)
|
||||
wcswidth("\033a\033[2mb", 2)
|
||||
wcswidth("a\033]8;id=moo;https://foo\033\\a", 2)
|
||||
wcswidth("a\033x", 2)
|
||||
wcswidth("\u2716\u2716\ufe0f\U0001f337", 5)
|
||||
wcswidth("\u25b6\ufe0f", 2)
|
||||
wcswidth("\U0001f610\ufe0e", 1)
|
||||
wcswidth("\U0001f1e6a", 3)
|
||||
wcswidth("\U0001F1E6a\U0001F1E8a", 6)
|
||||
wcswidth("\U0001F1E6\U0001F1E8a", 3)
|
||||
wcswidth("\U0001F1E6\U0001F1E8\U0001F1E6", 4)
|
||||
wcswidth("a\u00adb", 2)
|
||||
// Thai/Lao SARA AM is a SpacingMark with width 1, it widens the cell it combines into
|
||||
wcswidth("จำ", 2)
|
||||
wcswidth("ำ", 1)
|
||||
wcswidth("กิ", 1)
|
||||
wcswidth("จำำ", 2)
|
||||
wcswidth("ກຳ", 2)
|
||||
wcswidth("a\x1b[22bcd", 25)
|
||||
// Flags individually and together
|
||||
wcwidth("\U0001f1ee\U0001f1f3", 2, 2)
|
||||
wcswidth("\U0001f1ee\U0001f1f3", 2)
|
||||
|
||||
truncate := func(text string, length int, expected string, expected_width int) {
|
||||
actual, actual_width := TruncateToVisualLengthWithWidth(text, length)
|
||||
if actual != expected {
|
||||
t.Fatalf("Failed to truncate \"%s\" to %d\nExpected: %#v\nActual: %#v", text, length, expected, actual)
|
||||
}
|
||||
if actual_width != expected_width {
|
||||
t.Fatalf("Failed to truncate with width \"%s\" to %d\nExpected: %d\nActual: %d", text, length, expected_width, actual_width)
|
||||
}
|
||||
}
|
||||
truncate("abc", 4, "abc", 3)
|
||||
truncate("abc", 3, "abc", 3)
|
||||
truncate("abc", 2, "ab", 2)
|
||||
truncate("abc", 0, "", 0)
|
||||
truncate("a🌷", 2, "a", 1)
|
||||
truncate("a🌷", 3, "a🌷", 3)
|
||||
truncate("a🌷b", 3, "a🌷", 3)
|
||||
truncate("a🌷b", 4, "a🌷b", 4)
|
||||
truncate("a🌷\ufe0e", 2, "a🌷\ufe0e", 2)
|
||||
truncate("a🌷\ufe0eb", 3, "a🌷\ufe0eb", 3)
|
||||
truncate("a\x1b[31mb", 2, "a\x1b[31mb", 2)
|
||||
truncate("a\x1b[7bb", 2, "a", 1)
|
||||
truncate("a\x1b[3bbc", 5, "a\x1b[3bb", 5)
|
||||
}
|
||||
|
||||
func TestCellIterator(t *testing.T) {
|
||||
f := func(text string, expected ...string) {
|
||||
ci := NewCellIterator(text)
|
||||
actual := make([]string, 0, len(expected))
|
||||
for ci.Forward() {
|
||||
actual = append(actual, ci.Current())
|
||||
}
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Failed forward iteration for string: %#v\n%s", text, diff)
|
||||
}
|
||||
}
|
||||
|
||||
f("abc", "a", "b", "c")
|
||||
f("a🌷ò", "a", "🌷", "ò")
|
||||
f("a🌷\ufe0eò", "a", "🌷\ufe0e", "ò")
|
||||
f("òne", "ò", "n", "e")
|
||||
|
||||
r := func(text string, expected ...string) {
|
||||
ci := NewCellIterator(text).GotoEnd()
|
||||
actual := make([]string, 0, len(expected))
|
||||
for ci.Backward() {
|
||||
actual = append(actual, ci.Current())
|
||||
}
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Failed reverse iteration for string: %#v\n%s", text, diff)
|
||||
}
|
||||
}
|
||||
|
||||
r("abc", "c", "b", "a")
|
||||
r("a🌷ò", "ò", "🌷", "a")
|
||||
r("òne", "e", "n", "ò")
|
||||
|
||||
ci := NewCellIterator("123")
|
||||
ci.Forward()
|
||||
ci.Forward()
|
||||
ci.Forward()
|
||||
ci.Backward()
|
||||
if ci.Current() != "2" {
|
||||
t.Fatalf("switching to backward failed, %#v != %#v", "2", ci.Current())
|
||||
}
|
||||
ci.Backward()
|
||||
if ci.Current() != "1" {
|
||||
t.Fatalf("switching to backward failed, %#v != %#v", "1", ci.Current())
|
||||
}
|
||||
ci.Forward()
|
||||
if ci.Current() != "2" {
|
||||
t.Fatalf("switching to forward failed, %#v != %#v", "2", ci.Current())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user