From 340fe26d81861a0c6cdcaa9d599650edcb67337c Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Sat, 10 Nov 2018 18:35:00 +0100 Subject: [PATCH] update Align() method to add '...' at the end when too long | managing special characters --- internal/clifmt/symbols.go | 71 +++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/internal/clifmt/symbols.go b/internal/clifmt/symbols.go index 7e8c8fe..c7e7b00 100644 --- a/internal/clifmt/symbols.go +++ b/internal/clifmt/symbols.go @@ -36,50 +36,49 @@ func Title(s string) { } // Align prints strings with space padding to align line ends (fixed width) -func Align(s string) { - - // 1. print string - fmt.Printf("%s", s) - - // 2. get actual size - size := len(s) - - // 3. remove \033[XYm format characters - size -= (len(strings.Split(s, "\033")) - 0) * 6 - - // 3. add 1 char for each \033[0m - size += len(strings.Split(s, "\033[0m")) - 1 - - // 4. print trailing spaces - for i := size; i < alignOffset; i++ { - fmt.Printf(" ") - } -} - -// AlignLimited prints strings with space padding to align line ends (fixed width) // also crops the content to add '...' at the end if too long (must have a space // at the end) -func AlignLimited(s string) { +func Align(s string) { - // format string - if len(s) > alignOffset-1 { - s = fmt.Sprintf("%s... ", s[:alignOffset-4]) + // 1. replace tabs with 4 spaces + tabs := strings.Split(s, "\t") + s = strings.Join(tabs, " ") + + // 1. get real size + size := getRealSize(s) + + if size > alignOffset-6 { + + for i, l := 0, len(s); i < l; i++ { // find when real size is right under + next := fmt.Sprintf("%s\033[0m… ", s[0:i+1]) + if getRealSize(next) >= alignOffset-5 { + s = next + break + } + + } + size = getRealSize(s) - 1 } - // 1. print string + // 2. print string fmt.Printf("%s", s) - // 2. get actual size - size := len(s) - - // 3. remove \033[XYm format characters - size -= (len(strings.Split(s, "\033")) - 0) * 6 - - // 3. add 1 char for each \033[0m - size += len(strings.Split(s, "\033[0m")) - 1 - - // 4. print trailing spaces + // 3. print trailing spaces for i := size; i < alignOffset; i++ { fmt.Printf(" ") } } + +// getRealSize returns the real size escaping special characters +func getRealSize(s string) int { + // 1. get actual size + size := len(s) + + // 2. remove \033[XYm format characters + size -= 7 * len(strings.Split(s, "\033")) + + // 3. compensate 1 char for \033[0m + size += len(strings.Split(s, "\033[0m")) + + return size +}