forked from markdown-it/markdown-it-footnote
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
1323 lines (1087 loc) · 43.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Process footnotes
//
import { strict as assert } from 'assert';
////////////////////////////////////////////////////////////////////////////////
// Renderer partials
interface FootnotePluginOptions {
numberSequence?: Array<any>;
modeOverride?: string;
sortOrder: number;
refCombiner?: string;
}
interface GenericInfoParameters {
options: any; // markdown_it options object
plugin_options: FootnotePluginOptions;
env: any; // markdown_it environment object
self: any; // reference to this plugin instance
}
interface RenderInfoParameters extends GenericInfoParameters {
tokens: Array<any>; // array of tokens
idx: number; // index of current token in token array
}
interface footnoteMetaInfo {
id: number;
label?: string;
labelOverride?: string;
mode?: string;
content?: string;
tokens?: Array<any>;
count: number;
}
function anchorFnDefault(n: number, excludeSubId: number, baseInfo: RenderInfoParameters) {
const env = baseInfo.env;
assert.ok(env != null);
let prefix = '';
if (typeof env.docId === 'string' && env.docId.length > 0) {
prefix = '-' + env.docId + '-';
}
return prefix + n;
}
function captionFnDefault(n, baseInfo: RenderInfoParameters) {
//return '[' + n + ']';
return '' + n;
}
function headerFnDefault(category, baseInfo: GenericInfoParameters) {
switch (category) {
case 'aside':
return 'Side Notes';
case 'section':
return 'Section Notes';
case 'end':
return 'Endnotes';
default: // used for error category, e.g. 'Error::Unused'
return category;
}
}
function determine_footnote_symbol(idx: number, info: footnoteMetaInfo, baseInfo: GenericInfoParameters): string {
const plugin_options = baseInfo.plugin_options;
assert.ok(plugin_options != null);
// rule to construct the printed label:
//
// mark = labelOverride /* || info.label */ || idx;
const label = info.labelOverride;
if (label) {
return label;
}
if (plugin_options.numberSequence == null || plugin_options.numberSequence.length === 0) {
return '' + idx;
}
const len = plugin_options.numberSequence.length;
if (idx >= len) {
// is last slot numeric or alphanumerically?
const slot = plugin_options.numberSequence[len - 1];
if (Number.isFinite(slot)) {
const delta = idx - len + 1;
return '' + (slot + delta);
}
// non-numerical last slot --> duplicate, triplicate, etc.
const dupli = (idx / len) | 0; // = int(x mod N)
const remainder = idx % len;
const core = plugin_options.numberSequence[remainder];
let str = '' + core;
for (let i = 1; i < dupli; i++) {
str += core;
}
return str;
}
return '' + plugin_options.numberSequence[idx];
}
const bunched_mode_classes = [ '', 'footnote-bunched-ref-ref', 'footnote-bunched-ref-text' ];
function generateFootnoteRefHtml(id, caption, refId, bunched_footnote_ref_mode, renderInfo: RenderInfoParameters) {
let localOverride = renderInfo.tokens[renderInfo.idx].meta.text;
if (localOverride) {
localOverride = `<span class="footnote-ref-extra-text">${ localOverride }</span>`;
}
return `<a class="footnote-ref ${ bunched_mode_classes[bunched_footnote_ref_mode] }" href="#fn${ id }" id="fnref${ refId }">${ localOverride || '' }<sup class="footnote-ref">${ caption }</sup></a>` +
(bunched_footnote_ref_mode !== 0 ? `<sup class="footnote-ref-combiner ${ bunched_mode_classes[bunched_footnote_ref_mode] }">${ renderInfo.plugin_options.refCombiner || '' }</sup>` : '');
}
function generateFootnoteSectionStartHtml(renderInfo: RenderInfoParameters) {
const tok = renderInfo.tokens[renderInfo.idx];
assert.ok(tok != null);
assert.ok(tok.meta != null);
const header = (tok.markup ? `<h3 class="footnotes-header">${ tok.markup }</h3>` : '');
let category = tok.meta.category;
assert.ok(category.length > 0);
// `category` can contain CSS class illegal characters, e.g. when category = 'Error::Unused':
category = category.replace(/[^a-zA-Z0-9_-]+/g, '_');
return `<hr class="footnotes-sep footnotes-category-${ category }" id="fnsection-hr-${ tok.meta.sectionId }"${ renderInfo.options.xhtmlOut ? ' /' : '' }><aside class="footnotes footnotes-category-${ category }" id="fnsection-${ tok.meta.sectionId }">${ header }<ul class="footnotes-list">\n`;
}
function generateFootnoteSectionEndHtml(renderInfo: RenderInfoParameters) {
return '</ul>\n</aside>\n';
}
function generateFootnoteStartHtml(id, caption, renderInfo: RenderInfoParameters) {
// allow both a JavaWScript --> CSS approach via `data-footnote-caption`
// and a classic CSS approach while a display:inline-block SUP presenting
// the LI 'button' instead:
return `<li tabindex="-1" id="fn${ id }" class="footnote-item" data-footnote-caption="${ caption }"><span class="footnote-caption"><sup class="footnote-caption">${ caption }</sup></span><span class="footnote-content">`;
}
function generateFootnoteEndHtml(renderInfo: RenderInfoParameters) {
return '</span></li>\n';
}
function generateFootnoteBackRefHtml(id, refId, renderInfo: RenderInfoParameters) {
const tok = renderInfo.tokens[renderInfo.idx];
assert.ok(tok != null);
assert.ok(tok.meta != null);
/* ↩ with escape code to prevent display as Apple Emoji on iOS */
return ` <a href="#fnref${ refId }" class="footnote-backref footnote-backref-${ tok.meta.subId } footnote-backref-R${ tok.meta.backrefCount - tok.meta.subId - 1 }">\u21a9\uFE0E</a>`;
}
/*
ref:
return `<label aria-describedby="fn${id}" role="presentation" class="sidelink" for="fn${id}-content">
<a aria-hidden="true" href="#fn${id}"><output class="highlight fnref" id="fnref${refid}">${caption}
</output></a></label>`;
open:
return `<aside id="fn${id}" class="sidenote" role="note">
<output aria-hidden="true" class="highlight" id="fn${id}-content">
<label role="presentation" for="fnref${id}">`;
}
function render_sidenote_close() {
return '</label></output></aside>\n';
}
*/
interface FootnotePluginOptions /* extends FootnotePluginOptions */ { // eslint-disable-line no-redeclare
anchorFn: (n: number, excludeSubId: number, baseInfo: RenderInfoParameters) => string;
captionFn: (n: number, baseInfo: RenderInfoParameters) => string;
headerFn: (category: string, baseInfo: GenericInfoParameters) => string;
mkLabel: (idx: number, info: footnoteMetaInfo, baseInfo: GenericInfoParameters) => string;
}
const default_plugin_options: FootnotePluginOptions = {
// atDocumentEnd: false, -- obsoleted option of the original plugin
anchorFn: anchorFnDefault,
captionFn: captionFnDefault,
headerFn: headerFnDefault,
mkLabel: determine_footnote_symbol,
// see also https://www.editage.com/insights/footnotes-in-tables-part-1-choice-of-footnote-markers-and-their-sequence
// why asterisk/star is not part of the default footnote marker sequence.
//
// For similar reasons, we DO NOT include the section § symbol in this list.
//
// when numberSequnce is NULL/empty, a regular numerical numbering is assumed.
// Otherwise, the array is indexed; when there are more footnotes than entries in
// the numberSequence array, the entries are re-used, but doubled/trippled, etc.
//
// When the indexing in this array hits a NUMERIC value (as last entry), any higher
// footnotes are NUMBERED starting at that number.
//
// NOTE: as we can reference the same footnote from multiple spots, we do not depend
// on CSS counter() approaches by default, but providee this mechanism in the plugin
// code itself.
numberSequence: [ '†', '‡', '††', '‡‡', '¶', 1 ],
// Overrides the footnode mode when set to one of the following:
//
// Recognized 'modes':
// '>': aside note (default for inline notes)
// ':': end node
// '=': section note (default for regular referenced notes)
//
// Also accepts these keywords: 'aside', 'section', 'end'
//
modeOverride: null,
// list section notes and endnotes in order of:
//
// 0: first *appearance* in the text
// 1: first *reference* in the text
// 2: *definition* in the text
// 3: sorted alphanumerically by *coded* label,
// i.e. *numeric* labels are sorted in numeric order (so `10` comes AFTER `7`!),
// while all others are sorted using `String.localeCompare()`. When labels have
// a *numeric leading*, e.g. `71geo` --> `71`, that part is sorted numerically first.
//
// Here 'coded label' means the label constructed from the reference ids and label overrides
// as used in the markdown source, using the expression
// labelOverride || reference || id
// which gives for these examples (assuming them to be the only definitions in your input):
// [^refA]: ... --> null || 'refA' || 1
// [^refB LBL]: ... --> 'LBL' || 'refB' || 2
// 4: sorted alphanumerically by *printed* label
// which is like mode 3, but now for the label as will be seen in the *output*!
sortOrder: 4,
// what to print between bunched-together footnote references, i.e. the '+' in `blabla¹⁺²`
refCombiner: ','
};
export default function footnote_plugin(md, plugin_options) {
const parseLinkLabel = md.helpers.parseLinkLabel,
isSpace = md.utils.isSpace;
plugin_options = Object.assign({}, default_plugin_options, plugin_options);
const modeOverrideMap = {
aside: '>',
section: '=',
end: ':'
};
function determine_mode(mode: string, default_mode: string) {
let override = null;
if (plugin_options.modeOverride) {
const mode = modeOverrideMap[plugin_options.modeOverride] || plugin_options.modeOverride;
if ('>:='.includes(plugin_options.modeOverride)) {
override = plugin_options.modeOverride;
}
}
if ('>:='.includes(mode)) {
return {
mode: override || mode,
fromInput: true
};
}
return {
mode: override || default_mode,
fromInput: false
};
}
function render_footnote_n(tokens, idx, excludeSubId) {
const mark = tokens[idx].meta.id;
assert.ok(Number.isFinite(mark));
assert.ok(mark > 0);
let n = '' + mark; // = mark.toString();
assert.ok(n.length > 0);
if (!excludeSubId && tokens[idx].meta.subId > 0) {
n += '-' + tokens[idx].meta.subId;
}
return n;
}
function render_footnote_mark(renderInfo: RenderInfoParameters): string {
const token = renderInfo.tokens[renderInfo.idx];
assert.ok(token != null);
assert.ok(renderInfo.env.footnotes != null);
assert.ok(renderInfo.env.footnotes.list != null);
const info = renderInfo.env.footnotes.list[token.meta.id];
assert.ok(info != null);
const mark: string = plugin_options.mkLabel(token.meta.id, info, renderInfo);
assert.ok(mark.length > 0);
return mark;
}
function render_footnote_anchor_name(renderInfo: RenderInfoParameters) {
const n = render_footnote_n(renderInfo.tokens, renderInfo.idx, true);
return plugin_options.anchorFn(n, true, renderInfo);
}
function render_footnote_anchor_nameRef(renderInfo: RenderInfoParameters) {
const n = render_footnote_n(renderInfo.tokens, renderInfo.idx, false);
return plugin_options.anchorFn(n, false, renderInfo);
}
function render_footnote_caption(renderInfo: RenderInfoParameters) {
const n = render_footnote_mark(renderInfo);
return plugin_options.captionFn(n, renderInfo);
}
function render_footnote_ref(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
const id = render_footnote_anchor_name(renderInfo);
const caption = render_footnote_caption(renderInfo);
const refId = render_footnote_anchor_nameRef(renderInfo);
// check if multiple footnote references are bunched together:
// IFF they are, we should separate them with commas.
//
// Exception: when next token has an extra text (`meta.text`) the
// bunching together is not a problem as them the output will render
// like this: `bla<sup>1</sup><a>text<sup>2</sup></a>`, ergo a look
// like this: `bla¹text²` instead of bunched footnotes references ¹ and ²
// that would (without the extra comma injection) look like `bla¹²` instead
// of `x¹⁺²` (here '+' instead of ',' comma, but you get the idea -- there's no
// Unicode superscript-comma so that's why I used unicode superscript-plus
// in this 'ascii art' example).
//
const next_token = tokens[idx + 1] || {};
const next_token_meta = next_token.meta || {};
const bunched_footnote_ref_mode = (next_token.type === 'footnote_ref' ? !next_token_meta.text ? 1 : 2 : 0);
return generateFootnoteRefHtml(id, caption, refId, bunched_footnote_ref_mode, renderInfo);
}
function render_footnote_block_open(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
return generateFootnoteSectionStartHtml(renderInfo);
}
function render_footnote_block_close(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
return generateFootnoteSectionEndHtml(renderInfo);
}
function render_footnote_reference_open(tokens, idx, options, env, self) {
return '';
}
function render_footnote_reference_close() {
return '';
}
function render_footnote_mark_end_of_block() {
return '';
}
function render_footnote_open(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
const id = render_footnote_anchor_name(renderInfo);
const caption = render_footnote_caption(renderInfo);
// allow both a JavaScript --> CSS approach via `data-footnote-caption`
// and a classic CSS approach while a display:inline-block SUP presenting
// the LI 'button' instead:
return generateFootnoteStartHtml(id, caption, renderInfo);
}
function render_footnote_close(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
return generateFootnoteEndHtml(renderInfo);
}
function render_footnote_anchor_backref(tokens, idx, options, env, self) {
const renderInfo: RenderInfoParameters = {
tokens,
idx,
options,
env,
plugin_options,
self
};
const tok = tokens[idx];
assert.ok(tok != null);
assert.ok(tok.meta != null);
const id = render_footnote_anchor_name(renderInfo);
let refId = render_footnote_n(tokens, idx, false);
refId = plugin_options.anchorFn(refId, false, renderInfo);
return generateFootnoteBackRefHtml(id, refId, renderInfo);
}
md.renderer.rules.footnote_ref = render_footnote_ref;
md.renderer.rules.footnote_block_open = render_footnote_block_open;
md.renderer.rules.footnote_block_close = render_footnote_block_close;
md.renderer.rules.footnote_reference_open = render_footnote_reference_open;
md.renderer.rules.footnote_reference_close = render_footnote_reference_close;
md.renderer.rules.footnote_mark_end_of_block = render_footnote_mark_end_of_block;
md.renderer.rules.footnote_open = render_footnote_open;
md.renderer.rules.footnote_close = render_footnote_close;
md.renderer.rules.footnote_anchor = render_footnote_anchor_backref;
function obtain_footnote_info_slot(env, label: string|null, at_definition: boolean) {
// inline blocks have their own *child* environment in markdown-it v10+.
// As the footnotes must live beyond the lifetime of the inline block env,
// we must patch them into the `parentState.env` for the footnote_tail
// handler to be able to access them afterwards!
while (env.parentState) {
env = env.parentState.env;
assert.ok(env != null);
}
if (!env.footnotes) {
env.footnotes = {
// map label tto ID:
refs: {},
// store footnote info indexed by ID
list: [],
// remap ID to re-ordered ID (determines placement order for section notes and endnotes)
idMap: [ 0 ],
idMapCounter: 0,
// and a counter for the generated sections (including asides); see the demo/test which
// uses the generated `#fnsection-DDD` identifiers to hack/fix the styling, for example.
sectionCounter: 0
};
}
// When label is NULL, this is a request from in INLINE NOTE.
// NOTE: IDs are index numbers, BUT they start at 1 instead of 0 to make life easier in check code:
let footnoteId;
let infoRec: footnoteMetaInfo;
// label as index: prepend ':' to avoid conflict with Object.prototype members
if (label == null || !env.footnotes.refs[':' + label]) {
footnoteId = Math.max(1, env.footnotes.list.length);
infoRec = {
id: footnoteId,
label,
labelOverride: null,
mode: null,
content: null,
tokens: null,
count: 0
};
env.footnotes.list[footnoteId] = infoRec;
if (label != null) {
env.footnotes.refs[':' + label] = footnoteId;
}
} else {
footnoteId = env.footnotes.refs[':' + label];
infoRec = env.footnotes.list[footnoteId];
assert.ok(!!infoRec, 'expects non-NULL footnote info record');
}
const idMap = env.footnotes.idMap;
// now check if the idMap[] has been set up already as well. This depends on
// when WE are invoked (`at_definition`) and the configured `options.sortOrder`:
switch (plugin_options.sortOrder) {
// 0: first *appearance* in the text
default:
case 0:
// basically, this means: order as-is
if (!idMap[footnoteId]) {
idMap[footnoteId] = ++env.footnotes.idMapCounter;
}
break;
// 1: first *reference* in the text
case 1:
if (!at_definition && !idMap[footnoteId]) {
// first reference is now!
idMap[footnoteId] = ++env.footnotes.idMapCounter;
}
break;
// 2: *definition* in the text
case 2:
if (at_definition && !idMap[footnoteId]) {
// definition is now!
idMap[footnoteId] = ++env.footnotes.idMapCounter;
}
break;
// 3: sorted alphanumerically by label (inline footnotes will end up at the top, before all other notes)
case 3:
case 4:
// just note the footnoteId now; this must be re-ordered later when we have collected all footnotes.
//
// set it up when we get there...
break;
}
return infoRec;
}
function find_end_of_block_marker(state, startIndex) {
let idx, len;
const tokens = state.tokens;
for (idx = startIndex, len = tokens.length; idx < len; idx++) {
if (tokens[idx].type === 'footnote_mark_end_of_block') { return idx; }
}
// Punch a slot into the token stream (at the very end)
// for consistency with footnote_mark_end_of_block():
const token = new state.Token('footnote_mark_end_of_block', '', 0);
token.hidden = true;
tokens.push(token);
return tokens.length - 1;
}
function update_end_of_block_marker(state, footnoteId) {
// inject marker into parent = block level token stream to announce the advent of an (inline) footnote:
// because the markdown_it code uses a for() loop to go through the parent nodes while parsing the
// 'inline' chunks, we CANNOT safely inject a marker BEFORE the chunk, only AFTERWARDS:
const parentState = state.env.parentState;
const parentIndex = state.env.parentTokenIndex;
const markerTokenIndex = find_end_of_block_marker(parentState, parentIndex + 1);
const token = parentState.tokens[markerTokenIndex];
if (!token.meta) {
token.meta = {
footnote_list: []
};
}
token.meta.footnote_list.push(footnoteId);
}
// Mark end of paragraph/heading/whatever BLOCK (or rather: START of the next block!)
function footnote_mark_end_of_block(state, startLine, endLine, silent) {
if (!silent && state.tokens.length > 0) {
const token = state.push('footnote_mark_end_of_block', '', 0);
token.hidden = true;
}
return false;
}
// Process footnote block definition
function footnote_def(state, startLine, endLine, silent) {
let oldBMark, oldTShift, oldSCount, oldParentType, pos, token,
initial, offset, ch, posAfterColon,
start = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
// line should be at least 6 chars - "[^x]: " or "[^x]:> "
if (start + 5 > max) { return false; }
if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }
if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }
for (pos = start + 2; pos < max; pos++) {
if (state.src.charCodeAt(pos) === 0x0A /* LF */) { return false; }
if (state.src.charCodeAt(pos) === 0x5D /* ] */) {
break;
}
}
const labelEnd = pos;
if (pos === start + 2) { return false; } // no empty footnote labels
if (pos + 1 >= max || state.src.charCodeAt(++pos) !== 0x3A /* : */) { return false; }
const mode_rec = determine_mode(state.src[pos + 1], '='); // default mode is section_note mode.
if (mode_rec.fromInput) { pos++; }
const mode = mode_rec.mode;
if (pos + 1 >= max || state.src.charCodeAt(++pos) !== 0x20 /* space */) { return false; }
if (silent) { return true; }
pos++;
const labelInfo = decode_label(state.src.slice(start + 2, labelEnd), true);
if (!labelInfo) { return false; }
assert.ok(!labelInfo.extraText);
// Now see if we already have a footnote ID for this footnote label:
// fetch it if we have one and otherwise produce a new one so everyone
// can use this from now on.
//
// This scenario is possible when the footnote *definition* comes BEFORE
// the first actual footnote *use* (*reference*). This is UNUSUAL when people
// write texts, but it is *not impossible*, particularly now that we have
// specified-by-design that endnotes can be marked as such (`[^label]:: note text`)
// and freely mixed with sidenotes (`[^label]:> note text`) and section
// notes (`[^label]:= note text` (explicit mode) or `[^label]: note text`
// (implicit mode)), where *section notes* will placed at the spot in the text
// flow where they were *defined*. Again, highly irregular, BUT someone MAY
// feel the need to place some section note *definitions* ABOVE their first
// use point.
//
const infoRec = obtain_footnote_info_slot(state.env, labelInfo.label, true);
if (labelInfo.labelOverride) {
infoRec.labelOverride = labelInfo.labelOverride;
}
infoRec.mode = mode;
infoRec.content = state.src.slice(pos, max);
token = state.push('footnote_reference_open', '', 1);
token.meta = {
id: infoRec.id
};
token.hidden = true;
oldBMark = state.bMarks[startLine];
oldTShift = state.tShift[startLine];
oldSCount = state.sCount[startLine];
oldParentType = state.parentType;
posAfterColon = pos;
initial = offset = state.sCount[startLine] + pos - (state.bMarks[startLine] + state.tShift[startLine]);
while (pos < max) {
ch = state.src.charCodeAt(pos);
if (isSpace(ch)) {
if (ch === 0x09) {
offset += 4 - offset % 4;
} else {
offset++;
}
} else {
break;
}
pos++;
}
state.tShift[startLine] = pos - posAfterColon;
state.sCount[startLine] = offset - initial;
state.bMarks[startLine] = posAfterColon;
state.blkIndent += 4;
state.parentType = 'footnote';
if (state.sCount[startLine] < state.blkIndent) {
state.sCount[startLine] += state.blkIndent;
}
state.md.block.tokenize(state, startLine, endLine, true);
state.parentType = oldParentType;
state.blkIndent -= 4;
state.tShift[startLine] = oldTShift;
state.sCount[startLine] = oldSCount;
state.bMarks[startLine] = oldBMark;
token = state.push('footnote_reference_close', '', -1);
token.meta = {
id: infoRec.id
};
return true;
}
// Process inline footnotes (^[...] or ^[>...])
function footnote_inline(state, silent) {
let labelStart,
labelEnd,
token,
tokens,
max = state.posMax,
start = state.pos;
if (start + 2 >= max) { return false; }
if (state.src.charCodeAt(start) !== 0x5E/* ^ */) { return false; }
if (state.src.charCodeAt(start + 1) !== 0x5B/* [ */) { return false; }
labelStart = start + 2;
// NOTE: inline notes are automatically considered to be ASIDE notes,
// UNLESS otherwise specified!
//
// Recognized 'modes':
// '>': aside note (default for inline notes)
// ':': end node
// '=': section note (default for regular referenced notes)
//
// (Also note https://v4.chriskrycho.com/2015/academic-markdown-and-citations.html:
// our notes look like this: `[^ref]:` while Academic MarkDown references look
// like this: `[@Belawog2012]` i.e. no '^' in there. Hence these can safely co-exist.)
//
const mode_rec = determine_mode(state.src[start + 2], '>'); // default mode is aside ~ sidenote mode.
if (mode_rec.fromInput) {
labelStart++;
}
const mode = mode_rec.mode;
labelEnd = parseLinkLabel(state, start + 1);
// parser failed to find ']', so it's not a valid note
if (labelEnd < 0) { return false; }
// We found the end of the link, and know for a fact it's a valid link;
// so all that's left to do is to call tokenizer.
//
if (!silent) {
// WARNING: claim our footnote slot for there MAY be nested footnotes
// discovered in the next inline.parse() call below!
const infoRec = obtain_footnote_info_slot(state.env, null, true);
infoRec.mode = mode;
infoRec.count++;
token = state.push('footnote_ref', '', 0);
token.meta = {
id: infoRec.id
};
state.md.inline.parse(
state.src.slice(labelStart, labelEnd),
state.md,
state.env,
tokens = []
);
// Now fill our previously claimed slot:
infoRec.content = state.src.slice(labelStart, labelEnd);
infoRec.tokens = tokens;
// inject marker into parent = block level token stream to announce the advent of an (inline) footnote:
// because the markdown_it code uses a for() loop to go through the parent nodes while parsing the
// 'inline' chunks, we CANNOT safely inject a marker BEFORE the chunk, only AFTERWARDS:
update_end_of_block_marker(state, infoRec.id);
//md.block.ruler.enable('footnote_mark_end_of_block');
}
state.pos = labelEnd + 1;
state.posMax = max;
return true;
}
// Check if this is a valid ffootnote reference label.
//
// Also see if there's a label OVERRIDE text or marker ('@') provided.
//
// Return the parsed label record.
function decode_label(label: string, extra_text_is_labelOverride: boolean) {
if (!label) {
return null;
}
const m = label.match(/^(@?)(\S+)(?:\s+(.+))?$/); // label with OPTIONAL override text...
if (!m) {
return null;
}
assert.ok(m[2].length > 0);
let extraText = m[3]?.trim();
// label [output] override?
let override = null;
if (m[1]) {
override = m[2];
}
if (extra_text_is_labelOverride && extraText) {
override = extraText;
extraText = null;
}
return {
label: m[2],
labelOverride: override,
extraText
};
}
// Process footnote references with text ([^label ...])
function footnote_ref_with_text(state, silent) {
let pos,
footnoteSubId,
token,
max = state.posMax,
start = state.pos;
// should be at least 6 chars - "[^l x]"
if (start + 5 > max) { return false; }
if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }
if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }
for (pos = start + 2; pos < max; pos++) {
if (state.src.charCodeAt(pos) === 0x0A /* linefeed */) { return false; }
if (state.src.charCodeAt(pos) === 0x5D /* ] */) {
break;
}
}
if (pos === start + 2) { return false; } // no empty footnote labels
if (pos >= max) { return false; }
pos++;
const labelInfo = decode_label(state.src.slice(start + 2, pos - 1), false);
if (!labelInfo || !labelInfo.extraText) { return false; }
assert.ok(labelInfo.extraText.length > 0);
const infoRec = obtain_footnote_info_slot(state.env, labelInfo.label, false);
if (labelInfo.labelOverride) {
infoRec.labelOverride = labelInfo.labelOverride;
}
if (!silent) {
footnoteSubId = infoRec.count;
infoRec.count++;
token = state.push('footnote_ref', '', 0);
token.meta = {
id: infoRec.id,
subId: footnoteSubId,
text: labelInfo.extraText
};
update_end_of_block_marker(state, infoRec.id);
//md.block.ruler.enable('footnote_mark_end_of_block');
}
state.pos = pos;
state.posMax = max;
return true;
}
// Process footnote references ([^...])
function footnote_ref(state, silent) {
let pos,
footnoteSubId,
token,
max = state.posMax,
start = state.pos;
// should be at least 4 chars - "[^x]"
if (start + 3 > max) { return false; }
if (state.src.charCodeAt(start) !== 0x5B/* [ */) { return false; }
if (state.src.charCodeAt(start + 1) !== 0x5E/* ^ */) { return false; }
for (pos = start + 2; pos < max; pos++) {
//if (state.src.charCodeAt(pos) === 0x20) { return false; }
if (state.src.charCodeAt(pos) === 0x0A) { return false; }
if (state.src.charCodeAt(pos) === 0x5D /* ] */) {
break;
}
}
if (pos === start + 2) { return false; } // no empty footnote labels
if (pos >= max) { return false; }
pos++;
const labelInfo = decode_label(state.src.slice(start + 2, pos - 1), true);
if (!labelInfo) { return false; }
assert.ok(!labelInfo.extraText);
const infoRec = obtain_footnote_info_slot(state.env, labelInfo.label, false);
if (labelInfo.labelOverride) {
infoRec.labelOverride = labelInfo.labelOverride;
}
if (!silent) {
footnoteSubId = infoRec.count;
infoRec.count++;
token = state.push('footnote_ref', '', 0);
token.meta = {
id: infoRec.id,
subId: footnoteSubId
};
update_end_of_block_marker(state, infoRec.id);
//md.block.ruler.enable('footnote_mark_end_of_block');
}
state.pos = pos;
state.posMax = max;
return true;
}
function place_footnote_definitions_at(state, token_idx: number, footnote_id_list, category: string, baseInfo: GenericInfoParameters) {
if (footnote_id_list.length === 0) {
return; // nothing to inject...
}
let inject_tokens = [];
assert.ok(baseInfo.env.footnotes.list != null);
const footnote_spec_list = baseInfo.env.footnotes.list;
let token = new state.Token('footnote_block_open', '', 1);
token.markup = plugin_options.headerFn(category, baseInfo.env, plugin_options);
token.meta = {
sectionId: ++baseInfo.env.footnotes.sectionCounter,
category
};
inject_tokens.push(token);
for (const id of footnote_id_list) {
const fn = footnote_spec_list[id];
const inject_start_index = inject_tokens.length;
token = new state.Token('footnote_open', '', 1);
token.meta = {
id,
category
};
inject_tokens.push(token);
if (fn.label == null) {
// process an inline footnote text:
token = new state.Token('paragraph_open', 'p', 1);
token.block = true;
inject_tokens.push(token);
token = new state.Token('inline', '', 0);
token.children = fn.tokens;
token.content = fn.content;
inject_tokens.push(token);
token = new state.Token('paragraph_close', 'p', -1);
token.block = true;
inject_tokens.push(token);
} else {
// process a labeled footnote:
inject_tokens = inject_tokens.concat(fn.tokens || []);
}
//let lastParagraph;
//if (inject_tokens[inject_tokens.length - 1].type === 'paragraph_close') {
// lastParagraph = inject_tokens.pop();
//} else {
// lastParagraph = null;
//}