Class: PFM::FootnoteProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/pfm.rb

Overview

Converts Pandoc-style footnotes into appropriate HTML

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ FootnoteProcessor

Returns a new instance of FootnoteProcessor.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/pfm.rb', line 64

def initialize(options={})
  # looking for footnote refs like [^some_identifier]
  @note_regex = /
    ^
    \[\^
      ([\d\w\-_]+)
    \]:
  /x
  @ref_regex = /
    \[\^
      ([\d\w\-_]+)
    \]
  /x
end

Instance Method Details

#format_anchor(number, identifier) ⇒ Object



125
126
127
# File 'lib/pfm.rb', line 125

def format_anchor(number, identifier)
  %Q{<a name="#{identifier}" href="#__#{identifier}">#{number} &#8617;</a>.}
end

#format_ref(number, identifier) ⇒ Object



129
130
131
132
133
# File 'lib/pfm.rb', line 129

def format_ref(number, identifier)
  %Q{
    <sup><a name="__#{identifier}" href="##{identifier}">#{number}</a>.</sup>
  }.strip
end

#process(lines) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/pfm.rb', line 79

def process(lines)
  out = []
  refs = []
  notes = {}
  ref_counter = 0
  while line = lines.shift
    if md = @note_regex.match(line)
      full, identifier = md.to_a
      note = notes[identifier] = [line]
      while (next_line = lines.shift) && next_line !~ /^\s*$/
        note << next_line
      end

    elsif md = @ref_regex.match(line)
      full, identifier = md.to_a
      ref_counter += 1
      refs << identifier
      out << line.sub(full, format_ref(ref_counter, identifier))
    else
      out << line
    end
  end

  if refs.size > 0
    out << ""
    out << "# Notes"
    out << ""
    refs.each_with_index do |identifier, index|
      if note = notes[identifier]
        start = note.shift
        anchor = format_anchor(index + 1, identifier)
        start.sub! /^\[.*\]: /, ""
        out << "#{anchor} #{start}"

        note.each do |line|
          out << line
        end
        out << ""
      end
    end
  end
  out << ""
  out
end