• Stars
    star
    792
  • Rank 55,227 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 15 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ruby gem for colorizing printed text on ANSI terminals

Rainbow

Gem Version CI Code Climate Coverage Status

Rainbow is a ruby gem for colorizing printed text on ANSI terminals.

It provides a string presenter object, which adds several methods to your strings for wrapping them in ANSI escape codes. These codes when printed in a terminal change text attributes like text color, background color, intensity etc.

Usage

To make your string colored wrap it with Rainbow() presenter and call .color(<color name>) on it.

Example

require 'rainbow'

puts Rainbow("this is red").red + " and " + Rainbow("this on yellow bg").bg(:yellow) + " and " + Rainbow("even bright underlined!").underline.bright

# => "\e[31mthis is red\e[0m and \e[43mthis on yellow bg\e[0m and \e[4m\e[1meven bright underlined!\e[0m"

Screenshot of the previous code in a terminal

Or, watch this video example

Rainbow presenter API

Rainbow presenter adds the following methods to presented string:

  • color(c) (with foreground, and fg aliases)
  • background(c) (with bg alias)
  • bright
  • underline
  • blink
  • inverse
  • hide
  • faint (not well supported by terminal emulators)
  • italic (not well supported by terminal emulators)
  • cross_out, strike

Text color can also be changed by calling a method named by a color:

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • aqua
  • silver
  • aliceblue
  • indianred

All of the methods return self (the presenter object) so you can chain method calls:

Rainbow("hola!").blue.bright.underline

Refinement

If you want to use the Refinements version, you can:

require 'rainbow/refinement'
using Rainbow
puts "Hi!".green

Here's an IRB session example:

>> 'Hello, World!'.blue.bright.underline
NoMethodError: undefined method `blue' for "Hello, World!":String
    (ripl):1:in `<main>'
>> using Rainbow
=> main
>> 'Hello, World!'.blue.bright.underline
=> "\e[34m\e[1m\e[4mHello, World!\e[0m"

Color specification

Both color and background accept color specified in any of the following ways:

  • ANSI color number (where 0 is black, 1 is red, 2 is green and so on): Rainbow("hello").color(1)

  • ANSI color name or X11 color name as a symbol: Rainbow("hello").color(:yellow). This can be simplified to Rainbow("hello").yellow

    See Color list for all available color names.
    Note that ANSI colors can be changed in accordance with terminal setting.
    But X11 color is just a syntax sugar for RGB triplet. So you always see what you specified.

  • RGB triplet as separate values in the range 0-255: Rainbow("hello").color(115, 23, 98)

  • RGB triplet as a hex string: Rainbow("hello").color("FFC482") or Rainbow("hello").color("#FFC482")

When you specify a color with a RGB triplet rainbow finds the nearest match from 256 colors palette. Note that it requires a 256-colors capable terminal to display correctly.

Example: Choose a random color

You can pick a random color with Rainbow, it's a one-liner:

colors = Range.new(0,7).to_a
"whoop dee doop".chars.map { |char| Rainbow(char).color(colors.sample) }.join
# => "\e[36mw\e[0m\e[37mh\e[0m\e[34mo\e[0m\e[34mo\e[0m\e[37mp\e[0m\e[34m \e[0m\e[36md\e[0m\e[33me\e[0m\e[34me\e[0m\e[37m \e[0m\e[32md\e[0m\e[35mo\e[0m\e[33mo\e[0m\e[36mp\e[0m"

colors = [:aliceblue, :antiquewhite, :aqua, :aquamarine, :azure, :beige, :bisque, :blanchedalmond, :blueviolet]
"whoop dee doop".chars.map { |char| Rainbow(char).color(colors.sample) }.join
# => "\e[38;5;135mw\e[0m\e[38;5;230mh\e[0m\e[38;5;231mo\e[0m\e[38;5;135mo\e[0m\e[38;5;231mp\e[0m\e[38;5;231m \e[0m\e[38;5;122md\e[0m\e[38;5;231me\e[0m\e[38;5;231me\e[0m\e[38;5;230m \e[0m\e[38;5;122md\e[0m\e[38;5;51mo\e[0m\e[38;5;51mo\e[0m\e[38;5;51mp\e[0m"

Configuration

Rainbow can be enabled/disabled globally by setting:

Rainbow.enabled = true/false

When disabled all the methods return an unmodified string (Rainbow("hello").red == "hello").

It's enabled by default, unless STDOUT/STDERR is not a TTY or a terminal is dumb.

Advanced usage

Rainbow() and Rainbow.enabled operate on the global Rainbow wrapper instance. If you would like to selectively enable/disable coloring in separate parts of your application you can get a new Rainbow wrapper instance for each of them and control the state of coloring during the runtime.

rainbow_one = Rainbow.new
rainbow_two = Rainbow.new

rainbow_one.enabled = false

Rainbow("hello").red          # => "\e[31mhello\e[0m" ("hello" if not on TTY)
rainbow_one.wrap("hello").red # => "hello"
rainbow_two.wrap("hello").red # => "\e[31mhello\e[0m" ("hello" if not on TTY)

By default each new instance inherits enabled/disabled state from the global Rainbow.enabled.

This feature comes handy for example when you have multiple output formatters in your application and some of them print to a terminal but others write to a file. Normally rainbow would detect that STDIN/STDERR is a TTY and would colorize all the strings, even the ones that go through file writing formatters. You can easily solve that by disabling coloring for the Rainbow instances that are used by formatters with file output.

Installation

Add it to your Gemfile:

gem 'rainbow'

Or just install it via rubygems:

gem install rainbow

Color list

ANSI colors

black, red, green, yellow, blue, magenta, cyan, white

X11 colors

aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, blanchedalmond, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflower, cornsilk, crimson, darkblue, darkcyan, darkgoldenrod, darkgray, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrod, lightgray, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightsteelblue, lightyellow, lime, limegreen, linen, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navyblue, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, rebeccapurple, rosybrown, royalblue, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, webgray, webgreen, webmaroon, webpurple, wheat, whitesmoke, yellowgreen

Authors

More Repositories

1

vim-monokai

Monokai color scheme for Vim converted from Textmate theme
Vim Script
1,420
star
2

bitpocket

"DIY Dropbox" or "2-way directory (r)sync with proper deletion"
Shell
1,023
star
3

stderred

stderr in red
C
973
star
4

git-dude

Git commit notifier
Shell
949
star
5

racksh

Console for Rack based ruby web apps
Ruby
423
star
6

vim-pasta

Pasting in Vim with indentation adjusted to destination context
Vim Script
321
star
7

coloration

Textmate to Vim, JEdit and Kate/KWrite color scheme converter
Ruby
257
star
8

css2less

Css to LessCss converter
Ruby
62
star
9

off-plugin

Plugin for Netbeans and JEdit for quick finding and opening files by typing just few characters
Java
44
star
10

vim-sunburst

Sunburst color scheme for Vim converted with coloration.ku1ik.com from Textmate theme with the same name.
Vim Script
27
star
11

dotfiles

My virtual home
Vim Script
27
star
12

rack-revision-info

Rack middleware showing current git (or svn) revision number of deployed application
Ruby
20
star
13

rack-lesscss

Rack middleware for serving LessCSS files compiled to CSS
Ruby
14
star
14

tm2jed

Texmate-To-JEdit colour theme converter - NOTE: DEVELOPMENT MOVED TO sickill/coloration repo
Ruby
9
star
15

kanbanery-ruby-client

Ruby client library and CLI for Kanbanery.com
Ruby
8
star
16

ps

Unix "ps" on the web.
Ruby
7
star
17

traytor

Show (animated) tray icon from command line
Python
7
star
18

example-rack-framework

Example ruby web framework built with Rack
Ruby
6
star
19

skype-kde-notifications

Displaying Skype incoming messages with KDE4 visual notifications
Python
6
star
20

homepage

Personal homepage / blog
CSS
5
star
21

coloration-web

Web frontend for Coloration
CSS
5
star
22

merb-resque-mailer

Merb plugin for putting mail delivery jobs onto Resque queue
Ruby
4
star
23

krug-merb-presentation

Ruby
4
star
24

rubytime-plasmoid

Rubytime plasmoid with support for adding activities and notifications
C
4
star
25

vim-git-inline-diff

Git inline diff for Vim using Vim's signs feature
Vim Script
4
star
26

vimbanery

Vim-like keybindings for Kanbanery
JavaScript
4
star
27

canvator

HTML5 Canvas element demo
C++
4
star
28

gratifier

Desktop notifications with Gravatars!
Shell
3
star
29

archlinux-nginx-passenger

Nginx webserver with Passenger module for Archlinux
Shell
3
star
30

blogator

My old homepage/blog created with Sinatra + Datamapper
JavaScript
3
star
31

krug-chef-presentation

JavaScript
3
star
32

sickounter

Simple Sinatra powered downloads counter
Ruby
3
star
33

euruko2010-building-frameworks-with-rack

My Euruko 2010 conference presentation about building ruby web frameworks using Rack and available middleware
JavaScript
3
star
34

yeb

Ruby
3
star
35

kodr

Programmer's editor for KDE4 written in Ruby
Shell
3
star
36

expo

Beautiful html photo album generator
Ruby
2
star
37

minion

Dead simple ruby background jobs without workers
Ruby
2
star
38

clj-bwt

Clojure implementation of Burrows-Wheeler transform (block-sorting compression)
Clojure
2
star
39

ts-hermit

JavaScript
2
star
40

openfilefast-headless

Tool to find a file in a project (dir) using fuzzy matching (this is backend only, to be used with gui frontend)
Ruby
2
star
41

ecto-preload-bug

Example project for demonstrating Ecto preload bug
Elixir
2
star
42

tsm

Ruby
2
star
43

tmux

C
2
star
44

mail_friday

Ruby
2
star
45

urack

rack + usher + warden + tilt + rack-flash + ...
Ruby
2
star
46

flash

Keep the secrets out of emails and chat history!
Elixir
2
star
47

luna

Fresh Rails app for "Setting up fresh Ubuntu server for Rails" LLP workshop
Ruby
2
star
48

omnomnom

sinatra+heroku test app
Ruby
2
star
49

finish-him

Word autocomplete (expansion) plugin for JEdit editor written in Scala
Scala
2
star
50

gts-move-on

Clojure
1
star
51

phoenix-1.3-to-dev

Elixir
1
star
52

bitflip-gen

Rust
1
star
53

bb-lb-400

1
star
54

brunch-issue

CSS
1
star
55

tarpit

Tarpit for ssh/smtp/http
Rust
1
star
56

collatz-conjecture-rs

Collatz conjecture solver
Rust
1
star
57

nemesis

1
star
58

chrome-browserid

JavaScript
1
star
59

gh-356

JavaScript
1
star