module IRB::Color

Constants

BLUE
BOLD
CLEAR
CYAN
GREEN
MAGENTA
RED
TOKEN_KEYWORDS
TOKEN_SEQ_EXPRS
UNDERLINE

Public Class Methods

clear() click to toggle source
# File lib/irb/color.rb, line 66
def clear
  return '' unless colorable?
  "\e[#{CLEAR}m"
end
colorable?() click to toggle source
# File lib/irb/color.rb, line 45
def colorable?
  $stdout.tty? && ENV.key?('TERM') && ENV['TERM'] != 'dumb'
end
colorize(text, seq) click to toggle source
# File lib/irb/color.rb, line 71
def colorize(text, seq)
  return text unless colorable?
  "#{seq.map { |s| "\e[#{const_get(s)}m" }.join('')}#{text}#{clear}"
end
colorize_code(code) click to toggle source
# File lib/irb/color.rb, line 76
def colorize_code(code)
  return code unless colorable?

  colored = +''
  Ripper.lex(code).each do |(_line, _col), token, str, expr|
    if seq = dispatch_seq(token, expr, str)
      colored << "#{seq.map { |s| "\e[#{s}m" }.join('')}#{str}#{clear}"
    else
      colored << str
    end
  end
  colored
end
inspect_colorable?(obj) click to toggle source
# File lib/irb/color.rb, line 49
def inspect_colorable?(obj)
  case obj
  when String, Symbol, Regexp, Integer, Float, FalseClass, TrueClass, NilClass
    true
  when Hash
    obj.all? { |k, v| inspect_colorable?(k) && inspect_colorable?(v) }
  when Array
    obj.all? { |o| inspect_colorable?(o) }
  when Range
    inspect_colorable?(obj.begin) && inspect_colorable?(obj.end)
  when Module
    !obj.name.nil?
  else
    false
  end
end

Private Class Methods

dispatch_seq(token, expr, str) click to toggle source
# File lib/irb/color.rb, line 92
def dispatch_seq(token, expr, str)
  if token == :on_comment
    [BLUE, BOLD]
  elsif TOKEN_KEYWORDS.fetch(token, []).include?(str)
    [CYAN, BOLD]
  elsif (seq, exprs = TOKEN_SEQ_EXPRS[token]; exprs&.any? { |e| (expr & e) != 0 })
    seq
  else
    nil
  end
end