{"id":13393852,"url":"https://github.com/alecthomas/chroma","last_synced_at":"2025-09-09T20:48:25.548Z","repository":{"id":37383017,"uuid":"93619165","full_name":"alecthomas/chroma","owner":"alecthomas","description":"A general purpose syntax highlighter in pure Go ","archived":false,"fork":false,"pushed_at":"2025-05-05T01:37:55.000Z","size":14079,"stargazers_count":4573,"open_issues_count":110,"forks_count":417,"subscribers_count":29,"default_branch":"master","last_synced_at":"2025-05-05T14:29:08.571Z","etag":null,"topics":["console","go","golang","highlighter","highlighting","html","library","syntax","tool"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alecthomas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"COPYING","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":["alecthomas"]}},"created_at":"2017-06-07T09:47:08.000Z","updated_at":"2025-05-05T11:53:53.000Z","dependencies_parsed_at":"2024-01-15T01:43:59.956Z","dependency_job_id":"9a55ae9e-40b2-4341-b8f5-31002093fc06","html_url":"https://github.com/alecthomas/chroma","commit_stats":{"total_commits":718,"total_committers":231,"mean_commits":"3.1082251082251084","dds":0.6545961002785515,"last_synced_commit":"810464a509a74cb8f65940a28734f3b7e4cb94a2"},"previous_names":[],"tags_count":58,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fchroma","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fchroma/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fchroma/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alecthomas%2Fchroma/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alecthomas","download_url":"https://codeload.github.com/alecthomas/chroma/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253776504,"owners_count":21962499,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["console","go","golang","highlighter","highlighting","html","library","syntax","tool"],"created_at":"2024-07-30T17:01:01.357Z","updated_at":"2025-09-09T20:48:25.531Z","avatar_url":"https://github.com/alecthomas.png","language":"Go","readme":"![Chroma](chroma.jpg)\n\n# A general purpose syntax highlighter in pure Go\n\n[![Go Reference](https://pkg.go.dev/badge/github.com/alecthomas/chroma/v2.svg)](https://pkg.go.dev/github.com/alecthomas/chroma/v2) [![CI](https://github.com/alecthomas/chroma/actions/workflows/ci.yml/badge.svg)](https://github.com/alecthomas/chroma/actions/workflows/ci.yml) [![Slack chat](https://img.shields.io/static/v1?logo=slack\u0026style=flat\u0026label=slack\u0026color=green\u0026message=gophers)](https://invite.slack.golangbridge.org/)\n\n\nChroma takes source code and other structured text and converts it into syntax\nhighlighted HTML, ANSI-coloured text, etc.\n\nChroma is based heavily on [Pygments](http://pygments.org/), and includes\ntranslators for Pygments lexers and styles.\n\n## Table of Contents\n\n\u003c!-- TOC --\u003e\n\n1. [Supported languages](#supported-languages)\n2. [Try it](#try-it)\n3. [Using the library](#using-the-library)\n   1. [Quick start](#quick-start)\n   2. [Identifying the language](#identifying-the-language)\n   3. [Formatting the output](#formatting-the-output)\n   4. [The HTML formatter](#the-html-formatter)\n4. [More detail](#more-detail)\n   1. [Lexers](#lexers)\n   2. [Formatters](#formatters)\n   3. [Styles](#styles)\n5. [Command-line interface](#command-line-interface)\n6. [Testing lexers](#testing-lexers)\n7. [What's missing compared to Pygments?](#whats-missing-compared-to-pygments)\n\n\u003c!-- /TOC --\u003e\n\n## Supported languages\n\n| Prefix | Language\n| :----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|   A    | ABAP, ABNF, ActionScript, ActionScript 3, Ada, Agda, AL, Alloy, Angular2, ANTLR, ApacheConf, APL, AppleScript, ArangoDB AQL, Arduino, ArmAsm, ATL, AutoHotkey, AutoIt, Awk\n|   B    | Ballerina, Bash, Bash Session, Batchfile, Beef, BibTeX, Bicep, BlitzBasic, BNF, BQN, Brainfuck\n|   C    | C, C#, C++, Caddyfile, Caddyfile Directives, Cap'n Proto, Cassandra CQL, Ceylon, CFEngine3, cfstatement, ChaiScript, Chapel, Cheetah, Clojure, CMake, COBOL, CoffeeScript, Common Lisp, Coq, Core, Crystal, CSS, CSV, CUE, Cython\n|   D    | D, Dart, Dax, Desktop file, Diff, Django/Jinja, dns, Docker, DTD, Dylan\n|   E    | EBNF, Elixir, Elm, EmacsLisp, Erlang\n|   F    | Factor, Fennel, Fish, Forth, Fortran, FortranFixed, FSharp\n|   G    | GAS, GDScript, GDScript3, Gemtext, Genshi, Genshi HTML, Genshi Text, Gherkin, Gleam, GLSL, Gnuplot, Go, Go HTML Template, Go Template, Go Text Template, GraphQL, Groff, Groovy\n|   H    | Handlebars, Hare, Haskell, Haxe, HCL, Hexdump, HLB, HLSL, HolyC, HTML, HTTP, Hy\n|   I    | Idris, Igor, INI, Io, ISCdhcpd\n|   J    | J, Janet, Java, JavaScript, JSON, JSONata, Jsonnet, Julia, Jungle\n|   K    | Kotlin\n|   L    | Lean4, Lighttpd configuration file, LLVM, lox, Lua\n|   M    | Makefile, Mako, markdown, Mason, Materialize SQL dialect, Mathematica, Matlab, MCFunction, Meson, Metal, MiniZinc, MLIR, Modula-2, Mojo, MonkeyC, MoonScript, MorrowindScript, Myghty, MySQL\n|   N    | NASM, Natural, NDISASM, Newspeak, Nginx configuration file, Nim, Nix, NSIS, Nu\n|   O    | Objective-C, ObjectPascal, OCaml, Octave, Odin, OnesEnterprise, OpenEdge ABL, OpenSCAD, Org Mode\n|   P    | PacmanConf, Perl, PHP, PHTML, Pig, PkgConfig, PL/pgSQL, plaintext, Plutus Core, Pony, PostgreSQL SQL dialect, PostScript, POVRay, PowerQuery, PowerShell, Prolog, Promela, PromQL, properties, Protocol Buffer, PRQL, PSL, Puppet, Python, Python 2\n|   Q    | QBasic, QML\n|   R    | R, Racket, Ragel, Raku, react, ReasonML, reg, Rego, reStructuredText, Rexx, RPGLE, RPMSpec, Ruby, Rust\n|   S    | SAS, Sass, Scala, Scheme, Scilab, SCSS, Sed, Sieve, Smali, Smalltalk, Smarty, SNBT, Snobol, Solidity, SourcePawn, SPARQL, SQL, SquidConf, Standard ML, stas, Stylus, Svelte, Swift, SYSTEMD, systemverilog\n|   T    | TableGen, Tal, TASM, Tcl, Tcsh, Termcap, Terminfo, Terraform, TeX, Thrift, TOML, TradingView, Transact-SQL, Turing, Turtle, Twig, TypeScript, TypoScript, TypoScriptCssData, TypoScriptHtmlData, Typst\n|   U    | ucode\n|   V    | V, V shell, Vala, VB.net, verilog, VHDL, VHS, VimL, vue\n|   W    | WDTE, WebGPU Shading Language, WebVTT, Whiley\n|   X    | XML, Xorg\n|   Y    | YAML, YANG\n|   Z    | Z80 Assembly, Zed, Zig\n\n_I will attempt to keep this section up to date, but an authoritative list can be\ndisplayed with `chroma --list`._\n\n## Try it\n\nTry out various languages and styles on the [Chroma Playground](https://swapoff.org/chroma/playground/).\n\n## Using the library\n\nThis is version 2 of Chroma, use the import path:\n\n```go\nimport \"github.com/alecthomas/chroma/v2\"\n```\n\nChroma, like Pygments, has the concepts of\n[lexers](https://github.com/alecthomas/chroma/tree/master/lexers),\n[formatters](https://github.com/alecthomas/chroma/tree/master/formatters) and\n[styles](https://github.com/alecthomas/chroma/tree/master/styles).\n\nLexers convert source text into a stream of tokens, styles specify how token\ntypes are mapped to colours, and formatters convert tokens and styles into\nformatted output.\n\nA package exists for each of these, containing a global `Registry` variable\nwith all of the registered implementations. There are also helper functions\nfor using the registry in each package, such as looking up lexers by name or\nmatching filenames, etc.\n\nIn all cases, if a lexer, formatter or style can not be determined, `nil` will\nbe returned. In this situation you may want to default to the `Fallback`\nvalue in each respective package, which provides sane defaults.\n\n### Quick start\n\nA convenience function exists that can be used to simply format some source\ntext, without any effort:\n\n```go\nerr := quick.Highlight(os.Stdout, someSourceCode, \"go\", \"html\", \"monokai\")\n```\n\n### Identifying the language\n\nTo highlight code, you'll first have to identify what language the code is\nwritten in. There are three primary ways to do that:\n\n1. Detect the language from its filename.\n\n   ```go\n   lexer := lexers.Match(\"foo.go\")\n   ```\n\n2. Explicitly specify the language by its Chroma syntax ID (a full list is available from `lexers.Names()`).\n\n   ```go\n   lexer := lexers.Get(\"go\")\n   ```\n\n3. Detect the language from its content.\n\n   ```go\n   lexer := lexers.Analyse(\"package main\\n\\nfunc main()\\n{\\n}\\n\")\n   ```\n\nIn all cases, `nil` will be returned if the language can not be identified.\n\n```go\nif lexer == nil {\n  lexer = lexers.Fallback\n}\n```\n\nAt this point, it should be noted that some lexers can be extremely chatty. To\nmitigate this, you can use the coalescing lexer to coalesce runs of identical\ntoken types into a single token:\n\n```go\nlexer = chroma.Coalesce(lexer)\n```\n\n### Formatting the output\n\nOnce a language is identified you will need to pick a formatter and a style (theme).\n\n```go\nstyle := styles.Get(\"swapoff\")\nif style == nil {\n  style = styles.Fallback\n}\nformatter := formatters.Get(\"html\")\nif formatter == nil {\n  formatter = formatters.Fallback\n}\n```\n\nThen obtain an iterator over the tokens:\n\n```go\ncontents, err := ioutil.ReadAll(r)\niterator, err := lexer.Tokenise(nil, string(contents))\n```\n\nAnd finally, format the tokens from the iterator:\n\n```go\nerr := formatter.Format(w, style, iterator)\n```\n\n### The HTML formatter\n\nBy default the `html` registered formatter generates standalone HTML with\nembedded CSS. More flexibility is available through the `formatters/html` package.\n\nFirstly, the output generated by the formatter can be customised with the\nfollowing constructor options:\n\n- `Standalone()` - generate standalone HTML with embedded CSS.\n- `WithClasses()` - use classes rather than inlined style attributes.\n- `ClassPrefix(prefix)` - prefix each generated CSS class.\n- `TabWidth(width)` - Set the rendered tab width, in characters.\n- `WithLineNumbers()` - Render line numbers (style with `LineNumbers`).\n- `WithLinkableLineNumbers()` - Make the line numbers linkable and be a link to themselves.\n- `HighlightLines(ranges)` - Highlight lines in these ranges (style with `LineHighlight`).\n- `LineNumbersInTable()` - Use a table for formatting line numbers and code, rather than spans.\n\nIf `WithClasses()` is used, the corresponding CSS can be obtained from the formatter with:\n\n```go\nformatter := html.New(html.WithClasses(true))\nerr := formatter.WriteCSS(w, style)\n```\n\n## More detail\n\n### Lexers\n\nSee the [Pygments documentation](http://pygments.org/docs/lexerdevelopment/)\nfor details on implementing lexers. Most concepts apply directly to Chroma,\nbut see existing lexer implementations for real examples.\n\nIn many cases lexers can be automatically converted directly from Pygments by\nusing the included Python 3 script `pygments2chroma_xml.py`. I use something like\nthe following:\n\n```sh\npython3 _tools/pygments2chroma_xml.py \\\n  pygments.lexers.jvm.KotlinLexer \\\n  \u003e lexers/embedded/kotlin.xml\n```\n\nA list of all lexers available in Pygments can be found in [pygments-lexers.txt](https://github.com/alecthomas/chroma/blob/master/pygments-lexers.txt).\n\n### Formatters\n\nChroma supports HTML output, as well as terminal output in 8 colour, 256 colour, and true-colour.\n\nA `noop` formatter is included that outputs the token text only, and a `tokens`\nformatter outputs raw tokens. The latter is useful for debugging lexers.\n\n### Styles\n\nChroma styles are defined in XML. The style entries use the\n[same syntax](http://pygments.org/docs/styles/) as Pygments.\n\nAll Pygments styles have been converted to Chroma using the `_tools/style.py`\nscript.\n\nWhen you work with one of [Chroma's styles](https://github.com/alecthomas/chroma/tree/master/styles),\nknow that the `Background` token type provides the default style for tokens. It does so\nby defining a foreground color and background color.\n\nFor example, this gives each token name not defined in the style a default color\nof `#f8f8f8` and uses `#000000` for the highlighted code block's background:\n\n```xml\n\u003centry type=\"Background\" style=\"#f8f8f2 bg:#000000\"/\u003e\n```\n\nAlso, 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.\n\nFor a quick overview of the available styles and how they look, check out the [Chroma Style Gallery](https://xyproto.github.io/splash/docs/).\n\n## Command-line interface\n\nA command-line interface to Chroma is included.\n\nBinaries are available to install from [the releases page](https://github.com/alecthomas/chroma/releases).\n\nThe CLI can be used as a preprocessor to colorise output of `less(1)`,\nsee documentation for the `LESSOPEN` environment variable.\n\nThe `--fail` flag can be used to suppress output and return with exit status\n1 to facilitate falling back to some other preprocessor in case chroma\ndoes not resolve a specific lexer to use for the given file. For example:\n\n```shell\nexport LESSOPEN='| p() { chroma --fail \"$1\" || cat \"$1\"; }; p \"%s\"'\n```\n\nReplace `cat` with your favourite fallback preprocessor.\n\nWhen invoked as `.lessfilter`, the `--fail` flag is automatically turned\non under the hood for easy integration with [lesspipe shipping with\nDebian and derivatives](https://manpages.debian.org/lesspipe#USER_DEFINED_FILTERS);\nfor that setup the `chroma` executable can be just symlinked to `~/.lessfilter`.\n\n## Projects using Chroma\n\n* [`moor`](https://github.com/walles/moor) is a full-blown pager that colorizes\n  its input using Chroma\n* [Hugo](https://gohugo.io/) is a static site generator that [uses Chroma for syntax\n  highlighting code examples](https://gohugo.io/content-management/syntax-highlighting/)\n\n## Testing lexers\n\nIf you edit some lexers and want to try it, open a shell in `cmd/chromad` and run:\n\n```shell\ngo run . --csrf-key=securekey\n```\n\nA Link will be printed. Open it in your Browser. Now you can test on the Playground with your local changes.\n\nIf you want to run the tests and the lexers, open a shell in the root directory and run:\n\n```shell\ngo test ./lexers\n```\n\nWhen updating or adding a lexer, please add tests. See [lexers/README.md](lexers/README.md) for more.\n\n## What's missing compared to Pygments?\n\n- Quite a few lexers, for various reasons (pull-requests welcome):\n  - Pygments lexers for complex languages often include custom code to\n    handle certain aspects, such as Raku's ability to nest code inside\n    regular expressions. These require time and effort to convert.\n  - I mostly only converted languages I had heard of, to reduce the porting cost.\n- Some more esoteric features of Pygments are omitted for simplicity.\n- Though the Chroma API supports content detection, very few languages support them.\n  I have plans to implement a statistical analyser at some point, but not enough time.\n","funding_links":["https://github.com/sponsors/alecthomas"],"categories":["Go","开源类库","Open source library","Other","library","Repositories"],"sub_categories":["文本处理","Word Processing"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fchroma","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falecthomas%2Fchroma","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falecthomas%2Fchroma/lists"}