Class: Iro::Formatter::HTMLFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/iro/formatter/html_formatter.rb

Defined Under Namespace

Modules: ConvertedHighlight

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source:, highlight:, prefix:) ⇒ HTMLFormatter

Returns a new instance of HTMLFormatter.



27
28
29
30
31
# File 'lib/iro/formatter/html_formatter.rb', line 27

def initialize(source:, highlight:, prefix:)
  @source = source.each_line.map(&:chomp)
  @highlight = sort_highlight_by_position(highlight)
  @prefix = prefix
end

Class Method Details

.format(source, highlight, prefix: '') ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/iro/formatter/html_formatter.rb', line 14

def self.format(source, highlight, prefix: '')
  formatter = self.new(
    source: source,
    highlight: highlight,
    prefix: prefix,
  )
  formatter.format
end

.sample_stylesheetObject



23
24
25
# File 'lib/iro/formatter/html_formatter.rb', line 23

def self.sample_stylesheet
  File.join(__dir__, 'sample.css')
end

Instance Method Details

#formatObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/iro/formatter/html_formatter.rb', line 33

def format
  buf = []

  @source.each.with_index do |line, lineno|
    highlights = pop_highlight(lineno)
    if highlights.empty?
      buf << CGI.escapeHTML(line)
      next
    end

    last_col = 0
    highlighted_line = +''
    highlights.each do |hi|
      highlighted_line << CGI.escapeHTML(line[last_col...hi.column])
      last_col = hi.column + hi.length
      token = CGI.escapeHTML(line[(hi.column)...last_col])
      highlighted_line << %Q!<span class="#{@prefix}#{hi.group}">#{token}</span>!
    end
    highlighted_line << line[last_col..-1]
    buf << highlighted_line
  end

  buf.join("\n")
end

#pop_highlight(lineno) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/iro/formatter/html_formatter.rb', line 68

def pop_highlight(lineno)
  [].tap do |res|
    while @highlight.first&.line == lineno
      res << @highlight.shift
    end
  end
end

#sort_highlight_by_position(highlight) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/iro/formatter/html_formatter.rb', line 58

def sort_highlight_by_position(highlight)
  highlight.flat_map do |group, positions|
    positions.map do |pos|
      [group, *pos]
    end
  end.sort_by do |pos|
    [pos.line, pos.column]
  end
end