file-source-citation.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { mapMarkdownOutsideProtected } from './asset-markup/markdown-protected.js';
  2. /**
  3. * File backfill can produce the same link beside an existing citation. Only
  4. * identical labels AND targets separated by horizontal whitespace are redundant:
  5. * different locations, prose, paragraphs and table cells must stay intact.
  6. * Shared by answer repair and display/history projection; no source inference.
  7. */
  8. export function collapseAdjacentDuplicateFileCitations(markdown: string): string {
  9. if (!markdown.includes('#mavis-source=file:')) return markdown;
  10. return mapMarkdownOutsideProtected(markdown, (text) => {
  11. const citationPattern =
  12. /(?<![!\\])\[([^[\]\n]+)\]\([ \t]*(#mavis-source=file:[A-Za-z0-9_-]+)[ \t]*\)/gu;
  13. let previous: { label: string; href: string; end: number } | undefined;
  14. let cursor = 0;
  15. const parts: string[] = [];
  16. for (const match of text.matchAll(citationPattern)) {
  17. const start = match.index;
  18. const end = start + match[0].length;
  19. const lineStart = text.lastIndexOf('\n', start - 1) + 1;
  20. // Be conservative around indented code (and deeply nested lists).
  21. if (text.startsWith(' ', lineStart) || text[lineStart] === '\t') {
  22. previous = undefined;
  23. continue;
  24. }
  25. const label = match[1] ?? '';
  26. const href = match[2] ?? '';
  27. if (
  28. previous?.label === label &&
  29. previous.href === href &&
  30. /^[ \t]*$/u.test(text.slice(previous.end, start))
  31. ) {
  32. parts.push(text.slice(cursor, previous.end));
  33. cursor = end;
  34. }
  35. previous = { label, href, end };
  36. }
  37. parts.push(text.slice(cursor));
  38. return parts.join('');
  39. });
  40. }