Skip to content

Instantly share code, notes, and snippets.

@Julian-Nash
Created May 21, 2021 16:32
Show Gist options
  • Save Julian-Nash/39a1f6a3fb7ba53eea62f2e903a4249b to your computer and use it in GitHub Desktop.
Save Julian-Nash/39a1f6a3fb7ba53eea62f2e903a4249b to your computer and use it in GitHub Desktop.
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