summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Xu (Hello71) <alex_y_xu@yahoo.ca>2022-11-11 20:53:40 -0500
committerAlex Xu (Hello71) <alex_y_xu@yahoo.ca>2022-11-11 20:53:40 -0500
commitef0cd4bbf1ccdd1abdc2d86cc3a804762a2efcb0 (patch)
tree687fa41329f910d192df39d89688a6e7d78ed686
parent00aa9237051d7b763ea038be4cb74df317ebd9f6 (diff)
downloadcgit-syntax-highlighting-master.tar.xz
cgit-syntax-highlighting-master.zip
-rwxr-xr-xsyntax-highlighting-server.py30
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=[