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.

redcloth.rb 35KB

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