Clipboard support for copying pasting and cutting

This commit is contained in:
Zachary Yedidia
2016-03-19 18:38:28 -04:00
parent 28c5899b9e
commit 866ad9594e
3 changed files with 46 additions and 4 deletions

View File

@@ -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]

View File

@@ -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)

35
view.go
View File

@@ -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()))