From 9b55874cf40c86655b63b01f316560ca967e3db6 Mon Sep 17 00:00:00 2001 From: Chuangwu Deng Date: Sun, 22 Nov 2026 00:39:24 -0800 Subject: [PATCH] Release Citation Preview 1.3.0 with citation links and bibliography discovery Add blue citation links, split previews for whole-range links, section-aware nearby reference detection, and a manually invoked command for missing anchors. Preserve exact ref/sref targets and native editor behavior. --- .github/workflows/release.yml | 4 +- CHANGELOG.md | 9 ++ README.md | 77 ++++++++-- manifest.json | 4 +- package-lock.json | 4 +- package.json | 4 +- src/anchors.ts | 85 +++++++++++ src/bibliography.ts | 2 +- src/citation-state.ts | 8 ++ src/citations.ts | 74 +++++++--- src/editor.ts | 49 ++++++- src/main.ts | 119 +++++++++++++--- src/model.ts | 22 ++- src/popover.ts | 43 ++++-- src/reading.ts | 168 +++++++++++++++++++--- src/reference-lists.ts | 259 ++++++++++++++++++++++++++++++++++ src/settings.ts | 31 +++- src/types.ts | 40 +++++- styles.css | 52 ++++++- tests/anchors.test.ts | 66 +++++++++ tests/citations.test.ts | 43 ++++++ tests/editor.test.ts | 88 +++++++++++- tests/main.test.ts | 164 +++++++++++++++++++-- tests/popover.test.ts | 19 +++ tests/reading.test.ts | 183 ++++++++++++++++++++++++ tests/reference-lists.test.ts | 132 +++++++++++++++++ tests/scopes.test.ts | 16 +-- tests/settings.test.ts | 16 +++ versions.json | 3 +- 29 files changed, 1649 insertions(+), 135 deletions(-) create mode 100644 src/anchors.ts create mode 100644 src/citation-state.ts create mode 100644 src/reference-lists.ts create mode 100644 tests/anchors.test.ts create mode 100644 tests/reference-lists.test.ts create mode 100644 tests/settings.test.ts diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bda68db..1eb6f9b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -84,9 +84,9 @@ jobs: const text = [ `# Citation Preview ${tag}`, '', - '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.', + 'Display numeric citations such as [1-10] or [3,1-10,12] as blue links and hover to view their references together in Obsidian Page preview. Citation groups are assembled in memory from references in the same note.', '', - '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.', + 'Explicit links resolve by their unique ^ref-N and ^sref-N block IDs without requiring a bibliography heading. With plain numeric recognition enabled, citations can also use detected numbered reference lists, preferring the same structural section and then the nearest list, including entries without anchors. The optional Add missing reference anchors command writes block IDs only when manually invoked. See README.md for supported formats, list detection, and navigation behavior.', '', '## Changes', '', diff --git a/CHANGELOG.md b/CHANGELOG.md index e8fc817..b77cabb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.3.0 + +- Display resolved citations as blue links, including their outer brackets and separators, with an option to use the current theme's link color. Keep existing links and native single-reference previews; add navigation for resolved plain-text citation numbers without rewriting the note. +- Keep editor syntax and link destinations in their normal colors. Ordinary editor clicks still place the cursor; modified clicks navigate to the corresponding reference. +- Show an explicitly linked citation group such as `[1-5](#^ref-1)` in one preview with the specified reference first, a horizontal rule, and the full expanded group below. Preserve the existing link's click target. +- Recognize nearby numbered reference lists for plain numeric citations, including lists without block anchors. Prefer the same structural section, then the nearest detected list; report missing entries there instead of borrowing from another list. Exact `ref` and `sref` links continue to use their actual anchors independently of bibliography headings. +- Add the manually invoked **Add missing reference anchors** command. It adds missing block IDs to recognized reference entries in the current note, keeps existing IDs, avoids collisions, and applies edits as one undoable editor transaction. Normal previewing and navigation do not write to the note. +- Add regression coverage for list selection, anchor insertion, visible citation ranges, link preservation, grouped previews, and editor interactions. Keep the plugin ID `citation-range-preview` and minimum Obsidian version `1.15.1`. + ## 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. diff --git a/README.md b/README.md index 7f9ca81..8554f70 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Citation Preview -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. +Display numeric citations in Obsidian as blue links and preview their references together. Hover over a citation such as `[1, 3, 5]` or `[1–10]` to see its references in one Page preview popover. Explicit links resolve through the actual reference block IDs; plain numeric citations can use the nearest detected bibliography in the same Markdown note. ## Why Citation Preview? @@ -8,7 +8,7 @@ An Obsidian link points to a single target. To preview a group such as `[1-10]` Existing plugins address different workflows. ZotLit draws on a Zotero library, and Citation Suite resolves Pandoc citation keys using Zotero or a separate `.bib` or CSL JSON file. Inline Annotations displays notes attached to selected text. This leaves a gap for readers who want to preview a numeric citation group from the bibliography already in the current Markdown note. [ZotLit](https://github.com/aidenlx/zotlit) · [Citation Suite](https://github.com/pan4ratte/obsidian-citation-suite) · [Inline Annotations](https://github.com/cetrodk/obsidian-inline-annotations) -Citation Preview was built for that workflow. It assembles the cited entries in memory and displays them through Obsidian's native Page preview, so each reference is maintained once in the bibliography. In AI-assisted note writing, the assistant can preserve the original citations and put the numbered references in the same note. Previewing them runs locally, without an AI service, network lookup, helper files, or edits to the note. +Citation Preview was built for that workflow. It assembles the cited entries in memory and displays them through Obsidian's native Page preview, so each reference is maintained once in the bibliography. In AI-assisted note writing, the assistant can preserve the original citations and put the numbered references in the same note. Previewing and navigation run locally, without an AI service, network lookup, helper files, or edits to the note. A separate, manually invoked command can add missing reference anchors when you want persistent block links. ## Quick start @@ -29,7 +29,8 @@ Citation Preview was built for that workflow. It assembles the cited entries in [3] Example reference three. ^ref-3 ``` -3. In Reading view, hover over `[3, 1–3]`. With the default settings, the popover shows references 3, 1, and 2. In Live Preview or Source mode, hold **Ctrl** (Windows/Linux) or **Command** (macOS) while hovering, as for Obsidian's standard editor link previews. [Obsidian Page preview help](https://obsidian.md/help/plugins/page-preview) +3. In Reading view, resolved citations appear blue. Hover over `[3, 1–3]`: the popover shows references 3, 1, and 2. Click a visible citation number to go to its entry. +4. In Live Preview or Source mode, hold **Ctrl** (Windows/Linux) or **Command** (macOS) while hovering, as for Obsidian's standard editor link previews. Use the same modifier while clicking a generated citation link to navigate; ordinary clicks continue to place the editing cursor. [Obsidian Page preview help](https://obsidian.md/help/plugins/page-preview) See the [demonstration note](examples/Citation-demo.md) for more examples. @@ -39,13 +40,11 @@ See the [demonstration note](examples/Citation-demo.md) for more examples. - 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. +- Plain citations such as `[1–3]` use a detected numbered reference list when plain numeric recognition is enabled. Lists sharing a closer structural section with the citation take priority, followed by source proximity. Explicit links provide a stable choice of reference set when main and supplementary bibliographies reuse the same numbers. 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: +Explicit links use the actual anchors as their source of reference identity: | Reference block | Citation target | Meaning | | --- | --- | --- | @@ -74,25 +73,77 @@ Supplementary result: \[[1](<#^sref-1>)–[3](<#^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. +### Plain citations and nearby reference lists + +With **Recognize plain numeric citations** enabled, the plugin can also identify a numbered bibliography without block IDs. List structure and bibliographic content provide the evidence, such as DOI/ISBN identifiers, document-type markers, or author/year/publication details. A heading alone does not turn an arbitrary numbered list into references. Code, mathematics, frontmatter, and ordinary numbered instructions are excluded from this discovery. + +For example, these fictional entries have no anchors: + +```markdown +The two studies report related results [1-2]. + +## References + +[1] Smith A. Coastal observations [J]. Example Journal, 2024, 12: 10-20. +[2] Chen B. Atmospheric waves [J]. Example Journal, 2025, 13: 21-30. +``` + +The detected list supplies both entries for `[1-2]`. When several lists exist, a list sharing a deeper parent section with the citation takes priority. For example, a citation in a supplementary chapter selects that chapter's bibliography even when the preceding main bibliography is physically closer. Within the same structural context, proximity is measured between the citation and the list in the Markdown source; an equally close list after the citation is preferred. Without heading context, selection falls back to source proximity across the note. This uses heading structure, not a required heading name or language. + +Within a recognized citation group, a missing member is reported instead of retrieving the same number from another list. If no physical list is detected, a unique existing reference-anchor set can still supply a plain citation. An explicit `#^ref-1` or `#^sref-1` link always selects its actual reference set independently of section or proximity rules. + +Entries without anchors can be previewed and reached by their source position. This does not add block IDs or rewrite citations. Plain numeric recognition is heuristic: an interval such as `[1-5]` can be indistinguishable from a citation. Turn off **Recognize plain numeric citations** to restrict handling to explicit reference links. + +### Add missing reference anchors manually + +1. Open the target note in an editor. +2. Open the command palette and run **Citation Preview: Add missing reference anchors**. +3. Check the completion notice. You can undo the insertions in one editing step. + +Assign your own shortcut to this command under **Settings → Hotkeys** if desired. No default shortcut is reserved. + +The command adds block IDs only to entries in recognized reference lists. It preserves existing IDs, uses separate reference prefixes for independent lists, and skips conflicting or ambiguous entries. Running it again does not add another anchor to the same entry. It does not replace inline citations with Markdown links or renumber the bibliography. + +A partially anchored list keeps its existing reference prefix. New lists use `ref` by default or `sref` when a supplementary/appendix heading identifies them; additional independent lists use available prefixes such as `ref-list2`. These naming choices apply only to newly generated IDs. Existing explicit links continue to resolve independently of headings. + +**This command is the only feature that writes to your note.** Opening a note, hovering over citations, navigating to references, changing display settings, and building previews do not add anchors automatically. + +**Upgrading to 1.3.0:** existing `ref` and `sref` links keep their targets. Plain citations gain nearby-list discovery, and resolved citations use the new blue-link display by default. Existing settings are retained; the new display option can be disabled independently of previews. + ## 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 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. +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. + +An overall link such as `[1-5](#^ref-1)` has two meanings: its explicit target is reference 1, while its label names the range 1–5. Citation Preview shows both in **one popover**: the explicitly targeted entry first, a horizontal rule (`---`), and the complete expanded group underneath. Reference 1 therefore appears once above the divider and again as part of the five-entry group below. Clicking the existing overall link still follows its original target. + +### Link display and navigation + +- The complete resolved citation is blue, including the visible outer brackets and separators. The optional theme-color mode uses the current theme's link color, which may not be blue. +- Hovering anywhere in a group opens its combined preview. Clicking a generated visible number navigates to that number's entry; brackets and separators remain group-preview areas. +- For `[1-5]`, the displayed endpoints `1` and `5` can be navigated individually. References 2–4 are included in the group preview; the source text stays `[1-5]`. +- Existing Markdown links and Wikilinks keep their original targets and click behavior. In particular, an existing overall link is not split into nested links. +- References with block IDs use their exact targets. Recognized entries without IDs are reached by line position without writing to the note. +- Editing uses source-range decorations, so destinations such as `#^ref-1` and hidden Markdown syntax are not recolored as citation text. Normal selection and cursor placement remain available. +- Missing, duplicate, or ambiguous targets do not receive newly generated valid navigation links. Changes to reference targets refresh the corresponding display state. | Setting | Default | Effect | | --- | --- | --- | | Maximum references per group | 100 | Skip groups larger than the configured limit. | -| Recognize plain numeric citations | On | Preview bracketed numbers without links. Turn this off if ordinary numeric intervals are mistaken for citations. | +| Recognize plain numeric citations | On | Resolve bracketed numbers using section context and the nearest detected reference list, including unanchored entries. Turn this off if ordinary numeric intervals are mistaken for citations. | +| Show citations as links | On | Color resolved citations and add navigation for visible plain-text numbers. Turning this off keeps previews and existing Markdown links. | +| Citation color | Blue | Choose blue colors for light/dark themes or follow the current theme's link color. | | Require modifier key | Off | Require Ctrl or Command while hovering in Reading view. | -| Enable editor previews | On | Preview in Live Preview and Source mode with the standard editor modifier. | +| Enable editor previews and links | On | Show previews and link decorations in Live Preview and Source mode, using the standard editor modifier for navigation. | ## 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 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. +- **Obsidian's built-in Page preview must be enabled for previews.** 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 remains **Obsidian 1.15.1**. +- The plugin uses numeric Markdown citations and reference entries 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. +- Automatic bibliography detection is conservative and may skip unusual formats. For deterministic resolution, give entries supported unique block IDs and link to those exact IDs. Explicit anchor-based resolution never depends on a bibliography heading. - The preview is designed for desktop mouse hover. There is no dedicated touch gesture. +- Automated checks cover parsing, DOM behavior, plugin lifecycle boundaries, and real CodeMirror editing state. They do not replace visual verification in every Obsidian version and theme. ## Install or update diff --git a/manifest.json b/manifest.json index 4d3807b..2b12c29 100644 --- a/manifest.json +++ b/manifest.json @@ -1,9 +1,9 @@ { "id": "citation-range-preview", "name": "Citation Preview", - "version": "1.2.0", + "version": "1.3.0", "minAppVersion": "1.15.1", - "description": "Preview numeric citation groups in Page preview using reference block anchors in the same note.", + "description": "Preview and link numeric citation groups using reference anchors or nearby bibliographies 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 0634e86..ac78aed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "citation-preview", - "version": "1.2.0", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "citation-preview", - "version": "1.2.0", + "version": "1.3.0", "license": "MIT", "devDependencies": { "@codemirror/language": "^6.13.1", diff --git a/package.json b/package.json index eb4d591..713166d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "citation-preview", - "version": "1.2.0", - "description": "Preview numeric citation groups in Page preview using reference block anchors in the same note.", + "version": "1.3.0", + "description": "Preview and link numeric citation groups using reference anchors or nearby bibliographies in the same note.", "main": "main.js", "private": true, "scripts": { diff --git a/src/anchors.ts b/src/anchors.ts new file mode 100644 index 0000000..15b744c --- /dev/null +++ b/src/anchors.ts @@ -0,0 +1,85 @@ +import { ignoredMarkdownRanges, parseReferences, referenceAnchor, sourceLines } from './bibliography'; +import { blockAnchorAtEnd, detectReferenceLists } from './reference-lists'; + +export interface AnchorInsertion { + from: number; + to: number; + insert: string; +} + +export interface AnchorPlan { + /** Sorted insertions, suitable for one undoable editor transaction. */ + changes: AnchorInsertion[]; + added: number; + skipped: number; + lists: number; +} + +/** + * Plan only. No source or files are changed until a user invokes the registered command. + * Existing IDs, including non-reference IDs, are never replaced or duplicated on a block. + */ +export function planReferenceAnchors(source: string): AnchorPlan { + const lines = sourceLines(source); + const ignored = ignoredMarkdownRanges(source, lines, false); + const index = parseReferences(source, lines); + const lists = detectReferenceLists(source, index, lines); + const ids = new Set(); + const namespaces = new Set(); + const usedNumbers = new Map(index.sections.map(section => [section.id, new Set([...section.entries.keys(), ...section.duplicates])])); + let ignoredIndex = 0; + for (const line of lines) { + const anchor = blockAnchorAtEnd(line.text); + if (!anchor) continue; + const offset = line.from + anchor.from; + while (ignoredIndex < ignored.length && ignored[ignoredIndex].to <= offset) ignoredIndex += 1; + if (ignored[ignoredIndex]?.from <= offset) continue; + ids.add(anchor.id); + const identity = referenceAnchor(anchor.id); + if (identity) { + namespaces.add(identity.namespace); + const numbers = usedNumbers.get(identity.namespace) ?? new Set(); + numbers.add(identity.number); + usedNumbers.set(identity.namespace, numbers); + } + } + + const plan: AnchorPlan = { changes: [], added: 0, skipped: 0, lists: lists.length }; + const newNamespace = (supplemental: boolean): string => { + const base = supplemental ? 'sref' : 'ref'; + if (!namespaces.has(base)) { namespaces.add(base); return base; } + for (let suffix = 2; ; suffix += 1) { + const candidate = `${base}-list${suffix}`; + if (namespaces.has(candidate)) continue; + namespaces.add(candidate); + return candidate; + } + }; + + for (const list of lists) { + const existingNamespaces = new Set(list.items.flatMap(entry => { + const identity = entry.anchor ? referenceAnchor(entry.anchor.slice(1)) : undefined; + return identity ? [identity.namespace] : []; + })); + if (existingNamespaces.size > 1) { + plan.skipped += list.items.length; + continue; + } + const namespace = existingNamespaces.values().next().value + ?? newNamespace(list.supplemental); + for (const entry of list.items) { + if (entry.anchor || list.duplicates.has(entry.number)) { plan.skipped += 1; continue; } + const id = `${namespace}-${entry.number}`; + if (ids.has(id) || usedNumbers.get(namespace)?.has(entry.number)) { plan.skipped += 1; continue; } + // Detection ends at the final content character, before CRLF or trailing spaces. + plan.changes.push({ from: entry.to, to: entry.to, insert: ` ^${id}` }); + ids.add(id); + const numbers = usedNumbers.get(namespace) ?? new Set(); + numbers.add(entry.number); + usedNumbers.set(namespace, numbers); + plan.added += 1; + } + } + plan.changes.sort((left, right) => left.from - right.from); + return plan; +} diff --git a/src/bibliography.ts b/src/bibliography.ts index d4394f6..2703469 100644 --- a/src/bibliography.ts +++ b/src/bibliography.ts @@ -129,7 +129,7 @@ export function ignoredMarkdownRanges(source: string, lines = sourceLines(source } /** Only explicit reference block IDs establish a bibliography namespace. */ -function referenceAnchor(id: string): { number: number; namespace: string } | undefined { +export 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; diff --git a/src/citation-state.ts b/src/citation-state.ts new file mode 100644 index 0000000..097176e --- /dev/null +++ b/src/citation-state.ts @@ -0,0 +1,8 @@ +import type { CitationGroup } from './types'; + +/** Expanded preview numbers are deduplicated; native hover applies to one displayed linked token only. */ +export function usesNativeSinglePreview(group: CitationGroup): boolean { + if (!group.linked) return false; + if (group.tokens) return group.tokens.length === 1 && group.tokens[0].linked; + return group.numbers.length === 1; +} diff --git a/src/citations.ts b/src/citations.ts index 9283438..d810761 100644 --- a/src/citations.ts +++ b/src/citations.ts @@ -1,16 +1,19 @@ import { ignoredMarkdownRanges } from './bibliography'; import { localLinkAnchor } from './links'; +import { headingPathAt, nearestReferenceList } from './reference-lists'; import type { CitationGroup, ParseOptions, ReferenceIndex } from './types'; interface NumberToken { number: number; + from: number; + labelTo: number; to: number; linked: boolean; valid: boolean; scopeId?: string; target?: string; } -interface Parts { tokens: NumberToken[]; separators: string[]; to: number } +interface Parts { tokens: NumberToken[]; separators: string[]; separatorRanges: Array<{ from: number; to: number }>; to: number } function positiveInteger(text: string): number | undefined { if (!/^[1-9]\d{0,8}$/.test(text)) return undefined; @@ -18,13 +21,13 @@ function positiveInteger(text: string): number | undefined { return Number.isSafeInteger(value) ? value : undefined; } -function localReferenceLink(target: string, number: number, index: ReferenceIndex, sourcePath?: string): Pick { +function localReferenceLink(target: string, number: number | undefined, index: ReferenceIndex, sourcePath?: string): Pick { 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 }; + if (!entry || (number !== undefined && entry.number !== number)) return { valid: false }; return { valid: true, scopeId: entry.sectionId, target: anchor }; } @@ -63,18 +66,19 @@ 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, ...localReferenceLink(body.slice(0, divider), number, index, options.sourcePath) }; + const labelFrom = from + 2 + divider + 1 + (body.slice(divider + 1).match(/^\s*/)?.[0].length ?? 0); + return { number, from: labelFrom, labelTo: labelFrom + String(number).length, 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, ...localReferenceLink(destination.target, number, index, options.sourcePath) }; + return { number, from: from + 1, labelTo: from + 1 + linkLabel[1].length, 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; - return { number: Number(digits[0]), to: from + digits[0].length, linked: false, valid: true }; + return { number: Number(digits[0]), from, labelTo: from + digits[0].length, to: from + digits[0].length, linked: false, valid: true }; } function skipSpace(source: string, from: number): number { @@ -86,6 +90,7 @@ function skipSpace(source: string, from: number): number { function readParts(source: string, from: number, index: ReferenceIndex, options: ParseOptions): Parts | undefined { const tokens: NumberToken[] = []; const separators: string[] = []; + const separatorRanges: Array<{ from: number; to: number }> = []; let p = skipSpace(source, from); for (let count = 0; count <= options.maxReferences * 2; count += 1) { const token = readToken(source, p, index, options); @@ -93,8 +98,9 @@ function readParts(source: string, from: number, index: ReferenceIndex, options: tokens.push(token); p = skipSpace(source, token.to); const separator = source[p]; - if (!separator || !/[-–—−-,,;;、]/.test(separator)) return { tokens, separators, to: p }; + if (!separator || !/[-–—−-,,;;、]/.test(separator)) return { tokens, separators, separatorRanges, to: p }; separators.push(separator); + separatorRanges.push({ from: p, to: p + 1 }); p = skipSpace(source, p + 1); } return undefined; @@ -124,29 +130,39 @@ function expand(parts: Parts, cap: number): number[] | undefined { return values; } -function groupFromParts(parts: Parts, from: number, to: number, index: ReferenceIndex, options: ParseOptions, outerLink = false): CitationGroup | undefined { +function groupFromParts(parts: Parts, from: number, to: number, index: ReferenceIndex, options: ParseOptions, outerLinkTarget?: string): CitationGroup | undefined { if (parts.tokens.some(token => !token.valid)) return undefined; - const linked = outerLink || parts.tokens.some(token => token.linked); + const linked = outerLinkTarget !== undefined || parts.tokens.some(token => token.linked); if (!linked && !options.recognizePlainText) return undefined; const numbers = expand(parts, options.maxReferences); 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 nearest = !linked && index.lists?.length + ? nearestReferenceList(index.lists, from, to, headingPathAt(index.headingScopes ?? [], from)) : undefined; + if (nearest) { + if (!parts.tokens.some(token => nearest.entries.has(token.number) || nearest.duplicates.has(token.number))) return undefined; + scopeId = nearest.id; + } else { + const endpoints = parts.tokens.filter(token => index.entries.has(token.number) || index.duplicates.has(token.number)); + if (!endpoints.length) return undefined; + 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, scopeId, ambiguousScope, - linkTargets: parts.tokens.flatMap(token => token.target ? [token.target] : []) }; + linkTargets: parts.tokens.flatMap(token => token.target ? [token.target] : []), outerLinkTarget, + tokens: parts.tokens.map(token => ({ number: token.number, from: token.from, to: token.labelTo, + linked: !!outerLinkTarget || token.linked, target: outerLinkTarget ?? token.target })), + visibleRanges: [...parts.tokens.map(token => ({ from: token.from, to: token.labelTo })), ...parts.separatorRanges] + .sort((left, right) => left.from - right.from) }; } function bracketGroup(source: string, from: number, index: ReferenceIndex, options: ParseOptions): CitationGroup | undefined { @@ -155,21 +171,27 @@ function bracketGroup(source: string, from: number, index: ReferenceIndex, optio const parts = readParts(source, from + (escapedOpen ? 2 : 1), index, options); if (!parts) return undefined; let to = parts.to; + const closeFrom = to + (source.startsWith('\\]', to) ? 1 : 0); if (source.startsWith('\\]', to)) to += 2; else if (source[to] === ']') to += 1; else return undefined; if (source[to] === '[') return undefined; // Markdown reference-style links are not numeric citations. - let outerLink = false; + let outerLinkTarget: string | undefined; if (source[to] === '(') { const destination = destinationAt(source, to); if (!destination) return undefined; - const resolution = localReferenceLink(destination.target, parts.tokens[0].number, index, options.sourcePath); + const resolution = localReferenceLink(destination.target, parts.tokens.length > 1 ? undefined : parts.tokens[0].number, index, options.sourcePath); if (!resolution.valid) return undefined; parts.tokens[0] = { ...parts.tokens[0], ...resolution, linked: true }; - outerLink = true; + outerLinkTarget = resolution.target; to = destination.to; } - return groupFromParts(parts, from, to, index, options, outerLink); + const group = groupFromParts(parts, from, to, index, options, outerLinkTarget); + if (group && !outerLinkTarget) { + group.visibleRanges!.unshift({ from: from + (escapedOpen ? 1 : 0), to: from + (escapedOpen ? 2 : 1) }); + group.visibleRanges!.push({ from: closeFrom, to: closeFrom + 1 }); + } + return group; } function unbracketedLinks(source: string, from: number, index: ReferenceIndex, options: ParseOptions): CitationGroup | undefined { @@ -184,10 +206,10 @@ function maskRange(chars: string[], from: number, to: number): void { /** Used in editor mode and reading-mode tests; all offsets refer to the raw source. */ export function findCitationGroups(source: string, index: ReferenceIndex, options: ParseOptions, ignored = ignoredMarkdownRanges(source)): CitationGroup[] { - if ((!index.entries.size && !index.duplicates.size) || !Number.isFinite(options.maxReferences) || options.maxReferences < 1) return []; + if ((!index.entries.size && !index.duplicates.size && !index.lists?.length) || !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.referenceRanges]) maskRange(chars, range.from, range.to); + for (const range of [...ignored, ...index.referenceRanges, ...(index.lists?.flatMap(list => list.items) ?? [])]) 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; @@ -227,6 +249,12 @@ export function findCitationGroups(source: string, index: ReferenceIndex, option p = chain.to; continue; } + if (chain?.tokens.length === 1 && visibleSource.startsWith('[[', p)) { + const group = groupFromParts(chain, p, chain.to, index, boundedOptions); + if (group) groups.push(group); + p = chain.to; + continue; + } } const group = bracketGroup(visibleSource, p, index, boundedOptions); if (group) { diff --git a/src/editor.ts b/src/editor.ts index 6a8abf8..83a0579 100644 --- a/src/editor.ts +++ b/src/editor.ts @@ -1,9 +1,10 @@ import { editorInfoField } from 'obsidian'; import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from '@codemirror/view'; -import { RangeSetBuilder, StateEffect } from '@codemirror/state'; +import { StateEffect, type Range } from '@codemirror/state'; import type { CitationDocument } from './model'; import type { CitationGroup } from './types'; import type CitationPreview from './main'; +import { usesNativeSinglePreview } from './citation-state'; const refreshCitationMarks = StateEffect.define(); @@ -19,15 +20,32 @@ export class CitationEditor { this.win = view.dom.ownerDocument.defaultView ?? window; this.refresh(); view.dom.addEventListener('mouseover', this.onMouseOver, true); + view.dom.addEventListener('click', this.onClick, true); + view.dom.addEventListener('auxclick', this.onClick, true); } private readonly onMouseOver = (event: MouseEvent): void => { const mark = (event.target as Element | null)?.closest?.('.crp-editor-citation'); if (!mark || mark.contains(event.relatedTarget as Node | null)) return; + const previous = (event.relatedTarget as Element | null)?.closest?.('.crp-editor-citation'); + if (previous?.dataset.crpFrom === mark.dataset.crpFrom) return; const group = this.targets.get(Number(mark.dataset.crpFrom)); if (this.model && group && this.owner.hover(event, mark, this.model, group, true)) event.stopPropagation(); }; + private readonly onClick = (event: MouseEvent): void => { + if (event.type === 'click' && (event.button !== 0 || (!event.ctrlKey && !event.metaKey))) return; + if (event.type === 'auxclick' && event.button !== 1) return; + const mark = (event.target as Element | null)?.closest?.('.crp-editor-number'); + if (!mark || !this.model) return; + const group = this.targets.get(Number(mark.dataset.crpFrom)); + const number = Number(mark.dataset.crpNumber); + if (!group || !Number.isFinite(number)) return; + if (!this.owner.openCitation(this.model, group, number, event)) return; + event.preventDefault(); + event.stopPropagation(); + }; + private refresh(): void { this.path = this.view.state.field(editorInfoField, false)?.file?.path; this.targets.clear(); @@ -37,15 +55,30 @@ export class CitationEditor { return; } this.model = this.owner.parse(this.view.state.doc.toString(), this.path); - const builder = new RangeSetBuilder(); + const marks: Range[] = []; for (const group of this.model.groups) { - if (group.linked && group.numbers.length === 1) continue; this.targets.set(group.from, group); - builder.add(group.from, group.to, Decoration.mark({ - class: 'crp-editor-citation', attributes: { 'data-crp-from': String(group.from) } - })); + const attributes = { 'data-crp-from': String(group.from) }; + // A native single-link preview stays with Obsidian; its visible label still receives color. + if (!usesNativeSinglePreview(group)) { + marks.push(Decoration.mark({ class: 'crp-editor-citation', attributes }).range(group.from, group.to)); + } + if (!this.owner.settings.citationLinks || !this.model.isResolved(group)) continue; + const color = this.owner.settings.citationColor === 'theme' ? 'theme' : 'blue'; + for (const range of group.visibleRanges ?? []) { + if (range.to <= range.from) continue; + marks.push(Decoration.mark({ class: `crp-editor-link crp-link-${color}`, attributes }).range(range.from, range.to)); + } + // Explicit Markdown links retain the host's click semantics, including whole-range links. + if (group.outerLinkTarget) continue; + for (const token of group.tokens ?? []) { + if (token.linked || token.to <= token.from) continue; + marks.push(Decoration.mark({ class: 'crp-editor-number', attributes: { + ...attributes, 'data-crp-number': String(token.number) + } }).range(token.from, token.to)); + } } - this.decorations = builder.finish(); + this.decorations = Decoration.set(marks, true); } update(update: ViewUpdate): void { @@ -65,6 +98,8 @@ export class CitationEditor { destroy(): void { this.win.clearTimeout(this.timer); this.view.dom.removeEventListener('mouseover', this.onMouseOver, true); + this.view.dom.removeEventListener('click', this.onClick, true); + this.view.dom.removeEventListener('auxclick', this.onClick, true); } } diff --git a/src/main.ts b/src/main.ts index 3b15ada..3eb0c3e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,9 +1,11 @@ -import { MarkdownRenderChild, MarkdownView, Plugin, type MarkdownPostProcessorContext } from 'obsidian'; +import { MarkdownRenderChild, MarkdownView, Notice, Plugin, type MarkdownPostProcessorContext } from 'obsidian'; import type { Extension } from '@codemirror/state'; import { CitationDocument } from './model'; import { citationEditorExtension } from './editor'; -import { decorateReadingCitations } from './reading'; -import { installPreviewContent, isPagePreviewEnabled, requestPreview, type GroupPreview, type NativeHoverParent } from './popover'; +import { decorateReadingCitations, type ReadingTrigger } from './reading'; +import { installPreviewContent, isPagePreviewEnabled, requestPreview, type GroupPreview, type NativeHoverParent, type PreviewSection } from './popover'; +import { planReferenceAnchors } from './anchors'; +import { usesNativeSinglePreview } from './citation-state'; import { CitationSettingsTab, normalizeSettings } from './settings'; import { DEFAULT_SETTINGS, type CitationGroup, type PluginSettings } from './types'; @@ -11,11 +13,22 @@ interface ReadingTarget { model: CitationDocument; group: CitationGroup | undefined; key: string; + trigger: ReadingTrigger; } /** 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]); + return JSON.stringify([group.scopeId ?? null, group.linkTargets ?? [], group.numbers, + group.ambiguousScope ?? false, group.outerLinkTarget ?? null]); +} + +function referenceMarkdown(markdown: string): string { + return markdown.replace(/!\[\[/g, '[[').replace(/!\[([^\]]*)\]\(/g, '[$1]('); +} + +function previewSection(entries: readonly string[], numbers: readonly number[], title?: string): PreviewSection { + const markdown = entries.map(entry => '1. ' + (entry || '\u00a0').replace(/\n/g, '\n ')).join('\n'); + return { markdown, entries, numbers, title }; } export default class CitationPreview extends Plugin { @@ -27,11 +40,31 @@ export default class CitationPreview extends Plugin { readonly hoverParent: NativeHoverParent = { hoverPopover: null }; private previewPath?: string; private stopped = false; + private previewAvailable = false; async onload(): Promise { this.settings = normalizeSettings(await this.loadData()); this.addSettingTab(new CitationSettingsTab(this.app, this)); - if (!installPreviewContent(this.app, this)) return; + this.addCommand({ + id: 'add-missing-reference-anchors', + name: 'Add missing reference anchors', + editorCallback: (editor, context) => { + const plan = planReferenceAnchors(editor.getValue()); + if (!plan.added) { + new Notice(plan.skipped + ? `No anchors added. ${plan.skipped} conflicting or already anchored entries were skipped.` + : 'No missing reference anchors found in recognized reference lists.'); + return; + } + editor.transaction({ changes: plan.changes.map(change => ({ + from: editor.offsetToPos(change.from), to: editor.offsetToPos(change.to), text: change.insert + })) }, 'citation-preview:add-reference-anchors'); + if (context.file) this.invalidate(context.file.path); + new Notice(`Added ${plan.added} reference anchors. ${plan.skipped} entries skipped. Undo restores the previous text.`); + } + }); + // Link display and the manual command remain useful even without the native hover adapter. + this.previewAvailable = installPreviewContent(this.app, this); this.registerMarkdownPostProcessor((element, context) => this.processReading(element, context)); this.editorExtensions[0] = citationEditorExtension(this); this.registerEditorExtension(this.editorExtensions); @@ -76,7 +109,7 @@ 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 (!this.previewAvailable || !isPagePreviewEnabled(this.app)) return false; if (!editor && this.settings.requireModifier && !event.ctrlKey && !event.metaKey) return false; const key = groupKey(group); let preview = model.previewGroups.get(key); @@ -100,17 +133,48 @@ 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); + : model.references.lists?.find(section => section.id === group.scopeId) + ?? model.references.sections.find(section => section.id === group.scopeId); const entries = group.numbers.map(number => { if (group.ambiguousScope) return 'Ambiguous bibliography'; - const reference = references?.entries.get(number); + const reference = model.reference(group, number); if (!linktext && reference?.anchor?.startsWith('^')) linktext = '#' + reference.anchor; if (!reference) return references?.duplicates.has(number) ? 'Duplicate reference' : 'Reference not found'; - return reference.markdown.replace(/!\[\[/g, '[[').replace(/!\[([^\]]*)\]\(/g, '[$1]('); + return referenceMarkdown(reference.markdown); }); - const markdown = entries.map(entry => '1. ' + (entry || '\u00a0').replace(/\n/g, '\n ')).join('\n'); + const expanded = previewSection(entries, group.numbers); + if (group.outerLinkTarget && (group.tokens?.length ?? group.numbers.length) > 1) { + const explicit = model.references.anchors.get(group.outerLinkTarget); + if (explicit) { + const sections = [ + previewSection([referenceMarkdown(explicit.markdown)], [explicit.number], 'Linked reference'), + { ...expanded, title: 'Citation group' } + ]; + return { + ...expanded, linktext: '#' + group.outerLinkTarget, sections, + markdown: sections.map(section => `#### ${section.title}\n\n${section.markdown}`).join('\n\n---\n\n') + }; + } + } // A subpath also keeps missing or ambiguous reference previews in block mode. - return { linktext: linktext ?? '#^crp-preview', markdown, entries, numbers: group.numbers }; + return { ...expanded, linktext: linktext ?? '#^crp-preview' }; + } + + openCitation( + model: CitationDocument, + group: CitationGroup, + number: number, + event: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean; button?: number } + ): boolean { + if (!this.settings.citationLinks || !model.isResolved(group)) return false; + const reference = model.reference(group, number); + if (!reference) return false; + const newLeaf = !!(event.ctrlKey || event.metaKey || event.button === 1); + const target = reference.anchor ? '#' + reference.anchor : model.sourcePath; + const state = reference.anchor ? undefined : { eState: { line: reference.line } }; + void this.app.workspace.openLinkText(target, model.sourcePath, newLeaf, state) + .catch(() => { new Notice('Could not open the reference.'); }); + return true; } closePreview(path?: string): void { @@ -121,6 +185,10 @@ export default class CitationPreview extends Plugin { private invalidate(path: string): void { this.cache.delete(path); this.closePreview(path); + for (const target of this.readingByPath.get(path) ?? []) { + target.group = undefined; + target.trigger.update(target.model, undefined); + } } private processReading(element: HTMLElement, context: MarkdownPostProcessorContext): void { @@ -129,8 +197,11 @@ export default class CitationPreview extends Plugin { if (!info || !context.sourcePath) return; const path = context.sourcePath; const model = this.parse(info.text, path); - const groups = model.inLines(info.lineStart, info.lineEnd).filter(group => !group.linked || group.numbers.length > 1); - const triggers = decorateReadingCitations(element, groups, { sourcePath: path }); + const groups = model.inLines(info.lineStart, info.lineEnd); + const triggers = decorateReadingCitations(element, groups, { + sourcePath: path, model, settings: this.settings, + onNavigate: (currentModel, group, number, event) => this.openCitation(currentModel, group, number, event) + }); if (!triggers.length) return; const owner = new MarkdownRenderChild(element); context.addChild(owner); @@ -139,10 +210,11 @@ export default class CitationPreview extends Plugin { const registered: ReadingTarget[] = []; for (const trigger of triggers) { const anchor = trigger.element; - anchor.setAttribute('aria-haspopup', 'dialog'); - const target: ReadingTarget = { model, group: trigger.group, key: groupKey(trigger.group) }; + const target: ReadingTarget = { model, group: trigger.group, key: groupKey(trigger.group), trigger }; targets.add(target); registered.push(target); + if (usesNativeSinglePreview(trigger.group)) continue; + anchor.setAttribute('aria-haspopup', 'dialog'); let handled = false; owner.registerDomEvent(anchor, 'mouseover', event => { if (!target.group) return; @@ -179,10 +251,25 @@ export default class CitationPreview extends Plugin { this.closePreview(path); const model = this.parse(source, path); const byKey = new Map(model.groups.map(group => [groupKey(group), group])); + let rerender = false; for (const target of this.readingByPath.get(path) ?? []) { - target.group = byKey.get(target.key); + const previous = target.group; + if (previous && !previous.linked) { + // Plain citations may select a different nearest list after an edit. Rebind only + // the same source occurrence; equal labels elsewhere are not interchangeable. + const current = model.at(previous.from); + target.group = current && !current.linked && current.from === previous.from + && target.model.source.slice(previous.from, previous.to) === source.slice(current.from, current.to) + ? current : undefined; + } else { + target.group = byKey.get(target.key); + } target.model = model; + if (target.group) target.key = groupKey(target.group); + else rerender = true; + target.trigger.update(model, target.group); } + if (rerender) this.rerender(); } private rerender(): void { diff --git a/src/model.ts b/src/model.ts index c842e75..1d1d0fd 100644 --- a/src/model.ts +++ b/src/model.ts @@ -1,7 +1,8 @@ import { ignoredMarkdownRanges, parseReferences, sourceLines } from './bibliography'; import { findCitationGroups } from './citations'; +import { detectHeadingScopes, detectReferenceLists } from './reference-lists'; import type { GroupPreview } from './popover'; -import type { CitationGroup, PluginSettings, ReferenceIndex } from './types'; +import type { CitationGroup, PluginSettings, ReferenceEntry, ReferenceIndex } from './types'; /** Parsed once per document revision, shared by all hover targets in that revision. */ export class CitationDocument { @@ -18,6 +19,10 @@ export class CitationDocument { const lines = sourceLines(source); const ignored = ignoredMarkdownRanges(source, lines); this.references = parseReferences(source, lines, ignored); + if (settings.recognizePlainText) { + this.references.headingScopes = detectHeadingScopes(source, lines); + this.references.lists = detectReferenceLists(source, this.references, lines); + } this.groups = findCitationGroups(source, this.references, { maxReferences: settings.maxReferences, recognizePlainText: settings.recognizePlainText, @@ -28,6 +33,21 @@ export class CitationDocument { } } + /** Resolve only inside the selected list or namespace; never borrow from another bibliography. */ + reference(group: CitationGroup, number: number): ReferenceEntry | undefined { + if (group.ambiguousScope) return undefined; + const selected = group.scopeId === undefined ? this.references + : this.references.lists?.find(list => list.id === group.scopeId) + ?? this.references.sections.find(section => section.id === group.scopeId); + const entry = selected?.entries.get(number); + if (!entry || (entry.anchor && this.references.duplicateAnchors.has(entry.anchor))) return undefined; + return entry; + } + + isResolved(group: CitationGroup): boolean { + return group.numbers.length > 0 && group.numbers.every(number => this.reference(group, number) !== undefined); + } + at(position: number): CitationGroup | undefined { let low = 0; let high = this.groups.length - 1; diff --git a/src/popover.ts b/src/popover.ts index db0e8a8..5196e16 100644 --- a/src/popover.ts +++ b/src/popover.ts @@ -1,12 +1,18 @@ import { MarkdownRenderer, type App, type Component } from 'obsidian'; -export interface GroupPreview { - linktext: string; +export interface PreviewSection { + title?: string; markdown: string; entries: readonly string[]; numbers: readonly number[]; } +export interface GroupPreview extends PreviewSection { + linktext: string; + /** Explicit whole-group links retain their own result above the expanded group. */ + sections?: readonly PreviewSection[]; +} + export interface NativeHoverParent { hoverPopover: { hide(): void } | null; } @@ -58,22 +64,29 @@ export function installPreviewContent(app: App, owner: Component): boolean { embed.loadFile = async () => { embed.editable = false; embed.requestEdit = () => {}; + // The host may ask the same embed to load again after layout changes. + previewView.querySelectorAll(':scope > .crp-native-content').forEach(content => content.remove()); // The native virtualized sizer only renders indexed file sections. const section = previewView.createDiv({ cls: 'markdown-preview-sizer markdown-preview-section crp-native-content' }); - const content = section.createDiv({ cls: 'el-ol' }); - const { markdown, entries, numbers } = request.preview; - try { - await MarkdownRenderer.render(app, markdown, content, request.path, embed); - } catch { - content.replaceChildren(); - } - let list = content.querySelector(':scope > ol'); - if (!list || list.children.length !== numbers.length) { - content.replaceChildren(); - list = content.createEl('ol'); - for (const entry of entries) list.createEl('li', { text: entry }); + const blocks = request.preview.sections ?? [request.preview]; + for (const [index, block] of blocks.entries()) { + if (index) section.createEl('hr', { cls: 'crp-preview-divider' }); + if (block.title) section.createEl('h4', { text: block.title, cls: 'crp-preview-heading' }); + const content = section.createDiv({ cls: 'el-ol' }); + const { markdown, entries, numbers } = block; + try { + await MarkdownRenderer.render(app, markdown, content, request.path, embed); + } catch { + content.replaceChildren(); + } + let list = content.querySelector(':scope > ol'); + if (!list || list.children.length !== numbers.length) { + content.replaceChildren(); + list = content.createEl('ol'); + for (const entry of entries) list.createEl('li', { text: entry }); + } + list.querySelectorAll(':scope > li').forEach((item, itemIndex) => { item.value = numbers[itemIndex]; }); } - list.querySelectorAll(':scope > li').forEach((item, index) => { item.value = numbers[index]; }); }; return embed; } diff --git a/src/reading.ts b/src/reading.ts index ff24d6b..3543283 100644 --- a/src/reading.ts +++ b/src/reading.ts @@ -1,9 +1,13 @@ -import type { CitationGroup } from './types'; +import type { CitationGroup, PluginSettings } from './types'; +import type { CitationDocument } from './model'; import { localLinkAnchor } from './links'; +import { usesNativeSinglePreview } from './citation-state'; export interface ReadingTrigger { element: HTMLElement; group: CitationGroup; + /** Refresh resolution and virtual links without replacing existing native anchors. */ + update(model: CitationDocument, group: CitationGroup | undefined): void; /** Idempotent: remove only this wrapper and preserve every original child. */ dispose(): void; } @@ -11,6 +15,9 @@ export interface ReadingTrigger { export interface ReadingOptions { /** Used to distinguish a link to this note from an identically numbered other note. */ sourcePath?: string; + model?: CitationDocument; + settings?: Pick; + onNavigate?(model: CitationDocument, group: CitationGroup, number: number, event: MouseEvent | KeyboardEvent): boolean | void; } interface TextSegment { @@ -104,12 +111,17 @@ function candidates(run: TextRun): Candidate[] { const from = match.index; result.push({ run, from, to: from + match[0].length, key: signature(match[0]), bracketed: true }); } - // Explicit Markdown links can render as 1–10 without outer brackets. - const bare = /[0-90-9]+(?:\s*[-–—−-,,、;;]\s*[0-90-9]+)+/g; + // Explicit Markdown links can render as 1 or 1–10 without outer brackets. + // Plain source groups still require visible brackets when matching below. + const bracketedCandidates = [...result]; + let bracketIndex = 0; + const bare = /[0-90-9]+(?:\s*[-–—−-,,、;;]\s*[0-90-9]+)*/g; for (const match of run.text.matchAll(bare)) { const from = match.index; const to = from + match[0].length; - if (result.some(candidate => from >= candidate.from && to <= candidate.to)) continue; + while (bracketIndex < bracketedCandidates.length && bracketedCandidates[bracketIndex].to <= from) bracketIndex += 1; + const enclosing = bracketedCandidates[bracketIndex]; + if (enclosing && from >= enclosing.from && to <= enclosing.to) continue; if (/[\p{L}\p{N}_]/u.test(run.text[from - 1] ?? '') || /[\p{L}\p{N}_]/u.test(run.text[to] ?? '')) continue; result.push({ run, from, to, key: signature(match[0]), bracketed: false }); } @@ -163,6 +175,136 @@ function safeRange(candidate: Candidate, document: Document): Range | null { return range; } +function unwrap(element: HTMLElement): void { + const parent = element.parentNode; + if (!parent) return; + const fragment = element.ownerDocument.createDocumentFragment(); + while (element.firstChild) fragment.appendChild(element.firstChild); + parent.replaceChild(fragment, element); +} + +/** Read only the visible text; an enclosing native link always keeps its original target. */ +function visibleRun(root: HTMLElement): TextRun { + const run: TextRun = { text: '', segments: [] }; + const walker = root.ownerDocument.createTreeWalker(root, 4 /* SHOW_TEXT */); + let node: Node | null; + while ((node = walker.nextNode())) { + const text = node as Text; + const from = run.text.length; + run.text += text.data; + run.segments.push({ node: text, from, to: run.text.length }); + } + return run; +} + +/** Add links only to displayed number tokens, never to expanded, deduplicated preview numbers. */ +function numberRanges(root: HTMLElement, group: CitationGroup): Array<{ candidate: Candidate; number: number }> { + if (root.closest('a')) return []; + const run = visibleRun(root); + const matches = Array.from(run.text.matchAll(/[0-90-9]+/g)); + const numbers = matches.map(match => Number(signature(match[0]))); + const expected = group.tokens?.map(token => token.number) + ?? Array.from(group.label.matchAll(/\d+/g), match => Number(match[0])); + if (numbers.length !== expected.length || numbers.some((number, index) => number !== expected[index])) return []; + return matches.flatMap((match, index) => { + const candidate: Candidate = { + run, from: match.index, to: match.index + match[0].length, + key: match[0], bracketed: false + }; + if (candidateLinks(candidate).size) return []; + return [{ candidate, number: numbers[index] }]; + }); +} + +function createTrigger(wrapper: HTMLElement, initialGroup: CitationGroup, options: ReadingOptions): ReadingTrigger { + let currentModel = options.model; + let currentGroup: CitationGroup | undefined = initialGroup; + let disposed = false; + const generated: Array<{ element: HTMLAnchorElement; dispose(): void }> = []; + + const removeLinks = (): void => { + for (const link of generated.splice(0)) { + link.dispose(); + unwrap(link.element); + } + }; + + const refresh = (): void => { + removeLinks(); + const nativeSingle = currentGroup && usesNativeSinglePreview(currentGroup); + wrapper.classList.toggle('crp-native-citation', !!nativeSingle); + if (currentGroup && !nativeSingle) { + wrapper.setAttribute('tabindex', '0'); + wrapper.setAttribute('role', 'group'); + wrapper.setAttribute('aria-label', `Preview references ${currentGroup.label}`); + } else { + wrapper.removeAttribute('tabindex'); + wrapper.removeAttribute('role'); + wrapper.removeAttribute('aria-label'); + } + const resolved = !!currentModel && !!currentGroup && currentModel.isResolved(currentGroup); + const enabled = options.settings?.citationLinks ?? true; + wrapper.classList.toggle('crp-resolved', enabled && resolved); + wrapper.classList.toggle('crp-link-blue', enabled && resolved && options.settings?.citationColor !== 'theme'); + wrapper.classList.toggle('crp-link-theme', enabled && resolved && options.settings?.citationColor === 'theme'); + if (!enabled || !resolved || !currentModel || !currentGroup || !options.onNavigate) return; + + for (const { candidate, number } of numberRanges(wrapper, currentGroup).reverse()) { + const reference = currentModel.reference(currentGroup, number); + if (!reference) continue; + const range = safeRange(candidate, wrapper.ownerDocument); + if (!range) continue; + const link = wrapper.ownerDocument.createElement('a'); + const href = reference.anchor ? `#${reference.anchor}` : currentModel.sourcePath; + link.className = 'crp-reference-link'; + link.setAttribute('href', href); + link.setAttribute('data-href', href); + link.setAttribute('data-crp-number', String(number)); + link.setAttribute('aria-label', `Reference ${number}`); + try { + range.surroundContents(link); + } catch { + continue; + } + const navigate = (event: MouseEvent | KeyboardEvent): void => { + if (event.type === 'keydown' && (event as KeyboardEvent).key !== 'Enter') return; + if (event.type === 'click' && (event as MouseEvent).button !== 0) return; + if (event.type === 'auxclick' && (event as MouseEvent).button !== 1) return; + // Synthetic links are owned by this plugin, including keyboard and new-pane activation. + event.preventDefault(); + event.stopPropagation(); + if (currentModel && currentGroup) options.onNavigate?.(currentModel, currentGroup, number, event); + }; + link.addEventListener('click', navigate); + link.addEventListener('auxclick', navigate); + link.addEventListener('keydown', navigate); + generated.push({ element: link, dispose: () => { + link.removeEventListener('click', navigate); + link.removeEventListener('auxclick', navigate); + link.removeEventListener('keydown', navigate); + } }); + } + }; + + refresh(); + return { + element: wrapper, + group: initialGroup, + update(model, group): void { + if (disposed) return; + currentModel = model; + currentGroup = group; + refresh(); + }, + dispose(): void { + if (disposed) return; + disposed = true; + removeLinks(); + unwrap(wrapper); + } + }; +} + /** * Decorate only groups belonging to this rendered Markdown section. The caller must filter * source groups with MarkdownPostProcessorContext.getSectionInfo; global groups are ambiguous. @@ -209,9 +351,6 @@ export function decorateReadingCitations( if (!range) continue; const wrapper = root.ownerDocument.createElement('span'); wrapper.className = 'crp-citation'; - wrapper.setAttribute('tabindex', '0'); - wrapper.setAttribute('role', 'group'); - wrapper.setAttribute('aria-label', `Preview references ${group.label}`); wrapper.setAttribute('data-crp-label', group.label); try { range.surroundContents(wrapper); @@ -219,20 +358,7 @@ export function decorateReadingCitations( // Unusual plugin-rendered inline structures are safer to leave untouched. continue; } - let disposed = false; - triggers.push({ - element: wrapper, - group, - dispose(): void { - if (disposed) return; - disposed = true; - const parent = wrapper.parentNode; - if (!parent) return; - const fragment = root.ownerDocument.createDocumentFragment(); - while (wrapper.firstChild) fragment.appendChild(wrapper.firstChild); - parent.replaceChild(fragment, wrapper); - } - }); + triggers.push(createTrigger(wrapper, group, options)); } return triggers.reverse(); } diff --git a/src/reference-lists.ts b/src/reference-lists.ts new file mode 100644 index 0000000..8017cf1 --- /dev/null +++ b/src/reference-lists.ts @@ -0,0 +1,259 @@ +import { ignoredMarkdownRanges, parseReferences, referenceAnchor, sourceLines, type SourceRange } from './bibliography'; +import type { HeadingScope, ReferenceEntry, ReferenceIndex, ReferenceList } from './types'; + +interface Candidate extends ReferenceEntry { + evidence: number; + heading: string; + namespace?: string; +} + +const YEAR = /\b(?:1[5-9]|20|21)\d{2}[a-z]?\b/i; +const IDENTIFIER = /(?:\b10\.\d{4,9}\/\S+|\bISBN(?:-1[03])?\s*:?[\s\d-]{10,}|\barXiv\s*:\s*\d{4}\.\d{4,5})/i; +const DOCUMENT_TYPE = /\[(?:J|M|C|D|R|S|P|N|EB)(?:\/(?:OL|CD))?\]/i; +const PUBLICATION = /\b(?:Journal|Proceedings|Transactions|Letters|Review|Reviews|Press|Publisher|University|Geophys(?:ical)?|Atmos(?:pheric)?|Ocean(?:ography|ographic)?|Science|Nature|Springer|Elsevier)\b|学报|期刊|出版社|大学|会议|标准|专利/i; +const PAGES = /\b\d{1,4}\s*(?:\(\d{1,3}\))?\s*[:,]\s*(?:[A-Za-z]?\d{1,7})(?:\s*[-–—]\s*\d{1,7})?/; +const AUTHOR = /^(?:[A-ZÀ-ÖØ-Ý][\p{L}'’‐-]+(?:\s*,\s*|\s+)(?:[A-Z](?:[.\s,-]|$)|[A-Z][\p{L}'’‐-]+(?:\s*,|\s+and\s))|[\p{Script=Han}]{2,4}(?:[,,、..。]|\s+[\p{Script=Han}]{2,4}))/u; + +/** Exported for the insertion planner; only genuine block definitions match. */ +export function blockAnchorAtEnd(text: string): { id: string; from: number } | undefined { + const match = /(?:^|[ \t])\^([A-Za-z0-9-]+)[ \t]*$/.exec(text); + if (!match) return undefined; + return { id: match[1], from: match.index + match[0].indexOf('^') }; +} + +function blocked(offset: number, ranges: SourceRange[]): boolean { + let low = 0; + let high = ranges.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (ranges[mid].to <= offset) low = mid + 1; + else high = mid; + } + return !!ranges[low] && ranges[low].from <= offset; +} + +function numberedStart(text: string): { number: number; width: number } | undefined { + const match = /^ {0,3}(?:\*\*)?(?:\[([1-9]\d{0,8})\]|[([1-9]\d{0,8})]|【([1-9]\d{0,8})】|\(([1-9]\d{0,8})\)|(([1-9]\d{0,8}))|([1-9]\d{0,8})[.)、.])(?:\*\*)?[ \t]*/.exec(text); + if (!match) return undefined; + const number = Number(match.slice(1).find(value => value !== undefined)); + return { number, width: match[0].length }; +} + +function structuralBoundary(text: string): boolean { + return /^ {0,3}(?:#{1,6}(?:\s|$)|>|(?:`{3,}|~{3,})|\|)/.test(text) + || /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|=+)\s*$/.test(text); +} + +function headingText(text: string): string | undefined { + const atx = /^ {0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$/.exec(text); + if (atx) return atx[1]; + const bold = /^\s*\*\*(.{1,100})\*\*\s*$/.exec(text); + return bold?.[1]; +} + +/** Parse heading nesting once. Titles are not used to assign citation membership. */ +export function detectHeadingScopes(source: string, lines = sourceLines(source), ignored = ignoredMarkdownRanges(source, lines, false)): HeadingScope[] { + const scopes: HeadingScope[] = []; + const stack: Array<{ level: number; from: number }> = []; + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i]; + const content = line.from + (line.text.match(/^\s*/)?.[0].length ?? 0); + if (blocked(content, ignored)) continue; + const atx = /^ {0,3}(#{1,6})(?:\s|$)/.exec(line.text); + const setext = !atx && line.text.trim() && !numberedStart(line.text) && !structuralBoundary(line.text) + ? /^ {0,3}(=+|-+)\s*$/.exec(lines[i + 1]?.text ?? '') : null; + const level = atx ? atx[1].length : setext ? (setext[1][0] === '=' ? 1 : 2) : 0; + if (!level) continue; + while (stack.length && stack[stack.length - 1].level >= level) stack.pop(); + stack.push({ level, from: line.from }); + scopes.push({ from: line.from, path: stack.map(heading => heading.from) }); + if (setext) i += 1; + } + return scopes; +} + +export function headingPathAt(scopes: HeadingScope[], offset: number): number[] { + let low = 0; + let high = scopes.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (scopes[mid].from <= offset) low = mid + 1; + else high = mid; + } + return low > 0 ? scopes[low - 1].path : []; +} + +/** Structural numbering alone, or a year alone, cannot establish a bibliography. */ +function evidence(text: string, anchored: boolean): number { + if (anchored) return 4; + const clean = text + .replace(/\[\[([^\]\n|]+)(?:\|([^\]\n]+))?\]\]/g, (_match, target: string, label: string | undefined) => label ?? target) + .replace(/\[((?:\\.|[^\]\\])*)\]\((?:<[^>\r\n]*>|[^)\r\n]*)\)/g, '$1') + .replace(/<[^>\n]*>/g, '') + .replace(/\\([\\`*{}[\]()#+\-.!_>])/g, '$1') + .replace(/\*\*|__/g, '').trim(); + if (clean.length < 18) return 0; + if (IDENTIFIER.test(clean)) return 3; + const year = YEAR.test(clean); + if (year && DOCUMENT_TYPE.test(clean)) return 3; + if (!year || !AUTHOR.test(clean)) return 0; + if (PUBLICATION.test(clean) || PAGES.test(clean)) return 2; + const punctuation = clean.match(/[.。.]/g)?.length ?? 0; + return punctuation >= 2 ? 2 : 0; +} + +function addEntry(list: ReferenceList, entry: ReferenceEntry, duplicateAnchor: boolean): void { + list.items.push(entry); + if (duplicateAnchor || list.entries.has(entry.number) || list.duplicates.has(entry.number)) { + list.duplicates.add(entry.number); + list.entries.delete(entry.number); + return; + } + list.entries.set(entry.number, entry); +} + +/** + * Detect physically adjacent numbered bibliography entries conservatively. + * This never adds to or changes the explicit ref/sref anchor namespace index. + */ +export function detectReferenceLists( + source: string, + index: ReferenceIndex = parseReferences(source), + lines = sourceLines(source) +): ReferenceList[] { + const ignored = ignoredMarkdownRanges(source, lines, false); + const headingScopes = index.headingScopes ?? detectHeadingScopes(source, lines, ignored); + const blockIds = new Set(); + const duplicatedBlockIds = new Set(index.duplicateAnchors); + for (const line of lines) { + const anchor = blockAnchorAtEnd(line.text); + if (!anchor || blocked(line.from + anchor.from, ignored)) continue; + const id = `^${anchor.id}`; + if (blockIds.has(id)) duplicatedBlockIds.add(id); + blockIds.add(id); + } + const known = new Map(); + for (const entry of index.anchors.values()) known.set(entry.from, entry); + const candidates: Candidate[] = []; + let heading = ''; + + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i]; + if (blocked(line.from + (line.text.match(/^\s*/)?.[0].length ?? 0), ignored)) continue; + const nextHeading = headingText(line.text); + if (nextHeading && !numberedStart(line.text)) { heading = nextHeading; continue; } + if (!numberedStart(line.text) && /^ {0,3}(?:=+|-+)\s*$/.test(lines[i + 1]?.text ?? '') && line.text.trim()) { + heading = line.text.trim(); + i += 1; + continue; + } + const prefix = numberedStart(line.text); + const anchored = known.get(line.from); + if (!prefix && !anchored) continue; + if (/^(?: {4,}|\t)/.test(line.text)) continue; + + // Existing anchors already supply exact block boundaries, including multiline entries. + if (anchored) { + candidates.push({ ...anchored, evidence: 4, heading, namespace: anchored.sectionId }); + while (i + 1 < lines.length && lines[i + 1].from < anchored.to) i += 1; + continue; + } + if (!prefix) continue; + let last = i; + let end = line.from + line.text.trimEnd().length; + let existingAnchor = blockAnchorAtEnd(line.text); + let blank = false; + for (let next = i + 1; !existingAnchor && next < lines.length; next += 1) { + const follow = lines[next]; + if (!follow.text.trim()) { blank = true; continue; } + const anchorLine = /^\s*\^[A-Za-z0-9-]+\s*$/.test(follow.text); + if (numberedStart(follow.text) || headingText(follow.text) || structuralBoundary(follow.text)) break; + if (blocked(follow.from + (follow.text.match(/^\s*/)?.[0].length ?? 0), ignored)) break; + if (blank && !/^\s/.test(follow.text) && !anchorLine) break; + // An inline body citation is evidence that the reference block has ended. + if (!anchorLine && /(?:\[\s*\d+(?:\s*[-–,]\s*\d+)*\s*\]|#\^(?:s?ref))/.test(follow.text)) break; + last = next; + end = follow.from + follow.text.trimEnd().length; + existingAnchor = blockAnchorAtEnd(follow.text); + blank = false; + } + const raw = source.slice(line.from + prefix.width, end); + const lastLine = lines[last]; + const identity = existingAnchor ? referenceAnchor(existingAnchor.id) : undefined; + const contentEnd = existingAnchor ? lastLine.from + existingAnchor.from : end; + const markdown = source.slice(line.from + prefix.width, contentEnd) + .replace(/^(?: {1,4}|\t)(?=\S)/gm, '').trim(); + const score = evidence(markdown, identity !== undefined); + if (score) { + candidates.push({ + number: identity?.number ?? prefix.number, + sectionId: '', markdown, from: line.from, to: end, line: line.line, + anchor: existingAnchor ? `^${existingAnchor.id}` : undefined, + evidence: score, heading, namespace: identity?.namespace + }); + } + // A rejected list item still owns its continuation; do not discover nested entries inside it. + if (raw.trim()) i = last; + } + + const lists: ReferenceList[] = []; + let pending: Candidate[] = []; + const flush = (): void => { + if (!pending.length) return; + const strong = pending.some(entry => entry.evidence >= 3); + const headingEvidence = /references|bibliography|literature cited|参考文献|引用文献|文献目录/i.test(pending[0].heading); + // A lone anchored fragment need not be a physical list; the anchor namespace still resolves it. + if (pending.length === 1 && pending[0].evidence === 4 && !headingEvidence && !evidence(pending[0].markdown, false)) { + pending = []; + return; + } + // A single unanchored author/year entry needs a bibliography heading; identifiers are sufficient alone. + if (!strong && pending.length < 2 && !headingEvidence) { pending = []; return; } + const first = pending[0]; + const last = pending[pending.length - 1]; + const list: ReferenceList = { + id: `list:${first.from}`, title: first.heading || 'Detected references', + from: first.from, to: last.to, entries: new Map(), duplicates: new Set(), items: [], + supplemental: /supplement|appendix|补充|附录|附加/i.test(first.heading), + headingPath: headingPathAt(headingScopes, first.from) + }; + for (const candidate of pending) { + const { evidence: _evidence, heading: _heading, namespace: _namespace, ...entry } = candidate; + const copy = { ...entry, sectionId: list.id }; + addEntry(list, copy, !!entry.anchor && duplicatedBlockIds.has(entry.anchor)); + } + lists.push(list); + pending = []; + }; + for (const candidate of candidates) { + const previous = pending[pending.length - 1]; + if (previous) { + const gap = source.slice(previous.to, candidate.from); + const resets = candidate.number === 1 && previous.number > 1; + const changesNamespace = previous.namespace && candidate.namespace && previous.namespace !== candidate.namespace; + if (gap.trim() || resets || changesNamespace) flush(); + } + pending.push(candidate); + } + flush(); + return lists; +} + +/** Prefer the closest shared chapter, then distance; missing entries never select another list. */ +export function nearestReferenceList(lists: ReferenceList[], from: number, to: number, headingPath: readonly number[] = []): ReferenceList | undefined { + let best: ReferenceList | undefined; + let distance = Number.POSITIVE_INFINITY; + let shared = -1; + for (const list of lists) { + let common = 0; + while (common < headingPath.length && list.headingPath?.[common] === headingPath[common]) common += 1; + const current = list.from >= to ? list.from - to : from >= list.to ? from - list.to : 0; + if (common > shared || (common === shared && (current < distance + || (current === distance && list.from >= to && (!best || best.from < to))))) { + best = list; + distance = current; + shared = common; + } + } + return best; +} diff --git a/src/settings.ts b/src/settings.ts index 84d41ba..2398778 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -29,7 +29,9 @@ export function normalizeSettings(value: unknown): PluginSettings { maxReferences: number('maxReferences', 10, 500), recognizePlainText: bool('recognizePlainText'), requireModifier: bool('requireModifier'), - enableEditor: bool('enableEditor') + enableEditor: bool('enableEditor'), + citationLinks: bool('citationLinks'), + citationColor: data.citationColor === 'theme' ? 'theme' : 'blue' }; } @@ -42,6 +44,27 @@ export class CitationSettingsTab extends PluginSettingTab { /** Obsidian 1.13+ indexes these names/descriptions and renders each row on demand. */ getSettingDefinitions(): CitationSettingDefinition[] { return [ + { + name: 'Show citations as links', + desc: 'Color resolved citations and enable navigation for plain numeric citations. Existing links and hover previews keep working.', + render: setting => { + setting.addToggle(toggle => toggle.setValue(this.owner.settings.citationLinks).onChange(async value => { + this.owner.settings.citationLinks = value; + await this.owner.saveSettings(true); + })); + } + }, + { + name: 'Citation color', + desc: 'Use blue adapted to light and dark themes, or follow the theme’s link color.', + render: setting => { + setting.addDropdown(dropdown => dropdown.addOptions({ blue: 'Blue', theme: 'Follow theme' }) + .setValue(this.owner.settings.citationColor).onChange(async value => { + this.owner.settings.citationColor = value === 'theme' ? 'theme' : 'blue'; + await this.owner.saveSettings(true); + })); + } + }, { name: 'Maximum references per group', desc: 'Larger groups are skipped. This bounds work for malformed or very large ranges.', @@ -55,7 +78,7 @@ export class CitationSettingsTab extends PluginSettingTab { }, { name: 'Recognize plain numeric citations', - desc: 'Also recognize bracketed numbers without links when the note has numbered references. Turn off if numeric intervals are being mistaken for citations.', + desc: 'Resolve bracketed numbers using section context and the nearest reference list, including lists without anchors. Turn off if numeric intervals are being mistaken for citations.', render: setting => { setting.addToggle(toggle => toggle.setValue(this.owner.settings.recognizePlainText).onChange(async value => { this.owner.settings.recognizePlainText = value; @@ -74,8 +97,8 @@ export class CitationSettingsTab extends PluginSettingTab { } }, { - name: 'Enable editor previews', - desc: 'Show previews in live preview and source mode as well as reading view.', + name: 'Enable editor previews and links', + desc: 'Show previews and citation link styling in live preview and source mode as well as reading view.', render: setting => { setting.addToggle(toggle => toggle.setValue(this.owner.settings.enableEditor).onChange(async value => { this.owner.settings.enableEditor = value; diff --git a/src/types.ts b/src/types.ts index 8ff7e01..58fb820 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,6 +20,21 @@ export interface ReferenceSection { duplicates: Set; } +/** A physical bibliography, kept separate from explicit anchor namespaces. */ +export interface ReferenceList extends ReferenceSection { + /** All entries, including duplicated numbers, in source order. */ + items: ReferenceEntry[]; + /** Heading evidence is optional; explicit anchors never depend on it. */ + supplemental: boolean; + /** Structural heading identities, independent of their displayed wording. */ + headingPath?: number[]; +} + +export interface HeadingScope { + from: number; + path: number[]; +} + export interface ReferenceIndex { /** File-wide lookup, used only when a citation cannot select a bibliography. */ entries: Map; @@ -32,6 +47,19 @@ export interface ReferenceIndex { /** Exact, unique anchors take precedence over numeric naming conventions. */ anchors: Map; duplicateAnchors: Set; + /** Conservative bibliography detection used only for unlinked numeric citations. */ + lists?: ReferenceList[]; + /** Precomputed structural contexts for plain-citation lookup. */ + headingScopes?: HeadingScope[]; +} + +export interface CitationToken { + number: number; + /** The visible number's UTF-16 source range, excluding link syntax. */ + from: number; + to: number; + linked: boolean; + target?: string; } export interface CitationGroup { @@ -47,6 +75,12 @@ export interface CitationGroup { ambiguousScope?: boolean; /** Exact same-note anchors in source order, for aligning rendered links safely. */ linkTargets?: string[]; + /** Displayed numbers before range expansion and deduplication. */ + tokens?: CitationToken[]; + /** Visible citation characters only, never link destinations or escape backslashes. */ + visibleRanges?: Array<{ from: number; to: number }>; + /** Explicit destination of a link wrapping a whole group, including ^ but not #. */ + outerLinkTarget?: string; } export interface ParseOptions { @@ -61,11 +95,15 @@ export interface PluginSettings { recognizePlainText: boolean; requireModifier: boolean; enableEditor: boolean; + citationLinks: boolean; + citationColor: 'blue' | 'theme'; } export const DEFAULT_SETTINGS: PluginSettings = { maxReferences: 100, recognizePlainText: true, requireModifier: false, - enableEditor: true + enableEditor: true, + citationLinks: true, + citationColor: 'blue' }; diff --git a/styles.css b/styles.css index ca63d61..e1770d9 100644 --- a/styles.css +++ b/styles.css @@ -3,7 +3,57 @@ cursor: help; } -.crp-citation:focus-visible { +.crp-native-citation { + cursor: inherit; +} + +.crp-link-blue { + --crp-link-color: #2563eb; + --crp-link-hover-color: #1d4ed8; +} + +.theme-dark .crp-link-blue { + --crp-link-color: #75b9ff; + --crp-link-hover-color: #acd5ff; +} + +.crp-link-theme { + --crp-link-color: var(--link-color); + --crp-link-hover-color: var(--link-color-hover); +} + +.crp-citation.crp-resolved, +.crp-citation.crp-resolved a, +.markdown-source-view.mod-cm6 .cm-content .crp-editor-link, +.cm-editor .crp-editor-link { + color: var(--crp-link-color); +} + +.crp-citation.crp-resolved a { + text-decoration: none; +} + +.crp-citation.crp-resolved:hover, +.crp-citation.crp-resolved:hover a, +.crp-citation.crp-resolved:focus-visible, +.crp-citation.crp-resolved a:focus-visible, +.markdown-source-view.mod-cm6 .cm-content .crp-editor-link:hover, +.cm-editor .crp-editor-link:hover { + color: var(--crp-link-hover-color); + text-decoration: underline; + text-underline-offset: 0.12em; +} + +.crp-reference-link { + cursor: pointer; +} + +.cm-editor .crp-editor-number { + cursor: text; +} + +.crp-citation:focus-visible, +.crp-reference-link:focus-visible { outline: 2px solid var(--interactive-accent); outline-offset: 2px; } diff --git a/tests/anchors.test.ts b/tests/anchors.test.ts new file mode 100644 index 0000000..f658f34 --- /dev/null +++ b/tests/anchors.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; +import { planReferenceAnchors, type AnchorPlan } from '../src/anchors'; +import { parseReferences } from '../src/bibliography'; + +const first = 'Smith J. Atmospheric waves [J]. Journal of Climate, 2024, 37: 1-12.'; +const second = 'Jones B. Ocean dynamics [J]. Ocean Science, 2023, 19: 11-22.'; +function apply(source: string, plan: AnchorPlan): string { + for (const change of [...plan.changes].reverse()) source = source.slice(0, change.from) + change.insert + source.slice(change.to); + return source; +} + +describe('manual reference-anchor planning', () => { + it('plans insertions without changing the supplied string and is idempotent after application', () => { + const source = `Body [1,2].\n\n1. ${first}\n2. ${second}`; + const plan = planReferenceAnchors(source); + expect(source).not.toContain('^ref-'); + expect(plan).toMatchObject({ added: 2, skipped: 0, lists: 1 }); + expect(plan.changes.every(change => change.from === change.to)).toBe(true); + const result = apply(source, plan); + expect(parseReferences(result).anchors.size).toBe(2); + expect(planReferenceAnchors(result).changes).toEqual([]); + }); + + it('preserves CRLF, Unicode text, trailing spaces, and missing final newline', () => { + const source = `😀 Evidence [1,2].\r\n\r\n1. ${first} \r\n2. ${second}`; + const result = apply(source, planReferenceAnchors(source)); + expect(result.replace(/ \^ref-[12]/g, '')).toBe(source); + expect(result).toContain('^ref-1 \r\n'); + expect(result.endsWith('^ref-2')).toBe(true); + }); + + it('uses independent namespaces for main, supplementary, and later bibliographies', () => { + const source = `## References\n1. ${first}\n2. ${second}\n\n## Supplementary references\n1. ${first}\n2. ${second}\n\n## Other references\n1. ${first}\n2. ${second}`; + const plan = planReferenceAnchors(source); + expect(plan.changes.map(change => change.insert)).toEqual([ + ' ^ref-1', ' ^ref-2', ' ^sref-1', ' ^sref-2', ' ^ref-list2-1', ' ^ref-list2-2' + ]); + expect(parseReferences(apply(source, plan)).duplicateAnchors.size).toBe(0); + }); + + it('preserves any existing block ID and fills only safe missing IDs', () => { + const source = `1. ${first} ^custom\n2. ${second}\n3. ${first} ^ref-3`; + const plan = planReferenceAnchors(source); + expect(plan).toMatchObject({ added: 1, skipped: 2 }); + expect(plan.changes[0].insert).toBe(' ^ref-2'); + expect(apply(source, plan)).toContain('^custom'); + }); + + it('skips repeated numbers and semantic collisions between ref1 and ref-1', () => { + const source = `Existing unrelated reference. ^ref1\n\n## References\n1. ${first}\n2. ${second} ^ref-2\n3. ${first}\n3. ${second}`; + const plan = planReferenceAnchors(source); + expect(plan.added).toBe(0); + expect(plan.changes).toEqual([]); + }); + + it('does not reuse a namespace occupied by a different physical list', () => { + const source = `Old isolated reference. ^ref-20\n\n## New references\n1. ${first}\n2. ${second}`; + const plan = planReferenceAnchors(source); + expect(plan.changes.map(change => change.insert)).toEqual([' ^ref-list2-1', ' ^ref-list2-2']); + }); + + it('does not modify code, ordinary numbered lists, or bibliography-like examples in YAML', () => { + const source = `---\nexample: |\n 1. ${first}\n---\n\n1. First step.\n2. Second step.\n\n\`\`\`md\n1. ${first}\n2. ${second}\n\`\`\``; + expect(planReferenceAnchors(source).changes).toEqual([]); + }); +}); diff --git a/tests/citations.test.ts b/tests/citations.test.ts index 96df423..e217117 100644 --- a/tests/citations.test.ts +++ b/tests/citations.test.ts @@ -185,4 +185,47 @@ describe('findCitationGroups', () => { it('never parses the bibliography itself as citations', () => { expect(find('No body citations.')).toEqual([]); }); + + it('keeps displayed number tokens separate from expanded and deduplicated numbers', () => { + const body = '😀 A [3,1-5,3].'; + const group = find(body)[0]; + expect(group.numbers).toEqual([3, 1, 2, 4, 5]); + expect(group.tokens?.map(token => token.number)).toEqual([3, 1, 5, 3]); + expect(group.tokens?.map(token => body.slice(token.from, token.to))).toEqual(['3', '1', '5', '3']); + expect(group.visibleRanges?.map(range => body.slice(range.from, range.to)).join('')).toBe('[3,1-5,3]'); + }); + + it('exposes only displayed characters of Markdown and wiki-linked groups', () => { + for (const body of [ + String.raw`\[[1](<#^ref-1>),[3](#^ref-3)\]`, + String.raw`\[[[#^ref-1| 1 ]],[[#^ref-3|3]]\]` + ]) { + const group = find(body)[0]; + expect(group.tokens?.map(token => body.slice(token.from, token.to))).toEqual(['1', '3']); + expect(group.visibleRanges?.map(range => body.slice(range.from, range.to)).join('')).toBe('[1,3]'); + expect(group.tokens?.map(token => token.target)).toEqual(['^ref-1', '^ref-3']); + expect(group.outerLinkTarget).toBeUndefined(); + } + }); + + it('records an overall linked range target independently of its displayed endpoints', () => { + for (const target of ['ref-1', 'ref-3']) { + const body = `[1-5](#^${target})`; + const group = find(body)[0]; + expect(group.outerLinkTarget).toBe(`^${target}`); + expect(group.linkTargets).toEqual([`^${target}`]); + expect(group.numbers).toEqual([1, 2, 3, 4, 5]); + expect(group.tokens?.every(token => token.linked && token.target === `^${target}`)).toBe(true); + expect(group.visibleRanges?.map(range => body.slice(range.from, range.to)).join('')).toBe('1-5'); + } + }); + + it('exposes a single native wiki link for styling without inventing an overall link', () => { + const body = '[[#^ref-1|1]]'; + const group = find(body)[0]; + expect(group.numbers).toEqual([1]); + expect(group.linked).toBe(true); + expect(group.outerLinkTarget).toBeUndefined(); + expect(group.tokens?.map(token => body.slice(token.from, token.to))).toEqual(['1']); + }); }); diff --git a/tests/editor.test.ts b/tests/editor.test.ts index ca6609f..79d7878 100644 --- a/tests/editor.test.ts +++ b/tests/editor.test.ts @@ -16,7 +16,8 @@ function setup(source = original) { const parse = vi.fn((text: string, sourcePath: string) => new CitationDocument(text, sourcePath, settings)); const closePreview = vi.fn(); const hover = vi.fn(); - const owner = { settings, parse, closePreview, hover } as unknown as CitationPreview; + const openCitation = vi.fn(() => true); + const owner = { settings, parse, closePreview, hover, openCitation } as unknown as CitationPreview; const compartment = new Compartment(); const info = { file: { path } } as MarkdownFileInfo; const view = new EditorView({ @@ -28,7 +29,9 @@ function setup(source = original) { views.push(view); const marks = () => Array.from(view.dom.querySelectorAll('.crp-editor-citation')); const reconfigure = () => view.dispatch({ effects: compartment.reconfigure(citationEditorExtension(owner)) }); - return { view, settings, marks, reconfigure, parse, closePreview, hover }; + const colors = () => Array.from(view.dom.querySelectorAll('.crp-editor-link')); + const numbers = () => Array.from(view.dom.querySelectorAll('.crp-editor-number')); + return { view, settings, marks, colors, numbers, reconfigure, parse, closePreview, hover, openCitation }; } afterEach(() => { @@ -107,4 +110,85 @@ describe('editor integration with real CodeMirror state', () => { vi.advanceTimersByTime(120); expect(parse).toHaveBeenCalledOnce(); }); + + it('colors visible citation labels without coloring Markdown destinations or escaping', () => { + const source = original.replace('Evidence [1–3].', + String.raw`Evidence \[[1](<#^ref-1>)\] and \[[1](#^ref-1)–[3](#^ref-3)\].`); + const { colors, hover } = setup(source); + const visible = colors().map(mark => mark.textContent).join(''); + expect(visible).toBe('[1][1–3]'); + expect(visible).not.toMatch(/ref|\^|\\|[<>]/); + expect(colors().every(mark => mark.classList.contains('crp-link-blue'))).toBe(true); + colors()[0].dispatchEvent(new MouseEvent('mouseover', { bubbles: true, ctrlKey: true })); + expect(hover).not.toHaveBeenCalled(); + }); + + it('navigates plain visible number tokens on modifier-click and leaves ordinary editing clicks alone', () => { + const { numbers, openCitation } = setup(); + expect(numbers().map(mark => mark.textContent)).toEqual(['1', '3']); + const ordinary = new MouseEvent('click', { bubbles: true, cancelable: true }); + numbers()[0].dispatchEvent(ordinary); + expect(openCitation).not.toHaveBeenCalled(); + expect(ordinary.defaultPrevented).toBe(false); + + const modified = new MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: true }); + numbers()[1].dispatchEvent(modified); + expect(openCitation).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ source: original, sourcePath: path }), + expect.objectContaining({ numbers: [1, 2, 3] }), 3, modified); + expect(modified.defaultPrevented).toBe(true); + }); + + it('leaves explicit links including a whole-range link to native editor navigation', () => { + const source = original.replace('Evidence [1–3].', 'Evidence [1-3](#^ref-1) and [1](#^ref-1).'); + const { colors, numbers, openCitation } = setup(source); + expect(colors().map(mark => mark.textContent).join('')).toBe('1-31'); + expect(numbers()).toHaveLength(0); + for (const mark of colors()) { + mark.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: true })); + } + expect(openCitation).not.toHaveBeenCalled(); + }); + + it('keeps custom hover on repeated mixed tokens even when their preview numbers deduplicate to one', () => { + const source = original.replace('Evidence [1–3].', 'Evidence [1,[1](#^ref-1)].'); + const { marks, numbers, hover } = setup(source); + expect(marks()).toHaveLength(1); + expect(numbers().map(mark => mark.textContent)).toEqual(['1']); + const event = new MouseEvent('mouseover', { bubbles: true, ctrlKey: true }); + numbers()[0].dispatchEvent(event); + expect(hover).toHaveBeenCalledWith(event, marks()[0], + expect.objectContaining({ source }), expect.objectContaining({ numbers: [1], linked: true }), true); + }); + + it('removes clickable decoration immediately during an edit before the debounced reparse', () => { + vi.useFakeTimers(); + const { view, colors, numbers, openCitation } = setup(); + const oldNumber = numbers()[0]; + view.dispatch({ changes: { from: original.indexOf('^ref-3'), to: original.indexOf('^ref-3') + 6, insert: '^other-3' } }); + expect(colors()).toHaveLength(0); + expect(numbers()).toHaveLength(0); + oldNumber.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: true })); + expect(openCitation).not.toHaveBeenCalled(); + vi.advanceTimersByTime(120); + expect(colors()).toHaveLength(0); + expect(numbers()).toHaveLength(0); + }); + + it('disables links independently of group previews and applies the theme color preference', () => { + const { settings, colors, numbers, marks, reconfigure, hover } = setup(); + settings.citationLinks = false; + reconfigure(); + expect(colors()).toHaveLength(0); + expect(numbers()).toHaveLength(0); + expect(marks()).toHaveLength(1); + marks()[0].dispatchEvent(new MouseEvent('mouseover', { bubbles: true, ctrlKey: true })); + expect(hover).toHaveBeenCalledOnce(); + settings.citationLinks = true; + settings.citationColor = 'theme'; + reconfigure(); + expect(colors().length).toBeGreaterThan(0); + expect(colors().every(mark => mark.classList.contains('crp-link-theme'))).toBe(true); + expect(colors().some(mark => mark.classList.contains('crp-link-blue'))).toBe(false); + }); }); diff --git a/tests/main.test.ts b/tests/main.test.ts index 7915110..6c44b4d 100644 --- a/tests/main.test.ts +++ b/tests/main.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { Component, TFile, type App, type MarkdownPostProcessorContext, type MarkdownRenderChild, type PluginManifest } from 'obsidian'; +import { Component, TFile, type App, type Editor, type EditorTransaction, type MarkdownFileInfo, type MarkdownPostProcessorContext, type MarkdownRenderChild, type PluginManifest } from 'obsidian'; import CitationPreview from '../src/main'; import type { NativeHoverParent } from '../src/popover'; import { installTestDomMethods, registeredCommands, registeredProcessors } from './mocks/obsidian'; @@ -39,7 +39,7 @@ const manifest: PluginManifest = { }; const plugins: CitationPreview[] = []; -async function setup(note = source) { +async function setup(note = source, nativeAdapter = true) { const workspaceEvents = new HostEvents(); const vaultEvents = new HostEvents(); const metadataEvents = new HostEvents(); @@ -47,6 +47,7 @@ async function setup(note = source) { const file = Object.assign(new TFile(), { path: 'Paper.md' }); const corePlugin = { enabled: true }; const trigger = vi.fn<(_name: string, _payload: HoverLink) => void>(); + const openLinkText = vi.fn(async () => {}); const originalFactory = vi.fn((_context: { state: object }, _file: TFile, _subpath: string) => { const previewEl = document.createElement('div'); const embedEl = document.createElement('div'); @@ -59,13 +60,13 @@ async function setup(note = source) { const factories = { md: originalFactory }; const app = { workspace: { - containerEl, trigger, on: workspaceEvents.on.bind(workspaceEvents), + containerEl, trigger, openLinkText, on: workspaceEvents.on.bind(workspaceEvents), onLayoutReady: (callback: () => void) => callback(), getLeavesOfType: () => [], updateOptions: vi.fn() }, vault: { on: vaultEvents.on.bind(vaultEvents) }, metadataCache: { on: metadataEvents.on.bind(metadataEvents) }, internalPlugins: { getPluginById: (id: string) => id === 'page-preview' ? corePlugin : undefined }, - embedRegistry: { embedByExtension: factories } + embedRegistry: nativeAdapter ? { embedByExtension: factories } : undefined } as unknown as App; const plugin = new CitationPreview(app, manifest); plugins.push(plugin); @@ -96,7 +97,7 @@ async function setup(note = source) { await embed.loadFile(); return embed.containerEl; }; - return { plugin, corePlugin, containerEl, process, processPlain, trigger, render, owners, file, + return { plugin, corePlugin, containerEl, process, processPlain, trigger, openLinkText, render, owners, file, factories, originalFactory, workspaceEvents, vaultEvents, metadataEvents }; } @@ -263,13 +264,13 @@ describe('native Page preview host integration', () => { } }); - 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'; + it('uses the nearest plain-text bibliography without filling its missing entry from a farther list', async () => { + const note = 'Nearest [1–3].\n\n1. Main first. ^ref-1\n3. Main third. ^ref-3' + + '\n\n## Any title\n1. Supplement first. ^sref-1\n2. Supplement second. ^sref-2\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'] + [1, 'Main first.'], [2, 'Reference not found'], [3, 'Main third.'] ]); }); @@ -306,8 +307,11 @@ describe('native Page preview host integration', () => { const outerHover = vi.fn(); containerEl.addEventListener('mouseover', outerHover); await process(paragraph); - expect(single.closest('.crp-citation')).toBeNull(); - expect(anchor(paragraph).contains(first)).toBe(true); + const singleWrapper = single.closest('.crp-citation'); + const groupWrapper = first.closest('.crp-citation'); + expect(singleWrapper).not.toBeNull(); + expect(singleWrapper?.hasAttribute('tabindex')).toBe(false); + expect(groupWrapper).not.toBeNull(); const nativeEvent = mouseover(single); expect(outerHover).toHaveBeenCalledExactlyOnceWith(nativeEvent); @@ -315,7 +319,7 @@ describe('native Page preview host integration', () => { const groupEvent = mouseover(first); mouseover(last, { relatedTarget: first }); expect(trigger).toHaveBeenCalledExactlyOnceWith('hover-link', expect.objectContaining({ - event: groupEvent, targetEl: anchor(paragraph) + event: groupEvent, targetEl: groupWrapper })); expect(outerHover).toHaveBeenCalledOnce(); }); @@ -345,7 +349,7 @@ describe('native Page preview host integration', () => { if (!owner) throw new Error('Reading renderer did not receive its child component.'); const ownerTeardown = vi.fn(); owner.register(ownerTeardown); - expect(registeredCommands(plugin)).toHaveLength(0); + expect(registeredCommands(plugin).map(command => command.id)).toEqual(['add-missing-reference-anchors']); plugin.unload(); plugins.splice(plugins.indexOf(plugin), 1); @@ -359,4 +363,138 @@ describe('native Page preview host integration', () => { mouseover(target); expect(trigger).not.toHaveBeenCalled(); }); + + it('shows the explicit result above the expanded whole-link range in a single native preview', async () => { + const note = 'See [1-5](#^ref-1).\n\n' + Array.from({ length: 5 }, (_, i) => `${i + 1}. Entry ${i + 1}. ^ref-${i + 1}`).join('\n'); + const { process, render, plugin, file } = await setup(note); + const paragraph = document.createElement('p'); + paragraph.append('See '); + const existing = paragraph.appendChild(document.createElement('a')); + existing.href = '#^ref-1'; + existing.textContent = '1-5'; + paragraph.append('.'); + await process(paragraph); + mouseover(anchor(paragraph)); + const preview = await render(); + const lists = preview.querySelectorAll('.el-ol > ol'); + expect(lists).toHaveLength(2); + expect(preview.querySelectorAll('hr')).toHaveLength(1); + expect(Array.from(lists[0].children, item => item.textContent)).toEqual(['Entry 1.']); + expect(Array.from(lists[1].children, item => item.textContent)).toEqual(['Entry 1.', 'Entry 2.', 'Entry 3.', 'Entry 4.', 'Entry 5.']); + expect(existing.getAttribute('href')).toBe('#^ref-1'); + expect(existing.querySelector('a')).toBeNull(); + expect([...plugin.parse(note, file.path).previewGroups.values()][0].markdown).toContain('\n\n---\n\n'); + }); + + it('opens resolved anchored references and unanchored entries without writing the note', async () => { + const { plugin, file, openLinkText } = await setup(); + const anchored = plugin.parse(source, file.path); + expect(plugin.openCitation(anchored, anchored.groups[0], 3, { ctrlKey: true })).toBe(true); + expect(openLinkText).toHaveBeenLastCalledWith('#^ref-3', file.path, true, undefined); + + const unanchoredSource = 'Evidence [1,2].\n\n## References\n1. Smith J. Atmospheric waves[J]. Journal of Climate, 2024, 10: 1-9.\n2. Doe A. Coastal flooding[J]. Ocean Science, 2023, 9: 10-20.'; + const unanchored = plugin.parse(unanchoredSource, file.path); + expect(unanchored.groups).toHaveLength(1); + expect(plugin.openCitation(unanchored, unanchored.groups[0], 2, {})).toBe(true); + expect(openLinkText).toHaveBeenLastCalledWith(file.path, file.path, false, { eState: { line: 4 } }); + expect(unanchored.source).toBe(unanchoredSource); + plugin.settings.citationLinks = false; + expect(plugin.openCitation(unanchored, unanchored.groups[0], 2, {})).toBe(false); + expect(openLinkText).toHaveBeenCalledTimes(2); + }); + + it('refuses navigation when the selected group is incomplete', async () => { + const note = 'Evidence [1-3].\n\n1. First. ^ref-1\n3. Third. ^ref-3'; + const { plugin, file, openLinkText } = await setup(note); + const model = plugin.parse(note, file.path); + expect(model.groups).toHaveLength(1); + expect(plugin.openCitation(model, model.groups[0], 1, {})).toBe(false); + expect(openLinkText).not.toHaveBeenCalled(); + }); + + it('keeps link styling, navigation and the manual command available without the private hover adapter', async () => { + const { plugin, processPlain, trigger, openLinkText } = await setup(source, false); + const paragraph = await processPlain(); + const target = anchor(paragraph); + mouseover(target); + expect(trigger).not.toHaveBeenCalled(); + expect(target.classList.contains('crp-resolved')).toBe(true); + const generated = target.querySelector('a[data-crp-number="1"]'); + expect(generated).not.toBeNull(); + generated?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + expect(openLinkText).toHaveBeenCalledWith('#^ref-1', 'Paper.md', false, undefined); + expect(registeredCommands(plugin).map(command => command.id)).toContain('add-missing-reference-anchors'); + }); + + it('previews a mixed repeated-number group whose visible tokens deduplicate to one reference', async () => { + const note = String.raw`See \[1,[1](#^ref-1)\].` + '\n\n1. First reference. ^ref-1'; + const { process, trigger, render } = await setup(note); + const paragraph = document.createElement('p'); + paragraph.append('See [1,'); + const native = paragraph.appendChild(document.createElement('a')); + native.href = '#^ref-1'; + native.textContent = '1'; + paragraph.append('].'); + await process(paragraph); + const wrapper = anchor(paragraph); + const added = wrapper.querySelector('a.crp-reference-link'); + expect(added).not.toBeNull(); + expect(wrapper.getAttribute('tabindex')).toBe('0'); + mouseover(added!); + expect(trigger).toHaveBeenCalledOnce(); + expect(Array.from((await render()).querySelectorAll('li'), item => item.textContent)).toEqual(['First reference.']); + }); + + it('rebinds the same plain citation occurrence when the nearest recognized list changes', async () => { + const firstEntry = '1. Alpha A. First list[J]. Journal of Climate, 2024, 10: 1-9.'; + const note = `See [1].\n\n## First collection\n${firstEntry}\n\n## Second collection\n1. Beta B. Second list[J]. Ocean Science, 2023, 9: 10-20.`; + const { processPlain, render, metadataEvents, file, openLinkText, plugin } = await setup(note); + const paragraph = await processPlain(); + const wrapper = anchor(paragraph); + mouseover(wrapper); + expect((await render()).textContent).toContain('First list'); + const revised = note.replace(firstEntry, '1. Start an ordinary task.'); + metadataEvents.emit('changed', file, revised); + expect(anchor(paragraph)).toBe(wrapper); + mouseover(wrapper); + expect((await render()).textContent).toContain('Second list'); + const added = wrapper.querySelector('a.crp-reference-link'); + added?.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + const model = plugin.parse(revised, file.path); + const entry = model.reference(model.groups[0], 1); + expect(entry?.markdown).toContain('Second list'); + expect(openLinkText).toHaveBeenLastCalledWith(file.path, file.path, false, { eState: { line: entry?.line } }); + }); + + it('adds missing anchors only when the manual command runs and uses one editor transaction', async () => { + let buffer = 'Evidence [1-2].\r\n\r\n## References\r\n1. Smith J. Atmospheric waves[J]. Journal of Climate, 2024, 10: 1-9.\r\n2. Doe A. Coastal flooding[J]. Ocean Science, 2023, 9: 10-20.\r\n'; + const original = buffer; + const { plugin, file, processPlain } = await setup(buffer); + await processPlain(); + const transaction = vi.fn((tx: EditorTransaction) => { + const toOffset = (position: { line: number; ch: number }) => { + let offset = 0; + for (let line = 0; line < position.line; line++) offset = buffer.indexOf('\n', offset) + 1; + return offset + position.ch; + }; + const changes = (tx.changes ?? []).map(change => ({ from: toOffset(change.from), to: toOffset(change.to ?? change.from), text: change.text })); + for (const change of changes.sort((left, right) => right.from - left.from)) buffer = buffer.slice(0, change.from) + change.text + buffer.slice(change.to); + }); + const editor = { + getValue: () => buffer, + offsetToPos: (offset: number) => ({ line: buffer.slice(0, offset).split('\n').length - 1, ch: offset - buffer.lastIndexOf('\n', offset - 1) - 1 }), + transaction + } as unknown as Editor; + expect(buffer).toBe(original); + const command = registeredCommands(plugin).find(item => item.id === 'add-missing-reference-anchors'); + expect(command?.editorCallback).toBeTypeOf('function'); + command?.editorCallback?.(editor, { file } as MarkdownFileInfo); + expect(transaction).toHaveBeenCalledOnce(); + expect(buffer).toContain('^ref-1'); + expect(buffer).toContain('^ref-2'); + expect(buffer.replace(/ \^ref-[12]/g, '')).toBe(original); + expect(plugin.parse(buffer, file.path).references.anchors.size).toBe(2); + command?.editorCallback?.(editor, { file } as MarkdownFileInfo); + expect(transaction).toHaveBeenCalledOnce(); + }); }); diff --git a/tests/popover.test.ts b/tests/popover.test.ts index 04d5b64..47faaf9 100644 --- a/tests/popover.test.ts +++ b/tests/popover.test.ts @@ -100,6 +100,25 @@ describe('native Page preview Markdown embed', () => { expect(render).not.toHaveBeenCalled(); }); + it('keeps both whole-link results and their separator when Markdown rendering fails', async () => { + const { owner, previewEl, factories, file } = setup(); + vi.spyOn(MarkdownRenderer, 'render').mockRejectedValue(new Error('Renderer unavailable')); + const result = factories.md({ state: requestPreview(owner, file.path, { + ...preview, + sections: [ + { title: 'Linked reference', markdown: '1. First', entries: ['First'], numbers: [1] }, + { title: 'Citation group', markdown: '1. First\n1. Second', entries: ['First', 'Second'], numbers: [1, 2] } + ] + }) }, file, '^ref-1'); + await result.loadFile(); + expect(previewEl.querySelectorAll('.el-ol > ol')).toHaveLength(2); + expect(previewEl.querySelectorAll('hr')).toHaveLength(1); + expect(Array.from(previewEl.querySelectorAll('li'), item => [item.value, item.textContent])).toEqual([[1, 'First'], [1, 'First'], [2, 'Second']]); + await result.loadFile(); + expect(previewEl.querySelectorAll('.crp-native-content')).toHaveLength(1); + expect(previewEl.querySelectorAll('hr')).toHaveLength(1); + }); + it('uses the host loader when the preview renderer is unavailable', async () => { const { owner, embed, factories, file } = setup(); const originalLoad = embed.loadFile; diff --git a/tests/reading.test.ts b/tests/reading.test.ts index 6387f9c..fd129c5 100644 --- a/tests/reading.test.ts +++ b/tests/reading.test.ts @@ -1,6 +1,8 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from 'vitest'; import { decorateReadingCitations } from '../src/reading'; +import { CitationDocument } from '../src/model'; +import { DEFAULT_SETTINGS } from '../src/types'; import type { CitationGroup } from '../src/types'; function group(label = '[1–10]', linked = false, from = 0): CitationGroup { @@ -180,3 +182,184 @@ describe('reading view citation decoration', () => { expect(triggers[0].element.ownerDocument).toBe(otherDocument); }); }); + +describe('resolved reading links', () => { + const references = '\n\n' + Array.from({ length: 5 }, (_, index) => + `[${index + 1}] Author ${index + 1}. Reference text. ^ref-${index + 1}`).join('\n'); + const modelFor = (citation: string) => new CitationDocument(citation + references, 'Paper.md', DEFAULT_SETTINGS); + + it('links displayed tokens in their original order instead of expanded or deduplicated numbers', () => { + const model = modelFor('[3,1-5,3]'); + const root = fixture('

Evidence [3,1-5,3].

'); + const before = root.textContent; + const onNavigate = vi.fn(); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate, settings: DEFAULT_SETTINGS }); + expect(trigger.element.classList.contains('crp-resolved')).toBe(true); + expect(trigger.element.classList.contains('crp-link-blue')).toBe(true); + const anchors = Array.from(root.querySelectorAll('a')); + expect(anchors.map(anchor => anchor.textContent)).toEqual(['3', '1', '5', '3']); + expect(anchors.map(anchor => anchor.getAttribute('href'))).toEqual(['#^ref-3', '#^ref-1', '#^ref-5', '#^ref-3']); + anchors[2].dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + expect(onNavigate).toHaveBeenCalledExactlyOnceWith(model, model.groups[0], 5, expect.any(MouseEvent)); + expect(root.textContent).toBe(before); + trigger.dispose(); + expect(root.querySelector('a')).toBeNull(); + expect(root.querySelector('sup')?.textContent).toBe('[3,1-5,3]'); + expect(root.textContent).toBe(before); + }); + + it('styles a single native link without adding a second keyboard stop or intercepting its click', () => { + const model = modelFor('[1](#^ref-1)'); + const root = fixture('

See 1.

'); + const native = root.querySelector('a')!; + const nativeClick = vi.fn((event: Event) => event.preventDefault()); + native.addEventListener('click', nativeClick); + const onNavigate = vi.fn(); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate, settings: DEFAULT_SETTINGS }); + expect(trigger.element.textContent).toBe('1'); + expect(trigger.element.classList.contains('crp-resolved')).toBe(true); + expect(trigger.element.classList.contains('crp-native-citation')).toBe(true); + expect(trigger.element.hasAttribute('tabindex')).toBe(false); + expect(trigger.element.hasAttribute('role')).toBe(false); + native.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + expect(nativeClick).toHaveBeenCalledOnce(); + expect(onNavigate).not.toHaveBeenCalled(); + trigger.dispose(); + expect(root.querySelector('a')).toBe(native); + }); + + it('does not confuse a bare prose number or a figure link with a single citation link', () => { + const model = modelFor('[1](#^ref-1)'); + const root = fixture('

Value 1, figure 1, citation 1.

'); + const triggers = decorateReadingCitations(root, model.groups, { model, settings: DEFAULT_SETTINGS }); + expect(triggers).toHaveLength(1); + expect(triggers[0].element.closest('a')?.getAttribute('href')).toBe('#^ref-1'); + expect(root.querySelector('a[href="#^fig-1"]')?.querySelector('.crp-citation')).toBeNull(); + }); + + it('preserves one whole-range native anchor and never creates nested links', () => { + const model = modelFor('[1-5](#^ref-1)'); + const root = fixture('

1-5

'); + const native = root.querySelector('a'); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate: vi.fn(), settings: DEFAULT_SETTINGS }); + expect(trigger.element.classList.contains('crp-resolved')).toBe(true); + expect(root.querySelectorAll('a')).toHaveLength(1); + expect(root.querySelector('a')).toBe(native); + expect(native?.getAttribute('href')).toBe('#^ref-1'); + trigger.dispose(); + expect(root.querySelector('a')).toBe(native); + }); + + it('adds only missing number links around existing linked tokens and preserves formatting', () => { + const model = modelFor('[1,[3](#^ref-3),5]'); + const root = fixture('

[1,3,5]

'); + const native = root.querySelector('a'); + const emphasis = root.querySelector('em'); + const strong = root.querySelector('strong'); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate: vi.fn(), settings: DEFAULT_SETTINGS }); + expect(root.querySelectorAll('a')).toHaveLength(3); + expect(root.querySelector('a[href="#^ref-3"]')).toBe(native); + expect(root.querySelector('em')).toBe(emphasis); + expect(root.querySelector('strong')).toBe(strong); + trigger.dispose(); + expect(root.querySelectorAll('a')).toHaveLength(1); + expect(root.querySelector('a')).toBe(native); + expect(root.querySelector('em')).toBe(emphasis); + expect(root.textContent).toBe('[1,3,5]'); + }); + + it('keeps a repeated mixed group available for custom hover after preview-number deduplication', () => { + const model = modelFor('[1,[1](#^ref-1)]'); + expect(model.groups[0].numbers).toEqual([1]); + const root = fixture('

[1,1]

'); + const native = root.querySelector('a'); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate: vi.fn(), settings: DEFAULT_SETTINGS }); + expect(trigger.element.classList.contains('crp-native-citation')).toBe(false); + expect(trigger.element.getAttribute('tabindex')).toBe('0'); + expect(root.querySelectorAll('a')).toHaveLength(2); + expect(root.querySelectorAll('.crp-reference-link')).toHaveLength(1); + expect(Array.from(root.querySelectorAll('a'))[1]).toBe(native); + }); + + it('does not present incomplete groups as resolved links', () => { + const model = new CitationDocument('[1-5]\n\n[1] First. ^ref-1\n[5] Fifth. ^ref-5', 'Paper.md', DEFAULT_SETTINGS); + const root = fixture('

[1-5]

'); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate: vi.fn(), settings: DEFAULT_SETTINGS }); + expect(trigger.element.classList.contains('crp-resolved')).toBe(false); + expect(root.querySelector('a')).toBeNull(); + expect(trigger.element.getAttribute('tabindex')).toBe('0'); + }); + + it('removes stale resolution and generated links after metadata changes, and restores them when valid', () => { + const model = modelFor('[1-5]'); + const root = fixture('

[1-5]

'); + const onNavigate = vi.fn(); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate, settings: DEFAULT_SETTINGS }); + const oldLink = root.querySelector('a')!; + const changed = new CitationDocument('[1-5]', 'Paper.md', DEFAULT_SETTINGS); + trigger.update(changed, undefined); + expect(trigger.element.classList.contains('crp-resolved')).toBe(false); + expect(trigger.element.classList.contains('crp-link-blue')).toBe(false); + expect(root.querySelector('a')).toBeNull(); + expect(trigger.element.hasAttribute('tabindex')).toBe(false); + oldLink.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })); + expect(onNavigate).not.toHaveBeenCalled(); + trigger.update(model, model.groups[0]); + expect(trigger.element.classList.contains('crp-resolved')).toBe(true); + expect(root.querySelectorAll('a')).toHaveLength(2); + trigger.dispose(); + trigger.update(model, model.groups[0]); + expect(root.querySelector('a')).toBeNull(); + }); + + it('withdraws resolved styling while preserving native anchors and listeners after a reference is removed', () => { + const citation = String.raw`\[[1](#^ref-1)-[5](#^ref-5)\]`; + const model = modelFor(citation); + const root = fixture('

[1-5]

'); + const native = Array.from(root.querySelectorAll('a')); + const clicked = vi.fn((event: Event) => event.preventDefault()); + native[0].addEventListener('click', clicked); + const [trigger] = decorateReadingCitations(root, model.groups, { model, onNavigate: vi.fn(), settings: DEFAULT_SETTINGS }); + expect(trigger.element.classList.contains('crp-resolved')).toBe(true); + const changed = new CitationDocument(model.source.replace('^ref-3', '^other-3'), 'Paper.md', DEFAULT_SETTINGS); + trigger.update(changed, changed.groups[0]); + expect(trigger.element.classList.contains('crp-resolved')).toBe(false); + expect(trigger.element.classList.contains('crp-link-blue')).toBe(false); + expect(Array.from(root.querySelectorAll('a'))).toEqual(native); + expect(native.map(anchor => anchor.getAttribute('href'))).toEqual(['#^ref-1', '#^ref-5']); + native[0].dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + expect(clicked).toHaveBeenCalledOnce(); + }); + + it('supports keyboard and new-pane activation only on plugin-created anchors', () => { + const model = modelFor('[1]'); + const root = fixture('

[1]

'); + const onNavigate = vi.fn(); + decorateReadingCitations(root, model.groups, { model, onNavigate, settings: DEFAULT_SETTINGS }); + const anchor = root.querySelector('a')!; + const enter = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, metaKey: true }); + anchor.dispatchEvent(enter); + expect(enter.defaultPrevented).toBe(true); + expect(onNavigate).toHaveBeenLastCalledWith(model, model.groups[0], 1, enter); + const middle = new MouseEvent('auxclick', { button: 1, bubbles: true, cancelable: true }); + anchor.dispatchEvent(middle); + expect(middle.defaultPrevented).toBe(true); + expect(onNavigate).toHaveBeenLastCalledWith(model, model.groups[0], 1, middle); + anchor.dispatchEvent(new MouseEvent('auxclick', { button: 2, bubbles: true, cancelable: true })); + expect(onNavigate).toHaveBeenCalledTimes(2); + }); + + it('switches color preferences and removes virtual links when the feature is disabled', () => { + const model = modelFor('[1]'); + const root = fixture('

[1]

'); + const settings = { ...DEFAULT_SETTINGS, citationColor: 'theme' as const }; + const [trigger] = decorateReadingCitations(root, model.groups, { model, settings, onNavigate: vi.fn() }); + expect(trigger.element.classList.contains('crp-link-theme')).toBe(true); + expect(trigger.element.classList.contains('crp-link-blue')).toBe(false); + settings.citationLinks = false; + trigger.update(model, model.groups[0]); + expect(trigger.element.classList.contains('crp-resolved')).toBe(false); + expect(root.querySelector('a')).toBeNull(); + expect(trigger.element.getAttribute('tabindex')).toBe('0'); + }); +}); diff --git a/tests/reference-lists.test.ts b/tests/reference-lists.test.ts new file mode 100644 index 0000000..11ef453 --- /dev/null +++ b/tests/reference-lists.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from 'vitest'; +import { CitationDocument } from '../src/model'; +import { detectReferenceLists, nearestReferenceList } from '../src/reference-lists'; +import { DEFAULT_SETTINGS, type ReferenceList } from '../src/types'; + +const first = 'Smith J, Lee A. Atmospheric waves. Journal of Climate, 2024, 37: 1-12.'; +const second = 'Jones B. Ocean dynamics [J]. Ocean Science, 2023, 19: 11-22.'; +const third = '王五, 李四. 重力波研究[J]. 大气科学, 2022, 46(2): 1-10.'; +const make = (body: string) => new CitationDocument(body, 'Paper.md', DEFAULT_SETTINGS); + +describe('conservative physical bibliography detection', () => { + it.each(['[1]', '[1]', '【1】', '(1)', '(1)', '1.', '1)', '1、', '1.', '**[1]**'])('recognizes numbered bibliography marker %s without a heading', marker => { + const lists = detectReferenceLists(`${marker} ${first}\n2. ${second}`); + expect(lists).toHaveLength(1); + expect([...lists[0].entries.keys()]).toEqual([1, 2]); + }); + + it('does not infer a bibliography from a heading, years, or numbered steps alone', () => { + for (const source of [ + '## References\n1. First step.\n2. Second step.', + '## Timeline\n1. In 2024 the team measured rainfall.\n2. In 2025 the team revised the model.', + '## Data\n1. 2024, 37: 1-12.\n2. 2023, 19: 11-22.', + '1. Install the Journal software in 2024.\n2. Run the climate model in 2025.' + ]) expect(detectReferenceLists(source)).toEqual([]); + }); + + it('preserves multiline entries and excludes following prose and code', () => { + const source = `Evidence [1,2].\n\n1. Smith J, Lee A. Atmospheric waves.\n Journal of Climate, 2024, 37: 1-12.\n\n2. ${second}\n\nBody after references [1].\n\n\`\`\`md\n3. ${third}\n\`\`\``; + const model = make(source); + expect(model.references.lists).toHaveLength(1); + expect(model.references.lists![0].items).toHaveLength(2); + expect(model.reference(model.groups[0], 1)?.markdown).toContain('Atmospheric waves.\nJournal'); + expect(model.groups.map(group => group.numbers)).toEqual([[1, 2], [1]]); + expect(model.references.lists![0].items.some(entry => entry.markdown.includes('Body after'))).toBe(false); + }); + + it('supports linked and wiki-linked bibliography text while preserving original Markdown', () => { + const linked = '[Fritts, D.C.; Alexander, M.J. Gravity wave dynamics. Rev. Geophys. 2003, 41, 1003. \\[CrossRef\\]](<2003-Paper.md>)'; + const wiki = `[[Journal/Other paper|${third}]]`; + const source = `Evidence [1-3].\n\n1. ${first}\n2. ${linked}\n3. ${wiki}`; + const model = make(source); + expect(model.references.lists).toHaveLength(1); + expect(model.references.lists![0].items).toHaveLength(3); + expect(model.reference(model.groups[0], 2)?.markdown).toBe(linked); + expect(model.reference(model.groups[0], 3)?.markdown).toBe(wiki); + expect(model.isResolved(model.groups[0])).toBe(true); + }); + + it('accepts a single entry with a strong identifier and a single author/year entry under a bibliography heading', () => { + expect(detectReferenceLists('1. A documented report. https://doi.org/10.1234/abcd')).toHaveLength(1); + expect(detectReferenceLists(`## 参考文献\n1. ${first}`)).toHaveLength(1); + expect(detectReferenceLists(`1. ${first}`)).toHaveLength(0); + }); + + it('separates numbering resets and sections instead of merging bibliography numbers', () => { + const source = `A [1,2].\n\n1. ${first}\n2. ${second}\n\n1. ${third}\n2. ${second}\n\n## Other chapter\n\n1. ${first}\n2. ${second}`; + const lists = detectReferenceLists(source); + expect(lists).toHaveLength(3); + expect(lists.map(list => list.items.map(entry => entry.number))).toEqual([[1, 2], [1, 2], [1, 2]]); + }); + + it('detects repeated numbers as ambiguous instead of silently assigning one entry', () => { + const model = make(`Evidence [1,2].\n\n1. ${first}\n1. ${third}\n2. ${second}`); + expect(model.groups).toHaveLength(1); + expect(model.references.lists![0].duplicates.has(1)).toBe(true); + expect(model.reference(model.groups[0], 1)).toBeUndefined(); + expect(model.isResolved(model.groups[0])).toBe(false); + }); + + it('treats repeated generic block IDs anywhere in the note as ambiguous destinations', () => { + const model = make(`Evidence [1,2].\n\n1. ${first} ^shared\n2. ${second} ^safe\n\nUnrelated paragraph. ^shared`); + expect(model.references.lists![0].duplicates.has(1)).toBe(true); + expect(model.reference(model.groups[0], 1)).toBeUndefined(); + expect(model.isResolved(model.groups[0])).toBe(false); + }); + + it('respects the pure numeric recognition setting without changing explicit links', () => { + const source = `Plain [1,2]. Linked [1](#^ref-1).\n\n1. ${first} ^ref-1\n2. ${second}`; + const model = new CitationDocument(source, 'Paper.md', { ...DEFAULT_SETTINGS, recognizePlainText: false }); + expect(model.references.lists).toBeUndefined(); + expect(model.groups).toHaveLength(1); + expect(model.groups[0].linked).toBe(true); + }); +}); + +describe('nearest bibliography selection', () => { + it('resolves identical plain labels against their nearest preceding or following physical list', () => { + const source = `Early [1,2].\n\n1. ${first}\n2. ${second}\n\n${'Other prose.\n'.repeat(80)}\nLater [1,2].\n\n## Supplementary references\n1. ${third}\n2. ${second}`; + const model = make(source); + expect(model.groups).toHaveLength(2); + expect(model.groups[0].scopeId).not.toBe(model.groups[1].scopeId); + expect(model.reference(model.groups[0], 1)?.markdown).toBe(first); + expect(model.reference(model.groups[1], 1)?.markdown).toBe(third); + expect(model.groups.every(group => model.isResolved(group))).toBe(true); + }); + + it('does not borrow a missing item from a more distant list', () => { + const source = `Evidence [1-3].\n\n1. ${first}\n3. ${second}\n\n${'Other prose.\n'.repeat(30)}\n## Supplement\n1. ${third}\n2. ${second}\n3. ${first}`; + const model = make(source); + expect(model.groups).toHaveLength(1); + expect(model.reference(model.groups[0], 2)).toBeUndefined(); + expect(model.isResolved(model.groups[0])).toBe(false); + }); + + it('chooses the following list when distances are exactly equal', () => { + const list = (id: string, from: number, to: number): ReferenceList => ({ + id, title: id, from, to, entries: new Map(), duplicates: new Set(), items: [], supplemental: false + }); + const before = list('before', 0, 10); + const after = list('after', 30, 40); + expect(nearestReferenceList([before, after], 15, 25)).toBe(after); + expect(nearestReferenceList([after, before], 15, 25)).toBe(after); + }); + + it('prefers a bibliography in the same structural chapter over a closer list in another chapter', () => { + const source = `# Paper\n## Main material\nMain [1,2].\n### References\n1. ${first}\n2. ${second}\n\n## Supplemental material\n### Early figures\nSupplement [1,2].\n\n${'Extended supplementary discussion.\n'.repeat(100)}\n### References\n1. ${third}\n2. ${second}`; + for (const document of [source, source.replace(/^(#{1,6}) .*$/gm, '$1 Arbitrary title')]) { + const model = make(document); + expect(model.groups).toHaveLength(2); + expect(model.reference(model.groups[0], 1)?.markdown).toBe(first); + expect(model.reference(model.groups[1], 1)?.markdown).toBe(third); + } + }); + + it('keeps missing chapter-local entries missing even when another chapter contains the number', () => { + const source = `# Paper\n## Main\n1. ${first}\n2. ${second}\n3. ${third}\n\n## Supplement\n### Text\nEvidence [1-3].\n\n${'More text.\n'.repeat(50)}\n### Bibliography\n1. ${second}\n3. ${first}`; + const model = make(source); + expect(model.reference(model.groups[0], 1)?.markdown).toBe(second); + expect(model.reference(model.groups[0], 2)).toBeUndefined(); + expect(model.isResolved(model.groups[0])).toBe(false); + }); +}); diff --git a/tests/scopes.test.ts b/tests/scopes.test.ts index fdddf90..3349ab5 100644 --- a/tests/scopes.test.ts +++ b/tests/scopes.test.ts @@ -17,8 +17,7 @@ function parse(body: string, entries = references): CitationDocument { } 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); + return group.numbers.map(number => model.reference(group, number)?.markdown); } describe('anchor namespaces without bibliography headings', () => { @@ -74,17 +73,18 @@ describe('anchor namespaces without bibliography headings', () => { ]) expect(parse(body).groups).toEqual([]); }); - it('marks plain citations ambiguous when multiple namespaces contain their endpoints', () => { + it('selects the nearest physical bibliography for plain citations with repeated main/supplement numbers', () => { 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(); + expect(model.groups[0].ambiguousScope).toBe(false); + expect(model.groups[0].scopeId).toMatch(/^list:/); + expect(texts(model, model.groups[0])).toEqual(['Main first.', 'Main second.', 'Main third.']); }); - it('selects a plain citation namespace only with unique number evidence', () => { + it('does not fetch a missing plain-citation number from a distant reference block', () => { 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.']); + expect(model.groups[0].scopeId).toMatch(/^list:/); + expect(texts(model, model.groups[0])).toEqual(['Main first.', undefined]); }); it('does not create references from a heading or unanchored numbered prose', () => { diff --git a/tests/settings.test.ts b/tests/settings.test.ts new file mode 100644 index 0000000..52086b5 --- /dev/null +++ b/tests/settings.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vitest'; +import { normalizeSettings } from '../src/settings'; +import { DEFAULT_SETTINGS } from '../src/types'; + +describe('persisted citation display settings', () => { + it('migrates existing settings without losing their preview preferences', () => { + expect(normalizeSettings({ maxReferences: 50, recognizePlainText: false, requireModifier: true, enableEditor: false })) + .toEqual({ ...DEFAULT_SETTINGS, maxReferences: 50, recognizePlainText: false, requireModifier: true, enableEditor: false }); + }); + + it('accepts explicit link display preferences and rejects invalid stored values', () => { + expect(normalizeSettings({ citationLinks: false, citationColor: 'theme' })).toEqual({ ...DEFAULT_SETTINGS, citationLinks: false, citationColor: 'theme' }); + expect(normalizeSettings({ citationLinks: 'false', citationColor: '