summaryrefslogtreecommitdiff
path: root/helm.el
blob: 1d4dbf9c1bbaa872d43c4217713996238e643ef8 (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
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
;;; helm.el --- Emacs incremental and narrowing framework -*- lexical-binding: t -*-

;; Version: 3.6.2
;; URL: https://github.com/emacs-helm/helm

;; Copyright (C) 2007         Tamas Patrovics
;;               2008 ~ 2011  rubikitch <rubikitch@ruby-lang.org>
;;               2011 ~ 2019  Thierry Volpiatto <thierry.volpiatto@gmail.com>

;; This is a fork of anything.el wrote by Tamas Patrovics.

;; Authors of anything.el: Tamas Patrovics
;;                         rubikitch <rubikitch@ruby-lang.org>
;;                         Thierry Volpiatto <thierry.volpiatto@gmail.com>

;; Author: Thierry Volpiatto <thierry.volpiatto@gmail.com>
;; URL: http://github.com/emacs-helm/helm

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Code:

(require 'cl-lib)
(require 'async)
(require 'helm-lib)
(require 'helm-multi-match)
(require 'helm-source)
;; Soft require this as it is not bundled with helm-core package.
(require 'helm-global-bindings nil t)

;; Ensure async-bytecomp is used even with helm-core package.
(declare-function async-bytecomp-package-mode "ext:async-bytecomp.el")
(when (require 'async-bytecomp nil t)
  (and (fboundp 'async-bytecomp-package-mode)
       (async-bytecomp-package-mode 1)))

;; Setup completion styles for helm-mode
(helm--setup-completion-styles-alist)

(declare-function helm-comp-read "helm-mode.el")
(declare-function custom-unlispify-tag-name "cus-edit.el")

(defvar helm-marked-buffer-name)

;; Easy access to customize
;;;###autoload
(defun helm-configuration ()
  "Customize Helm."
  (interactive)
  (customize-group "helm"))

;;; Multi keys
;;
;;
;;;###autoload
(defun helm-define-multi-key (keymap key functions &optional delay)
  "In KEYMAP, define key sequence KEY for function list FUNCTIONS.
Each function runs sequentially for each KEY press.
If DELAY is specified, switch back to initial function of FUNCTIONS list
after DELAY seconds.
The functions in FUNCTIONS list take no args.
E.g.
    (defun foo ()
      (interactive)
      (message \"Run foo\"))
    (defun bar ()
      (interactive)
      (message \"Run bar\"))
    (defun baz ()
      (interactive)
      (message \"Run baz\"))

\(helm-define-multi-key global-map (kbd \"<f5> q\") '(foo bar baz) 2)

Each time \"<f5> q\" is pressed, the next function is executed.
Waiting more than 2 seconds between key presses switches back to
executing the first function on the next hit."
  (define-key keymap key (helm-make-multi-command functions delay)))

;;;###autoload
(defmacro helm-multi-key-defun (name docstring funs &optional delay)
  "Define NAME as a multi-key command running FUNS.
After DELAY seconds, the FUNS list is reinitialized.
See `helm-define-multi-key'."
  (declare (indent 2))
  (setq docstring (if docstring (concat docstring "\n\n")
                    "This is a helm-ish multi-key command."))
  `(defalias (quote ,name) (helm-make-multi-command ,funs ,delay) ,docstring))

(defun helm-make-multi-command (functions &optional delay)
  "Return an anonymous multi-key command running FUNCTIONS.
Run each function in the FUNCTIONS list in turn when called within DELAY seconds."
  (declare (indent 1))
  (let ((funs functions)
        (iter (cl-gensym "helm-iter-key"))
        (timeout delay))
    (eval (list 'defvar iter nil))
    (lambda ()
      (interactive)
      (helm-run-multi-key-command funs iter timeout))))

(defun helm-run-multi-key-command (functions iterator delay)
  (let ((fn (lambda ()
              (cl-loop for count from 1 to (length functions)
                       collect count)))
        next)
    (unless (and (symbol-value iterator)
                 ;; Reset iterator when another key is pressed.
                 (eq this-command real-last-command))
      (set iterator (helm-iter-list (funcall fn))))
    (setq next (helm-iter-next (symbol-value iterator)))
    (unless next
      (set iterator (helm-iter-list (funcall fn)))
      (setq next (helm-iter-next (symbol-value iterator))))
    (and next (symbol-value iterator)
         (call-interactively (nth (1- next) functions)))
    (when delay (run-with-idle-timer
                 delay nil (lambda ()
                             (set iterator nil))))))

(helm-multi-key-defun helm-toggle-resplit-and-swap-windows
    "Multi key command to re-split and swap Helm window.
First call runs `helm-toggle-resplit-window',
and second call within 1s runs `helm-swap-windows'."
  '(helm-toggle-resplit-window helm-swap-windows) 1)
(put 'helm-toggle-resplit-and-swap-windows 'helm-only t)

;;;###autoload
(defun helm-define-key-with-subkeys (map key subkey command
                                         &optional other-subkeys prompt exit-fn)
  "Define in MAP a KEY and SUBKEY to COMMAND.

This allows typing KEY to call COMMAND the first time and
type only SUBKEY on subsequent calls.

Arg MAP is the keymap to use, SUBKEY is the initial short
key binding to call COMMAND.

Arg OTHER-SUBKEYS is an alist specifying other short key bindings
to use once started, e.g.:

    (helm-define-key-with-subkeys global-map
       (kbd \"C-x v n\") ?n 'git-gutter:next-hunk
       '((?p . git-gutter:previous-hunk))\)

In this example, `C-x v n' will run `git-gutter:next-hunk'
subsequent \"n\" will run this command again and subsequent \"p\"
will run `git-gutter:previous-hunk'.

If specified PROMPT can be displayed in minibuffer to describe
SUBKEY and OTHER-SUBKEYS.  Arg EXIT-FN specifies a function to run
on exit.

For any other key pressed, run their assigned command as defined
in MAP and then exit the loop running EXIT-FN, if specified.

NOTE: SUBKEY and OTHER-SUBKEYS bindings support only char syntax
and vectors, so don't use strings to define them."
  (declare (indent 1))
  (define-key map key
    (lambda ()
      (interactive)
      (unwind-protect
          (progn
            (call-interactively command)
            (while (let ((input (read-key prompt)) other kb com)
                     (setq last-command-event input)
                     (cond
                      ((eq input subkey)
                       (call-interactively command)
                       t)
                      ((setq other (assoc input other-subkeys))
                       (call-interactively (cdr other))
                       t)
                      (t
                       (setq kb (vector last-command-event))
                       (setq com (lookup-key map kb))
                       (if (commandp com)
                           (call-interactively com)
                         (setq unread-command-events
                               (nconc (mapcar 'identity kb)
                                      unread-command-events)))
                       nil)))))
        (and exit-fn (funcall exit-fn))))))

;;; Keymap
;;
;;
(defvar helm-map
  (let ((map (make-sparse-keymap)))
    (set-keymap-parent map minibuffer-local-map)
    (define-key map (kbd "<down>")     'helm-next-line)
    (define-key map (kbd "<up>")       'helm-previous-line)
    (define-key map (kbd "C-n")        'helm-next-line)
    (define-key map (kbd "C-p")        'helm-previous-line)
    (define-key map (kbd "<C-down>")   'helm-follow-action-forward)
    (define-key map (kbd "<C-up>")     'helm-follow-action-backward)
    (define-key map (kbd "<prior>")    'helm-previous-page)
    (define-key map (kbd "<next>")     'helm-next-page)
    (define-key map (kbd "M-v")        'helm-previous-page)
    (define-key map (kbd "C-v")        'helm-next-page)
    (define-key map (kbd "M-<")        'helm-beginning-of-buffer)
    (define-key map (kbd "M->")        'helm-end-of-buffer)
    (define-key map (kbd "C-g")        'helm-keyboard-quit)
    (define-key map (kbd "<RET>")      'helm-maybe-exit-minibuffer)
    (define-key map (kbd "C-i")        'helm-select-action)
    (define-key map (kbd "C-j")        'helm-execute-persistent-action)
    (define-key map (kbd "C-o")        'helm-next-source)
    (define-key map (kbd "M-o")        'helm-previous-source)
    (define-key map (kbd "<right>")    'helm-next-source)
    (define-key map (kbd "<left>")     'helm-previous-source)
    (define-key map (kbd "C-l")        'helm-recenter-top-bottom-other-window)
    (define-key map (kbd "M-C-l")      'helm-reposition-window-other-window)
    (define-key map (kbd "C-M-v")      'helm-scroll-other-window)
    (define-key map (kbd "M-<next>")   'helm-scroll-other-window)
    (define-key map (kbd "C-M-y")      'helm-scroll-other-window-down)
    (define-key map (kbd "C-M-S-v")    'helm-scroll-other-window-down)
    (define-key map (kbd "M-<prior>")  'helm-scroll-other-window-down)
    (define-key map (kbd "<C-M-down>") 'helm-scroll-other-window)
    (define-key map (kbd "<C-M-up>")   'helm-scroll-other-window-down)
    (define-key map (kbd "C-@")        'helm-toggle-visible-mark)
    (define-key map (kbd "C-SPC")      'helm-toggle-visible-mark-forward)
    (define-key map (kbd "M-SPC")      'helm-toggle-visible-mark-backward)
    (define-key map (kbd "M-[")        nil)
    (define-key map (kbd "M-(")        'helm-prev-visible-mark)
    (define-key map (kbd "M-)")        'helm-next-visible-mark)
    (define-key map (kbd "C-k")        'helm-delete-minibuffer-contents)
    (define-key map (kbd "C-x C-f")    'helm-quit-and-find-file)
    (define-key map (kbd "M-m")        'helm-toggle-all-marks)
    (define-key map (kbd "M-a")        'helm-mark-all)
    (define-key map (kbd "M-U")        'helm-unmark-all)
    (define-key map (kbd "C-M-a")      'helm-show-all-candidates-in-source)
    (define-key map (kbd "C-M-e")      'helm-display-all-sources)
    (define-key map (kbd "C-s")        'undefined)
    (define-key map (kbd "M-s")        'undefined)
    (define-key map (kbd "C-}")        'helm-narrow-window)
    (define-key map (kbd "C-{")        'helm-enlarge-window)
    (define-key map (kbd "C-c -")      'helm-swap-windows)
    (define-key map (kbd "C-c _")      'helm-toggle-full-frame)
    (define-key map (kbd "C-c %")      'helm-exchange-minibuffer-and-header-line)
    (define-key map (kbd "C-c C-y")    'helm-yank-selection)
    (define-key map (kbd "C-c C-k")    'helm-kill-selection-and-quit)
    (define-key map (kbd "C-c C-i")    'helm-copy-to-buffer)
    (define-key map (kbd "C-c C-f")    'helm-follow-mode)
    (define-key map (kbd "C-c C-u")    'helm-refresh)
    (define-key map (kbd "C-c >")      'helm-toggle-truncate-line)
    (define-key map (kbd "C-c l")      'helm-display-line-numbers-mode)
    (define-key map (kbd "M-p")        'previous-history-element)
    (define-key map (kbd "M-n")        'next-history-element)
    (define-key map (kbd "C-!")        'helm-toggle-suspend-update)
    (define-key map (kbd "C-x b")      'helm-resume-previous-session-after-quit)
    (define-key map (kbd "C-x C-b")    'helm-resume-list-buffers-after-quit)
    (helm-define-key-with-subkeys map (kbd "C-c n") ?n 'helm-run-cycle-resume)
    ;; Disable `file-cache-minibuffer-complete'.
    (define-key map (kbd "<C-tab>")    'undefined)
    ;; Multi keys
    (define-key map (kbd "C-t")        'helm-toggle-resplit-and-swap-windows)
    ;; Debugging command
    (define-key map (kbd "C-h C-d")    'helm-enable-or-switch-to-debug)
    (define-key map (kbd "C-h c")      'helm-customize-group)
    ;; Allow to eval keymap without errors.
    (define-key map [f1] nil)
    (define-key map (kbd "C-h C-h")    'undefined)
    (define-key map (kbd "C-h h")      'undefined)
    (helm-define-key-with-subkeys map
      (kbd "C-w") ?\C-w 'helm-yank-text-at-point
      '((?\C-_ . helm-undo-yank-text-at-point)))
    ;; Use `describe-mode' key in `global-map'.
    (cl-dolist (k (where-is-internal 'describe-mode global-map))
      (define-key map k 'helm-help))
    (define-key map (kbd "C-c ?")    'helm-help)
    ;; Bind all actions from 1 to 12 to their corresponding nth index+1.
    (cl-loop for n from 0 to 12 do
             (define-key map (kbd (format "<f%s>" (1+ n)))
               `(lambda ()
                  (interactive)
                  (helm-select-nth-action ,n))))
    map)
  "Keymap for helm.")

(defun helm-customize-group-1 (group)
  (require 'cus-edit)
  (let ((name (format "*Customize Group: %s*"
                      (custom-unlispify-tag-name group))))
    (if (buffer-live-p (get-buffer name))
        (switch-to-buffer name)
      (custom-buffer-create
       (list (list group 'custom-group))
       name
       (concat " for group "
               (custom-unlispify-tag-name group))))))

(defun helm-customize-group ()
  "Jump to customization group of current source.

Default to Helm group when group is not defined in source."
  (interactive)
  (helm-run-after-exit 'helm-customize-group-1 (helm-attr 'group)))
(put 'helm-customize-group 'helm-only t)

(defun helm--action-at-nth-set-fn-1 (value &optional negative)
  (cl-loop for n from 1 to 9
           for key = (format value n)
           for sym = (make-symbol (format "helm-execute-selection-action-at-nth-+%d" n))
           for fn = `(lambda ()
                       (interactive)
                       (helm-execute-selection-action-at-nth ,(if negative (- n) n)))
           do (progn
                (defalias sym fn)
                (define-key helm-map (kbd key) sym))))

(defun helm--action-at-nth-set-fn- (var val)
  (set var val)
  (helm--action-at-nth-set-fn-1 val 'negative))

(defun helm--action-at-nth-set-fn+ (var val)
  (set var val)
  (helm--action-at-nth-set-fn-1 val))

(defcustom helm-action-at-nth-negative-prefix-key "C-x %d"
  "The prefix key to execute default action on nth <-n> candidate.

This is a format spec where %d will be replaced by the candidate
number.

NOTE: `setq' have no effect until you restart Emacs, use
customize for immediate effect."
  :group 'helm
  :type 'string
  :set #'helm--action-at-nth-set-fn-)

(defcustom helm-action-at-nth-positive-prefix-key "C-c %d"
  "The prefix key to execute default action on nth <+n> candidate.

This is a format spec where %d will be replaced by the candidate
number.

NOTE: `setq' have no effect until you restart Emacs, use
customize for immediate effect."
  :group 'helm
  :type 'string
  :set #'helm--action-at-nth-set-fn+)


(defgroup helm nil
  "Open Helm."
  :prefix "helm-" :group 'convenience)

(defcustom helm-completion-window-scroll-margin 5
  "`scroll-margin' to use for Helm completion window.
Set to 0 to disable.
NOTE: This has no effect when `helm-display-source-at-screen-top'
id is non-nil."
  :group 'helm
  :type  'integer)

(defcustom helm-left-margin-width 0
  "`left-margin-width' value for the `helm-buffer'."
  :group 'helm
  :type 'integer)

(defcustom helm-display-source-at-screen-top t
  "Display candidates at the top of screen.
This happens with `helm-next-source' and `helm-previous-source'.
NOTE: When non-nil (default), disable
`helm-completion-window-scroll-margin'."
  :group 'helm
  :type 'boolean)

(defcustom helm-candidate-number-limit 100
  "Global limit for number of candidates displayed.
When the pattern is empty, the number of candidates shown will be
as set here instead of the entire list, which may be hundreds or
thousands.  Since narrowing and filtering rapidly reduces
available candidates, having a small list will keep the interface
responsive.

Set this value to nil for no limit."
  :group 'helm
  :type '(choice (const :tag "Disabled" nil) integer))

(defcustom helm-input-idle-delay 0.01
  "Idle time before updating, specified in seconds."
  :group 'helm
  :type 'float)

(defcustom helm-exit-idle-delay 0
  "Idle time before exiting minibuffer while Helm is updating.
Has no affect when helm-buffer is up to date \(i.e. exit without
delay in this condition\)."
  :group 'helm
  :type 'float)

(defvaralias 'helm-samewindow 'helm-full-frame)
(make-obsolete-variable 'helm-samewindow 'helm-full-frame "1.4.8.1")
(defcustom helm-full-frame nil
  "Use current window for showing candidates.
If t, then Helm does not pop-up a new window."
  :group 'helm
  :type 'boolean)

(defcustom helm-candidate-separator
  (if (fontp (char-displayable-p (read "#x2015")))
      "――――――――――――――――――――――――――――――――――――――"
    "--------------------------------------")
  "Candidates separator of `multiline' source."
  :group 'helm
  :type 'string)

(defcustom helm-save-configuration-functions
  '(set-window-configuration . current-window-configuration)
  "Functions used to restore or save configurations for frames and windows.
Specified as a pair of functions, where car is the restore
function and cdr is the save function.

To save and restore frame configuration, set this variable to
'\(set-frame-configuration . current-frame-configuration\)

NOTE: This may not work properly with own-frame minibuffer
settings.  Older versions saves/restores frame configuration, but
the default has changed now to avoid flickering."
  :group 'helm
  :type 'sexp)

(defcustom helm-display-function 'helm-default-display-buffer
  "Function used to display `helm-buffer'.

Local value in `helm-buffer' will take precedence on this default
value.  Commands that are in `helm-commands-using-frame' will have
`helm-buffer' displayed in frame, `helm-display-function' being
ignored.
If no local value is found and current command is not one of
`helm-commands-using-frame' use this default value.
The function in charge of deciding which value use is
`helm-resolve-display-function'.

To set it locally to `helm-buffer' in Helm sources use
`helm-set-local-variable' in init function or use
:display-function slot in `helm' call."
  :group 'helm
  :type 'symbol)

(defcustom helm-case-fold-search 'smart
  "Adds 'smart' option to `case-fold-search'.
Smart option ignores case for searches as long as there are no
upper case characters in the pattern.

Use nil or t to turn off smart behavior and use
`case-fold-search' behavior.

Default is smart.

NOTE: Case fold search has no effect when searching asynchronous
sources, which relies on customized features implemented directly
into their execution process. See helm-grep.el for an example."
  :group 'helm
  :type '(choice (const :tag "Ignore case" t)
                 (const :tag "Respect case" nil)
                 (other :tag "Smart" 'smart)))

(defcustom helm-file-name-case-fold-search
  (if (memq system-type
            '(cygwin windows-nt ms-dos darwin))
      t
    helm-case-fold-search)
  "Local setting of `helm-case-fold-search' for reading filenames.

See `helm-case-fold-search' for more info."
  :group 'helm
  :type 'symbol)

(defcustom helm-reuse-last-window-split-state nil
  "Use the same state of window split, vertical or horizontal.
`helm-toggle-resplit-window' for the next helm session will use
the same window scheme as the previous session unless
`helm-split-window-default-side' is 'same or 'other."
  :group 'helm
  :type 'boolean)

(defcustom helm-split-window-preferred-function 'helm-split-window-default-fn
  "Default function used for splitting window."
  :group 'helm
  :type 'function)

(defcustom helm-split-window-default-side 'below
  "The default side to display `helm-buffer'.
Must be one acceptable arg for `split-window' SIDE,
that is `below', `above', `left' or `right'.

Other acceptable values are `same' which always displays
`helm-buffer' in current window and `other' that displays
`helm-buffer' below if only one window or in
`other-window-for-scrolling' when available.

A nil value has same effect as `below'. If `helm-full-frame' is
non-nil, it take precedence over this setting.

See also `helm-split-window-inside-p' and
`helm-always-two-windows' that take precedence over this.

NOTE: this has no effect if
`helm-split-window-preferred-function' is not
`helm-split-window-default-fn' unless this new function can
handle this."
  :group 'helm
  :type 'symbol)

(defcustom helm-split-window-other-side-when-one-window 'below
  "The default side to display `helm-buffer' when (1)
`helm-split-window-default-side' is 'other and (2)
the current frame only has one window. Possible values
are acceptable args for `split-window' SIDE, that is `below',
`above', `left' or `right'.

If `helm-full-frame' is non-nil, it takes precedence over this
setting.

See also `helm-split-window-inside-p' and `helm-always-two-windows' that
takes precedence over this.

NOTE: this has no effect if
`helm-split-window-preferred-function' is not
`helm-split-window-default-fn' unless this new function can
handle this."
  :group 'helm
  :type 'symbol)

(defcustom helm-display-buffer-default-height nil
  "Initial height of `helm-buffer', specified as an integer or a function.

The function should take one arg and be responsible for re-sizing
the window; function's return value is ignored.  Note that this
has no effect when the split is vertical.  See `display-buffer'
for more info."
  :group 'helm
  :type '(choice integer function))

(defcustom helm-display-buffer-default-width nil
  "Initial width of `helm-buffer', specified as an integer or a function.

The function should take one arg and be responsible for re-sizing
the window; function's return value is ignored.  Note that this
have no effect when the split is horizontal.  See `display-buffer'
for more info."
  :group 'helm
  :type '(choice integer function))

(defvaralias 'helm-split-window-in-side-p 'helm-split-window-inside-p)
(make-obsolete-variable 'helm-split-window-in-side-p 'helm-split-window-inside-p "2.8.6")
(defcustom helm-split-window-inside-p nil
  "Force split inside selected window when non-nil.
See also `helm-split-window-default-side'.

NOTE: this has no effect if
`helm-split-window-preferred-function' is not
`helm-split-window-default-fn' unless this new function can
handle this."
  :group 'helm
  :type 'boolean)

(defcustom helm-always-two-windows nil
  "When non-nil Helm uses two windows in this frame.

I.e. `helm-buffer' in one window and `helm-current-buffer'
in the other.

Note: this has no effect when `helm-split-window-inside-p' is
non-nil, or when `helm-split-window-default-side' is set to
'same.

When `helm-autoresize-mode' is enabled, setting this to nil
will have no effect.

Also when non-nil it overrides the effect of
`helm-split-window-default-side' set to `other'."
  :group 'helm
  :type 'boolean)

(defcustom helm-display-buffer-width 72
  "Frame width when displaying helm-buffer in own frame."
  :group 'helm
  :type 'integer)

(defcustom helm-display-buffer-height 20
  "Frame height when displaying helm-buffer in own frame."
  :group 'helm
  :type 'integer)

(defcustom helm-default-display-buffer-functions nil
  "Action functions to pass to `display-buffer'.
See (info \"(elisp) Action Functions for Buffer Display\").

It has no effect when `helm-always-two-windows' is non-nil and
may override other settings like `helm-split-window-inside-p'."
  :group 'helm
  :type '(repeat symbol))

(defcustom helm-default-display-buffer-alist nil
  "Additional alist to pass to `display-buffer' action.
See (info \"(elisp) Action Alists for Buffer Display\").

It has no effect when `helm-always-two-windows' is non-nil and
may override other settings like `helm-split-window-inside-p'.
Note that window-height and window-width have to be configured in
`helm-display-buffer-height' and `helm-display-buffer-width'."
  :group 'helm
  :type '(alist :key-type symbol :value-type sexp))

(defcustom helm-sources-using-default-as-input '(helm-source-imenu
                                                 helm-source-imenu-all
                                                 helm-source-info-elisp
                                                 helm-source-etags-select
                                                 helm-source-man-pages
                                                 helm-source-occur
                                                 helm-source-moccur
                                                 helm-source-grep-ag
                                                 helm-source-grep-git
                                                 helm-source-grep)
  "List of Helm sources that need to use `helm-maybe-use-default-as-input'.
When a source is a member of this list, default `thing-at-point'
will be used as input."
  :group 'helm
  :type '(repeat (choice symbol)))

(defcustom helm-delete-minibuffer-contents-from-point t
  "When non-nil, `helm-delete-minibuffer-contents' deletes region from `point'.
Otherwise it deletes `minibuffer-contents'.
See documentation for `helm-delete-minibuffer-contents'."
  :group 'helm
  :type 'boolean)

(defcustom helm-follow-mode-persistent nil
  "When non-nil, save last state of `helm-follow-mode' for the next Emacs sessions.

Each time you turn on or off `helm-follow-mode', the current
source name will be stored or removed from
`helm-source-names-using-follow'.

Note that this may be disabled in some places where it is unsafe
to use because persistent action is changing according to
context."
  :group 'helm
  :type 'boolean)

(defcustom helm-source-names-using-follow nil
  "A list of source names to have follow enabled.
This list of source names will be used only
when `helm-follow-mode-persistent' is non-nil.

You don't have to customize this yourself unless you really want
and know what you are doing, instead just set
`helm-follow-mode-persistent' to non-nil and as soon as you turn
on or off `helm-follow-mode' (C-c C-f) in a source, Helm will
save or remove source name in this variable."
  :group 'helm
  :type '(repeat (choice string)))

(defcustom helm-prevent-escaping-from-minibuffer t
  "Prevent escaping from minibuffer with `other-window' during the Helm session."
  :group 'helm
  :type 'boolean)

(defcustom helm-allow-mouse nil
  "Allow mouse usage during the Helm session when non-nil.

Note that this also allows moving out of minibuffer when clicking
outside of `helm-buffer', so it is up to you to get back to Helm
by clicking back in `helm-buffer' or minibuffer."
  :group 'helm
  :type 'boolean)

(defcustom helm-move-to-line-cycle-in-source nil
  "Cycle to the beginning or end of the list after reaching the bottom or top.
This applies when using `helm-next/previous-line'."
  :group 'helm
  :type 'boolean)

(defcustom helm-fuzzy-match-fn 'helm-fuzzy-match
  "The function for fuzzy matching in `helm-source-sync' based sources."
  :group 'helm
  :type 'function)

(defcustom helm-fuzzy-search-fn 'helm-fuzzy-search
  "The function for fuzzy matching in `helm-source-in-buffer' based sources."
  :group 'helm
  :type 'function)

(defcustom helm-fuzzy-sort-fn 'helm-fuzzy-matching-default-sort-fn
  "The sort transformer function used in fuzzy matching."
  :group 'helm
  :type 'function)

(defcustom helm-fuzzy-matching-highlight-fn 'helm-fuzzy-default-highlight-match
  "The function to highlight fuzzy matches."
  :group 'helm
  :type 'function)

(defcustom helm-autoresize-max-height 40
  "Specify maximum height and defaults to percent of Helm window's frame height.

See `fit-window-to-buffer' for more infos."
  :group 'helm
  :type 'integer)

(defcustom helm-autoresize-min-height 10
  "Specify minimum height and defaults to percent of Helm window's frame height.

If nil, `window-min-height' is used.
See `fit-window-to-buffer' for details."
  :group 'helm
  :type 'integer)

(defcustom helm-input-method-verbose-flag nil
  "The default value for `input-method-verbose-flag' used in Helm minibuffer.
It is nil by default, which does not turn off input method. Helm
updates and exits without interruption -- necessary for complex
methods.

If set to any other value as per `input-method-verbose-flag',
then use `C-\\' to disable the `current-input-method' to exit or
update Helm."
  :group 'helm
  :type '(radio :tag "A flag to control extra guidance for input methods in helm."
                (const :tag "Never provide guidance" nil)
                (const :tag "Always provide guidance" t)
                (const :tag "Provide guidance only for complex methods" complex-only)))

(defcustom helm-display-header-line t
  "Display header-line when non nil."
  :group 'helm
  :type 'boolean)

(defcustom helm-inherit-input-method t
  "Inherit `current-input-method' from `current-buffer' when non-nil.
The default is to enable this by default and then toggle
`toggle-input-method'."
  :group 'helm
  :type 'boolean)

(defcustom helm-echo-input-in-header-line nil
  "Send current input to header-line when non-nil."
  :group 'helm
  :type 'boolean)

(defcustom helm-header-line-space-before-prompt 'left-fringe
  "Specify the space before prompt in header-line.

This will be used when `helm-echo-input-in-header-line' is
non-nil.

Value can be one of the symbols 'left-fringe or 'left-margin or
an integer specifying the number of spaces before prompt.  Note
that on input longer that `window-width' the continuation string
will be shown on left side of window without taking care of
this."
  :group 'helm
  :type '(choice
          (symbol
           (const :tag "Fringe" 'left-fringe)
           (const :tag "Margin" 'left-margin))
          integer))

(defcustom helm-tramp-connection-min-time-diff 5
  "Value of `tramp-connection-min-time-diff' for Helm remote processes.
If set to zero Helm remote processes are not delayed.

Setting this to a value less than 5 or disabling it with a zero
value is risky, however on Emacs versions starting at 24.5 it
seems it is now possible to disable it.

Anyway at any time in Helm you can suspend your processes while
typing by hitting \\<helm-map> `\\[helm-toggle-suspend-update]'.

Only async sources than use a sentinel calling
`helm-process-deferred-sentinel-hook' are affected by this."
  :type 'integer
  :group 'helm)

(defcustom helm-debug-root-directory nil
  "When non-nil, save Helm log messages to a file in this directory.
When nil log messages are saved to a buffer instead.  Log message
are saved only when `helm-debug' is non-nil, so setting this
doesn't enable debugging by itself.

See `helm-log-save-maybe' for more info."
  :type 'string
  :group 'helm)

(defcustom helm-show-action-window-other-window nil
  "Show action buffer beside `helm-buffer' when non-nil.

If nil don't split and replace helm-buffer by the action buffer
in same window.
If left display the action buffer at the left of helm-buffer.
If right or any other value, split at right.

Note that this may not fit well with some Helm window
configurations, so it have only effect when
`helm-always-two-windows' is non-nil."
  :group 'helm
  :type '(choice
          (const :tag "Split at left" left)
          (const :tag "Don't split" nil)
          (other :tag "Split at right" right)))

(defcustom helm-cycle-resume-delay 1.0
  "Delay used before resuming in `helm-run-cycle-resume'."
  :type 'float
  :group 'helm)

(defcustom helm-display-buffer-reuse-frame nil
  "When non nil Helm frame is not deleted and reused in next sessions.

This was used to workaround a bug in Emacs where frames where
popping up slowly, now that the bug have been fixed upstream
\(emacs-27) probably you don't want to use this any more.  On
emacs-26 set `x-wait-for-event-timeout' to nil to have your
frames popping up fast."
  :group 'helm
  :type 'boolean)

(defcustom helm-commands-using-frame nil
  "A list of commands where `helm-buffer' is displayed in a frame."
  :group 'helm
  :type '(repeat symbol))

(defcustom helm-actions-inherit-frame-settings t
  "Actions inherit Helm frame settings of initial command when non nil."
  :group 'helm
  :type 'boolean)

(defcustom helm-use-undecorated-frame-option t
  "Display Helm frame undecorated when non nil.

This option has no effect with Emacs versions lower than 26."
  :group 'helm
  :type 'boolean)

(defcustom helm-frame-background-color nil
  "Background color for Helm frames, a string.
Fallback to default face background when nil."
  :group 'helm
  :type 'string)

(defcustom helm-frame-foreground-color nil
  "Foreground color for Helm frames, a string.
Fallback to default face foreground when nil"
  :group 'helm
  :type 'string)

(defcustom helm-frame-alpha nil
  "Alpha parameter for Helm frames, an integer.
Fallback to 100 when nil."
  :group 'helm
  :type 'integer)

(defcustom helm-use-frame-when-more-than-two-windows nil
  "Display Helm buffer in frame when more than two windows."
  :group 'helm
  :type 'boolean)

(defcustom helm-use-frame-when-dedicated-window nil
  "Display Helm buffer in frame when Helm is started from a dedicated window."
  :group 'helm
  :type 'boolean)

(defcustom helm-default-prompt-display-function
  #'helm-set-default-prompt-display
  "The function to use to set face of fake cursor in header-line."
  :group 'helm
  :type 'function)

(defcustom helm-truncate-lines nil
  "The value of `truncate-lines' when Helm starts.
You can toggle later `truncate-lines' with
\\<helm-map>\\[helm-toggle-truncate-line]."
  :group 'helm
  :type 'boolean)

;;; Faces
;;
;;
(defgroup helm-faces nil
  "Customize the appearance of Helm."
  :prefix "helm-"
  :group 'faces
  :group 'helm)

(defface helm-source-header
  `((((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "#22083397778B"
     :foreground "white"
     :weight bold :height 1.3 :family "Sans Serif")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "#abd7f0"
     :foreground "black"
     :weight bold :height 1.3 :family "Sans Serif"))
  "Face for source header in the Helm buffer."
  :group 'helm-faces)

(defface helm-visible-mark
  `((((min-colors 88) (background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "green1"
     :foreground "black")
    (((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "green"
     :foreground "black")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "#d1f5ea")
    (((min-colors 88))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "green1")
    (t ,@(and (>= emacs-major-version 27) '(:extend t))
       :background "green"))
  "Face for visible mark."
  :group 'helm-faces)

(defface helm-header
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
       :inherit header-line))
  "Face for header lines in the Helm buffer."
  :group 'helm-faces)

(defface helm-candidate-number
  `((((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "Yellow" :foreground "black")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "#faffb5" :foreground "black"))
  "Face for candidate number in mode-line."
  :group 'helm-faces)

(defface helm-candidate-number-suspended
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
     :inherit helm-candidate-number :inverse-video t))
  "Face for candidate number in mode-line when Helm is suspended."
  :group 'helm-faces)

(defface helm-selection
  `((((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "ForestGreen"
     :distant-foreground "black")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :background "#b5ffd1"
     :distant-foreground "black"))
  "Face for currently selected item in the Helm buffer."
  :group 'helm-faces)

(defface helm-separator
  `((((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "red")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "#ffbfb5"))
  "Face for multiline source separator."
  :group 'helm-faces)

(defface helm-action
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
       :underline t))
  "Face for action lines in the Helm action buffer."
  :group 'helm-faces)

(defface helm-prefarg
  `((((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "green")
    (((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "red"))
  "Face for showing prefix arg in mode-line."
  :group 'helm-faces)

(defface helm-match
  `((((background light))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "#b00000")
    (((background dark))
     ,@(and (>= emacs-major-version 27) '(:extend t))
     :foreground "gold1"))
  "Face used to highlight matches."
  :group 'helm-faces)

(defface helm-header-line-left-margin
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
       :foreground "black" :background "yellow"))
  "Face used to highlight helm-header sign in left-margin."
  :group 'helm-faces)

(defface helm-minibuffer-prompt
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
       :inherit minibuffer-prompt))
  "Face used for the minibuffer/headline prompt (such as Pattern:) in Helm."
  :group 'helm-faces)

(defface helm-eob-line
  `((t ,@(and (>= emacs-major-version 27) '(:extend t))
       :inherit default))
  "Face for empty line at end of sources in the Helm buffer.
Allow specifying the height of this line."
  :group 'helm-faces)

;;; Variables.
;;
;;
(defvar helm-selection-overlay nil
  "Overlay used to highlight the currently selected item.")

(defvar helm-async-processes nil
  "List of information about asynchronous processes managed by Helm.")

(defvar helm-before-initialize-hook nil
  "Runs before Helm initialization.
This hook runs before init functions in `helm-sources', which is
before creation of `helm-buffer'.  Set local variables for
`helm-buffer' that need a value from `current-buffer' with
`helm-set-local-variable'.")

(defvar helm-after-initialize-hook nil
  "Runs after Helm initialization.
This hook runs after `helm-buffer' is created but not from
`helm-buffer'.  The hook needs to specify in which buffer to
run.")

(defvaralias 'helm-update-hook 'helm-after-update-hook)
(make-obsolete-variable 'helm-update-hook 'helm-after-update-hook "1.9.9")

(defvar helm-after-update-hook nil
  "Runs after updating the Helm buffer with the new input pattern.")

(defvar helm-before-update-hook nil
  "Runs before updating the Helm buffer with the new input pattern.")

(defvar helm-cleanup-hook nil
  "Runs after exiting the minibuffer and before performing an
action.

This hook runs even if Helm exits the minibuffer abnormally (e.g.
via `helm-keyboard-quit').")

(defvar helm-select-action-hook nil
  "Runs when opening the action buffer.")

(defvar helm-before-action-hook nil
  "Runs before executing action.
Unlike `helm-cleanup-hook', this hook runs before Helm closes the
minibuffer and also before performing an action.")

(defvar helm-after-action-hook nil
  "Runs after executing action.")

(defvar helm-exit-minibuffer-hook nil
  "Runs just before exiting the minibuffer.

This hook runs when Helm exits the minibuffer normally (e.g., via
candidate selection), but does NOT run if Helm exits the
minibuffer abnormally (e.g. via `helm-keyboard-quit').")

(defvar helm-after-persistent-action-hook nil
  "Runs after executing persistent action.")

(defvar helm-move-selection-before-hook nil
  "Runs before moving selection in `helm-buffer'.")

(defvar helm-move-selection-after-hook nil
  "Runs after moving selection in `helm-buffer'.")

(defvar helm-after-preselection-hook nil
  "Runs after pre-selection in `helm-buffer'.")

(defvar helm-window-configuration-hook nil
  "Runs when switching to and from the action buffer.")

(defvar helm-execute-action-at-once-if-one nil
  "When non-nil execute the default action and then exit if only one candidate.
If symbol 'current-source is given as value exit if only one
candidate in current source.  This variable accepts a function
with no args that should returns a boolean value or
'current-source.")

(defvar helm-quit-if-no-candidate nil
  "When non-nil, quit if there are no candidates.
This variable accepts a function.")

(defvar helm-debug-variables nil
  "A list of Helm variables that `helm-debug-output' displays.
If nil, `helm-debug-output' includes only variables with `helm-'
prefixes.")

(defvar helm-debug-buffer "*Debug Helm Log*")

(defvar helm-debug nil
  "If non-nil, write log message to `helm-debug-buffer'.
Default is nil, which disables writing log messages because the
size of `helm-debug-buffer' grows quickly.")

(defvar helm-mode-line-string "\
\\<helm-map>\
\\[helm-help]:Help \
\\[helm-select-action]:Act \
\\[helm-maybe-exit-minibuffer]/\
f1/f2/f-n:NthAct \
\\[helm-toggle-suspend-update]:Tog.suspend \
\\[helm-customize-group]:Conf"
  "Help string displayed by Helm in the mode-line.
It is either a string or a list of two string arguments where the
first string is the name and the second string is displayed in
the mode-line. When nil, it defaults to `mode-line-format'.")

(defvar helm-minibuffer-set-up-hook nil
  "Hook that runs at minibuffer initialization.
A hook useful for modifying minibuffer settings in Helm.

An example that hides the minibuffer when using
`helm-echo-input-in-header-line':

      (add-hook 'helm-minibuffer-set-up-hook #'helm-hide-minibuffer-maybe)

Note that we check `helm-echo-input-in-header-line' value
from `helm-buffer' which allows detecting possible local
value of this var.")

(defvar helm-help-message
  "* Helm Generic Help
** Basics

To navigate in this Help buffer see [[Helm help][here]].

Helm narrows down the list of candidates as you type a filter
pattern.  See [[Matching in Helm][Matching in Helm]].

Helm accepts multiple space-separated patterns, each pattern can
be negated with \"!\".

Helm also supports fuzzy matching in some places when specified,
you will find several variables to enable fuzzy matching in
diverse [[Helm sources][sources]], see [[https://github.com/emacs-helm/helm/wiki/Fuzzy-matching][fuzzy-matching]] in helm-wiki for more infos.

Helm generally uses familiar Emacs keys to navigate the list.
Here follow some of the less obvious bindings:

- `\\<helm-map>\\[helm-maybe-exit-minibuffer]' selects the
candidate from the list, executes the default action upon exiting
the Helm session.

- `\\<helm-map>\\[helm-execute-persistent-action]' executes the
default action but without exiting the Helm session.  Not all
sources support this.

- `\\<helm-map>\\[helm-select-action]' displays a list of actions
available on current candidate or all marked candidates.  The
default binding <tab> is ordinarily used for completion, but that
would be redundant since Helm completes upon every character
entered in the prompt.  See [[https://github.com/emacs-helm/helm/wiki#helm-completion-vs-emacs-completion][Helm wiki]].

Note: In addition to the default actions list, additional actions
appear depending on the type of the selected candidate(s).  They
are called filtered actions.

** Helm sources

Helm uses what's called sources to provide different kinds of
completions.  Each Helm session can handle one or more source.  A
source is an alist object which is build from various classes,
see [[Writing your own Helm sources][here]] and
[[https://github.com/emacs-helm/helm/wiki/Developing#creating-a-source][Helm
wiki]] for more infos.

*** Configure sources

You will find in Helm sources already built and bound to a
variable called generally `helm-source-<something>'.  In this case
it is an alist and you can change the attributes (keys) values
using `helm-attrset' function in your configuration.  Of course
you have to ensure before calling `helm-attrset' that the file
containing source is loaded, e.g. with `with-eval-after-load'.  Of
course you can also completely redefine the source but this is
generally not elegant as it duplicate for its most part code
already defined in Helm.

You will find also sources that are not built and even not bound
to any variables because they are rebuilded at each start of a
Helm session.  In this case you can add a defmethod called
`helm-setup-user-source' to your config:

#+begin_src elisp

    (defmethod helm-setup-user-source ((source helm-moccur-class))
      (setf (slot-value source 'follow) -1))

#+end_src

See
[[https://github.com/emacs-helm/helm/wiki/FAQ#why-is-a-customizable-helm-source-nil][here]]
for more infos, and for more complex examples of configuration
[[https://github.com/thierryvolpiatto/emacs-tv-config/blob/master/init-helm.el#L340][here]].

** Modify keybindings in Helm

Helm main keymap is `helm-map', all keys bound in this map apply
to all Helm sources.  However, most sources have their own keymap,
with each binding overriding its counterpart in `helm-map', you
can see all bindings in effect in the [[Commands][Commands]]
section (available only if the source has its own keymap and
documentation of course).

** Matching in Helm

All that you write in minibuffer is interpreted as a regexp or
multiple regexps if separated by a space.  This is true for most
sources unless the developer of the source has disabled it or
have choosen to use fuzzy matching.  Even if a source has fuzzy
matching enabled, Helm will switch to multi match as soon as it
detects a space in the pattern.  It may also switch to multi match
as well if pattern starts with a \"^\" beginning of line sign.  In
those cases each pattern separated with space should be a regexp
and not a fuzzy pattern.  When using multi match patterns, each
pattern starting with \"!\" is interpreted as a negation i.e.
match everything but this.

*** Completion-styles

Helm generally fetches its candidates with the :candidates
function up to `helm-candidate-number-limit' and then applies
match functions to these candidates according to `helm-pattern'.
But Helm allows matching candidates directly from the :candidates
function using its own `completion-styles'.
Helm provides 'helm completion style but also 'helm-flex
completion style for Emacs<27 that don't have 'flex completion
style, otherwise (emacs-27) 'flex completion style is used to
provide fuzzy aka flex completion.
By default, like in Emacs vanilla, all completion commands \(e.g.,
`completion-at-point') using `completion-in-region' or
`completing-read' use `completion-styles'.
Some Helm native commands like `helm-M-x' do use
`completion-styles'.  Any Helm sources can use `completion-styles'
by using :match-dynamic slot and building their :candidates
function with `helm-dynamic-completion'.

Example:

#+begin_src elisp

    (helm :sources (helm-build-sync-source \"test\"
                     :candidates (helm-dynamic-completion
                                  '(foo bar baz foab)
                                  'symbolp)
                     :match-dynamic t)
          :buffer \"*helm test*\")

#+end_src

By default Helm sets up `completion-styles' and always adds 'helm
to it.  However the flex completion styles are not added.  This is
up to the user if she wants to have such completion to enable
this.
As specified above use 'flex for emacs-27 and 'helm-flex for
emacs-26. Anyway, 'helm-flex is not provided in
`completion-styles-alist' if 'flex is present.

Finally Helm provides two user variables to control
`completion-styles' usage: `helm-completion-style' and
`helm-completion-syles-alist'.  Both variables are customizable.
The former allows retrieving previous Helm behavior if needed, by
setting it to `helm' or `helm-fuzzy', default being `emacs' which
allows dynamic completion and usage of `completion-styles'.  The
second allows setting `helm-completion-style' per mode and also
specifying `completion-styles' per mode (see its docstring).  Note
that these two variables take effect only in helm-mode i.e. in
all that uses `completion-read' or `completion-in-region', IOW all
helmized commands.  File completion in `read-file-name' family
doesn't obey completion-styles and has its own file completion
implementation. Native Helm commands using `completion-styles'
doesn't obey `helm-completion-style' and
`helm-completion-syles-alist' (e.g., helm-M-x).

Also for a better control of styles in native Helm sources (not
helmized by helm-mode) using :match-dynamic,
`helm-dynamic-completion' provides a STYLES argument that allows
specifying explicitely styles for this source.

NOTE: Some old completion styles are not working fine with Helm
and are disabled by default in
`helm-blacklist-completion-styles'.  They are anyway not useful in
Helm because 'helm style supersedes these styles.

** Helm mode

`helm-mode' toggles Helm completion in native Emacs functions, so
when you turn `helm-mode' on, commands like `switch-to-buffer'
will use Helm completion instead of the usual Emacs completion
buffer.

*** What gets or does not get \"helmized\" when `helm-mode' is enabled?

Helm provides generic completion on all Emacs functions using
`completing-read', `completion-in-region' and their derivatives,
e.g. `read-file-name'.  Helm exposes a user variable to control
which function to use for a specific Emacs command:
`helm-completing-read-handlers-alist'.  If the function for a
specific command is nil, it turns off Helm completion.  See the
variable documentation for more infos.

*** Helm functions vs helmized Emacs functions

While there are Helm functions that perform the same completion
as other helmized Emacs functions, e.g. `switch-to-buffer' and
`helm-buffers-list', the native Helm functions like
`helm-buffers-list' can receive new features that allow marking
candidates, have several actions, etc.  Whereas the helmized Emacs
functions only have Helm completion, Emacs can provide no more
than one action for this function.  This is the intended behavior.

Generally you are better off using the native Helm command than
the helmized Emacs equivalent.

*** Completion behavior with Helm and completion-at-point

Helm is NOT completing dynamically.  That means that when you are
completing some text at point, completion is done against this
text and subsequent characters you add AFTER this text.  This
allows you to use matching methods provided by Helm, that is multi
matching or fuzzy matching (see [[Matching in Helm][Matching in
Helm]]).

Completion is not done dynamically (against `helm-pattern')
because backend functions (i.e. `competion-at-point-functions')
are not aware of Helm matching methods.

By behaving like this, the benefit is that you can fully use Helm
matching methods but you can't start a full completion against a
prefix different than the initial text you have at point.  Helm
warns you against this by colorizing the initial input and sends
a user-error message when trying to delete backward text beyond
this limit at first hit on DEL.  A second hit on DEL within a
short delay (1s) quits Helm and delete-backward char in
current-buffer.

** Helm help

\\[helm-documentation]: Show all Helm documentations concatenated
in one org file.

From a Helm session, just hit \\<helm-map>\\[helm-help] to have
the documentation for the current source followed by the global
Helm documentation.

While in the help buffer, most of the Emacs regular key bindings
are available; the most important ones are shown in minibuffer.
However, due to implementation restrictions, no regular Emacs
keymap is used (it runs in a loop when reading the help buffer).
Only simple bindings are available and they are defined in
`helm-help-hkmap', which is a simple alist of (key . function).
You can define or redefine bindings in help with
`helm-help-define-key' or by adding/removing entries directly in
`helm-help-hkmap'.
See `helm-help-hkmap' for restrictions on bindings and functions.

The documentation of default bindings are:

| Key       | Alternative keys | Command             |
|-----------+------------------+---------------------|
| C-v       | Space next       | Scroll up           |
| M-v       | b prior          | Scroll down         |
| C-s       |                  | Isearch forward     |
| C-r       |                  | Isearch backward    |
| C-a       |                  | Beginning of line   |
| C-e       |                  | End of line         |
| C-f       | right            | Forward char        |
| C-b       | left             | Backward char       |
| C-n       | down             | Next line           |
| C-p       | up               | Previous line       |
| M-a       |                  | Backward sentence   |
| M-e       |                  | Forward sentence    |
| M-f       |                  | Forward word        |
| M-b       |                  | Backward word       |
| M->       |                  | End of buffer       |
| M-<       |                  | Beginning of buffer |
| C-<SPACE> |                  | Toggle mark         |
| C-M-SPACE |                  | Mark sexp           |
| RET       |                  | Follow org link     |
| C-%       |                  | Push org mark       |
| C-&       |                  | Goto org mark-ring  |
| TAB       |                  | Org cycle           |
| M-<TAB>   |                  | Toggle visibility   |
| M-w       |                  | Copy region         |
| q         |                  | Quit                |

** Customize Helm

Helm provides a lot of user variables for extensive customization.
From any Helm session, type \\<helm-map>\\[helm-customize-group]
to jump to the current source `custom' group.  Helm also has a
special group for faces you can access via `M-x customize-group
RET helm-faces'.

Note: Some sources may not have their group set and default to
the `helm' group.

** Display Helm in windows and frames

You can display the Helm completion buffer in many different
window configurations, see the custom interface to discover the
different windows configurations available (See [[Customize
Helm][Customize Helm]] to jump to custom interface).  When using
Emacs in a graphic display (i.e. not in a terminal) you can as
well display your Helm buffers in separated frames globally for
all Helm commands or separately for specific Helm commands.  See
[[https://github.com/emacs-helm/helm/wiki/frame][helm wiki]] for
more infos.

** Helm's basic operations and default key bindings

| Key     | Alternative Keys | Command                                                              |
|---------+------------------+----------------------------------------------------------------------|
| C-p     | Up               | Previous line                                                        |
| C-n     | Down             | Next line                                                            |
| M-v     | prior            | Previous page                                                        |
| C-v     | next             | Next page                                                            |
| Enter   |                  | Execute first (default) action / Select [1]                          |
| M-<     |                  | First line                                                           |
| M->     |                  | Last line                                                            |
| C-M-S-v | M-prior, C-M-y   | Previous page (other-window)                                         |
| C-M-v   | M-next           | Next page (other-window)                                             |
| Tab     | C-i              | Show action list                                                     |
| M-o     | left             | Previous source                                                      |
| C-o     | right            | Next source                                                          |
| C-k     |                  | Delete pattern (with prefix arg delete from point to end or all [2]) |
| C-j     |                  | Persistent action (Execute and keep Helm session)                    |

\[1] Behavior may change depending context in some source e.g. `helm-find-files'.

\[2] Delete from point to end or all depending on the value of
`helm-delete-minibuffer-contents-from-point'.

NOTE: Any of these bindings are from `helm-map' and may be
overriten by the map specific to the current source in use (each
source can have its own keymap).

** The actions menu

You can display the action menu in the same window
as helm candidates (default) or in a side window according to
`helm-show-action-window-other-window' value.

When the action menu popup, the helm prompt is used to narrow
down this menu, no more candidates.

When `helm-allow-mouse' is non nil, you can use as well
mouse-3 (right click) in the candidate zone to select actions
with the mouse once your candidate is selected.

** Action transformers

You may be surprized to see your actions list changing depending
on the context.  This happen when a source has an action
transformer function which checks the current selected candidate
and adds specific actions for this candidate.

** Shortcuts for n-th first actions

f1-f12: Execute n-th action where n is 1 to 12.

** Shortcuts for executing the default action on the n-th candidate

Helm does not display line numbers by default, with Emacs-26+ you
can enable it permanently in all helm buffers with:

    (add-hook 'helm-after-initialize-hook 'helm-init-relative-display-line-numbers)

You can also toggle line numbers with
\\<helm-map>\\[helm-display-line-numbers-mode] in current Helm
buffer.

Of course when enabling `global-display-line-numbers-mode' Helm
buffers will have line numbers as well. \(Don't forget to
customize `display-line-numbers-type' to relative).

In Emacs versions < to 26 you will have to use
[[https://github.com/coldnew/linum-relative][linum-relative]]
package and `helm-linum-relative-mode'.

Then when line numbers are enabled with one of the methods above
the following keys are available([1]):

C-x <n>: Execute default action on the n-th candidate before
currently selected candidate.

C-c <n>: Execute default action on the n-th candidate after
current selected candidate.

\"n\" is limited to 1-9.  For larger jumps use other navigation
keys.

\[1] Note that the key bindings are always available even if line
numbers are not displayed.  They are just useless in this case.

** Mouse control in Helm

A basic support for the mouse is provided when the user sets
`helm-allow-mouse' to non-nil.

- mouse-1 selects the candidate.
- mouse-2 executes the default action on selected candidate.
- mouse-3 pops up the action menu.

Note: When mouse control is enabled in Helm, it also lets you
click around and lose the minibuffer focus: you'll have to click
on the Helm buffer or the minibuffer to retrieve control of your
Helm session.

** Marked candidates

You can mark candidates to execute an action on all of them
instead of the current selected candidate only.  (See bindings
below.) Most Helm actions operate on marked candidates unless
candidate-marking is explicitely forbidden for a specific source.

- To mark/unmark a candidate, use
\\[helm-toggle-visible-mark].  (See bindings below.) With a
numeric prefix arg mark ARG candidates forward, if ARG is
negative mark ARG candidates backward.

- To mark all visible unmarked candidates at once in current
source use \\[helm-mark-all].  With a prefix argument, mark all
candidates in all sources.

- To unmark all visible marked candidates at once use
  \\[helm-unmark-all].

- To mark/unmark all candidates at once use
\\[helm-toggle-all-marks].  With a prefix argument, mark/unmark
all candidates in all sources.

Note: When multiple candidates are selected across different
sources, only the candidates of the current source will be used
when executing most actions (as different sources can have
different actions).  Some actions support multi-source marking
however.

** Follow candidates

When `helm-follow-mode' is on (\\<helm-map>\\[helm-follow-mode]
to toggle it), moving up and down Helm session or updating the
list of candidates will automatically execute the
persistent-action as specified for the current source.

If `helm-follow-mode-persistent' is non-nil, the state of the
mode will be restored for the following Helm sessions.

If you just want to follow candidates occasionally without
enabling `helm-follow-mode', you can use
\\<helm-map>\\[helm-follow-action-forward] or
\\[helm-follow-action-backward] instead.  Conversely, when
`helm-follow-mode' is enabled, those commands go to previous/next
line without executing the persistent action.

** Frequently Used Commands

\\[helm-toggle-resplit-and-swap-windows]\t\tToggle vertical/horizontal split on first hit and swap Helm window on second hit.
\\[helm-exchange-minibuffer-and-header-line]\t\tExchange minibuffer and header-line.
\\[helm-quit-and-find-file]\t\tDrop into `helm-find-files'.
\\[helm-kill-selection-and-quit]\t\tKill display value of candidate and quit (with prefix arg, kill the real value).
\\[helm-yank-selection]\t\tYank current selection into pattern.
\\[helm-copy-to-buffer]\t\tCopy selected candidate at point in current buffer.
\\[helm-follow-mode]\t\tToggle automatic execution of persistent action.
\\[helm-follow-action-forward]\tRun persistent action then select next line.
\\[helm-follow-action-backward]\t\tRun persistent action then select previous line.
\\[helm-refresh]\t\tRecalculate and redisplay candidates.
\\[helm-toggle-suspend-update]\t\tToggle candidate updates.

** Special yes, no or yes for all answers

You may be prompted in the minibuffer to answer by [y,n,!,q] in
some places for confirmation.

- y  mean yes
- no mean no
- !  mean yes for all
- q  mean quit or abort current operation.

When using ! you will not be prompted for the same thing in
current operation any more, e.g. file deletion, file copy etc...

** Moving in `helm-buffer'

You can move in `helm-buffer' with the usual commands used in
Emacs: \(\\<helm-map>\\[helm-next-line],
\\<helm-map>\\[helm-previous-line], etc.  See above basic
commands.  When `helm-buffer' contains more than one source,
change source with \\<helm-map>\\[helm-next-source] and
\\[helm-previous-source].

Note: When reaching the end of a source,
\\<helm-map>\\[helm-next-line] will *not* go to the next source
when variable `helm-move-to-line-cycle-in-source' is non-nil, so
you will have to use \\<helm-map>\\[helm-next-source] and
\\[helm-previous-source].

** Resume previous session from current Helm session

You can use `C-c n' (`helm-run-cycle-resume') to cycle in
resumables sources.  `C-c n' is a special key set with
`helm-define-key-with-subkeys' which, after pressing it, allows
you to keep cycling with further `n'.

Tip: You can bound the same key in `global-map' to
     `helm-cycle-resume' with `helm-define-key-with-subkeys' to
     let you transparently cycle sessions, Helm fired up or not.
     You can also bind the cycling commands to single key
     presses (e.g., `S-<f1>') this time with a simple
     `define-key'.  (Note that `S-<f1>' is not available in
     terminals.)

Note: `helm-define-key-with-subkeys' is available only once Helm
is loaded.

You can also use
\\<helm-map>\\[helm-resume-previous-session-after-quit] to resume
the previous session, or
\\<helm-map>\\[helm-resume-list-buffers-after-quit] to have
completion on all resumable buffers.

** Global commands

*** Resume Helm session from outside Helm

\\<global-map>\\[helm-resume] revives the last Helm session.
Binding a key to this command will greatly improve Helm
interactivity, e.g. when quitting Helm accidentally.

You can call \\<global-map>\\[helm-resume] with a prefix argument
to choose \(with completion!) which session you'd like to resume.
You can also cycle in these sources with `helm-cycle-resume' (see
above).

** Debugging Helm

Helm exposes the special variable `helm-debug': setting it to
non-nil will enable Helm logging in a special outline-mode
buffer.  Helm resets the variable to nil at the end of each
session.

For convenience, \\<helm-map>\\[helm-enable-or-switch-to-debug]
allows you to turn on debugging for this session only.  To avoid
accumulating log entries while you are typing patterns, you can
use \\<helm-map>\\[helm-toggle-suspend-update] to turn off
updating.  When you are ready turn it on again to resume logging.

Once you exit your Helm session you can access the debug buffer
with `helm-debug-open-last-log'.  It is possible to save logs to
dated files when `helm-debug-root-directory' is set to a valid
directory.

Note: Be aware that Helm log buffers grow really fast, so use
`helm-debug' only when needed.

** Writing your own Helm sources

Writing simple sources for your own usage is easy.  When calling
the `helm' function, the sources are added the :sources slot
which can be a symbol or a list of sources.  Sources can be built
with different EIEIO classes depending on what you want to do.  To
simplify this, several `helm-build-*' macros are provided.  Below
there are simple examples to start with.

We will not go further here, see
[[https://github.com/emacs-helm/helm/wiki/Developing][Helm wiki]]
and the source code for more information and more complex
examples.

#+begin_src elisp

    ;; Candidates are stored in a list.
    (helm :sources (helm-build-sync-source \"test\"
                     ;; A function can be used as well
                     ;; to provide candidates.
                     :candidates '(\"foo\" \"bar\" \"baz\"))
          :buffer \"*helm test*\")

    ;; Candidates are stored in a buffer.
    ;; Generally faster but doesn't allow a dynamic updating
    ;; of the candidates list i.e the list is fixed on start.
    (helm :sources (helm-build-in-buffer-source \"test\"
                     :data '(\"foo\" \"bar\" \"baz\"))
          :buffer \"*helm test*\")

#+end_src

** Helm Map
\\{helm-map}"
  "Message string containing detailed help for `helm'.
It also accepts function or variable symbol.")

(defvar helm-autoresize-mode) ;; Undefined in `helm-default-display-buffer'.

(defvar helm-async-outer-limit-hook nil
  "A hook that runs in async sources when process output comes out of `candidate-number-limit'.
Should be set locally to `helm-buffer' with `helm-set-local-variable'.")

(defvar helm-quit-hook nil
  "A hook that runs when quitting Helm.")

(defvar helm-resume-after-hook nil
  "A hook that runs after resuming a Helm session.
The hook should takes one arg SOURCES.")

(defvar helm-help-buffer-name "*Helm Help*"
  "The name of helm help buffer.")

;;; Internal Variables
;;
;;
(defvar helm-source-filter nil
  "A list of source names to be displayed.
Other sources won't appear in the search results.
If nil, no filtering is done.
Don't set this directly, use `helm-set-source-filter' during a
Helm session to modify it.")
(defvar helm-current-prefix-arg nil
  "Record `current-prefix-arg' when exiting minibuffer.")
(defvar helm-saved-action nil
  "Saved value of the currently selected action by key.")
(defvar helm-saved-current-source nil
  "Value of the current source when the action list is shown.")
(defvar helm-in-persistent-action nil
  "Flag whether in persistent-action or not.")
(defvar helm-last-buffer nil
  "`helm-buffer' of a previous Helm session.")
(defvar helm-saved-selection nil
  "Value of the currently selected object when the action list is shown.")
(defvar helm-sources nil
  "[INTERNAL] Value of current sources in use, a list of alists.
The list of sources (symbols or alists) is normalized to alists
in `helm-initialize'.")
(defvar helm-buffer-file-name nil
  "Variable `buffer-file-name' when Helm is invoked.")
(defvar helm-candidate-cache (make-hash-table :test 'equal)
  "Holds the available candidate within a single Helm invocation.")
(defvar helm--candidate-buffer-alist nil)
(defvar helm-input ""
  "The input typed in the candidates panel.")
(defvar helm-input-local nil
  "Internal, store locally `helm-pattern' value for later use in `helm-resume'.")
(defvar helm--source-name nil)
(defvar helm-current-source nil)
(defvar helm-tick-hash (make-hash-table :test 'equal))
(defvar helm-issued-errors nil)
(defvar helm--last-log-file nil
  "The name of the log file of the last Helm session.")
(defvar helm--local-variables nil)
(defvar helm-split-window-state nil)
(defvar helm--window-side-state nil)
(defvar helm-selection-point nil
  "The value of point at selection.")
(defvar helm-alive-p nil)
(defvar helm-visible-mark-overlays nil)
(defvar helm-update-blacklist-regexps '("^" "^ *" "$" "!" " " "\\b"
                                        "\\<" "\\>" "\\_<" "\\_>" ".*"
                                        "??" "?*" "*?" "?"))
(defvar helm--force-updating-p nil
  "[INTERNAL] Don't use this in your programs.")
(defvar helm-exit-status 0
  "Flag to inform if Helm did exit or quit.
0 means Helm did exit when executing an action.
1 means Helm did quit with \\[keyboard-quit]
Knowing this exit-status could help restore a window config when
Helm aborts in some special circumstances.  See
`helm-exit-minibuffer' and `helm-keyboard-quit'.")
(defvar helm-minibuffer-confirm-state nil)
(defvar helm-quit nil)
(defvar helm-buffers nil
  "Helm buffers listed in order of most recently used.")
(defvar helm-current-position nil
  "Cons of \(point . window-start\)  when Helm is invoked.
`helm-current-buffer' uses this to restore position after
`helm-keyboard-quit'")
(defvar helm-last-frame-or-window-configuration nil
  "Used to store window or frame configuration at Helm start.")
(defvar helm-onewindow-p nil)
(defvar helm-types nil)
(defvar helm--mode-line-string-real nil) ; The string to display in mode-line.
(defvar helm-persistent-action-display-window nil)
(defvar helm-marked-candidates nil
  "Marked candidates.  List of \(source . real\) pair.")
(defvar helm--mode-line-display-prefarg nil)
(defvar helm--temp-follow-flag nil
  "[INTERNAL] A simple flag to notify persistent action we are following.")
(defvar helm--reading-passwd-or-string nil)
(defvar helm--in-update nil)
(defvar helm--in-fuzzy nil)
(defvar helm-maybe-use-default-as-input nil
  "Flag to notify the use of use-default-as-input.
Use only in let-bindings.
Use :default arg of `helm' as input to update display.
Note that if also :input is specified as `helm' arg, it will take
precedence on :default.")
(defvar helm--temp-hooks nil
  "Store temporary hooks added by `with-helm-temp-hook'.")
(defvar helm--prompt nil)
(defvar helm--file-completion-sources
  '("Find Files" "Read File Name")
  "Sources that use the *find-files mechanism can be added here.
Sources generated by `helm-mode' don't need to be added here
because they are automatically added.

You should not modify this yourself unless you know what you are
doing.")
(defvar helm--completing-file-name nil
  "Non nil when `helm-read-file-name' is running.
Used for `helm-file-completion-source-p'.")
;; Same as `ffap-url-regexp' but keep it here to ensure `ffap-url-regexp' is not nil.
(defvar helm--url-regexp "\\`\\(news\\(post\\)?:\\|mailto:\\|file:\\|\\(ftp\\|https?\\|telnet\\|gopher\\|www\\|wais\\)://\\)")
(defvar helm--ignore-errors nil
  "Flag to prevent Helm popping up errors in candidates functions.
Should be set in candidates functions if needed, and will be
restored at end of session.")
(defvar helm--action-prompt "Select action: ")
(defvar helm--cycle-resume-iterator nil)
(defvar helm--buffer-in-new-frame-p nil)
(defvar helm-initial-frame nil
  "[INTERNAL] The selected frame before starting Helm.
Helm use this internally to know in which frame it started, don't
modify this yourself.")
(defvar helm-popup-frame nil
  "The frame where Helm is displayed.

This is only used when Helm is using
`helm-display-buffer-in-own-frame' as `helm-display-function' and
`helm-display-buffer-reuse-frame' is non nil.")
(defvar helm--nested nil)
(defconst helm--frame-default-attributes
  '(width height tool-bar-lines left top
          title undecorated vertical-scroll-bars
          visibility fullscreen menu-bar-lines undecorated
          alpha foreground-color background-color)
  "Frame parameters to save in `helm--last-frame-parameters'.")
(defvar helm--last-frame-parameters nil
  "Frame parameters to save for later resuming.
Local to `helm-buffer'.")
(defvar helm--executing-helm-action nil
  "Non nil when action is triggering a new helm-session.
This may be let bounded in other places to notify the display
function to reuse the same frame parameters as the previous Helm
session just like resume would do.")
(defvar helm--current-buffer-narrowed nil)
(defvar helm--suspend-update-interactive-flag nil)
(defvar helm-persistent-action-window-buffer nil
  "[INTERNAL] Store the buffer where helm is started.
It is generally `helm-current-buffer', but when this one is displayed
in a dedicated buffer, helm can't start in this window and use another
window handling a buffer, it is this one we store.")

;; Utility: logging
(defun helm-log (format-string &rest args)
  "Log message `helm-debug' is non-nil.
Messages are written to the `helm-debug-buffer' buffer.

Argument FORMAT-STRING is a string to use with `format'.
Use optional arguments ARGS like in `format'."
  (when helm-debug
    (with-current-buffer (get-buffer-create helm-debug-buffer)
      (outline-mode)
      (buffer-disable-undo)
      (let ((inhibit-read-only t))
        (goto-char (point-max))
        (insert (let ((tm (current-time)))
                  (format (concat (if (string-match "Start session" format-string)
                                      "* " "** ")
                                  "%s.%06d (%s)\n %s\n")
                          (format-time-string "%H:%M:%S" tm)
                          (nth 2 tm)
                          (helm-log-get-current-function)
                          (apply #'format (cons format-string args)))))))))

(defun helm-log-run-hook (hook)
  "Run HOOK like `run-hooks' but write these actions to Helm log buffer."
  (helm-log "Executing %s with value = %S" hook (symbol-value hook))
  (helm-log "Executing %s with global value = %S" hook (default-value hook))
  (run-hooks hook)
  (helm-log "executed %s" hook))

(defvar helm--log-exclude-functions '(helm-interpret-value
                                      helm-log
                                      helm-log-get-current-function
                                      helm-log-error
                                      helm-log-save-maybe
                                      helm-log-run-hook
                                      helm-apply-functions-from-source
                                      helm-funcall-with-source helm-funcall-foreach
                                      helm-compute-attr-in-sources))
(defun helm-log-get-current-function ()
  "Get name of function calling `helm-log'."
  (cl-loop for btn from 1 to 40
           for btf = (cl-second (backtrace-frame btn))
           for fn  = (if (symbolp btf) (symbol-name btf) "")
           if (and (string-match "\\`helm" fn)
                   (not (memq btf helm--log-exclude-functions)))
           return fn))

(defun helm-log-error (&rest args)
  "Accumulate error messages into `helm-issued-errors'.
ARGS are args given to `format'.
E.g. (helm-log-error \"Error %s: %s\" (car err) (cdr err))."
  (apply 'helm-log (concat "ERROR: " (car args)) (cdr args))
  (let ((msg (apply 'format args)))
    (unless (member msg helm-issued-errors)
      (cl-pushnew msg helm-issued-errors :test 'equal))))

(defun helm-log-save-maybe ()
  "Save log buffer when `helm-debug-root-directory' is non nil.
Create `helm-debug-root-directory' directory if necessary.
Messages are logged to a file named with today's date and time in
this directory."
  (when (and (stringp helm-debug-root-directory)
             (not (file-directory-p helm-debug-root-directory)))
    (make-directory helm-debug-root-directory t))
  (when helm-debug
    (let ((logdir (expand-file-name (concat "helm-debug-"
                                            (format-time-string "%Y%m%d"))
                                    helm-debug-root-directory)))
      (make-directory logdir t)
      (with-current-buffer (get-buffer-create helm-debug-buffer)
        (goto-char (point-max))
        (insert "\


Local Variables:
mode: outline
End:")
        (write-region (point-min) (point-max)
                      (setq helm--last-log-file
                            (expand-file-name
                             (format-time-string "%Y%m%d-%H%M%S")
                             logdir))
                      nil 'silent)
        (kill-buffer))))
  (setq helm-debug nil))

;;;###autoload
(defun helm-debug-open-last-log ()
  "Open Helm log file or buffer of last Helm session."
  (interactive)
  (if helm--last-log-file
      (progn
        (find-file helm--last-log-file)
        (outline-mode) (view-mode 1) (visual-line-mode 1))
    (switch-to-buffer helm-debug-buffer)
    (view-mode 1) (visual-line-mode 1)))

(defun helm-print-error-messages ()
  "Print error messages in `helm-issued-errors'."
  (and helm-issued-errors
       (message "Helm issued errors: %s"
                (mapconcat 'identity (reverse helm-issued-errors) "\n"))))


;; Test tools
(defmacro with-helm-time-after-update (&rest body)
  (helm-with-gensyms (start-time time-elapsed)
    `(let ((,start-time (float-time)) ,time-elapsed)
       (add-hook 'helm-after-update-hook
                 (lambda ()
                   (setq ,time-elapsed (- (float-time) ,start-time))
                   (keyboard-quit)))
       (unwind-protect ,@body
         (remove-hook 'helm-after-update-hook
                      (lambda ()
                        (setq  ,time-elapsed (- (float-time) ,start-time))
                        (keyboard-quit))))
       ,time-elapsed)))


;; Helm API
(defmacro with-helm-default-directory (directory &rest body)
  (declare (indent 1) (debug t))
  `(let ((default-directory (or (and ,directory
                                     (file-name-as-directory ,directory))
                                default-directory)))
     ,@body))

(defun helm-default-directory ()
  "Return the local value of `default-directory' in `helm-buffer'."
  (buffer-local-value 'default-directory (get-buffer helm-buffer)))

(defmacro with-helm-temp-hook (hook &rest body)
  "Execute temporarily BODY as a function for HOOK."
  (declare (indent 1) (debug t))
  (helm-with-gensyms (helm--hook)
    `(progn
       (defun ,helm--hook ()
         (unwind-protect
             (progn ,@body)
           (remove-hook ,hook (quote ,helm--hook))
           (fmakunbound (quote ,helm--hook))))
       (push (cons ',helm--hook ,hook) helm--temp-hooks)
       (add-hook ,hook (quote ,helm--hook)))))

(defmacro with-helm-after-update-hook (&rest body)
  "Execute BODY at end of `helm-update'."
  (declare (indent 0) (debug t))
  `(with-helm-temp-hook 'helm-after-update-hook ,@body))

(defmacro with-helm-alive-p (&rest body)
  "Return error when BODY run outside Helm context."
  (declare (indent 0) (debug t))
  `(progn
     (if helm-alive-p
         (progn ,@body)
       (error "Running helm command outside of context"))))

(defmacro with-helm-in-frame (&rest body)
  "Execute Helm function in BODY displaying `helm-buffer' in separate frame."
  (declare (debug t) (indent 0))
  `(progn
     (helm-set-local-variable
      'helm-display-function 'helm-display-buffer-in-own-frame)
     ,@body))

;;; helm-attributes
;;
(defun helm-attr (attribute-name &optional source compute)
  "Get the value of ATTRIBUTE-NAME of SRC.

If SRC is omitted, use current source.

If COMPUTE is non-`nil' compute value of ATTRIBUTE-NAME with
`helm-interpret-value'.  COMPUTE can have also 'ignorefn as value,
in this case `helm-interpret-value' will return a function as
value unchanged, but will eval a symbol which is bound.

You can use `setf' to modify value of ATTRIBUTE-NAME unless
COMPUTE is specified, if attribute ATTRIBUTE-NAME is not found in
SOURCE `setf' will create new attribute ATTRIBUTE-NAME with
specified value.  You can also use `helm-attrset' to modify
ATTRIBUTE-NAME."
  (declare (gv-setter
            (lambda (val)
              `(let* ((src (or ,source (helm-get-current-source)))
                      (attr (assq ,attribute-name src)))
                 (cl-assert (null ,compute) nil
                            "`setf' can't set the computed value of attribute `%s'"
                            ,attribute-name)
                 (if attr
                     (setcdr attr ,val)
                   (and (setcdr src (cons (cons ,attribute-name ,val)
                                          (cdr src)))
                        ,val))))))
  (let ((src (or source (helm-get-current-source))))
    (helm-aif (assq attribute-name src)
        (if compute
            (helm-interpret-value (cdr it) src compute)
          (cdr it)))))

;; (helm-aif (assq attribute-name src)
;; (let* ((val     (cdr it))
;; When attr exists but have no cdr it is equal to `t'.
;; (attrval (or val t)))
;; Attributes with a boolean value have no cdr, so no need
;; to compute a value == to t.
;; (if (and compute val)
;; (helm-interpret-value val src compute)
;; attrval)))))

(cl-defun helm-attrset (attribute-name value
                                       &optional
                                       (src (helm-get-current-source)))
  "Set the value of ATTRIBUTE-NAME of source SRC to VALUE.

If ATTRIBUTE-NAME doesn't exists in source it is created with
value VALUE.  If SRC is omitted, use current source.  If operation
succeed, return value, otherwise nil.

Note that `setf' on `helm-attr' can be used instead of this
function."
  (setf (helm-attr attribute-name src) value))

(defun helm-add-action-to-source (name fn source &optional index)
  "Add new action NAME linked to function FN to SOURCE.
Function FN should be a valid function that takes one arg i.e.
candidate, argument NAME is a string that will appear in action
menu and SOURCE should be an existing helm source already loaded.
If INDEX is specified, action is added to the action list at INDEX,
otherwise added at end.
This allows users to add specific actions to an existing source
without modifying source code."
  (let ((actions    (helm-attr 'action source 'ignorefn))
        (new-action (list (cons name fn))))
    (when (functionp actions)
      (setq actions (list (cons "Default action" actions))))
    (helm-attrset 'action
                  (if index
                      (helm-append-at-nth actions new-action index)
                    (append actions new-action))
                  source)))

(defun helm-delete-action-from-source (action-or-name source)
  "Delete ACTION-OR-NAME from SOURCE.
ACTION-OR-NAME can either be the name of action or the symbol
function associated to name."
  (let* ((actions    (helm-attr 'action source 'ignorefn))
         (del-action (if (symbolp action-or-name)
                         (rassoc action-or-name actions)
                       (assoc action-or-name actions))))
    (helm-attrset 'action (delete del-action actions) source)))

(cl-defun helm-add-action-to-source-if (name fn source predicate
                                             &optional (index 4) test-only)
  "Add new action NAME linked to function FN to SOURCE.
Action NAME will be available when the current candidate matches
PREDICATE.
This function adds an entry in the `action-transformer' attribute
of SOURCE (or creates one if not found).
Function PREDICATE must take one candidate as arg.
Function FN should be a valid function that takes one arg i.e.
candidate, argument NAME is a string that will appear in action
menu and SOURCE should be an existing Helm source already loaded.
If INDEX is specified, action is added in action list at INDEX.
Value of INDEX should be always >=1, default to 4.  This allows
user to add a specific `action-transformer' to an existing source
without modifying source code.

E.g.

Add the action \"Byte compile file async\" linked to function
'async-byte-compile-file to source `helm-source-find-files' only
when predicate helm-ff-candidates-lisp-p returns non-nil:

\(helm-add-action-to-source-if \"Byte compile file async\"
                              'async-byte-compile-file
                              helm-source-find-files
                              'helm-ff-candidates-lisp-p\)."
  (let* ((actions     (helm-attr 'action source 'ignorefn))
         (action-transformers (helm-attr 'action-transformer source))
         (new-action  (list (cons name fn)))
         (transformer (lambda (actions candidate)
                        (cond ((funcall predicate candidate)
                               (helm-append-at-nth
                                actions new-action index))
                              (t actions)))))
    (when (functionp actions)
      (helm-attrset 'action (list (cons "Default action" actions)) source))
    (when (or (symbolp action-transformers) (functionp action-transformers))
      (setq action-transformers (list action-transformers)))
    (if test-only                       ; debug
        (delq nil (append (list transformer) action-transformers))
      (helm-attrset 'action-transformer
                    (helm-fast-remove-dups
                     (delq nil (append (list transformer) action-transformers))
                     :test 'equal)
                    source))))


;;; Source filter
;;
(defun helm-set-source-filter (sources)
  "Set the value of `helm-source-filter' to SOURCES and update.

This function sets a filter for Helm sources and it may be called
while Helm is running.  It can be used to toggle displaying of
sources dynamically.  For example, additional keys can be bound
into `helm-map' to display only the file-related results if there
are too many matches from other sources and you're after files
only:

Shift+F shows only file results from some sources:

\(define-key helm-map \"F\" 'helm-my-show-files-only)

\(defun helm-my-show-files-only ()
  (interactive)
  (helm-set-source-filter '(\"File Name History\"
                                  \"Files from Current Directory\")))

Shift+A shows all results:

\(define-key helm-map \"A\" 'helm-my-show-all)

\(defun helm-my-show-all ()
  (interactive)
  (helm-set-source-filter nil))

The -my- part is added to avoid collisions with
existing Helm function names."
  (with-helm-buffer
    (let ((cur-disp-sel (helm-get-selection nil t)))
      (set (make-local-variable 'helm-source-filter)
           (helm--normalize-filter-sources sources))
      (helm-log "helm-source-filter = %S" helm-source-filter)
      ;; Use force-update to run init/update functions.
      (helm-update (and (stringp cur-disp-sel)
                        (regexp-quote cur-disp-sel))))))

(defun helm--normalize-filter-sources (sources)
  (cl-loop for s in sources collect
           (cl-typecase s
             (symbol (assoc-default 'name (symbol-value s)))
             (list   (assoc-default 'name s))
             (string s))))

(defun helm-set-sources (sources &optional no-init no-update)
  "Set SOURCES during `helm' invocation.
If NO-INIT is non-nil, skip executing init functions of SOURCES.
If NO-UPDATE is non-nil, skip executing `helm-update'."
  (with-current-buffer helm-buffer
    (setq helm-sources (helm-get-sources sources))
    (helm-log "helm-sources = %S" helm-sources))
  (unless no-init (helm-compute-attr-in-sources 'init))
  (unless no-update (helm-update)))

(defun helm-get-selection (&optional buffer force-display-part source)
  "Return the currently selected item or nil.

If BUFFER is nil or unspecified, use `helm-buffer' as default value.
If FORCE-DISPLAY-PART is non-nil, return the display string.
If FORCE-DISPLAY-PART value is `withprop' the display string is returned
with its properties."
  (setq buffer (or buffer helm-buffer))
  (unless (or (helm-empty-buffer-p buffer)
              (helm-pos-header-line-p))
    (with-current-buffer buffer
      (let* ((disp-fn (if (eq force-display-part 'withprop)
                          'buffer-substring
                        'buffer-substring-no-properties))
             (selection
              (or (and (not force-display-part)
                       (get-text-property (overlay-start
                                           helm-selection-overlay)
                                          'helm-realvalue))
                  ;; It is needed to return properties of DISP in some case,
                  ;; e.g for `helm-confirm-and-exit-minibuffer',
                  ;; so use `buffer-substring' here when 'withprop is specified.
                  (let* ((beg  (overlay-start helm-selection-overlay))
                         (end  (overlay-end helm-selection-overlay))
                         ;; If there is no selection at point, the
                         ;; overlay is at its initial pos, (point-min)
                         ;; (point-min), that's mean the helm-buffer
                         ;; is not empty but have no selection yet,
                         ;; this happen with grep sentinel sending an
                         ;; error message in helm-buffer when no matches.
                         (disp (unless (= beg end) (funcall disp-fn beg (1- end))))
                         (src (or source (helm-get-current-source))))
                    (helm-aif (and src disp
                                   (not force-display-part)
                                   (assoc-default 'display-to-real src))
                        (helm-apply-functions-from-source source it disp)
                      disp)))))
        (unless (equal selection "")
          (helm-log "selection = %S" selection)
          selection)))))

(defun helm-get-actions-from-current-source (&optional source)
  "Return the associated action for the selected candidate.
It is a function symbol (sole action) or list
of (action-display . function)."
  (unless (helm-empty-buffer-p (helm-buffer-get))
    (let ((src (helm-get-current-source)))
      (helm-aif (helm-attr 'action-transformer)
          (helm-apply-functions-from-source
           (or source src) it
           (helm-attr 'action nil 'ignorefn)
           ;; Check if the first given transformer
           ;; returns the same set of actions for each
           ;; candidate in marked candidates.
           ;; If so use the car of marked to determine
           ;; the set of actions, otherwise use the selection.
           (if (cl-loop with marked = (helm-marked-candidates)
                        with act = (car (helm-mklist it))
                        with acts = (funcall act nil (car marked))
                        for c in marked
                        always (equal (funcall act nil c) acts))
               (car (helm-marked-candidates))
             (helm-get-selection nil nil src)))
        (helm-attr 'action nil 'ignorefn)))))

(defun helm-get-current-source ()
  "Return the source for the current selection.
Return nil when `helm-buffer' is empty."
  (or helm-current-source
      (with-helm-buffer
        (or (get-text-property (point) 'helm-cur-source)
            (progn
              ;; This is needed to not loose selection.
              (goto-char (overlay-start helm-selection-overlay))
              (let ((header-pos (or (helm-get-previous-header-pos)
                                    (helm-get-next-header-pos))))
                ;; Return nil when no--candidates.
                (when header-pos
                  (cl-loop with source-name = (save-excursion
                                                (goto-char header-pos)
                                                (helm-current-line-contents))
                           for source in helm-sources thereis
                           (and (equal (assoc-default 'name source) source-name)
                                source)))))))))

(defun helm-buffer-is-modified (buffer)
  "Return non-nil when BUFFER is modified since Helm was invoked."
  (let* ((buf         (get-buffer buffer))
         (key         (concat (buffer-name buf) "/" (helm-attr 'name)))
         (source-tick (or (gethash key helm-tick-hash) 0))
         (buffer-tick (buffer-chars-modified-tick buf))
         (modifiedp   (/= source-tick buffer-tick)))
    (puthash key buffer-tick helm-tick-hash)
    (helm-log "buffer = %S" buffer)
    (helm-log "modifiedp = %S" modifiedp)
    modifiedp))

(defun helm-current-buffer-is-modified ()
  "Check if `helm-current-buffer' is modified since Helm was invoked."
  (helm-buffer-is-modified helm-current-buffer))

(defun helm-run-after-exit (function &rest args)
  "Execute FUNCTION with ARGS after exiting Helm.
The action is to call FUNCTION with arguments ARGS.
Unlike `helm-exit-and-execute-action', this can be used
to call non-actions functions with any ARGS or no ARGS at all.

Use this on commands invoked from key bindings, but not on action
functions invoked as action from the action menu, i.e. functions
called with RET."
  (helm-kill-async-processes)
  (helm-log "function = %S" function)
  (helm-log "args = %S" args)
  (helm-exit-and-execute-action
   (lambda (_candidate)
     (apply function args))))

(defun helm-exit-and-execute-action (action)
  "Exit current Helm session and execute ACTION.
Argument ACTION is a function called with one arg (candidate) and
part of the actions of current source.

Use this on commands invoked from key bindings, but not
on action functions invoked as action from the action menu,
i.e. functions called with RET."
  ;; If ACTION is not an action available in source 'action attribute,
  ;; return an error.  This allow to remove unneeded actions from
  ;; source that inherit actions from type, note that ACTION have to
  ;; be bound to a symbol and not to be an anonymous action
  ;; i.e. lambda or byte-code.
  (let ((actions (helm-get-actions-from-current-source)))
    (when actions
      (cl-assert (or (eq action actions)
                     ;; Compiled lambdas
                     (byte-code-function-p action)
                     ;; Natively compiled (libgccjit)
                     (helm-subr-native-elisp-p action)
                     ;; Lambdas
                     (and (listp action) (functionp action))
                     ;; One of current actions.
                     (rassq action actions))
                 nil "No such action `%s' for this source" action)))
  (setq helm-saved-action action)
  (setq helm-saved-selection (or (helm-get-selection) ""))
  (setq helm--executing-helm-action t)
  ;; When toggling minibuffer and header-line, we want next action
  ;; inherit this setting.
  (helm-set-local-variable 'helm-echo-input-in-header-line
                           (with-helm-buffer helm-echo-input-in-header-line))
  ;; Ensure next action use same display function as initial helm-buffer when
  ;; helm-actions-inherit-frame-settings is non nil.
  (when (and helm-actions-inherit-frame-settings
             helm--buffer-in-new-frame-p)
    (helm-set-local-variable 'helm-display-function
                             (with-helm-buffer helm-display-function)
                             'helm--last-frame-parameters
                             (with-helm-buffer
                               (helm--get-frame-parameters)))
    ;; The helm-buffer keeps `helm-display-function' and
    ;; `helm--get-frame-parameters' values during 0.5 seconds, just
    ;; the time to execute the possible helm action with those values.
    ;; If no helm based action run within 0.5 seconds, the next helm
    ;; session will have to resolve again those variable values.
    (run-with-idle-timer 0.5 nil
                         (lambda () (helm-set-local-variable 'helm-display-function nil
                                                             'helm--last-frame-parameters nil))))
  (helm-exit-minibuffer))

(defun helm--get-frame-parameters (&optional frame)
  (cl-loop with params = (frame-parameters frame)
           for p in helm--frame-default-attributes
           when (assq p params) collect it))

(defalias 'helm-run-after-quit 'helm-run-after-exit)
(make-obsolete 'helm-run-after-quit 'helm-run-after-exit "1.7.7")
(defalias 'helm-quit-and-execute-action 'helm-exit-and-execute-action)
(make-obsolete 'helm-quit-and-execute-action 'helm-exit-and-execute-action "1.7.7")

(defun helm-interpret-value (value &optional source compute)
  "Interpret VALUE as variable, function or literal and return it.
If VALUE is a function, call it with no arguments and return the value
unless COMPUTE value is 'ignorefn.
If SOURCE compute VALUE for this source.
If VALUE is a variable, return the value.
If VALUE is a symbol, but it is not a function or a variable, cause an error.
Otherwise, return VALUE itself."
  (cond ((and source (functionp value) (not (eq compute 'ignorefn)))
         (helm-apply-functions-from-source source value))
        ((and (functionp value) (not (eq compute 'ignorefn)))
         (funcall value))
        ((and (symbolp value) (boundp value))
         (symbol-value value))
        ((and (symbolp value) (not (functionp value)))
         (error
          "helm-interpret-value: Symbol must be a function or a variable"))
        (t
         value)))

(defun helm-set-local-variable (&rest args)
  "Bind each pair in ARGS locally to `helm-buffer'.

Use this to set local vars before calling helm.

When used from an init or update function
\(i.e. when `helm-force-update' is running) the variables are set
using `make-local-variable' within the `helm-buffer'.

Usage: helm-set-local-variable ([VAR VALUE]...)
Just like `setq' except that the vars are not set sequentially.
IOW Don't use VALUE of previous VAR to set the VALUE of next VAR.

\(fn VAR VALUE ...)"
  (if helm--force-updating-p
      (with-helm-buffer
        (cl-loop for i on args by #'cddr
                 do (set (make-local-variable (car i)) (cadr i))))
    (setq helm--local-variables
          (append (cl-loop for i on args by #'cddr
                           collect (cons (car i) (cadr i)))
                  helm--local-variables))))

(defun helm--set-local-variables-internal ()
  (cl-loop for (var . val) in helm--local-variables
           ;; If `helm-set-local-variable' is called twice or more
           ;; on same variable use the last value entered which is
           ;; the first on stack e.g.
           ;; (helm-set-local-variable 'helm-foo 1)
           ;; (helm-set-local-variable 'helm-foo 2)
           ;; helm--local-variables =>
           ;; '((helm-foo . 2) (helm-foo. 1))
           ;; (helm-foo . 2) is retained and (helm-foo . 1)
           ;; ignored.
           unless (memq var computed)
           do (set (make-local-variable var) val)
           collect var into computed
           finally (setq helm--local-variables nil)))


;; API helper
(cl-defun helm-empty-buffer-p (&optional (buffer helm-buffer))
  "Check if BUFFER have candidates.
Default value for BUFFER is `helm-buffer'."
  (zerop (buffer-size (and buffer (get-buffer buffer)))))

(defun helm-empty-source-p ()
  "Check if current source contains candidates.
This could happen when for example the last element of a source
was deleted and the candidates list not updated."
  (when (helm-window)
    (with-helm-window
      (or (helm-empty-buffer-p)
          (and (helm-end-of-source-p)
               (eq (point-at-bol) (point-at-eol))
               (or
                (save-excursion
                  (forward-line -1)
                  (helm-pos-header-line-p))
                (bobp)))))))


;; Tools
;;
(defun helm-apply-functions-from-source (source functions &rest args)
  "From SOURCE apply FUNCTIONS on ARGS.

This function is used to process filter functions.  When filter is
a \`filtered-candidate-transformer', we pass to ARGS
candidates+source whereas when the filter is
`candidate-transformer' we pass to ARGS candidates only.
This function is also used to process functions called with no
args, e.g. init functions.  In this case it is called without
ARGS.
See `helm-process-filtered-candidate-transformer'
\`helm-compute-attr-in-sources' and
\`helm-process-candidate-transformer'.

Arg FUNCTIONS is either a symbol or a list of functions, each
function being applied on ARGS and called on the result of the
precedent function.  Return the result of last function call."
  (let ((helm--source-name (assoc-default 'name source))
        (helm-current-source source)
        (funs (if (functionp functions) (list functions) functions)))
    (cl-loop with result
             for fn in funs
             do (setq result (apply fn args))
             when (and args (cdr funs))
             ;; In filter functions, ARGS is a list of one or two elements where
             ;; the first element is the list of candidates and the second
             ;; a list containing the source.
             ;; When more than one fn, set the candidates list to what returns
             ;; this fn to compute the modified candidates with the next fn
             ;; and so on.
             do (setcar args result)
             finally return result)))

(defalias 'helm-funcall-with-source 'helm-apply-functions-from-source)
(make-obsolete 'helm-funcall-with-source 'helm-apply-functions-from-source "2.9.7")

(defun helm-compute-attr-in-sources (attr &optional sources)
  "Call the associated function(s) to ATTR for each source if any."
  (let ((sources (or (helm-get-sources sources)
                     ;; Fix error no buffer named *helm... by checking
                     ;; if helm-buffer exists.
                     (and (buffer-live-p (get-buffer (helm-buffer-get)))
                          ;; `helm-sources' are local to helm-buffer.
                          (with-helm-buffer helm-sources)))))
    (when sources
      (cl-dolist (source sources)
        (helm-aif (assoc-default attr source)
            (helm-apply-functions-from-source source it))))))

(defalias 'helm-funcall-foreach 'helm-compute-attr-in-sources)
(make-obsolete 'helm-funcall-foreach 'helm-compute-attr-in-sources "2.9.7")

(defun helm-normalize-sources (sources)
  "If SOURCES is only one source, make a list of one element."
  (if (or (and sources (symbolp sources))
          (and (listp sources) (assq 'name sources)))
      (list sources)
    sources))

(defun helm-get-candidate-number (&optional in-current-source)
  "Return candidates number in `helm-buffer'.
If IN-CURRENT-SOURCE is provided return the number of candidates
of current source only."
  (with-helm-buffer
    (if (or (helm-empty-buffer-p)
            (helm-empty-source-p))
        0
      (save-excursion
        (helm-aif (and in-current-source (helm-get-previous-header-pos))
            (goto-char it)
          (goto-char (point-min)))
        (forward-line 1)
        (if (helm-pos-multiline-p)
            (cl-loop with count-multi = 1
                     while (and (not (if in-current-source
                                         (save-excursion
                                           (forward-line 2)
                                           (or (helm-pos-header-line-p) (eobp)))
                                       (eobp)))
                                (search-forward helm-candidate-separator nil t))
                     do (cl-incf count-multi)
                     finally return count-multi)
          (cl-loop with ln = 0
                   while (not (if in-current-source
                                  (or (helm-pos-header-line-p) (eobp))
                                (eobp)))
                   ;; Don't count empty lines maybe added by popup (#1370).
                   unless (or (eq (point-at-bol) (point-at-eol))
                              (helm-pos-header-line-p))
                   do (cl-incf ln)
                   do (forward-line 1) finally return ln))))))

(defmacro with-helm-quittable (&rest body)
  "If an error occurs in execution of BODY, safely quit helm."
  (declare (indent 0) (debug t))
  `(condition-case _v
       (let (inhibit-quit)
         ,@body)
     (quit (setq quit-flag t)
           (setq helm-quit t)
           (exit-minibuffer)
           (keyboard-quit)
           ;; See comment about this in `with-local-quit'.
           (eval '(ignore nil)))))

;; Entry point
;; `:allow-nest' is not in this list because it is treated before.
(defconst helm-argument-keys
  '(:sources :input :prompt :resume
             :preselect :buffer :keymap :default :history))

;;;###autoload
(defun helm (&rest plist)
  "Main function to execute helm sources.

PLIST is a list like

\(:key1 val1 :key2 val2 ...\)

 or

\(&optional sources input prompt resume preselect
            buffer keymap default history allow-nest\).

** Keywords

Keywords supported:

- :sources
- :input
- :prompt
- :resume
- :preselect
- :buffer
- :keymap
- :default
- :history
- :allow-nest

Extra LOCAL-VARS keywords are supported, see the \"** Other
keywords\" section below.

Basic keywords are the following:

*** :sources

One of the following:

- List of sources
- Symbol whose value is a list of sources
- Alist representing a Helm source.
  - In this case the source has no name and is referenced in
    `helm-sources' as a whole alist.

*** :input

Initial input of minibuffer (temporary value of `helm-pattern')

*** :prompt

Minibuffer prompt. Default value is `helm--prompt'.

*** :resume

If t, allow resumption of the previous session of this Helm
command, skipping initialization.

If 'noresume, this instance of `helm' cannot be resumed.

*** :preselect

Initially selected candidate (string or regexp).

*** :buffer

Buffer name for this Helm session. `helm-buffer' will take this value.

*** :keymap

\[Obsolete]

Keymap used at the start of this Helm session.

It is overridden by keymaps specified in sources, and is kept
only for backward compatibility.

Keymaps should be specified in sources using the :keymap slot
instead. See `helm-source'.

This keymap is not restored by `helm-resume'.

*** :default

Default value inserted into the minibuffer \ with
\\<minibuffer-local-map>\\[next-history-element].

It can be a string or a list of strings, in this case
\\<minibuffer-local-map>\\[next-history-element] cycles through
the list items, starting with the first.

If nil, `thing-at-point' is used.

If `helm-maybe-use-default-as-input' is non-nil, display is
updated using this value if this value matches, otherwise it is
ignored. If :input is specified, it takes precedence on :default.

*** :history

Minibuffer input, by default, is pushed to `minibuffer-history'.

When an argument HISTORY is provided, input is pushed to
HISTORY. HISTORY should be a valid symbol.

*** :allow-nest

Allow running this Helm command in a running Helm session.

** Other keywords

Other keywords are interpreted as local variables of this Helm
session. The `helm-' prefix can be omitted. For example,

\(helm :sources 'helm-source-buffers-list
       :buffer \"*helm buffers*\"
       :candidate-number-limit 10\)

Starts a Helm session with the variable
`helm-candidate-number-limit' set to 10.

** Backward compatibility

For backward compatibility, positional parameters are
supported:

\(helm sources input prompt resume preselect
       buffer keymap default history allow-nest\)

However, the use of non-keyword args is deprecated.

\(fn &key SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT HISTORY ALLOW-NEST OTHER-LOCAL-VARS)"
  (let ((fn (cond ((or (and helm-alive-p (plist-get plist :allow-nest))
                       (and helm-alive-p (memq 'allow-nest plist)))
                   #'helm--nest)
                  ((keywordp (car plist))
                   #'helm)
                  (t #'helm-internal))))
    (if (and helm-alive-p (eq fn #'helm))
        (if (helm--alive-p)
            ;; A helm session is normally running.
            (error "Error: Trying to run helm within a running helm session")
          ;; A helm session is already running and user jump somewhere else
          ;; without deactivating it.
          (with-helm-buffer
            (prog1
                (message "Aborting an helm session running in background")
              ;; `helm-alive-p' will be reset in unwind-protect forms.
              (helm-keyboard-quit))))
      (if (keywordp (car plist))
          ;; Parse `plist' and move not regular `helm-argument-keys'
          ;; to `helm--local-variables', then calling helm on itself
          ;; with normal arguments (the non--arguments-keys removed)
          ;; will end up in [1].
          (progn
            (setq helm--local-variables
                  (append helm--local-variables
                          ;; Vars passed by keyword on helm call
                          ;; take precedence on same vars
                          ;; that may have been passed before helm call.
                          (helm-parse-keys plist)))
            (apply fn (mapcar (lambda (key) (plist-get plist key))
                              helm-argument-keys)))
        (apply fn plist))))) ; [1] fn == helm-internal.

(defun helm--alive-p ()
  "[INTERNAL] Check if `helm' is alive.
An Helm session is considered alive if `helm-alive-p' value is
non-nil, the `helm-buffer' is visible, and cursor is in the
minibuffer."
  (and helm-alive-p
       (get-buffer-window (helm-buffer-get) 'visible)
       (minibuffer-window-active-p (minibuffer-window))
       (minibufferp (current-buffer))))

(defun helm-parse-keys (keys)
  "Parse the KEYS arguments of `helm'.
Return only those keys not in `helm-argument-keys', prefix them
with \"helm\", and then convert them to an alist.  This allows
adding arguments that are not part of `helm-argument-keys', but
are valid helm variables nevertheless.  For example,
:candidate-number-limit is bound to `helm-candidate-number-limit'
in the source.

  (helm-parse-keys '(:sources ((name . \"test\")
                               (candidates . (a b c)))
                     :buffer \"toto\"
                     :candidate-number-limit 4))
  ==> ((helm-candidate-number-limit . 4))."

  (cl-loop for (key value) on keys by #'cddr
           for symname = (substring (symbol-name key) 1)
           for sym = (intern (if (string-match "^helm-" symname)
                                 symname
                               (concat "helm-" symname)))
           unless (memq key helm-argument-keys)
           collect (cons sym value)))

;;; Entry point helper
(defun helm-internal (&optional
                      sources input
                      prompt resume
                      preselect buffer
                      keymap default history)
  "The internal Helm function called by `helm'.
For SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT and
HISTORY args see `helm'."
  (cl-assert (or (stringp input)
                 (null input))
             nil "Error in %S buffer: Initial input should be a string or nil"
             buffer)
  (unless helm--nested (setq helm-initial-frame (selected-frame)))
  ;; Activate the advices.
  ;; Advices will be available only in >=emacs-24.4, but
  ;; allow compiling without errors on lower emacs.
  (when (fboundp 'advice-add)
    (advice-add 'tramp-read-passwd :around #'helm--suspend-read-passwd)
    (advice-add 'ange-ftp-get-passwd :around #'helm--suspend-read-passwd)
    (advice-add 'epa-passphrase-callback-function
                :around #'helm--suspend-read-passwd)
    ;; Ensure linum-mode is disabled in Helm buffers to preserve
    ;; performances (Issue #1894).
    (advice-add 'linum-on :override #'helm--advice-linum-on '((depth . 100))))
  (helm-log (concat "[Start session] " (make-string 41 ?+)))
  (helm-log "prompt = %S" prompt)
  (helm-log "preselect = %S" preselect)
  (helm-log "buffer = %S" buffer)
  (helm-log "keymap = %S" keymap)
  (helm-log "default = %S" default)
  (helm-log "history = %S" history)
  (setq helm--prompt (or prompt "pattern: "))
  (let ((non-essential t)
        ;; Prevent mouse jumping to the upper-right
        ;; hand corner of the frame (#1538).
        mouse-autoselect-window
        focus-follows-mouse
        mode-line-in-non-selected-windows
        minibuffer-completion-confirm
        (input-method-verbose-flag helm-input-method-verbose-flag)
        (helm-maybe-use-default-as-input
         (and (null input)
              (or helm-maybe-use-default-as-input ; it is let-bounded so use it.
                  (cl-loop for s in (helm-normalize-sources sources)
                           thereis (memq s helm-sources-using-default-as-input))))))
    (unwind-protect
        (condition-case-unless-debug _v
            (let ( ;; `helm--source-name' is non-`nil'
                  ;; when `helm' is invoked by action, reset it.
                  helm--source-name
                  helm-current-source
                  helm-in-persistent-action
                  helm-quit
                  (helm-buffer (or buffer helm-buffer)))
              (helm-initialize
               resume input default sources)
              ;; We don't display helm-buffer here to avoid popping
              ;; up a window or a frame when exiting immediately when
              ;; only one candidate (this avoid having the helm frame
              ;; flashing), lets first compute candidates and if more
              ;; than one display helm-buffer (this is done later in
              ;; helm-read-pattern-maybe).
              (unless helm-execute-action-at-once-if-one
                (helm-display-buffer helm-buffer resume)
                (select-window (helm-window)))
              ;; We are now in helm-buffer.
              (unless helm-allow-mouse
                (helm--remap-mouse-mode 1)) ; Disable mouse bindings.
              (add-hook 'post-command-hook 'helm--maybe-update-keymap)
              ;; Add also to update hook otherwise keymap is not updated
              ;; until a key is hitted (Issue #1670).
              (add-hook 'helm-after-update-hook 'helm--maybe-update-keymap)
              (add-hook 'post-command-hook 'helm--update-header-line)
              (helm-log "show prompt")
              (unwind-protect
                  (helm-read-pattern-maybe
                   prompt input preselect
                   resume keymap default history)
                (helm-cleanup))
              (prog1
                  (unless helm-quit (helm-execute-selection-action))
                (helm-log (concat "[End session] " (make-string 41 ?-)))))
          (quit
           (helm-restore-position-on-quit)
           (helm-log-run-hook 'helm-quit-hook)
           (helm-log (concat "[End session (quit)] " (make-string 34 ?-)))
           nil))
      (when (fboundp 'advice-remove)
        (advice-remove 'tramp-read-passwd #'helm--suspend-read-passwd)
        (advice-remove 'ange-ftp-get-passwd #'helm--suspend-read-passwd)
        (advice-remove 'epa-passphrase-callback-function #'helm--suspend-read-passwd)
        (advice-remove 'linum-on #'helm--advice-linum-on))
      (helm-log "helm-alive-p = %S" (setq helm-alive-p nil))
      (helm--remap-mouse-mode -1)       ; Reenable mouse bindings.
      (setq helm-alive-p nil)
      ;; Prevent error "No buffer named *helm*" triggered by
      ;; `helm-set-local-variable'.
      (setq helm--force-updating-p nil)
      (setq helm--buffer-in-new-frame-p nil)
      ;; Reset helm-pattern so that lambda's using it
      ;; before running helm will not start with its old value.
      (setq helm-pattern "")
      (setq helm--ignore-errors nil)
      (helm-log-save-maybe))))

(defun helm--advice-linum-on ()
  (unless (or (minibufferp)
              (string-match "\\`\\*helm" (buffer-name))
              (and (daemonp) (null (frame-parameter nil 'client))))
    (linum-mode 1)))

;;; Helm resume
;;
;;
(defun helm-resume (arg)
  "Resume a previous Helm session.
Call with a prefix arg to choose among existing Helm
buffers (sessions).  When calling from Lisp, specify a
`buffer-name' as a string with ARG."
  (interactive "P")
  (let (buffer
        cur-dir
        narrow-pos
        (helm-full-frame (default-value 'helm-full-frame))
        sources)
    (if arg
        (if (and (stringp arg) (bufferp (get-buffer arg)))
            (setq buffer arg)
          (setq buffer (helm-resume-select-buffer)))
      (setq buffer helm-last-buffer))
    (cl-assert buffer nil
               "helm-resume: No helm buffers found to resume")
    (setq sources (buffer-local-value
                   'helm-sources (get-buffer buffer)))
    ;; Reset `cursor-type' to nil as it have been set to t
    ;; when quitting previous session.
    (with-current-buffer buffer (setq cursor-type nil))
    (setq helm-full-frame (buffer-local-value
                           'helm-full-frame (get-buffer buffer)))
    (setq cur-dir (buffer-local-value
                   'default-directory (get-buffer buffer)))
    (setq helm-saved-selection nil
          helm-saved-action nil)
    (unless (buffer-live-p helm-current-buffer)
      ;; `helm-current-buffer' may have been killed.
      (setq helm-current-buffer (current-buffer)))
    (helm-aif (with-current-buffer buffer
                helm--current-buffer-narrowed)
        (progn
          (set-buffer (car it))
          (setq narrow-pos (cdr it))))
    ;; This happen when calling C-x b within helm.
    (helm-aif (get-buffer-window helm-marked-buffer-name 'visible)
        (progn (delete-window it) (kill-buffer helm-marked-buffer-name)))
    (save-restriction
      (when narrow-pos (apply #'narrow-to-region narrow-pos))
      ;; Restart with same `default-directory' value this session
      ;; was initially started with.
      (with-helm-default-directory cur-dir
        (unwind-protect
            (helm
             :sources sources
             :input (buffer-local-value 'helm-input-local (get-buffer buffer))
             :prompt (buffer-local-value 'helm--prompt (get-buffer buffer))
             :resume t
             :buffer buffer)
          (run-hook-with-args 'helm-resume-after-hook sources))))))

(defun helm-resume-previous-session-after-quit ()
  "Resume previous Helm session within a running Helm."
  (interactive)
  (with-helm-alive-p
    (let ((arg (if (null (member helm-buffer helm-buffers)) 0 1)))
      (if (> (length helm-buffers) arg)
          (helm-run-after-exit (lambda () (helm-resume (nth arg helm-buffers))))
        (message "No previous helm sessions available for resuming!")))))
(put 'helm-resume-previous-session-after-quit 'helm-only t)

(defun helm-resume-list-buffers-after-quit ()
  "List Helm buffers that can be resumed within a running Helm."
  (interactive)
  (with-helm-alive-p
    (if (> (length helm-buffers) 0)
        (helm-run-after-exit (lambda () (helm-resume t)))
      (message "No previous helm sessions available for resuming!"))))
(put 'helm-resume-list-buffers-after-quit 'helm-only t)

(defun helm-resume-p (resume)
  "Whether current Helm session is resumed or not."
  (eq resume t))

(defun helm-resume-select-buffer ()
  "Select an `helm-buffer' in `helm-buffers' list to resume a helm session.
Return nil if no `helm-buffer' found."
  (when helm-buffers
    (or (helm :sources (helm-build-sync-source "Resume helm buffer"
                         :candidates helm-buffers)
              :resume 'noresume
              :buffer "*helm resume*")
        (keyboard-quit))))

;;;###autoload
(defun helm-cycle-resume ()
  "Cycle in `helm-buffers' list and resume when waiting more than 1.2s."
  (interactive)
  (cl-assert (and helm-buffers helm-last-buffer)
             nil "No helm buffers to resume")
  ;; Setup a new iterator only on first hit on
  ;; `helm-run-cycle-resume', subsequents hits should reuse same
  ;; iterator.
  (unless (and (eq last-command 'helm-cycle-resume)
               helm--cycle-resume-iterator)
    (setq helm--cycle-resume-iterator
          (helm-iter-sub-next-circular
           helm-buffers helm-last-buffer :test 'equal)))
  (helm--resume-or-iter))

(defun helm--resume-or-iter (&optional from-helm)
  (message "Resuming helm buffer `%s'" helm-last-buffer)
  (if (sit-for helm-cycle-resume-delay)
      ;; Delay expire, run helm-resume.
      (if from-helm
          (helm-run-after-exit (lambda () (helm-resume helm-last-buffer)))
        (helm-resume helm-last-buffer))
    ;; key pressed before delay, cycle.
    (unless from-helm ; cycling to next item already done.
      (message "Resuming helm buffer `%s'"
               (setq helm-last-buffer
                     (helm-iter-next helm--cycle-resume-iterator))))))

(defun helm-run-cycle-resume ()
  "Same as `helm-cycle-resume' but intended to be called only from Helm."
  (interactive)
  (when (cdr helm-buffers) ; only one session registered.
    ;; Setup a new iterator only on first hit on
    ;; `helm-run-cycle-resume', subsequents hits should reuse same
    ;; iterator.
    (unless (and (eq last-command 'helm-run-cycle-resume)
                 helm--cycle-resume-iterator)
      (setq helm--cycle-resume-iterator
            (helm-iter-sub-next-circular
             helm-buffers helm-last-buffer :test 'equal)))
    ;; start at next buffer as we already are at `helm-last-buffer'.
    (setq helm-last-buffer
          (helm-iter-next helm--cycle-resume-iterator))
    (helm--resume-or-iter 'from-helm)))
(put 'helm-run-cycle-resume 'helm-only t)


;;;###autoload
(defun helm-other-buffer (sources buffer)
  "Simplified Helm interface with other `helm-buffer'.
Call `helm' only with SOURCES and BUFFER as args."
  (helm :sources sources :buffer buffer))

;;; Nested sessions
;;
;;
(defun helm--nest (&rest same-as-helm)
  "[INTERNAL] Allow calling `helm' within a running Helm session.

Arguments SAME-AS-HELM are the same as `helm'.

Don't use this directly, use instead `helm' with the keyword
:allow-nest.

\(fn &key SOURCES INPUT PROMPT RESUME PRESELECT BUFFER KEYMAP DEFAULT HISTORY OTHER-LOCAL-VARS)"
  (with-helm-window
    (let ((orig-helm-current-buffer helm-current-buffer)
          (orig-helm-buffer helm-buffer)
          (orig-helm--prompt helm--prompt)
          (orig-helm-sources helm-sources)
          (orig-helm--in-fuzzy helm--in-fuzzy)
          (orig-helm--display-frame helm--buffer-in-new-frame-p)
          (orig-helm-last-frame-or-window-configuration
           helm-last-frame-or-window-configuration)
          (orig-one-window-p helm-onewindow-p)
          (helm--nested t))
      ;; FIXME Using helm-full-frame here allow showing the new
      ;; helm-buffer in the same window as old helm-buffer, why?
      (helm-set-local-variable 'helm-full-frame t)
      (unwind-protect
          (let (helm-current-position
                helm-current-buffer
                helm-pattern
                (helm-buffer (or (cl-getf same-as-helm :buffer)
                                 (nth 5 same-as-helm)
                                 "*Helm*"))
                (enable-recursive-minibuffers t))
            (setq helm-sources nil)
            (apply #'helm same-as-helm))
        (with-current-buffer orig-helm-buffer
          (setq helm-sources orig-helm-sources)
          (setq helm--nested nil)
          (setq helm--buffer-in-new-frame-p orig-helm--display-frame)
          (setq helm-alive-p t) ; Nested session set this to nil on exit.
          (setq helm-buffer orig-helm-buffer)
          (setq helm-full-frame nil)
          (setq helm--prompt orig-helm--prompt)
          (setq helm--in-fuzzy orig-helm--in-fuzzy)
          (helm-initialize-overlays helm-buffer)
          (unless (helm-empty-buffer-p) (helm-mark-current-line t))
          (setq helm-last-frame-or-window-configuration
                orig-helm-last-frame-or-window-configuration)
          (setq cursor-type nil)
          (setq helm-current-buffer orig-helm-current-buffer)
          (setq helm-onewindow-p orig-one-window-p)
          ;; Be sure advices, hooks, and local modes keep running.
          (advice-add 'tramp-read-passwd
                      :around #'helm--suspend-read-passwd)
          (advice-add 'ange-ftp-get-passwd
                      :around #'helm--suspend-read-passwd)
          (advice-add 'epa-passphrase-callback-function
                      :around #'helm--suspend-read-passwd)
          (unless helm-allow-mouse
            (helm--remap-mouse-mode 1))
          (unless (cl-loop for h in post-command-hook
                           thereis (memq h '(helm--maybe-update-keymap
                                             helm--update-header-line)))
            (add-hook 'post-command-hook 'helm--maybe-update-keymap)
            (add-hook 'post-command-hook 'helm--update-header-line))
          (helm-display-mode-line (helm-get-current-source)))))))


;;; Accessors
;;
(defun helm-current-position (save-or-restore)
  "Save or restore current position in `helm-current-buffer'.
Argument SAVE-OR-RESTORE is either save or restore."
  (cl-case save-or-restore
    (save
     (helm-log "Save position at %S" (cons (point) (window-start)))
     (setq helm-current-position (cons (point) (window-start))))
    (restore
     ;; Maybe `helm-current-buffer' have been deleted
     ;; during helm session so check if it is here
     ;; otherwise position in underlying buffer will be lost.
     (when (get-buffer-window helm-current-buffer 'visible)
       (helm-log "Restore position at  %S in buffer %s"
                 helm-current-position
                 (buffer-name (current-buffer)))
       (goto-char (car helm-current-position))
       ;; Fix this position with the NOFORCE arg of `set-window-start'
       ;; otherwise, if there is some other buffer than `helm-current-buffer'
       ;; one, position will be lost.
       (set-window-start (selected-window) (cdr helm-current-position) t)))))


(defun helm-frame-or-window-configuration (save-or-restore)
  "Save or restore last frame or window configuration.
Argument SAVE-OR-RESTORE is either save or restore of window or
frame configuration as per `helm-save-configuration-functions'."
  (helm-log "helm-save-configuration-functions = %S"
            helm-save-configuration-functions)
  (let ((window-persistent-parameters (append '((no-other-window . t))
                                              window-persistent-parameters)))
    (cl-case save-or-restore
      (save    (setq helm-last-frame-or-window-configuration
                     (funcall (cdr helm-save-configuration-functions))))
      (restore (funcall (car helm-save-configuration-functions)
                        helm-last-frame-or-window-configuration)
               ;; Restore frame focus.
               ;; This is needed for minibuffer own-frame config
               ;; when recursive minibuffers are in use.
               ;; e.g M-: + helm-minibuffer-history.
               (cl-letf ((frame (if (minibufferp helm-current-buffer)
                                    (selected-frame)
                                  (last-nonminibuffer-frame)))
                         ;; This is a workaround, because the i3 window
                         ;; manager developers are refusing to fix their
                         ;; broken timestamp and event handling.
                         ;;
                         ;; We basically just disable the part of
                         ;; select-frame-set-input-focus that would call
                         ;; XSetInputFocus in Xlib (x-focus-frame), that
                         ;; resets a timestamp in the xserver which the i3
                         ;; developers fail to notice.
                         ;;
                         ;; Since they don't know about the new timestamp,
                         ;; their keyboard handling can break after a helm
                         ;; user quits emacs, as reported in #1641.
                         ;;
                         ;; Fortunately for us, we really don't need this
                         ;; XSetInputFocus call, since we already have focus
                         ;; for Emacs, the user is just using helm!  We call
                         ;; select-frame-set-input-focus for the other
                         ;; side-effects, not for x-focus-frame.
                         ((symbol-function 'x-focus-frame) #'ignore))
                 (select-frame-set-input-focus frame))))))

(defun helm-split-window-default-fn (window)
  "Default function to split windows before displaying `helm-buffer'.

It is used as default value for
`helm-split-window-preferred-function' which is then the
let-bounded value of `split-window-preferred-function' in
`helm-display-buffer'.  When `helm-display-function' which default
to `helm-default-display-buffer' is called from
`helm-display-buffer' the value of
`split-window-preferred-function' will be used by
`display-buffer'."
  (let* (split-width-threshold
         (win (if (and (fboundp 'window-in-direction)
                       ;; Don't try to split when starting in a minibuffer
                       ;; e.g M-: and try to use helm-show-kill-ring.
                       (not (minibufferp helm-current-buffer)))
                  (if (or (one-window-p t)
                          helm-split-window-inside-p)
                      (split-window
                       (selected-window) nil
                       (if (eq helm-split-window-default-side 'other)
                           helm-split-window-other-side-when-one-window
                         helm-split-window-default-side))
                    ;; If more than one window reuse one of them.
                    (cl-case helm-split-window-default-side
                      (left  (or (helm-window-in-direction 'left)
                                 (helm-window-in-direction 'above)
                                 (selected-window)))
                      (above (or (helm-window-in-direction 'above)
                                 (helm-window-in-direction 'left)
                                 (selected-window)))
                      (right (or (helm-window-in-direction 'right)
                                 (helm-window-in-direction 'below)
                                 (selected-window)))
                      (below (or (helm-window-in-direction 'below)
                                 (helm-window-in-direction 'right)
                                 (selected-window)))
                      (same  (selected-window))
                      (other (or (helm-other-window-for-scrolling)
                                 (selected-window)))
                      (t     (or (window-next-sibling) (selected-window)))))
                (split-window-sensibly window))))
    (setq helm-persistent-action-window-buffer (window-buffer win))
    win))

(defun helm-window-in-direction (direction)
  "Same as `window-in-direction' but check if window is dedicated.
Return nil when window is dedicated."
  (helm-aif (window-in-direction direction)
      (and (not (window-dedicated-p it)) it)))

(defun helm-other-window-for-scrolling ()
  "Same as `other-window-for-scrolling' but check if window is dedicated.
Returns nil when window is dedicated."
  (helm-aif (other-window-for-scrolling)
      (and (not (window-dedicated-p it)) it)))


;;; Display helm buffer
;;
;;
(defun helm-resolve-display-function (com)
  "Decide which display function to use according to `helm-commands-using-frame'.

The `helm-display-function' buffer local value takes precedence
on `helm-commands-using-frame'.
If `helm-initial-frame' has no minibuffer, use
`helm-display-buffer-in-own-frame' function.
Fallback to global value of `helm-display-function' when no local
value found and current command is not in
`helm-commands-using-frame'."
  (or (with-helm-buffer helm-display-function)
      (and (or (memq com helm-commands-using-frame)
               (and helm-use-frame-when-dedicated-window
                    (window-dedicated-p (get-buffer-window helm-current-buffer)))
               (and helm-use-frame-when-more-than-two-windows
                    (null helm--nested)
                    (> (length (window-list)) 2))
               ;; Frame parameter is unreliable for minibuffer on emacs-26.
               (null (member helm-initial-frame (minibuffer-frame-list))))
           #'helm-display-buffer-in-own-frame)
      (default-value 'helm-display-function)))

(defun helm-display-buffer (buffer &optional resume)
  "Display BUFFER.

The function used to display `helm-buffer' by calling
`helm-display-function' which splits window with
`helm-split-window-preferred-function'."
  (let ((split-window-preferred-function
         helm-split-window-preferred-function)
        (helm-split-window-default-side
         (if (and (not helm-full-frame)
                  helm-reuse-last-window-split-state)
             (cond ((eq helm-split-window-default-side 'same) 'same)
                   ((eq helm-split-window-default-side 'other) 'other)
                   (helm--window-side-state)
                   (t helm-split-window-default-side))
           helm-split-window-default-side))
        (disp-fn (with-current-buffer buffer
                   (helm-resolve-display-function
                    (if helm-actions-inherit-frame-settings
                        (helm-this-command) this-command)))))
    (prog1
        (funcall disp-fn buffer (or (helm-resume-p resume)
                                    (and helm-actions-inherit-frame-settings
                                         helm--executing-helm-action)))
      (with-helm-buffer (setq-local helm-display-function disp-fn))
      (setq helm-onewindow-p (one-window-p t))
      ;; Don't allow other-window and friends switching out of minibuffer.
      (when helm-prevent-escaping-from-minibuffer
        (helm-prevent-switching-other-window)))))

(cl-defun helm-prevent-switching-other-window (&key (enabled t))
  "Allow setting `no-other-window' parameter for all windows.
Arg ENABLE is the value of `no-other-window' window property."
  (walk-windows
   (lambda (w)
     (unless (window-dedicated-p w)
       (set-window-parameter w 'no-other-window enabled)))
   0))

(defun helm-default-display-buffer (buffer &optional _resume)
  "Default function to display `helm-buffer' BUFFER.

It is the default value of `helm-display-function'.
It uses `switch-to-buffer' or `display-buffer' depending on the
value of `helm-full-frame' or `helm-split-window-default-side'."
  (let (pop-up-frames
        (dedicated-p (window-dedicated-p
                      (get-buffer-window helm-current-buffer))))
    (if (and (null (eq dedicated-p t))
             (or (buffer-local-value 'helm-full-frame (get-buffer buffer))
                 (and (eq helm-split-window-default-side 'same)
                      (one-window-p t))))
        (progn (and (not (minibufferp helm-current-buffer))
                    (delete-other-windows))
               (switch-to-buffer buffer))
      (when (and (or helm-always-two-windows helm-autoresize-mode)
                 (not (eq helm-split-window-default-side 'same))
                 (not (minibufferp helm-current-buffer))
                 (not helm-split-window-inside-p)
                 ;; Prevent deleting OW only when helm-current-buffer
                 ;; is "strongly" dedicated.
                 (null (eq dedicated-p t)))
        (delete-other-windows))
      (display-buffer
       buffer `(,helm-default-display-buffer-functions
                . ,(append helm-default-display-buffer-alist
                           `((window-height . ,helm-display-buffer-default-height)
                             (window-width  . ,helm-display-buffer-default-width)))))
      (helm-log-run-hook 'helm-window-configuration-hook))))

;; Shut up byte-compiler in emacs-26
(defvar tab-bar-mode)

(defun helm-display-buffer-in-own-frame (buffer &optional resume)
  "Display Helm buffer BUFFER in a separate frame.

Function suitable for `helm-display-function',
`helm-completion-in-region-display-function' and/or
`helm-show-completion-default-display-function'.

See `helm-display-buffer-height' and `helm-display-buffer-width'
to configure frame size.

Note that this feature is available only with emacs-25+."
  (cl-assert (and (fboundp 'window-absolute-pixel-edges)
                  (fboundp 'frame-geometry))
             nil "Helm buffer in own frame is only available starting at emacs-25+")
  (if (not (display-graphic-p))
      ;; Fallback to default when frames are not usable.
      (helm-default-display-buffer buffer)
    (setq helm--buffer-in-new-frame-p t)
    (let* ((pos (window-absolute-pixel-position))
           (half-screen-size (/ (display-pixel-height x-display-name) 2))
           (frame-info (frame-geometry))
           (prmt-size (length helm--prompt))
           (line-height (frame-char-height))
           tab-bar-mode
           (default-frame-alist
             (if resume
                 (buffer-local-value 'helm--last-frame-parameters
                                     (get-buffer buffer))
               `((width . ,helm-display-buffer-width)
                 (height . ,helm-display-buffer-height)
                 (tool-bar-lines . 0)
                 (left . ,(- (car pos)
                             (* (frame-char-width)
                                (if (< (- (point) (point-at-bol)) prmt-size)
                                    (- (point) (point-at-bol))
                                  prmt-size))))
                 ;; Try to put frame at the best possible place.
                 ;; Frame should be below point if enough
                 ;; place, otherwise above point and
                 ;; current line should not be hidden
                 ;; by helm frame.
                 (top . ,(if (> (cdr pos) half-screen-size)
                             ;; Above point
                             (- (cdr pos)
                                ;; add 2 lines to make sure there is always a gap
                                (* (+ helm-display-buffer-height 2) line-height)
                                ;; account for title bar height too
                                (cddr (assq 'title-bar-size frame-info)))
                           ;; Below point
                           (+ (cdr pos) line-height)))
                 (title . "Helm")
                 (undecorated . ,helm-use-undecorated-frame-option)
                 (background-color . ,(or helm-frame-background-color
                                          (face-attribute 'default :background)))
                 (foreground-color . ,(or helm-frame-foreground-color
                                          (face-attribute 'default :foreground)))
                 (alpha . ,(or helm-frame-alpha 100))
                 (font . ,(assoc-default 'font (frame-parameters)))
                 (vertical-scroll-bars . nil)
                 (menu-bar-lines . 0)
                 (fullscreen . nil)
                 (visibility . ,(null helm-display-buffer-reuse-frame))
                 (minibuffer . t))))
           display-buffer-alist)
      ;; Display minibuffer above or below only in initial session,
      ;; not on a session triggered by action, this way if user have
      ;; toggled minibuffer and header-line manually she keeps this
      ;; setting in next action.
      (unless (or helm--executing-helm-action resume)
        ;; Add the hook inconditionally, if
        ;; helm-echo-input-in-header-line is nil helm-hide-minibuffer-maybe
        ;; will have anyway no effect so no need to remove the hook.
        (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe)
        (with-helm-buffer
          (setq-local helm-echo-input-in-header-line
                      (not (> (cdr pos) half-screen-size)))))
      (helm-display-buffer-popup-frame buffer default-frame-alist)
      ;; When frame size have been modified manually by user restore
      ;; it to default value unless resuming or not using
      ;; `helm-display-buffer-reuse-frame'.
      ;; This have to be done AFTER raising the frame otherwise
      ;; minibuffer visibility is lost until next session.
      (unless (or resume (not helm-display-buffer-reuse-frame))
        (set-frame-size helm-popup-frame
                        helm-display-buffer-width
                        helm-display-buffer-height)))
    (helm-log-run-hook 'helm-window-configuration-hook)))

(defun helm-display-buffer-popup-frame (buffer frame-alist)
  (if helm-display-buffer-reuse-frame
      (let* ((x (cdr (assoc 'left frame-alist)))
             (y (cdr (assoc 'top frame-alist)))
             (width (cdr (assoc 'width frame-alist)))
             (height (cdr (assoc 'height frame-alist))))
        (unless (and helm-popup-frame
                     (frame-live-p helm-popup-frame))
          (setq helm-popup-frame (make-frame frame-alist)))
        (select-frame helm-popup-frame)
        (set-frame-position helm-popup-frame x y)
        (set-frame-width helm-popup-frame width)
        (set-frame-height helm-popup-frame height)
        (switch-to-buffer buffer)
        (select-frame-set-input-focus helm-popup-frame t))
    ;; If user have changed `helm-display-buffer-reuse-frame' to nil
    ;; maybe kill the frame.
    (when (and helm-popup-frame
               (frame-live-p helm-popup-frame))
      (delete-frame helm-popup-frame))
    (display-buffer
     buffer '(display-buffer-pop-up-frame . nil))))

;; Ensure to quit helm when user delete helm frame manually.
;; If user deletes another frame keep session running.
(defun helm--delete-frame-function (frame)
  (when (and helm-alive-p
             ;; FRAME is handling helm-buffer
             (get-buffer-window helm-buffer frame))
    (helm-keyboard-quit)))
(add-hook 'delete-frame-functions 'helm--delete-frame-function)

;;; Initialize
;;
(defun helm-get-sources (sources)
  "Transform each element of SOURCES in alist.
Return the resulting list."
  (when sources
    (mapcar (lambda (source)
              (if (listp source)
                  source (symbol-value source)))
            (helm-normalize-sources sources))))

(defun helm-initialize (resume input default sources)
  "Start initialization of Helm session.
For RESUME INPUT DEFAULT and SOURCES see `helm'."
  (helm-log "start initialization: resume=%S input=%S"
            resume input)
  (helm-frame-or-window-configuration 'save)
  (let ((sources-list (helm-get-sources sources)))
    (setq helm--in-fuzzy
          (cl-loop for s in sources-list
                   for matchfns = (helm-match-functions s)
                   for searchfns = (helm-search-functions s)
                   when (or (memq 'helm-fuzzy-match matchfns)
                            (memq 'helm-fuzzy-search searchfns))
                   return t))
    (helm-log "sources-list = %S" sources-list)
    (helm-set-local-variable 'helm-sources sources-list)
    ;; Once `helm-buffer' is created `helm-sources' will be a local
    ;; variable which value is a list of alists.
    (helm-current-position 'save)
    (if (helm-resume-p resume)
        (helm-initialize-overlays (helm-buffer-get))
      (helm-initial-setup default sources-list))
    (setq helm-alive-p t)
    (unless (eq resume 'noresume)
      (helm--push-and-remove-dups helm-buffer 'helm-buffers)
      (setq helm-last-buffer helm-buffer))
    (when input
      (setq helm-input input
            helm-pattern input)
      (helm--fuzzy-match-maybe-set-pattern))
    ;; If a `resume' attribute is present `helm-compute-attr-in-sources'
    ;; will run its function.
    (when (helm-resume-p resume)
      (helm-compute-attr-in-sources 'resume))
    (helm-log "end initialization")))

(defun helm-initialize-overlays (buffer)
  "Initialize Helm overlays in BUFFER."
  (helm-log "overlay setup")
  (if helm-selection-overlay
      ;; make sure the overlay belongs to the helm buffer if
      ;; it's newly created
      (move-overlay helm-selection-overlay (point-min) (point-min)
                    (get-buffer buffer))

    (setq helm-selection-overlay
          (make-overlay (point-min) (point-min) (get-buffer buffer)))
    (overlay-put helm-selection-overlay 'face 'helm-selection)
    (overlay-put helm-selection-overlay 'priority 1)))

(defun helm-restore-position-on-quit ()
  "Restore position in `helm-current-buffer' when quitting."
  (helm-current-position 'restore))

(defun helm--push-and-remove-dups (elm sym)
  "Move ELM of SYM value on top and set SYM to this new value."
  (set sym (cons elm (delete elm (symbol-value sym)))))

(defun helm--current-buffer ()
  "[INTERNAL] Return `current-buffer' BEFORE `helm-buffer' is initialized.
Note that it returns the minibuffer in use after Helm has started
and is intended for `helm-initial-setup'.  To get the buffer where
Helm was started, use `helm-current-buffer' instead."
  (if (minibuffer-window-active-p (minibuffer-window))
      ;; If minibuffer is active be sure to use it's buffer
      ;; as `helm-current-buffer', this allow to use helm
      ;; from an already active minibuffer (M-: etc...)
      (window-buffer (active-minibuffer-window))
    ;; Fix Issue #456
    ;; Use this instead of `current-buffer' to ensure
    ;; helm session started in helm-mode from a completing-read
    ;; Use really the buffer where we started and not the one
    ;; where the completing-read is wrapped. i.e
    ;; (with-current-buffer SOME-OTHER-BUFFER (completing-read [...])
    (window-buffer (with-selected-window (minibuffer-window)
                     (minibuffer-selected-window)))))

(defun helm--run-init-hooks (hook sources)
  "Run after and before init hooks local to source.
See :after-init-hook and :before-init-hook in `helm-source'."
  (cl-loop with sname = (cl-ecase hook
                          (before-init-hook "h-before-init-hook")
                          (after-init-hook "h-after-init-hook"))
           with h = (cl-gensym sname)
           for s in sources
           for hv = (assoc-default hook s)
           if (and hv (not (symbolp hv)))
           do (set h hv)
           and do (helm-log-run-hook h)
           else do (helm-log-run-hook hv)))

(defun helm-initial-setup (default sources)
  "Initialize Helm settings and set up the Helm buffer."
  ;; Run global hook.
  (helm-log-run-hook 'helm-before-initialize-hook)
  ;; Run local source hook.
  (helm--run-init-hooks 'before-init-hook sources)
  ;; For initialization of helm locals vars that need
  ;; a value from current buffer, it is here.
  (helm-set-local-variable 'current-input-method current-input-method)
  (setq helm-current-prefix-arg nil
        helm-saved-action nil
        helm-saved-selection nil
        helm-suspend-update-flag nil
        ;; Ensure this is called BEFORE selecting helm-window.
        helm-current-buffer (helm--current-buffer)
        helm-buffer-file-name buffer-file-name
        helm-issued-errors nil
        helm-saved-current-source nil
        helm--suspend-update-interactive-flag nil)
  (when (and (with-helm-current-buffer
               (and (buffer-narrowed-p)
                    (use-region-p)))
             (not helm--nested))
    (helm-set-local-variable 'helm--current-buffer-narrowed
                             (list (current-buffer)
                                   (region-beginning) (region-end))))
  (unless (and (or helm-split-window-state
                   helm--window-side-state)
               helm-reuse-last-window-split-state)
    (setq helm-split-window-state
          (if (or (null split-width-threshold)
                  (and (integerp split-width-threshold)
                       (>= split-width-threshold (+ (frame-width) 4))))
              'vertical 'horizontal))
    (setq helm--window-side-state
          (or helm-split-window-default-side 'below)))
  ;; Call the init function for sources where appropriate
  (helm-compute-attr-in-sources 'init sources)
  (setq helm-pattern (or (and helm-maybe-use-default-as-input
                              (or (if (listp default)
                                      (car default) default)
                                  (with-helm-current-buffer
                                    (thing-at-point 'symbol))))
                         ""))
  (setq helm-input "")
  (clrhash helm-candidate-cache)
  (helm-create-helm-buffer)
  (helm-clear-visible-mark)
  ;; Run global hook.
  (helm-log-run-hook 'helm-after-initialize-hook)
  ;; Run local source hook.
  (helm--run-init-hooks 'after-init-hook sources))

(define-derived-mode helm-major-mode
  fundamental-mode "Hmm"
  "[INTERNAL] Provide major-mode name in Helm buffers.
Unuseful when used outside Helm, don't use it.")
(put 'helm-major-mode 'mode-class 'special)
(put 'helm-major-mode 'helm-only t)

(defun helm-create-helm-buffer ()
  "Create and setup `helm-buffer'."
  (let ((root-dir default-directory)
        (inhibit-read-only t))
    (with-current-buffer (get-buffer-create helm-buffer)
      (helm-log "Enabling major-mode %S" major-mode)
      (helm-log "kill local variables: %S" (buffer-local-variables))
      (kill-all-local-variables)
      (helm-major-mode)
      (set (make-local-variable 'buffer-read-only) nil)
      (buffer-disable-undo)
      (erase-buffer)
      (set (make-local-variable 'helm-map) helm-map)
      (set (make-local-variable 'helm-source-filter) nil)
      (make-local-variable 'helm-sources)
      (set (make-local-variable 'helm-display-function) nil)
      (set (make-local-variable 'helm-selection-point) nil)
      (set (make-local-variable 'scroll-margin)
           (if helm-display-source-at-screen-top
               0 helm-completion-window-scroll-margin))
      (set (make-local-variable 'default-directory) root-dir)
      (set (make-local-variable 'helm-marked-candidates) nil)
      (set (make-local-variable 'helm--prompt) helm--prompt)
      (helm-initialize-persistent-action)
      (helm-log "helm-display-function = %S" helm-display-function)
      (helm-log "helm--local-variables = %S" helm--local-variables)
      (helm--set-local-variables-internal)
      (setq truncate-lines helm-truncate-lines) ; already local.
      (setq left-margin-width helm-left-margin-width)
      (setq cursor-type nil))
    (helm-initialize-overlays helm-buffer)
    (get-buffer helm-buffer)))

(define-minor-mode helm--minor-mode
  "[INTERNAL] Enable keymap in Helm minibuffer.
Since this mode has no effect when run outside of Helm context,
please don't use it outside of Helm.

\\{helm-map}"
  :group 'helm
  :keymap (and helm-alive-p helm-map)
  (unless helm-alive-p (setq helm--minor-mode nil)))
(put 'helm--minor-mode 'helm-only t)

(defun helm--reset-default-pattern ()
  (setq helm-pattern "")
  (setq helm-maybe-use-default-as-input nil))

(defun helm-read-pattern-maybe (prompt
                                input preselect resume
                                keymap default history)
  "Read pattern with prompt PROMPT and initial input INPUT.
For PRESELECT RESUME KEYMAP DEFAULT HISTORY, see `helm'."
  (with-helm-buffer
    (if (and (helm-resume-p resume)
             ;; When no source, helm-buffer is empty
             ;; or contain non--candidate lines (e.g grep exit status)
             (helm-get-current-source))
        (helm-mark-current-line t)
      (helm-update preselect))
    (let* ((src        (helm-get-current-source))
           (src-keymap (assoc-default 'keymap src))
           (hist       (or (and history (symbolp history) history)
                           ;; Needed for resuming.
                           (assoc-default 'history src)))
           (timer nil)
           blink-matching-paren
           (resize-mini-windows (and (null helm-echo-input-in-header-line)
                                     resize-mini-windows))
           (first-src (car helm-sources))
           (source-process-p (or (assq 'candidates-process src)
                                 (assq 'candidates-process first-src))))
      (helm-log "helm-get-candidate-number => %S"
                (helm-get-candidate-number))
      (helm-log "helm-execute-action-at-once-if-one = %S"
                helm-execute-action-at-once-if-one)
      (helm-log "helm-quit-if-no-candidate = %S" helm-quit-if-no-candidate)
      (when (and src (helm-resume-p resume))
        (helm-display-mode-line src))
      ;; Reset `helm-pattern' and update
      ;; display if no result found with precedent value of `helm-pattern'
      ;; unless `helm-quit-if-no-candidate' is non-`nil', in this case
      ;; Don't force update with an empty pattern.
      ;; Reset also `helm-maybe-use-default-as-input' as this checking
      ;; happen only on startup.
      (when helm-maybe-use-default-as-input
        ;; Store value of `default' temporarily here waiting next update
        ;; to allow actions like helm-moccur-action matching pattern
        ;; at the place it jump to.
        (setq helm-input helm-pattern)
        (if source-process-p
            ;; Reset pattern to next update.
            (with-helm-after-update-hook
              (helm--reset-default-pattern))
          ;; Reset pattern right now.
          (helm--reset-default-pattern))
        ;; Ensure force-update when no candidates
        ;; when we start with an empty pattern.
        (and (helm-empty-buffer-p)
             (null helm-quit-if-no-candidate)
             (helm-force-update preselect)))
      ;; Handle `helm-execute-action-at-once-if-one' and
      ;; `helm-quit-if-no-candidate' now.
      (cond ((and (if (functionp helm-execute-action-at-once-if-one)
                      (funcall helm-execute-action-at-once-if-one)
                    helm-execute-action-at-once-if-one)
                  (= (helm-get-candidate-number
                      (eq helm-execute-action-at-once-if-one 'current-source))
                     1))
             (ignore))              ; Don't enter the minibuffer loop.
            ((and helm-quit-if-no-candidate
                  (= (helm-get-candidate-number) 0))
             (setq helm-quit t)
             (and (functionp helm-quit-if-no-candidate)
                  (funcall helm-quit-if-no-candidate)))
            (t              ; Enter now minibuffer and wait for input.
             (let ((tap (or default
                            (with-helm-current-buffer
                              (thing-at-point 'symbol)))))
               (when helm-execute-action-at-once-if-one
                 (helm-display-buffer helm-buffer resume)
                 (select-window (helm-window)))
               (unwind-protect
                   (minibuffer-with-setup-hook
                       (lambda ()
                         ;; Start minor-mode with global value of helm-map.
                         (helm--minor-mode 1)
                         ;; Now override the global value of `helm-map' with
                         ;; the local one which is in this order:
                         ;; - The keymap of current source.
                         ;; - The value passed in KEYMAP
                         ;; - Or fallback to the global value of helm-map.
                         (helm--maybe-update-keymap
                          (or src-keymap keymap helm-map))
                         (helm-log-run-hook 'helm-minibuffer-set-up-hook)
                         (setq timer
                               (run-with-idle-timer
                                (max (with-helm-buffer helm-input-idle-delay)
                                     0.001)
                                'repeat
                                (lambda ()
                                  ;; Stop updating in persistent action
                                  ;; or when `helm-suspend-update-flag'
                                  ;; is non-`nil'.
                                  (unless (or helm-in-persistent-action
                                              helm-suspend-update-flag)
                                    (save-selected-window
                                      (helm-check-minibuffer-input)
                                      (helm-print-error-messages))))))
                         ;; minibuffer has already been filled here.
                         (helm--update-header-line))
                     (read-from-minibuffer (propertize (or prompt "pattern: ")
                                                       'face 'helm-minibuffer-prompt)
                                           input helm-map
                                           nil hist tap
                                           helm-inherit-input-method))
                 (when timer (cancel-timer timer) (setq timer nil)))))))))

(defun helm-toggle-suspend-update ()
  "Enable or disable display update in helm.
This can be useful for example for quietly writing a complex
regexp without Helm constantly updating."
  (interactive)
  (helm-suspend-update (not helm-suspend-update-flag) t)
  (setq helm--suspend-update-interactive-flag
        (not helm--suspend-update-interactive-flag)))
(put 'helm-toggle-suspend-update 'helm-only t)

(defun helm-suspend-update (arg &optional verbose)
  "Enable or disable display update in helm.
If ARG is 1 or non nil suspend update, if it is -1 or nil reenable
updating.  When VERBOSE is specified display a message."
  (with-helm-buffer
    (when (setq helm-suspend-update-flag
                (helm-acase arg
                  (1 t)
                  (-1 nil)
                  (t it)))
      (helm-kill-async-processes)
      (setq helm-pattern ""))
    (when verbose
      (message (if helm-suspend-update-flag
                   "Helm update suspended!"
                 "Helm update re-enabled!")))
    (helm-aif (helm-get-current-source)
        (helm-display-mode-line it t))))

(defun helm-delete-backward-no-update (arg)
  "Disable update and delete ARG chars backward.
Update is reenabled when idle 1s."
  (interactive "p")
  (with-helm-alive-p
    (unless helm--suspend-update-interactive-flag
      (helm-suspend-update 1))
    (backward-delete-char arg)
    (run-with-idle-timer
     1 nil
     (lambda ()
       (unless helm--suspend-update-interactive-flag
         (helm-suspend-update -1)
         (helm-check-minibuffer-input)
         (helm-force-update))))))
(put 'helm-delete-backward-no-update 'helm-only t)

(defun helm--suspend-read-passwd (old--fn &rest args)
  "Suspend Helm while reading password.
This is used to advice `tramp-read-passwd', `ange-ftp-get-passwd'
and `epa-passphrase-callback-function'."
  ;; Suspend update when prompting for a tramp password.
  (setq helm-suspend-update-flag t)
  (setq overriding-terminal-local-map nil)
  (setq helm--reading-passwd-or-string t)
  (unwind-protect
      ;; No need to suspend timer in emacs-24.4
      ;; it is fixed upstream.
      (apply old--fn args)
    (setq helm--reading-passwd-or-string nil)
    (setq helm-suspend-update-flag nil)))

(defun helm--maybe-update-keymap (&optional map)
  "Handle different keymaps in multiples sources.

Overrides `helm-map' with the local map of current source.  If no
map is found in current source, does nothing (keeps previous
map)."
  (with-helm-buffer
    (helm-aif (or map (assoc-default 'keymap (helm-get-current-source)))
        ;; We used a timer in the past to leave
        ;; enough time to helm to setup its keymap
        ;; when changing source from a recursive minibuffer.
        ;; e.g C-x C-f M-y C-g
        ;; => *find-files have now the bindings of *kill-ring.
        ;; It is no more true now we are using `minor-mode-overriding-map-alist'
        ;; and `helm--minor-mode' thus it fix issue #1076 for emacs-24.3
        ;; where concurrent timers are not supported.
        ;; i.e update keymap+check input.
        (with-current-buffer (window-buffer (minibuffer-window))
          (setq minor-mode-overriding-map-alist `((helm--minor-mode . ,it)))))))

;;; Prevent loosing focus when using mouse.
;;
(defvar helm--remap-mouse-mode-map
  (let ((map (make-sparse-keymap)))
    (cl-loop for k in '([mouse-1] [mouse-2] [mouse-3]
                        [down-mouse-1] [down-mouse-2] [down-mouse-3]
                        [drag-mouse-1] [drag-mouse-2] [drag-mouse-3]
                        [double-mouse-1] [double-mouse-2] [double-mouse-3]
                        [triple-mouse-1] [triple-mouse-2] [triple-mouse-3])
             do (define-key map k 'ignore))
    map))

(define-minor-mode helm--remap-mouse-mode
  "[INTERNAL] Prevent escaping helm minibuffer with mouse clicks.
Do nothing when used outside of helm context.

WARNING: Do not use this mode yourself, it is internal to Helm."
  :group 'helm
  :global t
  :keymap helm--remap-mouse-mode-map
  (unless helm-alive-p
    (setq helm--remap-mouse-mode-map nil)))
(put 'helm--remap-mouse-mode 'helm-only t)

;; Clean up

(defun helm-cleanup ()
  "Clean up the mess when Helm exit or quit."
  (helm-log "start cleanup")
  (with-current-buffer helm-buffer
    (let ((frame (selected-frame)))
      (setq cursor-type t)
      ;; Ensure restoring default-value of mode-line to allow user
      ;; using the mouse when helm is inactive (issues #1517,#2377).
      (setq mode-line-format (default-value 'mode-line-format))
      (remove-hook 'post-command-hook 'helm--maybe-update-keymap)
      (remove-hook 'post-command-hook 'helm--update-header-line)
      ;; Be sure we call cleanup functions from helm-buffer.
      (helm-compute-attr-in-sources 'cleanup)
      ;; Delete or make invisible helm frame.
      (if (and helm--buffer-in-new-frame-p (null helm--nested))
          (progn
            (setq-local helm--last-frame-parameters
                        (helm--get-frame-parameters))
            (bury-buffer)
            (if helm-display-buffer-reuse-frame
                (make-frame-invisible frame) (delete-frame frame)))
        ;; bury-buffer from this window [1].
        ;; Do it at end to make sure buffer is still current.
        (bury-buffer))))
  (helm-kill-async-processes)
  ;; Remove the temporary hooks added
  ;; by `with-helm-temp-hook' that
  ;; may not have been consumed.
  (when helm--temp-hooks
    (cl-loop for (fn . hook) in helm--temp-hooks
             do (set hook (delete fn (symbol-value hook)))))
  ;; When running helm from a dedicated frame
  ;; with no minibuffer, helm will run in the main frame
  ;; which have a minibuffer, so be sure to disable
  ;; the `no-other-window' prop there.
  (helm-prevent-switching-other-window :enabled nil)
  (helm-log-run-hook 'helm-cleanup-hook)
  (helm-frame-or-window-configuration 'restore)
  ;; [1] now bury-buffer from underlying windows otherwise,
  ;; if this window is killed the underlying buffer will
  ;; be a helm buffer.
  (replace-buffer-in-windows helm-buffer)
  (setq helm-alive-p nil)
  ;; Prevent error "No buffer named *helm*" triggered by
  ;; `helm-set-local-variable'.
  (setq helm--force-updating-p nil)
  (setq helm--buffer-in-new-frame-p nil)
  ;; This is needed in some cases where last input
  ;; is yielded infinitely in minibuffer after helm session.
  (helm-clean-up-minibuffer))

(defun helm-clean-up-minibuffer ()
  "Remove contents of minibuffer."
  (let ((miniwin (minibuffer-window)))
    ;; Clean only current minibuffer used by helm.
    ;; i.e The precedent one is active.
    (unless (minibuffer-window-active-p miniwin)
      (with-current-buffer (window-buffer miniwin)
        (delete-minibuffer-contents)))))


;;; Input handling
;;
;;
(defun helm-check-minibuffer-input ()
  "Check minibuffer content."
  (with-helm-quittable
    (with-selected-window (or (active-minibuffer-window)
                              (minibuffer-window))
      (helm-check-new-input (minibuffer-contents)))))

(defun helm-check-new-input (input)
  "Check INPUT string and update the helm buffer if necessary."
  (unless (equal input helm-pattern)
    (setq helm-pattern input)
    (unless (helm-action-window)
      (setq helm-input helm-pattern))
    (helm-log "helm-pattern = %S" helm-pattern)
    (helm-log "helm-input = %S" helm-input)
    (helm-log-run-hook 'helm-before-update-hook)
    (setq helm--in-update t)
    (helm-update)))

(defun helm--reset-update-flag ()
  (run-with-idle-timer
   helm-exit-idle-delay nil
   (lambda () (setq helm--in-update nil))))

;; (add-hook 'helm-after-update-hook #'helm--reset-update-flag)


;; All candidates

(defun helm-get-candidates (source)
  "Retrieve and return the list of candidates from SOURCE."
  (let* ((candidate-fn (assoc-default 'candidates source))
         (candidate-proc (assoc-default 'candidates-process source))
         ;; See comment in helm-get-cached-candidates (Issue 2113).
         (inhibit-quit candidate-proc)
         cfn-error
         (notify-error
          (lambda (&optional e)
            (error
             "In `%s' source: `%s' %s %s"
             (assoc-default 'name source)
             (or candidate-fn candidate-proc)
             (if e "\n" "must be a list, a symbol bound to a list, or a function returning a list")
             (if e (prin1-to-string e) ""))))
         (candidates (condition-case-unless-debug err
                         ;; Process candidates-(process) function
                         ;; It may return a process or a list of candidates.
                         (if candidate-proc
                             ;; Calling `helm-interpret-value' with no
                             ;; SOURCE arg force the use of `funcall'
                             ;; and not `helm-apply-functions-from-source'.
                             (helm-interpret-value candidate-proc)
                           (helm-interpret-value candidate-fn source))
                       (error (helm-log "Error: %S" (setq cfn-error err)) nil))))
    (cond ((and (processp candidates) (not candidate-proc))
           (warn "Candidates function `%s' should be called in a `candidates-process' attribute"
                 candidate-fn))
          ((and candidate-proc (not (processp candidates)))
           (error "Candidates function `%s' should run a process" candidate-proc)))
    (cond ((processp candidates)
           ;; Candidates will be filtered later in process filter.
           candidates)
          ;; An error occured in candidates function.
          (cfn-error (unless helm--ignore-errors
                       (funcall notify-error cfn-error)))
          ;; Candidates function returns no candidates.
          ((or (null candidates)
               ;; Can happen when the output of a process
               ;; is empty, and the candidates function call
               ;; something like (split-string (buffer-string) "\n")
               ;; which result in a list of one empty string (Issue #938).
               ;; e.g (completing-read "test: " '(""))
               (equal candidates '("")))
           nil)
          ((listp candidates)
           ;; Transform candidates with `candidate-transformer' functions or
           ;; `real-to-display' functions if those are found,
           ;; otherwise return candidates unmodified.
           ;; `filtered-candidate-transformer' is NOT called here.
           (helm-transform-candidates candidates source))
          (t (funcall notify-error)))))

(defmacro helm-while-no-input (&rest body)
  "Same as `while-no-input' but without the `input-pending-p' test."
  (declare (debug t) (indent 0))
  (let ((catch-sym (make-symbol "input")))
    `(with-local-quit
       (catch ',catch-sym
         (let ((throw-on-input ',catch-sym))
           ,@body)))))

(defun helm-get-cached-candidates (source)
  "Return the cached value of candidates for SOURCE.
Cache the candidates if there is no cached value yet."
  (let* ((name (assoc-default 'name source))
         (candidate-cache (gethash name helm-candidate-cache))
         ;; Bind inhibit-quit to ensure function terminate in case of
         ;; quit from helm-while-no-input and processes are added to
         ;; helm-async-processes for further deletion (Issue 2113).
         (inhibit-quit (assoc-default 'candidates-process source)))
    (helm-aif candidate-cache
        (prog1 it (helm-log "Use cached candidates"))
      (helm-log "No cached candidates, calculate candidates")
      (let ((candidates (helm-get-candidates source)))
        (cond ((processp candidates)
               (push (cons candidates
                           (append source
                                   (list (cons 'item-count 0)
                                         (cons 'incomplete-line ""))))
                     helm-async-processes)
               (set-process-filter candidates 'helm-output-filter)
               (setq candidates nil))
              ((not (assq 'volatile source))
               (puthash name candidates helm-candidate-cache)))
        candidates))))


;;; Candidate transformers

(defun helm-process-candidate-transformer (candidates source)
  "Execute `candidate-transformer' function(s) on CANDIDATES in SOURCE."
  (helm-aif (assoc-default 'candidate-transformer source)
      (helm-apply-functions-from-source source it candidates)
    candidates))

(defun helm-process-filtered-candidate-transformer (candidates source)
  "Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE."
  (helm-aif (assoc-default 'filtered-candidate-transformer source)
      (helm-apply-functions-from-source source it candidates source)
    candidates))

(defmacro helm--maybe-process-filter-one-by-one-candidate (candidate source)
  "Execute `filter-one-by-one' function(s) on real value of CANDIDATE in SOURCE."
  `(helm-aif (assoc-default 'filter-one-by-one ,source)
       (let ((real (if (consp ,candidate)
                       (cdr ,candidate)
                     ,candidate)))
         (if (and (listp it)
                  (not (functionp it))) ;; Don't treat lambda's as list.
             (cl-loop for f in it
                      do (setq ,candidate (funcall f real))
                      finally return ,candidate)
           (setq ,candidate (funcall it real))))
     ,candidate))

(defun helm--initialize-one-by-one-candidates (candidates source)
  "Process CANDIDATES with the `filter-one-by-one' function in SOURCE.
Return CANDIDATES unchanged when pattern is not empty."
  (helm-aif (and (string= helm-pattern "")
                 (assoc-default 'filter-one-by-one source))
      (cl-loop for cand in candidates collect
               (helm--maybe-process-filter-one-by-one-candidate cand source))
    candidates))

(defun helm-process-filtered-candidate-transformer-maybe
    (candidates source process-p)
  "Execute `filtered-candidate-transformer' function(s) on CANDIDATES in SOURCE.
When PROCESS-P is non-nil execute
`filtered-candidate-transformer' functions if some, otherwise
return CANDIDATES."
  (if process-p
      ;; When no filter return CANDIDATES unmodified.
      (helm-process-filtered-candidate-transformer candidates source)
    candidates))

(defun helm-process-real-to-display (candidates source)
  "Execute real-to-display function on all CANDIDATES of SOURCE."
  (helm-aif (assoc-default 'real-to-display source)
      (setq candidates (helm-apply-functions-from-source
                        source 'mapcar
                        (lambda (cand)
                          (if (consp cand)
                              ;; override DISPLAY from candidate-transformer
                              (cons (funcall it (cdr cand)) (cdr cand))
                            (cons (funcall it cand) cand)))
                        candidates))
    candidates))

(defun helm-transform-candidates (candidates source &optional process-p)
  "Transform CANDIDATES from SOURCE according to candidate transformers.

When PROCESS-P is non-nil executes the
`filtered-candidate-transformer' functions, otherwise processes
`candidate-transformer' functions only,
`filtered-candidate-transformer' functions being processed later,
after the candidates have been narrowed by
`helm-candidate-number-limit', see `helm-compute-matches'.  When
`real-to-display' attribute is present, execute its functions on all
maybe filtered CANDIDATES."
  (helm-process-real-to-display
   (helm-process-filtered-candidate-transformer-maybe
    (helm-process-candidate-transformer
     candidates source)
    source process-p)
   source))


;; Narrowing candidates
(defun helm-candidate-number-limit (source)
  "Apply candidate-number-limit attribute value.
This overrides `helm-candidate-number-limit' variable.

E.g.:
If \(candidate-number-limit\) is in SOURCE, show all candidates in SOURCE.
If \(candidate-number-limit . 123\) is in SOURCE limit candidate to 123."
  (helm-aif (assq 'candidate-number-limit source)
      ;; When assoc value is nil use by default 99999999 otherwise use
      ;; the assoc value, when it is a symbol interpret its value (#1831).
      (or (helm-aand (cdr it) (helm-interpret-value it)) 99999999)
    (or helm-candidate-number-limit 99999999)))

(defun helm-candidate-get-display (candidate)
  "Get searched display part from CANDIDATE.
CANDIDATE is either a string, a symbol, or a \(DISPLAY . REAL\)
cons cell."
  (cond ((car-safe candidate))
        ((symbolp candidate)
         (symbol-name candidate))
        ((numberp candidate)
         (number-to-string candidate))
        (t candidate)))

(defun helm-process-pattern-transformer (pattern source)
  "Execute pattern-transformer attribute function(s) on PATTERN in SOURCE."
  (helm-aif (assoc-default 'pattern-transformer source)
      (helm-apply-functions-from-source source it pattern)
    pattern))

(defun helm-default-match-function (candidate)
  "Check if `helm-pattern' match CANDIDATE.
Default function to match candidates according to `helm-pattern'."
  (string-match helm-pattern candidate))


;;; Fuzzy matching
;;
;;
(defvar helm--fuzzy-regexp-cache (make-hash-table :test 'eq))
(defun helm--fuzzy-match-maybe-set-pattern ()
  ;; Computing helm-pattern with helm--mapconcat-pattern
  ;; is costly, so cache it once time for all and reuse it
  ;; until pattern change.
  (when helm--in-fuzzy
    (let ((fun (if (string-match "\\`\\^" helm-pattern)
                   #'identity
                 #'helm--mapconcat-pattern)))
      (clrhash helm--fuzzy-regexp-cache)
      ;; FIXME: Splitted part are not handled here,
      ;; I must compute them in `helm-search-match-part'
      ;; when negation and in-buffer are used.
      (if (string-match "\\`!" helm-pattern)
          (puthash 'helm-pattern
                   (if (> (length helm-pattern) 1)
                       (list (regexp-quote (substring helm-pattern 1 2))
                             (funcall fun (substring helm-pattern 1)))
                     '("" ""))
                   helm--fuzzy-regexp-cache)
        (puthash 'helm-pattern
                 (if (> (length helm-pattern) 0)
                     (list (regexp-quote (substring helm-pattern 0 1))
                           (funcall fun helm-pattern))
                   '("" ""))
                 helm--fuzzy-regexp-cache)))))

(defun helm-fuzzy-match (candidate)
  "Check if `helm-pattern' fuzzy matches CANDIDATE.
This function is used with sources built with `helm-source-sync'."
  (unless (string-match " " helm-pattern)
    ;; When pattern have one or more spaces, let
    ;; multi-match doing the job with no fuzzy matching.[1]
    (let ((regexp (cadr (gethash 'helm-pattern helm--fuzzy-regexp-cache))))
      (if (string-match "\\`!" helm-pattern)
          (not (string-match regexp candidate))
        (string-match regexp candidate)))))

(defun helm-fuzzy-search (pattern)
  "Same as `helm-fuzzy-match' but for sources built with
`helm-source-in-buffer'."
  (unless (string-match " " helm-pattern)
    ;; Same as in `helm-fuzzy-match' ref[1].
    (let* ((regexps (gethash 'helm-pattern helm--fuzzy-regexp-cache))
           (partial-regexp (car regexps))
           (regexp (cadr regexps)))
      (if (string-match "\\`!" pattern)
          ;; Don't try to search here, just return
          ;; the position of line and go ahead,
          ;; letting `helm-search-match-part' checking if
          ;; pattern match against this line.
          (prog1 (list (point-at-bol) (point-at-eol))
            (forward-line 1))
        ;; We could use here directly `re-search-forward'
        ;; on the regexp produced by `helm--mapconcat-pattern',
        ;; but it is very slow because emacs have to do an incredible
        ;; amount of loops to match e.g "[^f]*f[^o]*o..." in the whole buffer,
        ;; more the regexp is long more the amount of loops grow.
        ;; (Probably leading to a max-lisp-eval-depth error if both
        ;; regexp and buffer are too big)
        ;; So just search the first bit of pattern e.g "[^f]*f", and
        ;; then search the corresponding line with the whole regexp,
        ;; which increase dramatically the speed of the search.
        (cl-loop while (re-search-forward partial-regexp nil t)
                 for bol = (point-at-bol)
                 for eol = (point-at-eol)
                 if (progn (goto-char bol)
                           (re-search-forward regexp eol t))
                 do (goto-char eol) and return t
                 else do (goto-char eol)
                 finally return nil)))))

(defun helm-score-candidate-for-pattern (candidate pattern)
  "Assign score to CANDIDATE according to PATTERN.
Score is calculated for contiguous matches found with PATTERN.
Score is 100 (maximum) if PATTERN is fully matched in CANDIDATE.
One point bonus is added to score when PATTERN prefix matches
CANDIDATE.  Contiguous matches get a coefficient of 2."
  (let* ((cand (if (stringp candidate)
                   candidate (helm-stringify candidate)))
         (pat-lookup (helm--collect-pairs-in-string pattern))
         (str-lookup (helm--collect-pairs-in-string cand))
         (inter (cl-nintersection pat-lookup str-lookup :test 'equal))
         ;; Prefix
         (bonus (cond ((or (equal (car pat-lookup) (car str-lookup))
                           (equal (caar pat-lookup) (caar str-lookup)))
                       2)
                      ((and (null pat-lookup) ; length = 1
                            (string= pattern (substring cand 0 1)))
                       150)
                      (t 0)))
         ;; Exact match e.g. foo -> foo == 200
         (bonus1 (and (string= cand pattern) 200))
         ;; Partial match e.g. foo -> aafooaa == 100
         ;;               or   foo -> fooaaa
         (bonus2 (and (or (string-match
                           (concat "\\`" (regexp-quote pattern))
                           cand)
                          (string-match
                           (concat "\\<" (regexp-quote pattern) "\\>")
                           cand))
                      100)))
    (+ bonus
       (or bonus1 bonus2
           ;; Give a coefficient of 2 for contiguous matches.
           ;; That's mean that "wiaaaki" will not take precedence
           ;; on "aaawiki" when matching on "wiki" even if "wiaaaki"
           ;; starts by "wi".
           (* (length inter) 2)))))

(defun helm-fuzzy-matching-default-sort-fn-1 (candidates &optional use-real basename preserve-tie-order)
  "The transformer for sorting candidates in fuzzy matching.
It sorts on the display part by default.

It sorts CANDIDATES by their scores as calculated by
`helm-score-candidate-for-pattern'.  Set USE-REAL to non-nil to
sort on the real part.  If BASENAME is non-nil assume we are
completing filenames and sort on basename of candidates.  If
PRESERVE-TIE-ORDER is nil, ties in scores are sorted by length of
the candidates."
  (if (string= helm-pattern "")
      candidates
    (let ((table-scr (make-hash-table :test 'equal)))
      (sort candidates
            (lambda (s1 s2)
              ;; Score and measure the length on real or display part of candidate
              ;; according to `use-real'.
              (let* ((real-or-disp-fn (if use-real #'cdr #'car))
                     (cand1 (cond ((and basename (consp s1))
                                   (helm-basename (funcall real-or-disp-fn s1)))
                                  ((consp s1) (funcall real-or-disp-fn s1))
                                  (basename (helm-basename s1))
                                  (t s1)))
                     (cand2 (cond ((and basename (consp s2))
                                   (helm-basename (funcall real-or-disp-fn s2)))
                                  ((consp s2) (funcall real-or-disp-fn s2))
                                  (basename (helm-basename s2))
                                  (t s2)))
                     (data1 (or (gethash cand1 table-scr)
                                (puthash cand1
                                         (list (helm-score-candidate-for-pattern
                                                cand1 helm-pattern)
                                               (length (helm-stringify cand1)))
                                         table-scr)))
                     (data2 (or (gethash cand2 table-scr)
                                (puthash cand2
                                         (list (helm-score-candidate-for-pattern
                                                cand2 helm-pattern)
                                               (length (helm-stringify cand2)))
                                         table-scr)))
                     (len1 (cadr data1))
                     (len2 (cadr data2))
                     (scr1 (car data1))
                     (scr2 (car data2)))
                (cond ((= scr1 scr2)
                       (unless preserve-tie-order
                         (< len1 len2)))
                      ((> scr1 scr2)))))))))

(defun helm-fuzzy-matching-default-sort-fn (candidates _source)
  "Default `filtered-candidate-transformer' to sort candidates in fuzzy matching."
  (helm-fuzzy-matching-default-sort-fn-1 candidates))

(defun helm-fuzzy-matching-sort-fn-preserve-ties-order (candidates _source)
  "`filtered-candidate-transformer' to sort candidates in fuzzy matching, preserving order of ties.
The default function, `helm-fuzzy-matching-default-sort-fn',
sorts ties by length, shortest first.  This function may be more
useful when the order of the candidates is meaningful, e.g. with
`recentf-list'."
  (helm-fuzzy-matching-default-sort-fn-1 candidates nil nil t))

(defun helm--maybe-get-migemo-pattern (pattern)
  (or (and helm-migemo-mode
           (assoc-default pattern helm-mm--previous-migemo-info))
      pattern))

(defun helm-fuzzy-default-highlight-match (candidate)
  "The default function to highlight matches in fuzzy matching.
Highlight elements in CANDIDATE matching `helm-pattern' according
to the matching method in use."
  (if (string= helm-pattern "")
      ;; Empty pattern, do nothing.
      candidate
    ;; Else start highlighting.
    (let* ((pair    (and (consp candidate) candidate))
           (display (helm-stringify (if pair (car pair) candidate)))
           (real    (cdr pair))
           (regex   (helm--maybe-get-migemo-pattern helm-pattern))
           (mp      (pcase (get-text-property 0 'match-part display)
                      ((pred (string= display)) nil)
                      (str str)))
           (count   0)
           beg-str end-str)
      ;; Extract all parts of display keeping original properties.
      (when (and mp (ignore-errors
                      ;; Avoid error when candidate is a huge line.
                      (string-match (regexp-quote mp) display)))
        (setq beg-str (substring display 0 (match-beginning 0))
              end-str (substring display (match-end 0) (length display))
              mp (substring display (match-beginning 0) (match-end 0))))
      (with-temp-buffer
        ;; Insert the whole display part and remove non--match-part
        ;; to keep their original face properties.
        (insert (propertize (or mp display) 'read-only nil)) ; Fix (#1176)
        (goto-char (point-min))
        (condition-case nil
            (progn
              ;; Try first matching against whole pattern.
              (while (re-search-forward regex nil t)
                (cl-incf count)
                (helm-add-face-text-properties
                 (match-beginning 0) (match-end 0) 'helm-match))
              ;; If no matches start matching against multiples or fuzzy matches.
              (when (zerop count)
                (cl-loop with multi-match = (string-match-p " " helm-pattern)
                         with patterns = (if multi-match
                                             (mapcar #'helm--maybe-get-migemo-pattern
                                                     (helm-mm-split-pattern helm-pattern))
                                           (split-string helm-pattern "" t))
                         for p in patterns
                         ;; Multi matches (regexps patterns).
                         if multi-match do
                         (progn
                           (while (re-search-forward p nil t)
                             (helm-add-face-text-properties
                              (match-beginning 0) (match-end 0)
                              'helm-match))
                           (goto-char (point-min)))
                         ;; Fuzzy matches (literal patterns).
                         else do
                         (when (search-forward p nil t)
                           (helm-add-face-text-properties
                            (match-beginning 0) (match-end 0)
                            'helm-match)))))
          (invalid-regexp nil))
        ;; Now replace the original match-part with the part
        ;; with face properties added.
        (setq display (if mp (concat beg-str (buffer-string) end-str) (buffer-string))))
      (if real (cons display real) display))))

(defun helm-fuzzy-highlight-matches (candidates _source)
  "The filtered-candidate-transformer function to highlight fuzzy matches.
See `helm-fuzzy-default-highlight-match'."
  (cl-assert helm-fuzzy-matching-highlight-fn nil "Wrong type argument functionp: nil")
  (cl-loop for c in candidates
           collect (funcall helm-fuzzy-matching-highlight-fn c)))


;;; helm-flex style
;;
;; Provide the emacs-27 flex style for emacs<27.
;; Reuse the flex scoring algorithm of flex style in emacs-27.
(defun helm-flex--style-score (str regexp)
  "Score STR candidate according to PATTERN.

REGEXP should be generated from a pattern which is a list like
\'(point \"f\" any \"o\" any \"b\" any) for \"fob\" as pattern.
Such pattern is build with
`helm-completion--flex-transform-pattern' function.

Function extracted from `completion-pcm--hilit-commonality' in
emacs-27 to provide such scoring in emacs<27."
  ;; Don't modify the string itself.
  (setq str (copy-sequence str))
  (unless (string-match regexp str)
    (error "Internal error: %s does not match %s" regexp str))
  (let* ((md (match-data))
         (start (pop md))
         (len (length str))
         (score-numerator 0)
         (score-denominator 0)
         (last-b 0)
         (update-score
          (lambda (a b)
            "Update score variables given match range (A B)."
            (setq score-numerator (+ score-numerator (- b a)))
            (unless (or (= a last-b)
                        (zerop last-b)
                        (= a (length str)))
              (setq score-denominator (+ score-denominator
                                         1
                                         (expt (- a last-b 1)
                                               (/ 1.0 3)))))
            (setq last-b b))))
    (funcall update-score start start)
    (setq md (cdr md))
    (while md
      (funcall update-score start (pop md))
      (setq start (pop md)))
    (funcall update-score len len)
    (unless (zerop (length str))
      (put-text-property
       0 1 'completion-score
       (/ score-numerator (* len (1+ score-denominator)) 1.0) str)))
  str)


;;; Matching candidates
;;
;;
(defun helm-match-functions (source)
  (let ((matchfns (or (assoc-default 'match source)
                      (assoc-default 'match-strict source)
                      #'helm-default-match-function)))
    (if (and (listp matchfns) (not (functionp matchfns)))
        matchfns (list matchfns))))

(defun helm-search-functions (source)
  (let ((searchfns (assoc-default 'search source)))
    (if (and (listp searchfns) (not (functionp searchfns)))
        searchfns (list searchfns))))

(defun helm-match-from-candidates (cands matchfns match-part-fn limit source)
  (when cands ; nil in async sources.
    (condition-case-unless-debug err
        (cl-loop with hash = (make-hash-table :test 'equal)
                 with allow-dups = (assq 'allow-dups source)
                 with case-fold-search = (helm-set-case-fold-search)
                 with count = 0
                 for iter from 1
                 for fn in matchfns
                 when (< count limit) nconc
                 (cl-loop for c in cands
                          for dup = (gethash c hash)
                          for disp = (helm-candidate-get-display c)
                          while (< count limit)
                          for target = (if (helm-attr 'match-on-real source)
                                           (or (cdr-safe c)
                                               (get-text-property 0 'helm-realvalue disp))
                                         disp)
                          for prop-part = (get-text-property 0 'match-part target)
                          for part = (and match-part-fn
                                          (or prop-part
                                              (funcall match-part-fn target)))
                          ;; When allowing dups check if DUP
                          ;; have been already found in previous loop
                          ;; by comparing its value with ITER.
                          when (and (or (and allow-dups dup (= dup iter))
                                        (null dup))
                                    (condition-case nil
                                        (funcall fn (or part target))
                                      (invalid-regexp nil)))
                          do
                          (progn
                            ;; Give as value the iteration number of
                            ;; inner loop to be able to check if
                            ;; the duplicate have not been found in previous loop.
                            (puthash c iter hash)
                            (helm--maybe-process-filter-one-by-one-candidate c source)
                            (cl-incf count))
                          ;; Filter out nil candidates maybe returned by
                          ;; `helm--maybe-process-filter-one-by-one-candidate'.
                          and when c collect
                          (if (and part (not prop-part))
                              (if (consp c)
                                  (cons (propertize target 'match-part part) (cdr c))
                                (propertize c 'match-part part))
                            c)))
      (error (unless (eq (car err) 'invalid-regexp) ; Always ignore regexps errors.
               (helm-log-error "helm-match-from-candidates in source `%s': %s %s"
                               (assoc-default 'name source) (car err) (cdr err)))
             nil))))

(defun helm-compute-matches (source)
  "Start computing candidates in SOURCE."
  (save-current-buffer
    (let ((matchfns (helm-match-functions source))
          (matchpartfn (assoc-default 'match-part source))
          (helm--source-name (assoc-default 'name source))
          (helm-current-source source)
          (limit (helm-candidate-number-limit source))
          (helm-pattern (helm-process-pattern-transformer
                         helm-pattern source)))
      (helm--fuzzy-match-maybe-set-pattern)
      ;; If source have a `filtered-candidate-transformer' attr
      ;; Filter candidates with this func, otherwise just compute
      ;; candidates.
      ;; NOTE that this next block of code is returning nil on async sources,
      ;; the candidates being processed directly in `helm-output-filter'
      ;; process-filter.
      (helm-process-filtered-candidate-transformer
       ;; When using in-buffer method or helm-pattern is empty or
       ;; using dynamic completion always compute all candidates.
       (if (or (equal helm-pattern "")
               (assq 'match-dynamic source)
               (helm--candidates-in-buffer-p source))
           ;; Compute all candidates up to LIMIT.
           ;; one-by-one are computed here only for sources that
           ;; display a list of  candidates even with an empty
           ;; pattern.
           (helm--initialize-one-by-one-candidates
            (helm-take-first-elements
             (helm-get-cached-candidates source) limit)
            source)
         ;; Compute candidates according to pattern with their match
         ;; fns.
         ;; one-by-one filtered candidates are computed during the
         ;; execution of next loop in `helm-match-from-candidates'.
         (helm-match-from-candidates
          (helm-get-cached-candidates source) matchfns matchpartfn limit source))
       source))))

(defun helm--candidates-in-buffer-p (source)
  (assq 'search source))

(defun helm-render-source (source matches)
  "Display MATCHES from SOURCE according to its settings."
  (helm-log "Source = %S" (remove (assq 'keymap source) source))
  (when matches
    (helm-insert-header-from-source source)
    (cl-loop with separate = nil
             with start = (point)
             with singleline = (null (assq 'multiline source))
             for m in matches
             for count from 1
             if singleline
             do (helm-insert-match m 'insert count source)
             else
             do (progn
                  (if separate
                      (helm-insert-candidate-separator)
                    (setq separate t))
                  (helm-insert-match m 'insert count source))
             finally (and (null singleline)
                          (put-text-property start (point)
                                             'helm-multiline t)))))

(defmacro helm--maybe-use-while-no-input (&rest body)
  "Wrap BODY in `helm-while-no-input' unless initializing a remote connection."
  `(progn
     (if (and (file-remote-p helm-pattern)
              (not (file-remote-p helm-pattern nil t)))
         ;; Tramp will ask for passwd, don't use `helm-while-no-input'.
         ,@body
       (helm-log "Using here `helm-while-no-input'")
       (helm-while-no-input ,@body))))

(defun helm--collect-matches (src-list)
  "Return a list of matches for each source in SRC-LIST.

The resulting value is a list of lists, e.g. ((a b c) (c d) (e
f)) or \(nil nil nil) for three sources when no matches found,
however this function can be interrupted by new input and in this
case returns a plain nil i.e. not (nil), in this case
`helm-update' is not rendering the source, keeping previous
candidates in display."
  (let ((matches (helm--maybe-use-while-no-input
                  (cl-loop for src in src-list
                           collect (helm-compute-matches src)))))
    (unless (eq matches t) matches)))


;;; Case fold search
;;
;;
(cl-defun helm-set-case-fold-search (&optional (pattern helm-pattern))
  "Used to set the value of `case-fold-search' in Helm.
Return t or nil depending on the value of `helm-case-fold-search'
and `helm-pattern'."
  (if helm-alive-p
      (let ((helm-case-fold-search
             (helm-aif (assq 'case-fold-search (helm-get-current-source))
                 (cdr it)
               helm-case-fold-search))
            ;; Only parse basename for filenames
            ;; to avoid setting case sensitivity
            ;; when expanded directories contains upcase
            ;; characters.
            (bn-or-pattern (if (string-match "[~/]*" pattern)
                               (helm-basename pattern)
                             pattern)))
        (helm-set-case-fold-search-1 bn-or-pattern))
    case-fold-search))

(defun helm-set-case-fold-search-1 (pattern)
  (cl-case helm-case-fold-search
    (smart (let ((case-fold-search nil))
             (if (string-match "[[:upper:]]" pattern) nil t)))
    (t helm-case-fold-search)))


;;; Helm update
;;
(defun helm-update (&optional preselect source candidates)
  "Update candidates list in `helm-buffer' based on `helm-pattern'.
Argument PRESELECT is a string or regexp used to move selection
to a particular place after finishing update.
When SOURCE is provided update mode-line for this source, otherwise
the current source will be used.
Argument CANDIDATES when provided is used to redisplay these candidates
without recomputing them, it should be a list of lists."
  (helm-log "Start updating")
  (helm-kill-async-processes)
  ;; When persistent action have been called
  ;; we have two windows even with `helm-full-frame'.
  ;; So go back to one window when updating if `helm-full-frame'
  ;; is non-`nil'.
  (when (with-helm-buffer
          (and helm-onewindow-p
               ;; We are not displaying helm-buffer in a frame and
               ;; helm-window is already displayed.
               (not helm--buffer-in-new-frame-p)
               (helm-window)
               (not (helm-action-window))))
    (with-helm-window (delete-other-windows)))
  (with-current-buffer (helm-buffer-get)
    (set (make-local-variable 'helm-input-local) helm-pattern)
    (unwind-protect
        (let (sources matches)
          ;; Collect sources ready to be updated.
          (setq sources
                (cl-loop for src in helm-sources
                         when (helm-update-source-p src)
                         collect src))
          ;; When no sources to update erase buffer
          ;; to avoid duplication of header and candidates
          ;; when next chunk of update will arrive,
          ;; otherwise the buffer is erased AFTER [1] the results
          ;; are computed.
          (unless sources (erase-buffer))
          ;; Compute matches without rendering the sources.
          ;; This prevent the helm-buffer flickering when constantly
          ;; updating.
          (helm-log "Matches: %S"
                    (setq matches (or candidates (helm--collect-matches sources))))
          ;; If computing matches finished and is not interrupted
          ;; erase the helm-buffer and render results (Fix #1157).
          (when matches ;; nil only when interrupted by helm-while-no-input.
            (erase-buffer)             ; [1]
            (cl-loop for src in sources
                     for mtc in matches
                     do (helm-render-source src mtc))
            ;; Move to first line only when there is matches
            ;; to avoid cursor moving upside down (issue #1703).
            (helm--update-move-first-line)))
      ;; When there is only one async source, update mode-line and run
      ;; `helm-after-update-hook' in `helm-output-filter--post-process',
      ;; when there is more than one source, update mode-line and run
      ;; `helm-after-update-hook' now even if an async source is
      ;; present and running in BG.
      (let ((src (or source (helm-get-current-source))))
        (unless (assq 'candidates-process src)
          (helm-display-mode-line src 'force)
          (helm-log-run-hook 'helm-after-update-hook)))
      (when preselect
        (helm-log "Update preselect candidate %s" preselect)
        (if (helm-window)
            (with-helm-window (helm-preselect preselect source))
          (helm-preselect preselect source)))
      (setq helm--force-updating-p nil)
      (helm--reset-update-flag))
    (helm-log "end update")))

(defun helm-update-source-p (source)
  "Whether SOURCE needs updating or not."
  (let ((len (string-width
              (if (assq 'multimatch source)
                  ;; Don't count spaces entered when using
                  ;; multi-match.
                  (replace-regexp-in-string " " "" helm-pattern)
                helm-pattern))))
    (and (or (not helm-source-filter)
             (member (assoc-default 'name source) helm-source-filter))
         (>= len
             (helm-aif (assq 'requires-pattern source) (or (cdr it) 1) 0))
         ;; Entering repeatedly these strings (*, ?) takes 100% CPU
         ;; and hang emacs on MacOs preventing deleting backward those
         ;; characters (issue #1802).
         (not (string-match-p "\\`[*]+\\'" helm-pattern))
         ;; These incomplete regexps hang helm forever
         ;; so defer update. Maybe replace spaces quoted when using
         ;; multi-match.
         (not (member (replace-regexp-in-string "\\s\\ " " " helm-pattern)
                      helm-update-blacklist-regexps)))))

(defun helm--update-move-first-line ()
  "Goto first line of `helm-buffer'."
  (goto-char (point-min))
  (if (helm-window)
      (helm-move-selection-common :where 'line
                                  :direction 'next
                                  :follow t)
    (forward-line 1)
    (helm-mark-current-line)
    (helm-follow-execute-persistent-action-maybe)))

(cl-defun helm-force-update (&optional preselect (recenter t))
  "Force recalculation and update of candidates.

Unlike `helm-update', this function re-evaluates `init' and
`update' attributes when present; also `helm-candidate-cache' is
not reinitialized, meaning candidates are not recomputed unless
pattern has changed.

Selection is preserved to current candidate if it still exists after
update or moved to PRESELECT, if specified.
The helm-window is re-centered at the end when RECENTER is t which
is the default.  RECENTER can be also a number in this case it is
passed as argument to `recenter'."
  (with-helm-buffer
    (let* ((source    (helm-get-current-source))
           (selection (helm-aif (helm-get-selection nil t source)
                          (regexp-quote it))))
      (setq helm--force-updating-p t)
      (mapc 'helm-force-update--reinit helm-sources)
      (helm-update (or preselect selection) source)
      (when (and (helm-window) recenter)
        (with-helm-window
          (recenter (and (numberp recenter) recenter)))))))

(defun helm-refresh ()
  "Force recalculation and update of candidates."
  (interactive)
  (with-helm-alive-p
    (helm-force-update)))
(put 'helm-refresh 'helm-only t)

(defun helm-force-update--reinit (source)
  "Reinit SOURCE by calling its update and init functions."
  ;; When using a specific buffer as cache, don't kill it.
  (helm-aif (and (null (bufferp (assoc-default
                                 (helm-attr 'name source)
                                 helm--candidate-buffer-alist)))
                 (helm-apply-functions-from-source
                  source 'helm-candidate-buffer))
      (kill-buffer it))
  (cl-dolist (attr '(update init))
    (helm-aif (assoc-default attr source)
        (helm-apply-functions-from-source source it)))
  (helm-remove-candidate-cache source))

(defun helm-redisplay-buffer ()
  "Redisplay candidates in `helm-buffer'.

Candidates are not recomputed, only redisplayed after modifying
the whole list of candidates in each source with functions found
in `redisplay' attribute of current source.  Note that candidates
are redisplayed with their display part with all properties
included only.  This function is used in async sources to
transform the whole list of candidates from the sentinel
functions (i.e. when all candidates have been computed) because
other filters like `candidate-transformer' are modifying only
each chunk of candidates from `process-filter' as they come in
and not the whole list.  Use this for e.g. sorting the whole list
of async candidates once computed.

Note: To ensure redisplay is done in async sources after Helm
reached `candidate-number-limit' you will have also to redisplay
your candidates from `helm-async-outer-limit-hook'."
  (with-helm-buffer
    (let ((get-cands (lambda (source)
                       (let ((fns (assoc-default 'redisplay source))
                             candidates
                             helm-move-to-line-cycle-in-source
                             helm-allow-mouse)
                         (helm-goto-source source)
                         (helm-next-line)
                         (helm-awhile (condition-case-unless-debug nil
                                          (and (not (helm-pos-header-line-p))
                                               (helm-get-selection
                                                nil 'withprop source))
                                        (error nil))
                           (push it candidates)
                           (when (save-excursion
                                   (forward-line 1) (helm-end-of-source-p t))
                             (cl-return nil))
                           (helm-next-line))
                         (helm-apply-functions-from-source
                          source fns (nreverse candidates)))))
          (get-sources (lambda ()
                         (let (sources helm-move-to-line-cycle-in-source)
                           (helm-awhile (helm-get-current-source)
                             (push it sources)
                             (when (save-excursion
                                     (helm-move--end-of-source)
                                     (forward-line 1) (eobp))
                               (cl-return nil))
                             (helm-next-source))
                           (nreverse sources)))))
      (goto-char (point-min))
      (helm-update nil (helm-get-current-source)
                   (cl-loop with sources = (funcall get-sources)
                            for s in helm-sources
                            for name =  (assoc-default 'name s) collect
                            (when (cl-loop for src in sources thereis
                                           (string= name
                                                    (assoc-default 'name src)))
                              (funcall get-cands s)))))))

(defun helm-remove-candidate-cache (source)
  "Remove SOURCE from `helm-candidate-cache'."
  (remhash (assoc-default 'name source) helm-candidate-cache))

(defun helm-insert-match (match insert-function &optional num source)
  "Insert MATCH into `helm-buffer' with INSERT-FUNCTION.
If MATCH is a cons cell then insert the car as display with the
cdr stored as real value in a `helm-realvalue' text property.
Args NUM and SOURCE are also stored as text property when
specified as respectively `helm-cand-num' and `helm-cur-source'."
  (let ((start     (point-at-bol (point)))
        (dispvalue (helm-candidate-get-display match))
        (realvalue (cdr-safe match))
        (map       (when helm-allow-mouse (make-sparse-keymap)))
        (inhibit-read-only t)
        end)
    (when (and (stringp dispvalue)
               (not (zerop (length dispvalue))))
      (funcall insert-function dispvalue)
      (setq end (point-at-eol))
      ;; Some strings may handle another keymap prop.
      (remove-text-properties start end '(keymap nil))
      (put-text-property start end 'read-only nil)
      ;; Some sources with candidates-in-buffer have already added
      ;; 'helm-realvalue property when creating candidate buffer.
      (unless (get-text-property start 'helm-realvalue)
        (and realvalue
             (put-text-property start end
                                'helm-realvalue realvalue)))
      (when map
        (define-key map [mouse-1] 'helm-mouse-select-candidate)
        (define-key map [mouse-2] 'ignore)
        (define-key map [mouse-3] 'helm-menu-select-action)
        (add-text-properties
         start end
         `(mouse-face highlight
                      keymap ,map
                      help-echo ,(pcase (get-text-property start 'help-echo)
                                   ((and it (pred stringp))
                                    (concat it "\nmouse-1: select candidate\nmouse-3: menu actions"))
                                   (_ "mouse-1: select candidate\nmouse-3: menu actions")))))
      (when num
        (put-text-property start end 'helm-cand-num num))
      (when source
        (put-text-property start end 'helm-cur-source source))
      (funcall insert-function "\n"))))

(defun helm--mouse-reset-selection-help-echo ()
  (let* ((inhibit-read-only t)
         (start (overlay-start helm-selection-overlay))
         (end   (overlay-end helm-selection-overlay))
         (help-echo (get-text-property start 'help-echo)))
    (when (and (stringp help-echo)
               (string-match "mouse-2: execute action" help-echo))
      (put-text-property
       start end
       'help-echo (replace-match "mouse-1: select candidate"
                                 t t help-echo)))))

(defun helm--bind-mouse-for-selection (pos)
  (let ((inhibit-read-only t)
        (map (get-text-property pos 'keymap)))
    (when map
      (define-key map [mouse-2] 'helm-maybe-exit-minibuffer)
      (put-text-property
       helm-selection-point
       (overlay-end helm-selection-overlay)
       'help-echo (helm-aif (get-text-property pos 'help-echo)
                      (if (and (stringp it)
                               (string-match "mouse-1: select candidate" it))
                          (replace-match "mouse-2: execute action" t t it)
                        "mouse-2: execute action\nmouse-3: menu actions")
                    "mouse-2: execute action\nmouse-3: menu actions")))))

(defun helm-mouse-select-candidate (event)
  (interactive "e")
  (let* ((window (posn-window (event-end event)))
         (pos    (posn-point (event-end event))))
    (unwind-protect
        (with-current-buffer (window-buffer window)
          (if (and (helm-action-window)
                   (eql window (get-buffer-window helm-buffer)))
              (user-error "selection in helm-window not available while selecting action")
            (helm--mouse-reset-selection-help-echo)
            (goto-char pos)
            (when (helm-pos-multiline-p)
              (goto-char (or (helm-get-previous-candidate-separator-pos)
                             (helm-get-previous-header-pos)))
              (forward-line 1)))
          (helm-mark-current-line)
          (helm-follow-execute-persistent-action-maybe))
      (select-window (minibuffer-window))
      (set-buffer (window-buffer window)))))
(put 'helm-mouse-select-candidate 'helm-only t)

(defun helm-insert-header-from-source (source)
  "Insert SOURCE name in `helm-buffer' header.
Maybe insert, by overlay, additional info after the source name
if SOURCE has header-name attribute."
  (let ((name (assoc-default 'name source)))
    (helm-insert-header
     name
     (helm-aif (assoc-default 'header-name source)
         (helm-apply-functions-from-source source it name)))))

(defun helm-insert-header (name &optional display-string)
  "Insert header of source NAME into the helm buffer.
If DISPLAY-STRING is non-nil and a string value then display this
additional info after the source name by overlay."
  (unless (bobp)
    (let ((start (point)))
      (insert (propertize "\n" 'face 'helm-eob-line))
      (put-text-property start (point) 'helm-header-separator t)))
  (let ((start (point)))
    (insert name)
    (put-text-property (point-at-bol)
                       (point-at-eol) 'helm-header t)
    (when display-string
      (overlay-put (make-overlay (point-at-bol) (point-at-eol))
                   'display display-string))
    (insert "\n")
    (add-text-properties start (point) '(face helm-source-header
                                              ;; Disable line numbers on
                                              ;; source headers.
                                              display-line-numbers-disable t))))

(defun helm-insert-candidate-separator ()
  "Insert separator of candidates into the Helm buffer."
  (insert (propertize helm-candidate-separator 'face 'helm-separator))
  (put-text-property (point-at-bol)
                     (point-at-eol) 'helm-candidate-separator t)
  (insert "\n"))

(defun helm-init-relative-display-line-numbers ()
  "Enable `display-line-numbers' for Helm buffers.
This is intended to be added to `helm-after-initialize-hook'.
This will work only in Emacs-26+, i.e. Emacs versions that have
`display-line-numbers-mode'."
  (when (boundp 'display-line-numbers)
    (with-helm-buffer
      (setq display-line-numbers 'relative))))

(define-minor-mode helm-display-line-numbers-mode
  "Toggle display of line numbers in current Helm buffer."
  :group 'helm
  (with-helm-alive-p
    (cl-assert (boundp 'display-line-numbers) nil
               "`display-line-numbers' not available")
    (if helm-display-line-numbers-mode
        (with-helm-buffer
          (setq display-line-numbers 'relative))
      (with-helm-buffer
        (setq display-line-numbers nil)))))
(put 'helm-display-line-numbers-mode 'helm-only t)



;;; Async process
;;
(defun helm-output-filter (process output-string)
  "The `process-filter' function for Helm async sources."
  (with-helm-quittable
    (helm-output-filter-1 (assoc process helm-async-processes) output-string)))

(defun helm-output-filter-1 (process-assoc output-string)
  (helm-log "output-string = %S" output-string)
  (with-current-buffer helm-buffer
    (let ((source (cdr process-assoc)))
      (save-excursion
        (helm-aif (assoc-default 'insertion-marker source)
            (goto-char it)
          (goto-char (point-max))
          (helm-insert-header-from-source source)
          (setcdr process-assoc
                  (append source `((insertion-marker . ,(point-marker))))))
        (helm-output-filter--process-source
         (car process-assoc) output-string source
         (helm-candidate-number-limit source))))
    (helm-output-filter--post-process)))

(defun helm-output-filter--process-source (process output-string source limit)
  (cl-dolist (candidate (helm-transform-candidates
                         (helm-output-filter--collect-candidates
                          (split-string output-string "\n")
                          (assq 'incomplete-line source))
                         source t))
    (setq candidate
          (helm--maybe-process-filter-one-by-one-candidate candidate source))
    (if (assq 'multiline source)
        (let ((start (point)))
          (helm-insert-candidate-separator)
          (helm-insert-match candidate 'insert-before-markers
                             (1+ (cdr (assq 'item-count source)))
                             source)
          (put-text-property start (point) 'helm-multiline t))
      (helm-insert-match candidate 'insert-before-markers
                         (1+ (cdr (assq 'item-count source)))
                         source))
    (cl-incf (cdr (assq 'item-count source)))
    (when (>= (assoc-default 'item-count source) limit)
      (helm-kill-async-process process)
      (helm-log-run-hook 'helm-async-outer-limit-hook)
      (cl-return))))

(defun helm-output-filter--collect-candidates (lines incomplete-line-info)
  "Collect LINES maybe completing the truncated first and last lines."
  ;; The output of process may come in chunks of any size, so the last
  ;; line of LINES could be truncated, this truncated line is stored
  ;; in INCOMPLETE-LINE-INFO to be concatenated with the first
  ;; incomplete line of the next arriving chunk. INCOMPLETE-LINE-INFO
  ;; is an attribute of source; it is created with an empty string
  ;; when the source is computed => (incomplete-line . "")
  (helm-log "incomplete-line-info = %S" (cdr incomplete-line-info))
  (butlast
   (cl-loop for line in lines
            ;; On start `incomplete-line-info' value is empty string.
            for newline = (helm-aif (cdr incomplete-line-info)
                              (prog1
                                  (concat it line)
                                (setcdr incomplete-line-info nil))
                            line)
            collect newline
            ;; Store last incomplete line (last chunk truncated) until
            ;; new output arrives. Previously storing 'line' in
            ;; incomplete-line-info assumed output was truncated in
            ;; only two chunks. But output could be large and
            ;; truncated in more than two chunks. Therefore store
            ;; 'newline' to contain the previous chunks (Issue #1187).
            finally do (setcdr incomplete-line-info newline))))

(defun helm-output-filter--post-process ()
  (helm-aif (get-buffer-window helm-buffer 'visible)
      (with-selected-window it
        (helm-skip-noncandidate-line 'next)
        (helm-mark-current-line nil 'nomouse)
        ;; FIXME Don't hardcode follow delay.
        (helm-follow-execute-persistent-action-maybe 0.5)
        (helm-display-mode-line (helm-get-current-source))
        (helm-log-run-hook 'helm-after-update-hook)
        (helm--reset-update-flag))))

(defun helm-process-deferred-sentinel-hook (process event file)
  "Defer remote processes in sentinels.
Meant to be called at the beginning of a sentinel process
function."
  (when (and (not (zerop helm-tramp-connection-min-time-diff))
             (string= event "finished\n")
             (or (file-remote-p file)
                 ;; `helm-suspend-update-flag'
                 ;; is non-`nil' here only during a
                 ;; running process, this will never be called
                 ;; when user set it explicitly with `C-!'.
                 helm-suspend-update-flag))
    (setq helm-suspend-update-flag t)
    ;; Kill the process but don't delete entry in
    ;; `helm-async-processes'.
    (helm-kill-async-process process)
    ;; When tramp opens the same connection twice in less than 5
    ;; seconds, it throws 'suppress, which calls the real-handler on
    ;; the main "Emacs". To avoid this [1] helm waits for 5 seconds
    ;; before updates yet allows user input during this delay. [1] In
    ;; recent Emacs versions, this has been fixed so tramp returns nil
    ;; in such conditions. Note: `tramp-connection-min-time-diff' cannot
    ;; have values less than 5 seconds otherwise the process dies.
    (run-at-time helm-tramp-connection-min-time-diff
                 nil (lambda ()
                       (when helm-alive-p ; Don't run timer fn after quit.
                         (setq helm-suspend-update-flag nil)
                         (helm-check-minibuffer-input))))))

(defun helm-kill-async-processes ()
  "Kill all asynchronous processes registered in `helm-async-processes'."
  (while helm-async-processes
    (helm-kill-async-process (caar helm-async-processes))
    (setq helm-async-processes (cdr helm-async-processes))))

(defun helm-kill-async-process (process)
  "Stop output from `helm-output-filter' and kill associated PROCESS."
  (set-process-filter process nil)
  (delete-process process))


;;; Actions
;;
(defun helm-execute-selection-action ()
  "Execute current action."
  (helm-log-run-hook 'helm-before-action-hook)
  ;; Position can be change when `helm-current-buffer'
  ;; is split, so jump to this position before executing action.
  (helm-current-position 'restore)
  (unwind-protect
      (prog1 (helm-execute-selection-action-1)
        (helm-log-run-hook 'helm-after-action-hook))
    (setq helm--executing-helm-action nil)))

(defun helm-execute-selection-action-1 (&optional
                                        selection action
                                        preserve-saved-action)
  "Execute ACTION on current SELECTION.
If PRESERVE-SAVED-ACTION is non-nil, then save the action."
  (helm-log "executing action")
  (setq action (helm-get-default-action
                (or action
                    helm-saved-action
                    (if (get-buffer helm-action-buffer)
                        (helm-get-selection helm-action-buffer)
                      (helm-get-actions-from-current-source)))))
  (helm-aif (and (not helm-in-persistent-action)
                 (get-buffer helm-action-buffer))
      (kill-buffer it))
  (let ((source (or helm-saved-current-source
                    (helm-get-current-source)))
        non-essential)
    (setq selection (helm-coerce-selection
                     (or selection
                         helm-saved-selection
                         (helm-get-selection nil nil source)
                         (and (assq 'accept-empty source) ""))
                     source))
    (unless preserve-saved-action (setq helm-saved-action nil))
    (when (and selection action) (funcall action selection))))

(defun helm-coerce-selection (selection source)
  "Apply coerce attribute function to SELECTION in SOURCE.
Coerce source with coerce function."
  (helm-aif (assoc-default 'coerce source)
      (helm-apply-functions-from-source source it selection)
    selection))

(defun helm-get-default-action (action)
  "Get the first ACTION value of action list in source."
  (if (and (listp action) (not (functionp action)))
      (cdar action)
    action))

(defun helm--show-action-window-other-window-p ()
  (and helm-show-action-window-other-window
       (or helm-always-two-windows
           helm--buffer-in-new-frame-p)
       (eq helm-split-window-state 'vertical)))

(defun helm-select-action ()
  "Select an action for the currently selected candidate.
If action buffer is selected, back to the Helm buffer."
  (interactive)
  (with-helm-alive-p
    (let ((src (helm-get-current-source)))
      (helm-log-run-hook 'helm-select-action-hook)
      (setq helm-saved-selection (helm-get-selection nil nil src))
      (with-selected-frame (with-helm-window (selected-frame))
        (prog1
            (helm-acond ((get-buffer-window helm-action-buffer 'visible)
                         (set-window-buffer it helm-buffer)
                         (helm--set-action-prompt 'restore)
                         (when (helm--show-action-window-other-window-p)
                           (delete-window it))
                         (kill-buffer helm-action-buffer)
                         (setq helm-saved-selection nil)
                         (helm-set-pattern helm-input 'noupdate))
                        (helm-saved-selection
                         (setq helm-saved-current-source src)
                         (let ((actions (helm-get-actions-from-current-source src))
                               helm-onewindow-p)
                           (if (functionp actions)
                               (message "Sole action: %s"
                                        (if (or (consp actions)
                                                (byte-code-function-p actions)
                                                (helm-subr-native-elisp-p actions))
                                            "Anonymous" actions))
                             (helm-show-action-buffer actions)
                             ;; Be sure the minibuffer is entirely deleted (#907).
                             (helm--delete-minibuffer-contents-from "")
                             (helm--set-action-prompt)
                             (helm-check-minibuffer-input))))
                        (t (message "No Actions available")))
          (helm-display-mode-line (helm-get-current-source))
          (run-hooks 'helm-window-configuration-hook))))))
(put 'helm-select-action 'helm-only t)

(defun helm-menu-select-action (_event)
  "Popup action menu from mouse-3."
  (interactive "e")
  (if (get-buffer-window helm-action-buffer 'visible)
      (helm-select-action)
    (let ((src (helm-get-current-source)))
      (helm-aif (helm-get-actions-from-current-source src)
          (progn
            (setq helm-saved-current-source src)
            (if (functionp it)
                (message "Sole action: %s"
                         (if (or (consp it)
                                 (byte-code-function-p it)
                                 (helm-subr-native-elisp-p it))
                             "Anonymous" it))
              (setq helm-saved-action
                    (x-popup-menu
                     t (list "Available Actions"
                             (cons "" it))))
              (helm-maybe-exit-minibuffer))
            (message "No Actions available"))))))
(put 'helm-menu-select-action 'helm-only t)

(defun helm--set-action-prompt (&optional restore)
  (with-selected-window (minibuffer-window)
    (let ((inhibit-read-only t)
          (props '(face minibuffer-prompt
                        field t
                        read-only t
                        rear-nonsticky t
                        front-sticky t))
          (prt (if restore helm--prompt helm--action-prompt)))
      (erase-buffer)
      (insert (apply #'propertize prt props)))))

(defun helm-show-action-buffer (actions)
  (with-current-buffer (get-buffer-create helm-action-buffer)
    (erase-buffer)
    (buffer-disable-undo)
    (setq cursor-type nil)
    (set-window-buffer (if (helm--show-action-window-other-window-p)
                           (split-window (get-buffer-window helm-buffer)
                                         nil helm-show-action-window-other-window)
                         (get-buffer-window helm-buffer))
                       helm-action-buffer)
    (set (make-local-variable 'helm-sources)
         (list
          (helm-build-sync-source "Actions"
            :volatile t
            :nomark t
            :persistent-action #'ignore
            :persistent-help "DoNothing"
            :keymap 'helm-map
            :candidates actions
            :mode-line '("Action(s)" "\\<helm-map>\\[helm-select-action]:BackToCands RET/f1/f2/fn:NthAct")
            :candidate-transformer
            (lambda (candidates)
              (cl-loop for (i . j) in candidates
                       for count from 1
                       collect
                       (cons (concat (cond ((> count 12)
                                            "      ")
                                           ((< count 10)
                                            (format "[f%s]  " count))
                                           (t (format "[f%s] " count)))
                                     (propertize i 'face 'helm-action))
                             j)))
            :candidate-number-limit nil)))
    (set (make-local-variable 'helm-source-filter) nil)
    (set (make-local-variable 'helm-selection-overlay) nil)
    (helm-initialize-overlays helm-action-buffer)))


;; Selection of candidates

(defun helm-display-source-at-screen-top-maybe (unit)
  "Display source at the top of screen when UNIT value is 'source.
Return nil for any other value of UNIT."
  (when (and helm-display-source-at-screen-top (eq unit 'source))
    (set-window-start (selected-window)
                      (save-excursion (forward-line -1) (point)))))

(defun helm-skip-noncandidate-line (direction)
  "Skip source header or candidates separator when going in DIRECTION.
DIRECTION is either 'next or 'previous.
Same as `helm-skip-header-and-separator-line' but ensure point is
moved to the right place when at bob or eob."
  (helm-skip-header-and-separator-line direction)
  (and (bobp) (forward-line 1))     ; Skip first header.
  (and (eobp) (forward-line -1)))   ; Avoid last empty line.

(defun helm-skip-header-and-separator-line (direction)
  "Skip source header or candidate separator when going to next/previous line.
DIRECTION is either 'next or 'previous."
  (let ((fn (cl-ecase direction
              (next 'eobp)
              (previous 'bobp))))
    (while (and (not (funcall fn))
                (or (helm-pos-header-line-p)
                    (helm-pos-candidate-separator-p)))
      (forward-line (if (and (eq direction 'previous)
                             (not (eq (point-at-bol) (point-min))))
                        -1 1)))))

(defun helm-display-mode-line (source &optional force)
  "Set up mode-line and header-line for `helm-buffer'.

SOURCE is a Helm source object.

Optional argument FORCE forces redisplay of the Helm buffer's
mode and header lines."
  (set (make-local-variable 'helm-mode-line-string)
       (helm-interpret-value (or (and (listp source) ; Check if source is empty.
                                      (assoc-default 'mode-line source))
                                 (default-value 'helm-mode-line-string))
                             source))
  (let ((follow (and (or (helm-follow-mode-p source)
                         (and helm-follow-mode-persistent
                              (member (assoc-default 'name source)
                                      helm-source-names-using-follow)))
                     " (HF)"))
        (marked (and helm-marked-candidates
                     (cl-loop with cur-name = (assoc-default 'name source)
                              for c in helm-marked-candidates
                              for name = (assoc-default 'name (car c))
                              when (string= name cur-name)
                              collect c))))
    ;; Setup mode-line.
    (if helm-mode-line-string
        (setq mode-line-format
              `(:propertize
                (" " mode-line-buffer-identification " "
                 (:eval (format "L%-3d" (helm-candidate-number-at-point)))
                 ,follow
                 " "
                 (:eval ,(and marked
                              (propertize
                               (format "M%d" (length marked))
                               'face 'helm-visible-mark)))
                 (:eval (when ,helm--mode-line-display-prefarg
                          (let ((arg (prefix-numeric-value
                                      (or prefix-arg current-prefix-arg))))
                            (unless (= arg 1)
                              (propertize (format " [prefarg:%s]" arg)
                                          'face 'helm-prefarg)))))
                 " "
                 (:eval (with-helm-buffer
                          (helm-show-candidate-number
                           (car-safe helm-mode-line-string))))
                 " " helm--mode-line-string-real " "
                 (:eval (make-string (window-width) ? )))
                keymap (keymap (mode-line keymap
                                          (mouse-1 . ignore)
                                          (down-mouse-1 . ignore)
                                          (drag-mouse-1 . ignore)
                                          (mouse-2 . ignore)
                                          (down-mouse-2 . ignore)
                                          (drag-mouse-2 . ignore)
                                          (mouse-3 . ignore)
                                          (down-mouse-3 . ignore)
                                          (drag-mouse-3 . ignore))))
              helm--mode-line-string-real
              (substitute-command-keys (if (listp helm-mode-line-string)
                                           (cadr helm-mode-line-string)
                                         helm-mode-line-string)))
      (setq mode-line-format (default-value 'mode-line-format)))
    ;; Setup header-line.
    (cond (helm-echo-input-in-header-line
           (setq force t)
           (helm--set-header-line))
          (helm-display-header-line
           (let ((hlstr (helm-interpret-value
                         (and (listp source)
                              (assoc-default 'header-line source))
                         source))
                 (endstr (make-string (window-width) ? )))
             (setq header-line-format
                   (propertize (concat " " hlstr endstr)
                               'face 'helm-header))))))
  (when force (force-mode-line-update)))

(defun helm--set-header-line (&optional update)
  (with-selected-window (minibuffer-window)
    (when helm-display-header-line
      ;; Prevent cursor movement over the overlay displaying
      ;; persistent-help in minibuffer (issue #2108).
      (setq-local disable-point-adjustment t))
    (let* ((beg  (save-excursion (vertical-motion 0 (helm-window)) (point)))
           (end  (save-excursion (end-of-visual-line) (point)))
           ;; The visual line where the cursor is.
           (cont (buffer-substring beg end))
           (pref (propertize
                  " "
                  'display (if (string-match-p (regexp-opt `(,helm--prompt
                                                             ,helm--action-prompt))
                                               cont)
                               `(space :width ,helm-header-line-space-before-prompt)
                             (propertize
                              "->"
                              'face 'helm-header-line-left-margin))))
           (pos  (- (point) beg)))
      ;; Increment pos each time we find a "%" up to current-pos (#1648).
      (cl-loop for c across (buffer-substring-no-properties beg (point))
               when (eql c ?%) do (cl-incf pos))
      ;; Increment pos when cursor is on a "%" to make it visible in header-line
      ;; i.e "%%|" and not "%|%" (#1649).
      (when (eql (char-after) ?%) (setq pos (1+ pos)))
      (setq cont (replace-regexp-in-string "%" "%%" cont))
      (with-helm-buffer
        (setq header-line-format (concat pref cont " "))
        (funcall helm-default-prompt-display-function pos)
        (when update (force-mode-line-update))))))

(defun helm-set-default-prompt-display (pos)
  (put-text-property
   ;; Increment pos to handle the space before prompt (i.e `pref').
   (+ 1 pos) (+ 2 pos)
   'face
   ;; Don't just use cursor face, this can hide the current character.
   (list :inverse-video t
         :foreground (face-background 'cursor)
         :background (face-background 'default))
   header-line-format))

(defun helm-exchange-minibuffer-and-header-line ()
  "Display minibuffer in header-line and vice versa for current Helm session.

This is a toggle command."
  (interactive)
  (with-helm-window
    (add-hook 'helm-minibuffer-set-up-hook 'helm-hide-minibuffer-maybe)
    (setq-local helm-echo-input-in-header-line
                (not helm-echo-input-in-header-line))
    (with-selected-window (minibuffer-window)
      (if (with-helm-buffer helm-echo-input-in-header-line)
          (helm-hide-minibuffer-maybe)
        (remove-overlays)
        (setq cursor-type t)))
    (helm-display-mode-line (helm-get-current-source) t)))
(put 'helm-exchange-minibuffer-and-header-line 'helm-only t)

(defun helm--update-header-line ()
  ;; This should be used in `post-command-hook',
  ;; nowhere else.
  (when (with-helm-buffer helm-echo-input-in-header-line)
    (helm--set-header-line t)))

(defun helm-hide-minibuffer-maybe ()
  "Hide minibuffer contents in a Helm session.
This function should normally go to `helm-minibuffer-set-up-hook'.
It has no effect if `helm-echo-input-in-header-line' is nil."
  (when (with-helm-buffer helm-echo-input-in-header-line)
    (let ((ov (make-overlay (point-min) (point-max) nil nil t)))
      (overlay-put ov 'window (selected-window))
      (helm-aif (and helm-display-header-line
                     (helm-attr 'persistent-help))
          (progn
            (overlay-put ov 'display
                         (truncate-string-to-width
                          (substitute-command-keys
                           (concat "\\<helm-map>\\[helm-execute-persistent-action]: "
                                   (format "%s (keeping session)" it)))
                          (- (window-width) 1)))
            (overlay-put ov 'face 'helm-header))
        (overlay-put ov 'face (let ((bg-color (face-background 'default nil)))
                                `(:background ,bg-color :foreground ,bg-color))))

      (setq cursor-type nil))))

(defun helm-show-candidate-number (&optional name)
  "Used to display candidate number in mode-line.
You can specify NAME of candidates e.g. \"Buffers\" otherwise it
is \"Candidate\(s\)\" by default."
  (when helm-alive-p
    (unless (helm-empty-source-p)
      ;; Build a fixed width string when candidate-number < 1000
      (let* ((cand-name (or name "Candidate(s)"))
             (width (length (format "[999 %s]" cand-name))))
        (propertize
         (format (concat "%-" (number-to-string width) "s")
                 (format "[%s %s]"
                         (helm-get-candidate-number 'in-current-source)
                         cand-name))
         'face (if helm-suspend-update-flag
                   'helm-candidate-number-suspended
                 'helm-candidate-number))))))

(cl-defun helm-move-selection-common (&key where direction (follow t))
  "Move the selection marker to a new position.
Position is determined by WHERE and DIRECTION.
Key arg WHERE can be one of:
 - line
 - page
 - edge
 - source
Key arg DIRECTION can be one of:
 - previous
 - next
 - A source or a source name when used with :WHERE 'source."
  (let ((move-func (cl-case where
                     (line (cl-ecase direction
                             (previous 'helm-move--previous-line-fn)
                             (next 'helm-move--next-line-fn)))
                     (page (cl-ecase direction
                             (previous 'helm-move--previous-page-fn)
                             (next 'helm-move--next-page-fn)))
                     (edge (cl-ecase direction
                             (previous 'helm-move--beginning-of-buffer-fn)
                             (next 'helm-move--end-of-buffer-fn)))
                     (source (cl-case direction
                               (previous 'helm-move--previous-source-fn)
                               (next 'helm-move--next-source-fn)
                               (t (lambda () ; A source is passed as DIRECTION arg.
                                    (helm-move--goto-source-fn direction)))))))
        source)
    (unless (or (helm-empty-buffer-p (helm-buffer-get))
                (not (helm-window)))
      (with-helm-window
        (when helm-allow-mouse
          (helm--mouse-reset-selection-help-echo))
        (helm-log-run-hook 'helm-move-selection-before-hook)
        (funcall move-func)
        (and (memq direction '(next previous))
             (helm-skip-noncandidate-line direction))
        (when (helm-pos-multiline-p)
          (helm-move--beginning-of-multiline-candidate))
        (helm-display-source-at-screen-top-maybe where)
        (helm-mark-current-line)
        (when follow
          (helm-follow-execute-persistent-action-maybe))
        (helm-display-mode-line (setq source (helm-get-current-source)))
        (helm-log-run-hook 'helm-move-selection-after-hook)
        (helm--set-minibuffer-completion-confirm source)))))

(defun helm-move--beginning-of-multiline-candidate ()
  (let ((header-pos (helm-get-previous-header-pos))
        (separator-pos (helm-get-previous-candidate-separator-pos)))
    (when header-pos
      (goto-char (if (or (null separator-pos)
                         (< separator-pos header-pos))
                     header-pos
                   separator-pos))
      (forward-line 1))))

(defun helm-move--previous-multi-line-fn ()
  (forward-line -1)
  (unless (helm-pos-header-line-p)
    (helm-skip-header-and-separator-line 'previous)
    (helm-move--beginning-of-multiline-candidate)))

(defun helm-move--previous-line-fn ()
  (if (not (helm-pos-multiline-p))
      (forward-line -1)
    (helm-move--previous-multi-line-fn))
  (when (and helm-move-to-line-cycle-in-source
             (helm-pos-header-line-p))
    (forward-line 1)
    (helm-move--end-of-source)
    ;; We are at end of helm-buffer
    ;; check if last candidate is a multiline candidate
    ;; and jump to it
    (when (and (eobp)
               (save-excursion (forward-line -1) (helm-pos-multiline-p)))
      (helm-move--previous-multi-line-fn))))

(defun helm-move--next-multi-line-fn ()
  (let ((header-pos (helm-get-next-header-pos))
        (separator-pos (helm-get-next-candidate-separator-pos)))
    (cond ((and separator-pos
                (or (null header-pos) (< separator-pos header-pos)))
           (goto-char separator-pos))
          (header-pos
           (goto-char header-pos)))))

(defun helm-move--next-line-fn ()
  (if (not (helm-pos-multiline-p))
      (forward-line 1)
    (helm-move--next-multi-line-fn))
  (when (and helm-move-to-line-cycle-in-source
             (or (save-excursion (and (helm-pos-multiline-p)
                                      (goto-char (overlay-end
                                                  helm-selection-overlay))
                                      (helm-end-of-source-p t)))
                 (helm-end-of-source-p t)))
    (helm-move--beginning-of-source)))

(defun helm-move--previous-page-fn ()
  (condition-case nil
      (scroll-down)
    (beginning-of-buffer (goto-char (point-min)))))

(defun helm-move--next-page-fn ()
  (condition-case nil
      (scroll-up)
    (end-of-buffer (goto-char (point-max)))))

(defun helm-move--beginning-of-buffer-fn ()
  (goto-char (point-min)))

(defun helm-move--end-of-buffer-fn ()
  (goto-char (point-max)))

(defun helm-move--end-of-source ()
  (helm-aif (helm-get-next-header-pos)
      (progn (goto-char it) (forward-line -2))
    (goto-char (point-max))))

(defun helm-move--beginning-of-source ()
  (helm-aif (helm-get-previous-header-pos)
      (progn (goto-char it)
             (forward-line 1))
    (goto-char (point-min))))

(defun helm-move--previous-source-fn ()
  (forward-line -1)
  (if (bobp)
      (goto-char (point-max))
    (helm-skip-header-and-separator-line 'previous))
  (goto-char (helm-get-previous-header-pos))
  (forward-line 1))

(defun helm-move--next-source-fn ()
  (goto-char (or (and (not (save-excursion
                             (forward-line 1) (eobp)))
                      ;; Empty source at eob are just
                      ;; not displayed unless they are dummy.
                      ;; Issue #1117.
                      (helm-get-next-header-pos))
                 (point-min))))

(defun helm-move--goto-source-fn (source-or-name)
  (goto-char (point-min))
  (let ((name (if (stringp source-or-name)
                  source-or-name
                (assoc-default 'name source-or-name))))
    (if (or (null name) (string= name ""))
        (forward-line 1)
      (condition-case err
          (while (not (string= name (helm-current-line-contents)))
            (goto-char (helm-get-next-header-pos)))
        (error (helm-log "%S" err))))))

(defun helm-candidate-number-at-point ()
  (if helm-alive-p
      (with-helm-buffer
        (or (get-text-property (point) 'helm-cand-num) 1))
    (or (get-text-property (point) 'helm-cand-num) 1)))

(defun helm--next-or-previous-line (direction &optional arg)
  ;; Be sure to not use this in non--interactives calls.
  (let ((helm-move-to-line-cycle-in-source
         (and helm-move-to-line-cycle-in-source arg)))
    (if (and arg (> arg 1))
        (cl-loop with pos = (helm-candidate-number-at-point)
                 with cand-num = (helm-get-candidate-number t)
                 with iter = (min arg (if (eq direction 'next)
                                          (- cand-num pos)
                                        (min arg (1- pos))))
                 for count from 1
                 while (<= count iter)
                 do
                 (helm-move-selection-common :where 'line :direction direction))
      (helm-move-selection-common :where 'line :direction direction))))

(defun helm-previous-line (&optional arg)
  "Move selection to the ARG previous line(s).
Same behavior as `helm-next-line' when called with a numeric
prefix arg."
  (interactive "p")
  (with-helm-alive-p
    (helm--next-or-previous-line 'previous arg)))
(put 'helm-previous-line 'helm-only t)

(defun helm-next-line (&optional arg)
  "Move selection to the next ARG line(s).
When numeric prefix arg is > than the number of candidates, then
move to the last candidate of current source (i.e. don't move to
next source)."
  (interactive "p")
  (with-helm-alive-p
    (helm--next-or-previous-line 'next arg)))
(put 'helm-next-line 'helm-only t)

(defun helm-previous-page ()
  "Move selection back with a pageful."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'page :direction 'previous)))
(put 'helm-previous-page 'helm-only t)

(defun helm-next-page ()
  "Move selection forward with a pageful."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'page :direction 'next)))
(put 'helm-next-page 'helm-only t)

(defun helm-beginning-of-buffer ()
  "Move selection at the top."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'edge :direction 'previous)))
(put 'helm-beginning-of-buffer 'helm-only t)

(defun helm-end-of-buffer ()
  "Move selection at the bottom."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'edge :direction 'next)))
(put 'helm-end-of-buffer 'helm-only t)

(defun helm-previous-source ()
  "Move selection to the previous source."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'source :direction 'previous)))
(put 'helm-previous-source 'helm-only t)

(defun helm-next-source ()
  "Move selection to the next source."
  (interactive)
  (with-helm-alive-p
    (helm-move-selection-common :where 'source :direction 'next)))
(put 'helm-next-source 'helm-only t)

(defun helm-goto-source (&optional source-or-name)
  "Move the selection to the source named SOURCE-OR-NAME.

If SOURCE-OR-NAME is empty string or nil go to the first
candidate of first source."
  (helm-move-selection-common :where 'source :direction source-or-name))

(defun helm--follow-action (arg)
  (let ((helm--temp-follow-flag t) ; Needed in HFF.
        (in-follow-mode (helm-follow-mode-p)))
    ;; When follow-mode is already enabled, just go to next or
    ;; previous line.
    (when (or (eq last-command 'helm-follow-action-forward)
              (eq last-command 'helm-follow-action-backward)
              (eq last-command 'helm-execute-persistent-action)
              in-follow-mode)
      (if (> arg 0)
          (helm-move-selection-common :where 'line
                                      :direction 'next
                                      :follow nil)
        (helm-move-selection-common :where 'line
                                    :direction 'previous
                                    :follow nil)))
    (unless in-follow-mode
      (helm-execute-persistent-action))))

(defun helm-follow-action-forward ()
  "Go to next line and execute persistent action."
  (interactive)
  (with-helm-alive-p (helm--follow-action 1)))
(put 'helm-follow-action-forward 'helm-only t)

(defun helm-follow-action-backward ()
  "Go to previous line and execute persistent action."
  (interactive)
  (with-helm-alive-p (helm--follow-action -1)))
(put 'helm-follow-action-backward 'helm-only t)

(defun helm-mark-current-line (&optional resumep nomouse)
  "Move `helm-selection-overlay' to current line.
When RESUMEP is non nil move overlay to `helm-selection-point'.
When NOMOUSE is specified do not set mouse bindings.

Note that selection is unrelated to visible marks used for
marking candidates."
  (with-helm-buffer
    (when resumep
      (goto-char helm-selection-point))
    (move-overlay
     helm-selection-overlay (point-at-bol)
     (if (helm-pos-multiline-p)
         (let ((header-pos (helm-get-next-header-pos))
               (separator-pos (helm-get-next-candidate-separator-pos)))
           (or (and (null header-pos) separator-pos)
               (and header-pos separator-pos
                    (< separator-pos header-pos)
                    separator-pos)
               header-pos
               (point-max)))
       (1+ (point-at-eol))))
    (setq helm-selection-point (overlay-start helm-selection-overlay))
    (when (and helm-allow-mouse (null nomouse))
      (helm--bind-mouse-for-selection helm-selection-point))))

(defun helm-confirm-and-exit-minibuffer ()
  "Maybe ask for confirmation when exiting helm.
It is similar to `minibuffer-complete-and-exit' adapted to Helm.
If `minibuffer-completion-confirm' value is 'confirm, send
minibuffer confirm message and exit on next hit.  If
`minibuffer-completion-confirm' value is t, don't exit and send
message 'no match'."
  (interactive)
  (with-helm-alive-p
    (if (and (helm--updating-p)
             (null helm--reading-passwd-or-string))
        (progn (message "[Display not ready]")
               (sit-for 0.5) (message nil)
               (helm-update))
      (let* ((src (helm-get-current-source))
             (empty-buffer-p (with-current-buffer helm-buffer
                               (eq (point-min) (point-max))))
             (unknown (and (not empty-buffer-p)
                           (helm-aif (get-text-property
                                      0 'display
                                      (helm-get-selection nil 'withprop src))
                               (when (stringp it)
                                 (string-match-p "\\`\\[\\?\\]" it))))))
        (cond ((and (or empty-buffer-p unknown)
                    (memq minibuffer-completion-confirm
                          '(confirm confirm-after-completion)))
               (setq helm-minibuffer-confirm-state
                     'confirm)
               (setq minibuffer-completion-confirm nil)
               (minibuffer-message " [confirm]"))
              ;; When require-match is strict (i.e. `t'), buffer
              ;; should be either empty or in read-file-name have an
              ;; unknown candidate ([?] prefix), if it's not the case
              ;; fix it in helm-mode but not here.
              ((and (or empty-buffer-p unknown)
                    (eq minibuffer-completion-confirm t))
               (minibuffer-message " [No match]"))
              (empty-buffer-p
               ;; This is used when helm-buffer is totally empty,
               ;; i.e. the [?] have not been added because must-match
               ;; is used from outside helm-comp-read i.e. from a helm
               ;; source built with :must-match.
               (setq helm-saved-selection helm-pattern
                     helm-saved-action (helm-get-default-action
                                        (assoc-default
                                         'action
                                         (car (with-helm-buffer helm-sources))))
                     helm-minibuffer-confirm-state nil)
               (helm-exit-minibuffer))
              (t
               (setq helm-minibuffer-confirm-state nil)
               (helm-exit-minibuffer)))))))
(put 'helm-confirm-and-exit-minibuffer 'helm-only t)

(defun helm-confirm-and-exit-hook ()
  "Restore `minibuffer-completion-confirm' when helm update."
  (unless (or (eq minibuffer-completion-confirm t)
              (not helm-minibuffer-confirm-state))
    (setq minibuffer-completion-confirm
          helm-minibuffer-confirm-state)))
(add-hook 'helm-after-update-hook 'helm-confirm-and-exit-hook)

(defun helm--set-minibuffer-completion-confirm (src)
  (with-helm-buffer
    (helm-aif (helm-attr 'must-match src)
        (setq minibuffer-completion-confirm it))))

(defun helm-read-string (prompt &optional initial-input history
                                default-value inherit-input-method)
  "Same as `read-string' but for reading string from a helm session."
  (let ((helm--reading-passwd-or-string t))
    (read-string
     prompt initial-input history default-value inherit-input-method)))

(defun helm--updating-p ()
  ;; helm timer is between two cycles.
  ;; IOW `helm-check-minibuffer-input' haven't yet compared input
  ;; and `helm-pattern'.
  (or (not (equal (minibuffer-contents) helm-pattern))
      ;; `helm-check-minibuffer-input' have launched `helm-update'.
      helm--in-update))

(defun helm-maybe-exit-minibuffer ()
  (interactive)
  (with-helm-alive-p
    (if (and (helm--updating-p)
             (null helm--reading-passwd-or-string))
        (progn
          (message "[Display not ready]")
          (sit-for 0.5) (message nil)
          (helm-update))
      (helm-exit-minibuffer))))
(put 'helm-maybe-exit-minibuffer 'helm-only t)

(defun helm-exit-minibuffer ()
  "Select the current candidate by exiting the minibuffer."
  (unless helm-current-prefix-arg
    (setq helm-current-prefix-arg current-prefix-arg))
  (setq helm-exit-status 0)
  (helm-log-run-hook 'helm-exit-minibuffer-hook)
  (exit-minibuffer))

(defun helm-keyboard-quit ()
  "Quit minibuffer in helm.
If action buffer is displayed, kill it."
  (interactive)
  (with-helm-alive-p
    (when (get-buffer-window helm-action-buffer 'visible)
      (kill-buffer helm-action-buffer))
    (setq helm-exit-status 1)
    (abort-recursive-edit)))
(put 'helm-keyboard-quit 'helm-only t)

(defun helm-get-next-header-pos ()
  "Return the position of the next header from point."
  (next-single-property-change (point) 'helm-header))

(defun helm-get-previous-header-pos ()
  "Return the position of the previous header from point."
  (previous-single-property-change (point) 'helm-header))

(defun helm-pos-multiline-p ()
  "Return non-`nil' if the current position is in the multiline source region."
  (get-text-property (point) 'helm-multiline))

(defun helm-get-next-candidate-separator-pos ()
  "Return the position of the next candidate separator from point."
  (let ((hp (helm-get-next-header-pos)))
    (helm-aif (next-single-property-change (point) 'helm-candidate-separator)
        (or
         ;; Be sure we don't catch
         ;; the separator of next source.
         (and hp (< it hp) it)
         ;; The separator found is in next source
         ;; we are at last cand, so use the header pos.
         (and hp (< hp it) hp)
         ;; A single source, just try next separator.
         it))))

(defun helm-get-previous-candidate-separator-pos ()
  "Return the position of the previous candidate separator from point."
  (previous-single-property-change (point) 'helm-candidate-separator))

(defun helm-pos-header-line-p ()
  "Return t if the current line is a header line."
  (or (get-text-property (point-at-bol) 'helm-header)
      (get-text-property (point-at-bol) 'helm-header-separator)))

(defun helm-pos-candidate-separator-p ()
  "Return t if the current line is a candidate separator."
  (get-text-property (point-at-bol) 'helm-candidate-separator))


;;; Debugging
;;
;;
(defun helm-debug-output ()
  "Show all Helm-related variables at this time."
  (interactive)
  (with-helm-alive-p
    (helm-help-internal " *Helm Debug*" 'helm-debug-output-function)))
(put 'helm-debug-output 'helm-only t)

(defun helm-debug-output-function (&optional vars)
  (message "Calculating all helm-related values...")
  (insert "If you debug some variables or forms, set `helm-debug-variables'
to a list of forms.\n\n")
  (cl-dolist (v (or vars
                    helm-debug-variables
                    (apropos-internal "^helm-" 'boundp)))
    (insert "** "
            (pp-to-string v) "\n"
            (pp-to-string (with-current-buffer helm-buffer (eval v))) "\n"))
  (message "Calculating all helm-related values...Done"))

(defun helm-enable-or-switch-to-debug ()
  "First hit enable helm debugging, second hit switch to debug buffer."
  (interactive)
  (with-helm-alive-p
    (if helm-debug
        (helm-run-after-exit
         #'helm-debug-open-last-log)
      (setq helm-debug t)
      (with-helm-buffer (setq truncate-lines nil))
      (message "Debugging enabled"))))
(put 'helm-enable-or-switch-to-debug 'helm-only t)


;; Misc
(defun helm-kill-buffer-hook ()
  "Remove tick entry from `helm-tick-hash' and remove buffer from
`helm-buffers' when killing a buffer."
  (cl-loop for key being the hash-keys in helm-tick-hash
           if (string-match (format "^%s/" (regexp-quote (buffer-name))) key)
           do (remhash key helm-tick-hash))
  (setq helm-buffers (remove (buffer-name) helm-buffers)))
(add-hook 'kill-buffer-hook 'helm-kill-buffer-hook)

(defun helm-preselect (candidate-or-regexp &optional source)
  "Move selection to CANDIDATE-OR-REGEXP on Helm start.

CANDIDATE-OR-REGEXP can be a:

- String
- Cons cell of two strings
- Nullary function, which moves to a candidate

When CANDIDATE-OR-REGEXP is a cons cell, tries moving to first
element of the cons cell, then the second, and so on.  This allows
selection of duplicate candidates after the first.

Optional argument SOURCE is a Helm source object."
  (with-helm-buffer
    (when candidate-or-regexp
      (if source
          (helm-goto-source source)
        (goto-char (point-min))
        (forward-line 1))
      (if (functionp candidate-or-regexp)
          (funcall candidate-or-regexp)
        (let ((start (point)) mp)
          (helm-awhile (if (consp candidate-or-regexp)
                           (and (re-search-forward (car candidate-or-regexp) nil t)
                                (re-search-forward (cdr candidate-or-regexp) nil t))
                         (re-search-forward candidate-or-regexp nil t))
            ;; If search fall on an header line continue loop
            ;; until it match or fail (Issue #1509).
            (unless (helm-pos-header-line-p) (cl-return (setq mp it))))
          (goto-char (or mp start)))))
    (forward-line 0) ; Avoid scrolling right on long lines.
    (when (helm-pos-multiline-p)
      (helm-move--beginning-of-multiline-candidate))
    (when (helm-pos-header-line-p) (forward-line 1))
    (when helm-allow-mouse
      (helm--mouse-reset-selection-help-echo))
    (helm-mark-current-line)
    (helm-display-mode-line (or source (helm-get-current-source)))
    (helm-log-run-hook 'helm-after-preselection-hook)))

(defun helm-delete-current-selection ()
  "Delete the currently selected item."
  (with-helm-window
    (cond ((helm-pos-multiline-p)
           (helm-aif (helm-get-next-candidate-separator-pos)
               (delete-region (point-at-bol)
                              (1+ (progn (goto-char it) (point-at-eol))))
             ;; last candidate
             (goto-char (helm-get-previous-candidate-separator-pos))
             (delete-region (point-at-bol) (point-max)))
           (when (helm-end-of-source-p)
             (goto-char (or (helm-get-previous-candidate-separator-pos)
                            (point-min)))
             (forward-line 1)))
          (t
           (delete-region (point-at-bol) (1+ (point-at-eol)))
           (when (helm-end-of-source-p t)
             (let ((headp (save-excursion
                            (forward-line -1)
                            (not (helm-pos-header-line-p)))))
               (and headp (forward-line -1))))))
    (unless (helm-end-of-source-p t)
      (helm-mark-current-line))))

(defun helm-end-of-source-1 (n at-point)
  (save-excursion
    (if (and (helm-pos-multiline-p) (null at-point))
        (null (helm-get-next-candidate-separator-pos))
      (forward-line (if at-point 0 n))
      (or (eq (point-at-bol) (point-at-eol))
          (helm-pos-header-line-p)
          (if (< n 0) (bobp) (eobp))))))

(defun helm-end-of-source-p (&optional at-point)
  "Return non-nil if we are at EOB or end of source."
  (helm-end-of-source-1 1 at-point))

(defun helm-beginning-of-source-p (&optional at-point)
  "Return non-nil if we are at BOB or beginning of source."
  (helm-end-of-source-1 -1 at-point))

(defun helm--edit-current-selection-internal (func)
  (with-helm-window
    (forward-line 0)
    (let ((realvalue (get-text-property (point) 'helm-realvalue))
          (multiline (get-text-property (point) 'helm-multiline)))
      (funcall func)
      (forward-line 0)
      (and realvalue
           (put-text-property (point) (point-at-eol)
                              'helm-realvalue realvalue))
      (and multiline
           (put-text-property (point)
                              (or (helm-get-next-candidate-separator-pos)
                                  (point-max))
                              'helm-multiline multiline))
      (helm-mark-current-line))))

(defmacro helm-edit-current-selection (&rest forms)
  "Evaluate FORMS at current selection in the helm buffer.
Used generally to modify current selection."
  (declare (indent 0) (debug t))
  `(helm--edit-current-selection-internal
    (lambda () ,@forms)))

(defun helm--delete-minibuffer-contents-from (from-str)
  ;; Giving an empty string value to FROM-STR delete all.
  (let ((input (minibuffer-contents)))
    (helm-reset-yank-point)
    (if (> (length input) 0)
        ;; minibuffer is not empty, delete contents from end
        ;; of FROM-STR and update.
        (helm-set-pattern from-str)
      ;; minibuffer is already empty, force update.
      (helm-force-update))))

(defun helm-delete-minibuffer-contents (&optional arg)
  "Delete minibuffer contents.
When `helm-delete-minibuffer-contents-from-point' is non-nil,
delete minibuffer contents from point instead of deleting all.
With a prefix arg reverse this behaviour.  When at the end of
minibuffer, delete all."
  (interactive "P")
  (let ((str (if helm-delete-minibuffer-contents-from-point
                 (if (or arg (eobp))
                     "" (helm-minibuffer-completion-contents))
               (if (and arg (not (eobp)))
                   (helm-minibuffer-completion-contents) ""))))
    (helm--delete-minibuffer-contents-from str)))


;;; helm-source-in-buffer.
;;
(defun helm-candidates-in-buffer (&optional source)
  "The top level function used to store candidates with `helm-source-in-buffer'.

Candidates are stored in a buffer generated internally by
`helm-candidate-buffer' function.  Each candidate must be placed
in one line.

The buffer is created and fed in the init attribute function of
Helm.

E.g.:

     (helm-build-in-buffer-source \"test\"
       :init (lambda ()
               (helm-init-candidates-in-buffer
                   'global '(foo foa fob bar baz))))

A shortcut can be used to simplify:

     (helm-build-in-buffer-source \"test\"
       :data '(foo foa fob bar baz))

By default, Helm makes candidates by evaluating the candidates
function, then narrows them by `string-match' for each candidate.

But this is slow for large number of candidates.  The new way is
to store all candidates in a buffer and then narrow with
`re-search-forward'.  Search function is customizable by search
attribute.  The important point is that buffer processing is MUCH
FASTER than string list processing and is the Emacs way.

The init function writes all candidates to a newly-created
candidate buffer.  The candidates buffer is created or specified
by `helm-candidate-buffer'.  Candidates are stored in a line.

The candidates function narrows all candidates, IOW creates a
subset of candidates dynamically.

Class `helm-source-in-buffer' is implemented with three attributes:

    (candidates . helm-candidates-in-buffer)
    (volatile)
    (match identity)

The volatile attribute is needed because
`helm-candidates-in-buffer' creates candidates dynamically and
need to be called every time `helm-pattern' changes.

Because `helm-candidates-in-buffer' plays the role of `match'
attribute function, specifying `(match identity)' makes the
source slightly faster.

However if source contains `match-part' attribute, match is
computed only on part of candidate returned by the call of
function provided by this attribute.  The function should have one
arg, candidate, and return only a specific part of candidate.

To customize `helm-candidates-in-buffer' behaviour, use `search',
`get-line' and `match-part' attributes."
  (let ((src (or source (helm-get-current-source))))
    (helm-candidates-in-buffer-1
     (helm-candidate-buffer)
     helm-pattern
     (or (assoc-default 'get-line src)
         #'buffer-substring-no-properties)
     (or (assoc-default 'search src)
         '(helm-candidates-in-buffer-search-default-fn))
     (helm-candidate-number-limit src)
     (helm-attr 'match-part)
     src)))

(defun helm-candidates-in-buffer-search-default-fn (pattern)
  "Search PATTERN with `re-search-forward' with bound and noerror args."
  (condition-case _err
      (re-search-forward pattern nil t)
    (invalid-regexp nil)))

(defun helm-candidates-in-buffer-1 (buffer pattern get-line-fn
                                           search-fns limit
                                           match-part-fn source)
  "Return the list of candidates inserted in BUFFER matching PATTERN."
  ;; buffer == nil when candidates buffer does not exist.
  (when buffer
    (with-current-buffer buffer
      (let ((inhibit-point-motion-hooks t)
            (start-point (1- (point-min))))
        (goto-char start-point)
        (if (string= pattern "")
            (helm-initial-candidates-from-candidate-buffer
             get-line-fn limit)
          (helm-search-from-candidate-buffer
           pattern get-line-fn search-fns limit
           start-point match-part-fn source))))))


(defun helm-search-from-candidate-buffer (pattern get-line-fn search-fns
                                                  limit start-point match-part-fn source)
  (let ((inhibit-read-only t))
    (helm--search-from-candidate-buffer-1
     (lambda ()
       (cl-loop with hash = (make-hash-table :test 'equal)
                with allow-dups = (assq 'allow-dups source)
                with case-fold-search = (helm-set-case-fold-search)
                with count = 0
                for iter from 1
                for searcher in search-fns
                do (progn
                     (goto-char start-point)
                     ;; The character at start-point is a newline,
                     ;; if pattern match it that's mean we are
                     ;; searching for newline in buffer, in this
                     ;; case skip this false line.
                     ;; See comment >>>[1] in
                     ;; `helm--search-from-candidate-buffer-1'.
                     (and (condition-case nil
                              (looking-at pattern)
                            (invalid-regexp nil))
                          (forward-line 1)))
                nconc
                (cl-loop with pos-lst
                         ;; POS-LST is used as a flag to decide if we
                         ;; run `helm-search-match-part' even if
                         ;; MATCH-PART isn't specified on source. This
                         ;; happen when fuzzy matching or using a
                         ;; negation (!) in one of the patterns, in
                         ;; these case the searcher returns a list
                         ;; '(BEG END) instead of an integer like
                         ;; `re-search-forward'.
                         while (and (setq pos-lst (funcall searcher pattern))
                                    (not (eobp))
                                    (< count limit))
                         for cand = (apply get-line-fn
                                           (if (and pos-lst (listp pos-lst))
                                               pos-lst
                                             (list (point-at-bol) (point-at-eol))))
                         when (and match-part-fn
                                   (not (get-text-property 0 'match-part cand)))
                         do (setq cand
                                  (propertize cand 'match-part (funcall match-part-fn cand)))
                         for dup = (gethash cand hash)
                         when (and (or (and allow-dups dup (= dup iter))
                                       (null dup))
                                   (or
                                    ;; Always collect when cand is matched
                                    ;; by searcher funcs and match-part attr
                                    ;; is not present.
                                    (and (not match-part-fn)
                                         (not (consp pos-lst)))
                                    ;; If match-part attr is present, or if SEARCHER fn
                                    ;; returns a cons cell, collect PATTERN only if it
                                    ;; match the part of CAND specified by
                                    ;; the match-part func.
                                    (helm-search-match-part cand pattern)))
                         do (progn
                              (puthash cand iter hash)
                              (helm--maybe-process-filter-one-by-one-candidate cand source)
                              (cl-incf count))
                         and collect cand))))))

(defun helm-search-match-part (candidate pattern)
  "Match PATTERN only on match-part property value of CANDIDATE.

Because `helm-search-match-part' may be called even if
unspecified in source (negation or fuzzy), the part to match
falls back to the whole candidate even if match-part hasn't been
computed by match-part-fn and stored in the match-part property."
  (let ((part (or (get-text-property 0 'match-part candidate)
                  candidate))
        (fuzzy-regexp (cadr (gethash 'helm-pattern helm--fuzzy-regexp-cache)))
        (matchfn (if helm-migemo-mode
                     'helm-mm-migemo-string-match 'string-match)))
    (if (string-match " " pattern)
        (cl-loop for i in (helm-mm-split-pattern pattern) always
                 (if (string-match "\\`!" i)
                     (not (funcall matchfn (substring i 1) part))
                   (funcall matchfn i part)))
      (if (string-match "\\`!" pattern)
          (if helm--in-fuzzy
              ;; Fuzzy regexp have already been
              ;; computed with substring 1.
              (not (string-match fuzzy-regexp part))
            (not (funcall matchfn (substring pattern 1) part)))
        (funcall matchfn (if helm--in-fuzzy fuzzy-regexp pattern) part)))))

(defun helm-initial-candidates-from-candidate-buffer (get-line-fn limit)
  (delq nil (cl-loop for i from 1 to limit
                     until (eobp)
                     collect (funcall get-line-fn
                                      (point-at-bol) (point-at-eol))
                     do (forward-line 1))))

(defun helm--search-from-candidate-buffer-1 (search-fn)
  ;; We are adding a newline at bob and at eol
  ;; and removing these newlines afterward.
  ;; This is a bad hack that should be removed.
  ;; To avoid matching the empty line at first line
  ;; when searching with e.g occur and "^$" just
  ;; forward-line before searching (See >>>[1] above).
  (goto-char (point-min))
  (insert "\n")
  (goto-char (point-max))
  (insert "\n")
  (unwind-protect
      (funcall search-fn)
    (goto-char (point-min))
    (delete-char 1)
    (goto-char (1- (point-max)))
    (delete-char 1)
    (set-buffer-modified-p nil)))

(defun helm-candidate-buffer (&optional buffer-spec)
  "Register and return a buffer storing candidates of current source.

This is used to initialize a buffer for storing candidates for a
candidates-in-buffer source, candidates will be searched in this
buffer and displayed in `helm-buffer'.  This should be used only
in init functions, don't relay on this in other places unless you
know what you are doing.

This function is still in public API only for backward
compatibility, you should use instead
`helm-init-candidates-in-buffer' for initializing your sources.

Internally, this function is called without argument and returns
the buffer corresponding to current source i.e.
`helm--source-name' which is available in only some places.

Acceptable values of BUFFER-SPEC:

- global (a symbol)
  Create a new global candidates buffer,
  named \" *helm candidates:SOURCE*\".
  This is used by `helm-init-candidates-in-buffer' and it is
  the most common usage of BUFFER-SPEC.
  The buffer will be killed and recreated at each new
  helm-session.

- local (a symbol)
  Create a new local candidates buffer,
  named \" *helm candidates:SOURCE*HELM-CURRENT-BUFFER\".
  You may want to use this when you want to have a different
  buffer each time source is used from a different
  `helm-current-buffer'.
  The buffer is erased and refilled at each new session but not
  killed. You probably don't want to use this value for
  BUFFER-SPEC.

- nil (omit)
  Only return the candidates buffer of current source if found.

- A buffer
  Register a buffer as a candidates buffer.
  The buffer needs to exists, it is not created.
  This allow you to use the buffer as a cache, it is faster
  because the buffer is already drawn, but be careful when using
  this as you may mangle your buffer depending on what you write
  in your init(s) function, IOW don't modify the contents of the
  buffer in init(s) function but in a transformer.
  The buffer is not erased nor deleted.
  Generally it is safer to use a copy of buffer inserted
  in a global or local buffer.

If for some reasons a global buffer and a local buffer exist and
are belonging to the same source, the local buffer takes
precedence on the global one and is used instead.

When forcing update only the global and local buffers are killed
before running again the init function."
  (let ((global-bname (format " *helm candidates:%s*"
                              helm--source-name))
        (local-bname (format " *helm candidates:%s*%s"
                             helm--source-name
                             (buffer-name helm-current-buffer))))
    (when buffer-spec
      ;; Register buffer in `helm--candidate-buffer-alist'.
      ;; This is used only to retrieve buffer associated to current source
      ;; when using named buffer as value of BUFFER-SPEC.
      (setq helm--candidate-buffer-alist
            (cons (cons helm--source-name buffer-spec)
                  (delete (assoc helm--source-name
                                 helm--candidate-buffer-alist)
                          helm--candidate-buffer-alist)))
      ;; When using global or local as value of CREATE-OR-BUFFER
      ;; create the buffer global-bname or local-bname, otherwise
      ;; reuse the named buffer.
      (unless (bufferp buffer-spec)
        ;; Global buffers are killed and recreated.
        (and (eq buffer-spec 'global)
             (buffer-live-p (get-buffer global-bname))
             (kill-buffer global-bname))
        ;; Create global or local buffer.
        ;; Local buffer, once created are reused and a new one
        ;; is created when `helm-current-buffer' change across sessions.
        (with-current-buffer (get-buffer-create
                              (cl-ecase buffer-spec
                                (global global-bname)
                                (local  local-bname)))
          ;; We need a buffer not read-only to perhaps insert later
          ;; text coming from read-only buffers (issue #1176).
          (set (make-local-variable 'buffer-read-only) nil)
          ;; Undo is automatically disabled in buffer names starting
          ;; with a space, so no need to disable it.
          (erase-buffer)
          (font-lock-mode -1))))
    ;; Finally return the candidates buffer.
    (helm-acond ((get-buffer local-bname))
                ((get-buffer global-bname))
                ((assoc-default helm--source-name helm--candidate-buffer-alist)
                 (and (or (stringp it) (bufferp it))
                      (buffer-live-p (get-buffer it))
                      it)))))

(defun helm-init-candidates-in-buffer (buffer-spec data)
  "Register BUFFER-SPEC with DATA for a helm candidates-in-buffer session.

Arg BUFFER-SPEC can be a `buffer-name' (stringp), a buffer-spec
object \(bufferp), or a symbol, either 'local or 'global which is
passed to `helm-candidate-buffer'.
The most common usage of BUFFER-SPEC is 'global.

Arg DATA can be either a list or a plain string.
Returns the resulting buffer.

Use this in your init function to register a buffer for a
`helm-source-in-buffer' session and feed it with DATA.  You
probably don't want to bother with this and use the :data slot
when initializing a source with `helm-source-in-buffer' class."
  (declare (indent 1))
  (let ((caching (and (or (stringp buffer-spec)
                          (bufferp buffer-spec))
                      (buffer-live-p (get-buffer buffer-spec))))
        (buf (helm-candidate-buffer
              (if (or (stringp buffer-spec)
                      (bufferp buffer-spec))
                  (get-buffer-create buffer-spec)
                buffer-spec)))) ; a symbol 'global or 'local.
    (unless caching
      (with-current-buffer buf
        (erase-buffer)
        (cond ((listp data)
               (insert (mapconcat (lambda (i)
                                    (cond ((symbolp i) (symbol-name i))
                                          ((numberp i) (number-to-string i))
                                          (t i)))
                                  data "\n")))
              ((stringp data) (insert data))))
      buf)))


;;; Resplit helm window
;;
;;
(defun helm-toggle-resplit-window ()
  "Toggle resplit helm window, vertically or horizontally."
  (interactive)
  (with-helm-alive-p
    (if (and (= (length (window-list nil 1)) 2)
             (not (window-dedicated-p
                   (get-buffer-window helm-current-buffer))))
        (progn
          (when helm-prevent-escaping-from-minibuffer
            (helm-prevent-switching-other-window :enabled nil))
          (unwind-protect
              (with-helm-window
                (cond ((or helm-full-frame (one-window-p t))
                       (user-error "Attempt to resplit a single window"))
                      ((helm-action-window)
                       (user-error "Can't resplit while selecting actions"))
                      (t
                       (let ((before-height (window-height)))
                         (delete-window)
                         (set-window-buffer
                          (select-window
                           (if (= (window-height) before-height) ; initial split was horizontal.
                               ;; Split window vertically with `helm-buffer' placed
                               ;; on the good side according to actual value of
                               ;; `helm-split-window-default-side'.
                               (prog1
                                   (cond ((or (eq helm-split-window-default-side 'above)
                                              (eq helm-split-window-default-side 'left))
                                          (split-window
                                           (selected-window) nil 'above))
                                         (t (split-window-vertically)))
                                 (setq helm-split-window-state 'vertical))
                             ;; Split window vertically, same comment as above.
                             (setq helm-split-window-state 'horizontal)
                             (cond ((or (eq helm-split-window-default-side 'left)
                                        (eq helm-split-window-default-side 'above))
                                    (split-window (selected-window) nil 'left))
                                   (t (split-window-horizontally)))))
                          helm-buffer))))
                (setq helm--window-side-state (helm--get-window-side-state)))
            (when helm-prevent-escaping-from-minibuffer
              (helm-prevent-switching-other-window :enabled t))))
      (error "current window configuration not suitable for splitting"))))
(put 'helm-toggle-resplit-window 'helm-only t)

;; Utility: Resize helm window.
(defun helm-enlarge-window-1 (n)
  "Enlarge or narrow helm window.
If N is positive enlarge, if negative narrow."
  (unless helm-full-frame
    (let ((horizontal-p (eq helm-split-window-state 'horizontal)))
      (with-helm-window
        (enlarge-window n horizontal-p)))))

(defun helm-narrow-window ()
  "Narrow helm window."
  (interactive)
  (with-helm-alive-p
    (helm-enlarge-window-1 -1)))
(put 'helm-narrow-window 'helm-only t)

(defun helm-enlarge-window ()
  "Enlarge helm window."
  (interactive)
  (with-helm-alive-p
    (helm-enlarge-window-1 1)))
(put 'helm-enlarge-window 'helm-only t)

(defun helm-toggle-full-frame (&optional arg)
  "Toggle `helm-buffer' full-frame view."
  (interactive "p")
  (cl-assert (null (helm-action-window))
             nil "Unable to toggle full frame from action window")
  (when arg ; Called interactively
    (cl-assert (null helm--buffer-in-new-frame-p)
               nil "Can't toggle full frame when using helm own frame"))
  (if (or helm-onewindow-p
          (buffer-local-value 'helm-full-frame (get-buffer helm-buffer)))
      (with-helm-window
        (setq-local helm-full-frame nil)
        (setq helm-onewindow-p nil)
        (let ((split-window-preferred-function
               helm-split-window-preferred-function))
          (switch-to-buffer helm-current-buffer)
          (helm-display-buffer helm-buffer)
          (select-window (minibuffer-window))))
    (with-helm-window
      (delete-other-windows)
      (setq-local helm-full-frame t)
      (setq helm-onewindow-p t))))
(put 'helm-toggle-full-frame 'helm-only t)

(defun helm-swap-windows ()
  "Swap window holding `helm-buffer' with other window."
  (interactive)
  (with-helm-alive-p
    (if (= (length (window-list nil 1)) 2)
        (cond ((and helm-full-frame (one-window-p t))
               (user-error "Can't swap windows in a single window"))
              ((helm-action-window)
               (user-error "Can't resplit while selecting actions"))
              (t
               (let* ((w1          (helm-window))
                      (split-state (eq helm-split-window-state 'horizontal))
                      (w1size      (window-total-size w1 split-state))
                      (b1          (window-buffer w1)) ; helm-buffer
                      (s1          (window-start w1))
                      (cur-frame   (window-frame w1))
                      (w2          (with-selected-window (helm-window)
                                     ;; Don't try to display helm-buffer
                                     ;; in a dedicated window.
                                     (get-window-with-predicate
                                      (lambda (w) (not (window-dedicated-p w)))
                                      1 cur-frame)))
                      (w2size      (window-total-size w2 split-state))
                      (b2          (window-buffer w2)) ; probably helm-current-buffer
                      (s2          (window-start w2))
                      resize)
                 (with-selected-frame (window-frame w1)
                   (helm-replace-buffer-in-window w1 b1 b2)
                   (helm-replace-buffer-in-window w2 b2 b1)
                   (setq resize
                         (cond ( ;; helm-window is smaller than other window.
                                (< w1size w2size)
                                (- (- (max w2size w1size)
                                      (min w2size w1size))))
                               ( ;; helm-window is larger than other window.
                                (> w1size w2size)
                                (- (max w2size w1size)
                                   (min w2size w1size)))
                               ( ;; windows have probably same size.
                                t nil)))
                   ;; Maybe resize the window holding helm-buffer.
                   (and resize (window-resize w2 resize split-state))
                   (set-window-start w1 s2 t)
                   (set-window-start w2 s1 t))
                 (setq helm--window-side-state (helm--get-window-side-state)))))
      (error "current window configuration not suitable for splitting"))))
(put 'helm-swap-windows 'helm-only t)

(defun helm--get-window-side-state ()
  "Return the position of `helm-window' from `helm-current-buffer'.
Possible values are 'left 'right 'below or 'above."
  (let ((side-list '(left right below above)))
    (cl-loop for side in side-list
             thereis (and (equal (helm-window)
                                 (window-in-direction
                                  side (get-buffer-window helm-current-buffer t)
                                  t))
                          side))))

(defun helm-replace-buffer-in-window (window buffer1 buffer2)
  "Replace BUFFER1 by BUFFER2 in WINDOW registering BUFFER1."
  (when (get-buffer-window buffer1)
    (unrecord-window-buffer window buffer1)
    (set-window-buffer window buffer2)))

;; Utility: select another action by key
(defun helm-select-nth-action (n)
  "Select the N nth action for the currently selected candidate."
  (let ((src (helm-get-current-source)))
    (setq helm-saved-selection (helm-get-selection nil nil src))
    (unless helm-saved-selection
      (error "Nothing is selected"))
    (setq helm-saved-action
          (helm-get-nth-action
           n
           (if (get-buffer-window helm-action-buffer 'visible)
               (assoc-default 'candidates src)
             (helm-get-actions-from-current-source src))))
    (helm-maybe-exit-minibuffer)))

(defun helm-get-nth-action (n action)
  (cond ((and (zerop n) (functionp action))
         action)
        ((listp action)
         (or (cdr (elt action n))
             (error "No such action")))
        ((and (functionp action) (< 0 n))
         (error "Sole action"))
        (t
         (error "Error in `helm-select-nth-action'"))))

(defun helm-execute-selection-action-at-nth (linum)
  "Execute default action on candidate at LINUM lines from selection."
  (let ((prefarg current-prefix-arg))
    (if (>= linum 0)
        (helm-next-line linum)
      (helm-previous-line (lognot (1- linum))))
    (setq current-prefix-arg prefarg)
    (helm-exit-minibuffer)))

;;; Persistent Action
;;
(defun helm-initialize-persistent-action ()
  (set (make-local-variable 'helm-persistent-action-display-window) nil))

(cl-defun helm-execute-persistent-action (&optional attr split)
  "Perform the associated action ATTR without quitting helm.

Arg ATTR default will be `persistent-action' or
`persistent-action-if' if unspecified depending on what's found
in source, but it can be anything else.
In this case you have to add this new attribute to your source.
See `persistent-action' and `persistent-action-if' slot
documentation in `helm-source'.

When `helm-full-frame' is non-nil, and `helm-buffer' is displayed
in only one window, the helm window is split to display
`helm-select-persistent-action-window' in other window to
maintain visibility.  The argument SPLIT can be used to force
splitting inconditionally, it is unused actually."
  (interactive)
  (with-helm-alive-p
    (let ((source (helm-get-current-source)))
      (unless attr
        (setq attr (or (car (assq 'persistent-action source))
                       (car (assq 'persistent-action-if source)))))
      (helm-log "executing persistent-action")
      (let* ((selection (and source (helm-get-selection nil nil source)))
             (attr-val (if (eq attr 'persistent-action-if)
                           (funcall (assoc-default attr source) selection)
                         (assoc-default attr source)))
             ;; If attr value is a cons, use its car as persistent function
             ;; and its car to decide if helm window should be splitted.
             (fn       (if (and (consp attr-val)
                                ;; maybe a lambda.
                                (not (functionp attr-val)))
                           (car attr-val) attr-val))
             (no-split (and (consp attr-val)
                            (not (functionp attr-val))
                            (cdr attr-val)))
             (cursor-in-echo-area t)
             mode-line-in-non-selected-windows)
        (progn
          (when (and helm-onewindow-p (null no-split)
                     (null helm--buffer-in-new-frame-p))
            (helm-toggle-full-frame))
          (when (eq fn 'ignore)
            (cl-return-from helm-execute-persistent-action nil))
          (when source
            (with-helm-window
              (save-selected-window
                (if no-split
                    (helm-select-persistent-action-window :split 'never)
                  (helm-select-persistent-action-window
                   :split (or split helm-onewindow-p)))
                (helm-log "current-buffer = %S" (current-buffer))
                (let ((helm-in-persistent-action t)
                      (same-window-regexps '("."))
                      display-buffer-function pop-up-windows pop-up-frames
                      special-display-regexps special-display-buffer-names)
                  (helm-execute-selection-action-1
                   selection (or fn (helm-get-actions-from-current-source source)) t)
                  (unless (helm-action-window)
                    (helm-log-run-hook 'helm-after-persistent-action-hook)))
                ;; A typical case is when a persistent action delete
                ;; the buffer already displayed in
                ;; `helm-persistent-action-display-window' and `helm-full-frame'
                ;; is enabled, we end up with the `helm-buffer'
                ;; displayed in two windows.
                (when (and helm-onewindow-p
                           (> (length (window-list)) 1)
                           (equal (buffer-name
                                   (window-buffer
                                    helm-persistent-action-display-window))
                                  (helm-buffer-get)))
                  (delete-other-windows))))))))))
(put 'helm-execute-persistent-action 'helm-only t)

(cl-defun helm-persistent-action-display-window (&key split)
  "Return the window that will be used for persistent action.
If SPLIT is t window is split in persistent action, if it has the
special symbol `never' don't split, if it is nil normally don't
split but this may happen in case of dedicated-windows or
unsuitable window to display persistent action buffer."
  (with-helm-window
    (let (prev-win cur-win)
      (setq helm-persistent-action-display-window
            (cond ((and (window-live-p helm-persistent-action-display-window)
                        (not (member helm-persistent-action-display-window
                                     (get-buffer-window-list helm-buffer))))
                   helm-persistent-action-display-window)
                  ((and helm--buffer-in-new-frame-p helm-initial-frame)
                   (with-selected-frame helm-initial-frame (selected-window)))
                  ((and split (not (eq split 'never))) (split-window))
                  ;; Fix Issue #2050 with dedicated window.
                  ((and (window-dedicated-p
                         (setq prev-win (previous-window (selected-window) 1)))
                        (not (eq split 'never)))
                   (with-helm-after-update-hook
                     (and (window-live-p helm-persistent-action-display-window)
                          (delete-window helm-persistent-action-display-window)))
                   ;; If next-window is usable use it, otherwise split
                   ;; the helm window.
                   (let ((nw (next-window (selected-window) 1)))
                     (if (eql nw prev-win) (split-window) nw)))
                  ((window-dedicated-p
                    (setq cur-win (get-buffer-window helm-current-buffer)))
                   (previous-window (selected-window) 1))
                  (cur-win)
                  (t prev-win))))))

(cl-defun helm-select-persistent-action-window (&key split)
  "Select the window that will be used for persistent action.
See `helm-persistent-action-display-window' for how to use SPLIT."
  (select-window (get-buffer-window (helm-buffer-get)))
  (prog1
      (select-window
       (setq minibuffer-scroll-window
             (helm-persistent-action-display-window :split split)))
    (helm-log "Selected window is %S" minibuffer-scroll-window)))

;;; Scrolling - recentering
;;
;;
(defun helm-other-window-base (command &optional arg)
  (let ((minibuffer-scroll-window
         (helm-persistent-action-display-window)))
    (funcall command (or arg helm-scroll-amount))))

(defun helm-scroll-other-window (&optional arg)
  "Scroll other window upward ARG many lines.
When arg is not provided scroll `helm-scroll-amount' lines.
See `scroll-other-window'."
  (interactive "P")
  (with-helm-alive-p (helm-other-window-base 'scroll-other-window arg)))
(put 'helm-scroll-other-window 'helm-only t)

(defun helm-scroll-other-window-down (&optional arg)
  "Scroll other window downward ARG many lines.
When arg is not provided scroll `helm-scroll-amount' lines.
See `scroll-other-window-down'."
  (interactive "P")
  (with-helm-alive-p (helm-other-window-base 'scroll-other-window-down arg)))
(put 'helm-scroll-other-window-down 'helm-only t)

(defun helm-recenter-top-bottom-other-window (&optional arg)
  "Run `recenter-top-bottom' in other window.
Meaning of prefix ARG is the same as in `recenter-top-bottom'."
  (interactive "P")
  (with-helm-alive-p
    (with-helm-window
      (with-selected-window (helm-persistent-action-display-window)
        (recenter-top-bottom arg)))))
(put 'helm-recenter-top-bottom-other-window 'helm-only t)

(defun helm-reposition-window-other-window (&optional arg)
  "Run `reposition-window' in other window.
Meaning of prefix ARG is the same as in `reposition-window'."
  (interactive "P")
  (with-helm-alive-p
    (with-helm-window
      (with-selected-window (helm-persistent-action-display-window)
        (reposition-window arg)))))
(put 'helm-reposition-window-other-window 'helm-only t)


;; Utility: Visible Mark

(defun helm-clear-visible-mark ()
  (with-current-buffer (helm-buffer-get)
    (mapc 'delete-overlay helm-visible-mark-overlays)
    (set (make-local-variable 'helm-visible-mark-overlays) nil)))

(defun helm-this-visible-mark ()
  (cl-loop for o in (overlays-at (point))
           when (overlay-get o 'visible-mark)
           return o))

(defun helm-delete-visible-mark (overlay)
  (let ((src (helm-get-current-source)))
    (setq helm-marked-candidates
          (remove
           (cons src (helm-get-selection nil nil src))
           helm-marked-candidates))
    (delete-overlay overlay)
    (setq helm-visible-mark-overlays
          (delq overlay helm-visible-mark-overlays))))

(defun helm-make-visible-mark (&optional src selection)
  (let* ((source (or src  (helm-get-current-source)))
         (sel    (or selection (helm-get-selection
                                nil (helm-attr 'marked-with-props source)
                                source)))
         (selection-end (if (helm-pos-multiline-p)
                            ;; Stays within source
                            (or (helm-get-next-candidate-separator-pos)
                                (helm-get-next-header-pos)
                                (point-max))
                          ;; Not multiline
                          (1+ (point-at-eol))))
         (o (make-overlay (point-at-bol) selection-end)))
    (overlay-put o 'priority 0)
    (overlay-put o 'face   'helm-visible-mark)
    (overlay-put o 'source (assoc-default 'name source))
    (overlay-put o 'string (buffer-substring (overlay-start o) (overlay-end o)))
    (overlay-put o 'real sel)
    (overlay-put o 'visible-mark t)
    (cl-pushnew o helm-visible-mark-overlays)
    (push (cons source sel) helm-marked-candidates)))

(defun helm-toggle-visible-mark (arg)
  "Toggle Helm visible mark at point ARG times.
If ARG is negative toggle backward."
  (interactive "p")
  (with-helm-alive-p
    (with-helm-window
      (let ((nomark (assq 'nomark (helm-get-current-source)))
            (next-fns (if (< arg 0)
                          '(helm-beginning-of-source-p . helm-previous-line)
                        '(helm-end-of-source-p . helm-next-line))))
        (if nomark
            (message "Marking not allowed in this source")
          (cl-loop with n = (if (< arg 0) (* arg -1) arg)
                   repeat n do
                   (progn
                     (helm-aif (helm-this-visible-mark)
                         (helm-delete-visible-mark it)
                       (helm-make-visible-mark))
                     (if (funcall (car next-fns))
                         (progn
                           (helm-display-mode-line (helm-get-current-source))
                           (cl-return nil))
                       (funcall (cdr next-fns))))))))))
(put 'helm-toggle-visible-mark 'helm-only t)

(defun helm-toggle-visible-mark-forward ()
  (interactive)
  (helm-toggle-visible-mark 1))

(defun helm-toggle-visible-mark-backward ()
  (interactive)
  (helm-toggle-visible-mark -1))

(defun helm-file-completion-source-p (&optional source)
  "Return non-nil if current source is a file completion source."
  (or helm--completing-file-name ; helm-read-file-name
      (let ((cur-source (cdr (assq 'name
                                   (or source (helm-get-current-source))))))
        (cl-loop for i in helm--file-completion-sources
                 thereis (string= cur-source i)))))

(defun helm-mark-all (&optional all)
  "Mark all visible unmarked candidates in current source.

With a prefix arg mark all visible unmarked candidates in all
sources."
  (interactive "P")
  (with-helm-alive-p
    (with-helm-window ; Using `with-helm-buffer' for some unknow reasons infloop.
      (if (null all)
          (helm-mark-all-1 t)
        (let ((pos (point)))
          (goto-char (point-min))
          (helm-awhile (helm-get-next-header-pos)
            (goto-char it)
            (forward-line 1)
            (helm-mark-current-line)
            (helm-mark-all-1))
          ;; `save-excursion' seems confused if used in addition of
          ;; the one used in `helm-mark-all-1', so save POS and back
          ;; to it when loop is finished.
          (goto-char pos)
          (helm-mark-current-line)
          (helm-display-mode-line (helm-get-current-source) t))))))
(put 'helm-mark-all 'helm-only t)

(defun helm-mark-all-1 (&optional ensure-beg-of-source)
  "Mark all visible unmarked candidates in current source.
Need to be wrapped in `with-helm-window'.
Arg ENSURE-BEG-OF-SOURCE ensure we are at beginning of source
when starting to mark candidates, if handled elsewhere before
starting it is not needed."
  (let* ((src        (helm-get-current-source))
         (follow     (if (helm-follow-mode-p src) 1 -1))
         (nomark     (assq 'nomark src))
         (src-name   (assoc-default 'name src))
         (filecomp-p (or (helm-file-completion-source-p src)
                         (string= src-name "Files from Current Directory"))))
    ;; Note that `cl-letf' prevents edebug working properly.
    (cl-letf (((symbol-function 'message) #'ignore))
      (helm-follow-mode -1)
      (unwind-protect
          (if nomark
              (user-error "Marking not allowed in this source")
            (save-excursion
              (when ensure-beg-of-source
                (goto-char (helm-get-previous-header-pos))
                (forward-line 1))
              (let* ((next-head (helm-get-next-header-pos))
                     (end       (and next-head
                                     (save-excursion
                                       (goto-char next-head)
                                       (forward-line -1)
                                       (point))))
                     (maxpoint  (or end (point-max))))
                (while (< (point) maxpoint)
                  (helm-mark-current-line)
                  (let* ((prefix (get-text-property (point-at-bol) 'display))
                         (cand   (helm-get-selection
                                  nil (helm-attr 'marked-with-props src)
                                  src))
                         (bn     (and filecomp-p (helm-basename cand))))
                    ;; Don't mark possibles directories ending with . or ..
                    ;; autosave files/links and non--existent files.
                    (unless
                        (or (helm-this-visible-mark)
                            ;; Non existing files in HFF and
                            ;; RFN. Display may be an image. See
                            ;; https://github.com/yyoncho/helm-treemacs-icons/issues/5
                            ;; and also issue #2296.
                            (equal prefix "[?]")
                            (and filecomp-p
                                 (or
                                  ;; autosave files
                                  (string-match-p "\\`[.]?#.*#?\\'" bn)
                                  ;; dot files
                                  (member bn '("." "..")))))
                      (helm-make-visible-mark src cand)))
                  (when (helm-pos-multiline-p)
                    (goto-char
                     (or (helm-get-next-candidate-separator-pos)
                         (point-max))))
                  (forward-line 1))))
            (helm-mark-current-line))
        (helm-follow-mode follow)))))

(defun helm-unmark-all ()
  "Unmark all candidates in all sources of current helm session."
  (interactive)
  (with-helm-alive-p
    (with-helm-window
      (save-excursion
        (helm-clear-visible-mark))
      (setq helm-marked-candidates nil)
      (helm-mark-current-line)
      (helm-display-mode-line (helm-get-current-source)))))
(put 'helm-unmark-all 'helm-only t)

(defun helm-toggle-all-marks (&optional all)
  "Toggle all marks.

Mark all visible candidates of current source or unmark all
candidates visible or invisible in all sources of current Helm
session.

With a prefix argument mark all candidates in all sources."
  (interactive "P")
  (with-helm-alive-p
    (let ((marked (helm-marked-candidates)))
      (if (and (>= (length marked) 1)
               (with-helm-window helm-visible-mark-overlays))
          (helm-unmark-all)
        (helm-mark-all all)))))
(put 'helm-toggle-all-marks 'helm-only t)

(defun helm--compute-marked (real source &optional wildcard)
  (let* ((coerced (helm-coerce-selection real source))
         (wilds   (and wildcard
                       (condition-case nil
                           (helm-file-expand-wildcards
                            coerced t)
                         (error nil)))))
    ;; Avoid returning a not expanded wildcard fname.
    ;; e.g assuming "/tmp" doesn't contain "*.el"
    ;; return nil when coerced is "/tmp/*.el".
    (unless (or wilds (null wildcard)
                (string-match-p helm--url-regexp coerced)
                (file-exists-p coerced)
                (and (stringp coerced)
                     (null (string-match-p "[[*?]" coerced))))
      (setq coerced nil))
    (or wilds (and coerced (list coerced)))))

(cl-defun helm-marked-candidates (&key with-wildcard all-sources)
  "Return marked candidates of current source, if any.

Otherwise return one element list consisting of the current
selection.  When key WITH-WILDCARD is specified, expand it.  When
ALL-SOURCES key value is non-nil returns marked candidates of all
sources."
  (with-current-buffer helm-buffer
    (let* ((current-src (helm-get-current-source))
           (candidates
            (cl-loop for (source . real) in (reverse helm-marked-candidates)
                     for use-wc = (and with-wildcard
                                       (string-match-p "\\*" real)
                                       (null (file-exists-p real)))
                     when (or all-sources
                              (equal (assq 'name source)
                                     (assq 'name current-src)))
                     append (helm--compute-marked real source use-wc)))
           sel)
      (unless candidates
        (setq sel (helm-get-selection
                   nil (helm-attr 'marked-with-props
                                  current-src)
                   current-src))
        (setq candidates
              (helm--compute-marked
               sel current-src
               (and with-wildcard (null (file-exists-p sel))))))
      (helm-log "Marked candidates = %S" candidates)
      candidates)))

(defun helm--remove-marked-and-update-mode-line (elm)
  (with-helm-buffer
    (setq helm-marked-candidates
          (delete (rassoc elm helm-marked-candidates)
                  helm-marked-candidates))
    (helm-display-mode-line (helm-get-current-source))))

(defun helm-current-source-name= (name)
  (save-excursion
    (goto-char (helm-get-previous-header-pos))
    (equal name (helm-current-line-contents))))

(defun helm-revive-visible-mark ()
  "Restore marked candidates when helm updates display."
  (with-current-buffer helm-buffer
    (save-excursion
      (cl-dolist (o helm-visible-mark-overlays)
        (let ((o-src-str (overlay-get o 'source))
              (o-str (overlay-get o 'string))
              beg end)
          ;; Move point to end of source header line.
          (goto-char (point-min))
          (search-forward o-src-str nil t)
          (while (and (search-forward o-str nil t)
                      (cl-loop for ov in (overlays-at (point-at-bol 0))
                               never (overlay-get ov 'visible-mark))
                      (helm-current-source-name= o-src-str))
            (setq beg (match-beginning 0)
                  end (match-end 0))
            ;; Calculate real value of candidate.
            ;; It can be nil if candidate have only a display value.
            (let ((real (get-text-property (point-at-bol 0) 'helm-realvalue)))
              (if real
                  ;; Check if real value of current candidate is the same
                  ;; than the one stored in overlay.
                  ;; This is needed when some cands have same display names.
                  ;; Using equal allow testing any type of value for real cand.
                  ;; Issue (#706).
                  (and (equal (overlay-get o 'real) real)
                       (move-overlay o beg end))
                (and (equal o-str (buffer-substring beg end))
                     (move-overlay o beg end))))))))))
(add-hook 'helm-after-update-hook 'helm-revive-visible-mark)

(defun helm-next-point-in-list (curpos points &optional prev)
  (cond
   ;; rule out special cases.
   ((null points) curpos)
   ((and prev (<= curpos (car points)))
    (nth (1- (length points)) points))
   ((< (car (last points)) curpos)
    (if prev (car (last points)) (nth 0 points)))
   ((and (not prev) (>= curpos (car (last points))))
    (nth 0 points))
   (t
    (nth (if prev
             (cl-loop for pt in points
                      for i from 0
                      if (<= curpos pt) return (1- i))
           (cl-loop for pt in points
                    for i from 0
                    if (< curpos pt) return i))
         points))))

(defun helm-next-visible-mark (&optional prev)
  "Move next Helm visible mark.
If PREV is non-nil move to precedent."
  (interactive)
  (with-helm-alive-p
    (with-helm-window
      (ignore-errors
        (goto-char (helm-next-point-in-list
                    (point)
                    (sort (mapcar 'overlay-start helm-visible-mark-overlays) '<)
                    prev)))
      (helm-mark-current-line))))
(put 'helm-next-visible-mark 'helm-only t)

(defun helm-prev-visible-mark ()
  "Move previous helm visible mark."
  (interactive)
  (with-helm-alive-p
    (helm-next-visible-mark t)))
(put 'helm-prev-visible-mark 'helm-only t)

;;; Utility: Selection Paste
;;
(defun helm-yank-selection (arg)
  "Set minibuffer contents to current display selection.
With a prefix arg set to real value of current selection."
  (interactive "P")
  (with-helm-alive-p
    (let ((str (format "%s" (helm-get-selection nil (not arg)))))
      (kill-new str)
      (helm-set-pattern str))))
(put 'helm-yank-selection 'helm-only t)

(defun helm-kill-selection-and-quit (arg)
  "Store display value of current selection to kill ring.
With a prefix arg use real value of current selection.
Display value is shown in `helm-buffer' and real value is used to
perform actions."
  (interactive "P")
  (with-helm-alive-p
    (helm-run-after-exit
     (lambda (sel)
       (kill-new sel)
       ;; Return nil to force `helm-mode--keyboard-quit'
       ;; in `helm-comp-read' otherwise the value "Saved to kill-ring: foo"
       ;; is used as exit value for `helm-comp-read'.
       (prog1 nil (message "Saved to kill-ring: %s" sel) (sit-for 1)))
     (format "%s" (helm-get-selection nil (not arg))))))
(put 'helm-kill-selection-and-quit 'helm-only t)

(defun helm-copy-to-buffer ()
  "Copy selection or marked candidates to `helm-current-buffer'.
Note that the real values of candidates are copied and not the
display values."
  (interactive)
  (with-helm-alive-p
    (helm-run-after-exit
     (lambda (cands)
       (with-helm-current-buffer
         (insert (mapconcat (lambda (c)
                              (format "%s" c))
                            cands "\n"))))
     (helm-marked-candidates))))
(put 'helm-copy-to-buffer 'helm-only t)


;;; Follow-mode: Automatic execution of persistent-action
;;
;;
(defvar helm-follow-input-idle-delay nil
  "`helm-follow-mode' will execute its persistent action after this delay.
Note that if the `follow-delay' attr is present in source, it
will take precedence over this.")

(defun helm-follow-mode (&optional arg)
  "Execute persistent action every time the cursor is moved.

This mode is source local, i.e. It applies on current source only.
\\<helm-map>
This mode can be enabled or disabled interactively at anytime during
a helm session with \\[helm-follow-mode].

When enabling interactively `helm-follow-mode' in a source, you
can keep it enabled for next Emacs sessions by setting
`helm-follow-mode-persistent' to a non-nil value.

When `helm-follow-mode' is called with a prefix arg and
`helm-follow-mode-persistent' is non-nil `helm-follow-mode' will
be persistent only for this Emacs session, but not for the next
Emacs sessions, i.e. the current source will not be saved to
`helm-source-names-using-follow'.

A prefix arg with `helm-follow-mode' already enabled will have no
effect.

Note that you can use instead of this mode the commands
`helm-follow-action-forward' and `helm-follow-action-backward' at
anytime in all Helm sessions.

They are bound by default to \\[helm-follow-action-forward] and
\\[helm-follow-action-backward]."
  (interactive (list (helm-aif (and current-prefix-arg
                                    (prefix-numeric-value current-prefix-arg))
                         (unless (helm-follow-mode-p) it))))
  (with-helm-alive-p
    (with-current-buffer helm-buffer
      (let* ((src      (helm-get-current-source))
             (name     (assoc-default 'name src))
             (fol-attr (assq 'follow src))
             (enabled  (or (helm-follow-mode-p src)
                           (and helm-follow-mode-persistent
                                (member (assoc-default 'name src)
                                        helm-source-names-using-follow)))))
        (if src
            (progn
              (if (eq (cdr fol-attr) 'never)
                  (message "helm-follow-mode not allowed in this source")
                ;; Make follow attr persistent for this emacs session.
                (helm-follow-mode-set-source
                 (if (or enabled (and (numberp arg) (< arg 0))) -1 1)
                 src)
                ;; When arg is nil assume the call is interactive.
                ;; However if user call helm-follow-mode with a prefix arg,
                ;; the call will be considered non--interactive and
                ;; src-name will NOT be saved to helm-source-names-using-follow.
                ;; When called from lisp (non--interactive) src-name
                ;; will never be saved.
                (when (and helm-follow-mode-persistent (null arg))
                  (if (null enabled)
                      (unless (member name helm-source-names-using-follow)
                        (push name helm-source-names-using-follow)
                        (customize-save-variable 'helm-source-names-using-follow
                                                 helm-source-names-using-follow))
                    (when (member name helm-source-names-using-follow)
                      (setq helm-source-names-using-follow
                            (delete name helm-source-names-using-follow))
                      (customize-save-variable 'helm-source-names-using-follow
                                               helm-source-names-using-follow))))
                (message "helm-follow-mode is %s"
                         (if (helm-follow-mode-p src)
                             "enabled" "disabled"))
                (helm-display-mode-line src t)))
          (message "Not enough candidates for helm-follow-mode"))))))
(put 'helm-follow-mode 'helm-only t)

(defun helm-follow-execute-persistent-action-maybe (&optional delay)
  "Execute persistent action in mode `helm-follow-mode'.

This happen after: DELAY or the 'follow-attr value of current
source or `helm-follow-input-idle-delay' or
`helm-input-idle-delay' secs."
  (let* ((src (helm-get-current-source))
         (at (or delay
                 (assoc-default 'follow-delay src)
                 helm-follow-input-idle-delay
                 (or (and helm-input-idle-delay
                          (max helm-input-idle-delay 0.01))
                     0.01))))
    (when (and (not (get-buffer-window helm-action-buffer 'visible))
               (not (helm-pos-header-line-p))
               (or (helm-follow-mode-p src)
                   (and helm-follow-mode-persistent
                        (member (assoc-default 'name src)
                                helm-source-names-using-follow)))
               (null (eq (assoc-default 'follow src) 'never))
               (helm-get-selection nil nil src))
      (helm-follow-mode-set-source 1 src)
      (run-with-idle-timer at nil (lambda ()
                                    (when helm-alive-p
                                      (helm-execute-persistent-action)))))))

(defun helm-follow-mode-p (&optional source)
  (with-helm-buffer
    (eq (helm-attr 'follow (or source (helm-get-current-source))) 1)))

(defun helm-follow-mode-set-source (value &optional source)
  (with-helm-buffer
    (helm-attrset 'follow value (or source (helm-get-current-source)))))

;;; Auto-resize mode
;;
(defun helm--autoresize-hook (&optional max-height min-height)
  (when (helm-window)
    (with-helm-window
      (fit-window-to-buffer nil
                            (/ (* (frame-height)
                                  (or max-height helm-autoresize-max-height))
                               100)
                            (/ (* (frame-height)
                                  (or min-height helm-autoresize-min-height))
                               100)))))

(define-minor-mode helm-autoresize-mode
  "Auto resize helm window when enabled.
Helm window is re-sized according to `helm-autoresize-max-height'
and `helm-autoresize-min-height'.  Note that when this mode is
enabled, Helm behaves as if `helm-always-two-windows' is enabled.

See `fit-window-to-buffer' for more infos."
  :group 'helm
  :global t
  (if helm-autoresize-mode
      (progn (add-hook 'helm-after-update-hook 'helm--autoresize-hook)
             (add-hook 'helm-window-configuration-hook 'helm--autoresize-hook))
    (remove-hook 'helm-after-update-hook 'helm--autoresize-hook)
    (remove-hook 'helm-window-configuration-hook 'helm--autoresize-hook)))

(defun helm-help ()
  "Generate Helm's help according to `help-message' attribute.

If `helm-buffer' is empty, provide completions on `helm-sources'
to choose its local documentation.
If source doesn't have any `help-message' attribute, a generic
message explaining this is added instead.
The global `helm-help-message' is always added after this local
help."
  (interactive)
  (require 'helm-mode) ; for helm-comp-read.
  (with-helm-alive-p
    (let ((source (or (helm-get-current-source)
                      (helm-comp-read
                       "Help for: "
                       (cl-loop for src in (with-helm-buffer helm-sources)
                                collect `(,(assoc-default 'name src) .
                                          ,src))
                       :allow-nest t
                       :exec-when-only-one t))))
      (save-selected-window
        (helm-help-internal
         helm-help-buffer-name
         (lambda ()
           (helm-aif (assoc-default 'help-message source)
               (insert (substitute-command-keys
                        (helm-interpret-value it)))
             (insert "* No specific help for this source available."))
           (insert "\n\n"
                   (substitute-command-keys
                    (helm-interpret-value helm-help-message)))))))))
(put 'helm-help 'helm-only t)

(defun helm-toggle-truncate-line ()
  "Toggle `truncate-lines' value in `helm-buffer'"
  (interactive)
  (with-helm-alive-p
    (with-helm-buffer
      (setq truncate-lines (not truncate-lines))
      (when (helm-get-previous-header-pos)
        (helm-update (regexp-quote (helm-get-selection nil t)))))))
(put 'helm-toggle-truncate-line 'helm-only t)


(provide 'helm)

;; Local Variables:
;; byte-compile-warnings: (not obsolete)
;; coding: utf-8
;; indent-tabs-mode: nil
;; End:

;;; helm.el ends here