Class: Lesstile

Inherits:
Object
  • Object
show all
Defined in:
lib/lesstile.rb

Constant Summary collapse

VERSION =
'1.0'
CodeDetectionRegex =
/---\s*?([\w\s\._+()-]*?)\s*?\n(.*?)---\n/m
CodeRayFormatter =

A formatter that syntax highlights code using CodeRay

lambda {|code, lang| 
  CodeRay.scan(CGI::unescapeHTML(code), lang).html(:line_numbers => :table).div 
}

Class Method Summary collapse

Class Method Details

.default_optionsObject



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/lesstile.rb', line 49

def default_options
  {
    :code_formatter => lambda {|code, lang| "<pre><code>#{code}</code></pre>" },
    :text_formatter => lambda {|text| 
      text = text.dup
      text.gsub!(/\n/, "<br />\n")
      text.gsub!('&quot;', '"')
      text.gsub!(Regexp.new('"([^"]+)":(' + URI.regexp.to_s + ')'), '<a href="\2">\1</a>')
      text
    }
  }
end

.format_as_html(text, options = {}) ⇒ Object

Returns lesstile formatted text as valid HTML5

options (all optional):

  • text_formatter: A callback function used to format text.

  • code_formatter: A callback function used to format code. Typically used for syntax highlighting.



45
46
47
# File 'lib/lesstile.rb', line 45

def format_as_html(text, options = {})
  format_as_xhtml(text, options)
end

.format_as_xhtml(text, options = {}) ⇒ Object

Returns lesstile formatted text as valid XHTML

options (all optional):

  • text_formatter: A callback function used to format text.

  • code_formatter: A callback function used to format code. Typically used for syntax highlighting.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/lesstile.rb', line 15

def format_as_xhtml(text, options = {})
  options = default_options.merge(options)

  text += "\n" unless ends_with?(text, "\n")
  text.gsub!(/\r\n/, "\n")
  text = CGI::escapeHTML(text)

  output = ""

  while match = text.match(CodeDetectionRegex)
    captures = match.captures
    code = captures[1]
    lang = blank?(captures[0]) ? nil : captures[0].downcase.strip.intern

    output += 
      options[:text_formatter][match.pre_match] +
      options[:code_formatter][code, lang]

    text = match.post_match
  end
  
  output += options[:text_formatter][text.chomp]
  output
end