github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/utils/ansi/ansi.go (about) 1 package ansi 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/lmorg/murex/lang" 8 "github.com/lmorg/murex/lang/types" 9 ) 10 11 var rxAnsiConsts = regexp.MustCompile(`\{([-\^A-Z0-9]+)\}`) 12 13 // IsAllowed returns a boolean value depending on whether the shell is configured to allow ANSI colours 14 func IsAllowed() bool { 15 v, err := lang.ShellProcess.Config.Get("shell", "color", types.Boolean) 16 if err != nil { 17 return false 18 } 19 return v.(bool) 20 } 21 22 // ExpandConsts writes a new string with the {CONST} values replaced 23 func ExpandConsts(s string) string { 24 return expandConsts(s, !IsAllowed()) 25 } 26 27 // ForceExpandConsts expands consts irrespective of user preferences. It is not 28 // recommended that you use this apart from in other testing functions. 29 func ForceExpandConsts(s string, noColour bool) string { 30 return expandConsts(s, noColour) 31 } 32 33 func expandConsts(s string, noColour bool) string { 34 match := rxAnsiConsts.FindAllStringSubmatch(s, -1) 35 for i := range match { 36 37 // misc escape sequences 38 b := constants[match[i][1]] 39 if len(b) != 0 { 40 s = strings.ReplaceAll(s, match[i][0], string(b)) 41 continue 42 } 43 44 // SGR (Select Graphic Rendition) parameters 45 b = sgr[match[i][1]] 46 if len(b) != 0 { 47 if noColour { 48 b = []byte{} 49 } 50 s = strings.ReplaceAll(s, match[i][0], string(b)) 51 continue 52 } 53 54 } 55 56 return s 57 }