Created
May 21, 2021 16:32
-
-
Save Julian-Nash/39a1f6a3fb7ba53eea62f2e903a4249b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pygments import highlight | |
from pygments.formatters.html import HtmlFormatter | |
from pygments.lexers import guess_lexer, get_lexer_for_filename, get_lexer_by_name | |
class HTMLCodeHighlighter: | |
""" Generate highlighted HTML snippets of code (pip install Pygments)""" | |
@classmethod | |
def _highlight(cls, code: str, lexer): | |
return highlight(code, lexer, HtmlFormatter()) | |
@classmethod | |
def highlight_code_by_filename(cls, code: str, filename: str) -> str: | |
lexer = get_lexer_for_filename(filename) | |
return cls._highlight(code, lexer) | |
@classmethod | |
def highlight_code_by_language(cls, code: str, language: str) -> str: | |
lexer = get_lexer_by_name(language) | |
return cls._highlight(code, lexer) | |
@classmethod | |
def highlight_code(cls, code: str) -> str: | |
lexer = guess_lexer(code) | |
return cls._highlight(code, lexer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment