mirror of
https://gitlab.com/ArkHost/HelixNotes.git
synced 2026-11-19 10:38:20 +01:00
fix: keep links working when notes are renamed or moved
Renaming through the title field saved the new title before the file was renamed, so the rename took the new title for the old one and [[Old]] links were never updated. It now uses the old file name. A rename now also updates heading and block links, other capitals, [[Note.md]] and Markdown links to the file. Moving a note, and renaming or moving a notebook, updates links that contain a folder, keeping each link's form, and points the moved notes' own relative links from their new folder. Code is left as written, and a name another note shares is not rewritten. Open notes with unsaved edits follow the same rules, checked on both sides against tests/fixtures/renamed-links.json.
This commit is contained in:
1 parent
c7bcb993bb
commit
3b59d34fed
7 files changed
+1376
-191
No files matched your search
+31
-17
@@ -72,11 +72,7 @@ struct LinksRewrittenEvent<'a> {
|
||||
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,
|
||||
renames: &'a [operations::LinkRename],
|
||||
}
|
||||
|
||||
// A rename also rewrites the notes that link to the renamed one. Keep their previous state in
|
||||
@@ -85,10 +81,10 @@ struct LinksRewrittenEvent<'a> {
|
||||
fn announce_rewritten_links<R: Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
vault: &str,
|
||||
renamed: &operations::RenamedNote,
|
||||
links: &operations::LinkRewrite,
|
||||
max_versions: u32,
|
||||
) {
|
||||
for note in &renamed.links.notes {
|
||||
for note in &links.notes {
|
||||
let filename = Path::new(¬e.path)
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
@@ -104,11 +100,7 @@ fn announce_rewritten_links<R: Runtime>(
|
||||
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,
|
||||
renames: &links.renames,
|
||||
},
|
||||
) {
|
||||
log::error!("Could not notify note windows about updated links: {error}");
|
||||
@@ -770,9 +762,15 @@ pub async fn rename_notebook<R: Runtime>(
|
||||
new_name: String,
|
||||
) -> Result<String, String> {
|
||||
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_notebook(&vault_path, &path, &new_name)?;
|
||||
let (renamed, links) = operations::rename_notebook(&vault_path, &path, &new_name)?;
|
||||
emit_path_move(&app, &vault_path, &path, &renamed, None);
|
||||
announce_rewritten_links(&app, &vault_path, &links, max_versions);
|
||||
if let Some(search) = search {
|
||||
if let Err(error) = search.queue_vault_refresh(&vault_path) {
|
||||
log::error!("Failed to queue renamed notebook search refresh: {error}");
|
||||
@@ -790,11 +788,18 @@ pub async fn move_notebook<R: Runtime>(
|
||||
dest_parent: String,
|
||||
) -> Result<String, String> {
|
||||
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 vault_path = vault_path.as_str();
|
||||
|
||||
let new_full_path = operations::move_notebook(vault_path, ¬ebook_path, &dest_parent)?;
|
||||
let (new_full_path, links) =
|
||||
operations::move_notebook(vault_path, ¬ebook_path, &dest_parent)?;
|
||||
emit_path_move(&app, vault_path, ¬ebook_path, &new_full_path, None);
|
||||
announce_rewritten_links(&app, vault_path, &links, max_versions);
|
||||
|
||||
// Reconcile renamed paths without blocking the move on a full rebuild.
|
||||
if let Some(search) = search {
|
||||
@@ -1016,7 +1021,7 @@ pub async fn rename_note<R: Runtime>(
|
||||
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);
|
||||
announce_rewritten_links(&app, &vault_path, &renamed.links, 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}");
|
||||
@@ -1050,14 +1055,23 @@ pub async fn move_note<R: Runtime>(
|
||||
dest_notebook: String,
|
||||
) -> Result<String, String> {
|
||||
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 vault_path = vault_path.as_str();
|
||||
|
||||
let new_full_path = operations::move_note(vault_path, ¬e_path, &dest_notebook)?;
|
||||
let (new_full_path, links) = operations::move_note(vault_path, ¬e_path, &dest_notebook)?;
|
||||
emit_path_move(&app, vault_path, ¬e_path, &new_full_path, None);
|
||||
announce_rewritten_links(&app, vault_path, &links, max_versions);
|
||||
|
||||
index_note_bg(search.clone(), ¬e_path);
|
||||
index_note_bg(search, &new_full_path);
|
||||
index_note_bg(search.clone(), &new_full_path);
|
||||
for note in &links.notes {
|
||||
index_note_bg(search.clone(), ¬e.path);
|
||||
}
|
||||
|
||||
Ok(new_full_path)
|
||||
}
|
||||
|
||||
@@ -182,7 +182,9 @@ fn imported_document_links_remain_managed_and_stable_after_note_and_notebook_mov
|
||||
.as_ref(),
|
||||
);
|
||||
assert_eq!(fs::read(attachment).unwrap(), b"pdf");
|
||||
let moved = super::operations::move_note(&vault, ¬e.path, &vault).unwrap();
|
||||
let moved = super::operations::move_note(&vault, ¬e.path, &vault)
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(fs::read_to_string(moved).unwrap(), note.raw);
|
||||
// Imported managed paths remain stable when their containing notebook is moved too.
|
||||
let second = import_note(
|
||||
|
||||
+876
-141
File diff suppressed because it is too large.
Load diff
@@ -69,7 +69,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 { renamedHref, 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';
|
||||
@@ -7380,35 +7380,42 @@
|
||||
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) {
|
||||
/** Bring the links of the open note in line with renamed or moved notes they point to. */
|
||||
function applyRenamedLinks(renames: LinkRename[], noteDir: string) {
|
||||
if ($sourceMode) {
|
||||
const view = source.view;
|
||||
if (!view) return;
|
||||
const changes = renamedLinkChanges(view.state.doc.toString(), rename);
|
||||
const changes = renamedLinkChanges(view.state.doc.toString(), renames, noteDir);
|
||||
if (changes.length) view.dispatch({ changes });
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
const { schema, doc } = editor.state;
|
||||
const wikiLink = schema.marks.wikiLink;
|
||||
const link = schema.marks.link;
|
||||
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 linkMark = link ? node.marks.find((m: any) => m.type === link) : null;
|
||||
const href = linkMark ? renamedHref(String(linkMark.attrs.href ?? ''), noteDir, renames) : null;
|
||||
if (linkMark && href !== null) {
|
||||
const marks = node.marks.map((m: any) => m === linkMark ? link.create({ ...linkMark.attrs, href }) : m);
|
||||
const titled = renames.find((rename) => rename.old_title === text && rename.old_title !== rename.new_title);
|
||||
edits.push({ from: pos, to: pos + node.nodeSize, node: schema.text(titled ? titled.new_title : text, marks) });
|
||||
} else if (mark) {
|
||||
const ref = (mark.attrs.title as string | null) || text;
|
||||
const next = renamedLink(ref, ref === text ? null : text, rename);
|
||||
const next = renamedLink(ref, ref === text ? null : text, renames);
|
||||
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 path = String(mark.attrs.path ?? '').replace(/\\/g, '/').toLowerCase();
|
||||
const moved = renames.find((rename) => `${rename.old_ref}.md`.toLowerCase() === path);
|
||||
const attrs = { ...mark.attrs, title: next.ref, path: moved ? `${moved.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)) {
|
||||
for (const change of renamedLinkChanges(text, renames, noteDir)) {
|
||||
edits.push({ from: pos + change.from, to: pos + change.to, node: schema.text(change.insert, node.marks) });
|
||||
}
|
||||
}
|
||||
@@ -7419,7 +7426,7 @@
|
||||
editor.view.dispatch(tr);
|
||||
}
|
||||
|
||||
type LinksRewrittenEvent = LinkRename & { vault_path: string; path: string; old_raw: string; new_raw: string };
|
||||
type LinksRewrittenEvent = { vault_path: string; path: string; old_raw: string; new_raw: string; renames: LinkRename[] };
|
||||
let unlistenLinksRewritten: (() => void) | null = null;
|
||||
listen<LinksRewrittenEvent>('vault-links-rewritten', ({ payload }) => {
|
||||
if (editorDisposed || payload.vault_path !== $appConfig?.active_vault
|
||||
@@ -7436,7 +7443,10 @@
|
||||
if (saves.raw !== payload.new_raw) flagExternalConflict();
|
||||
return;
|
||||
}
|
||||
applyRenamedLinks(payload);
|
||||
const vault = payload.vault_path.replace(/\\/g, '/');
|
||||
const notePath = payload.path.replace(/\\/g, '/');
|
||||
const relative = notePath.startsWith(`${vault}/`) ? notePath.slice(vault.length + 1) : notePath;
|
||||
applyRenamedLinks(payload.renames, relative.includes('/') ? relative.slice(0, relative.lastIndexOf('/')) : '');
|
||||
})();
|
||||
}).then(fn => {
|
||||
if (editorDisposed) fn();
|
||||
|
||||
+202
-20
@@ -1,17 +1,20 @@
|
||||
/*
|
||||
* Renaming a note rewrites the wiki links to it in every note that links there (see
|
||||
* Renaming a note rewrites the 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.
|
||||
* backend's; both are checked against `tests/fixtures/renamed-links.json`.
|
||||
*/
|
||||
|
||||
export interface LinkRename {
|
||||
/** Vault-relative path of the note without `.md`, before and after. */
|
||||
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. */
|
||||
/** Links written with the title follow (the title changed and no other note has it). */
|
||||
title_rules: boolean;
|
||||
/** No other note has this file name, so a bare file name or top-level path means this note. */
|
||||
file_rules?: boolean;
|
||||
}
|
||||
|
||||
export interface RenamedLink {
|
||||
@@ -19,16 +22,139 @@ export interface RenamedLink {
|
||||
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 lower = (value: string) => value.toLowerCase();
|
||||
|
||||
function splitRef(ref: string): [string, string] {
|
||||
const slash = ref.lastIndexOf('/');
|
||||
return slash < 0 ? ['', ref] : [ref.slice(0, slash), ref.slice(slash + 1)];
|
||||
}
|
||||
|
||||
const joinRef = (dir: string, name: string) => (dir ? `${dir}/${name}` : name);
|
||||
|
||||
/** `name` without a trailing `.md` (any capitals), and that extension as written. */
|
||||
function splitMdExt(name: string): [string, string] {
|
||||
return /\.md$/i.test(name) ? [name.slice(0, -3), name.slice(-3)] : [name, ''];
|
||||
}
|
||||
|
||||
const byPath = (renames: readonly LinkRename[], ref: string) =>
|
||||
renames.find((rename) => lower(rename.old_ref) === lower(ref));
|
||||
|
||||
/**
|
||||
* The wiki link `[[ref]]` or `[[ref|display]]` after the renames, or null when it is not affected.
|
||||
* `ref` may carry a heading or block (`Note#Part`, `Note^id`) and a `.md` extension; both are kept.
|
||||
*/
|
||||
export function renamedLink(ref: string, display: string | null, renames: LinkRename | readonly LinkRename[]): RenamedLink | null {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const anchorAt = ref.search(/[#^]/);
|
||||
const name = anchorAt < 0 ? ref : ref.slice(0, anchorAt);
|
||||
const anchor = anchorAt < 0 ? '' : ref.slice(anchorAt);
|
||||
const [base, ext] = splitMdExt(name);
|
||||
let rename = list.find((candidate) => candidate.title_rules && lower(candidate.old_title) === lower(base));
|
||||
let next = rename?.new_title;
|
||||
if (!rename) {
|
||||
rename = byPath(list, base.replace(/\\/g, '/'));
|
||||
if (!rename || rename.old_ref === rename.new_ref) return null;
|
||||
const stemChanges = splitRef(rename.old_ref)[1] !== splitRef(rename.new_ref)[1];
|
||||
// At the top of the vault the path is the bare name, as unsure as a title link.
|
||||
if (!rename.old_ref.includes('/') && !(rename.file_rules && stemChanges)) return null;
|
||||
next = rename.new_ref;
|
||||
}
|
||||
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 };
|
||||
return { ref: next + ext + anchor, display: followsTitle ? rename.new_title : display };
|
||||
}
|
||||
|
||||
/** Resolve `.` and `..` in a slash path; null when it climbs out of the vault. */
|
||||
function normalizeDir(path: string): string | null {
|
||||
const parts: string[] = [];
|
||||
for (const part of path.split('/')) {
|
||||
if (!part || part === '.') continue;
|
||||
if (part === '..') {
|
||||
if (!parts.length) return null;
|
||||
parts.pop();
|
||||
} else parts.push(part);
|
||||
}
|
||||
if (rename.old_ref !== rename.new_ref && ref === rename.old_ref) {
|
||||
return { ref: rename.new_ref, display: followsTitle ? rename.new_title : display };
|
||||
return parts.join('/');
|
||||
}
|
||||
|
||||
/** The `../`-style prefix that leads from folder `from` to folder `to`, ending in `/` unless empty. */
|
||||
function relativeDir(from: string, to: string): string {
|
||||
const a = from.split('/').filter(Boolean);
|
||||
const b = to.split('/').filter(Boolean);
|
||||
let common = 0;
|
||||
while (common < a.length && common < b.length && a[common] === b[common]) common++;
|
||||
return '../'.repeat(a.length - common) + b.slice(common).map((part) => `${part}/`).join('');
|
||||
}
|
||||
|
||||
function decode(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Characters a link destination without `<>` cannot hold as they are. */
|
||||
function encodeFileName(name: string): string {
|
||||
return name.replace(/[% \t()<>#]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
|
||||
}
|
||||
|
||||
const encodePath = (path: string, angled: boolean) => (angled ? path : path.split('/').map(encodeFileName).join('/'));
|
||||
|
||||
/**
|
||||
* The destination of a Markdown link (`Note.md`, `../Folder/Note%20name.md#Part`, `<Note name.md>`)
|
||||
* after the renames, or null when it does not point at a renamed note. `noteDir` is the
|
||||
* vault-relative folder of the note holding the link. The link keeps its form: relative stays
|
||||
* relative, from the vault root stays so, and a bare name stays bare when it still finds the note.
|
||||
*/
|
||||
export function renamedHref(href: string, noteDir: string, renames: LinkRename | readonly LinkRename[]): string | null {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const angled = href.length >= 2 && href.startsWith('<') && href.endsWith('>');
|
||||
const dest = angled ? href.slice(1, -1) : href;
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(dest) || !dest || dest.startsWith('#')) return null;
|
||||
const hashAt = dest.indexOf('#');
|
||||
const path = hashAt < 0 ? dest : dest.slice(0, hashAt);
|
||||
const anchor = hashAt < 0 ? '' : dest.slice(hashAt);
|
||||
const slash = path.lastIndexOf('/');
|
||||
const rawDir = slash < 0 ? '' : path.slice(0, slash + 1);
|
||||
const rawFile = path.slice(slash + 1);
|
||||
const [, ext] = splitMdExt(rawFile);
|
||||
if (!ext) return null;
|
||||
const [stem] = splitMdExt(decode(rawFile));
|
||||
const dir = decode(rawDir).replace(/\\/g, '/');
|
||||
let rename: LinkRename | undefined;
|
||||
let form: 'bare' | 'relative' | 'root' = 'relative';
|
||||
if (!dir) {
|
||||
rename = byPath(list, joinRef(noteDir, stem));
|
||||
if (!rename) {
|
||||
// A bare name from another folder finds the note by its unique file name.
|
||||
rename = list.find((candidate) => {
|
||||
const [, oldStem] = splitRef(candidate.old_ref);
|
||||
return candidate.file_rules && lower(oldStem) === lower(stem) && oldStem !== splitRef(candidate.new_ref)[1];
|
||||
});
|
||||
form = 'bare';
|
||||
}
|
||||
} else {
|
||||
const relative = dir.startsWith('/') ? null : normalizeDir(`${noteDir}/${dir}`);
|
||||
rename = relative === null ? undefined : byPath(list, joinRef(relative, stem));
|
||||
if (!rename) {
|
||||
const root = normalizeDir(dir);
|
||||
rename = root === null ? undefined : byPath(list, joinRef(root, stem));
|
||||
form = 'root';
|
||||
}
|
||||
}
|
||||
if (!rename || rename.old_ref === rename.new_ref) return null;
|
||||
const [oldDir] = splitRef(rename.old_ref);
|
||||
const [newDir, newStem] = splitRef(rename.new_ref);
|
||||
const file = encodePath(newStem + ext, angled);
|
||||
const prefix = lower(oldDir) === lower(newDir)
|
||||
? rawDir
|
||||
: form === 'bare'
|
||||
? ''
|
||||
: form === 'relative'
|
||||
? encodePath(relativeDir(noteDir, newDir), angled)
|
||||
: (dir.startsWith('/') ? '/' : '') + (newDir ? `${encodePath(newDir, angled)}/` : '');
|
||||
const next = prefix + file + anchor;
|
||||
return angled ? `<${next}>` : next;
|
||||
}
|
||||
|
||||
export interface TextChange {
|
||||
@@ -37,15 +163,71 @@ export interface TextChange {
|
||||
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[] = [];
|
||||
// In a table cell the alias separator is written `\\|`, since a bare `|` ends the cell.
|
||||
for (const match of text.matchAll(/\[\[([^\[\]|]+?)(?:(\\?\|)([^\[\]]*))?\]\]/g)) {
|
||||
const next = renamedLink(match[1], match[3] ?? null, rename);
|
||||
if (!next) continue;
|
||||
const insert = next.display === null ? `[[${next.ref}]]` : `[[${next.ref}${match[2]}${next.display}]]`;
|
||||
changes.push({ from: match.index, to: match.index + match[0].length, insert });
|
||||
/** Ranges of `text` outside fenced code blocks and inline code, where links are links. */
|
||||
function proseRanges(text: string): [number, number][] {
|
||||
const ranges: [number, number][] = [];
|
||||
let fence: { char: string; length: number } | null = null;
|
||||
let offset = 0;
|
||||
for (const line of text.split(/(?<=\n)/)) {
|
||||
const start = offset;
|
||||
offset += line.length;
|
||||
const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line.replace(/\r?\n$/, ''));
|
||||
if (fence) {
|
||||
if (opening && opening[1][0] === fence.char && opening[1].length >= fence.length && !opening[2].trim()) fence = null;
|
||||
continue;
|
||||
}
|
||||
if (opening && !(opening[1][0] === '`' && opening[2].includes('`'))) {
|
||||
fence = { char: opening[1][0], length: opening[1].length };
|
||||
continue;
|
||||
}
|
||||
let from = start;
|
||||
const ticks = /`+/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = ticks.exec(line))) {
|
||||
const closing = new RegExp(`(?<!\`)${match[0]}(?!\`)`, 'g');
|
||||
closing.lastIndex = match.index + match[0].length;
|
||||
const end = closing.exec(line);
|
||||
if (!end) continue;
|
||||
ranges.push([from, start + match.index]);
|
||||
from = start + end.index + end[0].length;
|
||||
ticks.lastIndex = end.index + end[0].length;
|
||||
}
|
||||
ranges.push([from, offset]);
|
||||
}
|
||||
return changes;
|
||||
return ranges;
|
||||
}
|
||||
|
||||
const WIKI_LINK = /\[\[([^[\]\n]+?)\]\]/g;
|
||||
const MARKDOWN_LINK = /\[([^[\]\n]*)\]\((<[^<>\n]*>|(?:[^\s()<>]|\([^\s()<>]*\))+)([^)\n]*)\)/g;
|
||||
|
||||
/** The edits that bring the wiki and Markdown links in Markdown text in line with the rename. */
|
||||
export function renamedLinkChanges(text: string, renames: LinkRename | readonly LinkRename[], noteDir = ''): TextChange[] {
|
||||
const list = Array.isArray(renames) ? renames : [renames as LinkRename];
|
||||
const changes: TextChange[] = [];
|
||||
for (const [from, to] of proseRanges(text)) {
|
||||
const prose = text.slice(from, to);
|
||||
for (const match of prose.matchAll(WIKI_LINK)) {
|
||||
const inner = match[1];
|
||||
// In a table cell the alias separator is written `\|`, since a bare `|` ends the cell.
|
||||
const bar = inner.indexOf('|');
|
||||
const escaped = bar > 0 && inner[bar - 1] === '\\';
|
||||
const ref = bar < 0 ? inner : inner.slice(0, escaped ? bar - 1 : bar);
|
||||
const display = bar < 0 ? null : inner.slice(bar + 1);
|
||||
const next = renamedLink(ref, display, list);
|
||||
if (!next) continue;
|
||||
const separator = escaped ? '\\|' : '|';
|
||||
const insert = next.display === null ? `[[${next.ref}]]` : `[[${next.ref}${separator}${next.display}]]`;
|
||||
if (insert !== match[0]) changes.push({ from: from + match.index!, to: from + match.index! + match[0].length, insert });
|
||||
}
|
||||
for (const match of prose.matchAll(MARKDOWN_LINK)) {
|
||||
const href = renamedHref(match[2], noteDir, list);
|
||||
if (href === null) continue;
|
||||
// Link text that was the old title follows the new one.
|
||||
const titled = list.find((rename) => rename.old_title === match[1] && rename.old_title !== rename.new_title);
|
||||
const label = titled ? titled.new_title : match[1];
|
||||
const insert = `[${label}](${href}${match[3]})`;
|
||||
if (insert !== match[0]) changes.push({ from: from + match.index!, to: from + match.index! + match[0].length, insert });
|
||||
}
|
||||
}
|
||||
return changes.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
Vendored
+230
@@ -0,0 +1,230 @@
|
||||
[
|
||||
{
|
||||
"name": "title links, aliases and links to other notes",
|
||||
"rename": {
|
||||
"old_ref": "Home",
|
||||
"new_ref": "Start",
|
||||
"old_title": "Home",
|
||||
"new_title": "Start",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "See [[Home]], [[Home|the start page]] and [[Home|Home]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n",
|
||||
"expected": "See [[Start]], [[Start|the start page]] and [[Start|Start]].\nAlso [[Index|Home]] and [[Notes/Home|Home]].\n"
|
||||
},
|
||||
{
|
||||
"name": "headings, blocks, other capitals, the .md extension and embeds",
|
||||
"rename": {
|
||||
"old_ref": "Home",
|
||||
"new_ref": "Start",
|
||||
"old_title": "Home",
|
||||
"new_title": "Start",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "[[Home#Section]] [[Home^abc123]] [[Home#Section|Home]] [[home]] [[HOME|x]] [[Home.md]] [[Home.md#Part]] ![[Home]] ![[Home#Part|300]] [[Homepage]] [[Home Office]]\n",
|
||||
"expected": "[[Start#Section]] [[Start^abc123]] [[Start#Section|Start]] [[Start]] [[Start|x]] [[Start.md]] [[Start.md#Part]] ![[Start]] ![[Start#Part|300]] [[Homepage]] [[Home Office]]\n"
|
||||
},
|
||||
{
|
||||
"name": "aliased links in a table cell",
|
||||
"rename": {
|
||||
"old_ref": "Home",
|
||||
"new_ref": "Start",
|
||||
"old_title": "Home",
|
||||
"new_title": "Start",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "| [[Home\\|Home]] | [[Home\\|start]] and [[Index\\|Home]] | [[Home#A\\|Home]] |\n",
|
||||
"expected": "| [[Start\\|Start]] | [[Start\\|start]] and [[Index\\|Home]] | [[Start#A\\|Start]] |\n"
|
||||
},
|
||||
{
|
||||
"name": "links in code stay as written",
|
||||
"rename": {
|
||||
"old_ref": "Home",
|
||||
"new_ref": "Start",
|
||||
"old_title": "Home",
|
||||
"new_title": "Start",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "Inline `[[Home]]` and ``a ` [[Home]]`` but [[Home]].\n```\n[[Home]] [x](Home.md)\n```\n~~~~md\n[[Home]]\n~~~\n~~~~\nAfter [[Home]] and `unclosed [[Home]]\n",
|
||||
"expected": "Inline `[[Home]]` and ``a ` [[Home]]`` but [[Start]].\n```\n[[Home]] [x](Home.md)\n```\n~~~~md\n[[Home]]\n~~~\n~~~~\nAfter [[Start]] and `unclosed [[Start]]\n"
|
||||
},
|
||||
{
|
||||
"name": "Markdown links in the same folder",
|
||||
"rename": {
|
||||
"old_ref": "Home",
|
||||
"new_ref": "Start",
|
||||
"old_title": "Home",
|
||||
"new_title": "Start",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "[Home](Home.md) [x](Home.md#Part \"title\") [x](./Home.md) [x](<Home.md>) [x](home.md) \nUntouched: [x](https://example.com/Home.md) [x](Other.md) [x](Home) [x](#Home) [Home](Index.md)\n",
|
||||
"expected": "[Start](Start.md) [x](Start.md#Part \"title\") [x](./Start.md) [x](<Start.md>) [x](Start.md) \nUntouched: [x](https://example.com/Home.md) [x](Other.md) [x](Home) [x](#Home) [Home](Index.md)\n"
|
||||
},
|
||||
{
|
||||
"name": "a note in a folder, linked from that folder",
|
||||
"rename": {
|
||||
"old_ref": "Work/Old Plan",
|
||||
"new_ref": "Work/New Plan",
|
||||
"old_title": "Old Plan",
|
||||
"new_title": "New Plan",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "Work",
|
||||
"input": "[a](Old%20Plan.md) [a](<Old Plan.md>) [[Old Plan]] [[Work/Old Plan#Goals|g]] [[Work\\Old Plan]]\n",
|
||||
"expected": "[a](New%20Plan.md) [a](<New Plan.md>) [[New Plan]] [[Work/New Plan#Goals|g]] [[Work/New Plan]]\n"
|
||||
},
|
||||
{
|
||||
"name": "a note in a folder, linked from another folder",
|
||||
"rename": {
|
||||
"old_ref": "Work/Old Plan",
|
||||
"new_ref": "Work/New Plan",
|
||||
"old_title": "Old Plan",
|
||||
"new_title": "New Plan",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "Other/Deep",
|
||||
"input": "[a](../../Work/Old%20Plan.md#Goals) [a](Work/Old%20Plan.md) [a](/Work/Old%20Plan.md) [a](Old%20Plan.md) [a](Elsewhere/Old%20Plan.md) [a](../Old%20Plan.md)\n",
|
||||
"expected": "[a](../../Work/New%20Plan.md#Goals) [a](Work/New%20Plan.md) [a](/Work/New%20Plan.md) [a](New%20Plan.md) [a](Elsewhere/Old%20Plan.md) [a](../Old%20Plan.md)\n"
|
||||
},
|
||||
{
|
||||
"name": "another note has the same name: only path links follow",
|
||||
"rename": {
|
||||
"old_ref": "Work/Old Plan",
|
||||
"new_ref": "Work/New Plan",
|
||||
"old_title": "Old Plan",
|
||||
"new_title": "New Plan",
|
||||
"title_rules": false,
|
||||
"file_rules": false
|
||||
},
|
||||
"note_dir": "Other",
|
||||
"input": "[[Old Plan]] [[Old Plan|x]] [[Work/Old Plan|Old Plan]] [a](Old%20Plan.md) [a](../Work/Old%20Plan.md)\n",
|
||||
"expected": "[[Old Plan]] [[Old Plan|x]] [[Work/New Plan|New Plan]] [a](Old%20Plan.md) [a](../Work/New%20Plan.md)\n"
|
||||
},
|
||||
{
|
||||
"name": "new names with characters a link destination has to encode",
|
||||
"rename": {
|
||||
"old_ref": "Plan",
|
||||
"new_ref": "Plan (v2) #1",
|
||||
"old_title": "Plan",
|
||||
"new_title": "Plan (v2) #1",
|
||||
"title_rules": true,
|
||||
"file_rules": true
|
||||
},
|
||||
"note_dir": "",
|
||||
"input": "[a](Plan.md) [a](<Plan.md>) [[Plan]]\n",
|
||||
"expected": "[a](Plan%20%28v2%29%20%231.md) [a](<Plan (v2) #1.md>) [[Plan (v2) #1]]\n"
|
||||
},
|
||||
{
|
||||
"name": "a note at the top of the vault whose name another note shares",
|
||||
"rename": {
|
||||
"old_ref": "Plan B",
|
||||
"new_ref": "Plan C",
|
||||
"old_title": "Plan B",
|
||||
"new_title": "Plan C",
|
||||
"title_rules": false,
|
||||
"file_rules": false
|
||||
},
|
||||
"note_dir": "Other",
|
||||
"input": "[[Plan B]] [[Plan B|x]] [[Plan B#Part]] [a](Plan%20B.md) [b](../Plan%20B.md)\n",
|
||||
"expected": "[[Plan B]] [[Plan B|x]] [[Plan B#Part]] [a](Plan%20B.md) [b](../Plan%20C.md)\n"
|
||||
},
|
||||
{
|
||||
"name": "a note moved to another folder, linked from its old folder",
|
||||
"renames": [
|
||||
{
|
||||
"old_ref": "Work/Plan",
|
||||
"new_ref": "Archive/Plan",
|
||||
"old_title": "Plan",
|
||||
"new_title": "Plan",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
}
|
||||
],
|
||||
"note_dir": "Work",
|
||||
"input": "[p](Plan.md) [[Work/Plan]] [[Plan]] [q](./Plan.md#Goals)\n",
|
||||
"expected": "[p](../Archive/Plan.md) [[Archive/Plan]] [[Plan]] [q](../Archive/Plan.md#Goals)\n"
|
||||
},
|
||||
{
|
||||
"name": "a note moved to another folder, linked from elsewhere",
|
||||
"renames": [
|
||||
{
|
||||
"old_ref": "Work/Plan",
|
||||
"new_ref": "Archive/Plan",
|
||||
"old_title": "Plan",
|
||||
"new_title": "Plan",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
}
|
||||
],
|
||||
"note_dir": "Other",
|
||||
"input": "[[Work/Plan#Goals|g]] [a](../Work/Plan.md) [b](Plan.md) [r](/Work/Plan.md) [c](<../Work/Plan.md>) [d](Work/Plan.md)\n",
|
||||
"expected": "[[Archive/Plan#Goals|g]] [a](../Archive/Plan.md) [b](Plan.md) [r](/Archive/Plan.md) [c](<../Archive/Plan.md>) [d](Archive/Plan.md)\n"
|
||||
},
|
||||
{
|
||||
"name": "a renamed notebook moves every note in it",
|
||||
"renames": [
|
||||
{
|
||||
"old_ref": "Work/A",
|
||||
"new_ref": "Projects/A",
|
||||
"old_title": "A",
|
||||
"new_title": "A",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
},
|
||||
{
|
||||
"old_ref": "Work/Sub/B",
|
||||
"new_ref": "Projects/Sub/B",
|
||||
"old_title": "B",
|
||||
"new_title": "B",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
}
|
||||
],
|
||||
"note_dir": "Other",
|
||||
"input": "[[Work/A]] [[Work/Sub/B|b]] [x](../Work/Sub/B.md) [y](../Work/Other.md) [[A]]\n",
|
||||
"expected": "[[Projects/A]] [[Projects/Sub/B|b]] [x](../Projects/Sub/B.md) [y](../Work/Other.md) [[A]]\n"
|
||||
},
|
||||
{
|
||||
"name": "a note moved from the top of the vault into a folder",
|
||||
"renames": [
|
||||
{
|
||||
"old_ref": "Plan",
|
||||
"new_ref": "My Folder/Plan",
|
||||
"old_title": "Plan",
|
||||
"new_title": "Plan",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
}
|
||||
],
|
||||
"note_dir": "",
|
||||
"input": "[[Plan]] [a](Plan.md) [b](<Plan.md>)\n",
|
||||
"expected": "[[Plan]] [a](My%20Folder/Plan.md) [b](<My Folder/Plan.md>)\n"
|
||||
},
|
||||
{
|
||||
"name": "a note moved to the top of the vault",
|
||||
"renames": [
|
||||
{
|
||||
"old_ref": "Work/Plan",
|
||||
"new_ref": "Plan",
|
||||
"old_title": "Plan",
|
||||
"new_title": "Plan",
|
||||
"title_rules": false,
|
||||
"file_rules": true
|
||||
}
|
||||
],
|
||||
"note_dir": "Other",
|
||||
"input": "[[Work/Plan]] [a](../Work/Plan.md) [b](/Work/Plan.md)\n",
|
||||
"expected": "[[Plan]] [a](../Plan.md) [b](/Plan.md)\n"
|
||||
}
|
||||
]
|
||||
@@ -49,3 +49,15 @@ test('aliased links in a table cell follow a rename', () => {
|
||||
'| [[Start\\|Start]] | [[Start\\|start]] and [[Index\\|Home]] |'
|
||||
);
|
||||
});
|
||||
|
||||
// The same cases are checked against the backend rewrite in operations.rs.
|
||||
const fixtures = JSON.parse(await readFile(new URL('./fixtures/renamed-links.json', import.meta.url), 'utf8'));
|
||||
for (const fixture of fixtures) {
|
||||
test(`shared rename case: ${fixture.name}`, () => {
|
||||
let result = fixture.input;
|
||||
for (const change of renamedLinkChanges(fixture.input, fixture.renames ?? fixture.rename, fixture.note_dir).reverse()) {
|
||||
result = result.slice(0, change.from) + change.insert + result.slice(change.to);
|
||||
}
|
||||
assert.equal(result, fixture.expected);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user