kramdown 0.7.0 → 0.8.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of kramdown might be problematic. Click here for more details.

Files changed (93) hide show
  1. data/CONTRIBUTERS +4 -0
  2. data/ChangeLog +671 -0
  3. data/README +10 -0
  4. data/Rakefile +40 -23
  5. data/VERSION +1 -1
  6. data/data/kramdown/document.html +1 -1
  7. data/data/kramdown/document.latex +10 -5
  8. data/doc/default.less.css +52 -10
  9. data/doc/default.template +4 -0
  10. data/doc/documentation.page +72 -0
  11. data/doc/index.page +8 -41
  12. data/doc/installation.page +6 -6
  13. data/doc/links.markdown +2 -0
  14. data/doc/quickref.page +6 -2
  15. data/doc/syntax.page +8 -7
  16. data/doc/tests.page +1 -2
  17. data/lib/kramdown.rb +1 -1
  18. data/lib/kramdown/compatibility.rb +1 -1
  19. data/lib/kramdown/converter.rb +8 -3
  20. data/lib/kramdown/converter/base.rb +27 -5
  21. data/lib/kramdown/converter/html.rb +26 -28
  22. data/lib/kramdown/converter/latex.rb +29 -15
  23. data/lib/kramdown/document.rb +15 -8
  24. data/lib/kramdown/error.rb +1 -1
  25. data/lib/kramdown/options.rb +21 -13
  26. data/lib/kramdown/parser.rb +9 -3
  27. data/lib/kramdown/parser/base.rb +95 -0
  28. data/lib/kramdown/parser/html.rb +387 -0
  29. data/lib/kramdown/parser/kramdown.rb +11 -56
  30. data/lib/kramdown/parser/kramdown/attribute_list.rb +1 -1
  31. data/lib/kramdown/parser/kramdown/autolink.rb +1 -1
  32. data/lib/kramdown/parser/kramdown/blank_line.rb +1 -1
  33. data/lib/kramdown/parser/kramdown/blockquote.rb +1 -1
  34. data/lib/kramdown/parser/kramdown/codeblock.rb +1 -1
  35. data/lib/kramdown/parser/kramdown/codespan.rb +1 -1
  36. data/lib/kramdown/parser/kramdown/emphasis.rb +1 -1
  37. data/lib/kramdown/parser/kramdown/eob.rb +1 -1
  38. data/lib/kramdown/parser/kramdown/escaped_chars.rb +1 -1
  39. data/lib/kramdown/parser/kramdown/extension.rb +2 -90
  40. data/lib/kramdown/parser/kramdown/footnote.rb +1 -1
  41. data/lib/kramdown/parser/kramdown/header.rb +1 -1
  42. data/lib/kramdown/parser/kramdown/horizontal_rule.rb +1 -1
  43. data/lib/kramdown/parser/kramdown/html.rb +69 -149
  44. data/lib/kramdown/parser/kramdown/html_entity.rb +4 -4
  45. data/lib/kramdown/parser/kramdown/line_break.rb +1 -1
  46. data/lib/kramdown/parser/kramdown/link.rb +2 -2
  47. data/lib/kramdown/parser/kramdown/list.rb +2 -6
  48. data/lib/kramdown/parser/kramdown/math.rb +3 -3
  49. data/lib/kramdown/parser/kramdown/paragraph.rb +1 -1
  50. data/lib/kramdown/parser/kramdown/smart_quotes.rb +3 -2
  51. data/lib/kramdown/parser/kramdown/table.rb +3 -2
  52. data/lib/kramdown/parser/kramdown/typographic_symbol.rb +7 -3
  53. data/lib/kramdown/version.rb +2 -2
  54. data/man/man1/kramdown.1 +19 -0
  55. data/test/run_tests.rb +1 -0
  56. data/test/test_files.rb +68 -7
  57. data/test/testcases/block/09_html/comment.html +5 -0
  58. data/test/testcases/block/09_html/comment.text +3 -0
  59. data/test/testcases/block/09_html/content_model/tables.html +2 -2
  60. data/test/testcases/block/09_html/html_to_native/code.html +10 -0
  61. data/test/testcases/block/09_html/html_to_native/code.text +9 -0
  62. data/test/testcases/block/09_html/html_to_native/comment.html +7 -0
  63. data/test/testcases/block/09_html/html_to_native/comment.text +8 -0
  64. data/test/testcases/block/09_html/html_to_native/emphasis.html +1 -0
  65. data/test/testcases/block/09_html/html_to_native/emphasis.text +1 -0
  66. data/test/testcases/block/09_html/html_to_native/entity.html +1 -0
  67. data/test/testcases/block/09_html/html_to_native/entity.text +1 -0
  68. data/test/testcases/block/09_html/html_to_native/header.html +6 -0
  69. data/test/testcases/block/09_html/html_to_native/header.options +2 -0
  70. data/test/testcases/block/09_html/html_to_native/header.text +6 -0
  71. data/test/testcases/block/09_html/html_to_native/list_dl.html +8 -0
  72. data/test/testcases/block/09_html/html_to_native/list_dl.text +8 -0
  73. data/test/testcases/block/09_html/html_to_native/list_ol.html +15 -0
  74. data/test/testcases/block/09_html/html_to_native/list_ol.text +17 -0
  75. data/test/testcases/block/09_html/html_to_native/list_ul.html +19 -0
  76. data/test/testcases/block/09_html/html_to_native/list_ul.text +22 -0
  77. data/test/testcases/block/09_html/html_to_native/options +1 -0
  78. data/test/testcases/block/09_html/html_to_native/paragraph.html +3 -0
  79. data/test/testcases/block/09_html/html_to_native/paragraph.text +4 -0
  80. data/test/testcases/block/09_html/html_to_native/table_normal.html +13 -0
  81. data/test/testcases/block/09_html/html_to_native/table_normal.text +12 -0
  82. data/test/testcases/block/09_html/html_to_native/table_simple.html +10 -0
  83. data/test/testcases/block/09_html/html_to_native/table_simple.text +14 -0
  84. data/test/testcases/block/09_html/html_to_native/typography.html +1 -0
  85. data/test/testcases/block/09_html/html_to_native/typography.text +1 -0
  86. data/test/testcases/block/09_html/parse_as_raw.html +3 -5
  87. data/test/testcases/block/09_html/parse_as_raw.text +0 -1
  88. data/test/testcases/span/04_footnote/definitions.latex +18 -0
  89. data/test/testcases/span/04_footnote/footnote_nr.latex +6 -0
  90. data/test/testcases/span/04_footnote/markers.latex +32 -0
  91. data/test/testcases/span/05_html/invalid.html +1 -0
  92. data/test/testcases/span/05_html/invalid.text +1 -0
  93. metadata +52 -5
@@ -1,7 +1,7 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  #
3
3
  #--
4
- # Copyright (C) 2009 Thomas Leitner <t_leitner@gmx.at>
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
5
  #
6
6
  # This file is part of kramdown.
7
7
  #
@@ -69,7 +69,8 @@ module Kramdown
69
69
  # #new) and the conversion phase.
70
70
  attr_reader :warnings
71
71
 
72
- # Holds needed parse information like ALDs, link definitions and so on.
72
+ # Holds needed parse information which is dependent on the used parser, like ALDs, link
73
+ # definitions and so on. This information may be used by converters afterwards.
73
74
  attr_reader :parse_infos
74
75
 
75
76
  # Holds conversion information which is dependent on the used converter. A converter clears this
@@ -77,15 +78,16 @@ module Kramdown
77
78
  attr_reader :conversion_infos
78
79
 
79
80
 
80
- # Create a new Kramdown document from the string +source+ and use the provided +options+.
81
+ # Create a new Kramdown document from the string +source+ and use the provided +options+. The
82
+ # options that can be used are defined in the Options module.
81
83
  #
82
84
  # The special options key <tt>:input</tt> can be used to select the parser that should parse the
83
85
  # +source+. It has to be the name of a class in the Kramdown::Parser module. For example, to
84
86
  # select the kramdown parser, one would set the <tt>:input</tt> key to +Kramdown+. If this key
85
87
  # is not set, it defaults to +Kramdown+.
86
88
  #
87
- # The +source+ is immediately parsed by the selected parser so that after this call the document
88
- # tree is available and the output can be generated.
89
+ # The +source+ is immediately parsed by the selected parser so that the document tree is
90
+ # immediately available and the output can be generated.
89
91
  def initialize(source, options = {})
90
92
  @options = Options.merge(options)
91
93
  @warnings = []
@@ -106,7 +108,7 @@ module Kramdown
106
108
  # For example, +to_html+ would instantiate the Kramdown::Converter::Html class.
107
109
  def method_missing(id, *attr, &block)
108
110
  if id.to_s =~ /^to_(\w+)$/
109
- Converter.const_get($1.capitalize).convert(self)
111
+ Converter.const_get($1[0..0].upcase + $1[1..-1]).convert(self)
110
112
  else
111
113
  super
112
114
  end
@@ -125,7 +127,7 @@ module Kramdown
125
127
  # (paragraphs, headers, emphasis, ...). The type of element can be set via the #type accessor.
126
128
  class Element
127
129
 
128
- # A symbol representing the element type. For example, +:p+ or +:blockquote+.
130
+ # A symbol representing the element type. For example, <tt>:p</tt> or <tt>:blockquote</tt>.
129
131
  attr_accessor :type
130
132
 
131
133
  # The value of the element. The interpretation of this field depends on the type of the element.
@@ -133,7 +135,12 @@ module Kramdown
133
135
  attr_accessor :value
134
136
 
135
137
  # The options hash for the element. It is used for storing arbitray options as well as the
136
- # *attributes* of the element under the <tt>:attr</tt> key.
138
+ # following special contents:
139
+ #
140
+ # - *Attributes* of the element under the <tt>:attr</tt> key
141
+ # - Category of the element, either <tt>:block</tt> or <tt>:span</tt>, under the
142
+ # <tt>:category</tt> key. If this key is absent, it can be assumed that the element is in the
143
+ # <tt>:span</tt> category.
137
144
  attr_accessor :options
138
145
 
139
146
  # The child elements of this element.
@@ -1,7 +1,7 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  #
3
3
  #--
4
- # Copyright (C) 2009 Thomas Leitner <t_leitner@gmx.at>
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
5
  #
6
6
  # This file is part of kramdown.
7
7
  #
@@ -1,7 +1,7 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  #
3
3
  #--
4
- # Copyright (C) 2009 Thomas Leitner <t_leitner@gmx.at>
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
5
  #
6
6
  # This file is part of kramdown.
7
7
  #
@@ -22,7 +22,8 @@
22
22
 
23
23
  module Kramdown
24
24
 
25
- # This module defines all options that are used by parsers and/or converters.
25
+ # This module defines all options that are used by parsers and/or converters as well as providing
26
+ # methods to deal with the options.
26
27
  module Options
27
28
 
28
29
  # Helper class introducing a boolean type for specifying boolean values (+true+ and +false+) as
@@ -39,13 +40,13 @@ module Kramdown
39
40
  # ----------------------------
40
41
  # :section: Option definitions
41
42
  #
42
- # This sections informs about the methods that can be used on the Options class.
43
+ # This sections informs describes the methods that can be used on the Options module.
43
44
  # ----------------------------
44
45
 
45
46
  # Contains the definition of an option.
46
47
  Definition = Struct.new(:name, :type, :default, :desc)
47
48
 
48
- # Allowed option types
49
+ # Allowed option types.
49
50
  ALLOWED_TYPES = [String, Integer, Float, Symbol, Boolean, Array, Object]
50
51
 
51
52
  @options = {}
@@ -54,7 +55,7 @@ module Kramdown
54
55
  # Symbol, Boolean, Array, Object), default value +default+ and the description +desc+.
55
56
  #
56
57
  # The type 'Object' should only be used if none of the other types suffices because such an
57
- # option will be opaque!
58
+ # option will be opaque and cannot be used, for example, by CLI command!
58
59
  def self.define(name, type, default, desc)
59
60
  raise ArgumentError, "Option name #{name} is already used" if @options.has_key?(name)
60
61
  raise ArgumentError, "Invalid option type #{type} specified" if !ALLOWED_TYPES.include?(type)
@@ -67,7 +68,7 @@ module Kramdown
67
68
  @options
68
69
  end
69
70
 
70
- # Return +true+ if an option +name+ is defined.
71
+ # Return +true+ if an option called +name+ is defined.
71
72
  def self.defined?(name)
72
73
  @options.has_key?(name)
73
74
  end
@@ -79,7 +80,8 @@ module Kramdown
79
80
  temp
80
81
  end
81
82
 
82
- # Merge the #defaults Hash with the parsed options from the given Hash.
83
+ # Merge the #defaults Hash with the *parsed* options from the given Hash, i.e. only valid option
84
+ # names are considered and their value is run through the #parse method.
83
85
  def self.merge(hash)
84
86
  temp = defaults
85
87
  hash.each do |k,v|
@@ -185,14 +187,18 @@ Default: true
185
187
  Used by: kramdown parser
186
188
  EOF
187
189
 
188
- define(:extension, Object, nil, <<EOF)
189
- An object for handling the extensions
190
+ define(:html_to_native, Boolean, false, <<EOF)
191
+ Convert HTML elements to native elements
190
192
 
191
- The value for this option needs to be an object that can handle the
192
- extensions found in a kramdown document. If this option is `nil`, the
193
- default extension object is used.
193
+ If this option is `true`, the parser converts HTML elements to native
194
+ elements. For example, when parsing `<em>hallo</em>` the emphasis tag
195
+ would normally be converted to an `:html` element with tag type `:em`.
196
+ If `html_to_native` is `true`, then the emphasis would be converted to a
197
+ native `:em` element.
194
198
 
195
- Default: nil
199
+ This is useful for converters that cannot deal with HTML elements.
200
+
201
+ Default: false
196
202
  Used by: kramdown parser
197
203
  EOF
198
204
 
@@ -207,6 +213,8 @@ Used by: HTML converter
207
213
  EOF
208
214
 
209
215
  define(:filter_html, Array, [], <<EOF)
216
+ NOTE: This option is deprecated and will be removed in a future release!
217
+
210
218
  An array of HTML tags that should be filtered from the output
211
219
 
212
220
  The value can either be specified as array or as a space separated
@@ -1,7 +1,7 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  #
3
3
  #--
4
- # Copyright (C) 2009 Thomas Leitner <t_leitner@gmx.at>
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
5
  #
6
6
  # This file is part of kramdown.
7
7
  #
@@ -22,11 +22,17 @@
22
22
 
23
23
  module Kramdown
24
24
 
25
- # This module contains all available parsers. Currently, there is only one parser for parsing
26
- # documents in kramdown format.
25
+ # == Parser Module
26
+ #
27
+ # This module contains all available parsers. Currently, there two parsers:
28
+ #
29
+ # * Kramdown for parsing documents in kramdown format
30
+ # * Html for parsing HTML documents
27
31
  module Parser
28
32
 
33
+ autoload :Base, 'kramdown/parser/base'
29
34
  autoload :Kramdown, 'kramdown/parser/kramdown'
35
+ autoload :Html, 'kramdown/parser/html'
30
36
 
31
37
  end
32
38
 
@@ -0,0 +1,95 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ #--
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
+ #
6
+ # This file is part of kramdown.
7
+ #
8
+ # kramdown is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU General Public License as published by
10
+ # the Free Software Foundation, either version 3 of the License, or
11
+ # (at your option) any later version.
12
+ #
13
+ # This program is distributed in the hope that it will be useful,
14
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ # GNU General Public License for more details.
17
+ #
18
+ # You should have received a copy of the GNU General Public License
19
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ #++
21
+ #
22
+
23
+ module Kramdown
24
+
25
+ module Parser
26
+
27
+ # == Base class for parsers
28
+ #
29
+ # This class serves as base class for parsers. It provides common methods that can/should be
30
+ # used by all parsers, especially by those using StringScanner for parsing.
31
+ #
32
+ class Base
33
+
34
+ # Initialize the parser with the given Kramdown document +doc+.
35
+ def initialize(doc)
36
+ @doc = doc
37
+ @doc.parse_infos.clear
38
+ @text_type = :text
39
+ end
40
+ private_class_method(:new, :allocate)
41
+
42
+ # Parse the +source+ string into an element tree, using the information provided by the
43
+ # Kramdown document +doc+.
44
+ #
45
+ # Initializes a new instance of the calling class and then calls the #parse method that must
46
+ # be implemented by each subclass.
47
+ def self.parse(source, doc)
48
+ new(doc).parse(source)
49
+ end
50
+
51
+
52
+ # Add the given warning +text+ to the warning array of the Kramdown document.
53
+ def warning(text)
54
+ @doc.warnings << text
55
+ #TODO: add position information
56
+ end
57
+
58
+ # Modify the string +source+ to be usable by the parser.
59
+ def adapt_source(source)
60
+ source.gsub(/\r\n?/, "\n").chomp + "\n"
61
+ end
62
+
63
+ # This helper method adds the given +text+ either to the last element in the +tree+ if it is a
64
+ # +type+ element or creates a new text element with the given +type+.
65
+ def add_text(text, tree = @tree, type = @text_type)
66
+ if tree.children.last && tree.children.last.type == type
67
+ tree.children.last.value << text
68
+ elsif !text.empty?
69
+ tree.children << Element.new(type, text)
70
+ end
71
+ end
72
+
73
+ # Extract the part of the StringScanner +srcscan+ backed string specified by the +range+. This
74
+ # method also works correctly under Ruby 1.9.
75
+ def extract_string(range, strscan)
76
+ result = nil
77
+ if RUBY_VERSION >= '1.9'
78
+ begin
79
+ enc = strscan.string.encoding
80
+ strscan.string.force_encoding('ASCII-8BIT')
81
+ result = strscan.string[range].force_encoding(enc)
82
+ ensure
83
+ strscan.string.force_encoding(enc)
84
+ end
85
+ else
86
+ result = strscan.string[range]
87
+ end
88
+ result
89
+ end
90
+
91
+ end
92
+
93
+ end
94
+
95
+ end
@@ -0,0 +1,387 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ #--
4
+ # Copyright (C) 2009-2010 Thomas Leitner <t_leitner@gmx.at>
5
+ #
6
+ # This file is part of kramdown.
7
+ #
8
+ # kramdown is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU General Public License as published by
10
+ # the Free Software Foundation, either version 3 of the License, or
11
+ # (at your option) any later version.
12
+ #
13
+ # This program is distributed in the hope that it will be useful,
14
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ # GNU General Public License for more details.
17
+ #
18
+ # You should have received a copy of the GNU General Public License
19
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
+ #++
21
+ #
22
+
23
+ require 'rexml/parsers/baseparser'
24
+ require 'strscan'
25
+
26
+ module Kramdown
27
+
28
+ module Parser
29
+
30
+ # Used for parsing a HTML document.
31
+ class Html < Base
32
+
33
+ # Contains all constants that are used when parsing.
34
+ module Constants
35
+ #:stopdoc:
36
+ # The following regexps are based on the ones used by REXML, with some slight modifications.
37
+ HTML_DOCTYPE_RE = /<!DOCTYPE.*?>/m
38
+ HTML_COMMENT_RE = /<!--(.*?)-->/m
39
+ HTML_INSTRUCTION_RE = /<\?(.*?)\?>/m
40
+ HTML_ATTRIBUTE_RE = /\s*(#{REXML::Parsers::BaseParser::UNAME_STR})\s*=\s*(["'])(.*?)\2/m
41
+ HTML_TAG_RE = /<((?>#{REXML::Parsers::BaseParser::UNAME_STR}))\s*((?>\s+#{REXML::Parsers::BaseParser::UNAME_STR}\s*=\s*(["']).*?\3)*)\s*(\/)?>/m
42
+ HTML_TAG_CLOSE_RE = /<\/(#{REXML::Parsers::BaseParser::NAME_STR})\s*>/m
43
+ HTML_ENTITY_RE = /&([\w:][\-\w\d\.:]*);|&#(\d+);|&\#x([0-9a-fA-F]+);/
44
+
45
+
46
+ HTML_PARSE_AS_BLOCK = %w{applet button blockquote colgroup dd div dl fieldset form iframe li
47
+ map noscript object ol table tbody thead tfoot tr td ul}
48
+ HTML_PARSE_AS_SPAN = %w{a abbr acronym address b bdo big cite caption del dfn dt em
49
+ h1 h2 h3 h4 h5 h6 i ins kbd label legend optgroup p q rb rbc
50
+ rp rt rtc ruby samp select small span strong sub sup th tt var}
51
+ HTML_PARSE_AS_RAW = %w{script math option textarea pre code}
52
+
53
+ HTML_PARSE_AS = Hash.new {|h,k| h[k] = :raw}
54
+ HTML_PARSE_AS_BLOCK.each {|i| HTML_PARSE_AS[i] = :block}
55
+ HTML_PARSE_AS_SPAN.each {|i| HTML_PARSE_AS[i] = :span}
56
+ HTML_PARSE_AS_RAW.each {|i| HTML_PARSE_AS[i] = :raw}
57
+
58
+ # Some HTML elements like script belong to both categories (i.e. are valid in block and
59
+ # span HTML) and don't appear therefore!
60
+ HTML_SPAN_ELEMENTS = %w{a abbr acronym b big bdo br button cite code del dfn em i img input
61
+ ins kbd label option q rb rbc rp rt rtc ruby samp select small span
62
+ strong sub sup textarea tt var}
63
+ HTML_BLOCK_ELEMENTS = %w{address article aside applet body button blockquote caption col colgroup dd div dl dt fieldset
64
+ figcaption footer form h1 h2 h3 h4 h5 h6 header hgroup hr html head iframe legend listing menu
65
+ li map nav ol optgroup p pre section summary table tbody td th thead tfoot tr ul}
66
+ HTML_ELEMENTS_WITHOUT_BODY = %w{area base br col command embed hr img input keygen link meta param source track wbr}
67
+ end
68
+
69
+
70
+ # Contains the parsing methods. This module can be mixed into any parser to get HTML parsing
71
+ # functionality. The only thing that must be provided by the class are instance variable
72
+ # <tt>@stack</tt> for storing needed state and <tt>@src</tt> (instance of StringScanner) for
73
+ # the actual parsing.
74
+ module Parser
75
+
76
+ include Constants
77
+
78
+ # Process the HTML start tag that has already be scanned/checked. Does the common processing
79
+ # steps and then yields to the caller for further processing.
80
+ def handle_html_start_tag
81
+ name = @src[1]
82
+ closed = !@src[4].nil?
83
+ attrs = {}
84
+ @src[2].scan(HTML_ATTRIBUTE_RE).each {|attr,sep,val| attrs[attr] = val}
85
+
86
+ el = Element.new(:html_element, name, :attr => attrs, :category => :block)
87
+ @tree.children << el
88
+
89
+ if !closed && HTML_ELEMENTS_WITHOUT_BODY.include?(el.value)
90
+ warning("The HTML tag '#{el.value}' cannot have any content - auto-closing it")
91
+ closed = true
92
+ end
93
+ if name == 'script'
94
+ handle_html_script_tag
95
+ yield(el, true)
96
+ else
97
+ yield(el, closed)
98
+ end
99
+ end
100
+
101
+ def handle_html_script_tag
102
+ curpos = @src.pos
103
+ if result = @src.scan_until(/(?=<\/script\s*>)/m)
104
+ add_text(extract_string(curpos...@src.pos, @src), @tree.children.last, :raw)
105
+ @src.scan(HTML_TAG_CLOSE_RE)
106
+ else
107
+ add_text(@src.scan(/.*/m), @tree.children.last, :raw)
108
+ warning("Found no end tag for 'script' - auto-closing it")
109
+ end
110
+ end
111
+
112
+ HTML_RAW_START = /(?=<(#{REXML::Parsers::BaseParser::UNAME_STR}|\/|!--|\?))/
113
+
114
+ # Parse raw HTML from the current source position, storing the found elements in +el+.
115
+ # Parsing continues until one of the following criteria are fulfilled:
116
+ #
117
+ # - The end of the document is reached.
118
+ # - The matching end tag for the element +el+ is found (only used if +el+ is an HTML
119
+ # element).
120
+ #
121
+ # When an HTML start tag is found, processing is deferred to #handle_html_start_tag,
122
+ # providing the block given to this method.
123
+ def parse_raw_html(el, &block)
124
+ @stack.push(@tree)
125
+ @tree = el
126
+
127
+ done = false
128
+ while !@src.eos? && !done
129
+ if result = @src.scan_until(HTML_RAW_START)
130
+ add_text(result, @tree, :text)
131
+ if result = @src.scan(HTML_COMMENT_RE)
132
+ @tree.children << Element.new(:xml_comment, result, :category => :block, :parent_is_raw => true)
133
+ elsif result = @src.scan(HTML_INSTRUCTION_RE)
134
+ @tree.children << Element.new(:xml_pi, result, :category => :block, :parent_is_raw => true)
135
+ elsif @src.scan(HTML_TAG_RE)
136
+ handle_html_start_tag(&block)
137
+ elsif @src.scan(HTML_TAG_CLOSE_RE)
138
+ if @tree.value == @src[1]
139
+ done = true
140
+ else
141
+ warning("Found invalidly used HTML closing tag for '#{@src[1]}' - ignoring it")
142
+ end
143
+ else
144
+ add_text(@src.scan(/./), @tree, :text)
145
+ end
146
+ else
147
+ result = @src.scan(/.*/m)
148
+ add_text(result, @tree, :text)
149
+ warning("Found no end tag for '#{@tree.value}' - auto-closing it") if @tree.type == :html_element
150
+ done = true
151
+ end
152
+ end
153
+
154
+ @tree = @stack.pop
155
+ end
156
+
157
+ end
158
+
159
+
160
+ # Converts HTML elements to native elements if possible.
161
+ class ElementConverter
162
+
163
+ include Constants
164
+
165
+ REMOVE_TEXT_CHILDREN = %w{html head hgroup ol ul dl table colgroup tbody thead tfoot tr select optgroup}
166
+ REMOVE_WHITESPACE_CHILDREN = %w{body section nav article aside header footer address
167
+ div li dd blockquote figure figcaption td th fieldset form}
168
+ STRIP_WHITESPACE = %w{address article aside blockquote body caption dd div dl dt fieldset figcaption form footer
169
+ header h1 h2 h3 h4 h5 h6 legend li nav p section td th}
170
+ SIMPLE_ELEMENTS = %w{em strong blockquote hr br a img p thead tbody tfoot tr td th ul ol dl li dl dt dd}
171
+
172
+ # Convert the element +el+ and its children.
173
+ def process(el, convert_simple = true, parent = nil)
174
+ case el.type
175
+ when :xml_comment, :xml_pi, :html_doctype
176
+ ptype = if parent.nil?
177
+ 'div'
178
+ else
179
+ case parent.type
180
+ when :html_element then parent.value
181
+ when :code_span then 'code'
182
+ when :code_block then 'pre'
183
+ when :header then 'h1'
184
+ else parent.type.to_s
185
+ end
186
+ end
187
+ el.options = {:category => HTML_PARSE_AS_SPAN.include?(ptype) ? :span : :block}
188
+ return
189
+ when :html_element
190
+ else return
191
+ end
192
+
193
+ type = el.value
194
+ remove_text_children(el) if REMOVE_TEXT_CHILDREN.include?(type)
195
+
196
+ mname = "convert_#{el.value}"
197
+ if self.class.method_defined?(mname)
198
+ send(mname, el)
199
+ elsif convert_simple && SIMPLE_ELEMENTS.include?(type)
200
+ set_basics(el, type.intern, HTML_SPAN_ELEMENTS.include?(type) ? :span : :block)
201
+ process_children(el, convert_simple)
202
+ else
203
+ process_html_element(el, convert_simple)
204
+ end
205
+
206
+ strip_whitespace(el) if STRIP_WHITESPACE.include?(type)
207
+ remove_whitespace_children(el) if REMOVE_WHITESPACE_CHILDREN.include?(type)
208
+ end
209
+
210
+ def process_children(el, convert_simple = true)
211
+ el.children.map! do |c|
212
+ if c.type == :text
213
+ process_text(c.value)
214
+ else
215
+ process(c, convert_simple, el)
216
+ c
217
+ end
218
+ end.flatten!
219
+ end
220
+
221
+ # Process the HTML text +raw+: compress whitespace (if +preserve+ is +false+) and convert
222
+ # entities in entity elements.
223
+ def process_text(raw, preserve = false)
224
+ raw.gsub!(/\s+/, ' ') unless preserve
225
+ src = StringScanner.new(raw)
226
+ result = []
227
+ while !src.eos?
228
+ if tmp = src.scan_until(/(?=#{HTML_ENTITY_RE})/)
229
+ result << Element.new(:text, tmp)
230
+ src.scan(HTML_ENTITY_RE)
231
+ val = src[1] || (src[2] && src[2].to_i) || src[3].hex
232
+ result << if %w{lsquo rsquo ldquo rdquo}.include?(val)
233
+ Element.new(:smart_quote, val.intern)
234
+ elsif %w{mdash ndash hellip laquo raquo}.include?(val)
235
+ Element.new(:typographic_sym, val.intern)
236
+ else
237
+ Element.new(:entity, val)
238
+ end
239
+ else
240
+ result << Element.new(:text, src.scan(/.*/m))
241
+ end
242
+ end
243
+ result
244
+ end
245
+
246
+ def process_html_element(el, convert_simple = true)
247
+ el.options = {:category => HTML_SPAN_ELEMENTS.include?(el.value) ? :span : :block,
248
+ :parse_type => HTML_PARSE_AS[el.value],
249
+ :attr => el.options[:attr]
250
+ }
251
+ process_children(el, convert_simple)
252
+ end
253
+
254
+ def remove_text_children(el)
255
+ el.children.delete_if {|c| c.type == :text}
256
+ end
257
+
258
+ def strip_whitespace(el)
259
+ return if el.children.empty?
260
+ if el.children.first.type == :text
261
+ el.children.first.value.lstrip!
262
+ end
263
+ if el.children.last.type == :text
264
+ el.children.last.value.rstrip!
265
+ end
266
+ end
267
+
268
+ def remove_whitespace_children(el)
269
+ i = -1
270
+ el.children.delete_if do |c|
271
+ i += 1
272
+ c.type == :text && c.value.strip.empty? &&
273
+ (i == 0 || i == el.children.length - 1 || (el.children[i-1].options[:category] == :block &&
274
+ el.children[i+1].options[:category] == :block))
275
+ end
276
+ end
277
+
278
+ def set_basics(el, type, category, opts = {})
279
+ el.type = type
280
+ el.options = {:category => category, :attr => el.options[:attr]}.merge(opts)
281
+ el.value = nil
282
+ end
283
+
284
+ def extract_text(el, raw)
285
+ raw << el.value.to_s if el.type == :text
286
+ el.children.each {|c| extract_text(c, raw)}
287
+ end
288
+
289
+ def convert_h1(el)
290
+ set_basics(el, :header, :block, :level => el.value[1..1].to_i)
291
+ extract_text(el, el.options[:raw_text] = '')
292
+ process_children(el)
293
+ end
294
+ %w{h2 h3 h4 h5 h6}.each {|i| alias_method("convert_#{i}".intern, :convert_h1)}
295
+
296
+ def convert_code(el)
297
+ if el.value == 'code'
298
+ set_basics(el, :codespan, :span)
299
+ else
300
+ set_basics(el, :codeblock, :block)
301
+ end
302
+ raw = ''
303
+ extract_text(el, raw)
304
+ result = process_text(raw, true)
305
+ if result.length > 1 || result.first.type != :text
306
+ el.children = result
307
+ else
308
+ el.value = result.first.value
309
+ end
310
+ end
311
+ alias :convert_pre :convert_code
312
+
313
+ def convert_table(el)
314
+ if !is_simple_table?(el)
315
+ process_html_element(el, false)
316
+ return
317
+ end
318
+ process_children(el)
319
+ set_basics(el, :table, :block)
320
+ el.options[:alignment] = []
321
+ helper = lambda do |c|
322
+ if c.type == :tr && el.options[:alignment].empty?
323
+ el.options[:alignment] = [:default] * c.children.length
324
+ break
325
+ else
326
+ c.children.each {|cc| helper.call(cc)}
327
+ end
328
+ end
329
+ helper.call(el)
330
+ true
331
+ end
332
+
333
+ def is_simple_table?(el)
334
+ only_phrasing_content = lambda do |c|
335
+ c.children.all? do |cc|
336
+ (cc.type == :text || !HTML_BLOCK_ELEMENTS.include?(cc.value)) && only_phrasing_content.call(cc)
337
+ end
338
+ end
339
+ helper = Proc.new do |c|
340
+ if c.value == 'th' || c.value == 'td'
341
+ return false if !only_phrasing_content.call(c)
342
+ else
343
+ c.children.each {|cc| helper.call(cc)}
344
+ end
345
+ end
346
+ helper.call(el)
347
+ true
348
+ end
349
+
350
+ end
351
+
352
+ include Parser
353
+
354
+ # Parse +source+ as HTML document and return the created +tree+.
355
+ def parse(source)
356
+ @stack = []
357
+ @tree = Element.new(:root)
358
+ @src = StringScanner.new(adapt_source(source))
359
+
360
+ while true
361
+ if result = @src.scan(/\s*#{HTML_INSTRUCTION_RE}/)
362
+ @tree.children << Element.new(:xml_pi, result.strip, :category => :block)
363
+ elsif result = @src.scan(/\s*#{HTML_DOCTYPE_RE}/)
364
+ @tree.children << Element.new(:html_doctype, result.strip, :category => :block)
365
+ elsif result = @src.scan(/\s*#{HTML_COMMENT_RE}/)
366
+ @tree.children << Element.new(:xml_comment, result.strip, :category => :block)
367
+ else
368
+ break
369
+ end
370
+ end
371
+
372
+ tag_handler = lambda do |c, closed|
373
+ parse_raw_html(c, &tag_handler) if !closed
374
+ end
375
+ parse_raw_html(@tree, &tag_handler)
376
+
377
+ ec = ElementConverter.new
378
+ @tree.children.each {|c| ec.process(c)}
379
+ ec.remove_whitespace_children(@tree)
380
+ @tree
381
+ end
382
+
383
+ end
384
+
385
+ end
386
+
387
+ end