-
Notifications
You must be signed in to change notification settings - Fork 5
/
smartypants.mjs
757 lines (757 loc) · 22 KB
/
smartypants.mjs
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
const tags_to_skip = /<(\/?)(?:pre|code|kbd|script|math)[^>]*>/i;
/**
* @param text text to be parsed
* @param attr value of the smart_quotes="" attribute
*/
const SmartyPants = (text = '', attr = '1') => {
var do_quotes;
var do_backticks;
var do_dashes;
var do_ellipses;
var do_stupefy;
var convert_quot = 0;
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
/**
* Parse attributes:
* 0 : do nothing
* 1 : set all
* 2 : set all, using old school en- and em- dash shortcuts
* 3 : set all, using inverted old school en and em- dash shortcuts
*
* q : quotes
* b : backtick quotes (``double'' only)
* B : backtick quotes (``double'' and `single')
* d : dashes
* D : old school dashes
* i : inverted old school dashes
* e : ellipses
* w : convert " entities to " for Dreamweaver users
*/
if (attr === '0') {
// Do nothing
return text;
}
else if (attr === '1') {
// Do everything, turn all options on.
do_quotes = 1;
do_backticks = 1;
do_dashes = 1;
do_ellipses = 1;
}
else if (attr === '2') {
// Do everything, turn all options on, use old school dash shorthand.
do_quotes = 1;
do_backticks = 1;
do_dashes = 2;
do_ellipses = 1;
}
else if (attr === '3') {
// Do everything, turn all options on, use inverted old school dash shorthand.
do_quotes = 1;
do_backticks = 1;
do_dashes = 3;
do_ellipses = 1;
}
else if (attr === '-1') {
// Special "stupefy" mode.
do_stupefy = 1;
}
else {
for (let i = 0; i < attr.length; i++) {
let c = attr[i];
if (c === 'q') {
do_quotes = 1;
}
if (c === 'b') {
do_backticks = 1;
}
if (c === 'B') {
do_backticks = 2;
}
if (c === 'd') {
do_dashes = 1;
}
if (c === 'D') {
do_dashes = 2;
}
if (c === 'i') {
do_dashes = 3;
}
if (c === 'e') {
do_ellipses = 1;
}
if (c === 'w') {
convert_quot = 1;
}
}
}
var tokens = _tokenize(text);
var result = '';
/**
* Keep track of when we're inside <pre> or <code> tags.
*/
var in_pre = 0;
/**
* This is a cheat, used to get some context
* for one-character tokens that consist of
* just a quote char. What we do is remember
* the last character of the previous text
* token, to use as context to curl single-
* character quote tokens correctly.
*/
var prev_token_last_char = '';
for (let i = 0; i < tokens.length; i++) {
let cur_token = tokens[i];
if (cur_token[0] === 'tag') {
result = result + cur_token[1];
let matched = tags_to_skip.exec(cur_token[1]);
if (matched) {
if (matched[1] === '/') {
in_pre = 0;
}
else {
in_pre = 1;
}
}
}
else {
let t = cur_token[1];
let last_char = t.substring(t.length - 1, t.length); // Remember last char of this token before processing.
if (!in_pre) {
t = ProcessEscapes(t);
if (convert_quot) {
t = t.replace(/$quot;/g, '"');
}
if (do_dashes) {
if (do_dashes === 1) {
t = EducateDashes(t);
}
if (do_dashes === 2) {
t = EducateDashesOldSchool(t);
}
if (do_dashes === 3) {
t = EducateDashesOldSchoolInverted(t);
}
}
if (do_ellipses) {
t = EducateEllipses(t);
}
// Note: backticks need to be processed before quotes.
if (do_backticks) {
t = EducateBackticks(t);
if (do_backticks === 2) {
t = EducateSingleBackticks(t);
}
}
if (do_quotes) {
if (t === '\'') {
// Special case: single-character ' token
if (/\S/.test(prev_token_last_char)) {
t = '’';
}
else {
t = '‘';
}
}
else if (t === '"') {
// Special case: single-character " token
if (/\S/.test(prev_token_last_char)) {
t = '”';
}
else {
t = '“';
}
}
else {
// Normal case:
t = EducateQuotes(t);
}
}
if (do_stupefy) {
t = StupefyEntities(t);
}
}
prev_token_last_char = last_char;
result = result + t;
}
}
return result;
};
const SmartQuotes = (text = '', attr = '1') => {
/**
* should we educate ``backticks'' -style quotes?
*/
// var do_backticks:number;
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
if (attr === '0') {
// Do nothing
return text;
// } else if (attr === '2') {
// // smarten ``backticks'' -style quotes
// do_backticks = 1;
// } else {
// do_backticks = 0;
}
/**
* Special case to handle quotes at the very end of $text when preceded by
* an HTML tag. Add a space to give the quote education algorithm a bit of
* context, so that it can guess correctly that it's a closing quote:
*/
var add_extra_space = 0;
if (/>['"]$/.test(text)) {
add_extra_space = 1; // Remember, so we can trim the extra space later.
text = text + ' ';
}
var tokens = _tokenize(text);
var result = '';
/**
* Keep track of when we're inside <pre> or <code> tags.
*/
var in_pre = 0;
/**
* This is a cheat, used to get some context
* for one-character tokens that consist of
* just a quote char. What we do is remember
* the last character of the previous text
* token, to use as context to curl single-
* character quote tokens correctly.
*/
var prev_token_last_char = '';
for (let i = 0; i < tokens.length; i++) {
let cur_token = tokens[i];
if (cur_token[0] === 'tag') {
result = result + cur_token[1];
let matched = tags_to_skip.exec(cur_token[1]);
if (matched) {
if (matched[1] === '/') {
in_pre = 0;
}
else {
in_pre = 1;
}
}
}
else {
let t = cur_token[1];
let last_char = t.substring(t.length - 1, t.length); // Remember last char of this token before processing.
if (!in_pre) {
t = ProcessEscapes(t);
if (t === '\'') {
// Special case: single-character ' token
if (/\S/.test(prev_token_last_char)) {
t = '’';
}
else {
t = '‘';
}
}
else if (t === '"') {
// Special case: single-character " token
if (/\S/.test(prev_token_last_char)) {
t = '”';
}
else {
t = '“';
}
}
else {
// Normal case:
t = EducateQuotes(t);
}
}
prev_token_last_char = last_char;
result = result + t;
}
}
if (add_extra_space) {
result = result.replace(/ $/, '');
}
return result;
};
const SmartDashes = (text = '', attr = '1') => {
// reference to the subroutine to use for dash education, default to EducateDashes:
var dash_sub_ref = EducateDashes;
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
if (attr === '0') {
// Do nothing
return text;
}
else if (attr === '2') {
// use old smart dash shortcuts, "--" for en, "---" for em
dash_sub_ref = EducateDashesOldSchool;
}
else if (attr === '3') {
// inverse of 2, "--" for em, "---" for en
dash_sub_ref = EducateDashesOldSchoolInverted;
}
var tokens = _tokenize(text);
var result = '';
/**
* Keep track of when we're inside <pre> or <code> tags.
*/
var in_pre = 0;
for (let i = 0; i < tokens.length; i++) {
let cur_token = tokens[i];
if (cur_token[0] === 'tag') {
result = result + cur_token[1];
let matched = tags_to_skip.exec(cur_token[1]);
if (matched) {
if (matched[1] === '/') {
in_pre = 0;
}
else {
in_pre = 1;
}
}
}
else {
let t = cur_token[1];
if (!in_pre) {
t = ProcessEscapes(t);
t = dash_sub_ref(t);
}
result = result + t;
}
}
return result;
};
const SmartEllipses = (text = '', attr = '1') => {
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
if (attr === '0') {
// Do nothing
return text;
}
var tokens = _tokenize(text);
var result = '';
/**
* Keep track of when we're inside <pre> or <code> tags.
*/
var in_pre = 0;
for (let i = 0; i < tokens.length; i++) {
let cur_token = tokens[i];
if (cur_token[0] === 'tag') {
result = result + cur_token[1];
let matched = tags_to_skip.exec(cur_token[1]);
if (matched) {
if (matched[1] === '/') {
in_pre = 0;
}
else {
in_pre = 1;
}
}
}
else {
let t = cur_token[1];
if (!in_pre) {
t = ProcessEscapes(t);
t = EducateEllipses(t);
}
result = result + t;
}
}
return result;
};
/**
* @param {string} str String
* @return {string} The string, with "educated" curly quote HTML entities.
*
* Example input: "Isn't this fun?"
* Example output: “Isn’t this fun?”
*/
const EducateQuotes = (str) => {
/**
* Make our own "punctuation" character class, because the POSIX-style
* [:PUNCT:] is only available in Perl 5.6 or later:
*
* JavaScript don't have punctuation class neither.
*/
var punct_class = '[!"#\$\%\'()*+,-./:;<=>?\@\[\\\]\^_`{|}~]'; // eslint-disable-line no-useless-escape
/**
* Special case if the very first character is a quote
* followed by punctuation at a non-word-break. Close the quotes by brute force:
*/
str = str.replace(new RegExp(`^'(?=${punct_class}\\B)`), '’'); // eslint-disable-line no-useless-escape
str = str.replace(new RegExp(`^"(?=${punct_class}\\B)`), '”'); // eslint-disable-line no-useless-escape
/**
* Special case for double sets of quotes, e.g.:
* <p>He said, "'Quoted' words in a larger quote."</p>
*/
str = str.replace(/"'(?=\w)/, '“‘');
str = str.replace(/'"(?=\w)/, '‘“');
/**
* Special case for decade abbreviations (the '80s):
*/
str = str.replace(/'(?=\d\d)/, '’');
var close_class = '[^\\ \\t\\r\\n\\[\\{\\(\\-]'; // eslint-disable-line no-useless-escape
var not_close_class = '[\\ \\t\\r\\n\\[\\{\\(\\-]'; // eslint-disable-line no-useless-escape
var dec_dashes = '–|—';
/**
* Get most opening single quotes:
* s {
* (
* \s | # a whitespace char, or
* | # a non-breaking space entity, or
* -- | # dashes, or
* &[mn]dash; | # named dash entities
* $dec_dashes | # or decimal entities
* &\#x201[34]; # or hex
* )
* ' # the quote
* (?=\w) # followed by a word character
* } {$1‘}xg;
*/
str = str.replace(new RegExp(`(\\s| |--|&[mn]dash;|${dec_dashes}|ȁ[34])'(?=\\w)`, 'g'), '\$1‘'); // eslint-disable-line no-useless-escape
/**
* Single closing quotes:
* s {
* ($close_class)?
* '
* (?(1)| # If $1 captured, then do nothing;
* (?=\s | s\b) # otherwise, positive lookahead for a whitespace
* ) # char or an 's' at a word ending position. This
* # is a special case to handle something like:
* # "<i>Custer</i>'s Last Stand."
* } {$1’}xgi;
*/
str = str.replace(new RegExp(`(${close_class})'`, 'g'), '\$1’'); // eslint-disable-line no-useless-escape
str = str.replace(new RegExp(`(${not_close_class}?)'(?=\\s|s\\b)`, 'g'), '\$1’'); // eslint-disable-line no-useless-escape
/**
* Any remaining single quotes should be opening ones:
*/
str = str.replace(/'/g, '‘');
/**
* Get most opening double quotes:
* s {
* (
* \s | # a whitespace char, or
* | # a non-breaking space entity, or
* -- | # dashes, or
* &[mn]dash; | # named dash entities
* $dec_dashes | # or decimal entities
* &\#x201[34]; # or hex
* )
* " # the quote
* (?=\w) # followed by a word character
* } {$1“}xg;
*/
str = str.replace(new RegExp(`(\\s| |--|&[mn]dash;|${dec_dashes}|ȁ[34])"(?=\\w)`, 'g'), '\$1“'); // eslint-disable-line no-useless-escape
/**
* Double closing quotes:
* s {
* ($close_class)?
* "
* (?(1)|(?=\s)) # If $1 captured, then do nothing;
* # if not, then make sure the next char is whitespace.
* } {$1”}xg;
*/
str = str.replace(new RegExp(`(${close_class})"`, 'g'), '\$1”'); // eslint-disable-line no-useless-escape
str = str.replace(new RegExp(`(${not_close_class}?)"(?=\\s)`, 'g'), '\$1”'); // eslint-disable-line no-useless-escape
/**
* Any remaining quotes should be opening ones.
*/
str = str.replace(/"/g, '“');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with ``backticks'' -style double quotes
* translated into HTML curly quote entities.
*
* Example input: ``Isn't this fun?''
* Example output: “Isn't this fun?”
*/
const EducateBackticks = (str) => {
str = str.replace(/``/g, '“');
str = str.replace(/''/g, '”');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with `backticks' -style single quotes
* translated into HTML curly quote entities.
*
* Example input: `Isn't this fun?'
* Example output: ‘Isn’t this fun?’
*/
const EducateSingleBackticks = (str) => {
str = str.replace(/`/g, '‘');
str = str.replace(/'/g, '’');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each instance of "--" translated to
* an em-dash HTML entity.
*/
const EducateDashes = (str) => {
str = str.replace(/--/g, '—');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each instance of "--" translated to
* an en-dash HTML entity, and each "---" translated to
* an em-dash HTML entity.
*/
const EducateDashesOldSchool = (str) => {
str = str.replace(/---/g, '—');
str = str.replace(/--/g, '–');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each instance of "--" translated to
* an em-dash HTML entity, and each "---" translated to
* an en-dash HTML entity. Two reasons why: First, unlike the
* en- and em-dash syntax supported by
* EducateDashesOldSchool(), it's compatible with existing
* entries written before SmartyPants 1.1, back when "--" was
* only used for em-dashes. Second, em-dashes are more
* common than en-dashes, and so it sort of makes sense that
* the shortcut should be shorter to type. (Thanks to Aaron
* Swartz for the idea.)
*/
const EducateDashesOldSchoolInverted = (str) => {
str = str.replace(/---/g, '–');
str = str.replace(/--/g, '—');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each instance of "..." translated to
* an ellipsis HTML entity. Also converts the case where
* there are spaces between the dots.
*
* Example input: Huh...?
* Example output: Huh…?
*/
const EducateEllipses = (str) => {
str = str.replace(/\.\.\./g, '…');
str = str.replace(/\. \. \./g, '…');
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each SmartyPants HTML entity translated to
* its ASCII counterpart.
*
* Example input: “Hello — world.”
* Example output: "Hello -- world."
*/
const StupefyEntities = (str) => {
str = str.replace(/–/g, '-'); // en-dash
str = str.replace(/—/g, '--'); // em-dash
str = str.replace(/‘/g, '\''); // open single quote
str = str.replace(/’/g, '\''); // close single quote
str = str.replace(/“/g, '"'); // open double quote
str = str.replace(/”/g, '"'); // close double quote
str = str.replace(/…/g, '...'); // ellipsis
return str;
};
/**
* @param {string} str String
* @return {string} The string, with each SmartyPants HTML entity translated to
* UTF-8 characters.
*
* Example input: “Hello ’ world.”
* Example output: "Hello — world."
*/
const EducateEntities = (text, attr = '1') => {
var do_quotes;
var do_backticks;
var do_dashes;
var do_ellipses;
// var do_stupefy:number;
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
if (attr === '0') {
// Do nothing
return text;
}
else if (attr === '1') {
// Do everything, turn all options on.
do_quotes = 1;
do_backticks = 1;
do_dashes = 1;
do_ellipses = 1;
}
else if (attr === '2') {
// Do everything, turn all options on, use old school dash shorthand.
do_quotes = 1;
do_backticks = 1;
do_dashes = 3;
do_ellipses = 1;
}
else if (attr === '3') {
// Do everything, turn all options on, use inverted old school dash shorthand.
do_quotes = 1;
do_backticks = 1;
do_dashes = 3;
do_ellipses = 1;
// } else if (attr === '-1') {
// // Special "stupefy" mode.
// do_stupefy = 1;
}
else {
for (let i = 0; i < attr.length; i++) {
let c = attr[i];
if (c === 'q') {
do_quotes = 1;
}
if (c === 'b') {
do_backticks = 1;
}
if (c === 'B') {
do_backticks = 2;
}
if (c === 'd') {
do_dashes = 1;
}
if (c === 'D') {
do_dashes = 2;
}
if (c === 'i') {
do_dashes = 3;
}
if (c === 'e') {
do_ellipses = 1;
}
}
}
if (do_dashes) {
text = text.replace(/–/g, '\u2013'); // en-dash
text = text.replace(/—/g, '\u2014'); // em-dash
}
if (do_quotes || do_backticks) {
text = text.replace(/‘/g, '\u2018'); // open single quote
text = text.replace(/’/g, '\u2019'); // close single quote
text = text.replace(/“/g, '\u201c'); // open double quote
text = text.replace(/”/g, '\u201d'); // close double quote
}
if (do_ellipses) {
text = text.replace(/…/g, '\u2026'); // ellipsis
}
return text;
};
/**
* @param {string} str String
* @return {string} The string, with each SmartyPants UTF-8 chars translated to
* its ASCII counterpart.
*
* Example input: “Hello — world.”
* Example output: "Hello -- world."
*/
const StupifyUTF8Char = (str) => {
str = str.replace(/\u2013/g, '-'); // en-dash
str = str.replace(/\u2014/g, '--'); // em-dash
str = str.replace(/\u2018/g, '\''); // open single quote
str = str.replace(/\u2019/g, '\''); // close single quote
str = str.replace(/\u201c/g, '"'); // open double quote
str = str.replace(/\u201d/g, '"'); // close double quote
str = str.replace(/\u2026/g, '...'); // ellipsis
return str;
};
/**
* @param {string} str String
* @return {string} string, with after processing the following backslash
* escape sequences. This is useful if you want to force a "dumb"
* quote or other character to appear.
*
* Escape Value
* ------ -----
* \\ \
* \" "
* \' '
* \. .
* \- -
* \` `
*
*/
const ProcessEscapes = (str) => {
str = str.replace(/\\\\/g, '\');
str = str.replace(/\\"/g, '"');
str = str.replace(/\\'/g, ''');
str = str.replace(/\\\./g, '.');
str = str.replace(/\\-/g, '-');
str = str.replace(/\\`/g, '`');
return str;
};
/**
* @param {string} str String containing HTML markup.
* @return {Array<token>} Reference to an array of the tokens comprising the input
* string. Each token is either a tag (possibly with nested,
* tags contained therein, such as <a href="<MTFoo>">, or a
* run of text between tags. Each element of the array is a
* two-element array; the first is either 'tag' or 'text';
* the second is the actual value.
*
* Based on the _tokenize() subroutine from Brad Choate's MTRegex plugin.
* <http://www.bradchoate.com/past/mtregex.php>
*/
const _tokenize = (str) => {
var pos = 0;
var len = str.length;
var tokens = [];
var match = /<!--[\s\S]*?-->|<\?.*?\?>|<[^>]*>/g;
var matched = null;
while (matched = match.exec(str)) { // eslint-disable-line no-cond-assign
if (pos < matched.index) {
let t = ['text', str.substring(pos, matched.index)];
tokens.push(t);
}
let t = ['tag', matched.toString()];
tokens.push(t);
pos = match.lastIndex;
}
if (pos < len) {
let t = ['text', str.substring(pos, len)];
tokens.push(t);
}
return tokens;
};
const smartypantsu = (text = '', attr = '1') => {
var str = SmartyPants(text, attr);
if (typeof attr === 'number') {
attr = attr.toString();
}
else {
attr = attr.replace(/\s/g, '');
}
if (attr === '-1') {
return StupifyUTF8Char(str);
}
else {
return EducateEntities(str, attr);
}
};
export { SmartyPants as smartypants };
export { SmartQuotes as smartquotes };
export { SmartDashes as smartdashes };
export { SmartEllipses as smartellipses };
export { smartypantsu };
export default SmartyPants;