#-- encoding: UTF-8 # vim:ts=4:sw=4: # = RedCloth - Textile and Markdown Hybrid for Ruby # # Homepage:: http://whytheluckystiff.net/ruby/redcloth/ # Author:: why the lucky stiff (http://whytheluckystiff.net/) # Copyright:: (cc) 2004 why the lucky stiff (and his puppet organizations.) # License:: BSD # # (see http://hobix.com/textile/ for a Textile Reference.) # # Based on (and also inspired by) both: # # PyTextile: http://diveintomark.org/projects/textile/textile.py.txt # Textism for PHP: http://www.textism.com/tools/textile/ # # # = RedCloth # # RedCloth is a Ruby library for converting Textile and/or Markdown # into HTML. You can use either format, intermingled or separately. # You can also extend RedCloth to honor your own custom text stylings. # # RedCloth users are encouraged to use Textile if they are generating # HTML and to use Markdown if others will be viewing the plain text. # # == What is Textile? # # Textile is a simple formatting style for text # documents, loosely based on some HTML conventions. # # == Sample Textile Text # # h2. This is a title # # h3. This is a subhead # # This is a bit of paragraph. # # bq. This is a blockquote. # # = Writing Textile # # A Textile document consists of paragraphs. Paragraphs # can be specially formatted by adding a small instruction # to the beginning of the paragraph. # # h[n]. Header of size [n]. # bq. Blockquote. # # Numeric list. # * Bulleted list. # # == Quick Phrase Modifiers # # Quick phrase modifiers are also included, to allow formatting # of small portions of text within a paragraph. # # \_emphasis\_ # \_\_italicized\_\_ # \*strong\* # \*\*bold\*\* # ??citation?? # -deleted text- # +inserted text+ # ^superscript^ # ~subscript~ # @code@ # %(classname)span% # # ==notextile== (leave text alone) # # == Links # # To make a hypertext link, put the link text in "quotation # marks" followed immediately by a colon and the URL of the link. # # Optional: text in (parentheses) following the link text, # but before the closing quotation mark, will become a Title # attribute for the link, visible as a tool tip when a cursor is above it. # # Example: # # "This is a link (This is a title) ":http://www.textism.com # # Will become: # # This is a link # # == Images # # To insert an image, put the URL for the image inside exclamation marks. # # Optional: text that immediately follows the URL in (parentheses) will # be used as the Alt text for the image. Images on the web should always # have descriptive Alt text for the benefit of readers using non-graphical # browsers. # # Optional: place a colon followed by a URL immediately after the # closing ! to make the image into a link. # # Example: # # !http://www.textism.com/common/textist.gif(Textist)! # # Will become: # # # # With a link: # # !/common/textist.gif(Textist)!:http://textism.com # # Will become: # # # # == Defining Acronyms # # HTML allows authors to define acronyms via the tag. The definition appears as a # tool tip when a cursor hovers over the acronym. A crucial aid to clear writing, # this should be used at least once for each acronym in documents where they appear. # # To quickly define an acronym in Textile, place the full text in (parentheses) # immediately following the acronym. # # Example: # # ACLU(American Civil Liberties Union) # # Will become: # # ACLU # # == Adding Tables # # In Textile, simple tables can be added by separating each column by # a pipe. # # |a|simple|table|row| # |And|Another|table|row| # # Attributes are defined by style definitions in parentheses. # # table(border:1px solid black). # (background:#ddd;color:red). |{}| | | | # # == Using RedCloth # # RedCloth is simply an extension of the String class, which can handle # Textile formatting. Use it like a String and output HTML with its # RedCloth#to_html method. # # doc = RedCloth.new " # # h2. Test document # # Just a simple test." # # puts doc.to_html # # By default, RedCloth uses both Textile and Markdown formatting, with # Textile formatting taking precedence. If you want to turn off Markdown # formatting, to boost speed and limit the processor: # # class RedCloth::Textile.new( str ) class RedCloth3 < String VERSION = '3.0.4' DEFAULT_RULES = [:textile, :markdown] # # Two accessor for setting security restrictions. # # This is a nice thing if you're using RedCloth for # formatting in public places (e.g. Wikis) where you # don't want users to abuse HTML for bad things. # # If +:filter_html+ is set, HTML which wasn't # created by the Textile processor will be escaped. # # If +:filter_styles+ is set, it will also disable # the style markup specifier. ('{color: red}') # attr_accessor :filter_html, :filter_styles # # Accessor for toggling hard breaks. # # If +:hard_breaks+ is set, single newlines will # be converted to HTML break tags. This is the # default behavior for traditional RedCloth. # attr_accessor :hard_breaks # Accessor for toggling lite mode. # # In lite mode, block-level rules are ignored. This means # that tables, paragraphs, lists, and such aren't available. # Only the inline markup for bold, italics, entities and so on. # # r = RedCloth.new( "And then? She *fell*!", [:lite_mode] ) # r.to_html # #=> "And then? She fell!" # attr_accessor :lite_mode # # Accessor for toggling span caps. # # Textile places `span' tags around capitalized # words by default, but this wreaks havoc on Wikis. # If +:no_span_caps+ is set, this will be # suppressed. # attr_accessor :no_span_caps # # Establishes the markup predence. Available rules include: # # == Textile Rules # # The following textile rules can be set individually. Or add the complete # set of rules with the single :textile rule, which supplies the rule set in # the following precedence: # # refs_textile:: Textile references (i.e. [hobix]http://hobix.com/) # block_textile_table:: Textile table block structures # block_textile_lists:: Textile list structures # block_textile_prefix:: Textile blocks with prefixes (i.e. bq., h2., etc.) # inline_textile_image:: Textile inline images # inline_textile_link:: Textile inline links # inline_textile_span:: Textile inline spans # glyphs_textile:: Textile entities (such as em-dashes and smart quotes) # # == Markdown # # refs_markdown:: Markdown references (for example: [hobix]: http://hobix.com/) # block_markdown_setext:: Markdown setext headers # block_markdown_atx:: Markdown atx headers # block_markdown_rule:: Markdown horizontal rules # block_markdown_bq:: Markdown blockquotes # block_markdown_lists:: Markdown lists # inline_markdown_link:: Markdown links attr_accessor :rules # Returns a new RedCloth object, based on _string_ and # enforcing all the included _restrictions_. # # r = RedCloth.new( "h1. A bold man", [:filter_html] ) # r.to_html # #=>"
' * (l - indent) else '' * (indent - l) end) + "\n\n") indent = l end quotes << (content + "\n") end quotes << ("\n" + '' * indent + "\n\n") quotes end end CODE_RE = /(\W) @ (?:\|(\w+?)\|)? (.+?) @ (?=\W)/x def inline_textile_code(text) text.gsub!(CODE_RE) do |_m| before, lang,code, after = $~[1..4] lang = " lang=\"#{ lang }\"" if lang rip_offtags("#{before}
#{code}
#{after}", false)
end
end
def LT(text)
text =~ /\#$/ ? 'o' : 'u'
end
def hard_break(text)
text.gsub!( /(.)\n(?!\Z| *([#*=]+(\s|$)|[{|]))/, "\\1#{ blk }
"
else
blk = "\t#{ blk }
" end end # hard_break blk blk + "\n#{ code_blk }" end end end.join( "\n\n" ) ) end def textile_bq( _tag, atts, cite, content ) cite, cite_title = check_refs( cite ) cite = " cite=\"#{ cite }\"" if cite atts = shelve( atts ) if atts "\t\n\t\t" end def textile_p( tag, atts, _cite, content ) atts = shelve( atts ) if atts "\t<#{ tag }#{ atts }>#{ content }#{ tag }>" end alias textile_h1 textile_p alias textile_h2 textile_p alias textile_h3 textile_p alias textile_h4 textile_p alias textile_h5 textile_p alias textile_h6 textile_p def textile_fn_( _tag, num, atts, _cite, content ) atts << " id=\"fn#{ num }\" class=\"footnote\"" content = "#{ num } #{ content }" atts = shelve( atts ) if atts "\t#{ content }
\n\t
#{ content }
" end BLOCK_RE = /^(([a-z]+)(\d*))(#{A}#{C})\.(?::(\S+))? (.*)$/m def block_textile_prefix( text ) if text =~ BLOCK_RE tag,tagpre,num,atts,cite,content = $~[1..6] atts = pba( atts ) # pass to prefix handler replacement = nil if respond_to? "textile_#{ tag }", true replacement = method( "textile_#{ tag }" ).call( tag, atts, cite, content ) elsif respond_to? "textile_#{ tagpre }_", true replacement = method( "textile_#{ tagpre }_" ).call( tagpre, num, atts, cite, content ) end text.gsub!( $& ) { replacement } if replacement end end SETEXT_RE = /\A(.+?)\n([=-])[=-]* *$/m def block_markdown_setext( text ) if text =~ SETEXT_RE tag = if $2 == "="; "h1"; else; "h2"; end blk, cont = "<#{ tag }>#{ $1 }#{ tag }>", $' blocks cont text.replace( blk + cont ) end end ATX_RE = /\A(\#{1,6}) # $1 = string of #'s [ ]* (.+?) # $2 = Header text [ ]* \#* # optional closing #'s (not counted) $/x def block_markdown_atx( text ) if text =~ ATX_RE tag = "h#{ $1.length }" blk, cont = "<#{ tag }>#{ $2 }#{ tag }>\n\n", $' blocks cont text.replace( blk + cont ) end end MARKDOWN_BQ_RE = /\A(^ *> ?.+$(.+\n)*\n*)+/m def block_markdown_bq( text ) text.gsub!( MARKDOWN_BQ_RE ) do |blk| blk.gsub!( /^ *> ?/, '' ) flush_left blk blocks blk blk.gsub!( /^(\S)/, "\t\\1" ) "\n#{ blk }\n\n\n" end end MARKDOWN_RULE_RE = /^(#{ ['*', '-', '_'].map { |ch| ' ?(' + Regexp::quote( ch ) + ' ?){3,}' }.join( '|' ) })$/ def block_markdown_rule( text ) text.gsub!( MARKDOWN_RULE_RE ) do |_blk| "
" out = "
#{ out }" else out = "#{ stln }
, etc.
if $1
if line =~ OFFTAG_OPEN
codepre += 1
elsif line =~ OFFTAG_CLOSE
codepre -= 1
codepre = 0 if codepre < 0
end
elsif codepre.zero?
glyphs_textile( line, level + 1 )
else
htmlesc( line, :NoQuotes )
end
# p [level, codepre, line]
line
end
end
end
def rip_offtags( text, escape_aftertag=true )
if text =~ /<.*>/
## strip and encode content
codepre, used_offtags = 0, {}
text.gsub!( OFFTAG_MATCH ) do |line|
if $3
first, offtag, aftertag = $3, $4, $5
codepre += 1
used_offtags[offtag] = true
if codepre - used_offtags.length > 0
htmlesc( line, :NoQuotes )
@pre_list.last << line
line = ""
else
### htmlesc is disabled between CODE tags which will be parsed with highlighter
### Regexp in formatter.rb is : /\s?(.+)/m
### NB: some changes were made not to use $N variables, because we use "match"
### and it breaks following lines
htmlesc( aftertag, :NoQuotes ) if aftertag && escape_aftertag && !first.match(//)
line = ""
first.match(/<#{ OFFTAGS }([^>]*)>/)
tag = $1
$2.to_s.match(/(class\=("[^"]+"|'[^']+'))/i)
tag << " #{$1}" if $1
@pre_list << "<#{ tag }>#{ aftertag }"
end
elsif $1 and codepre > 0
if codepre - used_offtags.length > 0
htmlesc( line, :NoQuotes )
@pre_list.last << line
line = ""
end
codepre -= 1 unless codepre.zero?
used_offtags = {} if codepre.zero?
end
line
end
end
text
end
def smooth_offtags( text )
unless @pre_list.empty?
## replace content
text.gsub!( // ) { @pre_list[$1.to_i] }
end
end
def inline( text )
[/^inline_/, /^glyphs_/].each do |meth_re|
@rules.each do |rule_name|
method( rule_name ).call( text ) if rule_name.to_s.match( meth_re )
end
end
end
def h_align( text )
H_ALGN_VALS[text]
end
def v_align( text )
V_ALGN_VALS[text]
end
def textile_popup_help( name, windowW, windowH )
' ' + name + '
'
end
# HTML cleansing stuff
BASIC_TAGS = {
'a' => ['href', 'title'],
'img' => ['src', 'alt', 'title'],
'br' => [],
'i' => nil,
'u' => nil,
'b' => nil,
'pre' => nil,
'kbd' => nil,
'code' => ['lang'],
'cite' => nil,
'strong' => nil,
'em' => nil,
'ins' => nil,
'sup' => nil,
'sub' => nil,
'del' => nil,
'table' => nil,
'tr' => nil,
'td' => ['colspan', 'rowspan'],
'th' => nil,
'ol' => nil,
'ul' => nil,
'li' => nil,
'p' => nil,
'h1' => nil,
'h2' => nil,
'h3' => nil,
'h4' => nil,
'h5' => nil,
'h6' => nil,
'blockquote' => ['cite']
}
def clean_html( text, tags = BASIC_TAGS )
text.gsub!( /]*)>/ ) do
raw = $~
tag = raw[2].downcase
if tags.has_key? tag
pcs = [tag]
tags[tag].each do |prop|
['"', "'", ''].each do |q|
q2 = ( q != '' ? q : '\s' )
if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]+)#{q}/i
attrv = $1
next if prop == 'src' and attrv =~ %r{^(?!http)\w+:}
pcs << "#{prop}=\"#{$1.gsub('"', '\\"')}\""
break
end
end
end if tags[tag]
"<#{raw[1]}#{pcs.join " "}>"
else
" "
end
end
end
ALLOWED_TAGS = %w(redpre pre code notextile)
def escape_html_tags(text)
text.gsub!(%r{<(\/?([!\w]+)[^<>\n]*)(>?)}) {|_m| ALLOWED_TAGS.include?($2) ? "<#{$1}#{$3}" : "<#{$1}#{'>' unless $3.blank?}" }
end
end