rouge

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: BSD-3-Clause Imports: 6 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-rouge/rouge

rouge — go-rouge

Docs License Go Coverage

A pure-Go (no cgo) reimplementation of the Ruby rouge syntax highlighter — the state-machine regex lexers, the token hierarchy, and the HTML formatters of the gem, emitting exactly the CSS short-codes (k, s, c, nf, …) rouge emits. It tokenizes source and renders <span class> HTML that matches the gem byte-for-byte on the supported lexers, without any Ruby runtime.

It is a sibling of go-ruby-regexp (the Onigmo engine it lexes with), go-ruby-erb, and go-ruby-yaml, and is bound into go-embedded-ruby to give rbgo a CGO-free Rouge.highlight.

API

import "github.com/go-rouge/rouge"

// Rouge.highlight(text, lexer, formatter) -> HTML
html, err := rouge.Highlight(`puts "hello"`, "ruby", "html")
// => <span class="nb">puts</span> <span class="s2">"hello"</span>

// Rouge::Lexer.find / find_fancy / guess
lex := rouge.FindLexer("rb")          // by tag or alias (case-insensitive)
lex = rouge.FindFancy("ruby?opt=1")   // "tag" or "tag?opts"
lex = rouge.Guess(src)                // content sniff; never nil (PlainText fallback)

// Token stream + the HTML / HTMLInline formatters directly
toks := lex.Lex(src)                          // []TokenValue{Token, Value}
out := rouge.HTMLFormatter{}.Format(toks)     // <span class="…"> per token
page := rouge.WrapHTML(out)                   // <pre class="highlight"><code>…</code></pre>
inline := rouge.HTMLInlineFormatter{Theme: rouge.Github}.Format(toks) // inline styles
  • Token model — rouge.Token mirrors Rouge::Token::Tokens: a tree with a dotted Qualname() (Literal.String.Double), the CSS Shortname the HTML formatter emits (s2), Matches(ancestor), and TokenByName("Keyword.Constant").
  • Formatters — HTML (<span class="shortcode">, the gem's exact codes; Text/Escape pass through) and HTMLInline (inline style= from a Theme), registered as "html" / "html_inline"; plus WrapHTML for the gem's <pre class="highlight"><code> page wrapper. Beyond the gem, HLJS ("hljs") writes highlight.js class names (hljs-keyword, hljs-title function_), so stylesheets written for highlight.js colour Rouge's tokens; HLJSScope(token) gives the mapping. go-slides uses it for Marp's themes.
  • Themes — Base16, Github, ThankfulEyes: their resolved rendered_rules captured token-by-token, with StyleFor walking the ancestor chain exactly like Rouge::Theme.get_style.

Lexers

33 lexers. Each one is a near-mechanical transcription of the gem's state … rule … definition, validated by a differential oracle against the reference rouge gem (5.0.0; the Julia and R goldens were captured from 5.1.0, and tools/goldens verify reproduced the Python and Ruby goldens under it first): every committed testdata/* corpus file is highlighted and compared byte-for-byte to the gem's HTML (the *.html goldens). tools/goldens is the capture tool that produces them; its verify subcommand reproduces a golden that is already committed, which is the control on the capture itself.

Where the gem expresses a lexer as a subclass, so does this port: one builder carries the shared states and the hooks a subclass uses, so a rule added to C is a rule C++ gets, and a rule added to JavaScript is a rule TSX gets.

Byte-faithful (gem-identical HTML on the benign corpus):

Lexer Tag(s) Notes
Ruby ruby, rb symbols, %w/%r/%(…) sigils, heredocs (<</<<-/<<~), interpolation, ternary, method-call disambiguation
Go go, golang
Python python, py f-strings, case/match, decorators, doctest
JavaScript javascript, js regex/template/object/ternary state machine
JSON json
YAML yaml, yml indentation state machine, anchors, block scalars, tags
HTML html delegates <script>/<style> to JS/CSS
CSS css property/builtin/color/function sets
Shell shell, bash, zsh, ksh, sh heredocs, $()/${}/$(()), case
Diff diff, patch, udiff with content detector
Markdown markdown, md, mkd delegates fenced code to the named lexer, frontmatter to YAML
SQL sql case-insensitive keyword/type sets
PHP php, php3, php4, php5 start_inline option, <?php/<?= template delegation to HTML, string interpolation, heredocs, enums, function/property-hook sub-states
Java java text blocks, annotations, method signatures (the gem delegates the return arguments to Java itself), all four numeric bases with _ separators
C c preprocessor states (#if 0, #include <>/"", macro continuation), labels, function-signature recursion
C++ cpp, c++ C plus templates, raw strings with a delimiter backreference, ' digit separators, <=>, ::-aware case
Rust rust, rs, rust,no_run, rs,no_run, rust,ignore, rs,ignore, rust,should_panic, rs,should_panic nesting doc/plain block comments that keep the OUTER kind, macro delimiter counting, raw strings, rustc shebang detector
COBOL cobol divisions, sections and the IBM z/OS reserved-word list; fixed-form and *> comments
Fortran fortran Fortran 2008 free form: kind parameters, B/O/Z literals, .EQ.-style operator words, two-word keywords, FORMAT state
HCL hcl Hashicorp Configuration Language (*.hcl, *.nomad)
Terraform terraform, tf HCL plus ${…} interpolation, regex literals, var/local declarations
TOML toml tables and arrays of tables, dotted and quoted keys, dates and times, all four numeric bases with _ separators, multiline basic and literal strings
XML xml also SVG, PLIST, XSL/XSD/WSDL/RSS (*.svg, *.plist, *.xsl, …) — CDATA, processing instructions, entities, attribute states; content detector on the XML declaration and the doctype
Make make, makefile, mf, gnumake, bsdmake recipes, macro expansion, the GNU function list, conditionals, define; recipe bodies delegated to a continuing Shell lexer
TypeScript typescript, ts JavaScript plus the TypeScript word sets, as/satisfies, optional-property labels, ?. and ??
JSX jsx, react JavaScript plus elements, attributes and {…} interpolation; the text between tags delegated to a continuing HTML lexer
TSX tsx JSX plus TypeScript, and the <T,> / <Type> generic-argument rules
Dockerfile docker, dockerfile, containerfile instruction keywords, FROM … AS …, ONBUILD; RUN bodies delegated to a continuing Shell lexer
Protobuf protobuf, proto messages, enums, services, oneof, extensions, scalar types, all numeric forms
Julia julia, jl *.jl; #= … =# nesting block comments, function/macro and struct/abstract type name states, the generated type list, I"…"/L"…"/E"…" strings with $ formats, all numeric bases with _ separators, Unicode identifiers and operators; julia shebang detector
R r, R, s, S *.R, *.r, .Rhistory, .Rprofile; #' doc comments, %op%, hex/float/L/i numbers, primitive functions recognised only before (, keyword/constant/builtin classification; Rscript shebang detector
PlainText plaintext, text fallback

Documented simplifications (honest deviations from the gem):

  • Markdown fenced code blocks: the closed-fence form is byte-faithful; the gem's anonymous dynamic state for an unclosed fence is approximated.
  • HTML <script>/<style> delegation is per-chunk (matching the gem); like the gem, a token straddling a bare < inside an embedded string can split (the gem itself emits an Error there).
  • Ruby %-sigil string bodies are scanned in one pass (nesting + interpolation + escapes preserved); the heredoc (?<!\p{Word}) guard is done against the preceding byte (the engine has no variable-width lookbehind).
  • Guess uses each lexer's content detector only (a subset of the gem's multi-signal guesser) — enough for the unambiguous formats (diff, YAML, shebangs, doctype).
  • COBOL and Fortran drop the leading ^ of three rules, and COBOL drops a (?<![\w-]) guard, because in the gem neither assertion constrains anything. Rouge scans with StringScanner#skip, where both are evaluated as though the scan pointer were the start of the string. Measured against rouge 5.0.0: X * c gives Comment::Special for * c immediately after the X; selected_real_kind(15, 307) gives Name::Label for both numbers, from Fortran's ^(\s*)([0-9]+)\b statement-label rule; and = -ABC. gives Name then Punctuation, not a declined match. This engine anchors every rule with \G and evaluates ^ and lookbehind against the real buffer, so transcribing them literally makes the rules unreachable. \G alone already says "at the scan position", which is what the gem's assertions amount to.
  • HCL does not carry the gem's here-document rule or its :heredoc / :heredoc_nl states, because the gem cannot reach them: hcl.rb lists the operator class [-+*\/!%&<>|=:?] — which contains < — before the (<<-?)… rule, so <<EOF is consumed as two operators and a name. Measured: testdata/hcl.hcl carries two here-documents and the gem's own golden for it contains zero Str::Heredoc and zero Name::Constant spans. If upstream reorders those rules, the states go back.
  • Rust uses [\p{L}\p{Nl}_] and \p{Word} where the gem writes \p{XID_Start} and \p{XID_Continue}, which this engine does not provide. \p{Word} is Ruby's \p{L}\p{M}\p{N}\p{Pc}, a superset of XID_Continue and the same set for any identifier a program can carry; the Rust corpus includes non-ASCII identifiers so the substitution is checked against the gem rather than assumed.
  • TypeScript drops the three lookbehinds of the gem's as / satisfies rule, for the same reason COBOL and Fortran drop theirs: in the gem they constrain nothing. Measured against rouge 5.0.0 — fed x.as y, 1as b, ...as c and z as d, the gem marks as as Keyword::Declaration on all four lines, including the one after a dot that the gem's own source comment gives as the negative example. What actually keeps .as( out is the rule's trailing \s+, not its lookbehind.
  • Protobuf keeps the gem's [+-=] as written. It is a character range from + (U+002B) to = (U+003D) rather than the three characters it looks like, so it also covers , - . / 0-9 : ; <. Every one of those that could reach it is claimed by an earlier rule, so the widening is inert — but it is the gem's behaviour.
  • Make keeps the gem's unreachable function rule in :shell: the macro rule listed above it matches $( first, so the function rule can never fire. Like HCL's here-document, it is recorded rather than quietly "fixed", so that a reordering upstream is a change this port can follow.
  • Julia (julia.rb, rouge v5.1.0) drops the trailing-transpose rule (?<=[.\w)\]])'+ and the leading \b of its three word sets, for the reason given for TypeScript above: under StringScanner#skip the positive lookbehind can never hold, and \b at the scan pointer is true before any word character (every alternative starts with one). Measured: A' is a name and an Error in the gem, and 2if x marks if as a keyword. julia.rb's NAME_RE uses \p{Po}, which the engine does not have; it is spelled out from Go's unicode.Po table (\p{P} would also admit dashes and brackets). Its [^\S\n]+ is written (?:(?!\n)\s)+: the engine evaluates a negated class holding \S byte-wise, so it swallowed every non-ASCII character after a space (2 * π). Its mutable struct keyword alternative can never match, because the word set is an /x regexp and the space is ignored; that is kept.
  • R (r.rb, rouge v5.1.0) writes the primitive-function rule without its leading \b and (?<!.), again because both are evaluated at the scan pointer in the gem: x+1abs(2) gives abs as Name::Function. The mimetypes of both lexers are not carried (this library's lexer metadata has no such field).
  • PHP does not model funcnamehighlighting (the gem's built-in-function table promoting known calls to Name.Builtin); calls render as Name.Function, exactly as the gem does with funcnamehighlighting:false, the configuration the PHP goldens are captured under. Its start_inline fancy-spec option (php?start_inline=1) is honoured. FindFancy now applies a lexer's recognised options where the lexer defines them (PHP's start_inline); other options are still accepted and ignored.

Engine

Lexing runs on the sibling go-ruby-regexp Onigmo engine via its MatchAt(src, pos) primitive, which anchors \G at the scan cursor while keeping the whole buffer visible — so a rule's ^ matches only at a true line start and lookbehind sees the real prefix.

That is stricter than the gem, and the difference is why several rules are transcribed without their assertions (see the COBOL/Fortran and TypeScript notes above). Rouge tests rules with StringScanner#skip at the scan pointer, where a lookbehind cannot read the bytes before that pointer: a negative lookbehind always succeeds and a positive one always fails. Each such rule is therefore written from what the gem does, measured, rather than from what its pattern reads like.

A lexer may also delegate to another. Two shapes exist, both the gem's: delegate lexes a chunk with a fresh sub-lexer, while subDelegate is the gem's delegate @sub — it calls the sub-lexer's continue_lex, so its state stack survives between chunks and a quote opened in one chunk is still open in the next. Make, Dockerfile and JSX need the second kind.

Building this port upstreamed a handful of Onigmo-faithfulness fixes to that engine (\<punct> and \f \v \a \e escapes, the \p{Nl}/\p{No}/\p{Cf} property subcategories, and MatchAt itself).

Tests & coverage

Tests are deterministic and Ruby-free: the differential goldens were captured from the rouge gem once and committed, so go test reproduces gem-faithfulness without the gem on PATH (the gem is not stdlib, and the cross-arch / Windows CI lanes have no Ruby). Coverage is 100% including error branches, with zero uncovered blocks rather than a rounded total.

go test ./...

A lexer is a parser fed untrusted input, so every lexer is fuzzed (FuzzLexers, seed corpus committed under testdata/fuzz/). The invariant it asserts is the one that holds whatever the input: lexing accounts for every byte — none dropped, which would delete source from a rendered page, and none invented, which would be an injection.

"Every" is enforced by TestFuzzTagsCoverEveryLexer, which reads the lexer registry and fails on one that is registered but not fuzzed. ⛔ Until it was written this sentence was false: the fuzz list held only the eight lexers added in v0.7.0, so the twenty-three that had faced untrusted input the longest were the ones nobody fuzzed. A list is a list, and a short one fuzzes happily.

go test -fuzz FuzzLexers

Memory is bounded per match: every rule runs under a 16 MiB backtrack-stack limit (Onigmo's onig_set_match_stack_limit_size, via go-ruby-regexp's WithStackLimit). When a match hits it the rest of the input comes back as one Text token, not a panic and not an allocation that grows with the input. R's '(\\.|.)*?' holds 64 bytes per input byte, so an unterminated 1 MiB string is refused while a 256 KiB one is still lexed; every golden passes at 8 KiB. TestStackLimitBomb asserts the refusal, and CI runs it again alone under GOMEMLIMIT and ulimit -v.

Lexing is linear in the input, including against inputs built to defeat the lazy quantifiers the gem's rules use — unterminated comments, strings, tags, macros and template literals. TestLexingIsLinearInTheInput measures the adversarial shapes at 1k/2k/4k bytes; linear is 2x per doubling and 4x is quadratic. TestLongRunOfOneTokenIsLexedInLinearTime adds the long-run case at 64 KiB and 256 KiB: joining a run of equal tokens by += was quadratic, and a 1 MiB unterminated Julia block comment (one token per character) took about 28 seconds until the run was joined in one pass.

It was not always true. C, C++ and Java were quadratic on an unterminated block comment — 32 KiB took about 26 seconds (#17) — because the C-family function-signature rule scans forward for a { or ; that never arrives, and the lexer retries it at every scan position: O(n) attempts of O(n) work.

The fix is a necessary-condition prefilter, rule.needAny. That rule cannot match unless a { or ; lies at or after the scan position, so when none does the regex is never run. The position of the last such byte is found once per lex, making the check O(1). It can only skip attempts that would have FAILED, so the emitted tokens are unchanged by construction — which is what lets it exist in a library whose contract is byte-for-byte equivalence with the gem. The byte-for-byte golden suite passes unchanged.

Measured after the fix, on the input that used to take 26 seconds:

bytes C C++ Java
4096 1.59 ms 1.80 ms 1.85 ms
32768 12.51 ms 14.53 ms 14.80 ms

12.5 ms where it was ~26 s, and 1.95–2.03x per doubling throughout.

This section once said the worst ratio was 2.36x, with nothing in the repository reproducing it. It was wrong; writing the measurement is what showed that, and the defect it exposed is the one fixed above.

CI builds and tests on 3 OSes (linux/macos/windows) and the six 64-bit Go targets (amd64/arm64/riscv64/loong64/ppc64le/s390x).

License

BSD-3-Clause — see LICENSE. Copyright the go-rouge/rouge authors. The bundled themes' colour tables derive from the BSD-3-licensed rouge gem.

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

Documentation

Overview

Package rouge is a pure-Go (CGO=0), MRI-faithful port of the Ruby `rouge` syntax-highlighting gem (https://github.com/rouge-ruby/rouge). It tokenizes source code with state-machine regex lexers and formats the token stream as HTML, emitting exactly the CSS short-codes (k, s, c, nf, ...) the gem emits.

The token hierarchy, the regex-lexer engine, and the HTML formatters mirror the gem's data structures so the rendered HTML matches byte-for-byte on the supported lexers.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Text is the root token; it has the empty short-code.
	Text           = tok(nil, "Text", "")
	TextWhitespace = tok(Text, "Whitespace", "w")

	Escape = tok(nil, "Escape", "esc")
	Error  = tok(nil, "Error", "err")
	Other  = tok(nil, "Other", "x")

	Keyword            = tok(nil, "Keyword", "k")
	KeywordConstant    = tok(Keyword, "Constant", "kc")
	KeywordDeclaration = tok(Keyword, "Declaration", "kd")
	KeywordNamespace   = tok(Keyword, "Namespace", "kn")
	KeywordPseudo      = tok(Keyword, "Pseudo", "kp")
	KeywordReserved    = tok(Keyword, "Reserved", "kr")
	KeywordType        = tok(Keyword, "Type", "kt")
	KeywordVariable    = tok(Keyword, "Variable", "kv")

	Name                 = tok(nil, "Name", "n")
	NameAttribute        = tok(Name, "Attribute", "na")
	NameBuiltin          = tok(Name, "Builtin", "nb")
	NameBuiltinPseudo    = tok(NameBuiltin, "Pseudo", "bp")
	NameClass            = tok(Name, "Class", "nc")
	NameConstant         = tok(Name, "Constant", "no")
	NameDecorator        = tok(Name, "Decorator", "nd")
	NameEntity           = tok(Name, "Entity", "ni")
	NameException        = tok(Name, "Exception", "ne")
	NameFunction         = tok(Name, "Function", "nf")
	NameFunctionMagic    = tok(NameFunction, "Magic", "fm")
	NameProperty         = tok(Name, "Property", "py")
	NameLabel            = tok(Name, "Label", "nl")
	NameNamespace        = tok(Name, "Namespace", "nn")
	NameOther            = tok(Name, "Other", "nx")
	NameTag              = tok(Name, "Tag", "nt")
	NameVariable         = tok(Name, "Variable", "nv")
	NameVariableClass    = tok(NameVariable, "Class", "vc")
	NameVariableGlobal   = tok(NameVariable, "Global", "vg")
	NameVariableInstance = tok(NameVariable, "Instance", "vi")
	NameVariableMagic    = tok(NameVariable, "Magic", "vm")

	Literal     = tok(nil, "Literal", "l")
	LiteralDate = tok(Literal, "Date", "ld")

	LiteralString          = tok(Literal, "String", "s")
	LiteralStringAffix     = tok(LiteralString, "Affix", "sa")
	LiteralStringBacktick  = tok(LiteralString, "Backtick", "sb")
	LiteralStringChar      = tok(LiteralString, "Char", "sc")
	LiteralStringDelimiter = tok(LiteralString, "Delimiter", "dl")
	LiteralStringDoc       = tok(LiteralString, "Doc", "sd")
	LiteralStringDouble    = tok(LiteralString, "Double", "s2")
	LiteralStringEscape    = tok(LiteralString, "Escape", "se")
	LiteralStringHeredoc   = tok(LiteralString, "Heredoc", "sh")
	LiteralStringInterpol  = tok(LiteralString, "Interpol", "si")
	LiteralStringOther     = tok(LiteralString, "Other", "sx")
	LiteralStringRegex     = tok(LiteralString, "Regex", "sr")
	LiteralStringSingle    = tok(LiteralString, "Single", "s1")
	LiteralStringSymbol    = tok(LiteralString, "Symbol", "ss")

	LiteralNumber            = tok(Literal, "Number", "m")
	LiteralNumberBin         = tok(LiteralNumber, "Bin", "mb")
	LiteralNumberFloat       = tok(LiteralNumber, "Float", "mf")
	LiteralNumberHex         = tok(LiteralNumber, "Hex", "mh")
	LiteralNumberInteger     = tok(LiteralNumber, "Integer", "mi")
	LiteralNumberIntegerLong = tok(LiteralNumberInteger, "Long", "il")
	LiteralNumberOct         = tok(LiteralNumber, "Oct", "mo")
	LiteralNumberOther       = tok(LiteralNumber, "Other", "mx")

	Operator     = tok(nil, "Operator", "o")
	OperatorWord = tok(Operator, "Word", "ow")

	Punctuation          = tok(nil, "Punctuation", "p")
	PunctuationIndicator = tok(Punctuation, "Indicator", "pi")

	Comment            = tok(nil, "Comment", "c")
	CommentHashbang    = tok(Comment, "Hashbang", "ch")
	CommentDoc         = tok(Comment, "Doc", "cd")
	CommentMultiline   = tok(Comment, "Multiline", "cm")
	CommentPreproc     = tok(Comment, "Preproc", "cp")
	CommentPreprocFile = tok(Comment, "PreprocFile", "cpf")
	CommentSingle      = tok(Comment, "Single", "c1")
	CommentSpecial     = tok(Comment, "Special", "cs")

	Generic           = tok(nil, "Generic", "g")
	GenericDeleted    = tok(Generic, "Deleted", "gd")
	GenericEmph       = tok(Generic, "Emph", "ge")
	GenericEmphStrong = tok(Generic, "EmphStrong", "ges")
	GenericError      = tok(Generic, "Error", "gr")
	GenericHeading    = tok(Generic, "Heading", "gh")
	GenericInserted   = tok(Generic, "Inserted", "gi")
	GenericLineno     = tok(Generic, "Lineno", "gl")
	GenericOutput     = tok(Generic, "Output", "go")
	GenericPrompt     = tok(Generic, "Prompt", "gp")
	GenericStrong     = tok(Generic, "Strong", "gs")
	GenericSubheading = tok(Generic, "Subheading", "gu")
	GenericTraceback  = tok(Generic, "Traceback", "gt")
)

The token hierarchy. These mirror Rouge::Token::Tokens one-for-one, including the CSS short-codes, which are kept in sync with pygments STANDARD_TYPES.

View Source
var Base16 = &Theme{name: "base16", rules: map[string]string{
	"Text":                    "color: #383838",
	"Error":                   "color: #181818;background-color: #ab4642",
	"Comment":                 "color: #585858",
	"Comment.Preproc":         "color: #f7ca88",
	"Name.Tag":                "color: #f7ca88",
	"Operator":                "color: #d8d8d8",
	"Punctuation":             "color: #d8d8d8",
	"Generic.Inserted":        "color: #a1b56c",
	"Generic.Deleted":         "color: #ab4642",
	"Generic.Heading":         "color: #7cafc2;background-color: #181818;font-weight: bold",
	"Generic.Emph":            "font-style: italic",
	"Generic.EmphStrong":      "font-weight: bold;font-style: italic",
	"Generic.Strong":          "font-weight: bold",
	"Keyword":                 "color: #ba8baf",
	"Keyword.Constant":        "color: #dc9656",
	"Keyword.Type":            "color: #dc9656",
	"Keyword.Declaration":     "color: #dc9656",
	"Literal.String":          "color: #a1b56c",
	"Literal.String.Affix":    "color: #ba8baf",
	"Literal.String.Regex":    "color: #86c1b9",
	"Literal.String.Interpol": "color: #a16946",
	"Literal.String.Escape":   "color: #a16946",
	"Name.Namespace":          "color: #f7ca88",
	"Name.Class":              "color: #f7ca88",
	"Name.Constant":           "color: #f7ca88",
	"Name.Attribute":          "color: #7cafc2",
	"Literal.Number":          "color: #a1b56c",
	"Literal.String.Symbol":   "color: #a1b56c",
}}

Base16 is the rouge "base16" theme.

View Source
var Github = &Theme{name: "github", rules: map[string]string{
	"Text":                    "color: #24292f;background-color: #f6f8fa",
	"Keyword":                 "color: #cf222e",
	"Generic.Error":           "color: #f6f8fa",
	"Generic.Deleted":         "color: #82071e;background-color: #ffebe9",
	"Name.Builtin":            "color: #953800",
	"Name.Class":              "color: #953800",
	"Name.Constant":           "color: #953800",
	"Name.Namespace":          "color: #953800",
	"Literal.String.Regex":    "color: #116329",
	"Name.Attribute":          "color: #116329",
	"Name.Tag":                "color: #116329",
	"Generic.Inserted":        "color: #116329;background-color: #dafbe1",
	"Generic.EmphStrong":      "font-weight: bold;font-style: italic",
	"Keyword.Constant":        "color: #0550ae",
	"Literal":                 "color: #0550ae",
	"Literal.String.Backtick": "color: #0550ae",
	"Name.Builtin.Pseudo":     "color: #0550ae",
	"Name.Exception":          "color: #0550ae",
	"Name.Label":              "color: #0550ae",
	"Name.Property":           "color: #0550ae",
	"Name.Variable":           "color: #0550ae",
	"Operator":                "color: #0550ae",
	"Generic.Heading":         "color: #0550ae;font-weight: bold",
	"Generic.Subheading":      "color: #0550ae;font-weight: bold",
	"Literal.String":          "color: #0a3069",
	"Name.Decorator":          "color: #8250df",
	"Name.Function":           "color: #8250df",
	"Error":                   "color: #f6f8fa;background-color: #82071e",
	"Comment":                 "color: #6e7781",
	"Generic.Lineno":          "color: #6e7781",
	"Generic.Traceback":       "color: #6e7781",
	"Name.Entity":             "color: #24292f",
	"Literal.String.Interpol": "color: #24292f",
	"Generic.Emph":            "color: #24292f;font-style: italic",
	"Generic.Strong":          "color: #24292f;font-weight: bold",
}}

Github is the rouge "github" theme.

View Source
var ThankfulEyes = &Theme{name: "thankful_eyes", rules: map[string]string{
	"Text":                    "color: #faf6e4;background-color: #122b3b",
	"Generic.Lineno":          "color: #dee5e7;background-color: #4e5d62",
	"Generic.Prompt":          "color: #a8e1fe;font-weight: bold",
	"Comment":                 "color: #6c8b9f;font-style: italic",
	"Comment.Preproc":         "color: #b2fd6d;font-weight: bold",
	"Error":                   "color: #fefeec;background-color: #cc0000",
	"Generic.Error":           "color: #cc0000;font-weight: bold;font-style: italic",
	"Keyword":                 "color: #f6dd62;font-weight: bold",
	"Operator":                "color: #4df4ff;font-weight: bold",
	"Punctuation":             "color: #4df4ff",
	"Generic.Deleted":         "color: #cc0000",
	"Generic.Inserted":        "color: #b2fd6d",
	"Generic.Emph":            "font-style: italic",
	"Generic.EmphStrong":      "font-weight: bold;font-style: italic",
	"Generic.Strong":          "font-weight: bold",
	"Generic.Traceback":       "color: #dee5e7;background-color: #4e5d62",
	"Keyword.Constant":        "color: #f696db;font-weight: bold",
	"Keyword.Namespace":       "color: #ffb000;font-weight: bold",
	"Keyword.Pseudo":          "color: #ffb000;font-weight: bold",
	"Keyword.Reserved":        "color: #ffb000;font-weight: bold",
	"Generic.Heading":         "color: #ffb000;font-weight: bold",
	"Generic.Subheading":      "color: #ffb000;font-weight: bold",
	"Keyword.Type":            "color: #b2fd6d;font-weight: bold",
	"Name.Constant":           "color: #b2fd6d;font-weight: bold",
	"Name.Class":              "color: #b2fd6d;font-weight: bold",
	"Name.Decorator":          "color: #b2fd6d;font-weight: bold",
	"Name.Namespace":          "color: #b2fd6d;font-weight: bold",
	"Name.Builtin.Pseudo":     "color: #b2fd6d;font-weight: bold",
	"Name.Exception":          "color: #b2fd6d;font-weight: bold",
	"Name.Label":              "color: #ffb000;font-weight: bold",
	"Name.Tag":                "color: #ffb000;font-weight: bold",
	"Literal.Number":          "color: #f696db;font-weight: bold",
	"Literal.Date":            "color: #f696db;font-weight: bold",
	"Literal.String.Symbol":   "color: #f696db;font-weight: bold",
	"Literal.String":          "color: #fff0a6;font-weight: bold",
	"Literal.String.Affix":    "color: #f6dd62;font-weight: bold",
	"Literal.String.Escape":   "color: #4df4ff;font-weight: bold",
	"Literal.String.Char":     "color: #4df4ff;font-weight: bold",
	"Literal.String.Interpol": "color: #4df4ff;font-weight: bold",
	"Name.Builtin":            "font-weight: bold",
	"Name.Entity":             "color: #999999;font-weight: bold",
	"Text.Whitespace":         "color: #BBBBBB",
	"Generic.Output":          "color: #BBBBBB",
	"Name.Function":           "color: #a8e1fe",
	"Name.Property":           "color: #a8e1fe",
	"Name.Attribute":          "color: #a8e1fe",
	"Name.Variable":           "color: #a8e1fe;font-weight: bold",
}}

ThankfulEyes is the rouge "thankful_eyes" theme.

Functions

func HLJSScope added in v0.5.0

func HLJSScope(t *Token) string

HLJSScope returns the highlight.js scope of a token ("title.function"), or "" when it has none.

func Highlight

func Highlight(text, lexerName, formatterName string) (string, error)

Highlight tokenizes text with the named lexer and renders it with the named formatter, returning the formatted string. It mirrors Rouge.highlight. An unknown lexer or formatter name returns an error.

func WrapHTML

func WrapHTML(inner string) string

WrapHTML wraps formatted HTML in the gem's themed-page container, <pre class="highlight"><code>...</code></pre>, matching the markup Rouge::Formatters::HTMLPygments (and the rougify CLI) produce around the inner spans. The inner string must already be HTML from HTMLFormatter.

Types

type Formatter

type Formatter interface {
	// Format renders the whole token stream to a string.
	Format(tokens []TokenValue) string
	// Tag returns the formatter's registry tag (e.g. "html").
	Tag() string
}

Formatter renders a token stream into a string (HTML, inline-styled HTML, ...), mirroring Rouge::Formatter.

func FindFormatter

func FindFormatter(tag string) Formatter

FindFormatter returns the formatter registered under tag, or nil. Mirrors Rouge::Formatter.find.

type HLJSFormatter added in v0.5.0

type HLJSFormatter struct{}

HLJSFormatter renders the token stream with highlight.js class names (<span class="hljs-keyword">), so that stylesheets written for highlight.js — Marp's themes, for one — colour Rouge's output. This is not a Rouge formatter; the gem has no equivalent.

Tokens map to highlight.js scopes as its scope reference defines them (https://highlightjs.readthedocs.io/en/latest/css-classes-reference.html). A sub-scope becomes extra classes with one trailing underscore per level of depth, as highlight.js writes them: title.function is class="hljs-title function_". A token with no counterpart (plain text, names without a role, errors) is written unwrapped.

func (HLJSFormatter) Format added in v0.5.0

func (HLJSFormatter) Format(tokens []TokenValue) string

Format renders the stream.

func (HLJSFormatter) Tag added in v0.5.0

func (HLJSFormatter) Tag() string

Tag returns "hljs".

type HTMLFormatter

type HTMLFormatter struct{}

HTMLFormatter renders the token stream as <span class="shortcode"> elements, mirroring Rouge::Formatters::HTML. The bare Text token and the Escape token pass their value through without a wrapping span. Highlight does not add a <pre>/<code> wrapper; use WrapHTML for the gem's themed-page wrapper.

func (HTMLFormatter) Format

func (HTMLFormatter) Format(tokens []TokenValue) string

Format renders the stream. Each token becomes its escaped value wrapped in a span carrying the token's CSS short-code, except Text (passed through) and Escape (passed through unescaped, as in Rouge's escape?-aware path).

func (HTMLFormatter) Tag

func (HTMLFormatter) Tag() string

Tag returns "html".

type HTMLInlineFormatter

type HTMLInlineFormatter struct {
	// Theme supplies per-token CSS declarations.
	Theme *Theme
}

HTMLInlineFormatter renders each token with an inline style attribute computed from a Theme, mirroring Rouge::Formatters::HTMLInline. Text passes through without a span.

func (HTMLInlineFormatter) Format

func (f HTMLInlineFormatter) Format(tokens []TokenValue) string

Format renders the stream with inline styles from the formatter's Theme.

func (HTMLInlineFormatter) Tag

Tag returns "html_inline".

type Lexer

type Lexer interface {
	// Lex returns the token stream for text. The stream never contains empty
	// values.
	Lex(text string) []TokenValue
	// Tag returns the lexer's primary tag.
	Tag() string
	// Title returns the human-readable title.
	Title() string
	// Aliases returns alternate names.
	Aliases() []string
}

Lexer tokenizes source text into a stream of (token, value) pairs. Every lexer in this package is a *RegexLexer, but the interface lets callers and formatters work against the abstraction, mirroring Rouge::Lexer.

func FindFancy

func FindFancy(spec string) Lexer

FindFancy resolves a "fancy" lexer spec of the form "tag" or "tag?option=value&...", mirroring Rouge::Lexer.find_fancy. When the spec carries options and the resolved lexer understands them (its options hook is set, e.g. PHP's start_inline), FindFancy returns a configured variant; otherwise the options are ignored. An empty or "guess" name returns nil so callers can fall back to Guess. An unknown tag returns nil.

func FindLexer

func FindLexer(name string) Lexer

FindLexer returns the lexer registered under the given tag or alias, or nil if none matches. The lookup is case-insensitive on the tag, mirroring Rouge::Lexer.find.

func Guess

func Guess(text string) Lexer

Guess picks a lexer for text using each lexer's content sniffer (Rouge's self.detect?). The first lexer (in registration order) that claims the text wins; if none does, PlainText is returned, so Guess never returns nil. This is a deliberately small subset of Rouge's multi-signal guesser: it uses only the content detectors, which is enough for the formats whose detectors are unambiguous (e.g. diff). See README "Simplified" notes.

type RegexLexer

type RegexLexer struct {
	// contains filtered or unexported fields
}

RegexLexer is a stateful, regex-rule lexer. A concrete lexer registers its states with newRegexLexer / state-builder helpers and exposes itself through the Lexer interface. It is immutable after construction and safe for concurrent use; per-lex mutable state lives in lexState.

func (*RegexLexer) Aliases

func (rl *RegexLexer) Aliases() []string

Aliases returns the lexer's alternate names (e.g. "rb" for Ruby).

func (*RegexLexer) Lex

func (rl *RegexLexer) Lex(text string) []TokenValue

Lex tokenizes text and returns the token stream, mirroring Rouge::Lexer#lex for a RegexLexer. The stream never contains empty values.

func (*RegexLexer) Tag

func (rl *RegexLexer) Tag() string

Tag returns the lexer's primary tag (e.g. "ruby").

func (*RegexLexer) Title

func (rl *RegexLexer) Title() string

Title returns the lexer's human-readable title.

type Theme

type Theme struct {
	// contains filtered or unexported fields
}

Theme maps tokens to inline CSS declarations for the HTMLInline formatter, mirroring the resolved output of Rouge::Theme#style_for(tok).rendered_rules. Lookup walks the token's ancestor chain and returns the rules of the most specific ancestor that has a style, falling back to the base (Text) style, exactly like Rouge::Theme.get_style.

func FindTheme

func FindTheme(name string) *Theme

FindTheme returns the theme registered under name, or nil. Mirrors Rouge::Theme.find.

func (*Theme) Name

func (t *Theme) Name() string

Name returns the theme's name.

func (*Theme) StyleFor

func (t *Theme) StyleFor(tok *Token) string

StyleFor returns the ";"-joined inline CSS declarations for tok, resolving up the ancestor chain the way Rouge::Theme.get_style does: the closest ancestor (including tok itself) with a defined style wins; if none is defined the base Text style is used; if even Text is undefined the result is empty.

type Token

type Token struct {
	// Name is the simple token name, e.g. "Function".
	Name string
	// Shortname is the CSS class the HTML formatter emits, e.g. "nf". The root
	// Text token has the empty short-code.
	Shortname string
	// Parent is the enclosing token, nil for the root Text token.
	Parent *Token
	// contains filtered or unexported fields
}

Token is a syntactic token type, e.g. Keyword or Literal.String. Tokens form a tree mirroring Rouge::Token::Tokens: every token has a Name, a one- or two-letter CSS Shortname the HTML formatter emits, and a Parent. Tokens are compared by identity (pointer), so the package-level token variables below are the canonical instances.

func TokenByName

func TokenByName(qualname string) *Token

TokenByName returns the canonical token for a dotted qualified name (e.g. "Keyword.Constant"), or nil if no such token exists. It mirrors Rouge::Token::Tokens[qualname].

func (*Token) Matches

func (t *Token) Matches(other *Token) bool

Matches reports whether t is other or a descendant of other, mirroring Rouge::Token.matches? (other appears in t's ancestor chain).

func (*Token) Qualname

func (t *Token) Qualname() string

Qualname is the dotted fully-qualified name of the token, e.g. "Literal.String.Double", matching Rouge::Token#qualname.

func (*Token) String

func (t *Token) String() string

String returns the token's qualified name.

type TokenValue

type TokenValue struct {
	Token *Token
	Value string
}

TokenValue is a (token, value) pair in the lexed stream.

type UnknownError

type UnknownError struct {
	// Kind is "lexer" or "formatter".
	Kind string
	// Name is the unrecognized name.
	Name string
}

UnknownError reports an unknown lexer or formatter name from Highlight.

func (*UnknownError) Error

func (e *UnknownError) Error() string

Directories

Path Synopsis
tools
goldens module
refbench module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址