[go: up one dir, main page]

File: command_mode.c

package info (click to toggle)
cmus 2.10.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,040 kB
  • sloc: ansic: 38,844; sh: 1,578; makefile: 257; python: 157
file content (3165 lines) | stat: -rw-r--r-- 67,143 bytes parent folder | download
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
/*
 * Copyright 2008-2013 Various Authors
 * Copyright 2004-2005 Timo Hirvonen
 *
 * 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 2 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/>.
 */

#include "command_mode.h"
#include "search_mode.h"
#include "cmdline.h"
#include "options.h"
#include "ui_curses.h"
#include "history.h"
#include "tabexp.h"
#include "tabexp_file.h"
#include "browser.h"
#include "filters.h"
#include "player.h"
#include "output.h"
#include "editable.h"
#include "lib.h"
#include "pl.h"
#include "play_queue.h"
#include "cmus.h"
#include "worker.h"
#include "keys.h"
#include "xmalloc.h"
#include "xstrjoin.h"
#include "misc.h"
#include "path.h"
#include "spawn.h"
#include "utils.h"
#include "list.h"
#include "debug.h"
#include "load_dir.h"
#include "help.h"
#include "op.h"
#include "mpris.h"
#include "job.h"

#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>

static struct history cmd_history;
static char *cmd_history_filename;
static char *history_search_text = NULL;
static int arg_expand_cmd = -1;
static int mute_vol_l = 0, mute_vol_r = 0;

/* view {{{ */

void view_clear(int view)
{
	switch (view) {
	case TREE_VIEW:
	case SORTED_VIEW:
		worker_remove_jobs_by_type(JOB_TYPE_LIB);
		editable_clear(&lib_editable);

		/* FIXME: make this optional? */
		lib_clear_store();
		break;
	case PLAYLIST_VIEW:
		pl_clear();
		break;
	case QUEUE_VIEW:
		worker_remove_jobs_by_type(JOB_TYPE_QUEUE);
		editable_clear(&pq_editable);
		break;
	default:
		info_msg(":clear only works in views 1-4");
	}
}

void view_add(int view, char *arg, int prepend)
{
	char *tmp, *name;
	enum file_type ft;

	tmp = expand_filename(arg);
	ft = cmus_detect_ft(tmp, &name);
	if (ft == FILE_TYPE_INVALID) {
		error_msg("adding '%s': %s", tmp, strerror(errno));
		free(tmp);
		return;
	}
	free(tmp);

	switch (view) {
	case TREE_VIEW:
	case SORTED_VIEW:
		cmus_add(lib_add_track, name, ft, JOB_TYPE_LIB, 0, NULL);
		break;
	case PLAYLIST_VIEW:
		pl_add_file_to_marked_pl(name);
		break;
	case QUEUE_VIEW:
		if (prepend) {
			cmus_add(play_queue_prepend, name, ft, JOB_TYPE_QUEUE,
					0, NULL);
		} else {
			cmus_add(play_queue_append, name, ft, JOB_TYPE_QUEUE, 0,
					NULL);
		}
		break;
	default:
		info_msg(":add only works in views 1-4");
	}
	free(name);
}

static char *view_load_prepare(char *arg)
{
	char *name, *tmp = expand_filename(arg);
	enum file_type ft = cmus_detect_ft(tmp, &name);
	if (ft == FILE_TYPE_INVALID) {
		error_msg("loading '%s': %s", tmp, strerror(errno));
		free(tmp);
		return NULL;
	}
	free(tmp);

	if (ft == FILE_TYPE_FILE)
		ft = FILE_TYPE_PL;
	if (ft != FILE_TYPE_PL) {
		error_msg("loading '%s': not a playlist file", name);
		free(name);
		return NULL;
	}
	return name;
}

void view_load(int view, char *arg)
{
	char *name = view_load_prepare(arg);
	if (!name)
		return;

	switch (view) {
	case TREE_VIEW:
	case SORTED_VIEW:
		worker_remove_jobs_by_type(JOB_TYPE_LIB);
		editable_clear(&lib_editable);
		cmus_add(lib_add_track, name, FILE_TYPE_PL, JOB_TYPE_LIB, 0,
				NULL);
		free(lib_filename);
		lib_filename = name;
		break;
	default:
		info_msg(":load only works in views 1-2");
		free(name);
	}
}

static void do_save(for_each_ti_cb for_each_ti, const char *arg, char **filenamep,
		save_ti_cb save_ti)
{
	char *filename = *filenamep;

	if (arg) {
		if (strcmp(arg, "-") == 0) {
			filename = (char *) arg;
		} else {
			free(filename);
			filename = xstrdup(arg);
			*filenamep = filename;
		}
	} else if (!filename) {
		error_msg("need a file as argument, no default stored yet");
		return;
	}

	if (save_ti(for_each_ti, filename, NULL) == -1)
		error_msg("saving '%s': %s", filename, strerror(errno));
}

void view_save(int view, char *arg, int to_stdout, int filtered, int extended)
{
	char **dest;
	save_ti_cb     save_ti         = extended ? cmus_save_ext         : cmus_save;
	for_each_ti_cb lib_for_each_ti = filtered ? lib_for_each_filtered : lib_for_each;

	if (arg) {
		if (to_stdout) {
			arg = xstrdup(arg);
		} else {
			char *tmp = expand_filename(arg);
			arg = path_absolute(tmp);
			free(tmp);
		}
	}

	switch (view) {
	case TREE_VIEW:
	case SORTED_VIEW:
		if (worker_has_job_by_type(JOB_TYPE_LIB))
			goto worker_running;
		dest = extended ? &lib_ext_filename : &lib_filename;
		do_save(lib_for_each_ti, arg, dest, save_ti);
		break;
	case PLAYLIST_VIEW:
		if (arg)
			pl_export_selected_pl(arg);
		else
			pl_save();
		break;
	case QUEUE_VIEW:
		if (worker_has_job_by_type(JOB_TYPE_QUEUE))
			goto worker_running;
		dest = extended ? &play_queue_ext_filename : &play_queue_filename;
		do_save(play_queue_for_each, arg, dest, save_ti);
		break;
	default:
		info_msg(":save only works in views 1 - 4");
	}
	free(arg);
	return;
worker_running:
	error_msg("can't save when tracks are being added");
	free(arg);
}

/* }}} */

/* if only_last != 0, only return the last flag */
static int do_parse_flags(const char **strp, const char *flags, int only_last)
{
	const char *str = *strp;
	int flag = 0;

	if (str == NULL)
		return flag;

	while (*str && (only_last || !flag)) {
		if (*str != '-')
			break;

		// "-"
		if (str[1] == 0)
			break;

		// "--" or "-- "
		if (str[1] == '-' && (str[2] == 0 || str[2] == ' ')) {
			str += 2;
			break;
		}

		// not "-?" or "-? "
		if (str[2] && str[2] != ' ')
			break;

		flag = str[1];
		if (!strchr(flags, flag)) {
			error_msg("invalid option -%c", flag);
			return -1;
		}

		str += 2;

		while (*str == ' ')
			str++;
	}
	while (*str == ' ')
		str++;
	if (*str == 0)
		str = NULL;
	*strp = str;
	return flag;
}

static int parse_flags(const char **strp, const char *flags)
{
	return do_parse_flags(strp, flags, 1);
}

static int parse_one_flag(const char **strp, const char *flags)
{
	return do_parse_flags(strp, flags, 0);
}

/* is str == "...-", but not "...-- -" ? copied from do_parse_flags() */
static int is_stdout_filename(const char *str)
{
	if (!str)
		return 0;

	while (*str) {
		if (*str != '-')
			return 0;
		// "-"
		if (str[1] == 0)
			return 1;
		// "--" or "-- "
		if (str[1] == '-' && (str[2] == 0 || str[2] == ' '))
			return 0;
		// not "-?" or "-? "
		if (str[2] && str[2] != ' ')
			return 0;
		str += 2;
		while (*str == ' ')
			str++;
	}

	return 0;
}

static int flag_to_view(int flag)
{
	switch (flag) {
	case 'l':
	case 'L':
		return TREE_VIEW;
	case 'p':
		return PLAYLIST_VIEW;
	case 'q':
	case 'Q':
		return QUEUE_VIEW;
	default:
		return cur_view;
	}
}

struct window *current_win(void)
{
	switch (cur_view) {
	case TREE_VIEW:
		return lib_cur_win;
	case SORTED_VIEW:
		return lib_editable.shared->win;
	case PLAYLIST_VIEW:
		return pl_cursor_win();
	case QUEUE_VIEW:
		return pq_editable.shared->win;
	case BROWSER_VIEW:
		return browser_win;
	case HELP_VIEW:
		return help_win;
	case FILTERS_VIEW:
	default:
		return filters_win;
	}
}

static void cmd_add(char *arg)
{
	int flag = parse_flags((const char **)&arg, "lpqQ");

	if (flag == -1)
		return;
	if (arg == NULL) {
		error_msg("not enough arguments\n");
		return;
	}
	view_add(flag_to_view(flag), arg, flag == 'Q');
}

static void cmd_clear(char *arg)
{
	int flag = parse_flags((const char **)&arg, "lpq");

	if (flag == -1)
		return;
	if (arg) {
		error_msg("too many arguments\n");
		return;
	}
	view_clear(flag_to_view(flag));
}

static void cmd_load(char *arg)
{
	int flag = parse_flags((const char **)&arg, "lp");

	if (flag == -1)
		return;
	if (arg == NULL) {
		error_msg("not enough arguments\n");
		return;
	}
	view_load(flag_to_view(flag), arg);
}

static void cmd_save(char *arg)
{
	int to_stdout = is_stdout_filename(arg);
	int flag = 0, f, extended = 0;

	do {
		f = parse_one_flag((const char **)&arg, "eLlpq");
		if (f == 'e')
			extended = 1;
		else if (f)
			flag = f;
	} while (f > 0);

	if (flag == -1)
		return;
	view_save(flag_to_view(flag), arg, to_stdout, flag == 'L', extended);
}

static void cmd_set(char *arg)
{
	char *value = NULL;
	int i;

	for (i = 0; arg[i]; i++) {
		if (arg[i] == '=') {
			arg[i] = 0;
			value = &arg[i + 1];
			break;
		}
	}
	if (value) {
		option_set(arg, value);
		help_win->changed = 1;
		if (cur_view == TREE_VIEW) {
			lib_track_win->changed = 1;
			lib_tree_win->changed = 1;
		} else if (cur_view == PLAYLIST_VIEW) {
			pl_mark_for_redraw();
		} else {
			current_win()->changed = 1;
		}
		update_titleline();
		update_statusline();
	} else {
		struct cmus_opt *opt;
		char buf[OPTION_MAX_SIZE];

		/* support "set <option>?" */
		i--;
		if (arg[i] == '?')
			arg[i] = 0;

		opt = option_find(arg);
		if (opt) {
			opt->get(opt->data, buf, OPTION_MAX_SIZE);
			info_msg("setting: '%s=%s'", arg, buf);
		}
	}
}

static void cmd_toggle(char *arg)
{
	struct cmus_opt *opt = option_find(arg);

	if (opt == NULL)
		return;

	if (opt->toggle == NULL) {
		error_msg("%s is not toggle option", opt->name);
		return;
	}
	opt->toggle(opt->data);
	help_win->changed = 1;
	if (cur_view == TREE_VIEW) {
		lib_track_win->changed = 1;
		lib_tree_win->changed = 1;
	} else if (cur_view == PLAYLIST_VIEW) {
		pl_mark_for_redraw();
	} else {
		current_win()->changed = 1;
	}
	update_titleline();
	update_statusline();
}

static int get_number(char *str, char **end)
{
	int val = 0;

	while (*str >= '0' && *str <= '9') {
		val *= 10;
		val += *str++ - '0';
	}
	*end = str;
	return val;
}

static void cmd_seek(char *arg)
{
	int relative = 0;
	int seek = 0, sign = 1, count;

	switch (*arg) {
	case '-':
		sign = -1;
		/* fallthrough */
	case '+':
		relative = 1;
		arg++;
		break;
	}

	count = 0;
	goto inside;

	do {
		int num;
		char *end;

		if (*arg != ':')
			break;
		arg++;
inside:
		num = get_number(arg, &end);
		if (arg == end)
			break;
		arg = end;
		seek = seek * 60 + num;
	} while (++count < 3);

	seek *= sign;
	if (!count)
		goto err;

	if (count == 1) {
		switch (tolower((unsigned char)*arg)) {
		case 'h':
			seek *= 60;
			/* fallthrough */
		case 'm':
			seek *= 60;
			/* fallthrough */
		case 's':
			arg++;
			break;
		}
	}

	if (!*arg) {
		player_seek(seek, relative, 0);
		return;
	}
err:
	error_msg("expecting one argument: [+-]INTEGER[mh] or [+-]H:MM:SS");
}

static void cmd_factivate(char *arg)
{
	filters_activate_names(arg);
}

static void cmd_live_filter(char *arg)
{
	filters_set_live(arg);
}

static void cmd_filter(char *arg)
{
	filters_set_anonymous(arg);
}

static void cmd_fset(char *arg)
{
	filters_set_filter(arg);
}

static void cmd_help(char *arg)
{
	info_msg("To get started with cmus, read cmus-tutorial(7) and cmus(1) man pages");
}

static void cmd_invert(char *arg)
{
	switch (cur_view) {
	case SORTED_VIEW:
		editable_invert_marks(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_invert_marks();
		break;
	case QUEUE_VIEW:
		editable_invert_marks(&pq_editable);
		break;
	default:
		info_msg(":invert only works in views 2-4");
	}
}

static void cmd_mark(char *arg)
{
	switch (cur_view) {
	case SORTED_VIEW:
		editable_mark(&lib_editable, arg);
		break;
	case PLAYLIST_VIEW:
		pl_mark(arg);
		break;
	case QUEUE_VIEW:
		editable_mark(&pq_editable, arg);
		break;
	default:
		info_msg(":mark only works in views 2-4");
	}
}

static void cmd_unmark(char *arg)
{
	switch (cur_view) {
	case SORTED_VIEW:
		editable_unmark(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_unmark();
		break;
	case QUEUE_VIEW:
		editable_unmark(&pq_editable);
		break;
	default:
		info_msg(":unmark only works in views 2-4");
	}
}

static void cmd_update_cache(char *arg)
{
	int flag = parse_flags((const char **)&arg, "f");
	cmus_update_cache(flag == 'f');
}

static void cmd_cd(char *arg)
{
	if (arg) {
		char *dir, *absolute;

		dir = expand_filename(arg);
		absolute = path_absolute(dir);
		if (chdir(dir) == -1) {
			error_msg("could not cd to '%s': %s", dir, strerror(errno));
		} else {
			browser_chdir(absolute);
		}
		free(absolute);
		free(dir);
	} else {
		if (chdir(home_dir) == -1) {
			error_msg("could not cd to '%s': %s", home_dir, strerror(errno));
		} else {
			browser_chdir(home_dir);
		}
	}
}

static void cmd_bind(char *arg)
{
	int flag = parse_flags((const char **)&arg, "f");
	char *key, *func;

	if (flag == -1)
		return;

	if (arg == NULL)
		goto err;

	key = strchr(arg, ' ');
	if (key == NULL)
		goto err;
	*key++ = 0;
	while (*key == ' ')
		key++;

	func = strchr(key, ' ');
	if (func == NULL)
		goto err;
	*func++ = 0;
	while (*func == ' ')
		func++;
	if (*func == 0)
		goto err;

	key_bind(arg, key, func, flag == 'f');
	if (cur_view == HELP_VIEW)
		window_changed(help_win);
	return;
err:
	error_msg("expecting 3 arguments (context, key and function)\n");
}

static void cmd_unbind(char *arg)
{
	int flag = parse_flags((const char **)&arg, "f");
	char *key;

	if (flag == -1)
		return;

	if (arg == NULL)
		goto err;

	key = strchr(arg, ' ');
	if (key == NULL)
		goto err;
	*key++ = 0;
	while (*key == ' ')
		key++;
	if (*key == 0)
		goto err;

	strip_trailing_spaces(key);

	key_unbind(arg, key, flag == 'f');
	return;
err:
	error_msg("expecting 2 arguments (context and key)\n");
}

static void cmd_showbind(char *arg)
{
	char *key;

	key = strchr(arg, ' ');
	if (key == NULL)
		goto err;
	*key++ = 0;
	while (*key == ' ')
		key++;
	if (*key == 0)
		goto err;

	strip_trailing_spaces(key);

	show_binding(arg, key);
	return;
err:
	error_msg("expecting 2 arguments (context and key)\n");
}

static void cmd_quit(char *arg)
{
	int flag = parse_flags((const char **)&arg, "i");
	enum ui_query_answer answer;
	if (!worker_has_job_by_type(JOB_TYPE_ANY)) {
		if (flag != 'i' || yes_no_query("Quit cmus? [y/N]") != UI_QUERY_ANSWER_NO)
			cmus_running = 0;
	} else {
		answer = yes_no_query("Tracks are being added. Quit and truncate playlist(s)? [y/N]");
		if (answer != UI_QUERY_ANSWER_NO)
			cmus_running = 0;
	}
}

static void cmd_reshuffle(char *arg)
{
	lib_reshuffle();
	pl_reshuffle();
}

static void cmd_source(char *arg)
{
	char *filename = expand_filename(arg);

	if (source_file(filename) == -1)
		error_msg("sourcing %s: %s", filename, strerror(errno));
	free(filename);
}

static void cmd_colorscheme(char *arg)
{
	char filename[512];

	snprintf(filename, sizeof(filename), "%s/%s.theme", cmus_config_dir, arg);
	if (source_file(filename) == -1) {
		snprintf(filename, sizeof(filename), "%s/%s.theme", cmus_data_dir, arg);
		if (source_file(filename) == -1)
			error_msg("sourcing %s: %s", filename, strerror(errno));
	}
}

/*
 * \" inside double-quotes becomes "
 * \\ inside double-quotes becomes \
 */
static char *parse_quoted(const char **strp)
{
	const char *str = *strp;
	const char *start;
	char *ret, *dst;

	str++;
	start = str;
	while (1) {
		int c = *str++;

		if (c == 0)
			goto error;
		if (c == '"')
			break;
		if (c == '\\') {
			if (*str++ == 0)
				goto error;
		}
	}
	*strp = str;
	ret = xnew(char, str - start);
	str = start;
	dst = ret;
	while (1) {
		int c = *str++;

		if (c == '"')
			break;
		if (c == '\\') {
			c = *str++;
			if (c != '"' && c != '\\')
				*dst++ = '\\';
		}
		*dst++ = c;
	}
	*dst = 0;
	return ret;
error:
	error_msg("`\"' expected");
	return NULL;
}

static char *parse_escaped(const char **strp)
{
	const char *str = *strp;
	const char *start;
	char *ret, *dst;

	start = str;
	while (1) {
		int c = *str;

		if (c == 0 || c == ' ' || c == '\'' || c == '"')
			break;

		str++;
		if (c == '\\') {
			c = *str;
			if (c == 0)
				break;
			str++;
		}
	}
	*strp = str;
	ret = xnew(char, str - start + 1);
	str = start;
	dst = ret;
	while (1) {
		int c = *str;

		if (c == 0 || c == ' ' || c == '\'' || c == '"')
			break;

		str++;
		if (c == '\\') {
			c = *str;
			if (c == 0) {
				*dst++ = '\\';
				break;
			}
			str++;
		}
		*dst++ = c;
	}
	*dst = 0;
	return ret;
}

static char *parse_one(const char **strp)
{
	const char *str = *strp;
	char *ret = NULL;

	while (1) {
		char *part = NULL;
		int c = *str;

		if (!c || c == ' ')
			break;
		if (c == '"') {
			part = parse_quoted(&str);
			if (part == NULL)
				goto error;
		} else if (c == '\'') {
			/* backslashes are normal chars inside single-quotes */
			const char *end;

			str++;
			end = strchr(str, '\'');
			if (end == NULL)
				goto sq_missing;
			part = xstrndup(str, end - str);
			str = end + 1;
		} else {
			part = parse_escaped(&str);
		}

		if (ret == NULL) {
			ret = xstrdup(part);
		} else {
			char *tmp = xstrjoin(ret, part);
			free(ret);
			ret = tmp;
		}
		free(part);
	}
	*strp = str;
	return ret;
sq_missing:
	error_msg("`'' expected");
error:
	free(ret);
	return NULL;
}

char **parse_cmd(const char *cmd, int *args_idx, int *ac)
{
	char **av = NULL;
	int nr = 0;
	int alloc = 0;

	while (*cmd) {
		char *arg;

		/* there can't be spaces at start of command
		 * and there is at least one argument */
		if (cmd[0] == '{' && cmd[1] == '}' && (cmd[2] == ' ' || cmd[2] == 0)) {
			/* {} is replaced with file arguments */
			if (*args_idx != -1)
				goto only_once_please;
			*args_idx = nr;
			cmd += 2;
			goto skip_spaces;
		} else {
			arg = parse_one(&cmd);
			if (arg == NULL)
				goto error;
		}

		if (nr == alloc) {
			alloc = alloc ? alloc * 2 : 4;
			av = xrenew(char *, av, alloc + 1);
		}
		av[nr++] = arg;
skip_spaces:
		while (*cmd == ' ')
			cmd++;
	}
	av[nr] = NULL;
	*ac = nr;
	return av;
only_once_please:
	error_msg("{} can be used only once");
error:
	while (nr > 0)
		free(av[--nr]);
	free(av);
	return NULL;
}

struct track_info_selection {
	struct track_info **tis;
	int tis_alloc;
	int tis_nr;
};

static int add_ti(void *data, struct track_info *ti)
{
	struct track_info_selection *sel = data;
	if (sel->tis_nr == sel->tis_alloc) {
		sel->tis_alloc = sel->tis_alloc ? sel->tis_alloc * 2 : 8;
		sel->tis = xrenew(struct track_info *, sel->tis, sel->tis_alloc);
	}
	track_info_ref(ti);
	sel->tis[sel->tis_nr++] = ti;
	return 0;
}

static void cmd_run(char *arg)
{
	char **av, **argv;
	int ac, argc, i, run, files_idx = -1;
	struct track_info_selection sel = { .tis = NULL };

	if (cur_view > QUEUE_VIEW) {
		info_msg("Command execution is supported only in views 1-4");
		return;
	}

	av = parse_cmd(arg, &files_idx, &ac);
	if (av == NULL) {
		return;
	}

	/* collect selected files (struct track_info) */
	switch (cur_view) {
	case TREE_VIEW:
		_tree_for_each_sel(add_ti, &sel, 0);
		break;
	case SORTED_VIEW:
		_editable_for_each_sel(&lib_editable, add_ti, &sel, 0);
		break;
	case PLAYLIST_VIEW:
		_pl_for_each_sel(add_ti, &sel, 0);
		break;
	case QUEUE_VIEW:
		_editable_for_each_sel(&pq_editable, add_ti, &sel, 0);
		break;
	}

	if (sel.tis_nr == 0) {
		/* no files selected, do nothing */
		free_str_array(av);
		return;
	}
	sel.tis[sel.tis_nr] = NULL;

	/* build argv */
	argv = xnew(char *, ac + sel.tis_nr + 1);
	argc = 0;
	if (files_idx == -1) {
		/* add selected files after rest of the args */
		for (i = 0; i < ac; i++)
			argv[argc++] = av[i];
		for (i = 0; i < sel.tis_nr; i++)
			argv[argc++] = sel.tis[i]->filename;
	} else {
		for (i = 0; i < files_idx; i++)
			argv[argc++] = av[i];
		for (i = 0; i < sel.tis_nr; i++)
			argv[argc++] = sel.tis[i]->filename;
		for (i = files_idx; i < ac; i++)
			argv[argc++] = av[i];
	}
	argv[argc] = NULL;

	for (i = 0; argv[i]; i++)
		d_print("ARG: '%s'\n", argv[i]);

	run = 1;
	if (confirm_run && (sel.tis_nr > 1 || strcmp(argv[0], "rm") == 0)) {
		if (yes_no_query("Execute %s for the %d selected files? [y/N]", arg, sel.tis_nr) != UI_QUERY_ANSWER_YES) {
			info_msg("Aborted");
			run = 0;
		}
	}
	if (run) {
		int status;

		if (spawn(argv, &status, 1)) {
			error_msg("executing %s: %s", argv[0], strerror(errno));
		} else {
			if (WIFEXITED(status)) {
				int rc = WEXITSTATUS(status);

				if (rc)
					error_msg("%s returned %d", argv[0], rc);
			}
			if (WIFSIGNALED(status))
				error_msg("%s received signal %d", argv[0], WTERMSIG(status));

			switch (cur_view) {
			case TREE_VIEW:
			case SORTED_VIEW:
				/* this must be done before sel.tis are unreffed */
				free_str_array(av);
				free(argv);

				/* remove non-existed files, update tags for changed files */
				cmus_update_tis(sel.tis, sel.tis_nr, 0);

				/* we don't own sel.tis anymore! */
				return;
			}
		}
	}
	free_str_array(av);
	free(argv);
	for (i = 0; sel.tis[i]; i++)
		track_info_unref(sel.tis[i]);
	free(sel.tis);
}

static void cmd_shell(char *arg)
{
	const char * const argv[] = { "sh", "-c", arg, NULL };

	if (spawn((char **) argv, NULL, 0))
		error_msg("executing '%s': %s", arg, strerror(errno));
}

static int get_one_ti(void *data, struct track_info *ti)
{
	struct track_info **sel_ti = data;

	track_info_ref(ti);
	*sel_ti = ti;
	/* stop the for each loop, we need only the first selected track */
	return 1;
}

static void cmd_echo(char *arg)
{
	struct track_info *sel_ti;
	char *ptr = arg;

	while (1) {
		ptr = strchr(ptr, '{');
		if (ptr == NULL)
			break;
		if (ptr[1] == '}')
			break;
		ptr++;
	}

	if (ptr == NULL) {
		info_msg("%s", arg);
		return;
	}

	if (cur_view > QUEUE_VIEW) {
		info_msg("echo with {} in its arguments is supported only in views 1-4");
		return;
	}

	*ptr = 0;
	ptr += 2;

	/* get only the first selected track */
	sel_ti = NULL;

	switch (cur_view) {
	case TREE_VIEW:
		_tree_for_each_sel(get_one_ti, &sel_ti, 0);
		break;
	case SORTED_VIEW:
		_editable_for_each_sel(&lib_editable, get_one_ti, &sel_ti, 0);
		break;
	case PLAYLIST_VIEW:
		_pl_for_each_sel(get_one_ti, &sel_ti, 0);
		break;
	case QUEUE_VIEW:
		_editable_for_each_sel(&pq_editable, get_one_ti, &sel_ti, 0);
		break;
	}

	if (sel_ti == NULL)
		return;

	info_msg("%s%s%s", arg, sel_ti->filename, ptr);
	track_info_unref(sel_ti);
}

static int parse_vol_arg(const char *arg, int *value, unsigned int *flags)
{
	unsigned int f = 0;
	int ch, val = 0, digits = 0, sign = 1;

	if (*arg == '-') {
		arg++;
		f |= VF_RELATIVE;
		sign = -1;
	} else if (*arg == '+') {
		arg++;
		f |= VF_RELATIVE;
	}

	while (1) {
		ch = *arg++;
		if (ch < '0' || ch > '9')
			break;
		val *= 10;
		val += ch - '0';
		digits++;
	}
	if (digits == 0)
		goto err;

	if (ch == '%') {
		f |= VF_PERCENTAGE;
		ch = *arg;
	}
	if (ch)
		goto err;

	*value = sign * val;
	*flags = f;
	return 0;
err:
	return -1;
}

static void cmd_mute(char *arg)
{
	int l = 0, r = 0;

	if (volume_l == 0 && volume_r == 0) {
		// unmute
		l = mute_vol_l;
		r = mute_vol_r;
	} else {
		mute_vol_l = volume_l;
		mute_vol_r = volume_r;
	}

	int rc = player_set_vol(l, 0, r, 0);
	if (rc != OP_ERROR_SUCCESS) {
		char *msg = op_get_error_msg(rc, "can't change volume");
		error_msg("%s", msg);
		free(msg);
	} else {
		mpris_volume_changed();
	}
	update_statusline();
}


/*
 * :vol value [value]
 *
 * where value is [-+]?[0-9]+%?
 */
static void cmd_vol(char *arg)
{
	char **values = get_words(arg);
	unsigned int lf, rf;
	int l, r;

	if (values[1] && values[2])
		goto err;

	if (parse_vol_arg(values[0], &l, &lf))
		goto err;

	r = l;
	rf = lf;
	if (values[1] && parse_vol_arg(values[1], &r, &rf))
		goto err;

	free_str_array(values);

	int rc = player_set_vol(l, lf, r, rf);
	if (rc != OP_ERROR_SUCCESS) {
		char *msg = op_get_error_msg(rc, "can't change volume");
		error_msg("%s", msg);
		free(msg);
	} else {
		mpris_volume_changed();
	}
	update_statusline();
	return;
err:
	free_str_array(values);
	error_msg("expecting 1 or 2 arguments (total or L and R volumes [+-]INTEGER[%%])\n");
}

static void cmd_prev_view(char *arg)
{
	if (prev_view >= 0) {
		set_view(prev_view);
	}
}

static void cmd_left_view(char *arg)
{
	if (cur_view == TREE_VIEW) {
		set_view(HELP_VIEW);
	} else {
		set_view(cur_view - 1);
	}
}

static void cmd_right_view(char *arg)
{
	if (cur_view == HELP_VIEW) {
		set_view(TREE_VIEW);
	} else {
		set_view(cur_view + 1);
	}
}

static void cmd_pl_create(char *arg)
{
	pl_create(arg);
}

static void cmd_pl_export(char *arg)
{
	if (cur_view == PLAYLIST_VIEW)
		pl_export_selected_pl(arg);
	else
		info_msg(":pl-export only works in view 3");
}

static char *get_browser_add_file(void)
{
	char *sel = browser_get_sel();

	if (sel && (ends_with(sel, "/../") || ends_with(sel, "/.."))) {
		info_msg("For convenience, you can not add \"..\" directory from the browser view");
		free(sel);
		sel = NULL;
	}

	return sel;
}

static void cmd_pl_import(char *arg)
{
	char *name = NULL;

	if (arg)
		name = view_load_prepare(arg);
	else if (cur_view == BROWSER_VIEW)
		name = get_browser_add_file();
	else
		error_msg("not enough arguments");

	if (name) {
		pl_import(name);
		free(name);
	}
}

static void cmd_pl_rename(char *arg)
{
	if (cur_view == PLAYLIST_VIEW)
		pl_rename_selected_pl(arg);
	else
		info_msg(":pl-rename only works in view 3");
}

static void cmd_version(char *arg)
{
	info_msg(VERSION);
}

static void cmd_view(char *arg)
{
	int view;

	if (parse_enum(arg, 1, NR_VIEWS, view_names, &view) && (view - 1) != cur_view) {
		set_view(view - 1);
	}
}

static void cmd_push(char *arg)
{
	if (arg)
		cmdline_set_text(arg);
	enter_command_mode();
}

static void cmd_p_next(char *arg)
{
	cmus_next();
}

static void cmd_p_pause(char *arg)
{
	player_pause();
}

static void cmd_p_pause_playback(char *arg)
{
	player_pause_playback();
}

static void cmd_p_play(char *arg)
{
	if (arg) {
		char *tmp = expand_filename(arg);
		cmus_play_file(tmp);
		free(tmp);
	} else {
		player_play();
	}
}

static void cmd_p_prev(char *arg)
{
	if (rewind_offset < 0 || player_info.pos < rewind_offset) {
		cmus_prev();
	} else {
		player_play();
	}
}

static void cmd_p_next_album(char *arg)
{
	cmus_next_album();
}

static void cmd_p_prev_album(char *arg)
{
	cmus_prev_album();
}

static void cmd_p_stop(char *arg)
{
	player_stop();
}

static void cmd_pwd(char *arg)
{
	char buf[4096];
	if (getcwd(buf, sizeof buf)) {
		info_msg("%s", buf);
	}
}

static void cmd_raise_vte(char *arg)
{
	cmus_raise_vte();
}

static void cmd_rand(char *arg)
{
	switch (cur_view) {
	case TREE_VIEW:
		break;
	case SORTED_VIEW:
		editable_rand(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_rand();
		break;
	case QUEUE_VIEW:
		editable_rand(&pq_editable);
		break;
	}
}

static void cmd_search_next(char *arg)
{
	if (search_str) {
		if (!search_next(searchable, search_str, search_direction))
			search_not_found();
	}
}

static void cmd_search_prev(char *arg)
{
	if (search_str) {
		if (!search_next(searchable, search_str, !search_direction))
			search_not_found();
	}
}

static void cmd_search_start(char *arg)
{
	enter_search_mode();
}

static void cmd_search_b_start(char *arg)
{
	enter_search_backward_mode();
}

static int sorted_for_each_sel(track_info_cb cb, void *data, int reverse, int advance)
{
	return editable_for_each_sel(&lib_editable, cb, data, reverse, advance);
}

static int pq_for_each_sel(track_info_cb cb, void *data, int reverse, int advance)
{
	return editable_for_each_sel(&pq_editable, cb, data, reverse, advance);
}

static for_each_sel_ti_cb view_for_each_sel[4] = {
	tree_for_each_sel,
	sorted_for_each_sel,
	pl_for_each_sel,
	pq_for_each_sel
};

/* wrapper for add_ti_cb, (void *) can't store function pointers */
struct wrapper_cb_data {
	add_ti_cb cb;
};

/* wrapper for void lib_add_track(struct track_info *) etc. */
static int wrapper_cb(void *data, struct track_info *ti)
{
	struct wrapper_cb_data *add = data;

	add->cb(ti, NULL);
	return 0;
}

static void add_from_browser(add_ti_cb add, int job_type, int advance)
{
	char *sel = get_browser_add_file();

	if (sel) {
		enum file_type ft;
		char *ret;

		ft = cmus_detect_ft(sel, &ret);
		if (ft != FILE_TYPE_INVALID) {
			cmus_add(add, ret, ft, job_type, 0, NULL);
			if (advance)
				window_down(browser_win, 1);
		}
		free(ret);
		free(sel);
	}
}

static void cmd_win_add_l(char *arg)
{
	int flag = parse_flags((const char **)&arg, "n");
	if (flag == -1)
		return;

	if (cur_view == TREE_VIEW || cur_view == SORTED_VIEW)
		return;

	if (cur_view <= QUEUE_VIEW) {
		struct wrapper_cb_data add = { lib_add_track };
		view_for_each_sel[cur_view](wrapper_cb, &add, 0, flag != 'n');
	} else if (cur_view == BROWSER_VIEW) {
		add_from_browser(lib_add_track, JOB_TYPE_LIB, flag != 'n');
	}
}

static void cmd_win_add_p(char *arg)
{
	int flag = parse_flags((const char **)&arg, "n");
	if (flag == -1)
		return;

	if (cur_view == PLAYLIST_VIEW && pl_visible_is_marked())
		return;

	if (cur_view <= QUEUE_VIEW) {
		struct wrapper_cb_data add = { pl_add_track_to_marked_pl2 };
		view_for_each_sel[cur_view](wrapper_cb, &add, 0, flag != 'n');
	} else if (cur_view == BROWSER_VIEW) {
		char *sel = get_browser_add_file();
		if (sel) {
			if (pl_add_file_to_marked_pl(sel) && flag != 'n')
				window_down(browser_win, 1);
			free(sel);
		}
	}
}

static void cmd_win_add_Q(char *arg)
{
	int flag = parse_flags((const char **)&arg, "n");
	if (flag == -1)
		return;

	if (cur_view == QUEUE_VIEW)
		return;

	if (cur_view <= QUEUE_VIEW) {
		struct wrapper_cb_data add = { play_queue_prepend };
		view_for_each_sel[cur_view](wrapper_cb, &add, 1, flag != 'n');
	} else if (cur_view == BROWSER_VIEW) {
		add_from_browser(play_queue_prepend, JOB_TYPE_QUEUE, flag != 'n');
	}
}

static void cmd_win_add_q(char *arg)
{
	int flag = parse_flags((const char **)&arg, "n");
	if (flag == -1)
		return;

	if (cur_view == QUEUE_VIEW)
		return;

	if (cur_view <= QUEUE_VIEW) {
		struct wrapper_cb_data add = { play_queue_append };
		view_for_each_sel[cur_view](wrapper_cb, &add, 0, flag != 'n');
	} else if (cur_view == BROWSER_VIEW) {
		add_from_browser(play_queue_append, JOB_TYPE_QUEUE, flag != 'n');
	}
}

static void cmd_win_activate(char *arg)
{
	struct track_info *info = NULL;
	struct shuffle_info *previous = NULL, *next = NULL;
	struct rb_root *shuffle_root = NULL;

	if (cur_view == TREE_VIEW || cur_view == SORTED_VIEW) {
		if (shuffle == SHUFFLE_TRACKS) {
			if (lib_cur_track)
				previous = &lib_cur_track->simple_track.shuffle_info;
			shuffle_root = &lib_shuffle_root;
		} else if (shuffle == SHUFFLE_ALBUMS) {
			if (lib_cur_track)
				previous = &lib_cur_track->album->shuffle_info;
			shuffle_root = &lib_album_shuffle_root;
		}
	}

	switch (cur_view) {
	case TREE_VIEW:
		info = tree_activate_selected();
		if (shuffle == SHUFFLE_TRACKS)
			next = &lib_cur_track->simple_track.shuffle_info;
		else if (shuffle == SHUFFLE_ALBUMS)
			next = &lib_cur_track->album->shuffle_info;
		break;
	case SORTED_VIEW:
		info = sorted_activate_selected();
		if (shuffle == SHUFFLE_TRACKS)
			next = &lib_cur_track->simple_track.shuffle_info;
		else if (shuffle == SHUFFLE_ALBUMS)
			next = &lib_cur_track->album->shuffle_info;
		break;
	case PLAYLIST_VIEW:
		info = pl_play_selected_row();
		break;
	case QUEUE_VIEW:
		break;
	case BROWSER_VIEW:
		browser_enter();
		break;
	case FILTERS_VIEW:
		filters_activate(1);
		break;
	case HELP_VIEW:
		help_select();
		break;
	}

	if (info) {
		if (shuffle && next)
			shuffle_insert(shuffle_root, previous, next);
		/* update lib/pl mode */
		if (cur_view < 2)
			play_library = 1;
		if (cur_view == 2)
			play_library = 0;

		player_play_file(info);
	}
}

static void cmd_win_mv_after(char *arg)
{
	switch (cur_view) {
	case SORTED_VIEW:
		editable_move_after(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_win_mv_after();
		break;
	case QUEUE_VIEW:
		editable_move_after(&pq_editable);
		break;
	}
}

static void cmd_win_mv_before(char *arg)
{
	switch (cur_view) {
	case SORTED_VIEW:
		editable_move_before(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_win_mv_before();
		break;
	case QUEUE_VIEW:
		editable_move_before(&pq_editable);
		break;
	}
}

static void cmd_win_remove(char *arg)
{
	switch (cur_view) {
	case TREE_VIEW:
		tree_remove_sel();
		break;
	case SORTED_VIEW:
		editable_remove_sel(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_win_remove();
		break;
	case QUEUE_VIEW:
		editable_remove_sel(&pq_editable);
		break;
	case BROWSER_VIEW:
		browser_delete();
		break;
	case FILTERS_VIEW:
		filters_delete_filter();
		break;
	case HELP_VIEW:
		help_remove();
		break;
	}
}

static void cmd_win_sel_cur(char *arg)
{
	switch (cur_view) {
	case TREE_VIEW:
		tree_sel_current(auto_expand_albums_selcur);
		break;
	case SORTED_VIEW:
		sorted_sel_current();
		break;
	case PLAYLIST_VIEW:
		pl_select_playing_track();
		break;
	}
}

static void cmd_win_toggle(char *arg)
{
	switch (cur_view) {
	case TREE_VIEW:
		tree_toggle_expand_artist();
		break;
	case SORTED_VIEW:
		editable_toggle_mark(&lib_editable);
		break;
	case PLAYLIST_VIEW:
		pl_win_toggle();
		break;
	case QUEUE_VIEW:
		editable_toggle_mark(&pq_editable);
		break;
	case FILTERS_VIEW:
		filters_toggle_filter();
		break;
	case HELP_VIEW:
		help_toggle();
		break;
	}
}

static void cmd_win_scroll_down(char *arg)
{
	window_scroll_down(current_win());
}

static void cmd_win_scroll_up(char *arg)
{
	window_scroll_up(current_win());
}

static void cmd_win_bottom(char *arg)
{
	window_goto_bottom(current_win());
}

static void cmd_win_down(char *arg)
{
	unsigned num_rows = 1;
	char *end;

	if (arg) {
		if ((num_rows = get_number(arg, &end)) == 0 || *end) {
			error_msg("invalid argument\n");
			return;
		}
	}

	window_down(current_win(), num_rows);
}

static void cmd_win_next(char *arg)
{
	if (cur_view == TREE_VIEW)
		tree_toggle_active_window();
	else if (cur_view == PLAYLIST_VIEW)
		pl_win_next();
}

static void cmd_win_pg_down(char *arg)
{
	window_page_down(current_win());
}

static void cmd_win_pg_up(char *arg)
{
	window_page_up(current_win());
}

static void cmd_win_hf_pg_down(char *arg)
{
	window_half_page_down(current_win());
}

static void cmd_win_hf_pg_up(char *arg)
{
	window_half_page_up(current_win());
}

static void cmd_win_pg_top(char *arg)
{
	window_page_top(current_win());
}

static void cmd_win_pg_bottom(char *arg)
{
	window_page_bottom(current_win());
}

static void cmd_win_pg_middle(char *arg)
{
	window_page_middle(current_win());
}

static void cmd_win_update_cache(char *arg)
{
	struct track_info_selection sel = { .tis = NULL };
	int flag = parse_flags((const char **)&arg, "f");

	if (cur_view != TREE_VIEW && cur_view != SORTED_VIEW)
		return;

	view_for_each_sel[cur_view](add_ti, &sel, 0, 1);
	if (sel.tis_nr == 0)
		return;
	sel.tis[sel.tis_nr] = NULL;
	cmus_update_tis(sel.tis, sel.tis_nr, flag == 'f');
}

static void cmd_win_top(char *arg)
{
	window_goto_top(current_win());
}

static void cmd_win_up(char *arg)
{
	unsigned num_rows = 1;
	char *end;

	if (arg) {
		if ((num_rows = get_number(arg, &end)) == 0 || *end) {
			error_msg("invalid argument\n");
			return;
		}
	}

	window_up(current_win(), num_rows);
}

static void cmd_win_update(char *arg)
{
	switch (cur_view) {
	case TREE_VIEW:
	case SORTED_VIEW:
		cmus_update_lib();
		break;
	case PLAYLIST_VIEW:
		pl_win_update();
		break;
	case BROWSER_VIEW:
		browser_reload();
		break;
	}
}

static void cmd_browser_up(char *arg)
{
	browser_up();
}

static void cmd_refresh(char *arg)
{
	clearok(curscr, TRUE);
	refresh();
}

static int cmp_intp(const void *ap, const void *bp)
{
	int a = *(int *)ap;
	int b = *(int *)bp;
	return a - b;
}

static int *rand_array(int size, int nmax)
{
	int *r = xnew(int, size + 1);
	int i, offset = 0;
	int count = size;

	if (count > nmax / 2) {
		/*
		 * Imagine that there are 1000 tracks in library and we want to
		 * add 998 random tracks to queue.  After we have added 997
		 * random numbers to the array it would be quite hard to find a
		 * random number that isn't already in the array (3/1000
		 * probability).
		 *
		 * So we invert the logic:
		 *
		 * Find two (1000 - 998) random numbers in 0..999 range and put
		 * them at end of the array.  Sort the numbers and then fill
		 * the array starting at index 0 with incrementing values that
		 * are not in the set of random numbers.
		 */
		count = nmax - count;
		offset = size - count;
	}

	for (i = 0; i < count; ) {
		int v, j;
found:
		v = rand() % nmax;
		for (j = 0; j < i; j++) {
			if (r[offset + j] == v)
				goto found;
		}
		r[offset + i++] = v;
	}
	qsort(r + offset, count, sizeof(*r), cmp_intp);

	if (offset) {
		int j, n;

		/* simplifies next loop */
		r[size] = nmax;

		/* convert the indexes we don't want to those we want */
		i = 0;
		j = offset;
		n = 0;
		do {
			while (n < r[j])
				r[i++] = n++;
			j++;
			n++;
		} while (i < size);
	}
	return r;
}

static int count_albums(void)
{
	struct artist *artist;
	struct rb_node *tmp1, *tmp2;
	int count = 0;

	rb_for_each_entry(artist, tmp1, &lib_artist_root, tree_node) {
		rb_for_each(tmp2, &artist->album_root)
			count++;
	}
	return count;
}

struct album_list {
	struct list_head node;
	const struct album *album;
};

static void cmd_lqueue(char *arg)
{
	LIST_HEAD(head);
	const struct list_head *item;
	const struct album *album;
	int count = 1, nmax, i, pos;
	int *r;

	if (arg) {
		long int val;

		if (str_to_int(arg, &val) || val <= 0) {
			error_msg("argument must be positive integer");
			return;
		}
		count = val;
	}
	nmax = count_albums();
	if (count > nmax)
		count = nmax;
	if (!count)
		return;

	r = rand_array(count, nmax);
	album = to_album(rb_first(&to_artist(rb_first(&lib_artist_root))->album_root));
	pos = 0;
	for (i = 0; i < count; i++) {
		struct album_list *a;

		while (pos < r[i]) {
			struct artist *artist = album->artist;
			if (!rb_next(&album->tree_node)) {
				artist = to_artist(rb_next(&artist->tree_node));
				album = to_album(rb_first(&artist->album_root));
			} else {
				album = to_album(rb_next(&album->tree_node));
			}
			pos++;
		}
		a = xnew(struct album_list, 1);
		a->album = album;
		list_add_rand(&head, &a->node, i);
	}
	free(r);

	item = head.next;
	do {
		struct list_head *next = item->next;
		struct album_list *a = container_of(item, struct album_list, node);
		struct tree_track *t;
		struct rb_node *tmp;

		rb_for_each_entry(t, tmp, &a->album->track_root, tree_node)
			play_queue_append(tree_track_info(t), NULL);
		free(a);
		item = next;
	} while (item != &head);
}

struct track_list {
	struct list_head node;
	const struct simple_track *track;
};

static void cmd_tqueue(char *arg)
{
	LIST_HEAD(head);
	struct list_head *item;
	int count = 1, i, pos;
	int *r;

	if (arg) {
		long int val;

		if (str_to_int(arg, &val) || val <= 0) {
			error_msg("argument must be positive integer");
			return;
		}
		count = val;
	}
	if (count > lib_editable.nr_tracks)
		count = lib_editable.nr_tracks;
	if (!count)
		return;

	r = rand_array(count, lib_editable.nr_tracks);
	item = lib_editable.head.next;
	pos = 0;
	for (i = 0; i < count; i++) {
		struct track_list *t;

		while (pos < r[i]) {
			item = item->next;
			pos++;
		}
		t = xnew(struct track_list, 1);
		t->track = to_simple_track(item);
		list_add_rand(&head, &t->node, i);
	}
	free(r);

	item = head.next;
	do {
		struct list_head *next = item->next;
		struct track_list *t = container_of(item, struct track_list, node);
		play_queue_append(t->track->info, NULL);
		free(t);
		item = next;
	} while (item != &head);
}

/* tab exp {{{
 *
 * these functions fill tabexp struct, which is resetted beforehand
 */

/* buffer used for tab expansion */
static char expbuf[512];

static int filter_directories(const char *name, const struct stat *s)
{
	return S_ISDIR(s->st_mode);
}

static int filter_executable_files(const char *name, const struct stat *s)
{
	return S_ISREG(s->st_mode) && (s->st_mode & 0111);
}

static int filter_any(const char *name, const struct stat *s)
{
	return 1;
}

static int filter_playable(const char *name, const struct stat *s)
{
	return S_ISDIR(s->st_mode) || cmus_is_playable(name);
}

static int filter_playlist(const char *name, const struct stat *s)
{
	return S_ISDIR(s->st_mode) || cmus_is_playlist(name);
}

static int filter_supported(const char *name, const struct stat *s)
{
	return S_ISDIR(s->st_mode) || cmus_is_supported(name);
}

static void expand_files(const char *str)
{
	expand_files_and_dirs(str, filter_any);
}

static void expand_directories(const char *str)
{
	expand_files_and_dirs(str, filter_directories);
}

static void expand_playable(const char *str)
{
	expand_files_and_dirs(str, filter_playable);
}

static void expand_playlist(const char *str)
{
	expand_files_and_dirs(str, filter_playlist);
}

static void expand_supported(const char *str)
{
	expand_files_and_dirs(str, filter_supported);
}

static void expand_add(const char *str)
{
	int flag = parse_flags(&str, "lpqQ");

	if (flag == -1)
		return;
	if (str == NULL)
		str = "";
	expand_supported(str);

	if (tabexp.head && flag) {
		snprintf(expbuf, sizeof(expbuf), "-%c %s", flag, tabexp.head);
		free(tabexp.head);
		tabexp.head = xstrdup(expbuf);
	}
}

static void expand_program_paths(const char *str)
{
	if (str == NULL)
		str = "";
	if (str[0] == '~' || strchr(str, '/'))
		expand_files(str);
	else
		expand_env_path(str, filter_executable_files);
}

static void expand_program_paths_option(const char *str, const char *opt)
{
	expand_program_paths(str);

	if (tabexp.head && opt) {
		snprintf(expbuf, sizeof(expbuf), "%s=%s", opt, tabexp.head);
		free(tabexp.head);
		tabexp.head = xstrdup(expbuf);
	}
}

static void expand_load_save(const char *str)
{
	int flag = parse_flags(&str, "lp");

	if (flag == -1)
		return;
	if (str == NULL)
		str = "";
	expand_playlist(str);

	if (tabexp.head && flag) {
		snprintf(expbuf, sizeof(expbuf), "-%c %s", flag, tabexp.head);
		free(tabexp.head);
		tabexp.head = xstrdup(expbuf);
	}
}

static void expand_key_context(const char *str, const char *force)
{
	int pos, i, len = strlen(str);
	char **tails;

	tails = xnew(char *, NR_CTXS);
	pos = 0;
	for (i = 0; key_context_names[i]; i++) {
		int cmp = strncmp(str, key_context_names[i], len);
		if (cmp > 0)
			continue;
		if (cmp < 0)
			break;
		tails[pos++] = xstrdup(key_context_names[i] + len);
	}

	if (pos == 0) {
		free(tails);
		return;
	}
	if (pos == 1) {
		char *tmp = xstrjoin(tails[0], " ");
		free(tails[0]);
		tails[0] = tmp;
	}
	snprintf(expbuf, sizeof(expbuf), "%s%s", force, str);
	tabexp.head = xstrdup(expbuf);
	tabexp.tails = tails;
	tabexp.count = pos;
}

static int get_context(const char *str, int len)
{
	int i, c = -1, count = 0;

	for (i = 0; key_context_names[i]; i++) {
		if (strncmp(str, key_context_names[i], len) == 0) {
			if (key_context_names[i][len] == 0) {
				/* exact */
				return i;
			}
			c = i;
			count++;
		}
	}
	if (count == 1)
		return c;
	return -1;
}

static void expand_command_line(const char *str);

static void expand_bind_args(const char *str)
{
	/* :bind context key function
	 *
	 * possible values for str:
	 *   c
	 *   context k
	 *   context key f
	 *
	 * you need to know context before you can expand function
	 */
	/* start and end pointers for context, key and function */
	const char *cs, *ce, *ks, *ke, *fs;
	int i, c, k, count;
	int flag = parse_flags((const char **)&str, "f");
	const char *force = "";

	if (flag == -1)
		return;
	if (str == NULL)
		str = "";

	if (flag == 'f')
		force = "-f ";

	cs = str;
	ce = strchr(cs, ' ');
	if (ce == NULL) {
		expand_key_context(cs, force);
		return;
	}

	/* context must be expandable */
	c = get_context(cs, ce - cs);
	if (c == -1) {
		/* context is ambiguous or invalid */
		return;
	}

	ks = ce;
	while (*ks == ' ')
		ks++;
	ke = strchr(ks, ' ');
	if (ke == NULL) {
		/* expand key */
		int len = strlen(ks);
		PTR_ARRAY(array);

		for (i = 0; key_table[i].name; i++) {
			int cmp = strncmp(ks, key_table[i].name, len);
			if (cmp > 0)
				continue;
			if (cmp < 0)
				break;
			ptr_array_add(&array, xstrdup(key_table[i].name + len));
		}

		if (!array.count)
			return;

		if (array.count == 1) {
			char **ptrs = array.ptrs;
			char *tmp = xstrjoin(ptrs[0], " ");
			free(ptrs[0]);
			ptrs[0] = tmp;
		}

		snprintf(expbuf, sizeof(expbuf), "%s%s %s", force, key_context_names[c], ks);

		tabexp.head = xstrdup(expbuf);
		tabexp.tails = array.ptrs;
		tabexp.count = array.count;
		return;
	}

	/* key must be expandable */
	k = -1;
	count = 0;
	for (i = 0; key_table[i].name; i++) {
		if (strncmp(ks, key_table[i].name, ke - ks) == 0) {
			if (key_table[i].name[ke - ks] == 0) {
				/* exact */
				k = i;
				count = 1;
				break;
			}
			k = i;
			count++;
		}
	}
	if (count != 1) {
		/* key is ambiguous or invalid */
		return;
	}

	fs = ke;
	while (*fs == ' ')
		fs++;

	if (*fs == ':')
		fs++;

	/* expand com [arg...] */
	expand_command_line(fs);
	if (tabexp.head == NULL) {
		/* command expand failed */
		return;
	}

	/*
	 * tabexp.head is now "com"
	 * tabexp.tails is [ mand1 mand2 ... ]
	 *
	 * need to change tabexp.head to "context key com"
	 */

	snprintf(expbuf, sizeof(expbuf), "%s%s %s %s", force, key_context_names[c],
			key_table[k].name, tabexp.head);
	free(tabexp.head);
	tabexp.head = xstrdup(expbuf);
}

static void expand_unbind_args(const char *str)
{
	/* :unbind context key */
	/* start and end pointers for context and key */
	const char *cs, *ce, *ks;
	const struct binding *b;
	PTR_ARRAY(array);
	int c, len;

	cs = str;
	ce = strchr(cs, ' ');
	if (ce == NULL) {
		expand_key_context(cs, "");
		return;
	}

	/* context must be expandable */
	c = get_context(cs, ce - cs);
	if (c == -1) {
		/* context is ambiguous or invalid */
		return;
	}

	ks = ce;
	while (*ks == ' ')
		ks++;

	/* expand key */
	len = strlen(ks);
	b = key_bindings[c];
	while (b) {
		if (!strncmp(ks, b->key->name, len))
			ptr_array_add(&array, xstrdup(b->key->name + len));
		b = b->next;
	}
	if (!array.count)
		return;

	snprintf(expbuf, sizeof(expbuf), "%s %s", key_context_names[c], ks);

	tabexp.head = xstrdup(expbuf);
	tabexp.tails = array.ptrs;
	tabexp.count = array.count;
}

static void expand_factivate(const char *str)
{
	/* "name1 name2 name3", expand only name3 */
	struct filter_entry *e;
	const char *name;
	PTR_ARRAY(array);
	int str_len, len, i;

	str_len = strlen(str);
	i = str_len;
	while (i > 0) {
		if (str[i - 1] == ' ')
			break;
		i--;
	}
	len = str_len - i;
	name = str + i;

	list_for_each_entry(e, &filters_head, node) {
		if (!strncmp(name, e->name, len))
			ptr_array_add(&array, xstrdup(e->name + len));
	}
	if (!array.count)
		return;

	tabexp.head = xstrdup(str);
	tabexp.tails = array.ptrs;
	tabexp.count = array.count;
}

static void expand_fset(const char *str)
{
	struct filter_entry *e;
	PTR_ARRAY(array);

	list_for_each_entry(e, &filters_head, node) {
		char *line = xnew(char, strlen(e->name) + strlen(e->filter) + 2);
		sprintf(line, "%s=%s", e->name, e->filter);
		if (!strncmp(str, line, strlen(str)))
			ptr_array_add(&array, xstrdup(line + strlen(str)));
		free(line);
	}
	if (!array.count)
		return;

	tabexp.head = xstrdup(str);
	tabexp.tails = array.ptrs;
	tabexp.count = array.count;
}

static void expand_options(const char *str)
{
	struct cmus_opt *opt;
	int len;
	char **tails, *sep;

	/* tabexp is resetted */
	len = strlen(str);
	sep = strchr(str, '=');
	if (len > 1 && sep) {
		/* expand value */
		char *var = xstrndup(str, sep - str);

		list_for_each_entry(opt, &option_head, node) {
			if (strcmp(var, opt->name) == 0) {
				if (str[len - 1] == '=') {
					char buf[OPTION_MAX_SIZE];

					tails = xnew(char *, 1);

					buf[0] = 0;
					opt->get(opt->data, buf, OPTION_MAX_SIZE);
					tails[0] = xstrdup(buf);

					tabexp.head = xstrdup(str);
					tabexp.tails = tails;
					tabexp.count = 1;
				} else if (opt->flags & OPT_PROGRAM_PATH) {
					expand_program_paths_option(sep + 1, var);
				}
				break;
			}
		}
		free(var);
	} else {
		/* expand variable */
		int pos;

		tails = xnew(char *, nr_options);
		pos = 0;
		list_for_each_entry(opt, &option_head, node) {
			if (strncmp(str, opt->name, len) == 0)
				tails[pos++] = xstrdup(opt->name + len);
		}
		if (pos > 0) {
			if (pos == 1) {
				/* only one variable matches, add '=' */
				char *tmp = xstrjoin(tails[0], "=");

				free(tails[0]);
				tails[0] = tmp;
			}

			tabexp.head = xstrdup(str);
			tabexp.tails = tails;
			tabexp.count = pos;
		} else {
			free(tails);
		}
	}
}

static void expand_toptions(const char *str)
{
	struct cmus_opt *opt;
	int len, pos;
	char **tails;

	tails = xnew(char *, nr_options);
	len = strlen(str);
	pos = 0;
	list_for_each_entry(opt, &option_head, node) {
		if (opt->toggle == NULL)
			continue;
		if (strncmp(str, opt->name, len) == 0)
			tails[pos++] = xstrdup(opt->name + len);
	}
	if (pos > 0) {
		tabexp.head = xstrdup(str);
		tabexp.tails = tails;
		tabexp.count = pos;
	} else {
		free(tails);
	}
}

static void load_themes(const char *dirname, const char *str, struct ptr_array *array)
{
	struct directory dir;
	const char *name, *dot;
	int len = strlen(str);

	if (dir_open(&dir, dirname))
		return;

	while ((name = dir_read(&dir))) {
		if (!S_ISREG(dir.st.st_mode))
			continue;
		if (strncmp(name, str, len))
			continue;
		dot = strrchr(name, '.');
		if (dot == NULL || strcmp(dot, ".theme"))
			continue;
		if (dot - name < len)
			/* str is  "foo.th"
			 * matches "foo.theme"
			 * which also ends with ".theme"
			 */
			continue;
		ptr_array_add(array, xstrndup(name + len, dot - name - len));
	}
	dir_close(&dir);
}

static void expand_colorscheme(const char *str)
{
	PTR_ARRAY(array);

	load_themes(cmus_config_dir, str, &array);
	load_themes(cmus_data_dir, str, &array);

	if (array.count) {
		ptr_array_sort(&array, strptrcmp);

		tabexp.head = xstrdup(str);
		tabexp.tails = array.ptrs;
		tabexp.count = array.count;
	}
}

static void expand_commands(const char *str);

/* tab exp }}} */

/* sort by name */
struct command commands[] = {
	{ "add",                   cmd_add,              1, 1,  expand_add,           0, 0          },
	{ "bind",                  cmd_bind,             1, 1,  expand_bind_args,     0, CMD_UNSAFE },
	{ "browser-up",            cmd_browser_up,       0, 0,  NULL,                 0, 0          },
	{ "cd",                    cmd_cd,               0, 1,  expand_directories,   0, 0          },
	{ "clear",                 cmd_clear,            0, 1,  NULL,                 0, 0          },
	{ "colorscheme",           cmd_colorscheme,      1, 1,  expand_colorscheme,   0, 0          },
	{ "echo",                  cmd_echo,             1, -1, NULL,                 0, 0          },
	{ "factivate",             cmd_factivate,        0, 1,  expand_factivate,     0, 0          },
	{ "filter",                cmd_filter,           0, 1,  NULL,                 0, 0          },
	{ "fset",                  cmd_fset,             1, 1,  expand_fset,          0, 0          },
	{ "help",                  cmd_help,             0, 0,  NULL,                 0, 0          },
	{ "invert",                cmd_invert,           0, 0,  NULL,                 0, 0          },
	{ "live-filter",           cmd_live_filter,      0, 1,  NULL,                 0, CMD_LIVE   },
	{ "load",                  cmd_load,             1, 1,  expand_load_save,     0, 0          },
	{ "lqueue",                cmd_lqueue,           0, 1,  NULL,                 0, 0          },
	{ "mark",                  cmd_mark,             0, 1,  NULL,                 0, 0          },
	{ "mute",                  cmd_mute,             0, 0,  NULL,                 0, 0          },
	{ "player-next",           cmd_p_next,           0, 0,  NULL,                 0, 0          },
	{ "player-next-album",     cmd_p_next_album,     0, 0,  NULL,                 0, 0          },
	{ "player-pause",          cmd_p_pause,          0, 0,  NULL,                 0, 0          },
	{ "player-pause-playback", cmd_p_pause_playback, 0, 0,  NULL,                 0, 0          },
	{ "player-play",           cmd_p_play,           0, 1,  expand_playable,      0, 0          },
	{ "player-prev",           cmd_p_prev,           0, 0,  NULL,                 0, 0          },
	{ "player-prev-album",     cmd_p_prev_album,     0, 0,  NULL,                 0, 0          },
	{ "player-stop",           cmd_p_stop,           0, 0,  NULL,                 0, 0          },
	{ "prev-view",             cmd_prev_view,        0, 0,  NULL,                 0, 0          },
	{ "left-view",             cmd_left_view,        0, 0,  NULL,                 0, 0          },
	{ "right-view",            cmd_right_view,       0, 0,  NULL,                 0, 0          },
	{ "pl-create",             cmd_pl_create,        1, -1, NULL,                 0, 0          },
	{ "pl-export",             cmd_pl_export,        1, -1, NULL,                 0, 0          },
	{ "pl-import",             cmd_pl_import,        0, -1, NULL,                 0, 0          },
	{ "pl-rename",             cmd_pl_rename,        1, -1, NULL,                 0, 0          },
	{ "push",                  cmd_push,             0, -1, expand_commands,      0, 0          },
	{ "pwd",                   cmd_pwd,              0, 0,  NULL,                 0, 0          },
	{ "raise-vte",             cmd_raise_vte,        0, 0,  NULL,                 0, 0          },
	{ "rand",                  cmd_rand,             0, 0,  NULL,                 0, 0          },
	{ "quit",                  cmd_quit,             0, 1,  NULL,                 0, 0          },
	{ "refresh",               cmd_refresh,          0, 0,  NULL,                 0, 0          },
	{ "reshuffle",             cmd_reshuffle,        0, 0,  NULL,                 0, 0          },
	{ "run",                   cmd_run,              1, -1, expand_program_paths, 0, CMD_UNSAFE },
	{ "save",                  cmd_save,             0, 1,  expand_load_save,     0, CMD_UNSAFE },
	{ "search-b-start",        cmd_search_b_start,   0, 0,  NULL,                 0, 0          },
	{ "search-next",           cmd_search_next,      0, 0,  NULL,                 0, 0          },
	{ "search-prev",           cmd_search_prev,      0, 0,  NULL,                 0, 0          },
	{ "search-start",          cmd_search_start,     0, 0,  NULL,                 0, 0          },
	{ "seek",                  cmd_seek,             1, 1,  NULL,                 0, 0          },
	{ "set",                   cmd_set,              1, 1,  expand_options,       0, 0          },
	{ "shell",                 cmd_shell,            1, -1, expand_program_paths, 0, CMD_UNSAFE },
	{ "showbind",              cmd_showbind,         1, 1,  expand_unbind_args,   0, 0          },
	{ "shuffle",               cmd_reshuffle,        0, 0,  NULL,                 0, CMD_HIDDEN },
	{ "source",                cmd_source,           1, 1,  expand_files,         0, CMD_UNSAFE },
	{ "toggle",                cmd_toggle,           1, 1,  expand_toptions,      0, 0          },
	{ "tqueue",                cmd_tqueue,           0, 1,  NULL,                 0, 0          },
	{ "unbind",                cmd_unbind,           1, 1,  expand_unbind_args,   0, 0          },
	{ "unmark",                cmd_unmark,           0, 0,  NULL,                 0, 0          },
	{ "update-cache",          cmd_update_cache,     0, 1,  NULL,                 0, 0          },
	{ "version",               cmd_version,          0, 0,  NULL,                 0, 0          },
	{ "view",                  cmd_view,             1, 1,  NULL,                 0, 0          },
	{ "vol",                   cmd_vol,              1, 2,  NULL,                 0, 0          },
	{ "w",                     cmd_save,             0, 1,  expand_load_save,     0, CMD_UNSAFE },
	{ "win-activate",          cmd_win_activate,     0, 0,  NULL,                 0, 0          },
	{ "win-add-l",             cmd_win_add_l,        0, 1,  NULL,                 0, 0          },
	{ "win-add-p",             cmd_win_add_p,        0, 1,  NULL,                 0, 0          },
	{ "win-add-Q",             cmd_win_add_Q,        0, 1,  NULL,                 0, 0          },
	{ "win-add-q",             cmd_win_add_q,        0, 1,  NULL,                 0, 0          },
	{ "win-bottom",            cmd_win_bottom,       0, 0,  NULL,                 0, 0          },
	{ "win-down",              cmd_win_down,         0, 1,  NULL,                 0, 0          },
	{ "win-half-page-down",    cmd_win_hf_pg_down,   0, 0,  NULL,                 0, 0          },
	{ "win-half-page-up",      cmd_win_hf_pg_up,     0, 0,  NULL,                 0, 0          },
	{ "win-mv-after",          cmd_win_mv_after,     0, 0,  NULL,                 0, 0          },
	{ "win-mv-before",         cmd_win_mv_before,    0, 0,  NULL,                 0, 0          },
	{ "win-next",              cmd_win_next,         0, 0,  NULL,                 0, 0          },
	{ "win-page-bottom",       cmd_win_pg_bottom,    0, 0,  NULL,                 0, 0          },
	{ "win-page-down",         cmd_win_pg_down,      0, 0,  NULL,                 0, 0          },
	{ "win-page-middle",       cmd_win_pg_middle,    0, 0,  NULL,                 0, 0          },
	{ "win-page-top",          cmd_win_pg_top,       0, 0,  NULL,                 0, 0          },
	{ "win-page-up",           cmd_win_pg_up,        0, 0,  NULL,                 0, 0          },
	{ "win-remove",            cmd_win_remove,       0, 0,  NULL,                 0, CMD_UNSAFE },
	{ "win-scroll-down",       cmd_win_scroll_down,  0, 0,  NULL,                 0, 0          },
	{ "win-scroll-up",         cmd_win_scroll_up,    0, 0,  NULL,                 0, 0          },
	{ "win-sel-cur",           cmd_win_sel_cur,      0, 0,  NULL,                 0, 0          },
	{ "win-toggle",            cmd_win_toggle,       0, 0,  NULL,                 0, 0          },
	{ "win-top",               cmd_win_top,          0, 0,  NULL,                 0, 0          },
	{ "win-up",                cmd_win_up,           0, 1,  NULL,                 0, 0          },
	{ "win-update",            cmd_win_update,       0, 0,  NULL,                 0, 0          },
	{ "win-update-cache",      cmd_win_update_cache, 0, 1,  NULL,                 0, 0          },
	{ "wq",                    cmd_quit,             0, 1,  NULL,                 0, 0          },
	{ NULL,                    NULL,                 0, 0,  0,                    0, 0          }
};

/* fills tabexp struct */
static void expand_commands(const char *str)
{
	int i, len, pos;
	char **tails;

	/* tabexp is resetted */
	tails = xnew(char *, N_ELEMENTS(commands) - 1);
	len = strlen(str);
	pos = 0;
	for (i = 0; commands[i].name; i++) {
		if (strncmp(str, commands[i].name, len) == 0 && !(commands[i].flags & CMD_HIDDEN))
			tails[pos++] = xstrdup(commands[i].name + len);
	}
	if (pos > 0) {
		if (pos == 1) {
			/* only one command matches, add ' ' */
			char *tmp = xstrjoin(tails[0], " ");

			free(tails[0]);
			tails[0] = tmp;
		}
		tabexp.head = xstrdup(str);
		tabexp.tails = tails;
		tabexp.count = pos;
	} else {
		free(tails);
	}
}

struct command *get_command(const char *str)
{
	int i, len;

	while (*str == ' ')
		str++;
	for (len = 0; str[len] && str[len] != ' '; len++)
		;

	for (i = 0; commands[i].name; i++) {
		if (strncmp(str, commands[i].name, len))
			continue;

		if (commands[i].name[len] == 0) {
			/* exact */
			return &commands[i];
		}

		if (commands[i + 1].name && strncmp(str, commands[i + 1].name, len) == 0) {
			/* ambiguous */
			return NULL;
		}
		return &commands[i];
	}
	return NULL;
}

/* fills tabexp struct */
static void expand_command_line(const char *str)
{
	/* :command [arg]...
	 *
	 * examples:
	 *
	 * str      expanded value (tabexp.head)
	 * -------------------------------------
	 *   fs     fset
	 *   b c    bind common
	 *   se     se          (tabexp.tails = [ ek t ])
	 */
	/* command start/end, argument start */
	const char *cs, *ce, *as;
	const struct command *cmd;

	cs = str;
	ce = strchr(cs, ' ');
	if (ce == NULL) {
		/* expand command */
		expand_commands(cs);
		return;
	}

	/* command must be expandable */
	cmd = get_command(cs);
	if (cmd == NULL) {
		/* command ambiguous or invalid */
		return;
	}

	if (cmd->expand == NULL) {
		/* can't expand argument */
		return;
	}

	as = ce;
	while (*as == ' ')
		as++;

	/* expand argument */
	cmd->expand(as);
	if (tabexp.head == NULL) {
		/* argument expansion failed */
		return;
	}

	/* tabexp.head is now start of the argument string */
	snprintf(expbuf, sizeof(expbuf), "%s %s", cmd->name, tabexp.head);
	free(tabexp.head);
	tabexp.head = xstrdup(expbuf);
}

static void tab_expand(int direction)
{
	char *s1, *s2, *tmp;
	int pos;

	/* strip white space */
	pos = 0;
	while (cmdline.line[pos] == ' ' && pos < cmdline.bpos)
		pos++;

	/* string to expand */
	s1 = xstrndup(cmdline.line + pos, cmdline.bpos - pos);

	/* tail */
	s2 = xstrdup(cmdline.line + cmdline.bpos);

	tmp = tabexp_expand(s1, expand_command_line, direction);
	if (tmp) {
		/* tmp.s2 */
		int l1, l2;

		l1 = strlen(tmp);
		l2 = strlen(s2);
		cmdline.blen = l1 + l2;
		if (cmdline.blen >= cmdline.size) {
			while (cmdline.blen >= cmdline.size)
				cmdline.size *= 2;
			cmdline.line = xrenew(char, cmdline.line, cmdline.size);
		}
		sprintf(cmdline.line, "%s%s", tmp, s2);
		cmdline.bpos = l1;
		cmdline.cpos = u_strlen_safe(tmp);
		cmdline.clen = u_strlen_safe(cmdline.line);
		free(tmp);
	}
	free(s1);
	free(s2);
}

static void reset_tab_expansion(void)
{
	tabexp_reset();
	arg_expand_cmd = -1;
}

static void cmdline_modified(void)
{
	char *cmd, *arg;
	struct command *c;

	if (!parse_command(cmdline.line, &cmd, &arg))
		return;

	c = get_command(cmd);
	if (!c)
		goto end;

	if (c->flags & CMD_LIVE)
		run_parsed_command(cmd, arg);

end:
	free(cmd);
	free(arg);
}

int parse_command(const char *buf, char **cmdp, char **argp)
{
	int cmd_start, cmd_end, cmd_len;
	int arg_start, arg_end;
	int i;

	i = 0;
	while (buf[i] && buf[i] == ' ')
		i++;

	if (buf[i] == '#')
		return 0;

	cmd_start = i;
	while (buf[i] && buf[i] != ' ')
		i++;
	cmd_end = i;
	while (buf[i] && buf[i] == ' ')
		i++;
	arg_start = i;
	while (buf[i])
		i++;
	arg_end = i;

	cmd_len = cmd_end - cmd_start;
	if (cmd_len == 0)
		return 0;

	*cmdp = xstrndup(buf + cmd_start, cmd_len);
	if (arg_start == arg_end) {
		*argp = NULL;
	} else {
		*argp = xstrndup(buf + arg_start, arg_end - arg_start);
	}
	return 1;
}

int run_only_safe_commands;

void run_parsed_command(char *cmd, char *arg)
{
	int cmd_len = strlen(cmd);
	int i = 0;

	while (1) {
		const struct command *c = &commands[i];

		if (c->name == NULL) {
			error_msg("unknown command\n");
			break;
		}
		if (strncmp(cmd, c->name, cmd_len) == 0) {
			const char *next = commands[i + 1].name;
			int exact = c->name[cmd_len] == 0;

			if (!exact && next && strncmp(cmd, next, cmd_len) == 0) {
				error_msg("ambiguous command\n");
				break;
			}
			if (c->min_args > 0 && arg == NULL) {
				error_msg("not enough arguments\n");
				break;
			}
			if (c->max_args == 0 && arg) {
				error_msg("too many arguments\n");
				break;
			}
			if (run_only_safe_commands && (c->flags & CMD_UNSAFE)) {
				if (c->func != cmd_save || !is_stdout_filename(arg)) {
					d_print("trying to execute unsafe command over net\n");
					break;
				}
			}
			c->func(arg);
			break;
		}
		i++;
	}
}

void run_command(const char *buf)
{
	char *cmd, *arg;

	if (!parse_command(buf, &cmd, &arg))
		return;

	run_parsed_command(cmd, arg);
	free(arg);
	free(cmd);
}

static void reset_history_search(void)
{
	history_reset_search(&cmd_history);
	free(history_search_text);
	history_search_text = NULL;
}

static void backspace(void)
{
	if (cmdline.clen > 0) {
		cmdline_backspace();
	} else {
		input_mode = NORMAL_MODE;
	}
}

void command_mode_ch(uchar ch)
{
	switch (ch) {
	case 0x01: // ^A
		cmdline_move_home();
		break;
	case 0x02: // ^B
		cmdline_move_left();
		break;
	case 0x04: // ^D
		cmdline_delete_ch();
		cmdline_modified();
		break;
	case 0x05: // ^E
		cmdline_move_end();
		break;
	case 0x06: // ^F
		cmdline_move_right();
		break;
	case 0x03: // ^C
	case 0x07: // ^G
	case 0x1B: // ESC
		if (cmdline.blen) {
			history_add_line(&cmd_history, cmdline.line);
			cmdline_clear();
		}
		input_mode = NORMAL_MODE;
		break;
	case 0x10: // ^P
		command_mode_key(KEY_UP);
		return;
	case 0xE: // ^N
		command_mode_key(KEY_DOWN);
		return;
	case 0x0A:
		if (cmdline.blen) {
			run_command(cmdline.line);
			history_add_line(&cmd_history, cmdline.line);
			cmdline_clear();
		}
		input_mode = NORMAL_MODE;
		break;
	case 0x0B:
		cmdline_clear_end();
		cmdline_modified();
		break;
	case 0x09:
		tab_expand(1);
		break;
	case 0x15:
		cmdline_backspace_to_bol();
		cmdline_modified();
		break;
	case 0x17: // ^W
		cmdline_backward_delete_word(cmdline_word_delimiters);
		cmdline_modified();
		break;
	case 0x08: // ^H
	case 127:
		backspace();
		cmdline_modified();
		break;
	default:
		cmdline_insert_ch(ch);
		cmdline_modified();
	}
	reset_history_search();
	if (ch != 0x09)
		reset_tab_expansion();
}

void command_mode_escape(int c)
{
	switch (c) {
	case 98:
		cmdline_backward_word(cmdline_filename_delimiters);
		break;
	case 100:
		cmdline_delete_word(cmdline_filename_delimiters);
		cmdline_modified();
		break;
	case 102:
		cmdline_forward_word(cmdline_filename_delimiters);
		break;
	case 127:
	case KEY_BACKSPACE:
		cmdline_backward_delete_word(cmdline_filename_delimiters);
		cmdline_modified();
		break;
	}
	reset_history_search();
}

void command_mode_key(int key)
{
	if (key != KEY_BTAB)
		reset_tab_expansion();
	switch (key) {
	case KEY_DC:
		cmdline_delete_ch();
		cmdline_modified();
		break;
	case KEY_BACKSPACE:
		backspace();
		cmdline_modified();
		break;
	case KEY_LEFT:
		cmdline_move_left();
		return;
	case KEY_RIGHT:
		cmdline_move_right();
		return;
	case KEY_HOME:
		cmdline_move_home();
		return;
	case KEY_END:
		cmdline_move_end();
		return;
	case KEY_UP:
		{
			const char *s;

			if (history_search_text == NULL)
				history_search_text = xstrdup(cmdline.line);
			s = history_search_forward(&cmd_history, history_search_text);
			if (s)
				cmdline_set_text(s);
		}
		return;
	case KEY_DOWN:
		if (history_search_text) {
			const char *s;

			s = history_search_backward(&cmd_history, history_search_text);
			if (s) {
				cmdline_set_text(s);
			} else {
				cmdline_set_text(history_search_text);
			}
		}
		return;
	case KEY_BTAB:
		tab_expand(-1);
		break;
	default:
		d_print("key = %c (%d)\n", key, key);
	}
	reset_history_search();
}

void command_mode_mouse(MEVENT *event)
{
	if ((event->bstate & BUTTON1_PRESSED) || (event->bstate & BUTTON3_PRESSED)) {
		if (event->y <= window_get_nr_rows(current_win()) + 2) {
			if (cmdline.blen) {
				history_add_line(&cmd_history, cmdline.line);
				cmdline_clear();
			}
			input_mode = NORMAL_MODE;
			normal_mode_mouse(event);
			return;
		}
		if (event->x == 0)
			return;
		int i = event->x > cmdline.clen ? cmdline.clen : event->x - 1;
		while (i < cmdline.cpos)
			cmdline_move_left();
		while (i > cmdline.cpos)
			cmdline_move_right();
	} else if (event->bstate & BUTTON4_PRESSED) {
		command_mode_key(KEY_UP);
	} else if (event->bstate & BUTTON5_PRESSED) {
		command_mode_key(KEY_DOWN);
	}
}

void commands_init(void)
{
	cmd_history_filename = xstrjoin(cmus_config_dir, "/command-history");
	history_load(&cmd_history, cmd_history_filename, 2000);
}

void commands_exit(void)
{
	view_clear(TREE_VIEW);
	view_clear(SORTED_VIEW);
	view_clear(PLAYLIST_VIEW);
	view_clear(QUEUE_VIEW);
	history_save(&cmd_history);
	history_free(&cmd_history);
	free(cmd_history_filename);
	tabexp_reset();
}