diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index e78aad9..c657a2a 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -66,6 +66,56 @@ fn emit_path_move( } } +#[derive(Clone, serde::Serialize)] +struct LinksRewrittenEvent<'a> { + vault_path: &'a str, + path: &'a str, + old_raw: &'a str, + new_raw: &'a str, + old_ref: &'a str, + new_ref: &'a str, + old_title: &'a str, + new_title: &'a str, + title_rules: bool, +} + +// A rename also rewrites the notes that link to the renamed one. Keep their previous state in +// version history, and tell open editors so unsaved edits in such a note are not refused as a +// conflict with the disk. +fn announce_rewritten_links( + app: &AppHandle, + vault: &str, + renamed: &operations::RenamedNote, + max_versions: u32, +) { + for note in &renamed.links.notes { + let filename = Path::new(¬e.path) + .file_name() + .unwrap_or_default() + .to_string_lossy(); + let (meta, _) = crate::vault::frontmatter::parse_note(¬e.old_raw, &filename); + if !meta.id.is_empty() { + crate::history::maybe_snapshot(vault, &meta.id, ¬e.old_raw, max_versions); + } + if let Err(error) = app.emit( + "vault-links-rewritten", + LinksRewrittenEvent { + vault_path: vault, + path: ¬e.path, + old_raw: ¬e.old_raw, + new_raw: ¬e.new_raw, + old_ref: &renamed.links.old_ref, + new_ref: &renamed.links.new_ref, + old_title: &renamed.old_title, + new_title: &renamed.new_title, + title_rules: renamed.links.title_rules, + }, + ) { + log::error!("Could not notify note windows about updated links: {error}"); + } + } +} + // ── Vault Management ── #[cfg(target_os = "ios")] @@ -948,9 +998,15 @@ pub async fn rename_note( new_title: String, ) -> Result { let search = state.vault_snapshot(&vault_path)?; + let max_versions = state + .config + .lock() + .map_err(|error| error.to_string())? + .max_versions_per_note; let _write_guard = state.note_save.lock().await; let renamed = operations::rename_note(&path, &new_title, &vault_path)?; emit_path_move(&app, &vault_path, &path, &renamed.path, Some(&renamed)); + announce_rewritten_links(&app, &vault_path, &renamed, max_versions); if let Some(search) = search { if let Err(error) = search.queue_vault_refresh(&vault_path) { log::error!("Failed to queue renamed note search refresh: {error}"); diff --git a/src-tauri/src/vault/operations.rs b/src-tauri/src/vault/operations.rs index 4f99fbb..895f56b 100644 --- a/src-tauri/src/vault/operations.rs +++ b/src-tauri/src/vault/operations.rs @@ -1258,6 +1258,23 @@ pub struct RenamedNote { pub new_raw: String, pub old_title: String, pub new_title: String, + pub links: LinkRewrite, +} + +/// A note whose links were updated because the note they point to was renamed. +pub struct RewrittenNote { + pub path: String, + pub old_raw: String, + pub new_raw: String, +} + +/// What a rename changed in the notes that link to the renamed one. +pub struct LinkRewrite { + pub old_ref: String, + pub new_ref: String, + /// Whether links written with the note's title were updated too. + pub title_rules: bool, + pub notes: Vec, } pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result { @@ -1316,7 +1333,7 @@ pub fn rename_note(path: &str, new_title: &str, vault_path: &str) -> Result Result LinkRewrite { let vault = Path::new(vault_path); let hn_dir = helixnotes_dir(vault_path); @@ -1382,6 +1400,8 @@ fn update_wikilinks_after_rename( .map(|s| s.eq_ignore_ascii_case(old_title)) .unwrap_or(false) }); + let title_rules = old_title != new_title && title_is_unique; + let mut notes = Vec::new(); for entry in WalkDir::new(vault) .into_iter() @@ -1415,7 +1435,7 @@ fn update_wikilinks_after_rename( // Title-based rules only apply when the old title is unique in the vault. // If another note shares the same title, these would be ambiguous. - if old_title != new_title && title_is_unique { + if title_rules { // 1. Short title ref: [[Old Title]] → [[New Title]] result = result.replace(&format!("[[{}]]", old_title), &format!("[[{}]]", new_title)); @@ -1458,14 +1478,25 @@ fn update_wikilinks_after_rename( if result != content { // Replace the file in one step: a plain write truncates first, so a crash or a full // disk here could leave a note that merely links to the renamed one empty. - if let Err(error) = replace_file_atomically(path, result.as_bytes()) { - log::error!( + match replace_file_atomically(path, result.as_bytes()) { + Ok(()) => notes.push(RewrittenNote { + path: path_str.into_owned(), + old_raw: content, + new_raw: result, + }), + Err(error) => log::error!( "Could not update links in {} after a rename: {error}", path.display() - ); + ), } } } + LinkRewrite { + old_ref: old_rel_ref, + new_ref: new_rel_ref, + title_rules, + notes, + } } pub fn rename_notebook(vault_path: &str, path: &str, new_name: &str) -> Result { @@ -2562,13 +2593,27 @@ mod rename_link_tests { let new_path = vault.path().join("Start.md"); fs::write(&new_path, "# Start\n").unwrap(); - update_wikilinks_after_rename( + let original = fs::read_to_string(&linking).unwrap(); + let rewrite = update_wikilinks_after_rename( root, vault.path().join("Home.md").to_str().unwrap(), new_path.to_str().unwrap(), "Home", "Start", ); + // Only the note that changed is reported, with what it held before and after. + assert_eq!(rewrite.notes.len(), 1); + assert_eq!(rewrite.notes[0].path, linking.to_str().unwrap()); + assert_eq!(rewrite.notes[0].old_raw, original); + assert_eq!( + rewrite.notes[0].new_raw, + fs::read_to_string(&linking).unwrap() + ); + assert!(rewrite.title_rules); + assert_eq!( + (rewrite.old_ref.as_str(), rewrite.new_ref.as_str()), + ("Home", "Start") + ); assert_eq!( fs::read_to_string(&linking).unwrap(), diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index 9d06c46..57bd6e8 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -68,6 +68,7 @@ import { externalNoteReferences } from '$lib/editor/externalNote'; import { tagIterationKey } from '$lib/utils/tag-styles'; import { replaceWithWikiLink } from '$lib/editor/wikiLinks'; + import { renamedLink, renamedLinkChanges, type LinkRename } from '$lib/editor/renamedLinks'; import { assetSourceToMarkdown, assetUrlToLocalPath, encodeMarkdownPath, resolveFileReference, noteAssetRoot, isTrashedNote } from '$lib/utils/paths'; import GraphView from './GraphView.svelte'; import TagSuggestInput from './TagSuggestInput.svelte'; @@ -7191,6 +7192,69 @@ else unlistenPathMoved = fn; }).catch(error => console.error('Failed to listen for relocated notes:', error)); + /** Bring the wiki links of the open note in line with a rename of the note they point to. */ + function applyRenamedLinks(rename: LinkRename) { + if ($sourceMode) { + const view = source.view; + if (!view) return; + const changes = renamedLinkChanges(view.state.doc.toString(), rename); + if (changes.length) view.dispatch({ changes }); + return; + } + if (!editor) return; + const { schema, doc } = editor.state; + const wikiLink = schema.marks.wikiLink; + const edits: { from: number; to: number; node: any }[] = []; + doc.descendants((node: any, pos: number) => { + if (!node.isText) return; + const text = node.text as string; + const mark = wikiLink ? node.marks.find((m: any) => m.type === wikiLink) : null; + if (mark) { + const ref = (mark.attrs.title as string | null) || text; + const next = renamedLink(ref, ref === text ? null : text, rename); + if (!next) return; + const path = String(mark.attrs.path ?? '').replace(/\\/g, '/'); + const attrs = { ...mark.attrs, title: next.ref, + path: path === `${rename.old_ref}.md` ? `${rename.new_ref}.md` : mark.attrs.path }; + const marks = node.marks.map((m: any) => m === mark ? wikiLink.create(attrs) : m); + edits.push({ from: pos, to: pos + node.nodeSize, node: schema.text(next.display ?? next.ref, marks) }); + } else if (!wikiLink && !node.marks.some((m: any) => m.type.name === 'code')) { + // With wiki links switched off they are ordinary text in the note. + for (const change of renamedLinkChanges(text, rename)) { + edits.push({ from: pos + change.from, to: pos + change.to, node: schema.text(change.insert, node.marks) }); + } + } + }); + if (!edits.length) return; + const tr = editor.state.tr.setMeta('addToHistory', false); + for (const edit of edits.reverse()) tr.replaceWith(edit.from, edit.to, edit.node); + editor.view.dispatch(tr); + } + + type LinksRewrittenEvent = LinkRename & { vault_path: string; path: string; old_raw: string; new_raw: string }; + let unlistenLinksRewritten: (() => void) | null = null; + listen('vault-links-rewritten', ({ payload }) => { + if (editorDisposed || payload.vault_path !== $appConfig?.active_vault + || payload.path !== $activeNotePath || payload.path !== loadedPath) return; + // Without unsaved edits the note is simply reloaded when the file change is noticed. + if (!$editorDirty) return; + const session = saves.capture(); + void (async () => { + await saves.idle(); + if (editorDisposed || !saves.isCurrentSession(session) || $activeNotePath !== payload.path) return; + // The rename rewrote the version this draft is based on: take over the same link changes + // and continue from the rewritten file, so the draft saves instead of conflicting. + if (!saves.adoptMovedRaw(payload.old_raw, payload.new_raw)) { + if (saves.raw !== payload.new_raw) flagExternalConflict(); + return; + } + applyRenamedLinks(payload); + })(); + }).then(fn => { + if (editorDisposed) fn(); + else unlistenLinksRewritten = fn; + }).catch(error => console.error('Failed to listen for updated links:', error)); + let unlistenToolbarLayout: (() => void) | null = null; listen('toolbar-layout-changed', (event) => { const preference = JSON.stringify(event.payload); @@ -7226,6 +7290,7 @@ destroyEditor(); unlistenFileChange?.(); unlistenPathMoved?.(); + unlistenLinksRewritten?.(); unlistenToolbarLayout?.(); if (infoPathCopyTimer) clearTimeout(infoPathCopyTimer); }); diff --git a/src/lib/editor/renamedLinks.ts b/src/lib/editor/renamedLinks.ts new file mode 100644 index 0000000..5fa03b9 --- /dev/null +++ b/src/lib/editor/renamedLinks.ts @@ -0,0 +1,50 @@ +/* + * Renaming a note rewrites the wiki links to it in every note that links there (see + * `update_wikilinks_after_rename` in the backend). A note that is open with unsaved edits has to + * follow in the editor, or its next save would write the old links back. These rules mirror the + * backend's. + */ + +export interface LinkRename { + old_ref: string; + new_ref: string; + old_title: string; + new_title: string; + /** Whether links written with the note's title were rewritten, not only path links. */ + title_rules: boolean; +} + +export interface RenamedLink { + ref: string; + display: string | null; +} + +/** The link `[[ref]]` or `[[ref|display]]` after the rename, or null when it is not affected. */ +export function renamedLink(ref: string, display: string | null, rename: LinkRename): RenamedLink | null { + const followsTitle = display === rename.old_title && rename.old_title !== rename.new_title; + if (rename.title_rules && ref === rename.old_title) { + return { ref: rename.new_title, display: followsTitle ? rename.new_title : display }; + } + if (rename.old_ref !== rename.new_ref && ref === rename.old_ref) { + return { ref: rename.new_ref, display: followsTitle ? rename.new_title : display }; + } + return null; +} + +export interface TextChange { + from: number; + to: number; + insert: string; +} + +/** The edits that bring the wiki links in Markdown text in line with the rename. */ +export function renamedLinkChanges(text: string, rename: LinkRename): TextChange[] { + const changes: TextChange[] = []; + for (const match of text.matchAll(/\[\[([^\[\]|]+)(?:\|([^\[\]]*))?\]\]/g)) { + const next = renamedLink(match[1], match[2] ?? null, rename); + if (!next) continue; + const insert = next.display === null ? `[[${next.ref}]]` : `[[${next.ref}|${next.display}]]`; + changes.push({ from: match.index, to: match.index + match[0].length, insert }); + } + return changes; +} diff --git a/tests/renamed-links.test.mjs b/tests/renamed-links.test.mjs new file mode 100644 index 0000000..ea35a99 --- /dev/null +++ b/tests/renamed-links.test.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import { transformWithEsbuild } from 'vite'; + +const source = await readFile(new URL('../src/lib/editor/renamedLinks.ts', import.meta.url), 'utf8'); +const { code } = await transformWithEsbuild(source, 'renamedLinks.ts', { loader: 'ts', format: 'esm' }); +const { renamedLinkChanges } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`); + +const apply = (text, rename) => { + let result = text; + for (const change of renamedLinkChanges(text, rename).reverse()) { + result = result.slice(0, change.from) + change.insert + result.slice(change.to); + } + return result; +}; + +test('links to a renamed note follow it, as the backend rewrites them', () => { + // Same input and result as the backend test for update_wikilinks_after_rename. + const rename = { old_ref: 'Home', new_ref: 'Start', old_title: 'Home', new_title: 'Start', title_rules: true }; + assert.equal( + apply('See [[Home]], [[Home|the start page]] and [[Home|Home]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n', rename), + 'See [[Start]], [[Start|the start page]] and [[Start|Start]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n' + ); +}); + +test('path links follow a rename in a folder', () => { + const rename = { old_ref: 'Work/Plan', new_ref: 'Work/Roadmap', old_title: 'Plan', new_title: 'Roadmap', title_rules: true }; + assert.equal( + apply('[[Work/Plan]] [[Work/Plan|Plan]] [[Work/Plan|mine]] [[Plan]] [[Other/Plan]]', rename), + '[[Work/Roadmap]] [[Work/Roadmap|Roadmap]] [[Work/Roadmap|mine]] [[Roadmap]] [[Other/Plan]]' + ); +}); + +test('title links stay when another note shares the old title', () => { + const rename = { old_ref: 'Work/Plan', new_ref: 'Work/Roadmap', old_title: 'Plan', new_title: 'Roadmap', title_rules: false }; + assert.equal(apply('[[Plan]] [[Plan|x]] [[Work/Plan|Plan]]', rename), '[[Plan]] [[Plan|x]] [[Work/Roadmap|Roadmap]]'); +}); + +test('nothing changes when no link points at the renamed note', () => { + const rename = { old_ref: 'Home', new_ref: 'Start', old_title: 'Home', new_title: 'Start', title_rules: true }; + assert.deepEqual(renamedLinkChanges('Home is [[Elsewhere]] and `code`.', rename), []); +});