module Colours refine String do def reset ansi(0) end # FORMATTING def bold style 1 end def faint style 2 end def italic style 3 end def underline style 4 end # FOREGROUND COLOURS def black style 30 end def blue style 34 end def cyan style 36 end def green style 32 end def magenta style 35 end # TODO: wrong number def purple style 35 end def red style 31 end def white style 37 end def yellow style 33 end def bright_black style 90 end def bright_blue style 94 end def bright_cyan style 96 end def bright_green style 92 end def bright_magenta style 95 end def bright_red style 91 end def bright_white style 97 end def bright_yellow style 93 end # BACKGROUND COLOURS def bg_black style 40 end def bg_blue style 44 end def bg_cyan style 46 end def bg_green style 42 end def bg_magenta style 45 end def bg_red style 41 end def bg_white style 47 end def bg_yellow style 43 end # ANSI 256 COLOURS def bg(code) style "48;5;#{code}" end def fg(code) style "38;5;#{code}" end # MISC def backticks backtick + self + backtick end def near_black bg(240) end private def ansi(code) "\e[#{code}m" end def backtick '`'.yellow end def style(code) ansi(code) + self + reset end end class Demo class << self using Colours def all_ansi_256 puts display_all_ansi_256('bg') puts puts display_all_ansi_256('fg') puts puts display_all(styles) puts puts display_all(fg_colours) puts puts display_all(bright_colours) puts puts display_all(bg_colours) puts puts end private def display_all(formats) codes_displayed = 1 formats.each do |method, complementary_method| print ".#{method}".ljust(col_width).send(method).send(complementary_method) codes_displayed += 1 if codes_displayed * col_width > screen_width puts codes_displayed = 1 end end end def styles { bold: :white, faint: :white, italic: :white, underline: :white } end def fg_colours { black: :near_black, blue: :bg_black, cyan: :bg_black, green: :bg_black, magenta: :bg_black, red: :bg_black, white: :bg_black, yellow: :bg_black } end def bright_colours { bright_black: :bg_black, bright_blue: :bg_black, bright_cyan: :bg_black, bright_green: :bg_black, bright_magenta: :bg_black, bright_red: :bg_black, bright_white: :bg_black, bright_yellow: :bg_black } end def bg_colours { bg_black: :white, bg_blue: :black, bg_cyan: :black, bg_green: :black, bg_magenta: :black, bg_red: :black, bg_white: :black, bg_yellow: :black } end def display_all_ansi_256(method) # Use `Colours::Demo.all_ansi_256` to see colours available codes_displayed = 1 256.times do |code| print ".#{method}(#{code})".ljust(col_width).send(method, code).fg(89) codes_displayed += 1 if codes_displayed * col_width + 2 > screen_width puts codes_displayed = 1 end end end def col_width @col_width ||= '.bright_magenta '.length end def screen_width @screen_width ||= `tput cols`.to_i end end end end