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 safe automatic block reference completion https://github.com/siyuan-note/siyuan/issues/20524
Daniel119fb7666e7b
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex bbe01e8a7c..066a2137b6 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "إغلاق <code class='fn__code'>[[</code> تلقائيًا",+ "autoCloseRefBracketsTip": "عند الكتابة [[ يُضاف ]] تلقائيًا، وكتابة ]] تُكمل المرجع إلى المستند الذي يطابق عنوانه تمامًا أو تُنشئ مستندًا جديدًا","currentTime": "الوقت الحالي","exitWaiting": "جارٍ الخروج، يُرجى الانتظار...","exitWaitFailed": "تعذّر التأكد من اكتمال الإغلاق. يمكنك إعادة المحاولة أو إغلاق مربع الحوار هذا ومتابعة الانتظار.",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 2622cdd859..19fac162b3 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","currentTime": "Aktuelle Uhrzeit","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.",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 13551e0c0d..6bb551ea91 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","currentTime": "Current Time","exitWaiting": "Exiting, please wait...","exitWaitFailed": "Could not confirm that shutdown has completed. You can retry or close this dialog and continue waiting.",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex f2ee2be4c9..d861c23838 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","currentTime": "Hora actual","exitWaiting": "Saliendo, espere...","exitWaitFailed": "No se pudo confirmar que el cierre haya terminado. Puede reintentar o cerrar este diálogo y seguir esperando.",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 1a1c19beba..2253469a09 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","currentTime": "Heure actuelle","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.",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex a4c46b05a6..4761a9432b 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "סגירה אוטומטית של <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "הקלדת [[ מוסיפה ]] אוטומטית; הקלדת ]] משלימה את ההפניה למסמך שכותרתו תואמת בדיוק, או יוצרת מסמך חדש","currentTime": "השעה הנוכחית","exitWaiting": "היישום נסגר, נא להמתין...","exitWaitFailed": "לא ניתן לאשר שהסגירה הושלמה. אפשר לנסות שוב או לסגור את תיבת הדו־שיח ולהמשיך להמתין.",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 5897d4bc31..286df8bb8a 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> स्वतः बंद करें",+ "autoCloseRefBracketsTip": "[[ टाइप करने पर ]] स्वतः जुड़ जाता है; ]] टाइप करने पर बिल्कुल मेल खाते शीर्षक वाले दस्तावेज़ का संदर्भ पूरा होता है या नया दस्तावेज़ बनता है","currentTime": "वर्तमान समय","exitWaiting": "बंद किया जा रहा है, कृपया प्रतीक्षा करें...","exitWaitFailed": "बंद होने की प्रक्रिया पूरी होने की पुष्टि नहीं हो सकी। आप फिर से कोशिश कर सकते हैं या इस संवाद को बंद करके प्रतीक्षा जारी रख सकते हैं।",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 29031a91f9..e87b763442 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","currentTime": "Waktu Saat Ini","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.",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex b3813b9179..1d00e68f53 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","currentTime": "Ora attuale","exitWaiting": "Chiusura in corso, attendere...","exitWaitFailed": "Impossibile confermare il completamento della chiusura. Puoi riprovare oppure chiudere questa finestra di dialogo e continuare ad attendere.",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 701f22b88f..5bee8dfaa9 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> を自動で閉じる",+ "autoCloseRefBracketsTip": "[[ を入力すると ]] を自動挿入し、]] を入力するとタイトルが完全一致するドキュメントへの参照を完成させるか、新しいドキュメントを作成します","currentTime": "現在時刻","exitWaiting": "終了しています。お待ちください...","exitWaitFailed": "終了が完了したか確認できませんでした。再試行するか、このダイアログを閉じてお待ちください。",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex cf015606a2..465ed6a0d8 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "<code class='fn__code'>[[</code> 자동 닫기",+ "autoCloseRefBracketsTip": "[[ 입력 시 ]]가 자동으로 삽입되며, ]] 입력 시 제목이 정확히 일치하는 문서로 참조를 완성하거나 새 문서를 만듭니다","currentTime": "현재 시간","exitWaiting": "종료 중입니다. 잠시 기다려 주세요...","exitWaitFailed": "종료 완료 여부를 확인할 수 없습니다. 다시 시도하거나 이 대화 상자를 닫고 계속 기다려 주세요.",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 7a72b93fbe..201a6c8ab2 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","currentTime": "Huidige tijd","exitWaiting": "Afsluiten, even geduld...","exitWaitFailed": "Het is niet bevestigd dat het afsluiten is voltooid. Probeer het opnieuw of sluit dit dialoogvenster en blijf wachten.",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex ccf4c9e22b..63fe5660bc 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","currentTime": "Bieżąca godzina","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ć.",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 3f22173e59..faf6083bb7 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","currentTime": "Hora atual","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.",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 1eb1a883e8..82b6246dcc 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Автозакрытие <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "При вводе [[ автоматически добавляется ]]; ввод ]] завершает ссылку на документ с точно совпадающим заголовком или создаёт новый документ","currentTime": "Текущее время","exitWaiting": "Завершение работы, подождите...","exitWaitFailed": "Не удалось подтвердить завершение работы. Повторите попытку или закройте это диалоговое окно и продолжайте ждать.",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 37a8e17489..bde87142e6 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","currentTime": "Aktuálny čas","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ť.",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex b36b3d24a0..5de4c96889 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Аутоматски затвори <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Куцање [[ аутоматски додаје ]]; куцање ]] довршава референцу на документ са тачно истим насловом или прави нови документ","currentTime": "Тренутно време","exitWaiting": "Затварање, сачекајте...","exitWaitFailed": "Није могуће потврдити да је затварање завршено. Покушајте поново или затворите овај дијалог и наставите да чекате.",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex c2167ee9a0..bba19c0303 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "ปิด <code class='fn__code'>[[</code> อัตโนมัติ",+ "autoCloseRefBracketsTip": "เมื่อพิมพ์ [[ จะเติม ]] ให้อัตโนมัติ และเมื่อพิมพ์ ]] จะอ้างอิงเอกสารที่ชื่อตรงกันทุกตัวอักษร หรือสร้างเอกสารใหม่","currentTime": "เวลาปัจจุบัน","exitWaiting": "กำลังออกจากแอป โปรดรอสักครู่...","exitWaitFailed": "ไม่สามารถยืนยันได้ว่าการปิดเสร็จสิ้นแล้ว คุณสามารถลองอีกครั้ง หรือปิดกล่องโต้ตอบนี้แล้วรอต่อไปได้",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 2416061971..bd5d5449c3 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","currentTime": "Geçerli Saat","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.",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex b555de8170..b0c94e2878 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "autoCloseRefBrackets": "Автозакриття <code class='fn__code'>[[</code>",+ "autoCloseRefBracketsTip": "Під час введення [[ автоматично додається ]]; введення ]] завершує посилання на документ із точно збіжною назвою або створює новий документ","currentTime": "Поточний час","exitWaiting": "Завершення роботи, зачекайте...","exitWaitFailed": "Не вдалося підтвердити завершення роботи. Повторіть спробу або закрийте це діалогове вікно й продовжуйте чекати.",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 08fd26f637..782fe82680 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": "输入 [[ 时自动补全 ]],输入 ]] 时引用标题完全一致的文档,没有则新建文档","currentTime": "当前时间","exitWaiting": "正在退出,请稍候...","exitWaitFailed": "暂时无法确认退出是否完成。可以重试,或关闭此提示继续等待。",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 8f6fd3d3e3..9c1ad1171f 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": "輸入 [[ 時自動補上 ]],輸入 ]] 時引用標題完全相同的文件,沒有則新建文件","currentTime": "目前時間","exitWaiting": "正在退出,請稍候...","exitWaitFailed": "暫時無法確認是否已結束。可以重試,或關閉此提示繼續等待。",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.syindex 6da0dafde6..e935703896 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101256-f8b1sbi.sy@@ -6,7 +6,7 @@"id": "20200924101256-f8b1sbi","title": "Ref Content Block","type": "doc",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20200924101312-jj4e0v3",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -97,6 +97,70 @@}]},+ {+ "ID": "20261014130425-k3pzlyv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-k3pzlyv",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Enable automatic closing in "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Editor"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Bidirectional Links"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Auto-close [["+ },+ {+ "Type": "NodeText",+ "Data": ". This option is off by default. When enabled, typing [[ inserts ]] after the caret; typing two ] characters steps over them and completes the reference. Selecting a suggestion with Enter also replaces the closing brackets. Backspace inside an empty [[]] deletes the entire bracket pair."+ }+ ]+ },+ {+ "ID": "20261014130425-jqqpiql",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-jqqpiql",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Completing a reference with ]] first looks for a document with an exactly matching title, then a title matching without regard to case, then a matching daily note. If none match, a document is created at the configured location for reference creation. This does not apply in inline code, code blocks or inline math, and typing 【【 with an input method does not insert closing brackets."+ }+ ]+ },{"ID": "20210104091542-v1yca4p","Type": "NodeHeading",@@ -992,4 +1056,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.syindex 805e865bf4..94963ffdf5 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200813013559-sgbzl5k.sy@@ -6,7 +6,7 @@"id": "20200813013559-sgbzl5k","title": "引用内容块","type": "doc",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20200817123136-in6y5m1",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -97,6 +97,70 @@}]},+ {+ "ID": "20261014130425-cikkb9k",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-cikkb9k",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "编辑器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "双向链接"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "自动闭合 [["+ },+ {+ "Type": "NodeText",+ "Data": " 中可以启用自动闭合,默认关闭。启用后,输入 [[ 会在光标后补全 ]];输入两个 ] 可跳过闭合符并完成引用。回车选择候选项也会替换闭合符;在空的 [[]] 中退格会删除整个括号对。"+ }+ ]+ },+ {+ "ID": "20261014130425-nr878bc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-nr878bc",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "输入 ]] 完成引用时,先查找标题完全一致的文档,再查找忽略大小写后标题一致的文档,然后使用匹配的日记;都未匹配时按块引新建文档的默认位置创建文档。行级代码、代码块和行级公式中不生效,输入法输入的 【【 不会自动闭合。"+ }+ ]+ },{"ID": "20210104090557-841hf2w","Type": "NodeHeading",@@ -1008,7 +1072,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026apos;"+ "TextMarkTextContent": "'"},{"Type": "NodeText",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.syindex 05efb683c4..eeb65a7b1d 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120247-63nd8y5.sy@@ -6,7 +6,7 @@"id": "20211226120247-63nd8y5","title": "引用内容區塊","type": "doc",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226120337-x5qwass",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -97,6 +97,70 @@}]},+ {+ "ID": "20261014130425-brzvwem",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-brzvwem",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "編輯器"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "雙向連結"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "自動閉合 [["+ },+ {+ "Type": "NodeText",+ "Data": " 中可以啟用自動閉合,預設關閉。啟用後,輸入 [[ 會在游標後補全 ]];輸入兩個 ] 可跳過閉合符並完成區塊引用。按 Enter 選擇候選項也會替換閉合符;在空的 [[]] 中按退格會刪除整組括號。"+ }+ ]+ },+ {+ "ID": "20261014130425-eewkoer",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-eewkoer",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "輸入 ]] 完成區塊引用時,先尋找標題完全一致的文件,再尋找忽略大小寫後標題一致的文件,然後使用符合條件的日記;都未符合時依區塊引用新建文件的預設位置建立文件。行內程式碼、程式碼區塊和行內公式中不生效,輸入法輸入的 【【 不會自動閉合。"+ }+ ]+ },{"ID": "20211226120337-nfx8mlg","Type": "NodeHeading",@@ -970,7 +1034,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026apos;"+ "TextMarkTextContent": "'"},{"Type": "NodeText",@@ -1006,4 +1070,4 @@]}]-}\ No newline at end of file+}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.syindex 8ccb60c823..4947c6504f 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-uxno1yp.sy@@ -7,7 +7,7 @@"id": "20240530101000-uxno1yp","title": "コンテンツブロックの参照","type": "doc",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-3mutq27","id": "20240530101000-ggy8jav",- "updated": "20260927183214"+ "updated": "20261014130425"},"Children": [{@@ -105,6 +105,66 @@}]},+ {+ "ID": "20261014130425-0xqno1c",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-0xqno1c",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "エディター"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "双方向リンク"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "[[ を自動で閉じる"+ },+ {+ "Type": "NodeText",+ "Data": " で自動補完を有効にできます。初期状態では無効です。有効にすると、[[ を入力した際にカーソルの後ろへ ]] が挿入されます。] を2回入力すると閉じ括弧を飛び越えて参照を確定します。Enter で候補を選択した場合も閉じ括弧が置き換えられます。空の [[]] 内で Backspace を押すと括弧全体が削除されます。"+ }+ ]+ },+ {+ "ID": "20261014130425-xs624bu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014130425-xs624bu",+ "updated": "20261014130425"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "]] で参照を確定する際は、タイトルが完全一致するドキュメント、大文字と小文字を区別せず一致するドキュメント、該当するデイリーノートの順に参照先を探します。該当するものがなければ、参照時の新規作成先として設定した場所にドキュメントを作成します。インラインコード、コードブロック、インライン数式では動作せず、入力メソッドで 【【 を入力しても閉じ括弧は挿入されません。"+ }+ ]+ },{"ID": "20240530101000-avpxozm","Type": "NodeHeading",@@ -930,7 +990,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "((id \u0026quot;アンカーテキスト\u0026quot;))"+ "TextMarkTextContent": "((id "アンカーテキスト"))"},{"Type": "NodeText",@@ -977,7 +1037,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026quot;"+ "TextMarkTextContent": """},{"Type": "NodeText",@@ -1061,4 +1121,4 @@}}]-}\ No newline at end of file+}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..3e8a2fdb6f 100644--- a/app/src/protyle/hint/blockHintRange.test.ts+++ b/app/src/protyle/hint/blockHintRange.test.ts@@ -5,6 +5,7 @@ import {getBlockHintTriggerOffset,getBlockRefStaticText,isBlockHintQueryAtCaret,+ shouldAutoCloseRefBrackets,shouldCaptureHintUndoFocus,shouldIgnoreHintTrigger,stripBlockHintCloseKey,@@ -158,3 +159,14 @@ 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);+ });++});diff --git a/app/src/protyle/hint/blockHintRange.ts b/app/src/protyle/hint/blockHintRange.tsindex c4f476b575..4eebf536dc 100644--- a/app/src/protyle/hint/blockHintRange.ts+++ b/app/src/protyle/hint/blockHintRange.ts@@ -18,6 +18,11 @@ 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 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/dailyNoteRef.test.ts b/app/src/protyle/hint/dailyNoteRef.test.tsindex 9c306414fb..3816f1068f 100644--- a/app/src/protyle/hint/dailyNoteRef.test.ts+++ b/app/src/protyle/hint/dailyNoteRef.test.ts@@ -26,7 +26,7 @@ test("typing a slash in reference search does not run title replacement or showfetchPost: (path: string, request: {k: string}, callback: (response: unknown) => void) => {assert.equal(path, "/api/search/searchRefBlock");assert.equal(request.k, "10/");- callback({data: {k: "10/", newDoc: true, blocks: []}});+ callback({code: 0, data: {k: "10/", newDoc: true, blocks: []}});},});const protyle = {notebookId: "box", element: {clientWidth: 320}, block: {rootID: "root"},@@ -39,3 +39,52 @@ test("typing a slash in reference search does not run title replacement or showawait setImmediate();assert.equal(rendered, true);});++test("closing a reference resolves exact titles before daily notes or configured creation and rejects stale results", async () => {+ for (const scenario of ["document", "daily", "create", "subdoc", "stale", "error", "ordinary"]) {+ const block = {getAttribute: () => "block"};+ const closeContext = {range: "original"};+ const commits: string[] = [];+ let rendered = false;+ const hintRef = runInNewContext(code, {+ window: {siyuan: {config: {editor: {autoCloseRefBrackets: true}}, languages: {}}},+ Constants: {ZWSP: "\u200b"}, Lute: {Caret: "caret", UnEscapeHTMLStr: (text: string) => text},+ getEditorRange: () => ({startContainer: block}), hasClosestBlock: () => block,+ isEncryptedBox: () => true, genHintItemHTML: () => "document",+ getDailyNoteHints: async () => scenario === "daily" || scenario === "document" ?+ [{value: "daily-note:2026-10-14:box", html: "daily"}] : [],+ fetchPost: (_path: string, request: {exactDocTitle?: boolean; notebook?: string}, callback: (response: unknown) => void) => {+ assert.equal(request.exactDocTitle, scenario === "ordinary" ? undefined : true);+ assert.equal(request.notebook, "box");+ callback({code: scenario === "error" ? -1 : 0, data: {k: "Title", newDoc: scenario !== "document",+ blocks: scenario === "document" ? [{id: "exact", type: "NodeDocument", refText: "Title"}] : []}});+ },+ });+ const protyle = {notebookId: "box", element: {clientWidth: 320}, block: {rootID: "root"},+ wysiwyg: {element: {}}, hint: {+ splitChar: "[[", closeKeyTyped: scenario !== "ordinary", genLoading() {},+ getRefCloseContext: () => closeContext,+ isRefCloseContextCurrent: () => scenario !== "stale",+ prepareCreateTarget: () => ({promise: Promise.resolve(scenario === "subdoc"), isCurrent: () => true}),+ fillRefClose: (value: string, _protyle: unknown, original: unknown) => {+ assert.equal(original, closeContext);+ commits.push(value);+ },+ genHTML: () => { rendered = true; },+ }};+ hintRef("Title", protyle, "hint");+ await setImmediate();+ if (scenario === "document") {+ assert.equal(commits.length, 1);+ assert.match(commits[0], /data-id="exact"/);+ } else if (scenario === "daily") {+ assert.deepEqual(commits, ["daily-note:2026-10-14:box"]);+ } else if (scenario === "create" || scenario === "subdoc") {+ assert.equal(commits.length, 1);+ assert.ok(commits[0].startsWith(scenario === "create" ? "((newFile " : "((newSubDoc "));+ } else {+ assert.equal(commits.length, 0);+ assert.equal(rendered, scenario === "ordinary");+ }+ }+});diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 714bb91e44..8e850c59ea 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -615,12 +615,22 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHif (protyle.lite && isEncryptedBox(protyle.notebookId)) {refParam.notebook = protyle.notebookId;}+ // 自动闭合时输入 ]] 直接完成引用+ const closeContext = source === "hint" && !protyle.lite && protyle.hint.splitChar === "[[" && key.trim() !== "" &&+ protyle.hint.closeKeyTyped && window.siyuan.config.editor?.autoCloseRefBrackets &&+ protyle.hint.getRefCloseContext(protyle);+ if (closeContext) {+ refParam.exactDocTitle = true;+ }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]) => {if (!createTarget.isCurrent()) {return;}+ if (response.code !== 0 || (closeContext && !protyle.hint.isRefCloseContextCurrent(protyle, closeContext))) {+ return;+ }const dataList: IHintData[] = [];let createItemCount = 0;dataList.push(...dateHints);@@ -665,6 +675,15 @@ export const hintRef = (key: string, protyle: IProtyle, source: THintSource): IHhtml: genHintItemHTML(item),});});+ if (closeContext) {+ // 依次选择标题完全一致的文档、日记、新建文档+ const commitItem = response.data.blocks.length > 0 ? dataList[createItemCount] :+ (createItemCount > 0 ? dataList[0] : undefined);+ if (commitItem) {+ protyle.hint.fillRefClose(commitItem.value, protyle, closeContext);+ return;+ }+ }if (source === "search") {protyle.hint.splitChar = "((";protyle.hint.lastIndex = -1;diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.tsindex 67e4728e32..8c27ac018b 100644--- a/app/src/protyle/hint/fillCommand.test.ts+++ b/app/src/protyle/hint/fillCommand.test.ts@@ -10,7 +10,7 @@ import {shouldCaptureHintUndoFocus} from "./blockHintRange";const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");assert.ok(declaration && isClassDeclaration(declaration));-const methods = declaration.members.filter(member => ["fillCommand", "fill"].includes(member.name?.getText(source)))+const methods = declaration.members.filter(member => ["fillCommand", "fill", "consumeRefBracketClose"].includes(member.name?.getText(source))).map(member => member.getText(source)).join("\n");const code = transpileModule(`class Hint { ${methods} } new Hint();`, {compilerOptions: {target: ScriptTarget.ES2020},diff --git a/app/src/protyle/hint/frequentSlashExecution.test.ts b/app/src/protyle/hint/frequentSlashExecution.test.tsindex 74a06ea2d2..4deabe4a40 100644--- a/app/src/protyle/hint/frequentSlashExecution.test.ts+++ b/app/src/protyle/hint/frequentSlashExecution.test.ts@@ -11,7 +11,7 @@ const text = readFileSync("src/protyle/hint/index.ts", "utf8");const source = createSourceFile("index.ts", text, ScriptTarget.Latest);const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");assert.ok(declaration && isClassDeclaration(declaration));-const methods = declaration.members.filter(member => ["fillCommand", "fill", "getHTMLByData"].includes(member.name?.getText(source)))+const methods = declaration.members.filter(member => ["fillCommand", "fill", "getHTMLByData", "consumeRefBracketClose"].includes(member.name?.getText(source))).map(member => member.getText(source)).join("\n");const code = transpileModule(`class Hint { ${methods} } new Hint();`, {compilerOptions: {target: ScriptTarget.ES2020},diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 1cd8ee6b86..33c33ee3fe 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -86,6 +86,7 @@ import {isBlockHintQueryAtCaret,shouldCaptureHintUndoFocus,shouldIgnoreHintTrigger,+ shouldAutoCloseRefBrackets,stripBlockHintCloseKey,} from "./blockHintRange";import {getMobileHintPosition} from "./mobileHintPosition";@@ -134,6 +135,13 @@ export class Hint {private enableEmoji = true;public enableExtend = false;public splitChar = "";+ // 当前查询末尾是否包含完整闭合符(如 ]])+ public closeKeyTyped = false;+ private refBracketRange?: Range;+ private refBracketOrigin?: {notebookID: string; rootID: string; blockID: string; prefix: string};+ private refCloseContext?: {range: Range; text: string; notebookID: string; rootID: string};+ // 选中候选项时是否一并替换光标后自动补全的闭合符+ private consumeCloseKey = false;public lastIndex = -1;public hashTagSearchElement?: HTMLElement;private source: THintSource;@@ -393,6 +401,152 @@ 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, "]]");+ this.refBracketRange = range.cloneRange();+ this.refBracketRange.setStart(context.textNode, range.startOffset - 2);+ this.refBracketRange.setEnd(context.textNode, range.startOffset + 2);+ this.refBracketOrigin = {notebookID: protyle.notebookId, rootID: protyle.block.rootID,+ blockID: (hasClosestBlock(range.startContainer) || undefined)?.getAttribute("data-node-id"),+ prefix: context.textBeforeCaret};+ this.refCloseContext = undefined;+ }+ }++ // 输入 ] 时跳过已补全的闭合符,跳过第二个 ] 后完成引用;在空括号对之间退格时删除整个括号对+ // 返回 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);+ const pair = this.refBracketRange;+ if (!context || !pair || pair.startContainer !== context.textNode || pair.endContainer !== context.textNode ||+ !pair.toString().startsWith("[[") || !pair.toString().endsWith("]]")) {+ return false;+ }+ if (event.inputType === "insertText" && event.data === "]" && context.textAfterCaret.startsWith("]") &&+ range.startOffset >= pair.endOffset - 2 && range.startOffset < pair.endOffset &&+ this.splitChar === "[[" && this.canResumeBlockHint(protyle, range)) {+ range.setStart(context.textNode, range.startOffset + 1);+ range.collapse(true);+ focusByRange(range);+ if (range.startOffset === pair.endOffset) {+ this.refCloseContext = {range: pair.cloneRange(), text: pair.toString(),+ notebookID: protyle.notebookId, rootID: protyle.block.rootID};+ this.enableExtend = true;+ this.render(protyle);+ }+ return true;+ }+ if (event.inputType === "deleteContentBackward" && pair.toString() === "[[]]" &&+ range.startOffset === pair.startOffset + 2) {+ const block = hasClosestBlock(range.startContainer);+ if (!block) {+ return false;+ }+ const html = block.outerHTML;+ const undoContext = getUndoFocusContext(protyle.wysiwyg.element, range, true);+ const offset = pair.startOffset;+ pair.deleteContents();+ range.setStart(context.textNode, offset);+ range.collapse(true);+ focusByRange(range);+ this.refBracketRange = undefined;+ this.refBracketOrigin = undefined;+ this.refCloseContext = undefined;+ hideElements(["hint"], protyle);+ updateTransaction(protyle, block, html, undoContext);+ protyle.wysiwyg.preventKeyup = true;+ return true;+ }+ return false;+ }++ public getRefCloseContext(protyle: IProtyle) {+ return this.refCloseContext && this.isRefCloseContextCurrent(protyle, this.refCloseContext) ?+ this.refCloseContext : undefined;+ }++ public isRefCloseContextCurrent(protyle: IProtyle, context: typeof this.refCloseContext) {+ if (!context || !window.siyuan.config.editor.autoCloseRefBrackets || protyle.disabled ||+ window.siyuan.config.readonly || window.siyuan.isPublish ||+ protyle.notebookId !== context.notebookID || protyle.block.rootID !== context.rootID ||+ !protyle.wysiwyg.element.contains(context.range.startContainer) ||+ !protyle.wysiwyg.element.contains(context.range.endContainer) ||+ context.range.toString() !== context.text || getSelection().rangeCount === 0) {+ return false;+ }+ const range = getSelection().getRangeAt(0);+ return range.collapsed && range.startContainer === context.range.endContainer &&+ range.startOffset === context.range.endOffset;+ }++ public fillRefClose(value: string, protyle: IProtyle, context: typeof this.refCloseContext) {+ if (!this.isRefCloseContextCurrent(protyle, context)) {+ return;+ }+ protyle.toolbar.range = context.range.cloneRange();+ this.lastIndex = context.range.startOffset;+ this.fill(value, protyle, false);+ }++ private consumeRefBracketClose(range: 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);+ } else if (this.splitChar === "[[" && this.refBracketRange?.endContainer === range.endContainer &&+ this.refBracketRange.toString().endsWith("]]") &&+ range.endOffset === this.refBracketRange.endOffset - 1) {+ range.setEnd(range.endContainer, this.refBracketRange.endOffset);+ }+ }+ this.refBracketRange = undefined;+ this.refBracketOrigin = undefined;+ this.refCloseContext = undefined;+ }++ private getRefBracketContext(protyle: IProtyle, range: Range) {+ if (!window.siyuan.config.editor?.autoCloseRefBrackets || protyle.disabled ||+ window.siyuan.config.readonly || window.siyuan.isPublish || !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;+ const origin = this.refBracketOrigin;+ // 块重绘后按原块和触发符前缀恢复括号范围,不将其他位置的括号视为自动补全。+ if (origin && this.refBracketRange?.startContainer !== textNode &&+ protyle.notebookId === origin.notebookID && protyle.block.rootID === origin.rootID &&+ (hasClosestBlock(textNode) || undefined)?.getAttribute("data-node-id") === origin.blockID &&+ textNode.data.startsWith(origin.prefix)) {+ const end = textNode.data.indexOf("]]", origin.prefix.length);+ if (end > -1 && range.startOffset >= origin.prefix.length && range.startOffset <= end + 2) {+ this.refBracketRange = range.cloneRange();+ this.refBracketRange.setStart(textNode, origin.prefix.length - 2);+ this.refBracketRange.setEnd(textNode, end + 2);+ }+ }+ 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) ||@@ -959,10 +1113,15 @@ ${genHintItemHTML(item)}const undoContext = shouldCaptureHintUndoFocus(this.splitChar, Constants.BLOCK_HINT_KEYS, value) ?getUndoFocusContext(protyle.wysiwyg.element, range, true) : undefined;// 自顶向下法新建文档后光标定位问题 https://github.com/siyuan-note/siyuan/issues/299+ if (this.consumeCloseKey && range.collapsed) {+ this.getRefBracketContext(protyle, range);+ }if (this.lastIndex > -1) {range.setStart(range.startContainer, this.lastIndex);focusByRange(range);}+ // 自动闭合时,光标后的闭合符随查询一起被替换+ this.consumeRefBracketClose(range);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);@@ -1500,6 +1659,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) => {// 关闭标签搜索后 # 不再作为触发符,避免影响 / 等后续提示@@ -1545,7 +1706,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/hint/refBrackets.dom.test.ts b/app/src/protyle/hint/refBrackets.dom.test.tsnew file mode 100644index 0000000000..196bbf3f9a--- /dev/null+++ b/app/src/protyle/hint/refBrackets.dom.test.ts@@ -0,0 +1,179 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {createSourceFile, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";++const browserCases = (source: string) => {+ const check = require("node:assert/strict");+ const root = document.createElement("div");+ root.innerHTML = '<div data-node-id="block" data-type="NodeParagraph"><div contenteditable="true"></div></div>';+ document.body.append(root);+ const editable = root.firstElementChild.firstElementChild;+ window.siyuan = {config: {editor: {autoCloseRefBrackets: true, hashTagSearch: true}}} as any;+ const transactions: {before: string; after: string}[] = [];+ const dependencies = {+ Constants: {BLOCK_HINT_KEYS: ["[[", "(("], BLOCK_HINT_CLOSE_KEYS: {"[[": "]]", "((": "))"}, SIZE_TITLE: 512},+ hasClosestByAttribute: (node: Node, attribute: string, value: string) =>+ (node.nodeType === 3 ? node.parentElement : node as Element).closest(`[${attribute}~="${value}"]`),+ hasClosestBlock: (node: Node) => node.parentElement.closest("[data-node-id]"),+ focusByRange: (range: Range) => { getSelection().removeAllRanges(); getSelection().addRange(range); },+ getSelectionOffset: (_node: Node, _root: Element, range: Range) => ({start: range.startOffset}),+ getWholeTextOffset: (_node: Node, offset: number) => offset,+ getUndoFocusContext: () => ({id: "block"}),+ hideElements: (): undefined => undefined,+ updateTransaction: (_protyle: unknown, block: Element, before: string) => transactions.push({before, after: block.outerHTML}),+ };+ const Hint = new Function(...Object.keys(dependencies), source + "; return Hint;")(...Object.values(dependencies));+ const hint = new Hint();+ const protyle = {notebookId: "box", block: {rootID: "root"}, wysiwyg: {element: root, preventKeyup: false},+ toolbar: {range: undefined as Range}};+ hint.element = document.createElement("div");+ hint.element.className = "fn__none";+ let renders = 0;+ hint.render = () => {+ renders++;+ const range = getSelection().getRangeAt(0);+ hint.getKey(range.startContainer.textContent.substring(0, range.startOffset),+ range.startContainer.textContent.substring(range.startOffset), [{key: "[["}]);+ };+ const reset = (text: string, offset: number, split = false) => {+ editable.replaceChildren(document.createTextNode(text));+ if (split) {+ editable.replaceChildren(document.createTextNode(text.slice(0, 1)), document.createTextNode(text.slice(1)));+ }+ const node = editable.lastChild as Text;+ const range = document.createRange();+ range.setStart(node, split ? offset - 1 : offset);+ range.collapse(true);+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ hint.refBracketRange = undefined;+ hint.refBracketOrigin = undefined;+ hint.refCloseContext = undefined;+ hint.splitChar = "[[";+ hint.lastIndex = 0;+ hint.consumeCloseKey = true;+ return range;+ };+ const before = (inputType: string, data: string = null) =>+ hint.handleRefBracketBeforeInput(protyle, new InputEvent("beforeinput", {inputType, data}));++ let range = reset("[[ tail", 2, true);+ hint.autoCloseRefBrackets(protyle, range);+ check.equal(editable.textContent, "[[]] tail");+ check.equal(range.startOffset, 2);+ (range.startContainer as Text).insertData(2, "Title");+ range.setStart(range.startContainer, 7);+ range.collapse(true);+ check.equal(before("insertText", "]"), true);+ check.equal(renders, 0);+ check.equal(before("insertText", "]"), true);+ check.equal(renders, 1);+ check.equal(hint.closeKeyTyped, true);+ check.equal(editable.textContent, "[[Title]] tail");+ const context = hint.getRefCloseContext(protyle);+ check.ok(context);+ check.equal(context.text, "[[Title]]");+ range.setStart(range.startContainer, 3);+ range.collapse(true);+ check.equal(hint.isRefCloseContextCurrent(protyle, context), false);+ range.setStart(range.startContainer, 9);+ range.collapse(true);+ check.equal(hint.isRefCloseContextCurrent(protyle, context), true);+ (range.startContainer as Text).insertData(3, "changed");+ check.equal(hint.isRefCloseContextCurrent(protyle, context), false);++ range = reset("[[", 2);+ hint.autoCloseRefBrackets(protyle, range);+ editable.replaceChildren(document.createTextNode("[[Title]]"));+ range = document.createRange();+ range.setStart(editable.firstChild, 7);+ range.collapse(true);+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ check.equal(before("insertText", "]"), true);+ check.equal(before("insertText", "]"), true);+ check.ok(hint.getRefCloseContext(protyle));++ range = reset("[[", 2);+ hint.autoCloseRefBrackets(protyle, range);+ check.equal(before("deleteContentBackward"), true);+ check.equal(editable.textContent, "");+ check.equal(range.startOffset, 0);+ check.equal(transactions.length, 1);+ check.match(transactions[0].before, /\[\[\]\]/);+ check.equal(protyle.wysiwyg.preventKeyup, true);++ for (const offset of [7, 8]) {+ range = reset("[[", 2);+ hint.autoCloseRefBrackets(protyle, range);+ (range.startContainer as Text).insertData(2, "Title");+ range.setStart(range.startContainer, offset);+ range.setEnd(range.startContainer, offset);+ range.setStart(range.startContainer, 0);+ hint.consumeRefBracketClose(range);+ check.equal(range.toString(), "[[Title]]");+ }+ range = reset("[[Title]]", 7);+ check.equal(before("insertText", "]"), false);+ check.equal(hint.getRefCloseContext(protyle), undefined);+ for (const type of ["code", "NodeCodeBlock", "inline-math"]) {+ range = reset("[[", 2);+ editable.setAttribute("data-type", type);+ hint.autoCloseRefBrackets(protyle, range);+ check.equal(editable.textContent, "[[");+ editable.removeAttribute("data-type");+ }+ range = reset("[[", 2);+ window.siyuan.config.editor.autoCloseRefBrackets = false;+ hint.autoCloseRefBrackets(protyle, range);+ check.equal(editable.textContent, "[[");+ return "Reference bracket cases passed";+};++test("reference brackets preserve native ranges, close once, delete together and reject stale commits", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 45000,+}, async () => {+ const file = createSourceFile("index.ts", readFileSync(path.join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest, true);+ const hint = file.statements.find(isClassDeclaration);+ const names = ["autoCloseRefBrackets", "handleRefBracketBeforeInput", "getRefBracketContext", "canResumeBlockHint",+ "getRefCloseContext", "isRefCloseContextCurrent", "consumeRefBracketClose", "getKey"];+ const methods = names.map(name => hint.members.find(member => member.name?.getText(file) === name).getText(file));+ const helpers = readFileSync(path.join(__dirname, "blockHintRange.ts"), "utf8").replaceAll("export ", "");+ const source = transpileModule(helpers + "\nclass Hint {" + methods.join("\n") + "}", {+ compilerOptions: {target: ScriptTarget.ES2021},+ }).outputText;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-ref-bracket-test-"));+ const script = path.join(temporary, "run.cjs");+ const expression = `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)})`;+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("about:blank");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(expression)}));+ app.exit(0);+ } catch (error) {+ console.error(error);+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 40000, windowsHide: true});+ assert.match(result.stdout, /Reference bracket cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));+ assert.ok(path.basename(temporary).startsWith("siyuan-ref-bracket-test-"));+ rmSync(temporary, {recursive: true, force: true});+ }+});diff --git a/app/src/protyle/hint/slashUndo.test.ts b/app/src/protyle/hint/slashUndo.test.tsindex 94b1ae709d..50acdc3434 100644--- a/app/src/protyle/hint/slashUndo.test.ts+++ b/app/src/protyle/hint/slashUndo.test.ts@@ -11,7 +11,8 @@ import {shouldCaptureHintUndoFocus} from "./blockHintRange";const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");assert.ok(declaration && isClassDeclaration(declaration));-const fill = declaration.members.find(member => member.name?.getText(source) === "fill").getText(source);+const fill = declaration.members.filter(member => ["fill", "consumeRefBracketClose"].includes(member.name?.getText(source)))+ .map(member => member.getText(source)).join("\n");test("current time replaces the command through one insertion with its original undo context", () => {const code = transpileModule(`class Hint { ${fill} } new Hint();`, {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..9ec422a1c3 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1796,7 +1796,7 @@ export type SearchPath = { "blocks"?: Array<SearchBlock | null>; "box": string;export type SearchPathRequestInput = { "path": string; };-export type SearchRefBlockRequestInput = { "beforeLen"?: number; "id"?: string | null; "isDatabase"?: boolean | null; "isSquareBrackets"?: boolean | null; "k"?: string; "notebook"?: string | null; "reqId"?: JSONValue | null; "rootID"?: string; };+export type SearchRefBlockRequestInput = { "beforeLen"?: number; "exactDocTitle"?: boolean | null; "id"?: string | null; "isDatabase"?: boolean | null; "isSquareBrackets"?: boolean | null; "k"?: string; "notebook"?: string | null; "reqId"?: JSONValue | null; "rootID"?: string; };export type SearchRefCorrelation = { "reqId": JSONValue; };@@ -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; };@@ -6464,6 +6464,12 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 的 exactDocTitle 默认关闭,保留候选搜索行为;启用后仅匹配完整文档标题,+ * 先区分大小写,再忽略大小写,同级匹配按 ID 升序取一个,排除 id 和 rootID。+ * 精确匹配不受全文搜索字段、类型、忽略规则或结果上限影响;未匹配时 newDoc 为 true。+ * 保留发布权限、加密笔记本租约和原有响应变体,查询或文档读取失败时返回错误。+ */"/api/search/searchRefBlock": {request: SearchRefBlockRequestInput;response: { "code": 0; "data": SearchRefResult | (SearchRefCorrelation & { "blocks"?: never; "k"?: never; "newDoc"?: never; }); "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | SearchRefResult | (SearchRefCorrelation & { "blocks"?: never; "k"?: never; "newDoc"?: never; }); "msg": string; };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/contract_search_test.go b/kernel/api/contract_search_test.goindex 0fb7ed1998..56f4787f4e 100644--- a/kernel/api/contract_search_test.go+++ b/kernel/api/contract_search_test.go@@ -14,8 +14,10 @@ import ("github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/cache""github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -144,16 +146,18 @@ func TestAPIContractSearchLockedNotebook(t *testing.T) {engine := gin.New()engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })engine.POST("/api/search/searchRefBlock", searchRefBlock)- recorder := httptest.NewRecorder()- engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/search/searchRefBlock", strings.NewReader(`{"id":false,"notebook":"`+boxID+`","reqId":7}`)))- requireAPIContract(t, "POST", "/api/search/searchRefBlock", recorder)- var response struct {- Code int `json:"code"`- Msg string `json:"msg"`- Data json.RawMessage `json:"data"`- }- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 || response.Msg != "encrypted notebook is locked, please unlock it first" || string(response.Data) != `{"reqId":7}` {- t.Fatalf("locked ref search order changed: %s, %v", recorder.Body.String(), err)+ for _, extra := range []string{"", `,"exactDocTitle":true`} {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/search/searchRefBlock", strings.NewReader(`{"id":false,"notebook":"`+boxID+`","reqId":7`+extra+`}`)))+ requireAPIContract(t, "POST", "/api/search/searchRefBlock", recorder)+ var response struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 || response.Msg != "encrypted notebook is locked, please unlock it first" || string(response.Data) != `{"reqId":7}` {+ t.Fatalf("locked ref search order changed: %s, %v", recorder.Body.String(), err)+ }}}@@ -186,6 +190,7 @@ func TestAPIContractSearchPathAndSubtypeCompatibility(t *testing.T) {func testSearchQueryContracts(t *testing.T, docID string) {t.Helper()testSearchAssetMetadataContract(t)+ testExactRefDocTitleContract(t, docID)for _, entry := range []struct {path, body stringhandler gin.HandlerFunc@@ -219,6 +224,67 @@ func testSearchQueryContracts(t *testing.T, docID string) {}}+// 精确标题解析在独立契约测试进程中读取真实文档,覆盖搜索过滤和块命名干扰。+func testExactRefDocTitleContract(t *testing.T, sourceID string) {+ t.Helper()+ previousSearch := model.Conf.Search.Load()+ search := conf.NewSearch()+ search.Limit, search.Document, search.Name, search.Alias = 1, false, true, true+ model.Conf.Search.Store(search)+ defer model.Conf.Search.Store(previousSearch)+ for _, item := range []struct{ id, title, name string }{+ {"20261014000001-refttl1", "target", ""},+ {"20261014000002-refttl2", "Another document", "Target"},+ {"20261014000003-refttl3", "Target", ""},+ {"20261014000004-refttl4", "Äpfel", ""},+ } {+ tree := treenode.NewTree("20260912000000-boxapi1", "/"+item.id+".sy", "/"+item.title, item.title)+ tree.Root.SetIALAttr("name", item.name)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ sql.UpsertTreeQueue(tree)+ }+ sql.FlushQueue()+ engine := gin.New()+ engine.Use(boxLeaseMiddleware, func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator) })+ engine.POST("/api/search/searchRefBlock", searchRefBlock)+ for _, item := range []struct{ title, want string }{+ {"Target", "20261014000003-refttl3"},+ {"TARGET", "20261014000001-refttl1"},+ {"äpfel", "20261014000004-refttl4"},+ {"missing", ""},+ {"", ""},+ } {+ body, err := json.Marshal(map[string]string{"id": sourceID, "rootID": sourceID, "k": item.title})+ if err != nil {+ t.Fatal(err)+ }+ body = append(body[:len(body)-1], []byte(`,"beforeLen":0,"exactDocTitle":true,"reqId":12}`)...)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/search/searchRefBlock", strings.NewReader(string(body))))+ requireAPIContract(t, "POST", "/api/search/searchRefBlock", recorder)+ var response struct {+ Code int `json:"code"`+ Data struct {+ Blocks []*apicontract.SearchBlock `json:"blocks"`+ NewDoc bool `json:"newDoc"`+ } `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {+ t.Fatalf("exact title request failed: %s, %v", recorder.Body.String(), err)+ }+ if item.want == "" {+ if len(response.Data.Blocks) != 0 || response.Data.NewDoc != (item.title != "") {+ t.Fatalf("absent title response changed: %s", recorder.Body.String())+ }+ } else if len(response.Data.Blocks) != 1 || response.Data.Blocks[0].ID != item.want || response.Data.NewDoc {+ t.Fatalf("wrong title target: %s", recorder.Body.String())+ }+ }+}+// testSearchAssetMetadataContract 在独立数据库中验证图片元数据、文件筛选和分页。func testSearchAssetMetadataContract(t *testing.T) {t.Helper()diff --git a/kernel/api/publish_encrypted_test.go b/kernel/api/publish_encrypted_test.goindex 05405f1318..4bf2c6037f 100644--- a/kernel/api/publish_encrypted_test.go+++ b/kernel/api/publish_encrypted_test.go@@ -24,6 +24,7 @@ import ("testing""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util"@@ -54,6 +55,25 @@ func TestPublishReaderSearchAndBacklinkEncryptedNotebook(t *testing.T) {})engine.POST("/api/search/fullTextSearchBlock", fullTextSearchBlock)engine.POST("/api/ref/getBacklink2", getBacklink2)+ engine.POST("/api/search/searchRefBlock", searchRefBlock)++ t.Run("exact reference title", func(t *testing.T) {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/search/searchRefBlock",+ strings.NewReader(`{"id":"block","k":"secret","notebook":"`+boxID+`","exactDocTitle":true}`)))+ requireAPIContract(t, http.MethodPost, "/api/search/searchRefBlock", recorder)+ var response struct {+ Code int `json:"code"`+ Data struct {+ Blocks []*apicontract.SearchBlock `json:"blocks"`+ NewDoc bool `json:"newDoc"`+ } `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 ||+ len(response.Data.Blocks) != 0 || response.Data.NewDoc {+ t.Fatalf("published exact title search exposed encrypted data: %s, %v", recorder.Body.String(), err)+ }+ })t.Run("search", func(t *testing.T) {recorder := httptest.NewRecorder()diff --git a/kernel/api/search.go b/kernel/api/search.goindex e048bdcaf4..1612db94ba 100644--- a/kernel/api/search.go+++ b/kernel/api/search.go@@ -311,7 +311,16 @@ var searchRefBlock = contractHandler(apicontract.SearchRefBlock, func(c *gin.Con// 加密笔记本内的块引搜索走 InBox 版(只搜该 box 自己的加密 db,阻止跨加密边界引用)var blocks []*model.Blockvar newDoc bool- if notebook != "" && model.IsEncryptedBox(notebook) {+ if params.ExactDocTitle {+ boxID := ""+ if notebook != "" && model.IsEncryptedBox(notebook) {+ boxID = notebook+ }+ blocks, newDoc, err = model.SearchExactRefDocTitle(id, rootID, keyword, boxID)+ if err != nil {+ return apicontract.SearchRefBlock.FailureWithData(-1, err.Error(), echo)+ }+ } else if notebook != "" && model.IsEncryptedBox(notebook) {blocks, newDoc = model.SearchRefBlockInBox(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase, notebook)} else {blocks, newDoc = model.SearchRefBlock(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase)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/contracts.go b/kernel/apicontract/contracts.goindex f8e8645f85..27adcd7b64 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -754,6 +754,10 @@ var SemanticSearchBlock = define[SearchBlockRequest, SearchBlocksData]("semantic// SQL 模式保留换行、注释与字面量大小写,支持带别名的完整块投影。var FullTextSearchBlock = define[FullTextSearchBlockRequest, *FullTextSearchBlockData]("fullTextSearchBlock", "/api/search/fullTextSearchBlock", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")+// SearchRefBlock 的 exactDocTitle 默认关闭,保留候选搜索行为;启用后仅匹配完整文档标题,+// 先区分大小写,再忽略大小写,同级匹配按 ID 升序取一个,排除 id 和 rootID。+// 精确匹配不受全文搜索字段、类型、忽略规则或结果上限影响;未匹配时 newDoc 为 true。+// 保留发布权限、加密笔记本租约和原有响应变体,查询或文档读取失败时返回错误。var SearchRefBlock = define[SearchRefBlockRequest, SearchRefData]("searchRefBlock", "/api/search/searchRefBlock", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")var ListLoadedPlugins = define[EmptyRequest, []*LoadedPlugin]("listLoadedPlugins", "/api/plugin/listLoadedPlugins", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex fb067c5377..049eb55cef 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -38803,6 +38803,16 @@"beforeLen": {"type": "number"},+ "exactDocTitle": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"id": {"anyOf": [{@@ -39915,6 +39925,16 @@}]},+ "autoCloseRefBrackets": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"autoDirection": {"anyOf": [{@@ -44070,6 +44090,9 @@}]},+ "autoCloseRefBrackets": {+ "type": "boolean"+ },"autoDirection": {"type": "boolean"},@@ -44374,6 +44397,7 @@"allowHTMLBLockScript","allowSVGScript","assetOpen",+ "autoCloseRefBrackets","autoDirection","backlinkBlockSort","backlinkContainChildren",@@ -44529,6 +44553,16 @@}]},+ "autoCloseRefBrackets": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]+ },"autoDirection": {"anyOf": [{diff --git a/kernel/apicontract/search_ref.go b/kernel/apicontract/search_ref.goindex 380b6e5cc8..57e041543f 100644--- a/kernel/apicontract/search_ref.go+++ b/kernel/apicontract/search_ref.go@@ -14,6 +14,7 @@ type SearchRefBlockRequest struct {BeforeLen float64 `json:"beforeLen" api:"optional"`IsSquareBrackets bool `json:"isSquareBrackets" api:"optional,nullable"`IsDatabase bool `json:"isDatabase" api:"optional,nullable"`+ ExactDocTitle bool `json:"exactDocTitle" api:"optional,nullable"`Notebook string `json:"notebook" api:"optional,nullable,ignoretype"`ReqID JSONValue `json:"reqId" api:"optional,nullable"`fields map[string]json.RawMessage@@ -22,6 +23,7 @@ type SearchRefBlockRequest struct {type SearchRefParameters struct {IsSquareBrackets bool `json:"isSquareBrackets" api:"optional,nullable"`IsDatabase bool `json:"isDatabase" api:"optional,nullable"`+ ExactDocTitle bool `json:"exactDocTitle" api:"optional,nullable"`RootID string `json:"rootID"`ID string `json:"id"`K string `json:"k"`diff --git a/kernel/apicontract/search_test.go b/kernel/apicontract/search_test.goindex a3313852d0..2a35571dca 100644--- a/kernel/apicontract/search_test.go+++ b/kernel/apicontract/search_test.go@@ -111,3 +111,28 @@ func TestSearchRefDeferredParameters(t *testing.T) {t.Fatalf("ref input changed: %+v, %v, %v", params, err, decodeErr)}}++func TestSearchRefExactDocTitleContract(t *testing.T) {+ for _, body := range []string{+ `{"id":"block","rootID":"root","k":"title","beforeLen":0}`,+ `{"id":"block","rootID":"root","k":"title","beforeLen":0,"exactDocTitle":false}`,+ `{"id":"block","rootID":"root","k":"title","beforeLen":0,"exactDocTitle":null}`,+ `{"id":"block","rootID":"root","k":"title","beforeLen":0,"exactDocTitle":true}`,+ } {+ request, err := SearchRefBlock.Decode(strings.NewReader(body))+ if err != nil {+ t.Fatal(err)+ }+ params, err := request.Parameters()+ if err != nil || params.ExactDocTitle != strings.Contains(body, `"exactDocTitle":true`) {+ t.Fatalf("exact title option changed: %+v, %v", params, err)+ }+ }+ request, err := SearchRefBlock.Decode(strings.NewReader(`{"id":"block","rootID":"root","k":"title","beforeLen":0,"exactDocTitle":"true"}`))+ if err != nil {+ t.Fatal(err)+ }+ if _, err = request.Parameters(); err == nil {+ t.Fatal("invalid exact title flag accepted")+ }+}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,diff --git a/kernel/model/ref_title.go b/kernel/model/ref_title.gonew file mode 100644index 0000000000..f030b6eba0--- /dev/null+++ b/kernel/model/ref_title.go@@ -0,0 +1,45 @@+package model++import (+ "fmt"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// SearchExactRefDocTitle 在指定索引边界内解析完整文档标题,并读取目标文档后生成块引用。+func SearchExactRefDocTitle(id, rootID, title, boxID string) (blocks []*Block, newDoc bool, err error) {+ blocks = []*Block{}+ title = strings.TrimSpace(title)+ if title == "" {+ return+ }+ targetID, err := sql.QueryExactDocTitleIDInBox(title, id, rootID, boxID)+ if err != nil {+ return nil, false, err+ }+ if targetID == "" {+ return blocks, true, nil+ }+ bt := treenode.GetBlockTreeInExactBox(targetID, boxID)+ if bt == nil {+ return nil, false, fmt.Errorf("document [%s] not found", targetID)+ }+ tree, err := loadTreeByBlockTree(bt)+ if err != nil {+ return nil, false, err+ }+ if tree == nil || !strings.EqualFold(tree.Root.IALAttr("title"), title) {+ return nil, false, fmt.Errorf("document [%s] title index is outdated", targetID)+ }+ block := fromSQLBlock(sql.BuildBlockFromNode(tree.Root, tree), "", 0)+ if block == nil {+ return nil, false, fmt.Errorf("document [%s] index is unavailable", targetID)+ }+ block.RefText = getNodeRefText(tree.Root)+ blocks = append(blocks, block)+ prependNotebookNameInHPath(blocks)+ filterSelfHPath(blocks)+ return+}diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.goindex ccfe0d1320..9088ce9537 100644--- a/kernel/sql/encrypted_query.go+++ b/kernel/sql/encrypted_query.go@@ -49,6 +49,29 @@ func QueryDailyNoteRootIDsInBox(boxID, name, date string) (ids []string, err errreturn ids, rows.Err()}+// QueryExactDocTitleIDInBox 按完整文档标题查询,先精确匹配,再匹配 Unicode 大小写,保留数据库错误。+func QueryExactDocTitleIDInBox(title, id, rootID, boxID string) (ret string, err error) {+ rows, err := queryForBox(boxID, "SELECT id, content FROM blocks WHERE type = 'd' AND id != ? AND id != ? ORDER BY id", id, rootID)+ if err != nil {+ return "", err+ }+ defer rows.Close()+ var folded string+ for rows.Next() {+ var candidateID, candidateTitle string+ if err = rows.Scan(&candidateID, &candidateTitle); err != nil {+ return "", err+ }+ if candidateTitle == title {+ return candidateID, nil+ }+ if folded == "" && strings.EqualFold(candidateTitle, title) {+ folded = candidateID+ }+ }+ return folded, rows.Err()+}+// GetBlockInBox 按 id 在指定 box 的 db 里查 block。boxID 为空则查全局 db。func GetBlockInBox(id, boxID string) (ret *Block) {ret = getBlockCacheInBox(id, boxID)diff --git a/kernel/sql/ref_title_test.go b/kernel/sql/ref_title_test.gonew file mode 100644index 0000000000..ab27f3a727--- /dev/null+++ b/kernel/sql/ref_title_test.go@@ -0,0 +1,55 @@+package sql++import (+ "strings"+ "testing"+)++func TestExactRefDocTitleContractQuery(t *testing.T) {+ database, boxID := useEncryptedQueryTestDB(t)+ for _, item := range []struct{ id, title, name, typ string }{+ {"a-folded", "target", "", "d"},+ {"b-named", "Another document", "Target", "d"},+ {"c-exact", "Target", "", "d"},+ {"d-duplicate", "Target", "", "d"},+ {"e-unicode", "Äpfel", "", "d"},+ {"f-literal", "a'[%]_\\b", "", "d"},+ {"g-long", strings.Repeat("title", 120), "", "d"},+ {"h-paragraph", "Paragraph", "", "p"},+ } {+ if _, err := database.Exec("INSERT INTO blocks (id, content, name, type) VALUES (?, ?, ?, ?)", item.id, item.title, item.name, item.typ); err != nil {+ t.Fatal(err)+ }+ }+ for _, item := range []struct{ title, id, rootID, want string }{+ {"Target", "", "", "c-exact"},+ {"TARGET", "", "", "a-folded"},+ {"Target", "c-exact", "d-duplicate", "a-folded"},+ {"Another document", "", "", "b-named"},+ {"äPFEL", "", "", "e-unicode"},+ {"a'[%]_\\b", "", "", "f-literal"},+ {strings.Repeat("title", 120), "", "", "g-long"},+ {"Paragraph", "", "", ""},+ {"missing", "", "", ""},+ } {+ id, err := QueryExactDocTitleIDInBox(item.title, item.id, item.rootID, boxID)+ if err != nil || id != item.want {+ t.Fatalf("title %q: got %q, want %q, error %v", item.title, id, item.want, err)+ }+ }+ t.Run("notebook boundary", func(t *testing.T) {+ otherDB, otherBox := useEncryptedQueryTestDB(t)+ if _, err := otherDB.Exec("INSERT INTO blocks (id, content, type) VALUES ('other', 'Target', 'd')"); err != nil {+ t.Fatal(err)+ }+ if id, err := QueryExactDocTitleIDInBox("Target", "", "", otherBox); err != nil || id != "other" {+ t.Fatalf("notebook boundary changed: %q, %v", id, err)+ }+ })+ if err := database.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err := QueryExactDocTitleIDInBox("Target", "", "", boxID); err == nil {+ t.Fatal("database failure treated as an absent title")+ }+}