-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathFixCJK_noto.user.js
2023 lines (2022 loc) · 124 KB
/
FixCJK_noto.user.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
// ==UserScript==
// @name FixCJK!
// @name:zh-CN “搞定”CJK!
// @namespace https://github.com/stecue/fixcjk
// @version 1.3.18
// @description 1) Use real bold to replace synthetic SimSun bold; 2) Regular SimSun/中易宋体 can also be substituted; 3) Reassign font fallback list (Latin AND CJK). Browser serif/sans settings are overridden; 4) Use Latin fonts for Latin part in Latin/CJK mixed texts; 5) Fix fonts and letter-spacing for CJK punctuation marks.
// @description:zh-cn 中文字体和标点设定及修正脚本
// @author [email protected]
// @license GPLv3
// @match http://*/*
// @match https://*/*
// @exclude https://*jsfiddle.net*/*
// @exclude http://*stackexchange.com/*
// @exclude https://*stackexchange.com/*
// @exclude http://*mathoverflow.net/*
// @exclude https://*.live.com/*
// @exclude https://*.wolframcloud.com/*
// @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @grant GM_addStyle
// ==/UserScript==
(function () {
'use strict';
// You can change the the following fonts/settings until the "var FixPunct=" line.
///--CJK Fonts--///
var CJKdefault = '"Microsoft YaHei",SimSun,Source Han Sans SC,Noto Sans CJK SC,"WenQuanYi Zen Hei Sharp","WenQuanYi Micro Hei"'; //The default CJK font if no sans or serif is specified. Regular weight.
var CJKSimSun= '"Microsoft YaHei","Source Han Serif SC","Source Han Sans SC Regular","Source Han Serif CN","Note Serif CJK SC","WenQuanYi Micro Hei"'; //Fonts to replace SimSun;
var CJKserif = '"Microsoft YaHei","Source Han Serif SC","Source Han Sans SC Regular","Source Han Serif CN","WenQuanYi Micro Hei"'; //Default serif fonts for CJK. Although It is intended for regular weight but some element with bold weight still use the font here. Therefore "SimSun" itself is not a good choice because it does not have a real bold font.
var CJKsans = '"Microsoft YaHei","Source Han Sans SC","Source Han Sans SC Regular","Source Han Sans CN","Noto Sans CJK SC","Noto Sans CJK SC Regular"'; //Sans-serif fonts for CJK. Regular weight.
var CJKBold = '"Microsoft YaHei","Noto Sans CJK SC Bold","Noto Sans CJK SC","Source Han Sans SC Bold","Source Han Sans SC Bold","WenQuanYi Micro Hei"'; //The "good CJK font" to replace SimSun bold. Note that some elements still use font in CJKserif defined above such as the menus on JD.com.
var CJKPunct = 'Noto Sans CJK SC,Noto Serif CJK SC,Source Han Sans SC,Source Han Serif SC,Source Han Sans CN,Source Han Serif CN,SimHei,SimSun'; //The font to use for CJK quotation marks.
var KanaSerif = 'Source Han Serif SC,Noto Serif CJK SC'; //The serif fonts for kana (假名) if no lang=ja is set.
var KanaSans = 'Source Han Sans SC,Noto Sans CJK SC'; //The sans fonts for kana (假名) if no lang=ja is set.
var JaSerif = 'Noto Serif CJK JP,Source Han Serif,Source Han Serif JP,Noto Serif CJK SC,Source Han Serif SC,MS Mincho'; //Used in lang=ja elements only. KanaSans will be overrided.
var JaSans = 'Noto Sans CJK JP,Source Han Sans,Source Han Sans JP,Noto Sans CJK SC,Source Han Sans SC,Meiryo,MS Gothic'; //Used in lang=ja elements only. KanaSerif will be overrided.
var JaDefault = JaSans; //Default fonts if no "sans" or "sans-serif" is set for lang=ja elements.
///---Latin Fonts. Note: *DO NOT* use CJK fonts for the following Latin* settings, otherwise the above CJK settings might be overwritten!---///
var LatinInSimSun = 'Ubuntu Mono'; //The Latin font in a paragraph whose font was specified to "SimSun" only.
var LatinSerif = '"PT Serif",Constantia,"Liberation Serif","Times New Roman"'; //Serif fonts for Latin script. It will be overridden by a non-virtual font in the CSS font list if present.
var LatinSans = '"Open Sans","PT Sans",Lato,Verdana,Arial'; //Sans-serif fonts for Latin script. It will be overridden by a non-virtual font in the CSS font list if present.
var LatinMono = '"DejaVu Sans Mono",Consolas'; //Monospace fonts for Latin script. It will be overridden by a non-virtual font in the CSS font list if present.
var LatinDefault = LatinSans; //The default Latin fonts if no "serif" or "sans-serif" is provided. It is also the font that will be used if the specified fonts (by the webpage) cannot be found.
///---Choose what to fix---///
var FixRegular = true; //Also fix regular fonts. You need to keep this true if you want to use "LatinInSimSun" in Latin/CJK mixed context.
var FixPunct = true; //If Latin punctions in CJK paragraph need to be fixed. Usually one needs full-width punctions in CJK context. Turn it off if the script runs too slow or HTML strings are adding to your editing area.
///=== Experimental Options. The following options are for experienced users.===///
var usePaltForCJKText = true; //If apply "palt" to CJK text (not only puncts) as well.
var usePaltForAll = false; //If apply "palt" to as much elements as possible.
var useJustify = true; //Make justify as the default alignment.
var forceAutoSpaces = true; //if enabled, no need to double-click to add spaces.
var useBroaderSpaces = false; //Now It will NOT be set to true automatically if usePaltForCJKText===true.
var useXBroaderSpaces = false; //It will override useBroaderSpaces.
var use2XBroaderSpaces = false; //It will override useXBroaderSpaces.
var use3XBroaderSpaces = false; //It will override use2XBroaderSpaces.
var scrollToFixAll = false; //Scoll to FixAll,including PMs. Might slow down the browser.
var skipJaLang = false; //Skip lang=ja elements and webpages (usually pure Japanese pages). Keep it true if you want to apply your brower's Japanese font settings.
var unifiedCJK = false; // Use Chinese fonts for lang=ja if set to "true".
var FixPureLatin = false; //Appendent the script to all elements, including pure latins. The option is here for historical reasons and usually you should use the built-in font settings of your browser.
///=== "Safe" Zone Ends Here.Do not change following code unless you know the results! ===///
//--output the version info first--//
console.log('FixCJK! version '+GM_info.script.version);
// Global runtime flags
var isScrolling = false;
var SkipLabelCJK = false; //for internal use only. It will set to true if the page is pure Eng.
if (usePaltForAll === true)
usePaltForCJKText = true;
//if (usePaltForCJKText === true)
// useBroaderSpaces = true;
var timeOut=3000; //allow maximum 3.0 seconds to run this script.
var maxlength = 11002000; //maximum length of the page HTML to check for CJK punctuations.
var maxNumElements = 810240; // maximum number of elements to process.
var CJKOnlyThreshold = 110240; // Only CJK if the number of elements reaches this threshold.
var noBonusLength = 110240; //no bonus functions such as fixing "reversed" pairs.
var noBonusTimeout = 200; //Longest time (in ms) to run bonus functions for each element.
var sqz_timeout=50; // 50ms per element seems long enough.
var invForLimit=6; //the time limit factor (actual limit is timeOut/invForLimit) for the "for loop" in Round 2 & 3.
var processedAll=true;
var ifRound1=true;
var ifRound2=true;
var ifRound3=false;
var RawFixPunct=FixPunct;
var forceNoSimSun = false; //in case SimSun is the "!important" one. Note that other fixes will not be performed for applied tags.
var debug_verbose = false; //show/hide more information on console.
var debug_00 = false; //debug codes before Rounds 1/2/3/4.
var debug_01 = false; //Turn on colors for Round 1.
var debug_02 = false;
var debug_03 = false;
var debug_04 = false;
var debug_labelCJK = false;
var debug_re_to_check = false; //"true" might slow down a lot!
var debug_spaces =false;
var debug_wrap = false;
var debug_tagSeeThrough = false;
var debug_getBeforeTags = false;
var debug_noWrapping = false;
var debug_asyncTimers = true;
var useWrap=true;
var useRemoveSpacesForSimSun=false;
var useFeedback=false;
var useCSSforSimSun=false;
var useDelayedFix=false;
var useOverallTimeOut=false;
var useSFTags=false; //FIXME: use tags may cause problems on jd.com.
var re_allpuncts=/[、,。:;!?)】〉》」』『「《〈【(“”‘’]/;
//var re_extCJK=/[“”‘’\u3000-\u30FF\u3400-\u9FBF\uFF00-\uFFEF]/;
var re_extCJK=/[“”‘’\u3000-\u9FBF\uFF00-\uFFEF]/;
var re_pureCJK=/[\u3000-\u30FF\u3400-\u9FBF\uFF00-\uFFEF]/;
var re_to_check = /^\uEEEE/; //use ^\uEEEE for placeholder. Avoid using the "m" or "g" modifier for long document, but the difference seems small?
///=== The following variables should be strictly for internal use only.====///
var refixing=false;
var refixingFonts=false;
var respacing=false;
var lastspacing=0.0;
var rspLength=3; //If the font-list reaches the length here, the author is probably responsible enough to cover most Latin/English environment.
var waitForDoubleClick=200;
var SkippedTagsForFonts=/^(HTML|TITLE|HEAD|LINK|BODY|SCRIPT|noscript|META|STYLE|AUDIO|video|source|AREA|BASE|canvas|figure|map|object|textarea)$/i;
var SkippedTagsForMarks=/^(HTML|TITLE|HEAD|LINK|BODY|SCRIPT|noscript|META|STYLE|AUDIO|video|source|AREA|BASE|canvas|embed|figure|map|object|textarea|input|code|pre|time|tt|BUTTON|select|option|label|fieldset|datalist|keygen|output)$/i;
var SkippedTags=SkippedTagsForFonts;
//It seems that "lang" cannot be calculated. Just use node.getAttribute("lang") to get the lang of current elements.
var SkippedLangs='(xa|en)';
if (skipJaLang === true)
SkippedLangs=RegExp(SkippedLangs.replace(/xa/,'ja'),'i');
else
SkippedLangs=RegExp(SkippedLangs,'i');
var pureLatinTags=/^(TITLE|HEAD|LINK|SCRIPT|META|STYLE|AUDIO|video|source|AREA|BASE|canvas|figure|map|object|textarea|svg)$/i; //No CJK labeling for the elements and their desedents.
var stopTags=/^(SUB|SUP|BR|VR)$/i; //The "see-through" stops at these tags.
var stopClasses='mw-editsection,date';
var upEnoughTags=/^(address|article|aside|blockquote|canvas|dd|div|dl|dt|fieldset|figcaption|figure|footer|form|H[1-6]|header|hgroup|hr|li|main|nav|noscript|ol|output|p|pre|section|table|td|th|tr|tfoot|ul|video|BODY)$/ig; //"See-Through" stops here, the "block-lelvel" elements.
var ignoredTags=/^(math)$/i;
var noWrappingClasses='pl-c,toggle-comment,answer-date-link'; //Also known as "no wrapping list". Only wrapped CJK will be treated.
//noWrappingClasses=noWrappingClasses+',PollXChoice-choice--text'; //PollXChoice-choice--text from twitter, see issue #113.
if ( document.URL.match(/(bgm\.tv|bangumi.tv)/) )
noWrappingClasses=noWrappingClasses+',userInfo,userName';
if ( document.URL.match(/(www\.bilibili\.com|bilibili\.com)/) )
noWrappingClasses=noWrappingClasses+',update on,update ,update,v-wrap'; //Issue #129.
console.log('The following classes won\'t be treated:\n'+noWrappingClasses);
//Just define a "dumb" noWrappingHRefs.
var noWrappingHRefs=/^\uE000\uE000\uE000/;
//The folloing noWraping HRefs is still for bgm.tv
if ( document.URL.match(/(bgm\.tv|bangumi.tv)/) )
noWrappingHRefs=/\/user\//;
var preSimSunList='c30,c31,c32,c33,c34,c35,c36,c37,c38,c39,c40,c41,c42,c43,c44,c45,c46';
var preSimSunTags=/^(pre|code|tt)$/i;
//Safe2FixCJK\uE000,\uE211,\uE985,\uE699
var CJKAttrList='CJK2Fix,MarksFixedE135,FontsFixedCJK,Safe2FixCJK,PunctSpace2Fix,CJKTestedAndLabeled,SimSun2Fix,SimSunFixedCJK,LargeSimSun2Fix,checkSpacedQM,wrappedCJK2Fix,preCode,preMath,SpacesFixedE133';
var re_autospace_url=/zhihu\.com|guokr\.com|changhai\.org|wikipedia\.org|greasyfork\.org|github\.com/;
var preCodeTags='userInfo,code,pre,tt'; //Is this the same as "SkippedTagsForMarks"?
var preMathTags='math'; //Do not change puncts as well as fonts. Just like "math".
var t_start = performance.now();
var t_stop = t_start;
var re_simsun = / *simsun *| *宋体 *| *ËÎÌå *| *\5b8b\4f53 */i;
var sig_sim = 'FixedCJKFont\u0020易'; //Just for SimSun;
var sig_song = 'FixedCJKFont\u0020宋'; // signature to check if change is sucssful or not.
var sig_hei = 'FixedCJKFont\u0020黑'; // signature to check if change is sucssful or not.
var sig_bold = 'FixedCJKFont\u0020粗'; // signature to check if change is sucssful or not.
var sig_default = 'FixedCJKFont\u0020默'; // signature to check if change is sucssful or not.
var sig_mono= 'FixedCJKFont\u0020均';
var sig_punct = '\uE135'; //will be attached to CJKPunct; This is used in punct fixing not font fixing(?)
var qsig_sim = '"' + sig_sim + '"'; //Quoted sinagure; Actually no need to quote.
var qsig_song= '"'+sig_song+'"';
var qsig_hei = '"' + sig_hei + '"'; //Quoted sinagure;
var qsig_bold = '"' + sig_bold + '"';
var qsig_default = '"' + sig_default + '"';
var genPunct='FixedPMSans'; //Different from sig_punct
var qpreCJK = CJKdefault;
var qCJK = LatinDefault + ',' + CJKdefault + ',' + qsig_default;
var qCJK_ja = LatinDefault + ',' + JaDefault + ',' + qsig_default;
var qSimSun = qsig_sim+','+LatinInSimSun + ',' + CJKSimSun;
var qLargeSimSun = qsig_sim+','+ LatinSerif + ',' + 'SimSun';
var qBold = LatinInSimSun + ',' + CJKBold + ',' + qsig_bold;
var qsans = LatinSans + ',FixKanaSans,'+CJKsans + ',' + qsig_hei + ',' + 'sans-serif'; //To replace "sans-serif"
var qsans_ja = dequote(LatinSans + ',' + JaSans + ',' + qsig_hei + ',' + 'sans-serif');
var qserif = LatinSerif + ',FixKanaSerif,'+CJKserif +','+qsig_song+ ',' + 'serif'; //To replace "serif"
var qserif_ja = dequote(LatinSans + ',' + JaSerif + ',' + qsig_song + ',' + 'serif');
var qmono = sig_mono+','+LatinMono + ',' + CJKdefault + ',' + qsig_default + ',' + 'monospace'; //To replace "monospace".
//--Check the length of the webpage --//
var all = document.getElementsByTagName('*');
var NumAllDOMs=all.length;
var bodyhtml=document.getElementsByTagName("HTML");
if (bodyhtml[0].innerHTML.length > maxlength) {
console.log('FixCJK!: HTML too long, skip everything. Exiting now...');
ifRound1=false;
ifRound2=false;
ifRound3=false;
FixPunct=false;
}
else if (!(bodyhtml[0].innerHTML.match(/[\u3000-\u30FF\u3400-\u9FBF\uFF00-\uFFEF]/))) {
if (debug_verbose===true) {console.log('FixCJK!: Checking for CJK took '+((performance.now()-t_stop)/1000.0).toFixed(3)+' seconds. No CJK found.');}
if (debug_verbose===true) {console.log('FixCJK!: No need to check CJK punctuations.');}
FixPunct=false;
}
else {
if (debug_verbose===true) {console.log('FixCJK!: Checking for CJK took '+((performance.now()-t_stop)/1000.0).toFixed(3)+' seconds. CJK found.');}
//FixPunct=true;
}
var i = 0;
var max = all.length;
var child = all[i].firstChild;
var if_replace = false;
var font_str = ""; //window.getComputedStyle(all[i], null).getPropertyValue('font-family');
var fweight = ""; //window.getComputedStyle(all[i], null).getPropertyValue('font-weight');
var re_sans0 = /^ ?sans ?$|^ ?sans-serif ?$/i;
var re_serif = /^ ?serif ?$/i;
var re_mono0 = /^ ?mono ?$|^ ?monospace ?$/i;
//letter-spacing options
var kern_consec_ll='0.0em'; //。” or ))
var kern_consec_rr='0.0em'; //((
var kern_consec_lr='0.0em'; //)(
var kern_ind_open='0.22em'; //margin-left for opening punct.
var kern_ind_close='0.22em'; //margin-right closing punct.
//Whether to use the native embeded OpenType kerning or not, see
//https://helpx.adobe.com/typekit/using/open-type-syntax.html
var useNativeKerning=false;
if (useNativeKerning === true) {
kern_ind_open='0.0em';
kern_ind_close='0.0em';
}
//Check if the font definitions are valid
if (check_fonts(CJKdefault, 'CJKdefault') === false)
return false;
else if (check_fonts(CJKserif, 'CJKserif') === false)
return false;
else if (check_fonts(CJKsans, 'CJKsans') === false)
return false;
else if (check_fonts(CJKBold, 'CJKBold') === false)
return false;
else if (check_fonts(LatinInSimSun, 'LatinInSimSun') === false)
return false;
else if (check_fonts(LatinSans, 'LatinSans') === false)
return false;
else if (check_fonts(LatinSerif, 'LatinSerif') === false)
return false;
else if (check_fonts(LatinMono, 'LatinMono') === false)
return false;
else {
}
//---Some inital checkup and output the version info--//
if (debug_00 === true) {
console.log(dequote('"SimSun","Times New Roman"""""'));
console.log(qCJK);
}
//Assign fonts for puncts:
var punctStyle='@font-face { font-family: '+genPunct+';\n src: '+AddLocal(CJKPunct)+';\n unicode-range: U+3000-303F,U+FF00-FFEF;}';
//Use punct fonts of SimHei in SimSun;
punctStyle=punctStyle+'\n@font-face {font-family:FixedCJKFont\u0020易;\n src:local(SimHei);\n unicode-range: U+A0-B6,U+B8-2FF,U+2000-2017,U+201E-2FFF;}';
punctStyle=punctStyle+'\n@font-face {font-family:SimVecA;\n src:local(Ubuntu Mono);\n unicode-range: U+0-7F;}';
punctStyle=punctStyle+'\n@font-face {font-family:SimVecS;\n src:local(SimHei);\n unicode-range: U+A0-33FF;}';
punctStyle=punctStyle+'\n@font-face {font-family:SimVecC;\n src:local(Noto Sans CJK SC DemiLight);}';
//Make sure we only use the good "Chinese" part of YaHei.
punctStyle=punctStyle+'\n@font-face { font-family: Microsoft YaHei UI;\n src:local(Noto Sans CJK SC DemiLight);\n font-weight: normal;}';
punctStyle=punctStyle+'\n@font-face { font-family: Microsoft YaHei UI;\n src:local(Noto Sans CJK SC Bold);\n font-weight: bold;}';
punctStyle=punctStyle+'\n@font-face { font-family: 微软雅黑;\n src:local(Noto Sans CJK SC DemiLight);\n font-weight: normal;}';
punctStyle=punctStyle+'\n@font-face { font-family: 微软雅黑;\n src:local(Noto Sans CJK SC Bold);\n font-weight: bold;}';
punctStyle=punctStyle+'\n@font-face { font-family: 雅黑;\n src:local(Noto Sans CJK SC DemiLight);\n font-weight: normal;}';
punctStyle=punctStyle+'\n@font-face { font-family: 雅黑;\n src:local(Noto Sans CJK SC Bold);\n font-weight: bold;}';
punctStyle=punctStyle+'\n@font-face { font-family: 黑体;\n src:local(Noto Sans CJK SC DemiLight);\n font-weight: normal;}';
punctStyle=punctStyle+'\n@font-face { font-family: 黑体;\n src:local(Noto Sans CJK SC Bold);\n font-weight: bold;}';
punctStyle=punctStyle+'\n@font-face { font-family: Microsoft YaHei;\n src:local(Noto Sans CJK SC DemiLight);\n font-weight: normal;}';
punctStyle=punctStyle+'\n@font-face { font-family: Microsoft YaHei;\n src:local(Noto Sans CJK SC Bold);\n font-weight: bold;}';
if (useCSSforSimSun===true) {
punctStyle=punctStyle+'\n @font-face { font-family: SimSun;\n src: local('+FirstFontOnly('SimSun')+');\n unicode-range: U+3400-9FBF;}';
punctStyle=punctStyle+'\n @font-face { font-family: 宋体;\n src: local('+FirstFontOnly('SimSun')+');\n unicode-range: U+3400-9FBF;}';
punctStyle=punctStyle+'\n @font-face { font-family: ËÎÌå;\n src: local('+FirstFontOnly('SimSun')+');\n unicode-range: U+3400-9FBF;}';
punctStyle=punctStyle+'\n @font-face { font-family: 宋体;\n src: local('+FirstFontOnly(LatinInSimSun)+');\n unicode-range: U+0000-2C7F;}';
}
punctStyle=punctStyle+'\n cjkpuns { -moz-font-feature-settings:"palt"; -webkit-font-feature-settings:"palt";font-feature-settings:"palt";}';
if (useNativeKerning === true) {
punctStyle=punctStyle+'\n cjkpuns { font-kerning: normal; }';
}
if (usePaltForCJKText === true) {
punctStyle=punctStyle+'\n cjktext {-moz-font-feature-settings:"palt"; -webkit-font-feature-settings:"palt";font-feature-settings:"palt";}';
}
if (usePaltForAll === true) {
punctStyle=punctStyle+'\n * {-moz-font-feature-settings:"palt"; -webkit-font-feature-settings:"palt";font-feature-settings:"palt";}';
}
if (debug_00===true)
console.log(punctStyle);
punctStyle=punctStyle+'\n @font-face { font-family:FixKanaSans;\n src:'+AddLocal(KanaSans)+';\n unicode-range: U+3040-30FF;}';
punctStyle=punctStyle+'\n @font-face { font-family:FixKanaSerif;\n src:'+AddLocal(KanaSerif)+';\n unicode-range: U+3040-30FF;}';
console.log('---------------@font-face values-------------')
console.log(punctStyle)
console.log('-------------End of @font-face values--------')
GM_addStyle(punctStyle);
//--Style settings done. Now let's check if we need to continue--//
var docLang = document.documentElement.getAttribute("lang")+' '; //make sure docLang is not "";
if (debug_00 === true) {
console.log(docLang);
console.log(!(!docLang.match(SkippedLangs)));
}
if ( docLang.match(SkippedLangs) ) {
if (debug_00 === true) {
console.log(document.documentElement.innerText.match(re_pureCJK) );
}
if ( !document.documentElement.innerText.match(re_pureCJK) ) {
console.log('Non-optimal lang attribute detected...Long-click or double-click to re-enable FixCJK!');
SkipLabelCJK = true;
}
}
///----------------------------
qpreCJK = dequote(qpreCJK);
qCJK = dequote(qCJK);//LatinInSimSun + ',' + CJKdefault + ',' + qsig_default;
qSimSun = dequote(qSimSun);//LatinInSimSun + ',' + CJKserif + ',' + qsig_sun;
qLargeSimSun = dequote(qLargeSimSun);//LatinInSimSun + ',' + CJKserif + ',' + qsig_sun;
qBold = dequote(qBold);//LatinInSimSun + ',' + CJKBold + ',' + qsig_bold;
qsans = dequote(qsans);//LatinSans + ',' + CJKsans + ',' + qsig_hei + ',' + 'sans-serif'; //To replace "sans-serif"
qserif = dequote(qserif);//LatinSerif + ',' + CJKserif + ',' + qsig_sun + ',' + 'serif'; //To replace "serif"
qmono = dequote(qmono);//LatinMono + ',' + CJKdefault + ',' + qsig_default + ',' + 'monospace'; //To replace "monospace".
CJKPunct=dequote(CJKPunct)+','+sig_punct;
if (debug_00===true) {console.log('Entering Loops...');}
/// ===== Labeling CJK elements === ///
t_stop=performance.now();
var debug_addTested=false;
function addTested (node,currLevel) {
if (currLevel > 5) {
if (debug_addTested===true) console.log("TOO MANY LEVELS, exiting addTested()...");
return false;
}
var child=node.firstChild;
while (child) {
if (child.nodeType===1) {
addTested(child,currLevel+1);
}
child=child.nextSibling;
}
if (node.hasAttribute("data-CJKTestedAndLabeled")) {
if (debug_addTested===true) console.log("Labeled: "+node.nodeName);
return true;
}
else {
node.setAttribute("data-CJKTestedAndLabeled","");
if (debug_addTested===true) console.log("Labeled: "+node.nodeName);
return true;
}
}
/*
function labelCJKByNode(node,levelIndex) {
var t_stop=performance.now();
if (node instanceof SVGElement) {
return false;
}
//One do need to recheck the textContent everytime "ReFix" is triggered.
if ( (levelIndex < 2) && (!node.textContent.match(re_extCJK)) ) {
if (!node.hasAttribute("data-CJKTestedAndLabeled")) {
window.setTimeout(addTested,5,node,0);
}
return true;
}
var font_str=dequote(window.getComputedStyle(node, null).getPropertyValue('font-family'));
var child=node.firstChild;
while (child) {
if (child.nodeType===3) {
if (node.hasAttribute("data-CJKTestedAndLabeled") ) {
//Do nothing if already labeled.
}
else if (font_str.match(re_simsun)) {
if (inTheClassOf(node,preSimSunList) || node.nodeName.match(preSimSunTags)) {
node.style.fontFamily=font_str.replace(re_simsun,'SimVecA,SimVecS,SimVecC');
node.setAttribute("data-CJK2Fix","");
node.setAttribute("data-CJKTestedAndLabeled","");
}
else {
var font_size=(window.getComputedStyle(node, null).getPropertyValue('font-size')).slice(0,-2);
if (font_size < 18) {
node.setAttribute("data-CJK2Fix","");
node.setAttribute("data-SimSun2Fix","");
if (!inTheClassOf(node,noWrappingClasses)) {
node.setAttribute("data-PunctSpace2Fix","");
}
}
else {
//node.style.fontFamily=font_str; //Is this to improve the speed?
node.setAttribute("data-CJK2Fix","");
node.setAttribute("data-LargeSimSun2Fix","");
if (!inTheClassOf(node,noWrappingClasses)) {
node.setAttribute("data-PunctSpace2Fix","");
}
}
}
}
else if (child.data.match(re_extCJK)) {
node.setAttribute("data-CJK2Fix","");
if (!inTheClassOf(node,noWrappingClasses)) {
node.setAttribute("data-PunctSpace2Fix","");
}
}
}
else if (child.nodeType===1) {
labelCJKByNode(child,levelIndex+1);
}
child=child.nextSibling;
}
node.setAttribute("data-CJKTestedAndLabeled","");
return true;
}
*/
function labelCJK(useCJKTimeOut) {
if (SkipLabelCJK === true) {
console.log('Skipping labelCJK...');
return false;
}
var useBFS=false;
var child=document.body.firstChild;
var maxLabelingTime=150
var all='';
/*
if (useBFS===true) {
while (child) {
if (child.nodeType===1) {
//The levelIndex of document.body is 0.
labelCJKByNode(child,1);
}
child=child.nextSibling;
}
return true;
}
*/
//Skip wrapping CJK for anchors to javascripts, otherwise the anchors will break.
all=document.querySelectorAll('a:not([data-preCode])');
for (var ia=0;ia<all.length;ia++){
//if (isScrolling == true) {alert('trying to label CJK, but in scrolling....');break;}
if (all[ia].hasAttribute("data-CJKTestedAndLabeled")) {
continue;
}
if (all[ia].hasAttribute("data-mathml")) {
console.log(all[ia]);
all[ia].setAttribute("data-preMath","");
banMathHelper(all[ia]);
}
if(all[ia].nodeName.match(/^A$/i) && all[ia].href.match(/^javascript/i) && (all[ia].textContent.match(re_extCJK)) ) {
all[ia].setAttribute("data-preCode",""); //No wrapping if in the "preCode" class.
}
}
all=document.querySelectorAll(":not([data-CJKTestedAndLabeled])");
if (useCJKTimeOut===false) {
console.log(all.length+" elements to check and label. From");
console.log(all[0]);
console.log('To');
console.log(all[all.length-1]);
}
var t_stop=performance.now();
var t_last=0;
var t_init=t_stop;
var t_overall=0;
for (var i=all.length-1;i >= 0;i--) {
//if (isScrolling == true) {alert('trying to label CJK, but in scrolling....');break;}
if (useCJKTimeOut===true && i%100 === 0) { //useCJKTimeOut===false is the "Engineering mode".
t_last=performance.now()-t_stop;
t_stop=performance.now();
t_overall=performance.now()-t_init;
}
if (i>0 && t_last>20) {
if ( debug_labelCJK===true) {
console.log("FIXME: Curr: ");
console.log(all[i]);
console.log("FIXME: Prev: ");
console.log(all[i-1]);
console.log("Labeling Last elemnent: <"+all[i-1].nodeName+">.("+all[i-1].className+") took "+t_last.toFixed(1)+" ms.");
}
if (t_last>50) {
console.log("FIXME: Labeling last element took too much time. Too slow to labelCJK after "+t_overall.toFixed(1)+" ms.");
console.log("FIXME: Only "+document.querySelectorAll("[data-CJKTestedAndLabeled]").length+" tested in total on "+document.URL);
if (debug_labelCJK===true) {console.log(all[i-1]);}
break;
}
}
if ( i%100 === 0 && t_overall > maxLabelingTime) {
console.log("FIXME: Too slow to labelCJK after "+t_overall.toFixed(1)+" ms.");
//console.log("FIXME: Only "+document.querySelectorAll("[data-CJKTestedAndLabeled]").length+" tested in total on "+document.URL);
console.log("FIXME: Only "+i+" tested in total on "+document.URL);
if (debug_labelCJK===true) {console.log(all[i-1]);}
break;
}
if ((all[i].nodeName.match(SkippedTags)) || (!(!all[i].getAttribute("lang")) && all[i].getAttribute("lang").match(SkippedLangs) ) || all[i] instanceof SVGElement || all[i].hasAttribute("data-CJKTestedAndLabeled")){
if (debug_labelCJK===true && t_last>10 ) console.log("SKIPPED: "+all[i].nodeName);
//FIXME:HERE
window.setTimeout(function (node) {node.setAttribute("data-CJKTestedAndLabeled","");
},1,all[i]); //This is the most time consuming part. Trying to use async i/o.
if (all[i].nodeName.match(pureLatinTags)) {
if (useCJKTimeOut===true) {
window.setTimeout(addTested,5,all[i],0);
}
else {
window.setTimeout(addTested,5,all[i],-1000); //Means no limits in actual webpages.
}
}
continue;
}
font_str=dequote(window.getComputedStyle(all[i], null).getPropertyValue('font-family'));
if (inTheClassOf(all[i],preSimSunList) || all[i].nodeName.match(preSimSunTags)) {
all[i].style.fontFamily=font_str.replace(re_simsun,'SimVecA,SimVecS,SimVecC');
all[i].setAttribute("data-CJK2Fix","");
all[i].setAttribute("data-CJKTestedAndLabeled","");
continue;
}
if (debug_01===true) console.log(font_str);
if (font_str.match(re_simsun)) {
var font_size=(window.getComputedStyle(all[i], null).getPropertyValue('font-size')).slice(0,-2);
if (font_size < 18) {
all[i].setAttribute("data-CJK2Fix","");
all[i].setAttribute("data-SimSun2Fix","");
if (!inTheClassOf(all[i],noWrappingClasses) && all[i].contentEditable!=="true") {
all[i].setAttribute("data-PunctSpace2Fix","");
if ( all[i].textContent.match(/\w\s[\u3040-\u30FF\u3400-\u9FBF]|[\u3040-\u30FF\u3400-\u9FBF]\s\w/) && !all[i].textContent.match(re_allpuncts)){
//Do not wrap if already using "spaces" and no puncts
if (!all[i].textContent.match(/^([\s\u0020\u00A0\u2009\u200B-\u200E]| | )[^\s\u0020\u00A0\u2009\u200B-\u200E]/)) {
all[i].removeAttribute("data-PunctSpace2Fix");
all[i].setAttribute("data-preCode","");
}
}
}
}
else {
//all[i].style.fontFamily=font_str; //Is this to increase the speed?
all[i].setAttribute("data-CJK2Fix","");
all[i].setAttribute("data-LargeSimSun2Fix","");
if (!inTheClassOf(all[i],noWrappingClasses) && all[i].contentEditable!=="true") {
all[i].setAttribute("data-PunctSpace2Fix","");
if ( all[i].textContent.match(/\w\s[\u3040-\u30FF\u3400-\u9FBF]|[\u3040-\u30FF\u3400-\u9FBF]\s\w/) && !all[i].textContent.match(re_allpuncts)){
//Do not wrap if already using "spaces" and no puncts
if (!all[i].textContent.match(/^([\s\u0020\u00A0\u2009\u200B-\u200E]| | )[^\s\u0020\u00A0\u2009\u200B-\u200E]/)) {
all[i].removeAttribute("data-PunctSpace2Fix");
all[i].setAttribute("data-preCode","");
}
}
}
}
all[i].setAttribute("data-CJKTestedAndLabeled","");
continue;
}
if ( !(all[i].textContent.match(/[“”‘’\u3000-\u30FF\u3400-\u9FBF\uFF00-\uFFEF]/)) ){
if ( useCJKTimeOut===true && all[i].textContent.length > 20 && (font_str.split(',').length >= rspLength) ) { //20 is just to make sure they are actuall Latin elements,not just some place holder.
window.setTimeout(function (node) {node.setAttribute("data-CJKTestedAndLabeled","");},1,all[i]); //This is the most time consuming part. Trying to use async i/o.
window.setTimeout(addTested,5,all[i],0);//Still, it might cause some childs to be "unfixable", if the length of the place holder is longer than 100...
continue;
}
else if (useCJKTimeOut===false && (font_str.split(',').length >= rspLength) ) {
window.setTimeout(function (node) {node.setAttribute("data-CJKTestedAndLabeled","");},1,all[i]); //This is the most time consuming part. Trying to use async i/o.
if (debug_labelCJK===true) {console.log("Labeling non-CJK element: ");console.log(all[i]);}
window.setTimeout(addTested,5,all[i],-1000);//Still, it might cause some childs to be "unfixable", if the length of the place holder is longer than 100...
continue;
}
else {
//Just skip here. Might be important in the future.
continue;
}
}
child = all[i].firstChild;
while (child) {
var realSibling=child.nextSibling;
if (child.nodeType == 3 && (child.data.match(/[“”‘’\u3000-\u30FF\u3400-\u9FBF\uFF00-\uFFEF]/))) {
all[i].setAttribute("data-CJK2Fix","");
if (!inTheClassOf(all[i],noWrappingClasses) && all[i].contentEditable!=="true") {
all[i].setAttribute("data-PunctSpace2Fix","");
if ( all[i].textContent.match(/\w\s[\u3040-\u30FF\u3400-\u9FBF]|[\u3040-\u30FF\u3400-\u9FBF]\s\w/) && !all[i].textContent.match(re_allpuncts)){
//Do not wrap if already using "spaces" and no puncts
//If space at the beginning, it might the "extra space at the beginning but after PM in another node" case.
if (!all[i].textContent.match(/^([\s\u0020\u00A0\u2009\u200B-\u200E]| | )[^\s\u0020\u00A0\u2009\u200B-\u200E]/)) {
all[i].removeAttribute("data-PunctSpace2Fix");
all[i].setAttribute("data-preCode","");
}
}
}
//Do I need to test the parentNode? I deleted them in 1.1.3
break;
}
child=realSibling;
}
all[i].setAttribute("data-CJKTestedAndLabeled","");
}
}
//return true;
//Do not try to fixpuncts if it is an English site. Just trying to save time.
labelPreMath();
labelCJK(true);
//The following is not needed and the manipulation of global variables should not be performed.
//if ((document.querySelectorAll("[data-CJK2Fix]")).length < 1) {
// FixPunct=false;
// console.log("No puncts will be fixed.");
//}
if (debug_verbose===true) {console.log('FixCJK!: Labling took '+((performance.now()-t_stop)/1000).toFixed(3)+' seconds.');}
///===FixFonts, Rounds 1-3===///
FixAllFonts();
///===Round 4, FixPunct===///
if (debug_verbose===true) {console.log('FixCJK!: Labling and Fixing fonts took '+((t_stop-t_start)/1000).toFixed(3)+' seconds.');}
if ((t_stop-t_start)*2 > timeOut || max > maxNumElements ) {
console.log('FixCJK!: Too slow or too many elements.');
//FixPunct=false; //This seems meaningless. There is a overal timeOut anyway.
}
if (FixPunct===false) {
if (debug_verbose===true) {console.log('FixCJK!: Skipping fixing punctuations...');}
}
var returnNow=true;
var returnLater=false; //Do the actual fixing.
var MaxNumLoops=1;
if (useDelayedFix===true) {
var DelayedTimer=200;
window.setTimeout(FunFixPunct(true,MaxNumLoops,returnLater),DelayedTimer);
}
else {
window.setTimeout(function () {
labelPreCode();
labelNoWrappingList();
if (useWrap===true) wrapCJK();
FunFixPunct(true,MaxNumLoops,returnLater);
},10);
}
///===End of Solving the picture problem===///
if (debug_verbose===true) {console.log('FixCJK!: Fixing punctuations took '+((performance.now()-t_stop)/1000).toFixed(3)+' seconds.');}
///===Try to fix spaces if forceAutoSpaces is set===///
if (forceAutoSpaces === true)
window.setTimeout(function (){addSpaces(true,100);},10);
///===Add onClick listener before exiting===///
var NumClicks=0;
var t_last=performance.now();
var t_interval=1000; //The interval between two checks.
var t_interSpacing=500;
var NumAllCJKs=(document.querySelectorAll("[data-CJK2Fix]")).length;
var NumPureEng=0;
var LastURL=document.URL;
var LastMod=document.lastModified;
var ItvScl=2.0; //Real "cooling down time" is t_interval/ItvScl
// NumPureEng++ will cause problems on kkj.cn.
//if (NumAllCJKs*1.0/NumAllDOMs*100 < 1.0) {
// NumPureEng++;
//}
//document.onClick will cause problems on some webpages on Firefox.
var downtime=performance.now();
var downX=0;
var downY=0;
document.body.addEventListener("mousedown",function (e){downtime=performance.now();downX=e.clientX;downY=e.clientY;},false);
document.body.addEventListener("mouseup",function (e){
if (e.button>0 ) {
//do nothing if right button clicked.
return true;
}
else if (((performance.now()-downtime) < 300) && (Math.abs(e.clientX-downX)+Math.abs(e.clientY-downY)) ===0 ) {
//ReFix after other things are done.
FixPunct=RawFixPunct;
//Do not change SkipLabelCJK for single clicks.
//SkipLabelCJK = false;
setTimeout(ReFixCJK,5,e);
if (forceAutoSpaces === true)
setTimeout(function (){addSpaces(true,300);},5);
}
else if (((performance.now()-downtime) > 1500) && (Math.abs(e.clientX-downX)+Math.abs(e.clientY-downY)) ===0 ) {
//Force to labelCJK for all elements;
var t_CJK=performance.now();
labelPreMath();
SkipLabelCJK = false; //reset the variable which could be set b/c of the SkippedLangs.
labelCJK(false);
FixAllFonts(false);
labelPreCode();
labelNoWrappingList();
if (useWrap===true) wrapCJK();
FixPunct = true;
FunFixPunct(false,5,false);
FixPunct=RawFixPunct;
addSpaces(false,10000);
t_CJK=performance.now()-t_CJK;
console.log("Labeling and fixing all CJK elements took "+(t_CJK/1000).toFixed(1)+" seconds.");
}
},false);
//use named timers to keep track of refixes.
var timerReFix= null;
var timerSpaces = null;
var waitAfterScolling=300;
window.addEventListener("scroll",function (e){
isScrolling = true;
if(timerReFix !== null) {
clearTimeout(timerReFix);
}
if(timerSpaces !== null) {
clearTimeout(timerSpaces);
}
if (scrollToFixAll === true) {
FixPunct=RawFixPunct;
timerReFix=setTimeout(function (e) {
isScrolling=false;
ReFixCJK(e);
addSpaces(true,300);
},waitAfterScolling,e);
//timerReFix=setTimeout(ReFixCJK,waitAfterScolling,e);
//timerSpaces=setTimeout(addSpaces,waitAfterScolling,true,300);
}
else {
//setTimeout(function() {fireReFix=true;},t_interval/ItvScl/2); //Permit ReFixCJK after sometime of last scrolling.
timerReFix=setTimeout(function() {
isScrolling = false;
ReFixCJKFast();
if (forceAutoSpaces === true) {
addSpaces(true,30);
}
},waitAfterScolling);
}
},false);
document.body.addEventListener("dblclick",function(e) {
setTimeout(function (e) {
SkipLabelCJK = false;
FixPunct=RawFixPunct;
ReFixCJK(e);
addSpaces(true,300);
},5,e);
//setTimeout(function(){ fontsCheck(); }, 30);
//Prevent ReFixing for a certain time;
},false);
///===Time to exit the main function===///
var t_fullstop=performance.now();
if (processedAll===true) {
console.log('FixCJK!: NORMAL TERMINATION: '+((t_fullstop-t_start)/1000).toFixed(3)+' seconds (Fixing PMs not included) is the overall execution time. No skipped step(s).');
}
else {
console.log('FixCJK!: EXECUTION ABORTED: '+((t_fullstop-t_start)/1000).toFixed(3)+' seconds (Fixing PMs not included) is the overall execution time. Some step(s) were skipped due to performance issues.');
}
////////////////////======== Main Function Ends Here ==============/////////////////////////////
//===The actual listening functions===//
function labelPreMath() {
var bannedTagList=preMathTags.split(',');
for (var itag=0;itag<bannedTagList.length;itag++) {
var all2Ban=document.querySelectorAll(bannedTagList[itag]+":not([data-preMath])");
for (var iele=0;iele<all2Ban.length;iele++) {
banMathHelper(all2Ban[iele]);
}
}
}
function labelPreCode() {
var bannedTagList=preCodeTags.split(',');
for (var itag=0;itag<bannedTagList.length;itag++) {
var all2Ban=document.getElementsByTagName(bannedTagList[itag]);
for (var iele=0;iele<all2Ban.length;iele++) {
banHelper(all2Ban[iele]);
}
}
}
function labelNoWrappingList() {
var ie=0;
var bannedClassList=noWrappingClasses.split(',');
for (var i=0;i<bannedClassList.length;i++) {
var all2Ban=document.getElementsByClassName(bannedClassList[i]);
for (ie=0;ie<all2Ban.length;ie++)
banHelper(all2Ban[ie]);
}
var bannedElementList=document.querySelectorAll('[contenteditable="true"]');
for (ie=0;ie<bannedElementList.length;ie++) {
if (debug_noWrapping===true) console.log(bannedElementList[ie]);
banHelper(bannedElementList[ie]);
}
var bannedHRefs=document.getElementsByTagName("A");
for (var iA=0;iA<bannedHRefs.length;iA++) {
if (bannedHRefs[iA].href.match(noWrappingHRefs) ) {
banHelper(bannedHRefs[iA]);
//console.log(bannedHRefs[iA]);
}
}
}
function banHelper(node) {
var child=node.firstChild;
while (child) {
if ( child.nodeType===1 && !(child instanceof SVGElement) ) {
banHelper(child);
}
child=child.nextSibling;
}
if (!node.hasAttribute("data-preCode")) {
node.setAttribute("data-preCode","");
}
}
function banMathHelper(node) {
var child=node.firstChild;
while (child) {
if ( child.nodeType===1 && !(child instanceof SVGElement) ) {
banMathHelper(child);
}
child=child.nextSibling;
}
node.setAttribute("data-CJKTestedAndLabeled","");
node.setAttribute("data-FontsFixedCJK","");
node.setAttribute("data-MarksFixedE135","");
node.setAttribute("data-preMath","");
}
function addSpaces(useSpacingTimeout,spacingTimeOut) {
if (isScrolling == true) {console.log('Trying to add space but in scrolling...'); return false;}
if (respacing === true)
return false;
var t_spaces=performance.now();
if (t_spaces-lastspacing < t_interSpacing ) {
//console.log("Skiping spacing...");
return false;
}
lastspacing=t_spaces;
respacing=true;
if (debug_spaces===true) console.log('FixCJK!: Adding spaces...');
var allQ=document.querySelectorAll("[data-\uE985]");
for (var iq=0;iq<allQ.length;iq++) {
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\u2018/g,'\uEB18');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\u2019/g,'\uEB19');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\u201C/g,'\uEB1C');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\u201D/g,'\uEB1D');
}
addSpacesHelper(document.querySelectorAll("[data-PunctSpace2Fix]:not([data-SpacesFixedE133])"),useSpacingTimeout,spacingTimeOut);
allQ=document.querySelectorAll("[data-\uE985]"); //I need to reselect because the "references" are changed?
for (iq=0;iq<allQ.length;iq++) {
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\uEB18/g,'\u2018');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\uEB19/g,'\u2019');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\uEB1C/g,'\u201C');
allQ[iq].innerHTML=allQ[iq].innerHTML.replace(/\uEB1D/g,'\u201D');
}
if (useRemoveSpacesForSimSun===true) {
window.setTimeout(removeSpacesForSimSun,10);
}
respacing=false;
console.log("FixCJK: Adding spaces took "+((performance.now()-t_spaces)/1000).toFixed(3)+" seconds.");
function getAfterHTML(child) { //FIXME: A recursion block might be needed as getAfter(child)
var toReturn='';
var t_start=performance.now();
var inputNode=child;
child=child.nextSibling;
while (child && (performance.now()-t_start)<2 ) {
if (child.nodeType===3) {
toReturn = toReturn + child.data;
}
else if (child.nodeType===1 && (window.getComputedStyle(child,null).getPropertyValue("display")!=='none') ) {
if (child.nodeName.match(stopTags) || inTheClassOf(child,stopClasses) ) {
return toReturn+"上下标";
}
toReturn = toReturn + displayedText(child);
}
if (toReturn.match(/[\w\u3400-\u9FBF]/)) {
break;
}
child=child.nextSibling;
}
if (toReturn.length < 1 && !inputNode.parentNode.nodeName.match(upEnoughTags)) {
return getAfterHTML(inputNode.parentNode);
}
else {
return (toReturn.replace(/</,'<')).replace(/>/,'>');
}
}
function getBeforeHTML(child) {
var toReturn='';
var t_start=performance.now();
var inputNode=child;
child=child.previousSibling;
while (child && (performance.now()-t_start)<2 ) {
if (child.nodeType === 3) {
toReturn = child.data + toReturn;
}
else if (child.nodeType === 1 && (window.getComputedStyle(child,null).getPropertyValue("display")!=='none') ) {
if (child.nodeName.match(stopTags) || inTheClassOf(child,stopClasses) ) {
return "上下标"+toReturn;
}
toReturn = displayedText(child) + toReturn;
}
if (toReturn.match(/[\w\u3400-\u9FBF]/)) {
break;
}
child=child.previousSibling;
}
if (toReturn.length < 1 && !inputNode.parentNode.nodeName.match(upEnoughTags)) {
return getBeforeHTML(inputNode.parentNode);
}
else {
return (toReturn.replace(/</,'<')).replace(/>/,'>');
}
}
function addSpacesHelper(allE,useSpacingTimeout,spacingTimeOut) {
var t_substart=performance.now();
for (var is=0;is<allE.length;is++) {
if ( !(allE[is].nodeName.match(/CJKTEXT/)) || allE[is].hasAttribute("data-SpacesFixedE133") ) {
continue;
}
if ( useSpacingTimeout===true && (performance.now()-t_substart)> spacingTimeOut) {
console.log("Timeout: exiting addSpaces()...");
return false;
}
if (allE[is].hasAttribute("data-wrappedCJK2Fix") ) {
if ( !(allE[is].hasAttribute("data-preCode")) ) {
var tmp_str=allE[is].innerHTML;
if (tmp_str.match(/^([\s\u0020\u00A0\u2009\u200B-\u200E]| | ){0,5}[\u3040-\u30FF\u3400-\u9FBF]/)) {
//Make sure no text will be prepended to the "left" floated elements.
if (window.getComputedStyle(allE[is].parentNode, null).getPropertyValue('float')!=='left')
tmp_str=getBeforeHTML(allE[is])+'\uF203CJK\uF203'+tmp_str;
}
if (tmp_str.match(/[\u3040-\u30FF\u3400-\u9FBF][\s\u200B-\u200E\2060]{0,2}$/)) {
if (window.getComputedStyle(allE[is].parentNode, null).getPropertyValue('float')!=='right')
tmp_str=tmp_str+'\uF204CJK\uF204'+getAfterHTML(allE[is]);
}
//protect the Latins in tags, no need in 1.0+ b/c no “”’‘ in CJK <cjkpuns> tags.
//en:zh; //why didn't I use "non-CJK" list for Latin?
tmp_str=tmp_str.replace(/ /,'\u00A0'); //Or, tmp_str=tmp_str.replace(/\u0026nbsp\u003B/,'\u00A0');
tmp_str=tmp_str.replace(/ /,'\u2009'); //Or, tmp_str=tmp_str.replace(/\u0026thinsp\u003B/,'\u2009');
var re_enzh=/([\u0021\u0023-\u0026\u0029\u002A-\u003B\u003D\u003F-\u005A\u005C-\u007B\u007D-\u009F\u00A1-\u00FF\u0391-\u03FF\u2027\u2600-\u26FF’”])([\uF201-\uF204]CJK[\uF201-\uF204])?(?:[\u0020\u00A0\u2009\u200B-\u200E\u2060]){0,5}(\uF203CJK\uF203)?(?:[\u0020\u00A0\u200B-\u200E\u2060]){0,5}([\uF201-\uF204]CJK[\uF201-\uF204])?([\u3040-\u30FF\u3400-\u9FBF])/img;
var space2BeAdded='<cjktext data-CJKTestedAndLabeled data-MarksFixedE135 data-cjkpua=\uE699 class="FontsFixedCJK" style="display:inline;padding-left:0px;padding-right:0px;float:none;font-family:Arial,Helvetica,sans-serif;font-size:80%;">\u0020</cjktext>';
if (useSFTags===false) {
space2BeAdded='\u2009';
if (useBroaderSpaces === true)
space2BeAdded='\u0020';
if (useXBroaderSpaces === true)
space2BeAdded='\u2004'; // 1/3 EM SPACE;
if (use2XBroaderSpaces === true)
space2BeAdded='\u2002'; // 1/2 EM SPACE;
if (use3XBroaderSpaces === true)
space2BeAdded='\u2003'; // 1/1 EM SPACE;
} //\u2009 for thin space and \u200A for "hair space".
var enzh_withSpace='$1$2$3$4'+space2BeAdded+'$5';
tmp_str=tmp_str.replace(re_enzh,enzh_withSpace);
//now zh:en
var re_zhen=/([\u3040-\u30FF\u3400-\u9FBF])(?:[\u0020\u00A0\u2009\u200B-\u200E\u2060]| ){0,5}([\uF201-\uF204]CJK[\uF201-\uF204])?(?:[\u0020\u00A0\u200B-\u200E\u2060]| ){0,5}([\uF201-\uF204]CJK[\uF201-\uF204])?([‘“\u0021\u0023-\u0026\u0028\u002A-\u003B\u003D\u003F-\u005C\u005E-\u007B\u007D-\u009F\u00A1-\u00FF\u0391-\u03FF\u2027\u2600-\u26FF])/img;
var zhen_withSpace='$1'+space2BeAdded+'$2$3$4';
tmp_str=tmp_str.replace(re_zhen,zhen_withSpace);
//now en["']zh (TODO in 1.x?)
//now zh['"]en (TODO in 1.x?)
tmp_str=tmp_str.replace(/\uED20/mg,'');
tmp_str=tmp_str.replace(/^[^\u0000]*\uF203CJK\uF203([^\u0000]*)$/,'$1'); // '.' does not match \n in whatever mode.
tmp_str=tmp_str.replace(/^([^\u0000]*)\uF204CJK\uF204[^\u0000]*$/,'$1');
allE[is].innerHTML=tmp_str;
allE[is].setAttribute("data-SpacesFixedE133","");
}
else {
if (debug_spaces===true) {console.log("Skipping banned tags:"+allE[is].tagName);}
}
}
}
}
respacing=false;
}
function removeSpacesForSimSun() { //Need more work.
var allS=document.querySelectorAll("[data-\uE699]");
var font_str='';
for (var i=0;i<allS.length;i++) {
font_str=((dequote(window.getComputedStyle(allS[i].parentNode, null).getPropertyValue('font-family'))).split(','))[1];
if (font_str.match(re_simsun)) {
allS[i].innerHTML='';
}
else if (font_str.match(/FixedCJKFont.易/)) {
allS[i].parentNode.setAttribute("data-checkSpacedQM","");
}
}
allS=document.querySelectorAll("[data-checkSpacedQM]");
for (i=0;i<allS.length;i++){
var toRemoved=/(<cjktext[^><]*\uE699[^><]*>\u0020<\/cjkpuns>)((?:<[^><\uE985\uE211]*>)*[\u2018\u201C])/g;
if (allS[i].innerHTML.match(toRemoved)) {
allS[i].innerHTML=allS[i].innerHTML.replace(toRemoved,'$2');
}
//No closing tag: En"Zh
toRemoved=/([\u2019\u201D])<cjktext[^><]*\uE699[^><]*>\u0020<\/cjkpuns>/g;
if (allS[i].innerHTML.match(toRemoved)) {
allS[i].innerHTML=allS[i].innerHTML.replace(toRemoved,'$1');
}
//With closing tag: En"Zh
toRemoved=/((?:^|[^>]|<[^><\uE985\uE211]*>)[\u2019\u201D](?:<[^><\uE985\uE211]*>)+)(<cjktext[^><]*\uE699[^><]*>\u0020<\/cjkpuns>)/mg;
if (allS[i].innerHTML.match(toRemoved)) {
allS[i].innerHTML=allS[i].innerHTML.replace(toRemoved,'$1');
}
}
}
function ReFixCJKFast () {
//if (isScrolling == true) {alert('trying to label CJK, but in scrolling....');return;}
if (refixingFonts===true) {
console.log("Refixing, skipping this refix...");
window.setTimeout(function () {refixingFonts=false;},t_interval/ItvScl/2);
return false;
}
refixingFonts=true;
var bannedTagsInReFix=/^(A|BUTTON|TEXTAREA|AUDIO|VIDEO|SOURCE|FORM|INPUT|select|option|label|fieldset|datalist|keygen|output|canvas|nav|svg|img|figure|map|area|track|menu|menuitem)$/i;
t_start=performance.now();
if ( (t_start-t_last)*ItvScl > t_interval ) {
FixRegular = true; //Also fix regular fonts. You need to keep this true if you want to use "LatinInSimSun" in Latin/CJK mixed context.
FixPureLatin = false; //Appendent CJK fonts to all elements. No side effects found so far.
//FixPunct = false; //If Latin punctions in CJK paragraph need to be fixed. Usually one needs full-width punctions in CJK context. Turn it off if the script runs too slow or HTML strings are adding to your editing area.
ifRound1 = true;
ifRound2 = true;
ifRound3 = false;
maxlength = 1100200; //maximum length of the page HTML to check for CJK punctuations.
maxNumElements = 8000; // maximum number of elements to process.
CJKOnlyThreshold = 2000; // Only CJK if the number of elements reaches this threshold.
labelPreMath();
labelCJK(true);
FixAllFonts(true);
//FunFixPunct(true,2,returnLater); //No FixPunct unless "scrollToFixAll" is set to "true".
console.log('FixCJK!: Fast ReFixing took '+((performance.now()-t_start)/1000).toFixed(3)+' seconds.');
}
t_last=performance.now();
refixingFonts=false;
}
function ReFixCJK (e) {
if (refixing===true) {
if (debug_wrap===true) {console.log("Refixing, skipping this refix...");}
window.setTimeout(function () {refixing=false;},t_interval/ItvScl);
return false;
}
refixing=true;
var bannedTagsInReFix=/^(A|BUTTON|TEXTAREA|AUDIO|VIDEO|SOURCE|FORM|INPUT|select|option|label|fieldset|datalist|keygen|output|canvas|nav|svg|img|figure|map|area|track|menu|menuitem)$/i;
if (debug_verbose===true) {console.log(e.target.nodeName);}
t_start=performance.now();
//The "LastURL" method is not reliable.
//if (document.URL!==LastURL) {
// NumPureEng = 0;
// LastURL=document.URL;
//}
var clickedNode=e.target;