Guidedog 手册 1.0.0-beta.16
语言
本页内容
Guidedog / 文档 1.0.0-beta.16

gd_highlight

Syntax highlighting with Pygments’ token classes (k, nf, s2, c1) and stylesheets, for 35 languages, without a Python runtime.

The common path is one call:

let html = gd_highlight::highlight_html("def f(x):\n    return x\n", "python");
assert!(html.starts_with("<span class=\"k\">def</span>"));

The staged path finds a lexer (find_lexer), resolves Sphinx’s pseudo languages (resolve_lexer), scans tokens (scan_tokens, tokenize_into) and writes them (write_html, write_typst) into a caller’s String, which can be reused. Styles (Style, find_style, write_css, write_typst_theme) and problems (check_code, write_problem) complete the surface. Nothing here keeps global state; the same input always gives the same output.

Structs

pub struct gd_highlight::HtmlLines<'a>

Numbers and emphasizes lines as Pygments does for Sphinx’s :linenos: and :emphasize-lines: (linenos="inline", hl_lines).

Each line starts with <span class="linenos"> 7</span>, and an emphasized line, number included, is wrapped in <span class="hll">...\n</span>.

Fields

pub first: usize

The first line’s number; 0 leaves lines unnumbered.

pub emphasized: &'a [usize]

The 1-based numbers of the lines to emphasize, in any order.

pub struct gd_highlight::LexerInfo

A lexer’s static description.

Fields

pub name: &'static str

Pygments’ lexer name: "Python".

pub aliases: &'static [&'static str]

The names code blocks use; the first is the canonical one.

pub filenames: &'static [&'static str]

Glob patterns of file names: "*.py", "Makefile".

pub mimetypes: &'static [&'static str]

MIME types.

pub struct gd_highlight::Problem<'a>

A problem with a code block or a style name. It borrows the name and the code it was found in.

Fields

pub kind: ProblemKind

What is wrong.

pub name: &'a str

The language or style as written.

pub lexer: Lexer

The lexer the code was lexed with (LexingError).

pub suggestion: Option<&'static str>

A close name, for “Did you mean”.

pub line: usize

LexingError: the 1-based line of the first Error token.

pub column: usize

LexingError: its 1-based column, in characters.

pub excerpt: &'a str

LexingError: the line it is on.

pub near: &'a str

LexingError: its text, up to the line’s end.

Implementations

impl<'a> Problem<'a>
pub fn title(&self) -> &'static str

The report’s title: "UNKNOWN LANGUAGE".

Trait Implementations

impl fmt::Display for Problem<'_>
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

The report without a location.

impl std::error::Error for Problem<'_>
pub struct gd_highlight::Scanner<'a>

Tokenizes one input, yielding merged tokens as an iterator.

Create it with scan_tokens; it borrows the code and allocates nothing.

Trait Implementations

impl Iterator for Scanner<'_>
type Item = Token
fn next(&mut self) -> Option<Token>

The next token; neighbours of one kind come back merged.

pub struct gd_highlight::Color(pub [u8; 6])

A CSS colour as Pygments normalizes it: six hex digits, case kept.

Implementations

impl Color
pub fn as_str(&self) -> &str

The six hex digits, without #.

pub struct gd_highlight::Look

A token kind’s resolved style.

Fields

pub color: Option<Color>

The text colour.

pub background: Option<Color>

The background colour.

pub border: Option<Color>

The border colour.

pub bold: bool

Bold text.

pub italic: bool

Italic text.

pub underline: bool

Underlined text.

Implementations

impl Look
pub fn is_styled(&self) -> bool

Whether the look sets anything.

pub struct gd_highlight::StyleInfo

A style’s definition as Pygments’ style class holds it.

Fields

pub name: &'static str

The pygments_style name: "github-dark".

pub dark: bool

Whether the background is dark.

pub background: &'static str

The .highlight background.

pub highlight: &'static str

The background of emphasized lines (.hll).

pub line_number: &'static str

The colour of line numbers.

pub line_number_background: &'static str

The background of line numbers.

pub special_line_number: &'static str

The colour of special line numbers.

pub special_background: &'static str

The background of special line numbers.

pub base: &'static str

The root token’s definition, which every kind inherits.

pub rules: &'static [StyleRule]

The style’s dict.

pub struct gd_highlight::StyleLooks

Every kind’s look in one style, from resolve_style.

Fields

pub base: Look

The root token’s look, which kinds inherit.

pub kinds: [Look; TokenKind::COUNT]

The looks, indexed by kind as usize; read them with StyleLooks::look.

Implementations

impl StyleLooks
pub fn look(&self, kind: TokenKind) -> Look

The resolved look of kind.

pub struct gd_highlight::Token

A run of the input: code[start..end] has kind.

The tokens a scanner yields are contiguous, cover every byte exactly once, never split a UTF-8 character, and never put two neighbours of one kind side by side.

Fields

pub start: u32

Byte offset of the first byte.

pub end: u32

Byte offset just past the last byte.

pub kind: TokenKind

What the run is.

Enums

pub enum gd_highlight::Lexer

A language. Lexer::Default and Lexer::Guess are Sphinx’s pseudo languages, which scanning resolves against the code (see resolve_lexer).

Variants

Text

Plain text: text, none.

Python

Python.

Pycon

Python console sessions (pycon).

Pytb

Python tracebacks (pytb).

C
Cpp

C++.

Rust

Rust.

Go

Go.

Java

Java.

Kotlin

Kotlin.

Csharp

C#.

Swift

Swift.

Zig

Zig.

Odin

Odin.

Javascript

JavaScript.

Typescript

TypeScript.

Json

JSON.

Yaml

YAML.

Toml

TOML.

Ini

INI and similar configuration files.

Xml

XML.

Html

HTML, with <script> and <style> lexed as JavaScript and CSS.

Css

CSS.

Bash

Bash.

Console

Shell sessions (console).

Powershell

PowerShell.

Sql

SQL.

Diff

Unified and context diffs.

Makefile

Makefiles.

Dockerfile

Dockerfiles.

Rst

reStructuredText.

Markdown

Markdown and MyST.

Latex

TeX and LaTeX.

Typst

Typst.

Dot

Graphviz.

Default

Sphinx’s default: Python, a Python session, or text.

Guess

Sphinx’s guess: picked from the code.

Implementations

impl Lexer
pub const ALL: [Lexer; 37]

Every lexer, in declaration order.

pub enum gd_highlight::ProblemKind

What is wrong with a code block or a style name.

Variants

UnknownLanguage

Sphinx: “Pygments lexer name ‘x’ is not known”.

UnknownStyle

pygments_style names no style.

LexingError

Sphinx: “Lexing literal_block … resulted in an error”.

pub enum gd_highlight::Style

A pygments_style: every style Pygments ships, and Sphinx’s sphinx and none.

Variants

Abap

Pygments’ abap style.

Algol

Pygments’ algol style.

AlgolNu

Pygments’ algol_nu style.

Arduino

Pygments’ arduino style.

Autumn

Pygments’ autumn style.

Borland

Pygments’ borland style.

Bw

Pygments’ bw style.

Coffee

Pygments’ coffee style.

Colorful

Pygments’ colorful style.

Default

Pygments’ default style.

Dracula

Pygments’ dracula style.

Emacs

Pygments’ emacs style.

Friendly

Pygments’ friendly style.

FriendlyGrayscale

Pygments’ friendly_grayscale style.

Fruity

Pygments’ fruity style.

GithubDark

Pygments’ github-dark style.

GruvboxDark

Pygments’ gruvbox-dark style.

GruvboxLight

Pygments’ gruvbox-light style.

Igor

Pygments’ igor style.

Inkpot

Pygments’ inkpot style.

Lightbulb

Pygments’ lightbulb style.

Lilypond

Pygments’ lilypond style.

Lovelace

Pygments’ lovelace style.

Manni

Pygments’ manni style.

Material

Pygments’ material style.

Monokai

Pygments’ monokai style.

Murphy

Pygments’ murphy style.

Native

Pygments’ native style.

None

Pygments’ none style.

Nord

Pygments’ nord style.

NordDarker

Pygments’ nord-darker style.

OneDark

Pygments’ one-dark style.

ParaisoDark

Pygments’ paraiso-dark style.

ParaisoLight

Pygments’ paraiso-light style.

Pastie

Pygments’ pastie style.

Perldoc

Pygments’ perldoc style.

RainbowDash

Pygments’ rainbow_dash style.

Rrt

Pygments’ rrt style.

Sas

Pygments’ sas style.

SolarizedDark

Pygments’ solarized-dark style.

SolarizedLight

Pygments’ solarized-light style.

Sphinx

Pygments’ sphinx style.

Staroffice

Pygments’ staroffice style.

StataDark

Pygments’ stata-dark style.

StataLight

Pygments’ stata-light style.

Tango

Pygments’ tango style.

Trac

Pygments’ trac style.

Vim

Pygments’ vim style.

Vs

Pygments’ vs style.

Xcode

Pygments’ xcode style.

Zenburn

Pygments’ zenburn style.

Implementations

impl Style
pub const ALL: [Style; 51]

Every style, in declaration order.

#[repr(u8)] pub enum gd_highlight::TokenKind

Pygments’ token hierarchy.

Each kind has Pygments’ dotted name (kind_name), its short CSS class (kind_class) and its parent (kind_parent), so the stylesheets Sphinx themes already ship style the output unchanged. The kinds after TokenKind::GenericTraceback are subtypes only some lexers or styles use: the YAML lexer’s Punctuation.Indicator and Literal.Scalar.Plain, and the types only Pygments’ styles name (github-dark’s Generic.Underline, gruvbox’s Comment.PreProc, the LilyPond lexer’s types, which hang off the root).

Variants

Text

Pygments’ Text; written without a span.

Whitespace

Pygments’ Text.Whitespace.

Escape

Pygments’ Escape.

Error

Pygments’ Error.

Other

Pygments’ Other.

Keyword

Pygments’ Keyword.

KeywordConstant

Pygments’ Keyword.Constant.

KeywordDeclaration

Pygments’ Keyword.Declaration.

KeywordNamespace

Pygments’ Keyword.Namespace.

KeywordPseudo

Pygments’ Keyword.Pseudo.

KeywordReserved

Pygments’ Keyword.Reserved.

KeywordType

Pygments’ Keyword.Type.

Name

Pygments’ Name.

NameAttribute

Pygments’ Name.Attribute.

NameBuiltin

Pygments’ Name.Builtin.

NameBuiltinPseudo

Pygments’ Name.Builtin.Pseudo.

NameClass

Pygments’ Name.Class.

NameConstant

Pygments’ Name.Constant.

NameDecorator

Pygments’ Name.Decorator.

NameEntity

Pygments’ Name.Entity.

NameException

Pygments’ Name.Exception.

NameFunction

Pygments’ Name.Function.

NameFunctionMagic

Pygments’ Name.Function.Magic.

NameProperty

Pygments’ Name.Property.

NameLabel

Pygments’ Name.Label.

NameNamespace

Pygments’ Name.Namespace.

NameOther

Pygments’ Name.Other.

NameTag

Pygments’ Name.Tag.

NameVariable

Pygments’ Name.Variable.

NameVariableClass

Pygments’ Name.Variable.Class.

NameVariableGlobal

Pygments’ Name.Variable.Global.

NameVariableInstance

Pygments’ Name.Variable.Instance.

NameVariableMagic

Pygments’ Name.Variable.Magic.

Literal

Pygments’ Literal.

LiteralDate

Pygments’ Literal.Date.

String

Pygments’ Literal.String.

StringAffix

Pygments’ Literal.String.Affix.

StringBacktick

Pygments’ Literal.String.Backtick.

StringChar

Pygments’ Literal.String.Char.

StringDelimiter

Pygments’ Literal.String.Delimiter.

StringDoc

Pygments’ Literal.String.Doc.

StringDouble

Pygments’ Literal.String.Double.

StringEscape

Pygments’ Literal.String.Escape.

StringHeredoc

Pygments’ Literal.String.Heredoc.

StringInterpol

Pygments’ Literal.String.Interpol.

StringOther

Pygments’ Literal.String.Other.

StringRegex

Pygments’ Literal.String.Regex.

StringSingle

Pygments’ Literal.String.Single.

StringSymbol

Pygments’ Literal.String.Symbol.

Number

Pygments’ Literal.Number.

NumberBin

Pygments’ Literal.Number.Bin.

NumberFloat

Pygments’ Literal.Number.Float.

NumberHex

Pygments’ Literal.Number.Hex.

NumberInteger

Pygments’ Literal.Number.Integer.

NumberIntegerLong

Pygments’ Literal.Number.Integer.Long.

NumberOct

Pygments’ Literal.Number.Oct.

Operator

Pygments’ Operator.

OperatorWord

Pygments’ Operator.Word.

Punctuation

Pygments’ Punctuation.

PunctuationMarker

Pygments’ Punctuation.Marker.

Comment

Pygments’ Comment.

CommentHashbang

Pygments’ Comment.Hashbang.

CommentMultiline

Pygments’ Comment.Multiline.

CommentPreproc

Pygments’ Comment.Preproc.

CommentPreprocFile

Pygments’ Comment.PreprocFile.

CommentSingle

Pygments’ Comment.Single.

CommentSpecial

Pygments’ Comment.Special.

Generic

Pygments’ Generic.

GenericDeleted

Pygments’ Generic.Deleted.

GenericEmph

Pygments’ Generic.Emph.

GenericEmphStrong

Pygments’ Generic.EmphStrong.

GenericError

Pygments’ Generic.Error.

GenericHeading

Pygments’ Generic.Heading.

GenericInserted

Pygments’ Generic.Inserted.

GenericOutput

Pygments’ Generic.Output.

GenericPrompt

Pygments’ Generic.Prompt.

GenericStrong

Pygments’ Generic.Strong.

GenericSubheading

Pygments’ Generic.Subheading.

GenericTraceback

Pygments’ Generic.Traceback.

PunctuationIndicator

Pygments’ Punctuation.Indicator.

LiteralScalarPlain

Pygments’ Literal.Scalar.Plain.

GenericUnderline

Pygments’ Generic.Underline.

CommentPreProc

Pygments’ Comment.PreProc.

NameLvalue

Pygments’ Name.Lvalue.

NameBackslashReference

Pygments’ Name.BackslashReference.

NameBuiltinArticulation

Pygments’ Name.Builtin.Articulation.

NameBuiltinClef

Pygments’ Name.Builtin.Clef.

NameBuiltinContext

Pygments’ Name.Builtin.Context.

NameBuiltinContextProperty

Pygments’ Name.Builtin.ContextProperty.

NameBuiltinDynamic

Pygments’ Name.Builtin.Dynamic.

NameBuiltinGrob

Pygments’ Name.Builtin.Grob.

NameBuiltinGrobProperty

Pygments’ Name.Builtin.GrobProperty.

NameBuiltinHeaderVariable

Pygments’ Name.Builtin.HeaderVariable.

NameBuiltinMarkupCommand

Pygments’ Name.Builtin.MarkupCommand.

NameBuiltinMusicCommand

Pygments’ Name.Builtin.MusicCommand.

NameBuiltinMusicFunction

Pygments’ Name.Builtin.MusicFunction.

NameBuiltinPaperVariable

Pygments’ Name.Builtin.PaperVariable.

NameBuiltinRepeatType

Pygments’ Name.Builtin.RepeatType.

NameBuiltinScale

Pygments’ Name.Builtin.Scale.

NameBuiltinSchemeBuiltin

Pygments’ Name.Builtin.SchemeBuiltin.

NameBuiltinSchemeFunction

Pygments’ Name.Builtin.SchemeFunction.

NameBuiltinTranslator

Pygments’ Name.Builtin.Translator.

TokenString

Pygments’ String.

TokenStringEscape

Pygments’ String.Escape.

TokenStringSymbol

Pygments’ String.Symbol.

TokenNumber

Pygments’ Number.

Pitch

Pygments’ Pitch.

ChordModifier

Pygments’ ChordModifier.

Implementations

impl TokenKind
pub const ALL: [TokenKind; 108]

Every kind, in declaration order.

pub const COUNT: usize = Self::ALL.len()

How many kinds there are.

Functions

pub fn gd_highlight::push_html(out: &mut String, text: &str)

Appends text escaped as Pygments escapes it: & < > " '.

pub fn gd_highlight::write_code_html(lexer: Lexer, code: &str, out: &mut String)

Lexes code with lexer and appends its HTML to out, without a token buffer.

pub fn gd_highlight::write_code_html_lines(lexer: Lexer, code: &str, lines: HtmlLines<'_>, out: &mut String)

Lexes code and appends it as write_html_lines does.

pub fn gd_highlight::write_html(tokens: &[Token], code: &str, out: &mut String)

Appends the HTML of tokens, which cover code, to out.

pub fn gd_highlight::write_html_lines(tokens: &[Token], code: &str, lines: HtmlLines<'_>, out: &mut String)

Appends the HTML of tokens with numbered or emphasized lines. The whole block is lexed at once, so a string or comment across lines keeps its colour on every line.

pub fn gd_highlight::find_lexer(name: &str) -> Option<Lexer>

Finds a lexer by alias ("py", "c++"), as Pygments’ get_lexer_by_name does, ignoring case; failing that by file name ("a/setup.py", "Makefile") or MIME type. None when nothing matches.

pub fn gd_highlight::find_lexer_for_filename(path: &str) -> Option<Lexer>

Matches the base name of path against the lexers’ file patterns.

pub fn gd_highlight::lexer_alias(lexer: Lexer) -> &'static str

The lexer’s canonical alias: "python", "cpp".

pub fn gd_highlight::lexer_info(lexer: Lexer) -> &'static LexerInfo

The lexer’s static description: name, aliases, file patterns and MIME types.

pub fn gd_highlight::lexer_name(lexer: Lexer) -> &'static str

Pygments’ name for the lexer: "Python", "C++".

pub fn gd_highlight::resolve_lexer(lexer: Lexer, code: &str) -> Lexer

Makes Sphinx’s choice for a code block.

Lexer::Default is Python, or a Python console session when the code starts with >>>, and plain text when that does not lex cleanly. Python code that starts with >>> is a session. Lexer::Guess guesses from the code. Every other lexer is itself.

pub fn gd_highlight::suggest_lexer(name: &str) -> Option<&'static str>

The alias closest to a name find_lexer does not know, for “Did you mean” hints; None when nothing is close.

pub fn gd_highlight::guess_lexer(code: &str) -> Lexer

Picks a lexer from the code alone, as Sphinx’s “guess” language does: JSON that lexes cleanly is JSON; otherwise a scored rule table decides, and Lexer::Text wins when nothing matches.

pub fn gd_highlight::check_code<'a>(language: &'a str, code: &'a str) -> Option<Problem<'a>>

Finds what Sphinx would warn about when it highlights code as language: an unknown language, or code that does not lex as the language it is marked as. None when there is nothing to report; blocks in the default language never warn, since they fall back to plain text.

pub fn gd_highlight::check_style(name: &str) -> Option<Problem<'_>>

Reports a pygments_style that names no style; None when it names one.

pub fn gd_highlight::write_problem(problem: &Problem<'_>, location: &str, out: &mut String)

Appends an Elm-style report of problem to out; location, such as "index.rst:12", heads it unless it is empty.

-- UNKNOWN LANGUAGE ----------------------------------------------- index.rst:12

I do not know how to highlight "pyhton", so this block is shown as plain text.

Hint: Did you mean "python"?
pub fn gd_highlight::count_tokens(lexer: Lexer, code: &str) -> usize

How many tokens code lexes into, without storing them.

pub fn gd_highlight::has_errors(lexer: Lexer, code: &str) -> bool

Whether lexing code produces an Error token, which is when Sphinx warns that a block does not lex as its language.

pub fn gd_highlight::scan_tokens(lexer: Lexer, code: &str) -> Scanner<'_>

Starts scanning code with lexer; the pseudo lexers Lexer::Default and Lexer::Guess are resolved against the code first. Inputs are limited to 4 GiB; the rest of a longer input is not scanned.

pub fn gd_highlight::tokenize(lexer: Lexer, code: &str) -> Vec<Token>

The tokens of code in a new vector.

pub fn gd_highlight::tokenize_into(lexer: Lexer, code: &str, tokens: &mut Vec<Token>)

Lexes code into tokens, clearing it first so a caller can reuse its buffer.

pub fn gd_highlight::find_style(name: &str) -> Option<Style>

Finds a style by its Pygments name, ignoring case and surrounding spaces; None when no style has that name.

pub fn gd_highlight::kind_look(style: Style, kind: TokenKind) -> Look

The resolved look of one kind in a style.

pub fn gd_highlight::resolve_style(style: Style) -> StyleLooks

Resolves every kind’s look: its parent’s, changed by its own rules, as Pygments does.

pub fn gd_highlight::style_info(style: Style) -> &'static StyleInfo

The definition of style; it borrows static data.

pub fn gd_highlight::style_name(style: Style) -> &'static str

The style’s pygments_style name, as find_style takes it: "github-dark".

pub fn gd_highlight::write_css(style: Style, selector: &str, out: &mut String)

Writes the stylesheet Pygments writes for style with selector, as Sphinx writes _static/pygments.css with ".highlight". It appends to out and ends without a newline.

pub fn gd_highlight::kind_class(kind: TokenKind) -> &'static str

The CSS class Pygments’ HtmlFormatter writes for kind: "k", "s2", "c1".

It is "" for TokenKind::Text, which HTML writes without a span; subtypes outside the standard set carry their ancestors’ classes too ("p p-Indicator").

pub fn gd_highlight::kind_is(kind: TokenKind, ancestor: TokenKind) -> bool

Whether kind is ancestor or one of its descendants, as Pygments’ ttype in Token.String tells.

pub fn gd_highlight::kind_name(kind: TokenKind) -> &'static str

Pygments’ dotted name without the Token. root: "Literal.String.Double".

pub fn gd_highlight::kind_parent(kind: TokenKind) -> Option<TokenKind>

The kind’s parent; None for kinds directly below the root.

pub fn gd_highlight::token_text(token: Token, code: &str) -> &str

The input a token covers; "" when the token does not lie within code.

pub fn gd_highlight::push_typst_string(out: &mut String, text: &str)

Appends text as a Typst string literal.

pub fn gd_highlight::write_code_typst(lexer: Lexer, code: &str, out: &mut String)

Lexes code with lexer and appends its Typst array to out, without a token buffer.

pub fn gd_highlight::write_typst(tokens: &[Token], code: &str, out: &mut String)

Appends tokens of code to out as a Typst array of lines. A final newline does not start another line.

pub fn gd_highlight::write_typst_theme(style: Style, out: &mut String)

Appends style to out as a Typst dictionary: "background" is the block’s fill, "text" the default text settings, and each class maps to its text settings (fill, weight, style), with underline, background and border where set.

pub fn gd_highlight::highlight_html(code: &str, language: &str) -> String

Highlights code as language (an alias, file name or MIME type) and returns Pygments’ HTML spans: what goes inside <div class="highlight"><pre>.

The language is resolved as Sphinx resolves it; an unknown language is written as escaped plain text (use check_code to report it).

pub fn gd_highlight::highlight_typst(code: &str, language: &str) -> String

Highlights code as language and returns the Typst array write_typst writes.

An unknown language is written as plain text.

pub fn gd_highlight::style_css(style: Style, selector: &str) -> String

Returns the stylesheet write_css writes for style with selector.

Type Aliases

pub type gd_highlight::StyleRule = (TokenKind, &'static str)

One entry of a style’s dict: a kind and its definition. A style has at most one per kind.