Styles

Another way of printing ANSI formatted text is to use a reusable style object. It pre-computes ANSI formatted text and applies the style to a string which can then be written to the output stream.

An example:

#include <Ansi>
#include <iostream>

int main() {
    // NOTE: The first parameter is a StyleColor which can be
    // One of 3 formats: RGB, ANSI, or Term256
    // We can pass the ANSI color directly since the StyleColor
    // struct has an implicit constructor that takes an ANSI
    // color
    auto st = ansi::styling::Style(ansi::Red, {
        ansi::Underline
    });

    std::cout << st.apply("Text1")
        << " and "
        << st.apply("Text2") << std::endl;

    // Uses one of the 256 terminal colors by implicitly using
    // A StyleColor of type Term256
    auto st256 = ansi::styling::Style(220, {
        ansi::Bold
    });

    std::cout << st256.apply("Text1")
        << " and "
        << st256.apply("Text2") << std::endl;

    // Since the RGB StyleColor takes 3 parameters it has to
    // be manually instantiated
    auto strgb = ansi::styling::Style(
        ansi::StyleColor(30, 177, 249), {
        ansi::Bold
    });


    std::cout << strgb.apply("Text1")
        << " and "
        << strgb.apply("Text2") << std::endl;
}

The styling namespace has the following members:

namespace ansi::styling

Style classes for text.

Contains classes for applying a set of styles to some text.

Some examples:

#include <iostream>
#include <Ansi>

int main() {
 std::cout << ansi::styling::Style(ansi::styling::StyleColor(ansi::Yellow,
{ansi::Bold, ansi::Underline}).apply("Text")) << std::endl;
}

class Style
#include <>

Text styling.

Holds styling information to be applied to text

Public Functions

Style(StyleColor c, std::initializer_list<ansi::TextModifier> &&m)

Constructs a new Style using a color and a list of modifiers.

Parameters
  • c – The color of the text

  • m – A list of modifiers to apply to text

auto apply(const char *text) const -> ManipulatorFunc

Applies the style to text.

Note

Resets all styling after the text is written to the ostream

Parameters

text – The text to apply the style to

Returns

The manipulator to be used with operator<<

Style()

Default constructor.

Style(const Style &other)

Copy constructor.

Parameters

other – The Style object to copy from

Style(Style &&other) noexcept

Move constructor.

Parameters

other – The Style object to move from

auto operator=(const Style &other) -> Style&

Trivial copy assignment operator.

Parameters

other – The Style object to copy from

Returns

The assigned object

auto operator=(Style &&other) noexcept -> Style&

Trivial move assignment operator.

Parameters

other – The Style object to move from

Returns

The assigned object