import { App, Editor, MarkdownFileInfo, MarkdownView, Notice } from 'obsidian' import BindThemPlugin from './main' /** * FileHelper provides commands for file operations */ export class FileHelper { public app: App private plugin: BindThemPlugin constructor(app: App, plugin: BindThemPlugin) { this.app = app this.plugin = plugin } /** * Duplicate the current file */ public async duplicateFile(editor: Editor, view: MarkdownView | MarkdownFileInfo): Promise { const activeFile = this.app.workspace.getActiveFile() if (activeFile === null) { return } const selections = editor.listSelections() const parentPath = activeFile.parent?.path ?? '' const newFilePath = parentPath + '/' + activeFile.basename + ' (copy).' + activeFile.extension try { const newFile = await this.app.vault.copy(activeFile, newFilePath) if (view instanceof MarkdownView) { await view.leaf.openFile(newFile) } editor.setSelections(selections) } catch (e) { new Notice(String(e)) } } /** * Create a new file in the same directory as the current file. * If "Untitled.md" already exists, finds the next available * "Untitled N.md" name (mirrors Obsidian's own new-note behavior). */ public async newAdjacentFile(editor: Editor, view: MarkdownView | MarkdownFileInfo): Promise { const activeFile = this.app.workspace.getActiveFile() if (activeFile === null) { return } const parentPath = activeFile.parent?.path ?? '' const newFilePath = this.getAvailablePath(parentPath, 'Untitled', 'md') try { const newFile = await this.app.vault.create(newFilePath, '') if (view instanceof MarkdownView) { await view.leaf.openFile(newFile) } } catch (e) { new Notice(String(e)) } } /** * Find the first unused ".md" / " N.md" path in a folder */ private getAvailablePath(parentPath: string, basename: string, extension: string): string { let candidate = `${parentPath}/${basename}.${extension}` let n = 1 while (this.app.vault.getAbstractFileByPath(candidate) !== null) { candidate = `${parentPath}/${basename} ${n}.${extension}` n++ } return candidate } }