From 3eb2a9795d9d8f2b00ac6c00b97c0a329e616095 Mon Sep 17 00:00:00 2001 From: Aki Kareha Date: Wed, 25 Mar 2026 20:19:56 +0900 Subject: [PATCH] Add load and save --- cmd/levi/main.go | 4 +++- internal/editor/editor.go | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/cmd/levi/main.go b/cmd/levi/main.go index 978ba2d..88dd76b 100644 --- a/cmd/levi/main.go +++ b/cmd/levi/main.go @@ -1,11 +1,13 @@ package main import ( + "os" + "tea.kareha.org/lab/levi/internal/editor" ) func main() { - ed := editor.Init() + ed := editor.Init(os.Args) defer ed.Finish() ed.Main() } diff --git a/internal/editor/editor.go b/internal/editor/editor.go index 6cd931f..9f0243a 100644 --- a/internal/editor/editor.go +++ b/internal/editor/editor.go @@ -1,6 +1,7 @@ package editor import ( + "io/ioutil" "strings" "unicode/utf8" @@ -25,9 +26,29 @@ type Editor struct { head, tail string insert *strings.Builder mode mode + path string } -func Init() *Editor { +func Init(args []string) *Editor { + var path string + var lines []string + if len(args) > 1 { + path = args[1] + data, err := ioutil.ReadFile(path) + if err != nil { + panic(err) + } + if len(data) > 0 { + if data[len(data)-1] == '\n' { + data = data[:len(data)-1] + } + lines = strings.Split(string(data), "\n") + } + } + if len(lines) < 1 { + lines = make([]string, 1) + } + console.Raw() scr := newScreen() @@ -41,11 +62,12 @@ func Init() *Editor { x: 0, y: 0, vrow: 0, - lines: make([]string, 1), + lines: lines, head: "", tail: "", insert: new(strings.Builder), mode: modeCommand, + path: path, } } @@ -54,6 +76,14 @@ func (ed *Editor) Finish() { console.HomeCursor() console.Cooked() console.ShowCursor() + + if ed.path != "" { + text := strings.Join(ed.lines, "\n") + "\n" + err := ioutil.WriteFile(ed.path, []byte(text), 0644) + if err != nil { + panic(err) + } + } } func (ed *Editor) runeCount() int {