From 6d2aeb72b2a6ded37c5261d7c77bf78f87562009 Mon Sep 17 00:00:00 2001 From: Hyeonseo Nam Date: Thu, 16 Mar 2023 14:20:37 +0900 Subject: [PATCH] Edit view-manager.ts: add insertion functions --- src/view-manager.ts | 52 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/src/view-manager.ts b/src/view-manager.ts index b7cdb2f..81ce9c9 100644 --- a/src/view-manager.ts +++ b/src/view-manager.ts @@ -1,4 +1,4 @@ -import { App, MarkdownView } from "obsidian"; +import { App, MarkdownView, Notice, Editor} from "obsidian"; export class ViewManager { app: App; @@ -7,17 +7,18 @@ export class ViewManager { this.app = app; } - getSelection(): string | null { + async getSelection(editor?: Editor): Promise { + if (editor) { + return editor.getSelection(); + } const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); if (activeView) { - const editor = activeView.editor; - const selectedText = editor.getSelection(); - return selectedText; + return activeView.editor.getSelection(); } return null; } - getTitle(): string | null { + async getTitle(): Promise { const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); if (activeView) { return activeView.file.basename; @@ -25,7 +26,7 @@ export class ViewManager { return null; } - getFrontMatter(): Record | null { + async getFrontMatter(): Promise | null> { const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); if (activeView) { const file = activeView.file; @@ -35,5 +36,42 @@ export class ViewManager { return null; } + async insertAtFrontMatter(key: string, value: string, overwrite = false): Promise { + const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); + + if (activeView) { + const file = activeView.file; + await this.app.fileManager.processFrontMatter(file, (frontmatter) => { + frontmatter = frontmatter || {}; + + if (frontmatter[key] && !overwrite) { + // add value as list element if exist + if (Array.isArray(frontmatter[key])) { + frontmatter[key].push(value); + } else { + frontmatter[key] = [frontmatter[key], value]; + } + } else { + // overwrite + frontmatter[key] = value; + } + }); + } + } + async insertAtCursor(value: string, overwrite = false): Promise { + const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); + + if (activeView) { + const editor = activeView.editor; + const selection = editor.getSelection(); + if (selection && !overwrite) { + // replace selection + editor.setSelection(editor.getCursor('to')); + } + // overwrite + editor.replaceSelection(value); + } + } + } \ No newline at end of file