From 067b38c26a27c4ed29db092e487b8c108c76ee60 Mon Sep 17 00:00:00 2001 From: "Timothy J. Warren" Date: Tue, 30 Mar 2021 18:29:23 -0400 Subject: [PATCH] Open first line of a file --- editor/editor.go | 23 +++++++++++++++++++++-- gilo.go | 7 ++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/editor/editor.go b/editor/editor.go index 05ca7e5..883571b 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -1,6 +1,9 @@ package editor import ( + "bufio" + "log" + "os" "timshome.page/gilo/terminal" ) @@ -23,12 +26,28 @@ func New() *editor { screen := terminal.Size() cursor := &cursor { 0, 0 } var rows []*row + rows = append(rows, NewRow("")) return &editor{screen, cursor, rows } } -func (e *editor) Open() { - e.rows = append(e.rows, NewRow("Hello, world!")) +func (e *editor) Open(filename string) { + file, err := os.Open(filename) + if err != nil { + log.Fatalf("failed to open file") + } + defer file.Close() + + scanner := bufio.NewScanner(file) + scanner.Split(bufio.ScanLines) + + var lines []string + + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + e.rows = append(e.rows, NewRow(lines[0])) } func (e *editor) ProcessKeypress() bool { diff --git a/gilo.go b/gilo.go index aa1d408..dfc8531 100644 --- a/gilo.go +++ b/gilo.go @@ -3,6 +3,7 @@ package main import ( "fmt" "golang.org/x/term" + "os" "timshome.page/gilo/editor" "timshome.page/gilo/terminal" ) @@ -22,7 +23,11 @@ func main() { defer cleanup(oldState) e := editor.New() - e.Open() + + // If there is an argument passed, open it as a file to edit + if len(os.Args) >= 2 && os.Args[1] != "" { + e.Open(os.Args[1]) + } // The input loop for {