Class AttributedStringBuilder

  • All Implemented Interfaces:
    java.lang.Appendable, java.lang.CharSequence

    public class AttributedStringBuilder
    extends AttributedCharSequence
    implements java.lang.Appendable
    A mutable builder for creating styled text strings with ANSI attributes.

    The AttributedStringBuilder class provides a mutable implementation of AttributedCharSequence for constructing styled text strings. It allows for dynamic building of attributed strings by appending characters, strings, or other attributed strings with various styles.

    This class is similar to StringBuilder but with added support for ANSI style attributes. It provides methods for appending text with different styles, manipulating the content, and converting the result to an immutable AttributedString when building is complete.

    Key features include:

    • Append operations with different styles
    • Tab expansion with configurable tab stops
    • Style manipulation (foreground/background colors, bold, underline, etc.)
    • Regular expression based styling
    • Alternative character set support

    This class is commonly used for building complex styled output for terminal applications, such as syntax highlighting, interactive prompts, and formatted displays.

    See Also:
    AttributedCharSequence, AttributedString, AttributedStyle
    • Constructor Detail

      • AttributedStringBuilder

        public AttributedStringBuilder()
        Creates a new AttributedStringBuilder with the default initial capacity.

        This constructor creates a new AttributedStringBuilder with an initial capacity of 64 characters. The builder will automatically grow as needed when more characters are appended.

      • AttributedStringBuilder

        public AttributedStringBuilder​(int capacity)
        Creates a new AttributedStringBuilder with the specified initial capacity.

        This constructor creates a new AttributedStringBuilder with the specified initial capacity. The builder will automatically grow as needed when more characters are appended.

        Parameters:
        capacity - the initial capacity of the builder
    • Method Detail

      • append

        public static AttributedString append​(java.lang.CharSequence... strings)
        Creates an AttributedString by appending multiple character sequences.

        This static utility method creates a new AttributedString by appending all the specified character sequences. It is a convenient way to concatenate multiple strings or AttributedStrings into a single AttributedString.

        Parameters:
        strings - the character sequences to append
        Returns:
        a new AttributedString containing all the appended sequences
      • length

        public int length()
        Returns the length of this attributed string builder.

        This method returns the number of characters in this attributed string builder.

        Specified by:
        length in interface java.lang.CharSequence
        Returns:
        the number of characters in this attributed string builder
      • charAt

        public char charAt​(int index)
        Returns the character at the specified index in this attributed string builder.

        This method returns the character at the specified index in this attributed string builder.

        Specified by:
        charAt in interface java.lang.CharSequence
        Overrides:
        charAt in class AttributedCharSequence
        Parameters:
        index - the index of the character to return
        Returns:
        the character at the specified index
        Throws:
        java.lang.IndexOutOfBoundsException - if the index is out of range
      • styleAt

        public AttributedStyle styleAt​(int index)
        Returns the style at the specified index in this attributed string builder.

        This method returns the AttributedStyle object associated with the character at the specified index in this attributed string builder.

        Specified by:
        styleAt in class AttributedCharSequence
        Parameters:
        index - the index of the character whose style to return
        Returns:
        the style at the specified index
        Throws:
        java.lang.IndexOutOfBoundsException - if the index is out of range
      • buffer

        protected char[] buffer()
        Returns the character buffer for this attributed string builder.

        This method is used internally by the AttributedCharSequence implementation to access the underlying character buffer.

        Specified by:
        buffer in class AttributedCharSequence
        Returns:
        the character buffer
      • offset

        protected int offset()
        Returns the offset in the buffer where this attributed string builder starts.

        This method is used internally by the AttributedCharSequence implementation to determine the starting position in the buffer. For AttributedStringBuilder, this is always 0 since the builder uses the entire buffer.

        Specified by:
        offset in class AttributedCharSequence
        Returns:
        the offset in the buffer (always 0 for AttributedStringBuilder)
      • subSequence

        public AttributedString subSequence​(int start,
                                            int end)
        Returns a new AttributedString that is a subsequence of this attributed string builder.

        This method returns a new AttributedString that contains the characters and styles from this attributed string builder starting at the specified start index (inclusive) and ending at the specified end index (exclusive).

        Specified by:
        subSequence in interface java.lang.CharSequence
        Specified by:
        subSequence in class AttributedCharSequence
        Parameters:
        start - the start index, inclusive
        end - the end index, exclusive
        Returns:
        the specified subsequence with its attributes
        Throws:
        java.lang.IndexOutOfBoundsException - if start or end are negative, if end is greater than length(), or if start is greater than end
      • append

        public AttributedStringBuilder append​(java.lang.CharSequence csq)
        Appends the specified character sequence to this builder.

        This method appends the specified character sequence to this builder, applying the current style to all characters. If the character sequence is null, the string "null" is appended, as required by the Appendable interface.

        Specified by:
        append in interface java.lang.Appendable
        Parameters:
        csq - the character sequence to append, or null
        Returns:
        this builder
      • append

        public AttributedStringBuilder append​(java.lang.CharSequence csq,
                                              int start,
                                              int end)
        Appends a subsequence of the specified character sequence to this builder.

        This method appends a subsequence of the specified character sequence to this builder, applying the current style to all characters. If the character sequence is null, the string "null" is appended, as required by the Appendable interface.

        Specified by:
        append in interface java.lang.Appendable
        Parameters:
        csq - the character sequence to append, or null
        start - the index of the first character to append
        end - the index after the last character to append
        Returns:
        this builder
        Throws:
        java.lang.IndexOutOfBoundsException - if start or end are negative, or if end is greater than csq.length(), or if start is greater than end
      • append

        public AttributedStringBuilder append​(char c)
        Appends the specified character to this builder.

        This method appends the specified character to this builder, applying the current style to the character.

        Specified by:
        append in interface java.lang.Appendable
        Parameters:
        c - the character to append
        Returns:
        this builder
      • append

        public AttributedStringBuilder append​(char c,
                                              int repeat)
        Appends the specified character to this builder multiple times.

        This method appends the specified character to this builder the specified number of times, applying the current style to all characters.

        Parameters:
        c - the character to append
        repeat - the number of times to append the character
        Returns:
        this builder
      • append

        public AttributedStringBuilder append​(java.lang.CharSequence csq,
                                              AttributedStyle style)
        Appends the specified character sequence to this builder with the specified style.

        This method appends the specified character sequence to this builder, applying the specified style to all characters. This allows appending text with a style different from the current style without changing the current style.

        Parameters:
        csq - the character sequence to append
        style - the style to apply to the appended characters
        Returns:
        this builder
      • style

        public AttributedStringBuilder style​(AttributedStyle style)
        Sets the current style for this builder.

        This method sets the current style for this builder, which will be applied to all characters appended after this call (until the style is changed again).

        Parameters:
        style - the new current style
        Returns:
        this builder
      • style

        public AttributedStringBuilder style​(java.util.function.Function<AttributedStyle,​AttributedStyle> style)
        Updates the current style for this builder using a function.

        This method updates the current style for this builder by applying the specified function to the current style. This allows for fluent style modifications without creating intermediate style objects.

        Example usage:

         builder.style(s -> s.bold().foreground(AttributedStyle.RED));
         
        Parameters:
        style - the function to apply to the current style
        Returns:
        this builder
      • styled

        public AttributedStringBuilder styled​(java.util.function.Function<AttributedStyle,​AttributedStyle> style,
                                              java.lang.CharSequence cs)
        Appends the specified character sequence with a temporarily modified style.

        This method temporarily modifies the current style using the specified function, appends the specified character sequence with that style, and then restores the original style. This allows for appending styled text without permanently changing the current style.

        Parameters:
        style - the function to apply to the current style
        cs - the character sequence to append
        Returns:
        this builder
      • styled

        public AttributedStringBuilder styled​(AttributedStyle style,
                                              java.lang.CharSequence cs)
        Appends the specified character sequence with the specified style.

        This method temporarily sets the current style to the specified style, appends the specified character sequence with that style, and then restores the original style. This allows for appending styled text without permanently changing the current style.

        Parameters:
        style - the style to use
        cs - the character sequence to append
        Returns:
        this builder
      • styled

        public AttributedStringBuilder styled​(java.util.function.Function<AttributedStyle,​AttributedStyle> style,
                                              java.util.function.Consumer<AttributedStringBuilder> consumer)
        Performs operations with a temporarily modified style.

        This method temporarily modifies the current style using the specified function, performs the operations specified by the consumer with that style, and then restores the original style. This allows for performing complex styling operations without permanently changing the current style.

        Example usage:

         builder.styled(s -> s.bold().foreground(AttributedStyle.RED),
                       sb -> sb.append("Error: ").append(errorMessage));
         
        Parameters:
        style - the function to apply to the current style
        consumer - the consumer that performs operations on this builder
        Returns:
        this builder
      • style

        public AttributedStyle style()
        Returns the current style for this builder.

        This method returns the current style for this builder, which is applied to all characters appended after the style was set (until the style is changed).

        Returns:
        the current style
      • append

        public AttributedStringBuilder append​(AttributedString str)
        Appends the specified AttributedString to this builder.

        This method appends the specified AttributedString to this builder, preserving its character attributes. The current style is applied to any attributes that are not explicitly set in the AttributedString.

        Parameters:
        str - the AttributedString to append
        Returns:
        this builder
      • append

        public AttributedStringBuilder append​(AttributedString str,
                                              int start,
                                              int end)
        Appends a subsequence of the specified AttributedString to this builder.

        This method appends a subsequence of the specified AttributedString to this builder, preserving its character attributes. The current style is applied to any attributes that are not explicitly set in the AttributedString.

        Parameters:
        str - the AttributedString to append
        start - the index of the first character to append
        end - the index after the last character to append
        Returns:
        this builder
        Throws:
        java.lang.IndexOutOfBoundsException - if start or end are negative, or if end is greater than str.length(), or if start is greater than end
      • append

        public AttributedStringBuilder append​(AttributedCharSequence str)
        Appends the specified AttributedCharSequence to this builder.

        This method appends the specified AttributedCharSequence to this builder, preserving its character attributes. The current style is applied to any attributes that are not explicitly set in the AttributedCharSequence.

        Parameters:
        str - the AttributedCharSequence to append
        Returns:
        this builder
      • append

        public AttributedStringBuilder append​(AttributedCharSequence str,
                                              int start,
                                              int end)
        Appends a subsequence of the specified AttributedCharSequence to this builder.

        This method appends a subsequence of the specified AttributedCharSequence to this builder, preserving its character attributes. The current style is applied to any attributes that are not explicitly set in the AttributedCharSequence.

        If the sequence contains tab characters and tab stops are defined, the tabs will be expanded according to the current tab stop settings.

        Parameters:
        str - the AttributedCharSequence to append
        start - the index of the first character to append
        end - the index after the last character to append
        Returns:
        this builder
        Throws:
        java.lang.IndexOutOfBoundsException - if start or end are negative, or if end is greater than str.length(), or if start is greater than end
      • ensureCapacity

        protected void ensureCapacity​(int nl)
      • appendAnsi

        public void appendAnsi​(java.lang.String ansi)
        Appends the specified ANSI-encoded string to this builder.

        This method parses the ANSI escape sequences in the input string and appends the text with the corresponding styles to this builder. This is useful for converting ANSI-colored output from external commands into styled text.

        This method is equivalent to ansiAppend(String) but returns void.

        Parameters:
        ansi - the ANSI-encoded string to parse and append
        See Also:
        ansiAppend(String)
      • ansiAppend

        public AttributedStringBuilder ansiAppend​(java.lang.String ansi)
        Appends the specified ANSI-encoded string to this builder.

        This method parses the ANSI escape sequences in the input string and appends the text with the corresponding styles to this builder. This is useful for converting ANSI-colored output from external commands into styled text.

        The method recognizes standard ANSI SGR (Select Graphic Rendition) sequences for text attributes (bold, underline, etc.) and colors (foreground and background).

        Parameters:
        ansi - the ANSI-encoded string to parse and append
        Returns:
        this builder
      • setLength

        public void setLength​(int l)
        Sets the length of this attributed string builder.

        This method sets the length of this attributed string builder. If the specified length is less than the current length, the builder is truncated; if it is greater than the current length, the builder is extended with undefined characters and styles.

        Note that extending the builder with this method may result in undefined behavior if the extended region is accessed without first setting its characters and styles.

        Parameters:
        l - the new length
      • tabs

        public AttributedStringBuilder tabs​(int tabsize)
        Set the number of spaces a tab is expanded to. Tab size cannot be changed after text has been added to prevent inconsistent indentation. If tab size is set to 0, tabs are not expanded (the default).
        Parameters:
        tabsize - Spaces per tab or 0 for no tab expansion. Must be non-negative
        Returns:
        this
      • tabs

        public AttributedStringBuilder tabs​(java.util.List<java.lang.Integer> tabs)
        Sets the tab stops for this attributed string builder.

        This method sets the tab stops for this attributed string builder, which are used for tab expansion when appending tab characters. Tab stops cannot be changed after text has been added to prevent inconsistent indentation.

        Parameters:
        tabs - the list of tab stop positions
        Returns:
        this attributed string builder
        Throws:
        java.lang.IllegalStateException - if text has already been appended
      • altCharset

        public AttributedStringBuilder altCharset​(java.lang.String altIn,
                                                  java.lang.String altOut)
        Sets the alternate character set sequences for this builder.

        This method sets the alternate character set sequences for this builder, which are used for handling special characters like box drawing characters. The alternate character set cannot be changed after text has been added to prevent inconsistent character rendering.

        Parameters:
        altIn - the sequence to enable the alternate character set, or null to disable
        altOut - the sequence to disable the alternate character set, or null to disable
        Returns:
        this builder
        Throws:
        java.lang.IllegalStateException - if text has already been appended
      • styleMatches

        public AttributedStringBuilder styleMatches​(java.util.regex.Pattern pattern,
                                                    AttributedStyle s)
        Applies the specified style to all matches of the pattern in this builder.

        This method finds all matches of the specified regular expression pattern in this builder and applies the specified style to the matching regions. The style is applied to all characters in each match.

        Example usage:

         builder.append("Error: File not found")
                .styleMatches(Pattern.compile("Error:"), AttributedStyle.DEFAULT.foreground(AttributedStyle.RED));
         
        Parameters:
        pattern - the regular expression pattern to match
        s - the style to apply to matching regions
        Returns:
        this builder
      • styleMatches

        public AttributedStringBuilder styleMatches​(java.util.regex.Pattern pattern,
                                                    java.util.List<AttributedStyle> styles)
        Applies different styles to different capture groups in pattern matches.

        This method finds all matches of the specified regular expression pattern in this builder and applies different styles to different capture groups in each match. The first style in the list is applied to the first capture group, the second style to the second capture group, and so on.

        Example usage:

         builder.append("Error: File not found")
                .styleMatches(Pattern.compile("(Error): (File not found)"),
                             Arrays.asList(
                                 AttributedStyle.DEFAULT.foreground(AttributedStyle.RED),
                                 AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW)));
         
        Parameters:
        pattern - the regular expression pattern to match
        styles - the list of styles to apply to capture groups
        Returns:
        this builder
        Throws:
        java.lang.IndexOutOfBoundsException - if the pattern has fewer capture groups than styles