From 05227937a1f0003a9daceebc3c98d4726c4b3590 Mon Sep 17 00:00:00 2001 From: Chuangwu Deng Date: Sat, 21 Nov 2026 23:32:05 -0800 Subject: [PATCH] Fix citation anchor namespaces and prepare 1.2.0 --- .github/workflows/release.yml | 2 +- CHANGELOG.md | 10 ++ README.md | 51 +++++-- docs/RELEASE_CHECKLIST.md | 6 + examples/Citation-demo.md | 33 ++++- manifest.json | 4 +- package-lock.json | 4 +- package.json | 4 +- src/bibliography.ts | 251 +++++++++++++++++++--------------- src/citations.ts | 75 +++++----- src/links.ts | 29 ++++ src/main.ts | 27 ++-- src/reading.ts | 30 ++-- src/types.ts | 31 ++++- tests/bibliography.test.ts | 183 +++++++++++++++++++------ tests/citations.test.ts | 8 +- tests/main.test.ts | 124 +++++++++++++++++ tests/model.test.ts | 6 +- tests/reading.test.ts | 36 +++++ tests/scopes.test.ts | 106 ++++++++++++++ versions.json | 3 +- 21 files changed, 776 insertions(+), 247 deletions(-) create mode 100644 src/links.ts create mode 100644 tests/scopes.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a3b73d6..bda68db 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -86,7 +86,7 @@ jobs: '', 'Hover over numeric citations such as [1-10] or [3,1-10,12] to view the corresponding references together in Obsidian Page preview. Citation groups are assembled in memory from the numbered bibliography in the same note.', '', - 'A consistent citation and bibliography format is required. References must be explicitly numbered, unique, and listed under a supported bibliography heading in the same note. See README.md for the exact format and linked-citation examples.', + 'Reference blocks are identified by unique ^ref-N and ^sref-N block IDs in the same note. No particular bibliography heading is required. Use explicit links to distinguish main and supplementary references with the same number. See README.md for the exact format and linked-citation examples.', '', '## Changes', '', diff --git a/CHANGELOG.md b/CHANGELOG.md index 53c544d..e8fc817 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.2.0 + +- Identify references directly from their `^ref-N` and `^sref-N` block IDs, without requiring a bibliography heading. References work under arbitrary headings or with no heading, including notes whose headings contain section numbers or entry counts. +- Also support compact IDs such as `^ref1` and named sets such as `^ref-appendix-1`. Unanchored numbered lists no longer create reference entries; existing plain citations need identifiable reference blocks. +- Keep independent indexes for main and supplementary anchor prefixes, even when entries appear in different parts of a note. Resolve linked citations by their actual targets and expand ranges only within the selected reference set. +- Separate previews and refreshes for groups with identical visible numbers but different reference targets. Check the exact rendered link targets so figure or equation links cannot consume a citation's preview. +- Use the same local-link validation in Reading view and the editor, including relative and encoded note paths. +- Preserve compact and spaced reference lists and multiline reference blocks. Retain ambiguity reporting when a plain numeric citation does not identify a unique reference set. +- Add regression coverage and a copyable main/supplementary demonstration. Keep the plugin ID `citation-range-preview` and minimum Obsidian version `1.15.1`. + ## 1.1.1 - Make the native Page preview implementation available as an update for the existing Obsidian Community listing. The plugin keeps its existing ID, settings, and same-note bibliography format. diff --git a/README.md b/README.md index 2f2ce26..7f9ca81 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Citation Preview -Preview numeric citations in Obsidian using the bibliography already in the same Markdown note. Hover over a citation such as `[1, 3, 5]` or `[1–10]` to see the corresponding references together in a Page preview popover. +Preview numeric citations in Obsidian using the reference blocks already in the same Markdown note. Hover over a citation such as `[1, 3, 5]` or `[1–10]` to see the corresponding references together in a Page preview popover. Reference block IDs identify the entries; no particular bibliography heading is required. ## Why Citation Preview? @@ -22,8 +22,6 @@ Citation Preview was built for that workflow. It assembles the cited entries in Linked range endpoints can preview the entries in between \[[1](#^ref-1)–[3](#^ref-3)\]. - ## References - [1] Example reference one. ^ref-1 [2] Example reference two. ^ref-2 @@ -35,15 +33,50 @@ Citation Preview was built for that workflow. It assembles the cited entries in See the [demonstration note](examples/Citation-demo.md) for more examples. -## Citation and bibliography format +## Citation and reference block format - Put each citation on one line of normal prose. Use positive integers in square brackets, commas for separate numbers, and a hyphen or en dash for an ascending range. -- Put the bibliography under a supported heading such as `## References` or `## Bibliography` in the same note. Start each entry with its explicit number, such as `[1]`, `[2]`, `[3]`, and separate entries with a blank line. Explicitly numbered Markdown list entries such as `1.`, `2.`, `3.` also work. A list using `1.` for every item contains duplicate reference numbers in the source, even if it renders as a sequential list. -- For linked citations, give each target entry a unique block ID and link the matching number to it. Markdown links such as `\[[1](#^ref-1), [3](#^ref-3)\]` and Wikilinks such as `\[[[#^ref-1|1]], [[#^ref-3|3]]\]` keep the visible outer brackets and link the numbers to their own entries. Plain citations do not require block IDs. +- Identify main reference blocks with `^ref-1`, `^ref-2`, and so on; use `^sref-1`, `^sref-2`, and so on for supplementary references. The numeric suffix identifies the reference number, and the prefix distinguishes the two sets. Each block ID must be unique throughout the note. +- Reference blocks can appear under any heading or with no heading at all. Both compact lists and lists separated by blank lines work, including multiline entries. Entries with the same prefix belong to the same reference set even when they appear in different parts of the note. +- Link each stated number to its own block. Markdown links such as `\[[1](#^ref-1), [3](#^ref-3)\]` and Wikilinks such as `\[[[#^ref-1|1]], [[#^ref-3|3]]\]` keep the visible outer brackets. Angle-bracket destinations such as `[1](<#^ref-1>)` also work. +- Plain citations such as `[1–3]` can preview entries when the existing reference block IDs identify a unique set. When main and supplementary references reuse those numbers, use explicit links to select the intended set. + +The compact forms `^ref1` and `^sref1` are also supported. For additional independent sets, use a named prefix such as `^ref-appendix-1` or `^sref-a-1`, with the reference number after the final hyphen. Link to the exact ID used in the note. A visible list number is optional; the block ID supplies the reference number. + +**Upgrading from 1.1.x:** each reference now needs a supported block ID. A heading and an unanchored numbered list alone no longer establish a reference index. Plain in-text citations remain supported when their reference blocks are identifiable as described above. + +Version 1.2.0 uses the actual anchors as its source of reference identity: + +| Reference block | Citation target | Meaning | +| --- | --- | --- | +| `^ref-1` | `#^ref-1` | Main reference 1 | +| `^sref-1` | `#^sref-1` | Supplementary reference 1 | + +### Main and supplementary references in one note + +Main reference 1 and supplementary reference 1 coexist because `#^ref-1` and `#^sref-1` identify different blocks. A linked range expands only within the reference set selected by its endpoints: `ref-1` to `ref-3` selects `ref-1`, `ref-2`, and `ref-3`; the corresponding `sref` range selects the three supplementary entries. Previews with identical visible numbers keep their contents separate. + +```markdown +Main result: \[[1](<#^ref-1>)–[3](<#^ref-3>)\]. + +1. Main reference one. ^ref-1 +2. Main reference two. ^ref-2 +3. Main reference three. ^ref-3 + +## Supplementary notes +Supplementary result: \[[1](<#^sref-1>)–[3](<#^sref-3>)\]. + +### Sources +1. Supplementary reference one. ^sref-1 +2. Supplementary reference two. ^sref-2 +3. Supplementary reference three. ^sref-3 +``` + +The main references in this example have no heading, and the supplementary references use the arbitrary heading `Sources`. Changing either heading, including its language or entry count, does not change how the anchors resolve. A group whose explicit links mix `ref` and `sref` targets is left to normal link behavior; split it into one group for each set. ## Preview behavior -A group opens one native Page preview popover with an ordered list of references. Ranges expand in place, and repeated numbers appear only at their first occurrence. For example, `[3,1-10,12]` shows `3, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12` in that order. Recognized groups flag missing entries and duplicate numbers in the bibliography. +A group opens one native Page preview popover with an ordered list of references. Ranges expand in place, and repeated numbers appear only at their first occurrence. For example, `[3,1-10,12]` shows `3, 1, 2, 4, 5, 6, 7, 8, 9, 10, 12` in that order. Recognized groups flag missing entries and ambiguous reference numbers. The same number in the main and supplementary sets is valid when the citation identifies its target set. A single linked citation uses Obsidian's normal direct Page preview. A single unlinked citation can also preview its matching entry when plain numeric recognition is on. Body links keep their normal Obsidian click behavior, and the preview adds no jump buttons. @@ -57,8 +90,8 @@ A single linked citation uses Obsidian's normal direct Page preview. A single un ## Dependencies and limits - **Obsidian's built-in Page preview must be enabled.** Citation Preview uses Obsidian's private embed registry and renderer to display groups. Changes to those internals can affect compatibility across app versions. The minimum supported version is **Obsidian 1.15.1**, tested on desktop. -- The plugin uses numeric Markdown citations and explicitly numbered references in the current note. Author–date citations, general CSL processing, and resolving references from external sources are outside its scope. Citation lookup needs only Obsidian and the current note. -- Plain numeric recognition is heuristic. A bracketed interval can look like a citation when the note has matching numbered references. Check the heading, explicit numbering, and block targets if a preview is missing. +- The plugin uses numeric Markdown citations and reference block IDs in the current note. Author–date citations, general CSL processing, and resolving references from external sources are outside its scope. Citation lookup needs only Obsidian and the current note. +- Plain numeric recognition is heuristic. A bracketed interval can look like a citation when the note has matching reference blocks. Check the actual `^ref-N` or `^sref-N` block IDs and citation targets if a preview is missing. Headings do not determine whether a block is a reference. - The preview is designed for desktop mouse hover. There is no dedicated touch gesture. ## Install or update diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md index ff36f6e..3d615b4 100644 --- a/docs/RELEASE_CHECKLIST.md +++ b/docs/RELEASE_CHECKLIST.md @@ -5,6 +5,7 @@ - Install the locked dependencies with Node.js 24 and run `npm run check`. - Run `npm run package` and confirm the installation ZIP contains `main.js`, `manifest.json`, and `styles.css` under `citation-range-preview/`. - Check that the manifest, package metadata, compatibility map, and release tag agree. +- Verify the regression cases for reference blocks with arbitrary or absent headings, compact reference lists, and independent `ref`/`sref` numbering. ## Verify in Obsidian @@ -16,6 +17,11 @@ Enable the core Page preview plugin and open the [demonstration note](../example - Check that missing and duplicate reference numbers receive distinct messages. - Verify close behavior, typography, and list spacing in Reading view and confirm group previews work in the editor using its Page preview modifier. - Check that editing bibliography text refreshes the next preview without creating helper files. +- Copy the main/supplementary example into a separate note. Hover both linked `[1–3]` groups in either order and confirm that each displays only its own reference set. +- Rename or remove the reference headings and move one entry elsewhere in the note. The same reference IDs and ranges must continue to resolve. +- Edit a title in each bibliography, save the note, and confirm that both existing citation groups refresh without exchanging contents. +- Check that an ambiguous plain `[1–3]` does not silently select either reference set, and that duplicate block IDs never silently resolve to an arbitrary entry. +- Check same-note relative and encoded link destinations in Reading view and the editor. Numeric figure/equation links must retain their ordinary behavior. ## Publish diff --git a/examples/Citation-demo.md b/examples/Citation-demo.md index efaa14f..edccd46 100644 --- a/examples/Citation-demo.md +++ b/examples/Citation-demo.md @@ -1,10 +1,10 @@ # Citation Preview demonstration -> All ten references in this note are fictional test fixtures. Their authors, titles, journal, years, and pagination are invented for demonstration. Do not cite them as research or add them to a real bibliography. +> All reference examples in this note are fictional test fixtures. Their authors, titles, journal, years, and pagination are invented for demonstration. Do not cite them as research or add them to a real bibliography. Copy this note into an Obsidian vault with Citation Preview and the Page preview core plugin enabled. Start in Reading view and hover over a citation to see its references. In an editor, follow Obsidian's modifier-key setting for Page preview. -All examples use the same References section at the end of this note. Each entry starts with its unique number and ends with its matching block ID. +The live examples use the `^ref-1` through `^ref-10` blocks near the end of this note. Their heading is arbitrary; the block IDs identify the entries. The separate main/supplementary example below is a code block to copy into another note. ## Plain citations @@ -46,17 +46,42 @@ A Wikilink range: \[[[#^ref-1|1]]-[[#^ref-10|10]]\]. A mixed Wikilink group: \[[[#^ref-1|1]]-[[#^ref-3|3]], [[#^ref-5|5]], [[#^ref-8|8]]-[[#^ref-10|10]]\]. +## Main and supplementary bibliographies + +Copy the following block into a **separate note** as ordinary Markdown. Its six references are fictional placeholders. It uses compact lists and independent `ref`/`sref` numbering, as supported in 1.2.0. The main entries have no bibliography heading; the supplementary entries use an arbitrary heading. + +```markdown +## Main text + +Main evidence: \[[1](<#^ref-1>)–[3](<#^ref-3>)\]. + +1. Fictional main reference one. ^ref-1 +2. Fictional main reference two. ^ref-2 +3. Fictional main reference three. ^ref-3 + +## Supplementary notes + +Supplementary evidence: \[[1](<#^sref-1>)–[3](<#^sref-3>)\]. + +### Sources +1. Fictional supplementary reference one. ^sref-1 +2. Fictional supplementary reference two. ^sref-2 +3. Fictional supplementary reference three. ^sref-3 +``` + +Hover the two linked groups in either order. Although both display `[1–3]`, the first should show only the main references and the second only the supplementary references. Edit and save a title in each set, then hover again to confirm that the updated contents remain separate. Rename or remove `Sources`; the same links must continue to work. A plain `[1–3]` in this copied note is ambiguous: use the explicit links to select the intended reference set. + ## Additional checks - Hover over the beginning, separator, and end of a range; each should open the same complete group. - Confirm a single linked citation uses the standard block preview. -- Copy this note before testing duplicate numbering. Add a second entry numbered 4 to the copied bibliography and confirm that its preview reports the ambiguity. +- Copy this note before testing duplicate IDs. Add a second block with `^ref-4` and confirm that the plugin does not silently choose either duplicate. - Change a fictional title in the bibliography, then hover over its citation again to check that the preview updates. - Open another note with a different reference 1 and confirm that each note resolves its own bibliography. - Try reading view, Live Preview, and source mode separately. Editor previews are enabled by default. - Turn off **Recognize plain numeric citations** and confirm that the explicit linked forms still work. Turn it back on for the plain examples. -## References +## Sources for these examples [1] Example Author One. (2091). Fictional demonstration of a coastal signal. Journal of Fictional Preview Fixtures, 1, 1–2. **Fictional test reference.** ^ref-1 diff --git a/manifest.json b/manifest.json index 01b3bdb..4d3807b 100644 --- a/manifest.json +++ b/manifest.json @@ -1,9 +1,9 @@ { "id": "citation-range-preview", "name": "Citation Preview", - "version": "1.1.1", + "version": "1.2.0", "minAppVersion": "1.15.1", - "description": "Preview numeric citation groups in Page preview using the numbered bibliography in the same note.", + "description": "Preview numeric citation groups in Page preview using reference block anchors in the same note.", "author": "Chuangwu Deng", "authorUrl": "https://github.com/lyingTree", "isDesktopOnly": false diff --git a/package-lock.json b/package-lock.json index 76914ea..0634e86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "citation-preview", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "citation-preview", - "version": "1.1.1", + "version": "1.2.0", "license": "MIT", "devDependencies": { "@codemirror/language": "^6.13.1", diff --git a/package.json b/package.json index 0137d6f..eb4d591 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "citation-preview", - "version": "1.1.1", - "description": "Preview numeric citation groups in Page preview using the numbered bibliography in the same note.", + "version": "1.2.0", + "description": "Preview numeric citation groups in Page preview using reference block anchors in the same note.", "main": "main.js", "private": true, "scripts": { diff --git a/src/bibliography.ts b/src/bibliography.ts index 1a2712f..d4394f6 100644 --- a/src/bibliography.ts +++ b/src/bibliography.ts @@ -1,4 +1,4 @@ -import type { ReferenceEntry, ReferenceIndex } from './types'; +import type { ReferenceEntry, ReferenceIndex, ReferenceSection } from './types'; export interface SourceRange { from: number; to: number } @@ -29,9 +29,9 @@ function escaped(source: string, offset: number): boolean { } /** Syntax that must not be interpreted as citation text. No Markdown is executed. */ -export function ignoredMarkdownRanges(source: string, lines = sourceLines(source)): SourceRange[] { +export function ignoredMarkdownRanges(source: string, lines = sourceLines(source), includeIndentedCode = true): SourceRange[] { const ranges: SourceRange[] = []; - let fenced: { marker: string; length: number; from: number } | undefined; + let fenced: { marker: string; length: number; from: number; inList: boolean } | undefined; let frontmatterEnd = 0; if (lines[0]?.text.replace(/^\uFEFF/, '').trim() === '---') { const close = lines.findIndex((line, i) => i > 0 && /^(?:---|\.\.\.)\s*$/.test(line.text)); @@ -40,7 +40,13 @@ export function ignoredMarkdownRanges(source: string, lines = sourceLines(source } for (const line of lines) { if (line.from < frontmatterEnd) continue; - const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line.text); + const indent = indentation(line.text); + const continuationStart = !fenced && !includeIndentedCode && indent > 0 ? entryFirstLine(lines, line.line, 0) : undefined; + const parentList = continuationStart === undefined ? undefined : entryPrefix(lines[continuationStart].text); + const inList = !!parentList && indent >= parentList.contentIndent && indent < parentList.contentIndent + 4; + // Extra indentation is meaningful for a fence only inside an actual list item. + // Literal backticks in top-level indented code must not hide subsequent references. + const fence = (fenced?.inList || inList ? /^[ \t]*(`{3,}|~{3,})(.*)$/ : /^ {0,3}(`{3,}|~{3,})(.*)$/).exec(line.text); if (fenced) { if (fence && fence[1][0] === fenced.marker && fence[1].length >= fenced.length && !fence[2].trim()) { ranges.push({ from: fenced.from, to: line.to }); @@ -50,10 +56,10 @@ export function ignoredMarkdownRanges(source: string, lines = sourceLines(source } if (fence) { if (fence[1][0] === '`' && fence[2].includes('`')) continue; - fenced = { marker: fence[1][0], length: fence[1].length, from: line.from }; + fenced = { marker: fence[1][0], length: fence[1].length, from: line.from, inList }; continue; } - if (/^(?: {4}|\t)/.test(line.text)) ranges.push({ from: line.from, to: line.to }); + if (indent >= 4 && (includeIndentedCode || continuationStart === undefined)) ranges.push({ from: line.from, to: line.to }); if (/^ {0,3}\[[^\]\n]+\]:\s*/.test(line.text)) ranges.push({ from: line.from, to: line.to }); } if (fenced) ranges.push({ from: fenced.from, to: source.length }); @@ -122,129 +128,160 @@ export function ignoredMarkdownRanges(source: string, lines = sourceLines(source return merged; } -function heading(text: string): { level: number; title: string } | undefined { - const match = /^ {0,3}(#{1,6})\s+(.+?)\s*#*\s*$/.exec(text); +/** Only explicit reference block IDs establish a bibliography namespace. */ +function referenceAnchor(id: string): { number: number; namespace: string } | undefined { + const match = /^(s?ref)-?([1-9]\d{0,8})$/i.exec(id) + ?? /^((?:s?ref)(?:-[A-Za-z][A-Za-z0-9]*)+)-([1-9]\d{0,8})$/i.exec(id); if (!match) return undefined; - return { level: match[1].length, title: match[2] }; + return { number: Number(match[2]), namespace: match[1].toLowerCase() }; } -function isBibliographyTitle(title: string): boolean { - const normalized = title - .replace(/[*_]/g, '') - .replace(/^(?:\d+(?:\.\d+)*[.)、]?\s+|第[一二三四五六七八九十百\d]+[章节]\s*)/, '') - .replace(/[::]\s*$/, '') - .trim(); - return /^(?:references|bibliography|literature\s+cited|works\s+cited|参考文献|參考文獻|参考资料|參考資料)$/i.test(normalized); +function rangeAt(offset: number, ranges: SourceRange[]): SourceRange | undefined { + let low = 0; + let high = ranges.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (ranges[middle].to <= offset) low = middle + 1; + else high = middle; + } + const range = ranges[low]; + return range && range.from <= offset ? range : undefined; } -const EMPTY_ANCHOR = /]*\b(?:id|name)\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>\s*<\/a\s*>/gi; +function indentation(text: string): number { + let width = 0; + for (const char of text) { + if (char === ' ') { width += 1; continue; } + if (char === '\t') { width += 4 - width % 4; continue; } + break; + } + return width; +} -function anchorFrom(text: string): string | undefined { - const block = /(?:^|\s)\^([A-Za-z0-9-]+)\s*$/m.exec(text); - if (block) return `^${block[1]}`; - const anchor = /]*\b(?:id|name)\s*=\s*(?:"([^"]+)"|'([^']+)')[^>]*>/i.exec(text); - return anchor?.[1] ?? anchor?.[2]; +interface EntryPrefix { length: number; indent: number; contentIndent: number } + +function entryPrefix(text: string): EntryPrefix | undefined { + const match = /^[ \t]*(?:(?:\[\d+\]|[\d+]|【\d+】|\(\d+\)|(\d+)|\d+[.)、.])[ \t]*|[-+*][ \t]+)/.exec(text); + if (!match) return undefined; + return { + length: match[0].length, + indent: indentation(text), + contentIndent: indentation(match[0].replace(/\S/g, ' ')) + }; } -interface EntryStart { number: number; prefix: number; heading?: string; anchor?: string } - -function entryStart(text: string): EntryStart | undefined { - // HTML anchors may occur immediately before the reference label. - const anchorPrefix = /^(?:\s*]*\b(?:id|name)\s*=\s*(?:"[^"]+"|'[^']+')[^>]*>\s*<\/a\s*>\s*)*/i.exec(text)?.[0] ?? ''; - const tail = text.slice(anchorPrefix.length); - const h = heading(tail); - const value = h ? h.title : tail; - const numbered = /^\s*(?:\[(\d+)\]|[(\d+)]|【(\d+)】|\((\d+)\)|((\d+))|(\d+)[.)、.])(?:\s*|$)/.exec(value); - const bareHeading = h ? /^\s*(\d+)\s*$/.exec(value) : null; - const digits = numbered ? numbered.slice(1).find(Boolean) : bareHeading?.[1]; - if (!digits) return undefined; - const number = Number(digits); - if (!Number.isSafeInteger(number) || number < 1) return undefined; - const markerLength = numbered?.[0].length ?? value.length; - const prefix = anchorPrefix.length + (h ? tail.indexOf(h.title) : 0) + markerLength; - return { number, prefix, heading: h?.title, anchor: anchorFrom(anchorPrefix) }; +/** Structural block boundaries, independent of the wording or language of any heading. */ +function blockBoundary(text: string): boolean { + return /^ {0,3}#{1,6}(?:\s|$)/.test(text) + || /^[ \t]*(?:`{3,}|~{3,})/.test(text) + || /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|=+)\s*$/.test(text) + || /(?:^|\s)\^[A-Za-z0-9-]+\s*$/.test(text); } -function stripEntrySyntax(raw: string, start: EntryStart): string { - let text = raw.slice(start.prefix); - text = text.replace(EMPTY_ANCHOR, '').replace(/(?:^|\s)\^[A-Za-z0-9-]+\s*$/gm, ''); - // Reference continuations commonly indent their wrapped lines. - return text.replace(/^ {1,4}(?=\S)/gm, '').trim(); +/** Locate the paragraph/list item ending at an explicit anchor, never the following text. */ +function entryFirstLine(lines: SourceLine[], last: number, floor: number): number | undefined { + let first = last; + while (first > floor) { + const prefix = entryPrefix(lines[first].text); + if (prefix && prefix.indent <= 3) break; + const previous = lines[first - 1].text; + if (!previous.trim() || blockBoundary(previous)) break; + first -= 1; + } + const indent = indentation(lines[first].text); + if (!indent) return first; + if (entryPrefix(lines[first].text)?.indent === indent && indent <= 3) return first; + + // A separately spaced, indented continuation can still belong to the previous list item. + // A true indented code block has no enclosing item, or is indented four extra columns. + for (let previous = first - 1; previous >= floor; previous -= 1) { + const text = lines[previous].text; + if (!text.trim()) continue; + if (blockBoundary(text)) break; + const prefix = entryPrefix(text); + if (prefix && prefix.indent <= 3) { + if (indent < prefix.contentIndent || indent >= prefix.contentIndent + 4) break; + const continuation = lines.slice(previous + 1, first).every(line => !line.text.trim() || indentation(line.text) >= prefix.contentIndent); + if (continuation) return previous; + break; + } + if (indentation(text) < indent) break; + } + return indent >= 4 ? undefined : first; } -/** Parse only explicit bibliography sections; never derive references from body numbers. */ +/** Parse anchored reference blocks anywhere in the note. Heading text never creates entries. */ export function parseReferences(source: string, lines = sourceLines(source), ignored = ignoredMarkdownRanges(source, lines)): ReferenceIndex { - const result: ReferenceIndex = { entries: new Map(), duplicates: new Set(), sections: [] }; - let blocked = 0; - const isIgnored = (offset: number): boolean => { - while (blocked < ignored.length && ignored[blocked].to <= offset) blocked += 1; - return !!ignored[blocked] && ignored[blocked].from <= offset && offset < ignored[blocked].to; + const result: ReferenceIndex = { + entries: new Map(), duplicates: new Set(), sections: [], referenceRanges: [], + anchors: new Map(), duplicateAnchors: new Set() }; - let section: { from: number; level: number } | undefined; - let current: { line: SourceLine; start: EntryStart; from: number; prefixAnchor?: string } | undefined; - let precedingAnchor: { from: number; text: string } | undefined; - - const finishEntry = (to: number): void => { - if (!current) return; - const { line, start, from, prefixAnchor = '' } = current; - const raw = source.slice(line.from, to); - const markdown = stripEntrySyntax(raw, start); - const entry: ReferenceEntry = { - number: start.number, - markdown, - from, - to: to - (source.slice(from, to).match(/\s*$/)?.[0].length ?? 0), - line: line.line, - anchor: anchorFrom(prefixAnchor + raw) ?? start.anchor ?? start.heading - }; - if (result.entries.has(entry.number) || result.duplicates.has(entry.number)) { - result.duplicates.add(entry.number); - result.entries.delete(entry.number); - } else { - result.entries.set(entry.number, entry); + const namespaces = new Map(); + let hardIgnored: SourceRange[] | undefined; + let floor = 0; + + const addNumber = (entry: ReferenceEntry, index: Pick): void => { + if (index.entries.has(entry.number) || index.duplicates.has(entry.number)) { + index.duplicates.add(entry.number); + index.entries.delete(entry.number); + return; } - current = undefined; - }; - const finishSection = (to: number): void => { - if (!section) return; - finishEntry(to); - result.sections.push({ from: section.from, to }); - section = undefined; - precedingAnchor = undefined; + index.entries.set(entry.number, entry); }; for (let i = 0; i < lines.length; i += 1) { const line = lines[i]; - if (isIgnored(line.from)) continue; - const h = heading(line.text); - const setext = lines[i + 1] && /^ {0,3}(?:=+|-+)\s*$/.test(lines[i + 1].text); - const title = h?.title ?? line.text.trim(); - const isTitle = isBibliographyTitle(title); - if (isTitle) { - finishSection(line.from); - section = { from: line.from, level: h?.level ?? (setext && lines[i + 1].text.trim()[0] === '-' ? 2 : 1) }; - if (setext && !h) i += 1; - continue; + const match = /(?:^|[ \t])\^([A-Za-z0-9-]+)[ \t]*$/.exec(line.text); + if (!match) continue; + const identity = referenceAnchor(match[1]); + if (!identity) continue; + const caret = match.index + match[0].indexOf('^'); + const anchorOffset = line.from + caret; + if (rangeAt(anchorOffset, ignored)) { + if (indentation(line.text) < 4) continue; + // Recheck hard exclusions before accepting a list continuation that resembles code. + hardIgnored ??= ignoredMarkdownRanges(source, lines, false); + if (rangeAt(anchorOffset, hardIgnored)) continue; } - if (!section) continue; - const start = entryStart(line.text); - if (h && h.level <= section.level && !start) { finishSection(line.from); continue; } - if (start) { - const from = precedingAnchor?.from ?? line.from; - finishEntry(from); - current = { line, start, from, prefixAnchor: precedingAnchor?.text }; - precedingAnchor = undefined; - // A preceding anchor belongs to this entry, not the previous one. - continue; + const standalone = !line.text.slice(0, caret).trim(); + let last = standalone ? i - 1 : i; + while (last >= floor && !lines[last].text.trim()) last -= 1; + if (last < floor) continue; + if (standalone && blockBoundary(lines[last].text)) continue; + const first = entryFirstLine(lines, last, floor); + if (first === undefined) continue; + const from = lines[first].from; + const raw = source.slice(from, anchorOffset); + if (!raw.trim()) continue; + hardIgnored ??= ignoredMarkdownRanges(source, lines, false); + const contentFrom = from + (raw.match(/^\s*/)?.[0].length ?? 0); + const contentTo = anchorOffset - (raw.match(/\s*$/)?.[0].length ?? 0); + const blockedContent = rangeAt(contentFrom, hardIgnored); + if (blockedContent && blockedContent.to >= contentTo) continue; + + const prefix = entryPrefix(lines[first].text); + const markdown = raw.slice(prefix?.length ?? 0).replace(/^(?: {1,4}|\t)(?=\S)/gm, '').trim(); + if (!markdown) continue; + const to = anchorOffset + match[1].length + 1; + const anchor = `^${match[1]}`; + const entry: ReferenceEntry = { number: identity.number, markdown, from, to, line: lines[first].line, sectionId: identity.namespace, anchor }; + let section = namespaces.get(identity.namespace); + if (!section) { + section = { id: identity.namespace, title: identity.namespace, from, to, entries: new Map(), duplicates: new Set() }; + namespaces.set(identity.namespace, section); + result.sections.push(section); } - const anchorOnly = line.text.trim().replace(EMPTY_ANCHOR, '').trim() === '' && / { + const anchor = localLinkAnchor(target, sourcePath); + if (!anchor || index.duplicateAnchors.has(anchor)) return { valid: false }; + const entry = index.anchors.get(anchor); + // A plausible suffix is not evidence that a link points to a bibliography entry. + // Exact anchors also support supplementary and user-defined naming conventions. + if (!entry || entry.number !== number) return { valid: false }; + return { valid: true, scopeId: entry.sectionId, target: anchor }; } /** Read a Markdown link destination with bounded, balanced parentheses. */ @@ -78,14 +63,14 @@ function readToken(source: string, from: number, index: ReferenceIndex, options: if (divider < 0) return undefined; const number = positiveInteger(body.slice(divider + 1).trim()); if (!number) return undefined; - return { number, to: end + 2, linked: true, valid: localReferenceLink(body.slice(0, divider), number, index, options.sourcePath) }; + return { number, to: end + 2, linked: true, ...localReferenceLink(body.slice(0, divider), number, index, options.sourcePath) }; } const linkLabel = /^\[([1-9]\d{0,8})\]/.exec(source.slice(from, from + 12)); if (linkLabel) { const destination = destinationAt(source, from + linkLabel[0].length); if (!destination) return undefined; const number = Number(linkLabel[1]); - return { number, to: destination.to, linked: true, valid: localReferenceLink(destination.target, number, index, options.sourcePath) }; + return { number, to: destination.to, linked: true, ...localReferenceLink(destination.target, number, index, options.sourcePath) }; } const digits = /^[1-9]\d{0,8}/.exec(source.slice(from, from + 10)); if (!digits || /\d/.test(source[from + digits[0].length] ?? '')) return undefined; @@ -147,8 +132,21 @@ function groupFromParts(parts: Parts, from: number, to: number, index: Reference if (!numbers?.length) return undefined; // At least one indexed endpoint is evidence; absent intermediate entries are shown as missing. if (!parts.tokens.some(token => index.entries.has(token.number) || index.duplicates.has(token.number))) return undefined; + const scopes = new Set(parts.tokens.flatMap(token => token.scopeId ? [token.scopeId] : [])); + // A range has no defined intermediate entries when its endpoints belong to different bibliographies. + if (scopes.size > 1) return undefined; + let scopeId = scopes.values().next().value; + let ambiguousScope = false; + if (!scopeId) { + const endpoints = parts.tokens.filter(token => index.entries.has(token.number) || index.duplicates.has(token.number)); + const candidates = index.sections.filter(section => endpoints.every(token => section.entries.has(token.number) || section.duplicates.has(token.number))); + if (!candidates.length) return undefined; + if (candidates.length === 1) scopeId = candidates[0].id; + else ambiguousScope = true; + } const label = `[${parts.tokens.map((token, i) => `${token.number}${parts.separators[i] ? (/[-–—−-]/.test(parts.separators[i]) ? '–' : ', ') : ''}`).join('')}]`; - return { from, to, label, numbers, linked }; + return { from, to, label, numbers, linked, scopeId, ambiguousScope, + linkTargets: parts.tokens.flatMap(token => token.target ? [token.target] : []) }; } function bracketGroup(source: string, from: number, index: ReferenceIndex, options: ParseOptions): CitationGroup | undefined { @@ -164,7 +162,10 @@ function bracketGroup(source: string, from: number, index: ReferenceIndex, optio let outerLink = false; if (source[to] === '(') { const destination = destinationAt(source, to); - if (!destination || !localReferenceLink(destination.target, parts.tokens[0].number, index, options.sourcePath)) return undefined; + if (!destination) return undefined; + const resolution = localReferenceLink(destination.target, parts.tokens[0].number, index, options.sourcePath); + if (!resolution.valid) return undefined; + parts.tokens[0] = { ...parts.tokens[0], ...resolution, linked: true }; outerLink = true; to = destination.to; } @@ -186,7 +187,7 @@ export function findCitationGroups(source: string, index: ReferenceIndex, option if ((!index.entries.size && !index.duplicates.size) || !Number.isFinite(options.maxReferences) || options.maxReferences < 1) return []; const boundedOptions = { ...options, maxReferences: Math.min(1000, Math.floor(options.maxReferences)) }; const chars = source.split(''); - for (const range of [...ignored, ...index.sections]) maskRange(chars, range.from, range.to); + for (const range of [...ignored, ...index.referenceRanges]) maskRange(chars, range.from, range.to); // A Markdown link can wrap its destination in angle brackets, including local block links. // Preserve those destinations while masking HTML attributes and raw code containers. const markup = /\]\([ \t]*<[^<>\r\n]*>(?=[ \t]*(?:\)|["'(]))|<(pre|code|script|style)\b[^>]*>[\s\S]*?<\/\1\s*>|<[^>\n]*>/gi; diff --git a/src/links.ts b/src/links.ts new file mode 100644 index 0000000..53838d4 --- /dev/null +++ b/src/links.ts @@ -0,0 +1,29 @@ +function normalizePath(path: string): string { + const parts: string[] = []; + for (const part of path.replace(/\\/g, '/').replace(/\.md$/i, '').split('/')) { + if (!part || part === '.') continue; + if (part === '..') { parts.pop(); continue; } + parts.push(part); + } + return parts.join('/'); +} + +/** Normalize a link only when it targets the current note; never accept external URLs. */ +export function localLinkAnchor(target: string, sourcePath?: string): string | undefined { + let destination: string; + try { destination = decodeURIComponent(target); } catch { return undefined; } + if (/^[a-z][a-z\d+.-]*:/i.test(destination) || destination.startsWith('//')) return undefined; + const hash = destination.indexOf('#'); + if (hash < 0 || hash === destination.length - 1) return undefined; + const path = destination.slice(0, hash); + const anchor = destination.slice(hash + 1); + if (!path) return anchor; + if (!sourcePath) return undefined; + const source = normalizePath(sourcePath); + const normalized = normalizePath(path); + const directory = source.slice(0, Math.max(0, source.lastIndexOf('/'))); + const relative = normalizePath(`${directory}/${path}`); + const basename = source.slice(source.lastIndexOf('/') + 1); + if (normalized !== source && relative !== source && !(normalized === basename && !path.includes('/'))) return undefined; + return anchor; +} diff --git a/src/main.ts b/src/main.ts index 5d9b5ef..3b15ada 100644 --- a/src/main.ts +++ b/src/main.ts @@ -10,7 +10,12 @@ import { DEFAULT_SETTINGS, type CitationGroup, type PluginSettings } from './typ interface ReadingTarget { model: CitationDocument; group: CitationGroup | undefined; - label: string; + key: string; +} + +/** Visible numbers can repeat in independently numbered bibliographies. */ +function groupKey(group: CitationGroup): string { + return JSON.stringify([group.scopeId ?? null, group.linkTargets ?? [], group.numbers, group.ambiguousScope ?? false]); } export default class CitationPreview extends Plugin { @@ -73,10 +78,11 @@ export default class CitationPreview extends Plugin { hover(event: MouseEvent, anchor: HTMLElement, model: CitationDocument, group: CitationGroup, editor = false): boolean { if (!isPagePreviewEnabled(this.app)) return false; if (!editor && this.settings.requireModifier && !event.ctrlKey && !event.metaKey) return false; - let preview = model.previewGroups.get(group.label); + const key = groupKey(group); + let preview = model.previewGroups.get(key); if (!preview) { preview = this.buildPreview(model, group); - model.previewGroups.set(group.label, preview); + model.previewGroups.set(key, preview); } this.previewPath = model.sourcePath; this.app.workspace.trigger('hover-link', { @@ -93,14 +99,17 @@ export default class CitationPreview extends Plugin { private buildPreview(model: CitationDocument, group: CitationGroup): GroupPreview { let linktext: string | undefined; + const references = group.scopeId === undefined ? model.references + : model.references.sections.find(section => section.id === group.scopeId); const entries = group.numbers.map(number => { - const reference = model.references.entries.get(number); + if (group.ambiguousScope) return 'Ambiguous bibliography'; + const reference = references?.entries.get(number); if (!linktext && reference?.anchor?.startsWith('^')) linktext = '#' + reference.anchor; - if (!reference) return model.references.duplicates.has(number) ? 'Duplicate reference' : 'Reference not found'; + if (!reference) return references?.duplicates.has(number) ? 'Duplicate reference' : 'Reference not found'; return reference.markdown.replace(/!\[\[/g, '[[').replace(/!\[([^\]]*)\]\(/g, '[$1]('); }); const markdown = entries.map(entry => '1. ' + (entry || '\u00a0').replace(/\n/g, '\n ')).join('\n'); - // A subpath keeps the preview in block mode even when the bibliography has no anchors. + // A subpath also keeps missing or ambiguous reference previews in block mode. return { linktext: linktext ?? '#^crp-preview', markdown, entries, numbers: group.numbers }; } @@ -131,7 +140,7 @@ export default class CitationPreview extends Plugin { for (const trigger of triggers) { const anchor = trigger.element; anchor.setAttribute('aria-haspopup', 'dialog'); - const target: ReadingTarget = { model, group: trigger.group, label: trigger.group.label }; + const target: ReadingTarget = { model, group: trigger.group, key: groupKey(trigger.group) }; targets.add(target); registered.push(target); let handled = false; @@ -169,9 +178,9 @@ export default class CitationPreview extends Plugin { if (first.model.source === source) return; this.closePreview(path); const model = this.parse(source, path); - const byLabel = new Map(model.groups.map(group => [group.label, group])); + const byKey = new Map(model.groups.map(group => [groupKey(group), group])); for (const target of this.readingByPath.get(path) ?? []) { - target.group = byLabel.get(target.label); + target.group = byKey.get(target.key); target.model = model; } } diff --git a/src/reading.ts b/src/reading.ts index 736b72c..ff24d6b 100644 --- a/src/reading.ts +++ b/src/reading.ts @@ -1,4 +1,5 @@ import type { CitationGroup } from './types'; +import { localLinkAnchor } from './links'; export interface ReadingTrigger { element: HTMLElement; @@ -115,23 +116,9 @@ function candidates(run: TextRun): Candidate[] { return result.sort((left, right) => left.from - right.from); } -function normalizeNotePath(path: string): string { - return path.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\.md$/i, ''); -} - -function isLocalReferenceLink(anchor: HTMLAnchorElement, sourcePath?: string): boolean { +function referenceAnchor(anchor: HTMLAnchorElement, sourcePath?: string): string | undefined { const target = anchor.getAttribute('data-href') ?? anchor.getAttribute('href') ?? ''; - if (!target || /^[a-z][a-z\d+.-]*:/i.test(target) || target.startsWith('//')) return false; - const hash = target.indexOf('#'); - if (hash < 0 || hash === target.length - 1) return false; - const path = target.slice(0, hash); - if (!path) return true; - if (!sourcePath) return false; - let decoded = path; - try { decoded = decodeURIComponent(path); } catch { return false; } - const normalized = normalizeNotePath(decoded); - const current = normalizeNotePath(sourcePath); - return normalized === current || (!normalized.includes('/') && normalized === current.split('/').pop()); + return localLinkAnchor(target, sourcePath); } function candidateLinks(candidate: Candidate): Set { @@ -200,8 +187,15 @@ export function decorateReadingCitations( const bucket = available.get(candidate.key); if (!bucket?.length) continue; const links = candidateLinks(candidate); - const localLinks = links.size > 0 && Array.from(links).every(link => isLocalReferenceLink(link, options.sourcePath)); - const match = bucket.findIndex(group => group.linked ? localLinks : candidate.bracketed && links.size === 0); + const targets = Array.from(links, link => referenceAnchor(link, options.sourcePath)); + const localLinks = targets.length > 0 && targets.every(target => target !== undefined); + const match = bucket.findIndex(group => { + if (!group.linked) return candidate.bracketed && links.size === 0; + if (!localLinks) return false; + if (!group.linkTargets) return true; + return group.linkTargets.length === targets.length + && group.linkTargets.every((target, index) => target === targets[index]); + }); if (match < 0) continue; const group = bucket.splice(match, 1)[0]; plans.push({ candidate, group }); diff --git a/src/types.ts b/src/types.ts index 84ab331..8ff7e01 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,20 +1,37 @@ -/** A reference number is local to exactly one Markdown file. Offsets are UTF-16. */ +/** A reference number is local to an anchor namespace (ref, sref, ...). Offsets are UTF-16. */ export interface ReferenceEntry { number: number; + sectionId: string; markdown: string; from: number; to: number; line: number; - /** Existing ^block-id or #heading/HTML anchor, without the leading #. */ + /** Existing reference block ID including ^, without the leading #. */ anchor?: string; } +export interface ReferenceSection { + /** Namespace from the block ID, independent of headings or document position. */ + id: string; + title: string; + from: number; + to: number; + entries: Map; + duplicates: Set; +} + export interface ReferenceIndex { + /** File-wide lookup, used only when a citation cannot select a bibliography. */ entries: Map; /** Ambiguous numbers must never silently resolve to the wrong reference. */ duplicates: Set; - /** UTF-16 ranges occupied by bibliography sections. */ - sections: Array<{ from: number; to: number }>; + /** Independent anchor namespaces; headings never determine reference membership. */ + sections: ReferenceSection[]; + /** Actual reference blocks, not the prose between references in the same namespace. */ + referenceRanges: Array<{ from: number; to: number }>; + /** Exact, unique anchors take precedence over numeric naming conventions. */ + anchors: Map; + duplicateAnchors: Set; } export interface CitationGroup { @@ -24,6 +41,12 @@ export interface CitationGroup { numbers: number[]; /** True if the citation contains explicit links to numbered reference anchors. */ linked: boolean; + /** Anchor namespace selected by explicit links or unique number evidence. */ + scopeId?: string; + /** More than one anchor namespace could supply a plain numeric group. */ + ambiguousScope?: boolean; + /** Exact same-note anchors in source order, for aligning rendered links safely. */ + linkTargets?: string[]; } export interface ParseOptions { diff --git a/tests/bibliography.test.ts b/tests/bibliography.test.ts index dc3b96c..891c5e6 100644 --- a/tests/bibliography.test.ts +++ b/tests/bibliography.test.ts @@ -2,80 +2,175 @@ import { describe, expect, it } from 'vitest'; import { ignoredMarkdownRanges, parseReferences } from '../src/bibliography'; describe('parseReferences', () => { - it('indexes multiline references and preserves source offsets and block IDs', () => { - const source = '😀 Intro [1–2].\r\n\r\n## 参考文献\r\n\r\n1. Smith. First title.\r\n Journal, 2024. ^ref-1\r\n\r\n2. Lee. Second title. ^ref-2\r\n\r\n## Appendix\r\n1. Not a reference.\r\n'; + it('indexes multiline anchored references without headings and preserves exact source offsets', () => { + const source = '😀 Intro [1–2].\r\n\r\n1. Smith. First title.\r\n Journal, 2024. ^ref-1\r\n\r\n2. Lee. Second title. ^ref-2\r\n\r\nBody after references.'; const index = parseReferences(source); expect([...index.entries.keys()]).toEqual([1, 2]); - expect(index.entries.get(1)).toMatchObject({ number: 1, markdown: 'Smith. First title.\r\nJournal, 2024.', line: 4, anchor: '^ref-1' }); + expect(index.entries.get(1)).toMatchObject({ number: 1, markdown: 'Smith. First title.\r\nJournal, 2024.', line: 2, anchor: '^ref-1', sectionId: 'ref' }); const entry = index.entries.get(2)!; expect(source.slice(entry.from, entry.to)).toBe('2. Lee. Second title. ^ref-2'); - expect(source.slice(index.sections[0].from, index.sections[0].to)).not.toContain('Appendix'); + expect(index.referenceRanges).toHaveLength(2); }); - it.each(['References', 'REFERENCES', 'Bibliography', 'Literature cited', 'Works cited', '参考文献', '參考文獻', '6. References', '6.2 References', '**参考文献**'])('recognizes the bibliography heading %s', title => { - const index = parseReferences(`## ${title}\n[1] First reference.\n[2] Second reference.`); - expect(index.entries.size).toBe(2); + it.each(['', '## References\n', '## 6 参考文献(66条)\n', '### Unrelated heading\n', 'Some arbitrary prose.\n\n'])('does not depend on the text or presence of a heading: %s', heading => { + const index = parseReferences(`${heading}1. First. ^ref-1\n2. Second. ^ref-2`); + expect([...index.entries.keys()]).toEqual([1, 2]); + expect(index.sections[0]).toMatchObject({ id: 'ref', title: 'ref' }); + }); + + it.each(['## References', '## 参考文献', 'References\n----------', '### 7.7 补充参考文献(30条)'])('does not invent references from unanchored lists even under %s', heading => { + const index = parseReferences(`${heading}\n1. First.\n2. Second.`); + expect(index.entries.size).toBe(0); + expect(index.sections).toEqual([]); + expect(index.referenceRanges).toEqual([]); + }); + + it.each(['[1]', '[1]', '【1】', '(1)', '(1)', '1.', '1)', '1、', '1.', '-'])('strips the optional reference label %s', marker => { + expect(parseReferences(`${marker} First reference. ^ref-1`).entries.get(1)?.markdown).toBe('First reference.'); + }); + + it('accepts unnumbered paragraphs and uses the anchor number rather than a display label', () => { + expect(parseReferences('An unnumbered reference. ^ref-12').entries.get(12)?.markdown).toBe('An unnumbered reference.'); + const index = parseReferences('99. First reference. ^ref-1'); + expect([...index.entries.keys()]).toEqual([1]); + expect(index.entries.get(1)?.markdown).toBe('First reference.'); + }); + + it.each([ + ['ref1', 'ref'], ['ref-1', 'ref'], ['sref1', 'sref'], ['sref-1', 'sref'], + ['REF-1', 'ref'], ['Sref-a-1', 'sref-a'], ['ref-appendix-1', 'ref-appendix'], ['ref-appendix-a2-1', 'ref-appendix-a2'] + ])('uses the exact anchor %s and stable namespace %s', (anchor, namespace) => { + const index = parseReferences(`First reference. ^${anchor}`); + expect(index.anchors.get(`^${anchor}`)).toMatchObject({ number: 1, sectionId: namespace }); + expect(index.sections[0].id).toBe(namespace); + }); + + it.each(['fig-1', 'tbl-1', 'eq-1', 'reference-1', 'ref-0', 'sref-0', 'ref-1-2', 'ref-anything', 'some-id'])('does not infer a bibliography from a non-reference anchor %s', anchor => { + expect(parseReferences(`1. Content. ^${anchor}`).entries.size).toBe(0); + }); + + it('does not index mere citation destinations or HTML IDs as reference definitions', () => { + const source = 'Links [1](#^ref-1), [[#^sref-1|1]].\n\n1. Unanchored text.'; + expect(parseReferences(source).anchors.size).toBe(0); + }); + + it('aggregates interleaved main and supplementary definitions by anchor namespace', () => { + const source = [ + '## Arbitrary', '1. Main first. ^ref-1', '1. Supplementary first. ^sref-1', + '## Arbitrary', 'Body [1–2].', '', '2. Main second. ^ref-2', + '### Something else', '2. Supplementary second. ^sref-2' + ].join('\n'); + const index = parseReferences(source); + expect(index.sections.map(section => [section.id, [...section.entries.keys()]])).toEqual([['ref', [1, 2]], ['sref', [1, 2]]]); + expect(index.sections.map(section => [...section.duplicates])).toEqual([[], []]); + expect([...index.duplicates]).toEqual([1, 2]); + expect(index.anchors.size).toBe(4); + expect(index.anchors.get('^sref-2')?.markdown).toBe('Supplementary second.'); + expect(index.referenceRanges.every(range => !source.slice(range.from, range.to).includes('Body [1–2]'))).toBe(true); }); - it('recognizes setext and plain bibliography headings', () => { - expect(parseReferences('References\n----------\n\n[1] First.').entries.get(1)?.markdown).toBe('First.'); - expect(parseReferences('参考文献:\n1) First.').entries.get(1)?.markdown).toBe('First.'); + it('keeps duplicate number and duplicate anchor ambiguity within the correct namespace', () => { + const source = '1. First. ^ref1\n1. Another first. ^ref-1\n2. Second. ^ref-2\n1. Supplementary. ^sref-1'; + const index = parseReferences(source); + expect(index.sections[0].entries.has(1)).toBe(false); + expect(index.sections[0].duplicates.has(1)).toBe(true); + expect(index.sections[1].entries.get(1)?.markdown).toBe('Supplementary.'); + expect(index.anchors.get('^ref1')?.markdown).toBe('First.'); + expect(index.anchors.get('^ref-1')?.markdown).toBe('Another first.'); + expect(index.referenceRanges).toHaveLength(4); + }); + + it('never chooses an arbitrary entry when its actual anchor is repeated', () => { + const index = parseReferences('1. First. ^ref-1\n2. Second. ^ref-2\n1. Conflicting. ^ref-1\n1. Also conflicting. ^ref-1'); + expect(index.anchors.has('^ref-1')).toBe(false); + expect([...index.duplicateAnchors]).toEqual(['^ref-1']); + expect(index.anchors.get('^ref-2')?.markdown).toBe('Second.'); + expect(index.referenceRanges).toHaveLength(4); + }); + + it('does not create a new namespace when headings or entry positions change', () => { + const original = parseReferences('1. Main. ^ref-1\n1. Supplementary. ^sref-1'); + const reordered = parseReferences('## Random\n1. Supplementary. ^sref-1\n## Another\n1. Main. ^ref-1'); + expect(reordered.anchors.get('^ref-1')?.sectionId).toBe(original.anchors.get('^ref-1')?.sectionId); + expect(reordered.anchors.get('^sref-1')?.sectionId).toBe(original.anchors.get('^sref-1')?.sectionId); + }); + + it.each(['\n', '\n\n'])('supports a standalone block ID separated by %j', gap => { + const source = `1. First reference.\n Journal, 2024.${gap}^ref-1\n\nSecond reference.\n^ref-2`; + const index = parseReferences(source); + expect(index.entries.get(1)?.markdown).toBe('First reference.\nJournal, 2024.'); + expect(index.entries.get(2)?.markdown).toBe('Second reference.'); + expect(source.slice(index.referenceRanges[0].from, index.referenceRanges[0].to)).toBe(`1. First reference.\n Journal, 2024.${gap}^ref-1`); }); - it.each(['[1]', '[1]', '【1】', '(1)', '(1)', '1.', '1)', '1、', '1.'])('recognizes entry numbering %s', marker => { - expect(parseReferences(`## References\n${marker} First reference.`).entries.get(1)?.markdown).toBe('First reference.'); + it('handles compact lists and loose lists without joining neighboring references', () => { + const source = '1. First. ^ref-1\n2. Second. ^ref-2\n\n3. Third.\n Continuation. ^ref-3'; + expect([...parseReferences(source).entries.values()].map(entry => entry.markdown)).toEqual(['First.', 'Second.', 'Third.\nContinuation.']); }); - it('supports number headings and title headings', () => { - const index = parseReferences('## References\n### 1\nFirst paper.\n\n### [2] Second paper\nPublished in Journal.\n\n## Appendix\nAnother section.'); - expect(index.entries.get(1)).toMatchObject({ markdown: 'First paper.', anchor: '1' }); - expect(index.entries.get(2)).toMatchObject({ markdown: 'Second paper\nPublished in Journal.', anchor: '[2] Second paper' }); + it('ends each entry exactly at its anchor and never swallows following explanations or metadata', () => { + const source = '1. First. ^ref-1\nPublisher disclaimer.\n\n---\n[Zotero item](zotero://select/library/items/TEST)'; + const index = parseReferences(source); + expect(index.entries.get(1)?.markdown).toBe('First.'); + expect(source.slice(index.referenceRanges[0].from, index.referenceRanges[0].to)).toBe('1. First. ^ref-1'); + }); + + it('does not attach an empty standalone anchor to another anchored block', () => { + expect(parseReferences('^ref-1').entries.size).toBe(0); + const index = parseReferences('Figure caption. ^fig-1\n\n^ref-1\n\n1. Actual. ^ref-2'); + expect([...index.entries.keys()]).toEqual([2]); }); - it('assigns separate leading HTML anchors to the following reference', () => { - const source = '## References\n\n[1] First.\n\n[2] Second.\n[3] Third.'; + it('accepts four-space and tab-indented list continuations while excluding genuine indented code', () => { + const source = '1. First reference.\n Journal. ^ref-1\n\n2. Second reference.\n\tJournal. ^ref-2\n\n 3. Code pretending to be a reference. ^ref-3'; const index = parseReferences(source); - expect(index.entries.get(1)).toMatchObject({ markdown: 'First.', anchor: 'ref-1' }); - expect(index.entries.get(2)).toMatchObject({ markdown: 'Second.', anchor: 'ref-2' }); - expect(index.entries.get(3)).toMatchObject({ markdown: 'Third.', anchor: undefined }); - expect(source.slice(index.entries.get(2)!.from, index.entries.get(2)!.to)).toBe('\n[2] Second.'); + expect([...index.entries.keys()]).toEqual([1, 2]); + expect(index.entries.get(1)?.markdown).toBe('First reference.\nJournal.'); + expect(index.entries.get(2)?.markdown).toBe('Second reference.\nJournal.'); }); - it('recognizes inline HTML anchors while preserving real hyperlinks', () => { - const index = parseReferences('## References\n [1] First. [DOI](https://doi.org/10/example).\n[2] Second. ^ref-2'); - expect(index.entries.get(1)).toMatchObject({ markdown: 'First. [DOI](https://doi.org/10/example).', anchor: 'ref-1' }); - expect(index.entries.get(2)?.markdown).toBe('Second.'); + it('supports an indented continuation paragraph of a reference list item', () => { + const source = '1. First reference.\n\n Continuation.\n ^ref-1\n\n2. Second. ^ref-2'; + expect(parseReferences(source).entries.get(1)?.markdown).toBe('First reference.\n\nContinuation.'); }); - it('marks repeated numbers as ambiguous rather than selecting one', () => { - const index = parseReferences('## References\n[1] First.\n[1] Duplicate.\n[2] Second.\n[1] Another duplicate.'); - expect([...index.duplicates]).toEqual([1]); - expect(index.entries.has(1)).toBe(false); - expect(index.entries.get(2)?.markdown).toBe('Second.'); + it('does not accept code nested inside a list or a block ID following a code block', () => { + const source = '1. Body list item.\n\n Code. ^ref-1\n\n2. Another body item.\n ~~~md\n Code. ^ref-2\n ~~~\n\n Indented code.\n\n^ref-3\n\n4. Actual. ^ref-4'; + expect([...parseReferences(source).entries.keys()]).toEqual([4]); }); - it('does not invent a bibliography from numbered body paragraphs', () => { - expect(parseReferences('1. Introduction.\n2. Methods.\nA result [1–2].').entries.size).toBe(0); + it('does not let literal fences in indented code hide subsequent real references', () => { + const source = ' ```\n An indented code block.\n\n1. Valid first. ^ref-1\n2. Valid second. ^ref-2'; + expect([...parseReferences(source).entries.keys()]).toEqual([1, 2]); }); - it('ignores bibliography-looking source in YAML, code and comments', () => { - const source = '---\nvalue: |\n ## References\n [1] Frontmatter.\n---\n```md\n## References\n[1] Code.\n```\n\n%%\n## References\n[1] Obsidian comment.\n%%\n## References\n[2] Actual.'; + it('keeps indented literal fence pairs separate from real references between their code blocks', () => { + const source = ' ```\n First code block.\n\n1. First. ^ref-1\n\n ```\n Another code block.\n\n2. Second. ^ref-2'; + expect([...parseReferences(source).entries.keys()]).toEqual([1, 2]); + }); + + it('excludes list-fenced payloads with three-space indentation and resumes after the closing fence', () => { + const source = '1. Body list item.\n ~~~md\n 1. False. ^ref-1\n ~~~\n\n2. Actual. ^ref-2'; expect([...parseReferences(source).entries.keys()]).toEqual([2]); }); - it('ends an unterminated code fence at EOF', () => { - expect(parseReferences('```md\n## References\n[1] Code.').entries.size).toBe(0); + it('does not swallow headings or previous labeled blocks when locating unnumbered references', () => { + const source = 'Body text.\n## Anything\nA reference. ^ref-1\nA figure. ^fig-1\nAnother reference. ^ref-2'; + expect([...parseReferences(source).entries.values()].map(entry => entry.markdown)).toEqual(['A reference.', 'Another reference.']); + }); + + it('preserves Markdown links, inline code, and inline math in genuine reference text', () => { + const source = '1. [Title](https://example.org). `A code name` and $E=mc^2$. ^ref-1'; + expect(parseReferences(source).entries.get(1)?.markdown).toBe('[Title](https://example.org). `A code name` and $E=mc^2$.'); }); - it('ignores bibliography headings inside raw code and script containers', () => { - const source = '
\n## References\n[1] Code.\n
\n\n## References\n[3] Actual.'; - expect([...parseReferences(source).entries.keys()]).toEqual([3]); + it('ignores apparent reference anchors in YAML, fenced code, comments, raw code, and math', () => { + const source = '---\nvalue: False. ^ref-1\n---\n```md\nFalse. ^ref-2\n```\n\n%%\nFalse. ^ref-4\n%%\n
\nFalse. ^ref-5\n
\n\n$$\nFalse. ^ref-7\n$$\n8. Actual. ^ref-8'; + expect([...parseReferences(source).entries.keys()]).toEqual([8]); }); - it('detects duplicate IDs across multiple bibliography sections', () => { - const index = parseReferences('## References\n[1] First.\n## Body\ntext\n## Bibliography\n[1] Conflicting first.\n[2] Second.'); - expect(index.sections).toHaveLength(2); - expect(index.duplicates.has(1)).toBe(true); + it('ignores reference definitions inside an unterminated code fence', () => { + expect(parseReferences('```md\n1. Code. ^ref-1').entries.size).toBe(0); }); }); diff --git a/tests/citations.test.ts b/tests/citations.test.ts index 2ad4627..96df423 100644 --- a/tests/citations.test.ts +++ b/tests/citations.test.ts @@ -103,8 +103,8 @@ describe('findCitationGroups', () => { }); it('keeps separate local references instead of combining their bibliography indices', () => { - const first = '[1–3]\n\n## References\n[1] A.\n[2] B.\n[3] C.'; - const second = '[1–3]\n\n## References\n[1] X.\n[2] Y.\n[3] Z.'; + const first = '[1–3]\n\n[1] A. ^ref-1\n[2] B. ^ref-2\n[3] C. ^ref-3'; + const second = '[1–3]\n\n[1] X. ^ref-1\n[2] Y. ^ref-2\n[3] Z. ^ref-3'; const a = parseReferences(first); const b = parseReferences(second); expect(findCitationGroups(first, a, options)[0].numbers).toEqual([1, 2, 3]); @@ -114,12 +114,12 @@ describe('findCitationGroups', () => { }); it('keeps missing intermediate entries so the UI can report them', () => { - const source = '[1–10]\n\n## References\n[1] First.\n[10] Tenth.'; + const source = '[1–10]\n\n[1] First. ^ref-1\n[10] Tenth. ^ref-10'; expect(findCitationGroups(source, parseReferences(source), options)[0].numbers).toHaveLength(10); }); it('keeps ambiguous entries so the UI can report them', () => { - const source = '[1–2]\n\n## References\n[1] A.\n[1] Ambiguous.\n[2] B.'; + const source = '[1–2]\n\n[1] A. ^ref-1\n[1] Ambiguous. ^ref-1\n[2] B. ^ref-2'; const index = parseReferences(source); expect(index.duplicates.has(1)).toBe(true); expect(findCitationGroups(source, index, options)[0].numbers).toEqual([1, 2]); diff --git a/tests/main.test.ts b/tests/main.test.ts index 7d83e68..7915110 100644 --- a/tests/main.test.ts +++ b/tests/main.test.ts @@ -30,6 +30,9 @@ interface HoverLink { const bibliography = '## References\n[1] Original first. ^ref-1\n[2] Second reference. ^ref-2\n[3] Third reference. ^ref-3'; const source = `First [1, 3].\n\nSecond [2–3].\n\n${bibliography}`; +const multipleBibliographies = String.raw`Main \[[1](<#^ref-1>)–[2](<#^ref-2>)\], supplementary \[[1](<#^sref-1>)–[2](<#^sref-2>)\].` + + '\n\n## 6 参考文献(2条)\n1. Main first. ^ref-1\n2. Main second. ^ref-2' + + '\n\n## 7 Supplement\n### 7.7 补充参考文献(2条)\n1. Supplement first. ^sref-1\n2. Supplement second. ^sref-2'; const manifest: PluginManifest = { id: 'citation-range-preview', name: 'Citation Preview', version: '1.1.0', minAppVersion: '1.8.0', description: 'Test manifest.', author: 'Test', isDesktopOnly: false @@ -109,6 +112,24 @@ function mouseover(target: HTMLElement, options?: MouseEventInit): MouseEvent { return event; } +function independentlyNumberedCitations(): HTMLElement { + const paragraph = document.createElement('p'); + for (const [label, prefix] of [['Main', 'ref'], ['supplementary', 'sref']]) { + paragraph.append(`${label} `); + const sup = paragraph.appendChild(document.createElement('sup')); + sup.append('['); + for (const number of [1, 2]) { + if (number > 1) sup.append('–'); + const link = sup.appendChild(document.createElement('a')); + link.setAttribute('href', `#^${prefix}-${number}`); + link.textContent = String(number); + } + sup.append(']'); + paragraph.append(' '); + } + return paragraph; +} + beforeEach(() => installTestDomMethods(document)); afterEach(() => { for (const plugin of plugins.splice(0)) plugin.unload(); @@ -149,6 +170,109 @@ describe('native Page preview host integration', () => { expect((await render()).textContent).toContain('Saved replacement.'); }); + it('keeps equal visible citation ranges in separate bibliography scopes and preview caches', async () => { + const { plugin, process, render, trigger, file } = await setup(multipleBibliographies); + const paragraph = await process(independentlyNumberedCitations()); + const targets = Array.from(paragraph.querySelectorAll('.crp-citation')); + expect(targets.map(target => target.textContent)).toEqual(['[1–2]', '[1–2]']); + + for (const index of [0, 1, 0, 1]) { + mouseover(targets[index]); + const prefix = index === 0 ? 'Main' : 'Supplement'; + expect(Array.from((await render()).querySelectorAll('li'), item => [item.value, item.textContent])).toEqual([ + [1, `${prefix} first.`], [2, `${prefix} second.`] + ]); + expect(trigger.mock.lastCall?.[1].linktext).toBe(index === 0 ? '#^ref-1' : '#^sref-1'); + } + expect(plugin.parse(multipleBibliographies, file.path).previewGroups.size).toBe(2); + }); + + it('refreshes independently numbered bibliographies without rebinding equal labels to another scope', async () => { + const { process, render, metadataEvents, file } = await setup(multipleBibliographies); + const paragraph = await process(independentlyNumberedCitations()); + const targets = Array.from(paragraph.querySelectorAll('.crp-citation')); + expect(targets).toHaveLength(2); + for (const target of targets) mouseover(target); + + const revised = multipleBibliographies.replace('Main first.', 'Revised main first entry.') + .replace('Supplement first.', 'Revised supplementary first entry.'); + metadataEvents.emit('changed', file, revised); + expect(Array.from(paragraph.querySelectorAll('.crp-citation'))).toEqual(targets); + for (const index of [1, 0]) { + mouseover(targets[index]); + const entries = Array.from((await render()).querySelectorAll('li'), item => item.textContent); + expect(entries).toEqual(index === 0 + ? ['Revised main first entry.', 'Main second.'] + : ['Revised supplementary first entry.', 'Supplement second.']); + } + }); + + it('keeps reading targets valid when reference namespaces move and change order across arbitrary headings', async () => { + const { process, render, trigger, metadataEvents, file } = await setup(multipleBibliographies); + const paragraph = await process(independentlyNumberedCitations()); + const targets = Array.from(paragraph.querySelectorAll('.crp-citation')); + expect(targets).toHaveLength(2); + const revised = multipleBibliographies.split('\n')[0] + + '\n\n## Any title\n2. Supplement second. ^sref-2' + + '\n\n1. Main first moved. ^ref-1' + + '\n\n### Another title\n1. Supplement first moved. ^sref-1' + + '\n\n2. Main second. ^ref-2'; + metadataEvents.emit('changed', file, revised); + expect(Array.from(paragraph.querySelectorAll('.crp-citation'))).toEqual(targets); + + for (const index of [0, 1]) { + trigger.mockClear(); + mouseover(targets[index]); + expect(trigger).toHaveBeenCalledOnce(); + expect(Array.from((await render()).querySelectorAll('li'), item => item.textContent)).toEqual(index === 0 + ? ['Main first moved.', 'Main second.'] + : ['Supplement first moved.', 'Supplement second.']); + } + }); + + it.each(['removed', 'renamed'])('disables a stale reading target after its anchors are %s without borrowing another namespace', async change => { + const { process, render, trigger, metadataEvents, file } = await setup(multipleBibliographies); + const paragraph = await process(independentlyNumberedCitations()); + const targets = Array.from(paragraph.querySelectorAll('.crp-citation')); + expect(targets).toHaveLength(2); + const revised = change === 'renamed' ? multipleBibliographies.replace(/\^ref-/g, '^ref-renamed-') + : multipleBibliographies.replace('1. Main first. ^ref-1', '1. Removed main first.') + .replace('2. Main second. ^ref-2', '2. Removed main second.'); + metadataEvents.emit('changed', file, revised); + + trigger.mockClear(); + mouseover(targets[0]); + expect(trigger).not.toHaveBeenCalled(); + mouseover(targets[1]); + expect(trigger).toHaveBeenCalledOnce(); + expect(Array.from((await render()).querySelectorAll('li'), item => item.textContent)).toEqual([ + 'Supplement first.', 'Supplement second.' + ]); + }); + + it('uses the same scoped reference lookup for editor hovers', async () => { + const { plugin, file, render } = await setup(multipleBibliographies); + const model = plugin.parse(multipleBibliographies, file.path); + const target = document.createElement('span'); + expect(model.groups).toHaveLength(2); + for (const index of [1, 0]) { + plugin.hover(new MouseEvent('mouseover', { ctrlKey: true }), target, model, model.groups[index], true); + expect(Array.from((await render()).querySelectorAll('li'), item => item.textContent)).toEqual(index === 0 + ? ['Main first.', 'Main second.'] + : ['Supplement first.', 'Supplement second.']); + } + }); + + it('does not fill a unique intermediate reference from an ambiguous plain-text bibliography scope', async () => { + const note = 'Ambiguous [1–3].\n\n1. Main first. ^ref-1\n2. Main second. ^ref-2\n3. Main third. ^ref-3' + + '\n\n## Any title\n1. Supplement first. ^sref-1\n3. Supplement third. ^sref-3'; + const { processPlain, render } = await setup(note); + mouseover(anchor(await processPlain())); + expect(Array.from((await render()).querySelectorAll('li'), item => [item.value, item.textContent])).toEqual([ + [1, 'Ambiguous bibliography'], [2, 'Ambiguous bibliography'], [3, 'Ambiguous bibliography'] + ]); + }); + it('honors the reading-view modifier and the current core-plugin state', async () => { const { plugin, corePlugin, processPlain, trigger } = await setup(); const target = anchor(await processPlain()); diff --git a/tests/model.test.ts b/tests/model.test.ts index 6f63063..5eeccdc 100644 --- a/tests/model.test.ts +++ b/tests/model.test.ts @@ -94,9 +94,9 @@ describe('citation line filtering', () => { '', '## References', '', - '1. Fictional one.', - '2. Fictional two.', - '3. Fictional three.' + '1. Fictional one. ^ref-1', + '2. Fictional two. ^ref-2', + '3. Fictional three. ^ref-3' ].join('\n'); const model = new CitationDocument(source, 'Paper.md', DEFAULT_SETTINGS); expect(model.inLines(0, 1).map(group => group.numbers)).toEqual([[1, 2, 3], [2, 3]]); diff --git a/tests/reading.test.ts b/tests/reading.test.ts index b58003b..6387f9c 100644 --- a/tests/reading.test.ts +++ b/tests/reading.test.ts @@ -95,6 +95,42 @@ describe('reading view citation decoration', () => { expect(triggers[0].element.querySelector('a')?.getAttribute('data-href')).toBe('Notes/Paper.md#^ref-1'); }); + it('aligns reference targets rather than consuming equal-numbered figure links', () => { + const root = fixture('

Figures [1–10], references [1–10].

'); + const citation = { ...group('[1–10]', true), scopeId: 'main', linkTargets: ['^ref-1', '^ref-10'] }; + const triggers = decorateReadingCitations(root, [citation]); + expect(triggers).toHaveLength(1); + expect(triggers[0].element.querySelector('a')?.getAttribute('href')).toBe('#^ref-1'); + expect(root.querySelector('a[href="#^fig-1"]')?.closest('.crp-citation')).toBeNull(); + }); + + it('uses exact linked targets to distinguish equal visible numbers from different bibliographies', () => { + const root = fixture('

[1–10] then [1–10].

'); + const main = { ...group('[1–10]', true, 0), scopeId: 'main', linkTargets: ['^ref-1', '^ref-10'] }; + const supplement = { ...group('[1–10]', true, 50), scopeId: 'supplement', linkTargets: ['^sref-1', '^sref-10'] }; + const triggers = decorateReadingCitations(root, [main, supplement]); + expect(triggers.map(trigger => trigger.group.scopeId)).toEqual(['supplement', 'main']); + expect(triggers.map(trigger => trigger.element.querySelector('a')?.getAttribute('href'))).toEqual(['#^sref-1', '#^ref-1']); + }); + + it('resolves relative same-note paths and encoded anchors using the source parser rules', () => { + const root = fixture('

[1–10].

'); + const citation = { ...group('[1–10]', true), linkTargets: ['^ref-1', '^ref-10'] }; + const triggers = decorateReadingCitations(root, [citation], { sourcePath: 'Notes/Paper one.md' }); + expect(triggers).toHaveLength(1); + expect(triggers[0].element.textContent).toBe('[1–10]'); + }); + + it('requires the complete ordered target sequence while preserving repeated endpoint links', () => { + const root = fixture('

[1–10] then [1–10, 1].

'); + const range = { ...group('[1–10]', true), linkTargets: ['^ref-1', '^ref-10'] }; + const repeated = { ...group('[1–10, 1]', true, 30), linkTargets: ['^ref-1', '^ref-10', '^ref-1'] }; + const triggers = decorateReadingCitations(root, [range, repeated]); + expect(triggers).toHaveLength(1); + expect(triggers[0].group).toBe(repeated); + expect(triggers[0].element.querySelectorAll('a')).toHaveLength(3); + }); + it('supports endpoint links without outer brackets but does not decorate bare numbers', () => { const root = fixture('

Temperature 1–10 then 1–10.

'); const triggers = decorateReadingCitations(root, [group('[1–10]', true)]); diff --git a/tests/scopes.test.ts b/tests/scopes.test.ts new file mode 100644 index 0000000..fdddf90 --- /dev/null +++ b/tests/scopes.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest'; +import { CitationDocument } from '../src/model'; +import { DEFAULT_SETTINGS, type CitationGroup } from '../src/types'; + +const references = [ + '1. Main first. ^ref-1', + '2. Main second. ^ref-2', + '3. Main third. ^ref-3', + '', + '1. Supplement first. ^sref-1', + '2. Supplement second. ^sref-2', + '3. Supplement third. ^sref-3' +].join('\n'); + +function parse(body: string, entries = references): CitationDocument { + return new CitationDocument(`${body}\n\n${entries}`, 'Papers/Article.md', DEFAULT_SETTINGS); +} + +function texts(model: CitationDocument, group: CitationGroup): Array { + const scope = model.references.sections.find(section => section.id === group.scopeId); + return group.numbers.map(number => scope?.entries.get(number)?.markdown); +} + +describe('anchor namespaces without bibliography headings', () => { + it('resolves identical main and supplementary labels to different references', () => { + const model = parse(String.raw`Main \[[1](<#^ref-1>)–[3](<#^ref-3>)\]; supplement \[[1](<#^sref-1>)–[3](<#^sref-3>)\].`); + expect(model.groups.map(group => group.scopeId)).toEqual(['ref', 'sref']); + expect(model.groups.map(group => group.label)).toEqual(['[1–3]', '[1–3]']); + expect(texts(model, model.groups[0])).toEqual(['Main first.', 'Main second.', 'Main third.']); + expect(texts(model, model.groups[1])).toEqual(['Supplement first.', 'Supplement second.', 'Supplement third.']); + expect(model.references.anchors.size).toBe(6); + }); + + it('finds entries split across arbitrary headings and preserves intervening body citations', () => { + const source = String.raw`First \[[1](#^ref-1)–[3](#^ref-3)\].` + + '\n\n1. Main first. ^ref-1\n\n## An unrelated heading\n\nSecond [1–3].' + + '\n\n2. Main second. ^ref-2\n\n## Another heading\n\n3. Main third. ^ref-3'; + const model = new CitationDocument(source, 'Article.md', DEFAULT_SETTINGS); + expect(model.references.sections).toHaveLength(1); + expect(model.references.sections[0].id).toBe('ref'); + expect(model.groups).toHaveLength(2); + expect(model.groups.map(group => texts(model, group))).toEqual([ + ['Main first.', 'Main second.', 'Main third.'], + ['Main first.', 'Main second.', 'Main third.'] + ]); + }); + + it('supports supplementary wiki links and a linked range label', () => { + const model = parse(String.raw`\[[[#^sref-1|1]], [[#^sref-3|3]]\] and [1–3](<#^sref-1>).`); + expect(model.groups.map(group => group.scopeId)).toEqual(['sref', 'sref']); + expect(model.groups.map(group => group.linkTargets)).toEqual([['^sref-1', '^sref-3'], ['^sref-1']]); + expect(model.groups.map(group => group.numbers)).toEqual([[1, 3], [1, 2, 3]]); + }); + + it('keeps a missing intermediate item in its own namespace', () => { + const entries = references.replace('2. Supplement second. ^sref-2\n', ''); + const model = parse(String.raw`\[[1](#^sref-1)–[3](#^sref-3)\]`, entries); + expect(texts(model, model.groups[0])).toEqual(['Supplement first.', undefined, 'Supplement third.']); + }); + + it('does not silently merge explicitly linked namespaces', () => { + for (const separator of ['–', ',']) { + const model = parse(String.raw`\[[1](#^ref-1)${separator}[3](#^sref-3)\]`); + expect(model.groups).toEqual([]); + } + }); + + it('requires real targets and matching citation numbers', () => { + for (const body of [ + String.raw`\[[1](#^sref-2),[3](#^sref-3)\]`, + String.raw`\[[1](#^ref1),[3](#^ref-3)\]`, + String.raw`\[[1](#^fig-1),[3](#^fig-3)\]`, + String.raw`\[[1](Other.md#^sref-1),[3](#^sref-3)\]` + ]) expect(parse(body).groups).toEqual([]); + }); + + it('marks plain citations ambiguous when multiple namespaces contain their endpoints', () => { + const model = parse('An unlinked interval [1–3].'); + expect(model.groups).toHaveLength(1); + expect(model.groups[0].ambiguousScope).toBe(true); + expect(model.groups[0].scopeId).toBeUndefined(); + }); + + it('selects a plain citation namespace only with unique number evidence', () => { + const model = parse('Unlinked [1, 4].', references + '\n\n4. Main fourth. ^ref-4'); + expect(model.groups[0].scopeId).toBe('ref'); + expect(texts(model, model.groups[0])).toEqual(['Main first.', 'Main fourth.']); + }); + + it('does not create references from a heading or unanchored numbered prose', () => { + const model = parse('Evidence [1–3].', '## References\n1. Ordinary step.\n2. Another step.\n3. Last step.'); + expect(model.references.anchors.size).toBe(0); + expect(model.groups).toEqual([]); + }); + + it('expands the supplied supplement structure without depending on entry order', () => { + const entries = [ + ...Array.from({ length: 66 }, (_, i) => `${i + 1}. Main ${i + 1}. ^ref-${i + 1}`), + ...Array.from({ length: 30 }, (_, i) => `${i + 1}. Supplement ${i + 1}. ^sref-${i + 1}`) + ].reverse().join('\n'); + const model = parse(String.raw`\[[8](<#^sref-8>),[10](<#^sref-10>),[26](<#^sref-26>)-[28](<#^sref-28>)\]`, entries); + expect(model.references.anchors.size).toBe(96); + expect(model.groups[0].numbers).toEqual([8, 10, 26, 27, 28]); + expect(texts(model, model.groups[0])).toEqual(['Supplement 8.', 'Supplement 10.', 'Supplement 26.', 'Supplement 27.', 'Supplement 28.']); + }); +}); diff --git a/versions.json b/versions.json index 4ee930d..6f4e46c 100644 --- a/versions.json +++ b/versions.json @@ -1,5 +1,6 @@ { "1.0.0": "1.15.1", "1.0.1": "1.15.1", - "1.1.1": "1.15.1" + "1.1.1": "1.15.1", + "1.2.0": "1.15.1" }