PageRenderTime 72ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/redcloth3.rb

http://github.com/chiliproject/chiliproject
Ruby | 1196 lines | 793 code | 94 blank | 309 comment | 72 complexity | 974929682559e7dca2708376297524e3 MD5 | raw file
Possible License(s): GPL-2.0
  1. #-- encoding: UTF-8
  2. # vim:ts=4:sw=4:
  3. # = RedCloth - Textile and Markdown Hybrid for Ruby
  4. #
  5. # Homepage:: http://whytheluckystiff.net/ruby/redcloth/
  6. # Author:: why the lucky stiff (http://whytheluckystiff.net/)
  7. # Copyright:: (cc) 2004 why the lucky stiff (and his puppet organizations.)
  8. # License:: BSD
  9. #
  10. # (see http://hobix.com/textile/ for a Textile Reference.)
  11. #
  12. # Based on (and also inspired by) both:
  13. #
  14. # PyTextile: http://diveintomark.org/projects/textile/textile.py.txt
  15. # Textism for PHP: http://www.textism.com/tools/textile/
  16. #
  17. #
  18. # = RedCloth
  19. #
  20. # RedCloth is a Ruby library for converting Textile and/or Markdown
  21. # into HTML. You can use either format, intermingled or separately.
  22. # You can also extend RedCloth to honor your own custom text stylings.
  23. #
  24. # RedCloth users are encouraged to use Textile if they are generating
  25. # HTML and to use Markdown if others will be viewing the plain text.
  26. #
  27. # == What is Textile?
  28. #
  29. # Textile is a simple formatting style for text
  30. # documents, loosely based on some HTML conventions.
  31. #
  32. # == Sample Textile Text
  33. #
  34. # h2. This is a title
  35. #
  36. # h3. This is a subhead
  37. #
  38. # This is a bit of paragraph.
  39. #
  40. # bq. This is a blockquote.
  41. #
  42. # = Writing Textile
  43. #
  44. # A Textile document consists of paragraphs. Paragraphs
  45. # can be specially formatted by adding a small instruction
  46. # to the beginning of the paragraph.
  47. #
  48. # h[n]. Header of size [n].
  49. # bq. Blockquote.
  50. # # Numeric list.
  51. # * Bulleted list.
  52. #
  53. # == Quick Phrase Modifiers
  54. #
  55. # Quick phrase modifiers are also included, to allow formatting
  56. # of small portions of text within a paragraph.
  57. #
  58. # \_emphasis\_
  59. # \_\_italicized\_\_
  60. # \*strong\*
  61. # \*\*bold\*\*
  62. # ??citation??
  63. # -deleted text-
  64. # +inserted text+
  65. # ^superscript^
  66. # ~subscript~
  67. # @code@
  68. # %(classname)span%
  69. #
  70. # ==notextile== (leave text alone)
  71. #
  72. # == Links
  73. #
  74. # To make a hypertext link, put the link text in "quotation
  75. # marks" followed immediately by a colon and the URL of the link.
  76. #
  77. # Optional: text in (parentheses) following the link text,
  78. # but before the closing quotation mark, will become a Title
  79. # attribute for the link, visible as a tool tip when a cursor is above it.
  80. #
  81. # Example:
  82. #
  83. # "This is a link (This is a title) ":http://www.textism.com
  84. #
  85. # Will become:
  86. #
  87. # <a href="http://www.textism.com" title="This is a title">This is a link</a>
  88. #
  89. # == Images
  90. #
  91. # To insert an image, put the URL for the image inside exclamation marks.
  92. #
  93. # Optional: text that immediately follows the URL in (parentheses) will
  94. # be used as the Alt text for the image. Images on the web should always
  95. # have descriptive Alt text for the benefit of readers using non-graphical
  96. # browsers.
  97. #
  98. # Optional: place a colon followed by a URL immediately after the
  99. # closing ! to make the image into a link.
  100. #
  101. # Example:
  102. #
  103. # !http://www.textism.com/common/textist.gif(Textist)!
  104. #
  105. # Will become:
  106. #
  107. # <img src="http://www.textism.com/common/textist.gif" alt="Textist" />
  108. #
  109. # With a link:
  110. #
  111. # !/common/textist.gif(Textist)!:http://textism.com
  112. #
  113. # Will become:
  114. #
  115. # <a href="http://textism.com"><img src="/common/textist.gif" alt="Textist" /></a>
  116. #
  117. # == Defining Acronyms
  118. #
  119. # HTML allows authors to define acronyms via the tag. The definition appears as a
  120. # tool tip when a cursor hovers over the acronym. A crucial aid to clear writing,
  121. # this should be used at least once for each acronym in documents where they appear.
  122. #
  123. # To quickly define an acronym in Textile, place the full text in (parentheses)
  124. # immediately following the acronym.
  125. #
  126. # Example:
  127. #
  128. # ACLU(American Civil Liberties Union)
  129. #
  130. # Will become:
  131. #
  132. # <acronym title="American Civil Liberties Union">ACLU</acronym>
  133. #
  134. # == Adding Tables
  135. #
  136. # In Textile, simple tables can be added by seperating each column by
  137. # a pipe.
  138. #
  139. # |a|simple|table|row|
  140. # |And|Another|table|row|
  141. #
  142. # Attributes are defined by style definitions in parentheses.
  143. #
  144. # table(border:1px solid black).
  145. # (background:#ddd;color:red). |{}| | | |
  146. #
  147. # == Using RedCloth
  148. #
  149. # RedCloth is simply an extension of the String class, which can handle
  150. # Textile formatting. Use it like a String and output HTML with its
  151. # RedCloth#to_html method.
  152. #
  153. # doc = RedCloth.new "
  154. #
  155. # h2. Test document
  156. #
  157. # Just a simple test."
  158. #
  159. # puts doc.to_html
  160. #
  161. # By default, RedCloth uses both Textile and Markdown formatting, with
  162. # Textile formatting taking precedence. If you want to turn off Markdown
  163. # formatting, to boost speed and limit the processor:
  164. #
  165. # class RedCloth::Textile.new( str )
  166. class RedCloth3 < String
  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 = '(?:\[[^\[\]]+\])'
  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. (\w|[^\s].*?[^\s]) # content
  366. (?!\-\-)
  367. #{rcq}
  368. (#{QTAGS_JOIN}|) # oqa
  369. (?=[[:punct:]]|<|\s|\)|$)/x
  370. else
  371. /(#{rcq})
  372. (#{C})
  373. (?::(\S+))?
  374. (\w|[^\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. "<acronym title=\"#{htmlesc $2}\">#{$1}</acronym>"
  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. style << "#{ htmlesc $1 };" if text.sub!( /\{([^}]*)\}/, '' ) && !filter_styles
  447. lang = $1 if
  448. text.sub!( /\[([^)]+?)\]/, '' )
  449. cls = $1 if
  450. text.sub!( /\(([^()]+?)\)/, '' )
  451. style << "padding-left:#{ $1.length }em;" if
  452. text.sub!( /([(]+)/, '' )
  453. style << "padding-right:#{ $1.length }em;" if text.sub!( /([)]+)/, '' )
  454. style << "text-align:#{ h_align( $& ) };" if text =~ A_HLGN
  455. cls, id = $1, $2 if cls =~ /^(.*?)#(.*)$/
  456. atts = ''
  457. atts << " style=\"#{ style.join }\"" unless style.empty?
  458. atts << " class=\"#{ cls }\"" unless cls.to_s.empty?
  459. atts << " lang=\"#{ lang }\"" if lang
  460. atts << " id=\"#{ id }\"" if id
  461. atts << " colspan=\"#{ colspan }\"" if colspan
  462. atts << " rowspan=\"#{ rowspan }\"" if rowspan
  463. atts
  464. end
  465. TABLE_RE = /^(?:table(_?#{S}#{A}#{C})\. ?\n)?^(#{A}#{C}\.? ?\|.*?\|)(\n\n|\Z)/m
  466. # Parses a Textile table block, building HTML from the result.
  467. def block_textile_table( text )
  468. text.gsub!( TABLE_RE ) do |matches|
  469. tatts, fullrow = $~[1..2]
  470. tatts = pba( tatts, 'table' )
  471. tatts = shelve( tatts ) if tatts
  472. rows = []
  473. fullrow.each_line do |row|
  474. ratts, row = pba( $1, 'tr' ), $2 if row =~ /^(#{A}#{C}\. )(.*)/m
  475. cells = []
  476. row.split( /(\|)(?![^\[\|]*\]\])/ )[1..-2].each do |cell|
  477. next if cell == '|'
  478. ctyp = 'd'
  479. ctyp = 'h' if cell =~ /^_/
  480. catts = ''
  481. catts, cell = pba( $1, 'td' ), $2 if cell =~ /^(_?#{S}#{A}#{C}\. ?)(.*)/
  482. catts = shelve( catts ) if catts
  483. cells << "\t\t\t<t#{ ctyp }#{ catts }>#{ cell }</t#{ ctyp }>"
  484. end
  485. ratts = shelve( ratts ) if ratts
  486. rows << "\t\t<tr#{ ratts }>\n#{ cells.join( "\n" ) }\n\t\t</tr>"
  487. end
  488. "\t<table#{ tatts }>\n#{ rows.join( "\n" ) }\n\t</table>\n\n"
  489. end
  490. end
  491. LISTS_RE = /^([#*]+?#{C} .*?)$(?![^#*])/m
  492. LISTS_CONTENT_RE = /^([#*]+)(#{A}#{C}) (.*)$/m
  493. # Parses Textile lists and generates HTML
  494. def block_textile_lists( text )
  495. text.gsub!( LISTS_RE ) do |match|
  496. lines = match.split( /\n/ )
  497. last_line = -1
  498. depth = []
  499. lines.each_with_index do |line, line_id|
  500. if line =~ LISTS_CONTENT_RE
  501. tl,atts,content = $~[1..3]
  502. if depth.last
  503. if depth.last.length > tl.length
  504. (depth.length - 1).downto(0) do |i|
  505. break if depth[i].length == tl.length
  506. lines[line_id - 1] << "</li>\n\t</#{ lT( depth[i] ) }l>\n\t"
  507. depth.pop
  508. end
  509. end
  510. if depth.last and depth.last.length == tl.length
  511. lines[line_id - 1] << '</li>'
  512. end
  513. end
  514. unless depth.last == tl
  515. depth << tl
  516. atts = pba( atts )
  517. atts = shelve( atts ) if atts
  518. lines[line_id] = "\t<#{ lT(tl) }l#{ atts }>\n\t<li>#{ content }"
  519. else
  520. lines[line_id] = "\t\t<li>#{ content }"
  521. end
  522. last_line = line_id
  523. else
  524. last_line = line_id
  525. end
  526. if line_id - last_line > 1 or line_id == lines.length - 1
  527. depth.delete_if do |v|
  528. lines[last_line] << "</li>\n\t</#{ lT( v ) }l>"
  529. end
  530. end
  531. end
  532. lines.join( "\n" )
  533. end
  534. end
  535. QUOTES_RE = /(^>+([^\n]*?)(\n|$))+/m
  536. QUOTES_CONTENT_RE = /^([> ]+)(.*)$/m
  537. def block_textile_quotes( text )
  538. text.gsub!( QUOTES_RE ) do |match|
  539. lines = match.split( /\n/ )
  540. quotes = ''
  541. indent = 0
  542. lines.each do |line|
  543. line =~ QUOTES_CONTENT_RE
  544. bq,content = $1, $2
  545. l = bq.count('>')
  546. if l != indent
  547. quotes << ("\n\n" + (l>indent ? '<blockquote>' * (l-indent) : '</blockquote>' * (indent-l)) + "\n\n")
  548. indent = l
  549. end
  550. quotes << (content + "\n")
  551. end
  552. quotes << ("\n" + '</blockquote>' * indent + "\n\n")
  553. quotes
  554. end
  555. end
  556. CODE_RE = /(\W)
  557. @
  558. (?:\|(\w+?)\|)?
  559. (.+?)
  560. @
  561. (?=\W)/x
  562. def inline_textile_code( text )
  563. text.gsub!( CODE_RE ) do |m|
  564. before,lang,code,after = $~[1..4]
  565. lang = " lang=\"#{ lang }\"" if lang
  566. rip_offtags( "#{ before }<code#{ lang }>#{ code }</code>#{ after }", false )
  567. end
  568. end
  569. def lT( text )
  570. text =~ /\#$/ ? 'o' : 'u'
  571. end
  572. def hard_break( text )
  573. text.gsub!( /(.)\n(?!\Z| *([#*=]+(\s|$)|[{|]))/, "\\1<br />" ) if hard_breaks
  574. end
  575. BLOCKS_GROUP_RE = /\n{2,}(?! )/m
  576. def blocks( text, deep_code = false )
  577. text.replace( text.split( BLOCKS_GROUP_RE ).collect do |blk|
  578. plain = blk !~ /\A[#*> ]/
  579. # skip blocks that are complex HTML
  580. if blk =~ /^<\/?(\w+).*>/ and not SIMPLE_HTML_TAGS.include? $1
  581. blk
  582. else
  583. # search for indentation levels
  584. blk.strip!
  585. if blk.empty?
  586. blk
  587. else
  588. code_blk = nil
  589. blk.gsub!( /((?:\n(?:\n^ +[^\n]*)+)+)/m ) do |iblk|
  590. flush_left iblk
  591. blocks iblk, plain
  592. iblk.gsub( /^(\S)/, "\t\\1" )
  593. if plain
  594. code_blk = iblk; ""
  595. else
  596. iblk
  597. end
  598. end
  599. block_applied = 0
  600. @rules.each do |rule_name|
  601. block_applied += 1 if ( rule_name.to_s.match /^block_/ and method( rule_name ).call( blk ) )
  602. end
  603. if block_applied.zero?
  604. if deep_code
  605. blk = "\t<pre><code>#{ blk }</code></pre>"
  606. else
  607. blk = "\t<p>#{ blk }</p>"
  608. end
  609. end
  610. # hard_break blk
  611. blk + "\n#{ code_blk }"
  612. end
  613. end
  614. end.join( "\n\n" ) )
  615. end
  616. def textile_bq( tag, atts, cite, content )
  617. cite, cite_title = check_refs( cite )
  618. cite = " cite=\"#{ cite }\"" if cite
  619. atts = shelve( atts ) if atts
  620. "\t<blockquote#{ cite }>\n\t\t<p#{ atts }>#{ content }</p>\n\t</blockquote>"
  621. end
  622. def textile_p( tag, atts, cite, content )
  623. atts = shelve( atts ) if atts
  624. "\t<#{ tag }#{ atts }>#{ content }</#{ tag }>"
  625. end
  626. alias textile_h1 textile_p
  627. alias textile_h2 textile_p
  628. alias textile_h3 textile_p
  629. alias textile_h4 textile_p
  630. alias textile_h5 textile_p
  631. alias textile_h6 textile_p
  632. def textile_fn_( tag, num, atts, cite, content )
  633. atts << " id=\"fn#{ num }\" class=\"footnote\""
  634. content = "<sup>#{ num }</sup> #{ content }"
  635. atts = shelve( atts ) if atts
  636. "\t<p#{ atts }>#{ content }</p>"
  637. end
  638. BLOCK_RE = /^(([a-z]+)(\d*))(#{A}#{C})\.(?::(\S+))? (.*)$/m
  639. def block_textile_prefix( text )
  640. if text =~ BLOCK_RE
  641. tag,tagpre,num,atts,cite,content = $~[1..6]
  642. atts = pba( atts )
  643. # pass to prefix handler
  644. replacement = nil
  645. if respond_to? "textile_#{ tag }", true
  646. replacement = method( "textile_#{ tag }" ).call( tag, atts, cite, content )
  647. elsif respond_to? "textile_#{ tagpre }_", true
  648. replacement = method( "textile_#{ tagpre }_" ).call( tagpre, num, atts, cite, content )
  649. end
  650. text.gsub!( $& ) { replacement } if replacement
  651. end
  652. end
  653. SETEXT_RE = /\A(.+?)\n([=-])[=-]* *$/m
  654. def block_markdown_setext( text )
  655. if text =~ SETEXT_RE
  656. tag = if $2 == "="; "h1"; else; "h2"; end
  657. blk, cont = "<#{ tag }>#{ $1 }</#{ tag }>", $'
  658. blocks cont
  659. text.replace( blk + cont )
  660. end
  661. end
  662. ATX_RE = /\A(\#{1,6}) # $1 = string of #'s
  663. [ ]*
  664. (.+?) # $2 = Header text
  665. [ ]*
  666. \#* # optional closing #'s (not counted)
  667. $/x
  668. def block_markdown_atx( text )
  669. if text =~ ATX_RE
  670. tag = "h#{ $1.length }"
  671. blk, cont = "<#{ tag }>#{ $2 }</#{ tag }>\n\n", $'
  672. blocks cont
  673. text.replace( blk + cont )
  674. end
  675. end
  676. MARKDOWN_BQ_RE = /\A(^ *> ?.+$(.+\n)*\n*)+/m
  677. def block_markdown_bq( text )
  678. text.gsub!( MARKDOWN_BQ_RE ) do |blk|
  679. blk.gsub!( /^ *> ?/, '' )
  680. flush_left blk
  681. blocks blk
  682. blk.gsub!( /^(\S)/, "\t\\1" )
  683. "<blockquote>\n#{ blk }\n</blockquote>\n\n"
  684. end
  685. end
  686. MARKDOWN_RULE_RE = /^(#{
  687. ['*', '-', '_'].collect { |ch| ' ?(' + Regexp::quote( ch ) + ' ?){3,}' }.join( '|' )
  688. })$/
  689. def block_markdown_rule( text )
  690. text.gsub!( MARKDOWN_RULE_RE ) do |blk|
  691. "<hr />"
  692. end
  693. end
  694. # XXX TODO XXX
  695. def block_markdown_lists( text )
  696. end
  697. def inline_textile_span( text )
  698. QTAGS.each do |qtag_rc, ht, qtag_re, rtype|
  699. text.gsub!( qtag_re ) do |m|
  700. case rtype
  701. when :limit
  702. sta,oqs,qtag,content,oqa = $~[1..6]
  703. atts = nil
  704. if content =~ /^(#{C})(.+)$/
  705. atts, content = $~[1..2]
  706. end
  707. else
  708. qtag,atts,cite,content = $~[1..4]
  709. sta = ''
  710. end
  711. atts = pba( atts )
  712. atts = shelve( atts ) if atts
  713. "#{ sta }#{ oqs }<#{ ht }#{ atts }>#{ content }</#{ ht }>#{ oqa }"
  714. end
  715. end
  716. end
  717. LINK_RE = /
  718. (
  719. ([\s\[{(]|[#{PUNCT}])? # $pre
  720. " # start
  721. (#{C}) # $atts
  722. ([^"\n]+?) # $text
  723. \s?
  724. (?:\(([^)]+?)\)(?="))? # $title
  725. ":
  726. ( # $url
  727. (\/|[a-zA-Z]+:\/\/|www\.|mailto:) # $proto
  728. [\w\/]\S+?
  729. )
  730. (\/)? # $slash
  731. ([^\w\=\/;\(\)]*?) # $post
  732. )
  733. (?=<|\s|$)
  734. /x
  735. #"
  736. def inline_textile_link( text )
  737. text.gsub!( LINK_RE ) do |m|
  738. all,pre,atts,text,title,url,proto,slash,post = $~[1..9]
  739. if text.include?('<br />')
  740. all
  741. else
  742. url, url_title = check_refs( url )
  743. title ||= url_title
  744. # Idea below : an URL with unbalanced parethesis and
  745. # ending by ')' is put into external parenthesis
  746. if ( url[-1]==?) and ((url.count("(") - url.count(")")) < 0 ) )
  747. url=url[0..-2] # discard closing parenth from url
  748. post = ")"+post # add closing parenth to post
  749. end
  750. atts = pba( atts )
  751. atts = " href=\"#{ htmlesc url }#{ slash }\"#{ atts }"
  752. atts << " title=\"#{ htmlesc title }\"" if title
  753. atts = shelve( atts ) if atts
  754. external = (url =~ /^https?:\/\//) ? ' class="external"' : ''
  755. "#{ pre }<a#{ atts }#{ external }>#{ text }</a>#{ post }"
  756. end
  757. end
  758. end
  759. MARKDOWN_REFLINK_RE = /
  760. \[([^\[\]]+)\] # $text
  761. [ ]? # opt. space
  762. (?:\n[ ]*)? # one optional newline followed by spaces
  763. \[(.*?)\] # $id
  764. /x
  765. def inline_markdown_reflink( text )
  766. text.gsub!( MARKDOWN_REFLINK_RE ) do |m|
  767. text, id = $~[1..2]
  768. if id.empty?
  769. url, title = check_refs( text )
  770. else
  771. url, title = check_refs( id )
  772. end
  773. atts = " href=\"#{ url }\""
  774. atts << " title=\"#{ title }\"" if title
  775. atts = shelve( atts )
  776. "<a#{ atts }>#{ text }</a>"
  777. end
  778. end
  779. MARKDOWN_LINK_RE = /
  780. \[([^\[\]]+)\] # $text
  781. \( # open paren
  782. [ \t]* # opt space
  783. <?(.+?)>? # $href
  784. [ \t]* # opt space
  785. (?: # whole title
  786. (['"]) # $quote
  787. (.*?) # $title
  788. \3 # matching quote
  789. )? # title is optional
  790. \)
  791. /x
  792. def inline_markdown_link( text )
  793. text.gsub!( MARKDOWN_LINK_RE ) do |m|
  794. text, url, quote, title = $~[1..4]
  795. atts = " href=\"#{ url }\""
  796. atts << " title=\"#{ title }\"" if title
  797. atts = shelve( atts )
  798. "<a#{ atts }>#{ text }</a>"
  799. end
  800. end
  801. TEXTILE_REFS_RE = /(^ *)\[([^\[\n]+?)\](#{HYPERLINK})(?=\s|$)/
  802. MARKDOWN_REFS_RE = /(^ *)\[([^\n]+?)\]:\s+<?(#{HYPERLINK})>?(?:\s+"((?:[^"]|\\")+)")?(?=\s|$)/m
  803. def refs( text )
  804. @rules.each do |rule_name|
  805. method( rule_name ).call( text ) if rule_name.to_s.match /^refs_/
  806. end
  807. end
  808. def refs_textile( text )
  809. text.gsub!( TEXTILE_REFS_RE ) do |m|
  810. flag, url = $~[2..3]
  811. @urlrefs[flag.downcase] = [url, nil]
  812. nil
  813. end
  814. end
  815. def refs_markdown( text )
  816. text.gsub!( MARKDOWN_REFS_RE ) do |m|
  817. flag, url = $~[2..3]
  818. title = $~[6]
  819. @urlrefs[flag.downcase] = [url, title]
  820. nil
  821. end
  822. end
  823. def check_refs( text )
  824. ret = @urlrefs[text.downcase] if text
  825. ret || [text, nil]
  826. end
  827. IMAGE_RE = /
  828. (>|\s|^) # start of line?
  829. \! # opening
  830. (\<|\=|\>)? # optional alignment atts
  831. (#{C}) # optional style,class atts
  832. (?:\. )? # optional dot-space
  833. ([^\s(!]+?) # presume this is the src
  834. \s? # optional space
  835. (?:\(((?:[^\(\)]|\([^\)]+\))+?)\))? # optional title
  836. \! # closing
  837. (?::#{ HYPERLINK })? # optional href
  838. /x
  839. def inline_textile_image( text )
  840. text.gsub!( IMAGE_RE ) do |m|
  841. stln,algn,atts,url,title,href,href_a1,href_a2 = $~[1..8]
  842. htmlesc title
  843. atts = pba( atts )
  844. atts = " src=\"#{ htmlesc url.dup }\"#{ atts }"
  845. atts << " title=\"#{ title }\"" if title
  846. atts << " alt=\"#{ title }\""
  847. # size = @getimagesize($url);
  848. # if($size) $atts.= " $size[3]";
  849. href, alt_title = check_refs( href ) if href
  850. url, url_title = check_refs( url )
  851. out = ''
  852. out << "<a#{ shelve( " href=\"#{ href }\"" ) }>" if href
  853. out << "<img#{ shelve( atts ) } />"
  854. out << "</a>#{ href_a1 }#{ href_a2 }" if href
  855. if algn
  856. algn = h_align( algn )
  857. if stln == "<p>"
  858. out = "<p style=\"float:#{ algn }\">#{ out }"
  859. else
  860. out = "#{ stln }<div style=\"float:#{ algn }\">#{ out }</div>"
  861. end
  862. else
  863. out = stln + out
  864. end
  865. out
  866. end
  867. end
  868. def shelve( val )
  869. @shelf << val
  870. " :redsh##{ @shelf.length }:"
  871. end
  872. def retrieve( text )
  873. @shelf.each_with_index do |r, i|
  874. text.gsub!( " :redsh##{ i + 1 }:", r )
  875. end
  876. end
  877. def incoming_entities( text )
  878. ## turn any incoming ampersands into a dummy character for now.
  879. ## This uses a negative lookahead for alphanumerics followed by a semicolon,
  880. ## implying an incoming html entity, to be skipped
  881. text.gsub!( /&(?![#a-z0-9]+;)/i, "x%x%" )
  882. end
  883. def no_textile( text )
  884. text.gsub!( /(^|\s)==([^=]+.*?)==(\s|$)?/,
  885. '\1<notextile>\2</notextile>\3' )
  886. text.gsub!( /^ *==([^=]+.*?)==/m,
  887. '\1<notextile>\2</notextile>\3' )
  888. end
  889. def clean_white_space( text )
  890. # normalize line breaks
  891. text.gsub!( /\r\n/, "\n" )
  892. text.gsub!( /\r/, "\n" )
  893. text.gsub!( /\t/, ' ' )
  894. text.gsub!( /^ +$/, '' )
  895. text.gsub!( /\n{3,}/, "\n\n" )
  896. text.gsub!( /"$/, "\" " )
  897. # if entire document is indented, flush
  898. # to the left side
  899. flush_left text
  900. end
  901. def flush_left( text )
  902. indt = 0
  903. if text =~ /^ /
  904. while text !~ /^ {#{indt}}\S/
  905. indt += 1
  906. end unless text.empty?
  907. if indt.nonzero?
  908. text.gsub!( /^ {#{indt}}/, '' )
  909. end
  910. end
  911. end
  912. def footnote_ref( text )
  913. text.gsub!( /\b\[([0-9]+?)\](\s)?/,
  914. '<sup><a href="#fn\1">\1</a></sup>\2' )
  915. end
  916. OFFTAGS = /(code|pre|kbd|notextile)/
  917. OFFTAG_MATCH = /(?:(<\/#{ OFFTAGS }>)|(<#{ OFFTAGS }[^>]*>))(.*?)(?=<\/?#{ OFFTAGS }\W|\Z)/mi
  918. OFFTAG_OPEN = /<#{ OFFTAGS }/
  919. OFFTAG_CLOSE = /<\/?#{ OFFTAGS }/
  920. HASTAG_MATCH = /(<\/?\w[^\n]*?>)/m
  921. ALLTAG_MATCH = /(<\/?\w[^\n]*?>)|.*?(?=<\/?\w[^\n]*?>|$)/m
  922. def glyphs_textile( text, level = 0 )
  923. if text !~ HASTAG_MATCH
  924. pgl text
  925. footnote_ref text
  926. else
  927. codepre = 0
  928. text.gsub!( ALLTAG_MATCH ) do |line|
  929. ## matches are off if we're between <code>, <pre> etc.
  930. if $1
  931. if line =~ OFFTAG_OPEN
  932. codepre += 1
  933. elsif line =~ OFFTAG_CLOSE
  934. codepre -= 1
  935. codepre = 0 if codepre < 0
  936. end
  937. elsif codepre.zero?
  938. glyphs_textile( line, level + 1 )
  939. else
  940. htmlesc( line, :NoQuotes )
  941. end
  942. # p [level, codepre, line]
  943. line
  944. end
  945. end
  946. end
  947. def rip_offtags( text, escape_aftertag=true )
  948. if text =~ /<.*>/
  949. ## strip and encode <pre> content
  950. codepre, used_offtags = 0, {}
  951. text.gsub!( OFFTAG_MATCH ) do |line|
  952. if $3
  953. first, offtag, aftertag = $3, $4, $5
  954. codepre += 1
  955. used_offtags[offtag] = true
  956. if codepre - used_offtags.length > 0
  957. htmlesc( line, :NoQuotes )
  958. @pre_list.last << line
  959. line = ""
  960. else
  961. ### htmlesc is disabled between CODE tags which will be parsed with highlighter
  962. ### Regexp in formatter.rb is : /<code\s+class="(\w+)">\s?(.+)/m
  963. ### NB: some changes were made not to use $N variables, because we use "match"
  964. ### and it breaks following lines
  965. htmlesc( aftertag, :NoQuotes ) if aftertag && escape_aftertag && !first.match(/<code\s+class="(\w+)">/)
  966. line = "<redpre##{ @pre_list.length }>"
  967. first.match(/<#{ OFFTAGS }([^>]*)>/)
  968. tag = $1
  969. $2.to_s.match(/(class\=("[^"]+"|'[^']+'))/i)
  970. tag << " #{$1}" if $1
  971. @pre_list << "<#{ tag }>#{ aftertag }"
  972. end
  973. elsif $1 and codepre > 0
  974. if codepre - used_offtags.length > 0
  975. htmlesc( line, :NoQuotes )
  976. @pre_list.last << line
  977. line = ""
  978. end
  979. codepre -= 1 unless codepre.zero?
  980. used_offtags = {} if codepre.zero?
  981. end
  982. line
  983. end
  984. end
  985. text
  986. end
  987. def smooth_offtags( text )
  988. unless @pre_list.empty?
  989. ## replace <pre> content
  990. text.gsub!( /<redpre#(\d+)>/ ) { @pre_list[$1.to_i] }
  991. end
  992. end
  993. def inline( text )
  994. [/^inline_/, /^glyphs_/].each do |meth_re|
  995. @rules.each do |rule_name|
  996. method( rule_name ).call( text ) if rule_name.to_s.match( meth_re )
  997. end
  998. end
  999. end
  1000. def h_align( text )
  1001. H_ALGN_VALS[text]
  1002. end
  1003. def v_align( text )
  1004. V_ALGN_VALS[text]
  1005. end
  1006. def textile_popup_help( name, windowW, windowH )
  1007. ' <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 />'
  1008. end
  1009. # HTML cleansing stuff
  1010. BASIC_TAGS = {
  1011. 'a' => ['href', 'title'],
  1012. 'img' => ['src', 'alt', 'title'],
  1013. 'br' => [],
  1014. 'i' => nil,
  1015. 'u' => nil,
  1016. 'b' => nil,
  1017. 'pre' => nil,
  1018. 'kbd' => nil,
  1019. 'code' => ['lang'],
  1020. 'cite' => nil,
  1021. 'strong' => nil,
  1022. 'em' => nil,
  1023. 'ins' => nil,
  1024. 'sup' => nil,
  1025. 'sub' => nil,
  1026. 'del' => nil,
  1027. 'table' => nil,
  1028. 'tr' => nil,
  1029. 'td' => ['colspan', 'rowspan'],
  1030. 'th' => nil,
  1031. 'ol' => nil,
  1032. 'ul' => nil,
  1033. 'li' => nil,
  1034. 'p' => nil,
  1035. 'h1' => nil,
  1036. 'h2' => nil,
  1037. 'h3' => nil,
  1038. 'h4' => nil,
  1039. 'h5' => nil,
  1040. 'h6' => nil,
  1041. 'blockquote' => ['cite']
  1042. }
  1043. def clean_html( text, tags = BASIC_TAGS )
  1044. text.gsub!( /<!\[CDATA\[/, '' )
  1045. text.gsub!( /<(\/*)(\w+)([^>]*)>/ ) do
  1046. raw = $~
  1047. tag = raw[2].downcase
  1048. if tags.has_key? tag
  1049. pcs = [tag]
  1050. tags[tag].each do |prop|
  1051. ['"', "'", ''].each do |q|
  1052. q2 = ( q != '' ? q : '\s' )
  1053. if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i
  1054. attrv = $1
  1055. next if prop == 'src' and attrv =~ %r{^(?!http)\w+:}
  1056. pcs << "#{prop}=\"#{$1.gsub('"', '\\"')}\""
  1057. break
  1058. end
  1059. end
  1060. end if tags[tag]
  1061. "<#{raw[1]}#{pcs.join " "}>"
  1062. else
  1063. " "
  1064. end
  1065. end
  1066. end
  1067. ALLOWED_TAGS = %w(redpre pre code notextile)
  1068. def escape_html_tags(text)
  1069. text.gsub!(%r{<(\/?([!\w]+)[^<>\n]*)(>?)}) {|m| ALLOWED_TAGS.include?($2) ? "<#{$1}#{$3}" : "&lt;#{$1}#{'&gt;' unless $3.blank?}" }
  1070. end
  1071. end