Files
BindThem/src/FileHelper.ts
T
olivier 254fcc1b41
Node.js build / build (20.x) (push) Has been cancelled
Node.js build / build (22.x) (push) Has been cancelled
fix: heading-regex tag corruption, live command toggles, adjacent-file collision, stale selection listeners
- HEADING_REGEX now requires a space/EOL after '#' so tag lines
  (#project ...) are no longer misdetected as headings and corrupted.
- Command enable/disable settings now take effect immediately via
  checkCallback/editorCheckCallback instead of requiring a reload.
- New Adjacent File auto-increments (Untitled.md, Untitled 1.md, ...)
  instead of throwing once Untitled.md already exists.
- Selection-change tracking is delegated from document instead of a
  one-time .cm-content scan, so editors opened after startup are covered.

See CHANGELOG.md for details.
2026-09-07 12:36:08 -04:00

80 lines
2.2 KiB
TypeScript

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<void> {
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<void> {
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 "<basename>.md" / "<basename> 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
}
}