-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrobust-externalize.sty
4301 lines (3911 loc) · 187 KB
/
robust-externalize.sty
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
\ProvidesPackage{robust-externalize}[2024/03/19 v2.9+unstable Cache anything (tikz, latex, python) in a robust, efficient and pure way.]
% todo:
% change order argument replace from list, it is hard to read this way
\RequirePackage{pgfkeys} % We use the /robExt/... path to store our keys.
\RequirePackage{pgffor} % For the .list keys
\RequirePackage{graphicx} % For the includegraphics command
\RequirePackage{verbatim} % For the \verbatim command, useful for debugging purpose for instance
\RequirePackage{xsimverb} % To easily write verbatim code to files
\RequirePackage{etoolbox} % To easily write verbatim code to files
\RequirePackage{iftex} % computing md5 sum differs on lualatex/pdflatex/xelatex
\RequirePackage{xparse} % solve https://github.com/leo-colisson/robust-externalize/issues/6
\RequirePackage{atveryend} % to compile in parallel all images
%\usepackage{etl} % For auto forward https://tex.stackexchange.com/a/700844/116348
%% TODO list:
% - provide an easy way to use cross-ref, bibtex etc (we just need to add them when writing the file) without recompiling the whole document (we don't want to lose the cache everytime a new bib entry is added) but while preserving.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Utils %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the file contains a space, the jobname gets quotes around...
% https://tex.stackexchange.com/questions/418670/avoid-quotation-marks-when-using-jobname-or-currfilename
\newcommand*{\jobnameNoQuotes}{}
\newcommand*{\setjobnameNoQuotes}{%
\edef\jobnameNoQuotes{\jobname}%
\expandafter\expandafter\expandafter\setjobnameNoQuotesaux
\expandafter\jobnameNoQuotes\expandafter"\jobnameNoQuotes"\relax
}
\newcommand*{\setjobnameNoQuotesaux}{}
\def\setjobnameNoQuotesaux#1"#2"#3\relax{\def\jobnameNoQuotes{#2}}
\setjobnameNoQuotes
\ExplSyntaxOn
% in pgf it is not possible to use explsyntax
\NewDocumentCommand{\robExtMsgError}{m}{%
\msg_error:nn{robExt}{#1}
}
\NewDocumentCommand{\robExtIfWindowsTF}{mm}{%
\sys_if_platform_windows:TF {#1}{#2}%
}
% This will be printed in from of the error message, mostly useful in texstudio that only print lines
% containing errors
\def\robExtPrefixLogMessage{}
% Prints the next 4 lines after an error:
\def\robExtLinesAfterError{3}
\def\robExtRemoveLineNumber{}
%% Needed for studio to prepend ! in front of all lines, including big ones.
%% https://tex.stackexchange.com/questions/705502/message-add-symbol-in-front-of-new-lines-even-if-there-is-a-line-break
\def\robExtMessageWithPrefixNumberLines{^^J}%
\cs_new:Nn \robExt__message_with_prefix:n {
\str_set:Nn \l_tmpa_str {#1}
\int_compare:nNnTF {\str_count:N \l_tmpa_str + \str_count:N \robExtPrefixLogMessage} > {78} {
\typeout{\robExtPrefixLogMessage \str_range:Nnn \l_tmpa_str {1} {78 - \str_count:N \robExtPrefixLogMessage}\robExtMessageWithPrefixNumberLines}
\robExt__message_with_prefix:x {\str_range:Nnn \l_tmpa_str {78 - \str_count:N \robExtPrefixLogMessage + 1} {-1}}
}{
\typeout{\robExtPrefixLogMessage \l_tmpa_str \robExtMessageWithPrefixNumberLines}
}
}
\cs_generate_variant:Nn \robExt__message_with_prefix:n { x }
% We might want to remove l.XX in front of lines as emacs interpret this as a line of error and goes to a wrong place.
\cs_new:Nn \robExt__clean_line_if_needed:n {
\ifdefined\robExtRemoveLineNumber%
\str_compare:eNeTF {\str_range:nnn {#1} {1} {2}} = {l.} {
\str_range:nnn {#1} {3} {-1}%
} {
#1
}
\else
#1
\fi
}
\cs_generate_variant:Nn \robExt__clean_line_if_needed:n { V }
\cs_new:Nn \robExt_get_errors_from_file:n {
\ior_open:Nn \g__robExt_read_ior {#1}%
\cs_undefine:N \l__robExt_I_saw_an_error:
\str_clear_new:N \l__robExt_tmp_str%
\int_set:Nn \l_tmpa_int {0}
\ior_str_map_inline:Nn \g__robExt_read_ior {%
\ifdefined\robExtPrintWholeFile
\str_gput_right:Nx \l__robExt_tmp_str {\tl_to_str:n{##1}^^J}%
\cs_set:Nn \l__robExt_I_saw_an_error: {}
\int_set:Nn \l_tmpa_int {\robExtLinesAfterError}
\else
\str_if_in:xnTF {\str_lowercase:n{##1}} {error} {
\str_gput_right:Nx \l__robExt_tmp_str {\robExt__clean_line_if_needed:V{\tl_to_str:n{##1}^^J}}%
\cs_set:Nn \l__robExt_I_saw_an_error: {}
\int_set:Nn \l_tmpa_int {\robExtLinesAfterError}
} {
\str_if_in:xnTF {\str_lowercase:n{##1}} {invalid} {
\str_gput_right:Nx \l__robExt_tmp_str {\robExt__clean_line_if_needed:V{\tl_to_str:n{##1}^^J}}%
\cs_set:Nn \l__robExt_I_saw_an_error: {}
\int_set:Nn \l_tmpa_int {\robExtLinesAfterError}
} {
% Check if it starts with a ! (usually latex errors start with this symbol)
\str_compare:eNeTF {\str_range:nnn {##1} {1} {1}} = {!} {
\str_gput_right:Nx \l__robExt_tmp_str {\robExt__clean_line_if_needed:V{\tl_to_str:n{##1}^^J}}%
\cs_set:Nn \l__robExt_I_saw_an_error: {}
\int_set:Nn \l_tmpa_int {\robExtLinesAfterError}
}{
% Check if we saw an error not too long ago:
\int_compare:nNnTF {\l_tmpa_int} > {0} {
\str_gput_right:Nx \l__robExt_tmp_str {\robExt__clean_line_if_needed:V{\tl_to_str:n{##1}^^J}}%
} {
\str_set:Nn \l_tmp_str {##1}
}
\int_set:Nn \l_tmpa_int {\l_tmpa_int - 1}
}
}
}
\fi
}%
\cs_if_exist:NTF \l__robExt_I_saw_an_error: {} {
% We print the last line if we found no error. Might be useful for errors like:
% sh: ligne 1: gnuplot : commande introuvable.
\str_set_eq:NN \l__robExt_tmp_str \l_tmp_str
}
}
\cs_new:Nn \robExt_write_file_in_log:n {
\ior_open:Nn \g__robExt_read_ior {#1}%
\ior_str_map_inline:Nn \g__robExt_read_ior {%
\ifdefined\robExtPrintWholeFile
\ifdefempty{\robExtPrefixLogMessage}{
\typeout{\tl_to_str:n{##1}}%
}{
\robExt__message_with_prefix:x {\tl_to_str:n{##1}}
}
\else
\typeout{\tl_to_str:n{##1}}%
\fi
}%
}
\cs_generate_variant:Nn \robExt_write_file_in_log:n { x }
\ExplSyntaxOff
% Debug function: by default, do nothing
\def\robExtDebugMessage#1{}
\def\robExtDebugInfo#1{\message{#1}}
\def\robExtDebugWarning#1{\message{^^J[robExt warning] #1}}
\NewDocumentCommand{\robExtConfigure}{m}{%
\pgfqkeys{/robExt}{#1}% faster than \pgfkeys{/robExt/.cd,#1}
}
% https://tex.stackexchange.com/questions/690700/latex3-elegant-way-to-forward-a-variable-outside-of-the-group
% modified to deal with csname instead
\def\robExtKeepaftergroup#1{%
%\global \expandafter \expandafter \let \csname x:#1\endcsname =\csname #1\endcsname
\global \expanded{\noexpand \let \expandafter\noexpand\csname x:#1\endcsname =\expandafter\noexpand\csname #1\endcsname}%
\aftergroup\let%
\expandafter\aftergroup\csname #1\endcsname%
\expandafter\aftergroup \csname x:\string#1\endcsname%
}
\ExplSyntaxOn
%%%
%%% Expl3 variants
%%%
\cs_generate_variant:Nn \str_replace_all:Nnn { Nnx, Nnv, cnx, cxx, NnV, Nnx, Nnv }
\cs_generate_variant:Nn \str_set:Nn { NV }
\cs_generate_variant:Nn \str_if_in:nnTF { xnTF }
\cs_generate_variant:Nn \tl_rescan:nn { nv }
\cs_generate_variant:Nn \tl_set_rescan:Nnn { Nnv, NnV }
\cs_generate_variant:Nn \tl_gset_rescan:Nnn { cnv }
\cs_generate_variant:Nn \seq_remove_all:Nn { NV }
\cs_generate_variant:Nn \iow_now:Nn { NV,Nx }
\cs_generate_variant:Nn \iow_open:Nn { Nx }
\cs_generate_variant:Nn \ior_str_get:NN { Nc }
\cs_generate_variant:Nn \file_if_exist:nTF { xTF }
\cs_generate_variant:Nn \file_mdfive_hash:n { x }
\cs_generate_variant:Nn \cs_replacement_spec:N { c }
\cs_generate_variant:Nn \cs_argument_spec:N { c }
\cs_generate_variant:Nn \str_count_ignore_spaces:n { V }
\cs_generate_variant:Nn \str_count_spaces:n { e }
\cs_generate_variant:Nn \regex_extract_all:nnN { VVN, nVN, VVN }
\cs_generate_variant:Nn \regex_extract_all:NnN { NVN }
\cs_generate_variant:Nn \regex_match:nnTF { nVTF }
\cs_generate_variant:Nn \seq_set_split_keep_spaces:Nnn {Nnv}
%%%
%%% String manipulation
%%%
\cs_set:Nn \robExt_set_hash_robust:Nn {
\str_set:Nn {#1} {#2}
\str_replace_all:Nnx {#1} { ## } { \c_hash_str }
}
\cs_generate_variant:Nn \robExt_set_hash_robust:Nn { cn }
\cs_generate_variant:Nn \robExt_set_hash_robust:Nn { cx }
\NewDocumentCommand{\robExt@set@hash@robust}{mm}{\robExt_set_hash_robust:Nn #1 {#2}}
% Double the number of hashes... quite dirty but cannot find any solution or the user need to double it itself
%% See also https://tex.stackexchange.com/questions/695432/latex3-latex-doubles-the-number-of-hashes-when-storing-them-in-string/695460#695460
\NewDocumentCommand{\robExtStrSetDoubleHash}{mm}{
\str_set:Nn {#1} {#2}
\str_replace_all:Nnx {#1} { ## } { \c_hash_str \c_hash_str }
}
\NewDocumentCommand{\robExtStrSetHashRobust}{mm}{
\robExt_set_hash_robust:Nn {#1} {#2}
}
\NewDocumentCommand{\robExtRescanHashRobust}{m}{
\robExt_set_hash_robust:Nn \l__robExt_tmp_str {#1}
\tl_rescan:nv {}{ l__robExt_tmp_str }
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Error messages %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% In LaTeX3 error messages are defined here, this allows people to translate them, filter them, change them,
%% make them more verbose etc.
\msg_new:nnn {robExt}{underscore in name}{Error:~all~the~placeholders~should~contain~two~consecutive~underscores~in~their~name.}
\msg_new:nnn {robExt}{placeholder not existing}{[robExtGetPlaceholderInResultFromSinglePlaceholder] ~ The ~ placeholder ~ #1 ~ does ~ not ~ exists.}
\msg_new:nnn {robExt}{forgot template}{You ~ are ~ writing ~ __ROBEXT_TEMPLATE__ ~ to ~ your ~ file: ~ seems ~ like ~ you ~ forgot ~ to ~ define ~ your ~ template ~ or ~ set ~ a ~ preset}
\msg_new:nnn {robExt}{need shell escape}{You ~ need ~ to ~ compile ~ with ~ shell-escape ~ as ~ in: ~ "pdflatex ~ -shell-escape ~ yourfile.tex" ~ to ~ be ~ able ~ to ~ compile ~ automatically ~ the ~ figures}
\msg_new:nnn {robExt}{need shell escape with}{You ~ need ~ to ~ compile ~ with ~ shell-escape ~ as ~ in: ~ "pdflatex ~ -shell-escape ~ yourfile.tex" ~ to ~ be ~ able ~ to ~ #1}
\msg_new:nnn {robExt}{need shell escape parallel}{You ~ need ~ to ~ compile ~ with ~ shell-escape ~ as ~ in: ~ "pdflatex ~ -shell-escape ~ yourfile.tex" ~ to ~ be ~ able ~ to ~ compile ~ automatically ~ the ~ figures ~ in ~ parallel}
\msg_new:nnn {robExt}{missing compiled pdf parallel}{The~compilation~of~block~at~line~#2~failed~as~the~following ~ file~is~missing: ~ #1.pdf. ~ The ~ compilation ~ command ~ "#3"~used~to~compile~the~environment~on~line~#2~ certainly ~ failed, ~ see ~ logs ~ above ~ or ~ in ~ #1.log.}
\msg_new:nnn {robExt}{dependency does not exist}{The~dependency~#1~does~not~exist.}
\msg_new:nnn {robExt}{missing compiled pdf parallel with log}{The~compilation~of~the~code~block~at~line~#2~failed:~the~following ~ file~is~indeed~missing: ~ #1.pdf. ~ The ~ compilation ~ command ~ "#3"~used~to~compile~the~environment~on~line~#2~ certainly ~ failed~with~errors:^^Jvvvvvv^^J\l__robExt_tmp_str^^J\string^\string^\string^\string^\string^\string^ ^^JSee~full~logs~#4~ or ~ in ~ #1-compilation.log.}
\msg_new:nnn {robExt}{remove spaces until non spaces characters}{The~placeholder~#1~contains~characters~other~than~spaces~(#2)~before~the~separator~#3.}
\msg_new:nnn {robExt}{need to load pythonhighlight}{You~need~to~load~the~package~pythonhighlight~to~use~the~lstlisting~style~pythonhighlight-style.}
\msg_new:nnn {robExt}{auto forward not in cachemecode}{Auto~forward~is~less~efficient~in~cacheMeCode.}
\msg_new:nnn {robExt}{file does not exist}{The~file~#1~does~not~exist.}
% warnings
\msg_new:nnn {robExt}{recommend two underscores in placeholders}{We~recommend~to~use~only~placeholders~containing~two~consecutive~underscores~in~their~name}
\msg_new:nnn {robExt}{enabled parallel no shell escape}{Warning:~you~enabled~parallel~compilation~but~shell-escape~is~disabled.}
\msg_new:nnn {robExt}{rerun because parallel}{Warning:~Compiling~all~missing~figures~in~parallel~with~"#1".~You~need~to~rerun~LaTeX~to~include~them.}
\msg_new:nnn {robExt}{gpgetvar recompilation needed}{Warning:~you~need~to~recompile~as~the~gpgetvar~variable~"#1"~does~not~exist~yet.}
% dummy placeholders added if image is not present
\def\robExtImagePlaceholderIfManualMode{
\framebox[\linewidth]
{
\begin{minipage}{\linewidth}
\textbf{Manual ~ mode: ~ either ~ compile ~ with ~ \texttt{-shell-escape} ~ or ~ compile:\newline \texttt{\robExtAddCachePathAndName{\robExtFinalHash.tex}}\newline via ~ \newline \texttt{\l__robExt_current_compilation_command_str}\newline or ~ call ~ \newline\texttt{bash ~ \jobnameNoQuotes-\robExtAddPrefixName{compile-missing-figures.sh}}\newline to ~ compile ~ all ~ missing ~ figures.}
\end{minipage}
}
}
\def\robExtImagePlaceholderIfFallbackMode{
\framebox[\linewidth]
{
\begin{minipage}{\linewidth}
\textbf{Falling ~ back ~ to ~ draft ~ mode: ~ either ~ compile ~ with ~ \texttt{-shell-escape} ~ or ~ compile:\newline \texttt{\robExtAddCachePathAndName{\robExtFinalHash.tex}}\newline via ~ \newline \texttt{\l__robExt_current_compilation_command_str}\newline or ~ call ~ \newline\texttt{bash ~ \jobnameNoQuotes-\robExtAddPrefixName{compile-missing-figures.sh}}\newline to ~ compile ~ all ~ missing ~ figures.}
\end{minipage}
}
}
\def\robExtImagePlaceholderIfParallelCompilation{
\framebox[\linewidth]
{
\begin{minipage}{\linewidth}
\textbf{The~file:\\
\texttt{\robExtAddCachePathAndName{\robExtFinalHash.tex}}\\
is~compiled~in~parallel~mode.~You~need~to~recompile~your~document~to~include~it.}
\end{minipage}
}
}
\ExplSyntaxOff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% SCRIPTS %%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Important: this script is NOT executed by this file, it is only created so that users can remove unused previously cached files by running this script
%%% outside of LaTeX.
%%% Create scripts to remove useless files:
\begin{filecontents}[noheader,overwrite]{robExt-remove-old-figures.py}
#!/usr/bin/env python3
## This file is automatically generated, so do not change that file directly
## Instead, if you need to change it, copy it with a different name and edit the copy
import os
import re
import glob
# Just run this script in order to remove all old figures not listed in robExt-all-figures.txt.
# Note that this part is not extracted from the pdf file since it might be different on a previous run. You can however hardcode
# it here, your updated script will not be overriden unless you remove it yourself.
prefixes = [ "robExt-" ]
folders = [ "robustExternalize" ]
def main():
imagesToKeep = dict()
list_all_figures_file = glob.glob('*robExt-all-figures.txt')
for filename in list_all_figures_file:
with open(filename) as f:
for line in f:
line = line.strip()
if line.endswith('.tex'):
imagesToKeep[line[:-4]] = True # The exact value is not important, we mostly use dict to get ~O(1) access
listOfFilesToRemove = []
# We are looking for images in the folders
for folder in folders:
for root, dirs, files in os.walk(folder):
for f in files:
for prefix in prefixes: # Not the most efficient, but anyway we typically have a single prefix
# In case prefix contains weird caracters that collide with regexps:
prefixEsc = re.escape(prefix)
# result_search = re.search(rf"^({prefixEsc}[A-F0-1]{32}).*", f)
result_search = re.search(rf"^(.*[A-F0-9]{{32}}).*", f)
if result_search:
if result_search.group(1) not in imagesToKeep:
listOfFilesToRemove.append(os.path.join(root,f))
for f in listOfFilesToRemove:
print(f"-- {f}")
print(f"Above are the files to remove, are you sure you want to proceed? [y/N] (based on prefixes {prefixes})")
x = input().strip()
if x not in ["y", "Y"]:
print("All right, we abort.")
exit(1)
for f in listOfFilesToRemove:
os.remove(f)
print(f"Removed {f}")
if __name__ == '__main__':
main()
\end{filecontents}
\begin{filecontents}[noheader,overwrite]{robExt-prepare-for-arxiv.py}
#!/usr/bin/env python3
## This file is automatically generated, so do not change that file directly
## Instead, if you need to change it, copy it with a different name and edit the copy
## This file must be called when sending stuff to the arxiv website, that would otherwise remove the .pdf
## in presence of a .tex.
## This script will simply rename the .tex files in robustExternalize into .tex-backup.
## Then, you should call "rename backup files for arxiv" to rename back the files.
import os
import re
import glob
# Just run this script in order to remove all old figures not listed in robExt-all-figures.txt.
# Note that this part is not extracted from the pdf file since it might be different on a previous run. You can however hardcode
# it here, your updated script will not be overriden unless you remove it yourself.
prefixes = [ "robExt-" ]
folders = [ "robustExternalize" ]
def main():
listOfFilesToMove = []
listOfFilesAlreadyAdded = set()
for folder in folders:
for root, dirs, files in os.walk(folder):
for f in files:
if f.endswith(".tex"):
pdf = os.path.splitext(f)[0] + ".pdf"
if os.path.exists(os.path.join(root,pdf)):
listOfFilesToMove.append((os.path.join(root,f), os.path.join(root,f + "-backup")))
if f.endswith(".tex-backup"):
tex = os.path.splitext(f)[0] + ".tex"
listOfFilesAlreadyAdded.add(os.path.join(root,tex))
for (f,f2) in listOfFilesToMove:
print(f"-- {f} moved to {f2}")
listOfFilesAlreadyAdded.discard(f)
for f in listOfFilesAlreadyAdded:
print(f"-- {f} already moved")
print(f"Above are the files to move or already moved, are you sure you want to proceed? [y/N] (based on prefixes {prefixes})")
x = input().strip()
if x not in ["y", "Y"]:
print("All right, we abort.")
exit(1)
for (f,f2) in listOfFilesToMove:
os.replace(f, f2)
print(f"Moved {f} to {f2}")
with open('robExt-arxiv-files-to-rename.txt', 'w') as fd:
for (f,f2) in listOfFilesToMove:
fd.write(f'{f}\n')
for f in listOfFilesAlreadyAdded:
fd.write(f'{f}\n')
print('The files have been written to robExt-arxiv-files-to-rename.txt.')
print('Add \\robExtConfigure{rename backup files for arxiv} in your tex file.')
if __name__ == '__main__':
main()
\end{filecontents}
\ExplSyntaxOn
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Compatibility %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% These commands exist on really recent kernels (~june 2023), so we provide them in case they do not already exist
\ProvideDocumentCommand \NewEnvironmentCopy {mm} {
\expandafter \NewCommandCopy \csname#1\expandafter\endcsname \csname#2\endcsname
\expandafter \NewCommandCopy \csname end#1\expandafter\endcsname \csname end#2\endcsname
}
\ProvideDocumentCommand \RenewEnvironmentCopy {mm} {
\expandafter \RenewCommandCopy \csname#1\expandafter\endcsname \csname#2\endcsname
\expandafter \RenewCommandCopy \csname end#1\expandafter\endcsname \csname end#2\endcsname
}
\ProvideDocumentCommand \DeclareEnvironmentCopy {mm} {
\expandafter \DeclareCommandCopy \csname#1\expandafter\endcsname \csname#2\endcsname
\expandafter \DeclareCommandCopy \csname end#1\expandafter\endcsname \csname end#2\endcsname
}
\ProvideDocumentCommand \RenewEnvironmentCopy {mm} {
\expandafter \RenewCommandCopy \csname#1\expandafter\endcsname \csname#2\endcsname
\expandafter \RenewCommandCopy \csname end#1\expandafter\endcsname \csname end#2\endcsname
}
%% Depending on the engine, computing md5 is done in different ways
\sys_if_engine_luatex:TF{
\def\robExt@pdfmdfivesum#1{%
\directlua{tex.print(string.upper(md5.sumhexa("\luaescapestring{#1}")))}%
}%
}{
\sys_if_engine_xetex:TF {%
\def\robExt@pdfmdfivesum{\mdfivesum}%
}{%
\def\robExt@pdfmdfivesum{\pdfmdfivesum}%
}%
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Paths %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% For support of --output-directory
\def\robExtPrefixAllCompilationCommands{\ifdefined\robExtOutputDirectory cd~"\robExtOutputDirectory"~&&~\fi}
\def\robExtPrefixFilename{robExt-}
\NewExpandableDocumentCommand{\robExtAddCachePathAndName}{m}{%
\ifdefined\robExtCacheFolder%
\robExtCacheFolder%
\fi\robExtPrefixFilename#1%
}
\NewExpandableDocumentCommand{\robExtAddCachePath}{m}{%
\ifdefined\robExtCacheFolder%
\robExtCacheFolder%
\fi#1%
}
% mv in unix and move in windows:
\robExtIfWindowsTF{
\def\robExtMv{move}
\def\robExtCp{copy}
}{
\def\robExtMv{mv}
\def\robExtCp{cp}
}
\NewDocumentCommand{\robExtBackupSource}{m}{%
% arXiv will remove the .pdf file if the .tex is present. Solution: we move the .tex into .tex-backup
% and restore it during compilation. We could also backup the pdf but usually this file is bigger and will contain
% binary data that might not be so easy to copy in pure tex (in arxiv shell escape is disabled so we cannot
% use cp).
% \show\inBackupSource
\robExtRunCmdIfPossible{%
\robExtMv\space"\robExtAddCachePath{#1}"~%
"\robExtAddCachePath{#1-backup}"%
}%
}
\NewDocumentCommand{\robExtRunCmdIfPossible}{m}{%
% Check if the output directory exists
\bool_if:nTF { \sys_if_shell_unrestricted_p: || \cs_if_exist_p:N \robExtForceCompilation}
{
\ifdefined\robExtManualMode
\message{Warning:~running~in~manual~mode~so~we~cannot~run~the~command~``#1''.}
\iow_now:Nx \g__robExt_write_manually_compile_all_missing_figures_iow {#1}
\else
\message{Running:~\robExtPrefixAllCompilationCommands #1}%
\sys_shell_now:x {\robExtPrefixAllCompilationCommands #1}
\fi
}{
\ifdefined\robExtFallbackManualMode
\message{Warning:~shell~escape~fallback~to~manual~mode~so~cannot~run~#1.}
\iow_now:Nx \g__robExt_write_manually_compile_all_missing_figures_iow {#1}
\else
\msg_error:nnx{robExt}{need shell escape with}{run~#1}
\fi
}
}
\NewDocumentCommand{\robExtCheckIfPrefixFolderExists}{}{
% Check if the output directory exists and is not empty
\ifdefined\robExtCacheFolder
\ifx\robExtCacheFolder\empty\else
\bool_if:nTF { \sys_if_shell_unrestricted_p: || \cs_if_exist_p:N \robExtForceCompilation}
{
\ifdefined\robExtDoNotMkdirFolder\else
\ifdefined\robExtManualMode
\message{If ~ you ~ get~ an~ error,~ make ~ sure ~ to ~ enable ~ pdflatex ~ -shell-escape ~ or ~ to ~ MANUALLY ~ CREATE ~ THE ~ FOLDER ~ \robExtCacheFolder.}
\else
\sys_shell_now:x {\robExtPrefixAllCompilationCommands mkdir ~ -p ~ \robExtCacheFolder}
\fi
\fi
}{
\message{Warning: If ~ you ~ get~ an~ error,~ make ~ sure ~ to ~ enable ~ pdflatex ~ -shell-escape ~ or ~ to ~ manually ~ CREATE ~ THE ~ FOLDER ~ \robExtCacheFolder.}
}
\fi
\fi
}
\NewDocumentCommand{\robExtCopyFileToCache}{m}{
\robExtCheckIfPrefixFolderExists%
\file_if_exist:xTF {#1}{}{
\msg_error:nnx{robExt}{file does not exist}{#1~(to~copy~to~cache)}
}
\file_if_exist:xTF {\robExtAddCachePath{#1}}{
\robExtDebugInfo{The~file~\robExtAddCachePath{#1}~already~exists,~let~us~compare~md5~sum.}
\str_set:Nx \l_tmpa_str {\file_mdfive_hash:n{#1}}
\str_set:Nx \l_tmpb_str {\file_mdfive_hash:n{\robExtAddCachePath{#1}}}
\str_compare:eNeTF {\l_tmpa_str} = {\l_tmpb_str} {
\robExtDebugInfo{The~file~\robExtAddCachePath{#1}~has~the~good~md5~hash.}
}{
\robExtDebugInfo{The~md5~hashes~of~#1~and~\robExtAddCachePath{#1}~are~different(\l_tmpa_str \space vs \space \l_tmpb_str),~let~us~copy~the~file.}%
\robExtRunCmdIfPossible{\robExtCp \space "#1"~"\robExtAddCachePath{#1}"}%
}
}{
\robExtDebugInfo{The~file~\robExtAddCachePath{#1}~does~not~exist,~let~us~copy~it:}
\robExtRunCmdIfPossible{\robExtCp \space "#1"~"\robExtAddCachePath{#1}"}%
}
}
\let\copyFileToCache\robExtCopyFileToCache
% \robExtRenameBackupFilesForArxiv{robExt-arxiv-files-to-rename.txt} takes all elements listed in the .tex file
% (like robustExternalize/robExt-F83AB245D8043E653A89489C2E25AA6A.tex) and rename the
% robustExternalize/robExt-F83AB245D8043E653A89489C2E25AA6A.tex-backup into
% robustExternalize/robExt-F83AB245D8043E653A89489C2E25AA6A.tex
% (needed for arxiv)
% This is done, importantly, without shell escape as arxiv does not have shell escape.
\NewDocumentCommand{\robExtRenameBackupFilesForArxiv}{O{-backup}m}{
\file_if_exist:xTF{#2} {
\robExtDebugInfo{We~will~read~the~file~#2.}
\ior_open:Nn \g__robExt_read_ior {#2}%
%% We avoid creating a new ior since the number of available files is limited in tex
\seq_clear:N \l_tmpa_seq
\ior_str_map_inline:Nn \g__robExt_read_ior {%
\file_if_exist:xTF{##1#1} {
\seq_put_right:Nn \l_tmpa_seq {##1}
}{
\robExtDebugInfo{Warning:~##1#1~does~not~exist,~so~we~will~not~rename~back~this~file~for~arXiv.}
}
}%
\ior_close:N \g__robExt_read_ior
\seq_map_inline:Nn \l_tmpa_seq {
\robExtDebugInfo{We~copy~the~source~##1#1~to~##1^^J}%
% First we read the file:
\ior_open:Nn \g__robExt_read_ior {##1#1}%
\iow_open:Nx \g__robExt_write_iow {##1}
\ior_str_map_inline:Nn \g__robExt_read_ior {%
\iow_now:Nx \g__robExt_write_iow {\tl_to_str:n{####1}}%
}%
\iow_close:N \g__robExt_write_iow
\ior_close:N \g__robExt_read_ior
}
}{
\robExtDebugInfo{Warning:~#2~does~not~exist,~so~we~will~not~rename~back~elements~for~arXiv.}
}
}
\NewExpandableDocumentCommand{\robExtGetPrefixPath}{}{%
\ifdefined\robExtCacheFolder%
\robExtCacheFolder%
\fi%
}
\NewExpandableDocumentCommand{\robExtAddPrefixName}{m}{%
\robExtPrefixFilename#1%
}
%% Todo: not sure if I should use \seq_push:Nx \l_file_search_path_seq {subfolder}
%% to find the subfolder (seems to work for input/includegraphics/...), or if it's
%% better to hardcode the subfolder.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Setup new commands and variables %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Temporary: used when quickly writing to a file
\iow_new:N \g__robExt_write_iow
\ior_new:N \g__robExt_read_ior
%% This is used to write the full list of figures in a single file (used for instance by Makefile etc...)
%% TODO: create a makefile.
\iow_new:N \g__robExt_write_list_all_figures_iow
%% Create a file robExt-all-figures.txt with the list of .tex files
\iow_open:Nx \g__robExt_write_list_all_figures_iow {\jobnameNoQuotes-\robExtAddPrefixName{all-figures.txt}}
\iow_new:N \g__robExt_write_manually_compile_all_missing_figures_iow
\iow_open:Nx \g__robExt_write_manually_compile_all_missing_figures_iow {\jobnameNoQuotes-\robExtAddPrefixName{compile-missing-figures.sh}}
% Contains the list of dependency files (useful to compute the final md5sum)
\seq_new:N \l__robExt_dependencies_str
% Contains a string where on each line we have: "md5sum, dependency". The first line has nothing as "dependency" as it is the main fine whose final name is the md5sum of the dependencies.
\str_new:N \l__robExt_dependencies_mdfive_str
% Contains the current compilation command (including the name of the file to compile).
\str_new:N \l__robExt_current_compilation_command_str
\str_new:N \l__robExt_tmp_str
% To have a code compatible even on older versions
% https://tex.stackexchange.com/questions/615010/how-can-i-use-latex-hooks-in-historical-versions-of-tex-live
\providecommand\RobExtIfFormatAtLeastTF{\@ifl@t@r\fmtversion}
\RobExtIfFormatAtLeastTF{2020-10-01}%
{
% https://ctan.math.illinois.edu/macros/latex/base/lthooks-doc.pdf
\NewHook{robust-externalize/just-before-writing-files}
\def\robExtUseHookJustBeforeWritingFiles{\UseHook{robust-externalize/just-before-writing-files}}%
}%
{
\def\robExtUseHookJustBeforeWritingFiles{}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Placeholders %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Placeholders are strings like "__MYLIBRARY__" or "__MAINCONTENT__" that will be replaced by a given content.
%% In practice:
%% - for every placeholder MYPLACEHOLDER, a macro \l__robExt_placeholder_MYPLACEHOLDER_str is created, containing
%% the string to use to replace it
%% - a sequence \l__robExt_placeholder_group_main_seq that is a list of string, contains the list of all placeholders,
%% in a string, like [MYLIBRARY, MAINCONTENT] etc...
%% One issue is that LaTeX does not keep some symbols (e.g. % etc...) when used inside a macro, so we define
%% different commands depending on whether they can be used in a macro or not, whether they should be taken
%% from an external file etc...
\seq_clear_new:N \l__robExt_placeholder_group_main_seq
%%%
%%% Debug in terminal
%%%
\NewDocumentCommand{\robExtShowPlaceholder}{sm}{
\cs_if_exist:cTF {l__robExt_placeholder_#2_str} {
\message{Placeholder ~ #2 ~ contains:^^J \use:c{l__robExt_placeholder_#2_str}}
}{
\message{Placeholder ~ #2 ~ does ~ not ~ exist.}
}
\IfBooleanTF{#1}{}{\show\def}
}
\NewDocumentCommand{\robExtShowPlaceholders}{s}{
\message{List ~ of ~ placeholders:}
\seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {\message{##1,}}
\IfBooleanTF{#1}{}{\show\def}
}
\NewDocumentCommand{\robExtShowPlaceholdersContents}{s}{
\message{List ~ of ~ placeholders:}
\seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {\robExtShowPlaceholder*{##1}}
\IfBooleanTF{#1}{}{\show\def}
}
%%%
%%% Debug in document
%%%
\NewDocumentCommand{\robExtPrintPlaceholderNoReplacement}{sm}{%
% For some reasons, newlines are displayed as \Omega. We need to replace them with \\
% https://tex.stackexchange.com/questions/694716/print-latex3-string-verbatim/694717
\tl_set_eq:Nc \l__robExt_tmp_str { l__robExt_placeholder_#2_str }
\tl_replace_all:Nnn \l__robExt_tmp_str {^^J} { \mbox{}\par } % mbox is helpful to print empty lines
\tl_replace_all:Nnn \l__robExt_tmp_str { ~ } { \ }
\IfBooleanTF{#1}{\texttt{\use:c{l__robExt_placeholder_#2_str}}}{\begin{flushleft}\ttfamily%
\l__robExt_tmp_str
\end{flushleft}%
}
}
\let\printPlaceholderNoReplacement\robExtPrintPlaceholderNoReplacement
\NewDocumentCommand{\robExtPrintPlaceholder}{sm}{%
\robExtGetPlaceholderInResult{#2}
% For some reasons, newlines are displayed as \Omega. We need to replace them with \\
% https://tex.stackexchange.com/questions/694716/print-latex3-string-verbatim/694717
\tl_set_eq:NN \l__robExt_tmp_str \l_robExt_result_str
\tl_replace_all:Nnn \l__robExt_tmp_str {^^J} { \mbox{}\par }
\tl_replace_all:Nnn \l__robExt_tmp_str { ~ } { \ }
\IfBooleanTF{#1}{\texttt{\l__robExt_tmp_str}}{\begin{flushleft}\ttfamily%
\l__robExt_tmp_str
\end{flushleft}%
}
}
\let\printPlaceholder\robExtPrintPlaceholder
\NewDocumentCommand{\robExtPrintAllPlaceholdersExceptDefaults}{s}{
List ~ of ~ placeholders:\\
\seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {
% We hide the elements starting with __ROBEXT_
\str_if_in:nnTF { ##1 } { __ROBEXT_ } {
\IfBooleanTF {#1} {
- ~ Placeholder ~ called ~ \texttt{\tl_to_str:n {##1}} ~ defined ~ by ~ default ~ (we ~ hide ~ the ~ definition ~ to ~ save ~ space)\\
}{}
}{
- ~ Placeholder ~ called ~ \texttt{\tl_to_str:n {##1}} ~ contains: \robExtPrintPlaceholderNoReplacement{##1}
}
}
}
\let\printAllPlaceholdersExceptDefaults\robExtPrintAllPlaceholdersExceptDefaults
\let\printImportedPlaceholdersExceptDefaults\robExtPrintAllPlaceholdersExceptDefaults
\NewDocumentCommand{\robExtPrintAllPlaceholders}{}{
List ~ of ~ placeholders:\\
\seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {- ~ Placeholder ~ called ~ \texttt{\tl_to_str:n {##1}} ~ contains: \robExtPrintPlaceholderNoReplacement{##1}}
}
\let\printAllPlaceholders\robExtPrintAllPlaceholders
\let\printImportedPlaceholders\robExtPrintAllPlaceholders
%%%
%%% Evaluation of placeholders
%%%
\NewDocumentCommand{\robExtEvalPlaceholderNoReplacement}{m}{
% scantokens add an empty space at the end, so we need to add \empty to avoid it having effects
% https://tex.stackexchange.com/questions/213659/could-someone-further-elucidate-expansion-catcodes-and-scantokens
\tl_rescan:nv {}{ l__robExt_placeholder_#1_str }
}
\let\evalPlaceholderNoReplacement\robExtEvalPlaceholderNoReplacement
\NewExpandableDocumentCommand{\robExtGetPlaceholderNoReplacement}{m}{
\str_use:c { l__robExt_placeholder_#1_str }
}
\let\getPlaceholderNoReplacement\robExtGetPlaceholderNoReplacement
\NewDocumentCommand{\robExtRescanPlaceholderInVariableNoReplacement}{mm}{
\tl_gset_rescan:cnv {#1} {} { l__robExt_placeholder_#2_str }
}
\let\rescanPlaceholderInVariableNoReplacement\robExtRescanPlaceholderInVariableNoReplacement
% Make sure that the placeholder is in the list \l__robExt_placeholder_group_main_seq.
% This should automatically be called by other tools
\NewDocumentCommand{\robExtAddPlaceholderToList}{m}{
\cs_if_exist:NTF {\robExtCompletelyDisableWholeImportSystem}{}{
% Make sure we have a string here:
\robExt_set_hash_robust:Nn \l__robExt_tmp_str { #1 }
% First we remove existing occurrences (useful to avoid listing the same macro more than once
% if we redefine a macro):
\seq_remove_all:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
\seq_put_right:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
}
}
\let\robExtImportPlaceholder\robExtAddPlaceholderToList
\let\importPlaceholder\robExtAddPlaceholderToList
\NewDocumentCommand{\robExtClearImportedPlaceholders}{}{
\seq_clear:N \l__robExt_placeholder_group_main_seq
}
\let\clearImportedPlaceholders\robExtClearImportedPlaceholders
\NewDocumentCommand{\robExtRemoveImportedPlaceholder}{m}{
\robExt_set_hash_robust:Nn \l__robExt_tmp_str { #1 }
\seq_remove_all:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
}
\let\removeImportedPlaceholder\robExtRemoveImportedPlaceholder
% add it first in the list
\NewDocumentCommand{\robExtAddPlaceholderToListFirst}{m}{
% Make sure we have a string here:
\robExt_set_hash_robust:Nn \l__robExt_tmp_str { #1 }
% First we remove existing occurrences (useful to avoid listing the same macro more than once
% if we redefine a macro):
\seq_remove_all:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
\seq_put_left:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
}
\let\robExtImportPlaceholderFirst\robExtAddPlaceholderToListFirst
\let\importPlaceholderFirst\robExtAddPlaceholderToListFirst
% add it first in the list
\NewDocumentCommand{\robExtAddPlaceholdersToListFirst}{m}{
\robExt_set_hash_robust:Nn \l__robExt_tmp_str { #1 }
\seq_set_from_clist:NN \l_tmp_seq \l__robExt_tmp_str
% First we remove existing occurrences (useful to avoid listing the same macro more than once
% if we redefine a macro):
\seq_map_inline:Nn \l_tmp_seq {
% This seems to be required to ensure catcodes are correct before removing the elements:
\seq_remove_all:Nn \l__robExt_placeholder_group_main_seq {##1}
}
\seq_put_left:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
}
\let\robExtImportPlaceholdersFirst\robExtAddPlaceholdersToListFirst
\let\importPlaceholdersFirst\robExtAddPlaceholdersToListFirst
\NewDocumentCommand{\robExtRemovePlaceholder}{m}{
% This seems to be required to ensure catcodes are correct before removing the elements:
\robExt_set_hash_robust:Nn \l__robExt_tmp_str { #1 }
% First we check if it exists, no need to loop over everything otherwise
\str_if_exist:cTF { l__robExt_placeholder_#1_str } {
\seq_remove_all:NV \l__robExt_placeholder_group_main_seq \l__robExt_tmp_str
\expandafter \let \csname l__robExt_placeholder_#1_str \endcsname \undefined
} { }
}
\let\removePlaceholder\robExtRemovePlaceholder
\NewDocumentCommand{\checkIfPlaceholderNameIsLegal}{m}{
\cs_if_exist:NTF {\robExtPlaceholderOnlyWithUnderscores} {
\str_if_in:nnTF {#1}{__}{}{
\msg_error:nn{robExt}{underscore in name}
}
} {
\str_if_in:nnTF {#1}{__}{}{
\msg_warning:nn{robExt}{recommend two underscores in placeholders}
}
}
}
%% Usage: \placeholderFromContent{MYTITLE}{My slide title}
%% MYTITLE will contain at the end "My slide title"
%% Warning: only LaTeX-friendly code should be placed here, as LaTeX does not preserve some symbols and adds spaces
%% Tested!
%% The star version does NOT import the placeholder (useful for efficiency reasons)
\NewDocumentCommand{\robExtPlaceholderFromContent}{sm+m}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
\checkIfPlaceholderNameIsLegal{#2}
\ifdefined\robExtCompletelyDisableWholeImportSystem\else% Mostly for time optimizations...
\IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}%
\fi
}
\let\placeholderFromContent\robExtPlaceholderFromContent
\let\robExtSetPlaceholder\robExtPlaceholderFromContent
\let\setPlaceholder\robExtPlaceholderFromContent
\NewDocumentCommand{\robExtPlaceholderFromContentFirst}{smm}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
\checkIfPlaceholderNameIsLegal{#2}
\IfBooleanTF {#1} {} {\robExtAddPlaceholderToListFirst{#2}}
}
\let\placeholderFromContentFirst\robExtPlaceholderFromContentFirst
\let\robExtSetPlaceholderFirst\robExtPlaceholderFromContentFirst
\let\setPlaceholderFirst\robExtPlaceholderFromContentFirst
\NewDocumentCommand{\robExtPlaceholderFromString}{smm}{
\str_set_eq:cN { l__robExt_placeholder_#2_str } #3
\checkIfPlaceholderNameIsLegal{#2}
\IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\placeholderFromString\robExtPlaceholderFromString
\let\setPlaceholderFromString\robExtPlaceholderFromString
\NewDocumentCommand{\robExtPlaceholderFromStringExpanded}{smm}{
\str_set:cx { l__robExt_placeholder_#2_str } {#3}
\checkIfPlaceholderNameIsLegal{#2}
\IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\placeholderFromStringExpanded\robExtPlaceholderFromStringExpanded
\let\setPlaceholderFromStringExpanded\robExtPlaceholderFromStringExpanded
\NewDocumentCommand{\robExtCopyPlaceholder}{smm}{
\str_set_eq:cc { l__robExt_placeholder_#2_str } { l__robExt_placeholder_#3_str }
\IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\copyPlaceholder\robExtCopyPlaceholder
%% Add something to the right of the placeholder
%% By default it adds a space in between, unless we use the star version
\NewDocumentCommand{\robExtAddToPlaceholder}{smm}{
\str_if_exist:cTF { l__robExt_placeholder_#2_str } {
\robExt_set_hash_robust:Nn \l_tmp_str {#3} %% needed as put_right does not convert to string first
\IfBooleanTF{#1}{}{\str_put_right:cn { l__robExt_placeholder_#2_str } { ~ } }
\str_put_right:cV { l__robExt_placeholder_#2_str } \l_tmp_str
}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
\robExtAddPlaceholderToList{#2}
}
}
\let\addToPlaceholder\robExtAddToPlaceholder
\NewDocumentCommand{\robExtAddToPlaceholderNoImport}{smm}{
\str_if_exist:cTF { l__robExt_placeholder_#2_str } {
\robExt_set_hash_robust:Nn \l_tmp_str {#3} %% needed as put_right does not convert to string first
\IfBooleanTF{#1}{}{\str_put_right:cn { l__robExt_placeholder_#2_str } { ~ } }
\str_put_right:cV { l__robExt_placeholder_#2_str } \l_tmp_str
}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
}
}
\let\addToPlaceholderNoImport\robExtAddToPlaceholderNoImport
%% Add something to the right of the placeholder
%% By default it adds a space in between, unless we use the star version
\NewDocumentCommand{\robExtAddBeforePlaceholder}{smm}{
\str_if_exist:cTF { l__robExt_placeholder_#2_str } {
\robExt_set_hash_robust:Nn \l_tmp_str {#3} %% needed as put_right does not convert to string first
\IfBooleanTF{#1}{}{\str_put_left:cn { l__robExt_placeholder_#2_str } { ~ } }
\str_put_left:cV { l__robExt_placeholder_#2_str } \l_tmp_str
}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
\robExtAddPlaceholderToList{#2}
}
}
\let\addBeforePlaceholder\robExtAddBeforePlaceholder
\NewDocumentCommand{\robExtAddBeforePlaceholderNoImport}{smm}{
\str_if_exist:cTF { l__robExt_placeholder_#2_str } {
\robExt_set_hash_robust:Nn \l_tmp_str {#3} %% needed as put_right does not convert to string first
\IfBooleanTF{#1}{}{\str_put_left:cn { l__robExt_placeholder_#2_str } { ~ } }
\str_put_left:cV { l__robExt_placeholder_#2_str } \l_tmp_str
}{
\robExt_set_hash_robust:cn { l__robExt_placeholder_#2_str } {#3}
}
}
\let\addBeforePlaceholderNoImport\robExtAddBeforePlaceholderNoImport
\ExplSyntaxOff
% except inside setplaceholderfromcode, we want to modify by default the main content orig placeholder
\def\robExtCurrentPlaceholderName{__ROBEXT_MAIN_CONTENT_ORIG__}
\pgfqkeys{/robExt}{
defaultPlaceholderFromCodeStyle/.style={
remove leading spaces,
},
}
\ExplSyntaxOn
% Usage:
% \begin{placeholderFromCode}{HELPERFUNCTION}
% def my_helper_function(bla):
% return bla + 1
% \end{placeholderFromCode}
% HELPERFUNCTION will contain at the end "def ..."
% This environment cannot be placed inside any other macro/align/...
\NewDocumentEnvironment{RobExtPlaceholderFromCode}{sO{defaultPlaceholderFromCodeStyle}m}{%
\checkIfPlaceholderNameIsLegal{#3}%
% % debug part
% \str_set:Nn \l_test_str {#1}
% \show\l_test_str
%% Environments can't use verbatim yet: https://github.com/latex3/latex3/issues/591
% Might be related: https://tex.stackexchange.com/questions/633523/saving-the-body-of-an-environment-to-a-file-verbatim-using-xparse
%% Here is the first part:
%% https://tex.stackexchange.com/a/680259/116348 might work and be more efficient, but it might be less reliable
%% and definitely more complicated and error prone. Instead, we write to a file and read the result.
%% TODO: try to do it using verbatim, might be trivial or complicated, not sure, maybe see https://tex.stackexchange.com/questions/555359/reading-lines-verbatim-into-a-sequence-variable
\XSIMfilewritestart{\jobnameNoQuotes-robExt-tmp-file-you-can-remove.tmp}%
}{%
\XSIMfilewritestop%
\ior_open:Nn \g__robExt_read_ior {\jobnameNoQuotes-robExt-tmp-file-you-can-remove.tmp}%
%% Put the file in l__robExt_tmp_contain_file_str
\str_clear_new:N \l__robExt_tmp_str%
\ior_str_map_inline:Nn \g__robExt_read_ior {%
\str_gput_right:Nx \l__robExt_tmp_str {\tl_to_str:n{##1}^^J}%
}%
\str_set_eq:cN {l__robExt_placeholder_#3_str} \l__robExt_tmp_str%
%% We apply the style, useful for instance to remove indentation
\def\robExtCurrentPlaceholderName{#3}%
\pgfqkeys{/robExt}{#2}%
\IfBooleanTF {#1} {} {
\robExtAddPlaceholderToList{#3}
%% Otherwise they will be lost when the environment ends
\robExtKeepaftergroup{l__robExt_placeholder_group_main_seq}%
}%
%% for other variable
\robExtKeepaftergroup{l__robExt_placeholder_#3_str}%
}%
\let\PlaceholderFromCode\RobExtPlaceholderFromCode
\let\endPlaceholderFromCode\endRobExtPlaceholderFromCode
\let\SetPlaceholderCode\RobExtPlaceholderFromCode
\let\endSetPlaceholderCode\endRobExtPlaceholderFromCode
\NewDocumentCommand{\robExtKeepPlaceholderAfterGroup}{m}{