highlight_code

Function highlight_code 

Source
pub fn highlight_code(code: &str, language: &str) -> Vec<HighlightedToken>
Expand description

Highlights code using syntax highlighting rules based on the specified language.

This function applies syntax highlighting to source code, breaking it into tokens with appropriate colors for rendering in PDFs. It supports multiple programming languages including Rust, TypeScript, Python, Java, C, C++, Go, Bash, PowerShell, and many more.

§Arguments

  • code - The source code to highlight
  • language - The programming language identifier (e.g., “rust”, “typescript”, “python”) Common values: “rust”, “ts”, “tsx”, “js”, “jsx”, “py”, “java”, “c”, “cpp”, “go”, “bash”, “sh”, “powershell”, “ps1”

§Returns

A vector of HighlightedToken structs, each containing a piece of code text, its RGB color, and styling information (bold, italic). If the language is not recognized, falls back to plaintext (gray color).

§Examples

Highlight some Rust code:

use markdown2pdf::highlighting::highlight_code;

let code = r#"
fn main() {
    println!(\"Hello, world!\");
}
"#;
let tokens = highlight_code(code, "rust");

// Verify we got tokens back
assert!(!tokens.is_empty());

// Print highlighted tokens
for token in tokens {
    if !token.text.trim().is_empty() {
        let (r, g, b) = token.color.as_rgb_u8();
        println!("Token: '{}' Color: RGB({}, {}, {})",
                 token.text, r, g, b);
    }
}

Highlight TypeScript/React code:

use markdown2pdf::highlighting::highlight_code;

let code = r#"
const Component: React.FC = () => {
    return <div>Hello JSX</div>;
};
"#;
let tokens = highlight_code(code, "tsx");

// Verify TypeScript keywords are recognized
assert!(tokens.iter().any(|t| t.text.contains("const")));
assert!(tokens.iter().any(|t| t.text.contains("React")));