Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support code block Tab spacing in table cells and mind maps https://github.com/siyuan-note/siyuan/issues/19717

Daniel3879ec476600
diff --git a/app/src/protyle/lite/codeActions.ts b/app/src/protyle/lite/codeActions.ts
index b565134cce..1a77ec2a48 100644
--- a/app/src/protyle/lite/codeActions.ts
+++ b/app/src/protyle/lite/codeActions.ts
@@ -1,13 +1,35 @@
import {MenuItem} from "../../menus/Menu";
+import {Constants} from "../../constants";
import {showMessage} from "../../dialog/message";
import {isMobile} from "../../util/functions";
import {highlightRender} from "../render/highlightRender";
import {writeText} from "../util/compatibility";
import {nbsp2space, removeZWJ} from "../util/normalizeText";
+import {CODE_TAB_SPACE_VALUES} from "../wysiwyg/codeBlockUtil";
export const getLiteCodeMenuItems = (node: Element, update: (attribute: string, value: string) => void): IMenu[] => {
const editor = window.siyuan.config.editor;
- return [
+ const codeTabSpaces = node.getAttribute(Constants.CUSTOM_SY_CODE_TAB_SPACES);
+ const tabSpaces: IMenu = {
+ id: "md29",
+ iconHTML: "",
+ label: window.siyuan.languages.md29,
+ type: "submenu",
+ submenu: [{
+ id: "default",
+ iconHTML: "",
+ label: `${window.siyuan.languages.default} (${editor.codeTabSpaces})`,
+ checked: codeTabSpaces === null,
+ click: () => update(Constants.CUSTOM_SY_CODE_TAB_SPACES, ""),
+ }, ...CODE_TAB_SPACE_VALUES.map(value => ({
+ id: `tabSpaces${value}`,
+ iconHTML: "",
+ label: value.toString(),
+ checked: codeTabSpaces === value.toString(),
+ click: () => update(Constants.CUSTOM_SY_CODE_TAB_SPACES, value.toString()),
+ }))],
+ };
+ return [tabSpaces, ...[
{attribute: "linewrap", label: "md31", fallback: editor.codeLineWrap},
{attribute: "ligatures", label: "md2", fallback: editor.codeLigatures},
{attribute: "linenumber", label: "md27", fallback: editor.codeSyntaxHighlightLineNum},
@@ -16,11 +38,12 @@ export const getLiteCodeMenuItems = (node: Element, update: (attribute: string,
const checked = value === "true" || (value !== "false" && fallback);
return {
id: label,
+ iconHTML: "",
label: window.siyuan.languages[label],
checked,
click: () => update(attribute, String(!checked)),
};
- });
+ })];
};
export const bindLiteCodeActions = (host: HTMLElement, protyle: IProtyle, options: {
@@ -55,7 +78,11 @@ export const bindLiteCodeActions = (host: HTMLElement, protyle: IProtyle, option
return;
}
options.beforeChange?.();
- code.setAttribute(attribute, value);
+ if (value === "") {
+ code.removeAttribute(attribute);
+ } else {
+ code.setAttribute(attribute, value);
+ }
// 属性变化不会触发片段的正文观察器,需显式交由宿主事务保存。
options.onChange();
content.removeAttribute("data-render");
diff --git a/app/src/protyle/render/av/richText.ts b/app/src/protyle/render/av/richText.ts
index 9a5417ec98..4a633241eb 100644
--- a/app/src/protyle/render/av/richText.ts
+++ b/app/src/protyle/render/av/richText.ts
@@ -1,4 +1,6 @@
import {escapeHtml} from "../../../util/escape";
+import {Constants} from "../../../constants";
+import {CODE_TAB_SPACE_VALUES} from "../../wysiwyg/codeBlockUtil";
import {highlightRender} from "../highlightRender";
import {getAgentLute} from "../setLute";
import {restoreInlineElementBoundaries} from "../../util/inlineElementBoundary";
@@ -99,8 +101,12 @@ const replaceWithText = (element: Element) => {
element.replaceWith(document.createTextNode(element.textContent || ""));
};
-const removeUnsupportedBlockAttributes = (element: HTMLElement) => {
+const removeUnsupportedBlockAttributes = (element: HTMLElement, codeSettings: boolean) => {
Array.from(element.attributes).forEach((attribute) => {
+ if (codeSettings && element.dataset.type === "NodeCodeBlock" &&
+ attribute.name === Constants.CUSTOM_SY_CODE_TAB_SPACES) {
+ return;
+ }
if (attribute.name.startsWith("custom-") || attribute.name === "bookmark" ||
attribute.name === "memo" || attribute.name === "name" || attribute.name === "style") {
element.removeAttribute(attribute.name);
@@ -154,7 +160,7 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) =>
if (type === "NodeHeading") {
element.className = element.dataset.subtype;
}
- removeUnsupportedBlockAttributes(element);
+ removeUnsupportedBlockAttributes(element, images);
});
template.content.querySelectorAll(
(images ? "" : ".img, img, ") +
@@ -193,7 +199,9 @@ export const sanitizeAVRichTextBlockDOM = (blockDOM: string, images = false) =>
const imageAttribute = images && ["src", "data-src", "alt", "title", "loading"].includes(name) &&
(element.tagName === "IMG" || element.classList.contains("img"));
const codeAttribute = images && element.dataset.type === "NodeCodeBlock" &&
- ["linewrap", "ligatures", "linenumber"].includes(name) && ["true", "false"].includes(attribute.value);
+ (["linewrap", "ligatures", "linenumber"].includes(name) && ["true", "false"].includes(attribute.value) ||
+ name === Constants.CUSTOM_SY_CODE_TAB_SPACES &&
+ CODE_TAB_SPACE_VALUES.some(value => value.toString() === attribute.value));
if ((!AV_RICH_TEXT_EDITOR_ALLOWED_ATTRIBUTES.includes(name) && !imageAttribute && !codeAttribute) ||
name === "xlink:href" && !attribute.value.startsWith("#icon")) {
element.removeAttribute(attribute.name);
@@ -337,7 +345,7 @@ export const serializeAVRichTextBlockDOM = (blockDOM: string, lute = getAVRichTe
const singleEmptyParagraph = template.content.children.length === 1 &&
template.content.firstElementChild === paragraphs[0] && hasEmptyParagraph;
const hasCodeSettings = images && !!template.content.querySelector(
- '[data-type="NodeCodeBlock"]:is([linewrap], [ligatures], [linenumber])');
+ `[data-type="NodeCodeBlock"]:is([linewrap], [ligatures], [linenumber], [${Constants.CUSTOM_SY_CODE_TAB_SPACES}])`);
// 空段落和代码设置依靠块属性列表保留,同时保留相邻块的标识,避免属性被合并到前一段。
if ((hasEmptyParagraph && !singleEmptyParagraph) || hasCodeSettings) {
cleanBlockDOM = cleanAVRichTextBlockDOMStructure(sanitizedBlockDOM, true);
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index a2a2fb014a..23535ed3d6 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -136,7 +136,8 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
formula.setAttribute("data-render", "true");
});
}, {TIMEOUT_DBLCLICK: 190, CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap",
- CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data", CUSTOM_SY_MINDMAP_CODE: "custom-sy-mindmap-code"}, () => {});
+ CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data", CUSTOM_SY_MINDMAP_CODE: "custom-sy-mindmap-code",
+ CUSTOM_SY_CODE_TAB_SPACES: "custom-sy-code-tab-spaces"}, () => {});
const lute = Lute.New();
lute.SetKramdownIAL(true);
lute.SetProtyleWYSIWYG(true);
@@ -387,7 +388,9 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
check.ok(settingCode);
const codeSettingID = settingCode.dataset.nodeId;
const oldCodeSettings = codeSettingList.outerHTML;
- for (const [name, value] of [["linewrap", "false"], ["ligatures", "true"], ["linenumber", "false"]]) {
+ const codeSettings = [["linewrap", "false"], ["ligatures", "true"], ["linenumber", "false"],
+ ["custom-sy-code-tab-spaces", "2"]];
+ for (const [name, value] of codeSettings) {
settingCode.setAttribute(name, value);
}
check.equal(api.replaceListMindmapContent(codeSettingList, codeSettingNode.id,
@@ -398,11 +401,24 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
roundTrip.innerHTML = lute.Md2BlockDOM(lute.BlockDOM2Md(html));
const restoredCode = roundTrip.querySelector(`[data-node-id="${codeSettingID}"]`);
check.ok(restoredCode, "code settings keep the source block identity");
- for (const [name, value] of [["linewrap", "false"], ["ligatures", "true"], ["linenumber", "false"]]) {
+ for (const [name, value] of codeSettings) {
check.equal(restoredCode.getAttribute(name), html === oldCodeSettings ? null : value,
"source snapshots restore code settings through undo and redo");
}
}
+ settingCode.removeAttribute("custom-sy-code-tab-spaces");
+ check.equal(api.replaceListMindmapContent(codeSettingList, codeSettingNode.id,
+ codeSettingBlocks.map(block => block.outerHTML).join("")), true);
+ const resetCodeSettings = codeSettingList.outerHTML;
+ const resetCodeHolder = document.createElement("div");
+ resetCodeHolder.innerHTML = lute.Md2BlockDOM(lute.BlockDOM2Md(resetCodeSettings));
+ check.equal(resetCodeHolder.querySelector(`[data-node-id="${codeSettingID}"]`)
+ .hasAttribute("custom-sy-code-tab-spaces"), false, "default Tab spacing removes the saved override");
+ for (const html of [newCodeSettings, resetCodeSettings]) {
+ resetCodeHolder.innerHTML = lute.Md2BlockDOM(lute.BlockDOM2Md(html));
+ check.equal(resetCodeHolder.querySelector(`[data-node-id="${codeSettingID}"]`)
+ .getAttribute("custom-sy-code-tab-spaces"), html === newCodeSettings ? "2" : null);
+ }
const nestedTaskHolder = document.createElement("div");
lute.SetDataTask(true);
nestedTaskHolder.innerHTML = lute.Md2BlockDOM("- Node\n\n > - [ ] Nested task\n");
diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.ts
index b20ecb8587..9cbaab9573 100644
--- a/app/src/protyle/render/listMindmap/model.ts
+++ b/app/src/protyle/render/listMindmap/model.ts
@@ -562,7 +562,8 @@ export const replaceListMindmapContent = (list: HTMLElement, nodeId: string, blo
if (original) {
Array.from(original.attributes).forEach(attribute => {
if (!block.hasAttribute(attribute.name) &&
- !["data-type", "data-subtype", "class", "updated", "contenteditable", "data-task", "data-marker", "fold"]
+ !["data-type", "data-subtype", "class", "updated", "contenteditable", "data-task", "data-marker", "fold",
+ Constants.CUSTOM_SY_CODE_TAB_SPACES]
.includes(attribute.name) &&
!attribute.name.startsWith("data-list-mindmap-")) {
block.setAttribute(attribute.name, attribute.value);
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index 727ee96398..fbf5b11df3 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -10,9 +10,12 @@ import {createSourceFile, isClassDeclaration, isMethodDeclaration, ScriptTarget,
const browserCases = async (source: string, enterSource: string, hintSource: string, keydownSource: string,
copySource: string, selectionSource: string, highlightSource: string) => {
const check: typeof assert = require("node:assert/strict");
- const api = new Function(source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
+ const codeTabAttribute = "custom-sy-code-tab-spaces";
+ const api = new Function("Constants", source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +
- "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM};")() as
+ "updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM};")({
+ CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute,
+ }) as
typeof import("../render/setLute") & typeof import("../render/av/richTextValue") &
typeof import("./tableCellRichLute") & typeof import("../wysiwyg/codeBlockEnter") &
typeof import("./tableCellRich") & typeof import("../render/av/richText");
@@ -254,7 +257,7 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
const copied: string[] = [];
let messages = 0;
let bubbled = 0;
- Object.assign(window.siyuan, {languages: {copied: "Copied"}});
+ Object.assign(window.siyuan, {languages: {copied: "Copied", default: "Default"}});
const copyController = new AbortController();
let canEditCode = true;
let menuItems: IMenu[] = [];
@@ -270,6 +273,8 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
}}});
const copyDependencies = {
host, fragment, signal: copyController.signal,
+ Constants: {...constants, CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute},
+ getContenteditableElement, getUndoFocusContext: () => ({}), updateTransaction,
canEdit: () => canEditCode,
beforeChange: () => { oldCode = api.serializeTableCellRich(wysiwyg.innerHTML); },
commit: () => {
@@ -288,7 +293,9 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
messages++;
},
};
- new Function(...Object.keys(copyDependencies), copySource)(...Object.values(copyDependencies));
+ const codeActions = new Function(...Object.keys(copyDependencies), copySource +
+ "\nreturn {getCodeBlockTabSpace, tabCodeBlock};")(...Object.values(copyDependencies)) as
+ typeof import("../wysiwyg/codeBlock");
fixture.addEventListener("click", () => bubbled++);
for (const text of ["", "a\u00a0b\n <tag> & value\n\n", "\u200D```\n"]) {
wysiwyg.innerHTML = base.Md2BlockDOM("```js\nplaceholder\n```");
@@ -304,15 +311,16 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
check.equal(copied.length, 6);
check.equal(messages, 6);
check.equal(bubbled, 0, "copy stays inside the cell editor");
- Object.assign(window.siyuan.config.editor, {codeLineWrap: true, codeLigatures: false, codeSyntaxHighlightLineNum: true});
+ Object.assign(window.siyuan.config.editor,
+ {codeLineWrap: true, codeLigatures: false, codeSyntaxHighlightLineNum: true, codeTabSpaces: 4});
const settingsBody = "a | b\n\n<test> & c\n";
wysiwyg.innerHTML = base.Md2BlockDOM("```js\n" + settingsBody + "```");
const defaults = [true, false, true];
for (const [index, attribute] of ["linewrap", "ligatures", "linenumber"].entries()) {
wysiwyg.querySelector(".protyle-action__menu use").dispatchEvent(new MouseEvent("click", {bubbles: true}));
- check.equal(menuItems.length, 3);
- check.equal(menuItems[index].checked, defaults[index]);
- menuItems[index].click(document.createElement("button"), new MouseEvent("click"));
+ check.equal(menuItems.length, 4);
+ check.equal(menuItems[index + 1].checked, defaults[index]);
+ menuItems[index + 1].click(document.createElement("button"), new MouseEvent("click"));
wysiwyg.innerHTML = api.getTableCellRichBlockDOM(settingCell);
check.equal(wysiwyg.firstElementChild.getAttribute(attribute), String(!defaults[index]));
check.equal(wysiwyg.querySelector('.hljs [contenteditable="true"]').textContent, settingsBody);
@@ -327,27 +335,67 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
check.equal(api.getTableCellRichBlockDOM(settingCell), wysiwyg.innerHTML);
}
check.equal(updates, 3, "each setting explicitly commits through the host");
+ wysiwyg.innerHTML = base.Md2BlockDOM("```js\n" + settingsBody + "```");
+ for (const value of [0, 2, 4, 6, 8, null]) {
+ const previousValue = wysiwyg.firstElementChild.getAttribute(codeTabAttribute);
+ wysiwyg.querySelector(".protyle-action__menu").dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ const tabItems = menuItems.find(item => item.id === "md29").submenu;
+ check.deepEqual(tabItems.map(item => item.label), ["Default (4)", "0", "2", "4", "6", "8"]);
+ check.equal(tabItems.filter(item => item.checked).length, 1);
+ const option = tabItems.find(item => item.id === (value === null ? "default" : `tabSpaces${value}`));
+ option.click(document.createElement("button"), new MouseEvent("click"));
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ const code = wysiwyg.firstElementChild as HTMLElement;
+ check.equal(code.getAttribute(codeTabAttribute), value === null ? null : value.toString());
+ check.equal(code.querySelector('.hljs [contenteditable="true"]').textContent, settingsBody);
+ const expectedIndent = value === 0 ? "\t" : " ".repeat(value ?? 4);
+ check.equal(codeActions.getCodeBlockTabSpace(code), expectedIndent);
+ const redo = settingCell.getAttribute("data-sy-table-cell-rich");
+ api.updateTableCellEditingValue(settingCell, oldCode);
+ const undoHolder = document.createElement("div");
+ undoHolder.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ check.equal(undoHolder.firstElementChild.getAttribute(codeTabAttribute), previousValue);
+ settingCell.setAttribute("data-sy-table-cell-rich", redo);
+ const range = document.createRange();
+ range.setStart(code.querySelector('.hljs [contenteditable="true"]').firstChild, 0);
+ range.collapse(true);
+ codeActions.tabCodeBlock(protyle as unknown as IProtyle, code, range);
+ check.equal(code.querySelector('.hljs [contenteditable="true"]').textContent, expectedIndent + settingsBody);
+ wysiwyg.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ }
+ const editableUpdates = updates;
+ const editableMenus = menuShown;
canEditCode = false;
wysiwyg.querySelector(".protyle-action__menu").dispatchEvent(new MouseEvent("click", {bubbles: true}));
- check.equal(menuShown, 3, "read-only editors cannot open the settings menu");
- menuItems[0].click(document.createElement("button"), new MouseEvent("click"));
- check.equal(updates, 3, "stale menu callbacks cannot change a read-only editor");
+ check.equal(menuShown, editableMenus, "read-only editors cannot open the settings menu");
+ menuItems[1].click(document.createElement("button"), new MouseEvent("click"));
+ menuItems[0].submenu[1].click(document.createElement("button"), new MouseEvent("click"));
+ check.equal(updates, editableUpdates, "stale menu callbacks cannot change a read-only editor");
canEditCode = true;
mobileCodeMenu = true;
wysiwyg.querySelector(".protyle-action__menu").dispatchEvent(new MouseEvent("click", {bubbles: true}));
check.equal(mobileMenuShown, 1, "mobile opens the fullscreen menu");
- check.equal(menuShown, 3);
+ check.equal(menuShown, editableMenus);
wysiwyg.firstElementChild.setAttribute("linewrap", "invalid");
const cleanCode = document.createElement("div");
cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML, true);
check.equal(cleanCode.firstElementChild.hasAttribute("linewrap"), false);
cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML);
check.equal(cleanCode.firstElementChild.hasAttribute("ligatures"), false);
+ for (const value of ["", "3", "-2", "10", "02", "2.0", "true"]) {
+ wysiwyg.firstElementChild.setAttribute(codeTabAttribute, value);
+ cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML, true);
+ check.equal(cleanCode.firstElementChild.hasAttribute(codeTabAttribute), false);
+ }
+ wysiwyg.firstElementChild.setAttribute(codeTabAttribute, "2");
+ cleanCode.innerHTML = api.sanitizeAVRichTextBlockDOM(wysiwyg.innerHTML);
+ check.equal(cleanCode.firstElementChild.hasAttribute(codeTabAttribute), false);
copyController.abort();
wysiwyg.querySelector(".protyle-action__copy").dispatchEvent(new MouseEvent("click", {bubbles: true}));
check.equal(copied.length, 6, "closing the editor removes the copy handler");
- menuItems[0].click(document.createElement("button"), new MouseEvent("click"));
- check.equal(updates, 3, "closing the editor invalidates menu callbacks");
+ menuItems[1].click(document.createElement("button"), new MouseEvent("click"));
+ menuItems[0].submenu[1].click(document.createElement("button"), new MouseEvent("click"));
+ check.equal(updates, editableUpdates, "closing the editor invalidates menu callbacks");
const selectionDependencies = {getContenteditableElement, isNotEditBlock: () => false, revealTabsForTarget: () => {}};
const selectionAPI = new Function(...Object.keys(selectionDependencies), selectionSource +
"\nreturn {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection, focusByOffset, getSelectionOffset};")(
@@ -444,7 +492,7 @@ test("table cells insert code through slash and Enter without losing soft breaks
.replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
const read = (file: string) => readFileSync(path.join(__dirname, file), "utf8");
const source = ["longTextWrap.ts", "inlineElementBoundary.ts", "../toolbar/fontFamilyCore.ts", "../../util/escape.ts",
- "../render/setLute.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts",
+ "../render/setLute.ts", "../wysiwyg/codeBlockUtil.ts", "../render/av/richTextValue.ts", "../render/av/richText.ts",
"../wysiwyg/taskListMarker.ts", "../wysiwyg/codeBlockEnter.ts", "tableCellRichLute.ts", "tableCellRichValue.ts",
"tableCellRich.ts"].map(file => compile(read(file))).join("\n");
const hint = createSourceFile("hint.ts", read("../hint/index.ts"), ScriptTarget.Latest, true);
@@ -455,7 +503,8 @@ test("table cells insert code through slash and Enter without losing soft breaks
const start = editor.indexOf('host.addEventListener("keydown", event => {');
const end = editor.indexOf("}, {capture: true, signal});", start) + "}, {capture: true, signal});".length;
const keydownSource = compile(editor.substring(start, end));
- const copySource = compile(read("normalizeText.ts")) + "\n" + compile(read("../lite/codeActions.ts")) +
+ const copySource = ["normalizeText.ts", "../wysiwyg/codeBlockUtil.ts", "../wysiwyg/codeBlock.ts", "../lite/codeActions.ts"]
+ .map(file => compile(read(file))).join("\n") +
"\nbindLiteCodeActions(host, fragment.protyle, {signal, canEdit, beforeChange, onChange: commit});";
const selectionSource = compile(read("selection.ts")) + "\n" + compile(read("tableCellRichSelection.ts"));
const highlightSource = compile(read("../render/highlightRender.ts"));
diff --git a/kernel/av/table_cell_rich_test.go b/kernel/av/table_cell_rich_test.go
index 187cb5199b..e125526991 100644
--- a/kernel/av/table_cell_rich_test.go
+++ b/kernel/av/table_cell_rich_test.go
@@ -8,8 +8,12 @@ import (
)
func TestTableCellRichCodeSettings(t *testing.T) {
- for _, attribute := range []string{"linewrap", "linenumber", "ligatures"} {
- for _, value := range []string{"true", "false"} {
+ for _, attribute := range []string{"linewrap", "linenumber", "ligatures", "custom-sy-code-tab-spaces"} {
+ values := []string{"true", "false"}
+ if attribute == "custom-sy-code-tab-spaces" {
+ values = []string{"0", "2", "4", "6", "8"}
+ }
+ for _, value := range values {
t.Run(attribute+"/"+value, func(t *testing.T) {
source := "before\n\n```go\na | b\n```\n{: id=\"20260921000000-code001\" " + attribute + "=\"" + value + "\"}\n\nafter"
rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
@@ -40,7 +44,7 @@ func TestTableCellRichCodeSettings(t *testing.T) {
}
func TestTableCellRichRejectsInvalidCodeSettings(t *testing.T) {
- for _, source := range []string{
+ sources := []string{
"```go\ncode\n```\n{: id=\"20260921000000-code001\" linewrap=\"invalid\"}",
"```go\ncode\n```\n{: id=\"20260921000000-code001\" ligatures=\"TRUE\"}",
"```go\ncode\n```\n{: id=\"20260921000000-code001\" linenumber=\"1\"}",
@@ -48,7 +52,12 @@ func TestTableCellRichRejectsInvalidCodeSettings(t *testing.T) {
"paragraph\n{: id=\"20260921000000-code001\" linewrap=\"true\"}",
"# heading\n{: id=\"20260921000000-code001\" linenumber=\"false\"}",
"```mermaid\ngraph TD\n```\n{: id=\"20260921000000-code001\" linewrap=\"true\"}",
- } {
+ "paragraph\n{: id=\"20260921000000-code001\" custom-sy-code-tab-spaces=\"2\"}",
+ }
+ for _, value := range []string{"", "3", "-2", "10", "02", "2.0", "true"} {
+ sources = append(sources, "```go\ncode\n```\n{: id=\"20260921000000-code001\" custom-sy-code-tab-spaces=\""+value+"\"}")
+ }
+ for _, source := range sources {
rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}
if _, err := ParseTableCellRich(rich); err == nil {
t.Fatalf("accepted unsupported code attributes: %s", source)
diff --git a/kernel/av/value.go b/kernel/av/value.go
index d981260a0b..f42de3fb15 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -1334,6 +1334,16 @@ func isAllowedValueTextRichBlockIAL(node *ast.Node, codeSettings bool) bool {
("true" != attr[1] && "false" != attr[1]) || node.Previous.IALAttr(attr[0]) != attr[1] {
return false
}
+ case "custom-sy-code-tab-spaces":
+ if !codeSettings || nil == node.Previous || ast.NodeCodeBlock != node.Previous.Type ||
+ node.Previous.IALAttr(attr[0]) != attr[1] {
+ return false
+ }
+ switch attr[1] {
+ case "0", "2", "4", "6", "8":
+ default:
+ return false
+ }
default:
return false
}
@@ -1420,7 +1430,8 @@ func valueTextRichBlockDOM2Kramdown(luteEngine *lute.Lute, blockDOM string) stri
return ast.WalkContinue
}
if ast.NodeParagraph == node.Type && !singleEmptyParagraph && "" == strings.TrimSpace(strings.ReplaceAll(node.Content(), "\u200b", "")) ||
- ast.NodeCodeBlock == node.Type && ("" != node.IALAttr("linewrap") || "" != node.IALAttr("ligatures") || "" != node.IALAttr("linenumber")) {
+ ast.NodeCodeBlock == node.Type && ("" != node.IALAttr("linewrap") || "" != node.IALAttr("ligatures") ||
+ "" != node.IALAttr("linenumber") || "" != node.IALAttr("custom-sy-code-tab-spaces")) {
preserveBlockIDs = true
return ast.WalkStop
}
diff --git a/kernel/model/table_cell_rich_fts5_test.go b/kernel/model/table_cell_rich_fts5_test.go
index 1b62e96c91..a77283eddd 100644
--- a/kernel/model/table_cell_rich_fts5_test.go
+++ b/kernel/model/table_cell_rich_fts5_test.go
@@ -34,7 +34,7 @@ func TestTableCellRichCodeSettingsTransactions(t *testing.T) {
t.Fatal(err)
}
treenode.UpsertBlockTree(tree)
- const settings = plain + "\n" + `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`
+ const settings = plain + "\n" + `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false" custom-sy-code-tab-spaces="2"}`
for index, source := range []string{settings, plain, settings} {
updated := parse.Parse("", []byte("| Header |\n| --- |\n| code |"), luteEngine.ParseOptions)
updatedTable := updated.Root.FirstChild
diff --git a/kernel/model/table_cell_rich_test.go b/kernel/model/table_cell_rich_test.go
index 005bc47d77..f06c0b14cd 100644
--- a/kernel/model/table_cell_rich_test.go
+++ b/kernel/model/table_cell_rich_test.go
@@ -39,7 +39,8 @@ func TestTableCellRichDocumentReaders(t *testing.T) {
}
source := "- **first**\n- second\n\n```go\na | b\nc\n```"
for _, source := range []string{source, source + "\n" +
- `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`} {
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`,
+ source + "\n" + `{: id="20260921000000-code001" custom-sy-code-tab-spaces="2"}`} {
for name, read := range readers {
t.Run(name, func(t *testing.T) {
tree, err := read(legacy)
@@ -81,7 +82,7 @@ func TestTableCellRichDocumentReaders(t *testing.T) {
func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
luteEngine := util.NewLute()
source := "- **first**\n- second\n\n```go\na | b\nc\n```\n" +
- `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}` +
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false" custom-sy-code-tab-spaces="2"}` +
"\n\n![image](assets/original.png)"
tree := parse.Parse("", []byte("| Header |\n| --- |\n| value |"), luteEngine.ParseOptions)
cell := tree.Root.FirstChild.LastChild.FirstChild
@@ -102,7 +103,8 @@ func TestTableCellRichHTMLAndMarkdownExports(t *testing.T) {
t.Fatal(err)
}
codes := cell.ChildrenByType(ast.NodeCodeBlock)
- if len(codes) != 1 || codes[0].IALAttr("linewrap") != "false" || codes[0].IALAttr("linenumber") != "true" || codes[0].IALAttr("ligatures") != "false" {
+ if len(codes) != 1 || codes[0].IALAttr("linewrap") != "false" || codes[0].IALAttr("linenumber") != "true" ||
+ codes[0].IALAttr("ligatures") != "false" || codes[0].IALAttr("custom-sy-code-tab-spaces") != "2" {
t.Fatal("export materialization lost code settings")
}
ast.Walk(cell, func(node *ast.Node, entering bool) ast.WalkStatus {
diff --git a/kernel/treenode/table_cell_rich_test.go b/kernel/treenode/table_cell_rich_test.go
index c267aa95c6..9d91f0d8b6 100644
--- a/kernel/treenode/table_cell_rich_test.go
+++ b/kernel/treenode/table_cell_rich_test.go
@@ -65,7 +65,7 @@ func TestTableCellRichSourceProjectionAndSpec(t *testing.T) {
func TestTableCellRichSynchronizesAssetReferenceAndText(t *testing.T) {
tree, cell := richTableTree(t, "![image](assets/old.png) ((20240101000000-abcdefg 'reference')) text\n\n```go\nold\n```\n"+
- `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false"}`)
+ `{: id="20260921000000-code001" linewrap="false" linenumber="true" ligatures="false" custom-sy-code-tab-spaces="2"}`)
ast.Walk(cell, func(node *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
@@ -85,7 +85,7 @@ func TestTableCellRichSynchronizesAssetReferenceAndText(t *testing.T) {
t.Fatal(err)
}
for _, expected := range []string{"assets/new.png", "20240102000000-abcdefg", "<new> & value",
- `linewrap="false"`, `linenumber="true"`, `ligatures="false"`} {
+ `linewrap="false"`, `linenumber="true"`, `ligatures="false"`, `custom-sy-code-tab-spaces="2"`} {
if !strings.Contains(cell.TableCellRich.Content, expected) {
t.Fatalf("source does not contain %q: %s", expected, cell.TableCellRich.Content)
}