From c2b1fd2df344c8262190e4b582692c7877eb861c Mon Sep 17 00:00:00 2001 From: James Antill Date: Sun, 8 Oct 2017 18:12:47 -0400 Subject: [PATCH 1/2] Ask terminal for width, use 80 columns by default on err. --- powerline.go | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/powerline.go b/powerline.go index 8a92f5c1..50b64348 100644 --- a/powerline.go +++ b/powerline.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "golang.org/x/crypto/ssh/terminal" "golang.org/x/text/width" "os" "strconv" @@ -75,10 +76,27 @@ func (p *powerline) appendSegment(origin string, segment segment) { p.Segments = append(p.Segments, segment) } +func termWidth() int { + width, _, err := terminal.GetSize(int(os.Stdout.Fd())) + if err != nil { + shellMaxLengthStr, found := os.LookupEnv("COLUMNS") + if !found { + return 80 // Otherwise 0 default. + } + + shellMaxLength64, err := strconv.ParseInt(shellMaxLengthStr, 0, 64) + if err != nil { + return 80 // Otherwise 0 default. + } + + width = int(shellMaxLength64) + } + + return width +} + func (p *powerline) draw() string { - shellMaxLengthStr, _ := os.LookupEnv("COLUMNS") - shellMaxLength64, _ := strconv.ParseInt(shellMaxLengthStr, 0, 64) - shellMaxLength := int(shellMaxLength64) + shellMaxLength := termWidth() shellMaxLength = shellMaxLength * *p.args.MaxWidthPercentage / 100 From 3dec992aa5dac4e5fb415ec7aa56f2c13387c12a Mon Sep 17 00:00:00 2001 From: James Antill Date: Mon, 16 Oct 2017 01:01:43 -0400 Subject: [PATCH 2/2] Import runewidth and use it instead of len(), to fix utf8 problems. --- powerline.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/powerline.go b/powerline.go index 50b64348..e8bbc0eb 100644 --- a/powerline.go +++ b/powerline.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/mattn/go-runewidth" "golang.org/x/crypto/ssh/terminal" "golang.org/x/text/width" "os" @@ -102,8 +103,10 @@ func (p *powerline) draw() string { shellActualLength := 0 if shellMaxLength > 0 { + rlen := runewidth.StringWidth + for _, segment := range p.Segments { - shellActualLength += len(segment.content) + len(segment.separator) + shellActualLength += rlen(segment.content) + rlen(segment.separator) } for shellActualLength > shellMaxLength { minPriority := MaxInteger @@ -117,7 +120,7 @@ func (p *powerline) draw() string { if minPrioritySegmentId != -1 { segment := p.Segments[minPrioritySegmentId] p.Segments = append(p.Segments[:minPrioritySegmentId], p.Segments[minPrioritySegmentId+1:]...) - shellActualLength -= len(segment.content) + len(segment.separator) + shellActualLength -= rlen(segment.content) + rlen(segment.separator) } } }