Skip to content

Instantly share code, notes, and snippets.

@javiertejero
Forked from dshafik/hl.py
Created October 29, 2012 09:32
Show Gist options
  • Save javiertejero/3972600 to your computer and use it in GitHub Desktop.
Save javiertejero/3972600 to your computer and use it in GitHub Desktop.
CLI syntax highlighter
#!/usr/bin/env python
"""
GistID: 3972600
(this lives in the cloud at github gist:3972600/hl.py)
Highlight stdin using pygments and output to stdout
Auto-detects the input language.
Will not colorize if piped into something else.
Requires solarized_dark_pygments to be installed as a module (e.g. clone
it inside your site-packages in the virtualenv and create a __init__.py
file to set as a module)
(can be retrieved from git://github.com/gthank/solarized-dark-pygments.git)
Usage: echo '{"test": "foo", "bar": 123, "bat": false}' | hl
Usage: echo '{"test": "foo", "bar": 123, "bat": false}' | hl | pbcopy (not colored)
So basically this gist is similar to running this:
$ pygmentize -f terminal256 -O style=solarized256 -g
or
$ pygmentize -f terminal -O style=solarized -g
Based on the TERM enviroment variable, and when you have installed
the styles in the pygments folder. Of course pygmentize is much more
powerful and the use of this gist is discouraged (the goal to fork this
was to learn a bit from the pygments API).
"""
import sys
import os
import json
import pygments
from pygments.lexers import *
from pygments.formatters.terminal256 import Terminal256Formatter
from pygments.formatters.terminal import TerminalFormatter
from pygments.formatters.other import NullFormatter
from solarized_dark_pygments import solarized256, solarized
try:
FORMATTER = (Terminal256Formatter
if '256color' in os.environ.get('TERM', '')
else TerminalFormatter)
STYLE = (solarized256.Solarized256Style
if '256color' in os.environ.get('TERM', '')
else solarized.SolarizedStyle)
if not sys.stdout.isatty():
FORMATTER = NullFormatter
formatter = FORMATTER(style=STYLE)
content = sys.stdin.read()
lexer = guess_lexer(content)
print "## Lexer type: {0}".format(type(lexer))
if isinstance(lexer, JSONLexer):
content = json.dumps(json.loads(content), indent=4)
output = pygments.highlight(content, lexer, formatter)
print output
sys.exit(0)
except Exception as e:
print e
sys.exit(-1)
@javiertejero
Copy link
Author

Why do not use this gist?

Because 'pygmentize' will do this for you:

  • Output can be redirected to less -R and will not loose colouring,
  • Can receive files as a parameter and
  • Will infer/guess the file type from the file extension

Among many other things...

While this gist just deduces the term type from the environment, which is not very useful when you use always the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment