Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.swp
61 changes: 57 additions & 4 deletions box.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ package goterm

import (
"bytes"
"regexp"
"strings"
"unicode/utf8"
_ "unicode/utf8"
)

const DEFAULT_BORDER = "- │ ┌ ┐ └ ┘"
Expand Down Expand Up @@ -62,6 +63,8 @@ func (b *Box) Write(p []byte) (int, error) {
return b.Buf.Write(p)
}

var ANSI_RE = regexp.MustCompile(`\\0\d+\[\d+(?:;\d+)?m`)

// String renders Box
func (b *Box) String() (out string) {
borders := strings.Split(b.Border, " ")
Expand Down Expand Up @@ -100,12 +103,62 @@ func (b *Box) String() (out string) {
}

r := []rune(line)
if len(r) > contentWidth-1 {

lastAnsii := ""
withoutAnsii := []rune{}
withOffset := []rune{}
i := 0

for {
if i >= len(r) {
break
}

if r[i] == 27 {
lastAnsii = ""
withOffset = append(withOffset, r[i])
lastAnsii += string(r[i])
i++
for {

i++
if i > len(r) {
break
}

withOffset = append(withOffset, r[i])
lastAnsii += string(r[i])

if r[i] == 'm' {
i++
break
}
}
}

if i >= len(r) {
break
}

withoutAnsii = append(withoutAnsii, r[i])

if len(withoutAnsii) <= contentWidth {
withOffset = append(withOffset, r[i])
}

i++
}

if len(withoutAnsii) > contentWidth {
// If line is too large limit it
line = string(r[0:contentWidth])
line = string(withOffset)
} else {
// If line is too small enlarge it by adding spaces
line += strings.Repeat(" ", contentWidth-utf8.RuneCountInString(line))
line += strings.Repeat(" ", contentWidth-len(withoutAnsii))
}

if lastAnsii != "" {
line += RESET
}

line = prefix + line + suffix
Expand Down
3 changes: 2 additions & 1 deletion box_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ func TestBox(t *testing.T) {
└--------┘`

box := NewBox(10, 5, 0)
fmt.Fprint(box, "hello\nworld\ntest")
fmt.Fprint(box, "hello i'm very long string\nworld\ntest")

if box.String() != boxSample[1:] {
t.Error("\n" + box.String())
t.Error("!=")
t.Error(boxSample)
t.Error(len(box.String()), len(boxSample))
}
}

Expand Down
1 change: 1 addition & 0 deletions terminal_sysioctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package goterm

import (
"os"

"golang.org/x/sys/unix"
)

Expand Down
3 changes: 2 additions & 1 deletion terminal_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
package goterm

import (
"golang.org/x/sys/windows"
"os"

"golang.org/x/sys/windows"
)

func getWinsize() (*winsize, error) {
Expand Down