forthebadge forthebadge Gem Version

This gem was last updated on the 04.12.2023 (dd.mm.yyyy notation), at 03:39:43 o'clock.

The Colours project

Making colours great again! \o/

Goals, Scope and the History of the colours project

The Colours project originated from a distinct requirement to have to support colours on the commandline, such as for commandline-oriented scripts.

Colours can be immensely helpful for use in computer programs, so it appears to be a logical conclusion to make use of them on the commandline as well. The modern www also makes use of colours - just look at any random webpage; you may find lots of different colours in use there, for various reasons and purposes.

If you do happen to take a look on different projects offered on rubygems.org then you may be able to find lots of different colour-related projects, written in ruby. The primary reason as to why I created a new colour-centric project was because I needed certain functionality made available that was not provided by any of the other projects; at the least not in a way as I thought it should be available (and used in downstream projects).

For example, some terminals support RGB values and other terminals do not. I did not want to have to spend time thinking about this much at all, so I wanted to have a colours-related project that could abstract this away for me. That way I can focus on other problems, and delegate the colour-specific issues to this gem here.

Let's next show how this may then look on the commandline:

The main goal of the colours project is to collect colour-related code and make this code available to other projects, so that these projects can benefit from colour support via one project: the colours gem.

The primary goal herein lies on commandline applications, but there are some HTML components as part of this project that could be used as well, such as for when you wish to make use of HTML colours (slateblue, royalblue, teal, tomato, steelblue and names such as these) in a webpage.

Elements such as:

This is in dodgerblue.

The partial screenshot that was shown above indicates this situation, on a black KDE konsole background. (I tend to prefer dark backgrounds for my terminals.)

Note that many terminals support the display of HTML colours, via their corresponding RGB values. Since I wanted to use good terminals, such as the KDE konsole, the colours project also had to support these names directly, as method calls as well - names such as slateblue or royalblue). This is the reason why method calls such as Colours.royalblue() or Colours.darkgreen will also work - see for a later subsection how to customize (and control) this behaviour.

Historically the Colours gem was inspired by other, older projects, such as AnsiColours, ColourE, AliasE and several other smaller sub-projects that I have used over the years. These projects were eventually integrated into one namespace - module Colours. This gem is thus a bundled project. This is specifically mentioned in the event that you may wish to peek at the code, and wonder a little why it is structured the way it is.

Requiring the colours project

To require the colours project, simply do:

require 'colours'

You can also autoinclude this module into your project, at require-time, via:

require 'colours/autoinclude'

This will make the Colours namespace and the Colours::HtmlColours namespace available, via include Colours ultimately.

If you need more control over the include-action then you should just use the first variant, require 'colours', and then do the include action specifically onto whatever class/module you need that functionality.

The project was partially rewritten in November 2023. If you want to autoinclude the project still then I recommend you use this:

require 'colours/html_colours'

After that methods such as Colours.steelblue() will work.

ASCII Escape Characters

The code in the colours gem makes use of elements such as \033 or \x1b. These are basically the same ASCII escape characters, as the following table shows:

|-------------|------------| | octal | \033 | |-------------|------------| | hexadecimal | \x1b | |-------------|------------| | Unicode | \u1b, \U1b | |-------------|------------| | literal | \e, \E | |-------------|------------|

The last variant can often be found in Bash scripts.

The semicolon ; serves as the delimiter if multiple instructions are given.

The 8 actual colours defined by the ANSI standard are as follows:

0  black
1  red
2  green
3  yellow
4  blue
5  magenta
6  cyan
7  white

Linux terminals and colour support

The general syntax rules for colours is in the form of fg_bg values, where a value of 38 stands for the foreground, and 48 stands for the background.

For instance, the ANSI colour for red is 196 and the ANSI colour for black is 0.

To use the colour red, you could issue this command in Bash:

printf "\e[38;5;196m Hello world in red\n"

To use the colour black as background, you could issue this command:

printf "\e[48;5;0m Hello world in black\n"

Do note that the same can be accomplished via RGB values rather than ANSI color codes, as long as the terminal supports this (KDE Konsole does).

Depending on whether you want to apply the colour to the foreground or to the background, use an fg_bg value of 38 or 48 (respectively).

Examples for this:

# printf "\e[<fg_bg>;2;<R>;<G>;<B>m" # General syntax example.
printf "\e[38;2;255;0;0m Foreground color: red\n"
printf "\e[48;2;0;0;0m Background color: black\n"
printf "\033[91m\033[107mThis is red text on a white background\033[0m" # As this example shows, \e is the same as \033.

This may be the better variant altogether, as it is quite easy to convert into (and from) RGB values, but your mileage may vary.

Of course you can use this in plain ruby just as well - let's show this via puts:

puts "\e[38;2;#{222};#{131};#{141}m Hello world!"
puts "\e[38;2;#{122};#{56};#{141}m Hello world!"
puts "\e[38;2;122;156;141m Hello world!"
puts "\x1b[3mHello world!\x1b[0m"
puts "\e[38;3mHello world!\x1b[0m"

In bash the ESC code can be either of the following:

\e
\033 (octal)
\x1B (hexadecimal)

The "\e[0m" sequence removes all attributes, including formatting and colors. It may be useful to add it to the end of each colour text - and this is what the Colours project is essentially doing.

To see which colours are supported/supportable, for each terminal, have a look at the following link:

https://misc.flogisoft.com/bash/tip_colors_and_formatting#terminals_compatibility

To set both the foreground and background colours at once, you can use:

printf "\e[S;FG;BGm"
echo -e "\e[S;FG;BGm"

For example, bold white foreground on a red background:

printf "\e[1;97;41mHello world!"
printf "\e[1;97;41mHello world!\n"

Thus, if you would like to use red colour on black background, you could do this:

printf '\e[38;5;196m;\e[48;5;0m Hello world!\n'

Specifically, the background colours are:

40  black
41  red
42  green
43  yellow
44  blue
45  magenta
46  cyan
47  white

The following command will use red background:

echo -e '\e[0;41m'
echo -e '\e[0;41m hello world\n\n ok\e[0;m'

Introduction and Overview

The toplevel module name is Colours and you can include this module in any of your classes, via:

require 'colours'

include Colours

If you include Colours into main (toplevel), then you can simply use the colour-constants directly:

puts RED+'This is a red text.'
puts BLUE+'This will be in blue.'

Keep in mind when you use something like the above, with the leading escape-code for RED or BLUE, then this is missing the proper escape-code for end (revert). This value is usually \e[0;37m, or simpler, use Colours.rev() such as in:

puts RED+'This is a red text.'+Colours.rev
puts BLUE+'This will be in blue.'+Colours.rev

The corresponding colour-methods can also be used:

red 'This is a red text.'
blue 'This is a blue text.'

This has the advantage that you do not have to use Colours.rev anymore. So in some ways the colour-named methods are better. (Of course it is a bit complicated if you want to use RGB colours, so always make sure to specifically include what you really need.)

Colour-related constants are simply hardcoded, such as in this way:

GREEN = "\e[0;32m"

To test all colours, after requiring the project such as described above, do:

Colours.test

Several methods exist as well, such as sfancy(), swarn(), simp(), sdir() and sfile(), among others.

These methods can be used to colourize certain Strings, such as:

a file       use sfile()
a directory  use sdir()
a warning    use swarn()

The methods sfancy() and simp() are there to denote more important output, usually in the middle of a String. Think of this as a way to emphasize what you wish to display to the user at hand. (The important parts of the sentence should be colourized and emphasized. This is the whole point for simp() to exist; simp() is a shortcut for string_important, by the way.)

To make use of the html-colours component, such as converting a "HTML Colour" to its RGB values, you can do this:

puts Colours::HtmlColours.colour_to_rgb(:sienna) # ← This variant no longer works.
puts Colours.html_colours.colour_to_rgb(:sienna) # ← This variant no longer works.
pp Colours.colour_to_rgb(:sienna)                # ← This variant actually works, and will return an Array such as: [160, 82, 45]

If you want to return a random HTML colour, you can use this method call:

Colours::HtmlColours.random

or

Colours.html_colours.sample # => "darksalmon"
Colours.html_colours.sample # => "turquoise"
Colours.html_colours.sample # => "lightblue"

Or just:

Colours.sample # => "khaki"
Colours.random_html_colour # => "slateblue"

Use whichever variant you prefer. The shorter names are more elegant in my opinion.

In general, the html component can be used to convert the trivial html colours into corresponding R,G,B values.

Note that in November 2023 I rewrote parts of the gem. This also led to a re-evaluation of methods such as sdir() or sfancy().

I use sfile(), sdir() and sfancy() a lot. I also use simp(), as abbreviation for simportant(), sometimes. However had, other methods, such as ssymlink(), I rarely use; and I never used sarguments(), yet the project still carried code that supported such a use case. During the partial rewrite in November 2023 I decided to deprecate and remove sarguments() aka Colours.sarguments(). I also deprecated snormal(), aka Colours.snormal(), as I also have not ever used that method actually.

Obtain all available HTML colours

To obtain all available html-colours, do this:

Colours::HtmlColours.all_colours?

Or in a simpler way, without the ::HtmlColours part:

Colours.return_all_html_colours

There are presently 142 registered HTML colours available:

Colours.return_all_html_colours.size # => 142

If you need to find out whether a given String (a word) is registered as part of the HTML-Colours within module Colours, then you could use the following toplevel-method:

Colours.is_this_html_colour_included?
Colours.is_this_html_colour_included? :slateblue  # => true 
Colours.is_this_html_colour_included? 'royalblue' # => true

eparse()

The eparse() method is a convenience method to apply on Strings such as 'Foo: bar'. Note the ':' character there. That input will be split, and then displayed via two different colours.

Underline / Underlining

You can underline text, and print it onto the terminal, by issuing a command such as the following:

txt = 'Hello world!'

Colours.underline(txt)

You can also add colours to this, via {}:

Colours.underline(txt)
Colours.underline(txt) { :palegreen }
Colours.underline(txt) { :slateblue }
Colours.underline(txt) { :orange }
Colours.underline(txt) { :crimson }

Within the {} block you can use HTML colours, as symbol, such as :slateblue or :orange and so forth. If you would rather not like to use these colours then simply do not pass them into the method, as the first variant shows. :)

If you only want to get the colour code for that string, without displaying it on the terminal it, then you can use .string_underline() or .return_underline() method:

Colours.string_underline(txt) { :palegreen }
Colours.string_underline(txt) { :slateblue }
Colours.string_underline(txt) { :orange }
Colours.string_underline(txt) { :crimson }
Colours.return_underline(txt) { :royalblue }

include Colours::Methods

Since as of February 2019 there is a module called Methods part of the colours gem. This module allows us to include the konsole-related colour methods into a subclass.

Example:

class Foo
  include Colours::Methods
end

e Foo.new.royalblue('hey there')

As you can see, this class will have the HTML colours available, such as .royalblue() or .slateblue() and so forth.

I needed this in some of my other code, so it was added. I like full colour support on terminals such as KDE konsole.

Note that this has to be specifically included, as I am not sure everyone wants to have that the moment include Colours is done. The toplevel Colours module will stay a bit simpler by default; for customization, you will have to go the extra line through include Colours::Methods, which appears to be an acceptable trade-off.

Note that you can also subclass from a "dummy" class with colour support, such as royalblue() or slateblue.

Use code similar to the following variant for this:

require 'colours/base/base.rb'

class Foobar < Colours::Base # Or whatever the name of your class is
end

Showing the colour palette on the commandline

You can show the "classical" ASCII colours on the commandline by invoking this method:

Colours.show_palette

This also works, or should work, from the commandline, like so:

colours --show-palette
colours --palette

The KDE colour palette

The KDE project makes use of a special, named colour palette.

This palette includes the following 20 different colours, via a trivial name:

Abyss Blue
Alternate Grey
Beware Orange
Burnt Charcoal
Cardboard Grey
Charcoal Grey
Coastal Fog
Deco Blue
Hover Blue
Hyper Blue
Icon Blue
Icon Green
Icon Grey
Icon Red
Icon Yellow
Lazy Grey
Noble Fir
Paper White
Pimpinella
Plasma Blue

You can find these entries, including their hex-values and their RGB values, on websites such as this one here:

https://community.kde.org/KDE_Visual_Design_Group/HIG/Color

Note that these are also called the "Breeze" colours, which I assume is the name of the theme.

Since as of July 2018, the colours project also includes these colours, via the file colours/constants/kde_colour_palette.rb.

The entries are stored in a .yml file, so if anyone wants to re-use these from a yaml file, feel free to just copy/paste it from there. That file is at colours/yaml/kde_colour_palette.yml.

Internally, the values are made available via the constant:

Colours::KDE_COLOUR_PALETTE

Which is a hash. There are also a few methods that may be useful to use. For example, if you want to use a random colour, and output Hello world!, then you could use the following method:

Colours.write_this_via_kde_colour_palette 'Hello world!', :random

While random colours may be nice, perhaps you may want to use a definite colour from the above list. Say that you may want to write via Plasma Blue. In this case, you could use:

Colours.write_this_via_kde_colour_palette 'Hello world!', :plasma_blue

So using a symbol works too.

If you tend to use this regularly, then an even simpler way may exist, by simply calling a method that already has that as part of its name.

Examples with Hello World!:

Colours.kde_colour_palette_abyss_blue 'Hello world!'
Colours.kde_colour_palette_alternate_grey 'Hello world!'
Colours.kde_colour_palette_beware_orange 'Hello world!'
Colours.kde_colour_palette_burnt_charcoal 'Hello world!'
Colours.kde_colour_palette_cardboard_grey 'Hello world!'
Colours.kde_colour_palette_charcoal_grey 'Hello world!'
Colours.kde_colour_palette_coastal_fog 'Hello world!'
Colours.kde_colour_palette_deco_blue 'Hello world!'
Colours.kde_colour_palette_hover_blue 'Hello world!'
Colours.kde_colour_palette_hyper_blue 'Hello world!'
Colours.kde_colour_palette_icon_blue 'Hello world!'
Colours.kde_colour_palette_icon_green 'Hello world!'
Colours.kde_colour_palette_icon_grey 'Hello world!'
Colours.kde_colour_palette_icon_red 'Hello world!'
Colours.kde_colour_palette_icon_yellow 'Hello world!'
Colours.kde_colour_palette_lazy_grey 'Hello world!'
Colours.kde_colour_palette_noble_fir 'Hello world!'
Colours.kde_colour_palette_paper_white 'Hello world!'
Colours.kde_colour_palette_pimpinella 'Hello world!'
Colours.kde_colour_palette_plasma_blue 'Hello world!'

The reason as to why this is so long is so that we can avoid any name clashes - but in principle, we could also enable a shorter name, such as:

Colours.pimpinella # much shorter than Colours.kde_colour_palette_pimpinella

You can also use the "e" method, e which stands for echo, such as in:

Colours.epimpinella 'Hello cats!'
Colours.eplasma_blue 'Hello cats!'

This functionality is available for the Colours project since as of July 2018 - but be careful, since this may change one day, in the event that a conflict may exist with an already defined name (such as the names in the HTML colour charts, e. g. "slateblue", "royalblue" and so forth).

Do note that the behaviour may change, too; e. g. Colours.pimpinella() may in the future only return a String, and a new method called Colours.epimpinella() would be tasked with outputting the text - but for the time being, things stay as described above (in July 2018).

Using the Konsole submodule

In the past there was a Konsole submodule, but in May 2019 during a large rewrite, this submodule has been removed.

The functionality has been integrated into an autogenerated .rb file though. That module can be found in the file called toplevel_basic_colour_methods.rb.

Old invocation examples such as:

Colours[:slateblue]

Should be possible still.

You can also include this new module:

include Colours::AllColourMethods

Then you can simply call the respective colour output:

slateblue('Hello World!')

eslateblue()
eslateblue('Hello World!')

eslateblue() works like slateblue() but outputs the result.

konsole_colour_slateblue('Hello World!')
ekonsole_colour_slateblue('Hello world!')

The above two variants are probably too long, but they also exist if you wish to be more specific.

Automatic inclusion can be done like so:

require 'colours/konsole/autoinclude'

Konsole['slateblue']+'Hello World'
konsole :green, 'hello world'

Of course you can also manually include it by yourself:

require 'colours'

Note that when you include that module, you will have access to methods such as e. g. slateblue() or sandybrown().

konsole_colours :slateblue, 'hello world!'

256 colour support

Some terminals allow support for 256 colours.

The colours gem allows you to test this, via this toplevel-method:

Colours.show_all_256_colours

If you need to specifically use one of these colours, have a look at the following two methods:

Colours.return_this_256_colour()
Colours.display_this_256_colour()

The first input argument should be the number, from 0-255, and the second argument is the text that is to be displayed (append a newline to this if you need one).

The first input argument is called id, for the purpose of this document here.

Let's provide specific examples how to use the latter method.

For example, to ouput, in red, the sentence "Ruby is awesome!", you could use either of the following methods:

Colours.display_this_256_colour(88, "Ruby is awesome!\n")
Colours.display_this_in_256_colour(88, "Ruby is awesome!\n")

Note that you can also use several colours, based on the id input, via a pseudo-range. A pseudo-range is input that is a String and includes one '-' character. For example, 33-44 is a pseudo-range and so is 0-255.

In ruby code, this could work like so - give it a try:

require 'colours'

Colours.display_this_256_colour('0-255',"Hello world, in a batch!\n")

If you wish to make use of these colour-methods in one of your classes, then you can require the module, and include it into your class.

Example for this:

require 'colours/autogenerated/support_for_256_colours.rb'

class Foobar

  include Colours::SupportFor256Colours

  def initialize
    puts darkturquoise('HELLO ')+
         maroon('WORLD ')+
         'This is ok again'
  end

end

Foobar.new

Colours.show_basic_colour_palette

The method Colours.show_basic_colour_palette can be used to quickly show the basic colour palette supported on the commandline.

This is just the "bare minimum" really; if you use RGB values then you have tons of colours available.

Colours.bold_and_italic()

If you quickly want to turn something into bold and italic, on the commandline, you can use:

Colours.bold_and_italic

Of course there are some alternatives to this, such as:

Colours('Hello world').bold.italic

But if you just want a simple toplevel API then you can just use Colours.bold_and_italic(). There is more than one way to do it in ruby.

revert

The toplevel instance variable called @revert designates which escape code is used for reverting the colours again.

By default, this is \e0m. However had, for some strange reason this does not appear to work very well on the default terminal style that I use (KDE konsole, white font on black background). It seems to default to white bold text, but I would rather want light white text, aka \e[0;37m. This is why revert defaults to \e[0;37m.

If you wish to use \e0m instead, then you can do so via:

Colours.set_revert('\e0m')

Or, via symbol, to the same value:

Colours.set_revert(:default)

Legacy versions of the Colours gem

In May 2019, the old Konsole submodule has been removed; the functionality itself has been retained, though. Still, as the API changed this means that not everyone may be able to use the new colours gem release.

This is the reason why the old version at 0.3.40 will continue to be available here. This one still has the old Colours::Konsole submodule defined, so if you need it in a project, feel free to use that older version.

Otherwise I recommend to upgrade to the latest version of the colours gem - the code is, in my opinion, better too.

In 2021 the old gem was released; only version 0.5.55 is still available. Consider changing to the new code base if possible - it should have a higher quality as well.

Available colour methods

If you wish to find out which colour methods will be available by default, onto the main Colours namespace, you can use the following method to find out:

Colours.all_available_colour_methods?

This will return an Array containing the names of all these toplevel methods. In May 2019 we can find 307 available colour methods e. g. such as Colours.slateblue or Colours.lightblue and so forth.

Remove escaping sequences

If you wish to remove all escaping sequences from a given String, you can use the following API for this:

Colours.remove_escape_sequences()
Colours.remove_escape_sequences "\e[38;2;41;128;18mHello world!\e[0;37m" # => "Hello world!"
pp Colours.remove_escape_sequences(Colours.slateblue('Hello world!')) # => "Hello world!"

The latter example shows that the escape-sequences are properly removed.

If you still find an example where the escape sequences are not working properly, e. g. because they are retained, then consider this to be a bug; once reported, a test case can be added to allow for removing this escape sequence as well.

Sometimes you may only wish to remove the trailing escape sequence, aka "\e[0;37m". In this case the following method may be useful:

Colours.remove_trailing_end_from()
Colours.remove_trailing_ansii_escape_code()

Usage example:

x = Colours.remove_trailing_end_from("\e[38;2;70;130;180m\e[0;37m") # => "\e[38;2;70;130;180m"

Colours.does_this_line_include_a_html_colour?

If you need to determine whether a line (a string) includes a valid HTML colour, such as slateblue>, then you can use the following method:

Colours.does_this_line_include_a_html_colour?
Colours.does_this_line_include_a_html_colour? "<green>yo there</green> <orange>getline() function</orange>" # => true
Colours.does_this_line_include_a_html_colour? "foo bar" # => false

Colours.replace_all_html_colours_in_this_line

If you wish to replace all HTML colours in a given line/string, then the following toplevel method can be used:

Colours.replace_all_html_colours_in_this_line
puts Colours.replace_all_html_colours_in_this_line '<one>hey</one>' # ← This variant works as well.

This has been specifically added for commandline-use. It allows us to replace HTML colour "tags" with the corresponding RGB value, so that a terminal emulator such as the KDE konsole can display this.

Rainbow colours

You must install the paint gem first:

gem install paint

Then you can do the following:

Colours::RainbowColours.print_rainbow_line("Hello world \n" * 40)

To print a line directly you can also use printl_plain():

Colours::RainbowColours.println_plain "one two three four five six seven eight nine ten\n\n\n"

Generating a shell file with all HTML colours

You can generate a shell file that can be sourced, in bash, fish and possibly zsh, in order to make use of the HTML colours on the commandline.

The method that does so is:

Colours.generate_shell_file_containing_the_html_colours()

This will store in the current working directory; or to another directory if you pass an argument to it.

The file will have entries such as:

export CHARTREUSE="\e[38;2;127;255;0m"

This is the RGB variant for the colour at hand. The closing tag is missing there, so you may have to use it if you wish to output text that is coloured.

You can source this .sh file and re-use it in your own scripts.

You can also generate this shell file from the commandline, through bin/colours.

Issue a command like any of the following variants:

colours --generate-shell-file-containing-the-html-colours
colours --generate_shell_file_containing_the_html_colours
colours --generateshellfilecontainingthehtmlcolours
colours --create-shell-file

Colours.fancy_parse

The toplevel method Colours.fancy_parse() can be used to parse a more complicated text/string.

For example, say that you have a HTML string with embedded i tag and HTML colours.

You can display this on the commandline.

Example:

puts Colours.fancy_parse "<lightgreen><i>hey</i></lightgreen> <teal>there</teal>"
puts Colours.fancy_parse "<tomato>hey</tomato> <teal>there</teal>"
puts Colours.fancy_parse "<tomato><i>hey</i></tomato> <teal>there</teal>"
puts Colours.fancy_parse "<tomato><b>Hello world.</b></tomato>"
puts Colours.fancy_parse "<tomato>Hello world.</tomato>"

I recommend the KDE Konsole for this, but it should work on gnome-terminal as well. Currently (September 2019) only HTML colours, such as tomato, steelblue, and so forth, are supported, as well as i (italic). This may be extended at a later time including bold.

Note that this is not working perfectly correctly for longer strings with lots of tags. At a later point this will have to be improved, but for now, it simply has to suffice. Patches are welcome, though. :)

Support for italic text

In KDE konsole, the escape sequences \e[3m and \e[23m can be used to turn italics on and off, respectively. See this commit:

https://invent.kde.org/utilities/konsole/commit/68a98ed77063e622985d422b625d7dc5895f10c3

Let's have a look at an example for this in ruby (and KDE konsole, but it may work in other terminals as well, such as the mate-terminal, which in turn is based on VTE):

puts "\e[3mHello world!\e[23m" 

I tested this in July 2020 and it works fine.

You can use regular text afterwards and that works as well.

Example:

puts "\e[3mHello world!\e[23m abc"

See the following partial image:

Of course it can also work on the commandline, e. g. via bash/zsh or a similar shell, as the following example shows:

echo -e "\e[3mHello World\e[0m"

Notice the 3 there - this is the code for italic.

If you use the colours gem and you need a String in italic, consider using the following API:

puts Colours.string_italic("Hello World!")+' OK' # => Hello World! OK

Removing html-colours and other "tags" from a String

If you have entries such as or (aka one, and steelblue), and wish to replace them with the RGB values, for commandline use, you could try to use this method:

Colours.eliminate_html(your_string_here)
Colours.away_with_html_colours_and_special_numbers(your_string_here)
Colours.away_with_html_colours_and_special_numbers "<royalblue>+</royalblue>" # => "\e[38;2;128;128;128m\e[38;2;65;105;225m+\e[38;2;128;128;128m"

This was needed so that other projects can turn strings into colourized strings - on the commandline. This explains the result, as the \e is typically used to specify an escape sequence.

Converting hex-value to R,G,B value

If you need the R,G,B value from a hexadecimal value then you can use the following method:

Colours.convert_hex_to_rgb('#baf185') # => [186, 241, 133]
Colours.hex_to_rgb('#baf185') # => [186, 241, 133]

Note that this will return an Array, with R,G,B values. If you need a string, use .join() on that result.

Table indicating which terminal codes are available

Code Effect Note
0 Reset / Normal all attributes off
1 Bold or increased intensity
2 Faint (decreased intensity) Not widely supported.
3 Italic Not widely supported. Sometimes treated as inverse.
4 Underline
5 Slow Blink less than 150 per minute
6 Rapid Blink blinking 150+ per minute; not widely supported
7 reverse, also called reversed swap foreground and background colors; should work fairly well
8 Conceal Not widely supported.
9 Crossed-out Characters legible, but marked for deletion. Not widely supported.
10 Primary(default) font
11-19 Alternate font Select alternate font n-10
20 Fraktur hardly ever supported
21 Bold off or Double Underline Bold off not widely supported; double underline hardly ever supported.
22 Normal color or intensity Neither bold nor faint
23 Not italic, not Fraktur
24 Underline off Not singly or doubly underlined
25 Blink off
27 Inverse off
28 Reveal conceal off
29 Not crossed out
30-37 Set foreground color See color table
38 Set foreground color Next arguments are 5; or 2;;;, see below
39 Default foreground color implementation defined (according to standard)
40-47 Set background color See color table below
48 Set background color Next arguments are 5; or 2;;;, see below
49 Default background color implementation defined (according to standard)
51 Framed
52 Encircled
53 Overlined
54 Not framed or encircled
55 Not overlined
60 ideogram underline hardly ever supported
61 ideogram double underline hardly ever supported
62 ideogram overline hardly ever supported
63 ideogram double overline hardly ever supported
64 ideogram stress marking hardly ever supported
65 ideogram attributes off reset the effects of all of 60-64
90-97 Set bright foreground color aixterm (not in standard)
100-107 Set bright background color aixterm (not in standard)

class Colours::Colours

This oddly named class (Colours::Colours), residing in the file colours/class/colours.rb, has been inspired by another gem, called rainbow.

The rainbow gem allows you to do the following:

require 'rainbow'
x = Rainbow("hola!").blue.bright.underline
puts x

I found this very neat, API-wise, in particular the Rainbow(STRING_GOES_HERE) part. Then I realised that the colours gem does not allow for a toplevel-method call such as Colours(). So, in December 2021, I decided to change this, and added the file colours/class/class.rb.

The above-mentioned file defines Colours(), as method. In the long run I intend to make this fully compatible with what Rainbow() offers. In November 2022 various methods were added, including the colour-method names, such as .red, .green, as well as methods such as .underline or .italic. Some more methods may be added, but by and large I am quite happy with the code as it is.

Have a look at that .rb file to see what it is currently capable of doing.

Note that since as of November 2022, that file will also be automatically required. This was different before November 2022, which is why the version of the colours gem was changed. The old colours gem will remain on rubygems.org for some time, probably even years, to allow people to use the old code base if they prefer to.

The following listing shows how to test this, if you would like to:

require 'colours'

alias e puts

e Colours('This is red').red
e Colours('this should be tilted').italic+'.'
e Colours('This is red, tilted').red.italic+'.'
e Colours('This is blue, tilted').blue.italic+'.'
e Colours('This is green, tilted').green.italic+'.'
e Colours('This is brown, tilted').brown.italic+'.'
e Colours('This is purple, tilted').purple.italic+'.'
e Colours('This is cyan, tilted').cyan.italic+'.'
e Colours('This is light gray, tilted').light_gray.italic+'.'
e Colours('This is underlined').underlined+'.'
e Colours('This is underlined and italic').underlined.italic+'.'
e Colours('This is blue.').blue
e Colours('This is blue bright underline.').blue.bright.underline
e Colours('This is blue bright underline and italic.').blue.bright.underline.italic
e Colours('This is blue bright and italic.').blue.bright.italic
e Colours("this on yellow bg").bg(:yellow) + " and " +
  Colours('even bright underlined!').underline.bright+
  Colours(' Again!').underline.bright.red

Note that .bg() is an alias towards .background(). Both variants work; .background() is easier to read, in my opinion, but .bg() is shorter, so you may want to use that.

Converting html-colours to their HEX value

If you want to convert a html-colour into the corresponding RGB value then you can make use of the executable at bin/html_colour_to_hex_value.

The following snippet shows hows this can be used:

html_colour_to_hex_value slateblue # Output would be '#6A5ACD', without '' quotes.
html_colour_to_hex_value royalblue # Output would be '#4169E1',  without '' quotes.

(You may have to add the bin/ path of that gem to your $PATH. Or simply call that executable directly. It is also distributed with the .gem, of course.)

Internally the code that allows this is the following:

require 'colours/toplevel_methods/html_colour_to_hex_value.rb'
puts Colours.html_colour_to_hex_value(ARGV)

If you need the alpha value then you could use this method:

Colours.convert_hex_code_to_RGBA_array('#baf185') # => [186, 241, 133, 1.0]

This defaults to alpha being 1.0. In a future release of the colours gem this may be made more sophisticated, but for now this has to suffice.

Colours.reset_the_line

This method, called Colours.reset_the_line, can be used to "reset" the line to the very left position.

This is useful if you want to create a progress bar indicator.

Here is example code that shows this functionality:

index = 1
loop {
  Colours.reset_the_line
  print 'OK! '+
         Random.rand(11).to_s 
  index += 1
  break if index == 50
  sleep 0.3
}
puts

Colours.new

Since as of November 2022, Colours.new can be used to build up a String that should be colourized.

This will internally delegate towards:

::Colours::Colours.new(i)

This may need some modifications in the future; the code is also a bit confusing right now.

Licence

The colours project used to be under the GPL-2.0 licence (no later clause), until August 2019 (26.08.2019, in dd.mm.yyyy notation).

However had, I have changed my mind for various reasons (including the situation that different projects, with different licenses, may make use of the colours gem) and thus re-published the colours project under the less stringent MIT licence. Both licences, GPL and MIT, are perfectly fine licences, but I feel that for the basic building blocks, such as the colours gem, a less stringent licence makes a lot more sense.

See the file LICENCE.md for this licence, or just have look at the following URL here:

https://opensource.org/licenses/MIT

Replace the effective year simply with whatever was the last release on the rubygems.org homepage of this gem here - right now this is 2022, but I may not always update this to the current year. Look at the version published on the rubygems homepage of this gem to see the effective last year as the update - if a new release happened in 2023, then logically this here should refer to 2023 as well.

The most important requirement for the MIT licence is the no-warranty clause. The rest is, IMO, not so relevant (I don't even care about author citation either, but mentioning a no-warranty clause makes sense, in my opinion, simply as required legalese to avoid claims made that the software licence did not warn about anyone wanting to rely on something IF the no-warranty clause would not be mentioned).

https://ss64.com/nt/syntax-ansi.html

https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html

^^^ This webpage one shows how to build a progress-indicator in python. The equivalent ruby code is very similar.

Commandline executables for individual colours

In March 2023 I decided to add files such as bin/orange.

The idea here is that you can chain this via a pipe, such as:

cat foobar.md | grep orange

Or simply:

orange Hello world!
orange foobar.md # This variant should read the file, and read its content.

The idea here is to add this for each HTML colour. However had, I am not yet certain whether this should be done, as it would lead to many more files added to the colours gem. So for now, I may add single individual files but probably not all HTML colours, as executables. Perhaps in the future all HTML colours will have a corresponding bin/ executable file or I may add the option to autogenerate these files - we'll see.

KDE Konsole support

The Colours gem used to have a submodule called Konsole, in particular the KDE Konsole. In May 2019 this submodule was removed; the functionality is now available in the form of an autogenerated .rb file instead.

You can use RGB colours in the KDE konsole (but also in other terminal-types such as vte-based ones, like mate-terminal). gnome-terminal also supports true 24 bit colours, which means that 16 millions colours are supported.

For an example, have a look at the file bin/colours that is distributed with this gem here (the colours gem). That file will output all the HTML colour variants (via their RGB values). Best shown on a black background in your terminal though.

To view all RGB colours based on their HTML names, such as palegreen or slateblue, do this:

colours

Also note that since as of May 2018, you can invoke the HTML colours on the Konsole namespace directly, including text-output, via code like this:

Colours.edarkgreen 'yo there'
Colours.eslateblue 'yo there'
Colours.eroyalblue 'yo there'
Colours.edarkgreen 'Hello world!'

The leading 'e' of these methods stands for "echo", aka puts-related output (display onto the commandline). In other words, to print the text that comes afterwards.

To print something in bold, you can use Colours.bold() like in this way:

Colours.bold

How to use this in raw KDE konsole, if ruby is not available?

You need to make use of the corresponding R, G and B values.

Example for this:

printf "\e[38;2;100;200;200mTesting this output\e[0m\n"

class Colours::ReplaceTokensWithColourCode

class Colours::ReplaceTokensWithColourCode can be used to replace HTML-like tokens, such as , in a given String.

The use case for this is to be able to easily colourize words on the commandline, as well as sentences, in different colours. The studium-gem makes use of this, for instance, where exam-questions are colourized based on the more important parts of the question at hand.

Colours::HtmlColoursMethods

class Colours::HtmlColoursMethods will hold code for making use of HTML-colours as method names, such as:

Colours.royalblue()
Colours.royalblue('Hello World!')

To require this file do:

require 'colours/autogenerated/html_colours_methods.rb'

Note that depending on how you require the colours gem, this may also be automatically pulled in if you do:

include Colours

And then use methods such as Colours.sfancy().

Contact information and mandatory 2FA (no longer) coming up in 2022 / 2023

If your creative mind has ideas and specific suggestions to make this gem more useful in general, feel free to drop me an email at any time, via:

shevy@inbox.lt

Before that email I used an email account at Google gmail, but in 2021 I decided to slowly abandon gmail, for various reasons. In order to limit the explanation here, allow me to just briefly state that I do not feel as if I want to promote any Google service anymore when the user becomes the end product (such as via data collection by upstream services, including other proxy-services). My feeling is that this is a hugely flawed business model to begin with, and I no longer wish to support this in any way, even if only indirectly so, such as by using services of companies that try to promote this flawed model.

In regards to responding to emails: please keep in mind that responding may take some time, depending on the amount of work I may have at that moment. So it is not that emails are ignored; it is more that I have not (yet) found the time to read and reply. This means there may be a delay of days, weeks and in some instances also months. There is, unfortunately, not much I can do when I need to prioritise my time investment, but I try to consider all feedback as an opportunity to improve my projects nonetheless.

In 2022 rubygems.org decided to make 2FA mandatory for every gem owner eventually:

see https://blog.rubygems.org/2022/06/13/making-packages-more-secure.html

Mandatory 2FA will eventually be extended to all rubygems.org developers and maintainers. As I can not use 2FA, for reasons I will skip explaining here, this means that my projects will eventually be removed, as I no longer have any control over my projects hosted on rubygems.org (because I can not use 2FA).

At that point, I no longer have any control what is done to my projects since whoever is controlling the gems ecosystem took away our control here. I am not sure at which point ruby became corporate-controlled - that was not the case several years ago, so something has changed.

Ruby also only allows 2FA users to participate on the issue tracker these days:

https://bugs.ruby-lang.org/issues/18800

But this has been reverted some months ago, so it is no longer applicable. Suffice to say that I do not think that we should only be allowed to interact on the world wide web when some 'authority' authenticated us, such as via mandatory 2FA, so I hope this won't come back again.

Fighting spam is a noble goal, but when it also means you lock out real human people then this is definitely NOT a good situation to be had.