-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathParser.js
2013 lines (1747 loc) · 44 KB
/
Parser.js
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
/**#@+
* Boolean rules bitfield
*/
const RULE_AUTO_CLOSE = 1 << 0;
const RULE_AUTO_REOPEN = 1 << 1;
const RULE_BREAK_PARAGRAPH = 1 << 2;
const RULE_CREATE_PARAGRAPHS = 1 << 3;
const RULE_DISABLE_AUTO_BR = 1 << 4;
const RULE_ENABLE_AUTO_BR = 1 << 5;
const RULE_IGNORE_TAGS = 1 << 6;
const RULE_IGNORE_TEXT = 1 << 7;
const RULE_IGNORE_WHITESPACE = 1 << 8;
const RULE_IS_TRANSPARENT = 1 << 9;
const RULE_PREVENT_BR = 1 << 10;
const RULE_SUSPEND_AUTO_BR = 1 << 11;
const RULE_TRIM_FIRST_LINE = 1 << 12;
/**#@-*/
/**
* @const Bitwise disjunction of rules related to automatic line breaks
*/
const RULES_AUTO_LINEBREAKS = RULE_DISABLE_AUTO_BR | RULE_ENABLE_AUTO_BR | RULE_SUSPEND_AUTO_BR;
/**
* @const Bitwise disjunction of rules that are inherited by subcontexts
*/
const RULES_INHERITANCE = RULE_ENABLE_AUTO_BR;
/**
* @const All the characters that are considered whitespace
*/
const WHITESPACE = " \n\t";
/**
* @type {!Object.<string,number>} Number of open tags for each tag name
*/
let cntOpen;
/**
* @type {!Object.<string,number>} Number of times each tag has been used
*/
let cntTotal;
/**
* @type {!Object} Current context
*/
let context;
/**
* @type {number} How hard the parser has worked on fixing bad markup so far
*/
let currentFixingCost;
/**
* @type {?Tag} Current tag being processed
*/
let currentTag;
/**
* @type {boolean} Whether the output contains "rich" tags, IOW any tag that is not <p> or <br/>
*/
let isRich;
/**
* @type {!Logger} This parser's logger
*/
let logger = new Logger;
/**
* @type {number} How hard the parser should work on fixing bad markup
*/
let maxFixingCost = 10000;
/**
* @type {!Object} Associative array of namespace prefixes in use in document (prefixes used as key)
*/
let namespaces;
/**
* @type {!Array.<!Tag>} Stack of open tags (instances of Tag)
*/
let openTags;
/**
* @type {string} This parser's output
*/
let output;
/**
* @type {!Object.<!Object>}
*/
const plugins;
/**
* @type {number} Position of the cursor in the original text
*/
let pos;
/**
* @type {!Object} Variables registered for use in filters
*/
const registeredVars;
/**
* @type {!Object} Root context, used at the root of the document
*/
const rootContext;
/**
* @type {!Object} Tags' config
*/
const tagsConfig;
/**
* @type {!Array.<!Tag>} Tag storage
*/
let tagStack;
/**
* @type {boolean} Whether the tags in the stack are sorted
*/
let tagStackIsSorted;
/**
* @type {string} Text being parsed
*/
let text;
/**
* @type {number} Length of the text being parsed
*/
let textLen;
/**
* @type {number} Counter incremented everytime the parser is reset. Used to as a canary to detect
* whether the parser was reset during execution
*/
let uid = 0;
/**
* @type {number} Position before which we output text verbatim, without paragraphs or linebreaks
*/
let wsPos;
//==========================================================================
// Public API
//==========================================================================
/**
* Disable a tag
*
* @param {string} tagName Name of the tag
*/
function disableTag(tagName)
{
if (tagsConfig[tagName])
{
copyTagConfig(tagName).isDisabled = true;
}
}
/**
* Enable a tag
*
* @param {string} tagName Name of the tag
*/
function enableTag(tagName)
{
if (tagsConfig[tagName])
{
copyTagConfig(tagName).isDisabled = false;
}
}
/**
* Get this parser's Logger instance
*
* @return {!Logger}
*/
function getLogger()
{
return logger;
}
/**
* Parse a text
*
* @param {string} _text Text to parse
* @return {string} XML representation
*/
function parse(_text)
{
// Reset the parser and save the uid
reset(_text);
let _uid = uid;
// Do the heavy lifting
executePluginParsers();
processTags();
// Finalize the document
finalizeOutput();
// Check the uid in case a plugin or a filter reset the parser mid-execution
if (uid !== _uid)
{
throw 'The parser has been reset during execution';
}
// Log a warning if the fixing cost limit was exceeded
if (currentFixingCost > maxFixingCost)
{
logger.warn('Fixing cost limit exceeded');
}
return output;
}
/**
* Reset the parser for a new parsing
*
* @param {string} _text Text to be parsed
*/
function reset(_text)
{
// Normalize CR/CRLF to LF, remove characters that aren't allowed in XML
_text = _text.replace(/\r\n?/g, "\n");
_text = _text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFFE\uFFFF]/g, '');
// Clear the logs
logger.clear();
// Initialize the rest
cntOpen = {};
cntTotal = {};
currentFixingCost = 0;
currentTag = null;
isRich = false;
namespaces = {};
openTags = [];
output = '';
pos = 0;
tagStack = [];
tagStackIsSorted = false;
text = _text;
textLen = text.length;
wsPos = 0;
// Initialize the root context
context = rootContext;
context.inParagraph = false;
// Bump the UID
++uid;
}
/**
* Change a tag's tagLimit
*
* NOTE: the default tagLimit should generally be set during configuration instead
*
* @param {string} tagName The tag's name, in UPPERCASE
* @param {number} tagLimit
*/
function setTagLimit(tagName, tagLimit)
{
if (tagsConfig[tagName])
{
copyTagConfig(tagName).tagLimit = tagLimit;
}
}
/**
* Change a tag's nestingLimit
*
* NOTE: the default nestingLimit should generally be set during configuration instead
*
* @param {string} tagName The tag's name, in UPPERCASE
* @param {number} nestingLimit
*/
function setNestingLimit(tagName, nestingLimit)
{
if (tagsConfig[tagName])
{
copyTagConfig(tagName).nestingLimit = nestingLimit;
}
}
/**
* Copy a tag's config
*
* This method ensures that the tag's config is its own object and not shared with another
* identical tag
*
* @param {string} tagName Tag's name
* @return {!Object} Tag's config
*/
function copyTagConfig(tagName)
{
let tagConfig = {}, k;
for (k in tagsConfig[tagName])
{
tagConfig[k] = tagsConfig[tagName][k];
}
return tagsConfig[tagName] = tagConfig;
}
//==========================================================================
// Output handling
//==========================================================================
/**
* Replace Unicode characters outside the BMP with XML entities in the output
*/
function encodeUnicodeSupplementaryCharacters()
{
output = output.replace(
/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
encodeUnicodeSupplementaryCharactersCallback
);
}
/**
* Encode given surrogate pair into an XML entity
*
* @param {string} pair Surrogate pair
* @return {string} XML entity
*/
function encodeUnicodeSupplementaryCharactersCallback(pair)
{
let cp = (pair.charCodeAt(0) << 10) + pair.charCodeAt(1) - 56613888;
return '&#' + cp + ';';
}
/**
* Finalize the output by appending the rest of the unprocessed text and create the root node
*/
function finalizeOutput()
{
let tmp;
// Output the rest of the text and close the last paragraph
outputText(textLen, 0, true);
// Remove empty tag pairs, e.g. <I><U></U></I> as well as empty paragraphs
do
{
tmp = output;
output = output.replace(/<([^ />]+)[^>]*><\/\1>/g, '');
}
while (output !== tmp);
// Merge consecutive <i> tags
output = output.replace(/<\/i><i>/g, '');
// Remove illegal characters from the output to ensure it's valid XML
output = output.replace(/[\x00-\x08\x0B-\x1F\uFFFE\uFFFF]/g, '');
// Encode Unicode characters that are outside of the BMP
encodeUnicodeSupplementaryCharacters();
// Use a <r> root if the text is rich, or <t> for plain text (including <p></p> and <br/>)
let tagName = (isRich) ? 'r' : 't';
// Prepare the root node with all the namespace declarations
tmp = '<' + tagName;
if (HINT.namespaces)
{
for (let prefix in namespaces)
{
tmp += ' xmlns:' + prefix + '="urn:s9e:TextFormatter:' + prefix + '"';
}
}
output = tmp + '>' + output + '</' + tagName + '>';
}
/**
* Append a tag to the output
*
* @param {!Tag} tag Tag to append
*/
function outputTag(tag)
{
isRich = true;
let tagName = tag.getName(),
tagPos = tag.getPos(),
tagLen = tag.getLen(),
tagFlags = tag.getFlags(),
skipBefore = 0,
skipAfter = 0;
if (HINT.RULE_IGNORE_WHITESPACE && (tagFlags & RULE_IGNORE_WHITESPACE))
{
skipBefore = 1;
skipAfter = (tag.isEndTag()) ? 2 : 1;
}
// Current paragraph must end before the tag if:
// - the tag is a start (or self-closing) tag and it breaks paragraphs, or
// - the tag is an end tag (but not self-closing)
let closeParagraph = !!(!tag.isStartTag() || (HINT.RULE_BREAK_PARAGRAPH && (tagFlags & RULE_BREAK_PARAGRAPH)));
// Let the cursor catch up with this tag's position
outputText(tagPos, skipBefore, closeParagraph);
// Capture the text consumed by the tag
let tagText = (tagLen)
? htmlspecialchars_noquotes(text.substring(tagPos, tagPos + tagLen))
: '';
// Output current tag
if (tag.isStartTag())
{
// Handle paragraphs before opening the tag
if (!HINT.RULE_BREAK_PARAGRAPH || !(tagFlags & RULE_BREAK_PARAGRAPH))
{
outputParagraphStart(tagPos);
}
// Record this tag's namespace, if applicable
if (HINT.namespaces)
{
let colonPos = tagName.indexOf(':');
if (colonPos > 0)
{
namespaces[tagName.substring(0, colonPos)] = 0;
}
}
// Open the start tag and add its attributes, but don't close the tag
output += '<' + tagName;
// We output the attributes in lexical order. Helps canonicalizing the output and could
// prove useful someday
let attributes = tag.getAttributes(),
attributeNames = [];
for (let attrName in attributes)
{
attributeNames.push(attrName);
}
attributeNames.sort((a, b) => (a > b) ? 1 : -1);
attributeNames.forEach(
(attrName) =>
{
output += ' ' + attrName + '="' + htmlspecialchars_compat(attributes[attrName].toString()).replace(/\n/g, ' ') + '"';
}
);
if (tag.isSelfClosingTag())
{
if (tagLen)
{
output += '>' + tagText + '</' + tagName + '>';
}
else
{
output += '/>';
}
}
else if (tagLen)
{
output += '><s>' + tagText + '</s>';
}
else
{
output += '>';
}
}
else
{
if (tagLen)
{
output += '<e>' + tagText + '</e>';
}
output += '</' + tagName + '>';
}
// Move the cursor past the tag
pos = tagPos + tagLen;
// Skip newlines (no other whitespace) after this tag
wsPos = pos;
while (skipAfter && wsPos < textLen && text[wsPos] === "\n")
{
// Decrement the number of lines to skip
--skipAfter;
// Move the cursor past the newline
++wsPos;
}
}
/**
* Output the text between the cursor's position (included) and given position (not included)
*
* @param {number} catchupPos Position we're catching up to
* @param {number} maxLines Maximum number of lines to ignore at the end of the text
* @param {boolean} closeParagraph Whether to close the paragraph at the end, if applicable
*/
function outputText(catchupPos, maxLines, closeParagraph)
{
if (closeParagraph)
{
if (!(context.flags & RULE_CREATE_PARAGRAPHS))
{
closeParagraph = false;
}
else
{
// Ignore any number of lines at the end if we're closing a paragraph
maxLines = -1;
}
}
if (pos >= catchupPos)
{
// We're already there, close the paragraph if applicable and return
if (closeParagraph)
{
outputParagraphEnd();
}
}
// Skip over previously identified whitespace if applicable
if (wsPos > pos)
{
let skipPos = Math.min(catchupPos, wsPos);
output += text.substring(pos, skipPos);
pos = skipPos;
if (pos >= catchupPos)
{
// Skipped everything. Close the paragraph if applicable and return
if (closeParagraph)
{
outputParagraphEnd();
}
}
}
let catchupText;
// Test whether we're even supposed to output anything
if (HINT.RULE_IGNORE_TEXT && context.flags & RULE_IGNORE_TEXT)
{
catchupText = text.substring(pos, catchupPos);
// If the catchup text is not entirely composed of whitespace, we put it inside ignore tags
if (!/^[ \n\t]*$/.test(catchupText))
{
catchupText = '<i>' + htmlspecialchars_noquotes(catchupText) + '</i>';
}
output += catchupText;
pos = catchupPos;
if (closeParagraph)
{
outputParagraphEnd();
}
return;
}
// Compute the amount of text to ignore at the end of the output
let ignorePos = catchupPos,
ignoreLen = 0;
// Ignore as many lines (including whitespace) as specified
while (maxLines && --ignorePos >= pos)
{
let c = text[ignorePos];
if (c !== ' ' && c !== "\n" && c !== "\t")
{
break;
}
if (c === "\n")
{
--maxLines;
}
++ignoreLen;
}
// Adjust catchupPos to ignore the text at the end
catchupPos -= ignoreLen;
// Break down the text in paragraphs if applicable
if (HINT.RULE_CREATE_PARAGRAPHS && context.flags & RULE_CREATE_PARAGRAPHS)
{
if (!context.inParagraph)
{
outputWhitespace(catchupPos);
if (catchupPos > pos)
{
outputParagraphStart(catchupPos);
}
}
// Look for a paragraph break in this text
let pbPos = text.indexOf("\n\n", pos);
while (pbPos > -1 && pbPos < catchupPos)
{
outputText(pbPos, 0, true);
outputParagraphStart(catchupPos);
pbPos = text.indexOf("\n\n", pos);
}
}
// Capture, escape and output the text
if (catchupPos > pos)
{
catchupText = htmlspecialchars_noquotes(
text.substring(pos, catchupPos)
);
// Format line breaks if applicable
if (HINT.RULE_ENABLE_AUTO_BR && (context.flags & RULES_AUTO_LINEBREAKS) === RULE_ENABLE_AUTO_BR)
{
catchupText = catchupText.replace(/\n/g, "<br/>\n");
}
output += catchupText;
}
// Close the paragraph if applicable
if (closeParagraph)
{
outputParagraphEnd();
}
// Add the ignored text if applicable
if (ignoreLen)
{
output += text.substring(catchupPos, catchupPos + ignoreLen);
}
// Move the cursor past the text
pos = catchupPos + ignoreLen;
}
/**
* Output a linebreak tag
*
* @param {!Tag} tag
*/
function outputBrTag(tag)
{
outputText(tag.getPos(), 0, false);
output += '<br/>';
}
/**
* Output an ignore tag
*
* @param {!Tag} tag
*/
function outputIgnoreTag(tag)
{
let tagPos = tag.getPos(),
tagLen = tag.getLen();
// Capture the text to ignore
let ignoreText = text.substring(tagPos, tagPos + tagLen);
// Catch up with the tag's position then output the tag
outputText(tagPos, 0, false);
output += '<i>' + htmlspecialchars_noquotes(ignoreText) + '</i>';
isRich = true;
// Move the cursor past this tag
pos = tagPos + tagLen;
}
/**
* Start a paragraph between current position and given position, if applicable
*
* @param {number} maxPos Rightmost position at which the paragraph can be opened
*/
function outputParagraphStart(maxPos)
{
if (!HINT.RULE_CREATE_PARAGRAPHS)
{
return;
}
// Do nothing if we're already in a paragraph, or if we don't use paragraphs
if (context.inParagraph
|| !(context.flags & RULE_CREATE_PARAGRAPHS))
{
return;
}
// Output the whitespace between pos and maxPos if applicable
outputWhitespace(maxPos);
// Open the paragraph, but only if it's not at the very end of the text
if (pos < textLen)
{
output += '<p>';
context.inParagraph = true;
}
}
/**
* Close current paragraph at current position if applicable
*/
function outputParagraphEnd()
{
// Do nothing if we're not in a paragraph
if (!context.inParagraph)
{
return;
}
output += '</p>';
context.inParagraph = false;
}
/**
* Output the content of a verbatim tag
*
* @param {!Tag} tag
*/
function outputVerbatim(tag)
{
let flags = context.flags;
context.flags = tag.getFlags();
outputText(currentTag.getPos() + currentTag.getLen(), 0, false);
context.flags = flags;
}
/**
* Skip as much whitespace after current position as possible
*
* @param {number} maxPos Rightmost character to be skipped
*/
function outputWhitespace(maxPos)
{
while (pos < maxPos && " \n\t".indexOf(text[pos]) > -1)
{
output += text[pos];
++pos;
}
}
//==========================================================================
// Plugins handling
//==========================================================================
/**
* Disable a plugin
*
* @param {string} pluginName Name of the plugin
*/
function disablePlugin(pluginName)
{
if (plugins[pluginName])
{
plugins[pluginName].isDisabled = true;
}
}
/**
* Enable a plugin
*
* @param {string} pluginName Name of the plugin
*/
function enablePlugin(pluginName)
{
if (plugins[pluginName])
{
plugins[pluginName].isDisabled = false;
}
}
/**
* Execute given plugin
*
* @param {string} pluginName Plugin's name
*/
function executePluginParser(pluginName)
{
let pluginConfig = plugins[pluginName];
if (pluginConfig.quickMatch && text.indexOf(pluginConfig.quickMatch) < 0)
{
return;
}
let matches = [];
if (HINT.regexp && HINT.regexpLimit && typeof pluginConfig.regexp !== 'undefined' && typeof pluginConfig.regexpLimit !== 'undefined')
{
matches = getMatches(pluginConfig.regexp, pluginConfig.regexpLimit);
if (!matches.length)
{
return;
}
}
// Execute the plugin's parser, which will add tags via addStartTag() and others
getPluginParser(pluginName)(text, matches);
}
/**
* Execute all the plugins
*/
function executePluginParsers()
{
for (let pluginName in plugins)
{
if (!plugins[pluginName].isDisabled)
{
executePluginParser(pluginName);
}
}
}
/**
* Get regexp matches in a manner similar to preg_match_all() with PREG_SET_ORDER | PREG_OFFSET_CAPTURE
*
* @param {!RegExp} regexp
* @param {number} limit
* @return {!Array.<!Array>}
*/
function getMatches(regexp, limit)
{
// Reset the regexp
regexp.lastIndex = 0;
let matches = [], cnt = 0, m;
while (++cnt <= limit && (m = regexp.exec(text)))
{
// NOTE: coercing m.index to a number because Closure Compiler thinks pos is a string otherwise
let pos = m.index,
match = [[m[0], pos]],
i = 0;
while (++i < m.length)
{
let str = m[i];
// Sub-expressions that were not evaluated return undefined
if (str === undefined)
{
match.push(['', -1]);
}
else
{
match.push([str, text.indexOf(str, pos)]);
pos += str.length;
}
}
matches.push(match);
}
return matches;
}
/**
* Get the callback for given plugin's parser
*
* @param {string} pluginName
* @return {function(string, !Array)}
*/
function getPluginParser(pluginName)
{
return plugins[pluginName].parser;
}
/**
* Register a parser
*
* Can be used to add a new parser with no plugin config, or pre-generate a parser for an
* existing plugin
*
* @param {string} pluginName
* @param {!Function} parser
* @param {?RegExp=} regexp
* @param {number=} limit
*/
function registerParser(pluginName, parser, regexp, limit)
{
// Create an empty config for this plugin to ensure it is executed
if (!plugins[pluginName])
{
plugins[pluginName] = {};
}
if (regexp)
{
plugins[pluginName].regexp = regexp;
plugins[pluginName].limit = limit || Infinity;
}
plugins[pluginName].parser = parser;
}
//==========================================================================
// Rules handling
//==========================================================================
/**
* Apply closeAncestor rules associated with given tag
*
* @param {!Tag} tag Tag
* @return {boolean} Whether a new tag has been added
*/
function closeAncestor(tag)
{
if (!HINT.closeAncestor)
{
return false;
}
if (openTags.length)
{
let tagName = tag.getName(),
tagConfig = tagsConfig[tagName];
if (tagConfig.rules.closeAncestor)
{
let i = openTags.length;
while (--i >= 0)
{
let ancestor = openTags[i],
ancestorName = ancestor.getName();
if (tagConfig.rules.closeAncestor[ancestorName])
{
++currentFixingCost;
// We have to close this ancestor. First we reinsert this tag...
tagStack.push(tag);
// ...then we add a new end tag for it with a better priority
addMagicEndTag(ancestor, tag.getPos(), tag.getSortPriority() - 1);
return true;
}
}
}
}
return false;
}
/**
* Apply closeParent rules associated with given tag
*
* @param {!Tag} tag Tag
* @return {boolean} Whether a new tag has been added
*/
function closeParent(tag)
{
if (!HINT.closeParent)
{
return false;
}
if (openTags.length)
{
let tagName = tag.getName(),
tagConfig = tagsConfig[tagName];
if (tagConfig.rules.closeParent)
{
let parent = openTags[openTags.length - 1],
parentName = parent.getName();
if (tagConfig.rules.closeParent[parentName])
{
++currentFixingCost;
// We have to close that parent. First we reinsert the tag...
tagStack.push(tag);
// ...then we add a new end tag for it with a better priority
addMagicEndTag(parent, tag.getPos(), tag.getSortPriority() - 1);
return true;
}
}
}
return false;
}
/**
* Apply the createChild rules associated with given tag
*
* @param {!Tag} tag Tag
*/
function createChild(tag)