You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redcloth3.rb 39KB

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