summaryrefslogtreecommitdiff
path: root/macros/latex/contrib/robust-externalize/robust-externalize.sty
blob: 3bf14a9f955dc9765b7617fd1af63bff107188bc (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
\ProvidesPackage{robust-externalize}[2.2 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 %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 

\ExplSyntaxOn
\NewDocumentCommand{\robExtIfWindowsTF}{mm}{%
  \sys_if_platform_windows:TF {#1}{#2}%
}
\ExplSyntaxOff

% Debug function: by default, do nothing
\def\robExtDebugMessage#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 \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 \cs_replacement_spec:N { c }
\cs_generate_variant:Nn \cs_argument_spec:N { c }

\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 }

%%%
%%% 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 ~ #3 ~ 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 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}{The ~ pdf ~ file ~ #1.pdf ~ is ~ not ~ present. ~ The ~ compilation ~ command ~ certainly ~ failed, ~ see ~ logs ~ above ~ or ~ in ~ #1.log.}
\msg_new:nnn {robExt}{missing compiled pdf parallel}{The ~ pdf ~ file ~ #1.pdf ~ is ~ not ~ present. ~ 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}{auto forward not in cachemecode}{Auto~forward~is~less~efficient~in~cacheMeCode.}

% 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.}

% 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 ~ \jobname-\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 ~ \jobname-\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:
%%% Note that we don't override the script if it exists on purpose (the user might have changed it to fits their needs)
\begin{filecontents}[noheader]{robExt-remove-old-figures.py}
#!/usr/bin/env python3
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}

\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 %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\def\robExtPrefixFilename{robExt-}

\NewExpandableDocumentCommand{\robExtAddCachePathAndName}{m}{%
  \ifdefined\robExtCacheFolder%
    \robExtCacheFolder%
  \fi\robExtPrefixFilename#1%
}

\NewExpandableDocumentCommand{\robExtAddCachePath}{m}{%
  \ifdefined\robExtCacheFolder%
    \robExtCacheFolder%
  \fi#1%
}

\NewDocumentCommand{\robExtCheckIfPrefixFolderExists}{}{
  % Check if the output directory exists
  \ifdefined\robExtCacheFolder
    \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 {mkdir ~ -p ~ \robExtCacheFolder}
        \fi
      \fi
    }{
      \message{If ~ you ~ get~ an~ error,~ make ~ sure ~ to ~ enable ~ pdflatex ~ -shell-escape ~ or ~ to ~ manually ~ CREATE ~ THE ~ FOLDER ~ \robExtCacheFolder.}
    }
  \fi
}


\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 {\jobname-\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 {\jobname-\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} { \par }
  \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} { \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

\NewDocumentCommand{\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}{smm}{
  \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


% 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}{sm}{%
  \checkIfPlaceholderNameIsLegal{#2}%
  % % 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{\jobname-robExt-tmp-file-you-can-remove.tmp}%
}{%
  \XSIMfilewritestop%
  \ior_open:Nn \g__robExt_read_ior {\jobname-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_#2_str} \l__robExt_tmp_str%
  \IfBooleanTF {#1} {} {
    \robExtAddPlaceholderToList{#2}
    %% Otherwise they will be lost when the environment ends
    \robExtKeepaftergroup{l__robExt_placeholder_group_main_seq}%
  }
  %% for other variable
  \robExtKeepaftergroup{l__robExt_placeholder_#2_str}%
}%
\let\PlaceholderFromCode\RobExtPlaceholderFromCode
\let\endPlaceholderFromCode\endRobExtPlaceholderFromCode
\let\SetPlaceholderCode\RobExtPlaceholderFromCode
\let\endSetPlaceholderCode\endRobExtPlaceholderFromCode

\NewDocumentCommand{\robExtKeepPlaceholderAfterGroup}{m}{
  \robExtKeepaftergroup{l__robExt_placeholder_#1_str}%
}
\let\keepPlaceholderAfterGroup\robExtKeepPlaceholderAfterGroup

%% Usage:
%% \placeholderPathFromFilename{MYLIBPATH}{mylib.py}
%% This will copy mylib.py in the cache, and set MYLIBPATH to the name of the file in the cache like
%% MYLIBPATH = robExt-abcmylib.py
%% Tested!
\NewDocumentCommand{\robExtPlaceholderPathFromFilename}{smm}{
  \ior_open:Nn \g__robExt_read_ior {#3}
  %% Put the file in l__robExt_tmp_contain_file_str
  \str_clear_new:N \l__robExt_tmp_contain_file_str
  \ior_str_map_inline:Nn \g__robExt_read_ior {
    \str_put_right:Nx \l__robExt_tmp_contain_file_str {\tl_to_str:n{##1}^^J}
  }
  %% computes the new filename based on the md5
  \str_set:Nx \l__robExt_tmp_filename_no_prefix_str {\robExt@pdfmdfivesum{\l__robExt_tmp_contain_file_str}#3}
  %% Writes the content to the file
  \robExtCheckIfPrefixFolderExists
  \iow_open:Nx \g__robExt_write_iow {\robExtAddCachePathAndName{\l__robExt_tmp_filename_no_prefix_str}}
  \iow_now:NV \g__robExt_write_iow \l__robExt_tmp_contain_file_str
  \iow_close:N \g__robExt_write_iow
  %% sets the template name to the relative path to the file
  \str_set:cx { l__robExt_placeholder_#2_str } {\robExtPrefixFilename\l__robExt_tmp_filename_no_prefix_str}
  \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\placeholderPathFromFilename\robExtPlaceholderPathFromFilename

%% Usage:
%% \placeholderFromFileContent{MYLIB}{mylib.py}
%% This will set MYLIB to the content of the file mylib.py
%% Tested!
\NewDocumentCommand{\robExtPlaceholderFromFileContent}{smm}{
  \checkIfPlaceholderNameIsLegal{#2}
  \ior_open:Nn \g__robExt_read_ior {#3}
  %% Put the file in l__robExt_tmp_contain_file_str
  \str_clear_new:N \l__robExt_tmp_contain_file_str
  \ior_str_map_inline:Nn \g__robExt_read_ior {
    \str_put_right:Nx \l__robExt_tmp_contain_file_str {\tl_to_str:n{##1}^^J}
  }
  %% sets the template name to the relative path to the file
  \str_set_eq:cN { l__robExt_placeholder_#2_str } \l__robExt_tmp_contain_file_str
  \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\placeholderFromFileContent\robExtPlaceholderFromFileContent


%% Usage:
%% \placeholderPathFromContent{MYLIBPATH}{some code}
%% This will copy "some code" in the cache, and set MYLIBPATH to the name of the file in the cache like
%% MYLIBPATH = robExt-abc.py
%% Tested!
\NewDocumentCommand{\robExtPlaceholderPathFromContent}{smO{.tex}m}{
  \robExt_set_hash_robust:Nn \l__robExt_tmp_contain_file_str {#4}
  %% computes the new filename based on the md5
  \str_set:Nx \l__robExt_tmp_filename_no_prefix_str {\robExt@pdfmdfivesum{\l__robExt_tmp_contain_file_str}#3}
  %% Writes the content to the file
  \robExtCheckIfPrefixFolderExists
  \iow_open:Nx \g__robExt_write_iow {\robExtAddCachePathAndName{\l__robExt_tmp_filename_no_prefix_str}}
  \iow_now:NV \g__robExt_write_iow \l__robExt_tmp_contain_file_str
  \iow_close:N \g__robExt_write_iow
  %% sets the template name to the relative path to the file
  \str_set:cx { l__robExt_placeholder_#2_str } {\robExtPrefixFilename\l__robExt_tmp_filename_no_prefix_str}
  \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
}
\let\placeholderPathFromContent\robExtPlaceholderPathFromContent


%% Usage:
%% \begin{PlaceholderPathFromCode}{mylibpath}
%% def blabla():
%% \end{PlaceholderPathFromCode}
%% This will copy "some code" in the cache, and set MYLIBPATH to the name of the file in the cache like
%% MYLIBPATH = robExt-abc.py
\NewDocumentEnvironment{RobExtPlaceholderPathFromCode}{sO{}m}{
  \XSIMfilewritestart*{\jobname-robExt-tmp-file-you-can-remove.tmp}
}{
  \XSIMfilewritestop
  \ior_open:Nn \g__robExt_read_ior {\jobname-robExt-tmp-file-you-can-remove.tmp}
  %% Put the file in \l__robExt_tmp_contain_file_str
  \str_clear_new:N \l__robExt_tmp_contain_file_str
  \ior_str_map_inline:Nn \g__robExt_read_ior {
    \str_gput_right:Nx \l__robExt_tmp_contain_file_str {\tl_to_str:n{##1}^^J}
  }
  %% computes the new filename based on the md5
  \str_set:Nx \l__robExt_tmp_filename_no_prefix_str {\robExt@pdfmdfivesum{\l__robExt_tmp_contain_file_str}#2}
  %% Writes the content to the file
  \robExtCheckIfPrefixFolderExists
  \iow_open:Nx \g__robExt_write_iow {\robExtAddCachePathAndName{\l__robExt_tmp_filename_no_prefix_str}}
  \iow_now:NV \g__robExt_write_iow \l__robExt_tmp_contain_file_str
  \iow_close:N \g__robExt_write_iow
  %% sets the template name to the relative path to the file
  \str_set:cx { l__robExt_placeholder_#3_str } {\robExtPrefixFilename\l__robExt_tmp_filename_no_prefix_str}
  \IfBooleanTF {#1} {} {
    \robExtAddPlaceholderToList{#3}
    \robExtKeepaftergroup{l__robExt_placeholder_group_main_seq}
  }
  %% Otherwise they will be lost when the environment ends
  \robExtKeepaftergroup{l__robExt_placeholder_#3_str}
}
\let\PlaceholderPathFromCode\RobExtPlaceholderPathFromCode
\let\endPlaceholderPathFromCode\endRobExtPlaceholderPathFromCode

% %%% Evaluate a string by replacing the placeholders until there is none left
% %%% the result will be in \robExtResult
\cs_set:Nn \__robExt_replace_until_impossible: {
  \robExtDebugMessage{We~needed~to~run~replace_until_impossible}
  % Try to replace directly if single placeholder
  \str_if_exist:cTF { l__robExt_placeholder_ \l_robExt_result_str _str }{
    \str_set_eq:Nc {\l_robExt_result_str}{ l__robExt_placeholder_ \l_robExt_result_str _str }
    \str_set:Nn \l_robext_tmp_before {}
  } {
    \str_set_eq:NN \l_robext_tmp_before \l_robExt_result_str
    \seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {
      \robExtDebugMessage{Trying ~ to ~ replace ##1^^J}
      \str_if_exist:cTF { l__robExt_placeholder_##1_str } {
        \str_replace_all:Nnv \l_robExt_result_str { ##1 } { l__robExt_placeholder_##1_str }
      }{
        \robExtDebugWarning{WARNING: ~ the ~ placeholder ~ ##1 ~ does ~ not ~ exist.}
      }    
    }
  }
  % In quick mode, we first try to check if the string contains __ since by default all placeholders start with __
  % If not, no need to do one more run
  \cs_if_exist:NTF {\robExtPlaceholderOnlyWithUnderscores} {
    \str_if_in:NnTF { \l_robExt_result_str } { __ } {
      \str_compare:eNeTF \l_robext_tmp_before = \l_robExt_result_str {
        % We converged
      }{
        % The strings are different: we restart
        %\message{The strings are different, we restart: It ~ used ~ to ~ be ~\l_robext_tmp_before^^J^^J now it is^^J^^J \l_robExt_result_str}
        \__robExt_replace_until_impossible:
      }
    }{
      % We found no __ so we stop before even if a change was made
    }
  }{
    % We compare the result
    \str_compare:eNeTF \l_robext_tmp_before = \l_robExt_result_str {
      % \str_set_eq:cN { l__robExt_placeholder_#1_str } \l_robExt_result_str
      % \robExtAddPlaceholderToList{#1}
    }{
      % The strings are different: we restart
      \__robExt_replace_until_impossible:
    }
  }
}

\NewDocumentCommand{\robExtGetPlaceholderInResult}{sO{}m}{
  \robExt_set_hash_robust:Nn \l_robExt_result_str { #3 }
  \robExtDebugMessage{Begin~to~evaluate~placeholder^^J~\l_robExt_result_str}
  \__robExt_replace_until_impossible:
  \robExtDebugMessage{Ended~the~replacement^^J~\l_robExt_result_str}
  \tl_if_blank:nTF {#2} {} {
    % To avoid infinite recursion later and allow concatenation to a placeholder that does not exists
    % we remove the name of the placeholder at the end
    \str_remove_all:Nn \l_robExt_result_str { #2 }
    \str_set_eq:cN { l__robExt_placeholder_#2_str } \l_robExt_result_str
    \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
  }
}
\let\getPlaceholderInResult\robExtGetPlaceholderInResult

%% like robExtGetPlaceholderInResult put assumes that there is a single placeholder name.
%% It is used mainly for efficiency as it avoids a loop on all placeholder.
\NewDocumentCommand{\robExtGetPlaceholderInResultFromSinglePlaceholder}{sO{}m}{
  \cs_if_exist:cTF { l__robExt_placeholder_#3_str }{
    \str_set_eq:Nc { \l_robExt_result_str }{ l__robExt_placeholder_#3_str }
  }{
    \msg_error:nn{robExt}{placeholder not existing}
  }
  \robExtDebugMessage{Starting~to~replace~placeholder~#3~to~get~\l_robExt_result_str}
  \__robExt_replace_until_impossible:
  \robExtDebugMessage{Ended~up~with~\l_robExt_result_str}
  \tl_if_blank:nTF {#2} {} {
    % To avoid infinite recursion later and allow concatenation to a placeholder that does not exists
    % we remove the name of the placeholder at the end
    \str_remove_all:Nn \l_robExt_result_str { #2 }
    \str_set_eq:cN { l__robExt_placeholder_#2_str } \l_robExt_result_str
    \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#2}}
  }
}

\cs_set:Nn \__replace_from_list:N {
  \str_set_eq:NN \l_robext_tmp_before \l_robExt_result_str
  \clist_map_inline:Nn {#1} {
    \str_if_exist:cTF { l__robExt_placeholder_##1_str }{
      \str_replace_all:Nnv \l_robExt_result_str { ##1 } { l__robExt_placeholder_##1_str }
    } { }
  }
  % We compare the result
  \str_compare:eNeTF \l_robext_tmp_before = \l_robExt_result_str {
    % \str_set_eq:cN { l__robExt_placeholder_#1_str } \l_robExt_result_str
    % \robExtAddPlaceholderToList{#1}
  }{
    % The strings are different: we restart
    \__replace_from_list:N { #1 }
  }
}

\NewDocumentCommand{\robExtGetPlaceholderInResultReplaceFromList}{smO{}m}{
  \robExt_set_hash_robust:Nn \l_robExt_result_str { #4 }
  \clist_set:Nn \l__robExt_list_placeholder_replace_clist {#2}
  \__replace_from_list:N \l__robExt_list_placeholder_replace_clist
  \tl_if_blank:nTF {#3} {} {
    \str_remove_all:Nn \l_robExt_result_str { #3 }
    \str_set_eq:cN { l__robExt_placeholder_#3_str } \l_robExt_result_str
    \IfBooleanTF {#1} {} {\robExtAddPlaceholderToList{#3}}
  }
}
\let\getPlaceholderInResultReplaceFromList\robExtGetPlaceholderInResultReplaceFromList


% Otherwise we need latex3 
\def\robExtResult{\l_robExt_result_str}

%%%% Same version, but replaces only one (useful sometimes)
\cs_set:Nn \__replace_n_times:n {
  \str_set_eq:NN \l_robext_tmp_before \l_robExt_result_str
  \seq_map_inline:Nn \l__robExt_placeholder_group_main_seq {
    \str_replace_all:Nnv \l_robExt_result_str { ##1 } { l__robExt_placeholder_##1_str }
  }
  \int_compare:nTF { #1 > 1}{
    \__replace_n_times:n {\int_eval:n {#1-1}}
  }{}
}


\NewDocumentCommand{\robExtSetPlaceholderRec}{smm}{
  \IfBooleanTF {#1} {
    \robExtGetPlaceholderInResult*[#2]{#3}
  } {
    \robExtGetPlaceholderInResult[#2]{#3}
  }
}
\let\setPlaceholderRec\robExtSetPlaceholderRec

\NewDocumentCommand{\robExtSetPlaceholderRecReplaceFromList}{smmm}{
  \IfBooleanTF {#1} {
    \robExtGetPlaceholderInResultReplaceFromList*{#2}[#3]{#4}
  }{
    \robExtGetPlaceholderInResultReplaceFromList{#2}[#3]{#4}
  }
}
\let\setPlaceholderRecReplaceFromList\robExtSetPlaceholderRecReplaceFromList


\NewDocumentCommand{\robExtGetPlaceholder}{O{}m}{
  \robExtGetPlaceholderInResult[#1]{#2}
  \l_robExt_result_str
}
\let\getPlaceholder\robExtGetPlaceholder

%%% Evaluate a string by replacing the placeholders until there is none left
%%% the result will be in \robExtResult
\NewDocumentCommand{\robExtEvalPlaceholder}{m}{
  \robExt_set_hash_robust:Nn \l_test_str {#1}
  \robExtGetPlaceholderInResult{#1}
  \tl_rescan:nv {} { l_robExt_result_str }
}
\let\evalPlaceholder\robExtEvalPlaceholder

%%% Evaluate a string by replacing the placeholders until there is none left
%%% the result will be in \robExtResult
\NewDocumentCommand{\robExtEvalPlaceholderReplaceFromList}{mm}{
  \robExt_set_hash_robust:Nn \l_test_str {#2}
  \robExtGetPlaceholderInResultReplaceFromList{#1}{#2}
  \tl_rescan:nv {} { l_robExt_result_str }
}
\let\evalPlaceholderReplaceFromList\robExtEvalPlaceholderReplaceFromList

%%% Evaluate a placeholder by first trying some strings, then checking if a template is still present (if the
%%% mode is enabled), and then it continues normally. Mostly for performance reasons.
\NewDocumentCommand{\robExtEvalPlaceholderStartFromList}{mm}{
  \robExt_set_hash_robust:Nn \l_test_str {#2}
  \robExtGetPlaceholderInResultReplaceFromList{#1}{#2}
  \cs_if_exist:NTF {\robExtPlaceholderOnlyWithUnderscores} {
    %% there might be non-important placeholders that are replaced later:
    \str_set_eq:NN \l__robExt_result_minus_str \l_robExt_result_str
    \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_OUTPUT_PREFIX__}
    \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_SOURCE_FILE__}
    \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_OUTPUT_PDF__}
    \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_WAY_BACK__}
    \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_CACHE_FOLDER__}
    \str_if_in:NnTF { \l__robExt_result_minus_str } { __ } {
      \__robExt_replace_until_impossible:
    }{
    }
  }{ \__robExt_replace_until_impossible: }
  \tl_rescan:nv {} { l_robExt_result_str }
}
\let\evalPlaceholderStartFromList\robExtEvalPlaceholderStartFromList


\NewDocumentCommand{\robExtEvalPlaceholderInplace}{m}{
  \robExtGetPlaceholderInResult{#1}
  \tl_set_rescan:Nnx \l__robExt_tmp_tl  {} { \l_robExt_result_str }
  \robExt_set_hash_robust:cx { l__robExt_placeholder_#1_str } { \l__robExt_tmp_tl }
}
\let\evalPlaceholderInplace\robExtEvalPlaceholderInplace

\NewDocumentCommand{\robExtEvalPlaceholderInplaceFromSinglePlaceholder}{m}{
  \robExtGetPlaceholderInResultFromSinglePlaceholder{#1}
  \tl_set_rescan:Nnx \l__robExt_tmp_tl  {} { \l_robExt_result_str }
  \robExt_set_hash_robust:cx { l__robExt_placeholder_#1_str } { \l__robExt_tmp_tl }
}
\let\evalPlaceholderInplaceFromSinglePlaceholder\robExtEvalPlaceholderInplaceFromSinglePlaceholder


% Sometimes two symbols ## (with a different catcode than a normal hash) are added instead of a single #
\NewDocumentCommand{\robExtPlaceholderDoubleNumberHashesInplace}{m}{
  \str_replace_all:cxx { l__robExt_placeholder_#1_str } { \c_hash_str } { \c_hash_str \c_hash_str }
}
\let\placeholderDoubleNumberHashesInplace\robExtPlaceholderDoubleNumberHashesInplace

\NewDocumentCommand{\robExtPlaceholderHalveNumberHashesInplace}{m}{
  \str_replace_all:cxx { l__robExt_placeholder_#1_str } { \c_hash_str \c_hash_str } { \c_hash_str }
}
\let\placeholderHalveNumberHashesInplace\robExtPlaceholderHalveNumberHashesInplace

\NewDocumentCommand{\robExtPlaceholderReplaceInplace}{mmm}{
  \str_replace_all:cnn { l__robExt_placeholder_#1_str } { #2 } { #3 }
}
\let\placeholderReplaceInplace\robExtPlaceholderReplaceInplace

\NewDocumentCommand{\robExtPlaceholderReplaceInplaceEval}{mmm}{
  \str_replace_all:cxx { l__robExt_placeholder_#1_str } { #2 } { #3 }
}
\let\placeholderReplaceInplaceEval\robExtPlaceholderReplaceInplaceEval

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Placeholders groups %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% I used to put all placeholders into the same group, but it was quite inefficient (latex is really slow)
% Then I tried to hide this group but keep a single list of all items, but still automatically add items to it:
% also quite slow, and the list was not so useful anyway.
% In practice, however, we do not need to put the placeholders created by default in a group: we can just store them
% in a standalone way, and load them when needed. So now I create the concept of group: people can add placeholders
% to a group of placeholders to load them later if needed (e.g. to list all placeholders created by this library).
% The group named "main" will be the main one with imported groups, where stuff like "set placeholder rec" will search for the
% existing placeholders.
% The group named "preexisting" will contain the placeholders created by this library (useful mostly for
% debugging purpose).

\NewDocumentCommand{\robExtAddPlaceholdersToGroup}{mm}{
  % Make sure we have a string here:
  \robExt_set_hash_robust:Nn \l__robExt_tmp_str { #2 }
  \seq_set_from_clist:NN \l__robExt_tmp_seq \l__robExt_tmp_str
  \cs_if_exist:cTF {l__robExt_placeholder_group_#1_seq}{}{ \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}}
  % 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__robExt_tmp_seq {
    \message{Adding ##1 to #1}
    \seq_remove_all:cn {l__robExt_placeholder_group_#1_seq}  {##1}
    \seq_put_right:cn {l__robExt_placeholder_group_#1_seq} {##1}
  }
}
\let\addPlaceholdersToGroup\robExtAddPlaceholdersToGroup

\NewDocumentCommand{\robExtEnsureGroupPlaceholdersExists}{m}{
  \cs_if_exist:cTF {l__robExt_placeholder_group_#1_seq}{}{ \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}}
}
\let\ensureGroupPlaceholdersExists\robExtEnsureGroupPlaceholdersExists

\NewDocumentCommand{\robExtAddPlaceholdersToGroupBefore}{mm}{
  % Make sure we have a string here:
  \robExt_set_hash_robust:Nn \l__robExt_tmp_str { #2 }
  \seq_set_from_clist:NN \l__robExt_tmp_seq \l__robExt_tmp_str
  \seq_reverse:N \l__robExt_tmp_seq
  \cs_if_exist:cTF {l__robExt_placeholder_group_#1_seq}{}{ \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}}
  % 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__robExt_tmp_seq {
    \seq_remove_all:cn {l__robExt_placeholder_group_#1_seq}  {##1}
    \seq_put_left:cn {l__robExt_placeholder_group_#1_seq} {##1}
  }
}
\let\addPlaceholdersToGroupBefore\robExtAddPlaceholdersToGroupBefore

\NewDocumentCommand{\robExtRemovePlaceholdersFromGroup}{mm}{
  % Make sure we have a string here:
  \robExt_set_hash_robust:Nn \l__robExt_tmp_str { #2 }
  \seq_set_from_clist:NN \l__robExt_tmp_seq \l__robExt_tmp_str
  \seq_reverse:N \l__robExt_tmp_seq
  \cs_if_exist:cTF {l__robExt_placeholder_group_#1_seq}{}{ \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}}
  % 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__robExt_tmp_seq {
    \seq_remove_all:cn {l__robExt_placeholder_group_#1_seq}  {##1}
  }
}
\let\removePlaceholdersFromGroup\robExtRemovePlaceholdersFromGroup
\let\removePlaceholderFromGroup\robExtRemovePlaceholdersFromGroup

\NewDocumentCommand{\robExtClearGroupPlaceholders}{m}{
  \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}
}
\let\clearGroupPlaceholders\robExtClearGroupPlaceholders

\NewDocumentCommand{\robExtCopyGroupPlaceholders}{mm}{
  \seq_set_eq:cc {l__robExt_placeholder_group_#1_seq} {l__robExt_placeholder_group_#2_seq}
}
\let\copyGroupPlaceholders\robExtCopyGroupPlaceholders

\NewDocumentCommand{\robExtAppendGroupPlaceholders}{mm}{
  \seq_map_inline:cn {l__robExt_placeholder_group_#2_seq} {
    \seq_remove_all:cn {l__robExt_placeholder_group_#1_seq}  {##1}
    \seq_put_right:cn {l__robExt_placeholder_group_#1_seq} {##1}
  } 
}
\let\appendGroupPlaceholders\robExtAppendGroupPlaceholders

\NewDocumentCommand{\robExtAppendBeforeGroupPlaceholders}{mm}{
  \seq_eq:Nc \l__robExt_tmp_seq {l__robExt_placeholder_group_#2_seq}
  \seq_reverse:N \l__robExt_tmp_seq
  \seq_map_inline:Nn \l__robExt_tmp_seq {
    \seq_remove_all:cn {l__robExt_placeholder_group_#1_seq}  {##1}
    \seq_put_left:cn {l__robExt_placeholder_group_#1_seq} {##1}
  }
}
\let\appendBeforeGroupPlaceholders\robExtAppendBeforeGroupPlaceholders

\NewDocumentCommand{\robExtImportPlaceholdersFromGroup}{m}{
  \robExtAppendGroupPlaceholders{main}{#1}
}
\let\importPlaceholdersFromGroup\robExtImportPlaceholdersFromGroup

\NewDocumentCommand{\robExtImportAllPlaceholders}{}{
  \seq_map_inline:Nn \l__robExt_list_groups_seq {
    \robExtImportPlaceholdersFromGroup{##1}
  }
}
\let\importAllPlaceholders\robExtImportAllPlaceholders
%%%%
%%%% List groups, mostly for debugging purpose
%%%%

\seq_new:N \l__robExt_list_groups_seq % contains the list of all groups

\NewDocumentCommand{\robExtRegisterGroupPlaceholders}{m}{
  \seq_if_exist:cTF {l__robExt_placeholder_group_#1_seq}{}{
    \seq_clear_new:c {l__robExt_placeholder_group_#1_seq}
  }
  \seq_put_right:Nn \l__robExt_list_groups_seq {#1}
}
\let\registerGroupPlaceholders\robExtRegisterGroupPlaceholders
\let\newGroupPlaceholders\robExtRegisterGroupPlaceholders

\NewDocumentCommand{\robExtShowAllRegisteredGroupsAndPlaceholders}{s}{%
  \seq_map_inline:Nn \l__robExt_list_groups_seq {%
    \message{^^J- Group ##1: ^^J}%
    \seq_map_inline:cn {l__robExt_placeholder_group_##1_seq} {%
      \message{, ####1 }%
      \IfBooleanTF{#1}{
        \message{Content:\use:c{l__robExt_placeholder_####1_str}}
      }{}
    }%
    \message{^^J}
  }
  \show\def
}
\let\showAllRegisteredGroupsAndPlaceholders\robExtShowAllRegisteredGroupsAndPlaceholders

\NewDocumentCommand{\robExtPrintAllRegisteredGroups}{s}{%
  \seq_map_inline:Nn \l__robExt_list_groups_seq {%
    \texttt{##1}\par
  }
}
\let\printAllRegisteredGroups\robExtPrintAllRegisteredGroups

\NewDocumentCommand{\robExtPrintAllRegisteredGroupsAndPlaceholders}{s}{%
  \seq_map_inline:Nn \l__robExt_list_groups_seq {%
    - ~ Group \texttt{##1}:\par
    \seq_map_inline:cn {l__robExt_placeholder_group_##1_seq} {%
      Placeholder \texttt{####1}%
      \IfBooleanTF {#1}{\robExtPrintPlaceholderNoReplacement{####1}}{\par}
    }%
  }
}
\let\printAllRegisteredGroupsAndPlaceholders\robExtPrintAllRegisteredGroupsAndPlaceholders


% The star version displays the content as well
\NewDocumentCommand{\robExtPrintGroupPlaceholders}{sm}{%
  Content~ of~ group~ \texttt{#2}:\par%
  \seq_map_inline:cn {l__robExt_placeholder_group_#2_seq} {%
    -~Placeholder ~ \texttt{##1}\par \IfBooleanTF {#1}{\robExtPrintPlaceholderNoReplacement{##1}}{}
  }%
}
\let\printGroupPlaceholders\robExtPrintGroupPlaceholders


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Dependencies %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\NewDocumentCommand{\robExtResetDependencies}{m}{
  \seq_clear:N \l__robExt_dependencies_str
}

\NewDocumentCommand{\robExtAddDependency}{m}{
  \seq_put_left:Nx \l__robExt_dependencies_str {#1}
}

\NewDocumentCommand{\robExtDebugDependency}{}{
  \show\l__robExt_dependencies_str
}

% Useful when compiling commands
\NewDocumentCommand{\robExtSaveDependencies}{m}{
  \seq_gset_eq:cN {#1} \l__robExt_dependencies_str
}
\NewDocumentCommand{\robExtRestoreDependencies}{m}{
  \seq_set_eq:Nc \l__robExt_dependencies_str {#1}
}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Externalization %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% The idea is to populate a placeholder called __ROBEXT_TEMPLATE__ that will contain the file to generate
%% together with a placeholder called __ROBEXT_COMPILATION_COMMAND__ that will contain the command to compile the file

\NewDocumentCommand{\robExtSetCompilationCommand}{m}{
  \robExtSetPlaceholderFirst{__ROBEXT_COMPILATION_COMMAND__} {#1}
}

\NewDocumentCommand{\robExtAddArgumentToCompilationCommand}{m}{
  \robExtSetPlaceholderRec{__ROBEXT_COMPILATION_COMMAND__} {__ROBEXT_COMPILATION_COMMAND__ ~ "#1"}
}


%% Alias of robExtFinalFile to \robExtSourceFile, as I don't like anymore the name I chose
%\def\robExtSourceFile{\robExtFinalFile}

% First is name of sequence for only try (we only replace those and stop), second is name of sequence for first try (we first try with the sequence and
% then do a more normal thing), third is the name of the placeholder
\cs_set:Nn \try_to_evaluate_single_placeholder_without_going_to_replace_until_impossible:NNn {
  %%%%% Take care of the compilation command: might seem a bit weird and convoluted, but this is needed to get really good efficiency
  %%%%% since \__robExt_replace_until_impossible: is quite costly, we try to avoid it
  \cs_if_exist:NTF {#1} { % We only replace fixed state of placeholders
    \str_set_eq:Nc \l_robExt_result_str {l__robExt_placeholder_#3_str}
    \seq_map_inline:Nn {#1} {
      \robExtDebugMessage{replacing~##1~in~\l_robExt_result_str}
      \str_replace_all:Nnv \l_robExt_result_str {##1} {l__robExt_placeholder_##1_str}
    }
    \robExtDebugMessage{Cool,~we~avoided~the~costly~replace~(only~try).}
  }{
    \cs_if_exist:NTF {#2} { % We start by replacing a fixed state of placeholders
      \str_set_eq:Nc \l_robExt_result_str {l__robExt_placeholder_#3_str}
      \robExtDebugMessage{We~start~by~replacing~a~fixed~state~of~placeholders}
      \seq_map_inline:Nn {#2} {
        \str_if_exist:cTF {l__robExt_placeholder_##1_str} {
          \robExtDebugMessage{Replacing~##1~into~\use:c{l__robExt_placeholder_##1_str}}%
          \str_replace_all:Nnv \l_robExt_result_str {##1} {l__robExt_placeholder_##1_str}
        } {
          \robExtDebugMessage{Warning: ~ trying~to~replace~##1~that~does~not~exist.}
        }
      }
      %\show\l_robExt_result_str
      %% Check if there is some more stuff to replace (possible only if we consider only templates with underscores
      \cs_if_exist:NTF {\robExtPlaceholderOnlyWithUnderscores} {
        % all templates have underscores
        % first check if some non-important elements are here: for this we first remove them
        \str_set_eq:NN \l__robExt_result_minus_str \l_robExt_result_str
        \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_OUTPUT_PREFIX__}
        \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_SOURCE_FILE__}
        \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_OUTPUT_PDF__}
        \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_WAY_BACK__}
        \str_remove_all:Nn \l__robExt_result_minus_str {__ROBEXT_CACHE_FOLDER__}
        % Now, we check if some __ are left:
        \str_if_in:NnTF { \l__robExt_result_minus_str } { __ } {
          % Some templates are left
          \robExtDebugMessage{Still~some~templates~are~left.}
          \__robExt_replace_until_impossible:
        } {
          % No more template: the end
          \robExtDebugMessage{Cool,~we~avoided~the~costly~replace: \l_robExt_result_str.}
        }
      }{
        % no way to know, must do it anyway
        \robExtDebugMessage{Seems~like~not~all~templates~contain~underscore.~Too~bad,~it~will~be~slower}
        \__robExt_replace_until_impossible:
      }
    }{
      \robExtDebugMessage{No~advice~on~how~to~start:~doing~it~the~long~way}
      \robExtGetPlaceholderInResultFromSinglePlaceholder{#3}
    }
  }
}

\NewDocumentCommand{\robExtOnlyPlaceholdersInCompilationCommand}{m}{
  \seq_set_from_clist:Nn \robExtOnlyTryThisSequenceOnCompilationCommand {#1}
}
\let\onlyPlaceholdersInCompilationCommand\robExtOnlyPlaceholdersInCompilationCommand

\NewDocumentCommand{\robExtFirstPlaceholdersInCompilationCommand}{m}{
  \seq_set_from_clist:Nn \robExtFirstTryThisSequenceOnCompilationCommand {#1}
}
\let\firstPlaceholdersInCompilationCommand\robExtFirstPlaceholdersInCompilationCommand

\NewDocumentCommand{\robExtOnlyPlaceholdersInTemplate}{m}{
  \seq_set_from_clist:Nn \robExtOnlyTryThisSequenceOnTemplate {#1}
}
\let\onlyPlaceholdersInTemplate\robExtOnlyPlaceholdersInTemplate

\NewDocumentCommand{\robExtFirstPlaceholdersInTemplate}{m}{
  \seq_set_from_clist:Nn \robExtFirstTryThisSequenceOnTemplate {#1}
}
\let\firstPlaceholdersInTemplate\robExtFirstPlaceholdersInTemplate

% for use outside of expl3 (pgf)
\def\robExtCurrentCompilationCommand{\l__robExt_current_compilation_command_str}
\NewDocumentCommand{\robExtGetNearlyFinalValueTemplateAndCompilationCommand}{}{
  %% oututs the compilation in \l__robExt_current_compilation_command_str and the template in \l_robExt_result_str
  %% This is for efficiency reasons: we only allow a few placeholders:
  %% In compilation command:
  %% 
  %% In template:
  %% - __ROBEXT_MAIN_CONTENT__
  %% - __ROBEXT_MAIN_CONTENT_ORIG__
  %% - __ROBEXT_LATEX_PREAMBLE__
  %% - __ROBEXT_OUTPUT_PREFIX__
  %% - __ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__
  %% - __ROBEXT_LATEX_CREATE_OUT_FILE__
  %% Others
  %% - __ROBEXT_SOURCE_FILE__
  %% - __ROBEXT_OUTPUT_PDF__
  %% - __ROBEXT_WAY_BACK__
  %% - __ROBEXT_CACHE_FOLDER__
  \ifdefined\robExtDisablePlaceholders%
    \robExtDebugMessage{You~have~disabled~placeholders~(this~is~likely~a~compiled~template)}%
    \str_set_eq:NN \l__robExt_current_compilation_command_str \l__robExt_placeholder___ROBEXT_COMPILATION_COMMAND___str 
    \str_set_eq:NN \l_robExt_result_str \l__robExt_placeholder___ROBEXT_TEMPLATE___str%
    \str_replace_all:Nnv \l_robExt_result_str {__ROBEXT_MAIN_CONTENT__} {l__robExt_placeholder___ROBEXT_MAIN_CONTENT___str}
    \str_replace_all:Nnv \l_robExt_result_str {__ROBEXT_LATEX_PREAMBLE__} {l__robExt_placeholder___ROBEXT_LATEX_PREAMBLE___str}
    \str_replace_all:Nnv \l_robExt_result_str {__ROBEXT_MAIN_CONTENT_ORIG__} {l__robExt_placeholder___ROBEXT_MAIN_CONTENT_ORIG___str}
  \else
    \ifdefined\robExtEnableImportMechanism\else\robExtImportAllPlaceholders\fi%
    %%%%% Take care of the compilation command: might seem a bit weird and convoluted, but this is needed to get really good efficiency
    %%%%% since \__robExt_replace_until_impossible: is quite costly, we try to avoid it
    \try_to_evaluate_single_placeholder_without_going_to_replace_until_impossible:NNn \robExtOnlyTryThisSequenceOnCompilationCommand \robExtFirstTryThisSequenceOnCompilationCommand {__ROBEXT_COMPILATION_COMMAND__}
    \str_set_eq:NN \l__robExt_current_compilation_command_str \l_robExt_result_str
    %%%%% Take care of 
    \try_to_evaluate_single_placeholder_without_going_to_replace_until_impossible:NNn \robExtOnlyTryThisSequenceOnTemplate \robExtFirstTryThisSequenceOnTemplate {__ROBEXT_TEMPLATE__}
  \fi
}

\NewDocumentCommand{\robExtSetBackCompilationCommandAndTemplate}{}{
  \robExtPlaceholderFromString{__ROBEXT_COMPILATION_COMMAND__}{\l__robExt_current_compilation_command_str}%
  \robExtPlaceholderFromString{__ROBEXT_TEMPLATE__}{\l_robExt_result_str}%
}

\NewDocumentCommand{\robExtWriteFile}{m}{
  %%% First we get all dependencies stored in \l__robExt_dependencies_str to create a csv-like file:
  \str_clear:N \l__robExt_dependencies_mdfive_str
  \robExtGetNearlyFinalValueTemplateAndCompilationCommand
  % We first add on the first line the compilation command, and on the second line the template file.
  \str_set:Nx \l__robExt_dependencies_mdfive_str {command,\l__robExt_current_compilation_command_str^^J\robExt@pdfmdfivesum{\l_robExt_result_str ^^J},^^J} %% ^^J is a newline: LaTeX will automatically add a new line when writing the file
  \seq_map_inline:Nn \l__robExt_dependencies_str {
    \str_put_right:Nx \l__robExt_dependencies_mdfive_str {\file_mdfive_hash:n{##1},##1^^J} %% ^^J is a newline
  }
  %%
  %% Compute the final hash (the hash of all dependencies, including the current picture that is on the first line):
  %% The last newline is needed as the write operation automatically adds a newline.
  \tl_set:Nx \robExtFinalHash {\robExt@pdfmdfivesum{\l__robExt_dependencies_mdfive_str^^J}}
  % Might be useful to clean the previously compiled files, or change the MD5 sum, for instance if we do
  % not want to recompile when the file changes
  \robExtUseHookJustBeforeWritingFiles%
  %% We add the figure in the list of files.
  \iow_now:Nx \g__robExt_write_list_all_figures_iow {\robExtAddPrefixName{\robExtFinalHash.tex}}
  %% We can now set the placeholders, and recompute the final value of the file:
  %% I was doing before \robExtPlaceholderFromContent + \robExtEvalPlaceholderInplace, but it is too slow
  \str_set:Nx \l_tmp_output_prefix_str {\robExtAddPrefixName{\robExtFinalHash}}
  %%% No need to re-evaluate from scratch the string, 
  \str_replace_all:Nnx \l_robExt_result_str {__ROBEXT_OUTPUT_PREFIX__}{\l_tmp_output_prefix_str}
  \str_replace_all:Nnx \l_robExt_result_str {__ROBEXT_SOURCE_FILE__}{\l_tmp_output_prefix_str .tex}
  \str_replace_all:Nnx \l_robExt_result_str {__ROBEXT_OUTPUT_PDF__}{\l_tmp_output_prefix_str .pdf}
  \str_replace_all:Nnx \l_robExt_result_str {__ROBEXT_WAY_BACK__}{\robExtCacheFolderWayBack}
  \str_replace_all:Nnx \l_robExt_result_str {__ROBEXT_CACHE_FOLDER__}{\robExtCacheFolder}
  \file_if_exist:xTF{\robExtAddCachePathAndName{\robExtFinalHash.tex}}{
    \message{The\space file\space \robExtAddCachePathAndName{\robExtFinalHash.tex} \space already\space exists.^^J}
  }{
    \str_if_eq:VnTF { \l_robExt_result_str }{__ROBEXT_TEMPLATE__} {
      \msg_error:nn{robExt}{forgot template}
    }{
      % Check if the output directory exists
      \robExtCheckIfPrefixFolderExists
      \iow_open:Nx \g__robExt_write_iow {\robExtAddCachePathAndName{\robExtFinalHash.deps}}
      \iow_now:NV \g__robExt_write_iow \l__robExt_dependencies_mdfive_str
      \iow_close:N \g__robExt_write_iow
      %% Save the final file:
      \iow_open:Nx \g__robExt_write_iow {\robExtAddCachePathAndName{\robExtFinalHash.tex}}
      \iow_now:NV \g__robExt_write_iow \l_robExt_result_str
      \iow_close:N \g__robExt_write_iow
      \message{Source ~ saved ~ in ~ \robExtAddCachePathAndName{\robExtFinalHash.tex}.}
    }
  }
}

% https://tex.stackexchange.com/questions/133324/shell-escape-with-latex-3
% We need shell escape to work (but it's enabled by default on overleaf!)
% Think about the number of compilations.
\NewDocumentCommand{\robExtCompileFile}{m}{
  \file_if_exist:xTF{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}{
    \cs_if_exist:NTF {\robExtForceRecompilation}{
      % We cannot do an OR with file_if_exist since it is not expandable, hence this trick
      \let\l__robExt_do_not_compile\undefined
    }{
      \def\l__robExt_do_not_compile{}
    }
  }{
    \let\l__robExt_do_not_compile\undefined
  }
  \cs_if_exist:NTF {\l__robExt_do_not_compile}{
    \message{No ~ need ~ to ~ recompile ~ \robExtAddCachePathAndName{\robExtFinalHash.pdf}^^J}
  }{
    % Used to know later if we have run a compilation command at that step or not
    \cs_undefine:N \l__robExt_I_just_ran_a_compilation_command:
    % No need to re-evaluate it
    % \robExtGetPlaceholderInResultFromSinglePlaceholder{__ROBEXT_COMPILATION_COMMAND__}
    \str_replace_all:Nnx \l__robExt_current_compilation_command_str {__ROBEXT_OUTPUT_PREFIX__}{\l_tmp_output_prefix_str}
    \str_replace_all:Nnx \l__robExt_current_compilation_command_str {__ROBEXT_SOURCE_FILE__}{\l_tmp_output_prefix_str .tex}
    \str_replace_all:Nnx \l__robExt_current_compilation_command_str {__ROBEXT_OUTPUT_PDF__}{\l_tmp_output_prefix_str .pdf}
    \str_replace_all:Nnx \l__robExt_current_compilation_command_str {__ROBEXT_WAY_BACK__}{\robExtCacheFolderWayBack}
    \str_replace_all:Nnx \l__robExt_current_compilation_command_str {__ROBEXT_CACHE_FOLDER__}{\robExtCacheFolder}
    % Make sure this command is run from the cache folder
    \ifdefined\robExtCacheFolder
      \str_put_left:Nx \l__robExt_current_compilation_command_str {cd ~ \robExtCacheFolder \space && ~ }
    \fi%
    %%% We enable manual mode if we enabled "compile in parallel after=N" and we compiled more than N elements
    % Check if we want to run stuff in parallel
    \ifdefined\robExt@compile@parallel@after
      % TODO: ****
      \int_gset:Nn \g__robExt_number_figures_just_compiled_or_to_compile {\g__robExt_number_figures_just_compiled_or_to_compile + 1}
      % We check if the number of figures that we already compiled is large enough to start parallel compilation
      \int_compare:nNnTF {
        \g__robExt_number_figures_just_compiled_or_to_compile} > {\robExt@compile@parallel@after
      } {
        \def\robExtManualMode
      } {}
    \fi
    \ifdefined\robExtManualMode
      \message{[robExt] Manual mode enabled: please, manually compile the images using \l__robExt_current_compilation_command_str or run 'bash \jobname-\robExtAddPrefixName{compile-missing-figures.sh}'.}
      % Avoid writing the same command multiple times (might occur in environments that execute the
      % same command multiple times like align etc)
      \cs_if_exist:cTF {l__robExt_missing_figure_\l__robExt_current_compilation_command_str :}{}{
        \iow_now:Nx \g__robExt_write_manually_compile_all_missing_figures_iow {\l__robExt_current_compilation_command_str}% a new line is automatically added
        \cs_gset:cn {l__robExt_missing_figure_\l__robExt_current_compilation_command_str :} {}
        \ifdefined\robExt@compile@parallel@after
          \gdef\robExt@compile@parallel@must@compile{}
          \seq_gput_right:Nx \g__robExt_files_compiled_in_parallel {\robExtAddCachePathAndName{\robExtFinalHash}}
          % Gets the line with the error for easier debugging
          \cs_gset:cx {g__robExt_lines_error_\robExtAddCachePathAndName{\robExtFinalHash}:} {\msg_line_number:}
          \cs_gset:cx {g__robExt_compilation_command_\robExtAddCachePathAndName{\robExtFinalHash}:} {\l__robExt_current_compilation_command_str}
        \fi
      }
    \else
      \bool_if:nTF { \sys_if_shell_unrestricted_p: || \cs_if_exist_p:N \robExtForceCompilation }
      {
        \message{[robExt] We ~ will ~ start ~ the ~ compilation using: ~ \l__robExt_current_compilation_command_str.}
        \sys_shell_now:x {\l__robExt_current_compilation_command_str} % The ~ are used in ExplSyntaxOn to add space
        %% We notify that we are running the compilation command, this way it is possible to check later
        %% if the file is not present because of some compilation error or because we are in manual mode
        %% or fallback
        \cs_set:Nn \l__robExt_I_just_ran_a_compilation_command: {}
      }{
        \ifdefined\robExtFallbackManualMode
          % Avoid writing the same command multiple times (might occur in environments that execute the
          % same command multiple times like align etc)
          \cs_if_exist:cTF {l__robExt_missing_figure_\l__robExt_current_compilation_command_str :}{}{
            \message{[robExt] Fallback to manual mode: please, manually compile the images using \l__robExt_current_compilation_command_str or run 'bash \jobname-\robExtAddPrefixName{compile-missing-figures.sh}'.}
            \iow_now:Nx \g__robExt_write_manually_compile_all_missing_figures_iow {\l__robExt_current_compilation_command_str}% a new line is automatically added
            \cs_gset:cn {l__robExt_missing_figure_\l__robExt_current_compilation_command_str :} {}
            \ifdefined\robExt@compile@parallel@after
              \gdef\robExt@compile@parallel@must@compile{}
              \seq_gput_right:Nx \g__robExt_files_compiled_in_parallel {\robExtAddCachePathAndName{\robExtFinalHash}}
            \fi
          }
        \else
          \msg_error:nn{robExt}{need shell escape}
        \fi
      }
    \fi
  }
}

\robExtSetPlaceholder*{__ROBEXT_INCLUDE_COMMAND__}{%
  \ifdefined\robExtDepth%
    \raisebox{-\robExtDepth}{%
      \includegraphics[__ROBEXT_INCLUDEGRAPHICS_OPTIONS__]{%
        __ROBEXT_INCLUDEGRAPHICS_FILE__%
      }}%
  \else%
    \includegraphics[__ROBEXT_INCLUDEGRAPHICS_OPTIONS__]{%
      %\robExtAddCachePathAndName{\robExtFinalHash.pdf}%
      __ROBEXT_INCLUDEGRAPHICS_FILE__%
    }%
  \fi
}

% These special placeholders are not loaded before for efficiency reasons.
\NewDocumentCommand{\robExtLoadSpecialPlaceholders}{}{
  \robExtPlaceholderFromString {__ROBEXT_OUTPUT_PREFIX__}{\l_tmp_output_prefix_str}
  \robExtPlaceholderFromStringExpanded {__ROBEXT_SOURCE_FILE__}{\l_tmp_output_prefix_str .tex}
  \robExtPlaceholderFromStringExpanded {__ROBEXT_OUTPUT_PDF__}{\l_tmp_output_prefix_str .pdf}
  \robExtPlaceholderFromStringExpanded {__ROBEXT_WAY_BACK__}{\robExtCacheFolderWayBack}
  \robExtPlaceholderFromStringExpanded {__ROBEXT_CACHE_FOLDER__}{\robExtCacheFolder}
}

\def\robExtIncludeGraphicsArgs{}
%%% This command is not meant to be called by the end user. It will be called after the compilation to include
%%% the compiled file back into the original file.
\NewDocumentCommand{\robExtIncludeFile}{m}{%
  % We can disable this loading for efficiency reasons
  \ifdefined\robExtDoNotLoadSpecialPlaceholders\else\robExtLoadSpecialPlaceholders\fi%
  \ifdefined\robExtIncludeCommandAdvanced%
    \robExtIncludeCommandAdvanced%
  \else%
    {%
      \file_if_exist:xTF{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}{%
        \file_if_exist:xTF{\robExtAddCachePathAndName{\robExtFinalHash-out.tex}}{%
          \kern0pt%Without the kern, the next unskip would eat spaces before... and we don't want that. See also
          % https://tex.stackexchange.com/questions/104034/when-is-it-good-practice-to-use-unskip
          \input{\robExtAddCachePathAndName{\robExtFinalHash-out.tex}}\unskip% Otherwise if the file contains space it will be added here.
        }{}%
        %\robExtConfigure{run ~ before ~ include ~ command}%
        \ifdefined\robExtIncludeCommand%
          \robExtIncludeCommand%
        \else%
\robExtEvalPlaceholderStartFromList{__ROBEXT_INCLUDE_COMMAND__,__ROBEXT_INCLUDEGRAPHICS_OPTIONS__,__ROBEXT_INCLUDEGRAPHICS_FILE__,__ROBEXT_LATEX_TRIM_LENGTH__}{__ROBEXT_INCLUDE_COMMAND__}%
        \fi%
        %\robExtConfigure{run ~ after ~ include ~ command}%
      }{
        % Check if we tried to run a compilation command at the previous step:
        \cs_if_exist:NTF \l__robExt_I_just_ran_a_compilation_command: {
          % We ran a compilation command but it failed: we print an error message
          \msg_error:nnxxx{robExt}{missing compiled pdf parallel}{\robExtAddCachePathAndName{\robExtFinalHash}}{\msg_line_number:}{\l__robExt_current_compilation_command_str}
        } { % We ran no compilation command: we print instead a placeholder depending on the context:
          \cs_if_exist:NTF \robExt@compile@parallel@must@compile {
            % we are supposed to compile the current picture in parallel, let'us check if it will be possible:
            \bool_if:nTF { \sys_if_shell_unrestricted_p: || \cs_if_exist_p:N \robExtForceCompilation} {
              \robExtImagePlaceholderIfParallelCompilation
            }{
              \robExtImagePlaceholderIfManualMode
            }
          }{
            \cs_if_exist:NTF \robExtManualMode {
              \robExtImagePlaceholderIfManualMode
              \message{[robExt] ~ You ~ are ~ in ~ manual ~ mode: ~ please ~ compile ~ yourself ~ \robExtAddCachePathAndName{\robExtFinalHash.tex} ~ or ~ use ~ the ~ bash ~ \jobname-\robExtAddPrefixName{compile-missing-figures.sh}}
            }{
              \robExtImagePlaceholderIfFallbackMode
              \message{[robExt] ~ You ~ are ~ falling ~ back ~ to ~ manual ~ mode: ~ please ~ compile ~ yourself ~ \robExtAddCachePathAndName{\robExtFinalHash.tex} ~ or ~ use ~ the ~ bash ~ \jobname-\robExtAddPrefixName{compile-missing-figures.sh}}
            }
          }
        }
      }%
    }%
  \fi%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Disabling externalization
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% It seems that when we disable externalization on \tikz, \tikz internally call \tikzpicture in a
% weird way (certainly some tikz magic), and as a result it does not manage to grab the end of the CacheMe
% environment. For this reason, by default, |disable externalization| will disable **all** commands

\seq_clear_new:N \l_commands_to_reset_seq % List of commands to reset by default when disable externalization is set

\NewDocumentCommand{\robExtAddToCommandResetList}{m}{
  \seq_put_right:Nn \l_commands_to_reset_seq {#1}
}

\NewDocumentCommand{\robExtSetCommandResetList}{m}{
  \seq_set_from_clist:Nn \l_commands_to_reset_seq {#1}
}

\seq_clear_new:N \l_environments_to_reset_seq % List of environments to reset by default when disable externalization is set

\NewDocumentCommand{\robExtAddToEnvironmentResetList}{m}{
  \seq_put_right:Nn \l_environments_to_reset_seq {#1}
}

\NewDocumentCommand{\robExtSetEnvironmentResetList}{m}{
  \seq_set_from_clist:Nn \l_environments_to_reset_seq {#1}
}

\NewDocumentCommand{\robExtDisableTikzpictureOverwrite}{}{%
  \ifdefined\robExtTikzPictureOrig%
    \let\tikzpicture\robExtTikzPictureOrig%
    \let\endtikzpicture\endrobExtTikzPictureOrig%
  \fi%
  \ifdefined\robExtEnvironmentOrigName%
    \expanded{\noexpand\DeclareEnvironmentCopy{\robExtEnvironmentOrigName}{robExtEnvironmentOrig\robExtEnvironmentOrigName}}%
  \fi%
  \ifdefined\robExtCommandOrigName%
    \expandafter\DeclareCommandCopy\csname \robExtCommandOrigName\expandafter\endcsname\csname robExtCommandOrig\robExtCommandOrigName\endcsname%
  \fi%
  \ifdefined\robExtDoNotResetAllCommands\else%
    \seq_map_inline:Nn \l_commands_to_reset_seq {
      \cs_if_exist:cTF { robExtCommandOrig##1 } {
        \expandafter\DeclareCommandCopy\csname ##1\expandafter\endcsname\csname robExtCommandOrig##1\endcsname%
      } {}
    }
    \seq_map_inline:Nn \l_environments_to_reset_seq {
      \cs_if_exist:cTF { robExtEnvironmentOrig##1 } {
        \expanded{\noexpand\DeclareEnvironmentCopy{##1}{robExtEnvironmentOrig##1}}
      } {}
    }
  \fi%
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Automatically forward elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% \robExtSetCodeToRunIfMacroPresent{\hello}{some code} will execute "some code" if \hello is present in
% the main content to build and if "auto forward" is enabled.
\NewDocumentCommand{\robExtSetCodeToRunIfMacroPresent}{mm}{
  % we need to remove the leading space
  % \str_set:Nx \l__robExt_tmp_str {\cs_to_str:N #1}
  \expandafter\def \csname l__robExt_execute_if_macro_present\string#1\endcsname {#2}%
}

% \robExtRunCodeToRunForMacroPresent{\hello} will run the code that was configured when calling
% \robExtSetCodeToRunIfMacroPresent{\hello}{some code}
\NewDocumentCommand{\robExtRunCodeToRunForMacroPresent}{m}{
  % \str_set:Nx \l__robExt_tmp_str {\cs_to_str:N ##1}
  \cs_if_exist_use:c {l__robExt_execute_if_macro_present\string#1}
}

% \autoForwardMacro{\hello}[\firstMacroDeps,\secondMacroDeps] will be used to tell to "auto forward" to forward \hello, \firstMacroDeps, and \secondMacroDeps if \hello is present in the main content to build.
\NewDocumentCommand{\robExtConfigIfMacroPresent}{mm}{%
  \robExtSetCodeToRunIfMacroPresent{#1}{%
    \pgfkeysalso{#2}%
  }%
}
\let\configIfMacroPresent\robExtConfigIfMacroPresent

\NewDocumentCommand{\robExtAutoForwardMacro}{mO{}}{%
  \robExtConfigIfMacroPresent{#1}{
    forward=#1,#2
  }%a
}
\let\autoForwardMacro\robExtAutoForwardMacro

\NewDocumentCommand{\robExtLoadAutoForwardMacroConfig}{m}{
  %\str_set:Nx \l__robExt_tmp_str {\cs_to_str:N #1}
  \cs_if_exist:cTF {l__robExt_execute_if_macro_present\string#1}{
    % if the macro is present twice, we want to run \forward only once
    \cs_if_exist:cTF {l__robExt_execute_if_macro_present_already_forwarded\string#1 :}{}{
      \use:c {l__robExt_execute_if_macro_present\string#1}
      % define it so that we do not import twice next time
      \cs_set:cx {l__robExt_execute_if_macro_present_already_forwarded\string#1 :} {}
    }
  }{}
}



%% Old version: too inneficient
% \regex_const:Nn \l__robExt_macro_regex { \\[A-Za-z]+ }
% \NewDocumentCommand{\robExtAutoForward}{}{
%   \seq_clear_new:N \l__robExt_matches_seq
%   \regex_extract_all:NVN \l__robExt_macro_regex \l__robExt_placeholder___ROBEXT_MAIN_CONTENT_ORIG___str \l__robExt_matches_seq%
%   \seq_map_inline:Nn \l__robExt_matches_seq {
%     \robExtLoadAutoForwardMacroConfig{##1}
%   }
% }

%% "auto forward"
\NewDocumentCommand{\robExtAutoForward}{}{
  \ifdefined\robExtUserInputCacheMe\else
    \msg_warning:nn{robExt}{auto forward not in cachemecode}
    \tl_set_rescan:NnV \robExtUserInputCacheMe {} \l__robExt_placeholder___ROBEXT_MAIN_CONTENT_ORIG___str
  \fi
  \robExt@normalBraces\robExtUserInputCacheMe
  \expandafter\robExt@getfromstringA\robExtUserInputCacheMe\robExt@getfromstringA%\robExt@getfromstringA is added to know when to stop
}

% https://tex.stackexchange.com/questions/700834/efficiently-program-search-of-macro-in-string/700844
\def\robExt@getfromstringA#1{\ifx#1\robExt@getfromstringA \else
  %\ifcsname L:\string#1\endcsname \addto\listmacros{#1}\fi
  \robExtLoadAutoForwardMacroConfig{#1}%
  \expandafter\robExt@getfromstringA\fi
}

\def\robExt@normalBraces#1{{\catcode`{=12 \catcode`}=12 \everyeof={\endfile}%
   \expandafter\robExt@normalBracesA\expandafter#1\scantokens\expandafter{#1}}}
\def\robExt@normalBracesA#1#2\endfile{\gdef#1{#2}}

%%% To automatically define and forward
\NewDocumentCommand{\newcommandAutoForward}{moomO{}}{
  \IfNoValueTF{#2}{
    \IfNoValueTF{#3}{
      \newcommand{#1}{#4}
    }{
      \newcommand{#1}[#3]{#4}
    }
  }{
    \IfNoValueTF{#3}{
      \newcommand{#1}[#2]{#4}
    }{
      \newcommand{#1}[#2][#3]{#4}
    }
  }
  \robExtAutoForwardMacro{#1}[#5]
}

%%% To automatically define and forward
\NewDocumentCommand{\renewcommandAutoForward}{moomO{}}{
  \IfNoValueTF{#2}{
    \IfNoValueTF{#3}{
      \renewcommand{#1}{#4}
    }{
      \renewcommand{#1}[#3]{#4}
    }
  }{
    \IfNoValueTF{#3}{
      \renewcommand{#1}[#2]{#4}
    }{
      \renewcommand{#1}[#2][#3]{#4}
    }
  }
  \robExtAutoForwardMacro{#1}[#5]
}

%%% To automatically define and forward
\NewDocumentCommand{\providecommandAutoForward}{moomO{}}{
  \IfNoValueTF{#2}{
    \IfNoValueTF{#3}{
      \providecommand{#1}{#4}
    }{
      \providecommand{#1}[#3]{#4}
    }
  }{
    \IfNoValueTF{#3}{
      \providecommand{#1}[#2]{#4}
    }{
      \providecommand{#1}[#2][#3]{#4}
    }
  }
  \robExtAutoForwardMacro{#1}[#5]
}

\NewDocumentCommand{\NewDocumentCommandAutoForward}{mmO{}m}{
  \NewDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\RenewDocumentCommandAutoForward}{mmO{}m}{
  \RenewDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\ProvideDocumentCommandAutoForward}{mmO{}m}{
  \ProvideDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\DeclareDocumentCommandAutoForward}{mmO{}m}{
  \DeclareDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\NewExpandableDocumentCommandAutoForward}{mmO{}m}{
  \NewExpandableDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\RenewExpandableDocumentCommandAutoForward}{mmO{}m}{
  \RenewExpandableDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\ProvideExpandableDocumentCommandAutoForward}{mmO{}m}{
  \ProvideExpandableDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\DeclareExpandableDocumentCommandAutoForward}{mmO{}m}{
  \DeclareExpandableDocumentCommand{#1}{#2}{#4}
  \robExtAutoForwardMacro{#1}[#3]
}

\NewDocumentCommand{\defAutoForward}{mO{}mO{}}{
  \def#1#2{#3}
  \robExtAutoForwardMacro{#1}[#4]
}

% \robExtGenericAutoForward[tikz]{string to match}[additional style to run]{
%    code to run in cached file if string matches, and to always run in current folder if not using
%    the star version
%  }
\ExplSyntaxOff
\NewDocumentCommand{\robExtGenericAutoForward}{sO{latex}mO{}m}{%
  \IfBooleanTF{#1}{}{#5}% We run the code right now
  \robExt@set@hash@robust\zxTmpMacro{#5}%
  \robExtConfigure{%
    add to preset={#2}{%
      if matches word={#3}{
        command if externalization/.append code={
          \expanded{%
            \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
              \expandonce{\zxTmpMacro}%
              % #1%%
            }%
          }%
        },#4%
      }%
    }%
  }%
}
\let\genericAutoForward\robExtGenericAutoForward

% uses "if matches" instead of "if matches word"
\NewDocumentCommand{\robExtGenericAutoForwardStringMatch}{sO{latex}mO{}m}{%
  \IfBooleanTF{#1}{}{#5}% We run the code right now
  \robExt@set@hash@robust\zxTmpMacro{#5}%
  \robExtConfigure{%
    add to preset={#2}{%
      if matches={#3}{
        command if externalization/.append code={
          \expanded{%
            \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
              \expandonce{\zxTmpMacro}%
              % #1%%
            }%
          }%
        },#4%
      }%
    }%
  }%
}
\let\genericAutoForwardStringMatch\robExtGenericAutoForwardStringMatch
\ExplSyntaxOn

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Automatically forward (regex-based)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% called by style "if matches".
% \robExtRegexMatches{my regex}{my style} will apply "my style" if "__ROBEXT_MAIN_CONTENT_ORIG__" matches
% "my regex".
\NewDocumentCommand{\robExtIfMatchesRegex}{mm}{
  \regex_match:nVTF {#1} \l__robExt_placeholder___ROBEXT_MAIN_CONTENT_ORIG___str {\pgfkeysalso{#2}} {}
}

\NewDocumentCommand{\robExtIfMatchesString}{mm}{
  \str_if_in:NnTF \l__robExt_placeholder___ROBEXT_MAIN_CONTENT_ORIG___str {#1} {\pgfkeysalso{#2}} {}
}

\ExplSyntaxOff

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% We create interface into pgfkeys in order to allow easier creation of content via style
\pgfkeys{%
  /robExt/.cd,%
  % We create a default style that will be loaded (mostly for the user)
  default style/.style={},%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Code to create new styles %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % The advantage of this over .append style is that you do not need to double the number of hashes
  % don't know if there is a better solution.
  % https://tex.stackexchange.com/questions/695432/latex3-latex-doubles-the-number-of-hashes-when-storing-them-in-string/695461
  add to preset/.code 2 args={%
    \robExtStrSetDoubleHash{\robExtTmpStr}{#2}%
    % Sadly, \expanded{\noexpand } does not work, as I get extra {} around the def, creating a group
    % so the simpler seems to use this library ^^
    \robExtPlaceholderFromString{__ROBEXT_TMP__}{\robExtTmpStr}%
    \robExtEvalPlaceholderReplaceFromList{__ROBEXT_TMP__}{%
      \pgfkeys{%
        /robExt/.cd,
        #1/.append style={__ROBEXT_TMP__},%
      }%
    }%
    \robExtRemovePlaceholder{__ROBEXT_TMP__}% let us clean our variables
  },
  new preset/.code 2 args={%
    \robExtStrSetDoubleHash{\robExtTmpStr}{#2}%
    % Sadly, \expanded{\noexpand } does not work, as I get extra {} around the def, creating a group
    % so the simpler seems to use this library ^^
    \robExtPlaceholderFromString{__ROBEXT_TMP__}{\robExtTmpStr}%
    % \robExtShowPlaceholder*{__ROBEXT_TMP__}
    \robExtEvalPlaceholderReplaceFromList{__ROBEXT_TMP__}{%
      \pgfkeys{%
        /robExt/.cd,%
        #1/.style={__ROBEXT_TMP__},%
      }%
    }%
    \robExtRemovePlaceholder{__ROBEXT_TMP__}% let us clean our variables
  },
  % new compiled preset={latex compiled}{
  %  code to compile in order to produce the expected strings  
  % }{
  %  code to initialize
  % }
  compile latex template/.style={
    % to allow later addition to the preamble, we add a dummy value that we replace in a few lines
    % same for main content and content orig that we do not want to replace.
    add to placeholder={__ROBEXT_LATEX_PREAMBLE__}{__ROBEXT_LATEX_PREAMBLE_DUMMY__},
    set placeholder={__ROBEXT_MAIN_CONTENT__}{__ROBEXT_MAIN_CONTENT_DUMMY__},
    set placeholder={__ROBEXT_MAIN_CONTENT_ORIG__}{__ROBEXT_MAIN_CONTENT_ORIG_DUMMY__},
    /utils/exec={%
      \robExtGetNearlyFinalValueTemplateAndCompilationCommand%
      \robExtSetBackCompilationCommandAndTemplate%
    },
    set placeholder={__ROBEXT_LATEX_PREAMBLE_DUMMY__}{__ROBEXT_LATEX_PREAMBLE__},
    set placeholder={__ROBEXT_MAIN_CONTENT_DUMMY__}{__ROBEXT_MAIN_CONTENT__},
    set placeholder={__ROBEXT_MAIN_CONTENT_ORIG_DUMMY__}{__ROBEXT_MAIN_CONTENT_ORIG__},
    set placeholder rec replace from list={__ROBEXT_TEMPLATE__,__ROBEXT_LATEX_PREAMBLE_DUMMY__,__ROBEXT_MAIN_CONTENT_DUMMY__,__ROBEXT_MAIN_CONTENT_ORIG_DUMMY__}{__ROBEXT_TEMPLATE__}{__ROBEXT_TEMPLATE__},
    % For the include command
    set placeholder rec replace from list={__ROBEXT_INCLUDE_COMMAND__,__ROBEXT_INCLUDEGRAPHICS_OPTIONS__,__ROBEXT_INCLUDEGRAPHICS_FILE__,__ROBEXT_LATEX_TRIM_LENGTH__}{__ROBEXT_INCLUDE_COMMAND__}{__ROBEXT_INCLUDE_COMMAND__},
  },
  keep placeholder after group/.code={\robExtKeepPlaceholderAfterGroup{#1}},
  new compiled preset/.code n args={3}{
    \robExtStrSetDoubleHash{\robExtCodeToCompileStr}{#2}%
    \robExtStrSetDoubleHash{\robExtCodeToRunStr}{#3}%
    % Sadly, \expanded{\noexpand } does not work, as I get extra {} around the def, creating a group
    % so the simpler seems to use this library ^^
    \robExtPlaceholderFromString{__ROBEXT_TMP_CODE_TO_COMPILE__}{\robExtCodeToCompileStr}%
    \robExtPlaceholderFromString{__ROBEXT_TMP_CODE_TO_RUN__}{\robExtCodeToRunStr}%
    \robExtPlaceholderFromString{__ROBEXT_NAME_TEMPLATE_PREFIX__}{\robExtCodeToRunStr}%
    % \robExtShowPlaceholder*{__ROBEXT_TMP__}
    \robExtEvalPlaceholderReplaceFromList{__ROBEXT_TMP_CODE_TO_COMPILE__,__ROBEXT_TMP_CODE_TO_RUN__}{%
      \robExtConfigure{%
        #1-recompile/.code={%
          \begingroup%
            \robExtConfigure{
              __ROBEXT_TMP_CODE_TO_COMPILE__,
            }%
            \robExtCopyPlaceholder*{__ROBEXT_COMPILED_#1_TEMPLATE__}{__ROBEXT_TEMPLATE__}%
            \robExtKeepPlaceholderAfterGroup{__ROBEXT_COMPILED_#1_TEMPLATE__}%
            \robExtCopyPlaceholder*{__ROBEXT_COMPILED_#1_COMPILATION_COMMAND__}{__ROBEXT_COMPILATION_COMMAND__}%
            \robExtKeepPlaceholderAfterGroup{__ROBEXT_COMPILED_#1_COMPILATION_COMMAND__}%
            \robExtCopyPlaceholder*{__ROBEXT_COMPILED_#1_INCLUDE_COMMAND__}{__ROBEXT_INCLUDE_COMMAND__}%
            \robExtKeepPlaceholderAfterGroup{__ROBEXT_COMPILED_#1_INCLUDE_COMMAND__}%
            \robExtRescanPlaceholderInVariableNoReplacement{robExtCompiledIncludeCommand#1}{__ROBEXT_INCLUDE_COMMAND__}%
            \robExtKeepaftergroup{robExtCompiledIncludeCommand#1}%
            \robExtKeepaftergroup{l__robExt_placeholder___ROBEXT_COMPILED_#1_INCLUDE_COMMAND___str}%
            \robExtKeepaftergroup{l__robExt_placeholder___ROBEXT_COMPILED_#1_TEMPLATE___str}%
            \robExtSaveDependencies{robExtCompiledDependencies#1}%
          \endgroup%
        },
        #1-recompile,
        #1/.style={
          disable placeholders,
          set placeholder={__ROBEXT_LATEX_PREAMBLE__}{},
          add to preamble/.style={
            add to placeholder={__ROBEXT_LATEX_PREAMBLE__}{####1},
          },
          /utils/exec={\robExtRestoreDependencies{robExtCompiledDependencies#1}},
          custom include command={\csname robExtCompiledIncludeCommand#1\endcsname},
          copy placeholder no import={__ROBEXT_TEMPLATE__}{__ROBEXT_COMPILED_#1_TEMPLATE__},
          copy placeholder no import={__ROBEXT_COMPILATION_COMMAND__}{__ROBEXT_COMPILED_#1_COMPILATION_COMMAND__},
          __ROBEXT_TMP_CODE_TO_RUN__
        },%
      }%
    }%
    \robExtRemovePlaceholder{__ROBEXT_TMP_CODE_TO_RUN__}% let us clean our variables
    \robExtRemovePlaceholder{__ROBEXT_TMP_CODE_TO_COMPILE__}% let us clean our variables
  },
  in command/.style={
    set placeholder={__ROBEXT_MAIN_CONTENT__}{__ROBEXT_MAIN_CONTENT_ORIG__},
  },
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Interface to change placeholders %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  remove placeholder/.code={\robExtRemovePlaceholder{#1}},
  remove placeholders/.style={
    remove placeholder/.list={#1},
  },
    set main content/.style={
    set placeholder={__ROBEXT_MAIN_CONTENT_ORIG__}{#1}
  },
  copy placeholder/.code 2 args={\robExtCopyPlaceholder{#1}{#2}},
  copy placeholder no import/.code 2 args={\robExtCopyPlaceholder*{#1}{#2}},
  set placeholder/.code 2 args={\robExtSetPlaceholder{#1}{#2}},
  % do not import the placeholder (useful for efficiency reasons)
  set placeholder no import/.code 2 args={\robExtSetPlaceholder*{#1}{#2}},
  set placeholder first/.code 2 args={\robExtSetPlaceholderFirst*{#1}{#2}},
  set placeholder rec/.code 2 args={\robExtSetPlaceholderRec{#1}{#2}},
  set placeholder rec keep after group/.code 2 args={\robExtSetPlaceholderRec{#1}{#2}\robExtKeepPlaceholderAfterGroup{#1}},
  set placeholder rec no import/.code 2 args={\robExtSetPlaceholderRec*{#1}{#2}},
  set placeholder rec replace from list/.code n args={3}{\robExtSetPlaceholderRecReplaceFromList{#1}{#2}{#3}},
  set placeholder rec replace from list no import/.code n args={3}{\robExtSetPlaceholderRecReplaceFromList*{#1}{#2}{#3}},
  set placeholder eval/.code 2 args={\robExtSetPlaceholderRec{#1}{#2}\robExtEvalPlaceholderInplace{#1}},
  set placeholder eval no import/.code 2 args={\robExtSetPlaceholderRec*{#1}{#2}\robExtEvalPlaceholderInplace{#1}},
  set placeholder eval replace from list/.code n args={3}{\robExtSetPlaceholderRecReplaceFromList{#1}{#2}{#3}\robExtEvalPlaceholderInplace{#2}},
  set placeholder eval replace from list no import/.code n args={3}{\robExtSetPlaceholderRecReplaceFromList*{#1}{#2}{#3}\robExtEvalPlaceholderInplace{#2}},
  eval placeholder/.code={\robExtEvalPlaceholder{#1}},
  eval placeholder replace from list/.code 2 args={\robExtEvalPlaceholderReplaceFromList{#1}{#2}},
  set placeholder from content/.code 2 args={\robExtPlaceholderFromContent{#1}{#2}},
  set placeholder from content no import/.code 2 args={\robExtPlaceholderFromContent*{#1}{#2}},
  add to placeholder/.code 2 args={\robExtAddToPlaceholder{#1}{#2}},
  add to placeholder no import/.code 2 args={\robExtAddToPlaceholderNoImport{#1}{#2}},
  add to placeholder no space/.code 2 args={\robExtAddToPlaceholder*{#1}{#2}},
  add to placeholder no space no import/.code 2 args={\robExtAddToPlaceholderNoImport*{#1}{#2}},
  add before placeholder/.code 2 args={\robExtAddBeforePlaceholder{#1}{#2}},
  add before placeholder no space/.code 2 args={\robExtAddBeforePlaceholder*{#1}{#2}},
  add before placeholder no import/.code 2 args={\robExtAddBeforePlaceholderNoImport{#1}{#2}},
  add before placeholder no space no import/.code 2 args={\robExtAddBeforePlaceholderNoImport*{#1}{#2}},
  set placeholder path from filename/.code 2 args={\robExtPlaceholderPathFromFilename{#1}{#2}},
  set placeholder path from filename no import/.code 2 args={\robExtPlaceholderPathFromFilename*{#1}{#2}},
  set placeholder from file content/.code 2 args={\robExtPlaceholderFromFileContent{#1}{#2}},
  set placeholder from file content no import/.code 2 args={\robExtPlaceholderFromFileContent*{#1}{#2}},
  set placeholder path from content/.code n args={3}{\robExtPlaceholderPathFromContent{#1}[#3]{#2}},
  set placeholder path from content no import/.code n args={3}{\robExtPlaceholderPathFromContent*{#1}[#3]{#2}},
  eval placeholder in place/.code={\robExtEvalPlaceholderInplace{#1}},
  placeholder halve number hashes in place/.code={\robExtPlaceholderHalveNumberHashesInplace{#1}},
  placeholder double number hashes in place/.code={\robExtPlaceholderDoubleNumberHashesInplace{#1}},
  placeholder replace in place/.code n args={3}{\robExtPlaceholderReplaceInplace{#1}{#2}{#3}},
  placeholder replace in place eval/.code n args={3}{\robExtPlaceholderReplaceInplaceEval{#1}{#2}{#3}},
  % Interface to set template
  set template/.style={
    set placeholder first={__ROBEXT_TEMPLATE__}{#1},
  },
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Interface for optimization %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  % It is important to create an efficient code (otherwise the library can becomes pointless)
  % and it can help a lot if we give some advices to the system that evaluates placeholders, notably on
  % the replacement order it should follow:
  %%%% "only placeholders" says "use only these placeholders in this template/compilation command/... in that order
  %%%% while "first placeholders" says "start with these placeholders, if it is not enough, continue as usual
  only placeholders in compilation command/.code={\robExtOnlyPlaceholdersInCompilationCommand{#1}},
  first placeholders in compilation command/.code={\robExtFirstPlaceholdersInCompilationCommand{#1}},
  only placeholders in template/.code={\robExtOnlyPlaceholdersInTemplate{#1}},
  first placeholders in template/.code={\robExtFirstPlaceholdersInTemplate{#1}},
  only placeholders in include command/.code={\robExtOnlyPlaceholdersInIncludeCommand{#1}},
  first placeholders in include command/.code={\robExtFirstPlaceholdersInIncludeCommand{#1}},
  %%%%%%%%%%%%%
  %%% Debug %%%
  %%%%%%%%%%%%%
  more logs/.code={\def\robExtDebugMessage#1{\message{^^J[robExt] #1}}},
  less logs/.code={\def\robExtDebugMessage#1{}},
  show placeholder/.code={\robExtShowPlaceholder{#1}},
  show placeholders/.code={\robExtShowPlaceholders},
  show placeholders contents/.code={\robExtShowPlaceholdersContents},
  print imported placeholders except default/.code={\robExtPrintAllPlaceholdersExceptDefaults},
  print imported placeholders/.code={\robExtPrintAllPlaceholders},
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Optimizations %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  do not load special placeholders/.code={\let\robExtDoNotLoadSpecialPlaceholders\undefined},
  load special placeholders/.code={\def\robExtDoNotLoadSpecialPlaceholders{}},
  do not load special placeholders,
  %% Replace very little placeholders, basically only __ROBEXT_MAIN_CONTENT__, __ROBEXT_MAIN_CONTENT_ORIG__,
  %% and the default  (prefix, source, output, wayback, cache folder)
  disable placeholders/.code={\def\robExtDisablePlaceholders{}},
  enable placeholders/.code={\let\robExtDisablePlaceholders\undefined},
  %% If all placeholders have __, this option will speed up the compilation time
  all placeholders have underscores/.code={\def\robExtPlaceholderOnlyWithUnderscores{}},
  not all placeholders have underscores/.code={\let\robExtPlaceholderOnlyWithUnderscores\undefined},
  %% not sure if I want users to disable import mechanism as they might use dirty things
  enable import mechanism/.code={\def\robExtEnableImportMechanism{}},
  disable import mechanism/.code={\let\robExtEnableImportMechanism\undefined},
  disable optimizations/.style={
    not all placeholders have underscores,
    disable import mechanism,
  },
  enable optimizations/.style={
    all placeholders have underscores,
    enable import mechanism,
  },
  enable optimizations,
  %%%%%%%%%%%%%%
  %%% Groups %%%
  %%%%%%%%%%%%%%
  clear imported placeholders/.code={\robExtClearImportedPlaceholders},
  remove imported placeholder/.code={\robExtRemoveImportedPlaceholder{#1}},
  remove imported placeholders/.style={
    remove imported placeholder/.list={#1},
  },
  print group placeholders/.code={\robExtPrintGroupPlaceholders{#1}},
  new group placeholders/.code={\robExtRegisterGroupPlaceholders{#1}},
  add placeholder to group/.code 2 args={\robExtAddPlaceholdersToGroup{#1}{#2}},
  add placeholders to group/.code 2 args={\robExtAddPlaceholdersToGroup{#1}{#2}},
  remove placeholder from group/.code 2 args={\robExtRemovePlaceholdersFromGroup{#1}{#2}},
  remove placeholders from group/.code 2 args={\robExtRemovePlaceholdersFromGroup{#1}{#2}},
  copy group placeholders/.code 2 args={\robExtCopyGroupPlaceholders{#1}{#2}},
  append group placeholders/.code 2 args={\robExtAppendGroupPlaceholders{#1}{#2}},
  append before group placeholders/.code 2 args={\robExtAppendGroupPlaceholders{#1}{#2}},
  import placeholders from group/.code={\robExtImportPlaceholdersFromGroup{#1}},
  import all placeholders/.code={\robExtImportAllPlaceholders},
  % ok this is a different kind of group, here latex group { }
  import placeholder/.code={\robExtImportPlaceholder{#1}},
  import all placeholders/.code={\robExtImportAllPlaceholders},
  import placeholders/.style={
    import placeholder/.list={#1},
  },
  import placeholder first/.code={\robExtImportPlaceholderFirst{#1}},
  import placeholders first/.code={\robExtAddPlaceholdersToListFirst{#1}},
  import placeholders from group/.code={\robExtImportPlaceholdersFromGroup{#1}},
  print all registered groups/.code={\robExtPrintAllRegisteredGroups},
  print all registered groups and placeholders/.code={\robExtPrintAllRegisteredGroupsAndPlaceholders},
  show all registered groups/.code={\robExtShowAllRegisteredGroupsAndPlaceholders},
  show all registered groups and placeholders/.code={\robExtShowAllRegisteredGroupsAndPlaceholders},
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Configure dependencies %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Auxiliary command:
  dependenciesList/.code={\robExtAddDependency{#1}},
  % Usage like: dependencies={input_externalize.tex,input_b.tex}
  % They should be relative to the main file when using the subfolder option.
  dependencies/.style={
    /utils/exec={\robExtResetDependencies{}},
    dependenciesList/.list={#1}
  },
  add dependencies/.style={
    dependenciesList/.list={#1}
  },
  reset dependencies/.code={\robExtResetDependencies{}},
  %%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Compilation command %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%
  % People might want to force the compilation even if shell_unrestricted is false, notably if they
  % allow commands like mkdir/cd/pdflatex to run in restricted mode.
  force compilation/.code={\def\robExtForceCompilation{}},
  do not force compilation/.code={\let\robExtForceCompilation\undefined},
  % Recompile the file even if it has already been compiled (we do NOT clean the file as we do not feel
  % safe to remove files from this code, but this can also be done by the user hooking into
  recompile/.code={\def\robExtForceRecompilation{}},
  do not recompile/.code={\let\robExtForceRecompilation\undefined},
  set compilation command/.code={\robExtSetCompilationCommand{#1}},
  add argument to compilation command/.code={\robExtAddArgumentToCompilationCommand{#1}},
  add arguments to compilation command/.style={
    add argument to compilation command/.list={#1}
  },
  % This adds arguments like add key value to compilation command={mykey=myvalue} will add to the
  % compilation command two arguments: "mykey" "myvalue"
  % This is useful for scripts that are called like myscript key1 arg1 key2 arg2 key3 arg3, which is a
  % simple way to pass multiple arguments to a script like a python script
  add key value argument to compilation command/.code args={#1=#2}{\robExtAddArgumentToCompilationCommand{#1}\robExtAddArgumentToCompilationCommand{#2}},
  add key and file argument to compilation command aux/.style args={#1=#2}{
    add key value argument to compilation command={{#1}={\ifdefined\robExtCacheFolderWayBack\robExtCacheFolderWayBack\fi#2}},
  },
  add key and file argument to compilation command/.style={
    add key and file argument to compilation command aux/.list={#1},
    add dependencies={#1},
  },
  %%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Inclusion command %%%
  %%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Configure the command to include the compiled file back into the main file
  % By default, include command does a bit of logic before running the actual command, notably to
  % input the -out.tex file in order to pass information from the compiled file to the current file.
  % If you want to do everything by yourself, use:
  custom include command advanced/.code={\def\robExtIncludeCommandAdvanced{#1}},
  % The default include command includes the pdf, making sure it is raised depending on its depth,
  % but you can override it:
  custom include command/.code={\def\robExtIncludeCommand{#1}},
  %% Use this when we do not want to include anything (e.g. the video will be processed later in the chain):
  do not include pdf/.style={
    custom include command={}%
  },
  %% If you do or do not want to ask latex to run the compilation commands itself (for instance for security
  %% reasons, you can use these commands and run the command manually later):
  enable manual mode/.code={\def\robExtManualMode{}},
  disable manual mode/.code={\let\robExtManualMode\undefined},
  enable fallback to manual mode/.code={\def\robExtFallbackManualMode{}},
  disable fallback to manual mode/.code={\let\robExtFallbackManualMode\undefined},
  %% Arguments to include graphics
  include graphics args/.code={\def\robExtIncludeGraphicsArgs{#1}},
  %% The role of this command is to set \l_robExt_result_str, that will contain the final string.
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Configuration of the cache %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %% Configure the prefix (default to "robExt-")
  set filename prefix/.code={\def\robExtPrefixFilename{#1}},
  % first argument is subfolder, second is how to get from subfolder to the folder containing the source:
  % set subfolder and way back={robustExternal/}{../}
  % synonyme, "cache folder" is prefered over ""
  set subfolder and way back/.code 2 args={\def\robExtCacheFolder{#1}\def\robExtCacheFolderWayBack{#2}},
  set cache folder and way back/.code 2 args={\def\robExtCacheFolder{#1}\def\robExtCacheFolderWayBack{#2}},
  no cache folder/.code={\let\robExtCacheFolder\undefined\def\robExtCacheFolderWayBack{}},
  % By default we put everything in robustExternalize
  % Change this before starting to cache any library, and if you change it mid-document, be aware
  % that you will not be able to refer to elements in the old folder.
  set subfolder and way back={robustExternalize/}{../},
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Disable externalization %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %% Note: this does not work reliably for now
  %% TODO: fix this!
  disable externalization/.code={\def\robExtDisableExternalization{}},
  de/.style={disable externalization},
  disable externalization now/.code={\robExtDisableTikzpictureOverwrite\def\robExtDisableExternalization{}},
  enable externalization/.code={\let\robExtDisableExternalization\undefined},
  % Useful to wrap, for instance, text
  command if no externalization/.code={},
  command if no externalization/.code={\robExtDisableTikzpictureOverwrite\evalPlaceholder{__ROBEXT_MAIN_CONTENT__}},
  print verbatim if no externalization/.style={
    command if no externalization/.code={%
      \robExtPrintPlaceholder{__ROBEXT_MAIN_CONTENT__}%
    },
  },
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Forward macros if externalization is enabled %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  command if externalization/.code={},
  fw/.style={forward=#1},
  run code before main content if externalization enabled/.code={\message{#1}},
  % run code before main content if externalization enabled/.code={
  %   \message{aaa #1}
  %   \def\zx@tmp{#1}%
  %   \message{xxx}
  %   \show\zx@tmp%
  %   \scantokens{%
  %     \pgfkeysalso{
  %       command if externalization/.append code={%
  %         \expanded{%
  %           \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
  %             % \expandonce{\zx@tmp}%
  %             #1%%
  %           }%
  %         }%
  %       }%
  %     }%
  %   },
  % },
  forward/.style={%
    command if externalization/.append code={%
      \robExtGetCommandDefinitionInMacro{#1}%
      \expanded{%
        \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
          \expandonce{\robExtDefinitionCommand}%
        }%
      }%
    },
  },
  forward at letter/.style={%
    command if externalization/.append code={%
      \robExtGetCommandDefinitionInMacro{#1}%
      \expanded{%
        \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
          \noexpand\makeatletter%
          \expandonce{\robExtDefinitionCommand}%
          \noexpand\makeatother%
        }%
      }%
    },
  },
  forward eval/.style={%
    command if externalization/.append code={%
      \expanded{%
        \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
          \noexpand\def\noexpand#1{#1}%
        }%
      }%
    },%
  },
  forward counter/.style={%
    command if externalization/.append code={%
      \expanded{%
        \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
          \noexpand\makeatletter%
          % Make sure the counter exists:
          \noexpand\ifcsname c@#1\noexpand\endcsname\noexpand\else\noexpand\newcounter{#1}\noexpand\fi%
          \noexpand\setcounter{#1}{\the\value{#1}}%
          \noexpand\makeatother
        }%
      }%
    },%
  },%
  forward color/.style={
    command if externalization/.append code={%
      \extractcolorspecs{#1}{\zx@tmp@model}{\zx@tmp@cmd}%
      \expanded{%
        \noexpand\robExtAddBeforePlaceholder*{__ROBEXT_MAIN_CONTENT__}{%
          \noexpand\definecolor{#1}{\zx@tmp@model}{\zx@tmp@cmd}%
        }%
      }%
    },%
  },%
  %% This will try to automatically forward some macros. For this, you must first define
  %% 
  auto forward/.code={\robExtAutoForward},
  auto forward color/.style 2 args={%
    add to preset={#1}{
      % if matches={\b #2\b}{forward color=#2},
      % the Regex is maybe more precise (avoid unnecessary forwards) but is way faster
      if matches={#2}{forward color=#2},
    },
  },
  load auto forward macro config/.code={\robExtLoadAutoForwardMacroConfig{#1}},
  %% This will
  if matches regex/.code 2 args={\robExtIfMatchesRegex{#1}{#2}},
  if matches word/.code 2 args={\robExtIfMatchesString{#1}{#2}},
  if matches/.code 2 args={\robExtIfMatchesString{#1}{#2}},
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Run code before/after inclusion %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% todo: make sure that commands can be added instead of replaced
  execute before each externalization/.code={\def\robExtExecuteBefore{#1}},
  execute after each externalization/.code={\def\robExtExecuteAfter{#1}},
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Get the name of the produced file for later use %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
  %%% Here, we provide a way to put the prefixed name into a new global macro
  %%% Use like 'name output=VideoA'. This creates a few macros like:
  %%% \blenderpointNamedOutputFilenameVideoA containing thehashthatisusedforthename
  %%% \blenderpointNamedOutputPrVideoA containing thehashthatisusedforthename
  %% See \robExtGetNamedOutputFilename to get them with \robExtGetNamedOutputFullPath
  name output/.code={%
    \def\robExtExecuteNamedOutput{%
      \expandafter\xdef\csname #1\endcsname{\robExtPrefixFilename\robExtFinalHash}%
      \expandafter\xdef\csname #1InCache\endcsname{\robExtAddCachePathAndName{\robExtFinalHash}}%
    }%
  },
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Compile in parallel automatically
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  compile in parallel/.style={compile in parallel after=#1},
  compile in parallel/.default=0,
  compile in parallel after/.code={%
    \gdef\robExt@compile@parallel@after{#1}%
  },
  compile in parallel after/.default=0,
  disable compile in parallel/.code={\let\robExt@compile@parallel@after\undefined},
  if windows/.code={%
    \robExtIfWindowsTF{\pgfkeysalso{zx@tmp@key/.estyle={\unexpanded{#1}},zx@tmp@key}}{}%
  },
  if unix/.code={%
    \robExtIfWindowsTF{}{\pgfkeysalso{zx@tmp@key/.estyle={\unexpanded{#1}},zx@tmp@key}}%
  },
  compile in parallel command/.store in=\robExt@compile@parallel@command,
  % Different backends to compile in parallel
  compile in parallel with gnu parallel/.style={
    compile in parallel command={parallel --jobs #1 :::: '\jobname-\robExtAddPrefixName{compile-missing-figures.sh}'},
  },
  compile in parallel with gnu parallel/.default={200\%},
  compile in parallel with xargs/.style={
    % Use " instead of ' as Windows does not consider ' as a valid surrounding for strings
    compile in parallel command={xargs -t -I "{}" -P #1 \robExtParallelShell\space "{}" < "\jobname-\robExtAddPrefixName{compile-missing-figures.sh}"},
  },
  % With 0 it spawns as many shells at possible, i.e. it compiles all 200 pictures at the same time, making the
  % system a laggy, and it is actually *slower* (2:05mn vs 1:15mn) than when using 16 threads.
  compile in parallel with xargs/.default={16},
  % By default, we compile with xargs and 16 processes:
  compile in parallel with xargs,
}

\ExplSyntaxOn
\int_new:N \g__robExt_number_figures_just_compiled_or_to_compile
\int_set:Nn \g__robExt_number_figures_just_compiled_or_to_compile {0}
% Will hold the list of input files to compile in parallel. This is needed to
% check at the end to find the processes that failed to build.
\seq_new:N \g__robExt_files_compiled_in_parallel

\AfterLastShipout{
  % Check if we want to run stuff in parallel
  \ifdefined\robExt@compile@parallel@after
    % Check if we must compile
    \ifdefined\robExt@compile@parallel@must@compile
      % Check if we can compile
      \bool_if:nTF { \sys_if_shell_unrestricted_p: || \cs_if_exist_p:N \robExtForceCompilation}
      {
        % Check if a command was provided
        \ifdefined\robExtParallelShell\else
          \sys_if_platform_windows:TF {
            \def\robExtParallelShell{cmd~/C}
          }{
            \def\robExtParallelShell{sh~-c}
          }
        \fi
        % We close the file or reading it is empty
        \iow_close:N \g__robExt_write_manually_compile_all_missing_figures_iow
        \msg_warning:nnx{robExt}{rerun because parallel}{\robExt@compile@parallel@command}
        \message{\robExt@compile@parallel@command}
        \sys_shell_now:x {\robExt@compile@parallel@command}
        % We check if some files failed to compile
        \seq_map_inline:Nn \g__robExt_files_compiled_in_parallel {
          \message{#1}
          \file_if_exist:xTF{#1.pdf}{}{
            \msg_error:nnxxx{robExt}{missing compiled pdf parallel}{#1}{\use:c {g__robExt_lines_error_#1:}}{\use:c {g__robExt_compilation_command_#1:}}
          }
        }
      } {
        \ifdefined\robExtFallbackManualMode
          \msg_warning:nn{robExt}{enabled parallel no shell escape}
        \else
          \msg_error:nn{robExt}{need shell escape parallel}
        \fi
      }
    \fi
  \fi
}
\ExplSyntaxOff

% Not really made for the end user
% It assumes that __ROBEXT_COMPILATION_COMMAND__ and __ROBEXT_TEMPLATE__ is set
\NewDocumentCommand{\robExtEvaluateCompileAndInclude}{}{%
  \ifdefined\robExtDisableExternalization%
    \pgfkeys{%
      /robExt/.cd,
      command if no externalization,
    }%
  \else%
    \pgfkeys{%
      /robExt/.cd,
      command if externalization,
    }%
    \ifdefined\robExtExecuteBefore\robExtExecuteBefore\fi%
    \robExtWriteFile{}%
    \robExtCompileFile{}%
    \robExtIncludeFile{}%
    \ifdefined\robExtExecuteNamedOutput\robExtExecuteNamedOutput\fi%
    \ifdefined\robExtExecuteAfter\robExtExecuteAfter\fi%
  \fi%
  \message{Finished to include the file.}%
}


%% #1: Arguments, #2: content to externalize
\NewDocumentCommand{\robExtCacheMe}{O{}m}{%
  {% Group
    %% We store the input in a non-string element for efficiently implementing "auto forward"
    \edef\robExtUserInputCacheMe{\unexpanded{#2}}% \unexpanded is needed if the macro contains a #1
    \pgfkeys{%
      /robExt/.cd,%
      set placeholder={__ROBEXT_MAIN_CONTENT_ORIG__}{#2},%
      default style,%
      #1,
    }%
    \robExtEvaluateCompileAndInclude%
  }%
}
\let\cacheMe\robExtCacheMe

%% #1: Arguments, #2: content to externalize
\NewDocumentEnvironment{RobExtCacheMe}{m+b}{%
  \robExtCacheMe[#1]{#2}%
}{}
\let\CacheMe\RobExtCacheMe
\let\endCacheMe\endRobExtCacheMe

\NewDocumentEnvironment{RobExtCacheMeCode}{m}{%
  \RobExtPlaceholderFromCode{__ROBEXT_MAIN_CONTENT_ORIG__}%
}{%
  \endRobExtPlaceholderFromCode%
  \pgfkeys{%
    /robExt/.cd,%
    #1,%
  }%
  \robExtEvaluateCompileAndInclude%
}
\let\CacheMeCode\RobExtCacheMeCode
\let\endCacheMeCode\endRobExtCacheMeCode

\NewDocumentEnvironment{RobExtCacheMeNoContent}{+b}{%
  \robExtCacheMe[#1]{}%
}{}
\let\CacheMeNoContent\RobExtCacheMeNoContent
\let\endCacheMeNoContent\endRobExtCacheMeNoContent


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Forward a macro %%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% In this section, we provide commands to forward a macro, like
%% \def\myMacro{stuff}
%% \cacheMe<forward=\myMacro>
%% Note that this will only be forwarded if externalization is enabled (otherwise the macro already exists)
%% I published this code in this answer, thanks to egreg for some pointers
%% https://tex.stackexchange.com/questions/697120/how-to-extract-the-definition-of-a-macro-to-write-in-a-file-for-instance
\ExplSyntaxOn

\cs_new:Nn \__robExt_getCommandDefinitionFromXparse:N
{
  \str_clear_new:N \l__robExt_definition_str
  \GetDocumentCommandArgSpec { #1 }
  \str_set:Nx \l__robExt_definition_str {
    \c_backslash_str DeclareDocumentCommand
    \c_left_brace_str
    \c_backslash_str \cs_to_str:N #1
    \c_right_brace_str
    \c_left_brace_str \ArgumentSpecification \c_right_brace_str
    \c_left_brace_str
    \cs_replacement_spec:c { \cs_to_str:N #1 ~ code }
    \c_right_brace_str
  }%
}

\cs_new:Nn \__robExt_getCommandDefinitionFromDef:N
{
  \str_clear_new:N \l__robExt_definition_str
  \str_set:Nx \l__robExt_definition_str {
    \c_backslash_str def \c_backslash_str \cs_to_str:N #1
    \cs_argument_spec:c { \cs_to_str:N #1 }
    \c_left_brace_str
    \cs_replacement_spec:c { \cs_to_str:N #1 }
    \c_right_brace_str
  }%
}

\def\robExt@extractDefaultNewcommand#1#2#3#4{
  #4%
}%

\cs_new:Nn \__robExt_getCommandDefinitionFromNewcommand:N
{
  \str_clear_new:N \l__robExt_definition_str
  \str_clear_new:N \l__robExt_tmp
  %% \l__robExt_tmp_str will look like [#1]#2#3#4#5#6#7:
  \str_set:Nx \l__robExt_tmp_str {\cs_argument_spec:c { \c_backslash_str \cs_to_str:N #1 }}%
  %% We remove the brackets:
  \str_replace_all:Nnn \l__robExt_tmp_str {[} {}
  \str_replace_all:Nnn \l__robExt_tmp_str {]} {}
  \str_set:Nx \l__robExt_definition_str {
    %% Make sure the command does not exist
    \c_backslash_str providecommand \c_backslash_str \cs_to_str:N #1 \c_left_brace_str \c_right_brace_str
    %% this line will be like "\newdocumentcommand{\mymacro}"
    \c_backslash_str renewcommand \c_left_brace_str \c_backslash_str \cs_to_str:N #1 \c_right_brace_str
    %% It must have at least one argument, since elements without optional arguments are turned into \def
    %% Moreover, macros can't have more than 1 argument, so it will be easier to parse, we just need the last digit
    [\str_range:Nnn \l__robExt_tmp_str {-1} {-1}] %% <- this is the number of mandatory arguments
    [\expandafter \robExt@extractDefaultNewcommand #1 ] %% <- this is the value of the default argument
    \c_left_brace_str
    \cs_replacement_spec:c { \c_backslash_str \cs_to_str:N #1 }
    \c_right_brace_str
  }%
}

% \robExtGetCommandDefinitionInMacro{\myMacro} will populate
% \l__robExt_definition_str and \robExtDefinitionCommand
% with a string to execute to write it properly.
\NewDocumentCommand{\robExtGetCommandDefinitionInMacro}{m}{
  \cs_if_exist:NTF #1 {
    \cs_if_exist:cTF {\cs_to_str:N #1 ~ code}{
      % xparse-based definition
      \__robExt_getCommandDefinitionFromXparse:N #1%
    } {
      \cs_if_exist:cTF {\c_backslash_str \cs_to_str:N #1}{
        % \newcommand-based definition
        \__robExt_getCommandDefinitionFromNewcommand:N #1
      }{
        % \def-based definition
        \__robExt_getCommandDefinitionFromDef:N #1
      }
    }
  }{
    \msg_error:nn{robExt}{The~macro~#1~does~not~exist}
  }
  \let\robExtDefinitionCommand\l__robExt_definition_str
}

\NewDocumentCommand{\robExtGetCommandDefinition}{m}{%
  \robExtGetCommandDefinitionInMacro{#1}%
  \l__robExt_definition_str%
}
\ExplSyntaxOff

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%% Default presets %%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% We create here a few presets and placeholders useful later

%%%%%%
%%%%%% Group "special characters"
%%%%%%

%%%% Generic placeholders, practical to escape stuff
\robExtClearGroupPlaceholders{main}
\ExplSyntaxOn
\robExtPlaceholderFromString{__ROBEXT_LEFT_BRACE__}{\c_left_brace_str}
\robExtPlaceholderFromString{__ROBEXT_RIGHT_BRACE__}{\c_right_brace_str}
\robExtPlaceholderFromString{__ROBEXT_BACKSLASH__}{\c_backslash_str}
\robExtPlaceholderFromString{__ROBEXT_HASH__}{\c_hash_str}
\robExtPlaceholderFromString{__ROBEXT_PERCENT__}{\c_percent_str}
\robExtPlaceholderFromString{__ROBEXT_UNDERSCORE__}{\c_underscore_str}
\ExplSyntaxOff
\robExtCopyGroupPlaceholders{special characters}{main}
\robExtRegisterGroupPlaceholders{special characters}

%%%%%%
%%%%%% Group "latex"
%%%%%%

\robExtClearGroupPlaceholders{main}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_LATEX__}
\documentclass[__ROBEXT_LATEX_OPTIONS__]{__ROBEXT_LATEX_DOCUMENT_CLASS__}
__ROBEXT_LATEX_PREAMBLE__
% most packages must be loaded before hyperref
% so we typically want to load hyperref here
__ROBEXT_LATEX_PREAMBLE_HYPERREF__
% some packages must be loaded after hyperref
__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__
\begin{document}%
__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__
\end{document}
\end{RobExtPlaceholderFromCode}

\robExtSetPlaceholder{__ROBEXT_LATEX_OPTIONS__}{}
\robExtSetPlaceholder{__ROBEXT_LATEX_DOCUMENT_CLASS__}{standalone}
\robExtSetPlaceholder{__ROBEXT_LATEX_PREAMBLE__}{}
\robExtSetPlaceholder{__ROBEXT_LATEX_PREAMBLE_HYPERREF__}{}
\robExtSetPlaceholder{__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__}{}
\robExtSetPlaceholder{__ROBEXT_LATEX_TRIM_LENGTH__}{30cm}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__}
__ROBEXT_LATEX_CREATE_OUT_FILE__%
\newsavebox\boxRobExt%
\begin{lrbox}{\boxRobExt}%
  __ROBEXT_MAIN_CONTENT__%
\end{lrbox}%
\usebox{\boxRobExt}%
__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__%
\end{RobExtPlaceholderFromCode}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_LATEX_CREATE_OUT_FILE__}
%% We save the height/depth of the content by using a savebox:
\newwrite\writeRobExt%
\immediate\openout\writeRobExt=\jobname-out.tex%
\end{RobExtPlaceholderFromCode}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__}
\immediate\write\writeRobExt{%
  \string\def\string\robExtWidth{\the\wd\boxRobExt}%
  \string\def\string\robExtHeight{\the\ht\boxRobExt}%
  \string\def\string\robExtDepth{\the\dp\boxRobExt}%
}%
\end{RobExtPlaceholderFromCode}

%% Compilation commands
\robExtSetPlaceholder{__ROBEXT_LATEX_COMPILATION_COMMAND__}{__ROBEXT_LATEX_ENGINE__ __ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__ "__ROBEXT_SOURCE_FILE__"}
\robExtSetPlaceholder{__ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__}{-halt-on-error}
\robExtSetPlaceholder{__ROBEXT_LATEX_ENGINE__}{pdflatex}

\robExtConfigure{
  %%%% Allow users to specify which command to try (or try first) when replacing placeholders. Order matters.
  %%%% it looks ugly, but it is mostly for performance improvements.
  first placeholders latex/.style={
    first placeholders in compilation command={__ROBEXT_LATEX_COMPILATION_COMMAND__,__ROBEXT_LATEX_ENGINE__,__ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__},
    first placeholders in template={__ROBEXT_LATEX__,__ROBEXT_LATEX_OPTIONS__,__ROBEXT_LATEX_DOCUMENT_CLASS__,__ROBEXT_LATEX_PREAMBLE__,__ROBEXT_LATEX_PREAMBLE_HYPERREF__,__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__,__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__,__ROBEXT_LATEX_TRIM_LENGTH__,__ROBEXT_LATEX_CREATE_OUT_FILE__,__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__,__ROBEXT_MAIN_CONTENT__,__ROBEXT_MAIN_CONTENT_ORIG__},
  },
  only placeholders latex/.style={
    only placeholders in compilation command={__ROBEXT_LATEX_COMPILATION_COMMAND__,__ROBEXT_LATEX_ENGINE__,__ROBEXT_LATEX_COMPILATION_COMMAND_OPTIONS__},
    only placeholders in template={__ROBEXT_LATEX__,__ROBEXT_LATEX_OPTIONS__,__ROBEXT_LATEX_DOCUMENT_CLASS__,__ROBEXT_LATEX_PREAMBLE__,__ROBEXT_LATEX_PREAMBLE_HYPERREF__,__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__,__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__,__ROBEXT_LATEX_TRIM_LENGTH__,__ROBEXT_LATEX_CREATE_OUT_FILE__,__ROBEXT_LATEX_WRITE_DEPTH_TO_OUT_FILE__,__ROBEXT_MAIN_CONTENT__,__ROBEXT_MAIN_CONTENT_ORIG__},
  },
  % some useful presets
  latex/.style={
    enable placeholders,
    % This way it appears before orig in the list: more efficient
    import placeholders from group={latex},
    set placeholder={__ROBEXT_MAIN_CONTENT__}{__ROBEXT_MAIN_CONTENT_ORIG__},
    import placeholder={__ROBEXT_MAIN_CONTENT_ORIG__},
    first placeholders latex,
    set template={__ROBEXT_LATEX__},
    set compilation command={__ROBEXT_LATEX_COMPILATION_COMMAND__},
    %% Configure the latex compilation engine
    use latexmk/.style={
      set placeholder={__ROBEXT_LATEX_ENGINE__}{latexmk},
    },
    use lualatex/.style={
      set placeholder={__ROBEXT_LATEX_ENGINE__}{lualatex},
    },
    use xelatex/.style={
      set placeholder={__ROBEXT_LATEX_ENGINE__}{xelatex},
    },
    set latex options/.style={
      set placeholder={__ROBEXT_LATEX_OPTIONS__}{##1},
    },
    add to latex options/.style={
      add to placeholder no space={__ROBEXT_LATEX_OPTIONS__}{,##1},
    },
    set documentclass/.style={
      set placeholder={__ROBEXT_LATEX_DOCUMENT_CLASS__}{##1},
    },
    set preamble/.style={
      set placeholder={__ROBEXT_LATEX_PREAMBLE__}{##1},
    },
    add to preamble/.style={
      add to placeholder={__ROBEXT_LATEX_PREAMBLE__}{##1},
    },
    add before main content/.style={
      add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{##1},
    },
    add before preamble/.style={
      add before placeholder={__ROBEXT_LATEX_PREAMBLE__}{##1},
    },
    set preamble hyperref/.style={
      set placeholder={__ROBEXT_LATEX_PREAMBLE_HYPERREF__}{##1},
    },
    add to preamble hyperref/.style={
      add to placeholder={__ROBEXT_LATEX_PREAMBLE_HYPERREF__}{##1},
    },
    set preamble after hyperref/.style={
      set placeholder={__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__}{##1},
    },
    add to preamble after hyperref/.style={
      add to placeholder={__ROBEXT_LATEX_PREAMBLE_AFTER_HYPERREF__}{##1},
    },
    do not wrap code/.style={
      set placeholder={__ROBEXT_LATEX_MAIN_CONTENT_WRAPPED__}{__ROBEXT_MAIN_CONTENT__},
    },    
    add to includegraphics options={trim=__ROBEXT_LATEX_TRIM_LENGTH__ __ROBEXT_LATEX_TRIM_LENGTH__ __ROBEXT_LATEX_TRIM_LENGTH__ __ROBEXT_LATEX_TRIM_LENGTH__},
    add to latex options={margin=__ROBEXT_LATEX_TRIM_LENGTH__},
    do not add margins/.style={
      set placeholder={__ROBEXT_LATEX_TRIM_LENGTH__}{0cm}
    },
  },
  % U
  tikz/.style={
    latex,
    add to preamble={\usepackage{tikz}},
  },
  tikzpicture/.style={
    tikz,
    set placeholder no import={__ROBEXT_MAIN_CONTENT__}{\begin{tikzpicture}__ROBEXT_MAIN_CONTENT_ORIG__\end{tikzpicture}},
  },
}


\robExtCopyGroupPlaceholders{latex}{main}
\robExtRegisterGroupPlaceholders{latex}


%%%%%% 
%%%%%% Group "python"
%%%%%%

\robExtClearGroupPlaceholders{main}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_PYTHON__}
__ROBEXT_PYTHON_IMPORT__
__ROBEXT_PYTHON_MAIN_CONTENT_WRAPPED__
\end{RobExtPlaceholderFromCode}

\robExtSetPlaceholder{__ROBEXT_PYTHON_IMPORT__}{}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_PYTHON_MAIN_CONTENT_WRAPPED__}
# This file will be loaded in latex. Useful to pass data to the main document
f_out_write = open("__ROBEXT_OUTPUT_PREFIX__-out.tex", "w")

import os
import sys

def write_to_out(text):
    """Write to the -out.tex file that is loaded by default"""
    f_out_write.write(text)

def parse_args():
    args = {}
    if len(sys.argv) % 2 == 0:
        print("Error: the number of arguments must be even, as tuples of name and value")
        exit(1)
    for i in range(0,len(sys.argv)-1,2):
        args[sys.argv[i+1]] = sys.argv[i+2]
    return args

def get_cache_folder():
    '''
    Path of the cache folder. Warning: this works only when the python script
    is located in this cache folder (that should be true when it's called from LaTeX)
    '''
    return os.path.abspath(os.path.dirname(sys.argv[0])) 

def get_file_base():
    '''
    Outputs the base of the files (i.e. something like robExt-somehash, without any extension)
    '''
    return os.path.splitext(os.path.basename(sys.argv[0]))[0] # __file__ does not work as it refers to the library

def get_current_script():
    '''
    Outputs the path of the current script
    '''
    return os.path.abspath(sys.argv[0]) # __file__ does not work as it refers to the library

    
def get_filename_from_extension(extension):
    '''
    If you want to create a file with extension 'extension' (with the appropriate base name), this command
    is for you. For instance get_filename_from_extension(".mp4") would return something like
    robExt-somehash.mp4
    the extension can also be like get_filename_from_extension("-out.tex") etc.
    '''
    return os.path.join(get_cache_folder(), get_file_base() + extension)

def get_verbatim_output():
    '''Returns the path to -out.txt that is read by verbatim output'''    
    return get_filename_from_extension("-out.txt")

def get_pdf_output():
    '''Returns the path to -out.txt that is read by verbatim output'''    
    return get_filename_from_extension(".pdf")

    
def finished_with_no_error():
    '''
    Call this at the end of your script. This creates the path of the final pdf file that should be
    created (otherwise robust-externalize will think that the compilation failed)
    '''
    if not os.path.exists(get_filename_from_extension(".pdf")):
        # we create an empty path
        with open(get_filename_from_extension(".pdf"), 'w') as f:
            pass

### Starting main content
__ROBEXT_MAIN_CONTENT__
### Ending main content
__ROBEXT_PYTHON_FINISHED_WITH_NO_ERROR__
f_out_write.close()
\end{RobExtPlaceholderFromCode}

% It is annoying to manually call finished_with_no_error(), but it is handy to be able to disable it.
\begin{RobExtPlaceholderFromCode}{__ROBEXT_PYTHON_FINISHED_WITH_NO_ERROR__}
finished_with_no_error()
\end{RobExtPlaceholderFromCode}

%% On windows, python3 does not exist, and python points to python3. On linux, it seems to depend, at least on
%% my system it points to python3 as well.
\robExtSetPlaceholder{__ROBEXT_PYTHON_EXEC__}{python}

\robExtConfigure{
  python/.style={
    enable placeholders,
    import placeholders={__ROBEXT_PYTHON__,__ROBEXT_PYTHON_IMPORT__,__ROBEXT_PYTHON_MAIN_CONTENT_WRAPPED__,__ROBEXT_PYTHON_FINISHED_WITH_NO_ERROR__,__ROBEXT_PYTHON_EXEC__},
    set compilation command={__ROBEXT_PYTHON_EXEC__ "__ROBEXT_SOURCE_FILE__"},
    set template={__ROBEXT_PYTHON__},
    print verbatim if no externalization,
    force python3/.style={
      set placeholder={__ROBEXT_PYTHON_EXEC__}{python3}
    },
    add import/.style={
      add to placeholder no space={__ROBEXT_PYTHON_IMPORT__}{##1^^J},
    },
  }
}

\robExtCopyGroupPlaceholders{python}{main}
\robExtRegisterGroupPlaceholders{python}


%%%%%% 
%%%%%% Group "python print code result"
%%%%%%

\robExtClearGroupPlaceholders{main}

%% A style to print both the code and the result:
\begin{RobExtPlaceholderFromCode}{__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_BEFORE__}
# File where print("bla") should be redirected
# get_filename_from_extension("-foo.txt") will give you the path of the file
# in the cache that looks like robExt-somehash-foo.txt
print_file = open(get_filename_from_extension("-print.txt"),  "w")
sys.stdout = print_file
# This code will read the current code, and extract the lines between
# that starts with "### CODESTARTSHERE" and "### CODESTOPSHERE", and will write
# it into the *-code.text (we do not want to print all these functions in
# the final code)
with open(get_filename_from_extension("-code.txt"), "w") as f:
    # The current script has extension .tex
    with open(get_current_script(), "r") as script:
        should_write = False
        for line in script:
            if line.startswith("### CODESTARTSHERE"):
                should_write = True
            elif line.startswith("### CODESTOPSHERE"):
                should_write = False
            elif "HIDEME" in line:
                pass
            else:
                if should_write:
                    f.write(line)
### CODESTARTSHERE
\end{RobExtPlaceholderFromCode}


\begin{RobExtPlaceholderFromCode}{__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_AFTER__}
### CODESTOPSHERE
print_file.close()
\end{RobExtPlaceholderFromCode}

\robExtSetPlaceholder{__ROBEXT_PYTHON_TCOLORBOX_PROPS__}{colback=red!5!white,colframe=red!75!black}
\robExtSetPlaceholder{__ROBEXT_PYTHON_CODE_MESSAGE__}{}
\robExtSetPlaceholder{__ROBEXT_PYTHON_RESULT_MESSAGE__}{Output:}
\robExtSetPlaceholder{__ROBEXT_PYTHON_LSTINPUT_STYLE__}{frame=single, breakindent=.5\textwidth, frame=single, breaklines=true, style=mypython}

\robExtConfigure{
  python print code and result/.style={
    python,
    import placeholders={__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_BEFORE__,__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_AFTER__,__ROBEXT_PYTHON_TCOLORBOX_PROPS__,__ROBEXT_PYTHON_CODE_MESSAGE__,__ROBEXT_PYTHON_RESULT_MESSAGE__,__ROBEXT_PYTHON_LSTINPUT_STYLE__},
    add before placeholder no space={__ROBEXT_MAIN_CONTENT__}{__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_BEFORE__},
    add to placeholder no space={__ROBEXT_MAIN_CONTENT__}{__ROBEXT_PYTHON_PRINT_CODE_RESULT_TEMPLATE_AFTER__},
    set title/.style={
      set placeholder={__MY_TITLE__}{##1},
    },
    set title={Python code},
    custom include command={
      % Useful to replace __MY_TITLE__:
      \evalPlaceholder{
        \begin{tcolorbox}[title=__MY_TITLE__,__ROBEXT_PYTHON_TCOLORBOX_PROPS__]
          __ROBEXT_PYTHON_CODE_MESSAGE__%
          \lstinputlisting[__ROBEXT_PYTHON_LSTINPUT_STYLE__]{\robExtAddCachePathAndName{\robExtFinalHash-code.txt}}
          __ROBEXT_PYTHON_RESULT_MESSAGE__%
          \verbatiminput{\robExtAddCachePathAndName{\robExtFinalHash-print.txt}}
        \end{tcolorbox}
      }
    },
  },
}

\robExtCopyGroupPlaceholders{python print code result}{main}
\robExtRegisterGroupPlaceholders{python print code result}


%%%%%% 
%%%%%% Group "verbatim"
%%%%%%

\robExtClearGroupPlaceholders{main}

\robExtConfigure{
  verbatim text/.style={
    enable placeholders,
    set template={__ROBEXT_MAIN_CONTENT__},
    custom include command={\evalPlaceholder{\verbatiminput{\robExtAddCachePathAndName{\robExtFinalHash.tex}}}},
    %% Apparently this works on windows as well https://stackoverflow.com/questions/1702762/how-can-i-create-an-empty-file-at-the-command-line-in-windows
    set compilation command={echo "" > __ROBEXT_OUTPUT_PDF__},
  },
  verbatim text no include/.style={
    verbatim text,
    custom include command={\evalPlaceholder{%
        \xdef\robExtPathToInput{\robExtAddCachePathAndName{\robExtFinalHash.tex}}%
      }%
    }%
  },
}

\robExtCopyGroupPlaceholders{verbatim}{main}
\robExtRegisterGroupPlaceholders{verbatim}


%%%%%% 
%%%%%% Group "bash"
%%%%%%

\robExtClearGroupPlaceholders{main}

\begin{RobExtPlaceholderFromCode}{__ROBEXT_BASH_TEMPLATE__}
# Quit if there is an error
set -e
outputTxt="__ROBEXT_OUTPUT_PREFIX__-out.txt"
outputTex="__ROBEXT_OUTPUT_PREFIX__-out.tex"
outputPdf="__ROBEXT_OUTPUT_PDF__"
__ROBEXT_MAIN_CONTENT__
# Create the pdf file to certify that no compilation error occured
touch "${outputPdf}"
\end{RobExtPlaceholderFromCode}

\robExtSetPlaceholder{__ROBEXT_BASH_SHELL__}{bash}

\robExtConfigure{
  bash/.style={
    enable placeholders,
    import placeholders={__ROBEXT_BASH_TEMPLATE__,__ROBEXT_BASH_SHELL__},
    set compilation command={__ROBEXT_BASH_SHELL__ "__ROBEXT_SOURCE_FILE__"},
    set template={__ROBEXT_BASH_TEMPLATE__},
    print verbatim if no externalization,
  }
}

\robExtCopyGroupPlaceholders{bash}{main}
\robExtRegisterGroupPlaceholders{bash}

%%%%%% 
%%%%%% Group "default", available in all styles
%%%%%%

\robExtClearGroupPlaceholders{main}

% This additional level of indirection is made to allow an easier wrapping
% of \begin{tikzpicture} ... \end{tikzpicture} for instance.
% The original behavior (modify __ROBEXT_MAIN_CONTENT__ directly)
% was not really practical as if you use both |tikz| and |\cacheCommand|, it would wrap
% the environment twice.
\robExtSetPlaceholder{__ROBEXT_MAIN_CONTENT__}{__ROBEXT_MAIN_CONTENT_ORIG__}
\setPlaceholder{__ROBEXT_INCLUDEGRAPHICS_OPTIONS__}{}
\setPlaceholder{__ROBEXT_INCLUDEGRAPHICS_FILE__}{\robExtAddCachePathAndName{\robExtFinalHash.pdf}}

\robExtConfigure{
  % Allow nice optimizations
  all placeholders have underscores,
  set includegraphics options/.style={
    set placeholder no import={__ROBEXT_INCLUDEGRAPHICS_OPTIONS__}{#1},
  },
  add to includegraphics options/.style={
    add to placeholder no space no import={__ROBEXT_INCLUDEGRAPHICS_OPTIONS__}{,#1},
  },
  set placeholder no import={__ROBEXT_VERBATIM_COMMAND__}{\verbatiminput},
  % We expect the program to write in __ROBEXT_OUTPUT_PREFIX__-out.txt
  verbatim output/.style={
    import placeholders={__ROBEXT_VERBATIM_COMMAND__},
    custom include command={%
      \evalPlaceholder{%
        __ROBEXT_VERBATIM_COMMAND__{__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__-out.txt}%
      }%
    },
  },
  % Mostly for debugging purpose
  print command and source/.style={
    enable manual mode,
    custom include command advanced={%
      \evalPlaceholder{%
        Command: (run in folder \texttt{__ROBEXT_CACHE_FOLDER__})
        \robExtPrintPlaceholder{__ROBEXT_COMPILATION_COMMAND__}
        Dependencies:
        \verbatiminput{__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__.deps}%
        Source (in \texttt{__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__.tex}):
        \verbatiminput{__ROBEXT_CACHE_FOLDER____ROBEXT_OUTPUT_PREFIX__.tex}%
      }%
    },
  },
  debug/.style={
    print command and source
  },
}


\robExtCopyGroupPlaceholders{default}{main} % we do not reset it as it will be the default imported group
\robExtRegisterGroupPlaceholders{default}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%% Automatically cache environments, tikzpicture etc %%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%% 
%%%%%% Parse tikz
%%%%%%

%% The parser is mostly taken from
%% https://github.com/sasozivanovic/memoize/blob/master/memoize-tikz.tex

\newtoks\robExt@temptoks
\def\robExt@apptotoks#1#2{\expandafter#1\expandafter{\the#1#2}}

\def\robExt@tikz{%
  \robExt@temptoks={}%
  \robExt@tikz@anim%
}
\def\robExt@tikz@anim{%
  \pgfutil@ifnextchar[{\robExt@tikz@opt}{%
    \pgfutil@ifnextchar:{\robExt@tikz@anim@a}{%
      \robExt@tikz@code}}%]
}%
\def\robExt@tikz@anim@a#1=#2{%
  \robExt@apptotoks\robExt@temptoks{#1={#2}}%
  \robExt@tikz@anim%
}%
\def\robExt@tikz@opt[#1]{%
  \robExt@apptotoks\robExt@temptoks{[#1]}%
  \robExt@tikz@code%
}
\def\robExt@tikz@code{%
  \pgfutil@ifnextchar\bgroup\robExt@tikz@braced\robExt@tikz@single%
}
\def\robExt@tikz@braced#1{\robExt@apptotoks\robExt@temptoks{{#1}}\robExt@tikz@done}
\def\robExt@tikz@single#1;{\robExt@apptotoks\robExt@temptoks{#1;}\robExt@tikz@done}
\def\robExt@tikz@done{%
  \edef\robExt@marshal{%
    \noexpand\robExtRescanHashRobust{\noexpand\robExtCacheMe[\expandonce{\robExt@tmp@orig@args}, \expandonce{\robExt@tmp@args}]{%
        \noexpand\tikz\the\robExt@temptoks%
      }%
    }%
  }%
  \robExt@marshal%
}

\NewDocumentCommand{\robExtExternalizeAllTikzpictures}{O{tikz}O{tikzpicture}O{<>}}{%
  \robExtCacheEnvironment[#3]{tikzpicture}{#2}%
  % Tikz has a more complicated parsing system
  \DeclareCommandCopy{\robExtCommandOrigtikz}{\tikz}% we save the function for later reset
  \robExtAddToCommandResetList{tikz}% we add it to the list of functions to reset
  \DeclareDocumentCommand{\tikz}{D#3{}}{%
    \def\robExtCommandOrigName{tikz}% we specify the name of the current environment
    \edef\robExt@tmp@args{\detokenize{##1}}% we specify the name of the current environment
    \edef\robExt@tmp@orig@args{\detokenize{#1}}% we specify the name of the current environment
    % we start the parsing
    \robExt@tikz%
  }%
}
\let\cacheTikz\robExtExternalizeAllTikzpictures

%% The cached version
\DeclareDocumentEnvironment{tikzpictureC}{D<>{}O{}O{}}{%
  \begin{CacheMe}{tikzpicture,#1}[#2]%
}{\end{CacheMe}}%

%%%%%% 
%%%%%% The generic functions
%%%%%%

%% Usage: \robExtCacheEnvironment{myenv}
\NewDocumentCommand{\robExtCacheEnvironment}{O{<>}mm}{%
  %% We need to save the original environment to avoid infinite recursion if we disable externalization
  %% https://tex.stackexchange.com/questions/695391/why-isnt-my-environment-restored/695398
  \NewEnvironmentCopy{robExtEnvironmentOrig#2}{#2}%
  \robExtAddToEnvironmentResetList{#2}%
  \DeclareDocumentEnvironment{#2}{D#1{}}{%
    \def\robExtEnvironmentOrigName{#2}%
    \CacheMe{%
      #3,%
      set placeholder no import={__ROBEXT_MAIN_CONTENT__}{\begin{#2}__ROBEXT_MAIN_CONTENT_ORIG__\end{#2}},%
      ##1%
    }%
  }{\endCacheMe}%
}
\let\cacheEnvironment\robExtCacheEnvironment

% \robExtShowPlaceholder{__ROBEXT_MAIN_CONTENT__}
% \robExtShowPlaceholdersContents
%%%% Borrowed and adapted from https://github.com/sasozivanovic/memoize/blob/master/xparse-arglist.sty
%%%% see also https://tex.stackexchange.com/questions/695662/automatically-wrap-a-macro/695734
%% The idea of the library is that it builds a string like
%% [#2]<#3>{#4}
%% in order to generate something like
%% \NewDocumentCommand{\myfunction}{D<>{}O{coucou}D<>{yes}m}
%% {
%%  \cacheMe[#1]{\myfunction[#2]<#3>{#4}}
%% }
%%%%   _________________________________________________________________

\def\robExtArgumentList{%
  \expandafter\robExt@arglist\expandafter0\ArgumentSpecification.%
}

\def\robExt@arglist#1#2{%
  \ifcsname robExt@arglist@#2\endcsname
    \csname robExt@arglist@#2\expandafter\expandafter\expandafter\endcsname
  \else
    \expandafter\robExt@arglist@error
  \fi
  \expandafter{\the\numexpr#1+1\relax}%
}

% \robExt@arglist@...: #1 = the argument number
\def\robExt@arglist@m#1{\noexpand\unexpanded{{#####1}}\robExt@arglist{#1}}
\def\robExt@arglist@r#1#2#3{\noexpand\unexpanded{#2#####1#3}\robExt@arglist{#1}}
\def\robExt@arglist@R#1#2#3#4{\noexpand\unexpanded{#2#####1#3}\robExt@arglist{#1}}
\def\robExt@arglist@v#1{{Handled commands with verbatim arguments are not
    supported}\robExt@arglist{#1}} % error
\def\robExt@arglist@b#1{{This is not the way to handle
    environment}\robExt@arglist{#1}} % error
\def\robExt@arglist@o#1{\noexpand\unexpanded{[#####1]}\robExt@arglist{#1}}
\def\robExt@arglist@d#1#2#3{\noexpand\unexpanded{#2#####1#3}\robExt@arglist{#1}}
\def\robExt@arglist@O#1#2{\noexpand\unexpanded{[#####1]}\robExt@arglist{#1}}
% \def\robExt@arglist@O#1#2{\noexpand\unexpanded{[#####1]}\robExt@arglist{#1}}
\def\robExt@arglist@D#1#2#3#4{\noexpand\unexpanded{#2#####1#3}\robExt@arglist{#1}}
\def\robExt@arglist@s#1{\noexpand\IfBooleanT{#####1}{*}\robExt@arglist{#1}}
\def\robExt@arglist@t#1#2{\noexpand\IfBooleanT{#####1}{#2}\robExt@arglist{#1}}
\csdef{robExt@arglist@+}#1{\expandafter\robExt@arglist\expandafter{\the\numexpr#1-1\relax}}%
\csdef{robExt@arglist@.}#1{}
% e,E: Embellishments are not supported.
% > Argument processors are not supported. And how could they be?
\def\robExt@arglist@error#1.{{Unknown argument type}}
%%%% _________________________________________________________________

%% Since the very first occurrence of D is not forwarded to the function
%% we discard it:
%% The first argument of \robExt@arglist@D is the number of the argument
%% so #2#####1#3 reads as #2 = <, #### = #, #1 = > #3 = default value that can be discarded since it is already part of the argument spec.

\def\robExt@arglist@D#1#2#3#4{%
  \noexpand\unexpanded{%
    \ifnum #1=1 % If it is the first argument D, then we do not add anything to the argument string
    \else #2#####1#3\fi}\robExt@arglist{#1}%
}

%% Usage: \robExtCacheCommand[delimiters]{name command}[argument specification]{style}
%% Inspired and modified from
%% https://github.com/sasozivanovic/memoize/blob/81d960aa547148bdb38fea89917eda1476c9bace/memoize.sty#L744
\NewDocumentCommand{\robExtCacheCommand}{O{<>}mom}{%
  %% We get the specification of the command, like "O{}mm"
  \IfNoValueTF{#3}{%
    \expandafter\GetDocumentCommandArgSpec\csname #2\endcsname%
  }{%
    \def\ArgumentSpecification{#3}%
  }%
  \edef\ArgumentSpecification{D#1{}\ArgumentSpecification}%
  \robExtAddToCommandResetList{#2}%
  % We copy the original definition for later (if externalization is disabled)
  \expandafter\DeclareCommandCopy\csname robExtCommandOrig#2\expandafter\endcsname\csname #2\endcsname%
  \edef\robExt@marshal{%
    \noexpand\DeclareDocumentCommand%
      \expandonce{\csname #2\endcsname}%
      {\expandonce{\ArgumentSpecification}}%
      {%
        \noexpand\def\noexpand\robExtCommandOrigName{#2}%
        % todo: add a hook for users setup; prevent user from changing \MemoizeWrapper?
        \edef\noexpand\robExt@marshal{%
        \noexpand\noexpand\noexpand\robExtRescanHashRobust{\noexpand\noexpand\noexpand\robExtCacheMe[\detokenize{#4}, \noexpand\detokenize{####1}]{%
          \noexpand\noexpand\expandonce{\csname #2\endcsname}%
            \robExtArgumentList%
          }%
        }%
      }%
      % For debug
      %\noexpand\show\noexpand\robExt@marshal%
      \noexpand\robExt@marshal%
    }%
  }%
  % for debug
  %\show\robExt@marshal%
  \robExt@marshal%
}
\let\cacheCommand\robExtCacheCommand