UNPKG

ts-markdown-parser

Version:

TypeScript library that converts markdown to HTML (with code support).

46 lines 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.highlightPython = void 0; const keywords_1 = require("./keywords"); const libs_1 = require("./libs"); const markdown_parser_1 = require("../../utils/markdown-parser"); const highlightPython = (code) => { // Escape HTML entities code = code.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/`/g, "&#x60;"); let highlighted = code; // Regex to match strings (single and double quotes) if (!code.includes(`"""`)) { const stringRegex = /(?:r|R)?(["'])(?:\\.|(?!\1).)*\1/g; highlighted = code.replace(stringRegex, '<span class="md-string">$&</span>'); } // Regex to match single-line comments const singleLineCommentRegex = /(#.*)/g; highlighted = highlighted.replace(singleLineCommentRegex, '<span class="md-comment">$&</span>'); // Highlight decorators const decoratorRegex = /(^|\s)@[\w]+/gm; highlighted = highlighted.replace(decoratorRegex, '<span class="md-decorator">$&</span>'); // Highlight function calls const funcCallRegex = /(\b\w+)\s*\(([^)]*)\)/g; highlighted = highlighted.replace(funcCallRegex, '<span class="md-special">$1</span>($2)'); // Highlight class declarations const classDeclareRegex = /^class\s+([A-Z][a-zA-Z0-9_]*)/gi; highlighted = highlighted.replace(classDeclareRegex, 'class <span class="md-class">$1</span>'); // Function to prevent keyword replacement inside already wrapped <span> elements const replaceKeywords = (text) => { return text.replace(/(<span[^>]*>.*?<\/span>)|(\b\w+\b)/g, (match, span, word) => { if (span) return span; // Skip spans if (word && keywords_1.reservedKeywords.includes(word)) { return `<span class="md-keyword">${(0, markdown_parser_1.escapeHtml)(word)}</span>`; } if (word && libs_1.pythonStandardLibrary.includes(word)) { return `<span class="md-call-method">${(0, markdown_parser_1.escapeHtml)(word)}</span>`; } return word; }); }; // Highlight reserved keywords return replaceKeywords(highlighted); }; exports.highlightPython = highlightPython; //# sourceMappingURL=highlight.js.map