OSDN Git Service

Merged r6126 from trunk.
[redminele/redmine.git] / lib / redcloth3.rb
1 #                                vim:ts=4:sw=4:
2 # = RedCloth - Textile and Markdown Hybrid for Ruby
3 #
4 # Homepage::  http://whytheluckystiff.net/ruby/redcloth/
5 # Author::    why the lucky stiff (http://whytheluckystiff.net/)
6 # Copyright:: (cc) 2004 why the lucky stiff (and his puppet organizations.)
7 # License::   BSD
8 #
9 # (see http://hobix.com/textile/ for a Textile Reference.)
10 #
11 # Based on (and also inspired by) both:
12 #
13 # PyTextile: http://diveintomark.org/projects/textile/textile.py.txt
14 # Textism for PHP: http://www.textism.com/tools/textile/
15 #
16 #
17
18 # = RedCloth
19 #
20 # RedCloth is a Ruby library for converting Textile and/or Markdown
21 # into HTML.  You can use either format, intermingled or separately.
22 # You can also extend RedCloth to honor your own custom text stylings.
23 #
24 # RedCloth users are encouraged to use Textile if they are generating
25 # HTML and to use Markdown if others will be viewing the plain text.
26 #
27 # == What is Textile?
28 #
29 # Textile is a simple formatting style for text
30 # documents, loosely based on some HTML conventions.
31 #
32 # == Sample Textile Text
33 #
34 #  h2. This is a title
35 #
36 #  h3. This is a subhead
37 #
38 #  This is a bit of paragraph.
39 #
40 #  bq. This is a blockquote.
41 #
42 # = Writing Textile
43 #
44 # A Textile document consists of paragraphs.  Paragraphs
45 # can be specially formatted by adding a small instruction
46 # to the beginning of the paragraph.
47 #
48 #  h[n].   Header of size [n].
49 #  bq.     Blockquote.
50 #  #       Numeric list.
51 #  *       Bulleted list.
52 #
53 # == Quick Phrase Modifiers
54 #
55 # Quick phrase modifiers are also included, to allow formatting
56 # of small portions of text within a paragraph.
57 #
58 #  \_emphasis\_
59 #  \_\_italicized\_\_
60 #  \*strong\*
61 #  \*\*bold\*\*
62 #  ??citation??
63 #  -deleted text-
64 #  +inserted text+
65 #  ^superscript^
66 #  ~subscript~
67 #  @code@
68 #  %(classname)span%
69 #
70 #  ==notextile== (leave text alone)
71 #
72 # == Links
73 #
74 # To make a hypertext link, put the link text in "quotation 
75 # marks" followed immediately by a colon and the URL of the link.
76
77 # Optional: text in (parentheses) following the link text, 
78 # but before the closing quotation mark, will become a Title 
79 # attribute for the link, visible as a tool tip when a cursor is above it.
80
81 # Example:
82 #
83 #  "This is a link (This is a title) ":http://www.textism.com
84
85 # Will become:
86
87 #  <a href="http://www.textism.com" title="This is a title">This is a link</a>
88 #
89 # == Images
90 #
91 # To insert an image, put the URL for the image inside exclamation marks.
92 #
93 # Optional: text that immediately follows the URL in (parentheses) will 
94 # be used as the Alt text for the image. Images on the web should always 
95 # have descriptive Alt text for the benefit of readers using non-graphical 
96 # browsers.
97 #
98 # Optional: place a colon followed by a URL immediately after the 
99 # closing ! to make the image into a link.
100
101 # Example:
102 #
103 #  !http://www.textism.com/common/textist.gif(Textist)!
104 #
105 # Will become:
106 #
107 #  <img src="http://www.textism.com/common/textist.gif" alt="Textist" />
108 #
109 # With a link:
110 #
111 #  !/common/textist.gif(Textist)!:http://textism.com
112 #
113 # Will become:
114 #
115 #  <a href="http://textism.com"><img src="/common/textist.gif" alt="Textist" /></a>
116 #
117 # == Defining Acronyms
118 #
119 # HTML allows authors to define acronyms via the tag. The definition appears as a 
120 # tool tip when a cursor hovers over the acronym. A crucial aid to clear writing, 
121 # this should be used at least once for each acronym in documents where they appear.
122 #
123 # To quickly define an acronym in Textile, place the full text in (parentheses) 
124 # immediately following the acronym.
125
126 # Example:
127 #
128 #  ACLU(American Civil Liberties Union)
129 #
130 # Will become:
131 #
132 #  <acronym title="American Civil Liberties Union">ACLU</acronym>
133 #
134 # == Adding Tables
135 #
136 # In Textile, simple tables can be added by seperating each column by
137 # a pipe.
138 #
139 #     |a|simple|table|row|
140 #     |And|Another|table|row|
141 #
142 # Attributes are defined by style definitions in parentheses.
143 #
144 #     table(border:1px solid black).
145 #     (background:#ddd;color:red). |{}| | | |
146 #
147 # == Using RedCloth
148
149 # RedCloth is simply an extension of the String class, which can handle
150 # Textile formatting.  Use it like a String and output HTML with its
151 # RedCloth#to_html method.
152 #
153 #  doc = RedCloth.new "
154 #
155 #  h2. Test document
156 #
157 #  Just a simple test."
158 #
159 #  puts doc.to_html
160 #
161 # By default, RedCloth uses both Textile and Markdown formatting, with
162 # Textile formatting taking precedence.  If you want to turn off Markdown
163 # formatting, to boost speed and limit the processor:
164 #
165 #  class RedCloth::Textile.new( str )
166
167 class RedCloth3 < String
168
169     VERSION = '3.0.4'
170     DEFAULT_RULES = [:textile, :markdown]
171
172     #
173     # Two accessor for setting security restrictions.
174     #
175     # This is a nice thing if you're using RedCloth for
176     # formatting in public places (e.g. Wikis) where you
177     # don't want users to abuse HTML for bad things.
178     #
179     # If +:filter_html+ is set, HTML which wasn't
180     # created by the Textile processor will be escaped.
181     #
182     # If +:filter_styles+ is set, it will also disable
183     # the style markup specifier. ('{color: red}')
184     #
185     attr_accessor :filter_html, :filter_styles
186
187     #
188     # Accessor for toggling hard breaks.
189     #
190     # If +:hard_breaks+ is set, single newlines will
191     # be converted to HTML break tags.  This is the
192     # default behavior for traditional RedCloth.
193     #
194     attr_accessor :hard_breaks
195
196     # Accessor for toggling lite mode.
197     #
198     # In lite mode, block-level rules are ignored.  This means
199     # that tables, paragraphs, lists, and such aren't available.
200     # Only the inline markup for bold, italics, entities and so on.
201     #
202     #   r = RedCloth.new( "And then? She *fell*!", [:lite_mode] )
203     #   r.to_html
204     #   #=> "And then? She <strong>fell</strong>!"
205     #
206     attr_accessor :lite_mode
207
208     #
209     # Accessor for toggling span caps.
210     #
211     # Textile places `span' tags around capitalized
212     # words by default, but this wreaks havoc on Wikis.
213     # If +:no_span_caps+ is set, this will be
214     # suppressed.
215     #
216     attr_accessor :no_span_caps
217
218     #
219     # Establishes the markup predence.  Available rules include:
220     #
221     # == Textile Rules
222     #
223     # The following textile rules can be set individually.  Or add the complete
224     # set of rules with the single :textile rule, which supplies the rule set in
225     # the following precedence:
226     #
227     # refs_textile::          Textile references (i.e. [hobix]http://hobix.com/)
228     # block_textile_table::   Textile table block structures
229     # block_textile_lists::   Textile list structures
230     # block_textile_prefix::  Textile blocks with prefixes (i.e. bq., h2., etc.)
231     # inline_textile_image::  Textile inline images
232     # inline_textile_link::   Textile inline links
233     # inline_textile_span::   Textile inline spans
234     # glyphs_textile:: Textile entities (such as em-dashes and smart quotes)
235     #
236     # == Markdown
237     #
238     # refs_markdown::         Markdown references (for example: [hobix]: http://hobix.com/)
239     # block_markdown_setext:: Markdown setext headers
240     # block_markdown_atx::    Markdown atx headers
241     # block_markdown_rule::   Markdown horizontal rules
242     # block_markdown_bq::     Markdown blockquotes
243     # block_markdown_lists::  Markdown lists
244     # inline_markdown_link::  Markdown links
245     attr_accessor :rules
246
247     # Returns a new RedCloth object, based on _string_ and
248     # enforcing all the included _restrictions_.
249     #
250     #   r = RedCloth.new( "h1. A <b>bold</b> man", [:filter_html] )
251     #   r.to_html
252     #     #=>"<h1>A &lt;b&gt;bold&lt;/b&gt; man</h1>"
253     #
254     def initialize( string, restrictions = [] )
255         restrictions.each { |r| method( "#{ r }=" ).call( true ) }
256         super( string )
257     end
258
259     #
260     # Generates HTML from the Textile contents.
261     #
262     #   r = RedCloth.new( "And then? She *fell*!" )
263     #   r.to_html( true )
264     #     #=>"And then? She <strong>fell</strong>!"
265     #
266     def to_html( *rules )
267         rules = DEFAULT_RULES if rules.empty?
268         # make our working copy
269         text = self.dup
270         
271         @urlrefs = {}
272         @shelf = []
273         textile_rules = [:block_textile_table, :block_textile_lists,
274                          :block_textile_prefix, :inline_textile_image, :inline_textile_link,
275                          :inline_textile_code, :inline_textile_span, :glyphs_textile]
276         markdown_rules = [:refs_markdown, :block_markdown_setext, :block_markdown_atx, :block_markdown_rule,
277                           :block_markdown_bq, :block_markdown_lists, 
278                           :inline_markdown_reflink, :inline_markdown_link]
279         @rules = rules.collect do |rule|
280             case rule
281             when :markdown
282                 markdown_rules
283             when :textile
284                 textile_rules
285             else
286                 rule
287             end
288         end.flatten
289
290         # standard clean up
291         incoming_entities text 
292         clean_white_space text 
293
294         # start processor
295         @pre_list = []
296         rip_offtags text
297         no_textile text
298         escape_html_tags text
299         # need to do this before #hard_break and #blocks
300         block_textile_quotes text unless @lite_mode
301         hard_break text 
302         unless @lite_mode
303             refs text
304             blocks text
305         end
306         inline text
307         smooth_offtags text
308
309         retrieve text
310
311         text.gsub!( /<\/?notextile>/, '' )
312         text.gsub!( /x%x%/, '&#38;' )
313         clean_html text if filter_html
314         text.strip!
315         text
316
317     end
318
319     #######
320     private
321     #######
322     #
323     # Mapping of 8-bit ASCII codes to HTML numerical entity equivalents.
324     # (from PyTextile)
325     #
326     TEXTILE_TAGS =
327
328         [[128, 8364], [129, 0], [130, 8218], [131, 402], [132, 8222], [133, 8230], 
329          [134, 8224], [135, 8225], [136, 710], [137, 8240], [138, 352], [139, 8249], 
330          [140, 338], [141, 0], [142, 0], [143, 0], [144, 0], [145, 8216], [146, 8217], 
331          [147, 8220], [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], 
332          [153, 8482], [154, 353], [155, 8250], [156, 339], [157, 0], [158, 0], [159, 376]].
333
334         collect! do |a, b|
335             [a.chr, ( b.zero? and "" or "&#{ b };" )]
336         end
337
338     #
339     # Regular expressions to convert to HTML.
340     #
341     A_HLGN = /(?:(?:<>|<|>|\=|[()]+)+)/
342     A_VLGN = /[\-^~]/
343     C_CLAS = '(?:\([^)]+\))'
344     C_LNGE = '(?:\[[^\[\]]+\])'
345     C_STYL = '(?:\{[^}]+\})'
346     S_CSPN = '(?:\\\\\d+)'
347     S_RSPN = '(?:/\d+)'
348     A = "(?:#{A_HLGN}?#{A_VLGN}?|#{A_VLGN}?#{A_HLGN}?)"
349     S = "(?:#{S_CSPN}?#{S_RSPN}|#{S_RSPN}?#{S_CSPN}?)"
350     C = "(?:#{C_CLAS}?#{C_STYL}?#{C_LNGE}?|#{C_STYL}?#{C_LNGE}?#{C_CLAS}?|#{C_LNGE}?#{C_STYL}?#{C_CLAS}?)"
351     # PUNCT = Regexp::quote( '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' )
352     PUNCT = Regexp::quote( '!"#$%&\'*+,-./:;=?@\\^_`|~' )
353     PUNCT_NOQ = Regexp::quote( '!"#$&\',./:;=?@\\`|' )
354     PUNCT_Q = Regexp::quote( '*-_+^~%' )
355     HYPERLINK = '(\S+?)([^\w\s/;=\?]*?)(?=\s|<|$)'
356
357     # Text markup tags, don't conflict with block tags
358     SIMPLE_HTML_TAGS = [
359         'tt', 'b', 'i', 'big', 'small', 'em', 'strong', 'dfn', 'code', 
360         'samp', 'kbd', 'var', 'cite', 'abbr', 'acronym', 'a', 'img', 'br',
361         'br', 'map', 'q', 'sub', 'sup', 'span', 'bdo'
362     ]
363
364     QTAGS = [
365         ['**', 'b', :limit],
366         ['*', 'strong', :limit],
367         ['??', 'cite', :limit],
368         ['-', 'del', :limit],
369         ['__', 'i', :limit],
370         ['_', 'em', :limit],
371         ['%', 'span', :limit],
372         ['+', 'ins', :limit],
373         ['^', 'sup', :limit],
374         ['~', 'sub', :limit]
375     ] 
376     QTAGS_JOIN = QTAGS.map {|rc, ht, rtype| Regexp::quote rc}.join('|')
377     
378     QTAGS.collect! do |rc, ht, rtype|
379         rcq = Regexp::quote rc
380         re =
381             case rtype
382             when :limit
383                 /(^|[>\s\(])          # sta
384                 (?!\-\-)
385                 (#{QTAGS_JOIN}|)      # oqs
386                 (#{rcq})              # qtag
387                 (\w|[^\s].*?[^\s])    # content
388                 (?!\-\-)
389                 #{rcq}
390                 (#{QTAGS_JOIN}|)      # oqa
391                 (?=[[:punct:]]|<|\s|\)|$)/x
392             else
393                 /(#{rcq})
394                 (#{C})
395                 (?::(\S+))?
396                 (\w|[^\s\-].*?[^\s\-])
397                 #{rcq}/xm 
398             end
399         [rc, ht, re, rtype]
400     end
401
402     # Elements to handle
403     GLYPHS = [
404     #   [ /([^\s\[{(>])?\'([dmst]\b|ll\b|ve\b|\s|:|$)/, '\1&#8217;\2' ], # single closing
405     #   [ /([^\s\[{(>#{PUNCT_Q}][#{PUNCT_Q}]*)\'/, '\1&#8217;' ], # single closing
406     #   [ /\'(?=[#{PUNCT_Q}]*(s\b|[\s#{PUNCT_NOQ}]))/, '&#8217;' ], # single closing
407     #   [ /\'/, '&#8216;' ], # single opening
408     #   [ /</, '&lt;' ], # less-than
409     #   [ />/, '&gt;' ], # greater-than
410     #   [ /([^\s\[{(])?"(\s|:|$)/, '\1&#8221;\2' ], # double closing
411     #   [ /([^\s\[{(>#{PUNCT_Q}][#{PUNCT_Q}]*)"/, '\1&#8221;' ], # double closing
412     #   [ /"(?=[#{PUNCT_Q}]*[\s#{PUNCT_NOQ}])/, '&#8221;' ], # double closing
413     #   [ /"/, '&#8220;' ], # double opening
414     #   [ /\b( )?\.{3}/, '\1&#8230;' ], # ellipsis
415     #   [ /\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])/, '<acronym title="\2">\1</acronym>' ], # 3+ uppercase acronym
416     #   [ /(^|[^"][>\s])([A-Z][A-Z0-9 ]+[A-Z0-9])([^<A-Za-z0-9]|$)/, '\1<span class="caps">\2</span>\3', :no_span_caps ], # 3+ uppercase caps
417     #   [ /(\.\s)?\s?--\s?/, '\1&#8212;' ], # em dash
418     #   [ /\s->\s/, ' &rarr; ' ], # right arrow
419     #   [ /\s-\s/, ' &#8211; ' ], # en dash
420     #   [ /(\d+) ?x ?(\d+)/, '\1&#215;\2' ], # dimension sign
421     #   [ /\b ?[(\[]TM[\])]/i, '&#8482;' ], # trademark
422     #   [ /\b ?[(\[]R[\])]/i, '&#174;' ], # registered
423     #   [ /\b ?[(\[]C[\])]/i, '&#169;' ] # copyright
424     ]
425
426     H_ALGN_VALS = {
427         '<' => 'left',
428         '=' => 'center',
429         '>' => 'right',
430         '<>' => 'justify'
431     }
432
433     V_ALGN_VALS = {
434         '^' => 'top',
435         '-' => 'middle',
436         '~' => 'bottom'
437     }
438
439     #
440     # Flexible HTML escaping
441     #
442     def htmlesc( str, mode=:Quotes )
443       if str
444         str.gsub!( '&', '&amp;' )
445         str.gsub!( '"', '&quot;' ) if mode != :NoQuotes
446         str.gsub!( "'", '&#039;' ) if mode == :Quotes
447         str.gsub!( '<', '&lt;')
448         str.gsub!( '>', '&gt;')
449       end
450       str
451     end
452
453     # Search and replace for Textile glyphs (quotes, dashes, other symbols)
454     def pgl( text )
455         #GLYPHS.each do |re, resub, tog|
456         #    next if tog and method( tog ).call
457         #    text.gsub! re, resub
458         #end
459         text.gsub!(/\b([A-Z][A-Z0-9]{1,})\b(?:[(]([^)]*)[)])/) do |m|
460           "<acronym title=\"#{htmlesc $2}\">#{$1}</acronym>"
461         end
462     end
463
464     # Parses Textile attribute lists and builds an HTML attribute string
465     def pba( text_in, element = "" )
466         
467         return '' unless text_in
468
469         style = []
470         text = text_in.dup
471         if element == 'td'
472             colspan = $1 if text =~ /\\(\d+)/
473             rowspan = $1 if text =~ /\/(\d+)/
474             style << "vertical-align:#{ v_align( $& ) };" if text =~ A_VLGN
475         end
476
477         style << "#{ htmlesc $1 };" if text.sub!( /\{([^}]*)\}/, '' ) && !filter_styles
478
479         lang = $1 if
480             text.sub!( /\[([^)]+?)\]/, '' )
481
482         cls = $1 if
483             text.sub!( /\(([^()]+?)\)/, '' )
484                         
485         style << "padding-left:#{ $1.length }em;" if
486             text.sub!( /([(]+)/, '' )
487
488         style << "padding-right:#{ $1.length }em;" if text.sub!( /([)]+)/, '' )
489
490         style << "text-align:#{ h_align( $& ) };" if text =~ A_HLGN
491
492         cls, id = $1, $2 if cls =~ /^(.*?)#(.*)$/
493         
494         atts = ''
495         atts << " style=\"#{ style.join }\"" unless style.empty?
496         atts << " class=\"#{ cls }\"" unless cls.to_s.empty?
497         atts << " lang=\"#{ lang }\"" if lang
498         atts << " id=\"#{ id }\"" if id
499         atts << " colspan=\"#{ colspan }\"" if colspan
500         atts << " rowspan=\"#{ rowspan }\"" if rowspan
501         
502         atts
503     end
504
505     TABLE_RE = /^(?:table(_?#{S}#{A}#{C})\. ?\n)?^(#{A}#{C}\.? ?\|.*?\|)(\n\n|\Z)/m
506     
507     # Parses a Textile table block, building HTML from the result.
508     def block_textile_table( text ) 
509         text.gsub!( TABLE_RE ) do |matches|
510
511             tatts, fullrow = $~[1..2]
512             tatts = pba( tatts, 'table' )
513             tatts = shelve( tatts ) if tatts
514             rows = []
515
516             fullrow.each_line do |row|
517                 ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\. )(.*)/m
518                 cells = []
519                 row.split( /(\|)(?![^\[\|]*\]\])/ )[1..-2].each do |cell|
520                     next if cell == '|'
521                     ctyp = 'd'
522                     ctyp = 'h' if cell =~ /^_/
523
524                     catts = ''
525                     catts, cell = pba( $1, 'td' ), $2 if cell =~ /^(_?#{S}#{A}#{C}\. ?)(.*)/
526
527                     catts = shelve( catts ) if catts
528                     cells << "\t\t\t<t#{ ctyp }#{ catts }>#{ cell }</t#{ ctyp }>" 
529                 end
530                 ratts = shelve( ratts ) if ratts
531                 rows << "\t\t<tr#{ ratts }>\n#{ cells.join( "\n" ) }\n\t\t</tr>"
532             end
533             "\t<table#{ tatts }>\n#{ rows.join( "\n" ) }\n\t</table>\n\n"
534         end
535     end
536
537     LISTS_RE = /^([#*]+?#{C} .*?)$(?![^#*])/m
538     LISTS_CONTENT_RE = /^([#*]+)(#{A}#{C}) (.*)$/m
539
540     # Parses Textile lists and generates HTML
541     def block_textile_lists( text ) 
542         text.gsub!( LISTS_RE ) do |match|
543             lines = match.split( /\n/ )
544             last_line = -1
545             depth = []
546             lines.each_with_index do |line, line_id|
547                 if line =~ LISTS_CONTENT_RE 
548                     tl,atts,content = $~[1..3]
549                     if depth.last
550                         if depth.last.length > tl.length
551                             (depth.length - 1).downto(0) do |i|
552                                 break if depth[i].length == tl.length
553                                 lines[line_id - 1] << "</li>\n\t</#{ lT( depth[i] ) }l>\n\t"
554                                 depth.pop
555                             end
556                         end
557                         if depth.last and depth.last.length == tl.length
558                             lines[line_id - 1] << '</li>'
559                         end
560                     end
561                     unless depth.last == tl
562                         depth << tl
563                         atts = pba( atts )
564                         atts = shelve( atts ) if atts
565                         lines[line_id] = "\t<#{ lT(tl) }l#{ atts }>\n\t<li>#{ content }"
566                     else
567                         lines[line_id] = "\t\t<li>#{ content }"
568                     end
569                     last_line = line_id
570
571                 else
572                     last_line = line_id
573                 end
574                 if line_id - last_line > 1 or line_id == lines.length - 1
575                     depth.delete_if do |v|
576                         lines[last_line] << "</li>\n\t</#{ lT( v ) }l>"
577                     end
578                 end
579             end
580             lines.join( "\n" )
581         end
582     end
583     
584     QUOTES_RE = /(^>+([^\n]*?)(\n|$))+/m
585     QUOTES_CONTENT_RE = /^([> ]+)(.*)$/m
586     
587     def block_textile_quotes( text )
588       text.gsub!( QUOTES_RE ) do |match|
589         lines = match.split( /\n/ )
590         quotes = ''
591         indent = 0
592         lines.each do |line|
593           line =~ QUOTES_CONTENT_RE 
594           bq,content = $1, $2
595           l = bq.count('>')
596           if l != indent
597             quotes << ("\n\n" + (l>indent ? '<blockquote>' * (l-indent) : '</blockquote>' * (indent-l)) + "\n\n")
598             indent = l
599           end
600           quotes << (content + "\n")
601         end
602         quotes << ("\n" + '</blockquote>' * indent + "\n\n")
603         quotes
604       end
605     end
606
607     CODE_RE = /(\W)
608         @
609         (?:\|(\w+?)\|)?
610         (.+?)
611         @
612         (?=\W)/x
613
614     def inline_textile_code( text ) 
615         text.gsub!( CODE_RE ) do |m|
616             before,lang,code,after = $~[1..4]
617             lang = " lang=\"#{ lang }\"" if lang
618             rip_offtags( "#{ before }<code#{ lang }>#{ code }</code>#{ after }", false )
619         end
620     end
621
622     def lT( text ) 
623         text =~ /\#$/ ? 'o' : 'u'
624     end
625
626     def hard_break( text )
627         text.gsub!( /(.)\n(?!\Z| *([#*=]+(\s|$)|[{|]))/, "\\1<br />" ) if hard_breaks
628     end
629
630     BLOCKS_GROUP_RE = /\n{2,}(?! )/m
631
632     def blocks( text, deep_code = false )
633         text.replace( text.split( BLOCKS_GROUP_RE ).collect do |blk|
634             plain = blk !~ /\A[#*> ]/
635
636             # skip blocks that are complex HTML
637             if blk =~ /^<\/?(\w+).*>/ and not SIMPLE_HTML_TAGS.include? $1
638                 blk
639             else
640                 # search for indentation levels
641                 blk.strip!
642                 if blk.empty?
643                     blk
644                 else
645                     code_blk = nil
646                     blk.gsub!( /((?:\n(?:\n^ +[^\n]*)+)+)/m ) do |iblk|
647                         flush_left iblk
648                         blocks iblk, plain
649                         iblk.gsub( /^(\S)/, "\t\\1" )
650                         if plain
651                             code_blk = iblk; ""
652                         else
653                             iblk
654                         end
655                     end
656
657                     block_applied = 0 
658                     @rules.each do |rule_name|
659                         block_applied += 1 if ( rule_name.to_s.match /^block_/ and method( rule_name ).call( blk ) )
660                     end
661                     if block_applied.zero?
662                         if deep_code
663                             blk = "\t<pre><code>#{ blk }</code></pre>"
664                         else
665                             blk = "\t<p>#{ blk }</p>"
666                         end
667                     end
668                     # hard_break blk
669                     blk + "\n#{ code_blk }"
670                 end
671             end
672
673         end.join( "\n\n" ) )
674     end
675
676     def textile_bq( tag, atts, cite, content )
677         cite, cite_title = check_refs( cite )
678         cite = " cite=\"#{ cite }\"" if cite
679         atts = shelve( atts ) if atts
680         "\t<blockquote#{ cite }>\n\t\t<p#{ atts }>#{ content }</p>\n\t</blockquote>"
681     end
682
683     def textile_p( tag, atts, cite, content )
684         atts = shelve( atts ) if atts
685         "\t<#{ tag }#{ atts }>#{ content }</#{ tag }>"
686     end
687
688     alias textile_h1 textile_p
689     alias textile_h2 textile_p
690     alias textile_h3 textile_p
691     alias textile_h4 textile_p
692     alias textile_h5 textile_p
693     alias textile_h6 textile_p
694
695     def textile_fn_( tag, num, atts, cite, content )
696         atts << " id=\"fn#{ num }\" class=\"footnote\""
697         content = "<sup>#{ num }</sup> #{ content }"
698         atts = shelve( atts ) if atts
699         "\t<p#{ atts }>#{ content }</p>"
700     end
701
702     BLOCK_RE = /^(([a-z]+)(\d*))(#{A}#{C})\.(?::(\S+))? (.*)$/m
703
704     def block_textile_prefix( text ) 
705         if text =~ BLOCK_RE
706             tag,tagpre,num,atts,cite,content = $~[1..6]
707             atts = pba( atts )
708
709             # pass to prefix handler
710             replacement = nil
711             if respond_to? "textile_#{ tag }", true
712               replacement = method( "textile_#{ tag }" ).call( tag, atts, cite, content )
713             elsif respond_to? "textile_#{ tagpre }_", true
714               replacement = method( "textile_#{ tagpre }_" ).call( tagpre, num, atts, cite, content )  
715             end
716             text.gsub!( $& ) { replacement } if replacement
717         end
718     end
719     
720     SETEXT_RE = /\A(.+?)\n([=-])[=-]* *$/m
721     def block_markdown_setext( text )
722         if text =~ SETEXT_RE
723             tag = if $2 == "="; "h1"; else; "h2"; end
724             blk, cont = "<#{ tag }>#{ $1 }</#{ tag }>", $'
725             blocks cont
726             text.replace( blk + cont )
727         end
728     end
729
730     ATX_RE = /\A(\#{1,6})  # $1 = string of #'s
731               [ ]*
732               (.+?)       # $2 = Header text
733               [ ]*
734               \#*         # optional closing #'s (not counted)
735               $/x
736     def block_markdown_atx( text )
737         if text =~ ATX_RE
738             tag = "h#{ $1.length }"
739             blk, cont = "<#{ tag }>#{ $2 }</#{ tag }>\n\n", $'
740             blocks cont
741             text.replace( blk + cont )
742         end
743     end
744
745     MARKDOWN_BQ_RE = /\A(^ *> ?.+$(.+\n)*\n*)+/m
746
747     def block_markdown_bq( text )
748         text.gsub!( MARKDOWN_BQ_RE ) do |blk|
749             blk.gsub!( /^ *> ?/, '' )
750             flush_left blk
751             blocks blk
752             blk.gsub!( /^(\S)/, "\t\\1" )
753             "<blockquote>\n#{ blk }\n</blockquote>\n\n"
754         end
755     end
756
757     MARKDOWN_RULE_RE = /^(#{
758         ['*', '-', '_'].collect { |ch| ' ?(' + Regexp::quote( ch ) + ' ?){3,}' }.join( '|' )
759     })$/
760
761     def block_markdown_rule( text )
762         text.gsub!( MARKDOWN_RULE_RE ) do |blk|
763             "<hr />"
764         end
765     end
766
767     # XXX TODO XXX
768     def block_markdown_lists( text )
769     end
770
771     def inline_textile_span( text ) 
772         QTAGS.each do |qtag_rc, ht, qtag_re, rtype|
773             text.gsub!( qtag_re ) do |m|
774              
775                 case rtype
776                 when :limit
777                     sta,oqs,qtag,content,oqa = $~[1..6]
778                     atts = nil
779                     if content =~ /^(#{C})(.+)$/
780                       atts, content = $~[1..2]
781                     end
782                 else
783                     qtag,atts,cite,content = $~[1..4]
784                     sta = ''
785                 end
786                 atts = pba( atts )
787                 atts = shelve( atts ) if atts
788
789                 "#{ sta }#{ oqs }<#{ ht }#{ atts }>#{ content }</#{ ht }>#{ oqa }"
790
791             end
792         end
793     end
794
795     LINK_RE = /
796             (
797             ([\s\[{(]|[#{PUNCT}])?     # $pre
798             "                          # start
799             (#{C})                     # $atts
800             ([^"\n]+?)                 # $text
801             \s?
802             (?:\(([^)]+?)\)(?="))?     # $title
803             ":
804             (                          # $url
805             (\/|[a-zA-Z]+:\/\/|www\.|mailto:)  # $proto
806             [\w\/]\S+?
807             )               
808             (\/)?                      # $slash
809             ([^\w\=\/;\(\)]*?)         # $post
810             )
811             (?=<|\s|$)
812         /x 
813 #"
814     def inline_textile_link( text ) 
815         text.gsub!( LINK_RE ) do |m|
816           all,pre,atts,text,title,url,proto,slash,post = $~[1..9]
817           if text.include?('<br />')
818             all
819           else
820             url, url_title = check_refs( url )
821             title ||= url_title
822             
823             # Idea below : an URL with unbalanced parethesis and
824             # ending by ')' is put into external parenthesis
825             if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
826               url=url[0..-2] # discard closing parenth from url
827               post = ")"+post # add closing parenth to post
828             end
829             atts = pba( atts )
830             atts = " href=\"#{ htmlesc url }#{ slash }\"#{ atts }"
831             atts << " title=\"#{ htmlesc title }\"" if title
832             atts = shelve( atts ) if atts
833             
834             external = (url =~ /^https?:\/\//) ? ' class="external"' : ''
835             
836             "#{ pre }<a#{ atts }#{ external }>#{ text }</a>#{ post }"
837           end
838         end
839     end
840
841     MARKDOWN_REFLINK_RE = /
842             \[([^\[\]]+)\]      # $text
843             [ ]?                # opt. space
844             (?:\n[ ]*)?         # one optional newline followed by spaces
845             \[(.*?)\]           # $id
846         /x 
847
848     def inline_markdown_reflink( text ) 
849         text.gsub!( MARKDOWN_REFLINK_RE ) do |m|
850             text, id = $~[1..2]
851
852             if id.empty?
853                 url, title = check_refs( text )
854             else
855                 url, title = check_refs( id )
856             end
857             
858             atts = " href=\"#{ url }\""
859             atts << " title=\"#{ title }\"" if title
860             atts = shelve( atts )
861             
862             "<a#{ atts }>#{ text }</a>"
863         end
864     end
865
866     MARKDOWN_LINK_RE = /
867             \[([^\[\]]+)\]      # $text
868             \(                  # open paren
869             [ \t]*              # opt space
870             <?(.+?)>?           # $href
871             [ \t]*              # opt space
872             (?:                 # whole title
873             (['"])              # $quote
874             (.*?)               # $title
875             \3                  # matching quote
876             )?                  # title is optional
877             \)
878         /x 
879
880     def inline_markdown_link( text ) 
881         text.gsub!( MARKDOWN_LINK_RE ) do |m|
882             text, url, quote, title = $~[1..4]
883
884             atts = " href=\"#{ url }\""
885             atts << " title=\"#{ title }\"" if title
886             atts = shelve( atts )
887             
888             "<a#{ atts }>#{ text }</a>"
889         end
890     end
891
892     TEXTILE_REFS_RE =  /(^ *)\[([^\[\n]+?)\](#{HYPERLINK})(?=\s|$)/
893     MARKDOWN_REFS_RE = /(^ *)\[([^\n]+?)\]:\s+<?(#{HYPERLINK})>?(?:\s+"((?:[^"]|\\")+)")?(?=\s|$)/m
894
895     def refs( text )
896         @rules.each do |rule_name|
897             method( rule_name ).call( text ) if rule_name.to_s.match /^refs_/
898         end
899     end
900
901     def refs_textile( text ) 
902         text.gsub!( TEXTILE_REFS_RE ) do |m|
903             flag, url = $~[2..3]
904             @urlrefs[flag.downcase] = [url, nil]
905             nil
906         end
907     end
908     
909     def refs_markdown( text )
910         text.gsub!( MARKDOWN_REFS_RE ) do |m|
911             flag, url = $~[2..3]
912             title = $~[6]
913             @urlrefs[flag.downcase] = [url, title]
914             nil
915         end
916     end
917
918     def check_refs( text ) 
919         ret = @urlrefs[text.downcase] if text
920         ret || [text, nil]
921     end
922
923     IMAGE_RE = /
924             (>|\s|^)           # start of line?
925             \!                   # opening
926             (\<|\=|\>)?          # optional alignment atts
927             (#{C})               # optional style,class atts
928             (?:\. )?             # optional dot-space
929             ([^\s(!]+?)          # presume this is the src
930             \s?                  # optional space
931             (?:\(((?:[^\(\)]|\([^\)]+\))+?)\))?   # optional title
932             \!                   # closing
933             (?::#{ HYPERLINK })? # optional href
934         /x 
935
936     def inline_textile_image( text ) 
937         text.gsub!( IMAGE_RE )  do |m|
938             stln,algn,atts,url,title,href,href_a1,href_a2 = $~[1..8]
939             htmlesc title
940             atts = pba( atts )
941             atts = " src=\"#{ url }\"#{ atts }"
942             atts << " title=\"#{ title }\"" if title
943             atts << " alt=\"#{ title }\"" 
944             # size = @getimagesize($url);
945             # if($size) $atts.= " $size[3]";
946
947             href, alt_title = check_refs( href ) if href
948             url, url_title = check_refs( url )
949
950             out = ''
951             out << "<a#{ shelve( " href=\"#{ href }\"" ) }>" if href
952             out << "<img#{ shelve( atts ) } />"
953             out << "</a>#{ href_a1 }#{ href_a2 }" if href
954             
955             if algn 
956                 algn = h_align( algn )
957                 if stln == "<p>"
958                     out = "<p style=\"float:#{ algn }\">#{ out }"
959                 else
960                     out = "#{ stln }<div style=\"float:#{ algn }\">#{ out }</div>"
961                 end
962             else
963                 out = stln + out
964             end
965
966             out
967         end
968     end
969
970     def shelve( val ) 
971         @shelf << val
972         " :redsh##{ @shelf.length }:"
973     end
974     
975     def retrieve( text ) 
976         @shelf.each_with_index do |r, i|
977             text.gsub!( " :redsh##{ i + 1 }:", r )
978         end
979     end
980
981     def incoming_entities( text ) 
982         ## turn any incoming ampersands into a dummy character for now.
983         ## This uses a negative lookahead for alphanumerics followed by a semicolon,
984         ## implying an incoming html entity, to be skipped
985
986         text.gsub!( /&(?![#a-z0-9]+;)/i, "x%x%" )
987     end
988
989     def no_textile( text ) 
990         text.gsub!( /(^|\s)==([^=]+.*?)==(\s|$)?/,
991             '\1<notextile>\2</notextile>\3' )
992         text.gsub!( /^ *==([^=]+.*?)==/m,
993             '\1<notextile>\2</notextile>\3' )
994     end
995
996     def clean_white_space( text ) 
997         # normalize line breaks
998         text.gsub!( /\r\n/, "\n" )
999         text.gsub!( /\r/, "\n" )
1000         text.gsub!( /\t/, '    ' )
1001         text.gsub!( /^ +$/, '' )
1002         text.gsub!( /\n{3,}/, "\n\n" )
1003         text.gsub!( /"$/, "\" " )
1004
1005         # if entire document is indented, flush
1006         # to the left side
1007         flush_left text
1008     end
1009
1010     def flush_left( text )
1011         indt = 0
1012         if text =~ /^ /
1013             while text !~ /^ {#{indt}}\S/
1014                 indt += 1
1015             end unless text.empty?
1016             if indt.nonzero?
1017                 text.gsub!( /^ {#{indt}}/, '' )
1018             end
1019         end
1020     end
1021
1022     def footnote_ref( text ) 
1023         text.gsub!( /\b\[([0-9]+?)\](\s)?/,
1024             '<sup><a href="#fn\1">\1</a></sup>\2' )
1025     end
1026     
1027     OFFTAGS = /(code|pre|kbd|notextile)/
1028     OFFTAG_MATCH = /(?:(<\/#{ OFFTAGS }>)|(<#{ OFFTAGS }[^>]*>))(.*?)(?=<\/?#{ OFFTAGS }\W|\Z)/mi
1029     OFFTAG_OPEN = /<#{ OFFTAGS }/
1030     OFFTAG_CLOSE = /<\/?#{ OFFTAGS }/
1031     HASTAG_MATCH = /(<\/?\w[^\n]*?>)/m
1032     ALLTAG_MATCH = /(<\/?\w[^\n]*?>)|.*?(?=<\/?\w[^\n]*?>|$)/m
1033
1034     def glyphs_textile( text, level = 0 )
1035         if text !~ HASTAG_MATCH
1036             pgl text
1037             footnote_ref text
1038         else
1039             codepre = 0
1040             text.gsub!( ALLTAG_MATCH ) do |line|
1041                 ## matches are off if we're between <code>, <pre> etc.
1042                 if $1
1043                     if line =~ OFFTAG_OPEN
1044                         codepre += 1
1045                     elsif line =~ OFFTAG_CLOSE
1046                         codepre -= 1
1047                         codepre = 0 if codepre < 0
1048                     end 
1049                 elsif codepre.zero?
1050                     glyphs_textile( line, level + 1 )
1051                 else
1052                     htmlesc( line, :NoQuotes )
1053                 end
1054                 # p [level, codepre, line]
1055
1056                 line
1057             end
1058         end
1059     end
1060
1061     def rip_offtags( text, escape_aftertag=true )
1062         if text =~ /<.*>/
1063             ## strip and encode <pre> content
1064             codepre, used_offtags = 0, {}
1065             text.gsub!( OFFTAG_MATCH ) do |line|
1066                 if $3
1067                     first, offtag, aftertag = $3, $4, $5
1068                     codepre += 1
1069                     used_offtags[offtag] = true
1070                     if codepre - used_offtags.length > 0
1071                         htmlesc( line, :NoQuotes )
1072                         @pre_list.last << line
1073                         line = ""
1074                     else
1075                         ### htmlesc is disabled between CODE tags which will be parsed with highlighter
1076                         ### Regexp in formatter.rb is : /<code\s+class="(\w+)">\s?(.+)/m
1077                         ### NB: some changes were made not to use $N variables, because we use "match"
1078                         ###   and it breaks following lines
1079                         htmlesc( aftertag, :NoQuotes ) if aftertag && escape_aftertag && !first.match(/<code\s+class="(\w+)">/)
1080                         line = "<redpre##{ @pre_list.length }>"
1081                         first.match(/<#{ OFFTAGS }([^>]*)>/)
1082                         tag = $1
1083                         $2.to_s.match(/(class\=("[^"]+"|'[^']+'))/i)
1084                         tag << " #{$1}" if $1
1085                         @pre_list << "<#{ tag }>#{ aftertag }"
1086                     end
1087                 elsif $1 and codepre > 0
1088                     if codepre - used_offtags.length > 0
1089                         htmlesc( line, :NoQuotes )
1090                         @pre_list.last << line
1091                         line = ""
1092                     end
1093                     codepre -= 1 unless codepre.zero?
1094                     used_offtags = {} if codepre.zero?
1095                 end 
1096                 line
1097             end
1098         end
1099         text
1100     end
1101
1102     def smooth_offtags( text )
1103         unless @pre_list.empty?
1104             ## replace <pre> content
1105             text.gsub!( /<redpre#(\d+)>/ ) { @pre_list[$1.to_i] }
1106         end
1107     end
1108
1109     def inline( text ) 
1110         [/^inline_/, /^glyphs_/].each do |meth_re|
1111             @rules.each do |rule_name|
1112                 method( rule_name ).call( text ) if rule_name.to_s.match( meth_re )
1113             end
1114         end
1115     end
1116
1117     def h_align( text ) 
1118         H_ALGN_VALS[text]
1119     end
1120
1121     def v_align( text ) 
1122         V_ALGN_VALS[text]
1123     end
1124
1125     def textile_popup_help( name, windowW, windowH )
1126         ' <a target="_blank" href="http://hobix.com/textile/#' + helpvar + '" onclick="window.open(this.href, \'popupwindow\', \'width=' + windowW + ',height=' + windowH + ',scrollbars,resizable\'); return false;">' + name + '</a><br />'
1127     end
1128
1129     # HTML cleansing stuff
1130     BASIC_TAGS = {
1131         'a' => ['href', 'title'],
1132         'img' => ['src', 'alt', 'title'],
1133         'br' => [],
1134         'i' => nil,
1135         'u' => nil, 
1136         'b' => nil,
1137         'pre' => nil,
1138         'kbd' => nil,
1139         'code' => ['lang'],
1140         'cite' => nil,
1141         'strong' => nil,
1142         'em' => nil,
1143         'ins' => nil,
1144         'sup' => nil,
1145         'sub' => nil,
1146         'del' => nil,
1147         'table' => nil,
1148         'tr' => nil,
1149         'td' => ['colspan', 'rowspan'],
1150         'th' => nil,
1151         'ol' => nil,
1152         'ul' => nil,
1153         'li' => nil,
1154         'p' => nil,
1155         'h1' => nil,
1156         'h2' => nil,
1157         'h3' => nil,
1158         'h4' => nil,
1159         'h5' => nil,
1160         'h6' => nil, 
1161         'blockquote' => ['cite']
1162     }
1163
1164     def clean_html( text, tags = BASIC_TAGS )
1165         text.gsub!( /<!\[CDATA\[/, '' )
1166         text.gsub!( /<(\/*)(\w+)([^>]*)>/ ) do
1167             raw = $~
1168             tag = raw[2].downcase
1169             if tags.has_key? tag
1170                 pcs = [tag]
1171                 tags[tag].each do |prop|
1172                     ['"', "'", ''].each do |q|
1173                         q2 = ( q != '' ? q : '\s' )
1174                         if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i
1175                             attrv = $1
1176                             next if prop == 'src' and attrv =~ %r{^(?!http)\w+:}
1177                             pcs << "#{prop}=\"#{$1.gsub('"', '\\"')}\""
1178                             break
1179                         end
1180                     end
1181                 end if tags[tag]
1182                 "<#{raw[1]}#{pcs.join " "}>"
1183             else
1184                 " "
1185             end
1186         end
1187     end
1188     
1189     ALLOWED_TAGS = %w(redpre pre code notextile)
1190     
1191     def escape_html_tags(text)
1192       text.gsub!(%r{<(\/?([!\w]+)[^<>\n]*)(>?)}) {|m| ALLOWED_TAGS.include?($2) ? "<#{$1}#{$3}" : "&lt;#{$1}#{'&gt;' unless $3.blank?}" }
1193     end
1194 end
1195