From 8fcc7741d2c2975f866e12a045cb42f2220babf5 Mon Sep 17 00:00:00 2001 From: Tristan Sokol Date: Thu, 5 Jan 2023 08:37:08 -0600 Subject: [PATCH] Fixes #210 Add in new refactor file and extract to page command Co-authored-by: Tristan Sokol --- plugs/core/core.plug.yaml | 8 +++++++- plugs/core/refactor.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 plugs/core/refactor.ts diff --git a/plugs/core/core.plug.yaml b/plugs/core/core.plug.yaml index 70adedb..de5c677 100644 --- a/plugs/core/core.plug.yaml +++ b/plugs/core/core.plug.yaml @@ -21,7 +21,7 @@ functions: setEditorMode: path: "./editor.ts:setEditorMode" events: - - editor:init + - editor:init toggleVimMode: path: "./editor.ts:toggleVimMode" command: @@ -331,6 +331,12 @@ functions: key: "Alt-m" wrapper: "==" + # Refactoring Commands + extractToPageCommand: + path: ./refactor.ts:extractToPage + command: + name: "Extract text to new page" + # Plug manager updatePlugsCommand: path: ./plugmanager.ts:updatePlugsCommand diff --git a/plugs/core/refactor.ts b/plugs/core/refactor.ts new file mode 100644 index 0000000..099fb43 --- /dev/null +++ b/plugs/core/refactor.ts @@ -0,0 +1,37 @@ +import { + editor, + space, +} from "$sb/silverbullet-syscall/mod.ts"; + +export async function extractToPage() { + const newName = await editor.prompt(`New page title:`, 'new page'); + if (!newName) { + return; + } + + console.log("New name", newName); + + try { + // This throws an error if the page does not exist, which we expect to be the case + await space.getPageMeta(newName); + // So when we get to this point, we error out + throw new Error( + `Page ${newName} already exists, cannot rename to existing page.`, + ); + } catch (e: any) { + if (e.message.includes("not found")) { + // Expected not found error, so we can continue + } else { + await editor.flashNotification(e.message, "error"); + throw e; + } + } + let text = await editor.getText(); + const selection = await editor.getSelection(); + text = text.slice(selection.from, selection.to); + await editor.replaceRange(selection.from, selection.to, `[[${newName}]]`); + console.log("Writing new page to space"); + await space.writePage(newName, text); + console.log("Navigating to new page"); + await editor.navigate(newName); +}