diff options
-rwxr-xr-x | syntax-highlighting-server.py | 30 |
1 files changed, 11 insertions, 19 deletions
diff --git a/syntax-highlighting-server.py b/syntax-highlighting-server.py index 244e9d4..9d582ad 100755 --- a/syntax-highlighting-server.py +++ b/syntax-highlighting-server.py @@ -1,40 +1,32 @@ #!/usr/bin/env python3 -from starlette.applications import Starlette -from starlette.responses import HTMLResponse -from starlette.routing import Route import pygments from pygments.formatters import HtmlFormatter -from pygments.lexers import guess_lexer, guess_lexer_for_filename +from pygments.lexers import get_lexer_for_filename from pygments.lexers.special import TextLexer from pygments.util import ClassNotFound +from starlette.applications import Starlette +from starlette.responses import HTMLResponse +from starlette.routing import Route formatter = None async def startup_task(): - guess_lexer('') + get_lexer_for_filename('x.txt') global formatter formatter = HtmlFormatter(style='pastie', nobackground=True) -def do_highlight(filename, data): +async def run_highlight(request): + data = await request.body() try: - lexer = guess_lexer_for_filename(filename, data) + lexer = get_lexer_for_filename(request.query_params['filename'], data) except ClassNotFound: - try: - lexer = guess_lexer(data) - # SqlLexer always gives 0.01 - if lexer.analyse_text(data) <= 0.01: - lexer = TextLexer() - except ClassNotFound: - lexer = TextLexer() - return ''.join([ + lexer = TextLexer() + return HTMLResponse(''.join([ f'<!-- Pygments {pygments.__version__}: {lexer.name} ({lexer.__class__.__name__}) -->', '<style>', formatter.get_style_defs('.highlight'), '</style>', pygments.highlight(data, lexer, formatter) - ]) - -async def run_highlight(request): - return HTMLResponse(do_highlight(request.query_params['filename'], await request.body())) + ])) app = Starlette( routes=[ |