• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

chroma-0.6.3/H03-May-2022-

formatters/H30-Aug-2019-

lexers/H30-Aug-2019-

styles/H30-Aug-2019-

.gitignoreH A D30-Aug-2019316

.golangci.ymlH A D30-Aug-20191.1 KiB

.goreleaser.ymlH A D30-Aug-2019648

.travis.ymlH A D30-Aug-2019275

COPYINGH A D30-Aug-20191 KiB

README.mdH A D30-Aug-20199.4 KiB

coalesce.goH A D30-Aug-2019780

colour.goH A D30-Aug-20194.5 KiB

delegate.goH A D30-Aug-20193.2 KiB

doc.goH A D30-Aug-2019326

formatter.goH A D30-Aug-20191 KiB

go.modH A D30-Aug-2019588

go.sumH A D30-Aug-20192.5 KiB

iterator.goH A D30-Aug-20191.7 KiB

lexer.goH A D30-Aug-20192.7 KiB

mutators.goH A D30-Aug-20193.3 KiB

regexp.goH A D30-Aug-201910.8 KiB

remap.goH A D30-Aug-20191.7 KiB

style.goH A D30-Aug-20197.9 KiB

tokentype_string.goH A D30-Aug-20194.7 KiB

types.goH A D30-Aug-20197 KiB

README.md

1# Chroma — A general purpose syntax highlighter in pure Go [![Golang Documentation](https://godoc.org/github.com/alecthomas/chroma?status.svg)](https://godoc.org/github.com/alecthomas/chroma) [![Build Status](https://travis-ci.org/alecthomas/chroma.svg)](https://travis-ci.org/alecthomas/chroma) [![Gitter chat](https://badges.gitter.im/alecthomas.svg)](https://gitter.im/alecthomas/Lobby)
2
3> **NOTE:** As Chroma has just been released, its API is still in flux. That said, the high-level interface should not change significantly.
4
5Chroma takes source code and other structured text and converts it into syntax
6highlighted HTML, ANSI-coloured text, etc.
7
8Chroma is based heavily on [Pygments](http://pygments.org/), and includes
9translators for Pygments lexers and styles.
10
11## Table of Contents
12
13<!-- MarkdownTOC -->
14
151. [Supported languages](#supported-languages)
161. [Using the library](#using-the-library)
17    1. [Quick start](#quick-start)
18    1. [Identifying the language](#identifying-the-language)
19    1. [Formatting the output](#formatting-the-output)
20    1. [The HTML formatter](#the-html-formatter)
211. [More detail](#more-detail)
22    1. [Lexers](#lexers)
23    1. [Formatters](#formatters)
24    1. [Styles](#styles)
251. [Command-line interface](#command-line-interface)
261. [What's missing compared to Pygments?](#whats-missing-compared-to-pygments)
27
28<!-- /MarkdownTOC -->
29
30## Supported languages
31
32Prefix | Language
33:----: | --------
34A | ABNF, ActionScript, ActionScript 3, Ada, Angular2, ANTLR, ApacheConf, APL, AppleScript, Arduino, Awk
35B | Ballerina, Base Makefile, Bash, Batchfile, BlitzBasic, BNF, Brainfuck
36C | C, C#, C++, Cassandra CQL, CFEngine3, cfstatement/ColdFusion, CMake, COBOL, CSS, Cap'n Proto, Ceylon, ChaiScript, Cheetah, Clojure, CoffeeScript, Common Lisp, Coq, Crystal, Cython
37D | Dart, Diff, Django/Jinja, Docker, DTD
38E | EBNF, Elixir, Elm, EmacsLisp, Erlang
39F | Factor, Fish, Forth, Fortran, FSharp
40G | GAS, GDScript, GLSL, Genshi, Genshi HTML, Genshi Text, Gnuplot, Go, Go HTML Template, Go Text Template, GraphQL, Groovy
41H | Handlebars, Haskell, Haxe, Hexdump, HTML, HTTP, Hy
42I | Idris, INI, Io
43J | Java, JavaScript, JSON, Jsx, Julia, Jungle
44K | Kotlin
45L | Lighttpd configuration file, LLVM, Lua
46M | Mako, Markdown, Mason, Mathematica, MiniZinc, Modula-2, MonkeyC, MorrowindScript, Myghty, MySQL
47N | NASM, Newspeak, Nginx configuration file, Nim, Nix
48O | Objective-C, OCaml, Octave, OpenSCAD, Org Mode
49P | PacmanConf, Perl, PHP, Pig, PkgConfig, Plaintext, PL/pgSQL, PostgreSQL SQL dialect, PostScript, POVRay, PowerShell, Prolog, Protocol Buffer, Puppet, Python, Python 3
50Q | QBasic
51R | R, Racket, Ragel, reg, reStructuredText, Rexx, Ruby, Rust
52S | Sass, Scala, Scheme, Scilab, SCSS, Smalltalk, Smarty, Snobol, Solidity, SPARQL, SQL, SquidConf, Swift, systemd, Systemverilog
53T | TASM, Tcl, Tcsh, Termcap, Terminfo, Terraform, TeX, Thrift, TOML, TradingView, Transact-SQL, Turtle, Twig, TypeScript, TypoScript, TypoScriptCssData, TypoScriptHtmlData
54V | verilog, VHDL, VimL
55W | WDTE
56X | XML, Xorg
57Y | YAML
58
59_I will attempt to keep this section up to date, but an authoritative list can be
60displayed with `chroma --list`._
61
62## Using the library
63
64Chroma, like Pygments, has the concepts of
65[lexers](https://github.com/alecthomas/chroma/tree/master/lexers),
66[formatters](https://github.com/alecthomas/chroma/tree/master/formatters) and
67[styles](https://github.com/alecthomas/chroma/tree/master/styles).
68
69Lexers convert source text into a stream of tokens, styles specify how token
70types are mapped to colours, and formatters convert tokens and styles into
71formatted output.
72
73A package exists for each of these, containing a global `Registry` variable
74with all of the registered implementations. There are also helper functions
75for using the registry in each package, such as looking up lexers by name or
76matching filenames, etc.
77
78In all cases, if a lexer, formatter or style can not be determined, `nil` will
79be returned. In this situation you may want to default to the `Fallback`
80value in each respective package, which provides sane defaults.
81
82### Quick start
83
84A convenience function exists that can be used to simply format some source
85text, without any effort:
86
87```go
88err := quick.Highlight(os.Stdout, someSourceCode, "go", "html", "monokai")
89```
90
91### Identifying the language
92
93To highlight code, you'll first have to identify what language the code is
94written in. There are three primary ways to do that:
95
961. Detect the language from its filename.
97
98    ```go
99    lexer := lexers.Match("foo.go")
100    ```
101
1023. Explicitly specify the language by its Chroma syntax ID (a full list is available from `lexers.Names()`).
103
104    ```go
105    lexer := lexers.Get("go")
106    ```
107
1083. Detect the language from its content.
109
110    ```go
111    lexer := lexers.Analyse("package main\n\nfunc main()\n{\n}\n")
112    ```
113
114In all cases, `nil` will be returned if the language can not be identified.
115
116```go
117if lexer == nil {
118  lexer = lexers.Fallback
119}
120```
121
122At this point, it should be noted that some lexers can be extremely chatty. To
123mitigate this, you can use the coalescing lexer to coalesce runs of identical
124token types into a single token:
125
126```go
127lexer = chroma.Coalesce(lexer)
128```
129
130### Formatting the output
131
132Once a language is identified you will need to pick a formatter and a style (theme).
133
134```go
135style := styles.Get("swapoff")
136if style == nil {
137  style = styles.Fallback
138}
139formatter := formatters.Get("html")
140if formatter == nil {
141  formatter = formatters.Fallback
142}
143```
144
145Then obtain an iterator over the tokens:
146
147```go
148contents, err := ioutil.ReadAll(r)
149iterator, err := lexer.Tokenise(nil, string(contents))
150```
151
152And finally, format the tokens from the iterator:
153
154```go
155err := formatter.Format(w, style, iterator)
156```
157
158### The HTML formatter
159
160By default the `html` registered formatter generates standalone HTML with
161embedded CSS. More flexibility is available through the `formatters/html` package.
162
163Firstly, the output generated by the formatter can be customised with the
164following constructor options:
165
166- `Standalone()` - generate standalone HTML with embedded CSS.
167- `WithClasses()` - use classes rather than inlined style attributes.
168- `ClassPrefix(prefix)` - prefix each generated CSS class.
169- `TabWidth(width)` - Set the rendered tab width, in characters.
170- `WithLineNumbers()` - Render line numbers (style with `LineNumbers`).
171- `HighlightLines(ranges)` - Highlight lines in these ranges (style with `LineHighlight`).
172- `LineNumbersInTable()` - Use a table for formatting line numbers and code, rather than spans.
173
174If `WithClasses()` is used, the corresponding CSS can be obtained from the formatter with:
175
176```go
177formatter := html.New(html.WithClasses())
178err := formatter.WriteCSS(w, style)
179```
180
181## More detail
182
183### Lexers
184
185See the [Pygments documentation](http://pygments.org/docs/lexerdevelopment/)
186for details on implementing lexers. Most concepts apply directly to Chroma,
187but see existing lexer implementations for real examples.
188
189In many cases lexers can be automatically converted directly from Pygments by
190using the included Python 3 script `pygments2chroma.py`. I use something like
191the following:
192
193```sh
194python3 ~/Projects/chroma/_tools/pygments2chroma.py \
195  pygments.lexers.jvm.KotlinLexer \
196  > ~/Projects/chroma/lexers/kotlin.go \
197  && gofmt -s -w ~/Projects/chroma/lexers/*.go
198```
199
200See notes in [pygments-lexers.go](https://github.com/alecthomas/chroma/blob/master/pygments-lexers.txt)
201for a list of lexers, and notes on some of the issues importing them.
202
203### Formatters
204
205Chroma supports HTML output, as well as terminal output in 8 colour, 256 colour, and true-colour.
206
207A `noop` formatter is included that outputs the token text only, and a `tokens`
208formatter outputs raw tokens. The latter is useful for debugging lexers.
209
210### Styles
211
212Chroma styles use the [same syntax](http://pygments.org/docs/styles/) as Pygments.
213
214All Pygments styles have been converted to Chroma using the `_tools/style.py` script.
215
216When you work with one of [Chroma's styles](https://github.com/alecthomas/chroma/tree/master/styles), know that the `chroma.Background` token type provides the default style for tokens. It does so by defining a foreground color and background color.
217
218For example, this gives each token name not defined in the style a default color of `#f8f8f8` and uses `#000000` for the highlighted code block's background:
219
220~~~go
221chroma.Background: "#f8f8f2 bg:#000000",
222~~~
223
224Also, token types in a style file are hierarchical. For instance, when `CommentSpecial` is not defined, Chroma uses the token style from `Comment`. So when several comment tokens use the same color, you'll only need to define `Comment` and override the one that has a different color.
225
226For a quick overview of the available styles and how they look, check out the [Chroma Style Gallery](https://xyproto.github.io/splash/docs/).
227
228## Command-line interface
229
230A command-line interface to Chroma is included. It can be installed with:
231
232```sh
233go get -u github.com/alecthomas/chroma/cmd/chroma
234```
235
236## What's missing compared to Pygments?
237
238- Quite a few lexers, for various reasons (pull-requests welcome):
239    - Pygments lexers for complex languages often include custom code to
240      handle certain aspects, such as Perl6's ability to nest code inside
241      regular expressions. These require time and effort to convert.
242    - I mostly only converted languages I had heard of, to reduce the porting cost.
243- Some more esoteric features of Pygments are omitted for simplicity.
244- Though the Chroma API supports content detection, very few languages support them.
245  I have plans to implement a statistical analyser at some point, but not enough time.
246