Class: Octopress::Codefence::Highlighter

Inherits:
Object
  • Object
show all
Defined in:
lib/octopress-codefence.rb

Constant Summary collapse

AllOptions =
/([^\s]+)\s+(.+?)\s+(https?:\/\/\S+|\/\S+)\s*(.+)?/i
LangCaption =
/([^\s]+)\s*(.+)?/i

Instance Method Summary collapse

Constructor Details

#initialize(input, ext = nil, aliases = nil) ⇒ Highlighter

Returns a new instance of Highlighter.



19
20
21
22
23
# File 'lib/octopress-codefence.rb', line 19

def initialize(input, ext=nil, aliases=nil)
  @input   = input
  @ext     = ext
  @aliases = aliases
end

Instance Method Details

#get_code(code, options) ⇒ Object



89
90
91
92
93
94
# File 'lib/octopress-codefence.rb', line 89

def get_code(code, options)
  options[:aliases] = @aliases || {}
  code = CodeHighlighter.highlight(code, options)
  code = "<notextile>#{code}</notextile>" if !@ext.nil? and @ext.match(/textile/)
  code
end

#get_options(markup) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/octopress-codefence.rb', line 68

def get_options(markup)
  defaults = { escape: true }
  clean_markup = CodeHighlighter.clean_markup(markup)

  if clean_markup =~ AllOptions
    defaults = {
      lang: $1,
      title: $2,
      url: $3,
      link_text: $4,
    }
  elsif clean_markup =~ LangCaption
    defaults = {
      lang: $1,
      title: $2
    }
  end
  CodeHighlighter.parse_markup(markup, defaults)
end

#renderObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/octopress-codefence.rb', line 25

def render
  @input.encode!("UTF-8")
  @input = sub_option_comment(@input)

  # Match code bwteen backticks
  #
  @input.gsub /^`{3}(.+?)`{3}/m do
    str = $1.to_s

    # separate code from arguments after backticks
    #
    str.gsub /([^\n]+)?\n(.+?)\Z/m do
      markup = $1 || ''
      code = $2.to_s
      begin
        get_code(code, get_options(markup))
      rescue => e
        markup = "```#{markup}"
        CodeHighlighter.highlight_failed(e, "```[language] [title] [url] [link text] [linenos:false] [start:#] [mark:#,#-#]\ncode\n```", markup, code)
      end
    end
  end
end

#sub_option_comment(input) ⇒ Object

Allow html comments to set rendering options

Example:
 <!-- title:"Example 1" -->
 ```ruby

This becomes:

 ```ruby title:"Example 1"

This allows Readme files to be rendered by GitHub and other markdown codefences But when processed by Octopress Codefence, the code examples are rendered with options



62
63
64
65
66
# File 'lib/octopress-codefence.rb', line 62

def sub_option_comment(input)
  input.gsub /<!--(.+?)-->\n`{3}([^\n]+)/ do
    "```#{$2} #{$1}"
  end
end