Hurray, I can now press gg instead of g to go to the top in tt. Much better! :-) Other multi-key combinations are also easily possible now.

I should probably write a real article about this at some point, but here we go. The only downside with my new key binding system is that it breaks tview’s established pattern. You’ve got an InputHandler(), that is implemented using WrapInputHandler(…). It typically then directly implements the switching logic depending on the key press. Something like this:

func (w *Widget) InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
    // WrapInputHandler allows for intercepting key events with SetInputCapture(…)
    // from the outside for customization. This handles the default key bindings.
    return t.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
        switch event.Key() {
        case tcell.KeyRune:
            if event.Modifiers() == tcell.ModNone {
                switch event.Rune() {
                case 'k':
                    w.scrollUp()
                    return // we already handled the event, stop processing

                case 'j':
                    w.scrollDown()
                    return
                }
            }
        }

        // We didn't handle the key event. Maybe the parent
        // widget knows what to do with it.
        if handler := w.parent.InputHandler(); handler != nil {
            handler(event, setFocus)
        }
    })
}

From the outside, you can intercept and either stop or continue the widget’s original key handling with a potentially rewritten key event using SetInputCapture(…):

w := NewWidget()
// customized or additional key bindings
w.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
    switch event.Key() {
    case tcell.KeyUp:
        // Rewrite the event, so the "cursor up" key is an alias
        // for the vim key binding "k", that is handled by the
        // wrapped input handler above. (I know, I know, this is a
        // completely unrealistic example, why would anyone use
        // cursor keys when there are vim key bindings available?!)
        return tcell.NewEventKey(tcell.KeyRune, 'k', tcell.ModNone)

    case tcell.KeyRune:
        if event.Modifiers() == tcell.ModNone {
            switch event.Rune() {
                case 'q':
                    app.Stop()
                    // we already handled the event, do not pass it
                    // to the wrapped input handler above
                    return nil

                case 'r':
                    toggleMessageReadStatus()
                    return nil
            }
        }
    }

    // we didn't handle the event, pass it to the wrapped
    // input handler above
    return event
}

Since they all expect a single key, I’ve noticed that using multiple dedicated KeyBindings of mine on these different levels kinda breaks multi-key handling with common prefixes. The outer-most KeyBinding captures the prefix, but it can’t transfer it to the inner one if not handled by the outer one. At least not without some more (potentially ugly) changes. So, I now have to work with just a single KeyBindings object for the entire widget chain (if it consists of multiple other widgets or the regular input handler and input capture are in the game). The outside needs to register all its key bind customizations or extensions at the same level that the original widget handles its default ones. Doable by exposing the widget’s KeyBindings instance, but not pretty. You always have to keep this in mind.

With the KeyBindings, it will look like that:

type Widget struct {
    parent tview.Primitive

    // make it available to children or the outside either by
    // direct field access or by providing a getter method
    KeyBindings *bind.KeyBindings
}

func NewWidget() *Widget {
    w := &Widget{KeyBindings: &bind.KeyBindings{}}
    w.KeyBindings. // default key bindings
        Bind0(bind.KeySequence('k', w.scrollUp).
        Bind0(bind.KeySequence('j', w.scrollDown)
    return w
}

func (w *Widget) InputHandler() InputHandler() func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
    return t.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p tview.Primitive)) {
        // also note the missing support for focus transfer at the moment
        event = w.KeyBindings.Capture(event)
        if event == nil {
            return
        }

        if handler := w.parent.InputHandler(); handler != nil {
            handler(event, setFocus)
        }
    }
}

And then from the outside, or in a child widget:

w := NewWidget()
w.KeyBindings. // additional or customized key bindings
    Bind1(bind.KeySequence(tcell.KeyUp), func(*tcell.EventKey) *tcell.EventKey {
        return tcell.NewEventKey(tcell.KeyRune, 'k', tcell.ModNone)
    }).
    Bind0(bind.KeySequence('q'), app.Stop).
    Bind0(bind.KeySequence('r'), toggleMessageReadStatus)

When directly working with tview primitives that are not part of custom widget implementations, the following works well so far:

textView := tview.NewTextView().
    SetWordWrap(true).
    SetText("…")
    SetScrollable(true)
textView.SetInputCapture((&bind.KeyBindings{}).
    Bind0(bind.KeySequence('q'), app.Stop).
    Bind1(bind.KeySequence('g', 'g'), func(*tcell.EventKey) *tcell.EventKey {
        return tcell.NewEventKey(tcell.KeyHome, 0, tcell.ModNone)
    }).
    Capture)

I need to sleep on this some more.

Also, writing very long messages like this one is really not all that fun in tt’s editor. I should absolutely provide a way to shell out to vim.

(Took me about one and a half hours to compose, holy crap. But not only because of not using vim. Although, that might have saved me a quarter hour or so for sure. Proof-reading this message also uncovered quite a few bugs in my real documentation. So, that’s a big win!) Good night!

⤋ Read More