An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Support auto-closing [[ and completing block references by typing ]] https://github.com/siyuan-note/siyuan/issues/20524
Nathan Kbf047f9f59c7
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 8574aab077..a75abfb562 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "إغلاق <code class='fn__code'>[[</code> تلقائيًا",+ "autoCloseRefBracketsTip": "عند الكتابة [[ يُضاف ]] تلقائيًا، وكتابة ]] تُكمل المرجع إلى المستند الذي يطابق عنوانه تمامًا أو تُنشئ مستندًا جديدًا","exitWaiting": "جارٍ الخروج، يُرجى الانتظار...","exitWaitFailed": "تعذّر التأكد من اكتمال الإغلاق. يمكنك إعادة المحاولة أو إغلاق مربع الحوار هذا ومتابعة الانتظار.","previousExitWaiting": "في انتظار اكتمال الإغلاق السابق...",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 95c2169078..e0f8aa6522 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> automatisch schließen",+ "autoCloseRefBracketsTip": "Beim Tippen von [[ wird ]] automatisch eingefügt; die Eingabe von ]] vervollständigt den Verweis auf das Dokument mit exakt passendem Titel oder erstellt ein neues Dokument","exitWaiting": "Wird beendet, bitte warten...","exitWaitFailed": "Der Abschluss des Beendens konnte nicht bestätigt werden. Versuchen Sie es erneut oder schließen Sie diesen Dialog und warten Sie weiter.","previousExitWaiting": "Warten, bis der vorherige Beendigungsvorgang abgeschlossen ist...",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex c42154b5a4..1111e2819b 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Auto-close <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Typing [[ automatically inserts ]]; typing ]] completes the reference to the document with an exactly matching title, or creates a new document","exitWaiting": "Exiting, please wait...","exitWaitFailed": "Could not confirm that shutdown has completed. You can retry or close this dialog and continue waiting.","previousExitWaiting": "Waiting for the previous shutdown to finish...",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 61137c3d22..2e1165e8b8 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Cerrar <code class='fn__code'>[[</code> automáticamente",+ "autoCloseRefBracketsTip": "Al escribir [[ se inserta ]] automáticamente; al escribir ]] se completa la referencia al documento cuyo título coincide exactamente o se crea un documento nuevo","exitWaiting": "Saliendo, espere...","exitWaitFailed": "No se pudo confirmar que el cierre haya terminado. Puede reintentar o cerrar este diálogo y seguir esperando.","previousExitWaiting": "Esperando a que termine el cierre anterior...",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex fd7520dd0b..f641a7e0a8 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Fermeture automatique de <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Saisir [[ insère automatiquement ]] ; saisir ]] complète la référence vers le document dont le titre correspond exactement ou crée un nouveau document","exitWaiting": "Fermeture en cours, veuillez patienter...","exitWaitFailed": "Impossible de confirmer la fin de la fermeture. Vous pouvez réessayer ou fermer cette boîte de dialogue et continuer à patienter.","previousExitWaiting": "En attente de la fin de la fermeture précédente...",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 43df98e469..8efd5f8949 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "סגירה אוטומטית של <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "הקלדת [[ מוסיפה ]] אוטומטית; הקלדת ]] משלימה את ההפניה למסמך שכותרתו תואמת בדיוק, או יוצרת מסמך חדש","exitWaiting": "היישום נסגר, נא להמתין...","exitWaitFailed": "לא ניתן לאשר שהסגירה הושלמה. אפשר לנסות שוב או לסגור את תיבת הדו־שיח ולהמשיך להמתין.","previousExitWaiting": "ממתין להשלמת הסגירה הקודמת...",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex b765fbcb86..54b91652ca 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> स्वतः बंद करें",+ "autoCloseRefBracketsTip": "[[ टाइप करने पर ]] स्वतः जुड़ जाता है; ]] टाइप करने पर बिल्कुल मेल खाते शीर्षक वाले दस्तावेज़ का संदर्भ पूरा होता है या नया दस्तावेज़ बनता है","exitWaiting": "बंद किया जा रहा है, कृपया प्रतीक्षा करें...","exitWaitFailed": "बंद होने की प्रक्रिया पूरी होने की पुष्टि नहीं हो सकी। आप फिर से कोशिश कर सकते हैं या इस संवाद को बंद करके प्रतीक्षा जारी रख सकते हैं।","previousExitWaiting": "पिछली बंद होने की प्रक्रिया पूरी होने की प्रतीक्षा की जा रही है...",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex d8db03db34..58e945bd11 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Tutup <code class='fn__code'>[[</code> otomatis",+ "autoCloseRefBracketsTip": "Mengetik [[ otomatis menyisipkan ]]; mengetik ]] melengkapi referensi ke dokumen dengan judul yang sama persis, atau membuat dokumen baru","exitWaiting": "Menutup aplikasi, harap tunggu...","exitWaitFailed": "Tidak dapat memastikan bahwa proses penutupan telah selesai. Anda dapat mencoba lagi atau menutup dialog ini dan terus menunggu.","previousExitWaiting": "Menunggu proses penutupan sebelumnya selesai...",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 5f3d36cf7e..11615798d8 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Chiusura automatica di <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Digitando [[ viene inserito automaticamente ]]; digitando ]] si completa il riferimento al documento con titolo identico oppure si crea un nuovo documento","exitWaiting": "Chiusura in corso, attendere...","exitWaitFailed": "Impossibile confermare il completamento della chiusura. Puoi riprovare oppure chiudere questa finestra di dialogo e continuare ad attendere.","previousExitWaiting": "In attesa del completamento della chiusura precedente...",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 9e6f1f8609..1068a55c8a 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> を自動で閉じる",+ "autoCloseRefBracketsTip": "[[ を入力すると ]] を自動挿入し、]] を入力するとタイトルが完全一致するドキュメントへの参照を完成させるか、新しいドキュメントを作成します","exitWaiting": "終了しています。お待ちください...","exitWaitFailed": "終了が完了したか確認できませんでした。再試行するか、このダイアログを閉じてお待ちください。","previousExitWaiting": "前回の終了処理が完了するのを待っています...",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 644d3154ed..94e4605cb5 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> 자동 닫기",+ "autoCloseRefBracketsTip": "[[ 입력 시 ]]가 자동으로 삽입되며, ]] 입력 시 제목이 정확히 일치하는 문서로 참조를 완성하거나 새 문서를 만듭니다","exitWaiting": "종료 중입니다. 잠시 기다려 주세요...","exitWaitFailed": "종료 완료 여부를 확인할 수 없습니다. 다시 시도하거나 이 대화 상자를 닫고 계속 기다려 주세요.","previousExitWaiting": "이전 종료 작업이 완료되기를 기다리는 중...",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 8eee85a4e6..52e4650d4e 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> automatisch sluiten",+ "autoCloseRefBracketsTip": "Bij het typen van [[ wordt ]] automatisch ingevoegd; het typen van ]] voltooit de verwijzing naar het document met exact dezelfde titel of maakt een nieuw document aan","exitWaiting": "Afsluiten, even geduld...","exitWaitFailed": "Het is niet bevestigd dat het afsluiten is voltooid. Probeer het opnieuw of sluit dit dialoogvenster en blijf wachten.","previousExitWaiting": "Wachten tot het vorige afsluitproces is voltooid...",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 95adfd52c4..8979ceafb8 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Automatyczne zamykanie <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Wpisanie [[ automatycznie dodaje ]]; wpisanie ]] kończy odwołanie do dokumentu o dokładnie pasującym tytule lub tworzy nowy dokument","exitWaiting": "Zamykanie, proszę czekać...","exitWaitFailed": "Nie można potwierdzić zakończenia zamykania. Możesz spróbować ponownie lub zamknąć to okno dialogowe i nadal czekać.","previousExitWaiting": "Oczekiwanie na zakończenie poprzedniego zamykania...",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 069293beca..0692e8bd6b 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Fechar <code class='fn__code'>[[</code> automaticamente",+ "autoCloseRefBracketsTip": "Digitar [[ insere ]] automaticamente; digitar ]] completa a referência ao documento com título exatamente igual ou cria um novo documento","exitWaiting": "Encerrando, aguarde...","exitWaitFailed": "Não foi possível confirmar a conclusão do encerramento. Você pode tentar novamente ou fechar esta caixa de diálogo e continuar aguardando.","previousExitWaiting": "Aguardando a conclusão do encerramento anterior...",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex e340b838ab..5723bae85e 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Автозакрытие <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "При вводе [[ автоматически добавляется ]]; ввод ]] завершает ссылку на документ с точно совпадающим заголовком или создаёт новый документ","exitWaiting": "Завершение работы, подождите...","exitWaitFailed": "Не удалось подтвердить завершение работы. Повторите попытку или закройте это диалоговое окно и продолжайте ждать.","previousExitWaiting": "Ожидание завершения предыдущего сеанса...",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 09f5842af7..79ee17e1d4 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Automaticky uzavrieť <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Pri písaní [[ sa automaticky vloží ]]; napísanie ]] dokončí odkaz na dokument s presne zhodným názvom alebo vytvorí nový dokument","exitWaiting": "Ukončovanie, čakajte...","exitWaitFailed": "Nepodarilo sa potvrdiť dokončenie ukončovania. Môžete to skúsiť znova alebo zavrieť toto dialógové okno a ďalej čakať.","previousExitWaiting": "Čaká sa na dokončenie predchádzajúceho ukončovania...",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 8aae5f416f..c2911e9139 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Аутоматски затвори <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Куцање [[ аутоматски додаје ]]; куцање ]] довршава референцу на документ са тачно истим насловом или прави нови документ","exitWaiting": "Затварање, сачекајте...","exitWaitFailed": "Није могуће потврдити да је затварање завршено. Покушајте поново или затворите овај дијалог и наставите да чекате.","previousExitWaiting": "Чека се завршетак претходног затварања...",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 12495902a7..93b8e32723 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "ปิด <code class='fn__code'>[[</code> อัตโนมัติ",+ "autoCloseRefBracketsTip": "เมื่อพิมพ์ [[ จะเติม ]] ให้อัตโนมัติ และเมื่อพิมพ์ ]] จะอ้างอิงเอกสารที่ชื่อตรงกันทุกตัวอักษร หรือสร้างเอกสารใหม่","exitWaiting": "กำลังออกจากแอป โปรดรอสักครู่...","exitWaitFailed": "ไม่สามารถยืนยันได้ว่าการปิดเสร็จสิ้นแล้ว คุณสามารถลองอีกครั้ง หรือปิดกล่องโต้ตอบนี้แล้วรอต่อไปได้","previousExitWaiting": "กำลังรอให้การปิดครั้งก่อนเสร็จสิ้น...",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 1eb72e8897..fd5149a137 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> otomatik kapat",+ "autoCloseRefBracketsTip": "[[ yazıldığında ]] otomatik eklenir; ]] yazmak, başlığı tam olarak eşleşen belgeye başvuruyu tamamlar veya yeni bir belge oluşturur","exitWaiting": "Kapatılıyor, lütfen bekleyin...","exitWaitFailed": "Kapanmanın tamamlandığı doğrulanamadı. Yeniden deneyebilir veya bu iletişim kutusunu kapatıp beklemeye devam edebilirsiniz.","previousExitWaiting": "Önceki kapanma işleminin tamamlanması bekleniyor...",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex d42ce67912..182f08a966 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Автозакриття <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Під час введення [[ автоматично додається ]]; введення ]] завершує посилання на документ із точно збіжною назвою або створює новий документ","exitWaiting": "Завершення роботи, зачекайте...","exitWaitFailed": "Не вдалося підтвердити завершення роботи. Повторіть спробу або закрийте це діалогове вікно й продовжуйте чекати.","previousExitWaiting": "Очікування завершення попереднього сеансу...",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 8de38e34e7..d85274f776 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "自动闭合 <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "输入 [[ 时自动补全 ]],输入 ]] 时引用标题完全一致的文档,没有则新建文档","exitWaiting": "正在退出,请稍候...","exitWaitFailed": "暂时无法确认退出是否完成。可以重试,或关闭此提示继续等待。","previousExitWaiting": "正在等待上次退出完成...",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex ec362a40be..9ddd2fac58 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "自動閉合 <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "輸入 [[ 時自動補上 ]],輸入 ]] 時引用標題完全相同的文件,沒有則新建文件","exitWaiting": "正在退出,請稍候...","exitWaitFailed": "暫時無法確認是否已結束。可以重試,或關閉此提示繼續等待。","previousExitWaiting": "正在等待上次結束作業完成...",diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.tsindex ebd5025590..ddb13d066d 100644--- a/app/src/config/tabs/editorTab.ts+++ b/app/src/config/tabs/editorTab.ts@@ -284,6 +284,10 @@ const registerEditorBidirectionalGroup = (tab: SettingTabBuilder) => {title: window.siyuan.languages.onlySearchForDoc,desc: window.siyuan.languages.onlySearchForDocTip,});+ group.switch("editor.autoCloseRefBrackets", {+ title: window.siyuan.languages.autoCloseRefBrackets,+ desc: window.siyuan.languages.autoCloseRefBracketsTip,+ });group.number("editor.blockRefDynamicAnchorTextMaxLen", {title: window.siyuan.languages.md37,desc: window.siyuan.languages.md38,diff --git a/app/src/protyle/hint/blockHintRange.test.ts b/app/src/protyle/hint/blockHintRange.test.tsindex 99de06bf9b..9a040e9e63 100644--- a/app/src/protyle/hint/blockHintRange.test.ts+++ b/app/src/protyle/hint/blockHintRange.test.ts@@ -2,10 +2,13 @@ import {describe, it} from "node:test";import * as assert from "node:assert/strict";import {endsWithMultiCharHintPrefix,+ findExactDocTitleIndex,getBlockHintTriggerOffset,getBlockRefStaticText,isBlockHintQueryAtCaret,+ shouldAutoCloseRefBrackets,shouldCaptureHintUndoFocus,+ shouldDeleteRefBracketPair,shouldIgnoreHintTrigger,stripBlockHintCloseKey,} from "./blockHintRange";@@ -158,3 +161,33 @@ describe("endsWithMultiCharHintPrefix", () => {assert.equal(endsWithMultiCharHintPrefix("2", hintKeys), false);});});++describe("auto-closing reference brackets", () => {+ it("inserts closing brackets only right after a new [[", () => {+ assert.equal(shouldAutoCloseRefBrackets("note [[", ""), true);+ assert.equal(shouldAutoCloseRefBrackets("[[", " tail"), true);+ assert.equal(shouldAutoCloseRefBrackets("[[", "]]"), false);+ assert.equal(shouldAutoCloseRefBrackets("[", ""), false);+ assert.equal(shouldAutoCloseRefBrackets("[[Title", ""), false);+ });++ it("deletes the paired bracket only between empty brackets", () => {+ assert.equal(shouldDeleteRefBracketPair("[[", "]]"), true);+ assert.equal(shouldDeleteRefBracketPair("[", "]"), true);+ assert.equal(shouldDeleteRefBracketPair("[[Title", "]]"), false);+ assert.equal(shouldDeleteRefBracketPair("[[", "text"), false);+ });++ it("prefers an exact document title, then a case-insensitive one", () => {+ const items = [+ {type: "NodeParagraph", titles: ["Roam"]},+ {type: "NodeDocument", titles: ["roam"]},+ {type: "NodeDocument", titles: ["Roam"]},+ ];+ assert.equal(findExactDocTitleIndex(items, "Roam"), 2);+ assert.equal(findExactDocTitleIndex(items, "ROAM"), 1);+ assert.equal(findExactDocTitleIndex(items, " Roam "), 2);+ assert.equal(findExactDocTitleIndex(items, "Roam Research"), -1);+ assert.equal(findExactDocTitleIndex(items, ""), -1);+ });+});diff --git a/app/src/protyle/hint/blockHintRange.ts b/app/src/protyle/hint/blockHintRange.tsindex c4f476b575..d0118c2422 100644--- a/app/src/protyle/hint/blockHintRange.ts+++ b/app/src/protyle/hint/blockHintRange.ts@@ -18,6 +18,31 @@ export const isBlockHintQueryAtCaret = (textBeforeCaret: string, textAfterCaret:return query.trimStart() === query && query.length < maxLength;};+// 自动闭合:光标前刚输入 [[ 且光标后没有闭合符时补全 ]]+export const shouldAutoCloseRefBrackets = (textBeforeCaret: string, textAfterCaret: string) => {+ return textBeforeCaret.endsWith("[[") && !textAfterCaret.startsWith("]");+};++// 自动闭合:在空括号对之间退格时一并删除光标后的 ]+export const shouldDeleteRefBracketPair = (textBeforeCaret: string, textAfterCaret: string) => {+ return textBeforeCaret.endsWith("[") && textAfterCaret.startsWith("]");+};++// 输入 ]] 完成引用时,优先匹配标题完全一致的文档,其次忽略大小写匹配+export const findExactDocTitleIndex = (items: { type: string, titles: string[] }[], key: string) => {+ const title = key.trim();+ if (!title) {+ return -1;+ }+ const index = items.findIndex((item) => item.type === "NodeDocument" && item.titles.includes(title));+ if (index > -1) {+ return index;+ }+ const lowerTitle = title.toLowerCase();+ return items.findIndex((item) => item.type === "NodeDocument" &&+ item.titles.some((itemTitle) => itemTitle.toLowerCase() === lowerTitle));+};+// 手动输入的闭合标记(如 [[标题]] 中的 ]])不属于查询内容,选中候选项时随触发符一起被替换export const stripBlockHintCloseKey = (query: string, endSplit: string) => {return endSplit && query.endsWith(endSplit) ? query.substring(0, query.length - endSplit.length) : query;diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 34f18b32be..c750e430e4 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -57,6 +57,7 @@ import {import {countBlockWord} from "../../layout/status";import {genTemplateDocTreePlanHTML} from "../../template/docTree";import {getDailyNoteHints} from "./dailyNote";+import {findExactDocTitleIndex} from "./blockHintRange";const slashBuiltinStyleIDs: Partial<Record<string, TBuiltinInlineStyleID>> = {infoStyle: "info",@@ -610,6 +611,9 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHif (protyle.lite && isEncryptedBox(protyle.notebookId)) {refParam.notebook = protyle.notebookId;}+ // 自动闭合时输入 ]] 直接完成引用+ const commitOnClose = source === "hint" && !protyle.lite && protyle.hint.splitChar === "[[" && key.trim() !== "" &&+ protyle.hint.closeKeyTyped && window.siyuan.config.editor?.autoCloseRefBrackets;const dailyNotes = source === "hint" ? getDailyNoteHints(key, protyle).catch((): IHintData[] => []) : Promise.resolve([] as IHintData[]);fetchPost("/api/search/searchRefBlock", refParam, (response) => {Promise.all([createTarget.promise, dailyNotes]).then(([hideConfiguredCreate, dateHints]) => {@@ -660,6 +664,20 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHhtml: genHintItemHTML(item),});});+ if (commitOnClose) {+ // 依次选择标题完全一致的文档、日记、新建文档+ const exactIndex = findExactDocTitleIndex(response.data.blocks.map((item: IBlock) => ({+ type: item.type,+ titles: [item.refText, item.content].filter(Boolean).map((title) =>+ Lute.UnEscapeHTMLStr(stripSearchMark(title)).replaceAll(Constants.ZWSP, "")),+ })), key);+ const commitItem = exactIndex > -1 ? dataList[createItemCount + exactIndex] :+ (createItemCount > 0 ? dataList[0] : undefined);+ if (commitItem) {+ protyle.hint.fill(commitItem.value, protyle);+ return;+ }+ }if (source === "search") {protyle.hint.splitChar = "((";protyle.hint.lastIndex = -1;diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 93975a4162..e2045b4021 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -85,6 +85,8 @@ import {isBlockHintQueryAtCaret,shouldCaptureHintUndoFocus,shouldIgnoreHintTrigger,+ shouldAutoCloseRefBrackets,+ shouldDeleteRefBracketPair,stripBlockHintCloseKey,} from "./blockHintRange";import {getMobileHintPosition} from "./mobileHintPosition";@@ -133,6 +135,10 @@ export class Hint {private enableEmoji = true;public enableExtend = false;public splitChar = "";+ // 当前查询末尾是否手动输入了闭合符(如 ]])+ public closeKeyTyped = false;+ // 选中候选项时是否一并替换光标后自动补全的闭合符+ private consumeCloseKey = false;public lastIndex = -1;public hashTagSearchElement?: HTMLElement;private source: THintSource;@@ -392,6 +398,62 @@ export class Hint {});}+ // 输入 [[ 后在光标后补全 ]],光标保持在括号内+ public autoCloseRefBrackets(protyle: IProtyle, range: Range) {+ const context = this.getRefBracketContext(protyle, range);+ if (context && shouldAutoCloseRefBrackets(context.textBeforeCaret, context.textAfterCaret)) {+ context.textNode.insertData(range.startOffset, "]]");+ }+ }++ // 输入 ] 时跳过已补全的闭合符,跳过第二个 ] 后完成引用;在空括号对之间退格时一并删除 ]+ // 返回 true 表示已处理并需要阻止默认输入+ public handleRefBracketBeforeInput(protyle: IProtyle, event: InputEvent) {+ if (event.isComposing || getSelection().rangeCount === 0) {+ return false;+ }+ const range = getSelection().getRangeAt(0);+ const context = this.getRefBracketContext(protyle, range);+ if (!context) {+ return false;+ }+ if (event.inputType === "insertText" && event.data === "]" && context.textAfterCaret.startsWith("]") &&+ this.splitChar === "[[" && this.canResumeBlockHint(protyle, range)) {+ range.setStart(context.textNode, range.startOffset + 1);+ range.collapse(true);+ focusByRange(range);+ this.enableExtend = true;+ this.render(protyle);+ return true;+ }+ if (event.inputType === "deleteContentBackward" &&+ shouldDeleteRefBracketPair(context.textBeforeCaret, context.textAfterCaret)) {+ context.textNode.deleteData(range.startOffset, 1);+ }+ return false;+ }++ private getRefBracketContext(protyle: IProtyle, range: Range) {+ if (!window.siyuan.config.editor?.autoCloseRefBrackets || !range.collapsed ||+ range.startContainer.nodeType !== 3 || !protyle.wysiwyg.element.contains(range.startContainer) ||+ hasClosestByAttribute(range.startContainer, "data-type", "code") ||+ hasClosestByAttribute(range.startContainer, "data-type", "inline-math") ||+ hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {+ return undefined;+ }+ // 输入过程中文本可能被拆分为多个相邻文本节点,合并后才能判断光标前后的括号+ range.startContainer.parentNode?.normalize();+ if (range.startContainer.nodeType !== 3) {+ return undefined;+ }+ const textNode = range.startContainer as Text;+ return {+ textNode,+ textBeforeCaret: textNode.data.substring(0, range.startOffset),+ textAfterCaret: textNode.data.substring(range.startOffset),+ };+ }+public canResumeBlockHint(protyle: IProtyle, range: Range) {if (!range.collapsed || !protyle.wysiwyg.element.contains(range.startContainer) ||!Constants.BLOCK_HINT_KEYS.includes(this.splitChar) ||@@ -962,6 +1024,14 @@ ${genHintItemHTML(item)}range.setStart(range.startContainer, this.lastIndex);focusByRange(range);}+ // 自动闭合时,光标后的闭合符随查询一起被替换+ if (this.consumeCloseKey && Constants.BLOCK_HINT_KEYS.includes(this.splitChar)) {+ const closeKey = Constants.BLOCK_HINT_CLOSE_KEYS[this.splitChar];+ range.endContainer.parentNode?.normalize();+ if (range.endContainer.nodeType === 3 && range.endContainer.textContent.startsWith(closeKey, range.endOffset)) {+ range.setEnd(range.endContainer, range.endOffset + closeKey.length);+ }+ }if (["[[", "【【"].includes(this.splitChar) && /^daily-note:\d{4}-\d{2}-\d{2}:[a-z0-9-]*$/.test(value)) {const [, date, notebookID] = value.split(":");const target = captureDailyNoteSelection(protyle, range);@@ -1495,6 +1565,8 @@ ${genHintItemHTML(item)}const prevLastIndex = this.lastIndex;this.lastIndex = -1;this.splitChar = "";+ this.closeKeyTyped = false;+ this.consumeCloseKey = false;const disableHashTagSearch = window.siyuan.config.editor.hashTagSearch === false;extend.forEach((item) => {// 关闭标签搜索后 # 不再作为触发符,避免影响 / 等后续提示@@ -1540,7 +1612,10 @@ ${genHintItemHTML(item)}return "";}if (Constants.BLOCK_HINT_KEYS.includes(this.splitChar)) {- return stripBlockHintCloseKey(lastItem, Constants.BLOCK_HINT_CLOSE_KEYS[this.splitChar]);+ const query = stripBlockHintCloseKey(lastItem, Constants.BLOCK_HINT_CLOSE_KEYS[this.splitChar]);+ this.closeKeyTyped = query !== lastItem;+ this.consumeCloseKey = !!window.siyuan.config.editor.autoCloseRefBrackets;+ return query;}return lastItem;}diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 786c2c37c8..120c1c94db 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -4363,6 +4363,11 @@ export class WYSIWYG {event.stopPropagation();return;}+ if (!isComposition && protyle.hint.handleRefBracketBeforeInput(protyle, event)) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }if (event.target === this.element &&(event.inputType === "historyUndo" || event.inputType === "historyRedo")) {event.preventDefault();@@ -4542,6 +4547,9 @@ export class WYSIWYG {return;}this.escapeInline(protyle, range, event);+ if (event.data === "[") {+ protyle.hint.autoCloseRefBrackets(protyle, range);+ }// 原生输入结束后立即恢复各段折行,避免延迟解析前绘制出临时的整段换行。normalizeInlineElementBoundaries(this.element);diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 682899080d..3ca4940434 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1852,7 +1852,7 @@ export type SetCriterionRequestInput = { "criterion": CriterionInput | null; };export type SetDatabaseBlockViewRequestInput = { "avID": string; "id": string; "viewID": string; };-export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };+export type SetEditorRequestInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };export type SetEntryVisibilityRequestInput = { "active"?: string | null; "profiles"?: Array<SettingEntryVisibilityProfileInput | null> | null; "version"?: number | null; };@@ -1988,13 +1988,13 @@ export type SettingEditing = { "maxCompletionTokens": number; "maxHistoryMessageexport type SettingEditingInput = { "maxCompletionTokens"?: number | null; "maxHistoryMessages"?: number | null; "modelId"?: string | null; "temperature"?: number | null; };-export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "autoDirection": boolean; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkGlobalSort": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayImgAlt": boolean; "displayImgName": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "onlySearchForDoc": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };+export type SettingEditor = { "allowHTMLBLockScript": boolean; "allowSVGScript": boolean; "assetOpen": SettingAssetOpen | null; "autoCloseRefBrackets": boolean; "autoDirection": boolean; "backlinkBlockSort": number; "backlinkContainChildren": boolean; "backlinkExpandCount": number; "backlinkGlobalSort": number; "backlinkHideReference": boolean; "backlinkMentionExclude": string; "backlinkShowBottom": boolean; "backlinkSort": number | null; "backmentionExpandCount": number; "backmentionSort": number | null; "blockRefDynamicAnchorTextMaxLen": number; "checkBlockRef": boolean | null; "codeFontFamilies": Array<SettingEditorFont | null> | null; "codeLigatures": boolean; "codeLineWrap": boolean; "codeSyntaxHighlightLineNum": boolean; "codeTabSpaces": number; "cursorSurroundingLines": number; "databaseAttrClickMode": number; "databaseAttrHideEmpty": boolean; "databaseAttrShow": boolean | null; "databaseAttrUseTabs": boolean | null; "databaseAttrViewMode": number; "displayBookmarkIcon": boolean; "displayImgAlt": boolean; "displayImgName": boolean; "displayNetImgMark": boolean; "dragHTMLFileToIframe": boolean; "dynamicLoadBlocks": number; "embedBlockBreadcrumb": boolean; "emoji": Array<string> | null; "floatWindowDelay": number | null; "floatWindowMode": number; "fontFamilies": Array<SettingEditorFont | null> | null; "fontFamily": string; "fontFamilyDisplay": string; "fontSize": number; "fontSizeScrollZoom": boolean; "fontWeight": number; "fullWidth": boolean; "generateHistoryInterval": number; "hashTagSearch": boolean | null; "headingEmbedMode": number; "headingNumber": boolean; "headingNumberFormat": string; "historyRetentionDays": number; "justify": boolean; "katexMacros": string; "keepLoadedContent": boolean; "listItemDotNumberClickFocus": boolean; "listLogicalOutdent": boolean; "markdown": SettingMarkdown | null; "onlySearchForDoc": boolean; "pasteURLAutoConvert": boolean; "plantUMLServePath": string; "readOnly": boolean; "rtl": boolean; "spellcheck": boolean; "spellcheckLanguages": Array<string> | null; "virtualBlockRef": boolean; "virtualBlockRefExclude": string; "virtualBlockRefInclude": string; };export type SettingEditorFont = { "displayName": string; "family": string; "weight": number; };export type SettingEditorFontInput = { "displayName"?: string | null; "family"?: string | null; "weight"?: number | null; };-export type SettingEditorInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };+export type SettingEditorInput = { "allowHTMLBLockScript"?: boolean | null; "allowSVGScript"?: boolean | null; "assetOpen"?: SettingAssetOpenInput | null; "autoCloseRefBrackets"?: boolean | null; "autoDirection"?: boolean | null; "backlinkBlockSort"?: number | null; "backlinkContainChildren"?: boolean | null; "backlinkExpandCount"?: number | null; "backlinkGlobalSort"?: number | null; "backlinkHideReference"?: boolean | null; "backlinkMentionExclude"?: string | null; "backlinkShowBottom"?: boolean | null; "backlinkSort"?: number | null; "backmentionExpandCount"?: number | null; "backmentionSort"?: number | null; "blockRefDynamicAnchorTextMaxLen"?: number | null; "checkBlockRef"?: boolean | null; "codeFontFamilies"?: Array<SettingEditorFontInput | null> | null; "codeLigatures"?: boolean | null; "codeLineWrap"?: boolean | null; "codeSyntaxHighlightLineNum"?: boolean | null; "codeTabSpaces"?: number | null; "cursorSurroundingLines"?: number | null; "databaseAttrClickMode"?: number | null; "databaseAttrHideEmpty"?: boolean | null; "databaseAttrShow"?: boolean | null; "databaseAttrUseTabs"?: boolean | null; "databaseAttrViewMode"?: number | null; "displayBookmarkIcon"?: boolean | null; "displayImgAlt"?: boolean | null; "displayImgName"?: boolean | null; "displayNetImgMark"?: boolean | null; "dragHTMLFileToIframe"?: boolean | null; "dynamicLoadBlocks"?: number | null; "embedBlockBreadcrumb"?: boolean | null; "emoji"?: Array<string> | null; "floatWindowDelay"?: number | null; "floatWindowMode"?: number | null; "fontFamilies"?: Array<SettingEditorFontInput | null> | null; "fontFamily"?: string | null; "fontFamilyDisplay"?: string | null; "fontSize"?: number | null; "fontSizeScrollZoom"?: boolean | null; "fontWeight"?: number | null; "fullWidth"?: boolean | null; "generateHistoryInterval"?: number | null; "hashTagSearch"?: boolean | null; "headingEmbedMode"?: number | null; "headingNumber"?: boolean | null; "headingNumberFormat"?: string | null; "historyRetentionDays"?: number | null; "justify"?: boolean | null; "katexMacros"?: string | null; "keepLoadedContent"?: boolean | null; "listItemDotNumberClickFocus"?: boolean | null; "listLogicalOutdent"?: boolean | null; "markdown"?: SettingMarkdownInput | null; "onlySearchForDoc"?: boolean | null; "pasteURLAutoConvert"?: boolean | null; "plantUMLServePath"?: string | null; "readOnly"?: boolean | null; "rtl"?: boolean | null; "spellcheck"?: boolean | null; "spellcheckLanguages"?: Array<string> | null; "virtualBlockRef"?: boolean | null; "virtualBlockRefExclude"?: string | null; "virtualBlockRefInclude"?: string | null; };export type SettingEmbedding = { "apiKey": string; "baseURL": string; "dimensions": number; "enabled": boolean; "id": string; "name": string; "timeout": number; };diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 8b4d7dc609..6e739d8e1e 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -773,6 +773,10 @@ declare namespace Config {* Whether to enable the `[[` symbol to search only for document blocks*/onlySearchForDoc: boolean;+ /**+ * Whether typing `[[` auto-inserts `]]` and typing `]]` completes the block reference+ */+ autoCloseRefBrackets: boolean;/*** PlantUML rendering service address*/diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.goindex 69aaf51ddd..e69dd84681 100644--- a/kernel/api/setting_contract.go+++ b/kernel/api/setting_contract.go@@ -398,6 +398,7 @@ func settingEditorPayload(value *conf.Editor) *apicontract.SettingEditor {result.SpellcheckLanguages = value.SpellcheckLanguagesresult.HashTagSearch = value.HashTagSearchresult.OnlySearchForDoc = value.OnlySearchForDoc+ result.AutoCloseRefBrackets = value.AutoCloseRefBracketsresult.BacklinkExpandCount = value.BacklinkExpandCountresult.BackmentionExpandCount = value.BackmentionExpandCountresult.BacklinkMentionExclude = value.BacklinkMentionExcludediff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex fb067c5377..2c079406cb 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -39915,6 +39915,16 @@}]},+ "autoCloseRefBrackets": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"autoDirection": {"anyOf": [{@@ -44070,6 +44080,9 @@}]},+ "autoCloseRefBrackets": {+ "type": "boolean"+ },"autoDirection": {"type": "boolean"},@@ -44374,6 +44387,7 @@"allowHTMLBLockScript","allowSVGScript","assetOpen",+ "autoCloseRefBrackets","autoDirection","backlinkBlockSort","backlinkContainChildren",@@ -44529,6 +44543,16 @@}]},+ "autoCloseRefBrackets": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"autoDirection": {"anyOf": [{diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.goindex b3cc0b9ea1..aa90af895f 100644--- a/kernel/apicontract/setting.go+++ b/kernel/apicontract/setting.go@@ -237,11 +237,13 @@ type SettingEditor struct {RTL bool `json:"rtl" api:"optional,nullable"`// AutoDirection 默认关闭;段落和标题按首个强方向字符排版,列表项独立调整标记和缩进。// 手动方向优先,表格列顺序不变。- AutoDirection bool `json:"autoDirection" api:"optional,nullable"`- Spellcheck bool `json:"spellcheck" api:"optional,nullable"`- SpellcheckLanguages []string `json:"spellcheckLanguages" api:"optional,nullable"`- HashTagSearch *bool `json:"hashTagSearch" api:"optional,nullable"`- OnlySearchForDoc bool `json:"onlySearchForDoc" api:"optional,nullable"`+ AutoDirection bool `json:"autoDirection" api:"optional,nullable"`+ Spellcheck bool `json:"spellcheck" api:"optional,nullable"`+ SpellcheckLanguages []string `json:"spellcheckLanguages" api:"optional,nullable"`+ HashTagSearch *bool `json:"hashTagSearch" api:"optional,nullable"`+ OnlySearchForDoc bool `json:"onlySearchForDoc" api:"optional,nullable"`+ // AutoCloseRefBrackets 默认关闭;启用后输入 [[ 自动补全 ]],输入 ]] 时引用同名文档、日记或新建文档。+ AutoCloseRefBrackets bool `json:"autoCloseRefBrackets" api:"optional,nullable"`BacklinkExpandCount int `json:"backlinkExpandCount" api:"optional,nullable"`BackmentionExpandCount int `json:"backmentionExpandCount" api:"optional,nullable"`BacklinkMentionExclude string `json:"backlinkMentionExclude" api:"optional,nullable"`diff --git a/kernel/conf/editor.go b/kernel/conf/editor.goindex 282b8886e6..c1987e0ac7 100644--- a/kernel/conf/editor.go+++ b/kernel/conf/editor.go@@ -94,6 +94,7 @@ type Editor struct {SpellcheckLanguages []string `json:"spellcheckLanguages"` // 拼写检查语言HashTagSearch *bool `json:"hashTagSearch"` // 输入 # 时是否进行标签搜索OnlySearchForDoc bool `json:"onlySearchForDoc"` // 是否启用 [[ 仅搜索文档块+ AutoCloseRefBrackets bool `json:"autoCloseRefBrackets"` // 输入 [[ 时自动补全 ]],输入 ]] 时完成引用BacklinkExpandCount int `json:"backlinkExpandCount"` // 反向链接默认展开数量BackmentionExpandCount int `json:"backmentionExpandCount"` // 反链提及默认展开数量BacklinkMentionExclude string `json:"backlinkMentionExclude"` // 反链提及关键字排除列表@@ -236,6 +237,7 @@ func NewEditor() *Editor {Spellcheck: false,SpellcheckLanguages: []string{"en-US"},HashTagSearch: new(true),+ AutoCloseRefBrackets: false,BacklinkExpandCount: 8,BackmentionExpandCount: -1,BacklinkContainChildren: true,