|
| 1 | +from workers import WorkerEntrypoint, Response, Request |
| 2 | +from pygments import highlight |
| 3 | +from pygments.lexers import get_lexer_by_name, guess_lexer |
| 4 | +from pygments.formatters import HtmlFormatter |
| 5 | +from pygments.util import ClassNotFound |
| 6 | + |
| 7 | + |
| 8 | +class Default(WorkerEntrypoint): |
| 9 | + async def fetch(self, request: Request): |
| 10 | + return Response("Python RPC server is running. Use RPC to call methods.") |
| 11 | + |
| 12 | + async def highlight_code(self, code: str, language: str = None) -> dict: |
| 13 | + """ |
| 14 | + Syntax highlight code using Pygments. |
| 15 | +
|
| 16 | + Args: |
| 17 | + code: The source code to highlight |
| 18 | + language: Programming language (e.g., 'python', 'javascript', 'rust') |
| 19 | + If None, will attempt to guess the language |
| 20 | +
|
| 21 | + Returns: |
| 22 | + Dict with highlighted HTML and CSS |
| 23 | + """ |
| 24 | + try: |
| 25 | + # Get the appropriate lexer |
| 26 | + if language: |
| 27 | + lexer = get_lexer_by_name(language, stripall=True) |
| 28 | + else: |
| 29 | + lexer = guess_lexer(code) |
| 30 | + except ClassNotFound: |
| 31 | + return { |
| 32 | + "error": f"Language '{language}' not found", |
| 33 | + "html": f"<pre>{code}</pre>", |
| 34 | + "css": "", |
| 35 | + "language": "unknown", |
| 36 | + } |
| 37 | + |
| 38 | + # Create formatter with line numbers and styling |
| 39 | + formatter = HtmlFormatter( |
| 40 | + linenos=True, cssclass="highlight", style="monokai" |
| 41 | + ) |
| 42 | + |
| 43 | + # Generate highlighted HTML |
| 44 | + highlighted_html = highlight(code, lexer, formatter) |
| 45 | + |
| 46 | + # Get the CSS for styling |
| 47 | + css = formatter.get_style_defs(".highlight") |
| 48 | + |
| 49 | + return { |
| 50 | + "html": highlighted_html, |
| 51 | + "css": css, |
| 52 | + "language": lexer.name, |
| 53 | + "language_alias": lexer.aliases[0] if lexer.aliases else None, |
| 54 | + } |
| 55 | + |
| 56 | + |
0 commit comments