require 'simplecolor/version' require 'simplecolor/colors' #Usage: # #@example # class Foo # include SimpleColor # def to_str # ... # end # end # foo=Foo.new() # foo.color(:red) #after SimpleColor.mix_in_string, one can do #`"blue".color(:blue,:bold)` module SimpleColor SimpleColorError=Class.new(StandardError) require 'simplecolor/colorer' require 'simplecolor/rgb' # Wraps around Colorer to provide useful instance methods module ColorWrapper extend self # wrap self or the first argument with colors # @example ploum # SimpleColor.color("blue", :blue, :bold) # SimpleColor.color(:blue,:bold) { "blue" } # SimpleColor.color(:blue,:bold) << "blue" << SimpleColor.color(:clear) %i(color uncolor color! uncolor! color?).each do |m| define_method m do |*args, **kwds, &b| arg=if b b.call.to_s elsif respond_to?(:to_str) self.to_str else first=args.first if first.respond_to?(:to_str) args.shift.to_str elsif first.nil? args.shift else nil end end case m when :color # the rescue is here for ruby 2.3 which can't dup Nilclass. # Newer versions of ruby don't need it duped = arg.dup rescue arg Colorer.colorer(duped,*args,**kwds) when :uncolor duped = arg.dup rescue arg Colorer.uncolorer(duped,*args,**kwds) when :color! Colorer.colorer(arg,*args,**kwds) when :uncolor! Colorer.uncolorer(arg,*args,**kwds) when :color? Colorer.colored?(arg,*args,**kwds) end end end end module Utilities extend self # scan s from left to right and for each ansi sequences found # split it into elementary components and output the symbolic meaning # eg: SimpleColor.attributes_from_colors(SimpleColor.color("foo", :red)) # => [:red, :reset] def attributes_from_colors(s) s.scan(Colorer.regexp(:ansi)).flat_map do |a| next :reset if a=="\e[m" #alternative for reset stack=[] # a[/\e\[(.*)m/,1].split(';').map {|c| Colorer.colors.key(c.to_i)} codes=a[/\e\[(.*)m/,1].split(';') i=0; while i