-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path$$.Dom.TextParcels.jsxlib
4058 lines (3534 loc) · 159 KB
/
$$.Dom.TextParcels.jsxlib
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
/*******************************************************************************
Name: TextParcels
Desc: Explore Text containers in a Document.
Path: /etc/$$.Dom.TextParcels.jsxlib
Require: $$.Dom ; $$.MultiStream auto-included ;
the file etc/Linguist/$$.LNGS.jsxres must be includable
Encoding: ÛȚF8
Core: NO
Kind: Class.
API: =create() setStreamContextLength()
[PROTO] clear() changeSectionPrefixBehavior() setBasicOptions()
updateContainers() updateCells()
updateFootnotes() endnoteFrameIds()
updateLocations() updateAuto() ready() pageCount()
hasPageDups() sectionPrefix() pageSectionMatch()
pageMatch() targetPages() targetLayers()
targetParagraphStyles() targetCharacterStyles()
consolidate() getSamples() getMultiStream() getStats()
DOM-access: YES [READ-ONLY]
Todo: ---
Created: 201110 (YYMMDD)
Modified: 241215 (YYMMDD)
*******************************************************************************/
;$$.Dom.hasOwnProperty('TextParcels') || eval(__(CLASS, $$.Dom.toSource(), 'TextParcels', 241215, 'create'))
//==========================================================================
// BACKGROUND
//==========================================================================
/*
0. OVERVIEW
The class TextParcels captures visible text units in an InDesign document.
Its main purpose is to provide handy tools for scanning and reporting text
contents of particular kinds (footnotes, cells, etc) and/or available at
particular locations (e.g. specific pages or layers.)
These text units are often scattered throughout the DOM hierarchy, while
many InDesign scripts just seek to answer questions like "What texts appear
on page 12?", "What data do the tables contain in that document?", etc.
The main issue with text-related structures (frames, stories, text paths,
tables/cells, footnotes/endnotes, parent pages, layers) is, they rely on
complex interconnections between visible items and more abstract objects.
Parsing those entities in a consistent and optimal way is a true challenge,
especially when the target document has many pages and texts.
In order to identify or capture text units, scripts usually invoke DOM
commands like .findGrep() or .findText() but they have several downsides:
- They are resource-intensive and time-consuming;
- They assume you already know what *contents* you are looking for and
do not allow you to sort results *by location*;
- They do not cache results or keep in memory the locations already
visited (each call restarts from the beginning.)
TextParcels takes a different approach: it parses the document structure
(focusing on text containers) and builds various maps that address text
units and keep track of their respective locations. This technique is on
average faster, and much more granular, than repeatedly running `find...`
methods. This allows the client code to target specific locations and send
queries throughout text contents.
1. CLUSTERS
A cluster represents any visible text container, on a specific page, in a
given document. In most cases the container (e.g. a TextFrame or a TextPath)
determines both a target text (`container.texts[0]`) and the corresponding
location (`container.parentPage` for frames, `container.parent.parentPage`
for textpaths). But two particular cases had to be addressed too:
A) TABLE CELLS - Since Table objects can be threaded across multiple frames,
the actual location of a particular cell may differ from the Table container.
In this case we need to invoke the `parentTextFrames` property of the text.
Also, tables can appear in footnotes/endnotes and/or be nested in a cell.
The DOM path to a visible cell, whatever its depth in the hierarchy, can
always be reduced to `page-item[@id=x]/table[@id=y]/cell[@id=z]`, defined by
the three IDs x,y,z. Then the cell text can be retrieved using `/text[0]`.
However, the location of the cell requires an extra frame ID, as
`page-item[@id=x]` does not necessarily determine the actual location.
[REM] The 'universal' command `doc.pageItems.itemByID(<anyObjID>)` does
not work for Table IDs.
B) FOOTNOTES, ENDNOTES - If parsed, footnotes and endnotes may introduce
additional issues. Most of these components have their text entirely captu-
red by `myNote.texts[0]`, meaning that the footnote/endote ID is sufficient
to determine the text, while the frame (location) results from the
`parentTextFrames[0]` of that text. But if a note is threaded across
multiple frames, `parentTextFrames` will return more than one frame
and we must then 'split' the cluster into mutiple parts, of the form
`myNote.characters.itemByRange(a,b)`.
In the present implementation, each cluster is encoded by a compact string
having at least 4 characters:
<CLUSTER> :: `<K><LL><N><C>`
|________| <------ 4 characters (prefix)
where
<K> :: 1 character (cluster kind)
One of 'T'|'P'|'E'|'c'|'d'|'b'|'f'|'e' (see below.)
<LL> :: 2 characters (location-pageitem ID)
Either `\0\0` (if the location fits the cluster KeyId)
or <Hi><Lo> encoding of the uint32 ID.
<N> :: 1 character (next flag)
'+' if the cluster has a continued text,
'#' if it contains the last character of the story,
or if it is a cell/footnote/endnote
'!' if the story overflows here (only for T|P|E.)
<C> :: 0 or more characters (contents)
Raw contents of the cluster. If no contents is assigned
yet, the length of the cluster code is 4. Assigned
*empty* content is encoded \0 (1 char.)
Then cluster ids (referred to as KeyIDs below) are assigned and managed from
the TextParcels instance through its `clusters` property:
.clusters :: { <KeyID> => <CLUSTER> }
each <KeyId> having one of the following forms depending on the kind <K>:
<KeyID> :: `_x` | `_x_y_z` | `_x_a_b`
where x, y, and z denote DOM ids (uint32) while a and b denote character
indices. Below is detailed how KeyIDs are built:
DOM OBJECT <K> KEYID PATH AND <LL>
=======================================================================
TextFrame T _x text-frame[@id=x]
<LL> x
-----------------------------------------------------------------------
TextPath P _x text-path[@id=x]
<LL> some pageitem X
-----------------------------------------------------------------------
EndnoteTF E _x endnote-text-frame[@id=x]
<LL> x
-----------------------------------------------------------------------
Cell c|d|b _x_y_z page-item[@id=x]/table[@id=y]/cell[@id=z]
<LL> either x or another frame X (threaded table)
The `d` (resp. `b`) kind is used to indicate that
the cell takes place in a footnote (resp. endnote.)
-----------------------------------------------------------------------
Footnote f _x footnote[@id=x] if non-threaded
_x_a_b footnote[@id=x]/[a]to[b] if threaded
<LL> some frame X
The Endnote kind 'e' is NOT USED in the present implementation, although
available in principle:
Endnote e _x endnote[@id=x] if non-threaded
_x_a_b endnote[@id=x]/[a]to[b] if threaded
<LL> some frame X
For the time being, endnotes are fully processed as EndnoteTextFrame contents,
hence available in 'E' clusters.
*/
//==========================================================================
// NOTICE
//==========================================================================
/*
The present class is one of the building blocks of IndexMatic³, a full-text analyzer
and index builder for InDesign. -> https://indiscripts.com/category/projects/IndexMatic
For that reason, many internal bricks implemented below may sound crazy or pointless.
In particular, the `MultiStream` submodule available in this directory requires a deep
understanding of how text matching and query processing was implemented in IndexMatic.
It sometimes refers to extra entities (like the `XQuery` class) that are not available
in the public release of the /etc/ branch.
However, the basic features exposed by `$$.Dom.TextParcels` can still be enjoyed by
*experienced* developers who'd need to scan InDesign documents with high efficiency.
Since `$$.Dom.TextParcels` is a class (each instance handles a particular Document),
you will use the syntax
var myTP = new $$.TextParcels( myDocument, myOptions )
to get an instance of the class. The optional `myOptions` argument (object) can be
passed in to specify basic settings at construction time. Most options are boolean
(some are 'ternary'), they provide 'hints' to the scanner about clusters that can
be excluded and similar skippable things:
tables (-1|0|1) -1:restrict to tables ; 0:ignore tables ; 1:accept tables
endnotes (-1|0|1) -1:restrict to endnotes ; 0:ignore endnotes ; 1:accept endnotes
footnotes (-1|0|1) -1:restrict to FNs ; 0:ignore FNs ; 1:accept footnotes
nested (0|1) 0:ignore nested objects ; 1:accept
hidden (0|1) 0:ignore hidden texts ; 1:accept
wantVars (0|1) Whether text variable instances have to be scanned.
scanLanguages (0|1) Whether document languages have to be scanned.
These options can anyway be changed later using myTP.setBasicOptions(...)
-> Go into the prototyped `create` method for further detail on ctor options.
The data structure of TP instance is huge (see the ctor for detail). Here are the more
sensible properties:
docSpec: str (doc specifier)
name: str (doc name)
options: { tables, endnotes, footnotes, nested, hidden... }
icuBest: undef|str :: `xx_YY` (best guess about the iso language)
and here are more complex (although quite essential) components:
clusters: { _kid => `<K><LL>[+#!]<C>` },
threads: { _kid => `<nextKid>` },
locations: { _xid => `<pid>[_$]<yid><X1>?` | '0[_$]0' },
ranges: { _kid => `[_=]<zpc0><zpc1>...<zpcN>` | '' },
styles: { _sid => idx } [ idx => `_sid` ]
pagesMap: [ ofs => id ] + { _name => id | `id_id...` } + { $id => <ofs>name }
sections: [ idx => uniqueName ] + { _uniqueName => idx }
runs: { _pidOK => `_kidOK1|•kidOK2|...|•kidOKn` } ; where • denotes [_+]
(etc)
As you can see, a special, compact 'encoding' is used to represent clusters and related
information. (Clusters are introduced in the BACKGROUND section.) You'll need to get
familiar with those structures if you expect to explore the features in depth. But
you can still access many interesting routines from the public API available in the
[PROTO] areas. All methods are quite seriously documented...
-> See /tests/DomTextParcelsTest.jsx for a basic example.
*/
//==========================================================================
// TOOLS: PPAV SIGM REPT IDXS UP32 VRNG VREP RE_MRGE SEGS STMP NRMS SECT PGMP VRTP FSEC ISEQ IOBJ
//==========================================================================
[PRIVATE]
({
// Whether parentPage is available.
// ---
PPAV: $$.idVersion(7),
SIGM: function(/*uint|uint[]*/count, r,z)
//----------------------------------
// Sum the values if `count` is an array, return `count` otherwise.
{
if( 'number' == typeof count ) return count;
if( !count.length ) return 0;
r = 0;
for each( z in count ) r+=z;
return r;
},
REPT: function(/*(str|uint)[]*/a,/*uint[]|uint*/b, n,r,i,z)
// ---------------------------------
// (Repeat.) Repeats each a[i] element b[i] times and returns
// the resulting array, each element bing coerced into a string.
// E.g a=['x','y','z'] ; b=[2,0,4] => ['x','x','z','z','z','z']
// a=[1234,56,789] ; b=[1,3,2] => ['1234','56','56','56','789','789']
// ---
// => str[]
{
// If `b` is a single number, use `[b]`.
// ---
'number' == typeof b && (b=[b>>>0]);
// In case `a.length` != `b.length`, take the min number.
// ---
(n=a.length) > (z=b.length) && (n=z);
for( r=[], i=-1 ; ++i < n ; (z=b[i]) && r.push.apply(r,Array(1+z).join('\x01'+a[i]).slice(1).split('\x01')) );
return r;
},
IDXS: function(/*uid_uid...*/s,/*{_uid=>idx}*/q, a,i,k)
//----------------------------------
// (Index-String.) Converts `uid_uid...` string to UTF16-index string `<idx><idx>...`
// based on the map q :: { _uid => idx <= 0xFFFF }. If a `_uid` is not found in q,
// no <idx> character is associated to it.
// => str ; may contain \0
{
const CHR = String.fromCharCode;
for( a=s.split('_'), i=a.length ; i-- ; a[i] = q.hasOwnProperty(k='_'+a[i]) ? CHR(q[k]) : '' );
return a.join('');
},
UP32: function(/*str*/s,/*uint*/unitSz, r,n,i)
//----------------------------------
// Given a string `s` formatted as `_<x...><x...>...`
// where `x` is a U16 char followed by unitSz-1 characters,
// returns the corresponding `=<XX...><XX...>...` string
// where `XX` is '\0'+x.
// => str
{
for( r='=', n=s.length, i=1 ; i < n ; r=r.concat('\0',s.slice(i,i+=unitSz)) );
return r;
},
VRNG: function(/*`[_=]<Zpc0><Zpc1>...`*/rk,/*[<idxMax>_<newSize>,...,<idxMin>_<newSize>]*/vrep, U32,n,x,i,di,j,zi,xv,vv,dz,CAN_UP)
//----------------------------------
// (Adjust-Range-To-Variables.) Adjust the range sizes Z in `rk` to take
// care of variable replacements.
// If rk[0]=='_' (resp. '='), the Z's are 16bits (resp. 32bits) encoded
// Each character at idx specified in vrep has been replaced by either
// an empty string (<newSize>=='0') or a string of newSize > 1.
// [REM] In the rare case where Z values need to go up from 16 to 32bits
// encoding, the returned string is properly updated using ~.UP32.
// ---
// this :: ~
// => str ; adjusted `[_=]<Zpc0><Zpc1>...` with Z's updated.
{
const CHR = String.fromCharCode;
U32 = +('=' == rk.charAt(0));
CAN_UP = !U32;
n = rk.length;
for( x=0, di=3+U32, j=vrep.SIZE, xv=-1, i=1 ; i < n ; i+=di )
{
// zi :: size of the range, aka <z>.
// ---
zi = rk.charCodeAt(i);
U32 && ( zi=((zi<<16)|rk.charCodeAt(1+i)) >>> 0 );
// Get xv >= x ; vv :: `<xv>_<newSize>`
// ---
while( xv < x ) xv = 0 < j ? parseInt((vv=vrep[--j]),10) : 1/0;
if( !isFinite(xv) ) break;
// As long as xv < x=x+zi, accumulate the sizeFix (dz.)
// ---
for( x+=zi, dz=0 ; xv < x ; xv = 0 < j ? parseInt((vv=vrep[--j]),10) : 1/0 )
{
dz += -1 + parseInt(vv.slice(1+vv.indexOf('_')),10);
}
if( !dz ) continue;
// Update size: zi -> zi+dz
// ---
zi += dz;
if( CAN_UP && 0xFFFF < zi )
{
// Rewrite rk from 16 to 32bits (so it can receive zi > 0xFFFF.)
// ---
rk = this.UP32(rk,3);
// Update (U32,di,n,i) accordingly.
// ---
U32 = 1;
di = 4;
n = rk.length;
i = 1 + 4*((i-1)/3);
CAN_UP = 0;
}
zi = U32 ? CHR(zi>>>16,(0xFFFF&zi)>>>0) : CHR(zi);
rk = rk.slice(0,i).concat(zi, rk.slice(1+U32+i));
}
return rk;
},
VREP: function(/*str*/tx,/*?str[]&*/vrep,/*str|char*/rp,/*?str[]*/VTX, r,p,n,x,i,U32,dp,s,z,xp)
//----------------------------------
// (Variable-Replacement.) Replace variable markers in `tx` by some
// corresponding character or result text.
// vrep :: If supplied, volatile array of `<idx>_<newSize>` strings
// in *decreasing* indices. Length is stored in vrep.SIZE.
// rp :: Replacement scheme:
// '' -> Each \x18 in tx is replaced by an empty string
// char -> Each \x18 in tx is replaced by rp
// `[_=]<xkv0><xkv1>...<xkvN>` -> Each variable marker found
// at index `x` is replaced by VTX[v] ; or by the
// empty string if the association is missing.
// VTX :: varTexts array ; must be provided if rp.length > 1.
// ---
// this :: ~
// => str ; new tx
{
vrep||(vrep=0);
r = tx.split('\x18');
p = rp.length;
// Single char replacement.
// ---
if( 1===p ) return (vrep&&(vrep.SIZE=0)), r.join(rp);
// Removes all variables.
// ---
if( 0===p || !(VTX||0).length )
{
for( n=0, x=tx.length, i=r.length ; i-- ; x-=(1+r[i].length), vrep&&(vrep[n++]=x+'_0') );
vrep && (vrep.SIZE=n);
return r.join('');
}
U32 = '=' == rp.charAt(0);
dp = U32 ? 4 : 3;
// Lookup in VTX, removes otherwise.
// [REM] r[0] is never read/changed, hence the condition `--i > 0`
// ---
for( z=n=0, x=tx.length, xp=1/0, i=r.length ; --i > 0 ; z && (r[i]=s.concat(r[i])) )
{
x -= (1+r[i].length);
while( p > dp && xp > x )
{
xp = rp.charCodeAt(p-=dp);
U32 && ( xp=((xp<<16)|rp.charCodeAt(1+p)) >>> 0 );
}
s = ( x===xp && VTX[rp.charCodeAt(p+dp-1)] ) || '';
z = s.length;
vrep && 1 != z && (vrep[n++] = x + '_' + z);
}
vrep && (vrep.SIZE=n);
return r.join('');
},
// Detect a string that is entirely formed of 'blank' characters
// and then possibly ignorable when splitting style ranges.
// ---
RE_MRGE: /^[\u0003\u0007-\u000A\u000D\u0016\u0017\u0020\u001A\u007F-\u009F\u00A0\u00AD\u2000-\u200D\u2028\u2029\u202F\u205F\u2063\u3000\uFEFF\uFFFC\uFFFD]+$/g,
SEGS: function(/*str*/tx,/*str*/rk,/*0|str*/psi,/*0|str*/csi,/*num*/mxSz,/*uint|0*/mergeSpaces,/*bool*/endNoteFrame,/*char*/XR,/*char|false*/AC,/*?RegExp*/alphaReg, end,U32,PS,CS,R,z,nk,x,dx,i,zi,psOut,csOut,out,endSep,t,s,emk)
//----------------------------------
// (Valid-Style-Segments.) [FIX230604] This new version deals with endnote markers
// that must be preserved -- even in OUT segments! -- when endNoteFrame is on.
// ---
// - rk :: `[_=]<zpc0><zpc1>...` Range string associated to a cluster.
// - psi :: 0|CHR(i1)+CHR(i2)...
// - csi :: 0|CHR(i1)+CHR(i2)...
// - mxSz :: uint|+Infinity If finite, the segments are right-truncated
// so they have at most the length `mxSz`.
// - mergeSpaces :: uint|0 Tells how many blank characters can be merged
// to the current style without causing a cut.
// - endNoteFrame :: bool Whether the source cluster is a EndNoteTextFrame [FIX230601]
// - XR :: Minimal separator between splitted segments.
// - AC :: Character added before and/or after the XR separator depending
// on whether the start/end character of the cut is alphabetic. The re-
// sulting separator <SEP> is either <XR>|<AC><XR>|<XR><AC>| <AC><XR><AC>.
// - alphaReg :: If `AC` supplied, regex as specified in µ.getSamples.
// ---
// Scan the style ranges in `rk` and keep only the segments of tx that
// have an allowed style. Returns a string formed of valid segments (merged)
// and separators introduced between them if needed.
// ---
// callee.LAST_CUT contains the lattest right <SEP> (its initial value has
// been initialized to XR from the client routine.)
// this :: ~
// => <ISEP>?<range1><SEP><range2>...<ESEP>?
// where <SEP> :: <XR> | <AC><XR> | <XR><AC> | <AC><XR><AC>
// <ISEP> :: <XR> | <AC> | <XR><AC>
// <ESEP> :: <XR> | <AC><XR> ===> LAST_CUT
{
const RE_MG = 0 < mergeSpaces && this.RE_MRGE;
const USTY = callee.UNION_STYLES;
if( !(end=tx.length) ) return ''; // Just in case! (Shouldn't happen.)
U32 = 0x3D == rk.charCodeAt(0);
PS = psi && psi.length;
CS = csi && csi.length;
R = callee.Q || (callee.Q=[]);
z = R.SIZE = 0;
for( nk=rk.length, x=dx=0, i=1 ; i < nk ; i+=3, dx+=zi ) // [x, x+dx[ represents the current segment.
{
zi = rk.charCodeAt(i); // zi :: size of the stylerange.
U32 && ( zi=((zi<<16)|rk.charCodeAt(++i)) >>> 0 );
if( !zi ) continue; // Ignore zero-length range.
psOut = ( PS && -1 == psi.indexOf(rk.charAt(1+i)) ); // Is the para-style index <p> disallowed (i.e absent in nonempty psi)?
csOut = ( CS && -1 == csi.indexOf(rk.charAt(2+i)) ); // Is the char-style index <c> disallowed (i.e absent in nonempty csi)?
out = USTY ? (psOut && csOut) : (psOut || csOut); // [CHG240109] If UNION_STYLES is ON (which only happens if PC && CS),
// then the `out` flag must be set only if both psOut and csOut are true.
(1&z)==out && ( R[z++]=x, x+=dx, dx=0 ); // Toggle? ( 1==1 means IN->OUT ; 0==0 means OUT->IN )
// Register the current segment ; R[0] is always 0 and R[1] might be 0
}
( 1&z ) // 1&z means that the unregistered [x,end[ is IN,
? ( dx && ( R[z++]=x, R[z++]=x+dx ) ) // so we register it and we append the last OUT elem at x+dx (=end)
: ( R[z++]=x ); // otherwise [x,end[ is an OUT elem.
// ---
// z is necessarily odd :: <O>,<I>,<O>,...,<I>,<O>
// ---
if( RE_MG || (mxSz < tx.length) ) // Might simplify (truncate/merge)
for( i=z ; 0 < (i-=2) ; )
{
x = R[i];
dx = R[1+i]-x; // Size of IN segment
if( dx > mxSz ) // Sample truncation needed?
{
R[1+i] = x + mxSz + 1; // Make the OUT seg start at x+mxSz+1 < x+dx
}
else
{
2+i < z
&& mergeSpaces >= (zi=R[2+i]-(x+=dx)) // If the next OUT is small enough
&& RE_MG.test(tx.slice(x,x+zi)) // and spaces are mergeable from (i) to (i+2)
&& ( R.splice(1+i,2), z-=2 ); // then simply remove R[i+1],R[i+2]
}
}
// At every moment, endSep represents the 'last cut',
// it can be empty, <AC><XR> or <XR>.
// ---
endSep = 'string'==typeof callee.LAST_CUT ? callee.LAST_CUT : XR; // endSep :: '' | <XR> | <AC><XR>
// Compute segments. [REM230602] This loop is *not entered if z==1*.
// ---
for( i=-1, out=R[0] ; (i+=2) < z ; R[i]=tx.slice(x,out)+endSep )
{
// Left context -> Stored in R[i-1]
// ---
zi = (x=R[i])-out; // zi :: size of left OUT segment ; x :: IN index
t = zi ? (endSep ? '' : XR) : ''; // t :: '' | <XR> ; minimal L-sep (before IN), may be empty.
if( zi )
{
endNoteFrame
&& (emk=callee.ENDMARKS(tx,out,x,XR)).length
&& ( t=t+emk ); // Append (<FEFF><x04><XR>)+
AC && callee.TEST(tx,x-1,alphaReg,-1) && (t=t+AC); // Append <AC> if alpha before.
}
R[i-1] = t;
out = R[1+i];
t = out < end ? XR : '';
if( out < end )
{
AC && callee.TEST(tx,out,alphaReg,1) && (t=AC+t); // Prepend <AC> if alpha after.
}
endSep = t; // New endSep :: '' | <XR> | <AC><XR>
}
// Deal with the final <OUT> segment at z-1.
// (This MUST work if z==1 too.)
// ---
if( out < end )
{
// Non-empty final OUT
t = endSep ? '' : XR;
if( endNoteFrame && (emk=callee.ENDMARKS(tx,out,end,XR)).length )
{
R[z-1] = t + emk; // <XR>?<FEFF><x04><XR>+
endSep = XR;
}
else
{
R[z-1] = t; // Will add <XR> only if missing (i.e. `z==1`)
endSep || (endSep=XR); // Make sure endSep has XR (`z==1` case)
}
}
else
{
// Empty final OUT -> Ignore R[z-1], endSep is OK.
z--;
}
callee.LAST_CUT = endSep;
return z ? R.slice(0,z).join('') : '';
}
.setup
({
LAST_CUT: false, // safer
UNION_STYLES: false, // [ADD240109] Whether to perform UNION rather than INTERSECTION on styles.
TEST: function(/*str*/tx,/*uint*/i,/*RegExp*/re,/*-1|0|+1*/dir, d,t)
//----------------------------------
// Whether re matches tx[i].
// If dir==-1, consider the possible surrogate pair {i-1,i}
// If dir==+1, consider the possible surrogate pair {i,i+1}
{
if( !dir ) return re.test(tx.charAt(i));
d = 1;
0 > dir
? ( 0 < i && 0xD800 <= (t=tx.charCodeAt(i-1)) && t <= 0xDBFF && (--i,d=2) )
: ( 0xD800 <= (t=tx.charCodeAt(i)) && t <= 0xDBFF && d=2 );
return re.test(tx.slice(i,i+d))
},
ENDMARKS: function(/*str*/tx,/*uint*/x0,/*uint*/x1,/*char*/XR, r,p)
//----------------------------------
// [ADD230531] Return a sequence of `<FEFF><0004><XR>` markers reflecting how many
// occurrences of this sequence appear in the range [x0,x1[ of `tx`.
// => '' [KO] | (`<FEFF><0004>`)+
{
const MK_XR = '\uFEFF\x04' + XR;
for( r='', tx=tx.slice(x0,x1), p=-1 ; -1 != (p=tx.indexOf('\uFEFF\x04',2+p)) ; r+=MK_XR );
return r;
},
}),
STMP: function(/*'character'|'paragraph'*/cp,/*{}&*/map,/*Doc|StyleGp*/parent,/*str=''*/prefix, t,a,b,i)
//----------------------------------
// (Styles-Map.) Load styles (recursively) in the incoming `map` object,
// using the structure { _stylePath => styleId }
// Paths that involve group(s) are decomposed using <X2> separator,
// so each path has the form `name(<X2>name)*`
// ---
// => map&
{
(prefix||0).length || (prefix='');
if( (t=parent[cp+'Styles'].everyItem()).isValid )
for
(
a=t.name, b=t.id, i=-1 ;
++i < a.length ;
map[ '_'+prefix+a[i] ] = b[i]
);
if( (t=parent[cp+'StyleGroups'].everyItem()).isValid )
for
(
a=t.getElements(), i=-1 ;
++i < a.length ;
t=a[i], callee( cp, map, t, prefix+t.name+'\x02' )
);
return map;
},
NRMS: function(/*any|str|any[]&*/inputStyles, AS_STRING,a,re,i,s)
//----------------------------------
// (Normalize-Style-Paths.) If inputStyles is a string or an array,
// replace style paths formatted `[G1] [G2] ... name` into the
// expected form `G1<X2>G2<X2>...name` (optional space separators
// are removed.)
// [REM] This routine is invoked from the `target...Styles` methods
// to support user-friendly style specifications. The regular
// non-ambiguous form of style paths remains `G1<X2>G2<X2>...name`,
// since the name of a style (or groupstyle) can contain inner
// brackets, as in "my[Style]name". In such case, the <X2>-separated
// form is required upstream.
// => any | str | inputStyles&
{
AS_STRING = 'string' == typeof inputStyles;
a = AS_STRING ? [inputStyles] : inputStyles;
if( !(a instanceof Array) ) return inputStyles;
re = callee.RE_BRACKETS;
for
(
i=a.length ; i-- ; 'string' == typeof(s=a[i])
&& 0x5B==s.charCodeAt(0) && (a[i]=s.replace(re,'$1\x02'))
);
return AS_STRING ? a[0] : a;
}
.setup
({
RE_BRACKETS: /\[([^\]]+)\] */g,
}),
SECT: function(/*Document*/doc, r,o,i,t,k,n,x,z)
//----------------------------------
// (Sections.) Create the sections entity:
// idx => uniqueName
// _uniqueName => idx
// $idx => `<ofs><length>(-|+)prefix<X1>marker<X1>algo<X1>shift`
// [REM230829] The `includeSectionPrefix` property of a section is not ignored
// at this stage, so the prefix flag is set to `+` or `-` depending on it.
// However, the flag can be a posteriori forced to `+` or `-` from ~.PGMP.
// ---
// => new [{}]
{
// [REM] Typical result for section.properties:
// { length:3, alternateLayoutLength:3, alternateLayout:"Letter V", name:"", marker:"",
// continueNumbering:true, pageNumberStart:337,
// pageNumberStyle:<PNS>, includeSectionPrefix:false, sectionPrefix:"",
// pageStart:<Page>, id:236, label:"", parent:<Document>, index:0 }
// Note: pageNumberStart is defined even if continueNumbering is true,
// but in such case it is READ-ONLY. 1 <= pageNumberStart <= 999999
// ---
r = doc.sections.everyItem().properties;
// [FIX230216] WE CANNOT ASSUME THAT SECTIONS ARE ORDERED!!!!
// `sections.everyItem()` can deliver sections in arbitrary order, and
// sections[i] is not necessarily the (i-1)th visual section in the doc!
// So the only way to get reliable offset and meaningful indices is to
// reorder `r` according to `pageStart.documentOffset` before further proc.
for
(
i=r.length ;
i-- ;
(t=r[i]).length && (t=t.pageStart).isValid
? (r[i].docOffset=t.documentOffset) // Store the .docOffset prop (uint).
: r.splice(i,1) // In passing, remove empty sections!
);
r.sort(callee.SORT);
// Store o :: {customName => count} AND r[i].temp = customName
// [CHG230217] Since `1+t.index` didn't make sense in unordered section set, use `1+i` instead.
// ---
for
(
o={}, i=r.length ; i-- ;
t=r[i], k='_'+(t.name||t.marker||('['+(1+i)+']')),
t.temp = k,
o[k] = 1+(0|o[k])
);
// Rewrite the entity.
// [CHG230217] Since `1+t.index` didn't make sense in unordered section set, use `1+i` instead.
// ---
const CHR = String.fromCharCode;
const NS2S = callee.NS2S;
const ALGO = callee.ALGO;
for
(
x=0, n=r.length, i=-1 ; ++i < n ;
( 1 < o[k=(t=r[i]).temp] && (k+=' ['+(1+i)+']') ),
r['$'+i] = CHR(x) + CHR(z=t.length) +
( t.includeSectionPrefix ? '+' : '-' ) +
t.sectionPrefix + '\x01' +
t.marker + '\x01' +
(ALGO[NS2S[+t.pageNumberStyle]]||'NONE') + '\x01' + // Not found algo is labelled 'NONE'
(t.pageNumberStart-x), // [ADD220210] Shift (might be < 0 in clinical cases.)
r[k] = i, r[i] = k.slice(1), x+=z
);
return r;
}
.setup
({
NS2S : eval(PageNumberStyle.revSource()), // {1298231906:"ARABIC", 1296855660:"LOWER_LETTERS", etc}
ALGO :
{
ARABIC: 'ARAB', // 1, 2, 3, 4...
SINGLE_LEADING_ZEROS: 'ONEZ', // 01, 02, 03, 04...
DOUBLE_LEADING_ZEROS: 'TWOZ', // 001, 002, 003, 004...
TRIPLE_LEADING_ZEROS: 'THRZ', // 0001, 0002, 0003, 0004...
UPPER_ROMAN: 'UROM', // I, II, III, IV...
LOWER_ROMAN: 'LROM', // i, ii, iii, iv...
UPPER_LETTERS: 'ULET', // A, B, C, D, ... AA, AB...
LOWER_LETTERS: 'LLET', // a, b, c, d, ... aa, ab...
// ---
ARABIC_ALIF_BA_TAH: 'BATA', // أ, ب, ت, ث, ج, ح, خ, د, ذ, ر, ز, س, ش, ص, ض, ط, ظ, ع, غ, ف, ق, ك, ل, م, ن, ه, و, ي, أ أ, ب ب ...
// Order: U+06..23,28,2A,2B,2C,2D,2E,2F,30,31,32,33,34,35,36,37,38,39,3A,41,42,43,44,45,46,47,48,4A (28 chars)
ARABIC_ABJAD: 'ABJA', // أ, ب, ج, د, ه, و, ز, ح, ط, ي, ك, ل, م, ن, س, ع, ف, ص, ق, ر, ش, ت, ث, خ, ذ, ض, غ, ظ, أ أ, ب ب ...
// Order: U+06..23,28,2C,2F,47,48,32,2D,37,4A,43,44,45,46,33,39,41,35,42,31,34,2A,2B,2E,30,36,3A,38 (28 chars)
// ---
HEBREW_BIBLICAL: 'HBIB', // 1..999 ; Cf. github.com/chaimleib/hebrew-special-numbers
// In InDesign, only '15' and '16' suffixes undergo a special rewriting.
HEBREW_NON_STANDARD: 'HNON', // א ב ג ד ה ו ז ח ט י כ ל מ נ ס ע פ צ ק ר ש ת (22 chars then ULET algo.)
// ---
KANJI: 'KANJ', // Simplified Chinese numerals ; maps `0..9` to '\u3007\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D'
},
// [ADD230216] Sort by `.docOffset`
// ---
SORT: function(/*{docOffset,...}*/a,/*{docOffset,...}*/b){ return a.docOffset-b.docOffset; },
}),
PGMP: function(/*Document*/doc,/*?{}&*/secs,/*bool=0*/REMOVE_SEC_PREFIX, PV,r,n,a,dup,i,k,x,s,pfx,iSup,secFlag,cc)
//----------------------------------
// (Pages-Map.) Create the pages map entity:
// ofs => pid
// _name => pid | `pid_pid...`
// $pid => <ofs>name
// DUP_COUNT => uint
// [CHG230827] If supplied, `secs` forcibly provide section prefixes to page names. The secs
// structure is then modified s.t. whenever the `-` flag appears it is changed into `+`.
// secs :: [idx => uniqueName] + { $idx => `<ofs><length>(-|+)prefix<X1>marker<X1>algo<X1>shift` }&
// [ADD230829] If `REMOVE_SEC_PREFIX` is truthy (and secs is provided), section prefixes are
// forcibly removed from page names and the secs structure is then modified s.t. whenever the
// `+` flag appears it is changed into `-`.
// ---
// => new [{}]
{
r = (PV=doc.pages.everyItem()).id;
n = r.length;
a = PV.name; // May contain duplicates!
// [ADD230827] Forcibly prepend (resp. remove) section prefix to (resp. from) page names?
// ---
if( secs )
{
secFlag = REMOVE_SEC_PREFIX ? '-' : '+';
cc = secFlag.charCodeAt(0);
for( x=-1 ; ++x < secs.length ; ) // Loop in sections
{
s = secs[k='$'+x]; // `<ofs><length>(-|+)prefix<X1>...`
if( cc === s.charCodeAt(2) ) continue; // Nothing to do since the section prefix flag already reflects the desired state.
secs[k] = s.slice(0,2) + secFlag + (pfx=s.slice(3)); // Rewrite the signature with the desired flag (+|-).
pfx = pfx.slice(0, pfx.indexOf('\x01')); // Extract the prefix.
if( !pfx.length ) continue; // Empty prefix needs neither to be added or removed!
if( REMOVE_SEC_PREFIX ) for // Remove pfx from page names.
(
i=-1+s.charCodeAt(0), iSup=i+s.charCodeAt(1) ;
++i < iSup ;
0===(s=a[i]||'').indexOf(pfx) && (a[i]=s.slice(pfx.length))
);
else for // Prepend pfx to page names.
(
i=-1+s.charCodeAt(0), iSup=i+s.charCodeAt(1) ;
++i < iSup ;
(s=a[i]||0).length && (a[i]=pfx+s)
);
}
}
const CHR = String.fromCharCode;
for
(
dup=0, i=-1 ; ++i < n ;
k='_'+a[i], x=r[i],
(r[k]=r.hasOwnProperty(k)?(++dup,r[k]+'_'+x):x),
r['$'+x]=CHR(i)+k.slice(1)
);
r.DUP_COUNT = dup;
return r;
},
VRTP: function(/*Document*/doc, t,a,b,q,i,o,k)
//----------------------------------
// (VariableTypes.) Create the varTypes map { $varName => typeChar}
// where typeChar is among:
// 'T' = LastPageNumber ; 'V' = PrevPageNumber ; 'X' = NextPageNumber
// 'N' = ActivePageNumber ; 'H' = ChapterNumber ; 'u' = CustomText
// 'l' = FileName ; 'o' = ModifDate ; 'D' = OutputDate
// 'O' = CreationDate ; 'Y' = RunningHeaderPara ; 'Z' = RunningHeaderChar
// 'v' = OtherVarType
// ---
// => new {} ; { $varName => [TVXNHuloDOYZ]+ }
{
t = (t=doc.textVariables).length && t.everyItem();
if( !t.isValid ) return '';
a = t.name;
b = t.variableType;
if( !(q=callee.MAP) )
{
o = VariableTypes;
t = callee.INI;
q = {};
for( k in o )
o.hasOwnProperty(k) &&
t.hasOwnProperty(k) &&
q[+o[k]] = t[k];
}
for( t={}, i=-1 ; ++i < a.length ; t['$'+a[i]]=q[+b[i]]||'v' );
return t;
}
.setup
({
INI:
{
CUSTOM_TEXT_TYPE: 'u',
FILE_NAME_TYPE: 'l',
LAST_PAGE_NUMBER_TYPE: 'T',
CHAPTER_NUMBER_TYPE: 'H',
OUTPUT_DATE_TYPE: 'D',
CREATION_DATE_TYPE: 'O',
MODIFICATION_DATE_TYPE: 'o',
MATCH_CHARACTER_STYLE_TYPE: 'Z',
MATCH_PARAGRAPH_STYLE_TYPE: 'Y',
XREF_PAGE_NUMBER_TYPE: 'v',
XREF_CHAPTER_NUMBER_TYPE: 'v',
},
}),
FSEC: function(/*[{...}]*/q,/*str|uint*/secIdentifier, i,k,s,t,r)
//----------------------------------
// (Find-Section.) Find in q the 1st section that matches secIdentifier
// secIdentifier :: uniqueName|prefix|marker (str) | index (uint)
// q :: [ idx => uniqueName ] + { _uniqueName => idx }
// + { $idx => `<ofs><length>(-|+)prefix<X1>marker<X1>algo<X1>shift` }
// and returns the section data in a volatile object.
// ---
// => { uniqueName,index,offset,length,includePrefix,prefix,marker,algo,shift }& [OK] | false [KO]
{
if( secIdentifier===secIdentifier>>>0 && secIdentifier < q.length )
{
i = secIdentifier;
k = q[i];
s = q['$'+i];
}
else
{
k = String(secIdentifier);
if( q.hasOwnProperty(t='_'+k) )
{
i = q[t];
s = q['$'+i];
}
else
{
t = '\x01'+k+'\x01';
for( i=q.length ; i-- && -1 == ('\x01'+(s=q['$'+i]).slice(3)).indexOf(t) ; );
if( 0 > i ) return false;
}
}
// s :: `<ofs><length>(-|+)prefix<X1>marker<X1>algo<X1>shift`
// ---
r = callee.DATA;
// ---
r.uniqueName = k;
r.index = i;
r.offset = s.charCodeAt(0);
r.length = s.charCodeAt(1);
r.includePrefix = 0x2B==s.charCodeAt(2);
t = s.slice(3).split(RegExp.X1);
r.prefix = t[0]||'';
r.marker = t[1]||'';
r.algo = t[2]||'';
r.shft = parseInt(t[3],10)||0;
// ---
return r;
}
.setup
({
// Volatile retObj.
DATA: { uniqueName:'', index:'', offset:0, length:0, includePrefix:false, prefix:'', marker:'', algo:'', shft:0 },
}),
ISEQ: function(/*str|{id=>any}|(Class|str|id)[]|PluralClass*/arg,/*'Page'|'Layer'|etc*/ctor,/*'pages'|'layers'|etc*/coll,/*Document*/doc,/*?{_name=>id[_id...]}*/map, r,n,t,X,i,a,k)
//----------------------------------
// (ID-Sequence.) Check the ID sequence `arg`, which can be supplied in various forms:
// (a) Sequence of IDs as a string `id_id...`
// -> in that case `arg` itself is returned.
// (b) Set of IDs in the form { `id`=>bool } or { `_id`=>bool }
// -> only the IDs matching a truthy value are collected.
// (c) Plural DOM object
// -> `arg.id` is then used.
// (d1) Array of IDs (uint>0).
// (d2) Array of names: IDs are then accessed through `doc[coll].itemByName(...)`
// unless a specific `map` is supplied.
// [CHG210815] If `map` is supplied, it may either contain _name=>id (uint)
// or _name=>'id_id...' (str) mappings. Hence multiple ids are supported for
// a single name. When dealing with page names, it is recommended to supply a
// `map`, since `itemByName(...)` only retrieves the 1st identified page.
// (d3) Array of DOM instances whose constructor name is ctor.
// -> all underlying IDs are then collected.
// This function returns a string, possibly empty, in the form `id_id_...` If the
// returned string is empty, `callee.ERR_MSG` may contain an error message that
// tells why the input `arg` is invalid.
// ---
// => `id_id_...` [OK] | '' [KO] + .ERR_MSG
{
callee.ERR_MSG = '';
const RE_SEQ = /^(?:[1-9]+)|(?:[1-9]+(_\d+)+)$/;
r = '';
if( 'string' == typeof arg )
{
RE_SEQ.test(arg)
? ( r = arg )
: ( callee.ERR_MSG = __("Invalid `%1` argument: %2. As a string it should be a sequence of %3 IDs separated by '_'."
,coll
,arg.ltrunc(300).toSource()
,ctor
));
return r;
}
if( ctor == arg.constructor.name )
{
arg.isValid
? ( ((a=arg.id) instanceof Array || (a=[a])), r=a.join('_') )
: ( callee.ERR_MSG = __("Invalid `%1` argument: %2.", coll, arg.toSpecifier()) );
return r;
}
if( arg instanceof Array )
{
if( !(n=arg.length) ) return '';
t = arg[0];
if( !t && '0'!==t )
{
callee.ERR_MSG = __("Invalid `%1` argument: %2. As an array it should contain either names, IDs or %3 instances."
,coll
,arg
,ctor
);
return '';
}