Class: Gollum::Markup

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/gollum-lib/markup.rb,
lib/gollum-lib/markups.rb

Constant Summary collapse

PREFORMATTED_TAGS =

Find ‘id` within `data` and determine if it’s within preformatted tags.

data - The String data (with placeholders). id - The String SHA1 hash.

%w(code tt)

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#trim_leading_slash

Constructor Details

#initialize(page) ⇒ Markup

Initialize a new Markup object.

page - The Gollum::Page.

Returns a new Gollum::Markup object, ready for rendering.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/gollum-lib/markup.rb', line 48

def initialize(page)
  @wiki    = page.wiki
  @name    = page.filename
  @data    = page.text_data
  @version = page.version.id if page.version
  @format  = page.format
  @sub_page = page.sub_page
  @parent_page = page.parent_page
  @dir     = ::File.dirname(page.path)
  @tagmap  = {}
  @codemap = {}
  @wsdmap  = {}
  @premap  = {}
  @toc = nil
   = nil
  @to_xml = { :save_with => Nokogiri::XML::Node::SaveOptions::DEFAULT_XHTML ^ 1, :indent => 0, :encoding => 'UTF-8' }
end

Class Attribute Details

.formatsObject (readonly)

Returns the value of attribute formats.



21
22
23
# File 'lib/gollum-lib/markup.rb', line 21

def formats
  @formats
end

Instance Attribute Details

#metadataObject (readonly)

Returns the value of attribute metadata.



41
42
43
# File 'lib/gollum-lib/markup.rb', line 41

def 
  
end

#tocObject

Returns the value of attribute toc.



40
41
42
# File 'lib/gollum-lib/markup.rb', line 40

def toc
  @toc
end

Class Method Details

.register(ext, name, options = {}, &block) ⇒ Object

Register a file extension and associated markup type

ext - The file extension name - The name of the markup type options - Hash of options:

regexp - Regexp to match against.
         Defaults to exact match of ext.

If given a block, that block will be registered with GitHub::Markup to render any matching pages



33
34
35
36
37
# File 'lib/gollum-lib/markup.rb', line 33

def register(ext, name, options = {}, &block)
  regexp = options[:regexp] || Regexp.new(ext.to_s)
  @formats[ext] = { :name => name, :regexp => regexp }
  GitHub::Markup.add_markup(regexp, &block) if block_given?
end

Instance Method Details

#check_cache(type, id) ⇒ Object

Hook for getting the formatted value of extracted tag data.

type - Symbol value identifying what type of data is being extracted. id - String SHA1 hash of original extracted tag data.

Returns the String cached formatted data, or nil.



719
720
# File 'lib/gollum-lib/markup.rb', line 719

def check_cache(type, id)
end

#extract_code(data) ⇒ Object

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

data - The raw String data.

Returns the placeholder’d String data.



536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/gollum-lib/markup.rb', line 536

def extract_code(data)
  data.gsub!(/^([ \t]*)(~~~+) ?([^\r\n]+)?\r?\n(.+?)\r?\n\1(~~~+)[ \t\r]*$/m) do
    m_indent = $1
    m_start  = $2 # ~~~
    m_lang   = $3
    m_code   = $4
    m_end    = $5 # ~~~

    # start and finish tilde fence must be the same length
    return '' if m_start.length != m_end.length

    lang   = m_lang ? m_lang.strip : nil
    id     = Digest::SHA1.hexdigest("#{lang}.#{m_code}")
    cached = check_cache(:code, id)

    # extract lang from { .ruby } or { #stuff .ruby .indent }
    # see http://johnmacfarlane.net/pandoc/README.html#delimited-code-blocks

    if lang
        lang = lang.match(/\.([^}\s]+)/)
        lang = lang[1] unless lang.nil?
    end

    @codemap[id] = cached   ?
      { :output => cached } :
      { :lang => lang, :code => m_code, :indent => m_indent }

    "#{m_indent}#{id}" # print the SHA1 ID with the proper indentation
  end

  data.gsub!(/^([ \t]*)``` ?([^\r\n]+)?\r?\n(.+?)\r?\n\1```[ \t]*\r?$/m) do
    lang   = $2 ? $2.strip : nil
    id     = Digest::SHA1.hexdigest("#{lang}.#{$3}")
    cached = check_cache(:code, id)
    @codemap[id] = cached   ?
      { :output => cached } :
      { :lang => lang, :code => $3, :indent => $1 }
    "#{$1}#{id}" # print the SHA1 ID with the proper indentation
  end
  data
end

#extract_metadata(data) ⇒ Object

Extract metadata for data and build metadata table. Metadata consists of key/value pairs in “key:value” format found between markers. Each key/value pair must be on its own line. Internal whitespace in keys and values is preserved, but external whitespace is ignored.

Because ri and ruby 1.8.7 are awesome, the markers can’t be included in this documentation without triggering ‘Unhandled special: Special: type=17` Please read the source code for the exact markers

Returns the String of formatted data with metadata removed.



698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/gollum-lib/markup.rb', line 698

def (data)
   ||= {}
  # The markers are `<!-- ---` and `-->`
  data.gsub(/\<\!--+\s+---(.*?)--+\>/m) do
    # Split untrusted input on newlines, then remove bits that look like
    # HTML elements before parsing each line.
    $1.split("\n").each do |line|
      line.gsub!(/<[^>]*>/, '')
      k, v = line.split(':', 2)
      [k.strip] = (v ? v.strip : '') if k
    end
    ''
  end
end

#extract_remote_code(data) ⇒ Object

Remote code - fetch code from url and replace the contents to a

    code-block that gets run the next parse.
Acceptable formats:
   ```language:local-file.ext```
   ```language:/abs/other-file.ext```
   ```language:https://example.com/somefile.txt```


503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/gollum-lib/markup.rb', line 503

def extract_remote_code data
  data.gsub /^[ \t]*``` ?([^:\n\r]+):((http)?[^`\n\r]+)```/ do
    language = $1
    uri = $2
    protocol = $3

    # Detect local file
    if protocol.nil?
      if file = self.find_file(uri, @wiki.ref)
        contents = file.raw_data
      else
        # How do we communicate a render error?
        next "File not found: #{CGI::escapeHTML(uri)}"
      end
    else
      contents = Gollum::RemoteCode.new(uri).contents
    end

    "```#{language}\n#{contents}\n```\n"
  end
end

#extract_tags(data) ⇒ Object

Extract all tags into the tagmap and replace with placeholders.

data - The raw String data.

Returns the placeholder’d String data.



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/gollum-lib/markup.rb', line 169

def extract_tags(data)
  if @format == :asciidoc
    return data
  end
  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

#extract_wsd(data) ⇒ Object

Extract all sequence diagram blocks into the wsdmap and replace with placeholders.

data - The raw String data.

Returns the placeholder’d String data.



656
657
658
659
660
661
662
# File 'lib/gollum-lib/markup.rb', line 656

def extract_wsd(data)
  data.gsub(/^\{\{\{\{\{\{ ?(.+?)\r?\n(.+?)\r?\n\}\}\}\}\}\}\r?$/m) do
    id = Digest::SHA1.hexdigest($2)
    @wsdmap[id] = { :style => $1, :code => $2 }
    id
  end
end

#find_file(name, version = @version) ⇒ Object

Find the given file in the repo.

name - The String absolute or relative path of the file.

Returns the Gollum::File or nil if none was found.



456
457
458
459
460
461
462
463
# File 'lib/gollum-lib/markup.rb', line 456

def find_file(name, version=@version)
  if name =~ /^\//
    @wiki.file(name[1..-1], version)
  else
    path = @dir == '.' ? name : ::File.join(@dir, name)
    @wiki.file(path, version)
  end
end

#find_page_from_name(cname) ⇒ Object

Find a page from a given cname. If the page has an anchor (#) and has no match, strip the anchor and try again.

cname - The String canonical page name including path.

Returns a Gollum::Page instance if a page is found, or an Array of

Gollum::Page, String extra

if a page without the extra anchor data

is found.



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/gollum-lib/markup.rb', line 473

def find_page_from_name(cname)
  slash = cname.rindex('/')

  unless slash.nil?
    name = cname[slash+1..-1]
    path = cname[0..slash]
    page = @wiki.paged(name, path)
  else
    page = @wiki.paged(cname, '/') || @wiki.page(cname)
  end

  if page
    return page
  end
  if pos = cname.index('#')
    [@wiki.page(cname[0...pos]), cname[pos..-1]]
  end
end

#html_error(message) ⇒ Object

Render a (presumably) non-fatal error as HTML



257
258
259
# File 'lib/gollum-lib/markup.rb', line 257

def html_error(message)
  "<p class=\"gollum-error\">#{message}</p>"
end

#is_preformatted?(data, id) ⇒ Boolean

Returns:

  • (Boolean)


226
227
228
229
230
231
# File 'lib/gollum-lib/markup.rb', line 226

def is_preformatted?(data, id)
  doc = Nokogiri::HTML::DocumentFragment.parse(data)
  node = doc.search("[text()*='#{id}']").first
  node && (PREFORMATTED_TAGS.include?(node.name) ||
    node.ancestors.any? { |a| PREFORMATTED_TAGS.include?(a.name) })
end

#parse_image_tag_options(tag) ⇒ Object

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

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

Returns the options Hash:

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


365
366
367
368
369
370
371
# File 'lib/gollum-lib/markup.rb', line 365

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, encoding = nil) ⇒ Object

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

data - The String data (with placeholders). encoding - Encoding Constant or String.

Returns the marked up String data.



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/gollum-lib/markup.rb', line 599

def process_code(data, encoding = nil)
  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]

    remove_leading_space(code, /^#{spec[:indent]}/m)
    remove_leading_space(code, /^(  |\t)/m)

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

  highlighted = []
  blocks.each do |lang, code|
    encoding ||= 'utf-8'
    begin
      # must set startinline to true for php to be highlighted without <?
      # http://pygments.org/docs/lexers/
      hl_code = Pygments.highlight(code, :lexer => lang, :options => {:encoding => encoding.to_s, :startinline => true})
    rescue
      hl_code = code
    end
    highlighted << hl_code
  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) do
      body
    end
  end

  data
end

Attempt to process the tag as a file link tag.

tag - The String tag contents (the stuff inside the double

brackets).

Returns the String HTML if the tag is a valid file link tag or nil

if it is not.


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/gollum-lib/markup.rb', line 380

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

  name  = parts[0].strip
  path  = parts[1] && parts[1].strip
  path  = if path && file = find_file(path)
    ::File.join @wiki.base_path, file.path
  elsif path =~ %r{^https?://}
    path
  else
    nil
  end

  if name && path && file
    %{<a href="#{::File.join @wiki.base_path, file.path}">#{name}</a>}
  elsif name && path
    %{<a href="#{path}">#{name}</a>}
  else
    nil
  end
end

#process_headers(doc) ⇒ Object

Inserts header anchors and creates TOC

doc - Nokogiri parsed document

Returns doc Document and toc String



124
125
126
127
128
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
# File 'lib/gollum-lib/markup.rb', line 124

def process_headers(doc)
  toc = nil
  doc.css('h1,h2,h3,h4,h5,h6').each do |h|
    # must escape "
    h_name = h.content.gsub(' ','-').gsub('"','%22')

    level = h.name.gsub(/[hH]/,'').to_i

    # Add anchors
    h.add_child(%Q{<a class="anchor" id="#{h_name}" href="##{h_name}"></a>})

    # Build TOC
    toc ||= Nokogiri::XML::DocumentFragment.parse('<div class="toc"><div class="toc-title">Table of Contents</div></div>')
    tail ||= toc.child
    tail_level ||= 0

    while tail_level < level
      node = Nokogiri::XML::Node.new('ul', doc)
      tail = tail.add_child(node)
      tail_level += 1
    end
    while tail_level > level
      tail = tail.parent
      tail_level -= 1
    end
    node = Nokogiri::XML::Node.new('li', doc)
    # % -> %25 so anchors work on Firefox. See issue #475
    node.add_child(%Q{<a href="##{h_name}">#{h.content}</a>})
    tail.add_child(node)
  end
  toc = toc.to_xml(@to_xml) if toc != nil
  [doc, toc]
end

#process_image_tag(tag) ⇒ Object

Attempt to process the tag as an image tag.

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

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

if it is not.


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/gollum-lib/markup.rb', line 290

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

  name  = parts[0].strip
  path  = if file = find_file(name)
    ::File.join @wiki.base_path, file.path
  elsif name =~ /^https?:\/\/.+(jpg|png|gif|svg|bmp)$/i
    name
  end

  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_include_tag(tag) ⇒ Object

Attempt to process the tag as an include tag

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

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

if it is not.


268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/gollum-lib/markup.rb', line 268

def process_include_tag(tag)
  return unless /^include:/.match(tag)
  page_name = tag[8..-1]

  if @include_levels > 0
    page = @wiki.page(page_name)
    if page
      page.formatted_data(@encoding, @include_levels-1)
    else
      html_error("Cannot include #{process_page_link_tag(page_name)} - does not exist yet")
    end
  else
    html_error("Too many levels of included pages, will not include #{process_page_link_tag(page_name)}")
  end
end

Attempt to process the tag as a page link tag.

tag - The String tag contents (the stuff inside the double

brackets).

Returns the String HTML if the tag is a valid page link tag or nil

if it is not.


410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/gollum-lib/markup.rb', line 410

def process_page_link_tag(tag)
  parts = tag.split('|')
  parts.reverse! if @format == :mediawiki

  name, page_name = *parts.compact.map(&:strip)
  cname = @wiki.page_class.cname(page_name || name)

  if name =~ %r{^https?://} && page_name.nil?
    %{<a href="#{name}">#{name}</a>}
  else
    presence    = "absent"
    link_name   = cname
    page, extra = find_page_from_name(cname)
    if page
      link_name = @wiki.page_class.cname(page.name)
      presence  = "present"
    end
    link = ::File.join(@wiki.base_path, page ? page.escaped_url_path : CGI.escape(link_name))

    # //page is invalid
    # strip all duplicate forward slashes using helpers.rb trim_leading_slash
    # //page => /page
    link = trim_leading_slash link

    %{<a class="internal #{presence}" href="#{link}#{extra}">#{name}</a>}
  end
end

#process_tag(tag) ⇒ Object

Process a single tag into its final HTML form.

tag - The String tag contents (the stuff inside the double

brackets).

Returns the String HTML version of the tag.



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/gollum-lib/markup.rb', line 239

def process_tag(tag)
  if tag =~ /^_TOC_$/
    %{[[#{tag}]]}
  elsif tag =~ /^_$/
    %{<div class="clearfloats"></div>}
  elsif html = process_include_tag(tag)
    html
  elsif html = process_image_tag(tag)
    html
  elsif html = process_file_link_tag(tag)
    html
  else
    process_page_link_tag(tag)
  end
end

#process_tags(data) ⇒ Object

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

data - The String data (with placeholders).

Returns the marked up String data.



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/gollum-lib/markup.rb', line 204

def process_tags(data)
  @tagmap.each do |id, tag|
    # If it's preformatted, just put the tag back
    if is_preformatted?(data, id)
      data.gsub!(id) do
        "[[#{tag}]]"
      end
    else
      data.gsub!(id) do
        process_tag(tag).gsub('%2F', '/')
      end
    end
  end
  data
end

#process_toc_tags(data) ⇒ Object

Process the special table of contents tag [[TOC]]

data - The String data (with placeholders).

Returns the marked up String data.



444
445
446
447
448
449
# File 'lib/gollum-lib/markup.rb', line 444

def process_toc_tags(data)
  data.gsub!("[[_TOC_]]") do
    @toc.nil? ? '' : @toc
  end
  data
end

#process_wsd(data) ⇒ Object

Process all diagrams from the wsdmap and replace the placeholders with the final HTML.

data - The String data (with placeholders).

Returns the marked up String data.



670
671
672
673
674
675
676
677
678
679
# File 'lib/gollum-lib/markup.rb', line 670

def process_wsd(data)
  @wsdmap.each do |id, spec|
    style = spec[:style]
    code = spec[:code]
    data.gsub!(id) do
      Gollum::WebSequenceDiagram.new(code, style).to_tag
    end
  end
  data
end

#remove_leading_space(code, regex) ⇒ Object

Remove the leading space from a code block. Leading space is only removed if every single line in the block has leading whitespace.

code - The code block to remove spaces from regex - A regex to match whitespace



584
585
586
587
588
589
590
# File 'lib/gollum-lib/markup.rb', line 584

def remove_leading_space(code, regex)
  if code.lines.all? { |line| line =~ /\A\r?\n\Z/ || line =~ regex }
    code.gsub!(regex) do
      ''
    end
  end
end

#render(no_follow = false, encoding = nil, include_levels = 10) {|doc| ... } ⇒ Object

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

no_follow - Boolean that determines if rel=“nofollow” is added to all

<a> tags.

encoding - Encoding Constant or String.

Returns the formatted String content.

Yields:

  • (doc)


74
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/gollum-lib/markup.rb', line 74

def render(no_follow = false, encoding = nil, include_levels = 10)
  sanitize = no_follow ?
    @wiki.history_sanitizer :
    @wiki.sanitizer
    
  @encoding = encoding
  @include_levels = include_levels

  data = @data.dup
  data = (data)
  data = extract_remote_code(data)
  data = extract_code(data)
  data = extract_wsd(data)
  data = extract_tags(data)
  begin
    data = GitHub::Markup.render(@name, data)
    if data.nil?
      raise "There was an error converting #{@name} to HTML."
    end
  rescue Object => e
    data = html_error(e.message)
  end
  data = process_tags(data)
  data = process_code(data, encoding)

  doc = Nokogiri::HTML::DocumentFragment.parse(data)
  doc = sanitize.clean_node!(doc) if sanitize
  doc,toc = process_headers(doc)
  @toc = @sub_page ? ( @parent_page ? @parent_page.toc_data : "[[_TOC_]]" ) : toc
  yield doc if block_given?
  # nokogiri's save options are ored together. FORMAT has a value of 1 so ^ 1 removes it.
  # formatting will create extra spaces in pre tags.
  # https://github.com/sparklemotion/nokogiri/issues/782
  # DEFAULT_HTML encodes unicode so XHTML is used for proper unicode support in href.
  data = doc.to_xml( @to_xml )

  data = process_toc_tags(data)
  data = process_wsd(data)
  data.gsub!(/<p><\/p>/) do
    ''
  end

  data
end

#update_cache(type, id, data) ⇒ Object

Hook for caching the formatted value of extracted tag data.

type - Symbol value identifying what type of data is being extracted. id - String SHA1 hash of original extracted tag data. data - The String formatted value to be cached.

Returns nothing.



729
730
# File 'lib/gollum-lib/markup.rb', line 729

def update_cache(type, id, data)
end