package uvimport ()// StyledString is a string that can be decomposed into a series of styled// lines and cells. It is used to disassemble a rendered string with ANSI// escape codes into a series of cells that can be used in a [Buffer].// A StyledString supports reading [ansi.SGR] and [ansi.Hyperlink] escape// codes.typeStyledStringstruct {// Text is the original string that was used to create the styled string.Textstring// Wrap determines whether the styled string should wrap to the next line.Wrapbool// Tail is the string that will be appended to the end of the line when the // string is truncated i.e. when [StyledString.Wrap] is false.Tailstring}var _ Drawable = (*StyledString)(nil)// NewStyledString creates a new [StyledString] for the given method and styled// string. The method is used to calculate the width of each line.func ( string) *StyledString { := new(StyledString) .Text = return}// String returns the text of the styled string.//// It implements the [fmt.Stringer] interface.func ( *StyledString) () string {return .Text}// Lines returns the styled string decomposed into a slice of [Line]s.func ( *StyledString) ( ansi.Method) []Line {returnprintString(nil, , 0, 0, Rectangle{}, .Text, false, "")}// Draw renders the styled string to the given buffer at the// specified area.func ( *StyledString) ( Screen, Rectangle) {// Clear the area before drawing.for := .Min.Y; < .Max.Y; ++ {for := .Min.X; < .Max.X; ++ { .SetCell(, , nil) } } := .Text// We need to normalize newlines "\n" to "\r\n" to emulate a raw terminal // output. = strings.ReplaceAll(, "\r\n", "\n")printString(, .WidthMethod(), .Min.X, .Min.Y, , , !.Wrap, .Tail)}// Height returns the number of lines in the styled string. This is the number// of lines that the styled string will occupy when rendered to the screen.func ( *StyledString) () int {returnstrings.Count(.Text, "\n") + 1}// UnicodeWidth returns the cells width of the widest line in the styled string// using the [ansi.GraphemeWidth] method.func ( *StyledString) () int { , := .widthHeight(ansi.GraphemeWidth)return}// WcWidth returns the cells width of the widest line in the styled string// using the [ansi.WcWidth] method.func ( *StyledString) () int { , := .widthHeight(ansi.WcWidth)return}func ( *StyledString) ( ansi.Method) (, int) { := strings.Split(.Text, "\n") = len()for , := range { = max(, .StringWidth()) }return}// Bounds returns the minimum area that can contain the whole styled string.func ( *StyledString) () Rectangle { , := .widthHeight(ansi.GraphemeWidth)returnRect(0, 0, , )}// printString draws a string starting at the given position. If s is nil, it// will build and return a slice of [Line]s instead (unwrapped, ignoring bounds).func [ []byte | string](Screen,WidthMethod, , int,Rectangle, ,bool, string,) ( []Line) { := ansi.GetParser()deferansi.PutParser()varCellif && len() > 0 { = *NewCell(, ) }// A [WidthMethod] the ansi package doesn't know about falls back to // wcwidth, so the segmenter below always agrees with the decoder. , := ansi.DecodeSequenceWc[], ansi.WcWidthif == ansi.GraphemeWidth { , = ansi.DecodeSequence[], ansi.GraphemeWidth }if == nil { = []Line{} }varCellvarStylevarLinkvarbyte , := -1, -1// last cell written, for folding in combining marksforlen() > 0 { , , , := (, , )// The decoder's ASCII fast path doesn't check for trailing combining // sequences, so re-decode as a full cluster when one starts here. // The str[1] >= 0xc0 check skips the segmenter for plain ASCII.if == 1 && [0] > 0x1f && [0] < 0x7f && len() > 1 && [1] >= 0xc0 {if , := ansi.FirstGraphemeCluster(, ); len() > 1 { , , = , , len() } }switch {// Any positive width is a printable grapheme cluster. Wcwidth measures // a cluster per codepoint, so this is not bounded by how wide a glyph // can be: a ZWJ emoji sequence such as "๐จโ๐ฉโ๐งโ๐ฆ" is eight columns, // and capping the width here would fall through to the escape sequence // branch and drop the cluster from the screen.case > 0: .Width = .Content = string() .Style = .Link = if == nil {// Building lines: unwrapped, no boundsif >= len() { = append(, Line{}) } [] = append([], ) , = len([])-1, += } else {// Drawing to screen: handle wrapping, truncation, and boundsif ! && +.Width > .Max.X && +1 < .Max.Y {// Wrap the string to the width of the window = .Min.X ++ } := Pos(, )if .In() {if && .Width > 0 && +.Width > .Max.X-.Width {// Truncate the string and append the tail if any. = .Style = .Link = .SetCell(, , &) , = , += .Width } else {// Print the cell to the screen .SetCell(, , &) , = , += } } }// Reset cell for next iteration = Cell{}default:// Valid sequences always have a non-zero Cmd. // TODO: Handle cursor movement and other sequencesswitch {caseansi.HasCsiPrefix() && .Command() == 'm':// SGR - Select Graphic RenditionReadStyle(.Params(), &)caseansi.HasOscPrefix() && .Command() == 8:// HyperlinksReadLink(.Data(), &)caseansi.Equal(, ("\n")):if == nil {// When building lines, we need to ensure empty lines are represented.if >= len() { = append(, Line{}) } } ++// Always treat a NL as CR-LF similar to Termios ONLCR.fallthroughcaseansi.Equal(, ("\r")):if == nil { = 0 } else { = .Min.X }caselen() > 0 && [0] >= 0xc0:// A zero-width grapheme, i.e. a combining mark the re-decode // above couldn't fold because an escape sequence sits between // it and its base, as in "a\x1b[31m\u0301". Every escape // introducer is a C0 or C1 byte, so a UTF-8 lead byte here is // always text. The mark belongs to the cell we last wrote; the // accumulator below would let the next glyph clobber it.if == nil {if >= 0 && < len() && < len([]) { [][].Content += string() } } elseif >= 0 {if := .CellAt(, ); != nil { := * .Content += string() .SetCell(, , &) } }default: .Content += string() } }// Advance the state and data = = [:]if >= .Max.Y {// We've reached the bottom of the bounds, stop processing further // lines.break } }// Make sure to set the last cell if it's not empty.if !.IsZero() && != nil { .SetCell(, , &) }return}// ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a// list of parameters into pen.func ( ansi.Params, *Style) {iflen() == 0 { * = Style{}return }for := 0; < len(); ++ { , , := .Param(, 0)switch {case0: // Reset * = Style{}case1: // Bold .Attrs |= AttrBoldcase2: // Dim/Faint .Attrs |= AttrFaintcase3: // Italic .Attrs |= AttrItaliccase4: // Underline , , := .Param(+1, 0)if && { // Only accept subparameters i.e. separated by ":"switch {case0, 1, 2, 3, 4, 5: ++switch {case0: // No Underline .Underline = UnderlineStyleNonecase1: // Single Underline .Underline = UnderlineStyleSinglecase2: // Double Underline .Underline = UnderlineStyleDoublecase3: // Curly Underline .Underline = UnderlineStyleCurlycase4: // Dotted Underline .Underline = UnderlineStyleDottedcase5: // Dashed Underline .Underline = UnderlineStyleDashed } } } else {// Single Underline .Underline = UnderlineStyleSingle }case5: // Slow Blink .Attrs |= AttrBlinkcase6: // Rapid Blink .Attrs |= AttrRapidBlinkcase7: // Reverse .Attrs |= AttrReversecase8: // Conceal .Attrs |= AttrConcealcase9: // Crossed-out/Strikethrough .Attrs |= AttrStrikethroughcase22: // Normal Intensity (not bold or faint) .Attrs &^= (AttrBold | AttrFaint)case23: // Not italic, not Fraktur .Attrs &^= AttrItaliccase24: // Not underlined .Underline = UnderlineStyleNonecase25: // Blink off .Attrs &^= (AttrBlink | AttrRapidBlink)case27: // Positive (not reverse) .Attrs &^= AttrReversecase28: // Reveal .Attrs &^= AttrConcealcase29: // Not crossed out .Attrs &^= AttrStrikethroughcase30, 31, 32, 33, 34, 35, 36, 37: // Set foreground .Fg = ansi.Black + ansi.BasicColor(-30) //nolint:goseccase38: // Set foreground 256 or truecolorvarcolor.Color := ansi.ReadStyleColor([:], &)if > 0 { .Fg = += - 1 }case39: // Default foreground .Fg = nilcase40, 41, 42, 43, 44, 45, 46, 47: // Set background .Bg = ansi.Black + ansi.BasicColor(-40) //nolint:goseccase48: // Set background 256 or truecolorvarcolor.Color := ansi.ReadStyleColor([:], &)if > 0 { .Bg = += - 1 }case49: // Default Background .Bg = nilcase58: // Set underline colorvarcolor.Color := ansi.ReadStyleColor([:], &)if > 0 { .UnderlineColor = += - 1 }case59: // Default underline color .UnderlineColor = nilcase90, 91, 92, 93, 94, 95, 96, 97: // Set bright foreground .Fg = ansi.BrightBlack + ansi.BasicColor(-90) //nolint:goseccase100, 101, 102, 103, 104, 105, 106, 107: // Set bright background .Bg = ansi.BrightBlack + ansi.BasicColor(-100) //nolint:gosec } }}// ReadLink reads a hyperlink escape sequence from a data buffer into link.func ( []byte, *Link) { := bytes.Split(, []byte{';'})iflen() != 3 {return } .Params = string([1]) .URL = string([2])}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)