Coder Social home page Coder Social logo

ikalnytskyi / termcolor Goto Github PK

View Code? Open in Web Editor NEW
798.0 29.0 124.0 269 KB

Termcolor is a header-only C++ library for printing colored messages to the terminal. Written just for fun with a help of the Force.

Home Page: https://termcolor.readthedocs.io/

License: Other

C++ 95.96% CMake 4.04%
c-plus-plus terminal console fancy colors windows linux macos

termcolor's Introduction

Termcolor

termcolor in action

Termcolor is a header-only C++ library for printing colored messages to the terminal. Written just for fun with a help of the Force. Termcolor uses ANSI color formatting, so you can use it on every system that is used such terminals (most *nix systems, including Linux and Mac OS).

Note

On Windows, Windows API is used instead of escape codes but some limitations are applied (not everything is supported). That's why it's recommended to enter virtual terminal processing mode and set TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES macro to trick termcolor to use ANSI color codes.

It's licensed under the BSD (3-clause) License. That basically means: do whatever you want as long as copyright sticks around.

Installation

  • Add termcolor.hpp (grab it from include/termcolor/termcolor.hpp) to the project and use stream manipulators from the termcolor namespace.
  • You can also use vcpkg to install the library:

    $ vcpkg install termcolor
  • Or if you are on macOS, you can use Homebrew for that purpose:

    $ brew install termcolor
  • For up-to-date information about existing packages, refer to the the following picture:

    Packaging Status

How to use?

It's very easy to use. The idea is built upon C++ stream manipulators. Typical «Hello World» application looks like this:

The application above prints a string using different colors. There is one caveat though. You must not forget to reset colors, otherwise they will be applied to other prints as well.

Correct version of the code above should look like this:

By default, Termcolor ignores any colors for non-tty streams (e.g. std::stringstream), so the following snippet

will print «unicorn» using default color, not red. In order to change this behaviour one can use termcolor::colorize manipulator that enforce colors no matter what.

What manipulators are supported?

The manipulators are divided into four groups:

  • foreground, which changes text color;
  • background, which changes text background color;
  • attributes, which changes some text style (bold, underline, etc);
  • control, which changes termcolor's behaviour.

Also, there are color manipulators for 16 colors, 256 colors and true colors palettes.

Note

While termcolor supports true color, it's required for the terminal emulator you use to run your software to support true color too. So please ensure it's supported before filing an issue.

Foreground manipulators

16 colors

  1. termcolor::grey
  2. termcolor::red
  3. termcolor::green
  4. termcolor::yellow
  5. termcolor::blue
  6. termcolor::magenta
  7. termcolor::cyan
  8. termcolor::white
  9. termcolor::bright_grey
  10. termcolor::bright_red
  11. termcolor::bright_green
  12. termcolor::bright_yellow
  13. termcolor::bright_blue
  14. termcolor::bright_magenta
  15. termcolor::bright_cyan
  16. termcolor::bright_white

256 colors

  1. termcolor::color<256_COLOR_CODE>

true colors

  1. termcolor::color<RED, GREEN, BLUE>

Background manipulators

16 colors

  1. termcolor::on_grey
  2. termcolor::on_red
  3. termcolor::on_green
  4. termcolor::on_yellow
  5. termcolor::on_blue
  6. termcolor::on_magenta
  7. termcolor::on_cyan
  8. termcolor::on_white
  9. termcolor::on_bright_grey
  10. termcolor::on_bright_red
  11. termcolor::on_bright_green
  12. termcolor::on_bright_yellow
  13. termcolor::on_bright_blue
  14. termcolor::on_bright_magenta
  15. termcolor::on_bright_cyan
  16. termcolor::on_bright_white

256 colors

  1. termcolor::on_color<256_COLOR_CODE>

true colors

  1. termcolor::on_color<RED, GREEN, BLUE>

Attribute manipulators

(Windows API does not support these manipulators except for underline)

  1. termcolor::bold
  2. termcolor::dark
  3. termcolor::italic
  4. termcolor::underline
  5. termcolor::blink
  6. termcolor::reverse
  7. termcolor::concealed
  8. termcolor::crossed

Control manipulators

(Windows API does not support these manipulators)

  1. termcolor::colorize
  2. termcolor::nocolorize

Caveats

  1. On Windows, due to internal usage of <windows.h>, global namespace could be polluted with min/max macros. If such effect is desireable, please consider using #define NOMINMAX before #include <termcolor.hpp>.

termcolor's People

Contributors

gabrielhomsi avatar ikalnytskyi avatar mashumafi avatar mikelolasagasti avatar mtauban avatar nabijaczleweli avatar neroburner avatar panzergame avatar playday3008 avatar salirezag avatar theidexisted avatar trailfrenzy avatar wvenialbo avatar yuri-sevatz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

termcolor's Issues

#define min() and #define max() pollute global namespace by including termcolor.hpp

My work around was to #undef min and #undef max immediately after including termcolor.hpp. The macro version of min and max smashed the std::limits<>::min and std::limits<>::max. Is it possible to #undefine these two macros in termcolor.hpp since the min and max in now defined in #include which is the preferred way of using min() and max() for modern C++.

Intensity on Windows

I feel like there should be a termcolor::intense or something, similar to termcolor::bold, but since there isn't I made this hack to get around the issue

#include "termcolor/termcolor.hpp"

namespace termcolor
{
	namespace _internal
	{
		struct _Intensify
		{
			_Intensify(int color) : color(color) {}

			int color;
		};
	}

	inline _internal::_Intensify intense(int color)
	{
		return _internal::_Intensify(color);
	}
}

template < typename _CharT, typename _Traits>
inline std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os, termcolor::_internal::_Intensify __f)
{
	if (termcolor::_internal::is_colorized(__os))
	{
		termcolor::_internal::win_change_attributes(__os, FOREGROUND_INTENSITY | __f.color);
	}

	return __os;
}

Used like:

std::cerr << termcolor::intense(FOREGROUND_RED) << "You must only use one argument at a time!" << termcolor::reset << std::endl;

Would be nice if this was part of the official repo, I can make a pull request (that isn't a hack) if you'd like.

Fall back to no colors on unknown OSes

Hi,

Your code:

// the following snippet of code detects the current OS and
// defines the appropriate macro that is used to wrap some
// platform specific things
#if defined(_WIN32) || defined(_WIN64)
#   define TERMCOLOR_OS_WINDOWS
#elif defined(__APPLE__)
#   define TERMCOLOR_OS_MACOS
#elif defined(__unix__) || defined(__unix)
#   define TERMCOLOR_OS_LINUX
#else
#   error unsupported platform
#endif

Personally I would prefer that using termcolor on an unknown OS would simply fall back to using no colors instead of failing with a compilation error.

Another suggestion to increase portability is to check if non standard headers exist before including them.

// This headers provides the `isatty()`/`fileno()` functions,
// which are used for testing whether a standart stream refers
// to the terminal. As for Windows, we also need WinApi funcs
// for changing colors attributes of the terminal.
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
#   include <unistd.h>
#elif defined(TERMCOLOR_OS_WINDOWS)
#   include <io.h>
#   include <windows.h>
#endif

E.g. I would prefer using code like this:

#if (defined(TERMCOLOR_OS_MACOS) || \
     defined(TERMCOLOR_OS_LINUX)) && \
    (!defined(__has_include) || __has_include(<unistd.h>))
#   include <unistd.h>
#elif defined(TERMCOLOR_OS_WINDOWS) && \
    (!defined(__has_include) || (__has_include(<io.h> && __has_include(<windows.h>)))
#   include <windows.h>
#endif

Of course you still need to add a fall back mode (using more preprocessor checks) for the case when the headers do not exist.

Windows 10 Virtual Terminal Sequence Support

Hello!

Windows 10 supports VT100 escape sequences with a call to SetConsoleMode and the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag. Using this would give Windows users more features. You can also, for non Windows 10 versions, fallback to the current behavior.

fmt support? file descriptor support?

The README explains how to use this library with C++ streams. But - what about other ways of printing output? e.g. std::format, or in the other extreme, raw file descriptors?

Note: I'm asking for documentation, not features, in this issue.

Support for Gitbash on Windows

I'm using this library very successfully on Linux and Windows Powershell, but a lot of people use Gitbash on Windows. I'd love to get this working with Gitbash. Can it work with Gitbash?

How to use on VS?

Good Evening,
Just a quick question, how do I use this in a VS2015 Linux Project??

Add support for std::clog

clog is just like cerr, just buffered. Output to cerr can be formatted, but to clog - no. I think that support for formatting clog should be added.

colorize_index has different values in different translation units

Each translation unit contains it's own copy of the colorize_index static variable.
This is a normal property of static variables declared on a namespace level (which is a very different thing than static variables declared in a class or inside a function).
As a result colorize_index is initialized multiple times, and therefore each translation unit gets it's own, different colorize_index value.
Everything works as long as code that uses it is in one translation unit. Everything breaks if code is separated between translation units,
In my case there was no problem in debug builds, but in optimized builds (on g++/Linux and Visual C++/Windows), where code is heavily inlined, problems started to appear.

One solution to that problem could be storing colorize_index as a static variable inside a templated class:

        template<typename T>
        struct ColorizeIndexWrapper
        {
            static int colorize_index;
        };

        template<typename T>
        int ColorizeIndexWrapper<T>::colorize_index = std::ios_base::xalloc();

        // Usage:
        _internal::ColorizeIndexWrapper<int>::colorize_index

Wheel support for linux aarch64/x86

Summary
Installing termcolor on aarch64/x86 via pip using command "pip3 install termcolor" tries to build wheel from source code

Problem description
termcolor doesn't have wheel for aarch64/x86 on PyPI repository. So, while installing termcolor via pip on aarch64/x86 machine, pip builds the source code resulting in it takes more time to install termcolor. Making wheel available for aarch64/x86 will benefit aarch64/x86 users by minimizing termcolor installation time.

Expected Output
Pip should be able to download termcolor wheel from PyPI repository rather than building it from source code.

@termcolor-team, please let me know if I can help you building wheel/uploading to PyPI repository. I am curious to make termcolor wheel available for aarch64. It will be a great opportunity for me to work with you.

Control Characters on Windows Terminal

I was shopping around for a C++ lib to simplify text color to terminal apps. I found this, but notice it uses special handling for Windows. However, I noticed that control characters works in Windows Terminal (and VSCode terminal)

Would be interesting to have a switch to make Windows builds to also use control characters. Could this be of interest for this lib?

Use with stringstreams

I naively thought the stream manipulators here would work with a std::stringstream object, for later relaying to a terminal.

As it currently stands though, the library does a strict check on the stream to see if it's a terminal stream via termcolor.hpp#445, which it promptly fails and aborts.

Nonetheless, by just ensuring that function always returns true, I can get the following code to work quite normally.

#include <termcolor/termcolor.hpp>
#include <iostream>
#include <sstream>

int main(int argc, char **argv) {
  std::stringstream sstream;
  sstream << termcolor::cyan << "Dude" << termcolor::reset;
  std::cout << sstream.str() << std::endl;
  return 0;
}

This, I imagine is quite a common and practical use case. How important is it for strict terminal checks? Is this something that can be dropped or potentially made optional?

Add pkg-config integration.

It could be good to add a pkg-config file and include it in other integrations. I honestly haven't written one before, but I think it would be something like this. Very short. Just a thought because I use Mac/Homebrew/CMake. 😁

prefix=/usr/local
exec_prefix=${prefix}
includedir=${prefix}/include
libdir=${exec_prefix}/lib

Name: termcolor
Description: Header-only C++ library for printing colored messages to the terminal.
Version: 2.0.0
Cflags: -I${includedir}/

Test for wchar_t

I guess it will be good if you create same test for wcout, wcerr, wclog

ANSI getting printed instead of colored text

Hey, I'm Yuvraj.
Thank you for the package it's been awesome but for a long time one problem is bothering me. Instead of printing colored texts for one instance in my project it is just printing ANSI sequence in CMD.

Here's my code.

image

Can you help me out?

does not play nicely with MSYS/MinGW shells

on windows, the library performs very well but if you try to use it in a MSYS or MinGW shell it prints out unescaped data and does Not color it. this is partially acknowledged in the README, but I wanted to open an official issue to address it.

Tag a version

Could you create a tag to mark a release?

If you don't need semantic versioning you could use a vYY.MM.X versioning scheme. For examle v18.10.1

Otherwise I would have to create a fork and tag myself to add your project to Hunter just to have a persistent reference

Compile problem

||=== Build: Release in *** (compiler: GNU GCC Compiler) ===|
C:\Users\Geo\Desktop\DBG\SteamServerQuery\termcolor.hpp||In function 'bool termcolor::_internal::is_atty(const ostream&)':|
C:\Users\Geo\Desktop\DBG\SteamServerQuery\termcolor.hpp|452|error: '_fileno' was not declared in this scope|
C:\Users\Geo\Desktop\DBG\SteamServerQuery\termcolor.hpp||In function 'bool termcolor::_internal::is_atty(const ostream&)':|
C:\Users\Geo\Desktop\DBG\SteamServerQuery\termcolor.hpp|454|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 3 warning(s) (0 minute(s), 1 second(s)) ===|

Error lines:

//! Test whether a given `std::ostream` object refers to
        //! a terminal.
        inline
        bool is_atty(const std::ostream& stream)
        {
            FILE* std_stream = get_standard_stream(stream);

        #if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
            return ::isatty(fileno(std_stream));
        #elif defined(TERMCOLOR_OS_WINDOWS)
            return ::_isatty(_fileno(std_stream));
        #endif
        }

Compiler: TDM-GCC 4.9.2
IDE: CodeBlocks 16.01

Solution?

Expose is_colorized

Hi, it would be useful if the is_colorized function would be exposed outside the implementation detail namespace. That way I can know if it's safe to colorize into a transitory string (via stringstream for example) before outputing that string to a maybe colorized stream.

Small aside: while technically according to the standard your "_internal" namespace is valid, I would avoid anything that starts with an underscore.

Include Error

I'm under Code :: Blocks with the GCC compiler.
In the IDE, I added the file to my project.
I wanted to try to include your file to use it in addition to pdcurses but it does not seem to find the .hpp.
I put this line: #include <termcolor / termcolor.hpp>

Here is the error:
||=== Build: Debug in testapp (compiler: GNU GCC Compiler) ===|
C:\Users\Utilisateur\Desktop\Logiciels Programmations\Mes_Programmes\C++\testapp\main.cpp|2|fatal error: termcolor/termcolor.hpp: No such file or directory|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I would like to point out that I still have a lot of trouble understanding the general functioning of compilers and compiling, command lines and the addition of libs.
And then I have to learn to use the IDE and its options as well as the C/C ++ language. Especially as I am on Windows 10, not really help in apprenticeship compared to the say of the Linuxiens. ^^

So I do not know if it's a manipulation fault or if it's really the file itself that is not taken into account by the compiler I'm using.
But from what I've read in the documentation, it should work under windows?

If someone passes by and wants to answer me, I would be very happy to learn from where the error came. Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.