From fb2130518c964f869b782cb298297e443034dc53 Mon Sep 17 00:00:00 2001 From: asdf Date: Wed, 4 Sep 2019 22:57:26 +1000 Subject: [PATCH] first attempt on line wrapping indents issue --- cui/cui.go | 16 ++++++++++++---- cui/cui_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 cui/cui_test.go diff --git a/cui/cui.go b/cui/cui.go index f02ba14..a784ce7 100644 --- a/cui/cui.go +++ b/cui/cui.go @@ -81,17 +81,25 @@ func Clear(dir string) { } -func wrapLines(s []string, length int) []string { +// takes the document content (as a slice) and modifies any lines that are longer +// than the specified console width, splitting them over two lines. returns the +// amended document content as a slice. +func wrapLines(s []string, consolewidth int) []string { + indent := " " //11 spaces out := []string{} for _, ln := range s { - if len(ln) <= length { + if len(ln) <= consolewidth { out = append(out, ln) } else { words := strings.Split(ln, " ") var subout bytes.Buffer for i, wd := range words { sublen := subout.Len() - if sublen+len(wd)+1 <= length { + if sublen+len(wd)+1 <= consolewidth { + //if line was indented, reinsert indent + if i == 11 && sublen == 0 { + subout.WriteString(indent) + } if sublen > 0 { subout.WriteString(" ") } @@ -102,7 +110,7 @@ func wrapLines(s []string, length int) []string { } else { out = append(out, subout.String()) subout.Reset() - subout.WriteString(wd) + subout.WriteString(indent + wd) if i == len(words)-1 { out = append(out, subout.String()) subout.Reset() diff --git a/cui/cui_test.go b/cui/cui_test.go new file mode 100644 index 0000000..755fa02 --- /dev/null +++ b/cui/cui_test.go @@ -0,0 +1,36 @@ +package cui + +import ( + "reflect" + "testing" +) + +func Test_wrapLines_doesnt_break_indents(t *testing.T) { + indent := " " + tables := []struct { + testinput []string + expectedoutput []string + linelength int + }{ + { + //20 character input - should not wrap + []string{indent + "012345678"}, + []string{indent + "012345678"}, + 20, + }, + { + //21 character input - should wrap + []string{indent + "0123456789"}, + []string{indent + "0123456789"}, + 20, + }, + } + + for _, table := range tables { + output := wrapLines(table.testinput, table.linelength) + + if !reflect.DeepEqual(output, table.expectedoutput) { + t.Errorf("Expected %v, got %v", table.expectedoutput, output) + } + } +}