From 0aa819f32396a0ad680f5c60c4302823fa3d2f10 Mon Sep 17 00:00:00 2001 From: EnumDev Date: Sun, 8 Jun 2025 21:13:51 +0300 Subject: [PATCH] Implement copy and pasting --- src/buffer.go | 11 +++++++++-- src/window.go | 38 ++++++++++++++++++++++++++++---------- 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/src/buffer.go b/src/buffer.go index 813c3ff..24b2ba2 100644 --- a/src/buffer.go +++ b/src/buffer.go @@ -72,10 +72,17 @@ func (buffer *Buffer) GetSelectedText() string { start := buffer.Selection.selectionStart end := buffer.Selection.selectionEnd + if start >= len(buffer.Contents) { + start = len(buffer.Contents) - 1 + } + if end >= len(buffer.Contents) { + end = len(buffer.Contents) - 1 + } + if start <= end { - return buffer.Contents[buffer.Selection.selectionStart : buffer.Selection.selectionEnd+1] + return buffer.Contents[start : end+1] } else { - return buffer.Contents[buffer.Selection.selectionEnd : buffer.Selection.selectionStart+1] + return buffer.Contents[end : start+1] } } diff --git a/src/window.go b/src/window.go index 147926d..19d2032 100644 --- a/src/window.go +++ b/src/window.go @@ -3,8 +3,8 @@ package main import ( "github.com/gdamore/tcell" "log" - "maps" "slices" + "strings" ) type CursorMode uint8 @@ -21,6 +21,8 @@ type Window struct { ShowLineIndex bool CursorMode CursorMode + Clipboard string + CurrentBuffer *Buffer screen tcell.Screen @@ -317,16 +319,32 @@ func (window *Window) input(ev *tcell.EventKey) { ClearDropdowns() window.CursorMode = CursorModeBuffer } - } else if ev.Key() == tcell.KeyCtrlC { // Close buffer key - delete(Buffers, window.CurrentBuffer.Id) - buffersSlice := slices.Collect(maps.Values(Buffers)) - if len(buffersSlice) == 0 { - window.Close() - return + } else if ev.Key() == tcell.KeyCtrlC { // Copy to clipboard key + if window.CursorMode == CursorModeBuffer { + if window.CurrentBuffer.Selection == nil { + // Copy line + _, line := window.GetCursorPos2D() + window.Clipboard = strings.SplitAfter(window.CurrentBuffer.Contents, "\n")[line] + PrintMessage(window, "Copied line to clipboard.") + } else { + // Copy selection + window.Clipboard = window.CurrentBuffer.GetSelectedText() + PrintMessage(window, "Copied selection to clipboard.") + } + } + } else if ev.Key() == tcell.KeyCtrlV { // Paste from clipboard + if window.CursorMode == CursorModeBuffer { + str := window.CurrentBuffer.Contents + index := window.CurrentBuffer.CursorPos + + if index == len(str) { + str += window.Clipboard + } else { + str = str[:index] + window.Clipboard + str[index:] + } + window.CurrentBuffer.CursorPos += len(window.Clipboard) + window.CurrentBuffer.Contents = str } - window.CurrentBuffer = buffersSlice[0] - ClearDropdowns() - window.CursorMode = CursorModeBuffer } else if ev.Key() == tcell.KeyCtrlQ { // Exit key window.Close() } else if ev.Modifiers()&tcell.ModAlt != 0 { // Menu Bar