"Fossies" - the Fresh Open Source Software Archive

Member "redmine-4.1.1/lib/redmine/wiki_formatting/textile/redcloth3.rb" (6 Apr 2020, 39777 Bytes) of package /linux/www/redmine-4.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Ruby source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "redcloth3.rb": 4.1.0_vs_4.1.1.

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