UNPKG

mume-with-litvis

Version:

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

159 lines 6.22 kB
"use strict"; 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.run = exports.compileLaTeX = void 0; const child_process_1 = require("child_process"); const fs_extra_1 = require("fs-extra"); const path = require("path"); const vm = require("vm"); const LaTeX = require("./latex"); const utility = require("./utility"); function compileLaTeX(content, fileDirectoryPath, normalizedAttributes) { return __awaiter(this, void 0, void 0, function* () { const latexEngine = normalizedAttributes["latex_engine"] || "pdflatex"; const latexSVGDir = normalizedAttributes["latex_svg_dir"]; // if not provided, the svg files will be stored in temp folder and will be deleted automatically const latexZoom = normalizedAttributes["latex_zoom"]; const latexWidth = normalizedAttributes["latex_width"]; const latexHeight = normalizedAttributes["latex_height"]; const texFilePath = path.resolve(fileDirectoryPath, Math.random() .toString(36) .substr(2, 9) + "_code_chunk.tex"); yield utility.writeFile(texFilePath, content); try { const svgMarkdown = yield LaTeX.toSVGMarkdown(texFilePath, { latexEngine, markdownDirectoryPath: fileDirectoryPath, svgDirectoryPath: latexSVGDir, svgZoom: latexZoom, svgWidth: latexWidth, svgHeight: latexHeight, }); yield (0, fs_extra_1.unlink)(texFilePath); return svgMarkdown; } catch (e) { yield (0, fs_extra_1.unlink)(texFilePath); throw e; } }); } exports.compileLaTeX = compileLaTeX; /** * * @param code should be a javascript function string * @param options */ function runInVm(code, normalizedAttributes) { return __awaiter(this, void 0, void 0, function* () { const script = new vm.Script(`((${code})())`); const context = vm.createContext(normalizedAttributes["context"] || {}); return script.runInContext(context); }); } function run(content, fileDirectoryPath, cmd, normalizedAttributes, latexEngine = "pdflatex") { return __awaiter(this, void 0, void 0, function* () { let args = normalizedAttributes["args"] || []; if (typeof args === "string") { args = [args]; } const fileExtension = getFileExtension(cmd); const savePath = path.resolve(fileDirectoryPath, Math.random() .toString(36) .substr(2, 9) + "_code_chunk" + fileExtension); content = content.replace(/\u00A0/g, " "); if (cmd.match(/(la)?tex/) || cmd === "pdflatex") { const patchedAttributes = Object.assign(Object.assign({}, normalizedAttributes), { latex_engine: normalizedAttributes["latex_engine"] || latexEngine }); return compileLaTeX(content, fileDirectoryPath, patchedAttributes); } if (cmd === "node.vm") { return runInVm(content, normalizedAttributes); } if (cmd.match(/python/) && (normalizedAttributes["matplotlib"] || normalizedAttributes["mpl"])) { content = ` # -*- coding: utf-8 -*- # modify default matplotlib pyplot show function try: import matplotlib matplotlib.use('Agg') # use Agg backend import matplotlib.pyplot as plt import sys def new_plt_show(): plt.savefig(sys.stdout, format="svg") plt.show = new_plt_show # override old one except Exception: pass # modify default mpld3 behavior try: import matplotlib.pyplot as plt, mpld3 import sys def new_mpld3_show(): fig = plt.gcf() # get current figure sys.stdout.write(mpld3.fig_to_html(fig)) mpld3.show = new_mpld3_show # override old one mpld3.display = new_mpld3_show except Exception: pass ` + content; } yield utility.writeFile(savePath, content); // check macros let findInputFileMacro = false; args = args.map((arg) => { if (arg === "$input_file") { findInputFileMacro = true; return savePath; } else { return arg; } }); if (!findInputFileMacro && !normalizedAttributes["stdin"]) { args.push(savePath); } return yield new Promise((resolve, reject) => { const task = (0, child_process_1.spawn)(cmd, args, { cwd: fileDirectoryPath }); if (normalizedAttributes["stdin"]) { task.stdin.write(content); // pass content as stdin } task.stdin.end(); const chunks = []; task.stdout.on("data", (chunk) => { chunks.push(chunk); }); task.stderr.on("data", (chunk) => { chunks.push(chunk); }); task.on("error", (error) => { chunks.push(Buffer.from(error.toString(), "utf-8")); }); task.on("close", () => { (0, fs_extra_1.unlink)(savePath, () => { const data = Buffer.concat(chunks).toString(); resolve(data); }); }); }); }); } exports.run = run; const fileExtensionMap = { go: ".go", javascript: ".js", python: ".py", }; function getFileExtension(language) { return fileExtensionMap[language] || ""; } //# sourceMappingURL=code-chunk.js.map