ariya.io About Collections Archives

Syntax Highlighting in the Terminal

2 min read

Syntax higlighting provides some nice additional visual cues for a code fragment, especially when it is part of an article or a slide deck. But what about code examples in terminal? There is no reason why it should not be highlighted as well.

As part of a live coding session, often there is a need to quickly show the working snippets, either in the form of code, data (e.g. in JSON), or configuration (e.g. in YAML), in the terminal. A proven solution is to open the snippet in an IDE or an editor that supports syntax higlighting. However, it does not have to be that way. To reduce distractions (switching from and to a different application window), the snippet can be shown right there in the terminal in its full glory, with colors and such.

Among many different choices, highlight is quite popular. Because of that, it is easily installable using your favorite package manager (apt-get install highlight on Debian/Ubuntu, choco install highlight on Windows, etc). If you are on macOS and use Nix, it is nix-env -i highlight away.

Highlight is very powerful. It can convert code written in many languages into various formats, from LaTeX to HTML. For the purpose of terminal output, the command looks like:

$ highlight --out-format=xterm256 sourcefile

as illustrated in the following screenshot:

Highlight

For JavaScript-related code (that includes JSON), a good alternative is Cardinal, a tool made by @thlorenz. Once it is installed from npm with npm install -g cardinal, it is available as the command-line tool cdl.

Cardinal

Beside a command-line tool, Cardinal is also a Node.js library. Hence, it can be utilized by another utility that needs to display some code or configuration to the user: a bootstrapper, a scaffolding tool, etc.

Cardinal supports a few different themes and also a custom theme, if you fancy making one (see its documentation for the details). By tweaking its configuration file, e.g. ~/.cardinalrc, you can also display the line number on the left side.

Cardinal

Under the hood, Cardinal relies on the tokenization of the source input. This is carried out using Esprima via redeyed (another library by @thlorenz). Because of that, Cardinal can cope with syntactically invalid code (shown above as broken.js, note the missing closing bracket) or even a slight variant of JavaScript such as TypeScript (ZipCodeValidator.ts in the screenshot).

Next time you need to show some code in the terminal, think of Highlight or Cardinal!

Related posts:

♡ this article? Explore more, check the archives, or follow me Twitter.

Share this on Twitter Facebook Google+

comments powered by Disqus