Module: XCPretty::Syntax

Defined in:
lib/xcpretty/syntax.rb

Class Method Summary collapse

Class Method Details

.find_lexer(filename, contents) ⇒ Rouge::Lexer

Parameters:

  • filename (String)

    The filename

  • contents (String)

    The contents of the file

Returns:

  • (Rouge::Lexer)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/xcpretty/syntax.rb', line 41

def self.find_lexer(filename, contents)
  case File.extname(filename)
  when '.cpp', '.cc', '.c++', '.cxx', '.hpp', '.h++', '.hxx'
    Rouge::Lexers::Cpp
  when '.m', '.h' then Rouge::Lexers::ObjectiveC
  when '.swift' then Rouge::Lexers::Swift
  when '.ruby', '.rb' then Rouge::Lexers::Ruby
  else
    options = {
      filename: File.basename(filename),
      source: contents
    }
    Rouge::Lexer.guesses(options).first
  end
end

.highlight(snippet) ⇒ Object



13
14
15
16
# File 'lib/xcpretty/syntax.rb', line 13

def self.highlight(snippet)
  return snippet.contents unless Rouge
  highlight_with_formatter(snippet, Rouge::Formatters::Terminal256.new)
end

.highlight_html(snippet) ⇒ Object



18
19
20
21
# File 'lib/xcpretty/syntax.rb', line 18

def self.highlight_html(snippet)
  return snippet.contents unless Rouge
  highlight_with_formatter(snippet, Rouge::Formatters::HTML.new)
end

.highlight_with_formatter(snippet, formatter) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/xcpretty/syntax.rb', line 23

def self.highlight_with_formatter(snippet, formatter)
  if snippet.file_path.include?(':')
    filename = snippet.file_path.rpartition(':').first
  else
    filename = snippet.file_path
  end

  lexer = find_lexer(filename, snippet.contents)
  if lexer
    formatter.format(lexer.lex(snippet.contents))
  else
    snippet.contents
  end
end