1 // Frontend: Functions for terminal output
3 // Copyright (C) 2021 Simon Ruderich
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
35 func ColorString(isTTY bool, color Color, x string) string {
51 panic(fmt.Sprintf("invalid color %v", color))
53 // TODO: check terminal support
54 return "\033[" + code + "m" + x + "\033[0m"
57 var escapeRegexp = regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`)
59 // EscapeControlCharacters escapes all ASCII control characters (except
60 // newline and tab) by replacing them with their hex value. If the output is
61 // to a TTY then the escaped characters are colored.
63 // This function must be used when displaying any input from remote hosts to
64 // prevent terminal escape code injections.
65 func EscapeControlCharacters(isTTY bool, x string) string {
66 return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string {
68 panic("invalid escapeRegexp")
71 x = "\\r" // occurs often and more readable than \x0D
73 x = fmt.Sprintf("\\x%02X", x[0])
75 return ColorString(isTTY, ColorMagenta, x)