PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/extensions/textile_filter/vendor/redcloth/lib/rctodb.rb

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