PageRenderTime 65ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/redcloth3.rb

https://github.com/martindale/better
Ruby | 1182 lines | 779 code | 98 blank | 305 comment | 72 complexity | 27e8656847b008724ed76f9379f38cc8 MD5 | raw file
Possible License(s): LGPL-2.1, 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. # <acronym title="American Civil Liberties Union">ACLU</acronym>
  132. #
  133. # == Adding Tables
  134. #
  135. # In Textile, simple tables can be added by seperating 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 = [] ) # spec_me cover_me heckle_me
  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 ) # spec_me cover_me heckle_me
  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. hard_break text
  287. unless @lite_mode
  288. refs text
  289. # need to do this before text is split by #blocks
  290. block_textile_quotes 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 = '(?:\[[^\[\]]+\])'
  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.collect! do |rc, ht, rtype|
  355. rcq = Regexp::quote rc
  356. re =
  357. case rtype
  358. when :limit
  359. /(^|[>\s\(])
  360. (#{rcq})
  361. (#{C})
  362. (?::(\S+?))?
  363. (\w|[^\s\-].*?[^\s\-])
  364. #{rcq}
  365. (?=[[:punct:]]|\s|\)|$)/x
  366. else
  367. /(#{rcq})
  368. (#{C})
  369. (?::(\S+))?
  370. (\w|[^\s\-].*?[^\s\-])
  371. #{rcq}/xm
  372. end
  373. [rc, ht, re, rtype]
  374. end
  375. # Elements to handle
  376. GLYPHS = [
  377. # [ /([^\s\[{(>])?\'([dmst]\b|ll\b|ve\b|\s|:|$)/, '\1&#8217;\2' ], # single closing
  378. # [ /([^\s\[{(>#{PUNCT_Q}][#{PUNCT_Q}]*)\'/, '\1&#8217;' ], # single closing
  379. # [ /\'(?=[#{PUNCT_Q}]*(s\b|[\s#{PUNCT_NOQ}]))/, '&#8217;' ], # single closing
  380. # [ /\'/, '&#8216;' ], # single opening
  381. # [ /</, '&lt;' ], # less-than
  382. # [ />/, '&gt;' ], # greater-than
  383. # [ /([^\s\[{(])?"(\s|:|$)/, '\1&#8221;\2' ], # double closing
  384. # [ /([^\s\[{(>#{PUNCT_Q}][#{PUNCT_Q}]*)"/, '\1&#8221;' ], # double closing
  385. # [ /"(?=[#{PUNCT_Q}]*[\s#{PUNCT_NOQ}])/, '&#8221;' ], # double closing
  386. # [ /"/, '&#8220;' ], # double opening
  387. # [ /\b( )?\.{3}/, '\1&#8230;' ], # ellipsis
  388. # [ /\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])/, '<acronym title="\2">\1</acronym>' ], # 3+ uppercase acronym
  389. # [ /(^|[^"][>\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
  390. # [ /(\.\s)?\s?--\s?/, '\1&#8212;' ], # em dash
  391. # [ /\s->\s/, ' &rarr; ' ], # right arrow
  392. # [ /\s-\s/, ' &#8211; ' ], # en dash
  393. # [ /(\d+) ?x ?(\d+)/, '\1&#215;\2' ], # dimension sign
  394. # [ /\b ?[(\[]TM[\])]/i, '&#8482;' ], # trademark
  395. # [ /\b ?[(\[]R[\])]/i, '&#174;' ], # registered
  396. # [ /\b ?[(\[]C[\])]/i, '&#169;' ] # copyright
  397. ]
  398. H_ALGN_VALS = {
  399. '<' => 'left',
  400. '=' => 'center',
  401. '>' => 'right',
  402. '<>' => 'justify'
  403. }
  404. V_ALGN_VALS = {
  405. '^' => 'top',
  406. '-' => 'middle',
  407. '~' => 'bottom'
  408. }
  409. #
  410. # Flexible HTML escaping
  411. #
  412. def htmlesc( str, mode=:Quotes ) # cover_me heckle_me
  413. if str
  414. str.gsub!( '&', '&amp;' )
  415. str.gsub!( '"', '&quot;' ) if mode != :NoQuotes
  416. str.gsub!( "'", '&#039;' ) if mode == :Quotes
  417. str.gsub!( '<', '&lt;')
  418. str.gsub!( '>', '&gt;')
  419. end
  420. str
  421. end
  422. # Search and replace for Textile glyphs (quotes, dashes, other symbols)
  423. def pgl( text ) # cover_me heckle_me
  424. #GLYPHS.each do |re, resub, tog|
  425. # next if tog and method( tog ).call
  426. # text.gsub! re, resub
  427. #end
  428. text.gsub!(/\b([A-Z][A-Z0-9]{2,})\b(?:[(]([^)]*)[)])/) do |m|
  429. "<acronym title=\"#{htmlesc $2}\">#{$1}</acronym>"
  430. end
  431. end
  432. # Parses Textile attribute lists and builds an HTML attribute string
  433. def pba( text_in, element = "" ) # cover_me heckle_me
  434. return '' unless text_in
  435. style = []
  436. text = text_in.dup
  437. if element == 'td'
  438. colspan = $1 if text =~ /\\(\d+)/
  439. rowspan = $1 if text =~ /\/(\d+)/
  440. style << "vertical-align:#{ v_align( $& ) };" if text =~ A_VLGN
  441. end
  442. style << "#{ htmlesc $1 };" if text.sub!( /\{([^}]*)\}/, '' ) && !filter_styles
  443. lang = $1 if
  444. text.sub!( /\[([^)]+?)\]/, '' )
  445. cls = $1 if
  446. text.sub!( /\(([^()]+?)\)/, '' )
  447. style << "padding-left:#{ $1.length }em;" if
  448. text.sub!( /([(]+)/, '' )
  449. style << "padding-right:#{ $1.length }em;" if text.sub!( /([)]+)/, '' )
  450. style << "text-align:#{ h_align( $& ) };" if text =~ A_HLGN
  451. cls, id = $1, $2 if cls =~ /^(.*?)#(.*)$/
  452. atts = ''
  453. atts << " style=\"#{ style.join }\"" unless style.empty?
  454. atts << " class=\"#{ cls }\"" unless cls.to_s.empty?
  455. atts << " lang=\"#{ lang }\"" if lang
  456. atts << " id=\"#{ id }\"" if id
  457. atts << " colspan=\"#{ colspan }\"" if colspan
  458. atts << " rowspan=\"#{ rowspan }\"" if rowspan
  459. atts
  460. end
  461. TABLE_RE = /^(?:table(_?#{S}#{A}#{C})\. ?\n)?^(#{A}#{C}\.? ?\|.*?\|)(\n\n|\Z)/m
  462. # Parses a Textile table block, building HTML from the result.
  463. def block_textile_table( text ) # cover_me heckle_me
  464. text.gsub!( TABLE_RE ) do |matches|
  465. tatts, fullrow = $~[1..2]
  466. tatts = pba( tatts, 'table' )
  467. tatts = shelve( tatts ) if tatts
  468. rows = []
  469. fullrow.each_line do |row|
  470. ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\. )(.*)/m
  471. cells = []
  472. row.split( /(\|)(?![^\[\|]*\]\])/ )[1..-2].each do |cell|
  473. next if cell == '|'
  474. ctyp = 'd'
  475. ctyp = 'h' if cell =~ /^_/
  476. catts = ''
  477. catts, cell = pba( $1, 'td' ), $2 if cell =~ /^(_?#{S}#{A}#{C}\. ?)(.*)/
  478. catts = shelve( catts ) if catts
  479. cells << "\t\t\t<t#{ ctyp }#{ catts }>#{ cell }</t#{ ctyp }>"
  480. end
  481. ratts = shelve( ratts ) if ratts
  482. rows << "\t\t<tr#{ ratts }>\n#{ cells.join( "\n" ) }\n\t\t</tr>"
  483. end
  484. "\t<table#{ tatts }>\n#{ rows.join( "\n" ) }\n\t</table>\n\n"
  485. end
  486. end
  487. LISTS_RE = /^([#*]+?#{C} .*?)$(?![^#*])/m
  488. LISTS_CONTENT_RE = /^([#*]+)(#{A}#{C}) (.*)$/m
  489. # Parses Textile lists and generates HTML
  490. def block_textile_lists( text ) # cover_me heckle_me
  491. text.gsub!( LISTS_RE ) do |match|
  492. lines = match.split( /\n/ )
  493. last_line = -1
  494. depth = []
  495. lines.each_with_index do |line, line_id|
  496. if line =~ LISTS_CONTENT_RE
  497. tl,atts,content = $~[1..3]
  498. if depth.last
  499. if depth.last.length > tl.length
  500. (depth.length - 1).downto(0) do |i|
  501. break if depth[i].length == tl.length
  502. lines[line_id - 1] << "</li>\n\t</#{ lT( depth[i] ) }l>\n\t"
  503. depth.pop
  504. end
  505. end
  506. if depth.last and depth.last.length == tl.length
  507. lines[line_id - 1] << '</li>'
  508. end
  509. end
  510. unless depth.last == tl
  511. depth << tl
  512. atts = pba( atts )
  513. atts = shelve( atts ) if atts
  514. lines[line_id] = "\t<#{ lT(tl) }l#{ atts }>\n\t<li>#{ content }"
  515. else
  516. lines[line_id] = "\t\t<li>#{ content }"
  517. end
  518. last_line = line_id
  519. else
  520. last_line = line_id
  521. end
  522. if line_id - last_line > 1 or line_id == lines.length - 1
  523. depth.delete_if do |v|
  524. lines[last_line] << "</li>\n\t</#{ lT( v ) }l>"
  525. end
  526. end
  527. end
  528. lines.join( "\n" )
  529. end
  530. end
  531. QUOTES_RE = /(^>+([^\n]*?)(\n|$))+/m
  532. QUOTES_CONTENT_RE = /^([> ]+)(.*)$/m
  533. def block_textile_quotes( text ) # cover_me heckle_me
  534. text.gsub!( QUOTES_RE ) do |match|
  535. lines = match.split( /\n/ )
  536. quotes = ''
  537. indent = 0
  538. lines.each do |line|
  539. line =~ QUOTES_CONTENT_RE
  540. bq,content = $1, $2
  541. l = bq.count('>')
  542. if l != indent
  543. quotes << ("\n\n" + (l>indent ? '<blockquote>' * (l-indent) : '</blockquote>' * (indent-l)) + "\n\n")
  544. indent = l
  545. end
  546. quotes << (content + "\n")
  547. end
  548. quotes << ("\n" + '</blockquote>' * indent + "\n\n")
  549. quotes
  550. end
  551. end
  552. CODE_RE = /(\W)
  553. @
  554. (?:\|(\w+?)\|)?
  555. (.+?)
  556. @
  557. (?=\W)/x
  558. def inline_textile_code( text ) # cover_me heckle_me
  559. text.gsub!( CODE_RE ) do |m|
  560. before,lang,code,after = $~[1..4]
  561. lang = " lang=\"#{ lang }\"" if lang
  562. rip_offtags( "#{ before }<code#{ lang }>#{ code }</code>#{ after }" )
  563. end
  564. end
  565. def lT( text ) # cover_me heckle_me
  566. text =~ /\#$/ ? 'o' : 'u'
  567. end
  568. def hard_break( text ) # cover_me heckle_me
  569. text.gsub!( /(.)\n(?!\Z| *([#*=]+(\s|$)|[{|]))/, "\\1<br />" ) if hard_breaks
  570. end
  571. BLOCKS_GROUP_RE = /\n{2,}(?! )/m
  572. def blocks( text, deep_code = false ) # cover_me heckle_me
  573. text.replace( text.split( BLOCKS_GROUP_RE ).collect do |blk|
  574. plain = blk !~ /\A[#*> ]/
  575. # skip blocks that are complex HTML
  576. if blk =~ /^<\/?(\w+).*>/ and not SIMPLE_HTML_TAGS.include? $1
  577. blk
  578. else
  579. # search for indentation levels
  580. blk.strip!
  581. if blk.empty?
  582. blk
  583. else
  584. code_blk = nil
  585. blk.gsub!( /((?:\n(?:\n^ +[^\n]*)+)+)/m ) do |iblk|
  586. flush_left iblk
  587. blocks iblk, plain
  588. iblk.gsub( /^(\S)/, "\t\\1" )
  589. if plain
  590. code_blk = iblk; ""
  591. else
  592. iblk
  593. end
  594. end
  595. block_applied = 0
  596. @rules.each do |rule_name|
  597. block_applied += 1 if ( rule_name.to_s.match /^block_/ and method( rule_name ).call( blk ) )
  598. end
  599. if block_applied.zero?
  600. if deep_code
  601. blk = "\t<pre><code>#{ blk }</code></pre>"
  602. else
  603. blk = "\t<p>#{ blk }</p>"
  604. end
  605. end
  606. # hard_break blk
  607. blk + "\n#{ code_blk }"
  608. end
  609. end
  610. end.join( "\n\n" ) )
  611. end
  612. def textile_bq( tag, atts, cite, content ) # cover_me heckle_me
  613. cite, cite_title = check_refs( cite )
  614. cite = " cite=\"#{ cite }\"" if cite
  615. atts = shelve( atts ) if atts
  616. "\t<blockquote#{ cite }>\n\t\t<p#{ atts }>#{ content }</p>\n\t</blockquote>"
  617. end
  618. def textile_p( tag, atts, cite, content ) # cover_me heckle_me
  619. atts = shelve( atts ) if atts
  620. "\t<#{ tag }#{ atts }>#{ content }</#{ tag }>"
  621. end
  622. alias textile_h1 textile_p
  623. alias textile_h2 textile_p
  624. alias textile_h3 textile_p
  625. alias textile_h4 textile_p
  626. alias textile_h5 textile_p
  627. alias textile_h6 textile_p
  628. def textile_fn_( tag, num, atts, cite, content ) # cover_me heckle_me
  629. atts << " id=\"fn#{ num }\" class=\"footnote\""
  630. content = "<sup>#{ num }</sup> #{ content }"
  631. atts = shelve( atts ) if atts
  632. "\t<p#{ atts }>#{ content }</p>"
  633. end
  634. BLOCK_RE = /^(([a-z]+)(\d*))(#{A}#{C})\.(?::(\S+))? (.*)$/m
  635. def block_textile_prefix( text ) # cover_me heckle_me
  636. if text =~ BLOCK_RE
  637. tag,tagpre,num,atts,cite,content = $~[1..6]
  638. atts = pba( atts )
  639. # pass to prefix handler
  640. if respond_to? "textile_#{ tag }", true
  641. text.gsub!( $&, method( "textile_#{ tag }" ).call( tag, atts, cite, content ) )
  642. elsif respond_to? "textile_#{ tagpre }_", true
  643. text.gsub!( $&, method( "textile_#{ tagpre }_" ).call( tagpre, num, atts, cite, content ) )
  644. end
  645. end
  646. end
  647. SETEXT_RE = /\A(.+?)\n([=-])[=-]* *$/m
  648. def block_markdown_setext( text ) # cover_me heckle_me
  649. if text =~ SETEXT_RE
  650. tag = if $2 == "="; "h1"; else; "h2"; end
  651. blk, cont = "<#{ tag }>#{ $1 }</#{ tag }>", $'
  652. blocks cont
  653. text.replace( blk + cont )
  654. end
  655. end
  656. ATX_RE = /\A(\#{1,6}) # $1 = string of #'s
  657. [ ]*
  658. (.+?) # $2 = Header text
  659. [ ]*
  660. \#* # optional closing #'s (not counted)
  661. $/x
  662. def block_markdown_atx( text ) # cover_me heckle_me
  663. if text =~ ATX_RE
  664. tag = "h#{ $1.length }"
  665. blk, cont = "<#{ tag }>#{ $2 }</#{ tag }>\n\n", $'
  666. blocks cont
  667. text.replace( blk + cont )
  668. end
  669. end
  670. MARKDOWN_BQ_RE = /\A(^ *> ?.+$(.+\n)*\n*)+/m
  671. def block_markdown_bq( text ) # cover_me heckle_me
  672. text.gsub!( MARKDOWN_BQ_RE ) do |blk|
  673. blk.gsub!( /^ *> ?/, '' )
  674. flush_left blk
  675. blocks blk
  676. blk.gsub!( /^(\S)/, "\t\\1" )
  677. "<blockquote>\n#{ blk }\n</blockquote>\n\n"
  678. end
  679. end
  680. MARKDOWN_RULE_RE = /^(#{
  681. ['*', '-', '_'].collect { |ch| ' ?(' + Regexp::quote( ch ) + ' ?){3,}' }.join( '|' )
  682. })$/
  683. def block_markdown_rule( text ) # cover_me heckle_me
  684. text.gsub!( MARKDOWN_RULE_RE ) do |blk|
  685. "<hr />"
  686. end
  687. end
  688. # XXX TODO XXX
  689. def block_markdown_lists( text ) # cover_me heckle_me
  690. end
  691. def inline_textile_span( text ) # cover_me heckle_me
  692. QTAGS.each do |qtag_rc, ht, qtag_re, rtype|
  693. text.gsub!( qtag_re ) do |m|
  694. case rtype
  695. when :limit
  696. sta,qtag,atts,cite,content = $~[1..5]
  697. else
  698. qtag,atts,cite,content = $~[1..4]
  699. sta = ''
  700. end
  701. atts = pba( atts )
  702. atts << " cite=\"#{ cite }\"" if cite
  703. atts = shelve( atts ) if atts
  704. "#{ sta }<#{ ht }#{ atts }>#{ content }</#{ ht }>"
  705. end
  706. end
  707. end
  708. LINK_RE = /
  709. (
  710. ([\s\[{(]|[#{PUNCT}])? # $pre
  711. " # start
  712. (#{C}) # $atts
  713. ([^"\n]+?) # $text
  714. \s?
  715. (?:\(([^)]+?)\)(?="))? # $title
  716. ":
  717. ( # $url
  718. (\/|[a-zA-Z]+:\/\/|www\.|mailto:) # $proto
  719. [\w\/]\S+?
  720. )
  721. (\/)? # $slash
  722. ([^\w\=\/;\(\)]*?) # $post
  723. )
  724. (?=<|\s|$)
  725. /x
  726. #"
  727. def inline_textile_link( text ) # cover_me heckle_me
  728. text.gsub!( LINK_RE ) do |m|
  729. all,pre,atts,text,title,url,proto,slash,post = $~[1..9]
  730. if text.include?('<br />')
  731. all
  732. else
  733. url, url_title = check_refs( url )
  734. title ||= url_title
  735. # Idea below : an URL with unbalanced parethesis and
  736. # ending by ')' is put into external parenthesis
  737. if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
  738. url=url[0..-2] # discard closing parenth from url
  739. post = ")"+post # add closing parenth to post
  740. end
  741. atts = pba( atts )
  742. atts = " href=\"#{ url }#{ slash }\"#{ atts }"
  743. atts << " title=\"#{ htmlesc title }\"" if title
  744. atts = shelve( atts ) if atts
  745. external = (url =~ /^https?:\/\//) ? ' class="external"' : ''
  746. "#{ pre }<a#{ atts }#{ external }>#{ text }</a>#{ post }"
  747. end
  748. end
  749. end
  750. MARKDOWN_REFLINK_RE = /
  751. \[([^\[\]]+)\] # $text
  752. [ ]? # opt. space
  753. (?:\n[ ]*)? # one optional newline followed by spaces
  754. \[(.*?)\] # $id
  755. /x
  756. def inline_markdown_reflink( text ) # cover_me heckle_me
  757. text.gsub!( MARKDOWN_REFLINK_RE ) do |m|
  758. text, id = $~[1..2]
  759. if id.empty?
  760. url, title = check_refs( text )
  761. else
  762. url, title = check_refs( id )
  763. end
  764. atts = " href=\"#{ url }\""
  765. atts << " title=\"#{ title }\"" if title
  766. atts = shelve( atts )
  767. "<a#{ atts }>#{ text }</a>"
  768. end
  769. end
  770. MARKDOWN_LINK_RE = /
  771. \[([^\[\]]+)\] # $text
  772. \( # open paren
  773. [ \t]* # opt space
  774. <?(.+?)>? # $href
  775. [ \t]* # opt space
  776. (?: # whole title
  777. (['"]) # $quote
  778. (.*?) # $title
  779. \3 # matching quote
  780. )? # title is optional
  781. \)
  782. /x
  783. def inline_markdown_link( text ) # cover_me heckle_me
  784. text.gsub!( MARKDOWN_LINK_RE ) do |m|
  785. text, url, quote, title = $~[1..4]
  786. atts = " href=\"#{ url }\""
  787. atts << " title=\"#{ title }\"" if title
  788. atts = shelve( atts )
  789. "<a#{ atts }>#{ text }</a>"
  790. end
  791. end
  792. TEXTILE_REFS_RE = /(^ *)\[([^\[\n]+?)\](#{HYPERLINK})(?=\s|$)/
  793. MARKDOWN_REFS_RE = /(^ *)\[([^\n]+?)\]:\s+<?(#{HYPERLINK})>?(?:\s+"((?:[^"]|\\")+)")?(?=\s|$)/m
  794. def refs( text ) # cover_me heckle_me
  795. @rules.each do |rule_name|
  796. method( rule_name ).call( text ) if rule_name.to_s.match /^refs_/
  797. end
  798. end
  799. def refs_textile( text ) # cover_me heckle_me
  800. text.gsub!( TEXTILE_REFS_RE ) do |m|
  801. flag, url = $~[2..3]
  802. @urlrefs[flag.downcase] = [url, nil]
  803. nil
  804. end
  805. end
  806. def refs_markdown( text ) # cover_me heckle_me
  807. text.gsub!( MARKDOWN_REFS_RE ) do |m|
  808. flag, url = $~[2..3]
  809. title = $~[6]
  810. @urlrefs[flag.downcase] = [url, title]
  811. nil
  812. end
  813. end
  814. def check_refs( text ) # cover_me heckle_me
  815. ret = @urlrefs[text.downcase] if text
  816. ret || [text, nil]
  817. end
  818. IMAGE_RE = /
  819. (>|\s|^) # start of line?
  820. \! # opening
  821. (\<|\=|\>)? # optional alignment atts
  822. (#{C}) # optional style,class atts
  823. (?:\. )? # optional dot-space
  824. ([^\s(!]+?) # presume this is the src
  825. \s? # optional space
  826. (?:\(((?:[^\(\)]|\([^\)]+\))+?)\))? # optional title
  827. \! # closing
  828. (?::#{ HYPERLINK })? # optional href
  829. /x
  830. def inline_textile_image( text ) # cover_me heckle_me
  831. text.gsub!( IMAGE_RE ) do |m|
  832. stln,algn,atts,url,title,href,href_a1,href_a2 = $~[1..8]
  833. htmlesc title
  834. atts = pba( atts )
  835. atts = " src=\"#{ url }\"#{ atts }"
  836. atts << " title=\"#{ title }\"" if title
  837. atts << " alt=\"#{ title }\""
  838. # size = @getimagesize($url);
  839. # if($size) $atts.= " $size[3]";
  840. href, alt_title = check_refs( href ) if href
  841. url, url_title = check_refs( url )
  842. out = ''
  843. out << "<a#{ shelve( " href=\"#{ href }\"" ) }>" if href
  844. out << "<img#{ shelve( atts ) } />"
  845. out << "</a>#{ href_a1 }#{ href_a2 }" if href
  846. if algn
  847. algn = h_align( algn )
  848. if stln == "<p>"
  849. out = "<p style=\"float:#{ algn }\">#{ out }"
  850. else
  851. out = "#{ stln }<div style=\"float:#{ algn }\">#{ out }</div>"
  852. end
  853. else
  854. out = stln + out
  855. end
  856. out
  857. end
  858. end
  859. def shelve( val ) # cover_me heckle_me
  860. @shelf << val
  861. " :redsh##{ @shelf.length }:"
  862. end
  863. def retrieve( text ) # cover_me heckle_me
  864. @shelf.each_with_index do |r, i|
  865. text.gsub!( " :redsh##{ i + 1 }:", r )
  866. end
  867. end
  868. def incoming_entities( text ) # cover_me heckle_me
  869. ## turn any incoming ampersands into a dummy character for now.
  870. ## This uses a negative lookahead for alphanumerics followed by a semicolon,
  871. ## implying an incoming html entity, to be skipped
  872. text.gsub!( /&(?![#a-z0-9]+;)/i, "x%x%" )
  873. end
  874. def no_textile( text ) # cover_me heckle_me
  875. text.gsub!( /(^|\s)==([^=]+.*?)==(\s|$)?/,
  876. '\1<notextile>\2</notextile>\3' )
  877. text.gsub!( /^ *==([^=]+.*?)==/m,
  878. '\1<notextile>\2</notextile>\3' )
  879. end
  880. def clean_white_space( text ) # cover_me heckle_me
  881. # normalize line breaks
  882. text.gsub!( /\r\n/, "\n" )
  883. text.gsub!( /\r/, "\n" )
  884. text.gsub!( /\t/, ' ' )
  885. text.gsub!( /^ +$/, '' )
  886. text.gsub!( /\n{3,}/, "\n\n" )
  887. text.gsub!( /"$/, "\" " )
  888. # if entire document is indented, flush
  889. # to the left side
  890. flush_left text
  891. end
  892. def flush_left( text ) # cover_me heckle_me
  893. indt = 0
  894. if text =~ /^ /
  895. while text !~ /^ {#{indt}}\S/
  896. indt += 1
  897. end unless text.empty?
  898. if indt.nonzero?
  899. text.gsub!( /^ {#{indt}}/, '' )
  900. end
  901. end
  902. end
  903. def footnote_ref( text ) # cover_me heckle_me
  904. text.gsub!( /\b\[([0-9]+?)\](\s)?/,
  905. '<sup><a href="#fn\1">\1</a></sup>\2' )
  906. end
  907. OFFTAGS = /(code|pre|kbd|notextile)/
  908. OFFTAG_MATCH = /(?:(<\/#{ OFFTAGS }>)|(<#{ OFFTAGS }[^>]*>))(.*?)(?=<\/?#{ OFFTAGS }\W|\Z)/mi
  909. OFFTAG_OPEN = /<#{ OFFTAGS }/
  910. OFFTAG_CLOSE = /<\/?#{ OFFTAGS }/
  911. HASTAG_MATCH = /(<\/?\w[^\n]*?>)/m
  912. ALLTAG_MATCH = /(<\/?\w[^\n]*?>)|.*?(?=<\/?\w[^\n]*?>|$)/m
  913. def glyphs_textile( text, level = 0 ) # cover_me heckle_me
  914. if text !~ HASTAG_MATCH
  915. pgl text
  916. footnote_ref text
  917. else
  918. codepre = 0
  919. text.gsub!( ALLTAG_MATCH ) do |line|
  920. ## matches are off if we're between <code>, <pre> etc.
  921. if $1
  922. if line =~ OFFTAG_OPEN
  923. codepre += 1
  924. elsif line =~ OFFTAG_CLOSE
  925. codepre -= 1
  926. codepre = 0 if codepre < 0
  927. end
  928. elsif codepre.zero?
  929. glyphs_textile( line, level + 1 )
  930. else
  931. htmlesc( line, :NoQuotes )
  932. end
  933. # p [level, codepre, line]
  934. line
  935. end
  936. end
  937. end
  938. def rip_offtags( text ) # cover_me heckle_me
  939. if text =~ /<.*>/
  940. ## strip and encode <pre> content
  941. codepre, used_offtags = 0, {}
  942. text.gsub!( OFFTAG_MATCH ) do |line|
  943. if $3
  944. offtag, aftertag = $4, $5
  945. codepre += 1
  946. used_offtags[offtag] = true
  947. if codepre - used_offtags.length > 0
  948. htmlesc( line, :NoQuotes )
  949. @pre_list.last << line
  950. line = ""
  951. else
  952. htmlesc( aftertag, :NoQuotes ) if aftertag
  953. line = "<redpre##{ @pre_list.length }>"
  954. $3.match(/<#{ OFFTAGS }([^>]*)>/)
  955. tag = $1
  956. $2.to_s.match(/(class\=\S+)/i)
  957. tag << " #{$1}" if $1
  958. @pre_list << "<#{ tag }>#{ aftertag }"
  959. end
  960. elsif $1 and codepre > 0
  961. if codepre - used_offtags.length > 0
  962. htmlesc( line, :NoQuotes )
  963. @pre_list.last << line
  964. line = ""
  965. end
  966. codepre -= 1 unless codepre.zero?
  967. used_offtags = {} if codepre.zero?
  968. end
  969. line
  970. end
  971. end
  972. text
  973. end
  974. def smooth_offtags( text ) # cover_me heckle_me
  975. unless @pre_list.empty?
  976. ## replace <pre> content
  977. text.gsub!( /<redpre#(\d+)>/ ) { @pre_list[$1.to_i] }
  978. end
  979. end
  980. def inline( text ) # cover_me heckle_me
  981. [/^inline_/, /^glyphs_/].each do |meth_re|
  982. @rules.each do |rule_name|
  983. method( rule_name ).call( text ) if rule_name.to_s.match( meth_re )
  984. end
  985. end
  986. end
  987. def h_align( text ) # cover_me heckle_me
  988. H_ALGN_VALS[text]
  989. end
  990. def v_align( text ) # cover_me heckle_me
  991. V_ALGN_VALS[text]
  992. end
  993. def textile_popup_help( name, windowW, windowH ) # cover_me heckle_me
  994. ' <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 />'
  995. end
  996. # HTML cleansing stuff
  997. BASIC_TAGS = {
  998. 'a' => ['href', 'title'],
  999. 'img' => ['src', 'alt', 'title'],
  1000. 'br' => [],
  1001. 'i' => nil,
  1002. 'u' => nil,
  1003. 'b' => nil,
  1004. 'pre' => nil,
  1005. 'kbd' => nil,
  1006. 'code' => ['lang'],
  1007. 'cite' => nil,
  1008. 'strong' => nil,
  1009. 'em' => nil,
  1010. 'ins' => nil,
  1011. 'sup' => nil,
  1012. 'sub' => nil,
  1013. 'del' => nil,
  1014. 'table' => nil,
  1015. 'tr' => nil,
  1016. 'td' => ['colspan', 'rowspan'],
  1017. 'th' => nil,
  1018. 'ol' => nil,
  1019. 'ul' => nil,
  1020. 'li' => nil,
  1021. 'p' => nil,
  1022. 'h1' => nil,
  1023. 'h2' => nil,
  1024. 'h3' => nil,
  1025. 'h4' => nil,
  1026. 'h5' => nil,
  1027. 'h6' => nil,
  1028. 'blockquote' => ['cite']
  1029. }
  1030. def clean_html( text, tags = BASIC_TAGS ) # cover_me heckle_me
  1031. text.gsub!( /<!\[CDATA\[/, '' )
  1032. text.gsub!( /<(\/*)(\w+)([^>]*)>/ ) do
  1033. raw = $~
  1034. tag = raw[2].downcase
  1035. if tags.has_key? tag
  1036. pcs = [tag]
  1037. tags[tag].each do |prop|
  1038. ['"', "'", ''].each do |q|
  1039. q2 = ( q != '' ? q : '\s' )
  1040. if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i
  1041. attrv = $1
  1042. next if prop == 'src' and attrv =~ %r{^(?!http)\w+:}
  1043. pcs << "#{prop}=\"#{$1.gsub('"', '\\"')}\""
  1044. break
  1045. end
  1046. end
  1047. end if tags[tag]
  1048. "<#{raw[1]}#{pcs.join " "}>"
  1049. else
  1050. " "
  1051. end
  1052. end
  1053. end
  1054. ALLOWED_TAGS = %w(redpre pre code notextile)
  1055. def escape_html_tags(text) # cover_me heckle_me
  1056. text.gsub!(%r{<(\/?([!\w]+)[^<>\n]*)(>?)}) {|m| ALLOWED_TAGS.include?($2) ? "<#{$1}#{$3}" : "&lt;#{$1}#{'&gt;' unless $3.blank?}" }
  1057. end
  1058. end