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
-
.available_lexers ⇒ Array[String]
private
Return all available language lexers.
-
.guess_lang(code) ⇒ String?
private
Guess langauge from code snippet.
-
.highlight(code, mode: 256, lang: nil, enabled: nil, color: ->(line) { line }) ⇒ Object
Highlight code snippet.
Class Method Details
.available_lexers ⇒ Array[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
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
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
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 |