-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflexmark.cfc
More file actions
733 lines (574 loc) · 23.5 KB
/
Copy pathflexmark.cfc
File metadata and controls
733 lines (574 loc) · 23.5 KB
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
/**
Process markdown with Flexmark and generate data
## Background
Uses [Flexmark](https://github.com/vsch/flexmark-java) to render HTML and produce Meta data.
## Usage
See README.md
## Notes
There is a bug with Flexmark that we cater for here.
If you don't use the Anchor links plug in, it will remove any ids specified with the # syntax (e.g. {#title}). If you do use anchorlinks, it will move ALL attributes from the heading tag onto the anchor.
We therefore have a workaround, which is an option unwrapAnchors, which will look for empty `<a>` tags where the href is the same as the id tag, copy the attributes to the parent and unwrap the a tag. This is fine as there is no real need to use anchor tags any more, a link to any ID is possible.
## Usage
Instantiate with the plugins and options you require set by the arguments. If you want to use the advanced functionality, specify a path to the Jsoup Jar as well (jsoupjar).
Call one of the conversion methods, `toHtml` or `Markdown`. The latter requires the use of Jsoup (via the herlper component ColdSoup).
## History
*/
component name="flexmark" {
public function init(
required string jarpath,
boolean tables=true,
boolean abbreviation=true,
boolean admonition=true,
boolean anchorlink=true,
boolean anchorlinks_wrap_text=true,
boolean attributes=false,
boolean definition=true,
boolean emoji=true,
boolean escapedcharacter=true,
boolean footnote=true,
boolean strikethrough=true,
boolean unwrapAnchors=true,
boolean softbreaks=false,
boolean macros=true,
boolean typographic = false,
boolean tasklist = true,
boolean yaml = true,
boolean superscript = true,
string jsoupjar, // optional for full featured parsing using markdown() rather than toHtml()
coldsoup coldsoupObj // pass in instantiated coldsoup Object instead of creating one
) {
this.cr = newLine();
variables.useJsoup = isDefined("arguments.jsoupjar") OR isDefined("arguments.coldsoupObj") ;
if ( variables.useJsoup ) {
if ( isDefined("arguments.coldsoupObj") ) {
this.coldsoup = arguments.coldsoupObj;
}
else {
try {
this.coldsoup = new coldsoup.coldsoup(arguments.jsoupjar);
}
catch (any e) {
throw("Unable to instantiate coldsoup:" & e.message);
}
}
}
variables.yaml = arguments.yaml;
// doc properties allows us to use YAML to define
// publishing properties like toclevel.
variables.docProperties = {
"toclevel" = 3,
"notoc" = ""
};
// unwrapAnchors requires use of ColdSoup helper library.
variables.unwrapAnchors = arguments.unwrapAnchors && variables.useJsoup ;
// works ok with just JAR path
this.bundleName = arguments.jarpath;
var options = createObject("java", "com.vladsch.flexmark.util.data.MutableDataSet",this.bundlename).init();
// load option constants
var Parser = createObject("java", "com.vladsch.flexmark.parser.Parser",this.bundlename);
var HtmlRenderer = createObject("java", "com.vladsch.flexmark.html.HtmlRenderer",this.bundlename);
var extensions = optionList(optionsSet=arguments);
options.set(Parser.EXTENSIONS,extensions);
if (arguments.softbreaks) {
options.set(HtmlRendererClass.SOFT_BREAK, "<br />\n");
}
if (arguments.anchorlinks_wrap_text) {
var AnchorLinkExtensionClass = createObject( "java", "com.vladsch.flexmark.ext.anchorlink.AnchorLinkExtension", this.bundleName);
options.set(AnchorLinkExtensionClass.ANCHORLINKS_WRAP_TEXT,arguments.anchorlinks_wrap_text);
}
// build parser/renderer
variables.parser = Parser.builder(options).build();
variables.renderer = HtmlRenderer.builder(options).build();
this.patternObj = createObject( "java", "java.util.regex.Pattern" );
// used to preserve mustache vars. They get wrecked by Flexmark if we don't do this (it thinks they are attribute strings)
this.mustachepattern = this.patternObj.compile("(\{{2,3})(\w+)(\}{2,3})",this.patternObj.MULTILINE + this.patternObj.UNIX_LINES);
this.reversemustachepattern = this.patternObj.compile("(\[{2,3})(\w+)(\]{2,3})",this.patternObj.MULTILINE + this.patternObj.UNIX_LINES);
// variable replace syntax. Replace ${var} with variables from meta data
// also cope with {$var}
this.varpattern = this.patternObj.compile("(\$\{|\{\$)([A-Za-z0-9.]*[^{}])\}",this.patternObj.MULTILINE + this.patternObj.UNIX_LINES);
// deprecated
this.alphapattern = this.patternObj.compile("(?m)^@[\w\[\]]+\.?\w*\s+.+?\s*$",this.patternObj.MULTILINE + this.patternObj.UNIX_LINES);
return this;
}
private function optionList(struct optionsSet) {
var extensions = createObject( "java", "java.util.ArrayList" ).init();
if (optionsSet.keyExists("tables") && optionsSet["tables"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.tables.TablesExtension", this.bundleName).create());
}
if (optionsSet.keyExists("abbreviation") && optionsSet["abbreviation"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.abbreviation.AbbreviationExtension", this.bundleName).create());
}
if (optionsSet.keyExists("admonition") && optionsSet["admonition"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.admonition.AdmonitionExtension", this.bundleName).create());
// import com.vladsch.flexmark.ext.admonition.AdmonitionExtension;
}
if (optionsSet.keyExists("anchorlink") && optionsSet["anchorlink"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.anchorlink.AnchorLinkExtension", this.bundleName).create());
}
if (optionsSet.keyExists("attributes") && optionsSet["attributes"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.attributes.AttributesExtension", this.bundleName).create());
}
if (optionsSet.keyExists("definition") && optionsSet["definition"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.definition.DefinitionExtension", this.bundleName).create());
}
if (optionsSet.keyExists("emoji") && optionsSet["emoji"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.emoji.EmojiExtension", this.bundleName).create());
}
if (optionsSet.keyExists("escapedcharacter") && optionsSet["escapedcharacter"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.escaped.character.EscapedCharacterExtension", this.bundleName).create());
}
if (optionsSet.keyExists("footnote") && optionsSet["footnote"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.footnotes.FootnoteExtension", this.bundleName).create());
}
if (optionsSet.keyExists("macros") && optionsSet["macros"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.macros.MacrosExtension", this.bundleName).create());
}
if (optionsSet.keyExists("strikethrough") && optionsSet["strikethrough"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension", this.bundleName).create());
}
if (optionsSet.keyExists("tasklist") && optionsSet["tasklist"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.gfm.tasklist.TaskListExtension", this.bundleName).create());
}
if (optionsSet.keyExists("typographic") && optionsSet["typographic"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.typographic.TypographicExtension", this.bundleName).create());
}
if (optionsSet.keyExists("yaml") && optionsSet["yaml"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.yaml.front.matter.YamlFrontMatterExtension", this.bundleName).create());
}
if (optionsSet.keyExists("superscript") && optionsSet["superscript"]) {
extensions.add(createObject( "java", "com.vladsch.flexmark.ext.superscript.SuperscriptExtension", this.bundleName).create());
}
return extensions;
}
/**
* @hint Convert to html and generate meta data
*
* Returns a struct with keys
*
* html
* : The rendered html
* data
* : A struct of information about the document keyed by element id. Contains heading text
*
*
*
* @Text Text to process
* @options Publishing options, see docProperties. Will override any set in YAML
* @replace_vars replace vars in ${var} format with values from meta data
* @return Struct with keys html and data (see notes)
*
*/
public struct function markdown (required string text, struct options={}, replace_vars=true) localmode=true {
if (!variables.useJsoup ) {
throw("use of markdown() function requires coldsoup. Use toHtml() instead.");
}
// Add processing options. Note document properties have a different mechanism see variables.docProperties
StructAppend(arguments.options, {"meta"=1}, false);
doc = {"data" = {"meta"={}}};
doc.text = arguments.text;
meta = {};
doc.html = toHtml(text=arguments.text,data=meta);
// remove doc properties from meta and add to main struct
// This allows us to use YAML to defined publishing properties
// like toclevel but keeps the meta data clean
for (prop in variables.docProperties) {
if (StructKeyExists(arguments.options, prop) ) {
doc.data["#prop#"] = arguments.options[prop];
}
else if (StructKeyExists(meta, prop) ) {
doc.data["#prop#"] = meta[prop];
StructDelete(meta, prop);
}
// else add default
else if (variables.docProperties[prop] neq "") {
doc.data["#prop#"] = variables.docProperties[prop];
}
}
StructAppend(doc.data.meta, meta);
addContent(document=doc, meta=arguments.options.meta);
parseFootnotes(doc);
if (arguments.replace_vars) {
doc.html = replaceVars(doc.html, doc.data.meta);
}
return doc;
}
/**
* Plain markdown to html conversion
* @text Markdown text to convert
* @data Struct to update with YAML data
*/
public string function toHtml(required string text, struct data={}) localmode=true {
arguments.text = replaceMustacheVars(arguments.text);
local.document = variables.parser.parse( javacast("string", arguments.text ) );
if (variables.yaml) {
local.yamlVisitor = createObject( "java", "com.vladsch.flexmark.ext.yaml.front.matter.AbstractYamlFrontMatterVisitor",this.bundlename);
local.yamlVisitor.visit(document);
local.metadata = local.yamlVisitor.getData();
if (local.metadata.size()) {
for (local.key in local.metadata.keySet()) {
local.keyData =local.metadata.get(local.key);
try {
if ( ! ArrayLen(local.keyData) ) {
arguments.data[local.key] = "";
}
else {
arguments.data[local.key] = Trim(local.keyData[1]);
}
}
catch (any e) {
local.extendedinfo = {"error"=e,"keyData"=local.keyData};
throw(
extendedinfo = SerializeJSON(local.extendedinfo),
message = "Unable to parse Yaml:" & e.message,
detail = e.detail
);
}
}
}
}
arguments.text = variables.renderer.render(local.document);
arguments.text = replaceMustacheVars(arguments.text,true);
if (variables.unwrapAnchors) {
local.node = this.coldsoup.parse(arguments.text);
unwrapHeaders(local.node);
arguments.text = local.node.body().html();
}
return arguments.text;
}
/**
* Replace {{mustachevars}} with temporary place holders (and replace back)
*/
private string function replaceMustacheVars(required string text, boolean undo=false) localmode=true {
if (arguments.undo) {
matcher = this.reversemustachepattern.matcher(arguments.text);
}
else {
matcher = this.mustachepattern.matcher(arguments.text);
}
buffer = createObject("java", "java.lang.StringBuffer");
while (matcher.find()){
triple = matcher.group( 1 ).len() eq 3;
if (arguments.undo) {
rep = "{{" & (triple ? "{" : "") & matcher.group( 2 ) & "}}" & (triple ? "}" : "");
}
else {
rep = "[[" & (triple ? "[" : "") & matcher.group( 2 ) & "]]" & (triple ? "]" : "");
}
matcher.appendReplacement(buffer, rep ) ;
}
matcher.appendTail(buffer);
return buffer.toString();
}
/**
* @hint Replace mustache like variables with values form data struct
*
* Variables in form {$varname} are replaced with values from a data struct
*
* Originally meant for mustache compatibility, this has extended to allow nested structs with . notation for the
* variables
*
**/
public string function replaceVars(html,data) localmode=true {
//get around problem of extra p surrounding toc
arguments.html = REReplace(arguments.html,"\s*\<p[^>]*?\>\s*((\$\{|\{\$)toc\}\s*)\<\/p\>","\1");
// deprecated underscore handler
arguments.html = REReplace(arguments.html,"%%varUndrscReplace%%","_","all");
// find all variable names
matcher = this.varpattern.matcher(arguments.html);
// build cache of replacement values. Variables may be keyed e.g.
// meta.something and there's no quick lookup
replaceCache = {};
// use java buffer for single pass
buffer = createObject("java", "java.lang.StringBuffer");
// loop over them and relpace
while (matcher.find()){
varname = local.matcher.group( javacast("int",2) );
if (! replaceCache.keyExists( varname ) ) {
// TODO: only works for one level (and horrible)
if (ListLen( varname,".") gt 1) {
if (IsDefined("arguments.data.#varname#")) {
replaceCache[varname] = arguments.data[ListFirst(varname,".")][ListLast(varname,".")];
}
else {
replaceCache[varname] = local.matcher.group() ;
}
}
else {
if (StructKeyExists(arguments.data, varname)) {
replaceCache[varname] = arguments.data[varname];
}
else {
replaceCache[varname] = local.matcher.group() ;
}
}
}
try{
matcher.appendReplacement(buffer, matcher.quoteReplacement( replaceCache[varname] ) ) ;
}
catch (any e) {
local.extendedinfo = {"error"=e,"replaceCache"=replaceCache,"data"=data};
throw(
extendedinfo = SerializeJSON(local.extendedinfo),
message = "Error replacing vars:" & e.message,
detail = e.detail
);
}
}
matcher.appendTail(buffer);
arguments.html = buffer.toString();
return arguments.html;
}
/**
* DEPRECATED
* Parse attributes into a struct from a single tag string
* (e.g. [image id=xx]). Tag can be < or << or [ or [[
* enclosed. Attributes can be single quoted, double quote
* or alpha numeric
*
* @text The full tag string (start tag only, tag name ignored).
*/
public struct function parseTagAttributes(
required string text
) localmode=true {
temp = {};
stext = ReplaceList(arguments.text,"����","',',','");
stext = ListFirst(Trim(stext),"[]<>");
attrVals = ListRest(sText," ");
if (NOT IsDefined("variables.attrPattern")) {
patternObj = createObject( "java", "java.util.regex.Pattern");
myPattern = "(\w+)(\s*=\s*(""(.*?)""|'(.*?)'|([^'"">\s]+)))";
variables.attrPattern = patternObj.compile(myPattern);
}
tagObjs = variables.attrPattern.matcher(attrVals);
while (tagObjs.find()){
temp[tagObjs.group(javacast("int",1))] = reReplace(tagObjs.group(javacast("int",3)), "^(""|')(.*?)(""|')$", "\2");
}
return temp;
}
/**
* @hint Parse headings into a struct of structs (document.data.content)
*
* Each entry has the following keys
*
* id dom ID
* level toc level (id 1-4)
* text Heading text
* toc (boolean) include in toc
*
* @meta Use meta attribute on divs to convert content to a meta var.
*/
public void function addContent(required struct document, boolean meta=true) localmode="true" {
if (! arguments.document.keyExists("node") ) {
arguments.document.node = this.coldsoup.parse(arguments.document.html);
}
if (NOT structKeyExists(arguments.document,"data")) {
arguments.document["data"] = {};
}
if (NOT structKeyExists(arguments.document.data,"meta")) {
arguments.document.data["meta"] = {};
}
// There is also a bug in Flexmark which removes ids if you're not using anchorlinks.
// Therefore the only way to get the ids is to use anchor links and assign the id to the parent element
if (variables.unwrapAnchors) {
unwrapHeaders(arguments.document.node);
}
// any divs with meta=true are meta data vars
if (arguments.meta) {
metadivs = arguments.document.node.select("[meta]");
for (metadiv in metadivs) {
id = metadiv.attr("id");
if (! isDefined("id")) {
throw("Meta attribute defined on div without an ID.");
}
arguments.document.data.meta["#id#"] = metadiv.html();
metadiv.remove();
}
}
// notoc is list of jsoup selectors to exclude from toc. Apply "notoc" class to nodes to do this
if (StructKeyExists(arguments.document.data,"notoc")) {
for (notocrule in ListToArray( arguments.document.data.notoc ) ) {
notocnodes = arguments.document.node.select(Trim(notocrule));
for (notocNode in notocnodes) {
notocNode.addClass("notoc");
}
}
}
content = [=];
headers = arguments.document.node.select("h1,h2,h3,h4");
for ( header in headers) {
id = header.id();
// add entry to data for all cases. Boolean notoc indicates
// inclusion in toc
noToc = header.hasClass("notoc");
level = replace(header.tagName(), "h", "");
content["#id#"] = {"id"=id,"text"=header.text(),"level"=level,"toc"= (!noToc) && level <= arguments.document.data.toclevel};
if (noToc) {
header.removeClass("notoc");
}
}
arguments.document.data["content"] = content;
arguments.document.data.meta["toc"] = generateTocHTML(arguments.document.data);
// Assign values from default headings to meta fields
for (field in ['title','author','subject']) {
if (StructKeyExists(arguments.document.data.content,field) AND NOT StructKeyExists(arguments.document.data.meta,field)) {
arguments.document.data.meta["#field#"] = arguments.document.data.content[field].text;
}
}
// if not title set by id=title attribute then get first h1 tag
if (! StructKeyExists(arguments.document.data.meta, "title")) {
title = arguments.document.node.select("h1");
if (IsDefined("title") AND ArrayLen(title)) {
arguments.document.data.meta.title = title.first().text();
}
}
// auto cross references
links = arguments.document.node.select("a[href]");
for (link in links) {
id = ListLast(link.attr("href"),"##");
if (StructKeyExists(arguments.document.data.content,id)) {
text = link.text();
if (trim(text) eq "") {
link.html(arguments.document.data.content[id].text);
}
}
}
removeUnusedIDs(document=arguments.document,jsoupNode=arguments.document.node);
fixTableCaptions(jsoupNode=arguments.document.node);
arguments.document.html = arguments.document.node.body().html();
}
/**
* Convert caption attibutes to tags
*/
private void function fixTableCaptions(required any jsoupNode) {
local.tables = arguments.jsoupNode.select( "table[caption]" );
for (local.table in local.tables) {
local.table.prepend(this.coldsoup.createNode(tagName="caption",text=local.table.attr("caption")));
local.table.removeAttr("caption");
}
}
/**
* @hint Remove ID tags that aren't used from headers
*
* Flexmark will add an ID to every heading. This function removes them if
* they are not in the TOC or not referenced anywhere
*/
private string function removeUnusedIDs(required struct document, required any jsoupNode) localmode=true {
// get list of all links used
targets = {};
links = arguments.jsoupNode.select("[href]");
if (IsDefined("links")) {
for (link in links) {
href = link.attr("href");
if (IsDefined("href")) {
if (Left(href,1) eq "##" ) {
targets["#ListFirst(href,"##")#"] = true;
}
}
}
}
idTags = arguments.jsoupNode.select("[id]");
for (tag in idTags) {
id = tag.attr("id");
if (left(tag.tagName(),1) neq "h") continue;
if (IsDefined("id")) {
if (! ( targets.keyExists(id) || ( arguments.document.data.content.keyExists(id) && arguments.document.data.content[id].toc ) ) ) {
tag.removeAttr("id");
}
}
}
}
private void function unwrapHeaders(required any node) localmode=true {
headers = arguments.node.select("h1,h2,h3,h4");
for ( header in headers) {
// this gets overridden in flexmark if auto headers is on. See next
id = header.id();
// generate id from header text NB flexmark places the id and other attributes in to the <a> child tag
anchor = header.select("a");
if ( ArrayLen(anchor) ) {
tag = anchor.first();
id = tag.id();
href = anchor.attr("href");
if (IsDefined("href")) {
target = ListLast(href,"##");
// flexmark always adds href to anchors. If it links to itself it's an anchor not a link.
if (id == target) {
tag.removeAttr("href");
this.coldsoup.copyAttributes(tag,header);
tag.unwrap();
}
}
}
}
}
/**
* Generate HTML for a table of contents.
*
* @data Document data (see addContent(). Each heading needs an entry which is a struct with keys level,text, id, and toc)
* @return Formatted HTML
*/
private string function generateTocHTML(required struct data) localmode=true {
// TODO: class name parameterise
html = "<div id=""toc"" class=""toc toc_manual"">";
// default level for TOC headings
if (NOT StructKeyExists(arguments.data,"toclevel")) arguments.data["toclevel"] = variables.docProperties.toclevel;
if (! arguments.data.keyExists("content") ) {
throw(message="No content defined in data. Cannot generate toc");
}
insection = false;
for (id in arguments.data.content) {
heading = arguments.data.content[id];
toc = heading.toc ? : true; // toc can be set to false via notoc mechanism
level = heading.level ? : 20; // all headings should have a level 1-6.
// MUSTDO: this doesn't work if toclevel=1.
if (toc && level lte arguments.data.toclevel) {
if (arguments.data.toclevel gt 1 && level eq 1) {
if (insection) {
html &= "</div>";
}
html &= " <div class=""tocsection"">";
insection = true;
}
html &= " <p class=""toc#level#""><a href=""###heading.id#"">#heading.text#</a></p>" & newLine();
}
}
// close tocsection tag
if (arguments.data.toclevel gt 1) {
html &= "</div>";
}
html &= "</div>";
return html;
}
// Flexmark will place footnotes at the end of the HTML.
// We want to use them in different ways according to how we are diplsaying
// the content. Here we put them backinto the HTML as <span class='footnote'></span> elements.
// For Prince conversion, these are used as is. For Kindle/other html, it's easy to just redo the footnote html
//
private void function parseFootnotes(required any document) {
if (! arguments.document.keyExists("node") ) {
arguments.document.node = this.coldsoup.parse(arguments.document.html);
}
local.docs = arguments.document.node.select(".footnotes");
if (! local.docs.len()) {
return;
}
// get rid of the extraneous <sup> tags
local.markers = arguments.document.node.select("sup[id]");
for (local.marker in local.markers) {
local.marker.unwrap();
}
// find all the footnote markers
local.footnotes = arguments.document.node.select("a.footnote-ref");
for (local.marker in local.footnotes) {
/* find footnote with format
<li id="fn-2"> <p>Look it up if you don’t already know it. And then try not to do it.</p>
*/
local.href = local.marker.attr("href");
local.num = ListLast(local.href,"-");
local.note = arguments.document.node.select(local.href & " p").first().html();
local.marker.html("<span class='footnote'>#local.note#</span>").unwrap();
}
// remove the footnotes section
arguments.document.node.select(".footnotes").first().remove();
arguments.document.html = arguments.document.node.body().html();
}
}