Documentation
¶
Overview ¶
Package fasthighlight highlights code into HTML with language-specific tokenizers that do not use regular expressions. The highlighting follows the Chroma 2.27.0 language definitions as a reference, and fixes Chroma's mistakes.
This package does the highlighting only and has no dependencies outside the standard library. To turn Markdown into HTML with highlighted code blocks, use the markdown package (github.com/toshi-kuji/fasthighlight/markdown), which adds this package to goldmark.
The HTML it writes has the form <pre class="highlight"><code>…</code></pre>, and tokens are wrapped in <span>s with short class names such as k (keyword), s (string), and nf (function name) (the naming shared by Pygments, Chroma, and Rouge). Colors are applied with CSS. If a language name is given, <pre> gets data-lang="language name" and <code> gets class="language-language name", as written in the code block (even for a language that is not registered).
Usage ¶
Register the languages to highlight by importing the language packages. Use lang/all for all languages; import only the ones you need to keep your program small.
import _ "github.com/toshi-kuji/fasthighlight/lang/all"
Highlight one piece of code:
err := fasthighlight.Highlight(w, "go", code)
Code of a language that is not registered is only escaped, without highlighting. Highlight may be called from several goroutines at the same time.
To work with the tokens yourself (to build your own HTML, count keywords, and so on), look the language up and call Language.Tokenise; WriteHTML turns tokens into the same HTML as Highlight (without data-lang and the language- class):
l := fasthighlight.LookupRegistered("go")
for _, t := range l.Tokenise(code) {
fmt.Println(t.Type, t.Value) // the type (Keyword, NameFunction, ...) and the text
}
The tokens joined together are the code, with newlines normalized to \n.
Languages ¶
LookupRegistered finds a language among the registered ones (those that can be used for highlighting now, including languages registered directly with Register). LookupSupported finds a language among the languages fasthighlight provides, whether their packages are imported or not, and tells which package to import.
When you register a language yourself, set Language.ParallelHint by the same criterion as the languages fasthighlight provides: HintHeavy for languages whose highlighting takes much work (the programming languages, including CSS), and HintLight or nothing otherwise. The markdown package uses it to decide when to highlight a document's code blocks in parallel.
Index ¶
Constants ¶
const CoalesceLimit = 8192
CoalesceLimit is the upper limit (in bytes) on the length to which tokens of the same type are merged into one. As in Chroma's Coalesce, once a merged token reaches this length, following tokens of the same type are not merged (they become a separate token). In HTML, that makes a separate <span>.
Variables ¶
This section is empty.
Functions ¶
func Highlight ¶
Highlight turns one code block into HTML. lang is the code block's language name; if it is not empty, it is put in the <pre> data-lang and the <code> class (language-lang). A language that is not registered is written as Text without highlighting (only escaped). Highlight may be called from several goroutines at the same time: each language prepares its tables once, on first use, and the registry of languages is safe for concurrent use.
func IsPlainText ¶
IsPlainText reports whether a code block's language name marks it as plain text on purpose: the name or an alias of Chroma's plaintext lexer (plaintext, text, plain, no-highlight), in any case. Such a block is not highlighted, like any language that is not registered, but it is not missing a language, so markdown.Scan and fhl do not report it.
func NormalizeNewlines ¶
NormalizeNewlines turns \r\n and \r into \n (the same as Chroma's EnsureLF). If there is no \r, it returns s as is.
Types ¶
type Language ¶
type Language struct {
// Name is the name of the language. It is the same as name in the Chroma language definition (e.g. "TypeScript").
Name string
// Aliases are the names accepted as a code block's language name. They are the same as Chroma's alias.
// The lower-cased Name is also accepted automatically.
Aliases []string
// Filenames are file name patterns (e.g. "*.ts"). They are the same as Chroma's filename.
// When a language name is in neither the names nor the aliases, it is matched as an extension (e.g. "mts")
// or as a file name, as in Chroma.
Filenames []string
// EnsureNewline is Chroma's ensure_nl. If true, input that does not end with a newline gets one appended
// before it is split. As in Chroma, the appended newline stays in the output only when it is included
// in a token that started before it (e.g. "// c" becomes "// c\n", but no newline follows "x = 1").
EnsureNewline bool
// Package is the import path of the package that registers this language. Only languages provided by
// fasthighlight have it.
Package string
// ParallelHint tells how much work highlighting this language takes, which decides how few code blocks
// are enough to highlight a document in parallel (see the markdown package). It is HintHeavy,
// HintLight, or HintDefault (not specified).
//
// A language you register yourself should be chosen by the same criterion as the languages
// fasthighlight provides. Among those, the heavy ones are the programming languages (Bash, C, C#, C++,
// CSS, Go, Java, JavaScript, Kotlin, PHP, PowerShell, Python, R, react, Ruby, Rust, SCSS, Swift and
// TypeScript) and the languages mostly read as Bash (Bash Session, Docker and Makefile); the others are
// not specified, which is
// treated like HintLight. When in doubt, leave it unspecified or use HintLight (going parallel is less
// likely to make things slower).
ParallelHint ParallelHint
// Lex splits text into tokens. It is called from Tokenise.
// text is the input with a newline appended if EnsureNewline is set. end is the length before the
// append, and Lex must not start a new token (one match of a Chroma rule) at or after end. A match that
// started before end may include the appended newline past end (as in Chroma). The concatenated
// tokens are the part of text from its start (of length end or len(text)).
Lex func(text string, end int) []Token
// Prepare builds things such as keyword tables (optional). It is called once, before the first
// Tokenise. So that only the languages in use are prepared, the tables are built here, not at import time.
Prepare func()
// contains filtered or unexported fields
}
Language is the tokenizer for one language.
A language is registered with Register when its package is imported (the same mechanism as database/sql drivers in Go). To use all languages, import github.com/toshi-kuji/fasthighlight/lang/all.
The information about the languages fasthighlight provides (names and so on) is in the built-in catalog (Builtins). A language package receives its information with Builtin, adds Lex and Prepare, and registers it.
func Builtin ¶
Builtin returns the information of a language fasthighlight provides. A language package uses it to Register with Lex and Prepare added. It panics if the name is not in the list.
func Builtins ¶
func Builtins() []*Language
Builtins returns the information of all the languages fasthighlight provides, in name order. It includes languages that are not imported.
func Languages ¶
func Languages() []*Language
Languages returns the registered languages in name order.
func LookupRegistered ¶
LookupRegistered looks up a code block's language name among the languages that can be used for highlighting now: the registered ones, that is, those of the imported language packages and those registered directly with Register. It searches in the same order as Chroma's lexers.Get (names and aliases, extension, file name). It returns nil if not found.
func LookupSupported ¶
LookupSupported looks up a code block's language name among the languages fasthighlight provides (the built-in catalog, see Builtins), whether their packages are imported or not. Languages registered directly with Register are not included. It searches the same way as LookupRegistered and returns nil if not found.
The returned language's Package is the package to import to highlight it. If that package is not imported, the language is not registered and cannot be used for highlighting (it has no Lex).
type ParallelHint ¶
type ParallelHint int
ParallelHint tells how much work highlighting a language takes. It decides how few code blocks are enough to highlight a document in parallel.
const ( // HintDefault means the hint is not specified (the zero value). Parallel highlighting treats it like // HintLight. It is kept apart from HintLight so that an unspecified hint can be told apart from a // chosen one. HintDefault ParallelHint = iota // HintHeavy means highlighting takes much work, so going parallel pays off with fewer code blocks. HintHeavy // HintLight means highlighting takes little work, so going parallel pays off only with more code blocks. HintLight )
type Token ¶
Token is a part of the input and its type. Value is a substring of the input and is not copied.
type TokenType ¶
type TokenType int
TokenType is the type of a token.
Types form major categories in steps of 1000 and subcategories in steps of 100. For example, strings (LiteralString) are 3100 to 3199, which belong to the major category Literal (3000 to 3999).
const ( Background TokenType = -1 - iota PreWrapper Line LineNumbers LineNumbersTable LineHighlight LineTable LineTableTD LineLink CodeLine Error // input that could not be made into a token Other None Ignore EOFType TokenType = 0 )
Types of output parts (negative values).
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 )
Numbers.
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 (diffs, headings, and so on).
func (TokenType) Class ¶
Class returns the CSS class name of the type. For a type not in the table, ok is false.
func (TokenType) Parent ¶
Parent returns the next category up: for a subcategory member, the start of the subcategory; for the start of a subcategory, the start of the major category; for the start of a major category, 0.
func (TokenType) SubCategory ¶
SubCategory returns the start of the subcategory.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
bench
command
|
|
|
fhl
command
fhl is a command that turns Markdown files into HTML with highlighted code blocks.
|
fhl is a command that turns Markdown files into HTML with highlighted code blocks. |
|
prof
command
|
|
|
internal
|
|
|
bash
Package bash is the Bash tokenizer.
|
Package bash is the Bash tokenizer. |
|
c
Package c is the tokenizer for C and C++.
|
Package c is the tokenizer for C and C++. |
|
csharp
Package csharp is the C# tokenizer.
|
Package csharp is the C# tokenizer. |
|
css
Package css is the CSS tokenizer.
|
Package css is the CSS tokenizer. |
|
golang
Package golang is the Go tokenizer.
|
Package golang is the Go tokenizer. |
|
html
Package html is the HTML tokenizer.
|
Package html is the HTML tokenizer. |
|
http
Package http is the HTTP tokenizer.
|
Package http is the HTTP tokenizer. |
|
ini
Package ini is the INI tokenizer.
|
Package ini is the INI tokenizer. |
|
java
Package java is the Java tokenizer.
|
Package java is the Java tokenizer. |
|
js
Package js is the JavaScript tokenizer.
|
Package js is the JavaScript tokenizer. |
|
json
Package json is the JSON tokenizer.
|
Package json is the JSON tokenizer. |
|
kotlin
Package kotlin is the Kotlin tokenizer.
|
Package kotlin is the Kotlin tokenizer. |
|
lexkit
Package lexkit provides the shared parts of tokenizers that reproduce Chroma's regular-expression rules by hand.
|
Package lexkit provides the shared parts of tokenizers that reproduce Chroma's regular-expression rules by hand. |
|
markdown
Package markdown is the Markdown tokenizer.
|
Package markdown is the Markdown tokenizer. |
|
php
Package php is the PHP tokenizer.
|
Package php is the PHP tokenizer. |
|
python
Package python is the Python tokenizer.
|
Package python is the Python tokenizer. |
|
r
Package r is the R tokenizer.
|
Package r is the R tokenizer. |
|
ruby
Package ruby is the Ruby tokenizer.
|
Package ruby is the Ruby tokenizer. |
|
rust
Package rust is the tokenizer of Rust.
|
Package rust is the tokenizer of Rust. |
|
swift
Package swift is the Swift tokenizer.
|
Package swift is the Swift tokenizer. |
|
testcases
Package testcases holds the inputs shared by the tests of the main package and the comparison tests in compat/.
|
Package testcases holds the inputs shared by the tests of the main package and the comparison tests in compat/. |
|
typescript
Package typescript is the TypeScript tokenizer.
|
Package typescript is the TypeScript tokenizer. |
|
xml
Package xml is the XML tokenizer.
|
Package xml is the XML tokenizer. |
|
lang
|
|
|
all
Package all registers every language that fasthighlight supports.
|
Package all registers every language that fasthighlight supports. |
|
bash
Package bash registers Bash (sh, zsh, and other shells).
|
Package bash registers Bash (sh, zsh, and other shells). |
|
bashsession
Package bashsession registers Bash Session (a shell session: prompts with commands, and their output).
|
Package bashsession registers Bash Session (a shell session: prompts with commands, and their output). |
|
c
Package c registers C.
|
Package c registers C. |
|
cpp
Package cpp registers C++.
|
Package cpp registers C++. |
|
csharp
Package csharp registers C#.
|
Package csharp registers C#. |
|
css
Package css registers CSS.
|
Package css registers CSS. |
|
diff
Package diff registers diff.
|
Package diff registers diff. |
|
docker
Package docker registers Docker (Dockerfile and Containerfile).
|
Package docker registers Docker (Dockerfile and Containerfile). |
|
golang
Package golang registers Go.
|
Package golang registers Go. |
|
graphql
Package graphql registers GraphQL.
|
Package graphql registers GraphQL. |
|
html
Package html registers HTML.
|
Package html registers HTML. |
|
http
Package http registers HTTP.
|
Package http registers HTTP. |
|
ini
Package ini registers INI.
|
Package ini registers INI. |
|
java
Package java registers Java.
|
Package java registers Java. |
|
javascript
Package javascript registers JavaScript.
|
Package javascript registers JavaScript. |
|
json
Package json registers JSON.
|
Package json registers JSON. |
|
kotlin
Package kotlin registers Kotlin.
|
Package kotlin registers Kotlin. |
|
makefile
Package makefile registers Makefile (make, BSD make, and justfiles).
|
Package makefile registers Makefile (make, BSD make, and justfiles). |
|
markdown
Package markdown registers Markdown.
|
Package markdown registers Markdown. |
|
php
Package php registers PHP.
|
Package php registers PHP. |
|
powershell
Package powershell registers PowerShell.
|
Package powershell registers PowerShell. |
|
protobuf
Package protobuf registers Protocol Buffer.
|
Package protobuf registers Protocol Buffer. |
|
python
Package python registers Python.
|
Package python registers Python. |
|
r
Package r registers R.
|
Package r registers R. |
|
react
Package react registers react (JavaScript with JSX).
|
Package react registers react (JavaScript with JSX). |
|
ruby
Package ruby registers Ruby.
|
Package ruby registers Ruby. |
|
rust
Package rust registers Rust.
|
Package rust registers Rust. |
|
scss
Package scss registers SCSS.
|
Package scss registers SCSS. |
|
sql
Package sql registers SQL.
|
Package sql registers SQL. |
|
swift
Package swift registers Swift.
|
Package swift registers Swift. |
|
toml
Package toml registers TOML.
|
Package toml registers TOML. |
|
typescript
Package typescript registers TypeScript.
|
Package typescript registers TypeScript. |
|
xml
Package xml registers XML.
|
Package xml registers XML. |
|
yaml
Package yaml registers YAML.
|
Package yaml registers YAML. |
|
Package markdown turns Markdown into HTML with highlighted code blocks, by adding fasthighlight to goldmark (github.com/yuin/goldmark).
|
Package markdown turns Markdown into HTML with highlighted code blocks, by adding fasthighlight to goldmark (github.com/yuin/goldmark). |
|
website
|
|
|
demo/wasm
command
Command wasm is the WebAssembly side of the demo page (website/demo).
|
Command wasm is the WebAssembly side of the demo page (website/demo). |
