Documentation
¶
Overview ¶
Package chroma takes source code and other structured text and converts it into syntax highlighted HTML, ANSI- coloured text, etc.
Chroma is based heavily on Pygments, and includes translators for Pygments lexers and styles.
For more information, go here: https://github.com/alecthomas/chroma
Index ¶
- Constants
- Variables
- func Concaterator(iterators ...iter.Seq[Token]) iter.Seq[Token]
- func Literator(tokens ...Token) iter.Seq[Token]
- func Lookup[V any](values map[TokenType]V, t TokenType) (V, bool)
- func SplitTokensIntoLines(tokens iter.Seq[Token]) iter.Seq[[]Token]
- func Stringify(tokens ...Token) string
- func TokenTypeStrings() []string
- func Words(prefix, suffix string, words ...string) string
- type AnalyseConfig
- type Colour
- func (c Colour) Blue() uint8
- func (c Colour) Brighten(factor float64) Colour
- func (c Colour) BrightenOrDarken(factor float64) Colour
- func (c Colour) Brightness() float64
- func (c Colour) ClampBrightness(low, high float64) Colour
- func (c Colour) Distance(e2 Colour) float64
- func (c Colour) GoString() string
- func (c Colour) Green() uint8
- func (c Colour) IsSet() bool
- func (c Colour) Red() uint8
- func (c Colour) String() string
- type CompiledRule
- type CompiledRules
- type Config
- type Emitter
- type EmitterFunc
- type Formatter
- type FormatterFunc
- type Lexer
- func Coalesce(lexer Lexer) Lexer
- func DelegatingLexer(root Lexer, language Lexer) Lexer
- func MustNewXMLLexer(from fs.FS, path string) Lexer
- func NewXMLLexer(from fs.FS, path string) (Lexer, error)
- func NewXMLLexerFromConfig(config *Config, from fs.FS, path string) (Lexer, error)
- func RemappingLexer(lexer Lexer, mapper func(Token) []Token) Lexer
- func TypeRemappingLexer(lexer Lexer, mapping TypeMapping) Lexer
- type LexerMutator
- type LexerRegistry
- func (l *LexerRegistry) Aliases(skipWithoutAliases bool) []string
- func (l *LexerRegistry) All() []Lexer
- func (l *LexerRegistry) Analyse(text string) Lexer
- func (l *LexerRegistry) Get(name string) Lexer
- func (l *LexerRegistry) Match(filename string) Lexer
- func (l *LexerRegistry) MatchMimeType(mimeType string) Lexer
- func (l *LexerRegistry) Names(withAliases bool) []string
- func (l *LexerRegistry) Register(lexer Lexer) Lexer
- type LexerState
- type Mode
- type Mutator
- type MutatorFunc
- type RegexConfig
- type RegexLexer
- func (r *RegexLexer) AnalyseText(text string) float32
- func (r *RegexLexer) Config() *Config
- func (r *RegexLexer) Rules() (Rules, error)
- func (r *RegexLexer) SetAnalyser(analyser func(text string) float32) Lexer
- func (r *RegexLexer) SetRegistry(registry *LexerRegistry) Lexer
- func (r *RegexLexer) String() string
- func (r *RegexLexer) Tokenise(text string, opts ...TokeniseOption) (iter.Seq[Token], error)
- type Rule
- type Rules
- type Style
- func (s *Style) Builder() *StyleBuilder
- func (s *Style) Get(ttype TokenType) StyleEntry
- func (s *Style) Has(ttype TokenType) bool
- func (s *Style) MarshalXML(e *xml.Encoder, start xml.StartElement) error
- func (s *Style) Mode() Mode
- func (s *Style) Types() []TokenType
- func (s *Style) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
- type StyleBuilder
- func (s *StyleBuilder) Add(ttype TokenType, entry string) *StyleBuilder
- func (s *StyleBuilder) AddAll(entries StyleEntries) *StyleBuilder
- func (s *StyleBuilder) AddEntry(ttype TokenType, entry StyleEntry) *StyleBuilder
- func (s *StyleBuilder) Build() (*Style, error)
- func (s *StyleBuilder) Counterpart(name string) *StyleBuilder
- func (s *StyleBuilder) Get(ttype TokenType) StyleEntry
- func (s *StyleBuilder) Transform(transform func(StyleEntry) StyleEntry) *StyleBuilder
- type StyleEntries
- type StyleEntry
- type Token
- type TokenType
- func (t TokenType) Category() TokenType
- func (t TokenType) Emit(groups []string, _ *LexerState) iter.Seq[Token]
- func (t TokenType) InCategory(other TokenType) bool
- func (t TokenType) InSubCategory(other TokenType) bool
- func (i TokenType) IsATokenType() bool
- func (i TokenType) MarshalText() ([]byte, error)
- func (t TokenType) Parent() TokenType
- func (i TokenType) String() string
- func (t TokenType) SubCategory() TokenType
- func (i *TokenType) UnmarshalText(text []byte) error
- func (t *TokenType) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error
- type TokeniseOption
- type TokeniseOptions
- type Trace
- type Trilean
- type TypeMapping
- type ValidatingEmitter
- type ValidatingMutator
Constants ¶
const ( Whitespace = TextWhitespace Date = LiteralDate String = LiteralString StringAffix = LiteralStringAffix StringBacktick = LiteralStringBacktick StringChar = LiteralStringChar StringDelimiter = LiteralStringDelimiter StringDoc = LiteralStringDoc StringDouble = LiteralStringDouble StringEscape = LiteralStringEscape StringHeredoc = LiteralStringHeredoc StringInterpol = LiteralStringInterpol StringOther = LiteralStringOther StringRegex = LiteralStringRegex StringSingle = LiteralStringSingle StringSymbol = LiteralStringSymbol Number = LiteralNumber NumberBin = LiteralNumberBin NumberFloat = LiteralNumberFloat NumberHex = LiteralNumberHex NumberInteger = LiteralNumberInteger NumberIntegerLong = LiteralNumberIntegerLong NumberOct = LiteralNumberOct )
Aliases.
Variables ¶
var MatchTimeout = 2 * time.Second
MatchTimeout bounds each attempt to match a rule.
It is read when a lexer is first used, so set it before then.
var ( // StandardTypes maps token types to their short CSS class names. // // Token types deliberately absent from this map (e.g. NameKeyword, // LiteralStringAtom) inherit the class of their sub-category or // category via Lookup; formatters should resolve classes through that // fallback rather than expecting an entry for every TokenType. StandardTypes = map[TokenType]string{ Background: "bg", PreWrapper: "chroma", Line: "line", LineNumbers: "ln", LineNumbersTable: "lnt", LineHighlight: "hl", LineTable: "lntable", LineTableTD: "lntd", LineLink: "lnlinks", CodeLine: "cl", Text: "", Whitespace: "w", Error: "err", Other: "x", Keyword: "k", KeywordConstant: "kc", KeywordDeclaration: "kd", KeywordNamespace: "kn", KeywordPseudo: "kp", KeywordReserved: "kr", KeywordType: "kt", Name: "n", NameAttribute: "na", NameBuiltin: "nb", NameBuiltinPseudo: "bp", NameClass: "nc", NameConstant: "no", NameDecorator: "nd", NameEntity: "ni", NameException: "ne", NameFunction: "nf", NameFunctionMagic: "fm", NameProperty: "py", NameLabel: "nl", NameNamespace: "nn", NameOther: "nx", NameTag: "nt", NameVariable: "nv", NameVariableClass: "vc", NameVariableGlobal: "vg", NameVariableInstance: "vi", NameVariableMagic: "vm", Literal: "l", LiteralDate: "ld", String: "s", StringAffix: "sa", StringBacktick: "sb", StringChar: "sc", StringDelimiter: "dl", StringDoc: "sd", StringDouble: "s2", StringEscape: "se", StringHeredoc: "sh", StringInterpol: "si", StringOther: "sx", StringRegex: "sr", StringSingle: "s1", StringSymbol: "ss", Number: "m", NumberBin: "mb", NumberFloat: "mf", NumberHex: "mh", NumberInteger: "mi", NumberIntegerLong: "il", NumberOct: "mo", Operator: "o", OperatorWord: "ow", OperatorReserved: "or", Punctuation: "p", Comment: "c", CommentHashbang: "ch", CommentMultiline: "cm", CommentPreproc: "cp", CommentPreprocFile: "cpf", CommentSingle: "c1", CommentSpecial: "cs", Generic: "g", GenericDeleted: "gd", GenericEmph: "ge", GenericError: "gr", GenericHeading: "gh", GenericInserted: "gi", GenericOutput: "go", GenericPrompt: "gp", GenericStrong: "gs", GenericSubheading: "gu", GenericTraceback: "gt", GenericUnderline: "gl", } )
Functions ¶
func Concaterator ¶
Concaterator concatenates tokens from a series of iterators.
func Lookup ¶
Lookup returns the value in values for t, falling back through t's parents (sub-category, then category) until a match is found.
func SplitTokensIntoLines ¶
SplitTokensIntoLines lazily splits tokens into lines, splitting tokens containing newlines in two.
func TokenTypeStrings ¶
func TokenTypeStrings() []string
TokenTypeStrings returns a slice of all String values of the enum
Types ¶
type AnalyseConfig ¶
type AnalyseConfig struct {
Regexes []RegexConfig `xml:"regex,omitempty"`
// If true, the first matching score is returned.
First bool `xml:"first,attr"`
}
AnalyseConfig defines the list of regexes analysers.
type Colour ¶
type Colour int32
Colour represents an RGB colour.
func MustParseColour ¶
MustParseColour is like ParseColour except it panics if the colour is invalid.
Will panic if colour is in an invalid format.
func ParseColour ¶
ParseColour in the forms #rgb, #rrggbb, #ansi<colour>, or #<colour>. Will return an "unset" colour if invalid.
func (Colour) Brighten ¶
Brighten returns a copy of this colour with its brightness adjusted.
If factor is negative, the colour is darkened.
Uses approach described here (http://www.pvladov.com/2012/09/make-color-lighter-or-darker.html).
func (Colour) BrightenOrDarken ¶
BrightenOrDarken brightens a colour if it is < 0.5 brightness or darkens if > 0.5 brightness.
func (Colour) Brightness ¶
Brightness of the colour (roughly) in the range 0.0 to 1.0.
func (Colour) ClampBrightness ¶
ClampBrightness returns a copy of this colour with its brightness adjusted such that it falls within the range [low, high] (or very close to it due to rounding errors). The supplied values use the same [0.0, 1.0] range as Brightness.
func (Colour) Distance ¶
Distance between this colour and another.
This uses the approach described here (https://www.compuphase.com/cmetric.htm). This is not as accurate as LAB, et. al. but is *vastly* simpler and sufficient for our needs.
type CompiledRule ¶
A CompiledRule is a Rule with a pre-compiled regex.
Note that regular expressions are lazily compiled on first use of the lexer.
type CompiledRules ¶
type CompiledRules map[string][]*CompiledRule
CompiledRules is a map of rule name to sequence of compiled rules in that rule.
type Config ¶
type Config struct {
// Name of the lexer.
Name string `xml:"name,omitempty"`
// Shortcuts for the lexer
Aliases []string `xml:"alias,omitempty"`
// File name globs
Filenames []string `xml:"filename,omitempty"`
// Secondary file name globs
AliasFilenames []string `xml:"alias_filename,omitempty"`
// MIME types
MimeTypes []string `xml:"mime_type,omitempty"`
// Regex matching is case-insensitive.
CaseInsensitive bool `xml:"case_insensitive,omitempty"`
// Regex matches all characters.
DotAll bool `xml:"dot_all,omitempty"`
// Regex does not match across lines ($ matches EOL).
//
// Defaults to multiline.
NotMultiline bool `xml:"not_multiline,omitempty"`
// Make sure that the input ends with a newline. This
// is required for some lexers that consume input linewise.
EnsureNL bool `xml:"ensure_nl,omitempty"`
// Priority of lexer.
//
// If this is 0 it will be treated as a default of 1.
Priority float32 `xml:"priority,omitempty"`
// Delegate names the lexer that tokenises the text this lexer emits as
// Other. See DelegatingLexer.
Delegate string `xml:"delegate,omitempty"`
// Analyse is a list of regexes to match against the input.
//
// If First is set, the score of the first matching pattern is returned,
// otherwise the scores of all matching patterns are summed. Either way
// the result is capped at 1.
Analyse *AnalyseConfig `xml:"analyse,omitempty"`
}
Config for a lexer.
type Emitter ¶
type Emitter interface {
// Emit tokens for the given regex groups.
Emit(groups []string, state *LexerState) iter.Seq[Token]
}
An Emitter takes group matches and returns tokens.
func ByGroupNames ¶
ByGroupNames emits a token for each named matching group in the rule's regex.
func Using ¶
Using returns an Emitter that uses a given Lexer reference for parsing and emitting.
The referenced lexer must be stored in the same LexerRegistry.
func UsingByGroup ¶
UsingByGroup emits tokens for the matched groups in the regex using a sublexer. Used when lexing code blocks where the name of a sublexer is contained within the block, for example on a Markdown text block or SQL language block.
An attempt to load the sublexer will be made using the captured value from the text of the matched sublexerNameGroup. If a sublexer matching the sublexerNameGroup is available, then tokens for the matched codeGroup will be emitted using the sublexer. Otherwise, if no sublexer is available, then tokens will be emitted from the passed emitter.
Example:
var Markdown = lexers.Register(MustNewLexer(
&Config{
Name: "markdown",
Aliases: []string{"md", "mkd"},
Filenames: []string{"*.md", "*.mkd", "*.markdown"},
MimeTypes: []string{"text/x-markdown"},
},
Rules{
"root": {
{"^(```)(\\w+)(\\n)([\\w\\W]*?)(^```$)",
UsingByGroup(
2, 4,
String, String, String, Text, String,
),
nil,
},
},
},
))
See lexers/embedded/markdown.xml for the complete example.
Note: panic's if the number of emitters does not equal the number of matched groups in the regex.
func UsingLexer ¶
UsingLexer returns an Emitter that uses a given Lexer for parsing and emitting.
This Emitter cannot be represented in an XML lexer definition.
type EmitterFunc ¶
type EmitterFunc func(groups []string, state *LexerState) iter.Seq[Token]
EmitterFunc is a function that is an Emitter.
func (EmitterFunc) Emit ¶
func (e EmitterFunc) Emit(groups []string, state *LexerState) iter.Seq[Token]
Emit tokens for groups.
type Formatter ¶
type Formatter interface {
// Format writes the tokens from iterator to w using style.
//
// If the iterator panics, the Formatter should recover and return the
// panic as an error.
Format(w io.Writer, style *Style, iterator iter.Seq[Token]) error
}
A Formatter for Chroma lexers.
type FormatterFunc ¶
A FormatterFunc is a Formatter implemented as a function.
Guards against iterator panics.
type Lexer ¶
type Lexer interface {
// Config describing the features of the Lexer.
Config() *Config
// Tokenise returns an iterator over tokens in text. The iterator panics if
// lexing fails mid-stream; Formatters recover this, direct consumers must.
Tokenise(text string, options ...TokeniseOption) (iter.Seq[Token], error)
// SetRegistry sets the registry this Lexer is associated with.
//
// The registry should be used by the Lexer if it needs to look up other
// lexers.
SetRegistry(registry *LexerRegistry) Lexer
// SetAnalyser sets a function the Lexer should use for scoring how
// likely a fragment of text is to match this lexer, between 0.0 and 1.0.
// A value of 1 indicates high confidence.
//
// Lexers may ignore this if they implement their own analysers.
SetAnalyser(analyser func(text string) float32) Lexer
// AnalyseText scores how likely a fragment of text is to match
// this lexer, between 0.0 and 1.0. A value of 1 indicates high confidence.
AnalyseText(text string) float32
}
A Lexer for tokenising source code.
func Coalesce ¶
Coalesce is a Lexer interceptor that collapses runs of common types into a single token.
func DelegatingLexer ¶
DelegatingLexer combines two lexers to handle the common case of a language embedded inside another, such as PHP inside HTML or PHP inside plain text.
It takes two lexers as arguments: a root lexer and a language lexer. First everything is scanned using the language lexer, which must return "Other" for unrecognised tokens. Then all "Other" tokens are lexed using the root lexer. Finally, these two sets of tokens are merged.
The lexers from the template lexer package use this base lexer.
func MustNewXMLLexer ¶
MustNewXMLLexer constructs a new Lexer from an XML file or panics.
func NewXMLLexer ¶
NewXMLLexer creates a new Lexer from an XML lexer definition.
func NewXMLLexerFromConfig ¶
NewXMLLexerFromConfig creates a Lexer whose Config is already known, loading its rules lazily from the XML definition at path in from.
The lexer is a RegexLexer, wrapped in a DelegatingLexer if the Config has a Delegate. The delegate is looked up in the lexer's LexerRegistry.
The analyser regexes in config are compiled lazily on the first call to AnalyseText; an invalid analyser regex results in a zero score at analyse time rather than an error here.
func RemappingLexer ¶
RemappingLexer remaps a token to a set of, potentially empty, tokens.
func TypeRemappingLexer ¶
func TypeRemappingLexer(lexer Lexer, mapping TypeMapping) Lexer
TypeRemappingLexer remaps types of tokens coming from a parent Lexer.
eg. Map "defvaralias" tokens of type NameVariable to NameFunction:
mapping := TypeMapping{
{NameVariable, NameFunction, []string{"defvaralias"},
}
lexer = TypeRemappingLexer(lexer, mapping)
type LexerMutator ¶
type LexerMutator interface {
// MutateLexer can be implemented to mutate the lexer itself.
//
// Rules are the lexer rules, state is the state key for the rule the mutator is associated with.
MutateLexer(rules CompiledRules, state string, rule int) error
}
A LexerMutator is an additional interface that a Mutator can implement to modify the lexer when it is compiled.
type LexerRegistry ¶
type LexerRegistry struct {
// contains filtered or unexported fields
}
LexerRegistry is a registry of Lexers.
Registration is not synchronised: register all lexers (typically at init time) before using the registry concurrently.
func NewLexerRegistry ¶
func NewLexerRegistry() *LexerRegistry
NewLexerRegistry creates a new LexerRegistry of Lexers.
func (*LexerRegistry) Aliases ¶
func (l *LexerRegistry) Aliases(skipWithoutAliases bool) []string
Aliases of all the lexers, and skip those lexers who do not have any aliases, or show their name instead
func (*LexerRegistry) All ¶
func (l *LexerRegistry) All() []Lexer
All returns a copy of the registered lexers, sorted case-insensitively by name.
func (*LexerRegistry) Analyse ¶
func (l *LexerRegistry) Analyse(text string) Lexer
Analyse text content and return the "best" lexer..
func (*LexerRegistry) Get ¶
func (l *LexerRegistry) Get(name string) Lexer
Get a Lexer by name, alias or file extension.
func (*LexerRegistry) Match ¶
func (l *LexerRegistry) Match(filename string) Lexer
Match returns the highest priority lexer whose Filenames match the base name of filename, falling back to its AliasFilenames. Globs also match with one of the ignored backup suffixes, such as ".bak", appended.
func (*LexerRegistry) MatchMimeType ¶
func (l *LexerRegistry) MatchMimeType(mimeType string) Lexer
MatchMimeType attempts to find a lexer for the given MIME type.
func (*LexerRegistry) Names ¶
func (l *LexerRegistry) Names(withAliases bool) []string
Names of all lexers, optionally including aliases.
func (*LexerRegistry) Register ¶
func (l *LexerRegistry) Register(lexer Lexer) Lexer
Register a Lexer with the LexerRegistry. If the lexer is already registered it will be replaced.
Not safe to call concurrently with any other method on the registry.
type LexerState ¶
type LexerState struct {
Lexer *RegexLexer
Registry *LexerRegistry
Text []rune
Pos int
Rules CompiledRules
Stack []string
State string
Rule int
// Group matches.
Groups []string
// Named Group matches.
NamedGroups map[string]string
// contains filtered or unexported fields
}
LexerState contains the state for a single lex.
func (*LexerState) Iterator ¶
func (l *LexerState) Iterator() iter.Seq[Token]
Iterator returns an iterator over tokens from the lexer.
func (*LexerState) Nested ¶
func (l *LexerState) Nested(state string) TokeniseOption
Nested returns the option for an Emitter to tokenise part of the current match with another Lexer, or this one, starting in state.
func (*LexerState) Set ¶
func (l *LexerState) Set(key any, value any)
Set a value in the context shared by Mutators and Emitters during one tokenisation.
type Mode ¶
type Mode uint8
Mode indicates whether a style is intended for a light or dark background.
type Mutator ¶
type Mutator interface {
// Mutate the lexer state machine as it is processing.
Mutate(state *LexerState) error
}
A Mutator modifies the behaviour of the lexer.
func Combined ¶
Combined creates a new anonymous state from the given states, and pushes that state.
type MutatorFunc ¶
type MutatorFunc func(state *LexerState) error
A MutatorFunc is a Mutator that mutates the lexer state machine as it is processing.
func (MutatorFunc) Mutate ¶
func (m MutatorFunc) Mutate(state *LexerState) error
type RegexConfig ¶
RegexConfig defines a single regex pattern and its score in case of match.
type RegexLexer ¶
type RegexLexer struct {
// contains filtered or unexported fields
}
RegexLexer is the default lexer implementation used in Chroma.
func MustNewLexer ¶
func MustNewLexer(config *Config, rules func() Rules) *RegexLexer
MustNewLexer creates a new Lexer with deferred rules generation or panics.
func NewLexer ¶
func NewLexer(config *Config, rulesFunc func() Rules) (*RegexLexer, error)
NewLexer creates a new regex-based Lexer.
"rules" is a state machine transition map. Each key is a state. Values are sets of rules that match input, optionally modify lexer state, and output tokens.
func (*RegexLexer) AnalyseText ¶
func (r *RegexLexer) AnalyseText(text string) float32
AnalyseText scores how likely a fragment of text is to match this lexer, between 0.0 and 1.0.
func (*RegexLexer) Config ¶
func (r *RegexLexer) Config() *Config
Config returns the Config for this Lexer.
func (*RegexLexer) SetAnalyser ¶
func (r *RegexLexer) SetAnalyser(analyser func(text string) float32) Lexer
SetAnalyser sets the analyser function used to perform content inspection.
func (*RegexLexer) SetRegistry ¶
func (r *RegexLexer) SetRegistry(registry *LexerRegistry) Lexer
SetRegistry the lexer will use to lookup other lexers if necessary.
func (*RegexLexer) String ¶
func (r *RegexLexer) String() string
func (*RegexLexer) Tokenise ¶
func (r *RegexLexer) Tokenise(text string, opts ...TokeniseOption) (iter.Seq[Token], error)
Tokenise text using lexer, returning an iterator.
type Rule ¶
A Rule is the fundamental matching unit of the Regex lexer state machine.
func (*Rule) UnmarshalXML ¶
type Style ¶
type Style struct {
Name string
// Counterpart is the lowercase name of the style intended as this style's
// opposite-mode pair (eg. "github-dark" for "github"). Resolved via
// styles.GetForMode. May be empty.
Counterpart string
// contains filtered or unexported fields
}
A Style definition.
See http://pygments.org/docs/styles/ for details. Semantics are intended to be identical.
func MustNewStyle ¶
func MustNewStyle(name string, entries StyleEntries) *Style
MustNewStyle creates a new style or panics.
func MustNewXMLStyle ¶
MustNewXMLStyle is like NewXMLStyle but panics on error.
func NewStyle ¶
func NewStyle(name string, entries StyleEntries) (*Style, error)
NewStyle creates a new style definition.
func NewXMLStyle ¶
NewXMLStyle parses an XML style definition.
func (*Style) Builder ¶
func (s *Style) Builder() *StyleBuilder
Builder creates a mutable builder from this Style.
The builder can then be safely modified. This is a cheap operation.
func (*Style) Get ¶
func (s *Style) Get(ttype TokenType) StyleEntry
Get a style entry. Will try sub-category or category if an exact match is not found, and finally return the Background.
func (*Style) Has ¶
Has checks if an exact style entry match exists for a token type.
This is distinct from Get() which will merge parent tokens.
func (*Style) MarshalXML ¶
func (*Style) Mode ¶
Mode returns Light or Dark based on the brightness of the Background entry's background colour. Styles with an unset Background default to Light.
func (*Style) UnmarshalXML ¶
type StyleBuilder ¶
type StyleBuilder struct {
// contains filtered or unexported fields
}
A StyleBuilder is a mutable structure for building styles.
Once built, a Style is immutable.
func NewStyleBuilder ¶
func NewStyleBuilder(name string) *StyleBuilder
func (*StyleBuilder) Add ¶
func (s *StyleBuilder) Add(ttype TokenType, entry string) *StyleBuilder
Add an entry to the Style map.
See http://pygments.org/docs/styles/#style-rules for details.
func (*StyleBuilder) AddAll ¶
func (s *StyleBuilder) AddAll(entries StyleEntries) *StyleBuilder
func (*StyleBuilder) AddEntry ¶
func (s *StyleBuilder) AddEntry(ttype TokenType, entry StyleEntry) *StyleBuilder
func (*StyleBuilder) Build ¶
func (s *StyleBuilder) Build() (*Style, error)
func (*StyleBuilder) Counterpart ¶
func (s *StyleBuilder) Counterpart(name string) *StyleBuilder
Counterpart sets the lowercase name of the opposite-mode style.
func (*StyleBuilder) Get ¶
func (s *StyleBuilder) Get(ttype TokenType) StyleEntry
func (*StyleBuilder) Transform ¶
func (s *StyleBuilder) Transform(transform func(StyleEntry) StyleEntry) *StyleBuilder
Transform passes each style entry currently defined in the builder to the supplied function and saves the returned value. This can be used to adjust a style's colours; see Colour's ClampBrightness function, for example.
type StyleEntries ¶
StyleEntries mapping TokenType to colour definition.
type StyleEntry ¶
type StyleEntry struct {
// Hex colours.
Colour Colour
Background Colour
Border Colour
Bold Trilean
Italic Trilean
Underline Trilean
NoInherit bool
}
A StyleEntry in the Style map.
func MustParseStyleEntry ¶
func MustParseStyleEntry(entry string) StyleEntry
MustParseStyleEntry parses a Pygments style entry or panics.
func ParseStyleEntry ¶
func ParseStyleEntry(entry string) (StyleEntry, error)
ParseStyleEntry parses a Pygments style entry.
func (StyleEntry) Inherit ¶
func (s StyleEntry) Inherit(ancestors ...StyleEntry) StyleEntry
Inherit styles from ancestors.
Ancestors should be provided from oldest to newest.
func (StyleEntry) IsZero ¶
func (s StyleEntry) IsZero() bool
func (StyleEntry) MarshalText ¶
func (s StyleEntry) MarshalText() ([]byte, error)
func (StyleEntry) String ¶
func (s StyleEntry) String() string
func (StyleEntry) Sub ¶
func (s StyleEntry) Sub(e StyleEntry) StyleEntry
Sub subtracts e from s where elements match.
type TokenType ¶
type TokenType int
TokenType is the type of token to highlight.
It is also an Emitter, emitting a single token of itself
const ( // Default background style. Background TokenType = -1 - iota // PreWrapper style. PreWrapper // Line style. Line // Line numbers in output. LineNumbers // Line numbers in output when in table. LineNumbersTable // Line highlight style. LineHighlight // Line numbers table wrapper style. LineTable // Line numbers table TD wrapper style. LineTableTD // Line number links. LineLink // Code line wrapper style. CodeLine // Input that could not be tokenised. Error // Other is used by the Delegate lexer to indicate which tokens should be handled by the delegate. Other // No highlighting. None // Don't emit this token to the output. Ignore )
Meta token types.
const ( Keyword TokenType = 1000 + iota KeywordConstant KeywordDeclaration KeywordNamespace KeywordPseudo KeywordReserved KeywordType )
Keywords.
const ( Name TokenType = 2000 + iota NameAttribute NameClass NameConstant NameDecorator NameEntity NameException NameKeyword NameLabel NameNamespace NameOperator NameOther NamePseudo NameProperty NameTag )
Names.
const ( NameVariable TokenType = 2200 + iota NameVariableAnonymous NameVariableClass NameVariableGlobal NameVariableInstance NameVariableMagic )
Variable names.
const ( LiteralString TokenType = 3100 + iota LiteralStringAffix LiteralStringAtom LiteralStringBacktick LiteralStringBoolean LiteralStringChar LiteralStringDelimiter LiteralStringDoc LiteralStringDouble LiteralStringEscape LiteralStringHeredoc LiteralStringInterpol LiteralStringName LiteralStringOther LiteralStringRegex LiteralStringSingle LiteralStringSymbol )
Strings.
const ( LiteralNumber TokenType = 3200 + iota LiteralNumberBin LiteralNumberFloat LiteralNumberHex LiteralNumberInteger LiteralNumberIntegerLong LiteralNumberOct LiteralNumberByte )
Literals.
const ( Comment TokenType = 6000 + iota CommentHashbang CommentMultiline CommentSingle CommentSpecial )
Comments.
const ( Generic TokenType = 7000 + iota GenericDeleted GenericEmph GenericError GenericHeading GenericInserted GenericOutput GenericPrompt GenericStrong GenericSubheading GenericTraceback GenericUnderline )
Generic tokens.
func TokenTypeString ¶
TokenTypeString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.
func TokenTypeValues ¶
func TokenTypeValues() []TokenType
TokenTypeValues returns all values of the enum
func (TokenType) InCategory ¶
func (TokenType) InSubCategory ¶
func (TokenType) IsATokenType ¶
IsATokenType returns "true" if the value is listed in the enum definition. "false" otherwise
func (TokenType) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface for TokenType
func (TokenType) SubCategory ¶
func (*TokenType) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface for TokenType
func (*TokenType) UnmarshalXML ¶
type TokeniseOption ¶
type TokeniseOption func(*TokeniseOptions)
A TokeniseOption modifies the default TokeniseOptions.
func WithEnsureLF ¶
func WithEnsureLF(ensure bool) TokeniseOption
WithEnsureLF sets whether CRLF and CR line endings are converted to LF. Defaults to true.
func WithState ¶
func WithState(state string) TokeniseOption
WithState sets the state to start tokenisation in. Defaults to "root".
func WithTrace ¶
func WithTrace(trace func(Trace)) TokeniseOption
WithTrace calls trace after each attempt to match a rule, including in lexers that tokenise embedded fragments.
type TokeniseOptions ¶
type TokeniseOptions struct {
// State to start tokenisation in.
State string
// Nested is true when tokenising a fragment on behalf of another lexer.
Nested bool
// EnsureLF converts CRLF and CR line endings to LF.
EnsureLF bool
// Trace, if set, is called after each attempt to match a rule.
Trace func(Trace)
}
TokeniseOptions are the resolved options for a call to Lexer.Tokenise.
Lexer implementations obtain them with NewTokeniseOptions.
func NewTokeniseOptions ¶
func NewTokeniseOptions(options ...TokeniseOption) TokeniseOptions
NewTokeniseOptions applies options to the defaults, which are the "root" state with EnsureLF enabled.
type Trace ¶
type Trace struct {
Lexer string `json:"lexer"`
State string `json:"state"`
Rule int `json:"rule"`
Pattern string `json:"pattern"`
Pos int `json:"pos"`
Length int `json:"length"`
Elapsed float64 `json:"elapsedMs"` // Elapsed time spent matching for this rule.
}
Trace records one attempt to match a rule. Length is -1 if no rule matched.
type Trilean ¶
type Trilean uint8
Trilean value for StyleEntry value inheritance.
type TypeMapping ¶
TypeMapping defines type maps for the TypeRemappingLexer.
type ValidatingEmitter ¶
type ValidatingEmitter interface {
Emitter
ValidateEmitter(rule *CompiledRule) error
}
ValidatingEmitter is an Emitter that can validate against a compiled rule.
type ValidatingMutator ¶
type ValidatingMutator interface {
Mutator
ValidateMutator(rules CompiledRules) error
}
ValidatingMutator is a Mutator that can validate itself against the compiled rules.
Validation occurs once, after all LexerMutators have been applied.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
libchromawasm
command
Package main is an experimental WASM library intended for TinyGO.
|
Package main is an experimental WASM library intended for TinyGO. |
|
svg
Package svg contains an SVG formatter.
|
Package svg contains an SVG formatter. |
|
internal
|
|
|
automerge
command
Command automerge approves CI and enables auto-merge for pull requests that only change lexer rules, style entries or lexer test data.
|
Command automerge approves CI and enables auto-merge for pull requests that only change lexer rules, style entries or lexer test data. |
|
metadatagen
command
Command metadatagen generates a Go source file containing the <config> section of every embedded lexer XML definition, so that the lexer registry can be constructed without parsing any XML at init time.
|
Command metadatagen generates a Go source file containing the <config> section of every embedded lexer XML definition, so that the lexer registry can be constructed without parsing any XML at init time. |
|
playground
Package playground implements the highlighting pipeline shared by the chromad server and the WASM playground library.
|
Package playground implements the highlighting pipeline shared by the chromad server and the WASM playground library. |
|
Package quick provides simple, no-configuration source code highlighting.
|
Package quick provides simple, no-configuration source code highlighting. |
