1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
|
package textstyles
import (
"fmt"
"strings"
"unicode/utf8"
log "github.com/sirupsen/logrus"
"github.com/walles/moor/v2/internal/linemetadata"
"github.com/walles/moor/v2/twin"
)
const esc = '\x1b'
type styledStringSplitter struct {
input string
lineIndex *linemetadata.Index // Used for error reporting
plainTextStyle twin.Style
maxTokensCount int
reportedRunesCount int
nextByteIndex int
previousByteIndex int
inProgressString strings.Builder
inProgressStyle twin.Style
numbersBuffer []uint
trailer twin.Style
callback func(str string, style twin.Style)
}
// Returns the style of the line's trailer.
//
// The lineIndex is only used for error reporting.
//
// maxTokensCount: at most this many tokens will be included in the result. If
// 0, do all runes. For BenchmarkRenderHugeLine() performance.
func styledStringsFromString(plainTextStyle twin.Style, s string, lineIndex *linemetadata.Index, maxTokensCount int, callback func(string, twin.Style)) twin.Style {
if !strings.ContainsAny(s, "\x1b") {
// This shortcut makes BenchmarkPlainTextSearch() perform a lot better
callback(s, plainTextStyle)
return plainTextStyle
}
splitter := styledStringSplitter{
input: s,
lineIndex: lineIndex,
plainTextStyle: plainTextStyle, // How plain text should be styled
maxTokensCount: maxTokensCount,
inProgressStyle: plainTextStyle, // Plain text style until something else comes along
callback: callback,
trailer: plainTextStyle, // Plain text style until something else comes along
}
splitter.run()
return splitter.trailer
}
func (s *styledStringSplitter) nextChar() rune {
if s.nextByteIndex >= len(s.input) {
s.previousByteIndex = s.nextByteIndex
return -1
}
char, size := utf8.DecodeRuneInString(s.input[s.nextByteIndex:])
s.previousByteIndex = s.nextByteIndex
s.nextByteIndex += size
return char
}
// Returns whatever the last call to nextChar() returned
func (s *styledStringSplitter) lastChar() rune {
if s.previousByteIndex >= len(s.input) {
return -1
}
char, _ := utf8.DecodeRuneInString(s.input[s.previousByteIndex:])
return char
}
func (s *styledStringSplitter) run() {
char := s.nextChar()
for {
if char == -1 {
s.finalizeCurrentPart()
return
}
if char == esc {
escIndex := s.previousByteIndex
err := s.handleEscape()
if err != nil {
header := ""
if s.lineIndex != nil {
header = fmt.Sprintf("Line %s: ", s.lineIndex.Format())
}
failed := s.input[escIndex:s.nextByteIndex]
log.Debug(header, "<", strings.ReplaceAll(failed, "\x1b", "ESC"), ">: ", err)
// Somewhere in handleEscape(), we got a character that was
// unexpected. We need to treat everything up to before that
// character as just plain runes.
for _, char := range s.input[escIndex:s.previousByteIndex] {
s.handleRune(char)
}
// Start over with the character that caused the problem
char = s.lastChar()
continue
}
} else {
s.handleRune(char)
}
char = s.nextChar()
}
}
func (s *styledStringSplitter) handleRune(char rune) {
s.inProgressString.WriteRune(char)
}
func (s *styledStringSplitter) handleEscape() error {
char := s.nextChar()
if char == '[' {
// Got the start of a CSI sequence
return s.consumeControlSequence()
}
if char == ']' {
// Got the start of an OSC sequence
return s.consumeOsc()
}
if char == '(' {
// Designate G0 charset: https://www.xfree86.org/4.8.0/ctlseqs.html
return s.consumeG0Charset()
}
return fmt.Errorf("Unhandled Fe sequence ESC%c", char)
}
// Consume a control sequence up until it ends
func (s *styledStringSplitter) consumeControlSequence() error {
// Points to right after "ESC["
startIndex := s.nextByteIndex
// We're looking for a letter to end the CSI sequence
for {
char := s.nextChar()
if char == -1 {
return fmt.Errorf("Line ended in the middle of a control sequence")
}
// Range from here:
// https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_(Control_Sequence_Introducer)_sequences
if char >= 0x30 && char <= 0x3f {
// Sequence still in progress
continue
}
// The end, handle what we got
endIndexExclusive := s.nextByteIndex
return s.handleCompleteControlSequence(s.input[startIndex:endIndexExclusive])
}
}
func (s *styledStringSplitter) consumeG0Charset() error {
// First char after "ESC("
char := s.nextChar()
if char == 'B' {
// G0 charset is now "B" (ASCII)
s.startNewPart(s.plainTextStyle)
return nil
}
return fmt.Errorf("Unhandled G0 charset: %c", char)
}
// If the whole CSI sequence is ESC[33m, you should call this function with just
// "33m".
func (s *styledStringSplitter) handleCompleteControlSequence(sequence string) error {
if sequence == "K" || sequence == "0K" {
// Clear to end of line
s.trailer = s.inProgressStyle
return nil
}
lastChar := sequence[len(sequence)-1]
if lastChar == 'm' {
var newStyle twin.Style
var err error
newStyle, s.numbersBuffer, err = rawUpdateStyle(s.inProgressStyle, sequence, s.numbersBuffer)
if err != nil {
return err
}
s.startNewPart(newStyle)
return nil
}
if lastChar == 'n' {
// Device status report, expects us to respond, just ignore them.
//
// Ref: https://vt100.net/docs/vt510-rm/DSR.html
return nil
}
return fmt.Errorf("Unhandled CSI type %q", lastChar)
}
// Consume an OSC sequence up until it ends
func (s *styledStringSplitter) consumeOsc() error {
// Points to right after "ESC]"
startIndex := s.nextByteIndex
// We're looking for a letter to end the CSI sequence
for {
char := s.nextChar()
if char == -1 {
return fmt.Errorf("Line ended in the middle of an OSC sequence")
}
if char == '\a' {
// Got the end of the OSC sequence
return s.handleOsc(s.input[startIndex:s.previousByteIndex])
}
if char == esc {
escIndex := s.previousByteIndex
afterEsc := s.nextChar()
if afterEsc == '\\' {
// Got the end of the OSC sequence
return s.handleOsc(s.input[startIndex:escIndex])
}
if afterEsc == -1 {
return fmt.Errorf("Line ended while ending an OSC sequence")
}
return fmt.Errorf("Expected OSC sequence to end with BEL or ESC \\ but got ESC %q", afterEsc)
}
if s.input[startIndex:s.nextByteIndex] == "8;;" {
// Special case, here comes an URL
return s.handleURL()
}
}
}
// Expects an OSC sequence as argument. The terminator is not included, what we
// get here is just the payload.
func (s *styledStringSplitter) handleOsc(sequence string) error {
if strings.HasPrefix(sequence, "133;") && len(sequence) == len("133;A") {
// Got ESC]133;X, where "X" could be anything. These are prompt hints,
// and rendering those makes no sense. We should just ignore them:
// https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md
return nil
}
if strings.HasSuffix(sequence, "?") {
// OSC query, we don't intend to answer those, just ignore them.
//
// Ref: https://github.com/walles/moor/issues/279
return nil
}
return fmt.Errorf("Unhandled OSC sequence")
}
// Based on https://infra.spec.whatwg.org/#surrogate
func isSurrogate(char rune) bool {
if char >= 0xD800 && char <= 0xDFFF {
return true
}
return false
}
// Non-characters end with 0xfffe or 0xffff, or are in the range 0xFDD0 to 0xFDEF.
//
// Based on https://infra.spec.whatwg.org/#noncharacter
func isNonCharacter(char rune) bool {
if char >= 0xFDD0 && char <= 0xFDEF {
return true
}
// Non-characters end with 0xfffe or 0xffff
if char&0xFFFF == 0xFFFE || char&0xFFFF == 0xFFFF {
return true
}
return false
}
// Based on https://url.spec.whatwg.org/#url-code-points
func isValidURLChar(char rune) bool {
if char == '\\' {
// Ref: https://github.com/walles/moor/issues/244#issuecomment-2350908401
return true
}
if char == '%' {
// Needed for % escapes
return true
}
if char == '#' {
// Fragment identifier
return true
}
// ASCII alphanumerics
if char >= '0' && char <= '9' {
return true
}
if char >= 'A' && char <= 'Z' {
return true
}
if char >= 'a' && char <= 'z' {
return true
}
if strings.ContainsRune("!$&'()*+,-./:;=?@_~", char) {
return true
}
if char < 0x00a0 {
return false
}
if char > 0x10FFFD {
return false
}
if isSurrogate(char) {
return false
}
if isNonCharacter(char) {
return false
}
return true
}
// We just got ESC]8; and should now read the URL. URLs end with ASCII 7 BEL or ESC \.
func (s *styledStringSplitter) handleURL() error {
// Points to right after "ESC]8;"
urlStartIndex := s.nextByteIndex
justSawEsc := false
for {
char := s.nextChar()
if char == -1 {
return fmt.Errorf("Line ended in the middle of a URL")
}
if justSawEsc {
if char != '\\' {
return fmt.Errorf("Expected ESC \\ but got ESC %q", char)
}
// End of URL
urlEndIndexExclusive := s.nextByteIndex - 2
url := s.input[urlStartIndex:urlEndIndexExclusive]
s.startNewPart(s.inProgressStyle.WithHyperlink(&url))
return nil
}
// Invariant: justSawEsc == false
if char == esc {
justSawEsc = true
continue
}
if char == '\x07' {
// End of URL
urlEndIndexExclusive := s.nextByteIndex - 1
url := s.input[urlStartIndex:urlEndIndexExclusive]
s.startNewPart(s.inProgressStyle.WithHyperlink(&url))
return nil
}
if !isValidURLChar(char) {
return fmt.Errorf("Invalid URL character: <%q>", char)
}
// It's a valid URL char, keep going
}
}
func (s *styledStringSplitter) startNewPart(style twin.Style) {
if style == twin.StyleDefault {
style = s.plainTextStyle
}
if style == s.inProgressStyle {
// No need to start a new part
return
}
s.finalizeCurrentPart()
s.inProgressString.Reset()
s.inProgressStyle = style
}
func (s *styledStringSplitter) finalizeCurrentPart() {
if s.inProgressString.Len() == 0 {
// Nothing to do
return
}
partString := s.inProgressString.String()
s.callback(partString, s.inProgressStyle)
s.reportedRunesCount += utf8.RuneCountInString(partString)
if s.maxTokensCount > 0 && s.reportedRunesCount >= s.maxTokensCount {
// We've reported enough runes, stop processing any further input
s.nextByteIndex = len(s.input)
}
}
|