From 9040993232cc080a0d50f4e593d2e3d1ab66c2bc Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Tue, 2 Jan 2024 15:26:36 +0100 Subject: [PATCH] Making code jumping slightly less bad when selecting (#592) --- web/cm_plugins/fenced_code.ts | 6 +++++- web/cm_plugins/util.ts | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/web/cm_plugins/fenced_code.ts b/web/cm_plugins/fenced_code.ts index be218de4..a2b45e65 100644 --- a/web/cm_plugins/fenced_code.ts +++ b/web/cm_plugins/fenced_code.ts @@ -4,6 +4,7 @@ import { decoratorStateField, invisibleDecoration, isCursorInRange, + shouldRenderAsCode, } from "./util.ts"; import { MarkdownWidget } from "./markdown_widget.ts"; import { IFrameWidget } from "./iframe_widget.ts"; @@ -14,7 +15,10 @@ export function fencedCodePlugin(editor: Client) { syntaxTree(state).iterate({ enter({ from, to, name, node }) { if (name === "FencedCode") { - if (isCursorInRange(state, [from, to])) return; + if (shouldRenderAsCode(state, [from, to])) { + // Don't render the widget if the cursor is inside the fenced code + return; + } const text = state.sliceDoc(from, to); const [_, lang] = text.match(/^```(\w+)?/)!; const codeWidgetCallback = editor.system.codeWidgetHook diff --git a/web/cm_plugins/util.ts b/web/cm_plugins/util.ts index 636bc4a2..b822fc80 100644 --- a/web/cm_plugins/util.ts +++ b/web/cm_plugins/util.ts @@ -157,6 +157,20 @@ export function isCursorInRange(state: EditorState, range: [number, number]) { ); } +export function shouldRenderAsCode( + state: EditorState, + range: [number, number], +) { + const mainSelection = state.selection.main; + // When the selection is empty, we need to check if the cursor is inside the fenced code + if (mainSelection.empty) { + return checkRangeOverlap(range, [mainSelection.from, mainSelection.to]); + } else { + // If the selection is encompassing the fenced code we render as code + return checkRangeSubset([mainSelection.from, mainSelection.to], range); + } +} + /** * Decoration to simply hide anything. */