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:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

+688
View File
@@ -0,0 +1,688 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"fmt"
"io"
"strings"
"unicode"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
func (self *Readline) text_upto_cursor_pos() string {
buf := strings.Builder{}
buf.Grow(1024)
for i, line := range self.input_state.lines {
if i == self.input_state.cursor.Y {
buf.WriteString(line[:min(len(line), self.input_state.cursor.X)])
break
} else {
buf.WriteString(line)
buf.WriteString("\n")
}
}
return buf.String()
}
func (self *Readline) text_after_cursor_pos() string {
buf := strings.Builder{}
buf.Grow(1024)
for i, line := range self.input_state.lines {
if i == self.input_state.cursor.Y {
buf.WriteString(line[min(len(line), self.input_state.cursor.X):])
buf.WriteString("\n")
} else if i > self.input_state.cursor.Y {
buf.WriteString(line)
buf.WriteString("\n")
}
}
ans := buf.String()
if ans != "" {
ans = ans[:len(ans)-1]
}
return ans
}
func (self *Readline) all_text() string {
return strings.Join(self.input_state.lines, "\n")
}
func (self *Readline) set_text(text string) {
self.move_to_start()
self.erase_chars_after_cursor(123456789, true)
if text != "" {
self.add_text(text)
}
self.move_to_end()
}
func (self *Readline) add_text(text string) {
new_lines := make([]string, 0, len(self.input_state.lines)+4)
new_lines = append(new_lines, self.input_state.lines[:self.input_state.cursor.Y]...)
var lines_after []string
if len(self.input_state.lines) > self.input_state.cursor.Y+1 {
lines_after = self.input_state.lines[self.input_state.cursor.Y+1:]
}
has_trailing_newline := strings.HasSuffix(text, "\n")
add_line_break := func(line string) {
new_lines = append(new_lines, line)
self.input_state.cursor.X = len(line)
self.input_state.cursor.Y += 1
}
cline := self.input_state.lines[self.input_state.cursor.Y]
before_first_line := cline[:self.input_state.cursor.X]
after_first_line := ""
if self.input_state.cursor.X < len(cline) {
after_first_line = cline[self.input_state.cursor.X:]
}
for i, line := range utils.Splitlines(text) {
if i > 0 {
add_line_break(line)
} else {
line := before_first_line + line
self.input_state.cursor.X = len(line)
new_lines = append(new_lines, line)
}
}
if has_trailing_newline {
add_line_break("")
}
if after_first_line != "" {
if len(new_lines) == 0 {
new_lines = append(new_lines, "")
}
new_lines[len(new_lines)-1] += after_first_line
}
if len(lines_after) > 0 {
new_lines = append(new_lines, lines_after...)
}
self.input_state.lines = new_lines
}
func (self *Readline) move_cursor_left(amt uint, traverse_line_breaks bool) (amt_moved uint) {
for amt_moved < amt {
if self.input_state.cursor.X == 0 {
if !traverse_line_breaks || self.input_state.cursor.Y == 0 {
return amt_moved
}
self.input_state.cursor.Y -= 1
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
amt_moved++
continue
}
line := self.input_state.lines[self.input_state.cursor.Y]
for ci := wcswidth.NewCellIterator(line[:self.input_state.cursor.X]).GotoEnd(); amt_moved < amt && ci.Backward(); amt_moved++ {
self.input_state.cursor.X -= len(ci.Current())
}
}
return amt_moved
}
func (self *Readline) move_cursor_right(amt uint, traverse_line_breaks bool) (amt_moved uint) {
for amt_moved < amt {
line := self.input_state.lines[self.input_state.cursor.Y]
if self.input_state.cursor.X >= len(line) {
if !traverse_line_breaks || self.input_state.cursor.Y == len(self.input_state.lines)-1 {
return amt_moved
}
self.input_state.cursor.Y += 1
self.input_state.cursor.X = 0
amt_moved++
continue
}
for ci := wcswidth.NewCellIterator(line[self.input_state.cursor.X:]); amt_moved < amt && ci.Forward(); amt_moved++ {
self.input_state.cursor.X += len(ci.Current())
}
}
return amt_moved
}
func (self *Readline) move_cursor_to_target_line(source_line, target_line *ScreenLine) {
if source_line != target_line {
visual_distance_into_text := source_line.CursorCell - source_line.Prompt.Length
self.input_state.cursor.Y = target_line.ParentLineNumber
tp := wcswidth.TruncateToVisualLength(target_line.Text, visual_distance_into_text)
self.input_state.cursor.X = target_line.OffsetInParentLine + len(tp)
}
}
func (self *Readline) move_cursor_vertically(amt int) (ans int) {
if self.screen_width == 0 {
self.update_current_screen_size()
}
screen_lines := self.get_screen_lines()
cursor_line_num := 0
for i, sl := range screen_lines {
if sl.CursorCell > -1 {
cursor_line_num = i
break
}
}
target_line_num := min(max(0, cursor_line_num+amt), len(screen_lines)-1)
ans = target_line_num - cursor_line_num
if ans != 0 {
self.move_cursor_to_target_line(screen_lines[cursor_line_num], screen_lines[target_line_num])
}
return ans
}
func (self *Readline) move_cursor_down(amt uint) uint {
ans := uint(0)
if self.screen_width == 0 {
self.update_current_screen_size()
}
return ans
}
func (self *Readline) move_to_start_of_line() bool {
if self.input_state.cursor.X > 0 {
self.input_state.cursor.X = 0
return true
}
return false
}
func (self *Readline) move_to_end_of_line() bool {
line := self.input_state.lines[self.input_state.cursor.Y]
if self.input_state.cursor.X >= len(line) {
return false
}
self.input_state.cursor.X = len(line)
return true
}
func (self *Readline) move_to_start() bool {
if self.input_state.cursor.Y == 0 && self.input_state.cursor.X == 0 {
return false
}
self.input_state.cursor.Y = 0
self.move_to_start_of_line()
return true
}
func (self *Readline) move_to_end() bool {
line := self.input_state.lines[self.input_state.cursor.Y]
if self.input_state.cursor.Y == len(self.input_state.lines)-1 && self.input_state.cursor.X >= len(line) {
return false
}
self.input_state.cursor.Y = len(self.input_state.lines) - 1
self.move_to_end_of_line()
return true
}
func (self *Readline) erase_between(start, end Position) string {
if end.Less(start) {
start, end = end, start
}
buf := strings.Builder{}
if start.Y == end.Y {
line := self.input_state.lines[start.Y]
buf.WriteString(line[start.X:end.X])
self.input_state.lines[start.Y] = line[:start.X] + line[end.X:]
if self.input_state.cursor.Y == start.Y && self.input_state.cursor.X >= start.X {
if self.input_state.cursor.X < end.X {
self.input_state.cursor.X = start.X
} else {
self.input_state.cursor.X -= end.X - start.X
}
}
return buf.String()
}
lines := make([]string, 0, len(self.input_state.lines))
for i, line := range self.input_state.lines {
if i < start.Y || i > end.Y {
lines = append(lines, line)
} else if i == start.Y {
lines = append(lines, line[:start.X])
buf.WriteString(line[start.X:])
if self.input_state.cursor.Y == i && self.input_state.cursor.X > start.X {
self.input_state.cursor.X = start.X
}
} else if i == end.Y {
lines[len(lines)-1] += line[end.X:]
buf.WriteString(line[:end.X])
if i == self.input_state.cursor.Y {
self.input_state.cursor.Y = start.Y
if self.input_state.cursor.X < end.X {
self.input_state.cursor.X = start.X
} else {
self.input_state.cursor.X -= end.X - start.X
}
}
} else {
if i == self.input_state.cursor.Y {
self.input_state.cursor = start
}
buf.WriteString(line)
buf.WriteString("\n")
}
}
self.input_state.lines = lines
return buf.String()
}
func (self *Readline) erase_chars_before_cursor(amt uint, traverse_line_breaks bool) uint {
pos := self.input_state.cursor
num := self.move_cursor_left(amt, traverse_line_breaks)
if num == 0 {
return num
}
self.erase_between(self.input_state.cursor, pos)
return num
}
func (self *Readline) erase_chars_after_cursor(amt uint, traverse_line_breaks bool) uint {
pos := self.input_state.cursor
num := self.move_cursor_right(amt, traverse_line_breaks)
if num == 0 {
return num
}
self.erase_between(pos, self.input_state.cursor)
return num
}
func has_word_chars(text string) bool {
for _, ch := range text {
if unicode.IsLetter(ch) || unicode.IsDigit(ch) {
return true
}
}
return false
}
func (self *Readline) move_to_end_of_word(amt uint, traverse_line_breaks bool, is_part_of_word func(string) bool) (num_of_words_moved uint) {
if amt == 0 {
return 0
}
line := self.input_state.lines[self.input_state.cursor.Y]
in_word := false
ci := wcswidth.NewCellIterator(line[self.input_state.cursor.X:])
sz := 0
for ci.Forward() {
current_is_word_char := is_part_of_word(ci.Current())
plen := sz
sz += len(ci.Current())
if current_is_word_char {
in_word = true
} else if in_word {
self.input_state.cursor.X += plen
amt--
num_of_words_moved++
if amt == 0 {
return
}
in_word = false
}
}
if self.move_to_end_of_line() {
amt--
num_of_words_moved++
}
if amt > 0 {
if traverse_line_breaks && self.input_state.cursor.Y < len(self.input_state.lines)-1 {
self.input_state.cursor.Y++
self.input_state.cursor.X = 0
num_of_words_moved += self.move_to_end_of_word(amt, traverse_line_breaks, is_part_of_word)
}
}
return
}
func (self *Readline) move_to_start_of_word(amt uint, traverse_line_breaks bool, is_part_of_word func(string) bool) (num_of_words_moved uint) {
if amt == 0 {
return 0
}
line := self.input_state.lines[self.input_state.cursor.Y]
in_word := false
ci := wcswidth.NewCellIterator(line[:self.input_state.cursor.X]).GotoEnd()
sz := 0
for ci.Backward() {
current_is_word_char := is_part_of_word(ci.Current())
plen := sz
sz += len(ci.Current())
if current_is_word_char {
in_word = true
} else if in_word {
self.input_state.cursor.X -= plen
amt--
num_of_words_moved++
if amt == 0 {
return
}
in_word = false
}
}
if self.move_to_start_of_line() {
amt--
num_of_words_moved++
}
if amt > 0 {
if traverse_line_breaks && self.input_state.cursor.Y > 0 {
self.input_state.cursor.Y--
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
num_of_words_moved += self.move_to_start_of_word(amt, traverse_line_breaks, has_word_chars)
}
}
return
}
func (self *Readline) kill_text(text string) {
if ActionStartKillActions < self.last_action && self.last_action < ActionEndKillActions {
self.kill_ring.append_to_existing_item(text)
} else {
self.kill_ring.add_new_item(text)
}
}
func (self *Readline) kill_to_end_of_line() bool {
line := self.input_state.lines[self.input_state.cursor.Y]
if self.input_state.cursor.X >= len(line) {
return false
}
self.input_state.lines[self.input_state.cursor.Y] = line[:self.input_state.cursor.X]
self.kill_text(line[self.input_state.cursor.X:])
return true
}
func (self *Readline) kill_to_start_of_line() bool {
line := self.input_state.lines[self.input_state.cursor.Y]
if self.input_state.cursor.X <= 0 {
return false
}
self.input_state.lines[self.input_state.cursor.Y] = line[self.input_state.cursor.X:]
self.kill_text(line[:self.input_state.cursor.X])
self.input_state.cursor.X = 0
return true
}
func (self *Readline) kill_next_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
before := self.input_state.cursor
num_killed = self.move_to_end_of_word(amt, traverse_line_breaks, has_word_chars)
if num_killed > 0 {
self.kill_text(self.erase_between(before, self.input_state.cursor))
}
return num_killed
}
func (self *Readline) kill_previous_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
before := self.input_state.cursor
num_killed = self.move_to_start_of_word(amt, traverse_line_breaks, has_word_chars)
if num_killed > 0 {
self.kill_text(self.erase_between(self.input_state.cursor, before))
}
return num_killed
}
func has_no_space_chars(text string) bool {
for _, r := range text {
if unicode.IsSpace(r) {
return false
}
}
return true
}
func (self *Readline) kill_previous_space_delimited_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
before := self.input_state.cursor
num_killed = self.move_to_start_of_word(amt, traverse_line_breaks, has_no_space_chars)
if num_killed > 0 {
self.kill_text(self.erase_between(self.input_state.cursor, before))
}
return num_killed
}
func (self *Readline) ensure_position_in_bounds(pos *Position) *Position {
pos.Y = max(0, min(pos.Y, len(self.input_state.lines)-1))
line := self.input_state.lines[pos.Y]
pos.X = max(0, min(pos.X, len(line)))
return pos
}
func (self *Readline) yank(repeat_count uint, pop bool) bool {
if pop && self.last_action != ActionYank && self.last_action != ActionPopYank {
return false
}
text := ""
if pop {
text = self.kill_ring.pop_yank()
} else {
text = self.kill_ring.yank()
}
if text == "" {
return false
}
before := self.input_state.cursor
if pop {
self.ensure_position_in_bounds(&self.last_yank_extent.start)
self.ensure_position_in_bounds(&self.last_yank_extent.end)
self.erase_between(self.last_yank_extent.start, self.last_yank_extent.end)
self.input_state.cursor = self.last_yank_extent.start
before = self.input_state.cursor
}
self.add_text(text)
self.last_yank_extent.start = before
self.last_yank_extent.end = self.input_state.cursor
return true
}
func (self *Readline) history_first() bool {
self.create_history_matches()
return self.history_matches.first(self)
}
func (self *Readline) history_last() bool {
self.create_history_matches()
return self.history_matches.last(self)
}
func (self *Readline) history_prev(repeat_count uint) bool {
self.create_history_matches()
return self.history_matches.previous(repeat_count, self)
}
func (self *Readline) history_next(repeat_count uint) bool {
self.create_history_matches()
return self.history_matches.next(repeat_count, self)
}
func (self *Readline) _perform_action(ac Action, repeat_count uint) (err error, dont_set_last_action bool) {
switch ac {
case ActionBackspace:
if self.history_search != nil {
if self.remove_text_from_history_search(repeat_count) > 0 {
return
}
} else {
if self.erase_chars_before_cursor(repeat_count, true) > 0 {
return
}
}
case ActionDelete:
if self.erase_chars_after_cursor(repeat_count, true) > 0 {
return
}
case ActionMoveToStartOfLine:
if self.move_to_start_of_line() {
return
}
case ActionMoveToEndOfLine:
if self.move_to_end_of_line() {
return
}
case ActionMoveToEndOfWord:
if self.move_to_end_of_word(repeat_count, true, has_word_chars) > 0 {
return
}
case ActionMoveToStartOfWord:
if self.move_to_start_of_word(repeat_count, true, has_word_chars) > 0 {
return
}
case ActionMoveToStartOfDocument:
if self.move_to_start() {
return
}
case ActionMoveToEndOfDocument:
if self.move_to_end() {
return
}
case ActionCursorLeft:
if self.move_cursor_left(repeat_count, true) > 0 {
return
}
case ActionCursorRight:
if self.move_cursor_right(repeat_count, true) > 0 {
return
}
case ActionEndInput:
line := self.input_state.lines[self.input_state.cursor.Y]
if line == "" {
err = io.EOF
} else {
err = self.perform_action(ActionAcceptInput, 1)
}
return
case ActionAcceptInput:
err = ErrAcceptInput
return
case ActionCursorUp:
if self.move_cursor_vertically(-int(repeat_count)) != 0 {
return
}
case ActionCursorDown:
if self.move_cursor_vertically(int(repeat_count)) != 0 {
return
}
case ActionHistoryPreviousOrCursorUp:
dont_set_last_action = true
if self.perform_action(ActionCursorUp, repeat_count) == ErrCouldNotPerformAction {
err = self.perform_action(ActionHistoryPrevious, repeat_count)
}
return
case ActionHistoryNextOrCursorDown:
dont_set_last_action = true
if self.perform_action(ActionCursorDown, repeat_count) == ErrCouldNotPerformAction {
err = self.perform_action(ActionHistoryNext, repeat_count)
}
return
case ActionHistoryFirst:
if self.history_first() {
return
}
case ActionHistoryPrevious:
if self.history_prev(repeat_count) {
return
}
case ActionHistoryNext:
if self.history_next(repeat_count) {
return
}
case ActionHistoryLast:
if self.history_last() {
return
}
case ActionClearScreen:
self.loop.StartAtomicUpdate()
self.loop.ClearScreen()
self.RedrawNonAtomic()
self.loop.EndAtomicUpdate()
return
case ActionKillToEndOfLine:
if self.kill_to_end_of_line() {
return
}
case ActionKillToStartOfLine:
if self.kill_to_start_of_line() {
return
}
case ActionKillNextWord:
if self.kill_next_word(repeat_count, true) > 0 {
return
}
case ActionKillPreviousWord:
if self.kill_previous_word(repeat_count, true) > 0 {
return
}
case ActionKillPreviousSpaceDelimitedWord:
if self.kill_previous_space_delimited_word(repeat_count, true) > 0 {
return
}
case ActionYank:
if self.yank(repeat_count, false) {
return
}
case ActionPopYank:
if self.yank(repeat_count, true) {
return
}
case ActionAbortCurrentLine:
self.loop.QueueWriteString("\r\n")
self.ResetText()
return
case ActionHistoryIncrementalSearchForwards:
if self.history_search == nil {
self.create_history_search(false, repeat_count)
return
}
if self.next_history_search(false, repeat_count) {
return
}
case ActionHistoryIncrementalSearchBackwards:
if self.history_search == nil {
self.create_history_search(true, repeat_count)
return
}
if self.next_history_search(true, repeat_count) {
return
}
case ActionAddText:
text := strings.Repeat(self.text_to_be_added, int(repeat_count))
self.text_to_be_added = ""
if self.history_search != nil {
self.add_text_to_history_search(text)
} else {
self.add_text(text)
}
return
case ActionTerminateHistorySearchAndRestore:
if self.history_search != nil {
self.end_history_search(false)
return
}
case ActionTerminateHistorySearchAndApply:
if self.history_search != nil {
self.end_history_search(true)
return
}
case ActionCompleteForward:
if self.complete(true, repeat_count) {
return
}
case ActionCompleteBackward:
if self.complete(false, repeat_count) {
return
}
}
err = ErrCouldNotPerformAction
return
}
func (self *Readline) perform_action(ac Action, repeat_count uint) error {
err, dont_set_last_action := self._perform_action(ac, repeat_count)
if err == nil && !dont_set_last_action {
self.last_action = ac
if self.completions.current.results != nil && ac != ActionCompleteForward && ac != ActionCompleteBackward {
self.completions.current = completion{}
}
}
return err
}
+567
View File
@@ -0,0 +1,567 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"container/list"
"fmt"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
"strconv"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func new_rl() *Readline {
lp, _ := loop.New()
rl := New(lp, RlInit{Prompt: "$$ "})
rl.screen_width = 10
rl.screen_height = 100
return rl
}
func test_func(t *testing.T) func(string, func(*Readline), ...string) *Readline {
return func(initial string, prepare func(rl *Readline), expected ...string) *Readline {
rl := new_rl()
rl.add_text(initial)
if prepare != nil {
prepare(rl)
}
if len(expected) > 0 {
if expected[0] != rl.text_upto_cursor_pos() {
t.Fatalf("Text upto cursor pos not as expected for: %#v\n%#v != %#v", initial, expected[0], rl.text_upto_cursor_pos())
}
}
if len(expected) > 1 {
if expected[1] != rl.text_after_cursor_pos() {
t.Fatalf("Text after cursor pos not as expected for: %#v\n%#v != %#v", initial, expected[1], rl.text_after_cursor_pos())
}
}
if len(expected) > 2 {
if expected[2] != rl.all_text() {
t.Fatalf("Text not as expected for: %#v\n%#v != %#v", initial, expected[2], rl.all_text())
}
}
return rl
}
}
func TestAddText(t *testing.T) {
dt := test_func(t)
dt("test", nil, "test", "", "test")
dt("1234\n", nil, "1234\n", "", "1234\n")
dt("abcd", func(rl *Readline) {
rl.input_state.cursor.X = 2
rl.add_text("12")
}, "ab12", "cd", "ab12cd")
dt("abcd", func(rl *Readline) {
rl.input_state.cursor.X = 2
rl.add_text("12\n34")
}, "ab12\n34", "cd", "ab12\n34cd")
dt("abcd\nxyz", func(rl *Readline) {
rl.input_state.cursor.X = 2
rl.add_text("12\n34")
}, "abcd\nxy12\n34", "z", "abcd\nxy12\n34z")
}
func TestGetScreenLines(t *testing.T) {
rl := new_rl()
p := func(primary bool) Prompt {
if primary {
return rl.prompt
}
return rl.continuation_prompt
}
tsl := func(expected ...ScreenLine) {
q := rl.get_screen_lines()
actual := make([]ScreenLine, len(q))
for i, x := range q {
actual[i] = *x
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Did not get expected screen lines for: %#v and cursor: %+v\n%s", rl.AllText(), rl.input_state.cursor, diff)
}
}
tsl(ScreenLine{Prompt: p(true), CursorCell: 3, AfterLineBreak: true})
rl.add_text("123")
tsl(ScreenLine{Prompt: p(true), CursorCell: 6, Text: "123", CursorTextPos: 3, TextLengthInCells: 3, AfterLineBreak: true})
rl.add_text("456")
tsl(ScreenLine{Prompt: p(true), CursorCell: 9, Text: "123456", CursorTextPos: 6, TextLengthInCells: 6, AfterLineBreak: true})
rl.add_text("7")
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 7},
)
rl.add_text("89")
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 7, Text: "89", CursorCell: 2, TextLengthInCells: 2, CursorTextPos: 2},
)
rl.ResetText()
rl.add_text("123\n456abcdeXYZ")
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: 3, CursorTextPos: 3, Text: "XYZ"},
)
rl.input_state.cursor = Position{X: 2}
tsl(
ScreenLine{Prompt: p(true), CursorCell: 5, Text: "123", CursorTextPos: 2, TextLengthInCells: 3, AfterLineBreak: true},
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: -1, CursorTextPos: -1, Text: "XYZ"},
)
rl.input_state.cursor = Position{X: 2, Y: 1}
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: 4, CursorTextPos: 2, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: -1, CursorTextPos: -1, Text: "XYZ"},
)
rl.input_state.cursor = Position{X: 8, Y: 1}
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: 0, CursorTextPos: 0, Text: "XYZ"},
)
rl.ResetText()
rl.add_text("1234567\nabc")
rl.input_state.cursor = Position{X: 7}
tsl(
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "abc", CursorCell: 2, TextLengthInCells: 3, CursorTextPos: 0, AfterLineBreak: true},
)
}
func TestCursorMovement(t *testing.T) {
dt := test_func(t)
left := func(rl *Readline, amt uint, moved_amt uint, traverse_line_breaks bool) {
actual := rl.move_cursor_left(amt, traverse_line_breaks)
if actual != moved_amt {
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %#v != %#v", amt, actual, moved_amt)
}
}
dt("one\ntwo", func(rl *Readline) {
left(rl, 2, 2, false)
}, "one\nt", "wo")
dt("one\ntwo", func(rl *Readline) {
left(rl, 4, 3, false)
}, "one\n", "two")
dt("one\ntwo", func(rl *Readline) {
left(rl, 4, 4, true)
}, "one", "\ntwo")
dt("one\ntwo", func(rl *Readline) {
left(rl, 7, 7, true)
}, "", "one\ntwo")
dt("one\ntwo", func(rl *Readline) {
left(rl, 10, 7, true)
}, "", "one\ntwo")
dt("one😀", func(rl *Readline) {
left(rl, 1, 1, false)
}, "one", "😀")
dt("oneà", func(rl *Readline) {
left(rl, 1, 1, false)
}, "one", "à")
right := func(rl *Readline, amt uint, moved_amt uint, traverse_line_breaks bool) {
rl.input_state.cursor.Y = 0
rl.input_state.cursor.X = 0
actual := rl.move_cursor_right(amt, traverse_line_breaks)
if actual != moved_amt {
t.Fatalf("Failed to move cursor by %d\nactual != expected: %d != %d", amt, actual, moved_amt)
}
}
dt("one\ntwo", func(rl *Readline) {
right(rl, 2, 2, false)
}, "on", "e\ntwo")
dt("one\ntwo", func(rl *Readline) {
right(rl, 4, 3, false)
}, "one", "\ntwo")
dt("one\ntwo", func(rl *Readline) {
right(rl, 4, 4, true)
}, "one\n", "two")
dt("😀one", func(rl *Readline) {
right(rl, 1, 1, false)
}, "😀", "one")
dt("àb", func(rl *Readline) {
right(rl, 1, 1, false)
}, "à", "b")
rl := new_rl()
vert := func(amt int, moved_amt int, text_upto_cursor_pos string, initials ...Position) {
initial := Position{}
if len(initials) > 0 {
initial = initials[0]
}
rl.input_state.cursor = initial
actual := rl.move_cursor_vertically(amt)
if actual != moved_amt {
t.Fatalf("Failed to move cursor by %#v for: %#v \nactual != expected: %#v != %#v", amt, rl.AllText(), actual, moved_amt)
}
if diff := cmp.Diff(text_upto_cursor_pos, rl.text_upto_cursor_pos()); diff != "" {
t.Fatalf("Did not get expected screen lines for: %#v and cursor: %+v\n%s", rl.AllText(), initial, diff)
}
}
rl.ResetText()
rl.add_text("1234567xy\nabcd\n123")
vert(-1, -1, "1234567xy\nabc", Position{X: 3, Y: 2})
vert(-2, -2, "1234567xy", Position{X: 3, Y: 2})
vert(-30, -3, "123", Position{X: 3, Y: 2})
rl.ResetText()
rl.add_text("o\u0300ne two three\nfour five")
wf := func(amt uint, expected_amt uint, text_before_cursor string) {
pos := rl.input_state.cursor
actual_amt := rl.move_to_end_of_word(amt, true, has_word_chars)
if actual_amt != expected_amt {
t.Fatalf("Failed to move to word end, expected amt (%d) != actual amt (%d)", expected_amt, actual_amt)
}
if diff := cmp.Diff(text_before_cursor, rl.TextBeforeCursor()); diff != "" {
t.Fatalf("Did not get expected text before cursor for: %#v and cursor: %+v\n%s", rl.AllText(), pos, diff)
}
}
rl.input_state.cursor = Position{}
wf(1, 1, "òne")
wf(1, 1, "òne two")
wf(1, 1, "òne two three")
wf(1, 1, "òne two three\nfour")
wf(1, 1, "òne two three\nfour five")
wf(1, 0, "òne two three\nfour five")
rl.input_state.cursor = Position{}
wf(5, 5, "òne two three\nfour five")
rl.input_state.cursor = Position{X: 5}
wf(1, 1, "òne two")
wb := func(amt uint, expected_amt uint, text_before_cursor string) {
pos := rl.input_state.cursor
actual_amt := rl.move_to_start_of_word(amt, true, has_word_chars)
if actual_amt != expected_amt {
t.Fatalf("Failed to move to word end, expected amt (%d) != actual amt (%d)", expected_amt, actual_amt)
}
if diff := cmp.Diff(text_before_cursor, rl.TextBeforeCursor()); diff != "" {
t.Fatalf("Did not get expected text before cursor for: %#v and cursor: %+v\n%s", rl.AllText(), pos, diff)
}
}
rl.input_state.cursor = Position{X: 2}
wb(1, 1, "")
rl.input_state.cursor = Position{X: 8, Y: 1}
wb(1, 1, "òne two three\nfour ")
wb(1, 1, "òne two three\n")
wb(1, 1, "òne two ")
wb(1, 1, "òne ")
wb(1, 1, "")
wb(1, 0, "")
rl.input_state.cursor = Position{X: 8, Y: 1}
wb(5, 5, "")
rl.input_state.cursor = Position{X: 5}
wb(1, 1, "")
}
func TestYanking(t *testing.T) {
rl := new_rl()
as_slice := func(l *list.List) []string {
ans := make([]string, 0, l.Len())
for e := l.Front(); e != nil; e = e.Next() {
ans = append(ans, e.Value.(string))
}
return ans
}
assert_items := func(expected ...string) {
if diff := cmp.Diff(expected, as_slice(rl.kill_ring.items)); diff != "" {
t.Fatalf("kill ring items not as expected\n%s", diff)
}
}
assert_text := func(expected string) {
if diff := cmp.Diff(expected, rl.all_text()); diff != "" {
t.Fatalf("text not as expected:\n%s", diff)
}
}
rl.add_text("1 2 3\none two three")
rl.perform_action(ActionKillToStartOfLine, 1)
assert_items("one two three")
rl.perform_action(ActionCursorUp, 1)
rl.perform_action(ActionKillToEndOfLine, 1)
assert_items("1 2 3", "one two three")
rl.perform_action(ActionYank, 1)
assert_text("1 2 3\n")
rl.perform_action(ActionYank, 1)
assert_text("1 2 31 2 3\n")
rl.perform_action(ActionPopYank, 1)
assert_text("1 2 3one two three\n")
rl.perform_action(ActionPopYank, 1)
assert_text("1 2 31 2 3\n")
rl.ResetText()
rl.kill_ring.clear()
rl.add_text("one two three")
rl.perform_action(ActionMoveToStartOfLine, 1)
rl.perform_action(ActionKillNextWord, 1)
assert_items("one")
assert_text(" two three")
rl.perform_action(ActionKillNextWord, 1)
assert_items("one two")
assert_text(" three")
rl.perform_action(ActionCursorRight, 1)
rl.perform_action(ActionKillNextWord, 1)
assert_items("three", "one two")
assert_text(" ")
}
func TestEraseChars(t *testing.T) {
dt := test_func(t)
backspace := func(rl *Readline, amt uint, erased_amt uint, traverse_line_breaks bool) {
actual := rl.erase_chars_before_cursor(amt, traverse_line_breaks)
if actual != erased_amt {
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %d != %d", amt, actual, erased_amt)
}
}
dt("one\ntwo", func(rl *Readline) {
backspace(rl, 2, 2, false)
}, "one\nt", "")
dt("one\ntwo", func(rl *Readline) {
rl.input_state.cursor.X = 1
backspace(rl, 2, 1, false)
}, "one\n", "wo")
dt("one\ntwo", func(rl *Readline) {
rl.input_state.cursor.X = 1
backspace(rl, 2, 2, true)
}, "one", "wo")
dt("a😀", func(rl *Readline) {
backspace(rl, 1, 1, false)
}, "a", "")
dt("bà", func(rl *Readline) {
backspace(rl, 1, 1, false)
}, "b", "")
del := func(rl *Readline, amt uint, erased_amt uint, traverse_line_breaks bool) {
rl.input_state.cursor.Y = 0
rl.input_state.cursor.X = 0
actual := rl.erase_chars_after_cursor(amt, traverse_line_breaks)
if actual != erased_amt {
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %d != %d", amt, actual, erased_amt)
}
}
dt("one\ntwo", func(rl *Readline) {
del(rl, 2, 2, false)
}, "", "e\ntwo")
dt("😀a", func(rl *Readline) {
del(rl, 1, 1, false)
}, "", "a")
dt("àb", func(rl *Readline) {
del(rl, 1, 1, false)
}, "", "b")
dt("one\ntwo\nthree", func(rl *Readline) {
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
}, "oree", "")
dt("one\ntwo\nthree", func(rl *Readline) {
rl.input_state.cursor.X = 1
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
}, "o", "ree")
dt("one\ntwo\nthree", func(rl *Readline) {
rl.input_state.cursor = Position{X: 1, Y: 1}
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
}, "o", "ree")
dt("one\ntwo\nthree", func(rl *Readline) {
rl.input_state.cursor = Position{X: 1, Y: 0}
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
}, "o", "ree")
dt("one\ntwo\nthree", func(rl *Readline) {
rl.input_state.cursor = Position{X: 0, Y: 0}
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
}, "", "oree")
}
func TestNumberArgument(t *testing.T) {
rl := new_rl()
rl.screen_width = 100
test := func(ac Action, before_cursor, after_cursor string) {
rl.dispatch_key_action(ac)
if diff := cmp.Diff(before_cursor, rl.text_upto_cursor_pos()); diff != "" {
t.Fatalf("The text before the cursor was not as expected for action: %#v\n%s", ac, diff)
}
if diff := cmp.Diff(after_cursor, rl.text_after_cursor_pos()); diff != "" {
t.Fatalf("The text after the cursor was not as expected for action: %#v\n%s", ac, diff)
}
}
sw := func(num int) {
q := rl.format_arg_prompt(strconv.Itoa(num))
for _, sl := range rl.get_screen_lines() {
if num <= 0 && !strings.Contains(sl.Prompt.Text, "$$") {
t.Fatalf("arg prompt unexpectedly present for: %#v", rl.AllText())
}
if num > 0 && !strings.Contains(sl.Prompt.Text, q) {
t.Fatalf("arg prompt unexpectedly not present for: %#v prompt: %#v", rl.AllText(), sl.Prompt.Text)
}
}
}
sw(0)
rl.dispatch_key_action(ActionNumericArgumentDigit1)
sw(1)
rl.dispatch_key_action(ActionNumericArgumentDigit0)
sw(10)
rl.text_to_be_added = "x"
test(ActionAddText, "xxxxxxxxxx", "")
sw(0)
test(ActionNumericArgumentDigit0, "xxxxxxxxxx0", "")
sw(0)
rl.dispatch_key_action(ActionNumericArgumentDigit1)
test(ActionNumericArgumentDigitMinus, "xxxxxxxxxx0-", "")
sw(0)
rl.dispatch_key_action(ActionNumericArgumentDigit1)
sw(1)
rl.dispatch_key_action(ActionNumericArgumentDigit1)
sw(11)
test(ActionCursorLeft, "x", "xxxxxxxxx0-")
sw(0)
}
func TestHistory(t *testing.T) {
rl := new_rl()
add_item := func(x string) {
rl.history.AddItem(x, 0)
}
add_item("a one")
add_item("a two")
add_item("b three")
add_item("b four")
test := func(ac Action, before_cursor, after_cursor string) {
rl.perform_action(ac, 1)
if diff := cmp.Diff(before_cursor, rl.text_upto_cursor_pos()); diff != "" {
t.Fatalf("The text before the cursor was not as expected for action: %#v\n%s", ac, diff)
}
if diff := cmp.Diff(after_cursor, rl.text_after_cursor_pos()); diff != "" {
t.Fatalf("The text after the cursor was not as expected for action: %#v\n%s", ac, diff)
}
}
test(ActionHistoryPreviousOrCursorUp, "b four", "")
test(ActionHistoryPreviousOrCursorUp, "b three", "")
test(ActionHistoryPrevious, "a two", "")
test(ActionHistoryPrevious, "a one", "")
test(ActionHistoryPrevious, "a one", "")
test(ActionHistoryNext, "a two", "")
test(ActionHistoryNext, "b three", "")
test(ActionHistoryNext, "b four", "")
test(ActionHistoryNext, "", "")
test(ActionHistoryNext, "", "")
test(ActionHistoryPrevious, "b four", "")
test(ActionHistoryPrevious, "b three", "")
test(ActionHistoryNext, "b four", "")
rl.ResetText()
rl.add_text("a")
test(ActionHistoryPrevious, "a two", "")
test(ActionHistoryPrevious, "a one", "")
test(ActionHistoryPrevious, "a one", "")
test(ActionHistoryNext, "a two", "")
test(ActionHistoryNext, "a", "")
test(ActionHistoryNext, "a", "")
ah := func(before_cursor, after_cursor string) {
ab := rl.text_upto_cursor_pos()
aa := rl.text_after_cursor_pos()
if diff := cmp.Diff(before_cursor, ab); diff != "" {
t.Fatalf("Text before cursor not as expected:\n%s", diff)
}
if diff := cmp.Diff(after_cursor, aa); diff != "" {
t.Fatalf("Text after cursor not as expected:\n%s", diff)
}
}
add_item("xyz1")
add_item("xyz2")
add_item("xyz11")
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
ah("", "")
rl.text_to_be_added = "z"
rl.perform_action(ActionAddText, 1)
ah("xy", "z11")
rl.text_to_be_added = "2"
rl.perform_action(ActionAddText, 1)
ah("xy", "z2")
rl.text_to_be_added = "m"
rl.perform_action(ActionAddText, 1)
ah("No matches for: z2m", "")
rl.perform_action(ActionBackspace, 1)
ah("xy", "z2")
rl.perform_action(ActionBackspace, 1)
ah("xy", "z2")
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
ah("xy", "z1")
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
ah("xy", "z1")
rl.perform_action(ActionHistoryIncrementalSearchForwards, 1)
ah("xy", "z2")
rl.perform_action(ActionTerminateHistorySearchAndRestore, 1)
ah("a", "")
}
func TestReadlineCompletion(t *testing.T) {
completer := func(before_cursor, after_cursor string) (ans *cli.Completions) {
root := cli.NewRootCommand()
c := root.AddSubCommand(&cli.Command{Name: "test-completion"})
c.AddSubCommand(&cli.Command{Name: "a1"})
c.AddSubCommand(&cli.Command{Name: "a11"})
c.AddSubCommand(&cli.Command{Name: "a2"})
prefix := c.Name + " "
text := prefix + before_cursor
argv, position_of_last_arg := shlex.SplitForCompletion(text)
if len(argv) == 0 || position_of_last_arg < len(prefix) {
return
}
ans = root.GetCompletions(argv, nil)
ans.CurrentWordIdx = position_of_last_arg - len(prefix)
return
}
rl := new_rl()
rl.completions.completer = completer
ah := func(before_cursor, after_cursor string) {
ab := rl.text_upto_cursor_pos()
aa := rl.text_after_cursor_pos()
if diff := cmp.Diff(before_cursor, ab); diff != "" {
t.Fatalf("Text before cursor not as expected:\n%s", diff)
}
if diff := cmp.Diff(after_cursor, aa); diff != "" {
t.Fatalf("Text after cursor not as expected:\n%s", diff)
}
actual, _ := rl.completion_screen_lines()
expected := []string{"a1 a11 a2 "}
if diff := cmp.Diff(expected, actual[1:]); diff != "" {
t.Fatalf("Completion screen lines not as expected:\n%s", diff)
}
}
rl.add_text("a")
rl.perform_action(ActionCompleteForward, 1)
ah("a", "")
rl.perform_action(ActionCompleteForward, 1)
ah("a1 ", "")
rl.perform_action(ActionCompleteForward, 1)
ah("a11 ", "")
rl.perform_action(ActionCompleteForward, 1)
ah("a2 ", "")
rl.perform_action(ActionCompleteBackward, 1)
ah("a11 ", "")
}
+303
View File
@@ -0,0 +1,303 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"container/list"
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
const ST = "\x1b\\"
const PROMPT_MARK = "\x1b]133;"
type SyntaxHighlightFunction = func(text string, x, y int) string
type CompleterFunction = func(before_cursor, after_cursor string) *cli.Completions
type RlInit struct {
Prompt string
HistoryPath string
HistoryCount int
ContinuationPrompt string
EmptyContinuationPrompt bool
DontMarkPrompts bool
SyntaxHighlighter SyntaxHighlightFunction
Completer CompleterFunction
}
type Position struct {
X int
Y int
}
func (self Position) Less(other Position) bool {
return self.Y < other.Y || (self.Y == other.Y && self.X < other.X)
}
type kill_ring struct {
items *list.List
}
func (self *kill_ring) append_to_existing_item(text string) {
e := self.items.Front()
if e == nil {
self.add_new_item(text)
}
e.Value = e.Value.(string) + text
}
func (self *kill_ring) add_new_item(text string) {
if text != "" {
self.items.PushFront(text)
}
}
func (self *kill_ring) yank() string {
e := self.items.Front()
if e == nil {
return ""
}
return e.Value.(string)
}
func (self *kill_ring) pop_yank() string {
e := self.items.Front()
if e == nil {
return ""
}
self.items.MoveToBack(e)
return self.yank()
}
func (self *kill_ring) clear() {
self.items = self.items.Init()
}
type Prompt struct {
Text string
Length int
}
type InputState struct {
// Input lines
lines []string
// The cursor position in the text
cursor Position
}
func (self InputState) copy() InputState {
ans := self
l := make([]string, len(self.lines))
copy(l, self.lines)
ans.lines = l
return ans
}
type syntax_highlighted struct {
lines []string
src_for_last_highlight string
highlighter SyntaxHighlightFunction
last_highlighter_name string
}
type Readline struct {
prompt, continuation_prompt Prompt
mark_prompts bool
loop *loop.Loop
history *History
kill_ring kill_ring
input_state InputState
// The number of lines after the initial line on the screen
cursor_y int
screen_width, screen_height int
last_yank_extent struct {
start, end Position
}
bracketed_paste_buffer strings.Builder
last_action Action
history_matches *HistoryMatches
history_search *HistorySearch
keyboard_state KeyboardState
fmt_ctx *markup.Context
text_to_be_added string
syntax_highlighted syntax_highlighted
completions completions
}
func (self *Readline) make_prompt(text string, is_secondary bool) Prompt {
if self.mark_prompts {
m := PROMPT_MARK + "A"
if is_secondary {
m += ";k=s"
}
text = m + ST + text
}
return Prompt{Text: text, Length: wcswidth.Stringwidth(text)}
}
func New(loop *loop.Loop, r RlInit) *Readline {
hc := r.HistoryCount
if hc == 0 {
hc = 8192
}
ans := &Readline{
mark_prompts: !r.DontMarkPrompts, fmt_ctx: markup.New(true),
loop: loop, input_state: InputState{lines: []string{""}}, history: NewHistory(r.HistoryPath, hc),
syntax_highlighted: syntax_highlighted{highlighter: r.SyntaxHighlighter},
completions: completions{completer: r.Completer},
kill_ring: kill_ring{items: list.New().Init()},
}
if ans.completions.completer == nil && r.HistoryPath != "" {
ans.completions.completer = ans.HistoryCompleter
}
ans.prompt = ans.make_prompt(r.Prompt, false)
t := ""
if r.ContinuationPrompt != "" || !r.EmptyContinuationPrompt {
t = r.ContinuationPrompt
if t == "" {
t = ans.fmt_ctx.Yellow(">") + " "
}
}
ans.continuation_prompt = ans.make_prompt(t, true)
return ans
}
func (self *Readline) HistoryCompleter(before_cursor, after_cursor string) *cli.Completions {
return self.history_completer(before_cursor, after_cursor)
}
func (self *Readline) SetPrompt(prompt string) {
self.prompt = self.make_prompt(prompt, false)
}
func (self *Readline) Shutdown() {
self.history.Shutdown()
}
func (self *Readline) AddHistoryItem(hi HistoryItem) {
self.history.merge_items(hi)
}
func (self *Readline) ResetText() {
self.input_state = InputState{lines: []string{""}}
self.last_action = ActionNil
self.keyboard_state = KeyboardState{}
self.history_search = nil
self.completions.current = completion{}
self.cursor_y = 0
}
func (self *Readline) ChangeLoopAndResetText(lp *loop.Loop) {
self.loop = lp
self.ResetText()
}
func (self *Readline) Start() {
self.loop.SetCursorShape(loop.BAR_CURSOR, true)
self.loop.StartBracketedPaste()
self.Redraw()
}
func (self *Readline) End() {
self.loop.SetCursorShape(loop.BLOCK_CURSOR, true)
self.loop.EndBracketedPaste()
self.loop.QueueWriteString("\r\n")
if self.mark_prompts {
self.loop.QueueWriteString(PROMPT_MARK + "C" + ST)
}
}
func MarkOutputStart() string {
return PROMPT_MARK + "C" + ST
}
func (self *Readline) Redraw() {
self.loop.StartAtomicUpdate()
self.RedrawNonAtomic()
self.loop.EndAtomicUpdate()
}
func (self *Readline) RedrawNonAtomic() {
self.redraw()
}
func (self *Readline) OnKeyEvent(event *loop.KeyEvent) error {
err := self.handle_key_event(event)
if err == ErrCouldNotPerformAction {
err = nil
self.loop.Beep()
}
return err
}
func (self *Readline) OnText(text string, from_key_event bool, in_bracketed_paste bool) error {
if in_bracketed_paste {
self.bracketed_paste_buffer.WriteString(text)
return nil
}
if self.bracketed_paste_buffer.Len() > 0 {
self.bracketed_paste_buffer.WriteString(text)
text = self.bracketed_paste_buffer.String()
self.bracketed_paste_buffer.Reset()
}
self.text_to_be_added = text
return self.dispatch_key_action(ActionAddText)
}
func (self *Readline) TextBeforeCursor() string {
return self.text_upto_cursor_pos()
}
func (self *Readline) TextAfterCursor() string {
return self.text_after_cursor_pos()
}
func (self *Readline) AllText() string {
return self.all_text()
}
func (self *Readline) SetText(text string) {
self.set_text(text)
}
func (self *Readline) MoveCursorToEnd() bool {
return self.move_to_end()
}
// PerformAction runs the specified editing Action directly, without going through
// key resolution. Useful for callers that want to bind their own keys to a
// specific line-editing operation, bypassing this package's own default keymap.
func (self *Readline) PerformAction(ac Action, repeat_count uint) error {
if repeat_count == 0 {
repeat_count = 1
}
err := self.perform_action(ac, repeat_count)
if err == ErrCouldNotPerformAction {
self.loop.Beep()
err = nil
}
return err
}
func (self *Readline) CursorAtEndOfLine() bool {
return self.input_state.cursor.X >= len(self.input_state.lines[self.input_state.cursor.Y])
}
func (self *Readline) ClearCachedScreenSize() {
self.screen_width, self.screen_height = 0, 0
}
func (self *Readline) OnResize(old_size loop.ScreenSize, new_size loop.ScreenSize) error {
self.ClearCachedScreenSize()
self.Redraw()
return nil
}
+280
View File
@@ -0,0 +1,280 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type completion struct {
before_cursor, after_cursor string
results *cli.Completions
results_displayed, forwards bool
num_of_matches, current_match int
rendered_at_screen_width int
rendered_lines []string
last_rendered_above bool
}
func (self *completion) initialize() {
self.num_of_matches = 0
if self.results != nil {
for _, g := range self.results.Groups {
self.num_of_matches += len(g.Matches)
}
}
self.current_match = -1
if !self.forwards {
self.current_match = self.num_of_matches
}
if self.num_of_matches == 1 {
self.current_match = 0
}
}
func (self *completion) current_match_text() string {
if self.results != nil {
i := 0
for _, g := range self.results.Groups {
for _, m := range g.Matches {
if i == self.current_match {
t := m.Word
if !g.NoTrailingSpace && t != "" {
t += " "
}
return t
}
i++
}
}
}
return ""
}
type completions struct {
completer CompleterFunction
current completion
}
func (self *Readline) complete(forwards bool, repeat_count uint) bool {
c := &self.completions
if c.completer == nil {
return false
}
if self.last_action == ActionCompleteForward || self.last_action == ActionCompleteBackward {
if c.current.num_of_matches == 0 {
return false
}
delta := -1
if forwards {
delta = 1
}
repeat_count %= uint(c.current.num_of_matches)
delta *= int(repeat_count)
c.current.current_match = (c.current.current_match + delta + c.current.num_of_matches) % c.current.num_of_matches
repeat_count = 0
} else {
before, after := self.text_upto_cursor_pos(), self.text_after_cursor_pos()
c.current = completion{before_cursor: before, after_cursor: after, forwards: forwards, results: c.completer(before, after)}
c.current.initialize()
if repeat_count > 0 {
repeat_count--
}
if c.current.current_match != 0 {
if self.loop != nil {
self.loop.Beep()
}
}
}
c.current.forwards = forwards
if c.current.results == nil {
return false
}
ct := c.current.current_match_text()
if ct != "" {
all_text_before_completion := self.AllText()
before := c.current.before_cursor[:c.current.results.CurrentWordIdx] + ct
after := c.current.after_cursor
self.input_state.lines = utils.Splitlines(before)
if len(self.input_state.lines) == 0 {
self.input_state.lines = []string{""}
}
self.input_state.cursor.Y = len(self.input_state.lines) - 1
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
al := utils.Splitlines(after)
if len(al) > 0 {
self.input_state.lines[self.input_state.cursor.Y] += al[0]
self.input_state.lines = append(self.input_state.lines, al[1:]...)
}
if c.current.num_of_matches == 1 && self.AllText() == all_text_before_completion && repeat_count > 0 {
// when there is only a single match and it has already been inserted there is no point iterating over current completions
orig := self.last_action
self.last_action = ActionNil
self.complete(true, 1)
self.last_action = orig
}
}
if repeat_count > 0 {
self.complete(forwards, repeat_count)
}
return true
}
func (self *Readline) screen_lines_for_match_group_with_descriptions(g *cli.MatchGroup, lines []string) []string {
maxw := 0
for _, m := range g.Matches {
l := wcswidth.Stringwidth(m.Word)
if l > 16 {
maxw = 16
break
}
if l > maxw {
maxw = l
}
}
for _, m := range g.Matches {
lines = append(lines, utils.Splitlines(m.FormatForCompletionList(maxw, self.fmt_ctx, self.screen_width))...)
}
return lines
}
type cell struct {
text string
length int
}
func (self cell) whitespace(desired_length int) string {
return strings.Repeat(" ", max(0, desired_length-self.length))
}
type column struct {
cells []cell
length int
is_last bool
}
func (self *column) update_length() int {
self.length = 0
for _, c := range self.cells {
if c.length > self.length {
self.length = c.length
}
}
if !self.is_last {
self.length++
}
return self.length
}
func layout_words_in_table(words []string, lengths map[string]int, num_cols int) ([]column, int) {
cols := make([]column, num_cols)
for i, col := range cols {
col.cells = make([]cell, 0, len(words))
if i == len(cols)-1 {
col.is_last = true
}
}
c := 0
for _, word := range words {
cols[c].cells = append(cols[c].cells, cell{word, lengths[word]})
c++
if c >= num_cols {
c = 0
}
}
total_length := 0
for i := range cols {
if d := len(cols[0].cells) - len(cols[i].cells); d > 0 {
cols[i].cells = append(cols[i].cells, make([]cell, d)...)
}
total_length += cols[i].update_length()
}
return cols, total_length
}
func (self *Readline) screen_lines_for_match_group_without_descriptions(g *cli.MatchGroup, lines []string) []string {
words := make([]string, len(g.Matches))
lengths := make(map[string]int, len(words))
max_length := 0
for i, m := range g.Matches {
words[i] = m.Word
l := wcswidth.Stringwidth(words[i])
lengths[words[i]] = l
if l > max_length {
max_length = l
}
}
var ans []column
ncols := max(1, self.screen_width/(max_length+1))
for {
cols, total_length := layout_words_in_table(words, lengths, ncols)
if total_length > self.screen_width {
break
}
ans = cols
ncols++
}
if ans == nil {
for _, w := range words {
if lengths[w] > self.screen_width {
lines = append(lines, wcswidth.TruncateToVisualLength(w, self.screen_width))
} else {
lines = append(lines, w)
}
}
} else {
for r := 0; r < len(ans[0].cells); r++ {
w := strings.Builder{}
w.Grow(self.screen_width)
for c := 0; c < len(ans); c++ {
cell := ans[c].cells[r]
w.WriteString(cell.text)
if !ans[c].is_last {
w.WriteString(cell.whitespace(ans[c].length))
}
}
lines = append(lines, w.String())
}
}
return lines
}
func (self *Readline) completion_screen_lines() ([]string, bool) {
if self.completions.current.results == nil || self.completions.current.num_of_matches < 2 {
return []string{}, false
}
if len(self.completions.current.rendered_lines) > 0 && self.completions.current.rendered_at_screen_width == self.screen_width {
return self.completions.current.rendered_lines, true
}
lines := make([]string, 0, self.completions.current.num_of_matches)
for _, g := range self.completions.current.results.Groups {
if len(g.Matches) == 0 {
continue
}
if g.Title != "" {
lines = append(lines, self.fmt_ctx.Title(g.Title))
}
has_descriptions := false
for _, m := range g.Matches {
if m.Description != "" {
has_descriptions = true
break
}
}
if has_descriptions {
lines = self.screen_lines_for_match_group_with_descriptions(g, lines)
} else {
lines = self.screen_lines_for_match_group_without_descriptions(g, lines)
}
}
self.completions.current.rendered_lines = lines
self.completions.current.rendered_at_screen_width = self.screen_width
return lines, false
}
+228
View File
@@ -0,0 +1,228 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
"strings"
)
var _ = fmt.Print
func (self *Readline) update_current_screen_size() {
var screen_size loop.ScreenSize
var err error
if self.loop != nil {
screen_size, err = self.loop.ScreenSize()
if err != nil {
screen_size.WidthCells = 80
screen_size.HeightCells = 24
}
} else {
screen_size.WidthCells = 80
screen_size.HeightCells = 24
}
self.screen_width = max(1, int(screen_size.WidthCells))
self.screen_height = max(1, int(screen_size.HeightCells))
}
type ScreenLine struct {
ParentLineNumber, OffsetInParentLine int
Prompt Prompt
TextLengthInCells, CursorCell, CursorTextPos int
Text string
AfterLineBreak bool
}
func (self *Readline) format_arg_prompt(cna string) string {
return fmt.Sprintf("(arg: %s) ", self.fmt_ctx.Yellow(cna))
}
func (self *Readline) prompt_for_line_number(i int) Prompt {
is_line_with_cursor := i == self.input_state.cursor.Y
if is_line_with_cursor && self.keyboard_state.current_numeric_argument != "" {
return self.make_prompt(self.format_arg_prompt(self.keyboard_state.current_numeric_argument), i > 0)
}
if i == 0 {
if self.history_search != nil {
return self.make_prompt(self.history_search_prompt(), i > 0)
}
return self.prompt
}
return self.continuation_prompt
}
func (self *Readline) apply_syntax_highlighting() (lines []string, cursor Position) {
highlighter := self.syntax_highlighted.highlighter
highlighter_name := "default"
if self.history_search != nil {
highlighter = self.history_search_highlighter
highlighter_name = "## history ##"
}
if highlighter == nil {
return self.input_state.lines, self.input_state.cursor
}
src := strings.Join(self.input_state.lines, "\n")
if len(self.syntax_highlighted.lines) > 0 && self.syntax_highlighted.last_highlighter_name == highlighter_name && self.syntax_highlighted.src_for_last_highlight == src {
lines = self.syntax_highlighted.lines
} else {
if src == "" {
lines = []string{""}
} else {
text := highlighter(src, self.input_state.cursor.X, self.input_state.cursor.Y)
lines = utils.Splitlines(text)
for len(lines) < len(self.input_state.lines) {
lines = append(lines, "syntax highlighter malfunctioned")
}
}
}
line := lines[self.input_state.cursor.Y]
w := wcswidth.Stringwidth(self.input_state.lines[self.input_state.cursor.Y][:self.input_state.cursor.X])
x := len(wcswidth.TruncateToVisualLength(line, w))
return lines, Position{X: x, Y: self.input_state.cursor.Y}
}
func (self *Readline) get_screen_lines() []*ScreenLine {
if self.screen_width == 0 || self.screen_height == 0 {
self.update_current_screen_size()
}
lines, cursor := self.apply_syntax_highlighting()
ans := make([]*ScreenLine, 0, len(lines))
found_cursor := false
cursor_at_start_of_next_line := false
for i, line := range lines {
prompt := self.prompt_for_line_number(i)
offset := 0
has_cursor := i == cursor.Y
for is_first := true; is_first || offset < len(line); is_first = false {
l, width := wcswidth.TruncateToVisualLengthWithWidth(line[offset:], self.screen_width-prompt.Length)
sl := ScreenLine{
ParentLineNumber: i, OffsetInParentLine: offset,
Prompt: prompt, TextLengthInCells: width,
CursorCell: -1, Text: l, CursorTextPos: -1, AfterLineBreak: is_first,
}
if cursor_at_start_of_next_line {
cursor_at_start_of_next_line = false
sl.CursorCell = prompt.Length
sl.CursorTextPos = 0
found_cursor = true
}
ans = append(ans, &sl)
if has_cursor && !found_cursor && offset <= cursor.X && cursor.X <= offset+len(l) {
found_cursor = true
ctpos := cursor.X - offset
ccell := prompt.Length + wcswidth.Stringwidth(l[:ctpos])
if ccell >= self.screen_width {
if offset+len(l) < len(line) || i < len(lines)-1 {
cursor_at_start_of_next_line = true
} else {
ans = append(ans, &ScreenLine{ParentLineNumber: i, OffsetInParentLine: len(line)})
}
} else {
sl.CursorTextPos = ctpos
sl.CursorCell = ccell
}
}
prompt = Prompt{}
offset += len(l)
}
}
return ans
}
func (self *Readline) redraw() {
if self.screen_width == 0 || self.screen_height == 0 {
self.update_current_screen_size()
}
if self.screen_width < 4 {
return
}
if self.cursor_y > 0 {
self.loop.MoveCursorVertically(-self.cursor_y)
}
self.loop.QueueWriteString("\r")
self.loop.ClearToEndOfScreen()
prompt_lines := self.get_screen_lines()
csl, csl_cached := self.completion_screen_lines()
render_completion_above := len(csl)+len(prompt_lines) > self.screen_height
completion_needs_render := len(csl) > 0 && (!render_completion_above || !self.completions.current.last_rendered_above || !csl_cached)
final_cursor_x := -1
cursor_y := 0
move_cursor_up_by := 0
render_completion_lines := func() int {
if completion_needs_render {
if render_completion_above {
self.loop.QueueWriteString("\r")
} else {
self.loop.QueueWriteString("\r\n")
}
for i, cl := range csl {
self.loop.QueueWriteString(cl)
if i < len(csl)-1 || render_completion_above {
self.loop.QueueWriteString("\n\r")
}
}
return len(csl)
}
return 0
}
self.loop.AllowLineWrapping(false)
if render_completion_above {
render_completion_lines()
}
self.loop.AllowLineWrapping(true)
self.loop.QueueWriteString("\r")
text_length := 0
for i, sl := range prompt_lines {
cursor_moved_down := false
if i > 0 && sl.AfterLineBreak {
self.loop.QueueWriteString("\r\n")
cursor_moved_down = true
text_length = 0
}
if sl.Prompt.Length > 0 {
p := self.prompt_for_line_number(i)
self.loop.QueueWriteString(p.Text)
text_length += p.Length
}
self.loop.QueueWriteString(sl.Text)
text_length += sl.TextLengthInCells
if text_length == self.screen_width && sl.Text == "" && i == len(prompt_lines)-1 {
self.loop.QueueWriteString("\r\n")
cursor_moved_down = true
text_length = 0
}
if text_length > self.screen_width {
cursor_moved_down = true
text_length -= self.screen_width
}
if sl.CursorCell > -1 {
final_cursor_x = sl.CursorCell
} else if final_cursor_x > -1 {
if cursor_moved_down {
move_cursor_up_by++
}
}
if cursor_moved_down {
cursor_y++
}
}
if !render_completion_above {
move_cursor_up_by += render_completion_lines()
}
self.loop.MoveCursorVertically(-move_cursor_up_by)
self.loop.QueueWriteString("\r")
self.loop.MoveCursorHorizontally(final_cursor_x)
self.cursor_y = 0
cursor_y -= move_cursor_up_by
if cursor_y > 0 {
self.cursor_y = cursor_y
}
}
+431
View File
@@ -0,0 +1,431 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type HistoryItem struct {
Cmd string `json:"cmd"`
Cwd string `json:"cwd,omitempty"`
Timestamp time.Time `json:"timestamp"`
Duration time.Duration `json:"duration,omitempty"`
ExitCode int `json:"exit_code"`
}
type HistoryMatches struct {
items []HistoryItem
prefix string
current_idx int
original_input_state InputState
}
type HistorySearch struct {
query string
tokens []string
items []*HistoryItem
current_idx int
backwards bool
original_input_state InputState
}
type History struct {
file_path string
file *os.File
max_items int
items []HistoryItem
cmd_map map[string]int
}
func map_from_items(items []HistoryItem) map[string]int {
pmap := make(map[string]int, len(items))
for i, hi := range items {
pmap[hi.Cmd] = i
}
return pmap
}
func (self *History) add_item(x HistoryItem) bool {
existing, found := self.cmd_map[x.Cmd]
if found {
if self.items[existing].Timestamp.Before(x.Timestamp) {
self.items[existing] = x
return true
}
return false
}
self.cmd_map[x.Cmd] = len(self.items)
self.items = append(self.items, x)
return true
}
func (self *History) merge_items(items ...HistoryItem) {
if len(self.items) == 0 {
self.items = items
self.cmd_map = map_from_items(self.items)
return
}
if len(items) == 0 {
return
}
changed := false
for _, x := range items {
if self.add_item(x) {
changed = true
}
}
if !changed {
return
}
self.items = utils.StableSort(self.items, func(a, b HistoryItem) int {
return a.Timestamp.Compare(b.Timestamp)
})
if len(self.items) > self.max_items {
self.items = self.items[len(self.items)-self.max_items:]
}
self.cmd_map = map_from_items(self.items)
}
func (self *History) Write() {
if self.file == nil {
return
}
self.file.Seek(0, 0)
utils.LockFileExclusive(self.file)
defer utils.UnlockFile(self.file)
data, err := io.ReadAll(self.file)
if err != nil {
return
}
var items []HistoryItem
err = json.Unmarshal(data, &items)
if err != nil {
self.merge_items(items...)
}
ndata, err := json.MarshalIndent(self.items, "", " ")
if err != nil {
return
}
self.file.Truncate(int64(len(ndata)))
self.file.Seek(0, 0)
self.file.Write(ndata)
}
func (self *History) Read() {
if self.file == nil {
return
}
self.file.Seek(0, 0)
utils.LockFileShared(self.file)
data, err := io.ReadAll(self.file)
utils.UnlockFile(self.file)
if err != nil {
return
}
var items []HistoryItem
err = json.Unmarshal(data, &items)
if err == nil {
self.merge_items(items...)
}
}
func (self *History) AddItem(cmd string, duration time.Duration) {
self.merge_items(HistoryItem{Cmd: cmd, Duration: duration, Timestamp: time.Now()})
}
func (self *History) Shutdown() {
if self.file != nil {
self.Write()
self.file.Close()
self.file = nil
}
}
func NewHistory(path string, max_items int) *History {
ans := History{items: []HistoryItem{}, cmd_map: map[string]int{}, max_items: max_items}
if path != "" {
ans.file_path = path
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)
if err == nil {
ans.file = f
} else {
fmt.Fprintln(os.Stderr, "Failed to open history file at:", path, "with error:", err)
}
}
ans.Read()
return &ans
}
func (self *History) find_prefix_matches(prefix, current_command string, input_state InputState) *HistoryMatches {
ans := HistoryMatches{items: make([]HistoryItem, 0, len(self.items)+1), prefix: prefix, original_input_state: input_state}
if prefix == "" {
ans.items = ans.items[:len(self.items)]
copy(ans.items, self.items)
} else {
for _, x := range self.items {
if strings.HasPrefix(x.Cmd, prefix) {
ans.items = append(ans.items, x)
}
}
}
ans.items = append(ans.items, HistoryItem{Cmd: current_command})
ans.current_idx = len(ans.items) - 1
return &ans
}
func (self *Readline) create_history_matches() {
if self.last_action_was_history_movement() && self.history_matches != nil {
return
}
prefix := self.text_upto_cursor_pos()
self.history_matches = self.history.find_prefix_matches(prefix, self.AllText(), self.input_state.copy())
}
func (self *Readline) last_action_was_history_movement() bool {
switch self.last_action {
case ActionHistoryLast, ActionHistoryFirst, ActionHistoryNext, ActionHistoryPrevious:
return true
default:
return false
}
}
func (self *HistoryMatches) apply(rl *Readline) bool {
if self.current_idx >= len(self.items) || self.current_idx < 0 {
return false
}
if self.current_idx == len(self.items)-1 {
rl.input_state = self.original_input_state.copy()
} else {
item := self.items[self.current_idx]
rl.input_state.lines = utils.Splitlines(item.Cmd)
if len(rl.input_state.lines) == 0 {
rl.input_state.lines = []string{""}
}
idx := len(rl.input_state.lines) - 1
rl.input_state.cursor = Position{Y: idx, X: len(rl.input_state.lines[idx])}
}
return true
}
func (self *HistoryMatches) first(rl *Readline) bool {
self.current_idx = 0
return self.apply(rl)
}
func (self *HistoryMatches) last(rl *Readline) bool {
self.current_idx = max(0, len(self.items)-1)
return self.apply(rl)
}
func (self *HistoryMatches) previous(num uint, rl *Readline) bool {
if self.current_idx > 0 {
self.current_idx = max(0, self.current_idx-int(num))
return self.apply(rl)
}
return false
}
func (self *HistoryMatches) next(num uint, rl *Readline) bool {
if self.current_idx+1 < len(self.items) {
self.current_idx = min(len(self.items)-1, self.current_idx+int(num))
return self.apply(rl)
}
return false
}
func (self *Readline) create_history_search(backwards bool, num uint) {
self.history_search = &HistorySearch{backwards: backwards, original_input_state: self.input_state.copy()}
self.push_keyboard_map(history_search_shortcuts())
self.markup_history_search()
}
func (self *Readline) end_history_search(accept bool) {
if accept && self.history_search.current_idx < len(self.history_search.items) {
self.input_state.lines = utils.Splitlines(self.history_search.items[self.history_search.current_idx].Cmd)
self.input_state.cursor.Y = len(self.input_state.lines) - 1
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
} else {
self.input_state = self.history_search.original_input_state
}
self.input_state.cursor = *self.ensure_position_in_bounds(&self.input_state.cursor)
self.pop_keyboard_map()
self.history_search = nil
}
func (self *Readline) markup_history_search() {
if len(self.history_search.items) == 0 {
if len(self.history_search.tokens) == 0 {
self.input_state.lines = []string{""}
} else {
self.input_state.lines = []string{"No matches for: " + self.history_search.query}
}
self.input_state.cursor = Position{X: wcswidth.Stringwidth(self.input_state.lines[0])}
return
}
lines := utils.Splitlines(self.history_search.items[self.history_search.current_idx].Cmd)
cursor := Position{Y: len(lines)}
for _, tok := range self.history_search.tokens {
for i, line := range lines {
if idx := strings.Index(line, tok); idx > -1 {
q := Position{Y: i, X: idx}
if q.Less(cursor) {
cursor = q
}
break
}
}
}
self.input_state.lines = lines
self.input_state.cursor = *self.ensure_position_in_bounds(&cursor)
}
func (self *Readline) remove_text_from_history_search(num uint) uint {
l := len(self.history_search.query)
nl := max(0, l-int(num))
self.history_search.query = self.history_search.query[:nl]
num_removed := uint(l - nl)
self.add_text_to_history_search("") // update the search results
return num_removed
}
func (self *Readline) history_search_highlighter(text string, x, y int) string {
if len(self.history_search.items) == 0 {
return text
}
lines := utils.Splitlines(text)
for _, tok := range self.history_search.tokens {
for i, line := range lines {
if before, after, ok := strings.Cut(line, tok); ok {
lines[i] = before + self.fmt_ctx.Green(tok) + after
break
}
}
}
return strings.Join(lines, "\n")
}
func (self *Readline) add_text_to_history_search(text string) {
self.history_search.query += text
tokens, err := shlex.Split(self.history_search.query)
if err != nil {
tokens = strings.Split(self.history_search.query, " ")
}
self.history_search.tokens = tokens
var current_item *HistoryItem
if len(self.history_search.items) > 0 {
current_item = self.history_search.items[self.history_search.current_idx]
}
if len(self.history_search.tokens) == 0 {
self.history_search.items = []*HistoryItem{}
} else {
items := make([]*HistoryItem, len(self.history.items))
for i := range self.history.items {
items[i] = &self.history.items[i]
}
for _, token := range self.history_search.tokens {
matches := make([]*HistoryItem, 0, len(items))
for _, item := range items {
if strings.Contains(item.Cmd, token) {
matches = append(matches, item)
}
}
items = matches
}
self.history_search.items = items
}
idx := -1
for i, item := range self.history_search.items {
if item == current_item {
idx = i
break
}
}
if idx == -1 {
if self.history_search.backwards {
idx = len(self.history_search.items) - 1
} else {
idx = 0
}
}
self.history_search.current_idx = max(0, idx)
self.markup_history_search()
}
func (self *Readline) next_history_search(backwards bool, num uint) bool {
ni := self.history_search.current_idx
self.history_search.backwards = backwards
if len(self.history_search.items) == 0 {
return false
}
if backwards {
ni = max(0, ni-int(num))
} else {
ni = min(ni+int(num), len(self.history_search.items)-1)
}
if ni == self.history_search.current_idx {
return false
}
self.history_search.current_idx = ni
self.markup_history_search()
return true
}
func (self *Readline) history_search_prompt() string {
ans := "↑"
if !self.history_search.backwards {
ans = "↓"
}
failed := len(self.history_search.tokens) > 0 && len(self.history_search.items) == 0
if failed {
ans = self.fmt_ctx.BrightRed(ans)
} else {
ans = self.fmt_ctx.Green(ans)
}
return fmt.Sprintf("history %s: ", ans)
}
func (self *Readline) history_completer(before_cursor, after_cursor string) (ans *cli.Completions) {
ans = cli.NewCompletions()
if before_cursor != "" {
var words_before_cursor []string
words_before_cursor, ans.CurrentWordIdx = shlex.SplitForCompletion(before_cursor)
idx := len(words_before_cursor)
if idx > 0 {
idx--
}
seen := utils.NewSet[string](16)
mg := ans.AddMatchGroup("History")
for _, x := range self.history.items {
if strings.HasPrefix(x.Cmd, before_cursor) {
words, _ := shlex.SplitForCompletion(x.Cmd)
if idx < len(words) {
word := words[idx]
desc := ""
if !seen.Has(word) {
if word != x.Cmd {
desc = x.Cmd
}
mg.AddMatch(word, desc)
seen.Add(word)
}
}
}
}
}
return
}
+226
View File
@@ -0,0 +1,226 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package readline
import (
"errors"
"fmt"
"strconv"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/shortcuts"
)
var _ = fmt.Print
type ShortcutMap = shortcuts.ShortcutMap[Action]
type KeyboardState struct {
active_shortcut_maps []*ShortcutMap
current_pending_keys []string
current_numeric_argument string
}
var _default_shortcuts *ShortcutMap
func default_shortcuts() *ShortcutMap {
if _default_shortcuts == nil {
sm := shortcuts.New[Action]()
sm.AddOrPanic(ActionBackspace, "backspace")
sm.AddOrPanic(ActionBackspace, "shift+backspace")
sm.AddOrPanic(ActionBackspace, "ctrl+h")
sm.AddOrPanic(ActionDelete, "delete")
sm.AddOrPanic(ActionMoveToStartOfLine, "home")
sm.AddOrPanic(ActionMoveToStartOfLine, "ctrl+a")
sm.AddOrPanic(ActionMoveToEndOfLine, "end")
sm.AddOrPanic(ActionMoveToEndOfLine, "ctrl+e")
sm.AddOrPanic(ActionMoveToStartOfDocument, "ctrl+home")
sm.AddOrPanic(ActionMoveToEndOfDocument, "ctrl+end")
sm.AddOrPanic(ActionMoveToEndOfWord, "alt+f")
sm.AddOrPanic(ActionMoveToEndOfWord, "ctrl+right")
sm.AddOrPanic(ActionMoveToEndOfWord, "alt+right")
sm.AddOrPanic(ActionMoveToStartOfWord, "ctrl+left")
sm.AddOrPanic(ActionMoveToStartOfWord, "alt+left")
sm.AddOrPanic(ActionMoveToStartOfWord, "alt+b")
sm.AddOrPanic(ActionCursorLeft, "left")
sm.AddOrPanic(ActionCursorLeft, "ctrl+b")
sm.AddOrPanic(ActionCursorRight, "right")
sm.AddOrPanic(ActionCursorRight, "ctrl+f")
sm.AddOrPanic(ActionClearScreen, "ctrl+l")
sm.AddOrPanic(ActionAbortCurrentLine, "ctrl+c")
sm.AddOrPanic(ActionAbortCurrentLine, "ctrl+g")
sm.AddOrPanic(ActionEndInput, "ctrl+d")
sm.AddOrPanic(ActionAcceptInput, "enter")
sm.AddOrPanic(ActionKillToEndOfLine, "ctrl+k")
sm.AddOrPanic(ActionKillToStartOfLine, "ctrl+x")
sm.AddOrPanic(ActionKillToStartOfLine, "ctrl+u")
sm.AddOrPanic(ActionKillNextWord, "alt+d")
sm.AddOrPanic(ActionKillPreviousWord, "alt+backspace")
sm.AddOrPanic(ActionKillPreviousWord, "ctrl+backspace")
sm.AddOrPanic(ActionKillPreviousSpaceDelimitedWord, "ctrl+w")
sm.AddOrPanic(ActionYank, "ctrl+y")
sm.AddOrPanic(ActionPopYank, "alt+y")
sm.AddOrPanic(ActionHistoryPreviousOrCursorUp, "up")
sm.AddOrPanic(ActionHistoryNextOrCursorDown, "down")
sm.AddOrPanic(ActionHistoryPrevious, "ctrl+p")
sm.AddOrPanic(ActionHistoryNext, "ctrl+n")
sm.AddOrPanic(ActionHistoryFirst, "alt+<")
sm.AddOrPanic(ActionHistoryLast, "alt+>")
sm.AddOrPanic(ActionHistoryIncrementalSearchBackwards, "ctrl+r")
sm.AddOrPanic(ActionHistoryIncrementalSearchBackwards, "ctrl+?")
sm.AddOrPanic(ActionHistoryIncrementalSearchForwards, "ctrl+s")
sm.AddOrPanic(ActionHistoryIncrementalSearchForwards, "ctrl+/")
sm.AddOrPanic(ActionNumericArgumentDigit0, "alt+0")
sm.AddOrPanic(ActionNumericArgumentDigit1, "alt+1")
sm.AddOrPanic(ActionNumericArgumentDigit2, "alt+2")
sm.AddOrPanic(ActionNumericArgumentDigit3, "alt+3")
sm.AddOrPanic(ActionNumericArgumentDigit4, "alt+4")
sm.AddOrPanic(ActionNumericArgumentDigit5, "alt+5")
sm.AddOrPanic(ActionNumericArgumentDigit6, "alt+6")
sm.AddOrPanic(ActionNumericArgumentDigit7, "alt+7")
sm.AddOrPanic(ActionNumericArgumentDigit8, "alt+8")
sm.AddOrPanic(ActionNumericArgumentDigit9, "alt+9")
sm.AddOrPanic(ActionNumericArgumentDigitMinus, "alt+-")
sm.AddOrPanic(ActionCompleteForward, "Tab")
sm.AddOrPanic(ActionCompleteBackward, "Shift+Tab")
_default_shortcuts = sm
}
return _default_shortcuts
}
var _history_search_shortcuts *shortcuts.ShortcutMap[Action]
func history_search_shortcuts() *shortcuts.ShortcutMap[Action] {
if _history_search_shortcuts == nil {
sm := shortcuts.New[Action]()
sm.AddOrPanic(ActionBackspace, "backspace")
sm.AddOrPanic(ActionBackspace, "ctrl+h")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "home")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+a")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "end")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+e")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+home")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+end")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "alt+f")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+right")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+left")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "alt+b")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "left")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+b")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "right")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+f")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "up")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "down")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+c")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+g")
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "escape")
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "ctrl+d")
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "enter")
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "ctrl+j")
_history_search_shortcuts = sm
}
return _history_search_shortcuts
}
var ErrCouldNotPerformAction = errors.New("Could not perform the specified action")
var ErrAcceptInput = errors.New("Accept input")
func (self *Readline) push_keyboard_map(m *ShortcutMap) {
maps := self.keyboard_state.active_shortcut_maps
self.keyboard_state = KeyboardState{}
if maps == nil {
maps = make([]*ShortcutMap, 0, 2)
}
self.keyboard_state.active_shortcut_maps = append(maps, m)
}
func (self *Readline) pop_keyboard_map() {
maps := self.keyboard_state.active_shortcut_maps
self.keyboard_state = KeyboardState{}
if len(maps) > 0 {
maps = maps[:len(maps)-1]
self.keyboard_state.active_shortcut_maps = maps
}
}
func (self *Readline) handle_numeric_arg(ac Action) {
t := "-"
num := int(ac - ActionNumericArgumentDigit0)
if num < 10 {
t = strconv.Itoa(num)
}
cna := self.keyboard_state.current_numeric_argument
if (cna == "" && t == "0") || (cna != "" && t == "-") {
self.add_text(t)
self.keyboard_state.current_numeric_argument = ""
self.last_action = ActionAddText
} else {
self.keyboard_state.current_numeric_argument += t
self.last_action = ac
}
}
func (self *Readline) dispatch_key_action(ac Action) error {
self.keyboard_state.current_pending_keys = nil
if ActionNumericArgumentDigit0 <= ac && ac <= ActionNumericArgumentDigitMinus {
if self.history_search != nil {
return ErrCouldNotPerformAction
}
self.handle_numeric_arg(ac)
return nil
}
cna := self.keyboard_state.current_numeric_argument
self.keyboard_state.current_numeric_argument = ""
if cna == "" {
cna = "1"
}
repeat_count, err := strconv.Atoi(cna)
if err != nil || repeat_count <= 0 {
repeat_count = 1
}
return self.perform_action(ac, uint(repeat_count))
}
func (self *Readline) handle_key_event(event *loop.KeyEvent) error {
if event.Text != "" {
return nil
}
sm := default_shortcuts()
if len(self.keyboard_state.active_shortcut_maps) > 0 {
sm = self.keyboard_state.active_shortcut_maps[len(self.keyboard_state.active_shortcut_maps)-1]
}
ac, pending := sm.ResolveKeyEvent(event, self.keyboard_state.current_pending_keys...)
if pending != "" {
event.Handled = true
if self.keyboard_state.current_pending_keys == nil {
self.keyboard_state.current_pending_keys = []string{}
}
self.keyboard_state.current_pending_keys = append(self.keyboard_state.current_pending_keys, pending)
} else {
self.keyboard_state.current_pending_keys = nil
if ac != ActionNil {
event.Handled = true
return self.dispatch_key_action(ac)
}
}
return nil
}