Files
w3cjandClaude Opus 5.5 fb19879aaa fix(msg): one rule for which characters reach the terminal
msg.Safe is the one owner: a graphic character in any script is safe;
controls, bidi controls, format characters, variation selectors, private
use and the invisible fillers are not. Printable and OneLine drop what
Safe refuses, agent save's diff escapes it, and forbidigo bans
unicode.IsGraphic, IsPrint, IsControl and Bidi_Control outside
internal/msg.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-08 10:04:59 -07:00

42 lines
1.1 KiB
Go

package msg
import (
"strings"
"unicode/utf8"
)
// Printable returns s without the characters Safe refuses, but newline
// and tab, and without a lone C1 byte: nothing in it moves the cursor,
// rewrites, reorders or hides what a terminal shows. It's for text a VM
// or a build made (its output, a path, a host), and every message value
// goes through OneLine, its one-line form, when the message renders.
// Other bytes, invalid UTF-8 among them, stay as they are.
func Printable(s string) string { return clean(s, true) }
// OneLine is Printable without newlines and tabs too: text for one line,
// such as a message value, a status line or a log entry.
func OneLine(s string) string { return clean(s, false) }
func clean(s string, lines bool) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
r, n := utf8.DecodeRuneInString(s[i:])
switch {
case r == utf8.RuneError && n == 1:
if c := s[i]; c < 0x80 || c > 0x9f {
b.WriteByte(c)
}
case r == '\n' || r == '\t':
if lines {
b.WriteRune(r)
}
case !Safe(r):
default:
b.WriteString(s[i : i+n])
}
i += n
}
return b.String()
}