Skip to content

Commit

Permalink
Handle references within footnotes
Browse files Browse the repository at this point in the history
romaincazier committed Jan 9, 2025
1 parent 757514a commit db09826
Showing 2 changed files with 20 additions and 25 deletions.
2 changes: 1 addition & 1 deletion TextformatterFootnotes.info.php
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@

$info = [
"title" => "Footnotes",
"version" => "0.1.0",
"version" => "0.1.1",
"summary" => "Adds footnotes using Markdown Extra’s syntax, minus Markdown",
"author" => "EPRC",
"href" => "https://github.com/eprcstudio/TextformatterFootnotes",
43 changes: 19 additions & 24 deletions TextformatterFootnotes.module.php
Original file line number Diff line number Diff line change
@@ -84,21 +84,30 @@ public function ___addFootnotes($str, $options = [], $field = "") {
$references = [];
foreach($matches[0] as $key => $match) {
$identifier = $matches[1][$key];
if(!array_key_exists($identifier, $references)) {
$references[$identifier] = [
"id" => (!$options["continuous"] ? "$footnotesId:" : "") . $footnoteIndex,
"identifier" => $identifier,
"index" => $footnoteIndex,
"str" => $match
];
$footnoteIndex++;
}
// Have we already processed this identifier?
if(array_key_exists($identifier, $references)) continue;
// Are there any matching footnote?
if(!preg_match("/\[\^$identifier\]:/", $str)) continue;
$id = (!$options["continuous"] ? "$footnotesId:" : "") . $footnoteIndex;
$references[$identifier] = [
"id" => $id,
"identifier" => $identifier,
"index" => $footnoteIndex,
"str" => $match
];
// Convert references into anchor links
$ref =
"<sup id='fnref$id' class='$options[referenceClass]'>" .
"<a href='#fn$id' role='doc-noteref'>$footnoteIndex</a>" .
"</sup>";
$str = preg_replace("/\[\^$identifier\](?!:)/", $ref, $str);
$footnoteIndex++;
}

if(empty($references)) return $str;

// Get footnotes
if(!preg_match_all("/\[\^(\d+)\]\:(?:.(?!\[\^))*/", $str, $matches)) return $str;
if(!preg_match_all("/\[\^(\d+)\]:.+?(?=\[\^\d+\]:|$)/m", $str, $matches)) return $str;
$footnotes = [];
foreach($matches[0] as $key => $match) {
$identifier = $matches[1][$key];
@@ -124,20 +133,6 @@ public function ___addFootnotes($str, $options = [], $field = "") {

ksort($footnotes);

// Convert references into anchor links
$identifiers = array_column($footnotes, "identifier");
foreach($references as $reference) {
$identifier = $reference["identifier"];
// Cross-check
if(!in_array($identifier, $identifiers)) continue;
// Replace reference with anchor link
$ref =
"<sup id='fnref$reference[id]' class='$options[referenceClass]'>" .
"<a href='#fn$reference[id]' role='doc-noteref'>$reference[index]</a>" .
"</sup>";
$str = preg_replace("/\[\^$identifier\](?!:)/", $ref, $str);
}

// Append footnotes
if(!$options["outputAsArray"]) {
$str .= "\n" . $this->generateFootnotesMarkup($footnotes, $options);

0 comments on commit db09826

Please sign in to comment.