Skip to content

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

:sparkles: Support configurable cursor surrounding lines https://github.com/siyuan-note/siyuan/issues/19003

Daniel8cb053ad30ee
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 52d897b44d..7974f5fe0e 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "أسطر السياق حول المؤشر",
+ "cursorSurroundingLinesTip": "الحد الأدنى لعدد الأسطر المرئية بين المؤشر وحافتي المحرر العلوية والسفلية عند التنقل عموديًا باستخدام لوحة المفاتيح، و0 لتعطيل الميزة",
"applicationZoom": "تكبير/تصغير واجهة التطبيق",
"increaseEditorFontSize": "زيادة حجم خط المحرر",
"decreaseEditorFontSize": "تقليل حجم خط المحرر",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 6809067841..65cd49fd76 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Kontextzeilen um den Cursor",
+ "cursorSurroundingLinesTip": "Mindestanzahl sichtbarer Zeilen zwischen Cursor und oberem bzw. unterem Editorrand bei vertikaler Tastaturnavigation, 0 deaktiviert die Funktion",
"applicationZoom": "Anwendungsoberfläche skalieren",
"increaseEditorFontSize": "Editorschrift vergrößern",
"decreaseEditorFontSize": "Editorschrift verkleinern",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 5182c9bb5f..3cd7b44c49 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Cursor surrounding lines",
+ "cursorSurroundingLinesTip": "Minimum number of visible lines between the cursor and the top or bottom edge of the editor when navigating vertically with the keyboard, 0 to disable",
"applicationZoom": "Application Zoom",
"increaseEditorFontSize": "Increase Editor Font Size",
"decreaseEditorFontSize": "Decrease Editor Font Size",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 8cd0b6f6c0..32baecf212 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Líneas de contexto alrededor del cursor",
+ "cursorSurroundingLinesTip": "Número mínimo de líneas visibles entre el cursor y los bordes superior e inferior del editor al desplazarse verticalmente con el teclado, 0 para desactivar",
"applicationZoom": "Escala de la interfaz de la aplicación",
"increaseEditorFontSize": "Aumentar el tamaño de fuente del editor",
"decreaseEditorFontSize": "Reducir el tamaño de fuente del editor",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 6e6f168f49..42f5ee2b64 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Lignes de contexte autour du curseur",
+ "cursorSurroundingLinesTip": "Nombre minimal de lignes visibles entre le curseur et les bords supérieur et inférieur de l’éditeur lors d’un déplacement vertical au clavier, 0 pour désactiver",
"applicationZoom": "Zoom de l’interface de l’application",
"increaseEditorFontSize": "Augmenter la taille de police de l’éditeur",
"decreaseEditorFontSize": "Réduire la taille de police de l’éditeur",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index c290f9b4d3..5b1e8c3aad 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "שורות הקשר סביב הסמן",
+ "cursorSurroundingLinesTip": "מספר השורות הגלויות המזערי בין הסמן לקצה העליון או התחתון של העורך בעת ניווט אנכי באמצעות המקלדת, 0 להשבתה",
"applicationZoom": "שינוי קנה המידה של ממשק היישום",
"increaseEditorFontSize": "הגדלת גודל הגופן בעורך",
"decreaseEditorFontSize": "הקטנת גודל הגופן בעורך",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 0686566241..76f4653580 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "कर्सर के आसपास संदर्भ पंक्तियाँ",
+ "cursorSurroundingLinesTip": "कीबोर्ड से लंबवत नेविगेट करते समय कर्सर और संपादक के ऊपरी या निचले किनारे के बीच दिखाई देने वाली पंक्तियों की न्यूनतम संख्या, अक्षम करने के लिए 0",
"applicationZoom": "एप्लिकेशन इंटरफ़ेस ज़ूम",
"increaseEditorFontSize": "संपादक फ़ॉन्ट का आकार बढ़ाएँ",
"decreaseEditorFontSize": "संपादक फ़ॉन्ट का आकार घटाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 0ad1652da1..29f2eb3612 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Baris konteks di sekitar kursor",
+ "cursorSurroundingLinesTip": "Jumlah minimum baris yang terlihat antara kursor dan tepi atas atau bawah editor saat bernavigasi secara vertikal dengan papan ketik, 0 untuk menonaktifkan",
"applicationZoom": "Zoom antarmuka aplikasi",
"increaseEditorFontSize": "Perbesar ukuran font editor",
"decreaseEditorFontSize": "Perkecil ukuran font editor",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 7c18b7e676..60312ab1c7 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Righe di contesto attorno al cursore",
+ "cursorSurroundingLinesTip": "Numero minimo di righe visibili tra il cursore e il bordo superiore o inferiore dell’editor durante la navigazione verticale con la tastiera, 0 per disattivare",
"applicationZoom": "Zoom dell’interfaccia dell’applicazione",
"increaseEditorFontSize": "Aumenta la dimensione del carattere dell’editor",
"decreaseEditorFontSize": "Riduci la dimensione del carattere dell’editor",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 6c22a0fc49..dbd7508bc0 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "カーソル周辺のコンテキスト行数",
+ "cursorSurroundingLinesTip": "キーボードで上下に移動するとき、カーソルとエディターの上端または下端との間に表示する最小行数、0 で無効",
"applicationZoom": "アプリケーションインターフェースのズーム",
"increaseEditorFontSize": "エディタのフォントサイズを拡大",
"decreaseEditorFontSize": "エディタのフォントサイズを縮小",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 15265811cc..aaf0f030b9 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "커서 주변 문맥 줄 수",
+ "cursorSurroundingLinesTip": "키보드로 세로 이동할 때 커서와 편집기 위쪽 또는 아래쪽 가장자리 사이에 표시할 최소 줄 수, 0이면 비활성화",
"applicationZoom": "애플리케이션 인터페이스 확대/축소",
"increaseEditorFontSize": "편집기 글꼴 크기 늘리기",
"decreaseEditorFontSize": "편집기 글꼴 크기 줄이기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 82e1de7d90..bde8f2aa5d 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Contextregels rond de cursor",
+ "cursorSurroundingLinesTip": "Minimumaantal zichtbare regels tussen de cursor en de boven- of onderrand van de editor bij verticale toetsenbordnavigatie, 0 om uit te schakelen",
"applicationZoom": "Zoom van toepassingsinterface",
"increaseEditorFontSize": "Lettergrootte van editor vergroten",
"decreaseEditorFontSize": "Lettergrootte van editor verkleinen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index d92a833544..9937127dcd 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Wiersze kontekstu wokół kursora",
+ "cursorSurroundingLinesTip": "Minimalna liczba widocznych wierszy między kursorem a górną lub dolną krawędzią edytora podczas pionowej nawigacji klawiaturą, 0 wyłącza funkcję",
"applicationZoom": "Powiększenie interfejsu aplikacji",
"increaseEditorFontSize": "Zwiększ rozmiar czcionki edytora",
"decreaseEditorFontSize": "Zmniejsz rozmiar czcionki edytora",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 54e8a3a564..19e56d31eb 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Linhas de contexto ao redor do cursor",
+ "cursorSurroundingLinesTip": "Número mínimo de linhas visíveis entre o cursor e as bordas superior ou inferior do editor ao navegar verticalmente com o teclado, 0 para desativar",
"applicationZoom": "Zoom da interface do aplicativo",
"increaseEditorFontSize": "Aumentar o tamanho da fonte do editor",
"decreaseEditorFontSize": "Diminuir o tamanho da fonte do editor",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 78a2f8b39d..7f3cb3bc0b 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Строки контекста вокруг курсора",
+ "cursorSurroundingLinesTip": "Минимальное количество видимых строк между курсором и верхним или нижним краем редактора при вертикальной навигации с клавиатуры, 0 для отключения",
"applicationZoom": "Масштаб интерфейса приложения",
"increaseEditorFontSize": "Увеличить размер шрифта редактора",
"decreaseEditorFontSize": "Уменьшить размер шрифта редактора",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 91a866966a..8f9c88596b 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Riadky kontextu okolo kurzora",
+ "cursorSurroundingLinesTip": "Minimálny počet viditeľných riadkov medzi kurzorom a horným alebo dolným okrajom editora pri zvislej navigácii klávesnicou, 0 funkciu vypne",
"applicationZoom": "Priblíženie rozhrania aplikácie",
"increaseEditorFontSize": "Zväčšiť písmo editora",
"decreaseEditorFontSize": "Zmenšiť písmo editora",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 25bfc9a67c..cab51751f3 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "บรรทัดบริบทรอบเคอร์เซอร์",
+ "cursorSurroundingLinesTip": "จำนวนบรรทัดที่มองเห็นขั้นต่ำระหว่างเคอร์เซอร์กับขอบบนหรือขอบล่างของตัวแก้ไขเมื่อเลื่อนในแนวตั้งด้วยแป้นพิมพ์ โดย 0 คือปิดใช้งาน",
"applicationZoom": "ซูมส่วนติดต่อแอปพลิเคชัน",
"increaseEditorFontSize": "เพิ่มขนาดแบบอักษรของตัวแก้ไข",
"decreaseEditorFontSize": "ลดขนาดแบบอักษรของตัวแก้ไข",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index fdbd247180..428e4fb39d 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "İmleç çevresindeki bağlam satırları",
+ "cursorSurroundingLinesTip": "Klavye ile dikey gezinirken imleç ile düzenleyicinin üst veya alt kenarı arasında görünecek en az satır sayısı, devre dışı bırakmak için 0",
"applicationZoom": "Uygulama arayüzü yakınlaştırması",
"increaseEditorFontSize": "Düzenleyici yazı tipi boyutunu artır",
"decreaseEditorFontSize": "Düzenleyici yazı tipi boyutunu azalt",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 546d8869ac..db3dd55741 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "Рядки контексту навколо курсора",
+ "cursorSurroundingLinesTip": "Мінімальна кількість видимих рядків між курсором і верхнім або нижнім краєм редактора під час вертикальної навігації з клавіатури, 0 для вимкнення",
"applicationZoom": "Масштаб інтерфейсу застосунку",
"increaseEditorFontSize": "Збільшити розмір шрифту редактора",
"decreaseEditorFontSize": "Зменшити розмір шрифту редактора",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index d8db506980..6668dc0cc2 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "光标上下文行数",
+ "cursorSurroundingLinesTip": "使用键盘纵向移动光标时,光标与编辑器上下边缘之间至少保留的可见行数,0 表示禁用",
"applicationZoom": "应用界面缩放",
"increaseEditorFontSize": "增大编辑器字号",
"decreaseEditorFontSize": "减小编辑器字号",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index f31f9a17df..7d17412229 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "cursorSurroundingLines": "游標上下文行數",
+ "cursorSurroundingLinesTip": "使用鍵盤縱向移動游標時,游標與編輯器上下邊緣之間至少保留的可見行數,0 表示停用",
"applicationZoom": "應用程式介面縮放",
"increaseEditorFontSize": "增大編輯器字型大小",
"decreaseEditorFontSize": "減小編輯器字型大小",
diff --git a/app/src/config/tabs/editorTab.ts b/app/src/config/tabs/editorTab.ts
index c9bef73e69..6467165358 100644
--- a/app/src/config/tabs/editorTab.ts
+++ b/app/src/config/tabs/editorTab.ts
@@ -45,6 +45,12 @@ const registerEditorBehaviorGroup = (tab: SettingTabBuilder) => {
max: 8,
step: 2,
});
+ group.number("editor.cursorSurroundingLines", {
+ title: window.siyuan.languages.cursorSurroundingLines,
+ desc: window.siyuan.languages.cursorSurroundingLinesTip,
+ min: 0,
+ max: 20,
+ });
group.switch("editor.listLogicalOutdent", {
title: window.siyuan.languages.outlineOutdent,
desc: window.siyuan.languages.outlineOutdentTip,
diff --git a/app/src/protyle/wysiwyg/caretScroll.ts b/app/src/protyle/wysiwyg/caretScroll.ts
new file mode 100644
index 0000000000..54cf305440
--- /dev/null
+++ b/app/src/protyle/wysiwyg/caretScroll.ts
@@ -0,0 +1,67 @@
+import {getSelectionPosition} from "../util/selection";
+import {getCaretScrollDelta, type TCaretVerticalDirection} from "./caretScrollCore";
+
+const pendingFrames = new WeakMap<HTMLElement, number>();
+
+const getLineHeight = (element: Element) => {
+ const style = getComputedStyle(element);
+ const lineHeight = parseFloat(style.lineHeight);
+ if (Number.isFinite(lineHeight) && lineHeight > 0) {
+ return lineHeight;
+ }
+ const fontSize = parseFloat(style.fontSize);
+ return Number.isFinite(fontSize) && fontSize > 0 ? fontSize * 1.625 : window.siyuan.config.editor.fontSize * 1.625;
+};
+
+const scrollCaretIntoMargin = (protyle: IProtyle, direction: TCaretVerticalDirection) => {
+ const selection = window.getSelection();
+ if (!selection?.focusNode || !protyle.wysiwyg.element.contains(selection.focusNode)) {
+ return;
+ }
+ const focusElement = selection.focusNode.nodeType === Node.ELEMENT_NODE ?
+ selection.focusNode as Element : selection.focusNode.parentElement;
+ const editableElement = focusElement?.closest("[contenteditable=\"true\"]");
+ if (!editableElement || !protyle.wysiwyg.element.contains(editableElement)) {
+ return;
+ }
+ const range = document.createRange();
+ try {
+ range.setStart(selection.focusNode, selection.focusOffset);
+ } catch {
+ return;
+ }
+ range.collapse(true);
+ const caretPosition = getSelectionPosition(editableElement, range);
+ if (!Number.isFinite(caretPosition.top) || caretPosition.left === 0 && caretPosition.top === 0) {
+ return;
+ }
+ const lineHeight = getLineHeight(editableElement);
+ const viewportRect = protyle.contentElement.getBoundingClientRect();
+ const delta = getCaretScrollDelta({
+ caretTop: caretPosition.top,
+ caretHeight: lineHeight,
+ viewportTop: viewportRect.top,
+ viewportHeight: viewportRect.height,
+ lineHeight,
+ surroundingLines: window.siyuan.config.editor.cursorSurroundingLines,
+ }, direction);
+ if (delta !== 0) {
+ protyle.contentElement.scrollTop += delta;
+ }
+};
+
+export const scheduleCaretScroll = (protyle: IProtyle, direction: TCaretVerticalDirection) => {
+ if (window.siyuan.config.editor.cursorSurroundingLines <= 0) {
+ return;
+ }
+ const pendingFrame = pendingFrames.get(protyle.contentElement);
+ if (pendingFrame !== undefined) {
+ cancelAnimationFrame(pendingFrame);
+ }
+ pendingFrames.set(protyle.contentElement, requestAnimationFrame(() => {
+ pendingFrames.delete(protyle.contentElement);
+ if (protyle.element.isConnected) {
+ scrollCaretIntoMargin(protyle, direction);
+ }
+ }));
+};
diff --git a/app/src/protyle/wysiwyg/caretScrollCore.test.ts b/app/src/protyle/wysiwyg/caretScrollCore.test.ts
new file mode 100644
index 0000000000..10edca0213
--- /dev/null
+++ b/app/src/protyle/wysiwyg/caretScrollCore.test.ts
@@ -0,0 +1,44 @@
+import {strict as assert} from "node:assert";
+import {describe, it} from "node:test";
+import {getCaretScrollDelta} from "./caretScrollCore";
+
+const geometry = {
+ caretTop: 100,
+ caretHeight: 20,
+ viewportTop: 0,
+ viewportHeight: 200,
+ lineHeight: 20,
+ surroundingLines: 2,
+};
+
+describe("getCaretScrollDelta", () => {
+ it("does not scroll while the caret remains inside the margin", () => {
+ assert.equal(getCaretScrollDelta(geometry, "up"), 0);
+ assert.equal(getCaretScrollDelta(geometry, "down"), 0);
+ });
+
+ it("scrolls upward by the amount crossing the top margin", () => {
+ assert.equal(getCaretScrollDelta({...geometry, caretTop: 30}, "up"), -10);
+ });
+
+ it("scrolls downward by the amount crossing the bottom margin", () => {
+ assert.equal(getCaretScrollDelta({...geometry, caretTop: 150}, "down"), 10);
+ });
+
+ it("does not scroll when the setting is disabled", () => {
+ assert.equal(getCaretScrollDelta({...geometry, caretTop: 0, surroundingLines: 0}, "up"), 0);
+ assert.equal(getCaretScrollDelta({...geometry, caretTop: 180, surroundingLines: 0}, "down"), 0);
+ });
+
+ it("limits the margin to half of a small viewport", () => {
+ const smallViewport = {...geometry, caretTop: 0, viewportHeight: 60, surroundingLines: 20};
+ assert.equal(getCaretScrollDelta(smallViewport, "up"), -20);
+ assert.equal(getCaretScrollDelta({...smallViewport, caretTop: 40}, "down"), 20);
+ });
+
+ it("accounts for a viewport that does not start at zero", () => {
+ const offsetViewport = {...geometry, caretTop: 120, viewportTop: 100};
+ assert.equal(getCaretScrollDelta(offsetViewport, "up"), -20);
+ assert.equal(getCaretScrollDelta({...offsetViewport, caretTop: 250}, "down"), 10);
+ });
+});
diff --git a/app/src/protyle/wysiwyg/caretScrollCore.ts b/app/src/protyle/wysiwyg/caretScrollCore.ts
new file mode 100644
index 0000000000..fe50ed8469
--- /dev/null
+++ b/app/src/protyle/wysiwyg/caretScrollCore.ts
@@ -0,0 +1,26 @@
+export type TCaretVerticalDirection = "up" | "down";
+
+interface ICaretScrollGeometry {
+ caretTop: number;
+ caretHeight: number;
+ viewportTop: number;
+ viewportHeight: number;
+ lineHeight: number;
+ surroundingLines: number;
+}
+
+export const getCaretScrollDelta = (geometry: ICaretScrollGeometry, direction: TCaretVerticalDirection) => {
+ if (geometry.surroundingLines <= 0 || geometry.viewportHeight <= 0 || geometry.lineHeight <= 0) {
+ return 0;
+ }
+ const caretHeight = Math.max(0, geometry.caretHeight);
+ const maximumMargin = Math.max(0, (geometry.viewportHeight - caretHeight) / 2);
+ const margin = Math.min(geometry.surroundingLines * geometry.lineHeight, maximumMargin);
+ if (direction === "up") {
+ const minimumCaretTop = geometry.viewportTop + margin;
+ return geometry.caretTop < minimumCaretTop ? geometry.caretTop - minimumCaretTop : 0;
+ }
+ const maximumCaretBottom = geometry.viewportTop + geometry.viewportHeight - margin;
+ const caretBottom = geometry.caretTop + caretHeight;
+ return caretBottom > maximumCaretBottom ? caretBottom - maximumCaretBottom : 0;
+};
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 9f145d7866..fc96ecb878 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -120,6 +120,7 @@ import {focusAVByArrow} from "../render/av/focus";
import {hideMessage, showMessage} from "../../dialog/message";
import {isMobile} from "../../util/functions";
import {confirmBlockRef} from "../../util/checkBlockRef";
+import {scheduleCaretScroll} from "./caretScroll";
export const getContentByInlineHTML = (range: Range, cb: (content: string) => void) => {
let html = "";
@@ -379,6 +380,12 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
window.siyuan.menus.menu.remove();
}
+ if (!event.altKey && isNotCtrl(event) && !event.isComposing &&
+ (event.key === "ArrowUp" || event.key === "ArrowDown") &&
+ !protyle.wysiwyg.element.querySelector(".protyle-wysiwyg--select")) {
+ scheduleCaretScroll(protyle, event.key === "ArrowUp" ? "up" : "down");
+ }
+
if (!["Alt", "Meta", "Shift", "Control", "CapsLock", "Escape"].includes(event.key) && protyle.options.render.breadcrumb) {
protyle.breadcrumb.hide();
}
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index dd2f0c68e8..d294c3b52a 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -687,6 +687,10 @@ declare namespace Config {
* The font size used in the editor
*/
fontSize: number;
+ /**
+ * 使用键盘纵向移动时光标周围至少保留的可见行数
+ */
+ cursorSurroundingLines: number;
/**
* Whether the editor uses maximum width
*/
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 5f1e64a428..4c805570f5 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -478,6 +478,7 @@ func setEditor(c *gin.Context) {
} else {
*editor.FloatWindowDelay = max(0, min(2000, *editor.FloatWindowDelay))
}
+ editor.CursorSurroundingLines = conf.NormalizeCursorSurroundingLines(editor.CursorSurroundingLines)
editor.AssetOpen = conf.NormalizeAssetOpen(editor.AssetOpen)
oldVirtualBlockRef := model.Conf.Editor.VirtualBlockRef
diff --git a/kernel/conf/editor.go b/kernel/conf/editor.go
index 62cb5ccdf3..6618362611 100644
--- a/kernel/conf/editor.go
+++ b/kernel/conf/editor.go
@@ -46,6 +46,7 @@ type EditorFont struct {
type Editor struct {
AllowSVGScript bool `json:"allowSVGScript"` // 允许执行 SVG 内脚本
AllowHTMLBLockScript bool `json:"allowHTMLBLockScript"` // 允许执行 HTML 内容中的脚本
+ CursorSurroundingLines int `json:"cursorSurroundingLines"` // 光标上下文行数
FontSize int `json:"fontSize"` // 字体大小
FontSizeScrollZoom bool `json:"fontSizeScrollZoom"` // 保留用于配置兼容,前端不再使用
FontFamily string `json:"fontFamily"` // 首选字体(兼容旧版本)
@@ -145,6 +146,7 @@ func normalizeEditorFontFamilies(fontFamilies []*EditorFont) []*EditorFont {
const (
MinDynamicLoadBlocks = 48
+ MaxCursorSurroundingLines = 20
DefaultHeadingNumberFormat = "decimal-hierarchical"
)
@@ -152,6 +154,10 @@ func NormalizeBacklinkExpandCount(count int) int {
return max(-1, count)
}
+func NormalizeCursorSurroundingLines(lines int) int {
+ return max(0, min(MaxCursorSurroundingLines, lines))
+}
+
func NewAssetOpen() *AssetOpen {
return &AssetOpen{
Click: AssetOpenActionFollowTab,
@@ -185,6 +191,7 @@ func normalizeAssetOpenAction(action, fallback string) string {
func NewEditor() *Editor {
return &Editor{
+ CursorSurroundingLines: 0,
FontSize: 16,
FontSizeScrollZoom: false,
CodeSyntaxHighlightLineNum: false,
diff --git a/kernel/conf/editor_test.go b/kernel/conf/editor_test.go
index dd6a6d3181..1c3c24ab9b 100644
--- a/kernel/conf/editor_test.go
+++ b/kernel/conf/editor_test.go
@@ -39,6 +39,27 @@ func TestNormalizeBacklinkExpandCount(t *testing.T) {
}
}
+func TestNormalizeCursorSurroundingLines(t *testing.T) {
+ tests := []struct {
+ name string
+ lines int
+ expected int
+ }{
+ {"clamps negative values", -1, 0},
+ {"preserves disabled state", 0, 0},
+ {"preserves configured lines", 5, 5},
+ {"clamps values above maximum", 21, MaxCursorSurroundingLines},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if actual := NormalizeCursorSurroundingLines(test.lines); actual != test.expected {
+ t.Fatalf("expected %d, got %d", test.expected, actual)
+ }
+ })
+ }
+}
+
func TestNormalizeAssetOpen(t *testing.T) {
defaults := NormalizeAssetOpen(nil)
if defaults.Click != AssetOpenActionFollowTab || defaults.CtrlClick != AssetOpenActionFolder ||
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 046071027f..7371d19425 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -493,6 +493,7 @@ func InitConf() {
} else {
*Conf.Editor.FloatWindowDelay = max(0, min(2000, *Conf.Editor.FloatWindowDelay))
}
+ Conf.Editor.CursorSurroundingLines = conf.NormalizeCursorSurroundingLines(Conf.Editor.CursorSurroundingLines)
if conf.MinDynamicLoadBlocks > Conf.Editor.DynamicLoadBlocks {
Conf.Editor.DynamicLoadBlocks = conf.MinDynamicLoadBlocks
}