feat: Add inline macro support

This commit is contained in:
Yaotian-Liu 2023-06-08 00:12:36 +08:00
parent 5aa1faec57
commit 4be888e236
No known key found for this signature in database
GPG key ID: 160A5464FF2FBA1F
2 changed files with 33 additions and 2 deletions

View file

@ -13,6 +13,7 @@ import {
checkTranslatedMacros,
} from "src/latex_translator";
import { createExportButton } from "src/export_button";
import { extractInlineMacros } from "src/inline_macro";
import * as pseudocode from "pseudocode";
@ -29,11 +30,15 @@ export default class PseudocodePlugin extends Plugin {
const blockWidth = this.settings.blockSize;
blockDiv.style.width = `${blockWidth}em`;
// Extract inline macros
const [inlineMacros, nonMacroLines] = extractInlineMacros(source);
const allPreamble = this.preamble + inlineMacros;
// find all $ enclosements in source, and add the preamble.
// TODO: Might be able to optimize.
const mathRegex = /\$(.*?)\$/g;
const withPreamble = source.replace(mathRegex, (_, group1) => {
return `$${this.preamble}${group1}$`;
const withPreamble = nonMacroLines.replace(mathRegex, (_, group1) => {
return `$${allPreamble}${group1}$`;
});
const preEl = blockDiv.createEl("pre", {

26
src/inline_macro.ts Normal file
View file

@ -0,0 +1,26 @@
import {
translateUnsupportedMacrosPerf,
checkTranslatedMacros,
} from "./latex_translator";
export function extractInlineMacros(source: string): [string, string] {
const lines = source.split("\n");
let i: number;
for (i = 0; i < lines.length; i++) {
if (lines[i].includes("\\begin{algorithm}")) break;
}
const macroLines = lines.slice(0, i).join("\n");
const nonMacroLines = lines.slice(i).join("\n");
let inlineMacros = "";
try {
const translated = translateUnsupportedMacrosPerf(macroLines);
inlineMacros = checkTranslatedMacros(translated);
} catch (error) {
console.error(error);
}
return [inlineMacros, nonMacroLines];
}