A small and easy to use helper to include in your CMake build system to have colored text output, independent of the used Terminal or operating system.
See also: License (zlib)
The normal message(...)
command in CMake sadly doesn't support custom colors or styles for messages. With this helper file you can print messages with colors, have multiple colors in one message, or only have parts of the message printed with color, while the rest of the text in the same line is printed normally.
This helper does not use ANSI escape codes directly to print the colors and styles. It is fully compatible with every Terminal and every operating system.
Just copy the file colorFormatting.cmake
next to your CMakeLists.txt and include it in your CMakeLists.txt:
include("colorFormatting.cmake")
To print the whole message with one color and/or style you can use the messageWithColor(...)
function:
messageWithColor(COLOR BLUE "My message with blue color")
To print a message using bold text style and no color change use this argument:
messageWithColor(BOLD "My message in bold text")
The bold style can be combined with colors:
messageWithColor(BOLD COLOR GREEN "My message in bold text and green color")
To print a part of the message with colors and/or styles, there is another function called colorFormatText(...)
. It takes the same arguments as messageWithColor(...)
, but doesn't print anything directly.
Instead colorFormatText(...)
sets the variable COLOR_FORMATTED_TEXT
that you can print yourself. This way you can append unformatted text to formatted text:
# Formatted text is saved in COLOR_FORMATTED_TEXT
colorFormatText(COLOR GREEN "This is green:")
# Print the formatted text and append unformatted text
message("${COLOR_FORMATTED_TEXT} This is without color")
To print a message with multiple colors and/or styles, you can use the colorFormatTextAppend(...)
function. It takes the same arguments as colorFormatText(...)
, but doesn't print anything on it's own.
Instead it appends the given string to the COLOR_FORMATTED_TEXT_COMBINED
variable, that you can print yourself:
# Append multiple strings with different colors and styles
colorFormatTextAppend(COLOR RED "This is ")
colorFormatTextAppend(COLOR GREEN "a multicolor ")
colorFormatTextAppend(BOLD COLOR BLUE "message ")
colorFormatTextAppend(COLOR MAGENTA "test")
# Print the combined string with multiple colors
message("${COLOR_FORMATTED_TEXT_COMBINED}")
Color | Style | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
|
NOTE: If an invalid color argument is passed to any of the above functions, the text will be printed without any color change. No error message is printed.