Broken project to implement a cross-protocol browser in textual
HighlightedCode: Handle everything that pygments can handle
| -rwxr-xr-x | browset.py | 2 | ||||
| -rw-r--r-- | mime/highlightedcode.py | 17 |
2 files changed, 16 insertions, 3 deletions
@@ -88,7 +88,7 @@ class Browset(App): if "text/gemini" in mime: content = Gemtext(fp=fp, id="content") - elif mime in mimetolexer: + elif HighlightedCode.can_handle_mime(mime): content = HighlightedCode(fp=fp, id="content", mime=mime) else: content = Plaintext(fp=fp, id="content") diff --git a/mime/highlightedcode.py b/mime/highlightedcode.py index 63defef..49c5046 100644 --- a/mime/highlightedcode.py +++ b/mime/highlightedcode.py @@ -1,6 +1,8 @@ from textual.widgets import Static from textual.containers import Container from rich.syntax import Syntax +from pygments.lexers import get_lexer_for_mimetype +from pygments.util import ClassNotFound # mime list from gemini://geminispace.info/statistics mimetolexer = { @@ -23,6 +25,7 @@ mimetolexer = { "application/atom+xml": "xml", "text/xml": "xml", "image/svg+xml": "xml", + # Less popular mimes will call out to get_lexer_for_mimetype } class HighlightedCode(Static): @@ -41,5 +44,15 @@ class HighlightedCode(Static): if type(line) is bytes: line = line.decode("UTF-8") code += line - lexer = mimetolexer[mime] - self.mount(Static(Syntax(code,lexer=lexer))) + lexer = mimetolexer[mime] if mime in mimetolexer else get_lexer_for_mimetype(mime) + self.mount(Static(Syntax(code,lexer=lexer,background_color="default"))) + + def can_handle_mime(mime): + if mime in mimetolexer: + return True + try: + get_lexer_for_mimetype(mime) + return True + except ClassNotFound: + pass + return False |