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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | // import * as Baby from "babyparse"
import { DEngineClient } from "@dendronhq/engine-server";
import * as Baby from "babyparse";
import * as fs from "fs";
import * as less from "less";
import * as path from "path";
import * as request from "request";
import * as temp from "temp";
// import * as request from 'request'
// import * as less from "less"
// import * as temp from "temp"
// temp.track()
import { CustomSubjects } from "./custom-subjects";
import HeadingIdGenerator from "./heading-id-generator";
import { parseAttributes, stringifyAttributes } from "./lib/attributes";
import computeChecksum from "./lib/compute-checksum";
import * as PDF from "./pdf";
import * as utility from "./utility";
export interface HeadingData {
content: string;
level: number;
id: string;
}
export interface TransformMarkdownOutput {
outputString: string;
/**
* An array of slide configs.
*/
slideConfigs: object[];
/**
* whehter we found [TOC] in markdown file or not.
*/
tocBracketEnabled: boolean;
/**
* imported javascript and css files
* convert .js file to <script src='...'></script>
* convert .css file to <link href='...'></link>
*/
JSAndCssFiles: string[];
headings: HeadingData[];
/**
* Get `---\n...\n---\n` string.
*/
frontMatterString: string;
}
export interface TransformMarkdownOptions {
fileDirectoryPath: string;
projectDirectoryPath: string;
filesCache: { [key: string]: string };
useRelativeFilePath: boolean;
forPreview: boolean;
forMarkdownExport?: boolean;
protocolsWhiteListRegExp: RegExp;
notSourceFile?: boolean;
imageDirectoryPath?: string;
usePandocParser: boolean;
headingIdGenerator?: HeadingIdGenerator;
renderRefWithOutline?: boolean;
onWillTransformMarkdown?: (markdown: string) => Promise<string>;
onDidTransformMarkdown?: (markdown: string) => Promise<string>;
engine: DEngineClient;
}
const fileExtensionToLanguageMap = {
vhd: "vhdl",
erl: "erlang",
dot: "dot",
gv: "dot",
viz: "dot",
};
const selfClosingTag = {
area: 1,
base: 1,
br: 1,
col: 1,
command: 1,
embed: 1,
hr: 1,
img: 1,
input: 1,
keygen: 1,
link: 1,
meta: 1,
param: 1,
source: 1,
track: 1,
wbr: 1,
};
/**
* Convert 2D array to markdown table.
* The first row is headings.
*/
function twoDArrayToMarkdownTable(twoDArr) {
let output = " \n";
twoDArr.forEach((arr, offset) => {
let i = 0;
output += "|";
while (i < arr.length) {
output += arr[i] + "|";
i += 1;
}
output += " \n";
if (offset === 0) {
output += "|";
i = 0;
while (i < arr.length) {
output += "---|";
i += 1;
}
output += " \n";
}
});
output += " ";
return output;
}
function createAnchor(lineNo) {
return `\n\n<p data-line="${lineNo}" class="sync-line" style="margin:0;"></p>\n\n`;
}
let DOWNLOADS_TEMP_FOLDER = null;
/**
* download file and return its local path
*/
function downloadFileIfNecessary(filePath: string): Promise<string> {
return new Promise((resolve, reject) => {
if (!filePath.match(/^https?\:\/\//)) {
return resolve(filePath);
}
if (!DOWNLOADS_TEMP_FOLDER) {
DOWNLOADS_TEMP_FOLDER = temp.mkdirSync("mume_downloads");
}
request.get(
{ url: filePath, encoding: "binary" },
(error, response, body) => {
if (error) {
return reject(error);
} else {
const localFilePath =
path.resolve(DOWNLOADS_TEMP_FOLDER, computeChecksum(filePath)) +
path.extname(filePath);
fs.writeFile(localFilePath, body, "binary", (error2) => {
if (error2) {
return reject(error2);
} else {
return resolve(localFilePath);
}
});
}
},
);
});
}
/**
*
* Load file by `filePath`
* @param filePath
* @param param1
* @param filesCache
*/
async function loadFile(
filePath: string,
{ fileDirectoryPath, forPreview, imageDirectoryPath },
filesCache = {},
): Promise<string> {
if (filesCache[filePath]) {
return filesCache[filePath];
}
if (filePath.endsWith(".less")) {
// less file
const data = await utility.readFile(filePath, { encoding: "utf-8" });
return await new Promise<string>((resolve, reject) => {
less.render(
data,
{ paths: [path.dirname(filePath)] },
(error, output) => {
if (error) {
return reject(error);
} else {
return resolve(output.css || "");
}
},
);
});
} else if (filePath.endsWith(".pdf")) {
// pdf file
const localFilePath = await downloadFileIfNecessary(filePath);
const svgMarkdown = await PDF.toSVGMarkdown(localFilePath, {
markdownDirectoryPath: fileDirectoryPath,
svgDirectoryPath: imageDirectoryPath,
});
return svgMarkdown;
} else if (filePath.match(/^https?\:\/\//)) {
/*
else if filePath.endsWith('.js') # javascript file
requiresJavaScriptFiles(filePath, forPreview).then (jsCode)->
return resolve(jsCode)
.catch (e)->
return resolve(e)
# .catch (error)->
# return reject(error)
*/
// online file
// github
if (filePath.startsWith("https://github.com/")) {
filePath = filePath
.replace("https://github.com/", "https://raw.githubusercontent.com/")
.replace("/blob/", "/");
}
return await new Promise<string>((resolve, reject) => {
request(filePath, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(body.toString());
}
});
});
} else {
// local file
return await utility.readFile(filePath, { encoding: "utf-8" });
}
}
/**
*
* @param inputString
* @param fileDirectoryPath
* @param projectDirectoryPath
* @param param3
*/
export async function transformMarkdown(
inputString: string,
{
fileDirectoryPath = "",
projectDirectoryPath = "",
filesCache = {},
useRelativeFilePath = null,
forPreview = false,
forMarkdownExport = false,
protocolsWhiteListRegExp = null,
notSourceFile = false,
imageDirectoryPath = "",
usePandocParser = false,
headingIdGenerator = new HeadingIdGenerator(),
renderRefWithOutline = false,
onWillTransformMarkdown = null,
onDidTransformMarkdown = null,
engine,
}: TransformMarkdownOptions,
): Promise<TransformMarkdownOutput> {
let lastOpeningCodeBlockFence: string = null;
let codeChunkOffset = 0;
const slideConfigs = [];
const JSAndCssFiles = [];
let headings = [];
let tocBracketEnabled = false;
let frontMatterString = "";
/**
* As the recursive version of this function will cause the error:
* RangeError: Maximum call stack size exceeded
* I wrote it in iterative way.
* @param i start offset
* @param lineNo start line number
*/
async function helper(i, lineNo = 0): Promise<TransformMarkdownOutput> {
let outputString = "";
while (i < inputString.length) {
Iif (inputString[i] === "\n") {
// return helper(i+1, lineNo+1, outputString+'\n')
i = i + 1;
lineNo = lineNo + 1;
outputString = outputString + "\n";
continue;
}
let end = inputString.indexOf("\n", i);
Eif (end < 0) {
end = inputString.length;
}
let line = inputString.substring(i, end);
const inCodeBlock = !!lastOpeningCodeBlockFence;
const currentCodeBlockFence = (line.match(/^[`]{3,}/) || [])[0];
Iif (currentCodeBlockFence) {
if (!inCodeBlock && forPreview) {
outputString += createAnchor(lineNo);
}
const containsCmd = !!line.match(/\"?cmd\"?\s*[:=\s}]/);
if (!inCodeBlock && !notSourceFile && containsCmd) {
// it's code chunk, so mark its offset
line = line.replace("{", `{code_chunk_offset=${codeChunkOffset}, `);
codeChunkOffset++;
}
if (!inCodeBlock) {
lastOpeningCodeBlockFence = currentCodeBlockFence;
} else if (
currentCodeBlockFence.length >= lastOpeningCodeBlockFence.length
) {
lastOpeningCodeBlockFence = null;
}
// return helper(end+1, lineNo+1, outputString+line+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + line + "\n";
continue;
}
Iif (inCodeBlock) {
// return helper(end+1, lineNo+1, outputString+line+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + line + "\n";
continue;
}
let headingMatch;
let taskListItemMatch;
let htmlTagMatch;
/*
// I changed this because for case like:
* haha

The image will not be displayed correctly in preview as there will be `anchor` inserted
between...
*/
Iif (
line.match(/^(\!\[|@import)/) &&
inputString[i - 1] === "\n" &&
inputString[i - 2] === "\n"
) {
if (forPreview) {
outputString += createAnchor(lineNo); // insert anchor for scroll sync
}
/* tslint:disable-next-line:no-conditional-assignment */
} else Iif ((headingMatch = line.match(/^(\#{1,7}).*/))) {
/* ((headingMatch = line.match(/^(\#{1,7})(.+)$/)) ||
// the ==== and --- headers don't work well. For example, table and list will affect it, therefore I decide not to support it.
(inputString[end + 1] === '=' && inputString[end + 2] === '=') ||
(inputString[end + 1] === '-' && inputString[end + 2] === '-')) */ // headings
if (forPreview) {
outputString += createAnchor(lineNo);
}
let heading;
let level;
let tag;
// if (headingMatch) {
heading = line.replace(headingMatch[1], "");
tag = headingMatch[1];
level = tag.length;
/*} else {
if (inputString[end + 1] === '=') {
heading = line.trim()
tag = '#'
level = 1
} else {
heading = line.trim()
tag = '##'
level = 2
}
end = inputString.indexOf('\n', end + 1)
if (end < 0) end = inputString.length
}*/
/*if (!heading.length) {
// return helper(end+1, lineNo+1, outputString + '\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + "\n";
continue;
}*/
// check {class:string, id:string, ignore:boolean}
const optMatch = heading.match(/(\s+\{|^\{)(.+?)\}(\s*)$/);
let classes = "";
let id = "";
let ignore = false;
let opt;
if (optMatch) {
heading = heading.replace(optMatch[0], "");
try {
opt = parseAttributes(optMatch[0]);
(classes = opt["class"]),
(id = opt["id"]),
(ignore = opt["ignore"]);
delete opt["class"];
delete opt["id"];
delete opt["ignore"];
} catch (e) {
heading = "OptionsError: " + optMatch[1];
ignore = true;
}
}
if (!id) {
id = headingIdGenerator.generateId(heading);
if (usePandocParser) {
id = id.replace(/^[\d\-]+/, "");
if (!id) {
id = "section";
}
}
}
if (!ignore) {
headings.push({ content: heading, level, id });
}
if (usePandocParser) {
// pandoc
let optionsStr = "{";
if (id) {
optionsStr += `#${id} `;
}
if (classes) {
optionsStr += "." + classes.replace(/\s+/g, " .") + " ";
}
if (opt) {
for (const key in opt) {
if (typeof opt[key] === "number") {
optionsStr += " " + key + "=" + opt[key];
} else {
optionsStr += " " + key + '="' + opt[key] + '"';
}
}
}
optionsStr += "}";
// return helper(end+1, lineNo+1, outputString + `${tag} ${heading} ${optionsStr}` + '\n')
i = end + 1;
lineNo = lineNo + 1;
outputString =
outputString + `${tag} ${heading} ${optionsStr}` + "\n";
continue;
} else {
// markdown-it
if (!forMarkdownExport) {
// convert to <h? ... ></h?>
line = `${tag} ${heading}\n<p class="mume-header ${classes}" id="${id}"></p>`;
} else {
line = `${tag} ${heading}`;
}
// return helper(end+1, lineNo+1, outputString + line + '\n\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + line + "\n\n";
continue;
// I added one extra `\n` here because remarkable renders content below
// heading differently with `\n` and without `\n`.
}
} else Iif (line.match(/^\<!--/)) {
// custom comment
if (forPreview) {
outputString += createAnchor(lineNo);
}
let commentEnd = inputString.indexOf("-->", i + 4);
if (commentEnd < 0) {
// didn't find -->
// return helper(inputString.length, lineNo+1, outputString+'\n')
i = inputString.length;
lineNo = lineNo + 1;
outputString = outputString + "\n";
continue;
} else {
commentEnd += 3;
}
const subjectMatch = line.match(/^\<!--\s+([^\s]+)/);
if (!subjectMatch) {
const content = inputString.slice(i + 4, commentEnd - 3).trim();
const newlinesMatch = content.match(/\n/g);
const newlines = newlinesMatch ? newlinesMatch.length : 0;
// return helper(commentEnd, lineNo + newlines, outputString + '\n')
i = commentEnd;
lineNo = lineNo + newlines;
outputString = outputString + "\n";
continue;
} else {
const subject = subjectMatch[1];
if (subject === "@import") {
const commentEnd2 = line.lastIndexOf("-->");
if (commentEnd2 > 0) {
line = line.slice(4, commentEnd2).trim();
}
} else if (subject in CustomSubjects) {
const content = inputString.slice(i + 4, commentEnd - 3).trim();
const newlinesMatch = content.match(/\n/g);
const newlines = newlinesMatch ? newlinesMatch.length : 0;
const optionsMatch = content.match(/^([^\s]+?)\s([\s\S]+)$/);
let options = {};
if (optionsMatch && optionsMatch[2]) {
options = parseAttributes(optionsMatch[2]);
}
options["lineNo"] = lineNo;
if (subject === "pagebreak" || subject === "newpage") {
// pagebreak
// return helper(commentEnd, lineNo + newlines, outputString + '<div class="pagebreak"> </div>\n')
i = commentEnd;
lineNo = lineNo + newlines;
outputString = outputString + '<div class="pagebreak"> </div>\n';
continue;
} else if (subject.match(/^\.?slide\:?$/)) {
// slide
slideConfigs.push(options);
if (forMarkdownExport) {
// return helper(commentEnd, lineNo + newlines, outputString + `<!-- ${content} -->` + '\n')
i = commentEnd;
lineNo = lineNo + newlines;
outputString = outputString + `<!-- ${content} -->` + "\n";
continue;
} else {
// return helper(commentEnd, lineNo + newlines, outputString + '\n[MUMESLIDE]\n\n')
i = commentEnd;
lineNo = lineNo + newlines;
outputString = outputString + "\n[MUMESLIDE]\n\n";
continue;
}
}
} else {
const content = inputString.slice(i + 4, commentEnd - 3).trim();
const newlinesMatch = content.match(/\n/g);
const newlines = newlinesMatch ? newlinesMatch.length : 0;
// return helper(commentEnd, lineNo + newlines, outputString + '\n')
i = commentEnd;
lineNo = lineNo + newlines;
outputString = outputString + "\n";
continue;
}
}
} else Iif (line.match(/^\s*\[toc\]\s*$/i)) {
// [TOC]
if (forPreview) {
outputString += createAnchor(lineNo); // insert anchor for scroll sync
}
tocBracketEnabled = true;
// return helper(end+1, lineNo+1, outputString + `\n[MUMETOC]\n\n`)
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + `\n[MUMETOC]\n\n`;
continue;
} else Iif (
/* tslint:disable-next-line:no-conditional-assignment */
(taskListItemMatch = line.match(
/^\s*(?:[*\-+]|\d+\.)\s+(\[[xX\s]\])\s/,
))
) {
// task list
const checked = taskListItemMatch[1] !== "[ ]";
if (!forMarkdownExport) {
line = line.replace(
taskListItemMatch[1],
`<input type="checkbox" class="task-list-item-checkbox${
forPreview ? " sync-line" : ""
}" ${forPreview ? `data-line="${lineNo}"` : ""}${
checked ? " checked" : ""
}>`,
);
}
// return helper(end+1, lineNo+1, outputString+line+`\n`)
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + line + `\n`;
continue;
} else Iif (
/* tslint:disable-next-line:no-conditional-assignment */
(htmlTagMatch = line.match(
/^\s*<(?:([a-zA-Z]+)|([a-zA-Z]+)\s+(?:.+?))>/,
))
) {
// escape html tag like <pre>
const tagName = htmlTagMatch[1] || htmlTagMatch[2];
if (!(tagName in selfClosingTag)) {
const closeTagName = `</${tagName}>`;
const end2 = inputString.indexOf(
closeTagName,
i + htmlTagMatch[0].length,
);
if (end2 < 0) {
// HTML error. Tag not closed
// Do Nothing here. Reason:
// $$ x
// <y>
// $$
/*
i = inputString.length
lineNo = lineNo + 1
outputString = outputString + `\n\`\`\`\nHTML error. Tag <${tagName}> not closed. ${closeTagName} is required.\n\`\`\`\n\n`
continue
*/
} else {
const htmlString = inputString.slice(i, end2 + closeTagName.length);
const newlinesMatch = htmlString.match(/\n/g);
const newlines = newlinesMatch ? newlinesMatch.length : 0;
// return helper(commentEnd, lineNo + newlines, outputString + '\n')
i = end2 + closeTagName.length;
lineNo = lineNo + newlines;
outputString = outputString + htmlString;
continue;
}
}
}
// DENDRON START
// const REF_LINK_REGEX = /^(\s*)\(\((?<ref>[^)]+)\)\)/;
// const refMatch = line.match(REF_LINK_REGEX);
// if (refMatch) {
// const fileContent = ParserUtilsV2.getRemark()
// .use(dendronNoteRefPlugin, {
// renderWithOutline: renderRefWithOutline,
// replaceRefOpts: {
// forNoteRefInPreview: true,
// },
// engine,
// })
// .processSync(line)
// .toString();
// let output2: string = fileContent;
// output2 = "\n" + output2 + " ";
// i = end + 1;
// lineNo = lineNo + 1;
// outputString = outputString + output2 + "\n";
// continue;
// }
// file import
const importMatch = line.match(/^(\s*)\@import(\s+)\"([^\"]+)\";?/);
Iif (importMatch) {
outputString += importMatch[1];
const filePath = importMatch[3].trim();
const leftParen = line.indexOf("{");
let config = null;
let configStr = "";
if (leftParen > 0) {
const rightParen = line.lastIndexOf("}");
if (rightParen > 0) {
configStr = line.substring(leftParen + 1, rightParen);
try {
config = parseAttributes(configStr);
} catch (error) {
// null
}
}
}
let absoluteFilePath;
if (filePath.match(protocolsWhiteListRegExp)) {
absoluteFilePath = filePath;
} else if (filePath.startsWith("/")) {
absoluteFilePath = path.resolve(projectDirectoryPath, "." + filePath);
} else {
absoluteFilePath = path.resolve(fileDirectoryPath, filePath);
}
const extname = path.extname(filePath).toLocaleLowerCase();
let output = "";
if (
[".jpeg", ".jpg", ".gif", ".png", ".apng", ".svg", ".bmp"].indexOf(
extname,
) >= 0
) {
// image
let imageSrc: string = filesCache[filePath];
if (!imageSrc) {
if (filePath.match(protocolsWhiteListRegExp)) {
imageSrc = filePath;
} else if (useRelativeFilePath) {
imageSrc =
path.relative(fileDirectoryPath, absoluteFilePath) +
"?" +
Math.random();
} else {
imageSrc =
"/" +
path.relative(projectDirectoryPath, absoluteFilePath) +
"?" +
Math.random();
}
// enchodeURI(imageSrc) is wrong. It will cause issue on Windows
// #414: https://github.com/shd101wyy/markdown-preview-enhanced/issues/414
imageSrc = imageSrc.replace(/ /g, "%20").replace(/\\/g, "/");
filesCache[filePath] = imageSrc;
}
if (config) {
if (
config["width"] ||
config["height"] ||
config["class"] ||
config["id"]
) {
output = `<img src="${imageSrc}" `;
for (const key in config) {
if (config.hasOwnProperty(key)) {
output += ` ${key}="${config[key]}" `;
}
}
output += ">";
} else {
output = "![";
if (config["alt"]) {
output += config["alt"];
}
output += `](${imageSrc}`;
if (config["title"]) {
output += ` "${config["title"]}"`;
}
output += ") ";
}
} else {
output = ` `;
}
// return helper(end+1, lineNo+1, outputString+output+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + output + "\n";
continue;
} else if (filePath === "[TOC]") {
if (!config) {
config = {
// same case as in normalized attributes
["depth_from"]: 1,
["depth_to"]: 6,
["ordered_list"]: true,
};
}
config["cmd"] = "toc";
config["hide"] = true;
config["run_on_save"] = true;
config["modify_source"] = true;
if (!notSourceFile) {
// mark code_chunk_offset
config["code_chunk_offset"] = codeChunkOffset;
codeChunkOffset++;
}
const output2 = `\`\`\`text ${stringifyAttributes(
config,
)} \n\`\`\` `;
// return helper(end+1, lineNo+1, outputString+output+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + output2 + "\n";
continue;
} else {
try {
let fileContent = await loadFile(
absoluteFilePath,
{ fileDirectoryPath, forPreview, imageDirectoryPath },
filesCache,
);
filesCache[absoluteFilePath] = fileContent;
if (config && (config["line_begin"] || config["line_end"])) {
const lines = fileContent.split(/\n/);
fileContent = lines
.slice(
parseInt(config["line_begin"], 10) || 0,
parseInt(config["line_end"], 10) || lines.length,
)
.join("\n");
}
if (config && config["code_block"]) {
const fileExtension = extname.slice(1, extname.length);
output = `\`\`\`${config["as"] ||
fileExtensionToLanguageMap[fileExtension] ||
fileExtension} ${stringifyAttributes(
config,
)} \n${fileContent}\n\`\`\` `;
} else if (config && config["cmd"]) {
if (!config["id"]) {
// create `id` for code chunk
config["id"] = computeChecksum(absoluteFilePath);
}
if (!notSourceFile) {
// mark code_chunk_offset
config["code_chunk_offset"] = codeChunkOffset;
codeChunkOffset++;
}
const fileExtension = extname.slice(1, extname.length);
output = `\`\`\`${config["as"] ||
fileExtensionToLanguageMap[fileExtension] ||
fileExtension} ${stringifyAttributes(
config,
)} \n${fileContent}\n\`\`\` `;
} else if ([".md", ".markdown", ".mmark"].indexOf(extname) >= 0) {
if (onWillTransformMarkdown) {
fileContent = await onWillTransformMarkdown(fileContent);
}
// markdown files
// this return here is necessary
let output2;
let headings2;
({
outputString: output2,
headings: headings2,
} = await transformMarkdown(fileContent, {
fileDirectoryPath: path.dirname(absoluteFilePath),
projectDirectoryPath,
filesCache,
useRelativeFilePath: false,
forPreview: false,
forMarkdownExport,
protocolsWhiteListRegExp,
notSourceFile: true, // <= this is not the sourcefile
imageDirectoryPath,
usePandocParser,
headingIdGenerator,
engine: this.engine,
}));
if (onDidTransformMarkdown) {
output2 = await onDidTransformMarkdown(output2);
}
output2 = "\n" + output2 + " ";
headings = headings.concat(headings2);
// return helper(end+1, lineNo+1, outputString+output+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + output2 + "\n";
continue;
} else if (extname === ".html") {
// html file
output = "<div>" + fileContent + "</div> ";
} else if (extname === ".csv") {
// csv file
const parseResult = Baby.parse(fileContent.trim());
if (parseResult.errors.length) {
output = `<pre>${parseResult.errors[0]}</pre> `;
} else {
// format csv to markdown table
output = twoDArrayToMarkdownTable(parseResult.data);
}
} else if (extname === ".css" || extname === ".js") {
if (!forPreview) {
// not for preview, so convert to corresponding HTML tag directly.
let sourcePath;
if (filePath.match(protocolsWhiteListRegExp)) {
sourcePath = filePath;
} else if (useRelativeFilePath) {
sourcePath = path.relative(
fileDirectoryPath,
absoluteFilePath,
);
} else {
sourcePath = "file:///" + absoluteFilePath;
}
if (extname === ".js") {
output = `<script type="text/javascript" src="${sourcePath}"></script>`;
} else {
output = `<link rel="stylesheet" href="${sourcePath}">`;
}
} else {
output = "";
}
JSAndCssFiles.push(filePath);
} else if (/*extname === '.css' || */ extname === ".less") {
// css or less file
output = `<style>${fileContent}</style>`;
} else if (extname === ".pdf") {
if (config && config["page_no"]) {
// only disply the nth page. 1-indexed
const pages = fileContent.split("\n");
let pageNo = parseInt(config["page_no"], 10) - 1;
if (pageNo < 0) {
pageNo = 0;
}
output = pages[pageNo] || "";
} else if (
config &&
(config["page_begin"] || config["page_end"])
) {
const pages = fileContent.split("\n");
let pageBegin = parseInt(config["page_begin"], 10) - 1 || 0;
const pageEnd = config["page_end"] || pages.length - 1;
if (pageBegin < 0) {
pageBegin = 0;
}
output = pages.slice(pageBegin, pageEnd).join("\n") || "";
} else {
output = fileContent;
}
} else if (
extname === ".dot" ||
extname === ".gv" ||
extname === ".viz"
) {
// graphviz
output = `\`\`\`dot ${stringifyAttributes(
config,
true,
)}\n${fileContent}\n\`\`\` `;
} else if (extname === ".mermaid") {
// mermaid
output = `\`\`\`mermaid ${stringifyAttributes(
config,
true,
)}\n${fileContent}\n\`\`\` `;
} else if (extname === ".plantuml" || extname === ".puml") {
// PlantUML
output = `\`\`\`puml ${stringifyAttributes(
config,
true,
)}\n' @mume_file_directory_path:${path.dirname(
absoluteFilePath,
)}\n${fileContent}\n\`\`\` `;
} else {
/*
else if extname in ['.wavedrom']
output = "```wavedrom\n${fileContent}\n``` "
# filesCache?[absoluteFilePath] = output
else if extname == '.js'
if forPreview
output = '' # js code is evaluated and there is no need to display the code.
else
if filePath.match(/^https?\:\/\//)
output = "<script src=\"${filePath}\"></script>"
else
output = "<script>${fileContent}</script>"
*/
// # codeblock
let aS = null;
if (config) {
aS = config["as"];
}
if (config && config["code_block"] === false) {
// https://github.com/shd101wyy/markdown-preview-enhanced/issues/916
output = fileContent;
} else {
const fileExtension = extname.slice(1, extname.length);
output = `\`\`\`${aS ||
fileExtensionToLanguageMap[fileExtension] ||
fileExtension} ${
config ? stringifyAttributes(config) : ""
} \n${fileContent}\n\`\`\` `;
}
}
// return helper(end+1, lineNo+1, outputString+output+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + output + "\n";
continue;
} catch (error) {
output = `<pre>${error.toString()}</pre> `;
// return helper(end+1, lineNo+1, outputString+output+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + output + "\n";
continue;
}
}
} else {
// return helper(end+1, lineNo+1, outputString+line+'\n')
i = end + 1;
lineNo = lineNo + 1;
outputString = outputString + line + "\n";
continue;
}
}
// done
return {
outputString,
slideConfigs,
tocBracketEnabled,
JSAndCssFiles,
headings,
frontMatterString,
};
}
let endFrontMatterOffset = 0;
Iif (
inputString.startsWith("---") &&
/* tslint:disable-next-line:no-conditional-assignment */
(endFrontMatterOffset = inputString.indexOf("\n---")) > 0
) {
frontMatterString = inputString.slice(0, endFrontMatterOffset + 4);
return await helper(
frontMatterString.length,
frontMatterString.match(/\n/g).length,
);
} else {
return await helper(0, 0);
}
}
|