PageRenderTime 29ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/redcloth.rb

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