Class: Charming::Presentation::Markdown::SyntaxHighlighter

Inherits:
Object
  • Object
show all
Defined in:
lib/charming/presentation/markdown/syntax_highlighter.rb

Overview

SyntaxHighlighter turns a code block string into ANSI-styled terminal text using Rouge lexers. The theme provides markdown_code_* tokens for per-token styling; when a token is undefined in the theme, the highlighter falls back to a sensible base style (muted italic for comments, title for keywords, etc.).

Instance Method Summary collapse

Constructor Details

#initialize(theme: UI::Theme.default) ⇒ SyntaxHighlighter

theme is the active Charming theme. Defaults to UI::Theme.default.



14
15
16
# File 'lib/charming/presentation/markdown/syntax_highlighter.rb', line 14

def initialize(theme: UI::Theme.default)
  @theme = theme || UI::Theme.default
end

Instance Method Details

#render(code, language: nil) ⇒ Object

Highlights code (using Rouge) for the given language (auto-detected when nil) and returns a styled multi-line string. Each Rouge token is rendered with the theme style matching its token type.



21
22
23
24
25
26
# File 'lib/charming/presentation/markdown/syntax_highlighter.rb', line 21

def render(code, language: nil)
  lexer = lexer_for(language, code)
  lexer.lex(code.to_s).map do |token, value|
    style_for(token).render(value)
  end.join
end