import { tr } from "../i18n/index.ts";
import MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
import { inlineMathEnd } from "./inlineMath.ts";
import { activeTableFormulas } from "../formulas/index.ts";
import { hasTableDelimiter } from "../editor/markdownTable.ts";
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
markdown.use(footnotes);
export const escapeHtml = markdown.utils.escapeHtml;
// Require a row delimiter so deleting a blank line cannot turn prose into cells.
// Markdown-it checks blockquote terminators while it reads a table body.
markdown.block.ruler.before("table", "table_prose_boundary", (state, line, _end, silent) => {
return silent && state.parentType === "table" &&
!hasTableDelimiter(state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]));
}, { alt: ["blockquote"] });
// Inline note formats also round-trip through the table cell editor.
markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => {
const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos));
if (!marker) return false;
let end = state.pos + marker.length;
if (marker === "$") {
end = inlineMathEnd(state.src, state.pos, state.posMax);
if (end < 0) return false;
} else {
for (; end < state.posMax; end++) {
if (state.src[end] === "\\") { end++; continue; }
if (state.src.startsWith(marker, end)) break;
}
}
if (end >= state.posMax || end === state.pos + marker.length) return false;
if (!silent) {
const kind = marker === "==" ? "highlight" : marker === "$" ? "math" : "comment";
const token = state.push(`note_${kind}`, "", 0);
token.content = state.src.slice(state.pos + marker.length, end);
}
state.pos = end + marker.length;
return true;
});
for (const kind of ["highlight", "math", "comment"]) {
markdown.renderer.rules[`note_${kind}`] = (tokens, index, _options, env) => {
const content = tokens[index].content;
return kind === "highlight" ? `${markdown.renderInline(content, env)}` : `${escapeHtml(content)}`;
};
}
export function plainInlineMarkdown(source: string): string {
const literal = (text: string) => text.replace(/&/g, "&").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`);
function plain(tokens: Token[]): string {
return tokens.map(token => {
if (token.type === "note_highlight") return plain(markdown.parseInline(token.content, {}));
if (token.type === "hardbreak" || token.type === "softbreak") return "
";
if (token.type === "image") {
const target = String(token.attrGet("src") || "");
const label = plain(token.children || []);
return token.attrGet("data-md-kind") === "wiki" ? `![[${literal(target)}\\|${label}]]` : `.replace(/>/g, "%3E")}>)`;
}
if (token.children) return plain(token.children);
return token.nesting === 0 ? literal(token.content) : "";
}).join("");
}
return plain(markdown.parseInline(source, {}));
}
// Obsidian-style table cells use
for line breaks. Recognize only this
// attribute-free tag; arbitrary HTML remains escaped, including inside cells.
markdown.inline.ruler.before("html_inline", "note_line_break", (state, silent) => {
const match = /^
/i.exec(state.src.slice(state.pos));
if (!match) return false;
if (!silent) state.push("hardbreak", "br", 0);
state.pos += match[0].length;
return true;
});
const copyIcon = '';
// Parse wiki links as inline tokens, so code spans and fenced code stay literal.
markdown.inline.ruler.before("link", "wiki_link", (state, silent) => {
const match = /^(!?)\[\[([^\]\n]+)\]\]/.exec(state.src.slice(state.pos));
if (!match) return false;
const [target, ...alias] = match[2].split("|");
const label = alias.join("|") || target;
if (!target.trim() || !markdown.validateLink(target)) return false;
if (!silent) {
if (match[1]) {
const image = state.push("image", "img", 0);
image.attrs = [["src", target.trim()], ["alt", label], ["data-md-kind", "wiki"]];
image.content = label;
const text = new MarkdownIt.Token("text", "", 0);
text.content = label;
image.children = [text];
} else {
const open = state.push("link_open", "a", 1);
open.attrs = [["href", target.trim()], ["data-kind", "wiki"], ["class", "wiki"]];
state.push("text", "", 0).content = label;
state.push("link_close", "a", -1);
}
}
state.pos += match[0].length;
return true;
});
markdown.core.ruler.after("inline", "note_blocks", state => {
for (let i = 0; i < state.tokens.length; i++) {
const token = state.tokens[i];
if (token.type !== "inline" || !token.children?.length) continue;
const first = token.children[0];
if (first.type !== "text") continue;
const item = state.tokens[i - 2];
const task = /^\[([ xX])\]\s+/.exec(first.content);
if (task && item?.type === "list_item_open") {
const checked = task[1].toLowerCase() === "x";
item.attrJoin("class", `task-list-item${checked ? " is-checked" : ""}`);
first.content = first.content.slice(task[0].length);
const checkbox = new MarkdownIt.Token("html_inline", "", 0);
checkbox.content = ` `;
token.children.unshift(checkbox);
for (let parent = i - 3; parent >= 0; parent--) {
const ancestor = state.tokens[parent];
if ((ancestor.type === "bullet_list_open" || ancestor.type === "ordered_list_open") && ancestor.level < item.level) {
ancestor.attrJoin("class", "contains-task-list");
break;
}
}
}
const callout = /^\[!(note|tip|info|warning|danger|important|success|question)\][+-]?(?:[ \t]+([^\n]*))?(?:\n|$)/i.exec(first.content);
if (callout && item?.type === "blockquote_open") {
item.attrJoin("class", "md-callout");
item.attrSet("data-callout", callout[1].toLowerCase());
const title = callout[2] || callout[1].charAt(0).toUpperCase() + callout[1].slice(1).toLowerCase();
first.content = first.content.slice(callout[0].length);
if (!first.content && token.children[1]?.type === "softbreak") token.children.splice(1, 1);
const heading = new MarkdownIt.Token("html_inline", "", 0);
heading.content = `${escapeHtml(title)}`;
token.children.unshift(heading);
}
}
});
markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => {
if (!tokens[index].attrGet("data-kind")) tokens[index].attrSet("data-kind", "md");
return renderer.renderToken(tokens, index, options);
};
markdown.renderer.rules.fence = (tokens, index) => {
const token = tokens[index];
const language = token.info.trim().split(/\s+/)[0];
const code = `
${escapeHtml(token.content)}\n`;
return language.toLowerCase() === "mermaid"
? `${escapeHtml(properties)}${escapeHtml(properties)}