• Stars
    star
    370
  • Rank 115,405 (Top 3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 13 years ago
  • Updated 10 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 ANSI terminal colors 🎨︎ VERY FAST

Ruby Paint

Paint creates terminal colors and effects for you. It combines the strengths of term-ansicolor, rainbow, and similar projects into a simple to use, however still flexible terminal colors gem with no core extensions by default.

Supported Rubies: 3.3, 3.2, 3.1, 3.0

Unsupported, but might still work: 2.7, 2.6, 2.5, 2.4, 2.3, 2.2, 2.1, 2.0, 1.9

Features

  • No string extensions (suitable for library development)
  • Simple API
  • Faster than other terminal color gems (as of January 2024)
  • Supports true color or 256 colors (for capable terminals)
  • Allows you to set any terminal effects
  • Paint.mode: Fall-back modes for terminals with less colors, supported modes:
    • 0xFFFFFF (= 16777215) colors (true color)
    • 256 colors (palette)
    • 16 colors (only ANSI colors, combined with bright effect)
    • 8 colors (only ANSI colors)
    • 0 colors (no colors / deactivate)

Paint 2.0 | True Color Support

Starting with Paint 2.0, true color mode is the new default mode, since most major terminals now support 24bit colors. If it happens to not work in your setup:

  • Manually set Paint.mode = 256 at the beginning of your code
  • Please open a new issue so we can figure out how to blacklist the terminal used

Setup

Add to Gemfile:

gem 'paint'

and run bundle install.

In Ruby do:

require 'paint'

Usage

The only method you need is: Paint.[]

The first argument given to Paint.[] is the string to colorize (if the object is not a string, to_s will be called on it). The other arguments describe how to modify/colorize the string. Let's learn by example:

Paint['Ruby', :red]           # Sets ANSI color red
Paint['Ruby', :red, :bright]  # Also applies bright/bold effect
Paint['Ruby', :bright, :red]  # Does the same as above
Paint['Ruby', :red, :bright, :underline] # Effects can often be combined
Paint['Ruby', :red, :blue]    # The second color you define is for background
Paint['Ruby', nil, :blue]     # Pass a nil before a color to ignore foreground and only set background color
Paint['Ruby', [100, 255, 5]]  # You can define RGB colors. Depending on your terminal, this will create
                              # a "true color" or map to 256/16/8 colors.
Paint['Ruby', "gold", "snow"] # Paint supports rgb.txt color names, note that the arguments are strings
                              # (:yellow != "yellow")!
Paint['Ruby', "#123456"]      # HTML like definitions are possible
Paint['Ruby', "fff"]          # Another HTML hex definition
Paint['Ruby', :inverse]       # Swaps fore- and background
Paint['Ruby', :italic, :encircle, :rapid_blink, :overline] # Probably not supported effects
Paint['Ruby']                 # Don't pass any argument and the string will not be changed

When you pass multiple colors, the first one is taken as foreground color and the second one defines the background color, every following color will be ignored. To only change the background color, you have to pass a nil first. Effects can be passed in any order.

You can find more examples in the specs.

List of rgb.txt colors.

Windows Support

For ANSI support in Windows OS, you can use ansicon or ConEmu or WSL.

Paint.mode

You can choose between five ways to use Paint.[] by setting Paint.mode to one of the following:

  • 0xFFFFFF: Use 16777215 true colors
  • 256: Use the 256 colors palette
  • 16: Use the eight ANSI colors (combined with bright effect)
  • 8: Use the eight ANSI colors
  • 0: Don't colorize at all

Paint tries to automatically detect the proper value your terminal is capable of, please open an issue if Paint.detect_mode yields a wrong value for you.

Paint.detect_mode will return 0 if the NO_COLOR environment variable is set.

More Details About Terminal Colors and Effects

Terminal colors/effects get created by ANSI escape sequences. These are strings that look like this: \e[X;X;X;X;X]m where X are integers with some meaning. For example, 0 means reset, 31 means red foreground and 41 stands for red background. When you tell Paint to use one of the eight ANSI base colors as foreground color, it just inserts a number between 30 and 37 into the sequence. The following colors are available:

  • :black
  • :red
  • :green
  • :yellow
  • :blue
  • :magenta
  • :cyan
  • :white, :gray
  • (:default)

When combined with the :bright (= :bold) effect, the color in the terminal emulator often differs a little bit, thus it is possible to represent 16 colors.

Through special sequences it's also possible to set 256-colors, or even 16777215 colors, instead of only the 8 ANSI ones. However, this is not supported by all terminals. Paint automatically translates given RGB colors to a suitable color of the supported color spectrum.

When using the Paint.[] method, Paint wraps the given string between the calculated escape sequence and an reset sequence ("\e[0m"). You can get the raw escape sequence by using the Paint.color method.

Effects

See en.wikipedia.org/wiki/ANSI_escape_code for a more detailed discussion:

Often supported

0) :reset, :nothing
1) :bright, :bold
4) :underline
7) :inverse, :negative
8) :conceal, :hide
22) :clean
24) :underline_off
26) :inverse_off, :positive
27) :conceal_off, :show, :reveal

Not widely supported

2) :faint
3) :italic
5) :blink, :slow_blink
6) :rapid_blink
9) :crossed, :crossed_out
10) :default_font, :font0
11-19) :font1, :font2, :font3, :font4, :font5, :font6, :font7, :font8, :font9
20) :fraktur
21) :bright_off, :bold_off, :double_underline
23) :italic_off, :fraktur_off
25) :blink_off
29) :crossed_off, :crossed_out_off
51) :frame
52) :encircle
53) :overline
54) :frame_off, :encircle_off
55) :overline_off

Substitution & Nesting

From time to time, you might find yourself in a situation where you want to colorize a substring differently from the rest of the string. Paint supports this via a simple templating approach using the % method with an array argument. Use the %{var} notation within a string, and pass the template variables as a hash:

Paint%['Yellow string with a %{blue_text} in it', :yellow,
  blue_text: ["blue text", :blue]
]
# => "\e[33mYellow string with a \e[34mblue text\e[0m\e[33m in it\e[0m"

Please note that the resulting ASCII escape sequence can be quite verbose since it restores the parent context after the substitution.

Utilities

The Paint.random method generates a random ANSI color you can pass into Paint.[]:

Paint['Ruby', Paint.random]        # Get one of eight random ANSI foreground colors
Paint['Ruby', Paint.random(true)]  # Get one of eight random ANSI background colors

Another helper method is Paint.unpaint, which removes any ANSI colors:

Paint.unpaint( Paint['Ruby', :red, :bright] ).should == 'Ruby'

You can get a p like alternative for calling puts Paint.[]:

require 'paint/pa'
pa "Ruby", :red, :underline  # same as puts Paint["Ruby", :red, :underline]

Advanced Usage: Shortcuts

There is an extension gem available which allows you to define custom color definitions, which you can reuse later. See SHORTCUTS.md for documentation. This is completely optional.

J-_-L

Copyright (c) 2011-2024 Jan Lelis https://janlelis.com, released under the MIT license.

Thank you to rainbow and term-ansicolor for ideas and inspiration. Also, a lot of thanks to all the contributors!

More Repositories

1

irbtools

Improvements for Ruby's IRB console 💎︎
Ruby
919
star
2

clipboard

Ruby access to the clipboard on Windows, Linux, macOS, Java, WSL and more platforms 📋︎
Ruby
372
star
3

whirly

Colorful Terminal Spinner for Ruby 😀︎
Ruby
324
star
4

idiosyncratic-ruby.com

Documenting All Ruby Specialities 💎︎
JavaScript
312
star
5

uniscribe

Know your Unicode ✀
Ruby
280
star
6

pws

Command-Line Password Safe 🔐︎
Ruby
209
star
7

unicode-emoji

Up-to-date Emoji Regex in Ruby 💥
Ruby
146
star
8

unibits

Visualize different Unicode encodings in the terminal
Ruby
127
star
9

unicode-display_width

Monospace Unicode character width in Ruby
Ruby
118
star
10

sugar_refinery

Tiny refinements for Ruby
Ruby
110
star
11

stdgems

Ruby's default & bundled gems: The new standard library
Ruby
109
star
12

productive-sublime-snippets-ruby

Ruby Snippets for Sublime Text
Ruby
107
star
13

relaxed.ruby.style

A Relaxed Style Guide for Ruby & Configuration for RuboCop
Ruby
72
star
14

unicode-confusable

Unicode::Confusable.confusable? "ℜսᖯʏ", "Ruby"
Ruby
71
star
15

wirb

Ruby Object Inspection for IRB
Ruby
70
star
16

fresh

Fresh Ruby Enhanced SHell
Ruby
70
star
17

sig

Validate Method Arguments & Results in Ruby
Ruby
58
star
18

fancy_irb

Colors & Hash Rockets in IRB
Ruby
47
star
19

rg

A way to integrate AngularJS into a Rails project using CoffeeScript and Bower.
Ruby
46
star
20

debugging

Improve your Print Debugging
Ruby
42
star
21

unicode-x

Unicode Micro Libraries for Ruby
Ruby
38
star
22

characteristics

Character info under different encodings
Ruby
27
star
23

object_shadow

The Shadow of a Ruby Object lets you See and Manipulate its Instance Variables and Methods
Ruby
27
star
24

value_struct

Read-only structs in Ruby
Ruby
25
star
25

redux.rb

A tiny Ruby redux
Ruby
25
star
26

code

Displays a Ruby method's source code
Ruby
24
star
27

has_many_booleans

This Rails plugin/gem allows you to generate virtual boolean attributes, which get saved in the database as a single bitset integer.
Ruby
23
star
28

microevent.rb

Events for Ruby objects (a.k.a objects with Publish-Subscribe capabilities a.k.a. Observer pattern)
Ruby
23
star
29

ruby.style

Collects Ruby Style Guides
CSS
22
star
30

unicopy

Unicode command-line codepoint dumper
Ruby
20
star
31

unicode-blocks

Unicode Blocks of a Ruby String
Ruby
18
star
32

irbtools-more

irbtools-more adds gems to IRB that may not build out-of-the-box
18
star
33

character.construction

Notable characters, codepoints, and resources
Ruby
16
star
34

ruby_version

RubyVersion | Better than RUBY_VERSION
Ruby
15
star
35

better-array

Unobtrusive JavaScript Array Extras
JavaScript
15
star
36

render_react

Pre-render and mount React components from Ruby
Ruby
15
star
37

yyid.ex

Almost a random UUID in Elixir
Elixir
14
star
38

rubybuntu-gedit

Ruby/Rails/Web related gedit language definitions, mime types, styles and snippets.
Ruby
14
star
39

slim_migrations

Let's you write slightly slimmer Rails migrations.
Ruby
14
star
40

unicode-name

Unicode character names in Ruby
Ruby
13
star
41

uke

𝄝 Ukulele CLI Support
Ruby
13
star
42

gedit-external-tools

A repository for useful and handy snippets for gedit's external tools plugin
Shell
13
star
43

boolean2

Boolean2 is a Ruby constant that is an ancestor of true and false.
Ruby
11
star
44

derb

Dockerfile.erb
Ruby
11
star
45

unicode-scripts

Unicode Scripts / Script Extensions of a Ruby String
Ruby
11
star
46

az

From A to Z
Ruby
10
star
47

symbolify

␀ ␁ ␂ ␃ ␄ ␅ ␆ ␇ ␈ ␉ ␊ ␋ ␌ ␍ ␎ ␏ ␐ ␑ ␒ ␓ ␔ ␕ ␖ ␗ ␘ ␙ ␚ ␛ ␜ ␝ ␞ ␟ ␠ ␡
Ruby
9
star
48

micrologger

A minimal logger based on MicroEvent.rb
Ruby
9
star
49

watchbuffy

Which Buffy episode to put on next?
Ruby
8
star
50

ruby_info

RubyInfo | Better than SCRIPT_LINES__
Ruby
8
star
51

productive-sublime-snippets-erb

Productive Sublime Snippets for ERB
Ruby
8
star
52

unicoder

(wip)
Ruby
7
star
53

clipboard_formatter

A clipboard formatter for RSpec
Ruby
7
star
54

unicode-categories

Unicode General Categories of a Ruby String
Ruby
7
star
55

microgem

more gems
Ruby
6
star
56

rubynetz

Example Usage of Harvester
6
star
57

unicode-sequence_name

Unicode sequence names in Ruby
Ruby
6
star
58

unicode-types

Basic Unicode Types of a Ruby String
Ruby
6
star
59

Deutsch.rb

Like English.rb
Ruby
6
star
60

rubybuntu-language-specs

gtksourceview language specifications for Ruby/Web devoloper's gedit
Ruby
6
star
61

unicode-numeric_value

Convert a Unicode character into its numeric value
Ruby
6
star
62

ripl-multi_line

This ripl plugin allows you to evaluate multiple lines of code.
Ruby
6
star
63

ruby_engine

RubyEngine | Better than RUBY_ENGINE
Ruby
6
star
64

rubybuntu-mime

gnome mime types for Ruby/Web developer's gedit
5
star
65

promiseUserMedia.js

Promisified access to getUserMedia & vendor prefixes.
JavaScript
5
star
66

added

Module#added
Ruby
5
star
67

ripltools

This meta gem installs a bunch of ripl plugins for a nice-to-use general purpose ripl.
Ruby
5
star
68

every_day_irb

Ruby
4
star
69

procstar

Provides to_proc implementations for other Ruby classes than just Symbol
Ruby
4
star
70

rusty_clipboard

Ruby 🡪 Rust 🡪 System Clipboard
Ruby
4
star
71

unicode-age

Determine Unicode version required to display a string
Ruby
4
star
72

yyid.rb

Almost a random UUID in Ruby
Ruby
4
star
73

multi_block

Pass multiple blocks to a Ruby method
Ruby
4
star
74

ripl-color_result

This ripl plugin colorizes your results.
Ruby
4
star
75

nem

npm + gem = nem
Ruby
4
star
76

rubybuntu-editor-styles

gtksourceview styles for Ruby/Web devoloper's gedit
4
star
77

named_proc

Named procs and lambdas
Ruby
3
star
78

local_port

Returns the next free local port number to use for your shiny new service
Ruby
3
star
79

nomore

Blocks your computer from accessing domains on the internet
Ruby
3
star
80

cd

Enhanced cd command for the Ruby console.
Ruby
3
star
81

ripl-auto_indent

This ripl plugin indents your multi-line Ruby input.
Ruby
3
star
82

unicode-version

Which level of Unicode and Emoji support is included with Ruby?
Ruby
3
star
83

egonil

Egocentric Nil
Ruby
2
star
84

talk-ruby-unconf-surprises

Ruby is Full of Surprises (Ruby Unconf 2018)
JavaScript
2
star
85

iterate

Kernel#iterate
Ruby
2
star
86

ripl-rocket

Lets you display the ripl result as a comment on the same line.
Ruby
2
star
87

website

Ruby
2
star
88

instance_variables_from

Turn bindings, hashes or arrays into instance variables
Ruby
2
star
89

yyid.js

yyid() generates a random uuid* in the browser, uses the crypto api when available
JavaScript
2
star
90

pws-otp

Experimental OTP support for PWS
Ruby
2
star
91

null_plus

+nil
Ruby
2
star
92

ripl-color_streams

This ripl plugin colorizes your stdout and stderr streams.
Ruby
2
star
93

wcswidth-ruby

FFI bindings to libc's wcswidth() to determine the actual display width of strings
Ruby
2
star
94

unicode-category.js

Get the General Category of a Unicode character
JavaScript
1
star
95

yyid.go

Almost a random UUID in Go
Go
1
star
96

yyid-node.js

Almost a random UUID in node.js
JavaScript
1
star
97

communication-map

WebRTC based Location Sharing
CSS
1
star
98

null_question

Adds the null? predicate to Ruby's nil
Ruby
1
star
99

ripl-profiles

This ripl plugin adds a --profile option to ripl that loads profile files in ~/.ripl/profiles before starting ripl
Ruby
1
star
100

exists

Turns null objects into nil
Ruby
1
star