diff --git a/cursor.go b/cursor.go index 6258b399..15a6d657 100644 --- a/cursor.go +++ b/cursor.go @@ -39,8 +39,8 @@ func (c *Cursor) HasSelection() bool { return c.selectionEnd != c.selectionStart } -// DeleteSelected deletes the currently selected text -func (c *Cursor) DeleteSelected() { +// DeleteSelection deletes the currently selected text +func (c *Cursor) DeleteSelection() { if c.selectionStart > c.selectionEnd { c.v.eh.Remove(c.selectionEnd, c.selectionStart+1) // Since the cursor is already at the selection start we don't need to move @@ -52,6 +52,14 @@ func (c *Cursor) DeleteSelected() { } } +// GetSelection returns the cursor's selection +func (c *Cursor) GetSelection() string { + if c.selectionStart > c.selectionEnd { + return string([]rune(c.v.buf.text)[c.selectionEnd : c.selectionStart+1]) + } + return string([]rune(c.v.buf.text)[c.selectionStart : c.selectionEnd+1]) +} + // RuneUnder returns the rune under the cursor func (c *Cursor) RuneUnder() rune { line := c.v.buf.lines[c.y] diff --git a/todolist.md b/todolist.md index 2847e7aa..e8078867 100644 --- a/todolist.md +++ b/todolist.md @@ -25,6 +25,9 @@ - [x] Undo/redo stack - [ ] Functionality similar to nano +- [x] Clipboard support + - [x] Ctrl-v, Ctrl-c, and Ctrl-x + - [ ] Command execution - [ ] Allow executing simple commands at the bottom of the editor (like vim or emacs) diff --git a/view.go b/view.go index a3adbeb2..caa4ec5a 100644 --- a/view.go +++ b/view.go @@ -1,6 +1,7 @@ package main import ( + "github.com/atotto/clipboard" "github.com/gdamore/tcell" "strconv" ) @@ -145,7 +146,7 @@ func (v *View) HandleEvent(event tcell.Event) int { ret = 2 case tcell.KeyBackspace2: if v.cursor.HasSelection() { - v.cursor.DeleteSelected() + v.cursor.DeleteSelection() v.cursor.ResetSelection() ret = 2 } else if v.cursor.loc > 0 { @@ -178,6 +179,36 @@ func (v *View) HandleEvent(event tcell.Event) int { case tcell.KeyCtrlY: v.eh.Redo() ret = 2 + case tcell.KeyCtrlC: + if v.cursor.HasSelection() { + if !clipboard.Unsupported { + clipboard.WriteAll(v.cursor.GetSelection()) + ret = 2 + } + } + case tcell.KeyCtrlX: + if v.cursor.HasSelection() { + if !clipboard.Unsupported { + clipboard.WriteAll(v.cursor.GetSelection()) + v.cursor.DeleteSelection() + v.cursor.ResetSelection() + ret = 2 + } + } + case tcell.KeyCtrlV: + if !clipboard.Unsupported { + if v.cursor.HasSelection() { + v.cursor.DeleteSelection() + v.cursor.ResetSelection() + } + clip, _ := clipboard.ReadAll() + v.eh.Insert(v.cursor.loc, clip) + // This is a bit weird... Not sure if there's a better way + for i := 0; i < Count(clip); i++ { + v.cursor.Right() + } + ret = 2 + } case tcell.KeyPgUp: v.PageUp() return 2 @@ -192,7 +223,7 @@ func (v *View) HandleEvent(event tcell.Event) int { return 2 case tcell.KeyRune: if v.cursor.HasSelection() { - v.cursor.DeleteSelected() + v.cursor.DeleteSelection() v.cursor.ResetSelection() } v.eh.Insert(v.cursor.loc, string(e.Rune()))