UNPKG

mume-with-litvis

Version:

Fork of mume with added http://litvis.org/

256 lines 10 kB
"use strict"; /** * Convert Mume markdown to Githb Flavored Markdown */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.markdownConvert = void 0; const fs = require("fs"); const mkdirp = require("mkdirp"); const path = require("path"); const compute_checksum_1 = require("./lib/compute-checksum"); const process_graphs_1 = require("./process-graphs"); const toc_1 = require("./toc"); const transformer_1 = require("./transformer"); const utility = require("./utility"); /** * Convert all math expressions inside markdown to images. * @param text input markdown text * @param config */ function processMath(text, { mathInlineDelimiters, mathBlockDelimiters, mathRenderingOnlineService }) { let line = text.replace(/\\\$/g, "#slash_dollarsign#"); const inline = mathInlineDelimiters; const block = mathBlockDelimiters; const inlineBegin = "(?:" + inline .map((x) => x[0]) .join("|") .replace(/\\/g, "\\\\") .replace(/([\(\)\[\]\$])/g, "\\$1") + ")"; const inlineEnd = "(?:" + inline .map((x) => x[1]) .join("|") .replace(/\\/g, "\\\\") .replace(/([\(\)\[\]\$])/g, "\\$1") + ")"; const blockBegin = "(?:" + block .map((x) => x[0]) .join("|") .replace(/\\/g, "\\\\") .replace(/([\(\)\[\]\$])/g, "\\$1") + ")"; const blockEnd = "(?:" + block .map((x) => x[1]) .join("|") .replace(/\\/g, "\\\\") .replace(/([\(\)\[\]\$])/g, "\\$1") + ")"; // display line = line.replace(new RegExp(`(\`\`\`(?:[\\s\\S]+?)\`\`\`\\s*(?:\\n|$))|(?:${blockBegin}([\\s\\S]+?)${blockEnd})`, "g"), ($0, $1, $2) => { if ($1) { return $1; } let math = $2; math = math.replace(/\n/g, "").replace(/\#slash\_dollarsign\#/g, "\\$"); math = utility.escapeString(math); return `<p align="center"><img src=\"${mathRenderingOnlineService}?${math .trim() .replace(/ /g, "%20")}\"/></p> \n`; }); // inline line = line.replace(new RegExp(`(\`\`\`(?:[\\s\\S]+?)\`\`\`\\s*(?:\\n|$))|(?:${inlineBegin}([\\s\\S]+?)${inlineEnd})`, "g"), ($0, $1, $2) => { if ($1) { return $1; } let math = $2; math = math.replace(/\n/g, "").replace(/\#slash\_dollarsign\#/g, "\\$"); math = utility.escapeString(math); return `<img src=\"${mathRenderingOnlineService}?${math .trim() .replace(/ /g, "%20")}\"/>`; }); line = line.replace(/\#slash\_dollarsign\#/g, "\\$"); return line; } /** * Format paths * @param text * @param fileDirectoryPath * @param projectDirectoryPath * @param useRelativeFilePath * @param protocolsWhiteListRegExp */ function processPaths(text, fileDirectoryPath, projectDirectoryPath, useRelativeFilePath, protocolsWhiteListRegExp) { function resolvePath(src) { if (src.match(protocolsWhiteListRegExp)) { // do nothing } else if (useRelativeFilePath) { if (src.startsWith("/")) { src = path.relative(fileDirectoryPath, path.resolve(projectDirectoryPath, "." + src)); } } else { if (!src.startsWith("/")) { // ./test.png or test.png src = "/" + path.relative(projectDirectoryPath, path.resolve(fileDirectoryPath, src)); } } return src.replace(/\\/g, "/"); // https://github.com/shd101wyy/vscode-markdown-preview-enhanced/issues/17 } let inBlock = false; let lines = text.split("\n"); lines = lines.map((line) => { if (line.match(/^\s*```/)) { inBlock = !inBlock; return line; } else if (inBlock) { return line; } else { // replace path in ![](...) and []() let r = /(\!?\[.*?]\()([^\)|^'|^"]*)(.*?\))/gi; line = line.replace(r, (whole, a, b, c) => { if (b[0] === "<") { b = b.slice(1, b.length - 1); return a + "<" + resolvePath(b.trim()) + "> " + c; } else { return a + resolvePath(b.trim()) + " " + c; } }); // replace path in tag r = /(<[img|a|iframe].*?[src|href]=['"])(.+?)(['"].*?>)/gi; line = line.replace(r, (whole, a, b, c) => { return a + resolvePath(b) + c; }); return line; } }); return lines.join("\n"); } function markdownConvert(text, { projectDirectoryPath, fileDirectoryPath, protocolsWhiteListRegExp, filesCache, mathRenderingOption, mathInlineDelimiters, mathBlockDelimiters, mathRenderingOnlineService, codeChunksData, graphsCache, usePandocParser, imageMagickPath, mermaidTheme, plantumlServer, onWillTransformMarkdown = null, onDidTransformMarkdown = null, }, config) { return __awaiter(this, void 0, void 0, function* () { if (!config["path"]) { throw new Error("{path} has to be specified"); } if (!config["image_dir"]) { throw new Error("{image_dir} has to be specified"); } // dest let outputFilePath; if (config["path"][0] === "/") { outputFilePath = path.resolve(projectDirectoryPath, "." + config["path"]); } else { outputFilePath = path.resolve(fileDirectoryPath, config["path"]); } for (const key in filesCache) { if (key.endsWith(".pdf")) { delete filesCache[key]; } } let imageDirectoryPath; if (config["image_dir"][0] === "/") { imageDirectoryPath = path.resolve(projectDirectoryPath, "." + config["image_dir"]); } else { imageDirectoryPath = path.resolve(fileDirectoryPath, config["image_dir"]); } const useRelativeFilePath = !config["absolute_image_path"]; if (onWillTransformMarkdown) { text = yield onWillTransformMarkdown(text); } // import external files const data = yield (0, transformer_1.transformMarkdown)(text, { fileDirectoryPath, projectDirectoryPath, useRelativeFilePath, filesCache, forPreview: false, forMarkdownExport: true, protocolsWhiteListRegExp, imageDirectoryPath, usePandocParser, onWillTransformMarkdown, onDidTransformMarkdown, }); text = data.outputString; if (onDidTransformMarkdown) { text = yield onDidTransformMarkdown(text); } // replace [MUMETOC] const tocBracketEnabled = data.tocBracketEnabled; if (tocBracketEnabled) { // [TOC] const headings = data.headings; const { content: tocMarkdown } = (0, toc_1.toc)(headings, { ordered: false, depthFrom: 1, depthTo: 6, tab: " ", }); text = text.replace(/^\s*\[MUMETOC\]\s*/gm, "\n\n" + tocMarkdown + "\n\n"); } // change link path to project '/' path // this is actually different from pandoc-convert.coffee text = processPaths(text, fileDirectoryPath, projectDirectoryPath, useRelativeFilePath, protocolsWhiteListRegExp); text = mathRenderingOption !== "None" ? processMath(text, { mathInlineDelimiters, mathBlockDelimiters, mathRenderingOnlineService, }) : text; return yield new Promise((resolve, reject) => { mkdirp(imageDirectoryPath) .then(() => { (0, process_graphs_1.processGraphs)(text, { fileDirectoryPath, projectDirectoryPath, imageDirectoryPath, imageFilePrefix: (0, compute_checksum_1.default)(outputFilePath), useRelativeFilePath, codeChunksData, graphsCache, imageMagickPath, mermaidTheme, addOptionsStr: false, plantumlServer, }).then(({ outputString }) => { outputString = data.frontMatterString + outputString; // put the front-matter back. fs.writeFile(outputFilePath, outputString, { encoding: "utf-8" }, (error2) => { if (error2) { return reject(error2.toString()); } return resolve(outputFilePath); }); }); }) .catch((error) => { if (error) { return reject(error.toString()); } }); }); }); } exports.markdownConvert = markdownConvert; //# sourceMappingURL=markdown-convert.js.map