Skip to content

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

:sparkles: Detect existing code block indentation before Tab operations https://github.com/siyuan-note/siyuan/issues/20061

Daniel68e8706bfb0d
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
index c0c27d9e1b..323ed7a95b 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100950-9op5xi1.sy
@@ -7,7 +7,7 @@
"id": "20200924100950-9op5xi1",
"title": "Shortcuts",
"type": "doc",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -4274,7 +4274,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210106154056-koo4wdj",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14261,7 +14261,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20250423105026-c1t0rqo",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14487,6 +14487,29 @@
}
]
},
+ {
+ "ID": "20261002230606-fd59093",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002230606-fd59093",
+ "updated": "20261002230606"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "When a code block has no individual "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Number of Tab Spaces"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " setting, indenting or outdenting detects consistent indentation from at least two nonblank lines and saves it for that block. Tabs or the smallest space indent of 2, 4, 6, or 8 spaces are recognized; other space indents must be multiples of that width. Mixed indentation or insufficient evidence falls back to the global setting. An explicit block setting takes precedence. Detection does not reformat existing code."
+ }
+ ]
+ },
{
"ID": "20260128161005-l4atyjc",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
index 418edbc24e..7648502d7d 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200813004551-gm0pbn1.sy
@@ -7,7 +7,7 @@
"id": "20200813004551-gm0pbn1",
"title": "快捷键",
"type": "doc",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -4272,7 +4272,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20201227133317-rkh4bji",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14343,7 +14343,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20250423104310-6605t5b",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14569,6 +14569,29 @@
}
]
},
+ {
+ "ID": "20261002230606-2186dda",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002230606-2186dda",
+ "updated": "20261002230606"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "代码块尚未单独设置 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Tab 空格数"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 时,执行缩进或反缩进会从至少两行非空代码中识别一致的缩进,并保存为该代码块的设置。支持识别制表符,或以 2、4、6、8 个空格为最小宽度且其他缩进为其整数倍的空格缩进。混合缩进或依据不足时沿用全局设置。显式块级设置优先。识别不会重新格式化已有代码。"
+ }
+ ]
+ },
{
"ID": "20260128160714-suekyvu",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
index c15f4f9eaf..e75d241a1e 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122549-jktxego.sy
@@ -7,7 +7,7 @@
"id": "20211226122549-jktxego",
"title": "快捷鍵",
"type": "doc",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -4266,7 +4266,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226122652-htptsmh",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14261,7 +14261,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20250423105322-jc65ji5",
- "updated": "20261002224733"
+ "updated": "20261002230606"
},
"Children": [
{
@@ -14487,6 +14487,29 @@
}
]
},
+ {
+ "ID": "20261002230606-18ff032",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002230606-18ff032",
+ "updated": "20261002230606"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "程式碼區塊尚未單獨設定 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Tab 空格數"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 時,執行縮排或反縮排會從至少兩行非空程式碼中辨識一致的縮排,並儲存為該區塊的設定。支援辨識定位字元,或以 2、4、6、8 個空格為最小寬度且其他縮排為其整數倍的空格縮排。混合縮排或依據不足時沿用全域設定。明確指定的區塊設定優先。辨識不會重新格式化既有程式碼。"
+ }
+ ]
+ },
{
"ID": "20260128160937-uvbwubc",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
index 383c0e4ee3..e5600689f0 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xsbxokr.sy
@@ -9,7 +9,7 @@
"id": "20240530101000-xsbxokr",
"title": "ショートカット",
"type": "doc",
- "updated": "20261002224733"
+ "updated": "20261002230607"
},
"Children": [
{
@@ -4228,7 +4228,7 @@
"Properties": {
"ID": "20240530101000-twmuxke",
"id": "20240530101000-675gu9g",
- "updated": "20261002224733"
+ "updated": "20261002230607"
},
"Children": [
{
@@ -14162,7 +14162,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20250423105545-q3l2fg0",
- "updated": "20261002224733"
+ "updated": "20261002230607"
},
"Children": [
{
@@ -14388,6 +14388,29 @@
}
]
},
+ {
+ "ID": "20261002230607-6fbe978",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261002230607-6fbe978",
+ "updated": "20261002230607"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "コードブロックに個別の "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Tab スペースの数"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " が設定されていない場合、インデントの追加・削除時に2行以上の空でないコードから一貫したインデントを検出し、そのブロックの設定として保存します。タブ、または最小幅が2・4・6・8個のスペースで、ほかのインデントもその幅の整数倍になっている場合に検出できます。タブとスペースが混在している場合や判定材料が不足している場合は、全体の設定を使います。明示的なブロック設定が優先されます。検出によって既存のコードが再整形されることはありません。"
+ }
+ ]
+ },
{
"ID": "20260128161450-iiz9i7p",
"Type": "NodeHeading",
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index 1f94bfda6b..1641b6c4bf 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -473,7 +473,7 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
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};")(
+ "\nreturn {captureRichCellSelection, captureRichCellSelectionAtPoint, restoreRichCellSelection, focusByOffset, getSelectionOffset, setLastNodeRange};")(
...Object.values(selectionDependencies)) as typeof import("./tableCellRichSelection") & typeof import("./selection");
const renderDependencies = {
isFoldedRenderContent: () => false,
@@ -489,6 +489,61 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
return {value: span.outerHTML};
},
}});
+ const indentDependencies = {...copyDependencies, ...selectionAPI};
+ const indentActions = new Function(...Object.keys(indentDependencies), copySource + "\nreturn {tabCodeBlock};")(
+ ...Object.values(indentDependencies)) as typeof import("../wysiwyg/codeBlock");
+ const indentationCases: Array<{text: string, global: number, override?: string, detected?: string, unit: string}> = [
+ {text: "if ready:\n work()\n nested()\n", global: 0, detected: "2", unit: " "},
+ {text: "if ready:\n work()\n", global: 2, detected: "4", unit: " "},
+ {text: "if ready:\n\twork()\n", global: 4, detected: "0", unit: "\t"},
+ {text: "if ready:\n work()\n", global: 4, override: "0", unit: "\t"},
+ {text: "if ready:\n work()\n", global: 0, override: "4", unit: " "},
+ {text: "if ready:\n work()\n\tnested()\n", global: 4, unit: " "},
+ {text: " work()\n", global: 0, unit: "\t"},
+ ];
+ for (const item of indentationCases) {
+ window.siyuan.config.editor.codeTabSpaces = item.global;
+ wysiwyg.innerHTML = base.Md2BlockDOM("```text\n" + item.text + "```");
+ const code = wysiwyg.firstElementChild as HTMLElement;
+ const editable = getContenteditableElement(code);
+ if (item.override !== undefined) {
+ code.setAttribute(codeTabAttribute, item.override);
+ }
+ const originalHTML = code.outerHTML;
+ check.equal(editable.textContent, item.text, "loading pasted code preserves its whitespace");
+ const range = selectionAPI.focusByOffset(editable, 0, item.text.length - 1, false);
+ check.ok(range);
+ indentActions.tabCodeBlock(protyle as unknown as IProtyle, code, range);
+ const indented = item.text.slice(0, -1).split("\n").map(line => item.unit + line).join("\n") + "\n";
+ check.equal(editable.textContent, indented);
+ check.equal(code.getAttribute(codeTabAttribute), item.override ?? item.detected ?? null);
+ check.equal(calls.transaction.oldHTML, originalHTML, "undo restores both the text and the inherited setting");
+ api.updateTableCellEditingValue(settingCell, api.serializeTableCellRich(code.outerHTML));
+ const reopened = document.createElement("div");
+ reopened.innerHTML = api.getTableCellRichBlockDOM(settingCell);
+ check.equal(reopened.firstElementChild.getAttribute(codeTabAttribute), item.override ?? item.detected ?? null);
+ check.equal(getContenteditableElement(reopened).textContent, indented);
+ indentActions.tabCodeBlock(protyle as unknown as IProtyle, code, range, true);
+ check.equal(editable.textContent, item.text, "outdent uses the saved width and reverses the preceding indent");
+ }
+ window.siyuan.config.editor.codeTabSpaces = 0;
+ wysiwyg.innerHTML = base.Md2BlockDOM("```text\nif ready:\n work()\n```");
+ const outdentCode = wysiwyg.firstElementChild as HTMLElement;
+ const outdentEditable = getContenteditableElement(outdentCode);
+ const unchangedHTML = outdentCode.outerHTML;
+ const unchangedRange = selectionAPI.focusByOffset(outdentEditable, 0, 0, false);
+ check.ok(unchangedRange);
+ indentActions.tabCodeBlock(protyle as unknown as IProtyle, outdentCode, unchangedRange, true);
+ check.equal(outdentCode.outerHTML, unchangedHTML, "a no-op does not persist an inferred setting");
+ const outdentRange = selectionAPI.focusByOffset(outdentEditable, 12, 12, false);
+ check.ok(outdentRange);
+ indentActions.tabCodeBlock(protyle as unknown as IProtyle, outdentCode, outdentRange, true);
+ check.equal(outdentEditable.textContent, "if ready:\nwork()\n");
+ check.equal(outdentCode.getAttribute(codeTabAttribute), "2");
+ check.equal(calls.transaction.oldHTML, unchangedHTML);
+ indentActions.tabCodeBlock(protyle as unknown as IProtyle, outdentCode, outdentRange);
+ check.equal(outdentEditable.textContent, "if ready:\n work()\n", "indent retains the detected width after the last indent was removed");
+ window.siyuan.config.editor.codeTabSpaces = 4;
const body = "4441231234444\n\n\n123555555\n22\n\n123\n";
wysiwyg.innerHTML = base.Md2BlockDOM("sdf\n\n```java\n" + body + "```");
const codeEdit = wysiwyg.querySelector<HTMLElement>('.hljs [contenteditable="true"]');
diff --git a/app/src/protyle/wysiwyg/codeBlock.ts b/app/src/protyle/wysiwyg/codeBlock.ts
index 08525e1d3e..c2201c2536 100644
--- a/app/src/protyle/wysiwyg/codeBlock.ts
+++ b/app/src/protyle/wysiwyg/codeBlock.ts
@@ -3,6 +3,7 @@ import {focusByOffset, getSelectionOffset, getUndoFocusContext, setLastNodeRange
import {updateTransaction} from "./transaction";
import {Constants} from "../../constants";
import {
+ detectCodeTabSpaces,
getCodeBlockOutdentRange,
getCodeBlockLineRange,
getCodeTabSpace,
@@ -22,8 +23,17 @@ export const tabCodeBlock = (protyle: IProtyle, nodeElement: HTMLElement,
return;
}
const undoFocusContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);
- const tabSpace = getCodeBlockTabSpace(nodeElement);
+ const detectedSpaces = nodeElement.hasAttribute(Constants.CUSTOM_SY_CODE_TAB_SPACES) ? null :
+ detectCodeTabSpaces(editableElement.textContent);
+ const tabSpace = detectedSpaces === null ? getCodeBlockTabSpace(nodeElement) : getCodeTabSpace(detectedSpaces);
const oldHTML = nodeElement.outerHTML;
+ const commit = () => {
+ // 识别结果随缩进操作一同保存和撤销,后续操作沿用该代码块的设置。
+ if (detectedSpaces !== null) {
+ nodeElement.setAttribute(Constants.CUSTOM_SY_CODE_TAB_SPACES, detectedSpaces.toString());
+ }
+ updateTransaction(protyle, nodeElement, oldHTML, undoFocusContext);
+ };
if (range.collapsed) {
if (outdent) {
const caret = getSelectionOffset(editableElement, undefined, range).start;
@@ -48,7 +58,7 @@ export const tabCodeBlock = (protyle: IProtyle, nodeElement: HTMLElement,
range.setStartAfter(textNode);
range.collapse(true);
}
- updateTransaction(protyle, nodeElement, oldHTML, undoFocusContext);
+ commit();
return;
}
@@ -94,6 +104,6 @@ export const tabCodeBlock = (protyle: IProtyle, nodeElement: HTMLElement,
const brElement = wbrElement.parentElement.querySelector("br");
setLastNodeRange(brElement.previousSibling as Element, range, false);
brElement.remove();
- updateTransaction(protyle, nodeElement, oldHTML, undoFocusContext);
+ commit();
wbrElement.remove();
};
diff --git a/app/src/protyle/wysiwyg/codeBlockUtil.test.ts b/app/src/protyle/wysiwyg/codeBlockUtil.test.ts
index 3473931ddc..3461ed319d 100644
--- a/app/src/protyle/wysiwyg/codeBlockUtil.test.ts
+++ b/app/src/protyle/wysiwyg/codeBlockUtil.test.ts
@@ -1,6 +1,7 @@
import * as assert from "node:assert/strict";
import test from "node:test";
import {
+ detectCodeTabSpaces,
getCodeBlockOutdentRange,
getCodeBlockLineRange,
getCodeTabSpace,
@@ -19,6 +20,32 @@ test("code block Tab spaces inherit the global value unless explicitly overridde
assert.equal(getCodeTabSpace(4), " ");
});
+test("code block indentation detection recognizes consistent tabs and supported space widths", () => {
+ for (const spaces of [2, 4, 6, 8]) {
+ const indent = " ".repeat(spaces);
+ assert.equal(detectCodeTabSpaces(`root\n${indent}child\n${indent}${indent}nested\nend`), spaces);
+ assert.equal(detectCodeTabSpaces(`${indent}child\n${indent}${indent}nested`), spaces);
+ }
+ assert.equal(detectCodeTabSpaces("root\n\tchild\n\t\tnested\nend"), 0);
+ assert.equal(detectCodeTabSpaces("root\n \t \n child\n\t\n nested"), 2);
+});
+
+test("code block indentation detection declines mixed, inconsistent and insufficient samples", () => {
+ for (const text of ["", "\n \t\n", "root\nend", " child\n", "\tchild",
+ "root\n \tchild", "root\n\t child", "root\n child\n\tnested", "root\n\tchild\n nested",
+ "root\n child\n aligned", "root\n child\n nested", "root\n child"]) {
+ assert.equal(detectCodeTabSpaces(text), null, JSON.stringify(text));
+ }
+});
+
+test("detected indentation preserves pasted code levels and whitespace during explicit operations", () => {
+ const text = "if ready:\n if enabled:\n run( value)\n";
+ const tabSpace = getCodeTabSpace(detectCodeTabSpaces(text));
+ const selected = " if enabled:\n run( value)";
+ assert.equal(updateCodeBlockLines(selected, tabSpace), " if enabled:\n run( value)");
+ assert.equal(updateCodeBlockLines(selected, tabSpace, true), "if enabled:\n run( value)");
+});
+
test("code block selections start at the first touched line and exclude a trailing line start", () => {
const text = "first\nsecond\nthird\n";
assert.deepEqual(getCodeBlockLineRange(text, 2, 10), {start: 0, end: 10});
diff --git a/app/src/protyle/wysiwyg/codeBlockUtil.ts b/app/src/protyle/wysiwyg/codeBlockUtil.ts
index ee02932229..80878df8b5 100644
--- a/app/src/protyle/wysiwyg/codeBlockUtil.ts
+++ b/app/src/protyle/wysiwyg/codeBlockUtil.ts
@@ -9,6 +9,42 @@ export const resolveCodeTabSpaces = (attributeValue: string | null, globalValue:
export const getCodeTabSpace = (spaces: number) => spaces === 0 ? "\t" : "".padStart(spaces, " ");
+export const detectCodeTabSpaces = (text: string): number | null => {
+ const spaceIndents: number[] = [];
+ let hasTabs = false;
+ let lineCount = 0;
+ for (const line of text.split("\n")) {
+ if (!line.trim()) {
+ continue;
+ }
+ lineCount++;
+ const indent = line.match(/^[ \t]+/)?.[0];
+ if (!indent) {
+ continue;
+ }
+ if (indent.includes("\t")) {
+ if (indent.includes(" ") || spaceIndents.length > 0) {
+ return null;
+ }
+ hasTabs = true;
+ } else {
+ if (hasTabs) {
+ return null;
+ }
+ spaceIndents.push(indent.length);
+ }
+ }
+ if (lineCount < 2) {
+ return null;
+ }
+ if (hasTabs) {
+ return 0;
+ }
+ // 仅采用受支持的最小空格缩进,且其他缩进必须是它的整数倍。
+ const spaces = spaceIndents.reduce((minimum, value) => Math.min(minimum, value), Infinity);
+ return CODE_TAB_SPACE_VALUES.includes(spaces) && spaceIndents.every(value => value % spaces === 0) ? spaces : null;
+};
+
export const getCodeBlockLineRange = (text: string, start: number, end: number) => {
const rangeStart = Math.min(Math.max(start, 0), text.length);
const rangeEnd = Math.min(Math.max(end, rangeStart), text.length);