File: matlab-ts-mode.el

package info (click to toggle)
matlab-mode 7.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,132 kB
  • sloc: lisp: 167,753; sh: 5; makefile: 5
file content (4198 lines) | stat: -rw-r--r-- 185,146 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
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
;;; matlab-ts-mode.el --- MATLAB(R) Tree-Sitter Mode -*- lexical-binding: t -*-

;; Version: 7.1.1
;; URL: https://github.com/mathworks/Emacs-MATLAB-Mode
;; SPDX-License-Identifier: GPL-3.0-or-later
;;
;; Author: John Ciolfi <john.ciolfi.32@gmail.com>
;; Created: Jul-7-2025
;; Keywords: MATLAB

;; Copyright (C) 2025 Free Software Foundation, Inc.
;;
;; This file 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 file 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 file.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:
;;
;; Tree-sitter, https://tree-sitter.github.io/tree-sitter
;; based matlab mode: `matlab-ts-mode'
;; using https://github.com/acristoffers/tree-sitter-matlab
;;
;; Install tree-sitter-matlab by taking the matlab.EXT (EXT= .dll, .so, .dylib)
;; from the latest release of https://github.com/emacs-tree-sitter/tree-sitter-langs
;; and rename it to ~/.emacs.d/tree-sitter/libtree-sitter-matlab.EXT
;;

;;; Code:

(require 'compile)
(require 'treesit)

(require 'matlab--access)
(require 'matlab--shared)
(require 'matlab-is-matlab-file)
(require 'matlab-sections)
(require 'matlab-ts-mode--builtins)

;;; Customizations

(defgroup matlab-ts nil
  "MATLAB(R) tree-sitter mode."
  :prefix "matlab-ts-mode-"
  :group 'languages)

(defface matlab-ts-mode-pragma-face
  '((t :inherit font-lock-comment-face
       :bold t))
  "*Face to use for pragma %# lines.")

(defface matlab-ts-mode-string-delimiter-face
  '((t :inherit font-lock-string-face
       :bold t))
  "*Face to use for \\='single quote\\=' and \"double quote\" string delimiters.")

(defface matlab-ts-mode-comment-heading-face
  '((t :inherit font-lock-comment-face
       :overline t
       :bold t))
  "*Face for \"%% code section\" headings when NOT in matlab-sections-minor-mode.")

(defface matlab-ts-mode-comment-to-do-marker-face
  '((((class color) (background light))
     :inherit font-lock-comment-face
     :background "yellow"
     :weight bold)
    (((class color) (background dark))
     :inherit font-lock-comment-face
     :background "yellow4"
     :weight bold))
  ;; Note we split up the markers with spaces below so C-s when editing this file
  ;; doesn't find them.
  (concat "*Face use to highlight "
          "TO" "DO," " FIX" "ME," " and XX" "X markers ignoring case in comments.
Guidelines:
 - FIX" "ME" " and XX" "X markers should be fixed prior to committing
   code to a source repository.
 - TO" "DO markers can remain in code and be committed with the code to a
   source repository.  TO" "DO markers should reflect improvements are
   not problems with the existing code."))

(defface matlab-ts-mode-operator-face
  '((((class color) (background light)) :foreground "navy")
    (((class color) (background dark))  :foreground "LightBlue")
    (t :inverse-video t
       :weight bold))
  "*Face for operators: *, /, +, -, etc.")

(defface matlab-ts-mode-command-arg-face
  '((t :inherit font-lock-string-face
       :slant italic))
  "*Face used to highlight command dual arguments.")

(defface matlab-ts-mode-system-command-face
  '((t :inherit font-lock-builtin-face
       :slant italic))
  "*Face used to highlight \"!\" system commands.")

(defface matlab-ts-mode-property-face
  '((t :inherit font-lock-property-name-face
       :slant italic))
  "*Face used on properties, enumerations, and events.")

(defface matlab-ts-mode-number-face
  '((t :inherit font-lock-constant-face))
  "*Face used for numbers.")

(defface matlab-ts-mode-end-number-face
  '((t :inherit matlab-ts-mode-number-face
       :slant italic))
  "*Face used for \"end\" when used as an array or cell dimension number index.")

(defface matlab-function-signature-face
  '((t :inherit font-lock-type-face
       :weight bold
       :slant italic))
  "*Face used for classdef abstract method function signature declarations.")

(defface matlab-ts-mode-variable-override-builtin-face
  '((t :inherit font-lock-variable-name-face
       :underline t))
  "*Face used for variable overriding a builtin.
For example, it is valid to override the disp command:
  disp = 1:10;
and then trying to use disp to display results will not work.")

(defcustom matlab-ts-mode-font-lock-level 3
  "*Level of font lock for MATLAB code.
The \"Standard\" level plus either MLint flycheck or the MATLAB Language
Server gives all syntactic faces along with error indicators.

The \"Standard plus parse errors\" can result in too much use of the
`font-lock-warning-face' when there are syntax errors."
  :type '(choice (const :tag "Minimal" 1)
                 (const :tag "Low" 2)
                 (const :tag "Standard" 3)
                 (const :tag "Standard plus parse errors" 4)))

(defcustom matlab-ts-mode-on-save-fixes
  '(matlab-ts-mode-on-save-fix-name)
  "*List of function symbols which offer to fix *.m files on save.
During save these functions are called and will prompt to fix issues in
*.m files.  Each function gets no arguments, and returns nothing.  They
can move point, but it will be restored for them."
  :type '(repeat (choice :tag "Function: "
                         (matlab-ts-mode-on-save-fix-name))))

(defcustom matlab-ts-mode-highlight-comment-markers t
  "*Highlight triple-x, to-do, and fix-me comment markers?
See \\[matlab-ts-mode-comment-marker-help]."
  :type 'boolean)

(defcustom matlab-ts-mode-enable-mlint-flycheck t
  "*Enable MLint code analyzer via flycheck.
This requires that you install the flycheck package
https://www.flycheck.org can be installed by adding
to your ~/.emacs
  (require \\='package)
  (add-to-list \\='package-archives
               \\='(\"MELPA Stable\" . \"https://stable.melpa.org/packages/\") t)
Then restart Emacs and run
  \\[package-install] RET flycheck RET
You can also install via use-package or other methods."
  :type 'boolean)

(defcustom matlab-ts-mode-electric-ends t
  "*If t, insert end keywords to complete statements and insert % for doc comments.
For example, if you type
   classdef foo<RET>
an end statement will be inserted resulting in:
   classdef foo<RET>
       ^                  <== point here
   end
Insertion of end keywords works well when the code is
indented.  If you are editing code that is not indented,
you may wish to turn this off.

This will also add \"% \" for documentation comments.  For example,
   function foo
   % help for foo<RET>
   %
     ^                  <== \"% \" is inserted and point is here
   end"
  :type 'boolean)

;;; Global variables used in multiple code ";;; sections"

(defvar matlab-ts-mode--comment-section-heading-re
  "^[ \t]*\\(%%\\(?:[ \t].+\\)?\\)$"
  "Regexp matching \"%% headings\" lines.")

;;; Utilities

(defun matlab-ts-mode--real-node-at-point ()
  "Return \\='(pt . node) where node is not a newline.
The MATLAB tree-sitter grammar includes a newline as a node.
If we are on a newline, this will backup to a real node.
The returned point, pt, reflects that location."
  (let* ((pt (point))
         (node-at-point (treesit-node-at pt))
         ;; Handle case at end of a start node, e.g. point just after properties:
         ;;    properties
         ;;              ^
         ;;        foo;
         ;;    end
         ;; Likewise for comments
         ;;    % comment
         ;;             ^
         (real-node (if (and (equal "\n" (treesit-node-type node-at-point))
                             (> pt 1))
                        (progn
                          (setq pt (1- pt))
                          (treesit-node-at pt))
                      node-at-point)))
    (cons pt real-node)))

;;; File encoding

(defun matlab-ts-mode--check-file-encoding ()
  "Check/set file encoding.
Error is signaled if contents are corrupt because non-utf8 printable
content can crash Emacs via the matlab tree-sitter parser."

  ;; MCR check. Version info is at start.
  ;; R2025a example: V2MCC8000MEC2000MCR2000<binary-data>
  (save-excursion
    (goto-char (point-min))
    (when (looking-at "^V[0-9A-Z]+MCR[0-9]+" t)
      (fundamental-mode)
      (user-error "Not activating matlab-ts-mode because this is MATLAB Compiler Runtime content")))

  ;; We could check for utf-8 and error when non-utf8, but that may cause grief. Suppose
  ;; a malformed character is in a comment. That should be allowed.
  ;;    (when (not (string-match "utf-8" (symbol-name buffer-file-coding-system)))
  ;;       (user-error "Buffer does not have utf-8 encoding"))
  ;; Note we cannot
  ;;       (set-buffer-file-coding-system 'utf-8))
  ;; because this would modify it and modes shouldn't modify the buffer.

  (let ((bad-char-point (save-excursion
                          (goto-char (point-min))
                          ;; Due to the matlab-ts-mode syntax table entry
                          ;;      (modify-syntax-entry ?\n ">"     st)
                          ;; [:space:] doesn't match newlines.
                          (when (re-search-forward "[^[:print:][:space:]\n\r]" nil t)
                            (point)))))
    (when bad-char-point
      (fundamental-mode)
      (goto-char bad-char-point)
      (user-error
       "Not entering matlab-ts-mode due to non-printable utf8 character \"%c\" at point %d"
       (char-before) bad-char-point ))))

;;; Syntax table

(defvar matlab-ts-mode--syntax-table
  (let ((st (make-syntax-table (standard-syntax-table))))
    ;; Comment Handling:
    ;; 1. Single line comments: % text (single char start),
    ;;                          note includes "%{ text"
    ;; 2. Multiline comments:   %{
    ;;                            lines
    ;;                          %}
    ;; 3. Ellipsis line continuations comments: "... optional text"
    ;;    are handled in `matlab-ts-mode--syntax-propertize'
    (modify-syntax-entry ?%  "< 13"  st)
    (modify-syntax-entry ?{  "(} 2c" st)
    (modify-syntax-entry ?}  "){ 4c" st)
    ;; \n is a comment ender. Therefore, regex [:space:] won't recognize \n
    (modify-syntax-entry ?\n ">"     st)

    ;; String Handling:
    ;;   Single quoted string (character vector):    'text'
    ;;   Double-quoted string:                       "text"
    ;;   Transpose:           varname'
    ;;   Quoted quotes:       ' don''t '    or " this "" "
    ;;   Unterminated Char V: ' text
    (modify-syntax-entry ?'  "\"" st)
    (modify-syntax-entry ?\" "\"" st)

    ;; Words and Symbols:
    (modify-syntax-entry ?_  "_" st)

    ;; Punctuation:
    (modify-syntax-entry ?\\ "." st)
    (modify-syntax-entry ?\t " " st)
    (modify-syntax-entry ?+  "." st)
    (modify-syntax-entry ?-  "." st)
    (modify-syntax-entry ?*  "." st)
    (modify-syntax-entry ?/  "." st)
    (modify-syntax-entry ?=  "." st)
    (modify-syntax-entry ?<  "." st)
    (modify-syntax-entry ?>  "." st)
    (modify-syntax-entry ?&  "." st)
    (modify-syntax-entry ?|  "." st)

    ;; Parenthetical blocks:
    ;;   Note: these are in standard syntax table, repeated here for completeness.
    (modify-syntax-entry ?\(  "()" st)
    (modify-syntax-entry ?\)  ")(" st)
    (modify-syntax-entry ?\[  "(]" st)
    (modify-syntax-entry ?\]  ")[" st)
    (modify-syntax-entry ?{   "(}" st)
    (modify-syntax-entry ?}   "){" st)

    st)
  "The matlab-ts-mode syntax table.")

(defun matlab-ts-mode--put-char-category (pos category)
  "At character POS, put text property CATEGORY."
  (when (not (eobp))
    (put-text-property pos (1+ pos) 'category category)
    (put-text-property pos (1+ pos) 'mcm t)))

(defmacro matlab-ts-mode--syntax-symbol (symbol syntax doc)
  "Create a new SYMBOL with DOC used as a text property category with SYNTAX."
  (declare (indent defvar) (debug (sexp form sexp)) (doc-string 3))
  `(progn (defconst ,symbol ,syntax ,doc)
          (put ',symbol 'syntax-table ,symbol)))

;; In the Syntax Table descriptors, "<" is for comments
(matlab-ts-mode--syntax-symbol matlab-ts-mode--ellipsis-syntax (string-to-syntax "<")
                               "Syntax placed on ellipsis to treat them as comments.")

(defun matlab-ts-mode--syntax-propertize (&optional start end)
  "Scan region between START and END to add properties.
If region is not specified, scan the whole buffer.
This will mark ellipsis line continuation's
  ... optional text
as comments which is how they are treated by MATLAB."
  (save-match-data ;; avoid 'Syntax Checking transmuted the match-data'
    (save-excursion
      ;; Scan region, but always expand to beginning of line
      (goto-char (or start (point-min)))
      (beginning-of-line)

      ;; Edits can change what properties characters can have so remove ours and reapply
      (remove-text-properties (point) (save-excursion (goto-char (or end (point-max)))
                                                      (end-of-line) (point))
                              '(category nil mcm nil))

      ;; Tell Emacs that ellipsis (...) line continuations are comments.
      (while (and (not (>= (point) (or end (point-max)))) (not (eobp)))
        (if (treesit-search-forward-goto (treesit-node-at (point))
                                         (rx bos "line_continuation" eos)
                                         t) ;; goto start of: ... optional text
            (matlab-ts-mode--put-char-category (point) 'matlab-ts-mode--ellipsis-syntax)
          (goto-char (point-max)))))))

;;; font-lock

(defvar matlab-ts-mode--keywords
  ;; Nodes like "if" are captured by their text because they are part of a bigger node that captures
  ;; them as such (and need more than just their text to define the node), but it doesn't make much
  ;; sense to create a node for the text "break", "continue", etc. because that would create two
  ;; nodes for the same purpose, where one is sufficient.  In other words, "break" like nodes are
  ;; captured as named nodes, not as unnamed ones, so you need to use their node names instead of
  ;; the "content".  See https://github.com/acristoffers/tree-sitter-matlab/issues/25
  ;;
  ;; Keywords are documented here https://www.mathworks.com/help/matlab/ref/iskeyword.html
  ;; Note, arguments, methods, properties are semi-keywords in that in the right location
  ;; the are keywords, otherwise in the wrong location they are variables, but tree-sitter
  ;; correctly handles them by letting us look for these as content of the nodes.
  '("arguments"
    (break_statement)
    "case"
    "catch"
    "classdef"
    (continue_statement)
    "else"
    "elseif"
    "end"
    "enumeration"
    "events"
    "for"
    "function"
    "get." ;; when used in a classdef method, e.g. function value = get.propName(obj)
    "global"
    "if"
    "methods"
    "otherwise"
    "parfor"
    "persistent"
    "properties"
    (return_statement)
    "set." ;; when used in a classdef method, e.g. function obj = set.propName(obj, val)
    "spmd"
    "switch"
    "try"
    "while")
  "The matlab-ts-mode font-lock keywords.")

(defvar matlab-ts-mode--operators
  ;; https://www.mathworks.com/help/matlab/matlab_prog/matlab-operators-and-special-characters.html
  '("+"         ;; Addition or Unary plus, +value
    "-"         ;; Subtraction or Unary minus, -value
    ".*"        ;; Element-wise multiplication
    "*"         ;; Matrix multiplication
    "./"        ;; Element-wise right division
    "/"         ;; Matrix right division
    ".\\"       ;; Element-wise left division
    "\\"        ;; Matrix left division (also known as backslash)
    ".^"        ;; Element-wise power
    "^"         ;; Matrix power
    ".'"        ;; Transpose
    "'"         ;; Complex conjugate transpose
    "=="        ;; Equal to
    "~="        ;; Not equal to
    ">"         ;; Greater than
    ">="        ;; Greater than or equal to
    "<"         ;; Less than
    "<="        ;; Less than or equal to
    "&"         ;; Find logical AND
    "|"         ;; Find logical OR
    "&&"        ;; Find logical AND (with short-circuiting)
    "||"        ;; Find logical OR (with short-circuiting)
    "~"         ;; Find logical NOT
    "@"         ;; Create anonymous functions and function handles, call superclass methods
    ;; "!"      ;; "!" is like an operator, but has command-dual like syntax, so handled elsewhere
    "?"         ;; Retrieve metaclass information for class name
    "~"         ;; Represent logical NOT, suppress specific input or output arguments.
    "="         ;; Variable creation and indexing assignment.
    "<" "&"     ;; Specify one or more superclasses in a class definition.
    ".?"        ;; Specify the fields of a name-value structure as the names of all
    ;;           ;   writable properties of the class.
    ;;           ;   However, this isn't parsed correctly by matlab tree-sitter, see
    ;;           ;   https://github.com/acristoffers/tree-sitter-matlab/issues/35
    )
  "The matlab-ts-mode font-lock operators.")

(defvar matlab-ts-mode--type-functions
  '("double"
    "single"
    "int8"
    "int16"
    "int32"
    "int64"
    "uint8"
    "uint16"
    "uint32"
    "uint64")
  "The matlab-ts-mode data type functions.")

(cl-defun matlab-ts-mode--get-doc-comment-candidate (comment-node)
  "Get candidate doc comment node or nil.
Return a comment node based on COMMENT-NODE if it is a candidate for a
help doc comment."

  ;; Backup over a copyright comment line
  (when (string-match-p "\\`[ \t]*%[ \t]*copyright\\b"
                        (treesit-node-text comment-node))
    (setq comment-node (treesit-node-prev-sibling comment-node))
    (when (not (string= "comment" (treesit-node-type comment-node)))
      (cl-return-from matlab-ts-mode--get-doc-comment-candidate)))

  (let ((prev-node (treesit-node-prev-sibling comment-node)))
    (when prev-node
      (while (string-match-p (rx bos "line_continuation" eos)
                             (treesit-node-type prev-node))
        (setq prev-node (treesit-node-prev-sibling prev-node)))
      (let ((prev-type (treesit-node-type prev-node)))
        ;; The true (t) cases. Note line continuation ellipsis are allowed.
        ;;    function foo          function foo(a)
        ;;    % doc comment         % doc comment
        ;;    end                   end
        (when (or (string-match-p (rx bos (or
                                           "function_arguments" ;; function input args?
                                           "superclasses")      ;; subclass
                                      eos)
                                  prev-type)
                  (and (string= prev-type "identifier")           ;; id could be a fcn or class id
                       (let* ((prev-sibling (treesit-node-prev-sibling prev-node))
                              (prev-type (and prev-sibling (treesit-node-type prev-sibling))))
                         (and prev-type
                              (or
                               (string-match-p
                                (rx bos
                                    (or "function"         ;; fcn without in and out args
                                        "function_output"  ;; fcn w/out args and no in args
                                        "classdef")        ;; base class
                                    eos)
                                prev-type)
                               (and (string= prev-type "attributes")
                                    (equal (treesit-node-type (treesit-node-parent prev-sibling))
                                           "class_definition")))))))
          comment-node)))))

(defun matlab-ts-mode--is-doc-comment (comment-node parent)
  "Is the COMMENT-NODE under PARENT a help doc comment.
In MATLAB,

  function out = myFunction
  % The documentation help comment for myFunction immediately follows the
  % function definition.

      % code comments are preceded with a blank line
      out = 1;
  end

  function out = myFunction
  % The documentation help comment for myFunction immediately follows the
  % function definition.

  % copyright at column 0 and preceded by blank lines after the help comment

      % code comments are preceded with a blank line
      out = 1;
  end

  function out = myFunctionWithoutHelp

      % code comments are preceded with a blank line
      out = 1;
  end

Similar behavior for classdef's."

  (setq comment-node (matlab-ts-mode--get-doc-comment-candidate comment-node))
  (when (and comment-node
             (string-match-p (rx bos (or "function_definition" "class_definition") eos)
                             (treesit-node-type parent)))
    (let ((definition-point (treesit-node-start parent)))
      (save-excursion
        (goto-char (treesit-node-start comment-node))
        (beginning-of-line)

        ;; result - is doc comment?
        (or (<= (point) definition-point) ;; at definition?
            (and (> (point) definition-point)
                 (not (re-search-backward "^[ \t]*$" definition-point t))))))))

(defun matlab-ts-mode--doc-comment-capture (comment-node override start end &rest _)
  "Fontify function/classdef documentation comments.
COMMENT-NODE is the tree-sitter node from a treesit-font-lock-rules rule
and OVERRIDE is from that rule.  START and END specify the region to be
fontified which could be smaller or larger than the COMMENT-NODE
start-point and end-point."
  (when (matlab-ts-mode--is-doc-comment comment-node (treesit-node-parent comment-node))
    (treesit-fontify-with-override
     (treesit-node-start comment-node) (treesit-node-end comment-node)
     font-lock-doc-face override start end)))

(defun matlab-ts-mode--comment-heading-capture (comment-node override start end &rest _)
  "Fontify the \"%% heading\" start line in COMMENT-NODE.
COMMENT-NODE is the tree-sitter node from a treesit-font-lock-rules rule
and OVERRIDE is from that rule.  START and END specify the region to be
fontified which could be smaller or larger than the COMMENT-NODE
start-point and end-point."
  (save-excursion
    (goto-char (treesit-node-start comment-node))
    (beginning-of-line)
    (when (looking-at matlab-ts-mode--comment-section-heading-re)
      (let ((heading-start (match-beginning 1))
            (heading-end (match-end 1)))
        (treesit-fontify-with-override heading-start heading-end
                                       'matlab-ts-mode-comment-heading-face
                                       override start end)))))

(defvar matlab-ts-mode--comment-markers
  (list (concat "XX" "X")
        (concat "FIX" "ME")
        (concat "TO" "DO")))

(defvar matlab-ts-mode--comment-markers-re
  (rx-to-string `(seq word-start (group (or ,@matlab-ts-mode--comment-markers) word-end))))

(defun matlab-ts-mode--comment-to-do-capture (comment-node override start end &rest _)
  "Fontify triple-x, fix me, and to do markers in comments.
For guidelines on using these comment markers see:
  \\[matlab-ts-mode-comment-marker-help]
COMMENT-NODE is the tree-sitter comment node from a
treesit-font-lock-rules rule and OVERRIDE is from that rule.  START and
END specify the region to be fontified which could be smaller or larger
than the COMMENT-NODE start-point and end-point."
  (when matlab-ts-mode-highlight-comment-markers
    (save-excursion
      (let ((comment-end (treesit-node-end comment-node)))
        (goto-char (treesit-node-start comment-node))
        (while (< (point) comment-end)
          ;; Note, the markers below have spaces in them so we don't find them when searching "C-s"
          ;; while editing this file.
          (if (re-search-forward matlab-ts-mode--comment-markers-re comment-end t)
              (let ((keyword-start (match-beginning 1))
                    (keyword-end (match-end 1)))
                (treesit-fontify-with-override keyword-start keyword-end
                                               'matlab-ts-mode-comment-to-do-marker-face
                                               override start end))
            (goto-char comment-end)))))))

(defun matlab-ts-mode--namespace-builtins-capture (namespace-node override start end &rest _)
  "Fontify foo.bar.goo when it is a builtin function.
NAMESPACE-NODE is the tree-sitter field_expression or a superclass
property_name node.  These nodes have children that for a PATH,
e.g. \"foo.bar.goo\".  This is connected to the namespace-builtins
treesit-font-lock-rules rule and OVERRIDE is from that rule.  START and
END specify the region to be fontified which could be smaller or larger
than the FILED-EXPRESSION-NODE start-point and end-point."
  (let ((children (treesit-node-children namespace-node))
        (path "")) ;; The "path" of NAMESPACE, e.g. foo.bar.goo
    (cl-loop for child in children do
             (let ((child-type (treesit-node-type child)))
               (cond
                ;; Case: (identifier) or "."
                ((or (string= child-type "identifier")
                     (string= child-type "."))
                 (setq path (concat path (treesit-node-text child))))
                ;; Case: (function_call)
                ((string= child-type "function_call")
                 (let ((fcn-name-node (treesit-node-child-by-field-name child "name")))
                   (setq path (concat path (treesit-node-text fcn-name-node)))))
                ;; Case: other - shouldn't be able to get here, but be safe.
                (t
                 (cl-return)))))
    (let ((builtin-type (gethash path matlab-ts-mode--builtins-ht)))
      (when builtin-type
        (let ((builtin-start (treesit-node-start namespace-node))
              builtin-end
              prop-start
              prop-end)
          (if (eq builtin-type t)
              (setq builtin-end (+ builtin-start (length path)))
            ;; builtin-type is 'property or 'enumeration
            (when (not (string-match "\\`\\(.+\\.\\)\\([^.]+\\)\\'" path))
              (error "Assert: failed to parse path, %s" path))
            (setq builtin-end (+ builtin-start (- (length (match-string 1 path)) 2)))
            ;; We give the "." before the property or enum font-lock-delimiter-face, hence the +2.
            (setq prop-start (+ builtin-end 2))
            (setq prop-end (+ prop-start (length (match-string 2 path)))))

          (treesit-fontify-with-override builtin-start builtin-end 'font-lock-builtin-face
                                         override start end)
          (when prop-start
            (treesit-fontify-with-override prop-start prop-end 'matlab-ts-mode-property-face
                                           override start end)))))))

(defun matlab-ts-mode--is-fcn-name-value (identifier-node)
  "Return t if IDENTIFIER-NODE is a function name-value property."
  (let ((next-sibling (treesit-node-next-sibling identifier-node)))
    (and next-sibling
         (string= (treesit-node-text next-sibling) "="))))

(defun matlab-ts-mode--is-identifier-builtin (identifier-node)
  "Return t if IDENTIFIER-NODE is a function provided with MATLAB."
  (let ((parent (treesit-node-parent identifier-node)))
    ;; Consider
    ;;    foo.bar.disp.goo = 1;  % both foo and disp are builtin functions, but in this case fields
    ;;    foo.bar(1)             % +foo/bar.m - bar is a builtin, but foo.bar(1) is not.
    (when (and (not (equal (treesit-node-type parent) "field_expression"))
               (not (equal (treesit-node-type (treesit-node-parent parent)) "field_expression")))
      (let ((id (treesit-node-text identifier-node)))
        (gethash id matlab-ts-mode--builtins-ht)))))

(defun matlab-ts-mode--is-command-builtin (command-node)
  "Return t if COMMAND-NODE is a function provided with MATLAB."
  (let ((command (treesit-node-text command-node)))
    (gethash command matlab-ts-mode--builtins-ht)))

(defun matlab-ts-mode--is-variable-overriding-builtin (variable-node)
  "Is VARIABLE-NODE overriding a builtin?
Example, disp variable is overriding the disp builtin function:
   disp = 1:10;"
  (let ((variable (treesit-node-text variable-node)))
    (or (gethash variable matlab-ts-mode--builtins-ht)
        ;; Initially arguments, etc. capabilities didn't exist in MATLAB. When they were added,
        ;; compatibility was kept when these were used as variables. So, they are "semi-keywords".
        (string-match-p (rx bos (or "arguments" "enumeration" "events" "methods" "properties") eos)
                        (treesit-node-text variable-node)))))

(defvar matlab-ts-mode--font-lock-settings
  (treesit-font-lock-rules

   ;; F-Rule: Comments and line continuation: ... optional text
   :language 'matlab
   :feature 'comment
   '(
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_types.m
     (comment) @font-lock-comment-face
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_fcn.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_fcn_g2.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_continuation_multiArgFcn.m
     (line_continuation) @font-lock-comment-face)

   ;; F-Rule: special comments that override normal comment font
   :language 'matlab
   :feature 'comment-special
   :override t
   '(;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_pragma_in_fcn.m
     ((comment) @matlab-ts-mode-pragma-face
      (:match "\\`%#.+\\'" @matlab-ts-mode-pragma-face)) ;; %#pragma's
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_heading.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_sections.m
     ((comment) @matlab-ts-mode--comment-heading-capture) ;; %% comment section heading
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_no_doc_help.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_comment_fcn.m
     (function_definition (comment) @matlab-ts-mode--doc-comment-capture) ;; doc help comments
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MyClass.m
     (class_definition (comment) @matlab-ts-mode--doc-comment-capture)) ;; doc help comments

   ;; F-Rule: to do, fix me, triple-x marker comment keywords
   ;; See: test-matlab-ts-mode-font-lock-files/font_lock_comment_markers.m
   :language 'matlab
   :feature 'comment-marker
   :override t
   '(((comment) @matlab-ts-mode--comment-to-do-capture)
     ((line_continuation) @matlab-ts-mode--comment-to-do-capture))

   ;; F-Rule: Constant literal numbers, e.g. 1234, 12.34, 10e10
   ;; We could use this for items like true, false, pi, etc. See some of these numbers in:
   ;;   https://www.mathworks.com/content/dam/mathworks/fact-sheet/
   ;;   matlab-basic-functions-reference.pdf
   ;; however, they do show up as builtins, which to me seems more accurate.
   ;; This rule needs to come before the "F-Rule: keywords: if, else, end, etc." because
   ;; we want the end_keyword when used as a number index into a cell/matrix to be a number font.
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_numbers.m
   :language 'matlab
   :feature 'number
   '(((number) @matlab-ts-mode-number-face)
     ((end_keyword) @matlab-ts-mode-end-number-face))

   ;; F-Rule: variable
   ;; Could add font-lock-variable-name-face to variable uses.  Consider
   ;;     i1 = [1, 2];
   ;;     i2 = i1(1) + i3 + i4(i3);
   ;; we know i1 and i2 are variables from the (assignment left: (identifier))
   ;; However, we don't know if i3 or i4 are variables or functions because a function
   ;; can be called with no arguments, e.g. to call i3 function use i3 or i3(). i4 could
   ;; be a variable indexed by i1 or a function.
   ;;
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_variable.m
   :language 'matlab
   :feature 'variable
   '(((assignment left: (identifier) @matlab-ts-mode-variable-override-builtin-face
                  (:pred matlab-ts-mode--is-variable-overriding-builtin
                         @matlab-ts-mode-variable-override-builtin-face)))
     (assignment left: (identifier) @font-lock-variable-name-face)
     (multioutput_variable (identifier) @matlab-ts-mode-variable-override-builtin-face
                           (:pred matlab-ts-mode--is-variable-overriding-builtin
                                  @matlab-ts-mode-variable-override-builtin-face))
     (multioutput_variable (identifier) @font-lock-variable-name-face)
     (global_operator (identifier) @matlab-ts-mode-variable-override-builtin-face
                      (:pred matlab-ts-mode--is-variable-overriding-builtin
                             @matlab-ts-mode-variable-override-builtin-face))
     (global_operator (identifier) @font-lock-variable-name-face)
     (persistent_operator (identifier) @matlab-ts-mode-variable-override-builtin-face
                          (:pred matlab-ts-mode--is-variable-overriding-builtin
                                 @matlab-ts-mode-variable-override-builtin-face))
     (persistent_operator (identifier) @font-lock-variable-name-face)
     (for_statement (iterator (identifier) @matlab-ts-mode-variable-override-builtin-face
                              (:pred matlab-ts-mode--is-variable-overriding-builtin
                                     @matlab-ts-mode-variable-override-builtin-face)))
     (for_statement (iterator (identifier) @font-lock-variable-name-face))
     ;; Function inputs: functionName(in1, in2, in3)
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_in_args.m
     (function_arguments arguments:
                         (identifier)      @font-lock-variable-name-face
                         ("," (identifier) @font-lock-variable-name-face) :*)
     ;; Function single output argument: function out = functionName(in1, in2)
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_out_args.m
     (function_output (identifier) @font-lock-variable-name-face)
     ;; Function multiple output arguments: function [out1, out2] = functionName(in1, in2)
     (function_output (multioutput_variable (identifier) @font-lock-variable-name-face))
     ;; Enumeration's
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_enum.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_enum_FlowRate.m
     (enum (identifier) @matlab-ts-mode-property-face)
     ;; Events block in classdef
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_events.m
     (events (identifier) @matlab-ts-mode-property-face)
     ;; Namespaces, structs, classdef methods/property access. Note any keyword is allowed,
     ;; e.g. foo.methods.function = 1;
     (field_expression (identifier) @default))

   ;; F-Rule: keywords: if, else, end, etc.
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_keywords.m
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_methods.m
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_keyword_spmd.m
   :language 'matlab
   :feature 'keyword
   `([,@matlab-ts-mode--keywords] @font-lock-keyword-face)

   ;; F-Rule: Types, e.g. int32()
   :language 'matlab
   :feature 'type
   `((function_call name: (identifier)
                    @font-lock-type-face
                    (:match ,(rx-to-string `(seq bos
                                                 (or ,@matlab-ts-mode--type-functions)
                                                 eos)
                                           t)
                            @font-lock-type-face))
     (property name: (identifier) (identifier) @font-lock-type-face :?)
     (property name: (property_name (identifier)) (identifier) @font-lock-type-face :?))

   ;; F-Rule: namespaces (the +dir's, class methods, etc.)
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_namespaces.m
   :language 'matlab
   :feature 'namespace-builtins
   :override t
   `((superclasses (property_name) @matlab-ts-mode--namespace-builtins-capture)
     (field_expression) @matlab-ts-mode--namespace-builtins-capture)

   ;; F-Rule: factory items that come with MATLAB, Simulink, or add-on products
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_builtins.m
   :language 'matlab
   :feature 'builtins
   `(((identifier) @font-lock-builtin-face
      (:pred matlab-ts-mode--is-identifier-builtin @font-lock-builtin-face))
     ((command_name) @font-lock-builtin-face
      (:pred matlab-ts-mode--is-command-builtin @font-lock-builtin-face)))

   ;; F-Rule: function/classdef and items defining them, e.g. the function arguments
   :language 'matlab
   :feature 'definition
   '(
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_issue55_abstract.m
     (function_signature name: (identifier) @matlab-function-signature-face)
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_small_no_args.m
     (function_definition name: (identifier) @font-lock-function-name-face)
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_symPosDef.m
     (class_definition name: (identifier) @font-lock-function-name-face)
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MySubClass.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_MySubSubClass.m
     (superclasses (property_name (identifier)) @font-lock-function-name-face)
     ;; Fields of: arguments ... end , properties ... end
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_arguments.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_properties.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_MultiplePropBlocks.m
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_prop_access.m
     (property (validation_functions (identifier) @font-lock-function-call-face))
     (property name: (identifier) @matlab-ts-mode-property-face)
     (property name: (property_name (identifier) @matlab-ts-mode-property-face))
     ;; Attributes of properties, methods
     ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_class_attributes.m
     (attribute (identifier) @font-lock-type-face "=" (identifier) @font-lock-builtin-face)
     (attribute (identifier) @font-lock-type-face))

   ;; F-Rule: validation functions from namespace
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_arguments2_issue57.m
   :language 'matlab
   :feature 'definition
   :override t
   '((property (validation_functions (field_expression (identifier) @font-lock-function-call-face)))
     (property (validation_functions ((field_expression
                                       (function_call name: (identifier)
                                                      @font-lock-function-call-face))))))

   ;; F-Rule: Function Name = Value arguments
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_fcn_name_value_properties.m
   :language 'matlab
   :feature 'fcn-name-value
   '(((function_call (arguments (identifier) @matlab-ts-mode-property-face))
      (:pred matlab-ts-mode--is-fcn-name-value @matlab-ts-mode-property-face)))

   ;; F-Rule: command dual arguments
   :language 'matlab
   :feature 'command-arg
   '((command_argument) @matlab-ts-mode-command-arg-face)

   ;; F-Rule: system and command dual commands.
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_command.m
   :language 'matlab
   :feature 'command-name
   '(((command_name) @matlab-ts-mode-system-command-face
      ;; System command: ! ls *.m *.txt
      (:match "^!" @matlab-ts-mode-system-command-face))
     ;; Command-dual with at least one arg: myFunction arg
     ;; Commands with no args could be a variable or a function
     ((command (command_name) @font-lock-function-call-face (command_argument))))

   ;; F-Rule: strings "double quote" and 'single quote'
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_strings.m
   :language 'matlab
   :feature 'string
   '((string_content) @font-lock-string-face
     ((string_content) ["\"" "'"]) @matlab-ts-mode-string-delimiter-face
     (string ["\"" "'"] @matlab-ts-mode-string-delimiter-face)
     (escape_sequence) @font-lock-escape-face
     (formatting_sequence) @font-lock-escape-face)

   ;; F-rule: operators: *, /, +, -, etc.
   ;; Note, this rule must come after the string rule because single quote (') can be a transpose or
   ;; string delimiter.
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_operators.m
   :language 'matlab
   :feature 'operator
   `([,@matlab-ts-mode--operators] @matlab-ts-mode-operator-face)

   ;; F-Rule: Brackets
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_brackets.m
   :language 'matlab
   :feature 'bracket
   '((["(" ")" "[" "]" "{" "}"]) @font-lock-bracket-face)

   ;; F-Rule: Delimiters, e.g. semicolon
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_delimiters.m
   :language 'matlab
   :feature 'delimiter
   '((["." "," ":" ";"]) @font-lock-delimiter-face)

   ;; F-Rule: Syntax errors
   ;; Some errors span too much of the buffer's text, so one will probably not want this
   ;; enabled. Perhaps, once https://github.com/acristoffers/tree-sitter-matlab/issues/36
   ;; is fixed we can enable this, though a lot more testing is needed.
   ;;
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_error.m
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_error_small.m
   ;; See: tests/test-matlab-ts-mode-font-lock-files/font_lock_error_missing_continuation.m
   :language 'matlab
   :feature 'syntax-error
   :override t
   '((ERROR) @font-lock-warning-face)
   )
  "The matlab-ts-mode font-lock settings.")

;;; Indent

;; MATLAB Indent Standard
;;
;; Having one-style of consistent indentation makes reading others' code easier and thus
;; we do not provide indent customization.
;;
;; 1. Indent level of 4 spaces, no TAB characters, unicode, LF line-endings (no CRLF)
;;
;; 2. Code and comments should fit within 100 columns.A line may exceed 100 characters if it
;;    improves code readability.
;;
;;    In general, too much logic on a given line hurts readability.  Reading the first part of a
;;    line should convey the operation being performed by the line.  Adding unrelated concepts on a
;;    give line hurts readability. Hence the recommendation that lines are not too long.
;;
;;    The indent engine should NOT automatically re-flow lines to fit within 100 columns.
;;
;;    Consider the following where the row content causes the column width to be 105.
;;    Re-flowing would hurt readability.
;;
;;        mat = [ ...
;;                <row-1>;
;;                <row-2>;
;;                ...
;;                <row-N>;
;;              ]
;;
;;    Consider the following where the model/path/to/block causes the line to be greater than
;;    100. Re-flowing will hurt readability.
;;
;;      set_param(...
;;          'model/path/to/block', ...
;;          'Parameter', 'Value')
;;
;;    Adding the ability to explicitly re-flowing of code in a region, similar to the way M-q or
;;    `fill-paragraph' works in a comment, would be a nice addition.
;;
;; 3. Use 2-space offset for case labels.  The code under case or otherwise statements is one
;;    condition and hence should have the same indent level anchored from the switch statement.
;;    The level of complexity of the following two statements is the same which is clear from
;;    the level of indent of the doIt function call.
;;
;;    if condition1 == 1      |     switch condition1
;;       doIt                 |       case 1
;;    end                     |         doIt
;;                            |     end
;;
;; 4. Cells and arrays contain data and have indent level of 2 spaces.
;;
;;    Indents cells and array with an inner indent level of 2 spaces for the data. Cells and arrays
;;    which are structured data. Since there's no "conditionals" within structured data, we treat
;;    the nesting in structured data like labels and indent by 2 spaces. Also, data is aligned with
;;    the opening parenthesis or bracket. Example:
;;
;;      myCell = { ...
;;                 {1, 2, 3}, ...
;;                 { ...
;;                   [4, 5; ...
;;                    6, 7] ...
;;                 } ...
;;               }
;;
;; 5. Operator padding.
;;
;;    - Use a single space after (but not before) a comma.
;;
;;    - Use a single space on each side of binary operators (such as +), except for member
;;      operators.
;;
;;    - Do not use any space between member operators and their operands. For example: a.b
;;
;;    - Do not use any space between a unary operator and its operand. For example: -10
;;
;;    - Language keywords should have a space after them. For example: if (cond)
;;
;;    Example:
;;
;;        function out2 = myFcn(in1, in2)
;;            if (in1 > 1 && in2 > 1) || in2 > -10
;;                out1 = in1 * in2;
;;            else
;;                out1 = 0;
;;            end
;;        end
;;
;;    TODO [future] add operator padding to indent engine
;;
;; 6. Function call formats
;;    - On a single line:
;;
;;         [result1, result2] = myFunction(arg1, arg2)
;;
;;    - On multiple lines, aligning subsequent lines after the opening parenthesis:
;;
;;         [result1, result2] = myFunction(arg1, ...
;;                                         arg2)
;;
;;
;;
;;    - On multiple lines, aligning subsequent lines with 4 additional spaces
;;
;;         [result1, result2] = myFunction( ...
;;             arg1, arg2)
;;
;;    This is invalid:
;;       [result1, result2] = myFunction(arg1, ...
;;           arg2)                                     % arg2 should be aligned with arg1
;;
;; 7. Function definition formats
;;
;;    - On a single line
;;         function [out1, out2] = myFunction(in1, in2)
;;
;;    - Aligned on multiple lines
;;
;;         function ...
;;             [out1, ...         % comment
;;              out2] ...         % comment
;;             = myFunction ...
;;             (in1, ...          % comment
;;              in2)              % comment
;;
;; 8. Expressions
;;
;;    When you have long expressions, be consistent in how you break up the lines and minimize use
;;    of newlines. Use newlines to help with readability. Place operators at the end of a line,
;;    rather than at the beginning of a line.
;;
;;    Operators should never be at the start of a line in an expression which indicates that
;;    the expression continues. For example the && is at the end of the 1st line
;;    and not the start of the 2nd line:
;;
;;     if (thisOneThing > thisOtherLongLongLongLongLongLongThing &&
;;         aThirdThing == aFourthLongLongLongLongLongLongThing)
;;
;;         % code
;;     end
;;
;;    You can use extra newlines when it helps with readability, e.g.
;;
;;     if (c > 30 &&  % is cost per unit must be high?
;;         d > 40)    % and distance traveled high?
;;
;;         // code
;;     end
;;
;;    Use parentheses to clarify the intended precedence of "&&" and "||".
;;    For example:
;;
;;     if (c > 30 || (a > 10 && b > 20))
;;
;;     end
;;
;;    Do not overuse parentheses. Don't add them when they are not needed.  Overuse of parentheses
;;    can clutter code and reduce its readability.  Use of parentheses is a indicator that standard
;;    operator precedence rules are not in use, for example, "a = b * (c + d)" indicates to the
;;    reader that standard operator precedence is not in use.
;;
;;    As a guideline, use the minimum number of parentheses, except for
;;    parenthesis to clarify the precedence of "&&" and "||" or more
;;    generally, if in doubt about operator precedence, parenthesize.
;;
;;    Examples:
;;
;;     % Good                           % Bad: too many parens
;;     if (c > 30 && d > 40) || e       if (((c > 30) && (d > 40)) || e)
;;     end                              end
;;
;;
;; 9. Consecutive statement alignment
;;
;;    Be consistent in the alignment of consecutive statements. For example,
;;
;;        width  = 5;
;;        length = 10;
;;        area   = width * length;
;;
;;    alternatively you can un-align them:
;;
;;        width = 5;
;;        length = 10;
;;        area = width * length;
;;
;;    Don't mix the alignment
;;
;;        width  = 5;
;;        length = 10;
;;        area = width * length;   % Bad partially aligned
;;
;;     TODO [future] add consecutive statement alignment to the indent engine
;;
;; 10. Align consecutive trailing comments
;;
;; 11. Function/classdef doc help should be aligned with the function/classdef keyword.
;;
;; 12. Tabular data alignment
;;
;;     Be consistent in data alignment, either aligned:
;;
;;      table1 = [1,      2;
;;                1000,   1.9;
;;                100000, 1.875];
;;     or un-aligned
                                        ;
;;      table1 = [1, 2;
;;                1000, 1.9;
;;                100000, 1.875];
;;
;;     TODO [future] add an alignment directive, %$align
;;
;;     Alignment of tabular data should be done when there's an indent
;;     directive, perhaps named %$align which must precede the data to be
;;     aligned. For example, table1 would have it's columns aligned,
;;     whereas table2 would not:
;;
;;      %         Units   Cost   (%$align)
;;      %         -----   -----
;;      table1 = [1,      2;
;;                1000,   1.9;
;;                100000, 1.875];
;;
;; 13. Indent must follow the above rules when the code has syntax errors.

(defvar matlab-ts-mode--indent-level 4
  "Indentation level.")
(defvar matlab-ts-mode--switch-indent-level (/ matlab-ts-mode--indent-level 2)
  "Indentation level for switch-case statements.")
(defvar matlab-ts-mode--array-indent-level 2
  "Indentation level for elements in an array.")

(defvar matlab-ts-mode--i-error-row-matcher-pair)

(defun matlab-ts-mode--i-error-row-matcher (_node _parent bol &rest _)
  "Is point within an ERROR node and can we determine indent?
If so, set `matlab-ts-mode--i-error-row-matcher-pair' to the anchor and
offset we should use and return non-nil.  BOL, beginning-of-line point,
is where we start looking for the error node."
  ;; 1) Given
  ;;            mat = [ [1, 2]; [3, 4];
  ;;        TAB>
  ;;    we have parse tree
  ;;        (ERROR (identifier) = [
  ;;         (row
  ;;          (matrix [
  ;;           (row (number) , (number))
  ;;           ]))
  ;;         ;
  ;;         (row
  ;;          (matrix [
  ;;           (row (number) , (number))
  ;;           ]))
  ;;         ;)
  ;;
  ;; 2) Now add ellipsis continuation:
  ;;            mat = [ [1, 2]; [3, 4]; ...
  ;;        TAB>
  ;; we'll have parse tree
  ;;       (source_file
  ;;        (ERROR (identifier) = [
  ;;         (row
  ;;          (matrix [
  ;;           (row (number) , (number))
  ;;           ]))
  ;;         ;
  ;;         (row
  ;;          (matrix [
  ;;           (row (number) , (number))
  ;;           ]))
  ;;         ;)
  ;;        (line_continuation))
  ;; Notice the line_continuation is not under the ERROR node, so we need to find that,
  ;; hence below we navigate over line_continuation's.
  ;;
  ;; See https://github.com/acristoffers/tree-sitter-matlab/issues/46

  (save-excursion
    (goto-char bol)

    (when (string= (treesit-node-type (treesit-node-at (point))) "\n")
      (re-search-backward "[^ \t\n\r]" nil t))

    ;; Move inside the error node if at an error node.
    (when (string= (treesit-node-type (treesit-node-at (point))) "ERROR")
      (re-search-backward "[^ \t\n\r]" nil t))

    ;; If on a "[" or "{" move back (we don't want to shift the current line)
    (when (string-match-p (rx bos (or "[" "{") eos) (treesit-node-type (treesit-node-at (point))))
      (re-search-backward "[^ \t\n\r]" nil t))

    ;; Walk over line_continuation, ",", ";" and identify the "check node" we should be looking
    ;; at.
    (let ((check-node (treesit-node-at (point))))
      (while (string-match-p (rx bos (or "line_continuation" "," ";") eos)
                             (treesit-node-type check-node))
        (goto-char (treesit-node-start check-node))
        (if (re-search-backward "[^ \t\n\r]" nil t)
            (setq check-node (treesit-node-at (point)))
          ;; at start of buffer
          (setq check-node nil)))

      (when check-node
        ;; Look to see if we are under an ERROR node
        (let ((error-node (treesit-node-parent check-node)))
          (while (and error-node
                      (not (string= (treesit-node-type error-node) "ERROR")))
            (setq error-node (treesit-node-parent error-node)))

          ;; In an error-node, see if this error is due to an incomplete cell or matrix,
          ;; if so return the start point of the row to anchor against.
          (when error-node
            (while (and check-node
                        (not (string-match-p (rx bos (or "row" "[" "{") eos)
                                             (treesit-node-type check-node))))
              (setq check-node (treesit-node-parent check-node)))

            (when check-node
              (cond
               ((string-match-p (rx bos (or "[" "{") eos) (treesit-node-type check-node))
                (setq matlab-ts-mode--i-error-row-matcher-pair
                      (cons (treesit-node-start check-node) 2)))
               ;; Case: looking at row?
               (t
                ;; Find first row to anchor against
                (let ((prev-sibling (treesit-node-prev-sibling check-node)))
                  (while prev-sibling
                    (when (string= (treesit-node-type prev-sibling) "row")
                      (setq check-node prev-sibling))
                    (setq prev-sibling (treesit-node-prev-sibling prev-sibling))))
                ;; In an ERROR node of a matrix or cell, return anchor
                (setq matlab-ts-mode--i-error-row-matcher-pair
                      (cons (treesit-node-start check-node) 0)))))))))))

(defun matlab-ts-mode--i-error-row-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-error-row-matcher'."
  (car matlab-ts-mode--i-error-row-matcher-pair))

(defun matlab-ts-mode--i-error-row-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-error-row-matcher'."
  (cdr matlab-ts-mode--i-error-row-matcher-pair))

(defun matlab-ts-mode--i-doc-block-comment-matcher (node parent bol &rest _)
  "Is NODE, PARENT within a function/classdef doc block comment \"%{ ... %}\"?
BOL, beginning-of-line point, is where we start looking for the error
node."
  (and (not node)
       (string= "comment" (treesit-node-type parent))
       (save-excursion
         (goto-char (treesit-node-start parent))
         (looking-at "%{" t))
       (not (save-excursion (goto-char bol)
                            (looking-at "%" t)))
       (matlab-ts-mode--is-doc-comment parent (treesit-node-parent parent))))

(defvar matlab-ts-mode-i-doc-comment-matcher-pair)

(defun matlab-ts-mode--i-doc-comment-matcher (node parent bol &rest _)
  "Is NODE, PARENT, BOL a function/classdef doc comment?"
  (let (doc-comment-node)
    (cond
     ((and (string= "comment" (or (treesit-node-type node) ""))
           (matlab-ts-mode--is-doc-comment node parent))
      (setq doc-comment-node parent))

     ((and (not node)
           (string= "comment" (treesit-node-type parent))
           (matlab-ts-mode--is-doc-comment parent (treesit-node-parent parent)))
      ;; Case:        function a = foo(b) %#ok
      ;;        TAB>  % doc comment
      ;; tests/test-matlab-ts-mode-indent-files/indent_mlint_suppression_on_fcn.m
      (setq doc-comment-node (treesit-node-parent parent))))

    (when doc-comment-node
      (setq matlab-ts-mode-i-doc-comment-matcher-pair
            (cons (treesit-node-start doc-comment-node)
                  (if (save-excursion
                        (goto-char bol)
                        (and (not (looking-at "%"))
                             (re-search-backward "^[ \t]*%{[ \t]*$"
                                                 (treesit-node-start (treesit-node-at (point))) t)))
                      2
                    0))))))

(defun matlab-ts-mode--i-doc-comment-anchor (_node _parent _bol &rest _)
  "Return anchor for the function/classdef doc comment based on PARENT."
  (car matlab-ts-mode-i-doc-comment-matcher-pair))

(defun matlab-ts-mode--i-doc-comment-offset (_node _parent _bol &rest _)
  "Return offset for the function/classdef doc comment based on PARENT."
  (cdr matlab-ts-mode-i-doc-comment-matcher-pair))

(defun matlab-ts-mode--i-in-block-comment-matcher (node parent bol &rest _)
  "Is NODE, PARENT, BOL within a block \"{% ... %)\"?"
  (and (not node)
       (string= "comment" (treesit-node-type parent))
       (not (save-excursion (goto-char bol)
                            (looking-at "%" t)))))

(defun matlab-ts-mode--i-block-comment-end-matcher (node parent bol &rest _)
  "Is NODE, PARENT, BOL last line of \"{% ... %)\"?
Also handle single-line comment blocks, e.g.
          a = 1 % comment1 about a
   TAB>         % comment2 about a
but not
        function foo %#ok
   TAB> % doc comment line 1"

  (and (not node)
       (string= "comment" (treesit-node-type parent))
       (save-excursion
         (goto-char bol)
         (and (looking-at "%" t)
              (not (matlab-ts-mode--i-doc-comment-matcher node parent bol))))))

;; `matlab-ts-mode--function-indent-level'
;;
;; It is recommended that all function statements have terminating end statements.  In some cases
;; for compatibility MATLAB doesn't require a function end statement.  When functions do not have an
;; end, we don't indent the body of the function per older MATLAB coding standard.  Example:
;;
;;     function a = fcn1    |    function a = fcn2
;;     a = 1;               |        a = 1;
;;                          |    end
;;
;; If a *.m file contains functions, and one of the functions is terminated with end, then every
;; function in the file must be terminated with end.  If a *.m file contains a function with one or
;; more nested functions, then every function in the file must be terminated with end.  If a script
;; contains one or more local functions, then every function in the file must be terminated with
;; end.
;;
;; When we enter `matlab-ts-mode', we examine the content and set the state of this variable.  If
;; matlab-ts--function-indent-level is nil, while editing, if functions become terminated with
;; ends, we set this to t.  We never go from t to nil because it's easy to get in a temporary nil
;; state during edits and we don't want to cause unexpected indentation behavior.")

(defvar-local matlab-ts-mode--function-indent-level 'unset
  "Function indent level is 0 or `matlab-ts-mode--indent-level'.")

(defun matlab-ts-mode--set-function-indent-level (&optional _node parent _bol &rest _)
  "Setup the function indent level for end vs end-less functions.
For optional _NODE, PARENT, and _BOL see `treesit-simple-indent-rules'."

  ;; - When matlab-ts-mode--function-indent-level is 'unset we set this to
  ;;     0 or matlab-ts-mode--indent-level
  ;;   based on the buffer content.
  ;; - Otherwise, matlab-ts-mode--function-indent-level is 0, we will "upgrade" it to
  ;;   matlab-ts-mode--indent-level if function end's appear.

  (let ((root (if (and parent
                       (string= (treesit-node-type parent) "function_definition"))
                  parent
                (treesit-buffer-root-node))))
    (if (treesit-search-subtree (treesit-buffer-root-node) "\\`ERROR\\'")
        ;; If we have syntax errors, assume that functions will have ends when entering
        ;; matlab-ts-mode, otherwise leave matlab-ts--function-indent-level unchanged.
        (when (equal matlab-ts-mode--function-indent-level 'unset)
          (setq-local matlab-ts-mode--function-indent-level matlab-ts-mode--indent-level))
      (let ((first-fcn (treesit-search-subtree root (rx bos "function_definition" eos))))
        (if (not first-fcn)
            ;; assume that if functions are added they will have ends
            (setq-local matlab-ts-mode--function-indent-level matlab-ts-mode--indent-level)
          (let ((have-end (string= (treesit-node-type (treesit-node-child first-fcn -1)) "end")))
            (if (equal matlab-ts-mode--function-indent-level 'unset)
                (setq-local matlab-ts-mode--function-indent-level
                            (if have-end
                                matlab-ts-mode--indent-level
                              0))
              (when have-end
                (setq-local matlab-ts-mode--function-indent-level matlab-ts-mode--indent-level))
              ))))))
  matlab-ts-mode--function-indent-level)

(defun matlab-ts-mode--set-function-indent-level-for-gp (node parent bol &rest _)
  "Set and return offset for parent of PARENT (grand-parent of NODE) at BOL."
  (matlab-ts-mode--set-function-indent-level node (treesit-node-parent parent) bol))

(defvar matlab-ts--indent-debug-rule
  '((lambda (node parent bol)
      (message "-->N:%S P:%S L:%d BOL:%S GP:%S NPS:%S"
               node parent (line-number-at-pos) bol
               (treesit-node-parent parent)
               (treesit-node-prev-sibling node))
      nil)
    nil
    0))

(defvar matlab-ts-mode--indent-assert nil
  "Tests should set this to t to identify when we fail to find an indent rule.")

(defvar matlab-ts-mode--indent-assert-rule
  '((lambda (node parent bol)
      (when matlab-ts-mode--indent-assert
        (error "Assert no indent rule for: N:%S P:%S BOL:%S GP:%S NPS:%S BUF:%S"
               node parent bol
               (treesit-node-parent parent)
               (treesit-node-prev-sibling node)
               (buffer-name))))
    nil
    0))

(defvar matlab-ts-mode--i-error-switch-matcher-pair)

(defun matlab-ts-mode--i-error-switch-matcher (node _parent bol &rest _)
  "Tab on an empty line after switch, case, or otherwise?
NODE is nil in this case and BOL, beginning-of-line point, is where we
are indenting.  If so, set
`matlab-ts-mode--i-error-switch-matcher-pair'.

  Example:  switch fcn1(a)
      TAB>    ^

Similar for case and otherwise statements."
  (when (not node)
    (save-excursion
      (goto-char bol)
      (re-search-backward "[^ \t\n\r]" nil t)

      (let* ((check-node (treesit-node-at (point)))
             (error-node (treesit-node-parent check-node)))
        (while (and error-node
                    (not (string= (treesit-node-type error-node) "ERROR")))
          (setq error-node (treesit-node-parent error-node)))

        ;; In an error-node, see if this error is due to an incomplete switch statement.
        (when error-node
          (let ((child-node (treesit-node-child error-node 0)))
            (when (and child-node
                       (string-match-p (rx bos (or "switch" "case" "otherwise") eos)
                                       (treesit-node-type child-node)))
              (setq matlab-ts-mode--i-error-switch-matcher-pair
                    (cons (treesit-node-start child-node)
                          matlab-ts-mode--switch-indent-level)))))))))

(defun matlab-ts-mode--i-error-switch-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-error-switch-matcher'."
  (car matlab-ts-mode--i-error-switch-matcher-pair))

(defun matlab-ts-mode--i-error-switch-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-error-switch-matcher'."
  (cdr matlab-ts-mode--i-error-switch-matcher-pair))

(defun matlab-ts-mode--i-cont-matcher (node _parent _bol &rest _)
  "Is current NODE part of a valid continuation?"
  (let ((prev-sibling (treesit-node-prev-sibling node)))
    (and prev-sibling
         (string= (treesit-node-type prev-sibling) "line_continuation"))))

(defun matlab-ts-mode--i-cont-offset (node parent _bol &rest _)
  "Get the ellipsis continuation offset based on NODE with PARENT.
This is `matlab-ts-mode--indent-level' or 0 when in a cell or matrix
row."
  (let ((row-node (let ((n parent))
                    (while (and n
                                (not (string= (treesit-node-type n) "row")))
                      (setq n (treesit-node-parent n)))
                    n)))
    (cond
     (row-node
      0)
     ((string= (treesit-node-type parent) "superclasses")
      (if (and node
               (string= (treesit-node-type node) "&"))
          ;;     classdef indent_classdef_super_continued3 ...
          ;;         < otherThing ...
          ;; TAB>    & otherThing2 ...
          0
        ;;      classdef indent_classdef_super_continued < otherThing & ...
        ;; TAB>                                            otherThing2 & ...
        ;; See: test-matlab-ts-mode-indent-files/indent_classdef_super_continued.m
        2))
     (t
      matlab-ts-mode--indent-level))))


(defvar matlab-ts-mode--i-cont-incomplete-matcher-pair)

(cl-defun matlab-ts-mode--i-cont-incomplete-matcher (node parent _bol &rest _)
  "Is current line part of an ellipsis line continuation?
If so, set `matlab-ts-mode--i-cont-incomplete-matcher-pair'.  This is for
incomplete statements where NODE is nil and PARENT is line_continuation."

  ;; Case when code is incomplete:
  ;;
  ;;        x = 1 + myfcn(a, ...
  ;;   TAB>               ^       NODE is nil and PARENT is line_continuation

  (let ((check-node
         (cond ((and (not node)
                     (string= (treesit-node-type parent) "line_continuation"))
                parent)
               ((and node
                     (let ((prev-sibling (treesit-node-prev-sibling node)))
                       (when (equal (treesit-node-type prev-sibling) "line_continuation")
                         (treesit-node-prev-sibling node))))))))

    (save-excursion
      ;; Walk over line_continuation and identify the "check node" we should be looking at.
      (while (equal "line_continuation" (treesit-node-type check-node))
        (goto-char (treesit-node-start check-node))
        (if (re-search-backward "[^ \t\n\r]" nil t)
            (setq check-node (treesit-node-at (point)))
          ;; at start of buffer
          (setq check-node nil)))

      (when check-node
        (let ((anchor-node check-node)
              saw-close-paren)

          ;; Look for open paren of a function-call, index, or expression grouping
          (while (and anchor-node
                      (let ((anchor-type (treesit-node-type anchor-node)))
                        (pcase anchor-type
                          (")"
                           (setq saw-close-paren t)
                           t)
                          ("("
                           (if saw-close-paren
                               (progn
                                 (setq saw-close-paren nil)
                                 t)
                             nil ;; found an unbalanced open parenthesis
                             ))
                          (_
                           t))))
            (setq anchor-node (treesit-node-prev-sibling anchor-node)))


          ;; If anchor-node is non-nil, we found "(", anchor off it, e.g. "(arg"
          (when (and anchor-node
                     (save-excursion
                       (goto-char (treesit-node-start anchor-node))
                       ;; When not an argument after the "("
                       ;; Examples: "(-1,..." "(+1,...") "(a, ..."  "((1+2),..."  "({1},..."
                       (not (looking-at "([ \t]*[-+a-zA-Z0-9{(]" t))))

            (let ((prev-node (treesit-node-prev-sibling anchor-node))  ;; "fcn(" ?
                  id-start)
              (when (and (equal (treesit-node-type prev-node) "identifier")
                         (save-excursion
                           (setq id-start (treesit-node-start prev-node))
                           (goto-char id-start)
                           (beginning-of-line)
                           (back-to-indentation)
                           (= (point) id-start)))
                ;; Incomplete:      something.foo4 = ...
                ;;                       someFcn2( ...
                ;;             TAB>          1, ...
                (setq matlab-ts-mode--i-cont-incomplete-matcher-pair
                      (cons id-start matlab-ts-mode--indent-level))
                (cl-return-from matlab-ts-mode--i-cont-incomplete-matcher t)))
            (setq anchor-node nil) ;; can't anchor off the "("
            )

          ;; An expression of an if, while, or switch statement? Consider:
          ;;   if a > 1 && ...
          ;;      ^                     <== TAB goes here
          ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_if_cond.m
          (when (not anchor-node)
            (setq anchor-node check-node)
            (while (and anchor-node
                        (not (string-match-p (rx bos (or "if_statement" "while_statement"
                                                         "switch_statement")
                                                 eos)
                                             (treesit-node-type anchor-node))))
              (setq anchor-node (treesit-node-parent anchor-node)))
            (when anchor-node
              (setq anchor-node (treesit-node-child-by-field-name anchor-node "condition"))))

          ;; Look for parent that we can use for indent
          (when (not anchor-node)
            (setq anchor-node check-node)
            (while (and anchor-node
                        (not (string-match-p (rx bos (or "ERROR" "arguments") eos)
                                             (treesit-node-type anchor-node))))
              (setq anchor-node (treesit-node-parent anchor-node))))

          ;; Setup to indent if we found an anchor-node
          (when anchor-node
            (setq matlab-ts-mode--i-cont-incomplete-matcher-pair
                  (cons (treesit-node-start anchor-node)
                        (pcase (treesit-node-type anchor-node)
                          ("(" 1)
                          ("ERROR" matlab-ts-mode--indent-level)
                          (_ 0)))))
          )))))

(defun matlab-ts-mode--i-cont-incomplete-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-cont-incomplete-matcher'."
  (car matlab-ts-mode--i-cont-incomplete-matcher-pair))

(defun matlab-ts-mode--i-cont-incomplete-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-cont-incomplete-matcher'."
  (cdr matlab-ts-mode--i-cont-incomplete-matcher-pair))

(defun matlab-ts-mode--is-next-line-fcn-args-anchor-node (anchor-node)
  "Is ANCHOR-NODE for a  \"fcn(\ ...\", if so return new anchor node."
  (when (string= (treesit-node-type anchor-node) "(")
    (save-excursion
      (goto-char (treesit-node-start anchor-node))
      (and (< (point) (point-max))
           (goto-char (1+ (point)))
           (re-search-forward "[^ \t]" nil t)
           (equal (treesit-node-type (treesit-node-at (point))) "line_continuation")
           (goto-char (treesit-node-start anchor-node))
           (> (point) 1)

           (goto-char (1- (point))) ;; just before the "("
           (progn ;; skip back to first non-whitespace char before the "("
             (when (looking-at "[ \t]")
               (re-search-backward "[^ \t\r\n]" nil t))
             t)
           ;; is "fcn(" or "fcn ("?
           ;;       ^         ^
           (looking-at "[a-z0-9_]" t)

           ;; Found something that looks like a function-call, e.g. "id("
           ;; Return id-node if it's a fcn-call in a fcn-call.
           (or (let ((id-node (treesit-node-at (point))))

                 (goto-char (treesit-node-start id-node))

                 ;; Move over field expression, other1.other2.fcn1(foo.bar.fcn2(
                 (when (> (current-column) 0)
                   (goto-char (1- (point)))
                   (while (and (> (current-column) 0)
                               (looking-at "\\." t))
                     (goto-char (1- (point)))
                     (when (looking-at "[a-z0-9_]" t)
                       (setq id-node (treesit-node-at (point)))
                       (goto-char (treesit-node-start id-node))
                       (when (> (current-column) 0)
                         (goto-char (1- (point)))))))

                 (when (looking-at "[ \t]")
                   (re-search-backward "[^ \t\r\n]" nil t))
                 (when (looking-at "(")
                   id-node))
               (treesit-node-parent anchor-node))
           ))))

(defvar matlab-ts-mode--i-next-line-pair)

(defun matlab-ts-mode--is-prev-sibling-fcn-args (node)
  "Is a prev-sibling of NODE a function_arguments node?"
  (let* ((prev-sibling (treesit-node-prev-sibling node))
         (prev-type (treesit-node-type prev-sibling)))
    (while (and prev-sibling
                (not (string= prev-type "function_arguments"))
                ;; matlab tree-sitter uses a newline after arguments statement
                (not (string= prev-type "\n")))
      (setq prev-sibling (treesit-node-prev-sibling prev-sibling)))
    (when prev-sibling t)))

(defun matlab-ts-mode--i-next-line-indent-level (node bol anchor-node last-child-of-error-node)
  "Get indent level for `matlab-ts-mode--i-cont-incomplete-matcher'.

NODE is the node being indented using ANCHOR-NODE.
LAST-CHILD-OF-ERROR-NODE is nil or the last child of the error node we
are in.

BOL, is the beginning-of-line that is being indented.

Sets `matlab-ts-mode--i-next-line-pair' to (ANCHOR-NODE . OFFSET)"

  (let ((anchor-last-child (treesit-node-child anchor-node -1)))
    (when (and (equal (treesit-node-type anchor-last-child) "end")
               (or (not node)
                   (< (treesit-node-start anchor-last-child) (treesit-node-start node))))
      (setq anchor-node anchor-last-child)))

  (let ((updated-anchor-node (matlab-ts-mode--is-next-line-fcn-args-anchor-node anchor-node)))
    (when updated-anchor-node
      ;; Case: var_b = my_function( ...
      ;;           ^                        <== RET/TAB to here
      ;; See:  tests/test-matlab-ts-mode-indent-xr-files/indent_xr_fun_call1.m
      (setq anchor-node updated-anchor-node
            last-child-of-error-node nil)))

  (let ((indent-level
         (if (and node (string= (treesit-node-type node) "end"))
             (progn
               (when (string= "property" (treesit-node-type anchor-node))
                 (setq anchor-node (treesit-node-parent anchor-node)))
               0)
           (let ((anchor-type (treesit-node-type anchor-node)))
             (pcase anchor-type

               ("property"
                (if (or last-child-of-error-node
                        ;; Continuation:    arguments
                        ;;                     firstArgument ...
                        ;;         TAB>            double
                        (let ((prev-sibling (treesit-node-prev-sibling node)))
                          (and prev-sibling
                               (string= (treesit-node-type prev-sibling) "line_continuation"))))
                    matlab-ts-mode--indent-level
                  0))

               ((rx (seq bos (or "properties" "events" "methods" "arguments") eos))
                (cond
                 ((equal "end" (treesit-node-type (treesit-node-child anchor-node -1)))
                  ;; after properties, etc.
                  0)
                 ((string= anchor-type "arguments")
                  (if (or (not node)
                          (matlab-ts-mode--is-prev-sibling-fcn-args node))
                      (if (let ((prev-sibling (treesit-node-prev-sibling node)))
                            (and prev-sibling
                                 (string= (treesit-node-type prev-sibling) "line_continuation")))
                          ;; Continuation:    arguments
                          ;;                     firstArgument ...
                          ;;         TAB>            ^
                          (* 2 matlab-ts-mode--indent-level)
                        matlab-ts-mode--indent-level)
                    ;; Else function-call arguments
                    ;; See: tests/test-matlab-ts-mode-indent-files/indent_fcn_call_last_paren.m
                    0))
                 (t
                  matlab-ts-mode--indent-level)))

               ("("
                1)

               ("[" ;; either a matrix or function output
                (if (save-excursion
                      (goto-char (treesit-node-start anchor-node))
                      (while (and (re-search-backward "[^ \t\r\n]" nil t)
                                  (string= (treesit-node-type
                                            (treesit-node-at (point)))
                                           "line_continuation")))
                      (string= (treesit-node-type (treesit-node-at (point)))
                               "function"))
                    ;; function output
                    1
                  matlab-ts-mode--array-indent-level))

               ("{"
                (if (save-excursion
                      (goto-char (treesit-node-start anchor-node))
                      (when (> (point) 1)
                        (goto-char (1- (point)))
                        (looking-at "%" t)))
                    ;; Anchored under a block comment: %{
                    ;;                                   ^    <== TAB to here, one more than the "{"
                    1
                  matlab-ts-mode--array-indent-level))

               ((rx (seq bos (or "function" "function_definition") eos))
                (if (equal "end" (treesit-node-type (treesit-node-child anchor-node -1)))
                    ;; after function
                    0
                  ;; else under function
                  matlab-ts-mode--function-indent-level))

               ("row"
                0)

               ("try"
                (if (and node
                         (string-match-p (rx bos "catch_clause" eos)
                                         (treesit-node-type node)))
                    0
                  matlab-ts-mode--indent-level))

               ((rx (seq bos (or "if" "elseif") eos))
                (if (and node
                         ;; else, else_clause, elseif, or elseif_clause
                         (string-match-p (rx bos "else")
                                         (treesit-node-type node)))
                    0
                  (if (save-excursion
                        (goto-char bol)
                        (let ((prev-node (treesit-node-at (point))))
                          (when (looking-at "[^ \t\n\r]")
                            (setq prev-node (treesit-node-prev-sibling prev-node)))
                          (when (equal (treesit-node-type prev-node) "line_continuation")
                            (goto-char (treesit-node-start prev-node))
                            (back-to-indentation)
                            ;; move to first item after the if or elseif condition
                            (when (looking-at (rx (or "if" "elseif") (or " " "\t")))
                              (re-search-forward "[ \t]" nil t))
                            (let ((condition-node (treesit-node-at (point))))
                              (when (not (string= (treesit-node-type condition-node)
                                                  "line_continuation"))
                                (setq anchor-node condition-node))))))
                      ;; Case:   if condition || ...
                      ;;            ^                       <== TAB to here
                      0
                    ;; Case: if condition
                    ;;           ^                           <== TAB to here
                    matlab-ts-mode--indent-level)))

               ((rx (seq bos (or "switch" "case" "otherwise") eos))
                matlab-ts-mode--switch-indent-level)

               ("end"
                0)

               ("classdef"
                (if (and (string= (treesit-node-type node) "comment")
                         (save-excursion
                           (goto-char (treesit-node-start node))
                           (beginning-of-line)
                           (forward-line -1)
                           (back-to-indentation)
                           (equal (treesit-node-at (point)) anchor-node)))
                    ;; function doc comment
                    0
                  matlab-ts-mode--indent-level))

               ("<" ;; superclass
                (if (and node
                         (string= (treesit-node-type node) "&"))
                    ;;     classdef indent_classdef_super_continued3 ...
                    ;;         < otherThing ...
                    ;; TAB>    & otherThing2 ...
                    0
                  ;;      classdef indent_classdef_super_continued < otherThing & ...
                  ;; TAB>                                            otherThing2 & ...
                  ;; See: test-matlab-ts-mode-indent-files/indent_classdef_super_continued.m
                  2))

               (_
                matlab-ts-mode--indent-level)
               )))))
    (setq matlab-ts-mode--i-next-line-pair
          (cons (treesit-node-start anchor-node) indent-level))))

(defvar matlab-ts-mode--i-next-line-anchors-rx (rx (seq bos (or "function_definition"
                                                                "function"
                                                                "arguments"
                                                                "classdef"
                                                                "properties"
                                                                "property"
                                                                "enumeration"
                                                                "events"
                                                                "methods"
                                                                "if"
                                                                "elseif"
                                                                "switch"
                                                                "case"
                                                                "otherwise"
                                                                "for"
                                                                "parfor"
                                                                "while"
                                                                "try"
                                                                "catch"
                                                                "("
                                                                "["
                                                                "{"
                                                                "row"
                                                                "spmd"
                                                                "<" ;; superclasses
                                                                )
                                                        eos)))

(defun matlab-ts-mode--i-next-line-matcher-comment (node)
  "Is NODE a comment we should indent when in context of an error?"

  (when (and node
             (string-match-p (rx (seq bos "comment" eos)) (treesit-node-type node)))
    (let ((prev-sibling (treesit-node-prev-sibling node)))
      (when (equal (treesit-node-type prev-sibling) "ERROR")
        (let ((last-child (treesit-node-child prev-sibling -1)))

          ;; function foo(a,b,stuff,cmddual1fake,cmddual2fake)
          ;;     if foo %!!4
          ;;         C = "this is the end of the line";
          ;;         % !!8                                      <== TAB to here
          (when (and last-child
                     (string= (treesit-node-type last-child) ";"))
            (setq last-child (treesit-node-prev-sibling last-child)))

          (when last-child
            ;; classdef foo
            ;;     properties
            ;;         foo1;
            ;;     end
            ;;     % comment    <== RET on this node, last-child == "end"
            ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_classdef3.m
            (setq matlab-ts-mode--i-next-line-pair
                  (cons (treesit-node-start last-child) 0))
            t))))))

(defun matlab-ts-mode--not-node-and-blank (node bol)
  "Is NODE nil with BOL on a blank line?"
  ;; Consider the one-liner:
  ;;    classdef indent_xr_classdef1
  ;;        ^                                 TAB should go here
  ;;  on entry node is nil and parent is ERROR, so backup to the newline:
  ;;   (source_file
  ;;    (ERROR classdef (identifier) \n))
  ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_classdef1.m
  (and (not node)
       (save-excursion
         (goto-char bol)
         (beginning-of-line)
         (looking-at "^[ \t]*$" t))))

(defun matlab-ts-mode--last-child-of-error (node parent)
  "Get updated parent if ellipsis NODE with PARENT is not part of an error."

  ;; Handle continuation where the node is not part of the error node. Example:
  ;;    (source_file
  ;;     (ERROR classdef (identifier) \n properties \n (identifier) =)
  ;;     (line_continuation))
  ;; For
  ;;    classdef indent_xr_classdef2
  ;;        properties
  ;;            p3continued = ...
  ;;                ^                       << RET on prior line should go here
  ;; In this case, last-child-of-error-node will be the "=" node.
  (when (and (not node)
             (string= (treesit-node-type parent) "line_continuation"))
    (let ((prev-sibling (treesit-node-prev-sibling parent)))
      (when (equal (treesit-node-type prev-sibling) "ERROR")
        (treesit-node-child prev-sibling -1)))))

(defun matlab-ts-mode--i-next-line-prev-sibling-to-check (last-child-of-error-node node-to-check)
  "Locate the prev-sibling-to-check for `matlab-ts-mode--i-next-line-matcher'.
For LAST-CHILD-OF-ERROR-NODE and NODE-TO-CHECK see
`matlab-ts-mode--i-next-line-matcher'"

  (let (prev-sibling-to-check
        prev-sibling-error-node
        (close-paren-count 0)
        (prev-sibling (if last-child-of-error-node
                          last-child-of-error-node ;; is our "prev-sibling"
                        (treesit-node-prev-sibling node-to-check))))
    (while (and prev-sibling
                (not prev-sibling-to-check)
                (not prev-sibling-error-node))
      (let ((prev-sibling-type (treesit-node-type prev-sibling)))

        ;; Backup over "..." continuations because they may not be prev-sibling's.
        ;; Consider:
        ;;    function ...
        ;;        [    ...    <== TAB here
        ;; (source_file (ERROR function) (line_continuation) (ERROR [) (line_continuation))
        (save-excursion
          (while (and prev-sibling
                      (string= prev-sibling-type "line_continuation")
                      (let ((prev-sibling2 (treesit-node-prev-sibling prev-sibling)))
                        (or (not prev-sibling2)
                            (string= (treesit-node-type prev-sibling2) "ERROR"))))
            (goto-char (treesit-node-start prev-sibling))
            (when (re-search-backward "[^ \t\n\r]" nil t)
              (setq prev-sibling (treesit-node-at (point))
                    prev-sibling-type (when prev-sibling
                                        (treesit-node-type prev-sibling))))))

        (when prev-sibling
          (cond
           ((string= prev-sibling-type "ERROR")
            (setq prev-sibling-error-node prev-sibling))

           ((string= prev-sibling-type ")")
            (setq close-paren-count (1+ close-paren-count)))

           ((string= prev-sibling-type "(")
            (if (> close-paren-count 0)
                (setq close-paren-count (1- close-paren-count))
              (setq prev-sibling-to-check prev-sibling)))

           ((and (string-match-p matlab-ts-mode--i-next-line-anchors-rx prev-sibling-type)
                 (or (not (string= prev-sibling-type "("))
                     ;; See: test/test-matlab-ts-mode-indent-xr-files/indent_xr_i_cont_incomplete5.m
                     ;; result = longFunction( ...
                     ;;     ^                           <== RET on prior line or TAB goes here
                     ;;
                     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_fun3.m
                     ;; function out=indent_xr_fun3(in1, ...
                     ;;                             ^   <== RET on prior line or TAB goes here

                     ;; no function or similar item  before paren: e.g. no longFunction(
                     (not (let* ((pp-s (treesit-node-prev-sibling prev-sibling))
                                 (pp-s-type (treesit-node-type pp-s)))
                            (and pp-s-type
                                 (string-match-p (rx bos (or "identifier" "spmd") eos) pp-s-type))))

                     ;; OR we have something after the paren: e.g. (in1, ...
                     (not (equal (treesit-node-type
                                  (treesit-node-next-sibling prev-sibling))
                                 "line_continuation"))
                     ))
            (setq prev-sibling-to-check prev-sibling)))

          (setq prev-sibling (if prev-sibling-error-node
                                 nil
                               (treesit-node-prev-sibling prev-sibling))))))

    (cons prev-sibling-to-check prev-sibling-error-node)))

(cl-defun matlab-ts-mode--i-next-line-matcher (node parent bol &rest _)
  "Matcher for indent on a newline being inserted when in presence of errors.
If so, set `matlab-ts-mode--i-next-line-pair'.

NODE may or may not be nil.  When NODE is nil in this case and BOL,
beginning-of-line point, is where we are indenting.  If NODE is non-nil,
we check if it is an ERROR node.  Another case is when PARENT is be a newline
due to a RET on the prior line.

Example: in this case NODE will be nil and PARENT is a newline.  Example:
   % -*- matlab-ts -*-
   classdef foo
       ^                     <== TAB or RET on prior line goes here.
Hierarchy:
  #<treesit-node source_file in 1-36>
    #<treesit-node ERROR in 21-36>
      #<treesit-node \"
\" in 33-36>
Prev-siblings:
  > #<treesit-node \"classdef\" in 21-29>
    > #<treesit-node identifier in 30-33>
      > #<treesit-node \""

  (when (matlab-ts-mode--i-next-line-matcher-comment node)
    (cl-return-from matlab-ts-mode--i-next-line-matcher t))

  (when (matlab-ts-mode--not-node-and-blank node bol)
    (setq parent (treesit-node-at (point))))

  (let ((last-child-of-error-node (matlab-ts-mode--last-child-of-error node parent)))
    (when last-child-of-error-node
      (setq parent last-child-of-error-node))

    (when (or last-child-of-error-node
              (and node (string= (treesit-node-type node) "ERROR"))
              (string-match-p (rx (seq bos (or "ERROR" "\n") eos)) (treesit-node-type parent))
              (equal (treesit-node-type (treesit-node-parent parent)) "ERROR"))

      (let ((node-to-check (or last-child-of-error-node node parent))
            ancestor-error-node ;; is node, parent, or one of it's ancestors an ERROR?
            prev-sibling-error-node ;; is a previous sibling under an ERROR?
            prev-sibling-to-check
            ancestor-to-check)

        ;; ancestor-to-check
        (let ((ancestor node-to-check))
          (while (and ancestor (not ancestor-error-node))
            (let ((ancestor-type (treesit-node-type ancestor)))
              (cond

               ((string= ancestor-type "ERROR")
                (setq ancestor-error-node ancestor))

               ((and (not ancestor-to-check)
                     (string-match-p matlab-ts-mode--i-next-line-anchors-rx ancestor-type))
                (setq ancestor-to-check ancestor)))

              (setq ancestor (if ancestor-error-node
                                 nil
                               (treesit-node-parent ancestor)))))
          (when (eq ancestor-to-check node-to-check)
            (setq ancestor-to-check nil)))

        ;; prev-sibling-to-check
        (let ((pair (matlab-ts-mode--i-next-line-prev-sibling-to-check
                     last-child-of-error-node
                     node-to-check)))
          (setq prev-sibling-to-check (car pair)
                prev-sibling-error-node (cdr pair)))

        ;; We use regular matching rules when there is NO error.
        (when (and (not ancestor-error-node)
                   (not prev-sibling-error-node))
          (cl-return-from matlab-ts-mode--i-next-line-matcher nil))

        (let ((anchor-node (or ancestor-to-check
                               prev-sibling-to-check)))
          (when anchor-node
            (let* ((a-error-start (when ancestor-error-node
                                    (treesit-node-start ancestor-error-node)))
                   (p-error-start (when prev-sibling-error-node
                                    (treesit-node-start prev-sibling-error-node)))
                   (error-node (if (or (not p-error-start)
                                       (and a-error-start
                                            (> a-error-start p-error-start)))
                                   ancestor-error-node
                                 prev-sibling-error-node)))
              (when (and (or (not node)
                             (not (equal node error-node)))
                         (> (treesit-node-start error-node) (treesit-node-start anchor-node)))
                (setq anchor-node error-node)))

            (matlab-ts-mode--i-next-line-indent-level node bol anchor-node last-child-of-error-node)
            ;; t ==> matched
            t))))))

(defun matlab-ts-mode--i-next-line-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-next-line-matcher'."
  (car matlab-ts-mode--i-next-line-pair))

(defun matlab-ts-mode--i-next-line-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-next-line-matcher'."
  (cdr matlab-ts-mode--i-next-line-pair))

(defvar matlab-ts-mode--i-comment-under-fcn-pair)

(defun matlab-ts-mode--i-comment-under-fcn-matcher (node _parent _bol &rest _)
  "Matcher when NODE is a comment and under a function.
Example:
   function a=foo
       a=1;
       %comment <== TAB goes here."
  (let ((comment-or-ellipsis-re (rx bos (or "comment" "line_continuation"))))

    (when (and node
               (string-match-p comment-or-ellipsis-re (treesit-node-type node)))
      (let ((prev-sibling (treesit-node-prev-sibling node)))
        (while (and prev-sibling
                    (string-match-p comment-or-ellipsis-re (treesit-node-type prev-sibling)))
          (setq prev-sibling (treesit-node-prev-sibling prev-sibling)))

        (when (and prev-sibling
                   (string= (treesit-node-type prev-sibling) "function_definition"))
          (when (not (equal (treesit-node-type (treesit-node-child prev-sibling -1)) "end"))
            (setq matlab-ts-mode--i-comment-under-fcn-pair
                  (cons (treesit-node-start prev-sibling) matlab-ts-mode--indent-level))
            t))))))

(defun matlab-ts-mode--i-comment-under-fcn-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-comment-under-fcn-matcher'."
  (car matlab-ts-mode--i-comment-under-fcn-pair))

(defun matlab-ts-mode--i-comment-under-fcn-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-comment-under-fcn-matcher'."
  (cdr matlab-ts-mode--i-comment-under-fcn-pair))

(defvar matlab-ts-mode--i-fcn-args-next-line-pair)

(defun matlab-ts-mode--i-fcn-args-next-line-matcher (_node parent _bol &rest _)
  "Is NODE/PARENT for function definition arguments?
Example:
   function someFunction( ...
       a, b)                        <== TAB to here"

  (let ((parent-type (treesit-node-type parent)))

    (cond
     ((and (string= parent-type "function_arguments")
           (or
            ;; function someFunction(...
            ;;    a, b)                     <== TAB to here
            (save-excursion
              (goto-char (1+ (treesit-node-start parent)))
              (and (re-search-forward "[^ \t]" nil t)
                   (equal (treesit-node-type (treesit-node-at (point))) "line_continuation")))
            ;; I-Rule: function args next line
            ;;            function [a, b] = foo( ...
            ;;  TAB>      a, b)                          // should move over by 4
            ;;            end
            (save-excursion
              (goto-char (1+ (treesit-node-start parent)))
              (and (re-search-forward "[^ \t]" nil t)
                   (string= "line_continuation" (treesit-node-type (treesit-node-at (point)))))))
           ;; AND not
           ;;     function ...
           ;;         out ...
           ;;         = ...
           ;;         indent_ellipsis ...
           ;;         ( ...
           ;;          arg ...                 <== TAB here
           (save-excursion
             (goto-char (1- (treesit-node-start parent)))
             (not (looking-at "[ \t]" t))))
      (setq matlab-ts-mode--i-fcn-args-next-line-pair
            (cons (treesit-node-start (treesit-node-parent parent))
                  matlab-ts-mode--indent-level))
      t)

     ;; function someFunction(...
     ;;     in1, ...                  <== RET type "in1, ..." or TAB to here
     ;;     a, b)
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_fcn_args.m
     ((and (string= parent-type "line_continuation")
           (let ((gp (treesit-node-parent parent)))
             (and (equal (treesit-node-type gp) "function_arguments")
                  (save-excursion
                    (goto-char (1+ (treesit-node-start gp)))
                    (and (re-search-forward "[^ \t]" nil t)
                         (string= "line_continuation" (treesit-node-type
                                                       (treesit-node-at (point)))))))))
      (setq matlab-ts-mode--i-fcn-args-next-line-pair
            (cons (treesit-node-start (treesit-node-parent (treesit-node-parent parent)))
                  matlab-ts-mode--indent-level))
      t)

     (t
      ;; no match
      nil))))

(defun matlab-ts-mode--i-fcn-args-next-line-anchor (&rest _)
  "Return the anchor computed by `matlab-ts-mode--i-fcn-args-next-line-matcher'."
  (car matlab-ts-mode--i-fcn-args-next-line-pair))

(defun matlab-ts-mode--i-fcn-args-next-line-offset (&rest _)
  "Return the offset computed by `matlab-ts-mode--i-fcn-args-next-line-matcher'."
  (cdr matlab-ts-mode--i-fcn-args-next-line-pair))

(defvar matlab-ts-mode--i-assign-cont-pair nil)

(defun matlab-ts-mode--i-assign-cont-anchor (&rest _)
  "Return anchor for `matlab-ts-mode--i-assign-cont-matcher'."
  (car matlab-ts-mode--i-assign-cont-pair))

(defun matlab-ts-mode--i-assign-cont-offset (&rest _)
  "Return anchor for `matlab-ts-mode--i-assign-cont-matcher'."
  (cdr matlab-ts-mode--i-assign-cont-pair))

(defun matlab-ts-mode--i-assign-cont-matcher (node parent _bol &rest _)
  "Is NODE, PARENT part of an assignment line continuation?"
  (and node
       (equal (treesit-node-type (treesit-node-prev-sibling node)) "line_continuation")
       (string= (treesit-node-type parent) "function_call")

       (let ((grand-parent (treesit-node-parent parent))
             full-fcn-node
             assign-node)

         (pcase (treesit-node-type grand-parent)
           ("assignment"
            (setq full-fcn-node parent
                  assign-node grand-parent))
           ("field_expression"
            (let ((great-gp (treesit-node-parent grand-parent)))
              (when (equal (treesit-node-type great-gp) "assignment")
                (setq full-fcn-node grand-parent
                      assign-node great-gp)))))

         (when full-fcn-node
           (save-excursion
             (goto-char (treesit-node-start full-fcn-node))
             (beginning-of-line)
             (back-to-indentation)
             (setq matlab-ts-mode--i-assign-cont-pair ;; Matched one of two cases
                   (cons (if (= (point) (treesit-node-start full-fcn-node))
                             ;;     something.foo4 = ...
                             ;;         someFcn2( ...
                             ;; TAB>        1, ...
                             (point)
                           ;;      something.foo2 = someFcn(...
                           ;;  TAB>    1, ...
                           (treesit-node-start assign-node))
                         matlab-ts-mode--indent-level)))))))

(defvar matlab-ts-mode--i-arg-namespace-fcn-prop-anchor-value nil)

(defun matlab-ts-mode--i-arg-namespace-fcn-prop-matcher (node parent _bol &rest _)
  "Is NODE, PARENT a property default value?
Example:
        properties (Constant)
            property1 = containers.Map(...
    TAB>                    {"
  (and (equal (treesit-node-type node) "arguments")
       (string= (treesit-node-type parent) "function_call")
       (let ((grand-parent (treesit-node-parent parent)))
         (and (string= (treesit-node-type grand-parent) "field_expression")
              (let ((great-grand-parent (treesit-node-parent grand-parent)))
                (and (string= (treesit-node-type great-grand-parent) "default_value")
                     (let ((great-great-grand-parent (treesit-node-parent great-grand-parent)))
                       (and (string= (treesit-node-type great-great-grand-parent) "property")
                            (setq matlab-ts-mode--i-arg-namespace-fcn-prop-anchor-value
                                  (treesit-node-start great-great-grand-parent))))))))))

(defun matlab-ts-mode--i-arg-namespace-fcn-prop-anchor (_node _parent _bol &rest _)
  "Return anchor for `matlab-ts-mode--i-arg-namespace-fcn-prop-matcher'."
  matlab-ts-mode--i-arg-namespace-fcn-prop-anchor-value)

(defvar matlab-ts-mode--i-row-anchor-value nil)

(defun matlab-ts-mode--i-row-matcher (node parent _bol &rest _)
  "Is NODE, PARENT in a matrix with first row on the \"[\" or \"{\" line?
Example:
   m = [1, 2, ...
        3, 4]       <== TAB to here."
  (and node
       (string= (treesit-node-type node) "row")
       (string-match-p (rx bos (or "cell" "matrix") eos) (treesit-node-type parent))
       (save-excursion
         (goto-char (treesit-node-start parent))
         (forward-char)
         (when (and (looking-at "[ \t]")
                    (re-search-forward "[^ \t]" (line-end-position) t))
           (backward-char))
         ;; Have something after the "[", e.g. "[  123" or "[ ..."?
         (when (and (looking-at "[^ \t\r\n]")
                    (not (equal (treesit-node-type (treesit-node-at (point))) "line_continuation")))
           (setq matlab-ts-mode--i-row-anchor-value (treesit-node-start (treesit-node-at (point))))
           t))))

(defun matlab-ts-mode--i-row-anchor (_node _parent _bol &rest _)
  "Return anchor for `matlab-ts-mode--i-row-matcher'."
  matlab-ts-mode--i-row-anchor-value)

(defvar matlab-ts-mode--indent-rules
  `((matlab

     ;; I-Rule: last line of code block comment "%{ ... %}"?
     (,#'matlab-ts-mode--i-block-comment-end-matcher parent 0)

     ;; I-Rule: RET on an incomplete statement. Example:
     ;;         classdef foo
     ;;             ^                     <== TAB or RET on prior line goes here.
     (,#'matlab-ts-mode--i-next-line-matcher
      ,#'matlab-ts-mode--i-next-line-anchor
      ,#'matlab-ts-mode--i-next-line-offset)

     ;; I-Rule: comment under function, e.g. typing the following (no end):
     ;;         function a=foo
     ;;             a=1;
     ;;             %comment    <== TAB goes here
     (,#'matlab-ts-mode--i-comment-under-fcn-matcher
      ,#'matlab-ts-mode--i-comment-under-fcn-anchor
      ,#'matlab-ts-mode--i-comment-under-fcn-offset)

     ;; I-Rule: classdef's, function's, or code for a script that is at the top-level
     ((lambda (node parent _bol &rest _)
        (and node
             (not (string= (treesit-node-type node) "line_continuation"))
             (equal (treesit-node-type parent) "source_file")))
      ;; column-0 moves point, fixed in emacs 31
      (lambda (_node _parent bol &rest _)
        (save-excursion
          (goto-char bol)
          (line-beginning-position)))
      0)

     ;; I-Rule: within a function/classdef doc block comment "%{ ... %}"?
     (,#'matlab-ts-mode--i-doc-block-comment-matcher parent 2)

     ;; I-Rule: function/classdef doc comment?
     (,#'matlab-ts-mode--i-doc-comment-matcher
      ,#'matlab-ts-mode--i-doc-comment-anchor
      ,#'matlab-ts-mode--i-doc-comment-offset)

     ;; I-Rule: within a code block comment "%{ ... %}"?
     (,#'matlab-ts-mode--i-in-block-comment-matcher parent 2)

     ;; I-Rule: switch case and otherwise statements
     ((node-is ,(rx bos (or "case_clause" "otherwise_clause") eos))
      parent ,matlab-ts-mode--switch-indent-level)

     ;; I-Rule: nested functions
     ((n-p-gp ,(rx bos "function_definition" eos)
              ,(rx bos "block" eos)
              ,(rx bos "function_definition" eos))
      parent 0)

     ;; I-Rule: elseif, else, catch, end statements go back to parent level
     ((node-is ,(rx bos (or "elseif_clause" "else_clause" "catch_clause" "end") eos)) parent 0)


     ;; I-Rule: first line of code within a switch case or otherwise statement, node is block
     ((parent-is ,(rx bos (or "switch_statement" "case_clause" "otherwise_clause") eos))
      parent ,matlab-ts-mode--switch-indent-level)

     ;; I-Rule: function's
     ((parent-is ,(rx bos "function_definition" eos))
      parent ,#'matlab-ts-mode--set-function-indent-level-for-gp)

     ;; I-Rule: function a = indent_xr_fun()<RET>
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_fun*.m
     ((n-p-gp nil ,(rx bos "\n" eos) ,(rx bos (or "function_definition") eos))
      grand-parent ,#'matlab-ts-mode--set-function-indent-level)

     ;; I-Rule: constructs within classdef or function's.
     ((node-is ,(rx bos (or "arguments_statement" "block" "enumeration" "enum" "methods" "events"
                            "function_definition" "property" "properties")
                    eos))
      parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: classdef abstract methods
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_classdef_abs_methods.m
     ((n-p-gp nil ,(rx bos "\n" eos) ,(rx bos "function_signature" eos)) grand-parent 0)
     ((n-p-gp ,(rx bos "\n" eos) ,(rx bos "function_signature" eos) nil) parent 0)

     ;; I-Rule: items in blocks
     ((n-p-gp nil ,(rx bos "property" eos) ,(rx bos "properties" eos))
      grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: property continuation
     ((n-p-gp nil ,(rx bos "default_value" eos) ,(rx bos "property" eos))
      grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: end argument/property continuation
     ((n-p-gp ,(rx bos "}" eos) ,(rx bos "validation_functions" eos) nil) parent 0)

     ;; I-Rule: argument/property continuation
     ;;         arguments
     ;;             a ...
     ;;                 { ...
     ;;                   mustBeReal ...
     ;;                   ^                     <== TAB/RET to here
     ((parent-is ,(rx bos "validation_functions" eos)) parent 2)

     ;; I-Rule: property after a property
     ;;         properties
     ;;             p1
     ;;             ^              <= RET on prior line goes here
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_classdef2.m
     ((n-p-gp nil nil ,(rx bos "property" eos)) grand-parent 0)

     ;; I-Rule: code in if, for, methods, arguments statements, etc.
     ((parent-is ,(rx bos (or "if_statement" "for_statement" "while_statement"
                              "methods" "events" "enumeration"
                              "function_definition" "arguments_statement"
                              "properties")
                      eos))
      parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: case 10<RET>
     ((n-p-gp nil ,(rx bos "\n" eos) ,(rx bos (or "switch_statement" "case_clause"
                                                  "otherwise_clause")
                                          eos))
      grand-parent ,matlab-ts-mode--switch-indent-level)

     ;; I-Rule:  if condition1 || ...     |      if condition1 + condition2 == ...
     ;; <TAB>       condition2 || ...     |         2770000 ...
     ((parent-is ,(rx bos (or "boolean_operator" "comparison_operator") eos)) parent 0)

     ;; I-Rule:  elseif ...
     ;; <TAB>        condition2 || ...
     ((parent-is ,(rx bos (or "else_clause" "elseif_clause") eos))
      parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: if variable ...
     ;;             ^             <== TAB or RET on prior line
     ;;         end
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_statement_body.m
     ((n-p-gp nil ,(rx bos "\n" eos)
              ,(rx bos (or "class_definition"
                           "properties"
                           "enumeration"
                           "methods"
                           "events"
                           "function_definition"
                           "arguments_statement"
                           "spmd_statement"
                           "try_statement"
                           "catch_clause"
                           "while_statement"
                           "for_statement"
                           "if_statement" "else_clause" "elseif_clause")
                   eos))
      grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: grandparent is block
     ;;      for i=1:10
     ;;          disp(i)
     ;;          ^                         <== RET on prior line or tab goes here
     ;;      end
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_grandparent_is_block.m
     ((n-p-gp nil ,(rx bos "\n" eos) ,(rx bos "block" eos)) grand-parent 0)

     ;; I-Rule: disp(myMatrix(1:  ...
     ;; <TAB>                 end));
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_ranges.m
     ((parent-is ,(rx bos "range" eos)) parent 0)

     ;; I-Rule: try<RET>    |   catch<RET>
     ((parent-is ,(rx bos (or "try_statement" "catch_clause") eos))
      parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: function a
     ;;             x = 1;
     ;; <TAB>       y = 2;
     ((parent-is ,(rx bos "block" eos)) parent 0)

     ;; I-Rule: classdef indent_class_prop_continued
     ;;              properties
     ;;                  ListArrayHeight = struct( ...
     ;;         TAB>         'Short',  {1}, ...
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_class_prop_continued.m
     ((n-p-gp ,(rx bos (or ")" "arguments" "line_continuation") eos)
              ,(rx bos "function_call" eos)
              ,(rx bos "default_value" eos))
      great-grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule:  a = ...
     ;; <TAB>        1;
     ((parent-is ,(rx bos "assignment" eos)) parent ,matlab-ts-mode--indent-level)

     ;; I-Rule:  a = 2 * ...
     ;; <TAB>        1;
     ((parent-is ,(rx bos "binary_operator" eos)) parent 0)

     ;; I-Rule:      something.foo4 = ...
     ;;                  someFcn2( ...
     ;;          TAB>        1, ...
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_fcn_cont.m
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_fcn_call_last_paren.m
     (,#'matlab-ts-mode--i-assign-cont-matcher
      ,#'matlab-ts-mode--i-assign-cont-anchor
      ,#'matlab-ts-mode--i-assign-cont-offset)

     ;; I-Rule:  a = ( ...       |     a = [  ...     |     a = {  ...
     ;;               1 ...      |          1 ...     |          1 ...
     ;; <TAB>        );          |         ];         |         };
     ((node-is ,(rx bos (or ")" "]" "}") eos)) parent 0)

     ;; I-Rule:  a = ( ...
     ;; <TAB>         1 ...
     ((parent-is ,(rx bos "parenthesis" eos)) parent 1)

     ;; I-Rule:  a = [    2 ...       |   function a ...
     ;; <TAB>             1 ...       |            = fcn
     ((parent-is ,(rx bos (or "row" "function_output") eos)) parent 0)

     ;; I-Rule: a = [1, 2, ...
     ;;              3, 4]
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_matrix.m
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_cell.m
     (,#'matlab-ts-mode--i-row-matcher
      ,#'matlab-ts-mode--i-row-anchor
      0)

     ;; I-Rule:  a = [   ...    |    a = { ...
     ;; <TAB>          2 ...    |          2 ...
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_matrix.m
     ((parent-is ,(rx bos (or "cell" "matrix") eos)) parent ,matlab-ts-mode--array-indent-level)

     ;; I-Rule:   cell1 = { ...
     ;; See: ./test-matlab-ts-mode-indent-xr-files/indent_xr_cell1.m
     ((n-p-gp nil ,(rx bos "line_continuation" eos) ,(rx bos (or "cell" "matrix") eos))
      grand-parent ,matlab-ts-mode--array-indent-level)

     ;; I-Rule: function args next line
     ;;           function someFunction(...
     ;;               a, b)                          <== TAB/RET to here
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_fcn_args.m
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_fcn_args_on_next_line.m
     (,#'matlab-ts-mode--i-fcn-args-next-line-matcher
      ,#'matlab-ts-mode--i-fcn-args-next-line-anchor
      ,#'matlab-ts-mode--i-fcn-args-next-line-offset)

     ;;
     ;; I-Rule:  function [   ...              |    function name (a, ... % comment
     ;; <TAB>              a, ... % comment    |                   b, ... % comment
     ((parent-is ,(rx bos (or "multioutput_variable" "function_arguments") eos)) parent 1)

     ;; I-Rule:  a = ...
     ;; <TAB>        1;
     ((n-p-gp nil nil ,(rx bos "assignment" eos)) grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule:  a = my_function(1, ...
     ;; <TAB>                    2, ...
     ((parent-is ,(rx bos "arguments" eos)) parent 0)

     ;; I-Rule:      properties (Constant)
     ;;                  property1 = containers.Map(...
     ;;        TAB>          {
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_class_prop_continued2.m
     (,#'matlab-ts-mode--i-arg-namespace-fcn-prop-matcher
      ,#'matlab-ts-mode--i-arg-namespace-fcn-prop-anchor
      ,matlab-ts-mode--indent-level)

     ;; I-Rule:      someNamespace1.subNamespace2.myFunction( ...
     ;;        TAB>      a, ... % comment for param1
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_namespace_fcn_continued.m
     ((n-p-gp ,(rx bos "arguments" eos)
              ,(rx bos "function_call" eos)
              ,(rx bos "field_expression" eos))
      grand-parent ,matlab-ts-mode--indent-level)

     ;; I-Rule:  my_function( ...
     ;; <TAB>        1, ...
     ((node-is ,(rx bos "arguments" eos)) parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: function indent_tab_between_fcns   |   function indent_tab_in_fcn
     ;;         end                                |      disp('here')
     ;; <TAB>                                      |
     ;;         function b                         |   end
     ;;         end                                |
     ((lambda (node parent bol)
        (and (not parent)
             (string= (treesit-node-type parent) "\n")))
      grand-parent 0)

     ;; I-Rule: comments in classdef's
     ((parent-is ,(rx bos "class_definition" eos)) parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: comment within spmd
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_spmd.m
     ((parent-is ,(rx bos "spmd")) parent ,matlab-ts-mode--indent-level)

     ;; I-Rule: comment after property:
     ;;         arguments
     ;;             a
     ;;    TAB>     % comment
     ;;         end
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_comment_after_prop.m
     ((node-is "comment") parent 0)

     ;; I-Rule: cell/matrix row matcher when in an error node
     ;;         mat0 = [1, 2
     ;;                 ^            <-- TAB or RET on prior line goes here
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_mat*.m
     (,#'matlab-ts-mode--i-error-row-matcher
      ,#'matlab-ts-mode--i-error-row-anchor
      ,#'matlab-ts-mode--i-error-row-offset)

     ;; I-Rule: error-switch-matcher
     ;;         switch fcn1(a)
     ;;           ^                       <== TAB to here
     (,#'matlab-ts-mode--i-error-switch-matcher
      ,#'matlab-ts-mode--i-error-switch-anchor
      ,#'matlab-ts-mode--i-error-switch-offset)

     ;; I-Rule: line continuations for incomplete continuations
     ;;            myVariable = 1 + myfcn(a, ...
     ;;                                   ^              <== TAB or RET on prior line goes here
     ;;
     ;;            myVariable = 1 + myfcn(a, b) + ...
     ;;                ^                                 <== TAB or RET on prior line goes here
     ;; See: tests/test-matlab-ts-mode-indent-xr-files/indent_xr_i_cont_incomplete*.m
     (,#'matlab-ts-mode--i-cont-incomplete-matcher
      ,#'matlab-ts-mode--i-cont-incomplete-anchor
      ,#'matlab-ts-mode--i-cont-incomplete-offset)

     ;; I-Rule: line continuation for valid statements
     ;;             a1 = { ...
     ;;                    1 ...
     ;;                    + ...
     ;;                    2                    <== TAB or RET on prior line to here
     ;;                  };
     ;; See: test-matlab-ts-mode-indent-files/indent_cell.m
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_line_continuation.m
     ;; See: tests/test-matlab-ts-mode-indent-files/indent_line_continuation_row.m
     (,#'matlab-ts-mode--i-cont-matcher parent ,#'matlab-ts-mode--i-cont-offset)

     ;; I-Rule: Assert if no rule matched and asserts are enabled.
     ,matlab-ts-mode--indent-assert-rule
     ))
  "Tree-sitter indent rules for `matlab-ts-mode'.")

;;; Thing settings for movement, etc.

(defvar matlab-ts-mode--statements-type-re
  (rx (seq
       bos
       (or "arguments_statement"
           "assignment"
           "lambda"
           "class_definition"
           "enumeration"
           "events"
           "for_statement"
           "function_call"
           "function_definition"
           "if_statement"
           "methods"
           "property"
           "properties"
           "spmd_statement"
           "switch_statement"
           "try_statement"
           "while_statement")
       eos))
  "MATLAB command statements.")

(cl-defun matlab-ts-mode-beginning-of-statement (&optional
                                                 goto-end statement-type-re
                                                 find-outermost-statement
                                                 no-message)
  "Move to the beginning of a statement.
If optional GOTO-END is \\='end, move to end of the current statement.

We define a command statement to be a complete syntactic unit that has
a start and end.  For example, if point is in an assignment statement
    var = ...
        1;
move point to the \"v\" when GOTO-END is nil, otherwise move to the
point after \";\".  Likewise for other command statements.

The point is moved to the start or end of the innermost statement that
the point is on.  No movement is performed if point is not in a
statement.  This can occur when there are syntax errors or the buffer
has no content.

Optional STATEMENT-TYPE-RE is a regular expression matching the type of
statement to look for.  For example, to move to the beginning of the
current assignment statement, use

  (matlab-ts-mode-beginning-of-statement nil
    (rx (seq bos \"assignment\" eos))

If STATEMENT-TYPE-RE is not specified, `matlab-ts-mode--statements-type-re'
is used.

Optional FIND-OUTERMOST-STATEMENT, if t locates the outermost statement.
For example, if point is on the 11 below will move to the beginning of
the assignment and not the inner function_call statement.

 var = ...
     fun(11, ...
         22);

Optional NO-MESSAGE if non-nil will prevent messages from being displayed.

Returns nil if not in a statement, otherwise the anchor node
used to do the movement."
  (interactive)

  (cl-assert (or (not goto-end) (eq goto-end 'end)))

  (when (not statement-type-re)
    (setq statement-type-re matlab-ts-mode--statements-type-re))

  (let ((start-point (point))
        (search-node (treesit-node-at (point)))
        statement-node)

    ;; When on a newline, back up to prior statement
    (when (and (> (point) 1)
               (equal (treesit-node-type search-node) "\n")
               (re-search-backward "[^ \t\n\r]" nil t))
      (setq search-node (treesit-node-at (point))))

    ;; When at ";" use prev-sibling
    (when (equal (treesit-node-type search-node) ";")
      (setq search-node (treesit-node-prev-sibling search-node)))

    ;; find nearest ancestor that matches statement-type-re
    (while search-node

      ;; Find inner statement node
      (while (and search-node
                  (let ((type (treesit-node-type search-node)))
                    (when (equal type "ERROR")
                      ;; No movement if we have a syntax error
                      (unless no-message
                        (message "Not in statement due to syntax error"))
                      (cl-return-from matlab-ts-mode-beginning-of-statement))
                    (not (string-match-p statement-type-re type))))
        (setq search-node (treesit-node-parent search-node)))

      (when search-node
        (setq statement-node search-node)
        (if find-outermost-statement
            (setq search-node (treesit-node-parent search-node))
          (setq search-node nil))))

    (when (not statement-node)
      (unless no-message
        (message "Not in a statement"))
      (cl-return-from matlab-ts-mode-beginning-of-statement))

    (let* ((statement-start-point (treesit-node-start statement-node))
           (end-node (or
                      ;; Use next sibling node if it's a ";" for the an
                      ;; assignment or function_call.
                      (and (string-match-p (rx (seq bos (or "assignment"
                                                            "function_call"
                                                            "field_expression")
                                                    eos))
                                           (treesit-node-type statement-node))
                           (let ((next-node (treesit-node-next-sibling statement-node)))
                             (when (and next-node
                                        (string= ";" (treesit-node-type next-node)))
                               next-node)))
                      statement-node))
           (statement-end-point (treesit-node-end end-node)))
      (when (and (>= start-point statement-start-point)
                 (<= start-point statement-end-point))
        (cond
         ((eq goto-end 'end)
          (goto-char statement-end-point)
          end-node)
         (t
          (goto-char statement-start-point)
          statement-node))))))

(defun matlab-ts-mode-end-of-statement (&optional statement-type)
  "Move to the end of a command statement.
This is the opposite of `matlab-ts-mode-beginning-of-statement'.
Optional STATEMENT-TYPE is the type of statement to look for.  If
not specified statement in `matlab-ts-mode--statements-ht' are used."
  (interactive)
  (matlab-ts-mode-beginning-of-statement 'end statement-type))

;; TODO - use these for M-a, M-e?

(defun matlab-ts-mode-beginning-of-command ()
  "Move to the beginning of the command at point.
Commands are either assignment or function_call statements that can be
evaluated at the matlab prompt.  Movement occurs only if the point is in
an assignment or function call.  Note array indexing is considered a
function call."
  (when (matlab-ts-mode-beginning-of-statement nil
                                               (rx (seq bos (or "assignment"
                                                                "function_call"
                                                                "field_expression")
                                                        eos))
                                               t)
    (point)))

(defun matlab-ts-mode-end-of-command ()
  "Move to the end of the command at point.
Commands are either assignment or function_call statements that can be
evaluated at the matlab prompt.  Movement occurs only if the point is in
an assignment or function call.  Note array indexing is considered a
function call."
  (when (matlab-ts-mode-beginning-of-statement 'end
                                               (rx (seq bos (or "assignment"
                                                                "function_call"
                                                                "field_expression")
                                                        eos))
                                               t)
    (point)))

;; matlab-ts-mode--thing-settings used for:
;;   C-M-a  - M-x beginning-of-defun
;;   C-M-e  - M-x end-of-defun
;;   C-M-b  - M-x backward-sexp
;;   C-M-f  - M-x forward-sexp
;;   M-e    - M-x forward-sentence
;;   M-a    - M-x backward-sentence
;;   C-M-u  - M-x backward-up-list
;;
(defvar matlab-ts-mode--thing-settings
  `((matlab
     (defun ,(rx bos "function_definition" eos))
     (sexp ,(rx bos (or "function_definition"
                        "arguments_statement"

                        ;; "property" of "arguments_statement" and "properties"
                        ;;
                        ;; TODO: the property node includes a newline, which means C-M-f jumps to
                        ;; an odd location.  Should the matlab tree sitter grammar be updated or
                        ;; should we special case this?
                        ;;     function method1(in1, in2)
                        ;;         arguments
                        ;;             in1 (1,1) double
                        ;;             ^                         % <- point here, C-M-f
                        ;;             in2 (1,2) double
                        ;;     ^                                 % -> moves point here.
                        ;;         end
                        ;;
                        ;; Here's the nodes:
                        ;;     (property name: (identifier)
                        ;;      (dimensions ( (number) , (number) ))
                        ;;      (identifier) \n)
                        ;;     (property name: (identifier)
                        ;;      (dimensions ( (number) , (number) ))
                        ;;      (identifier) \n)
                        ;;
                        ;; See: https://github.com/acristoffers/tree-sitter-matlab/issues/91
                        "property"

                        "function_arguments"
                        "function_call"

                        "assignment"
                        "break_statement"
                        "cell"
                        "continue_statement"
                        "command"
                        "for_statement"
                        "global_operator"
                        "if_statement"
                        "matrix"
                        "persistent_operator"
                        "return_statement"
                        "switch_statement"
                        "case"
                        "otherwise"
                        "catch"
                        "try_statement"
                        "while_statement"

                        "class_definition"
                        "classdef"
                        "properties"
                        "methods"
                        "events"
                        "enumeration"
                        "enum"

                        "identifier")
                eos))

     (sentence ,(rx bos (or "function_definition"
                            "assignment"
                            "arguments_statement"
                            "for_statement"
                            "if_statement"
                            "switch_statement"
                            "try_statement"
                            "while_statement"
                            "class_definition"
                            "properties"
                            "methods"
                            "events"
                            "enumeration")))

     (text ,(rx bos (or "comment" "string" "line_continuation") eos))

     ))
  "Tree-sitter things for movement.")

(defun matlab-ts-mode--forward-sexp (&optional arg)
  "Use `treesit-forward-sexp' when matching code only.
ARG is described in the docstring of `forward-sexp'.  When we are
matching a parenthesis, bracket, brace, or when point is in a comment do
the normal s-expression movement by calling
`forward-sexp-default-function'."
  (interactive "^p")
  (let* ((move-back (and (numberp arg) (< arg 0)))
         (match-paren (if move-back
                          (member (char-before) '(?\] ?\) ?\}))
                        (member (char-after) '(?\[ ?\( ?\{))))
         node
         node-type)

    (if (or match-paren
            (progn
              (setq node (let ((pt-and-node (matlab-ts-mode--real-node-at-point)))
                           (cdr pt-and-node)))
              (setq node-type (treesit-node-type node))
              (equal node-type "comment")))
        ;; See tests/test-matlab-ts-mode-thing-settings-files/thing_forward_sexp1.m
        (forward-sexp-default-function arg)

      ;; ELSE if in string handle that locally, else use `treesit-forward-sexp'

      (let ((string-node (and node
                              (or (when (string-match-p (rx bos (or "'"
                                                                    "\""
                                                                    "string_content"
                                                                    "formatting_sequence"
                                                                    "escape_sequence")
                                                            eos)
                                                        node-type)
                                    ;; For "'", the parent could be a postfix_operator, e.g.
                                    ;; a transpose: [1 2; 3 4]'
                                    (let ((parent-node (treesit-node-parent node)))
                                      (when (string= (treesit-node-type parent-node) "string")
                                        parent-node)))
                                  (when (string= "string" node-type)
                                    node)))))
        (if string-node
            ;; See: tests/test-matlab-ts-mode-thing-settings-files/thing_mark_sexp.m
            (goto-char (if move-back
                           (treesit-node-start string-node)
                         (treesit-node-end string-node)))

          ;; Use treesit-forward-sexp
          ;;
          ;; Treesit doesn't behave well when point is not at the end or start of the node,
          ;; so fix that. Consider
          ;;     function foo
          ;;         ^          <== point here and C-M-f
          ;;     end
          ;;      ^             <== point here and C-M-b
          ;; See: tests/test-matlab-ts-mode-thing-settings-files/thing_fun_sexp.m
          (when (and node
                     (>= (point) (treesit-node-start node))
                     (< (point) (treesit-node-end node)))
            (if move-back
                (when (string= (treesit-node-type node) "end")
                  (goto-char (treesit-node-end node)))
              (goto-char (treesit-node-start node))))
          (treesit-forward-sexp arg))))))

;;; Change Log

(defun matlab-ts-mode--defun-name (node)
  "Return the defun name of NODE for Change Log entries."
  (when (string-match-p
         (rx bos (or "function_definition" "class_definition") eos)
         (treesit-node-type node))
    (treesit-node-text (treesit-node-child-by-field-name node "name"))))

;;; imenu

(defun matlab-ts-mode--imenu-create-index ()
  "Return index for imenu.
This will return alist of functions and classes in the current buffer:
   \\='((\"function1\" . start-point1)
     (\"function2\" . start-point2)"
  (let ((root (treesit-buffer-root-node))
        class-index
        fcn-index
        section-index)

    ;; Find classdef and function entries
    (treesit-search-subtree
     root
     (lambda (node)
       (let ((type (treesit-node-type node)))
         (pcase type

           ("class_definition"
            (let* ((name (treesit-node-text (treesit-node-child-by-field-name node "name")))
                   (start-pt (treesit-node-start node)))
              (push `(,name . ,start-pt) class-index)))

           ("function_definition"
            (let* ((name-node (treesit-node-child-by-field-name node "name"))
                   (prev-type (treesit-node-type (treesit-node-prev-sibling name-node)))
                   (name (treesit-node-text name-node))
                   (start-pt (treesit-node-start node))
                   (parent (treesit-node-parent node)))

              ;; classdef get.propName or set.propName
              (when (and prev-type
                         (string-match-p (rx bos (or "get." "set.") eos) prev-type))
                (setq name (concat prev-type name)))

              ;; If nested function prefix with that by looking to parent
              (while parent
                (when (string= "function_definition" (treesit-node-type parent))
                  (let ((parent-name
                         (treesit-node-text (treesit-node-child-by-field-name parent "name"))))
                    (setq name (concat parent-name "." name))))
                (setq parent (treesit-node-parent parent)))
              (push `(,name . ,start-pt) fcn-index))))
         nil)))

    (setq class-index (reverse class-index))
    (setq fcn-index (reverse fcn-index))

    ;; comment section headings
    (save-excursion
      (goto-char (point-min))
      (while (re-search-forward matlab-ts-mode--comment-section-heading-re nil t)
        (let* ((heading-start (match-beginning 1))
               (heading (match-string 1))
               (start-point (let ((node (treesit-node-at heading-start)))
                              (goto-char (treesit-node-end node))
                              ;; (when (looking-at "[ \t\r\n]")
                              ;;   (re-search-forward "[^ \t\r\n]" nil t))
                              (point))))
          (setq heading (replace-regexp-in-string "^%%[ \t]*" "" (string-trim heading)))
          (when (string= heading "")
            (setq heading (format "Section at line %d" (line-number-at-pos))))
          (push `(,heading . ,start-point) section-index)))
      (setq section-index (reverse section-index)))

    ;; Return the index
    (let (index)
      (when section-index
        (push `("Section" . ,section-index) index))
      (when fcn-index
        (push `("Function" . ,fcn-index) index))
      (when class-index
        (push `("Class" . ,class-index) index))
      index)))

(defun matlab-ts-mode--imenu-setup ()
  "Configure imenu to use tree-sitter, even when lsp-mode is available."

  ;; Test, see: ./tests/test-matlab-ts-mode-imenu.el
  ;;
  ;; When lsp-mode is active, it takes over imenu-create-index-function. To prevent this,
  ;; we could have people do:
  ;;   (add-hook 'matlab-ts-mode-hook (lambda ()
  ;;                                     (setq-local lsp-enable-imenu nil)
  ;;                                     (lsp) ;; or (lsp-deferred)
  ;;                                     ))
  ;; However, tree-sitter is faster and more robust, so always use that.
  ;;
  ;; See:
  ;; https://www.reddit.com/r/emacs/comments/1c216kr/experimenting_with_tree_sitter_and_imenulist
  (setq-local lsp-enable-imenu nil)
  (setq-local imenu-create-index-function #'matlab-ts-mode--imenu-create-index))

;;; Outline minor mode, M-x outline-minor-mode

(defun matlab-ts-mode--outline-predicate (node)
  "Outline headings for `outline-minor-mode' with MATLAB.
Returns t if tree-sitter NODE defines an outline heading."
  (let ((node-type (treesit-node-type node)))
    (or (string-match-p (rx bos (or "function_definition" "class_definition") eos) node-type)
        (and (string= "comment" node-type)
             (save-excursion
               (goto-char (treesit-node-start node))
               (beginning-of-line)
               (looking-at matlab-ts-mode--comment-section-heading-re t))))))

;;; Save hooks

(defun matlab-ts-mode--highlight-ask (begin end prompt)
  "Highlight from BEGIN to END while asking PROMPT as a yes-no question."
  (let ((mo (make-overlay begin end (current-buffer)))
        (show-paren-mode nil) ;; this will highlight things we often ask about.  disable.
        ans)
    (condition-case nil
        (progn
          (overlay-put mo 'face 'matlab-region-face)
          (setq ans (y-or-n-p prompt))
          (delete-overlay mo))
      (quit (delete-overlay mo)
            (user-error "Quit")))
    ans))

(defun matlab-ts-mode-on-save-fix-name (&optional no-prompt)
  "If file name and function/classdef name are different, offer to fix.
If optional NO-PROMPT is t, fix the name if needed without prompting."
  (interactive)
  (when (or no-prompt (not noninteractive)) ;; can only prompt if in interactive mode
    (let* ((root (treesit-buffer-root-node))
           (children (treesit-node-children root)))
      (cl-loop for child in children do
               (let ((child-type (treesit-node-type child)))
                 (cond
                  ;; Case: function_definition or class_definition
                  ((string-match-p (rx bos (or "function_definition" "class_definition") eos)
                                   child-type)
                   (let* ((def-name-node (treesit-node-child-by-field-name child "name"))
                          (def-name (treesit-node-text def-name-node))
                          (file-name (file-name-nondirectory (or (buffer-file-name) (buffer-name))))
                          (base-name-no-ext (replace-regexp-in-string "\\.[^.]+\\'" "" file-name)))
                     ;; When base-name-no-ext is a valid name, MATLAB will use that.
                     ;; Invalid file names result in an error in MATLAB, so don't try to fix
                     ;; the function/classdef name in that case.
                     (when (and (string-match-p "\\`[a-zA-Z][a-zA-Z0-9_]*\\'" base-name-no-ext)
                                (not (string= def-name base-name-no-ext)))
                       (let ((start-pt (treesit-node-start def-name-node))
                             (end-pt (treesit-node-end def-name-node)))
                         (when (or no-prompt
                                   (matlab-ts-mode--highlight-ask
                                    start-pt end-pt
                                    (concat (if (string= child-type "function_definition")
                                                "Function"
                                              "Classdef")
                                            " name and file names are different. Fix?")))
                           (save-excursion
                             (goto-char start-pt)
                             (delete-region start-pt end-pt)
                             (insert base-name-no-ext))))))
                   (cl-return))

                  ;; Case: any other code means this is a script, so no on save fix
                  ((not (string-match-p (rx bos (or "comment"
                                                    "line_continuation"
                                                    "\n")
                                            eos)
                                        child-type))
                   (cl-return))))))))

(defun matlab-ts-mode--write-file-callback ()
  "Called from `write-contents-functions'.
When `matlab-verify-on-save-flag' is true, run `matlab-mode-verify-fix-file'.
Enable/disable `matlab-sections-minor-mode' based on file content."
  (mapc (lambda (fix-function)
          (funcall fix-function))
        matlab-ts-mode-on-save-fixes)
  (matlab-sections-auto-enable-on-mfile-type-fcn (matlab-ts-mode--mfile-type))
  ;; `write-contents-functions' expects this callback to return nil to continue with other hooks and
  ;; the final save. See `run-hook-with-args-until-success'.
  nil)

;;; Electric Pair Mode, M-x electric-pair-mode

(declare-function electric-pair-default-inhibit "elec-pair")

(defun matlab-ts-mode--electric-pair-inhibit-predicate (char)
  "Return non-nil if `electric-pair-mode' should not pair this CHAR.
Do not pair the transpose operator, (\\='), but pair it when used as a
single quote string."

  ;; (point) is just after CHAR. For example, if we type a single quote:
  ;;   x = '
  ;;        ^--(point)

  (cond
   ;; Case: Single quote
   ;;  str = '      : start of single quote string => nil
   ;;  mat'         : transpose operator => t
   ;;  str = " ' "  : add single quote in string => t
   ((eq char ?')
    (let* ((node-back1 (treesit-node-at (- (point) 1)))
           (type-back1 (treesit-node-type node-back1)))
      (cond
       ;; Case: in comment, return t if it looks like a transpose, e.g. A' or similar.
       ((string-match-p (rx bos (or "comment" "line_continuation") eos) type-back1)
        (save-excursion
          (forward-char -1)
          (looking-at "\\w\\|\\s_\\|\\." t)))

       ;; Case: string delimiter
       ;;    double up if starting a new string => return nil
       ;; For:     s = '
       ;; we have: (source_file
       ;;           (postfix_operator operand: (identifier)
       ;;            (ERROR =)
       ;;            ')
       ;;           \n)
       ((string= "'" type-back1 )
        (not (equal (treesit-node-type (treesit-node-prev-sibling node-back1)) "ERROR")))

       ;; Case: inside a single quote string
       ;;    s = 'foobar'
       ;;            ^ insert here
       ;;    s = 'foo''bar'
       ((and (string= "string_content" type-back1)
             (string= "'" (treesit-node-type (treesit-node-prev-sibling node-back1))))
        nil)

       ;; Case: not a string delimiter, return t
       ;;   transpose:                  A'
       ;;   inside double quote string: "foo'bar"
       (t
        t))))

   ;; Case: Not a single quote, defer to the standard electric pair handling
   (t
    (funcall #'electric-pair-default-inhibit char))))

;;; show-paren-mode

(declare-function show-paren--default "paren")

(defun matlab-ts-mode--show-paren-or-block ()
  "Function to assign to `show-paren-data-function'.
Highlight MATLAB pairs in addition to standard items paired by
`show-paren-mode'.  Returns a list: \\='(HERE-BEGIN HERE-END THERE-BEGIN
THERE-END MISMATCH) or nil."
  (let* (here-begin
         here-end
         there-begin
         there-end
         mismatch
         (pt-and-node (matlab-ts-mode--real-node-at-point))
         (pt (car pt-and-node))
         (node (cdr pt-and-node)))

    ;; If point is in whitespace, (treesit-node-at (point)) returns the nearest node. For
    ;; paired matching we want the point on either a start or end paired item.
    (let ((node-start (treesit-node-start node))
          (node-end (treesit-node-end node)))
      (when (and (>= pt node-start)
                 (<= pt node-end))
        (let* ((start-to-parent '(("classdef"    . "class_definition")
                                  ("methods"     . "methods")
                                  ("properties"  . "properties")
                                  ("enumeration" . "enumeration")
                                  ("events"      . "events")
                                  ("function"    . "function_definition")
                                  ("arguments"   . "arguments_statement")
                                  ("if"          . "if_statement")
                                  ("switch"      . "switch_statement")
                                  ("for"         . "for_statement")
                                  ("parfor"      . "for_statement")
                                  ("while"       . "while_statement")
                                  ("try"         . "try_statement")
                                  ("spmd"        . "spmd_statement")
                                  ))
               (start-node-types (mapcar (lambda (pair) (car pair)) start-to-parent))
               (start-re (rx-to-string `(seq bos (or ,@start-node-types) eos) t))
               (node-type (treesit-node-type node))
               (parent-node (treesit-node-parent node))
               (parent-type (treesit-node-type parent-node)))

          (cond

           ;; Case: on a start node, e.g. "function"
           ((string-match-p start-re node-type)
            (let* ((expected-parent-type (cdr (assoc node-type start-to-parent)))
                   (expected-end-type "end") ;; all blocks terminate with an "end" statement
                   (end-node (car (last (treesit-node-children parent-node)))))
              (setq here-begin (treesit-node-start node)
                    here-end (treesit-node-end node))
              (if (and (equal (treesit-node-type parent-node) expected-parent-type)
                       (equal (treesit-node-type end-node) expected-end-type))
                  (setq there-begin (treesit-node-start end-node)
                        there-end (treesit-node-end end-node))
                ;; A missing end keyword will result in parent being "ERROR".
                ;; See: tests/test-matlab-ts-mode-show-paren-files/show_paren_classdef_missing_end.m
                (setq mismatch t))))

           ;; Case: on a "end" node or an inner block that should be matched with parent
           ((and (string-match-p (rx bos (or "end" "elseif" "else" "case" "otherwise" "catch") eos)
                                 node-type)
                 ;; and we have a matching parent node
                 (progn
                   (when (not (equal node-type "end"))
                     (setq parent-node (treesit-node-parent parent-node))
                     (setq parent-type (treesit-node-type parent-node)))
                   (let ((parents (mapcar (lambda (pair)
                                            (cdr pair))
                                          start-to-parent)))
                     (member parent-type parents))))
            (let ((parent-to-start (mapcar (lambda (pair)
                                             (cons (cdr pair) (car pair)))
                                           start-to-parent)))

              (setq here-begin (treesit-node-start node))
              (setq here-end (treesit-node-end node))
              (setq there-begin (treesit-node-start parent-node))
              (setq there-end (+ there-begin (length (cdr (assoc parent-type parent-to-start)))))))

           ;; Case: on a single or double quote for a string.
           ((and (or (equal "'" node-type)
                     (equal "\"" node-type))
                 (equal "string" parent-type))
            (let (q-start-node
                  q-end-node)
              (if (= (treesit-node-start parent-node) (treesit-node-start node))
                  ;; looking at start quote
                  (setq q-start-node node
                        q-end-node parent-node)
                ;; else looking at end quote
                (setq q-start-node parent-node
                      q-end-node node))

              (setq here-begin (treesit-node-start q-start-node))
              (setq here-end (1+ here-begin))

              (let* ((candidate-there-end (treesit-node-end q-end-node))
                     (candidate-there-begin (1- candidate-there-end)))
                (cond
                 ;; Case: Have starting quote of a string, but no content or closing quote.
                 ((= here-begin candidate-there-begin)
                  (setq mismatch t))
                 ;; Case: Have starting quote, have string content, but no closing quote
                 ((not (equal (char-after here-begin) (char-after candidate-there-begin)))
                  (setq mismatch t))
                 (t
                  (setq there-begin candidate-there-begin)
                  (setq there-end candidate-there-end))))))

           ))))

    (if (or here-begin here-end)
        (list here-begin here-end there-begin there-end mismatch)
      (funcall #'show-paren--default))))

;;; post-self-command-hook

(defun matlab-ts-mode--is-electric-end-missing (node)
  "Is statement NODE missing an \"end\"."
  (let ((last-child (treesit-node-child (treesit-node-parent node) -1)))
    (cond
     ;; Case: no end keyword for the node in the parse tree
     ((not (equal (treesit-node-type last-child) "end"))
      t)

     ;; Case: see if this is an end for a different statement. Consider:
     ;;   function foo(a)
     ;;       if a > 0            <== When RET typed, we want the electric end to be inserted
     ;;   end
     ;; The parse tree is:
     ;;   (function_definition function name: (identifier)
     ;;    (function_arguments ( arguments: (identifier) ))
     ;;    \n
     ;;    (block
     ;;     (if_statement if
     ;;      condition: (comparison_operator (identifier) > (number))
     ;;      \n end)
     ;;     \n))
     ;; Notice the end is attached to the if_statement.  Therefore, we use indent level
     ;; to see if it is really attached.
     ;; This works well assuming that the code is indented when one is editing it.
     ((let ((node-indent-level (save-excursion
                                 (goto-char (treesit-node-start node))
                                 (current-indentation)))
            (end-indent-level (save-excursion
                                (goto-char (treesit-node-start last-child))
                                (current-indentation))))
        (not (= node-indent-level end-indent-level)))
      t)

     ;; Case: newly added statement causes a parse error, so it's missing the end, Consider:
     ;;   classdef foo
     ;;       properties                   <== properties typed, followed by RET
     ;;       methods
     ;;       end
     ;;   end
     ;; which gives us parse tree:
     ;;   (source_file
     ;;    (class_definition classdef name: (identifier) \n
     ;;     (properties properties \n
     ;;      (ERROR , methods)
     ;;      \n end)
     ;;     end)
     ;;    \n)
     ((let* ((statement-node (treesit-node-parent node))
             (child-idx 0)
             (child (treesit-node-child statement-node child-idx))
             (node-type (treesit-node-type node)))

        (while (and child
                    (string-match-p (rx-to-string `(seq bos (or ,node-type "\n" "comment") eos) t)
                                    (treesit-node-type child)))
          (setq child-idx (1+ child-idx))
          (setq child (treesit-node-child statement-node child-idx)))
        (and child (string= (treesit-node-type child) "ERROR")))
      ;; An ERROR immediately after node
      t)

     ;; Otherwise: statement has an end
     (t
      nil
      ))))

(defun matlab-ts-mode--insert-electric-ends ()
  "A RET was type, insert the electric \"end\" if needed."

  ;; We could also insert the end of a block comment, "%}", when "%{" is seen but that would likely
  ;; be annoying because often %{ block comments %} are used to comment out sections of code.

  (let (end-indent-level
        extra-insert
        item-to-insert
        move-point-to-extra-insert
        (pre-insert "")
        (statement-with-end-re (rx (or "function" "arguments" "if" "switch" "while" "for"
                                       "parfor" "spmd" "try" "classdef" "enumeration"
                                       "properties" "methods" "events"))))

    (save-excursion
      (forward-line -1)
      (back-to-indentation)
      (let* ((node (treesit-node-at (point))))
        (when node
          (let ((node-type (treesit-node-type node)))

            (cond

             ;; Case: Was a statement entered that requires and end?
             ((and (string-match-p (concat "\\`" statement-with-end-re "\\'") node-type)
                   ;; must be at a keyword and not in whitespace before it
                   ;; See: tests/test-matlab-ts-mode-electric-ends-files/electric_ends_in_ws.m
                   (looking-at statement-with-end-re))
              (when (and (or (> matlab-ts-mode--function-indent-level 0)
                             (not (string= node-type "function")))
                         (matlab-ts-mode--is-electric-end-missing node)) ;; Missing an end?
                ;; Statement for the RET doesn't have an end, so add one at end-indent-level
                (setq end-indent-level (current-indentation))
                (setq pre-insert "\n")
                (setq item-to-insert "end\n")

                ;; Extra insert, e.g. case for the switch statement.
                (pcase node-type
                  ("switch"
                   (setq extra-insert "  case "
                         move-point-to-extra-insert t))
                  ("try"
                   (setq extra-insert "catch me"))
                  )))

             ;; Case: Single-line doc comment?
             ((and (string= node-type "comment")
                   (eq (get-char-property (point) 'face) 'font-lock-doc-face)
                   (looking-at "%[ \t]*[^ \t\r\n]"))
              (setq end-indent-level (current-indentation))
              (setq item-to-insert "% ")
              ))))))

    (when end-indent-level
      (let ((indent-level-spaces (make-string end-indent-level ? )))
        (save-excursion
          (when extra-insert
            (when (not move-point-to-extra-insert)
              (insert "\n"))
            (insert indent-level-spaces extra-insert))
          (insert pre-insert indent-level-spaces item-to-insert))
        (setq unread-command-events (nconc (listify-key-sequence (kbd "C-e"))
                                           unread-command-events))
        ))))

(defun matlab-ts-mode--post-insert-callback ()
  "Callback attached to `post-self-insert-hook'.

The matlab tree-sitter requires a final newline.  Setting
`require-final-newline' to \\='visit-save doesn't guarantee we have a newline
when typing code into the buffer, so we leverage `post-self-command-hook'
to insert a newline if needed.

  https://github.com/acristoffers/tree-sitter-matlab/issues/34

This callback also implements `matlab-ts-mode-electric-ends'."

  (when (eq major-mode 'matlab-ts-mode)
    (let ((ret-typed (eq last-command-event ?\n)))

      ;; Add final newline to the buffer?
      (save-excursion
        (goto-char (point-max))
        (when (not (= (char-before) ?\n))
          (insert "\n")))

      ;; Add "end" (for `matlab-ts-mode-electric-ends')
      (when (and ret-typed
                 matlab-ts-mode-electric-ends)
        (matlab-ts-mode--insert-electric-ends)))))

;;; MLint Flycheck

(defvar flycheck-checkers) ;; incase flycheck is not on the path

(declare-function flycheck-define-command-checker "flycheck")
(declare-function flycheck-buffer-saved-p "flycheck")

(when (and matlab-ts-mode-enable-mlint-flycheck
           (require 'flycheck nil 'noerror))
  (let* ((mlint (matlab--get-mlint-exe)))
    ;; If we have mlint, activate.
    ;; We could display a message here or in matlab-ts-mode if we don't have mlint, but
    ;; this would be just noise and cause problems when running tests with emacs -q.

    (when mlint
      (flycheck-define-command-checker
          'matlab-mlint
        "MATLAB mlint code analyzer"
        :command `(,mlint "-id" "-all" source-original)
        ;; Example mlint messages.
        ;; L 588 (C 46-49): LOAD: To avoid conflicts with functions ....
        :error-patterns
        '((warning line-start "L " line " (C " column "-" column "): " (id (* alnum)) ":" (message))
          (warning line-start "L " line " (C " column "): " (id (* alnum)) ":" (message)))
        :modes '(matlab-ts-mode)
        :predicate #'(lambda () (flycheck-buffer-saved-p)))
      ;; Register matlab-mlint with flycheck
      (add-to-list 'flycheck-checkers 'matlab-mlint))))

;;; MATLAB Code sections, `matlab-sections-minor-mode'

(defun matlab-ts-mode--mfile-type ()
  "Get *.m type, \\='empty, \\='script, \\='function, \\='class."
  (if (save-excursion
        (= (progn (forward-comment (point-max)) (point)) (point-max)))
      ;; Case: 'empty - No code (blanks and comments are considered empty)
      'empty
    (let* ((first-code-node (let* ((root (treesit-buffer-root-node))
                                   (child-idx 0)
                                   (child (treesit-node-child root child-idx)))
                              (while (and child
                                          (string-match-p (rx bos (or "comment"
                                                                      "line_continuation"
                                                                      "\n")
                                                              eos)
                                                          (treesit-node-type child)))
                                (setq child-idx (1+ child-idx))
                                (setq child (treesit-node-child root child-idx)))
                              child))
           (first-code-type (or (treesit-node-type first-code-node) "comment")))
      (pcase first-code-type
        ("class_definition" 'class)
        ("function_definition" 'function)
        (_ 'script)))))

;;; Comment markers

(defun matlab-ts-mode-comment-marker-help ()
  "Display help on triple-x, fix me, and to do comment markers."
  (interactive)
  (with-help-window "*Comment Marker Help*"
    (with-current-buffer "*Comment Marker Help*"
      (setq-local revert-buffer-function (lambda (&rest _)))
      (insert (format "\
Within comments, the following markers will be highlighted:

%-5s : Triple-x markers indicate coding tasks that must be completed
        prior to committing code to your repository.

%-5s : Fix-me markers should be fixed as soon as possible, but are not
        considered coding tasks that must be addressed prior to
        committing code to your repository.

%-5s : To-do markers represent future coding tasks and therefore code
        with these comments can be committed to your repository.
"
                      (propertize (nth 0 matlab-ts-mode--comment-markers)
                                  'face font-lock-warning-face)
                      (propertize (nth 1 matlab-ts-mode--comment-markers)
                                  'face font-lock-warning-face)
                      (propertize (nth 2 matlab-ts-mode--comment-markers)
                                  'face font-lock-warning-face))))))

(defun matlab-ts-mode-grep-comment-markers ()
  "Run grep on current file to find the triple-x, fix-me, and to do markers."
  (interactive)
  (when (not (buffer-file-name))
    (user-error "Buffer %s is not associated with a file" (buffer-name)))
  (when (buffer-modified-p)
    (if (y-or-n-p (format "Save %s? " (buffer-name)))
        (save-buffer)
      (user-error "Save %s before grep'ing for comment markers" (buffer-name))))
  (let ((pattern (mapconcat #'identity matlab-ts-mode--comment-markers "\\|")))
    (grep (concat grep-command "-wie \"" pattern "\" "
                  (file-name-nondirectory (buffer-file-name))))))

;;; View parse errors

(defun matlab-ts-mode--get-parse-errors (&optional file-name-for-error)
  "Return a string of parse errors in matlab-ts-mode current buffer.
Returns nil if there are no errors.

Optional FILE-NAME-FOR-ERROR is used instead of the `buffer-name' if
provided."

  ;; See: tests/test-matlab-ts-mode-view-parse-errors.el

  (let ((capture-errors (treesit-query-capture (treesit-buffer-root-node) '((ERROR) @e)))
        (result-list '())
        (buf-name (or file-name-for-error
                      (if (buffer-file-name)
                          (file-name-nondirectory (buffer-file-name))
                        (buffer-name)))))
    (dolist (capture-error capture-errors)
      (let* ((error-node (cdr capture-error))
             (start-point (treesit-node-start error-node))
             (start-line (line-number-at-pos start-point))
             (start-col (save-excursion ;; error messages are one based columns
                          (goto-char start-point)
                          (1+ (current-column))))
             (end-point (treesit-node-end error-node))
             (end-line (line-number-at-pos end-point))
             (end-col (save-excursion
                        (goto-char end-point)
                        (1+ (current-column)))))
        (push (format
               "%s:%d:%d: error: parse error from line %d:%d to line %d:%d (point %d to %d)
%5d | %s
      | %s^
"
               buf-name
               start-line start-col
               start-line start-col
               end-line end-col
               start-point
               end-point
               start-line
               ;; error line
               (buffer-substring (save-excursion
                                   (goto-char start-point)
                                   (line-beginning-position))
                                 (save-excursion
                                   (goto-char start-point)
                                   (line-end-position)))
               ;; space padding for the pointer (^)
               (save-excursion
                 (goto-char start-point)
                 (let ((n-spaces (- start-point (line-beginning-position))))
                   (make-string n-spaces ? ))))
              result-list)))
    (let ((errs (mapconcat #'identity (reverse result-list))))
      (if (string= errs "")
          (setq errs nil)
        (setq errs (concat "Tree-sitter parse errors.\n" errs)))
      errs)))

(defvar-local matlab-ts-parse-errors-compilation--buffer nil)

(defun matlab-ts-mode--view-parse-errors-recompile ()
  "Get latest parse errors."
  (interactive)
  (unless matlab-ts-parse-errors-compilation--buffer
    (error "No previously parsed buffer"))
  (when (not (buffer-live-p matlab-ts-parse-errors-compilation--buffer))
    (error "Previously parsed buffer was killed"))
  (with-current-buffer matlab-ts-parse-errors-compilation--buffer
    (matlab-ts-view-parse-errors 'no-pop-to-buffer)))

(defvar-keymap matlab-ts-parse-errors-mode-map
  "g" #'matlab-ts-mode--view-parse-errors-recompile)

;; Note, we are using a slightly shorter names (no -mode)
;;   matlab-ts-view-parse-errors
;;   matlab-ts-parse-errors-mode
;; so the mode line indicator, "matlab-ts-parse-errors" is slightly shorter

(define-compilation-mode matlab-ts-parse-errors-mode "m-ts-parse-errors"
                         "The variant of `compilation-mode' used for `matlab-ts-view-parse-errors'."
                         (setq-local matlab-ts-parse-errors-compilation--current-buffer (current-buffer)))

(defun matlab-ts-view-parse-errors (&optional no-pop-to-buffer)
  "View parse errors in matlab-ts-mode current buffer.
Optional NO-POP-TO-BUFFER, if non-nil will not run `pop-to-buffer'.
The errors are displayed in a \"*parse errors in BUFFER-NAME*\" buffer
and this buffer is returned."
  (interactive)

  (when (not (eq major-mode 'matlab-ts-mode))
    (user-error "Current buffer major-mode, %s, is not matlab-ts-mode"
                (symbol-name major-mode)))

  (let ((m-buf (current-buffer))
        (m-buf-dir default-directory)
        parse-errors-buf
        (errs (or (matlab-ts-mode--get-parse-errors)
                  "No tree-sitter errors\n"))
        (err-buf-name (concat "*parse errors in " (buffer-name) "*")))

    (with-current-buffer (setq parse-errors-buf (get-buffer-create err-buf-name))
      (read-only-mode -1)
      (auto-revert-mode 0) ;; no need to save history
      (erase-buffer)
      (insert errs)
      (matlab-ts-parse-errors-mode)
      (goto-char (point-min))
      (when (re-search-forward ": error: " nil t)
        (beginning-of-line))
      (setq default-directory m-buf-dir)
      (setq-local matlab-ts-parse-errors-compilation--buffer m-buf)
      (read-only-mode 1)
      (when (not no-pop-to-buffer)
        (pop-to-buffer (current-buffer) 'other-window)))
    parse-errors-buf))

;;; Our M-q matlab-ts-mode-prog-fill-reindent-defun

(defun matlab-ts-mode-prog-fill-reindent-defun (&optional justify)
  "MATLAB refill or reindent the paragraph or defun at point.

If the point is in a string or a comment, fill the paragraph that
contains point or follows point.  Optional JUSTIFY is passed
to `fill-paragraph'.

Otherwise, reindent the function definition that contains point
or follows point.

This exists because ellipsis line continuations cause
`prog-fill-reindent-defun' to not behave well.  Thus, we handle
these locally."
  (interactive "P")
  (save-excursion
    (let ((treesit-text-node
           (and (treesit-available-p)
                (treesit-parser-list)
                (let ((node (treesit-node-at (point))))
                  (and (treesit-node-match-p node 'text t)
                       (not (equal (treesit-node-type node) "line_continuation")))))))
      (if (or treesit-text-node
              ;; We can't fill strings because doing so introduces syntax errors
              (let ((sp (syntax-ppss)))
                (and (nth 8 sp) ;; string or comment
                     (not (nth 3 sp)))) ;; not string
              (let ((comment-start-pt
                     (save-excursion
                       (when (and (re-search-forward "\\s-*\\s<" (line-end-position) t)
                                  (not (equal (treesit-node-type (treesit-node-at (point)))
                                              "line_continuation")))
                         (point)))))
                (when comment-start-pt
                  (goto-char comment-start-pt))))
          (fill-paragraph justify (region-active-p))
        (beginning-of-defun)
        (let ((start (point)))
          (end-of-defun)
          (indent-region start (point) nil))))))

;;; Keymap

(defvar-keymap matlab-ts-mode-map
  :doc "Keymap for `matlab-ts-mode' buffers."
  :parent prog-mode-map

  ;; Editing commands
  "M-q" #'matlab-ts-mode-prog-fill-reindent-defun
  "C-c C-j" #'matlab-justify-line

  ;; Integration with `matlab-shell'
  "C-c C-s" 'matlab-shell-save-and-go
  "C-c C-r" 'matlab-shell-run-region
  "C-<return>" 'matlab-shell-run-region-or-line
  "C-c ?" 'matlab-shell-locate-fcn
  "C-h C-m" matlab--shell-help-map
  "M-s" 'matlab-show-matlab-shell-buffer
  "C-M-<mouse-2>" 'matlab-shell-find-file-click)

;;; Menu

(easy-menu-define matlab-mode-menu matlab-ts-mode-map
  "Menu for `matlab-ts-mode'."
  '("MATLAB"
    "---" "MATLAB shell"
    ["     Start MATLAB (M-x matlab-shell)" matlab-shell
     :active (not (matlab-shell-active-p))
     :visible (not (matlab-shell-active-p))
     :help "Run MATLAB in a *MATLAB* shell buffer"]
    ["     Switch to MATLAB (M-x matlab-shell)" matlab-shell
     :active (matlab-any-shell-active-p)
     :visible (matlab-any-shell-active-p)
     :help "Switch to the *MATLAB* shell buffer"]
    ["     Save and go" matlab-shell-save-and-go
     :active (matlab-any-shell-active-p)
     :help "Save this *.m file and evaluate it in the *MATLAB* shell"]
    ["     Run region" matlab-shell-run-region
     :active (matlab-any-shell-active-p)
     :help "Evaluate the active region in the *MATLAB* shell buffer"]
    ["     Run region or line" matlab-shell-run-region-or-line
     :active (matlab-any-shell-active-p)
     :help "Evaluate active region or current line in the *MATLAB* shell buffer"]
    ["     Run command" matlab-shell-run-command
     :active (matlab-shell-active-p)
     :help "Prompt for a command and run it in the *MATLAB* shell buffer.
Result is shown in a *MATLAB Run Command Result* buffer."]
    ["     Describe command" matlab-shell-describe-command
     :active (matlab-shell-active-p)
     :help "Run \"help COMMAND\" in the *MATLAB* shell buffer
and display in a help buffer."]
    ["     Describe variable" matlab-shell-describe-variable
     :active (matlab-shell-active-p)
     :help "Evaluate VARIABLE in the *MATLAB* shell buffer and
display result in a buffer"]
    ["     Command Apropos" matlab-shell-apropos
     :active (matlab-shell-active-p)
     :help "Look for active command in *MATLAB* shell buffer matching a regex"]
    ["     Locate MATLAB function" matlab-shell-locate-fcn
     :active (matlab-shell-active-p)
     :help "Run 'which FCN' in the *MATLAB* shell, and if it's a *.m file open it in a buffer"]
    ["     Switch to *MATLAB* shell" matlab-show-matlab-shell-buffer
     :active (matlab-shell-active-p)
     :help "Switch to the buffer containing the MATLAB process"]
    "---"
    ("Code Sections"
     ["Run section" matlab-sections-run-section
      :active matlab-sections-minor-mode
      :help "Run the current \"%% section\" in
matlab-shell (Unix) or matlab-netshell (Windows)"]
     ["Run prior sections" matlab-sections-run-prior-sections
      :active matlab-sections-minor-mode
      :help "Run all \"%% sections\" prior to the current section in
matlab-shell (Unix) or matlab-netshell (Windows)"]
     ["Move to beginning" matlab-sections-beginning-of-section
      :active matlab-sections-minor-mode
      :help "Move point to the beginning of the current \"%% section\""]
     ["Move to end" matlab-sections-end-of-section
      :active matlab-sections-minor-mode
      :help "Move point to the end of the current \"%% section\""]
     ["Backward section" matlab-sections-backward-section
      :active matlab-sections-minor-mode
      :help "Move point backward to the prior \"%% section\""]
     ["Forward section" matlab-sections-forward-section
      :active matlab-sections-minor-mode
      :help "Move point forward to the next \"%% section\""]
     ["Mark/select section" matlab-sections-mark-section
      :active matlab-sections-minor-mode
      :help "Select the current code selection region by placing the
mark at the beginning of the \"%% section\" and point at the end of the section"]
     ["Move section up" matlab-sections-move-section-up
      :active matlab-sections-minor-mode
      :help "Move the current \"%% section\" up."]
     ["Move section down" matlab-sections-move-section-down
      :active matlab-sections-minor-mode
      :help "Move the current \"%% section\" down."]
     "--"
     ["Sections help" matlab-sections-help])
    "----"
    ("Debug"
     ["Edit File (toggle read-only)" matlab-shell-gud-mode-edit
      :help "Exit MATLAB debug minor mode to edit without exiting MATLAB's K>> prompt."
      :visible gud-matlab-debug-active ]
     ["Add Breakpoint (ebstop in FILE at point)" mlgud-break
      :active (matlab-shell-active-p)
      :help "When MATLAB debugger is active, set break point at current M-file point"]
     ["Remove Breakpoint (ebclear in FILE at point)" mlgud-remove
      :active (matlab-shell-active-p)
      :help "When MATLAB debugger is active, remove break point in FILE at point." ]
     ["List Breakpoints (ebstatus)" mlgud-list-breakpoints
      :active (matlab-shell-active-p)
      :help "List active breakpoints."]
     ["Step (dbstep in)" mlgud-step
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, step into line"]
     ["Next (dbstep)" mlgud-next
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, step one line"]
     ["Finish function  (dbstep out)" mlgud-finish
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, run to end of function"]
     ["Continue (dbcont)" mlgud-cont
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, run to next break point or finish"]
     ["Evaluate Expression" matlab-shell-gud-show-symbol-value
      :active (matlab-any-shell-active-p)
      :help "When MATLAB is active, show value of the symbol under point."]
     ["Show Stack" mlg-show-stack
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, show the stack in a buffer."]

     ;; TODO [future] gud up/down
     ;;  Advertise these more if we can get them working w/ mlgud's frame show.
     ;;      ["Up Call Stack (dbup)" mlgud-up
     ;;       :active gud-matlab-debug-active
     ;;       :help "When MATLAB debugger is active and at break point, go up a frame"]
     ;;      ["Down Call Stack (dbdown)" mlgud-down
     ;;       :active gud-matlab-debug-active
     ;;       :help "When MATLAB debugger is active and at break point, go down a frame"]

     ["Quit debugging (dbquit)" mlgud-stop-subjob
      :active gud-matlab-debug-active
      :help "When MATLAB debugger is active, stop debugging"]
     )

    "----"
    ["View mlint code analyzer messages" flycheck-list-errors
     :help "View mlint code analyzer messages.
Click FlyC in the mode-line for more options."]
    ["View tree-sitter parse errors" matlab-ts-view-parse-errors
     :help "The MATLAB tree-sitter is the engine behind matlab-ts-mode.
Parse errors are not as detailed as mlint code analyzer messages."]
    "----"
    ["Jump to function" imenu]
    "----"
    ("Editing"
     ["Grep comment markers" matlab-ts-mode-grep-comment-markers
      :help "Run grep to find triple-x, fix-me, and to do comment markers."]
     ["Comment marker help" matlab-ts-mode-comment-marker-help]
     ["Fill comment / string / indent function" prog-fill-reindent-defun]
     ["Indent region" indent-region
      :help "Indent active region"]
     ["Justify line" matlab-justify-line]
     ["Comment DWIM" comment-dwim
      :help "Comment Do What I Mean
If region is active comment or uncomment it,
Else insert comment if line is empty,
Else call comment-indent.
See `comment-dwim' for more capabilities."]
     ["Comment/uncomment current line " comment-line
      :help "Comment or uncomment current line and leave point after it."]
     ["Set comment column to point" comment-set-column
      :help "Set the column for when M-; inserts a column"])

    "----"
    ["Check setup" matlab-ts-mode-check-setup]
    ("Customize"
     ["Customize matlab-ts-mode" (lambda ()
                                   (interactive)
                                   (customize-group 'matlab-ts))]
     ["Customize matlab-shell" (lambda ()
                                 (interactive)
                                 (require 'matlab-shell)
                                 (customize-group 'matlab-shell))
      :help "Customize \\[matlab-shell] which is used by matlab-ts-mode for code evaluation."]
     )
    ))

;;; matlab-ts-mode

;;;###autoload
(define-derived-mode matlab-ts-mode prog-mode "MATLAB:ts"
  "Major mode for editing MATLAB files, powered by tree-sitter.

If you have the MATLAB tree-sitter grammar installed,
  (treesit-ready-p \\='matlab)
is t

1. Tell Emacs to use matlab-ts-mode for MATLAB files by adding the
   following to your `user-init-file' which is typically ~/.emacs, or
   add it to your `site-run-file'

    (add-to-list \\='major-mode-remap-alist \\='(matlab-mode . matlab-ts-mode))

2. Tell `org-mode' that #+begin_src matlab ... #end_src blocks should use
   matlab-ts-mode:

     \\[customize-variable] RET org-src-lang-modes RET

   and map matlab to matlab-ts:

      Language name: matlab
      Major mode: matlab-ts

This mode is independent from the classic matlab-mode.el, `matlab-mode',
so configuration variables of that mode, do not affect this mode.

\\{matlab-ts-mode-map}"

  (matlab-ts-mode--check-file-encoding)

  (when (treesit-ready-p 'matlab)
    (treesit-parser-create 'matlab)

    ;; Syntax table - think of this as a "language character descriptor". It tells us what
    ;; characters belong to word like things giving us movement commands e.g. C-M-f, matching
    ;; parens, `show-paren-mode', etc.
    ;; See: ./tests/test-matlab-ts-mode-syntax-table.el
    (set-syntax-table matlab-ts-mode--syntax-table)
    (setq-local syntax-propertize-function #'matlab-ts-mode--syntax-propertize)

    ;; Comments.
    ;; See: tests/test-matlab-ts-mode-comments.el
    (setq-local comment-start      "% ")
    (setq-local comment-end        "")
    (setq-local comment-start-skip "%\\s-+")

    ;; Setup `forward-page' and `backward-page' to use ^L or "%% heading" comments
    ;; See: ./tests/test-matlab-ts-mode-page.el
    (setq-local page-delimiter "^\\(?:\f\\|\\s-*%%\\(?:\\s-\\|\n\\)\\)")

    ;; Font-lock.
    ;; See: ./tests/test-matlab-ts-mode-font-lock.el
    (setq-local treesit-font-lock-level matlab-ts-mode-font-lock-level)
    (setq-local treesit-font-lock-settings matlab-ts-mode--font-lock-settings)
    (setq-local treesit-font-lock-feature-list
                '((comment comment-special comment-marker definition fcn-name-value)
                  (keyword operator string type command-name command-arg)
                  (variable builtins namespace-builtins number bracket delimiter)
                  (syntax-error)))

    ;; Indent.
    ;; See: ./tests/test-matlab-ts-mode-indent.el
    (matlab-ts-mode--set-function-indent-level) ;; Set function indent level on file load
    (setq-local indent-tabs-mode nil) ;; For consistency between Unix and Windows we don't use TABs.
    (setq-local treesit-simple-indent-rules
                (if treesit--indent-verbose ;; add debugging print as first rule?
                    (list (append `,(list (caar matlab-ts-mode--indent-rules))
                                  (list matlab-ts--indent-debug-rule)
                                  (cdar matlab-ts-mode--indent-rules)))
                  matlab-ts-mode--indent-rules))

    ;; Thing settings for movement, etc.
    ;; See: tests/test-matlab-ts-mode-thing-settings.el
    (setq-local treesit-thing-settings matlab-ts-mode--thing-settings)

    ;; Change Logs.
    ;; See: tests/test-matlab-ts-mode-treesit-defun-name.el
    (setq-local treesit-defun-name-function #'matlab-ts-mode--defun-name)

    ;; M-x imenu
    (matlab-ts-mode--imenu-setup)

    ;; M-x outline-minor-mode
    ;; See: ./tests/test-matlab-ts-mode-outline.el
    (setq-local treesit-outline-predicate #'matlab-ts-mode--outline-predicate)

    ;; Save hook.
    ;; See: ./tests/test-matlab-ts-mode-on-save-fixes.el
    (add-hook 'write-contents-functions #'matlab-ts-mode--write-file-callback -99 t)

    ;; Electric pair mode.
    ;; See tests/test-matlab-ts-mode-electric-pair.el
    (setq-local electric-pair-inhibit-predicate #'matlab-ts-mode--electric-pair-inhibit-predicate)

    ;; show-paren-mode. Highlight parens OR function/end, if/end, etc. type blocks.
    ;; See: tests/test-matlab-ts-mode-show-paren.el
    (setq-local show-paren-data-function #'matlab-ts-mode--show-paren-or-block)

    ;; Final newline and electric ends.
    (setq-local require-final-newline 'visit-save)
    (add-hook 'post-self-insert-hook #'matlab-ts-mode--post-insert-callback -99 t)

    ;; give each file it's own parameter history
    (setq-local matlab-shell-save-and-go-history '("()"))

    ;; Activate MATLAB script ";; heading" matlab-sections-minor-mode if needed
    (matlab-sections-auto-enable-on-mfile-type-fcn (matlab-ts-mode--mfile-type))

    ;; TODO [future] Indent - complex for statement
    ;;         function a = foo(inputArgument1)
    ;;             for (idx = (a.b.getStartValue(((inputArgument1 + someOtherFunction(b)) * 2 - ...
    ;;                                            offset))) ...
    ;;     TAB>         : ...
    ;;                  2 * (a.b.myFcn(inputArgument1, ...
    ;;                                 'end') + ...
    ;;                       100))
    ;;                 disp(idx)
    ;;             end
    ;;         end
    ;;
    ;; TODO [future] Improve semantic movement
    ;;      thing-settings doesn't work well. Directly implement C-M-f, M-e, etc.
    ;;
    ;; TODO [future] add matlab-sections-minor-mode indicator in mode line and make it clickable so
    ;;      it can be turned off
    ;;
    ;; TODO [future] add error indicator in mode line and make it clickable so one can see the
    ;;      errors.  Also underline them.

    (treesit-major-mode-setup)

    ;; Correct forward-sexp setup created by `treesit-major-mode' so that for parenthesis, brackets,
    ;; braces, and comments we do normal s-expression matching using parenthesis. This fix is need
    ;; for our tests work. We need to evaluate (t-utils-NAME ....) expressions from within comments
    ;; using C-x C-e and this leverages forward-sexp to match up the parentheses.
    (setq-local forward-sexp-function #'matlab-ts-mode--forward-sexp)

    ;; M-x matlab-shell Debugger interconnect
    (let ((km (current-local-map)))
      (substitute-key-definition 'read-only-mode #'matlab-toggle-read-only km global-map))

    ))

;;; Check setup

(defvar flycheck-mode) ;; from flycheck.el
(declare-function flycheck-list-errors "flycheck.el")

(defun matlab-ts-mode-check-setup ()
  "Check that Emacs has been setup fully for use with MATLAB."
  (interactive)

  ;; TODO [future] check that we have the latest versions of packages

  (let ((msg ""))

    ;;---------;;
    ;; company ;;
    ;;---------;;
    (if (not (featurep 'flycheck))
        (setq msg (concat msg "\
- [ ] Package company is not installed (needed for TAB completions).
      To install: M-x package-install RET company RET\n"))
      (setq msg (concat msg "\
- [x] Package company is installed (needed for TAB completions)\n")))

    ;;--------------------;;
    ;; mlint and flycheck ;;
    ;;--------------------;;
    (cond
     ((not matlab-ts-mode-enable-mlint-flycheck)
      (setq msg (concat msg "\
- MATLAB mlint is disabled.  To enable,
  M-x customize-variable RET matlab-ts-mode-enable-mlint-flycheck\n")))

     ((not (featurep 'flycheck))
      (setq msg (concat msg "\
- [ ] Package flycheck is not installed (needed to view code issues as you type).
      To install, see C-h v matlab-ts-mode-enable-mlint-flycheck\n")))

     ((not (matlab--get-mlint-exe))
      (setq msg (concat msg "\
- [ ] MATLAB mlint is not found, to fix place /path/to/MATLAB-install on your system path\n")))

     ((not flycheck-mode)
      (setq msg (concat msg "\
- [ ] M-x flycheck-mode is not enabled.  A fix is to add to ~/.emacs
      (global-flycheck-mode)\n")))

     (t
      (setq msg (concat msg (format "\
- [x] matlab-mlint flycheck is setup.
      Use \"%s\" to view mlint errors or click FlyC on the mode line.\n"
                                    (substitute-command-keys "\\[flycheck-list-errors]"))))))

    ;;----------;;
    ;; lsp-mode ;;
    ;;----------;;

    ;; TODO [future] check lsp-matlab configuration, location of matlabls index.js
    ;; TODO [future] check that we have latest matlabls version
    ;; TODO [future] add auto-install of the language server, perhaps using the vscode bundle?

    (cond
     ((not (featurep 'lsp-mode))
      (setq msg (concat msg "\
- [ ] Package lsp-mode is not installed.
      lsp-mode provides code navigation, symbol rename, and more.
      To install, see
         https://github.com/mathworks/Emacs-MATLAB-Mode/blob/default/doc/\
matlab-language-server-lsp-mode.org\n")))

     ((and (not (member 'lsp          matlab-ts-mode-hook))
           (not (member 'lsp-deferred matlab-ts-mode-hook)))
      (setq msg (concat msg "\
- The matlab-ts-mode-hook does not contain #'lsp or #'lsp-deferred.  To fix, see
  https://github.com/mathworks/Emacs-MATLAB-Mode/blob/default/doc/\
matlab-language-server-lsp-mode.org\n"
                        )))

     (t
      (setq msg (concat msg "\
- [x] lsp-mode for code navigation, symbol rename, and more is setup\n"))))

    ;; Display check result
    (message "%s" msg)))

(provide 'matlab-ts-mode)
;;; matlab-ts-mode.el ends here

;; LocalWords:  SPDX gmail dylib libtree treesit builtins defface defcustom flycheck MLint MELPA LF
;; LocalWords:  defun progn setq MEC propertize varname eobp mcm defmacro sexp defconst bos eos prev
;; LocalWords:  classdef's Fontify fontified fontify gethash pragma's multioutput pred dir's bol cdr
;; LocalWords:  NPS BUF myfcn pcase xr repeat:nil docstring numberp imenu alist nondirectory mapc ws
;; LocalWords:  funcall mfile elec foo'bar mapcar lsp noerror alnum featurep grep'ing mapconcat wie
;; LocalWords:  Keymap keymap netshell gud ebstop mlgud ebclear ebstatus mlg mlgud's subjob reindent
;; LocalWords:  DWIM dwim parens caar cdar utils fooenum mcode CRLF cmddual lang nconc listify kbd
;; LocalWords:  matlabls vscode buf dolist sp ppss