1 // Frontend: Functions for terminal output
3 // SPDX-License-Identifier: GPL-3.0-or-later
4 // Copyright (C) 2021-2024 Simon Ruderich
23 func ColorString(isTTY bool, color Color, x string) string {
39 panic(fmt.Sprintf("invalid color %v", color))
41 // TODO: check terminal support
42 return "\033[" + code + "m" + x + "\033[0m"
45 var escapeRegexp = regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`)
47 // EscapeControlCharacters escapes all ASCII control characters (except
48 // newline and tab) by replacing them with their hex value. If the output is
49 // to a TTY then the escaped characters are colored.
51 // This function must be used when displaying any input from remote hosts to
52 // prevent terminal escape code injections.
53 func EscapeControlCharacters(isTTY bool, x string) string {
54 return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string {
56 panic("invalid escapeRegexp")
59 x = "\\r" // occurs often and more readable than \x0D
61 x = fmt.Sprintf("\\x%02X", x[0])
63 return ColorString(isTTY, ColorMagenta, x)