Text

Syntax highlighting

Code highlighted as HTML in 75 languages, with inline colours from a theme or with classes and a stylesheet, for docs and blog posts.

Version 1.0.0 · 5 functions · 1 crate

#code#html#docs#markdown

Functions

What use highlight.qwer gives a program, with the types Quillo sees. To take only some, or under other names: use highlight_html, highlight_classes from highlight (Quillo 0.6).

highlight_html(code: str, language: str, theme: str) → stror an error

code as a <pre> block of HTML with inline colours from theme (see highlight_themes(); "InspiredGitHub" is light, "base16-ocean.dark" dark). language is a name or file extension ("rust", "py", "sql"); one it does not know is plain text. Code up to 1 MB.

highlight_classes(code: str, language: str) → stror an error

code as HTML spans with classes (<span class="source rust">), no <pre> around it, for a stylesheet of your own or highlight_css. Code up to 1 MB.

highlight_css(theme: str) → stror an error

The CSS for highlight_classes' spans in the colours of theme; its .code rule is the background, for a <pre class="code"> around them.

highlight_themes() → list

The names of the themes there are.

highlight_languages() → list

The languages there are, by name, each with its file extensions: [{ name, extensions }].

Get it

$ quillo install highlight               # highlight.qwer into this folder$ quillo install highlight --example     # and its example, highlight.qwe

Or with curl:

$ curl -O https://quillolang.org/plugins/files/highlight.qwer$ curl -O https://quillolang.org/plugins/files/highlight.qwe

Then, in your program, all of it or only what you call:

main.qwe
use highlight.qweruse highlight_html, highlight_classes from highlight      // Quillo 0.6: only these

It uses this crate, which cargo fetches the first time the plugin is built:

[dependencies]
syntect = { version = "5.3", default-features = false, features = ["parsing", "default-syntaxes", "default-themes", "html", "regex-fancy"] }

Example

highlight.qwe
// A docs page with highlighted code, in two ways: inline colours, and classes with a stylesheet.////   quillo run highlight.qwe      then open http://localhost:8080/snippetuse "highlight.qwer"let sample = "fn main() {\n    let total: i64 = [1, 2, 3].iter().sum();\n    println!(\"total = {}\", total);\n}\n"route GET /snippet = <html>    <body>        <h1>Summing in Rust</h1>        {raw(highlight_html(sample, "rust", "InspiredGitHub")?)}    </body></html>route GET /classes ? { lang: str = "sql" } {    let html = highlight_classes("SELECT name, total FROM orders WHERE total > 100;\n", lang)?    <html>        <head><style>{raw(highlight_css("base16-ocean.dark")?)}</style></head>        <body><pre class="code">{raw(html)}</pre></body>    </html>}route GET /themes = { themes: highlight_themes(), languages: len(highlight_languages()) }
$ quillo run highlight.qwe$ curl 'localhost:8080/snippet'$ curl 'localhost:8080/classes'

Source

highlight.qwer
//! Code highlighted as HTML for docs, blogs and code review pages: Rust, Python, JavaScript, SQL, HTML and 70 more, with CSS classes or inline colours.//! version: 1.0.0//!//! [dependencies]//! syntect = { version = "5.3", default-features = false, features = ["parsing", "default-syntaxes", "default-themes", "html", "regex-fancy"] }use std::sync::OnceLock;use syntect::highlighting::ThemeSet;use syntect::html::{css_for_theme_with_class_style, highlighted_html_for_string, ClassStyle, ClassedHTMLGenerator};use syntect::parsing::{SyntaxReference, SyntaxSet};use syntect::util::LinesWithEndings;const MAX: usize = 1_000_000;fn syntaxes() -> &'static SyntaxSet {    static S: OnceLock<SyntaxSet> = OnceLock::new();    S.get_or_init(SyntaxSet::load_defaults_newlines)}fn themes() -> &'static ThemeSet {    static T: OnceLock<ThemeSet> = OnceLock::new();    T.get_or_init(ThemeSet::load_defaults)}fn syntax<'a>(ss: &'a SyntaxSet, language: &str, code: &str) -> &'a SyntaxReference {    let l = language.trim().trim_start_matches('.');    let alias = match l.to_lowercase().as_str() {        "js" | "javascript" | "jsx" | "ts" | "typescript" | "tsx" => "js",        "py" | "python" => "py",        "sh" | "bash" | "shell" | "zsh" => "sh",        "rs" | "rust" => "rs",        "md" | "markdown" => "md",        "yml" | "yaml" => "yaml",        "c++" | "cpp" => "cpp",        "c#" | "csharp" | "cs" => "cs",        "html" | "htm" => "html",        "golang" | "go" => "go",        "rb" | "ruby" => "rb",        _ => l,    };    ss.find_syntax_by_token(alias)        .or_else(|| ss.find_syntax_by_first_line(code))        .unwrap_or_else(|| ss.find_syntax_plain_text())}/// `code` as a `<pre>` block of HTML with inline colours from `theme` (see `highlight_themes()`; "InspiredGitHub" is light, "base16-ocean.dark" dark). `language` is a name or file extension ("rust", "py", "sql"); one it does not know is plain text. Code up to 1 MB.pub fn highlight_html(code: &str, language: &str, theme: &str) -> Result<String, String> {    if code.len() > MAX {        return Err("code up to 1 MB".into());    }    let ss = syntaxes();    let t = themes().themes.get(theme).ok_or_else(|| format!("no theme {:?}; see highlight_themes()", theme))?;    highlighted_html_for_string(code, ss, syntax(ss, language, code), t).map_err(|e| e.to_string())}/// `code` as HTML spans with classes (`<span class="source rust">`), no `<pre>` around it, for a stylesheet of your own or `highlight_css`. Code up to 1 MB.pub fn highlight_classes(code: &str, language: &str) -> Result<String, String> {    if code.len() > MAX {        return Err("code up to 1 MB".into());    }    let ss = syntaxes();    let mut g = ClassedHTMLGenerator::new_with_class_style(syntax(ss, language, code), ss, ClassStyle::Spaced);    for line in LinesWithEndings::from(code) {        g.parse_html_for_line_which_includes_newline(line).map_err(|e| e.to_string())?;    }    Ok(g.finalize())}/// The CSS for `highlight_classes`' spans in the colours of `theme`; its `.code` rule is the background, for a `<pre class="code">` around them.pub fn highlight_css(theme: &str) -> Result<String, String> {    let t = themes().themes.get(theme).ok_or_else(|| format!("no theme {:?}; see highlight_themes()", theme))?;    css_for_theme_with_class_style(t, ClassStyle::Spaced).map_err(|e| e.to_string())}/// The names of the themes there are.pub fn highlight_themes() -> Vec<String> {    themes().themes.keys().cloned().collect()}/// The languages there are, by name, each with its file extensions: `[{ name, extensions }]`.pub fn highlight_languages() -> Vec<serde_json::Value> {    syntaxes().syntaxes().iter().map(|s| serde_json::json!({ "name": s.name, "extensions": s.file_extensions })).collect()}
AsciiDoc asciidoc.qwer · 1.0.0AsciiDoc to HTML: headings with ids, attributes and conditionals, nested lists with continuation, description lists, tables with spans, admonitions, source blocks with callouts, quotes, images, footnotes, a table of contents. Text is escaped and `javascript:` links dropped, raw passthrough refused unless asked for, and includes refused or kept inside one folder, with line ranges and tags.markupdocumentationhtmldocs6 views · 11 downloadsHTML to Markdown html_markdown.qwer · 1.0.0HTML turned into clean Markdown as Turndown does: headings, lists, links, images, code blocks, quotes and tables kept, scripts and the parts you name dropped; for importing old posts, editor output, and pages for an LLM.htmlmarkdownimportllm7 views · 6 downloadsReadability readability.qwer · 1.0.0A web page's article without its menus, ads and footer: title, author, date, clean HTML, plain text or Markdown, for read-later apps, link previews and summaries.htmlscrapingtextmarkdownimport8 views · 7 downloadsMarkdown TOC markdown_toc.qwer · 1.0.0Tables of contents for Markdown: headings as a list or tree with GitHub-style anchors, a ready TOC, and HTML with heading ids.markdowndocstextnavigation7 views · 8 downloadsChunker chunker.qwer · 1.0.0Text and Markdown split into chunks by characters or OpenAI tokens, with overlap, cut at headings, paragraphs and sentences, for embeddings and LLM prompts.aillmembeddingsmarkdownsearch9 views · 8 downloadsHTML to text html_text.qwer · 1.0.0HTML as readable plain text for the text part of an email: headings, lists and tables laid out, links listed at the end, and one-line previews.emailhtmltextexport7 views · 7 downloads
Thread
86Useful? Like it, or add to its thread below.

Thread 0 posts

On Syntax highlighting: questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.