Class: Kramdown::Parser::BeanKramdown

Inherits:
Kramdown show all
Defined in:
lib/kramdown/parser/bean_kramdown.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}% ?/

Constants inherited from Kramdown

Kramdown::ABBREV_DEFINITION_START, Kramdown::ACHARS, Kramdown::ALD_ANY_CHARS, Kramdown::ALD_ID_CHARS, Kramdown::ALD_ID_NAME, Kramdown::ALD_START, Kramdown::ALD_TYPE_ANY, Kramdown::ALD_TYPE_CLASS_NAME, Kramdown::ALD_TYPE_ID_NAME, Kramdown::ALD_TYPE_KEY_VALUE_PAIR, Kramdown::ALD_TYPE_REF, Kramdown::ATX_HEADER_MATCH, Kramdown::ATX_HEADER_START, Kramdown::AUTOLINK_START, Kramdown::AUTOLINK_START_STR, Kramdown::BLANK_LINE, Kramdown::BLOCKQUOTE_START, Kramdown::BLOCK_BOUNDARY, Kramdown::BLOCK_EXTENSIONS_START, Kramdown::BLOCK_MATH_START, Kramdown::CODEBLOCK_MATCH, Kramdown::CODEBLOCK_START, Kramdown::CODESPAN_DELIMITER, Kramdown::DEFINITION_LIST_START, Kramdown::EMPHASIS_START, Kramdown::EOB_MARKER, Kramdown::ESCAPED_CHARS, Kramdown::EXT_BLOCK_START, Kramdown::EXT_BLOCK_STOP_STR, Kramdown::EXT_SPAN_START, Kramdown::EXT_START_STR, Kramdown::EXT_STOP_STR, Kramdown::FENCED_CODEBLOCK_MATCH, Kramdown::FENCED_CODEBLOCK_START, Kramdown::FOOTNOTE_DEFINITION_START, Kramdown::FOOTNOTE_MARKER_START, Kramdown::HEADER_ID, Kramdown::HR_START, Kramdown::HTML_BLOCK_START, Kramdown::HTML_MARKDOWN_ATTR_MAP, Kramdown::HTML_SPAN_START, Kramdown::IAL_BLOCK, Kramdown::IAL_BLOCK_START, Kramdown::IAL_CLASS_ATTR, Kramdown::IAL_SPAN_START, Kramdown::IMAGE_BRACKET_STOP_RE, Kramdown::IMAGE_DEFINITION_START, Kramdown::IMAGE_INLINE_ID_RE, Kramdown::IMAGE_INLINE_TITLE_RE, Kramdown::IMAGE_PAREN_STOP_RE, Kramdown::IMAGE_START, Kramdown::INLINE_MATH_START, Kramdown::LAZY_END, Kramdown::LAZY_END_HTML_SPAN_ELEMENTS, Kramdown::LAZY_END_HTML_START, Kramdown::LAZY_END_HTML_STOP, Kramdown::LINE_BREAK, Kramdown::LINK_BRACKET_STOP_RE, Kramdown::LINK_DEFINITION_START, Kramdown::LINK_INLINE_ID_RE, Kramdown::LINK_INLINE_TITLE_RE, Kramdown::LINK_PAREN_STOP_RE, Kramdown::LINK_START, Kramdown::LIST_ITEM_IAL, Kramdown::LIST_ITEM_IAL_CHECK, Kramdown::LIST_START, Kramdown::LIST_START_OL, Kramdown::LIST_START_UL, Kramdown::PARAGRAPH_END, Kramdown::PARAGRAPH_MATCH, Kramdown::PARAGRAPH_START, Kramdown::SETEXT_HEADER_START, Kramdown::SMART_QUOTES_RE, Kramdown::SPAN_EXTENSIONS_START, Kramdown::SQ_CLOSE, Kramdown::SQ_PUNCT, Kramdown::SQ_RULES, Kramdown::SQ_SUBSTS, Kramdown::TABLE_FSEP_LINE, Kramdown::TABLE_HSEP_ALIGN, Kramdown::TABLE_LINE, Kramdown::TABLE_PIPE_CHECK, Kramdown::TABLE_ROW_LINE, Kramdown::TABLE_SEP_LINE, Kramdown::TABLE_START, Kramdown::TRAILING_WHITESPACE, Kramdown::TYPOGRAPHIC_SYMS, Kramdown::TYPOGRAPHIC_SYMS_RE, Kramdown::TYPOGRAPHIC_SYMS_SUBST

Constants included from Html::Parser

Html::Parser::HTML_RAW_START

Constants included from Html::Constants

Html::Constants::HTML_ATTRIBUTE_RE, Html::Constants::HTML_BLOCK_ELEMENTS, Html::Constants::HTML_COMMENT_RE, Html::Constants::HTML_CONTENT_MODEL, Html::Constants::HTML_CONTENT_MODEL_BLOCK, Html::Constants::HTML_CONTENT_MODEL_RAW, Html::Constants::HTML_CONTENT_MODEL_SPAN, Html::Constants::HTML_DOCTYPE_RE, Html::Constants::HTML_ELEMENTS_WITHOUT_BODY, Html::Constants::HTML_ENTITY_RE, Html::Constants::HTML_INSTRUCTION_RE, Html::Constants::HTML_SPAN_ELEMENTS, Html::Constants::HTML_TAG_CLOSE_RE, Html::Constants::HTML_TAG_RE

Constants included from Kramdown

VERSION

Instance Attribute Summary

Attributes inherited from Base

#options, #root, #source, #warnings

Instance Method Summary collapse

Methods inherited from Kramdown

#add_link, #after_block_boundary?, #before_block_boundary?, #handle_extension, #handle_kramdown_html_tag, #normalize_link_id, #parse, #parse_abbrev_definition, #parse_attribute_list, #parse_atx_header, #parse_autolink, #parse_blank_line, #parse_block_extensions, #parse_block_html, #parse_block_math, #parse_blockquote, #parse_codeblock, #parse_codeblock_fenced, #parse_codespan, #parse_definition_list, #parse_emphasis, #parse_eob_marker, #parse_escaped_chars, #parse_extension_start_tag, #parse_first_list_line, #parse_footnote_definition, #parse_footnote_marker, #parse_horizontal_rule, #parse_html_entity, #parse_image, #parse_image_definition, #parse_inline_math, #parse_line_break, #parse_link, #parse_link_definition, #parse_list, #parse_paragraph, #parse_setext_header, #parse_smart_quotes, #parse_span_extensions, #parse_span_html, #parse_table, #parse_typographic_syms, #replace_abbreviations, #update_ial_with_ial

Methods included from Html::Parser

#handle_html_start_tag, #handle_raw_html_tag, #parse_raw_html

Methods included from Kramdown

data_dir

Methods inherited from Base

#adapt_source, #add_text, #extract_string, #parse, parse, #warning

Constructor Details

#initialize(source, options) ⇒ BeanKramdown

initialise new parsers



11
12
13
14
15
16
17
18
19
# File 'lib/kramdown/parser/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/parser/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/parser/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/parser/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/parser/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/parser/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