Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { spawn } from "child_process";
import { unlink } from "fs-extra";
import * as path from "path";
import * as vm from "vm";
import * as LaTeX from "./latex";
import { Attributes } from "./lib/attributes";
import * as utility from "./utility";
export async function compileLaTeX(
content: string,
fileDirectoryPath: string,
normalizedAttributes: Attributes,
): Promise<string> {
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",
);
await utility.writeFile(texFilePath, content);
try {
const svgMarkdown = await LaTeX.toSVGMarkdown(texFilePath, {
latexEngine,
markdownDirectoryPath: fileDirectoryPath,
svgDirectoryPath: latexSVGDir,
svgZoom: latexZoom,
svgWidth: latexWidth,
svgHeight: latexHeight,
});
await unlink(texFilePath);
return svgMarkdown;
} catch (e) {
await unlink(texFilePath);
throw e;
}
}
/**
*
* @param code should be a javascript function string
* @param options
*/
async function runInVm(
code: string,
normalizedAttributes: Attributes,
): Promise<string> {
const script = new vm.Script(`((${code})())`);
const context = vm.createContext(normalizedAttributes["context"] || {});
return script.runInContext(context);
}
export async function run(
content: string,
fileDirectoryPath: string,
cmd: string,
normalizedAttributes: Attributes,
latexEngine: string = "pdflatex",
): Promise<string> {
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 = {
...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;
}
await 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 await new Promise<string>((resolve, reject) => {
const task = 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", () => {
unlink(savePath, () => {
const data = Buffer.concat(chunks).toString();
resolve(data);
});
});
});
}
const fileExtensionMap = {
go: ".go",
javascript: ".js",
python: ".py",
};
function getFileExtension(language: string): string {
return fileExtensionMap[language] || "";
}
|