diff --git a/src/block_utils.ts b/src/block_utils.ts new file mode 100644 index 0000000..001290f --- /dev/null +++ b/src/block_utils.ts @@ -0,0 +1,64 @@ +import { Editor, EditorPosition, MarkdownView, SectionCache, TFile } from "obsidian"; + +export abstract class BlockUtils { + private static getBlock(editor: Editor, file: TFile): SectionCache | undefined { + const cursor = editor.getCursor("to"); + const fileCache = app.metadataCache.getFileCache(file); + + const currentBlock = + fileCache?.sections?.find((section) => + section.position.start.line <= cursor.line && + section.position.end.line >= cursor.line + ); + return currentBlock; + } + + private static getIdOfBlock( + editor: Editor, + block: SectionCache, + ): string { + const blockId = block.id; + + if (blockId) { + return blockId; + } + + // Add a block id + const sectionEnd = block.position.end; + const end: EditorPosition = { + ch: sectionEnd.col, + line: sectionEnd.line, + }; + + const newId = Math.random().toString(36).substring(2, 8); + const spacer = BlockUtils.shouldInsertAfter(block) ? "\n\n" : " "; + + editor.replaceRange(`${spacer}^${newId}`, end); + return newId; + } + + private static shouldInsertAfter(block: SectionCache): boolean { + if (block.type) { + return [ + "blockquote", + "code", + "table", + "heading", + "comment", + "footnoteDefinition", + ].includes(block.type); + } + } + + public static getBlockId(): string | undefined { + const view = app.workspace.getActiveViewOfType(MarkdownView); + if (view) { + const editor = view.editor; + const file = view.file; + const block = this.getBlock(editor, file); + if (block) + return this.getIdOfBlock(editor, block); + } + } + +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index b5b9688..1c80383 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,6 +2,7 @@ import { base64ToArrayBuffer, CachedMetadata, MarkdownView, normalizePath, Notic import { stripMD } from "obsidian-community-lib"; import { appHasDailyNotesPluginLoaded, createDailyNote, getAllDailyNotes, getDailyNote } from "obsidian-daily-notes-interface"; import { v4 as uuidv4 } from 'uuid'; +import { BlockUtils } from "./block_utils"; import { getDailyNotePath } from "./daily_note_utils"; import { CommandModal } from "./modals/command_modal"; import { EnterDataModal } from "./modals/enter_data_modal"; @@ -75,6 +76,21 @@ export default class AdvancedURI extends Plugin { } }); + this.addCommand({ + id: "copy-uri-block", + name: "copy URI for current block", + checkCallback: (checking) => { + const view = this.app.workspace.getActiveViewOfType(MarkdownView); + if (checking) return view != undefined; + const id = BlockUtils.getBlockId(); + if (id) { + this.copyURI({ + filepath: view.file.path, + block: id + }); + } + } + }); this.registerObsidianProtocolHandler("advanced-uri", async (e) => { const parameters = e as unknown as Parameters;