Skip to content

Instantly share code, notes, and snippets.

@deepns
Created May 13, 2021 02:35
Show Gist options
  • Save deepns/22d366709a96f9e6fceba8abc8bdb156 to your computer and use it in GitHub Desktop.
Save deepns/22d366709a96f9e6fceba8abc8bdb156 to your computer and use it in GitHub Desktop.
Syntax highlighting in Python using Pygments
# Syntax highlighting code in Python using pygments
# install pygments if not installed already
# pip3 install pygments
# sample languages used here: markdown, json
from pygments import highlight
from pygments.lexers import get_lexer_by_name
# Formatting the output to be sent to a terminal
# Hence using Terminal256Formatter. Many other formatters
from pygments.formatters import Terminal256Formatter
markdown_text = """
# Heading 1
## Heading 2
This is `inline code`.
```c
// fenced code block
void foo() {
printf("bar");
}
```
### Lists
- **bold**
- *italic*
#### Checklists
- [ ] TBD
- [x] Done
"""
# The list of available styles can be obtained from get_all_styles
# from pygments.styles import get_all_styles
# print(list(get_all_styles()))
# styles available as of pygments 2.8.1.
# ['default', 'emacs', 'friendly', 'colorful', 'autumn', 'murphy', 'manni',
# 'material', 'monokai', 'perldoc', 'pastie', 'borland', 'trac', 'native',
# 'fruity', 'bw', 'vim', 'vs', 'tango', 'rrt', 'xcode', 'igor', 'paraiso-light',
# 'paraiso-dark', 'lovelace', 'algol', 'algol_nu', 'arduino', 'rainbow_dash',
# 'abap', 'solarized-dark', 'solarized-light', 'sas', 'stata', 'stata-light',
# 'stata-dark', 'inkpot', 'zenburn']
print(highlight(code=markdown_text,
lexer=get_lexer_by_name("markdown"),
formatter=Terminal256Formatter(style="monokai")))
# Highlighting json objects
import json
data = {
"year" : 2020,
"sucks": True
}
# Convert object into json formatted string using json.dumps
data_with_syntax_highlighting = highlight(
code=json.dumps(data, indent=2),
lexer=get_lexer_by_name("json"),
formatter=Terminal256Formatter(style="monokai"))
# with syntax highlighting, the raw string would like below.
# '\x1b[38;5;15m{\x1b[39m\n\x1b[38;5;15m \x1b[39m\x1b[38;5;197m"year"\x1b[39m\x1b[38;5;15m:\x1b[39m\x1b[38;5;15m \x1b[39m\x1b[38;5;141m2020\x1b[39m\x1b[38;5;15m,\x1b[39m\n\x1b[38;5;15m \x1b[39m\x1b[38;5;197m"sucks"\x1b[39m\x1b[38;5;15m:\x1b[39m\x1b[38;5;15m \x1b[39m\x1b[38;5;81mtrue\x1b[39m\n\x1b[38;5;15m}\x1b[39m\n'
print(data_with_syntax_highlighting)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment