// ************************************************************************* // * (C)opyright 2026 by Ruben Carlo Benante * // * * // * This program is free software; you can redistribute it and/or modify * // * it under the terms of the GNU General Public License as published by * // * the Free Software Foundation, either version 3 of the License, or * // * (at your option) any later version. * // * * // * This program is distributed in the hope that it will be useful, * // * but WITHOUT ANY WARRANTY; without even the implied warranty of * // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * // * GNU General Public License for more details. * // * * // * You should have received a copy of the GNU General Public License * // * along with this program. If not, see http://www.gnu.org/licenses/. * // * * // * Contact author at: * // * Ruben Carlo Benante * // * rcb@beco.cc * // ************************************************************************* import { Plugin, TFile, TAbstractFile, TFolder, Menu, Notice, moment, } from 'obsidian'; import { extractPrefix, computeBasename, generateSlug, buildFilename, } from './slug'; import { ZettelcleanSettings, DEFAULT_SETTINGS, ZettelcleanSettingTab, } from './settings'; const SETTLE_MS = 4000; // rename ~4s after the H1 stops changing const COOLDOWN_MS = 6000; // do not rename the same path again within 6s export default class ZettelcleanPlugin extends Plugin { settings!: ZettelcleanSettings; private renameTimers = new Map(); private lastRenamedAt = new Map(); private isRenameInProgress = false; async onload() { await this.loadSettings(); this.addSettingTab(new ZettelcleanSettingTab(this.app, this)); // Fires after the metadata cache reparses a note, so headings[] is fresh. this.registerEvent( this.app.metadataCache.on('changed', (file) => this.scheduleSync(file), ), ); // File-explorer right-click menu: retrofit item for files, slug item for folders. this.registerEvent( this.app.workspace.on('file-menu', (menu, file) => { this.addTimeIdMenu(menu, file); this.addFolderSlugMenu(menu, file); }), ); } onunload() { for (const t of this.renameTimers.values()) window.clearTimeout(t); this.renameTimers.clear(); } async loadSettings() { this.settings = Object.assign( {}, DEFAULT_SETTINGS, (await this.loadData()) as Partial, ); } async saveSettings() { await this.saveData(this.settings); } private pathFor(file: TFile, base: string): string { const dir = file.parent && file.parent.path !== '/' ? `${file.parent.path}/` : ''; return `${dir}${base}.md`; } // Guard layer: only the actively edited zettel, honoring the 6s cooldown, // (re)arming the 4s settle timer on every cache change. private scheduleSync(file: TAbstractFile) { if (this.isRenameInProgress) return; // our own rename, ignore if (!(file instanceof TFile) || file.extension !== 'md') return; const allowDate = this.settings.prefixMode === 'date'; if (extractPrefix(file.basename, allowDate) === null) return; // opt-in gate if (this.app.workspace.getActiveFile() !== file) return; // only the edited note const last = this.lastRenamedAt.get(file.path); if (last && Date.now() - last < COOLDOWN_MS) return; // 6s cooldown const existing = this.renameTimers.get(file.path); if (existing) window.clearTimeout(existing); this.renameTimers.set( file.path, window.setTimeout(() => { this.renameTimers.delete(file.path); void this.syncNow(file); }, SETTLE_MS), ); } // Compute the target basename via the sticky rule, bail if unchanged, else rename. private async syncNow(file: TFile) { const first = this.app.metadataCache.getFileCache(file)?.headings?.[0]; const h1 = first && first.level === 1 ? first.heading : ''; const allowDate = this.settings.prefixMode === 'date'; const newBase = computeBasename(file.basename, h1, allowDate); if (newBase === null || newBase === file.basename) return; // unrecognized or no change const newPath = this.pathFor(file, newBase); if (this.app.vault.getAbstractFileByPath(newPath)) { new Notice(`Can't rename to "${newBase}.md" - that name already exists`); return; // conflict: keep current name, tell the user } this.isRenameInProgress = true; try { await this.app.fileManager.renameFile(file, newPath); this.lastRenamedAt.set(newPath, Date.now()); } catch (e) { console.error('zettelclean: rename failed', e); new Notice('Rename failed (see console)'); } finally { this.isRenameInProgress = false; } } private addTimeIdMenu(menu: Menu, file: TAbstractFile) { if (!(file instanceof TFile) || file.extension !== 'md') return; const allowDate = this.settings.prefixMode === 'date'; if (extractPrefix(file.basename, allowDate) !== null) return; // already a zettel menu.addItem((item) => item .setTitle('Prefix timestamp to filename') .setIcon('clock') .onClick(() => void this.addTimeId(file)), ); } // Retrofit: mint a fresh timestamp for a note that has no TIMEID yet. private async addTimeId(file: TFile) { let id = moment().format('YYYYMMDDHHmmss'); // core Unique-note format const first = this.app.metadataCache.getFileCache(file)?.headings?.[0]; const h1 = first && first.level === 1 ? first.heading : file.basename; const slug = generateSlug(h1); let target = this.pathFor(file, buildFilename(id, slug)); // Rare same-second + same-title collision: extend the id (up to 18 digits). while (this.app.vault.getAbstractFileByPath(target) && id.length < 18) { id += String(Math.floor(Date.now() % 10)); target = this.pathFor(file, buildFilename(id, slug)); } await this.app.fileManager.renameFile(file, target); } // Folder right-click: slug the folder's own name (this folder only, instant). private addFolderSlugMenu(menu: Menu, file: TAbstractFile) { if (!(file instanceof TFolder) || file.isRoot()) return; // never the vault root menu.addItem((item) => item .setTitle('Slug folder name') .setIcon('folder') .onClick(() => void this.slugFolder(file)), ); } private async slugFolder(folder: TFolder) { const newName = generateSlug(folder.name); if (!newName || newName === folder.name) { new Notice('Folder name is already clean'); return; } const parent = folder.parent; const dir = parent && parent.path !== '/' ? `${parent.path}/` : ''; const newPath = `${dir}${newName}`; // folders have no extension if (this.app.vault.getAbstractFileByPath(newPath)) { new Notice(`Cannot rename: "${newName}" already exists`); return; } await this.app.fileManager.renameFile(folder, newPath); // updates [[links]] new Notice(`Renamed folder "${folder.name}" -> "${newName}"`); } }