PageRenderTime 140ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/oldredcloth.rb

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