import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable.ts"; import { plainInlineMarkdown } from "../workspace/noteHtml.ts"; export type CellPoint = { row: number; column: number }; export type CellRange = { anchor: CellPoint; head: CellPoint }; export type CellFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear"; export function bounds(range: CellRange) { return { top: Math.min(range.anchor.row, range.head.row), bottom: Math.max(range.anchor.row, range.head.row), left: Math.min(range.anchor.column, range.head.column), right: Math.max(range.anchor.column, range.head.column) }; } const sourceRow = (row: number) => row === 0 ? 0 : row + 1; export function mapTableCells(source: string, range: CellRange, transform: (text: string) => string): string { const table = parseMarkdownTable(source); if (!table) return source; const { top, bottom, left, right } = bounds(range); for (let r = Math.max(0, top); r <= Math.min(bottom, table.rows.length - 2); r++) { for (let c = Math.max(0, left); c <= Math.min(right, table.columns - 1); c++) { source = replaceTableCell(source, sourceRow(r), c, transform(table.rows[sourceRow(r)].cells[c]?.text || "")); } } return source; } export function formatTableCells(source: string, range: CellRange, format: CellFormat): string { if (format === "clear") return mapTableCells(source, range, plainInlineMarkdown); const marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format]; const wrapped = (text: string) => format === "code" ? /^(`+)(?!`)([\s\S]*[^`])\1(?!`)$/.test(text) : text.startsWith(marker) && text.endsWith(marker) && text.length > marker.length * 2 && !(format === "italic" && text.startsWith("**") && !text.startsWith("***")); let allWrapped = true; mapTableCells(source, range, text => { if (text.trim() && !wrapped(text)) allWrapped = false; return text; }); return mapTableCells(source, range, text => { if (!text.trim()) return text; if (wrapped(text)) return allWrapped ? (format === "code" ? plainInlineMarkdown(text) : text.slice(marker.length, -marker.length)) : text; if (format === "code") { const fence = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(m => m[0].length)) + 1); return `${fence} ${text} ${fence}`; } return marker + text + marker; }); } export function alignTableCells(source: string, range: CellRange, alignment: "left" | "center" | "right"): string { const table = parseMarkdownTable(source); if (!table) return source; const { left, right } = bounds(range); const marker = { left: ":---", center: ":---:", right: "---:" }[alignment]; for (let c = Math.min(right, table.columns - 1); c >= Math.max(0, left); c--) { const cell = table.rows[1].cells[c]; source = source.slice(0, cell.from) + marker + source.slice(cell.to); } return source; } export function copyTableCells(source: string, range: CellRange): string { const table = parseMarkdownTable(source); if (!table) return ""; const { top, bottom, left, right } = bounds(range); const quote = (value: string) => /[\t\r\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value; return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n"); } export function copyTableMarkdown(source: string, range: CellRange): string { const table = parseMarkdownTable(source); if (!table) return ""; const { top, bottom, left, right } = bounds(range); const rows = Array.from({ length: bottom - top + 1 }, (_, r) => `| ${Array.from({ length: right - left + 1 }, (_, c) => table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "").join(" | ")} |`); rows.splice(1, 0, `| ${Array.from({ length: right - left + 1 }, () => "---").join(" | ")} |`); return rows.join("\n"); } // Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table. export function clipboardCells(text: string): string[][] { const table = parseMarkdownTable(text); if (table) return table.rows.filter((_, i) => i !== 1).map(row => row.cells.map(cell => cell.text)); const rows: string[][] = [[]]; let cell = "", quoted = false; text = text.replace(/\r\n?/g, "\n").replace(/\n$/, ""); for (let i = 0; i < text.length; i++) { const char = text[i]; if (char === '"' && (quoted || !cell)) { if (quoted && text[i + 1] === '"') { cell += '"'; i++; } else quoted = !quoted; } else if (!quoted && (char === "\t" || char === "\n")) { rows.at(-1)!.push(cell); cell = ""; if (char === "\n") rows.push([]); } else cell += char; } rows.at(-1)!.push(cell); return rows.map(row => row.map(value => value.replace(/\n/g, "
").replace(/(\\*)\|/g, (match, slashes: string) => slashes.length % 2 ? match : `${slashes}\\|`))); } export function pasteTableCells(source: string, range: CellRange, text: string): string { if (!parseMarkdownTable(source)) return source; const cells = clipboardCells(text), { top, bottom, left, right } = bounds(range); if (cells.length === 1 && cells[0].length === 1) return mapTableCells(source, range, () => cells[0][0]); const gridWidth = Math.max(...cells.map(row => row.length)); const height = Math.max(bottom - top + 1, cells.length), width = Math.max(right - left + 1, gridWidth); while (parseMarkdownTable(source)!.columns < left + width) source = appendTableColumn(source); while (parseMarkdownTable(source)!.rows.length - 1 < top + height) source = appendTableRow(source); for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) { source = replaceTableCell(source, sourceRow(top + r), left + c, cells[r % cells.length][c % gridWidth] ?? ""); } return source; } // Whole rows/columns are removed structurally; a partial rectangle shifts cells left. export function deleteTableCells(source: string, range: CellRange): string { const table = parseMarkdownTable(source); if (!table) return source; const { top, bottom, left, right } = bounds(range); const allRows = top === 0 && bottom >= table.rows.length - 2; const allColumns = left === 0 && right >= table.columns - 1; if (allRows && allColumns) return source.slice(table.end); const rows = table.rows.flatMap((row, i) => { const r = i === 0 ? 0 : i - 1; if (allColumns && i !== 1 && r >= top && r <= bottom) return []; const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || ""); if (allRows || (i !== 1 && r >= top && r <= bottom)) { cells.splice(left, right - left + 1); if (!allRows) while (cells.length < table.columns) cells.push(""); } return [{ ...row, cells }]; }); // Deleting the header promotes the first remaining body row. if (allColumns && top === 0) [rows[0], rows[1]] = [rows[1], rows[0]]; return rows.map(row => `${row.indent}| ${row.cells.join(" | ")} |`).join(table.eol) + source.slice(table.end); }