Giter Club home page Giter Club logo

pastel's Introduction

pastel logo

Pastel

Gem Version Actions CI Build status Code Climate Coverage Status

Terminal output styling with intuitive and clean API that doesn't monkey patch String class.

Pastel is minimal and focused to work in all terminal emulators.

screenshot

Pastel provides independent coloring component for TTY toolkit.

Features

  • Doesn't monkey patch String
  • Intuitive and expressive API
  • Minimal and focused to work on all terminal emulators
  • Auto-detection of color support
  • Allows nested styles
  • Performant

Installation

Add this line to your application's Gemfile:

gem "pastel"

And then execute:

$ bundle

Or install it yourself as:

$ gem install pastel

Contents

1 Usage

Pastel provides a simple, minimal and intuitive API for styling your strings:

pastel = Pastel.new

puts pastel.red("Unicorns!")

Pastel doesn't print the colored string out, just returns it, you'll have to print it yourself.

You can compose multiple styles through chainable API:

pastel.red.on_green.bold("Unicorns!")

It allows you to combine styled strings with unstyled ones:

pastel.red("Unicorns") + " will rule " + pastel.green("the World!")

It supports variable number of arguments:

pastel.red("Unicorns", "are", "running", "everywhere!")

You can also nest styles as follows:

pastel.red("Unicorns ", pastel.on_green("everywhere!"))

Nesting is smart enough to know where one color ends and another one starts:

pastel.red("Unicorns " + pastel.green("everywhere") + pastel.on_yellow("!"))

You can also nest styles inside blocks:

pastel.red.on_green("Unicorns") {
  green.on_red("will ", "dominate") {
    yellow("the world!")
  }
}

When dealing with multiline strings you can set eachline option(more info see eachline):

pastel = Pastel.new(eachline: "\n")

You can also predefine needed styles and reuse them:

error    = pastel.red.bold.detach
warning  = pastel.yellow.detach

puts error.("Error!")
puts warning.("Warning")

If your output is redirected to a file, you probably don't want Pastel to add color to your text. See https://github.com/piotrmurach/pastel#210-enabled for a way to easily accomplish this.

Pastel has companion library called pastel-cli that allows you to style text in terminal via pastel executable:

$ pastel green "Unicorns & rainbows!"

2 Interface

2.1 Color

pastel.<color>[.<color>...](string, [string...])

Color styles are invoked as method calls with a string argument. A given color can take any number of strings as arguments. Then it returns a colored string which isn't printed out to terminal. You need to print it yourself if you need to. This is done so that you can save it as a string, pass to something else, send it to a file handle and so on.

pastel.red("Unicorns ", pastel.bold.underline("everywhere"), "!")

Please refer to 3. Supported Colors section for full list of supported styles.

2.2 Decorate

This method is a lower level string styling call that takes as the first argument the string to style followed by any number of color attributes, and returns string wrapped in styles.

pastel.decorate("Unicorn", :green, :on_blue, :bold)

This method will be useful in situations where colors are provided as a list of parameters that have been generated dynamically.

2.3 Undecorate

It performs the opposite to decorate method by turning color escape sequences found in the string into a list of hash objects corresponding with the attribute names set by those sequences. Depending on the parsed string, each hash object may contain :foreground, :background, :text and/or :style keys.

pastel.undecorate("\e[32mfoo\e[0m \e[31mbar\e[0m")
# => [{foreground: :green, text: "foo"}, {text: " "}, {foreground: :red, text: "bar"}]

To translate the color name into sequence use lookup

2.4 Detach

The detach method allows to keep all the associated colors with the detached instance for later reference. This method is useful when detached colors are being reused frequently and thus shorthand version is preferred. The detached object can be invoked using call method or it's shorthand .(), as well as array like access []. For example, the following are equivalent examples of detaching colors:

notice = pastel.blue.bold.detach

notice.call("Unicorns running")
notice.("Unicorns running")
notice["Unicorns running"]

2.5 Strip

Strip only color sequence characters from the provided strings and preserve any movement codes or other escape sequences. The return value will be either array of modified strings or a single string. The arguments are not modified.

pastel.strip("\e[1A\e[1m\e[34mbold blue text\e[0m")  # => "\e[1Abold blue text"

2.6 Styles

To get a full list of supported styles with the corresponding color codes do:

pastel.styles

2.7 Lookup

To perform translation of color name into ansi escape code use lookup:

pastel.lookup(:red)   # => "\e[31m"
pastel.lookup(:reset) # => "\e[0m"

2.8 Valid?

Determine whether a color or a list of colors are valid. valid? takes one or more attribute strings or symbols and returns true if all attributes are known and false otherwise.

pastel.valid?(:red, :blue) # => true
pastel.valid?(:unicorn)    # => false

2.9 Colored?

In order to determine if string has color escape codes use colored? like so

pastel.colored?("\e[31mcolorful\e[0m")  # => true

2.10 Enabled?

In order to detect if your terminal supports coloring do:

pastel.enabled?   # => false

In cases when the color support is not provided no styling will be applied to the colored string. Moreover, you can force Pastel to always print out string with coloring switched on:

pastel = Pastel.new(enabled: true)
pastel.enabled?   # => true

If you are outputting to stdout or stderr, and want to suppress color if output is redirected to a file, you can set the enabled attribute dynamically, as in:

stdout_pastel = Pastel.new(enabled: $stdout.tty?)
stderr_pastel = Pastel.new(enabled: $stderr.tty?)

2.11 Eachline

Normally Pastel colors string by putting color codes at the beginning and end of the string, but if you provide eachline option set to some string, that string will be considered the line delimiter. Consequently, each line will be separately colored with escape sequence and reset code at the end. This option is desirable if the output string contains newlines and you're using background colors. Since color code that spans more than one line is often interpreted by terminal as providing background for all the lines that follow. This in turn may cause programs such as pagers to spill the colors throughout the text. In most cases you will want to set eachline to \n character like so:

pastel = Pastel.new(eachline: "\n")
pastel.red("foo\nbar")  # => "\e[31mfoo\e[0m\n\e[31mbar\e[0m"

2.12 Alias Color

In order to setup an alias for standard colors do:

pastel.alias_color(:funky, :red, :bold)

From that point forward, :funky alias can be passed to decorate, valid? with the same meaning as standard colors:

pastel.funky.on_green("unicorn")   # => will use :red, :bold color

This method allows you to give more meaningful names to existing colors.

You can also use the PASTEL_COLORS_ALIASES environment variable (see Environment) to specify aliases.

Note: Aliases are global and affect all callers in the same process.

3 Supported Colors

Pastel works with terminal emulators that support minimum sixteen colors. It provides 16 basic colors and 8 styles with further 16 bright color pairs. The corresponding bright color is obtained by prepending the bright to the normal color name. For example, color red will have bright_red as its pair.

The variant with on_ prefix will style the text background color.

The foreground colors:

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • bright_black
  • bright_red
  • bright_green
  • bright_yellow
  • bright_blue
  • bright_magenta
  • bright_cyan
  • bright_white

The background colors:

  • on_black
  • on_red
  • on_green
  • on_yellow
  • on_blue
  • on_magenta
  • on_cyan
  • on_white
  • on_bright_black
  • on_bright_red
  • on_bright_green
  • on_bright_yellow
  • on_bright_blue
  • on_bright_magenta
  • on_bright_cyan
  • on_bright_white

Generic styles:

  • clear
  • bold
  • dim
  • italic
  • underline
  • inverse
  • hidden
  • strikethrough

4 Environment

4.1 PASTEL_COLORS_ALIASES

This environment variable allows you to specify custom color aliases at runtime that will be understood by Pastel. The environment variable is read and used when the instance of Pastel is created. You can also use alias_color to create aliases.

Only alphanumeric and _ and . are allowed in the alias names with the following format:

PASTEL_COLORS_ALIASES="newcolor_1=red,newcolor_2=on_green,funky=red.bold"

5. Command line

You can also install pastel-cli to use pastel executable in terminal:

$ pastel green 'Unicorns & rainbows!'

Contributing

  1. Fork it ( https://github.com/piotrmurach/pastel/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Code of Conduct

Everyone interacting in the Pastel project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

Copyright

Copyright (c) 2014 Piotr Murach. See LICENSE for further details.

pastel's People

Contributors

danielvartanov avatar deepj avatar keithrbennett avatar mattbrictson avatar mfurtak avatar npezza93 avatar ordinaryzelig avatar piotrmurach avatar rkushnir avatar spaghetticode avatar vadviktor 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

pastel's Issues

undecorate does not recognize nested color in style

Describe the problem

Undecorate does not recognize nested colors/styles.

Steps to reproduce the problem

require 'pastel'
require 'strscan'
pastel = ::Pastel.new
pastel.new.undecorate(pastel.bold('FIRST' + pastel.blue('SECOND') + 'THIRD'))[1]
# {:foreground=>:blue, :text=>"SECOND"}
pastel.new.undecorate(pastel.on_yellow('FIRST' + pastel.blue('SECOND') + 'THIRD'))[1]
# {:foreground=>:blue, :text=>"SECOND"}
pastel.new.undecorate(pastel.on_yellow('FIRST' + pastel.bold('SECOND') + 'THIRD'))[1]
# {:style=>:bold, :text=>"SECOND"}

Actual behaviour

The nested part ('SECOND') does not not retain the wrapping color/style.

Expected behaviour

Expected the undecorate to recognize the nested valid styles.

Describe your environment

  • OS version: Ubuntu 18.04.3 LTS
  • Ruby version: ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux] (in docker, FROM ruby:2.6.5)
  • Pastel version: 0.7.3

Provide an option for Pastel to disable color (methods would be no-ops).

(I have not yet started working with this gem, so I apologize in advance if this feature already exists.)

Colored output is very helpful when output to a terminal, but when output to a block device (e.g. by redirecting stdout on the command line to a file), it can be a big problem. It would be great if Pastel instances had enabled and enabled= methods, or some other way to enable and disable production of the ANSI escape (color) sequences. Then, the developer could test the stream to see what kind of device it is, and set the enabled attribute accordingly, e.g.

pastel.enabled = $stdout.tty?

For cases where you would want to disable ANSI sequences in files (always, in my opinion), this would eliminate the need to do the test everywhere a pastel method is called.

This would also enable use of the same code using Pastel calls for building console messages and log messages, with two separate Pastel instances with different enabled settings.

The system cannot find the path specified.

I'm using Windows 10 with version 2.2.4 of Ruby and am getting an error saying, "The system cannot find the path specified." I haven't messed with Ruby for a while, so I might be doing something foolish. Here is my example code.

gem 'pastel'
require 'pastel'

pastel = Pastel.new
puts "Using Pastel Version #{Pastel::VERSION}"
puts pastel.red('This should be red!')
puts "\e[32mfoo\e[0m \e[31mbar\e[0m"

And here is the output:

The system cannot find the path specified.
Using Pastel Version 0.6.1
This should be red!
foo bar

The "This should be red!" output, is not colored at all. But, the next line "foo bar" is colored green and red as expected using the \e codes.

I tried poking around the source a bit but couldn't find a spot where the library would be looking for some external file. Any idea what could be going on?

Undefined method `color?` for TTY::Screen::Class

Hello,

I have a code complaining as soon as I call prompt = TTY::Prompt.new.
Here is the trace:

avril14th@avril14th:~/src/white2$ rake admin:organization:create
rake aborted!
NoMethodError: undefined method `color?' for TTY::Screen:Class
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/pastel-0.5.2/lib/pastel/color.rb:24:in `block in initialize'
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/pastel-0.5.2/lib/pastel/color.rb:24:in `fetch'
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/pastel-0.5.2/lib/pastel/color.rb:24:in `initialize'
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/pastel-0.5.2/lib/pastel.rb:32:in `new'
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/pastel-0.5.2/lib/pastel.rb:32:in `new'
/home/avril14th/.rvm/gems/ruby-2.2.3/gems/tty-prompt-0.3.0/lib/tty/prompt.rb:57:in `initialize'
/home/avril14th/src/white2/lib/tasks/admin.rake:9:in `new'
/home/avril14th/src/white2/lib/tasks/admin.rake:9:in `block (3 levels) in <top (required)>'

I use tty-prompt 0.30 in a Rails 4.2.5 app.

As it turns out (https://github.com/peter-murach/tty-screen/blob/8c325a4566669c28f33bc28ff2b13831cbc22bf3/CHANGELOG.md#v050---2016-01-03) support for color detection has been removed from TTY::Screen and added a separate gem. Either update dependency or remove call should do it. (I'd say second choice makres sence ;D)

pastel with color-element in a variable

I'm playing around with beautiful lib pastel on linux and do not see a solution for my use case. I want to define colors for some cells in variables. But in this case I don't see my values in cell but whole pastel-string. How can I get over this?
Example:

`

require 'tty'
require 'pastel'
pastel=Pastel.new

puts "This works:"
table = TTY::Table.new ['header1', 'header2'], [[{value: pastel.blue('a1'),alignment: :center}, 'a2'], ['b1', 'b2']]
t = table.render do |renderer|
end
puts t

puts "This does not:"
val1 = "{value: pastel.blue('a1'),alignment: :center}"
table = TTY::Table.new ['header1', 'header2'], [[val1, 'a2'], ['b1', 'b2']]
t = table.render do |renderer|
end
puts t

`
This is my output (a1 is blue in first table):

`

This works:
header1 header2
a1 a2
b1 b2
This does not:
header1 header2
{value: pastel.blue('a1'),alignment: :center} a2
b1 b2
`
Did I miss something in documentation?

detach problem

In Pry, in the OS X terminal, detach doesn't work as the README suggests:

pry> error = pastel.red.on_bold.detach
=> #<Pastel::Detached styles=[:red, :on_bold]>
pry> error('Error!')
NoMethodError: undefined method `error' for main:Object
from (pry):19:in `__pry__'

Running pry 0.10.1, pastel 0.5.0, and Mac OS 10.10.5.

Getting a warning on use of Pastel

Hi there,
I get these two lines on any script which uses Pastel...

/Users/jschank/.rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/tty-screen-0.4.0/lib/tty/screen/size.rb:129: warning: private attribute?
no native curses support

But the colorization does work.
Is there anything I can do to prevent these lines from being emitted?

I am using a mac, on El Capitan.

Thanks,
John Schank

Can pastel work in Jenkins?

I tried using pastel in Jenkins, but no colors are seen.

The colorize gem works in Jenkins with a few tweaks, but pastel seems to have more features.

It would be great if pastel could work in Jenkins.

NO_COLOR

Describe the problem

With paint, there is a mode to disable coloring, and it also follows NO_COLOR env. var. if set. This is especially useful if you want to have a --no-color option on your CLI. Very useful when you want to pipe your CLI to other commands and to disable ANSI escape.

How would the new feature work?

An option to disable coloring manually plus automatically follows NO_COLOR.

Drawbacks

I don't.

Does Pastel work in IRB?

I'm trying to use Pastel in IRB, before I use it in my codebase. But it doesn't seem to work. It would be great if you could provide some feedback on this. Thanks.

screen shot 2015-09-20 at 4 31 46 pm

doesn't working on 2.x

trying the gem on 2.x I ve got that on the require 'pastel', I am on xunbuntu 12.04, using rvm.

[Tophe:/data/svn/dev/dev/ruby/stub] $ gem install pastel
Fetching: equatable-0.5.0.gem (100%)
Successfully installed equatable-0.5.0
Fetching: pastel-0.2.0.gem (100%)
Successfully installed pastel-0.2.0
Parsing documentation for equatable-0.5.0
Installing ri documentation for equatable-0.5.0
Parsing documentation for pastel-0.2.0
Installing ri documentation for pastel-0.2.0
Done installing documentation for equatable, pastel after 0 seconds
2 gems installed
[Tophe:/data/svn/dev/dev/ruby/stub] $ ruby pastel_demo.rb
/home/Tophe/.rvm/gems/ruby-2.1.2/gems/pastel-0.2.0/lib/pastel/delegator.rb:9:in <class:Delegator>': uninitialized constant Pastel::Delegator::Forwardable (NameError) from /home/Tophe/.rvm/gems/ruby-2.1.2/gems/pastel-0.2.0/lib/pastel/delegator.rb:8:inmodule:Pastel'
from /home/Tophe/.rvm/gems/ruby-2.1.2/gems/pastel-0.2.0/lib/pastel/delegator.rb:3:in <top (required)>' from /home/Tophe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
from /home/Tophe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in require' from /home/Tophe/.rvm/gems/ruby-2.1.2/gems/pastel-0.2.0/lib/pastel.rb:7:in<top (required)>'
from /home/Tophe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in require' from /home/Tophe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
from pastel_demo.rb:2:in `

'
[Tophe:/data/svn/dev/dev/ruby/stub] 1 $ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-linux]
[Tophe:/data/svn/dev/dev/ruby/stub] $ uname -a
Linux info3 3.2.0-57-generic #87-Ubuntu SMP Tue Nov 12 21:35:10 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Pastel is not found

Hello,

I may be missing something but have tried to use this gem:

  • installed it with bundler in my project
  • installed it separately with gem
  • tried to use it in pry, irb and a separate file

all of the above resulted in the message: uninitialized constant Pastel (NameError).
Using 2.1.2, 2.1.4 MRI managed by rbenv on Ubuntu 14.04.

Could you help me figuring out why do I fail at the very beginning, please? 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.