File: colorizer.cpp

package info (click to toggle)
cupt 2.10.4%2Bnmu2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,144 kB
  • sloc: cpp: 23,642; perl: 1,599; sh: 40; makefile: 19
file content (88 lines) | stat: -rw-r--r-- 2,440 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**************************************************************************
*   Copyright (C) 2011 by Eugene V. Lyubimkin                             *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License                  *
*   (version 3 or above) as published by the Free Software Foundation.    *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU GPL                        *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA               *
**************************************************************************/
#include <unistd.h>
#include <cstdlib>

#include "colorizer.hpp"

namespace {

const string noColor = "\e[0m";

bool guessColorSupport() {
	if (isatty(STDOUT_FILENO))
	{
		const char* term = getenv("TERM");
		if (term)
		{
			if (strcmp(term, "xterm") == 0 ||
				strncmp(term, "xterm-", 6) == 0 ||
				strcmp(term, "linux") == 0)
			{
				return true;
			}
		}
	}

	return false;
}

}

Colorizer::Colorizer(const Config& config)
{
	const string optionName("cupt::console::use-colors");
	const auto strValue = config.getString(optionName);
	__enabled = (strValue == "auto" ? guessColorSupport() : config.getBool(optionName));
}

string Colorizer::makeBold(const string& input) const
{
	if (__enabled)
	{
		return string("\e[1m") + input + noColor;
	}
	else
	{
		return input;
	}
}

string Colorizer::colorize(const string& input, Color color, bool bold) const
{
	if (color == Default)
	{
		return bold ? makeBold(input) : input;
	}

	if (__enabled)
	{
		auto boldPrefix = bold ? "1;" : "";
		return format2("\e[%s3%cm", boldPrefix, color) + input + noColor;
	}
	else
	{
		return input;
	}
}

bool Colorizer::enabled() const
{
	return __enabled;
}