update Align() method to add '...' at the end when too long | managing special characters

This commit is contained in:
xdrm-brackets 2018-11-10 18:35:00 +01:00
parent cafd4063a0
commit 340fe26d81
1 changed files with 35 additions and 36 deletions

View File

@ -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
}