Module: TTY::Markdown::SyntaxHighliter Private

Defined in:
lib/tty/markdown/syntax_highlighter.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Syntax highlighting for terminal code snippets

Class Method Summary collapse

Class Method Details

.available_lexersArray[String]

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return all available language lexers

Returns:

  • (Array[String])


18
19
20
21
22
23
24
25
26
# File 'lib/tty/markdown/syntax_highlighter.rb', line 18

def available_lexers
  Rouge::Lexer.all.sort_by(&:tag).inject([]) do |names, lexer|
    names << lexer.tag
    if lexer.aliases.any?
      lexer.aliases.each { |a| names << a }
    end
    names
  end
end

.guess_lang(code) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Guess langauge from code snippet

Returns:

  • (String, nil)


34
35
36
37
38
39
40
# File 'lib/tty/markdown/syntax_highlighter.rb', line 34

def guess_lang(code)
  lang = nil
  start_line = code.lines[0]
  if available_lexers.include?(start_line.strip.downcase)
    lang = start_line.strip.downcase
  end
end

.highlight(code, **options) ⇒ Object

Highlight code snippet



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tty/markdown/syntax_highlighter.rb', line 46

def highlight(code, **options)
  lang = guess_lang(code)
  mode = options[:mode] || TTY::Color.mode
  lines = code.dup.lines
  if options[:fenced].nil?
    code = lines[1...-1].join + lines[-1].strip
  end

  lexer = Rouge::Lexer.find_fancy(lang, code) || Rouge::Lexers::PlainText

  if mode >= 256
    formatter = Rouge::Formatters::Terminal256.new
    formatter.format(lexer.lex(code))
  else
    pastel = Pastel.new
    code.split("\n").map { |line| pastel.yellow(line) }.join("\n")
  end
end