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])

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

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)

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

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

.highlight(code, mode: 256, lang: nil, enabled: nil, color: ->(line) { line }) ⇒ Object

Highlight code snippet

Parameters:

  • code (String)
  • mode (Integer) (defaults to: 256)

    the color mode supported by the terminal

  • lang (String) (defaults to: nil)

    the code snippet language

  • enabled (Boolean) (defaults to: nil)

    whether or not coloring is enabled

  • color (Proc) (defaults to: ->(line) { line })

    the fallback coloring


54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/tty/markdown/syntax_highlighter.rb', line 54

def highlight(code, mode: 256, lang: nil, enabled: nil,
              color: ->(line) { line })
  lang = guess_lang(code) if lang.nil?
  lexer = Rouge::Lexer.find_fancy(lang, code) || Rouge::Lexers::PlainText

  if enabled == false
    code
  elsif 256 <= mode
    formatter = Rouge::Formatters::Terminal256.new
    formatter.format(lexer.lex(code))
  else
    code.lines.map { |line| color.(line.chomp) }.join("\n")
  end
end