PageRenderTime 73ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/redcloth3.rb

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