From 6ec60cf9d8b9656468254f4099eded5a2304b4c4 Mon Sep 17 00:00:00 2001 From: Joe Lim <50560759+joelim-work@users.noreply.github.com> Date: Wed, 4 Mar 2026 17:02:26 +1100 Subject: [PATCH] chore!: change to use v3 of Tcell (#2286) * Remove SGR 8 * Remove `` * Migrate to v3 of Tcell * Refactor key handling functionality * Bump Tcell version * Replace `SetContent` API with `Put` API * bump dependencies * Use new color package * Fix cursor position for grapheme clusters * Some editing fixes to support grapheme clusters * Ignore carriage return when printing * Move grapheme cluster handling into misc.go * Fix length of filenames containing emoji * Use slices.Concat * Use `string` instead of `[]rune` for `win.print` * Add note about modifier limitations * Update `CHANGELOG.md` --- CHANGELOG.md | 2 + app.go | 2 +- client.go | 2 +- colors.go | 2 +- colors_test.go | 2 +- doc.md | 10 +- doc.txt | 10 +- eval.go | 20 ++- go.mod | 8 +- go.sum | 12 +- icons.go | 2 +- key.go | 228 ++++++++++++++++++++++++ key_test.go | 46 +++++ lf.1 | 11 +- misc.go | 21 ++- misc_test.go | 36 ++++ opts.go | 70 ++++---- sixel.go | 2 +- termseq.go | 5 +- termseq_test.go | 76 ++++---- ui.go | 454 +++++++++++------------------------------------- 21 files changed, 558 insertions(+), 463 deletions(-) create mode 100644 key.go create mode 100644 key_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1abac291..c831d36c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,10 +12,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed +- The key `` has been renamed to `` for `map` keybindings (#2286). - `.Stat.DirSize` and `.Stat.DirCount` in the ruler file no longer have a pointer type, and will be set to `-1` instead of `nil` if the corresponding value cannot be determined (#2397). ### Added +- Emoji sequences containing Zero Width Joiner characters are now displayed as a single combined glyph (#2286). - A new field `.All` is added to the `ruler` file to display the number of all files (i.e. visible + hidden) in the current working directory (#2376). - A new option `numbercursorfmt` is added to further customize the appearance of line numbers (#2395). diff --git a/app.go b/app.go index a4605a3d..a8b0d979 100644 --- a/app.go +++ b/app.go @@ -268,7 +268,7 @@ func (app *app) loop() { serverChan = readExpr() } - app.ui.readExpr() + go app.ui.readEvents() if gConfigPath != "" { if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) { diff --git a/client.go b/client.go index b1119717..add2c227 100644 --- a/client.go +++ b/client.go @@ -11,7 +11,7 @@ import ( "sync" "time" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) type State struct { diff --git a/colors.go b/colors.go index 0decf846..d4463145 100644 --- a/colors.go +++ b/colors.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) type styleMap struct { diff --git a/colors_test.go b/colors_test.go index 9afc7536..1dddabc8 100644 --- a/colors_test.go +++ b/colors_test.go @@ -3,7 +3,7 @@ package main import ( "testing" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) func TestParseColor(t *testing.T) { diff --git a/doc.md b/doc.md index 43005218..b222a742 100644 --- a/doc.md +++ b/doc.md @@ -236,7 +236,7 @@ The following Command-line mode commands are provided by lf: cmd-home (default '' and '') cmd-end (default '' and '') cmd-delete (default '' and '') - cmd-delete-back (default '' and '') + cmd-delete-back (default '') cmd-delete-home (default '') cmd-delete-end (default '') cmd-delete-unix-word (default '') @@ -246,7 +246,7 @@ The following Command-line mode commands are provided by lf: cmd-word (default '') cmd-word-back (default '') cmd-delete-word (default '') - cmd-delete-word-back (default '' and '') + cmd-delete-word-back (default '') cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') @@ -794,7 +794,7 @@ Move the cursor to the beginning/end of the line. Delete the next character. -## cmd-delete-back (default `` and ``) +## cmd-delete-back (default ``) Delete the previous character. When at the beginning of a prompt, returns either to Normal mode or to `:` mode. @@ -823,7 +823,7 @@ Move the cursor by one word in the forward/backward direction. Delete the next word in the forward direction. -## cmd-delete-word-back (default `` and ``) +## cmd-delete-word-back (default ``) Delete the previous word in the backward direction. @@ -1584,6 +1584,8 @@ It is possible to combine special keys with modifiers: map down +Combining multiple modifiers (e.g. `Ctrl+Shift+Space`) is not supported. + WARNING: Some key combinations will likely be intercepted by your OS, window manager, or terminal. Other key combinations cannot be recognized by lf due to the way terminals work (e.g. `Ctrl+h` combination sends a backspace key instead). The easiest way to find out the name of a key combination and whether it will work on your system is to press the key while lf is running and read the name from the `unknown mapping` error. diff --git a/doc.txt b/doc.txt index 83ca82bb..1a22011d 100644 --- a/doc.txt +++ b/doc.txt @@ -248,7 +248,7 @@ The following Command-line mode commands are provided by lf: cmd-home (default '' and '') cmd-end (default '' and '') cmd-delete (default '' and '') - cmd-delete-back (default '' and '') + cmd-delete-back (default '') cmd-delete-home (default '') cmd-delete-end (default '') cmd-delete-unix-word (default '') @@ -258,7 +258,7 @@ The following Command-line mode commands are provided by lf: cmd-word (default '') cmd-word-back (default '') cmd-delete-word (default '') - cmd-delete-word-back (default '' and '') + cmd-delete-word-back (default '') cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') @@ -845,7 +845,7 @@ cmd-delete (default and ) Delete the next character. -cmd-delete-back (default and ) +cmd-delete-back (default ) Delete the previous character. When at the beginning of a prompt, returns either to Normal mode or to : mode. @@ -874,7 +874,7 @@ cmd-delete-word (default ) Delete the next word in the forward direction. -cmd-delete-word-back (default and ) +cmd-delete-word-back (default ) Delete the previous word in the backward direction. @@ -1740,6 +1740,8 @@ It is possible to combine special keys with modifiers: map down +Combining multiple modifiers (e.g. Ctrl+Shift+Space) is not supported. + WARNING: Some key combinations will likely be intercepted by your OS, window manager, or terminal. Other key combinations cannot be recognized by lf due to the way terminals work (e.g. Ctrl+h combination sends a diff --git a/eval.go b/eval.go index 4941577d..5228dbe5 100644 --- a/eval.go +++ b/eval.go @@ -14,7 +14,7 @@ import ( "unicode" "unicode/utf8" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) func applyBoolOpt(opt *bool, e *setExpr) error { @@ -1565,7 +1565,7 @@ func (e *callExpr) eval(app *app, _ []string) { } log.Println("pushing keys", e.args[0]) for _, val := range splitKeys(e.args[0]) { - app.ui.keyChan <- val + app.ui.evChan <- parseKey(val) } case "addcustominfo": var k, v string @@ -1913,14 +1913,16 @@ func (e *callExpr) eval(app *app, _ []string) { if len(app.ui.cmdAccLeft) == 0 { return } - app.ui.cmdAccRight = append([]rune{app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1]}, app.ui.cmdAccRight...) - app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] + last := lastGraphemeCluster(app.ui.cmdAccLeft) + app.ui.cmdAccRight = slices.Concat(app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-len(last):], app.ui.cmdAccRight) + app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-len(last)] case "cmd-right": if len(app.ui.cmdAccRight) == 0 { return } - app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[0]) - app.ui.cmdAccRight = app.ui.cmdAccRight[1:] + first := firstGraphemeCluster(app.ui.cmdAccRight) + app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:len(first)]...) + app.ui.cmdAccRight = app.ui.cmdAccRight[len(first):] case "cmd-home": app.ui.cmdAccRight = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) app.ui.cmdAccLeft = nil @@ -1931,7 +1933,8 @@ func (e *callExpr) eval(app *app, _ []string) { if len(app.ui.cmdAccRight) == 0 { return } - app.ui.cmdAccRight = app.ui.cmdAccRight[1:] + first := firstGraphemeCluster(app.ui.cmdAccRight) + app.ui.cmdAccRight = app.ui.cmdAccRight[len(first):] update(app) case "cmd-delete-back": if len(app.ui.cmdAccLeft) == 0 { @@ -1949,7 +1952,8 @@ func (e *callExpr) eval(app *app, _ []string) { } return } - app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] + last := lastGraphemeCluster(app.ui.cmdAccLeft) + app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-len(last)] update(app) case "cmd-delete-home": if len(app.ui.cmdAccLeft) == 0 { diff --git a/go.mod b/go.mod index d8b76683..1ec38be9 100644 --- a/go.mod +++ b/go.mod @@ -5,16 +5,16 @@ go 1.24.0 require ( github.com/djherbis/times v1.6.0 github.com/fsnotify/fsnotify v1.9.0 - github.com/gdamore/tcell/v2 v2.13.8 + github.com/gdamore/tcell/v3 v3.1.2 github.com/mattn/go-runewidth v0.0.20 + github.com/rivo/uniseg v0.4.7 golang.org/x/sys v0.41.0 golang.org/x/term v0.40.0 ) require ( - github.com/clipperhouse/uax29/v2 v2.2.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/gdamore/encoding v1.0.1 // indirect github.com/lucasb-eyer/go-colorful v1.3.0 // indirect - github.com/rivo/uniseg v0.4.7 // indirect - golang.org/x/text v0.31.0 // indirect + golang.org/x/text v0.34.0 // indirect ) diff --git a/go.sum b/go.sum index ff624b63..d65c17b4 100644 --- a/go.sum +++ b/go.sum @@ -1,13 +1,13 @@ -github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY= -github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= -github.com/gdamore/tcell/v2 v2.13.8 h1:Mys/Kl5wfC/GcC5Cx4C2BIQH9dbnhnkPgS9/wF3RlfU= -github.com/gdamore/tcell/v2 v2.13.8/go.mod h1:+Wfe208WDdB7INEtCsNrAN6O2m+wsTPk1RAovjaILlo= +github.com/gdamore/tcell/v3 v3.1.2 h1:qEaXnDaYZpCIMDfa3XFHkxrwFBINUuDiePwj39vErZ8= +github.com/gdamore/tcell/v3 v3.1.2/go.mod h1:MikpZpivMtggrw1kL999dI2VuXw6Wya4724VAh3DzIg= github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-runewidth v0.0.20 h1:WcT52H91ZUAwy8+HUkdM3THM6gXqXuLJi9O3rjcQQaQ= @@ -45,8 +45,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= diff --git a/icons.go b/icons.go index 77aadd74..525341c9 100644 --- a/icons.go +++ b/icons.go @@ -6,7 +6,7 @@ import ( "path/filepath" "strings" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) type iconDef struct { diff --git a/key.go b/key.go new file mode 100644 index 00000000..cd5a3985 --- /dev/null +++ b/key.go @@ -0,0 +1,228 @@ +package main + +import ( + "fmt" + "regexp" + "strings" + + "github.com/gdamore/tcell/v3" +) + +var gKeyVal = map[tcell.Key]string{ + tcell.KeyEnter: "", + tcell.KeyBackspace: "", + tcell.KeyTab: "", + tcell.KeyBacktab: "", + tcell.KeyEsc: "", + tcell.KeyDelete: "", + tcell.KeyInsert: "", + tcell.KeyUp: "", + tcell.KeyDown: "", + tcell.KeyLeft: "", + tcell.KeyRight: "", + tcell.KeyHome: "", + tcell.KeyEnd: "", + tcell.KeyUpLeft: "", + tcell.KeyUpRight: "", + tcell.KeyDownLeft: "", + tcell.KeyDownRight: "", + tcell.KeyCenter: "
", + tcell.KeyPgDn: "", + tcell.KeyPgUp: "", + tcell.KeyClear: "", + tcell.KeyExit: "", + tcell.KeyCancel: "", + tcell.KeyPause: "", + tcell.KeyPrint: "", + tcell.KeyF1: "", + tcell.KeyF2: "", + tcell.KeyF3: "", + tcell.KeyF4: "", + tcell.KeyF5: "", + tcell.KeyF6: "", + tcell.KeyF7: "", + tcell.KeyF8: "", + tcell.KeyF9: "", + tcell.KeyF10: "", + tcell.KeyF11: "", + tcell.KeyF12: "", + tcell.KeyF13: "", + tcell.KeyF14: "", + tcell.KeyF15: "", + tcell.KeyF16: "", + tcell.KeyF17: "", + tcell.KeyF18: "", + tcell.KeyF19: "", + tcell.KeyF20: "", + tcell.KeyF21: "", + tcell.KeyF22: "", + tcell.KeyF23: "", + tcell.KeyF24: "", + tcell.KeyF25: "", + tcell.KeyF26: "", + tcell.KeyF27: "", + tcell.KeyF28: "", + tcell.KeyF29: "", + tcell.KeyF30: "", + tcell.KeyF31: "", + tcell.KeyF32: "", + tcell.KeyF33: "", + tcell.KeyF34: "", + tcell.KeyF35: "", + tcell.KeyF36: "", + tcell.KeyF37: "", + tcell.KeyF38: "", + tcell.KeyF39: "", + tcell.KeyF40: "", + tcell.KeyF41: "", + tcell.KeyF42: "", + tcell.KeyF43: "", + tcell.KeyF44: "", + tcell.KeyF45: "", + tcell.KeyF46: "", + tcell.KeyF47: "", + tcell.KeyF48: "", + tcell.KeyF49: "", + tcell.KeyF50: "", + tcell.KeyF51: "", + tcell.KeyF52: "", + tcell.KeyF53: "", + tcell.KeyF54: "", + tcell.KeyF55: "", + tcell.KeyF56: "", + tcell.KeyF57: "", + tcell.KeyF58: "", + tcell.KeyF59: "", + tcell.KeyF60: "", + tcell.KeyF61: "", + tcell.KeyF62: "", + tcell.KeyF63: "", + tcell.KeyF64: "", + tcell.KeyCtrlA: "", + tcell.KeyCtrlB: "", + tcell.KeyCtrlC: "", + tcell.KeyCtrlD: "", + tcell.KeyCtrlE: "", + tcell.KeyCtrlF: "", + tcell.KeyCtrlG: "", + tcell.KeyCtrlJ: "", + tcell.KeyCtrlK: "", + tcell.KeyCtrlL: "", + tcell.KeyCtrlN: "", + tcell.KeyCtrlO: "", + tcell.KeyCtrlP: "", + tcell.KeyCtrlQ: "", + tcell.KeyCtrlR: "", + tcell.KeyCtrlS: "", + tcell.KeyCtrlT: "", + tcell.KeyCtrlU: "", + tcell.KeyCtrlV: "", + tcell.KeyCtrlW: "", + tcell.KeyCtrlX: "", + tcell.KeyCtrlY: "", + tcell.KeyCtrlZ: "", +} + +var gValKey map[string]tcell.Key + +func init() { + gValKey = make(map[string]tcell.Key, len(gKeyVal)) + for k, v := range gKeyVal { + gValKey[v] = k + } +} + +// for simplicity, assume there will only be one modifier (ctrl, shift or alt) +var reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`) + +func wrapModifier(s string, mod string) string { + s = strings.TrimPrefix(s, "<") + s = strings.TrimSuffix(s, ">") + return fmt.Sprintf("<%s-%s>", mod, s) +} + +func addKeyModifier(s string, mod tcell.ModMask) string { + if reModKey.MatchString(s) { + return s + } + + switch { + case mod&tcell.ModCtrl != 0: + return wrapModifier(s, "c") + case mod&tcell.ModShift != 0: + return wrapModifier(s, "s") + case mod&tcell.ModAlt != 0: + return wrapModifier(s, "a") + default: + return s + } +} + +func readKey(ev *tcell.EventKey) string { + var s string + if ev.Key() == tcell.KeyRune { + switch ev.Str() { + case "<": + s = "" + case ">": + s = "" + case " ": + s = "" + default: + s = ev.Str() + } + } else { + s = gKeyVal[ev.Key()] + } + + return addKeyModifier(s, ev.Modifiers()) +} + +func parseKeyModifier(s string) (tcell.ModMask, string) { + matches := reModKey.FindStringSubmatch(s) + if matches == nil { + return tcell.ModNone, s + } + + mod := tcell.ModNone + switch matches[1] { + case "c": + mod = tcell.ModCtrl + case "s": + mod = tcell.ModShift + case "a": + mod = tcell.ModAlt + } + + s = matches[2] + if len(s) > 1 { + s = "<" + s + ">" + } + + return mod, s +} + +func parseKey(s string) *tcell.EventKey { + if key, ok := gValKey[s]; ok { + return tcell.NewEventKey(key, "", tcell.ModNone) + } + + mod, s := parseKeyModifier(s) + + k := tcell.KeyRune + if key, ok := gValKey[s]; ok { + k = key + s = "" + } else { + switch s { + case "": + s = "<" + case "": + s = ">" + case "": + s = " " + } + } + + return tcell.NewEventKey(k, s, mod) +} diff --git a/key_test.go b/key_test.go new file mode 100644 index 00000000..54bab0d4 --- /dev/null +++ b/key_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "testing" + + "github.com/gdamore/tcell/v3" +) + +var gKeyTests = []struct { + ev *tcell.EventKey + s string +}{ + {tcell.NewEventKey(tcell.KeyRune, "<", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyRune, ">", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyRune, " ", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyRune, "a", tcell.ModNone), "a"}, + {tcell.NewEventKey(tcell.KeyCtrlA, "", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyRune, "A", tcell.ModNone), "A"}, + {tcell.NewEventKey(tcell.KeyRune, "a", tcell.ModAlt), ""}, + {tcell.NewEventKey(tcell.KeyLeft, "", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyLeft, "", tcell.ModCtrl), ""}, + {tcell.NewEventKey(tcell.KeyLeft, "", tcell.ModShift), ""}, + {tcell.NewEventKey(tcell.KeyLeft, "", tcell.ModAlt), ""}, + {tcell.NewEventKey(tcell.KeyEsc, "", tcell.ModNone), ""}, + {tcell.NewEventKey(tcell.KeyF1, "", tcell.ModNone), ""}, +} + +func TestReadKey(t *testing.T) { + for _, test := range gKeyTests { + if got := readKey(test.ev); got != test.s { + t.Errorf("at input '%#v' expected '%s' but got '%s'", test.ev, test.s, got) + } + } +} + +func TestParseKey(t *testing.T) { + keyEqual := func(ev1, ev2 *tcell.EventKey) bool { + return ev1.Key() == ev2.Key() && ev1.Modifiers() == ev2.Modifiers() && ev1.Str() == ev2.Str() + } + + for _, test := range gKeyTests { + if got := parseKey(test.s); !keyEqual(got, test.ev) { + t.Errorf("at input '%s' expected '%#v' but got '%#v'", test.s, test.ev, got) + } + } +} diff --git a/lf.1 b/lf.1 index 479e49bc..bf01f169 100644 --- a/lf.1 +++ b/lf.1 @@ -258,7 +258,7 @@ cmd\-right (default \(aq\(aq and \(aq\(aq) cmd\-home (default \(aq\(aq and \(aq\(aq) cmd\-end (default \(aq\(aq and \(aq\(aq) cmd\-delete (default \(aq\(aq and \(aq\(aq) -cmd\-delete\-back (default \(aq\(aq and \(aq\(aq) +cmd\-delete\-back (default \(aq\(aq) cmd\-delete\-home (default \(aq\(aq) cmd\-delete\-end (default \(aq\(aq) cmd\-delete\-unix\-word (default \(aq\(aq) @@ -268,7 +268,7 @@ cmd\-transpose\-word (default \(aq\(aq) cmd\-word (default \(aq\(aq) cmd\-word\-back (default \(aq\(aq) cmd\-delete\-word (default \(aq\(aq) -cmd\-delete\-word\-back (default \(aq\(aq and \(aq\(aq) +cmd\-delete\-word\-back (default \(aq\(aq) cmd\-capitalize\-word (default \(aq\(aq) cmd\-uppercase\-word (default \(aq\(aq) cmd\-lowercase\-word (default \(aq\(aq) @@ -773,7 +773,7 @@ Move the cursor to the left/right. Move the cursor to the beginning/end of the line. .SS cmd\-delete (default \f[CR]\f[R] and \f[CR]\f[R]) Delete the next character. -.SS cmd\-delete\-back (default \f[CR]\f[R] and \f[CR]\f[R]) +.SS cmd\-delete\-back (default \f[CR]\f[R]) Delete the previous character. When at the beginning of a prompt, returns either to Normal mode or to \f[CR]:\f[R] mode. @@ -789,7 +789,7 @@ Transpose the positions of the last two characters/words. Move the cursor by one word in the forward/backward direction. .SS cmd\-delete\-word (default \f[CR]\f[R]) Delete the next word in the forward direction. -.SS cmd\-delete\-word\-back (default \f[CR]\f[R] and \f[CR]\f[R]) +.SS cmd\-delete\-word\-back (default \f[CR]\f[R]) Delete the previous word in the backward direction. .SS cmd\-capitalize\-word (default \f[CR]\f[R]), cmd\-uppercase\-word (default \f[CR]\f[R]), cmd\-lowercase\-word (default \f[CR]\f[R]) Capitalize/uppercase/lowercase the current word and jump to the next @@ -1578,6 +1578,9 @@ It is possible to combine special keys with modifiers: map down .EE .PP +Combining multiple modifiers (e.g. +\f[CR]Ctrl+Shift+Space\f[R]) is not supported. +.PP WARNING: Some key combinations will likely be intercepted by your OS, window manager, or terminal. Other key combinations cannot be recognized by lf due to the way diff --git a/misc.go b/misc.go index 945b763d..fbbf284a 100644 --- a/misc.go +++ b/misc.go @@ -16,10 +16,10 @@ import ( "unicode" "github.com/mattn/go-runewidth" + "github.com/rivo/uniseg" ) var ( - reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`) reRulerSub = regexp.MustCompile(`%[apmcsvfithPd]|%\{[^}]+\}`) reSixelSize = regexp.MustCompile(`"1;1;(\d+);(\d+)`) ) @@ -84,6 +84,25 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { return rs } +// firstGraphemeCluster returns the runes forming the first grapheme cluster of +// the input. +func firstGraphemeCluster(rs []rune) []rune { + gr := uniseg.NewGraphemes(string(rs)) + gr.Next() + return gr.Runes() +} + +// lastGraphemeCluster returns the runes forming the last grapheme cluster of +// the input. +func lastGraphemeCluster(rs []rune) []rune { + gr := uniseg.NewGraphemes(string(rs)) + var last []rune + for gr.Next() { + last = gr.Runes() + } + return last +} + // cmdEscape is used to escape whitespace and special characters with // backslashes in a given string. func cmdEscape(s string) string { diff --git a/misc_test.go b/misc_test.go index 865633dc..ea52ac51 100644 --- a/misc_test.go +++ b/misc_test.go @@ -126,6 +126,42 @@ func TestRuneSliceWidthLastRange(t *testing.T) { } } +func TestFirstGraphemeCluster(t *testing.T) { + tests := []struct { + rs []rune + exp []rune + }{ + {[]rune{}, nil}, + {[]rune{'a'}, []rune{'a'}}, + {[]rune{'世', '界'}, []rune{'世'}}, + {[]rune{0x1f3f3, 0xfe0f, 'a'}, []rune{0x1f3f3, 0xfe0f}}, // white flag + } + + for _, test := range tests { + if got := firstGraphemeCluster(test.rs); !reflect.DeepEqual(got, test.exp) { + t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got) + } + } +} + +func TestLastGraphemeCluster(t *testing.T) { + tests := []struct { + rs []rune + exp []rune + }{ + {[]rune{}, nil}, + {[]rune{'a'}, []rune{'a'}}, + {[]rune{'世', '界'}, []rune{'界'}}, + {[]rune{'a', 0x1f3f3, 0xfe0f}, []rune{0x1f3f3, 0xfe0f}}, // white flag + } + + for _, test := range tests { + if got := lastGraphemeCluster(test.rs); !reflect.DeepEqual(got, test.exp) { + t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got) + } + } +} + func TestCmdEscape(t *testing.T) { tests := []struct { s string diff --git a/opts.go b/opts.go index 6e2f2316..6471b6cf 100644 --- a/opts.go +++ b/opts.go @@ -371,42 +371,40 @@ func init() { // Command-line mode bindings can be assigned directly gOpts.cmdkeys = map[string]expr{ - "": &callExpr{"cmd-insert", []string{" "}, 1}, - "": &callExpr{"cmd-escape", nil, 1}, - "": &callExpr{"cmd-complete", nil, 1}, - "": &callExpr{"cmd-enter", nil, 1}, - "": &callExpr{"cmd-enter", nil, 1}, - "": &callExpr{"cmd-history-next", nil, 1}, - "": &callExpr{"cmd-history-next", nil, 1}, - "": &callExpr{"cmd-history-prev", nil, 1}, - "": &callExpr{"cmd-history-prev", nil, 1}, - "": &callExpr{"cmd-delete", nil, 1}, - "": &callExpr{"cmd-delete", nil, 1}, - "": &callExpr{"cmd-delete-back", nil, 1}, - "": &callExpr{"cmd-delete-back", nil, 1}, - "": &callExpr{"cmd-left", nil, 1}, - "": &callExpr{"cmd-left", nil, 1}, - "": &callExpr{"cmd-right", nil, 1}, - "": &callExpr{"cmd-right", nil, 1}, - "": &callExpr{"cmd-home", nil, 1}, - "": &callExpr{"cmd-home", nil, 1}, - "": &callExpr{"cmd-end", nil, 1}, - "": &callExpr{"cmd-end", nil, 1}, - "": &callExpr{"cmd-delete-home", nil, 1}, - "": &callExpr{"cmd-delete-end", nil, 1}, - "": &callExpr{"cmd-delete-unix-word", nil, 1}, - "": &callExpr{"cmd-yank", nil, 1}, - "": &callExpr{"cmd-transpose", nil, 1}, - "": &callExpr{"cmd-interrupt", nil, 1}, - "": &callExpr{"cmd-word", nil, 1}, - "": &callExpr{"cmd-word-back", nil, 1}, - "": &callExpr{"cmd-capitalize-word", nil, 1}, - "": &callExpr{"cmd-delete-word", nil, 1}, - "": &callExpr{"cmd-delete-word-back", nil, 1}, - "": &callExpr{"cmd-delete-word-back", nil, 1}, - "": &callExpr{"cmd-uppercase-word", nil, 1}, - "": &callExpr{"cmd-lowercase-word", nil, 1}, - "": &callExpr{"cmd-transpose-word", nil, 1}, + "": &callExpr{"cmd-insert", []string{" "}, 1}, + "": &callExpr{"cmd-escape", nil, 1}, + "": &callExpr{"cmd-complete", nil, 1}, + "": &callExpr{"cmd-enter", nil, 1}, + "": &callExpr{"cmd-enter", nil, 1}, + "": &callExpr{"cmd-history-next", nil, 1}, + "": &callExpr{"cmd-history-next", nil, 1}, + "": &callExpr{"cmd-history-prev", nil, 1}, + "": &callExpr{"cmd-history-prev", nil, 1}, + "": &callExpr{"cmd-delete", nil, 1}, + "": &callExpr{"cmd-delete", nil, 1}, + "": &callExpr{"cmd-delete-back", nil, 1}, + "": &callExpr{"cmd-left", nil, 1}, + "": &callExpr{"cmd-left", nil, 1}, + "": &callExpr{"cmd-right", nil, 1}, + "": &callExpr{"cmd-right", nil, 1}, + "": &callExpr{"cmd-home", nil, 1}, + "": &callExpr{"cmd-home", nil, 1}, + "": &callExpr{"cmd-end", nil, 1}, + "": &callExpr{"cmd-end", nil, 1}, + "": &callExpr{"cmd-delete-home", nil, 1}, + "": &callExpr{"cmd-delete-end", nil, 1}, + "": &callExpr{"cmd-delete-unix-word", nil, 1}, + "": &callExpr{"cmd-yank", nil, 1}, + "": &callExpr{"cmd-transpose", nil, 1}, + "": &callExpr{"cmd-interrupt", nil, 1}, + "": &callExpr{"cmd-word", nil, 1}, + "": &callExpr{"cmd-word-back", nil, 1}, + "": &callExpr{"cmd-capitalize-word", nil, 1}, + "": &callExpr{"cmd-delete-word", nil, 1}, + "": &callExpr{"cmd-delete-word-back", nil, 1}, + "": &callExpr{"cmd-uppercase-word", nil, 1}, + "": &callExpr{"cmd-lowercase-word", nil, 1}, + "": &callExpr{"cmd-transpose-word", nil, 1}, } gOpts.cmds = make(map[string]expr) diff --git a/sixel.go b/sixel.go index 6399bf09..292c8614 100644 --- a/sixel.go +++ b/sixel.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) type sixelScreen struct { diff --git a/termseq.go b/termseq.go index 72211a32..c8003a2f 100644 --- a/termseq.go +++ b/termseq.go @@ -8,7 +8,7 @@ import ( "strings" "unicode/utf8" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" ) // gEscapeCode is the byte that starts ANSI control sequences. @@ -172,8 +172,7 @@ loop: st = st.Reverse(true) case "8": // TODO: tcell PR for proper conceal - _, bg, _ := st.Decompose() - st = st.Foreground(bg) + st = st.Foreground(st.GetBackground()) case "9": st = st.StrikeThrough(true) case "22": diff --git a/termseq_test.go b/termseq_test.go index d572ab25..ad4d2e63 100644 --- a/termseq_test.go +++ b/termseq_test.go @@ -1,9 +1,11 @@ package main import ( + "reflect" "testing" - "github.com/gdamore/tcell/v2" + "github.com/gdamore/tcell/v3" + "github.com/gdamore/tcell/v3/color" ) func TestStripTermSequence(t *testing.T) { @@ -105,7 +107,7 @@ func TestParseEscapeSequence(t *testing.T) { exp tcell.Style }{ {"\033[1m", tcell.StyleDefault.Bold(true)}, - {"\033[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(tcell.ColorMaroon).Background(tcell.ColorGreen)}, + {"\033[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(color.XTerm1).Background(color.XTerm2)}, } for _, test := range tests { @@ -122,7 +124,7 @@ func TestApplyTermSequence(t *testing.T) { }{ {"", tcell.StyleDefault}, {"\x1b[1m", tcell.StyleDefault.Bold(true)}, - {"\x1b[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(tcell.ColorMaroon).Background(tcell.ColorGreen)}, + {"\x1b[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(color.XTerm1).Background(color.XTerm2)}, { "\x1b]8;;https://example.com\x1b\\", tcell.StyleDefault.UrlId("lf_hyperlink_100680ad546ce6a5").Url("https://example.com"), @@ -138,7 +140,7 @@ func TestApplyTermSequence(t *testing.T) { } for _, test := range tests { - if got := applyTermSequence(test.s, tcell.StyleDefault); got != test.exp { + if got := applyTermSequence(test.s, tcell.StyleDefault); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input %q expected '%v' but got '%v'", test.s, test.exp, got) } } @@ -153,25 +155,25 @@ func TestApplySGR(t *testing.T) { stExp tcell.Style }{ {"", none, none}, - {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, + {"", none.Foreground(color.XTerm1).Background(color.XTerm1), none}, {"", none.Bold(true), none}, - {"", none.Foreground(tcell.ColorMaroon).Bold(true), none}, + {"", none.Foreground(color.XTerm1).Bold(true), none}, {"0", none, none}, - {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, + {"0", none.Foreground(color.XTerm1).Background(color.XTerm1), none}, {"0", none.Bold(true), none}, - {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none}, + {"0", none.Foreground(color.XTerm1).Bold(true), none}, {"1", none, none.Bold(true)}, {"4", none, none.Underline(true)}, {"7", none, none.Reverse(true)}, - {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)}, - {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)}, + {"1", none.Foreground(color.XTerm1), none.Foreground(color.XTerm1).Bold(true)}, + {"4", none.Foreground(color.XTerm1), none.Foreground(color.XTerm1).Underline(true)}, + {"7", none.Foreground(color.XTerm1), none.Foreground(color.XTerm1).Reverse(true)}, {"4", none.Bold(true), none.Bold(true).Underline(true)}, - {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)}, + {"4", none.Foreground(color.XTerm1).Bold(true), none.Foreground(color.XTerm1).Bold(true).Underline(true)}, {"4:0", none, none}, {"4:0", none.Underline(true), none}, @@ -188,44 +190,44 @@ func TestApplySGR(t *testing.T) { {"27", none.Bold(true).Reverse(true), none.Bold(true)}, {"29", none.Bold(true).StrikeThrough(true), none.Bold(true)}, - {"31", none, none.Foreground(tcell.ColorMaroon)}, - {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, - {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"31", none, none.Foreground(color.XTerm1)}, + {"31", none.Foreground(color.XTerm2), none.Foreground(color.XTerm1)}, + {"31", none.Foreground(color.XTerm2).Bold(true), none.Foreground(color.XTerm1).Bold(true)}, - {"41", none, none.Background(tcell.ColorMaroon)}, - {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, + {"41", none, none.Background(color.XTerm1)}, + {"41", none.Background(color.XTerm2), none.Background(color.XTerm1)}, - {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"1;31", none, none.Foreground(color.XTerm1).Bold(true)}, + {"1;31", none.Foreground(color.XTerm2), none.Foreground(color.XTerm1).Bold(true)}, - {"01;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"01;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"01;31", none, none.Foreground(color.XTerm1).Bold(true)}, + {"01;31", none.Foreground(color.XTerm2), none.Foreground(color.XTerm1).Bold(true)}, - {"38;5;0", none, none.Foreground(tcell.ColorBlack)}, - {"38;5;1", none, none.Foreground(tcell.ColorMaroon)}, - {"38;5;8", none, none.Foreground(tcell.ColorGray)}, - {"38;5;16", none, none.Foreground(tcell.Color16)}, - {"38;5;232", none, none.Foreground(tcell.Color232)}, + {"38;5;0", none, none.Foreground(color.XTerm0)}, + {"38;5;1", none, none.Foreground(color.XTerm1)}, + {"38;5;8", none, none.Foreground(color.XTerm8)}, + {"38;5;16", none, none.Foreground(color.XTerm16)}, + {"38;5;232", none, none.Foreground(color.XTerm232)}, - {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, - {"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"38;5;1", none.Foreground(color.XTerm2), none.Foreground(color.XTerm1)}, + {"38;5;1", none.Foreground(color.XTerm2).Bold(true), none.Foreground(color.XTerm1).Bold(true)}, - {"48;5;0", none, none.Background(tcell.ColorBlack)}, - {"48;5;1", none, none.Background(tcell.ColorMaroon)}, - {"48;5;8", none, none.Background(tcell.ColorGray)}, - {"48;5;16", none, none.Background(tcell.Color16)}, - {"48;5;232", none, none.Background(tcell.Color232)}, + {"48;5;0", none, none.Background(color.XTerm0)}, + {"48;5;1", none, none.Background(color.XTerm1)}, + {"48;5;8", none, none.Background(color.XTerm8)}, + {"48;5;16", none, none.Background(color.XTerm16)}, + {"48;5;232", none, none.Background(color.XTerm232)}, - {"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, + {"48;5;1", none.Background(color.XTerm2), none.Background(color.XTerm1)}, - {"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"1;38;5;1", none, none.Foreground(color.XTerm1).Bold(true)}, + {"1;38;5;1", none.Foreground(color.XTerm2), none.Foreground(color.XTerm1).Bold(true)}, {"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))}, {"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))}, // Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446 - {"38;5;34;1", none, none.Foreground(tcell.Color34).Bold(true)}, + {"38;5;34;1", none, none.Foreground(color.XTerm34).Bold(true)}, } for _, test := range tests { diff --git a/ui.go b/ui.go index 3aac8e83..1cfa5890 100644 --- a/ui.go +++ b/ui.go @@ -14,144 +14,13 @@ import ( "text/tabwriter" "text/template" "time" - "unicode" "unicode/utf8" - "github.com/gdamore/tcell/v2" - "github.com/mattn/go-runewidth" + "github.com/gdamore/tcell/v3" + "github.com/rivo/uniseg" "golang.org/x/term" ) -var gKeyVal = map[tcell.Key]string{ - tcell.KeyEnter: "", - tcell.KeyBackspace: "", - tcell.KeyTab: "", - tcell.KeyBacktab: "", - tcell.KeyEsc: "", - tcell.KeyBackspace2: "", - tcell.KeyDelete: "", - tcell.KeyInsert: "", - tcell.KeyUp: "", - tcell.KeyDown: "", - tcell.KeyLeft: "", - tcell.KeyRight: "", - tcell.KeyHome: "", - tcell.KeyEnd: "", - tcell.KeyUpLeft: "", - tcell.KeyUpRight: "", - tcell.KeyDownLeft: "", - tcell.KeyDownRight: "", - tcell.KeyCenter: "
", - tcell.KeyPgDn: "", - tcell.KeyPgUp: "", - tcell.KeyClear: "", - tcell.KeyExit: "", - tcell.KeyCancel: "", - tcell.KeyPause: "", - tcell.KeyPrint: "", - tcell.KeyF1: "", - tcell.KeyF2: "", - tcell.KeyF3: "", - tcell.KeyF4: "", - tcell.KeyF5: "", - tcell.KeyF6: "", - tcell.KeyF7: "", - tcell.KeyF8: "", - tcell.KeyF9: "", - tcell.KeyF10: "", - tcell.KeyF11: "", - tcell.KeyF12: "", - tcell.KeyF13: "", - tcell.KeyF14: "", - tcell.KeyF15: "", - tcell.KeyF16: "", - tcell.KeyF17: "", - tcell.KeyF18: "", - tcell.KeyF19: "", - tcell.KeyF20: "", - tcell.KeyF21: "", - tcell.KeyF22: "", - tcell.KeyF23: "", - tcell.KeyF24: "", - tcell.KeyF25: "", - tcell.KeyF26: "", - tcell.KeyF27: "", - tcell.KeyF28: "", - tcell.KeyF29: "", - tcell.KeyF30: "", - tcell.KeyF31: "", - tcell.KeyF32: "", - tcell.KeyF33: "", - tcell.KeyF34: "", - tcell.KeyF35: "", - tcell.KeyF36: "", - tcell.KeyF37: "", - tcell.KeyF38: "", - tcell.KeyF39: "", - tcell.KeyF40: "", - tcell.KeyF41: "", - tcell.KeyF42: "", - tcell.KeyF43: "", - tcell.KeyF44: "", - tcell.KeyF45: "", - tcell.KeyF46: "", - tcell.KeyF47: "", - tcell.KeyF48: "", - tcell.KeyF49: "", - tcell.KeyF50: "", - tcell.KeyF51: "", - tcell.KeyF52: "", - tcell.KeyF53: "", - tcell.KeyF54: "", - tcell.KeyF55: "", - tcell.KeyF56: "", - tcell.KeyF57: "", - tcell.KeyF58: "", - tcell.KeyF59: "", - tcell.KeyF60: "", - tcell.KeyF61: "", - tcell.KeyF62: "", - tcell.KeyF63: "", - tcell.KeyF64: "", - tcell.KeyCtrlA: "", - tcell.KeyCtrlB: "", - tcell.KeyCtrlC: "", - tcell.KeyCtrlD: "", - tcell.KeyCtrlE: "", - tcell.KeyCtrlF: "", - tcell.KeyCtrlG: "", - tcell.KeyCtrlJ: "", - tcell.KeyCtrlK: "", - tcell.KeyCtrlL: "", - tcell.KeyCtrlN: "", - tcell.KeyCtrlO: "", - tcell.KeyCtrlP: "", - tcell.KeyCtrlQ: "", - tcell.KeyCtrlR: "", - tcell.KeyCtrlS: "", - tcell.KeyCtrlT: "", - tcell.KeyCtrlU: "", - tcell.KeyCtrlV: "", - tcell.KeyCtrlW: "", - tcell.KeyCtrlX: "", - tcell.KeyCtrlY: "", - tcell.KeyCtrlZ: "", - tcell.KeyCtrlSpace: "", - tcell.KeyCtrlUnderscore: "", - tcell.KeyCtrlRightSq: "", - tcell.KeyCtrlBackslash: "", - tcell.KeyCtrlCarat: "", -} - -var gValKey map[string]tcell.Key - -func init() { - gValKey = make(map[string]tcell.Key, len(gKeyVal)) - for k, v := range gKeyVal { - gValKey[v] = k - } -} - type win struct { w, h, x, y int } @@ -169,69 +38,65 @@ func (win *win) renew(w, h, x, y int) { // It ignores supported terminal control sequences (see [readTermSequence]) // and accounts for tab expansions using the `tabstop` option. func printLength(s string) int { - ind := 0 - off := 0 + length := 0 + + i := 0 slen := len(s) - for i := 0; i < slen; i++ { + for i < slen { seq := readTermSequence(s[i:]) if seq != "" { - i += len(seq) - 1 + i += len(seq) continue } - r, w := utf8.DecodeRuneInString(s[i:]) - i += w - 1 + gc, _, w, _ := uniseg.FirstGraphemeClusterInString(s[i:], -1) + i += len(gc) - if r == '\t' { - ind += gOpts.tabstop - (ind-off)%gOpts.tabstop + if gc == "\t" { + length += gOpts.tabstop - length%gOpts.tabstop } else { - ind += runewidth.RuneWidth(r) + length += w } } - return ind + return length } func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style { - off := x - var comb []rune - slen := len(s) - for i := 0; i < slen; i++ { - seq := readTermSequence(s[i:]) - if seq != "" { - st = applyTermSequence(seq, st) - i += len(seq) - 1 - continue - } - - r, w := utf8.DecodeRuneInString(s[i:]) - for { - rc, wc := utf8.DecodeRuneInString(s[i+w:]) - if !unicode.Is(unicode.Mn, rc) { - break - } - comb = append(comb, rc) - i += wc - } - - if x < win.w { - screen.SetContent(win.x+x, win.y+y, r, comb, st) - comb = nil - } - - i += w - 1 - - if r == '\t' { - ind := gOpts.tabstop - (x-off)%gOpts.tabstop - for i := 0; i < ind && x+i < win.w; i++ { - screen.SetContent(win.x+x+i, win.y+y, ' ', nil, st) - } - x += ind - } else { - x += runewidth.RuneWidth(r) + var b strings.Builder + off := 0 + put := func() { + if b.Len() > 0 { + s := b.String() + screen.PutStrStyled(win.x+x+off, win.y+y, s, st) + off += printLength(s) + b.Reset() } } + i := 0 + slen := len(s) + for i < slen { + seq := readTermSequence(s[i:]) + if seq != "" { + put() + st = applyTermSequence(seq, st) + i += len(seq) + continue + } + + gc, _, _, _ := uniseg.FirstGraphemeClusterInString(s[i:], -1) + if gc == "\t" { + w := gOpts.tabstop - (x+off+printLength(b.String()))%gOpts.tabstop + b.WriteString(strings.Repeat(" ", w)) + } else if gc != "\r" { + b.WriteString(gc) + } + + i += len(gc) + } + + put() return st } @@ -515,7 +380,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty } filename := []rune(truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, []rune(gOpts.truncatechar)[0])) - for j := runeSliceWidth(filename); j < maxFilenameWidth; j++ { + for j := uniseg.StringWidth(string(filename)); j < maxFilenameWidth; j++ { filename = append(filename, ' ') } @@ -636,15 +501,12 @@ type menuSelect struct { type ui struct { screen tcell.Screen // primary screen used for drawing and event polling sxScreen sixelScreen // sixel preview state - polling bool // whether event polling is running wins []*win // pane windows from `ratios` (last is `preview` when enabled) promptWin *win // prompt line window msgWin *win // status line window menuWin *win // menu window msg string // message/output shown in msgWin exprChan chan expr // expr queue - keyChan chan string // key queue (send via `push`) - tevChan chan tcell.Event // terminal events from screen.PollEvent evChan chan tcell.Event // merged event queue (keyChan + tevChan) menu string // rendered (multiline) menu text (i.e. completions, binds, marks) menuSelect *menuSelect // selected menu entry (completion menu only) @@ -652,8 +514,8 @@ type ui struct { cmdAccLeft []rune // command buffer left of cursor cmdAccRight []rune // command buffer right of cursor cmdYankBuf []rune // yank buffer for command line editing - keyAcc []rune // keys typed so far for mapping lookup - keyCount []rune // count prefix for next command + keyAcc string // keys typed so far for mapping lookup + keyCount string // count prefix for next command styles styleMap // parsed styles icons iconMap // parsed icons ruler *template.Template // compiled `rulerfile` @@ -667,14 +529,11 @@ func newUI(screen tcell.Screen) *ui { ui := &ui{ screen: screen, - polling: true, wins: getWins(screen), promptWin: newWin(wtot, 1, 0, 0), msgWin: newWin(wtot, 1, 0, htot-1), menuWin: newWin(wtot, 1, 0, htot-2), exprChan: make(chan expr, 1000), - keyChan: make(chan string, 1000), - tevChan: make(chan tcell.Event, 1000), evChan: make(chan tcell.Event, 1000), styles: parseStyles(), icons: parseIcons(), @@ -683,8 +542,6 @@ func newUI(screen tcell.Screen) *ui { } ui.ruler, ui.rulerErr = parseRuler(gOpts.rulerfile) - go ui.pollEvents() - return ui } @@ -698,18 +555,6 @@ func (ui *ui) winAt(x, y int) (int, *win) { return -1, nil } -func (ui *ui) pollEvents() { - var ev tcell.Event - for { - ev = ui.screen.PollEvent() - if ev == nil { - ui.polling = false - return - } - ui.tevChan <- ev - } -} - func (ui *ui) renew() { ui.wins = getWins(ui.screen) @@ -909,7 +754,7 @@ func (ui *ui) drawRuler(nav *nav) { tot := len(dir.files) ind := min(dir.ind+1, tot) hid := len(dir.allFiles) - tot - acc := string(ui.keyCount) + string(ui.keyAcc) + acc := ui.keyCount + ui.keyAcc var percentage string beg := max(dir.ind-dir.pos, 0) @@ -1113,7 +958,7 @@ func (ui *ui) drawRulerFile(nav *nav) { data := rulerData{ SPACER: "\x1f", Message: ui.msg, - Keys: string(ui.keyCount) + string(ui.keyAcc), + Keys: ui.keyCount + ui.keyAcc, Progress: progress, Copy: copiedPaths, Cut: cutPaths, @@ -1172,35 +1017,35 @@ func (ui *ui) drawBox() { w, h := ui.screen.Size() for i := 1; i < w-1; i++ { - ui.screen.SetContent(i, 1, tcell.RuneHLine, nil, st) - ui.screen.SetContent(i, h-2, tcell.RuneHLine, nil, st) + ui.screen.PutStrStyled(i, 1, string(tcell.RuneHLine), st) + ui.screen.PutStrStyled(i, h-2, string(tcell.RuneHLine), st) } for i := 2; i < h-2; i++ { - ui.screen.SetContent(0, i, tcell.RuneVLine, nil, st) - ui.screen.SetContent(w-1, i, tcell.RuneVLine, nil, st) + ui.screen.PutStrStyled(0, i, string(tcell.RuneVLine), st) + ui.screen.PutStrStyled(w-1, i, string(tcell.RuneVLine), st) } if gOpts.roundbox { - ui.screen.SetContent(0, 1, '╭', nil, st) - ui.screen.SetContent(w-1, 1, '╮', nil, st) - ui.screen.SetContent(0, h-2, '╰', nil, st) - ui.screen.SetContent(w-1, h-2, '╯', nil, st) + ui.screen.PutStrStyled(0, 1, "╭", st) + ui.screen.PutStrStyled(w-1, 1, "╮", st) + ui.screen.PutStrStyled(0, h-2, "╰", st) + ui.screen.PutStrStyled(w-1, h-2, "╯", st) } else { - ui.screen.SetContent(0, 1, tcell.RuneULCorner, nil, st) - ui.screen.SetContent(w-1, 1, tcell.RuneURCorner, nil, st) - ui.screen.SetContent(0, h-2, tcell.RuneLLCorner, nil, st) - ui.screen.SetContent(w-1, h-2, tcell.RuneLRCorner, nil, st) + ui.screen.PutStrStyled(0, 1, string(tcell.RuneULCorner), st) + ui.screen.PutStrStyled(w-1, 1, string(tcell.RuneURCorner), st) + ui.screen.PutStrStyled(0, h-2, string(tcell.RuneLLCorner), st) + ui.screen.PutStrStyled(w-1, h-2, string(tcell.RuneLRCorner), st) } wacc := 0 for wind := range len(ui.wins) - 1 { wacc += ui.wins[wind].w + 1 - ui.screen.SetContent(wacc, 1, tcell.RuneTTee, nil, st) + ui.screen.PutStrStyled(wacc, 1, string(tcell.RuneTTee), st) for i := 2; i < h-2; i++ { - ui.screen.SetContent(wacc, i, tcell.RuneVLine, nil, st) + ui.screen.PutStrStyled(wacc, i, string(tcell.RuneVLine), st) } - ui.screen.SetContent(wacc, h-2, tcell.RuneBTee, nil, st) + ui.screen.PutStrStyled(wacc, h-2, string(tcell.RuneBTee), st) } } @@ -1292,7 +1137,7 @@ func (ui *ui) draw(nav *nav) { prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth) left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)) ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+string(left)+string(ui.cmdAccRight)) - ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+runeSliceWidth(left), ui.msgWin.y) + ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+uniseg.StringWidth(string(left)), ui.msgWin.y) } ui.drawPreview(nav, &context) @@ -1482,71 +1327,6 @@ func listFilesInCurrDir(nav *nav) string { return b.String() } -func (ui *ui) pollEvent() tcell.Event { - select { - case val := <-ui.keyChan: - var ch rune - var mod tcell.ModMask - k := tcell.KeyRune - - if key, ok := gValKey[val]; ok { - return tcell.NewEventKey(key, ch, mod) - } - - switch { - case utf8.RuneCountInString(val) == 1: - ch, _ = utf8.DecodeRuneInString(val) - case val == "": - ch = '<' - case val == "": - ch = '>' - case val == "": - ch = ' ' - case reModKey.MatchString(val): - matches := reModKey.FindStringSubmatch(val) - switch matches[1] { - case "c": - mod = tcell.ModCtrl - case "s": - mod = tcell.ModShift - case "a": - mod = tcell.ModAlt - } - val = matches[2] - if utf8.RuneCountInString(val) == 1 { - ch, _ = utf8.DecodeRuneInString(val) - break - } else if key, ok := gValKey["<"+val+">"]; ok { - k = key - break - } - fallthrough - default: - k = tcell.KeyESC - ui.echoerrf("unknown key: %s", val) - } - - return tcell.NewEventKey(k, ch, mod) - case ev := <-ui.tevChan: - return ev - } -} - -func addSpecialKeyModifier(val string, mod tcell.ModMask) string { - switch { - case !strings.HasPrefix(val, "<"): - return val - case mod == tcell.ModCtrl && !strings.HasPrefix(val, "")...) - case tev.Rune() == '>': - ui.keyAcc = append(ui.keyAcc, []rune("")...) - case tev.Rune() == ' ': - ui.keyAcc = append(ui.keyAcc, []rune("")...) - case tev.Modifiers() == tcell.ModAlt: - ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', tev.Rune(), '>') - case unicode.IsDigit(tev.Rune()) && len(ui.keyAcc) == 0: - ui.keyCount = append(ui.keyCount, tev.Rune()) - default: - ui.keyAcc = append(ui.keyAcc, tev.Rune()) + isDigitKey := func(*tcell.EventKey) bool { + if tev.Key() != tcell.KeyRune || tev.Modifiers() != tcell.ModNone { + return false } - } else { - val := gKeyVal[tev.Key()] - val = addSpecialKeyModifier(val, tev.Modifiers()) - if val == "" && len(ui.keyAcc) != 0 { - ui.keyAcc = nil - ui.keyCount = nil - ui.menu = "" - return draw - } - ui.keyAcc = append(ui.keyAcc, []rune(val)...) + + s := tev.Str() + return len(s) == 1 && s[0] >= '0' && s[0] <= '9' } - if len(ui.keyAcc) == 0 { + switch { + case tev.Key() == tcell.KeyEsc && ui.keyAcc != "": + ui.keyAcc = "" + ui.keyCount = "" + ui.menu = "" return draw + case isDigitKey(tev) && ui.keyAcc == "": + ui.keyCount += tev.Str() + return draw + default: + ui.keyAcc += readKey(tev) } - binds, ok := findBinds(keys, string(ui.keyAcc)) + binds, ok := findBinds(keys, ui.keyAcc) switch len(binds) { case 0: - ui.echoerrf("unknown mapping: %s", string(ui.keyAcc)) - ui.keyAcc = nil - ui.keyCount = nil + ui.echoerrf("unknown mapping: %s", ui.keyAcc) + ui.keyAcc = "" + ui.keyCount = "" ui.menu = "" return draw default: if ok { - if len(ui.keyCount) > 0 { - c, err := strconv.Atoi(string(ui.keyCount)) + if ui.keyCount != "" { + c, err := strconv.Atoi(ui.keyCount) if err != nil { log.Printf("converting command count: %s", err) } count = c } - expr := keys[string(ui.keyAcc)] + expr := keys[ui.keyAcc] if count != 0 { switch e := expr.(type) { @@ -1626,14 +1396,14 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr { } } - ui.keyAcc = nil - ui.keyCount = nil + ui.keyAcc = "" + ui.keyCount = "" ui.menu = "" return expr } if gOpts.showbinds { // mode and already typed keys are obvious here; no need to clutter the menu - ui.menu = listMatchingBinds(binds, string(ui.keyAcc)) + ui.menu = listMatchingBinds(binds, ui.keyAcc) } return draw } @@ -1680,8 +1450,8 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr { } if button != "" && button != "" { ui.echoerrf("unknown mapping: %s", button) - ui.keyAcc = nil - ui.keyCount = nil + ui.keyAcc = "" + ui.keyCount = "" ui.menu = "" return draw } @@ -1756,21 +1526,12 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr { func readCmdEvent(ev tcell.Event) expr { if tev, ok := ev.(*tcell.EventKey); ok { - if tev.Key() == tcell.KeyRune { - if tev.Modifiers() == tcell.ModAlt { - val := string([]rune{'<', 'a', '-', tev.Rune(), '>'}) - if expr, ok := gOpts.cmdkeys[val]; ok { - return expr - } - } else { - return &callExpr{"cmd-insert", []string{string(tev.Rune())}, 1} - } - } else { - val := gKeyVal[tev.Key()] - val = addSpecialKeyModifier(val, tev.Modifiers()) - if expr, ok := gOpts.cmdkeys[val]; ok { - return expr - } + if tev.Key() == tcell.KeyRune && tev.Modifiers()&tcell.ModAlt == 0 { + return &callExpr{"cmd-insert", []string{tev.Str()}, 1} + } + + if expr, ok := gOpts.cmdkeys[readKey(tev)]; ok { + return expr } } return nil @@ -1788,12 +1549,10 @@ func (ui *ui) readEvent(ev tcell.Event, nav *nav) expr { return ui.readNormalEvent(ev, nav) } -func (ui *ui) readExpr() { - go func() { - for { - ui.evChan <- ui.pollEvent() - } - }() +func (ui *ui) readEvents() { + for ev := range ui.screen.EventQ() { + ui.evChan <- ev + } } func (ui *ui) suspend() error { @@ -1802,12 +1561,7 @@ func (ui *ui) suspend() error { } func (ui *ui) resume() error { - err := ui.screen.Resume() - if !ui.polling { - go ui.pollEvents() - ui.polling = true - } - return err + return ui.screen.Resume() } func (ui *ui) exportSizes() {