You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

redcloth3.rb 38KB

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