jroimartin / gocui

Minimalist Go package aimed at creating Console User Interfaces.
BSD 3-Clause "New" or "Revised" License
9.92k stars 608 forks source link

Query individual runes under cursor position. #191

Open hexaflex-zz opened 5 years ago

hexaflex-zz commented 5 years ago

The View type has a Word and Line method. I am finding myself in need of looking at individual runes under the current cursor position.

This is useful when implementing extended editor functionality like moving the cursor left or right by a whole words, or deleting a whole word at a time. These require one to scan backward or forward from the current cursor position, until a whitespace character is encountered. A View.Rune(x, y int) (rune, error) function allows us to do this in a nice and clean fashion.

I implemented it myself, but it requires access to the unexperted realPosition function.

// Rune returns the rune at the given position.
func (v *View) Rune(x, y int) (rune, error) {
    x, y, err := v.realPosition(x, y)
    if err != nil {
        return 0, err
    }

    if x < 0 || y < 0 || y >= len(v.lines) || x >= len(v.lines[y]) {
        return 0, errors.New("invalid point")
    }

    return v.lines[y][x].chr, nil
}