ts-markdown-parser
Version:
TypeScript library that converts markdown to HTML (with code support).
58 lines • 2.83 kB
JavaScript
;
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 = (line) => {
// Escape HTML entities
line = line.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/`/g, "`");
// Find the first #, but ignore if it's the first non-whitespace char (whole line is a comment)
// (You can tweak this to be more robust with a parser if you want to ignore # inside strings, but for Markdown, this is fine)
const hashIdx = line.indexOf("#");
if (hashIdx === -1) {
// No comment on this line; highlight all
return highlightPythonCode(line);
}
// If # is the first non-whitespace, treat whole line as comment
if (/^\s*#/.test(line)) {
return `<span class="md-comment">${(0, markdown_parser_1.escapeHtml)(line)}</span>`;
}
// Otherwise, split code and comment
const codePart = line.slice(0, hashIdx);
const commentPart = line.slice(hashIdx);
// Highlight code part only
const codeHighlighted = highlightPythonCode(codePart);
// Wrap comment with NO inner highlight
return codeHighlighted + `<span class="md-comment">${(0, markdown_parser_1.escapeHtml)(commentPart)}</span>`;
};
exports.highlightPython = highlightPython;
// Helper: Only highlight code, never wrap comments here
function highlightPythonCode(code) {
// Strings
const stringRegex = /(?:r|R)?(["'])(?:\\.|(?!\1).)*\1/g;
let highlighted = code.replace(stringRegex, '<span class="md-string">$&</span>');
// Decorators
const decoratorRegex = /(^|\s)@[\w]+/gm;
highlighted = highlighted.replace(decoratorRegex, '<span class="md-decorator">$&</span>');
// Function calls
const funcCallRegex = /(\b\w+)\s*\(([^)]*)\)/g;
highlighted = highlighted.replace(funcCallRegex, '<span class="md-special">$1</span>($2)');
// Class declarations
const classDeclareRegex = /^class\s+([A-Z][a-zA-Z0-9_]*)/gi;
highlighted = highlighted.replace(classDeclareRegex, 'class <span class="md-class">$1</span>');
// Keywords and stdlib
highlighted = highlighted.replace(/(<span[^>]*>.*?<\/span>)|(\b\w+\b)/g, (match, span, word) => {
if (span)
return span;
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;
});
return highlighted;
}
//# sourceMappingURL=highlight.js.map