From 14db4bf2404b9791cde0c2a219fbc804d1ff94c0 Mon Sep 17 00:00:00 2001 From: Andras Schmelczer Date: Sat, 7 Jun 2025 21:51:14 +0100 Subject: [PATCH] Extract getCursorsFromEditor --- .../src/obsidian-file-system.ts | 26 +++++++------------ .../src/utils/get-cursors-from-editor.ts | 17 ++++++++++++ 2 files changed, 27 insertions(+), 16 deletions(-) create mode 100644 frontend/obsidian-plugin/src/utils/get-cursors-from-editor.ts diff --git a/frontend/obsidian-plugin/src/obsidian-file-system.ts b/frontend/obsidian-plugin/src/obsidian-file-system.ts index 9905b036..6546b0fb 100644 --- a/frontend/obsidian-plugin/src/obsidian-file-system.ts +++ b/frontend/obsidian-plugin/src/obsidian-file-system.ts @@ -7,6 +7,7 @@ import type { } from "sync-client"; import { lineAndColumnToPosition } from "./utils/line-and-column-to-position"; import { positionToLineAndColumn } from "./utils/position-to-line-and-column"; +import { getCursorsFromEditor } from "./utils/get-cursors-from-editor"; export class ObsidianFileSystemOperations implements FileSystemOperations { public constructor( @@ -78,26 +79,19 @@ export class ObsidianFileSystemOperations implements FileSystemOperations { if (view?.file?.path === path) { const text = view.editor.getValue(); - const cursors = view.editor - .listSelections() - .flatMap(({ anchor, head }, i) => [ + + const cursors = getCursorsFromEditor(view.editor).flatMap( + ({ id, start: anchor, end: head }) => [ { - id: 2 * i, - characterPosition: lineAndColumnToPosition( - text, - anchor.line, - anchor.ch - ) + id: 2 * id, + characterPosition: anchor }, { - id: 2 * i + 1, - characterPosition: lineAndColumnToPosition( - text, - head.line, - head.ch - ) + id: 2 * id + 1, + characterPosition: head } - ]); + ] + ); const result = updater({ text, diff --git a/frontend/obsidian-plugin/src/utils/get-cursors-from-editor.ts b/frontend/obsidian-plugin/src/utils/get-cursors-from-editor.ts new file mode 100644 index 00000000..8844942a --- /dev/null +++ b/frontend/obsidian-plugin/src/utils/get-cursors-from-editor.ts @@ -0,0 +1,17 @@ +import { Editor } from "obsidian"; +import { lineAndColumnToPosition } from "./line-and-column-to-position"; + +export interface Cursor { + id: number; + start: number; + end: number; +} + +export function getCursorsFromEditor(editor: Editor): Cursor[] { + const text = editor.getValue(); + return editor.listSelections().map(({ anchor, head }, i) => ({ + id: i, + start: lineAndColumnToPosition(text, anchor.line, anchor.ch), + end: lineAndColumnToPosition(text, head.line, head.ch) + })); +}