Module: Markdpwn::Code

Defined in:
lib/markdpwn/code.rb

Overview

Code formatting.

Class Method Summary collapse

Class Method Details

.pygment(code, options = {}) ⇒ Object

The raw Pygments output for parsing some code.



29
30
31
32
33
34
35
# File 'lib/markdpwn/code.rb', line 29

def self.pygment(code, options = {})
  lexer = pygments_lexer options
  pygments_args = { formatter: 'html',
      options: { encoding: 'utf-8', nowrap: true } }
  pygments_args[:lexer] = lexer if lexer
  Pygments.highlight code, pygments_args
end

.pygments_lexer(options = {}) ⇒ String

The name of the Python lexer that is most suitable for some code.

Parameters:

  • options (Hash) (defaults to: {})

    code properties that help choose the formatter

Options Hash (options):

  • :code (String)

    the code to be parsed, or a sample of the code; if code is provided, a language will always be returned

Returns:

  • (String)

    the name of a Pygments lexer that can parse the code

See Also:

  • for other available options


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/markdpwn/code.rb', line 44

def self.pygments_lexer(options = {})
  if language = options[:language]
    lexer = begin
      Pygments.lexer_name_for lexer: language
    rescue IOError
      nil
    end
    return lexer if lexer
  end

  if mime_type = options[:mime_type]
    lexer = begin
      Pygments.lexer_name_for mimetype: mime_type
    rescue IOError
      nil
    end
    return lexer if lexer
  end

  if file_name = options[:file_name]
    lexer = begin
      Pygments.lexer_name_for filename: file_name
    rescue IOError
      nil
    end
    return lexer if lexer
  end

  if code = options[:code]
    lexer = begin
      Pygments.lexer_name_for code
    rescue IOError
      nil
    end
    return lexer if lexer
  end

  nil
end

.render(code, options = {}) ⇒ String

Marks up code.

Parameters:

  • code (String)

    the code to be formatted

  • options (Hash) (defaults to: {})

    code properties that help choose the formatter

Options Hash (options):

  • :mime_type (String)

    the MIME type of the code file; e-mail attachments and git blobs have MIME types

  • :file_name (String)

    the name of the file containing the piece of code; meaningful for files in version control repositories, e-mail attachments, and code fetched from links

  • :language (String)

    the name of the code’s language; GFM code blocks can include a language name

Returns:

  • (String)

    a HTML fragment containing the formatted code



19
20
21
22
23
24
25
# File 'lib/markdpwn/code.rb', line 19

def self.render(code, options = {})
  [
    %Q|<div class="markdpwn-parsed-code">|,
    pygment(code, options),
    "</div>"
  ].join ''
end