Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,20 @@ _See supra note_ {ref-a}.

If `ref-a` is ultimately note 7, the rendered text reads `See supra note 7.` The compiler determines numbers from real `[^key]` citations before rendering, so `{key}` does not create a footnote or change numbering and can safely appear before or after the citation. An unknown `{key}` is left visible rather than being assigned a number. The previous double-braced syntax (`{{key}}`) is no longer interpolated. References and citations inside fenced code blocks or inline code spans are shown literally and never influence footnote numbering.

### Repeated footnote citations

Under **Sections & TOC**, choose **Repeated footnote references**, or use
`--repeated-footnotes reuse|full|supra` on the CLI. The default (`reuse`)
preserves the original numbering. The `full` mode assigns each occurrence
a new number with the full definition. The `supra` mode assigns each
occurrence a new number, uses _Id._ for consecutive citations to the same
defined key, and _See supra_ note {key}. for nonconsecutive repeats, with
the final note number linked to the first full citation. The word “note”
and the number are not italicized. Numbering depends on citation order,
not page or paragraph placement. The source Markdown, code spans, fences,
and quotation-local citations are unchanged. This option applies to PDF
output, including endnotes; Word exports retain their existing behavior.

## Optional PDF/A-4 output

Standard PDF remains the default. Choose **PDF/A-4 (ISO 19005-4:2020)**
Expand Down
1 change: 1 addition & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,7 @@ def metadata_value(name: str) -> str | None:
smart_quotes=truthy("smart_quotes"),
quote_inline_number_footnotes=truthy("quote_inline_number_footnotes"),
quote_source_before_footnotes=truthy("quote_source_before_footnotes"),
repeated_footnotes=request.form.get("repeated_footnotes", "reuse"),
emoji_style=emoji_style,
emoji_pack=emoji_pack,
underline_links=truthy("underline_links"),
Expand Down
89 changes: 86 additions & 3 deletions pdf_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def transform(segment: str) -> str:



def protect_inline_code(text: str) -> tuple[str, dict[str, str]]:
def protect_inline_code(text: str, *, preserve_source: bool = False) -> tuple[str, dict[str, str]]:
"""Protect backtick code spans and escaped backticks from Markdown parsing.

Code spans use matching backtick-run lengths. Newlines become spaces;
Expand Down Expand Up @@ -290,7 +290,7 @@ def token(markup: str) -> str:
slash_count += 1
if slash_count % 2:
result.append(text[cursor:index - 1])
result.append(token("`"))
result.append(token(text[index - 1:index + 1] if preserve_source else "`"))
index += 1
cursor = index
continue
Expand Down Expand Up @@ -322,7 +322,10 @@ def token(markup: str) -> str:
if content.startswith(" ") and content.endswith(" ") and content.strip(" "):
content = content[1:-1]
result.append(text[cursor:index])
result.append(token(f'<font name="Courier">{html.escape(content, quote=False)}</font>'))
result.append(token(
text[index:closing_end] if preserve_source
else f'<font name="Courier">{html.escape(content, quote=False)}</font>'
))
index = closing_end
cursor = index

Expand Down Expand Up @@ -446,6 +449,7 @@ def __init__(
smart_quotes: bool = False,
quote_inline_number_footnotes: bool = False,
quote_source_before_footnotes: bool = False,
repeated_footnotes: str = "reuse",
emoji_style: str = "twemoji",
emoji_pack: Path | None = None,
underline_links: bool = True,
Expand All @@ -461,6 +465,9 @@ def __init__(
self.smart_quotes = smart_quotes
self.quote_inline_number_footnotes = quote_inline_number_footnotes
self.quote_source_before_footnotes = quote_source_before_footnotes
if repeated_footnotes not in {"reuse", "full", "supra"}:
raise ValueError("Unknown repeated footnote mode.")
self.repeated_footnotes = repeated_footnotes
validate_emoji_style(emoji_style, emoji_pack)
self.emoji_style = emoji_style
self.emoji_pack = emoji_pack
Expand All @@ -486,6 +493,8 @@ def __init__(
self.body_text, self.note_defs = extract_footnotes(body)
self.body_text = normalize_page_breaks(self.body_text)
self._prepare_signature_directives()
if self.repeated_footnotes != "reuse":
self.expand_repeated_footnotes()
self.prime_note_numbers()
self.styles = self._styles()

Expand Down Expand Up @@ -999,6 +1008,75 @@ def note_number(self, key: str) -> int:
def note_destination(number: int) -> str:
return f"footnote-{number}"

def expand_repeated_footnotes(self) -> None:
"""Give repeated document citations unique keys without changing the source file."""
prefix = "pdfcompiler-repeat-"
reserved = self.body_text + "\n" + "\n".join(self.note_defs) + "\n" + "\n".join(self.note_defs.values())
while prefix in reserved:
prefix += "x"
seen: set[str] = set()
previous: str | None = None
serial = 0

def expand(text: str, local_notes: dict[str, str]) -> str:
nonlocal previous, serial

def replace(match: re.Match[str]) -> str:
nonlocal previous, serial
key = match.group(1)
if key in local_notes:
return match.group(0)
consecutive = key == previous
previous = key
# Do not turn an unresolved reference into an apparently valid citation.
if key not in self.note_defs or key not in seen:
seen.add(key)
return match.group(0)
serial += 1
alias = f"{prefix}{serial}"
if self.repeated_footnotes == "full":
self.note_defs[alias] = self.note_defs[key]
elif consecutive:
self.note_defs[alias] = "_Id._"
else:
self.note_defs[alias] = f"_See supra_ note {{{key}}}."
return f"[^{alias}]"

return self.note_ref_re.sub(replace, text)

# Fence boundaries must be identified before shielding inline code. Preserve
# original code spans rather than replacing them with rendered HTML.
lines = self.body_text.splitlines()
index = 0
fence_marker: str | None = None
while index < len(lines):
fence_marker, boundary = advance_code_fence(lines[index], fence_marker)
if boundary or fence_marker is not None:
index += 1
continue
start = index
if lines[index].startswith(">"):
while index < len(lines) and lines[index].startswith(">"):
index += 1
quote_lines = [line.lstrip(">").strip() for line in lines[start:index]]
local_notes = self.quotation_local_notes(quote_lines) if (
quote_lines and re.fullmatch(r"\[!QUOTE\]\s*", quote_lines[0], re.IGNORECASE)
) else {}
else:
while index < len(lines) and not lines[index].startswith(">"):
_, boundary = advance_code_fence(lines[index], None)
if boundary:
break
index += 1
local_notes = {}
chunk = "\n".join(lines[start:index])
shielded, spans = protect_inline_code(chunk, preserve_source=True)
expanded = expand(shielded, local_notes)
for token, original in spans.items():
expanded = expanded.replace(token, original)
lines[start:index] = expanded.split("\n")
self.body_text = "\n".join(lines)

def prime_note_numbers(self) -> None:
"""Assign final note numbers from real footnote citations before rendering."""
shielded, _ = protect_inline_code(self.body_text)
Expand Down Expand Up @@ -1560,6 +1638,10 @@ def main() -> int:
action="store_true",
help="Place [!SOURCE] attribution before quote-local footnotes (off by default)",
)
parser.add_argument(
"--repeated-footnotes", choices=("reuse", "full", "supra"), default="reuse",
help="Reuse note numbers, or generate full or Id./supra notes for repeated citations",
)
args = parser.parse_args()

output = args.output or args.source.with_suffix(".pdf")
Expand Down Expand Up @@ -1587,6 +1669,7 @@ def main() -> int:
smart_quotes=args.smart_quotes,
quote_inline_number_footnotes=args.quote_inline_number_footnotes,
quote_source_before_footnotes=args.quote_source_before_footnotes,
repeated_footnotes=args.repeated_footnotes,
emoji_style=args.emoji_style,
emoji_pack=args.emoji_pack,
**presentation,
Expand Down
8 changes: 8 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,14 @@ <h1>PDF Compiler</h1>
</select>
<small>Endnotes keep global numbering and links. H1 grouping collects notes at the document end under the H1 where each note is first cited.</small>
</label>
<label>Repeated footnote references
<select name="repeated_footnotes">
<option value="reuse">Reuse original footnote number</option>
<option value="full">New footnote with full citation</option>
<option value="supra">New footnote with automatic Id. / supra citation</option>
</select>
<small>Automatic short citations italicize Id. or See supra, leaving note and its linked number upright. Quotation-local footnotes remain independent.</small>
</label>
<label class="check full"><input type="checkbox" name="quote_inline_number_footnotes"> Enable inline numbered footnotes (<code>[11]</code>) in sourced blockquotes
<small>Off by default to avoid interpreting ordinary bracketed text as a citation. With this on, <code>[11]</code> and <code>[11]:</code> work only inside <code>[!QUOTE]</code> blocks with matching local definitions. Standard <code>[^11]</code> works without this setting.</small>
</label>
Expand Down
46 changes: 44 additions & 2 deletions tests/test_footnote_number_references.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@


class FootnoteNumberReferenceTests(unittest.TestCase):
def renderer_for(self, markdown: str):
def renderer_for(self, markdown: str, **kwargs):
temp = TemporaryDirectory()
root = Path(temp.name)
source = root / "document.md"
source.write_text(markdown, encoding="utf-8")
renderer = PdfRenderer(source, root / "output.pdf")
renderer = PdfRenderer(source, root / "output.pdf", **kwargs)
return temp, renderer

def test_interpolates_assigned_note_number(self):
Expand Down Expand Up @@ -62,6 +62,48 @@ def test_repeated_citation_keeps_one_number(self):
self.assertEqual(renderer.order, ["ref-a"])
self.assertEqual(renderer.nums["ref-a"], 1)

def test_automatic_short_notes(self):
temp, renderer = self.renderer_for(
"A.[^a] Again.[^a]\n\nB.[^b]\n\nA again.[^a] Again.[^a]\n\n"
"[^a]: Source A.\n[^b]: Source B.\n",
repeated_footnotes="supra",
)
self.addCleanup(temp.cleanup)
self.assertEqual(len(renderer.order), 5)
self.assertEqual(renderer.nums["a"], 1)
self.assertEqual(renderer.nums["b"], 3)
definitions = [renderer.note_defs[key] for key in renderer.order]
self.assertEqual(definitions, [
"Source A.", "_Id._", "Source B.", "_See supra_ note {a}.", "_Id._",
])
rendered, _ = renderer.markdown_inline(definitions[3], False)
self.assertEqual(rendered, '<i>See supra</i> note <link href="#footnote-1">1</link>.')
self.assertEqual(renderer.build()[1], 5)
self.assertIn("Again.[^a]", renderer.source.read_text(encoding="utf-8"))

def test_full_repeated_notes(self):
temp, renderer = self.renderer_for(
"A.[^a] Again.[^a]\n\n[^a]: Source A.\n",
repeated_footnotes="full",
)
self.addCleanup(temp.cleanup)
self.assertEqual([renderer.note_defs[key] for key in renderer.order],
["Source A.", "Source A."])

def test_short_notes_ignore_literal_and_quote_local_references(self):
temp, renderer = self.renderer_for(
"A.[^a]\n\n`[^b]`\n\n~~~markdown\n[^b]\n~~~\n\n"
"> [!QUOTE]\n> Quoted.[^b]\n> [^b]: Local.\n\n"
"Again.[^a]\n\n[^a]: Source A.\n[^b]: Source B.\n",
repeated_footnotes="supra",
)
self.addCleanup(temp.cleanup)
self.assertEqual([renderer.note_defs[key] for key in renderer.order],
["Source A.", "_Id._"])
self.assertIn("> Quoted.[^b]", renderer.body_text)
self.assertIn("`[^b]`", renderer.body_text)
self.assertEqual(renderer.build()[1], 2)

def test_single_brace_reference_with_whitespace(self):
temp, renderer = self.renderer_for(
"Alpha.[^ref-a]\n\n[^ref-a]: A.\n"
Expand Down
Loading