Class: Unmagic::Color::Console::Highlighter

Inherits:
Object
  • Object
show all
Defined in:
lib/unmagic/color/console/highlighter.rb

Overview

Simple syntax highlighter for Ruby code snippets.

Highlights strings, numbers, symbols, and comments using ANSI color codes.

Examples:

Basic usage

hl = Unmagic::Color::Console::Highlighter.new
puts hl.highlight('color.to_rgb.to_s')
puts hl.comment('# This is a comment')

With custom colors

hl = Unmagic::Color::Console::Highlighter.new(colors: { string: "#00FF00" })
puts hl.highlight('parse("#FF0000")')

Constant Summary collapse

DEFAULT =

Default colors for syntax highlighting

{
  string: "#00FF00",
  number: "#FF00FF",
  symbol: "#FFFF00",
  comment: "#696969",
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(mode: :palette16, colors: DEFAULT) ⇒ Highlighter

Returns a new instance of Highlighter.

Parameters:

  • mode (Symbol) (defaults to: :palette16)

    ANSI color mode (:truecolor, :palette256, :palette16)

  • colors (Hash) (defaults to: DEFAULT)

    Color overrides (keys: :string, :number, :symbol, :comment)



30
31
32
33
# File 'lib/unmagic/color/console/highlighter.rb', line 30

def initialize(mode: :palette16, colors: DEFAULT)
  @mode = mode
  @colors = DEFAULT.merge(colors)
end

Instance Method Details

#colorize(text, key) ⇒ String

Colorize text with a specific color.

Parameters:

  • text (String)

    Text to colorize

  • key (Symbol)

    Color key from the colors hash

Returns:

  • (String)

    Text with ANSI color codes



94
95
96
97
# File 'lib/unmagic/color/console/highlighter.rb', line 94

def colorize(text, key)
  color = Color.parse(@colors[key])
  "\e[#{color.to_ansi(mode: @mode)}m#{text}\e[0m"
end

#comment(text) ⇒ String

Format text as a comment.

Parameters:

  • text (String)

    Comment text

Returns:

  • (String)

    Gray-colored text



85
86
87
# File 'lib/unmagic/color/console/highlighter.rb', line 85

def comment(text)
  colorize(text, :comment)
end

#highlight(code) ⇒ String

Highlight a code snippet with syntax coloring.

Supports multi-line input. Lines starting with # are treated as comments.

Parameters:

  • code (String)

    Ruby code to highlight (single or multi-line)

Returns:

  • (String)

    Code with ANSI color codes



41
42
43
# File 'lib/unmagic/color/console/highlighter.rb', line 41

def highlight(code)
  code.lines.map { |line| highlight_line(line.chomp) }.join("\n")
end

Format text as a clickable hyperlink.

Uses ANSI palette16 blue with underline, plus OSC 8 hyperlink sequence for iTerm2 and other modern terminals.

Parameters:

  • url (String)

    The URL to link to

  • text (String) (defaults to: url)

    The display text (defaults to url)

Returns:

  • (String)

    Styled, clickable link



107
108
109
110
# File 'lib/unmagic/color/console/highlighter.rb', line 107

def link(url, text = url)
  # ANSI palette16 blue (34) + underline (4)
  "\e[4;34m\e]8;;#{url}\a#{text}\e]8;;\a\e[0m"
end