class CodeRay::Encoders::Terminal

MIT License (www.opensource.org/licenses/mit-license.php)
Based on idea by Nathan Weizenbaum (nex-3.com)
By Rob Aldred (robaldred.co.uk)
== Authors & License
Alias: term
Note: This encoder is in beta. It currently doesn’t use the Styles.
Outputs code highlighted for a color terminal.

def ansi_clear

def ansi_clear
  ansi_colorize(0)
end

def ansi_colorize(color)

def ansi_colorize(color)
  Array(color).map { |c| "\e[#{c}m" }.join
end

def begin_group kind

def begin_group kind
  @opened << kind
  @out << open_token(kind)
end

def end_group kind

def end_group kind
  if @opened.empty?
    # nothing to close
  else
    @opened.pop
    @out << ansi_clear
    @out << open_token(@opened.last)
  end
end

def end_line kind

def end_line kind
  if @opened.empty?
    # nothing to close
  else
    @opened.pop
    # whole lines to be highlighted,
    # eg. added/modified/deleted lines in a diff
    @out << "\t" * 100 + ansi_clear
    @out << open_token(@opened.last)
  end
end

def open_token kind

def open_token kind
  if color = TOKEN_COLORS[kind]
    if Hash === color
      @subcolors = color
      ansi_colorize(color[:self]) if color[:self]
    else
      @subcolors = {}
      ansi_colorize(color)
    end
  else
    @subcolors = nil
    ''
  end
end

def setup(options)

def setup(options)
  super
  @opened = []
  @subcolors = nil
end

def text_token text, kind

def text_token text, kind
  if color = (@subcolors || TOKEN_COLORS)[kind]
    if Hash === color
      if color[:self]
        color = color[:self]
      else
        @out << text
        return
      end
    end
    
    @out << ansi_colorize(color)
    @out << text.gsub("\n", ansi_clear + "\n" + ansi_colorize(color))
    @out << ansi_clear
    @out << ansi_colorize(@subcolors[:self]) if @subcolors && @subcolors[:self]
  else
    @out << text
  end
end