Class: Gimli::Markup

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

Overview

Contains functionality to render html from a markup file

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Gimli::Markup

Initialize a new Markup object.

Parameters:



30
31
32
33
34
35
36
37
38
# File 'lib/gimli/markup.rb', line 30

def initialize(file)
  @filename = file.filename
  @name = file.name
  @data = file.data
  @format = file.format
  @tagmap = {}
  @codemap = {}
  @premap = {}
end

Instance Method Details

#check_cache(type, id) ⇒ String

Hook for getting the formatted value of extracted tag data.

Parameters:

  • type (Symbol)

    Symbol value identifying what type of data is being extracted.

  • id (String)

    String SHA1 hash of original extracted tag data.

Returns:

  • (String)

    Returns the String cached formatted data, or nil.



272
273
# File 'lib/gimli/markup.rb', line 272

def check_cache(type, id)
end

#doc_to_html(doc) ⇒ Object



67
68
69
# File 'lib/gimli/markup.rb', line 67

def doc_to_html(doc)
  doc.to_xhtml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XHTML, :encoding => 'UTF-8')
end

#extract_code(data) ⇒ String

Extract all code blocks into the codemap and replace with placeholders.

Parameters:

  • data (String)

    The raw String data.

Returns:

  • (String)

    Returns the placeholder’d String data.



212
213
214
215
216
217
218
219
220
221
222
# File 'lib/gimli/markup.rb', line 212

def extract_code(data)
  data.gsub!(/^``` ?([^\r\n]+)?\r?\n(.+?)\r?\n```\r?$/m) do
    id     = Digest::SHA1.hexdigest($2)
    cached = check_cache(:code, id)
    @codemap[id] = cached   ?
      { :output => cached } :
      { :lang => $1, :code => $2 }
    id
  end
  data
end

#extract_tags(data) ⇒ String

Extract all tags into the tagmap and replace with placeholders.

Parameters:

  • data (String)
    • The raw string data.

Returns:

  • (String)

    Returns the placeholder’s string data.



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/gimli/markup.rb', line 75

def extract_tags(data)
  data.gsub!(/(.?)\[\[(.+?)\]\]([^\[]?)/m) do
    if $1 == "'" && $3 != "'"
      "[[#{$2}]]#{$3}"
    elsif $2.include?('][')
      if $2[0..4] == 'file:'
        pre = $1
        post = $3
        parts = $2.split('][')
        parts[0][0..4] = ""
        link = "#{parts[1]}|#{parts[0].sub(/\.org/,'')}"
        id = Digest::SHA1.hexdigest(link)
        @tagmap[id] = link
        "#{pre}#{id}#{post}"
      else
        $&
      end
    else
      id = Digest::SHA1.hexdigest($2)
      @tagmap[id] = $2
      "#{$1}#{id}#{$3}"
    end
  end
  data
end

#parse_image_tag_options(tag) ⇒ Hash

Parse any options present on the image tag and extract them into a Hash of option names and values.

Returns the options Hash:

key - The String option name.
val - The String option value or true if it is a binary option.

Parameters:

  • tag (String)

    The String tag contents (the stuff inside the double brackets).

Returns:

  • (Hash)


200
201
202
203
204
205
206
# File 'lib/gimli/markup.rb', line 200

def parse_image_tag_options(tag)
  tag.split('|')[1..-1].inject({}) do |memo, attr|
    parts = attr.split('=').map { |x| x.strip }
    memo[parts[0]] = (parts.size == 1 ? true : parts[1])
    memo
  end
end

#process_code(data) ⇒ String

Process all code from the codemap and replace the placeholders with the final HTML.

Parameters:

  • data (String)

    The String data (with placeholders).

Returns:

  • (String)

    Returns the marked up String data.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/gimli/markup.rb', line 229

def process_code(data)
  return data if data.nil? || data.size.zero? || @codemap.size.zero?
  blocks    = []
  @codemap.each do |id, spec|
    next if spec[:output] # cached

    code = spec[:code]
    if code.lines.all? { |line| line =~ /\A\r?\n\Z/ || line =~ /^(  |\t)/ }
      code.gsub!(/^(  |\t)/m, '')
    end

    code = Iconv.conv('ISO-8859-1//IGNORE', 'utf-8', code)

    blocks << [spec[:lang], code]
  end

  highlighted = begin
    blocks.size.zero? ? [] : Gimli::Albino.colorize(blocks)
  rescue ::Albino::ShellArgumentError, ::Albino::TimeoutExceeded,
           ::Albino::MaximumOutputExceeded
    []
  end

  @codemap.each do |id, spec|
    body = spec[:output] || begin
      if (body = highlighted.shift.to_s).size > 0
        update_cache(:code, id, body)
        body
      else
        "<pre><code>#{CGI.escapeHTML(spec[:code])}</code></pre>"
      end
    end
    data.gsub!(id, body)
  end

  data
end

#process_image_tag(tag) ⇒ String|nil

Attempt to process the tag as an image tag.

Parameters:

  • tag (String)

    The String tag contents (the stuff inside the double brackets).

Returns:

  • (String|nil)

    Returns the String HTML if the tag is a valid image tag or nil if it is not.



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/gimli/markup.rb', line 129

def process_image_tag(tag)
  parts = tag.split('|')
  return if parts.size.zero?

  name  = parts[0].strip
  path  = name

  if path
    opts = parse_image_tag_options(tag)

    containered = false

    classes = [] # applied to whatever the outermost container is
    attrs   = [] # applied to the image

    align = opts['align']
    if opts['float']
      containered = true
      align ||= 'left'
      if %w{left right}.include?(align)
        classes << "float-#{align}"
      end
    elsif %w{top texttop middle absmiddle bottom absbottom baseline}.include?(align)
      attrs << %{align="#{align}"}
    elsif align
      if %w{left center right}.include?(align)
        containered = true
        classes << "align-#{align}"
      end
    end

    if width = opts['width']
      if width =~ /^\d+(\.\d+)?(em|px)$/
        attrs << %{width="#{width}"}
      end
    end

    if height = opts['height']
      if height =~ /^\d+(\.\d+)?(em|px)$/
        attrs << %{height="#{height}"}
      end
    end

    if alt = opts['alt']
      attrs << %{alt="#{alt}"}
    end

    attr_string = attrs.size > 0 ? attrs.join(' ') + ' ' : ''

    if opts['frame'] || containered
      classes << 'frame' if opts['frame']
      %{<span class="#{classes.join(' ')}">} +
      %{<span>} +
      %{<img src="#{path}" #{attr_string}/>} +
      (alt ? %{<span>#{alt}</span>} : '') +
      %{</span>} +
      %{</span>}
    else
      %{<img src="#{path}" #{attr_string}/>}
    end
  end
end

#process_tag(tag) ⇒ String

Process a single tag into its final HTML form.

Parameters:

  • tag (String)

    The String tag contents (the stuff inside the double brackets).

Returns:

  • (String)

    Returns the String HTML version of the tag.



117
118
119
120
121
122
123
# File 'lib/gimli/markup.rb', line 117

def process_tag(tag)
  if html = process_image_tag(tag)
    html
  elsif html = process_file_link_tag(tag)
    html
  end
end

#process_tags(data) ⇒ String

Process all tags from the tagmap and replace the placeholders with the final markup.

Parameters:

  • data (String)
    • The data (with placeholders)

Returns:

  • (String)

    Returns the marked up String data.



106
107
108
109
110
111
# File 'lib/gimli/markup.rb', line 106

def process_tags(data)
  @tagmap.each do |id, tag|
    data.gsub!(id, process_tag(tag))
  end
  data
end

#render {|doc| ... } ⇒ String

Render the content with Gollum wiki syntax on top of the file’s own markup language.

Yields:

  • (doc)

Returns:

  • (String)

    The formatted data



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/gimli/markup.rb', line 44

def render
  data = extract_code(@data.dup)
  data = extract_tags(data)
  begin
    data = data.force_encoding('utf-8') if data.respond_to? :force_encoding
    data = GitHub::Markup.render(@filename, data)
    if data.nil?
      raise "There was an error converting #{@name} to HTML."
    end
  rescue Object => e
    data = %{<p class="gimli-error">#{e.message}</p>}
  end
  data = process_tags(data)
  data = process_code(data)

  doc  = Nokogiri::HTML::DocumentFragment.parse(data, 'UTF-8')
  yield doc if block_given?
  data = doc_to_html(doc)

  data.gsub!(/<p><\/p>/, '')
  data
end

#update_cache(type, id, data) ⇒ nil

Hook for caching the formatted value of extracted tag data.

Parameters:

  • type (Symbol)

    Symbol value identifying what type of data is being extracted.

  • id (String)

    String SHA1 hash of original extracted tag data.

  • data (String)

    The String formatted value to be cached.

Returns:

  • (nil)


281
282
# File 'lib/gimli/markup.rb', line 281

def update_cache(type, id, data)
end