colorize icon indicating copy to clipboard operation
colorize copied to clipboard

Option to prevent re-coloring

Open jsm opened this issue 9 years ago • 5 comments

For example:

"Error Code: #{error.colorizer(:red)}".colorizer(:yellow)

I would want the code to still be red, with the rest of the text being yellow.

jsm avatar Nov 02 '15 22:11 jsm

"#{"Error Code:".colorize(:yellow)} #{error.colorize(:red)}"

fazibear avatar Nov 03 '15 09:11 fazibear

Sorry, that was a really basic example, easily solved by what you suggest. Here's an example that more closely mimics my situation.

# myscript.sh
echo -e "\033[0;31mI\033[0m print \033[0;32mmixed\033[0m \033[0;35mcolors\033[0m"
exit 1
class CustomLogger < BaseLogger
  def warning(msg)
    super(msg.colorizer(:yellow))
  end
end

Log = CustomLogger.new

def custom_executor(cmd)
  output = `#{cmd}`
  Log.warning(output) if !$?.success?
end

custom_executor('bash myscript.sh')

In this case, I can't control the bash script's coloring, but I want to preserve as much of it as I can, but color anything that doesn't already have color to yellow.

If you don't have time to implement something like this, you could give me some pointers on how I could do this. Or if you don't think you would merge in a pull request with this functionality, feel free to say so as well.

jsm avatar Nov 03 '15 10:11 jsm

Bump

jsm avatar May 06 '16 22:05 jsm

I think you could split the string with regex to pull out already colored parts, and then colorize each of those. Will try to pr if I have time, no promises :-P

CapCap avatar Jul 08 '16 18:07 CapCap

@jsm Actually, something like this:

require 'colorize'

def colorize_nicely(str, color={color: :red, background: :green})
  k = ''
  r = /(\033\[[\d;]+m.*?\033\[[\d;]+m\s+?)/m

  z = str.split(r).reject { |s| !s || (k << s if s.strip.length == 0)  }

  if z.length == 1
    if z[0].match(/\033\[[\d;]+m/im)
      return str
    else
      return str.colorize(color)
    end
  end

  z.each do |s|
    if s.strip.length == 0
      k << s
    else
      k << colorize_nicely(s, color)
    end
  end

  k
end

s = "#{'Now'.green.on_yellow} #{'I'.blue.on_red} will #{'play'.yellow} #{'nicer'.red.on_blue} with others"
puts s
puts colorize_nicely(s)

CapCap avatar Jul 08 '16 20:07 CapCap