Class: Kramdown::Parser::BeanKramdown

Inherits:
Kramdown
  • Object
show all
Defined in:
lib/kramdown/bean_kramdown.rb,
lib/kramdown/bean_kramdown/oembed.rb,
lib/kramdown/bean_kramdown/info_box.rb,
lib/kramdown/parser/bean_kramdown/oembed.rb,
lib/kramdown/parser/bean_kramdown/info_box.rb

Constant Summary collapse

EXCEPT =

Array with all the parsing methods that should be removed from the standard kramdown parser.

[:codeblock_fenced, :block_extensions, :span_extensions]
OEMBED_DEFINITION_START =
/^#{OPT_SPACE}\[([^\n\]]+)\]:[ \t]*(?:<(.*?)>|([^'"\n]*?\S[^'"\n]*?))[ \t]*?(?:\n?[ \t]*?(["'])(.+?)\4[ \t]*?)?\n/
OEMBED_BRACKET_STOP_RE =
/(\])|!?\[/
OEMBED_PAREN_STOP_RE =
/(\()|(\))|\s(?=['"])/
OEMBED_INLINE_ID_RE =
/\s*?\[([^\]]+)?\]/
OEMBED_INLINE_TITLE_RE =
/\s*?(["'])(.+?)\1\s*?\)/
OEMBED_START =
/\?\[(?=[^^])/
INFO_BOX_START =
/^#{OPT_SPACE}% ?/

Instance Method Summary collapse

Constructor Details

#initialize(source, options) ⇒ BeanKramdown

initialise new parsers



11
12
13
14
15
16
17
18
19
# File 'lib/kramdown/bean_kramdown.rb', line 11

def initialize(source, options)
  super
  
  @block_parsers.unshift(:info_box)
  @span_parsers.unshift(:oembed)
  
  @block_parsers.delete_if {|i| EXCEPT.include?(i)}
  @span_parsers.delete_if {|i| EXCEPT.include?(i)}
end

Instance Method Details

#add_oembed(el, href, title, alt_text = nil) ⇒ Object

This helper methods adds the approriate attributes to the element el of type a or img and the element itself to the @tree.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/kramdown/bean_kramdown/oembed.rb', line 59

def add_oembed(el, href, title, alt_text = nil)
  
  providers = {
    :twitter         => "https://api.twitter.com/1/statuses/oembed.json?url=%s",
    :youtube         => "http://www.youtube.com/oembed?url=%s&format=json&maxwidth=550",
    :flickr          => "http://flickr.com/services/oembed?url=%s&maxwidth=460&format=json&maxwidth=550",
    :vidler          => "http://lab.viddler.com/services/oembed/?url=%s&type=simple&format=json",
    :qik             => "http://qik.com/api/oembed.json?url=%s&maxwidth=550",
    :revision3       => "http://revision3.com/api/oembed/?url=%s&format=json&maxwidth=550",
    :hulu            => "http://www.hulu.com/api/oembed.json?url=%s&maxwidth=550",
    :vimeo           => "http://vimeo.com/api/oembed.json?url=%s&maxwidth=550",
    :collegehumor    => "http://www.collegehumor.com/oembed.json?url=%s&maxwidth=550",
    # :pollyeverywhere => "http://www.polleverywhere.com/services/oembed?url=%s&format=json",
    # :opera           => "http://my.opera.com/service/oembed/?url=%s",
    :embedly         => "http://api.embed.ly/1/oembed?url=%w&maxwidth=550",
    :ifixit          => "http://www.ifixit.com/Embed?url=%s&format=json",
    :smugmug         => "http://api.smugmug.com/services/oembed/?url=%s&format=json",
    :slideshare      => "http://www.slideshare.net/api/oembed/2?url=%s&format=json&maxwidth=550",
    :wordpress       => "http://public-api.wordpress.com/oembed/1.0/?format=json&url=%s&maxwidth=550"
  }
  # ready the hash for matching
  provider_names = (providers.keys.each { |name| name.to_s }).join('|')
  # match possible providers to see if we have a provider suitable for embedding the current href/url 
  result = href.match provider_names
  if result and result[0]
    safe_href = CGI.escape(href)
    provider = result[0].to_sym
    oembed_url = providers[provider] % safe_href
    # unique figure id
    fig_id = rand(1000)
    # oembed 
    el = Element.new :oembed
    begin
      # get the oEmbed content
      result = JSON.parse(open(oembed_url).read)
      el.attr['provider_name'] = result['provider_name']
      case result['type']
      when "photo"
        title = result['title']
        el.attr['role'] = "img"
        img = Element.new(:img)
        img.attr['src'] = result['url']
        img.attr['alt'] = result['title']
        img.attr['width'] = result['width']
        img.attr['height'] = result['height']
        img.children.clear
        el.children << img
      when "video"
        title = result['title']
        el.attr['html'] = CGI.unescapeHTML(result['html'])
      when "rich"
        el.attr['html'] = CGI.unescapeHTML(result['html'])
      end
      
    if title
      # unique figure id
      el_id = rand(1000)
      el.attr['id'] = el_id
      cap = Element.new(:figCaption, title)
      cap.attr['id'] = el_id
      if el.attr['role'] === "img"
        link = Element.new(:a, result['author_name'])
        link.attr['href'] = result['author_url']
        cap.children << link
      end
      el.children << cap 
    end
    @tree.children << el
      
    rescue
      warning("Could not retrieve oEmbed information for URL #{oembed_url}")
    end
  else
    warning("No oEmbed provider found for URL #{href}")
  end
  
  
  
  # if el.type == :a
  #   el.attr['href'] = href
  # else
  #   el.attr['src'] = href
  #   el.attr['alt'] = alt_text
  #   el.children.clear
  # end
  # el.attr['title'] = title if title
  # @tree.children << el
end

#normalize_oembed_id(id) ⇒ Object

Normalize the oembed identifier.



39
40
41
# File 'lib/kramdown/bean_kramdown/oembed.rb', line 39

def normalize_oembed_id(id)
  id.gsub(/(\s|\n)+/, ' ').downcase
end

#parse_info_boxObject

Parse the info box at the current location.



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/kramdown/bean_kramdown/info_box.rb', line 34

def parse_info_box
  result = @src.scan(PARAGRAPH_MATCH)
  while !@src.match?(self.class::LAZY_END)
    result << @src.scan(PARAGRAPH_MATCH)
  end
  result.gsub!(INFO_BOX_START, '')

  el = new_block_el(:info_box)
  @tree.children << el
  parse_blocks(el, result)
  true
end

#parse_oembedObject

Parse the oembed at the current scanner position. This method is used to parse normal oembeds as well as image oembeds.



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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/kramdown/bean_kramdown/oembed.rb', line 156

def parse_oembed
  result = @src.scan(OEMBED_START)
  reset_pos = @src.pos
  oembed_type = :img

  el = Element.new(oembed_type)

  count = 1
  found = parse_spans(el, OEMBED_BRACKET_STOP_RE) do
    count = count + (@src[1] ? -1 : 1)
    count - el.children.select {|c| c.type == :img}.size == 0
  end
  if !found || (oembed_type == :a && el.children.empty?)
    @src.pos = reset_pos
    add_text(result)
    return
  end
  alt_text = extract_string(reset_pos...@src.pos, @src)
  @src.scan(OEMBED_BRACKET_STOP_RE)

  # reference style oembed or no oembed url
  if @src.scan(OEMBED_INLINE_ID_RE) || !@src.check(/\(/)
    oembed_id = normalize_oembed_id(@src[1] || alt_text)
    if @oembed_defs.has_key?(oembed_id)
      add_oembed(el, @oembed_defs[oembed_id].first, @oembed_defs[oembed_id].last, alt_text)
    else
      warning("No oembed definition for oembed ID '#{oembed_id}' found")
      @src.pos = reset_pos
      add_text(result)
    end
    return
  end

  # oembed url in parentheses
  if @src.scan(/\(<(.*?)>/)
    oembed_url = @src[1]
    if @src.scan(/\)/)
      add_oembed(el, oembed_url, nil, alt_text)
      return
    end
  else
    oembed_url = ''
    nr_of_brackets = 0
    while temp = @src.scan_until(OEMBED_PAREN_STOP_RE)
      oembed_url << temp
      if @src[2]
        nr_of_brackets -= 1
        break if nr_of_brackets == 0
      elsif @src[1]
        nr_of_brackets += 1
      else
        break
      end
    end
    oembed_url = oembed_url[1..-2]
    oembed_url.strip!

    if nr_of_brackets == 0
      add_oembed(el, oembed_url, nil, alt_text)
      return
    end
  end

  if @src.scan(OEMBED_INLINE_TITLE_RE)
    add_oembed(el, oembed_url, @src[2], alt_text)
  else
    @src.pos = reset_pos
    add_text(result)
  end
end

#parse_oembed_definitionObject

Parse the oembed definition at the current location.



46
47
48
49
50
51
52
53
# File 'lib/kramdown/bean_kramdown/oembed.rb', line 46

def parse_oembed_definition
  @src.pos += @src.matched_size
  oembed_id, oembed_url, oembed_title = normalize_oembed_id(@src[1]), @src[2] || @src[3], @src[5]
  warning("Duplicate oembed ID '#{oembed_id}' - overwriting") if @oembed_defs[oembed_id]
  @oembed_defs[oembed_id] = [oembed_url, oembed_title]
  @tree.children << Element.new(:eob, :oembed_def)
  true
end