1
0
mirror of https://github.com/alecthomas/chroma.git synced 2025-02-13 13:28:27 +02:00

cmd: add optional silent fail mode on no specific lexer

Makes use of chroma easier in/as less(1) preprocessors.

https://manpages.debian.org/less#INPUT_PREPROCESSOR
  export LESSOPEN='| p() { chroma --fail "$1" || cat "$1"; }; p "%s"'

https://manpages.debian.org/lesspipe#USER_DEFINED_FILTERS
  ln -s ~/go/bin/chroma ~/.lessfilter
This commit is contained in:
Ville Skyttä 2021-05-04 17:12:52 +03:00 committed by Alec Thomas
parent 2e23e7f215
commit e87e5b2208
2 changed files with 27 additions and 0 deletions

View File

@ -255,6 +255,24 @@ A command-line interface to Chroma is included. It can be installed with:
go get -u github.com/alecthomas/chroma/cmd/chroma
```
The CLI can be used as a preprocessor to colorise output of `less(1)`,
see documentation for the `LESSOPEN` environment variable.
The `--fail` flag can be used to suppress output and return with exit status
1 to facilitate falling back to some other preprocessor in case chroma
does not resolve a specific lexer to use for the given file. For example:
```shell
export LESSOPEN='| p() { chroma --fail "$1" || cat "$1"; }; p "%s"'
```
Replace `cat` with your favourite fallback preprocessor.
When invoked as `.lessfilter`, the `--fail` flag is automatically turned
on under the hood for easy integration with [lesspipe shipping with
Debian and derivatives](https://manpages.debian.org/lesspipe#USER_DEFINED_FILTERS);
for that setup the `chroma` executable can be just symlinked to `~/.lessfilter`.
<a id="markdown-whats-missing-compared-to-pygments" name="whats-missing-compared-to-pygments"></a>
## What's missing compared to Pygments?

View File

@ -7,6 +7,7 @@ import (
"io/ioutil"
"os"
"os/signal"
"path"
"runtime"
"runtime/pprof"
"sort"
@ -43,6 +44,7 @@ command, for Go.
Trace bool `help:"Trace lexer states as they are traversed."`
Check bool `help:"Do not format, check for tokenisation errors instead."`
Filename string `help:"Filename to use for selecting a lexer when reading from stdin."`
Fail bool `help:"Exit silently with status 1 if no specific lexer was found."`
Lexer string `help:"Lexer to use when formatting." default:"autodetect" short:"l" enum:"${lexers}"`
Style string `help:"Style to use for formatting." default:"swapoff" short:"s" enum:"${styles}"`
@ -105,6 +107,10 @@ func main() {
}()
defer pprof.StopCPUProfile()
}
if path.Base(os.Args[0]) == ".lessfilter" {
// https://manpages.debian.org/lesspipe#USER_DEFINED_FILTERS
cli.Fail = true
}
var out io.Writer = os.Stdout
if runtime.GOOS == "windows" && isatty.IsTerminal(os.Stdout.Fd()) {
@ -238,6 +244,9 @@ func listAll() {
func lex(ctx *kong.Context, path string, contents string) chroma.Iterator {
lexer := selexer(path, contents)
if lexer == nil {
if cli.Fail {
ctx.Exit(1)
}
lexer = lexers.Fallback
}
if rel, ok := lexer.(*chroma.RegexLexer); ok {