From a7f7c5ad40a3f6960ba61e67f737ddef56408d6e Mon Sep 17 00:00:00 2001 From: Alexey Yerin Date: Mon, 26 Apr 2021 13:18:01 +0300 Subject: [PATCH] editor: add ^W delete word binding It allows to delete the current word (any string of characters until a space). Also, all spaces at the start are cleared to allow doing something like: Hello world| Hello | <- the cursor is at a space | <- nothing left --- app.go | 6 ++++++ ui/editor.go | 30 ++++++++++++++++++++++++++++++ ui/ui.go | 4 ++++ 3 files changed, 40 insertions(+) diff --git a/app.go b/app.go index 6809a04..13d77ab 100644 --- a/app.go +++ b/app.go @@ -448,6 +448,12 @@ func (app *App) handleKeyEvent(ev *tcell.EventKey) { app.typing() app.updatePrompt() } + case tcell.KeyCtrlW: + ok := app.win.InputDeleteWord() + if ok { + app.typing() + app.updatePrompt() + } case tcell.KeyTab: ok := app.win.InputAutoComplete(1) if ok { diff --git a/ui/editor.go b/ui/editor.go index 66774e0..5419eaa 100644 --- a/ui/editor.go +++ b/ui/editor.go @@ -116,6 +116,36 @@ func (e *Editor) remRuneAt(idx int) { e.text[e.lineIdx] = e.text[e.lineIdx][:len(e.text[e.lineIdx])-1] } +func (e *Editor) RemWord() (ok bool) { + ok = 0 < e.cursorIdx + if !ok { + return + } + + line := e.text[e.lineIdx] + + // To allow doing something like this (| is the cursor): + // Hello world| + // Hello | + // | + for line[e.cursorIdx - 1] == ' ' { + e.remRuneAt(e.cursorIdx - 1) + e.Left() + } + + for i := e.cursorIdx - 1; i >= 0; i -= 1 { + if line[i] == ' ' { + break + } + e.remRuneAt(i) + e.Left() + } + + e.autoCache = nil + return +} + + func (e *Editor) Flush() (content string) { content = string(e.text[e.lineIdx]) if len(e.text[len(e.text)-1]) == 0 { diff --git a/ui/ui.go b/ui/ui.go index e527f8e..50ddab5 100644 --- a/ui/ui.go +++ b/ui/ui.go @@ -192,6 +192,10 @@ func (ui *UI) InputDelete() (ok bool) { return ui.e.RemRuneForward() } +func (ui *UI) InputDeleteWord() (ok bool) { + return ui.e.RemWord() +} + func (ui *UI) InputAutoComplete(offset int) (ok bool) { return ui.e.AutoComplete(offset) } -- 2.34.4