badness 0.5.0

A language server, formatter, and linter for LaTeX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
//! The badness language server (Phase 4 + the ra-style threading follow-up).
//!
//! badness uses **`lsp-server` + `lsp-types`** (rust-analyzer's synchronous
//! stack), *not* tower-lsp-server — see the LSP note in `AGENTS.md`. salsa's
//! single-writer / snapshot-readers model composes cleanly with `lsp-server`'s
//! sync main loop.
//!
//! Scope: full-document **formatting**, a **document-symbol** outline,
//! **completion** (command/environment names, `\ref` keys, file paths), and
//! pushed parser **diagnostics**. Further features (hover, go-to-def, range
//! formatting) are deferred.
//!
//! ## Architecture
//!
//! Three roles, message-passing between them:
//!
//! - **Main loop** ([`main_loop`]) — owns [`GlobalState`] (the open-document
//!   buffers + editor settings), holds **no** database. It routes
//!   `connection.receiver` messages to the worker, applies incremental
//!   `didChange` edits to its buffers, resolves the [`FormatStyle`] for each
//!   format request, and forwards [`Outbound`] results from the workers back to
//!   the client (version-gating diagnostics).
//! - **Worker thread** ([`Worker`]) — the *sole* database writer. A buffer edit
//!   is a write-phase `upsert_file` (`&mut db`) — plus a one-time
//!   [`seed_dir`](Worker::seed_dir) that pulls the rest of the project off disk —
//!   followed by a read-phase *analyze* (parse diagnostics + lint over an interned
//!   `Project`) dispatched onto the read pool, kept to at most one in flight via
//!   [`decide`] and superseded by a fresher edit of the same URI. When seeding
//!   grows the member set, every open document is re-linted ([`Outbound::RelintAll`]).
//!   `didClose` evicts the file.
//! - **Read pool** (`task_pool`) — runs the diagnostics analyze and formatting
//!   reads off a short-lived [`Analysis`] snapshot, each wrapped in
//!   [`salsa::Cancelled::catch`] so a racing write either drops the read
//!   (diagnostics) or makes it recompute from the captured text (formatting).
//!
//! > Note (raised per AGENTS tenet): a whole-file `.tex` parse is sub-ms, so the
//! > `decide`/supersede scheduler has little to actually preempt *today* — it is
//! > built to match the documented target architecture and starts paying off the
//! > moment an expensive async read (hover/completion/cross-file lint) lands.
//!
//! **Filesystem path as the salsa key.** A `file:` document URI is decoded to its
//! real (normalized) filesystem path ([`uri_to_path`]); a non-`file` buffer
//! (untitled, etc.) falls back to the URI string as a synthetic key and never
//! joins a project. Open-buffer text always comes from `didOpen`/`didChange`,
//! while non-open project members (siblings reached via `\input`/`\bibliography`)
//! are read once off disk — see [`Worker::seed_dir`] — so `undefined-ref`,
//! cross-file `duplicate-label`, and `undefined-citation` can fire live. Edits to
//! a non-open member on disk are not yet watched (`workspace/didChangeWatchedFiles`
//! is a follow-up; see `TODO.md`).

// `lsp_types::Uri` (a `fluent_uri` newtype) carries an internal `Cell` tag for
// its mutable-view mechanism, which trips `clippy::mutable_key_type` when a `Uri`
// is used as a map key. Our URIs are owned + parsed (never "taken"), and `Uri`'s
// `Hash`/`Eq` go through `as_str()`, so this is sound. Allow it module-wide.
#![allow(clippy::mutable_key_type)]

mod code_action;
mod completion_resolve;
mod folding;
mod hover;
mod task_pool;

use std::collections::{HashMap, HashSet};
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::thread::JoinHandle;

use crossbeam_channel::{Receiver, Sender, select, unbounded};
use lsp_server::{Connection, ErrorCode, Message, Notification, Request, RequestId, Response};
use lsp_types::notification::{
    DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument,
    DidOpenTextDocument, Notification as _, PublishDiagnostics,
};
use lsp_types::request::{
    CodeActionRequest, Completion, DocumentDiagnosticRequest, DocumentHighlightRequest,
    DocumentSymbolRequest, FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest,
    PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _,
    ResolveCompletionItem, WorkspaceDiagnosticRefresh, WorkspaceSymbolRequest,
};
use lsp_types::{
    CodeActionParams, CodeActionProviderCapability, CompletionItem, CompletionItemKind,
    CompletionList, CompletionOptions, CompletionParams, CompletionResponse, Diagnostic,
    DiagnosticOptions, DiagnosticServerCapabilities, DiagnosticSeverity,
    DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams,
    DidChangeWatchedFilesRegistrationOptions, DidCloseTextDocumentParams,
    DidOpenTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport,
    DocumentDiagnosticReportResult, DocumentFormattingParams, DocumentHighlight,
    DocumentHighlightKind, DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbol,
    DocumentSymbolParams, DocumentSymbolResponse, FileChangeType, FileSystemWatcher, FoldingRange,
    FoldingRangeParams, FoldingRangeProviderCapability, FullDocumentDiagnosticReport, GlobPattern,
    GotoDefinitionParams, GotoDefinitionResponse, HoverParams, HoverProviderCapability,
    InsertTextFormat, Location, NumberOrString, OneOf, Position, PrepareRenameResponse,
    PublishDiagnosticsParams, Range, ReferenceParams, Registration, RegistrationParams,
    RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameOptions,
    RenameParams, ServerCapabilities, SymbolKind, TextDocumentContentChangeEvent,
    TextDocumentPositionParams, TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit,
    UnchangedDocumentDiagnosticReport, Uri, WorkspaceEdit, WorkspaceSymbol, WorkspaceSymbolParams,
    WorkspaceSymbolResponse,
};
use rowan::{TextRange, TextSize};
use salsa::Database as _;
use serde::Deserialize;
use smol_str::SmolStr;

use crate::bib::completion::{
    BibCandidateKind, BibCompletionCandidate, bib_candidates, classify_bib_context,
};
use crate::bib::outline::{BibOutlineItem, outline as bib_outline};
use crate::bib::semantic::Model as BibModel;
use crate::bib::{
    format_node as bib_format_node, format_with_style as bib_format_with_style, parse as bib_parse,
};
use crate::completion::{CandidateKind, CompletionCandidate, CompletionContext, FileArgKind};
use crate::config::{Config, LintConfig};
use crate::file_discovery::{ExcludeFilter, FileKind, collect_lint_files, file_kind_or_tex};
use crate::formatter::{
    FormatStyle, WrapMode, format_node_range_with_signatures, format_node_with_signatures,
    format_with_style_flavored,
};
use crate::incremental::{Analysis, IncrementalDatabase};
use crate::linter::{RuleSelection, Severity, lint_document};
use crate::parser::{parse, parse_with_flavor};
use crate::project::{ProjectMember, ResolvedCitations, ResolvedLabels};
use crate::semantic::{OutlineItem, OutlineSymbol, SemanticModel, SignatureDb, outline};
use crate::syntax::SyntaxNode;
use crate::text::LineIndex;

use task_pool::{Spawner, TaskPool, read_pool_size};

/// A boxed error suitable for the LSP entry point.
type DynError = Box<dyn std::error::Error + Sync + Send>;

/// Start the language server over stdio, blocking until the client disconnects.
pub fn run() -> Result<(), DynError> {
    let (connection, io_threads) = Connection::stdio();
    serve(connection)?;
    io_threads.join()?;
    Ok(())
}

/// Perform the `initialize` handshake on `connection`, then run the message loop
/// until shutdown. Split out from [`run`] so tests can drive it over a
/// `Connection::memory()` pair.
pub fn serve(connection: Connection) -> Result<(), DynError> {
    let capabilities = serde_json::to_value(server_capabilities())?;
    let init_params = connection.initialize(capabilities)?;
    main_loop(connection, init_params)
}

/// Advertise what we support: **incremental** text sync + whole-document
/// formatting. Diagnostics are offered both ways — *pushed* via
/// `publishDiagnostics` (the default, needing no flag) and *pulled* via
/// `textDocument/diagnostic` (the `diagnostic_provider` capability). A client that
/// advertises pull support is served pull-only; everyone else keeps push (see
/// `supports_pull_diagnostics`). `workspace/diagnostic` is deferred (see `TODO.md`).
fn server_capabilities() -> ServerCapabilities {
    ServerCapabilities {
        text_document_sync: Some(TextDocumentSyncCapability::Kind(
            TextDocumentSyncKind::INCREMENTAL,
        )),
        diagnostic_provider: Some(DiagnosticServerCapabilities::Options(DiagnosticOptions {
            identifier: Some("badness".to_owned()),
            // Editing an `\input` target / `.bib` changes this file's
            // `undefined-ref` / `undefined-citation` set, so a pull in one file can
            // depend on another's content.
            inter_file_dependencies: true,
            // Deferred: workspace pull is a streaming/long-poll protocol that fits
            // the one-shot read-job model poorly (see `TODO.md`).
            workspace_diagnostics: false,
            work_done_progress_options: Default::default(),
        })),
        document_formatting_provider: Some(OneOf::Left(true)),
        // Format the editor selection, expanded to whole top-level blocks (see
        // `compute_range_format`).
        document_range_formatting_provider: Some(OneOf::Left(true)),
        document_symbol_provider: Some(OneOf::Left(true)),
        // Aggregate the per-file outline (sections, labels, floats, theorems,
        // macros, environments) across every tracked project file. No lazy
        // `resolve`, so each result carries its full `Location`.
        workspace_symbol_provider: Some(OneOf::Left(true)),
        // Surface linter autofixes as quick-fixes. `Simple(true)` returns
        // fully-built actions (no `codeAction/resolve` step).
        code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
        hover_provider: Some(HoverProviderCapability::Simple(true)),
        definition_provider: Some(OneOf::Left(true)),
        references_provider: Some(OneOf::Left(true)),
        // Shade a cross-reference key and every same-key occurrence in the buffer.
        // Single-file (the lightweight cousin of `references_provider`).
        document_highlight_provider: Some(OneOf::Left(true)),
        // Rename a `\label`/`\cite` key and every referencing command across its
        // namespace. `prepare_provider` lets the client pre-validate the cursor and
        // anchor the prepare range to the key token.
        rename_provider: Some(OneOf::Right(RenameOptions {
            prepare_provider: Some(true),
            work_done_progress_options: Default::default(),
        })),
        folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
        completion_provider: Some(CompletionOptions {
            // `\` opens command/env names; `{` opens a name/key/path argument;
            // `/` re-triggers path segments. Snippet support is read off the
            // client's capabilities, so no extra server flag is needed.
            trigger_characters: Some(vec![
                "\\".to_owned(),
                "{".to_owned(),
                "/".to_owned(),
                "@".to_owned(),
            ]),
            // A highlighted item is sent back via `completionItem/resolve` to gain
            // its signature/citation detail lazily (see [`completion_resolve`]).
            resolve_provider: Some(true),
            ..Default::default()
        }),
        ..Default::default()
    }
}

/// An open document buffer: its current text and the version it is at.
struct Document {
    text: String,
    version: i32,
}

/// The main loop's state: open-document buffers and the client's editor settings.
/// Holds no database — the worker thread owns that.
struct GlobalState {
    documents: HashMap<Uri, Document>,
    editor_settings: EditorSettings,
    /// Per-document config resolutions, keyed by the document's **anchor directory**
    /// (its parent). A discovered `badness.toml` is authoritative; editor settings
    /// are the fallback. Populated lazily by [`GlobalState::resolve_settings`] and
    /// cleared wholesale on `didChangeConfiguration`.
    config_cache: HashMap<PathBuf, ResolvedSettings>,
    /// The client advertised `textDocument/diagnostic` pull support, so we serve
    /// diagnostics pull-only and **suppress** the `publishDiagnostics` push (the two
    /// are mutually exclusive, matching rust-analyzer/panache).
    supports_pull_diagnostics: bool,
    /// The client advertised `workspace.diagnostic.refreshSupport`, so a cross-file
    /// change can nudge it to re-pull via `workspace/diagnostic/refresh` (the pull
    /// analog of the push path's `RelintAll`).
    supports_diagnostic_refresh: bool,
    /// The client advertised `workspace.didChangeWatchedFiles.dynamicRegistration`, so
    /// on `initialized` we register watchers for `**/*.{tex,bib}` and `badness.toml`
    /// and reanalyze on on-disk edits to non-open project files.
    supports_dynamic_watchers: bool,
    /// Monotonic id for server→client requests (e.g. `workspace/diagnostic/refresh`,
    /// `client/registerCapability`). Namespaced from the client's request ids, so they
    /// never collide.
    next_request_id: i32,
}

/// Formatting settings supplied by the editor, as `initializationOptions` at
/// startup or via `workspace/didChangeConfiguration`. A fallback beneath the
/// per-request [`FormattingOptions`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase", default)]
struct EditorSettings {
    line_width: Option<u32>,
    indent_width: Option<u32>,
}

impl EditorSettings {
    /// Extract our settings from a client-supplied JSON value. Accepts either the
    /// bare options object or a tree namespaced under a `"badness"` key (how
    /// `workspace/didChangeConfiguration` clients typically scope settings).
    fn from_client_value(value: &serde_json::Value) -> Self {
        let section = value
            .get("badness")
            .filter(|v| v.is_object())
            .unwrap_or(value);
        serde_json::from_value(section.clone()).unwrap_or_default()
    }

    /// Overlay these settings onto the formatter defaults.
    fn to_format_style(&self) -> FormatStyle {
        let mut style = FormatStyle::default();
        if let Some(width) = self.line_width {
            style.line_width = width as usize;
        }
        if let Some(width) = self.indent_width {
            style.indent_width = width as usize;
        }
        style
    }
}

/// A document's resolved configuration: the formatter [`FormatStyle`] (with `wrap`
/// still a placeholder — the file kind decides it per request) plus the lint
/// selection. Built from a discovered `badness.toml` (file-wins) or, absent one,
/// from the editor settings. Cached per anchor dir in [`GlobalState::config_cache`].
#[derive(Debug, Clone)]
struct ResolvedSettings {
    /// Width knobs set; `wrap` is the [`WrapMode::default`] placeholder.
    style: FormatStyle,
    /// Configured paragraph wrap, if any. `None` ⇒ the file-kind default applies.
    wrap_override: Option<WrapMode>,
    /// Whether a `badness.toml` governed this resolution. When `true` the file
    /// config wins outright and a request's `tab_size` is ignored.
    config_present: bool,
    /// The `[lint]` `select`/`ignore` selection (default — every rule — when no file).
    lint: LintConfig,
    /// The sibling-discovery exclude filter, rooted at the config's directory. The
    /// exclude-nothing [`ExcludeFilter::none`] when no config governs (editor
    /// fallback) — preserving the unfiltered walk that path always did.
    exclude: ExcludeFilter,
}

impl ResolvedSettings {
    /// Resolution from a discovered config (when `present`), else from the editor
    /// settings, applying the file-wins rule. The `exclude` filter is left
    /// exclude-nothing here; [`resolve_settings`] compiles and installs the real
    /// one (it holds the config's root directory).
    ///
    /// [`resolve_settings`]: GlobalState::resolve_settings
    fn from_config(config: &Config, present: bool, editor: &EditorSettings) -> Self {
        if present {
            Self {
                style: FormatStyle::from(&config.format),
                wrap_override: config.format.wrap.map(Into::into),
                config_present: true,
                lint: config.lint.clone(),
                exclude: ExcludeFilter::none(),
            }
        } else {
            Self::from_editor(editor)
        }
    }

    /// Editor-settings-only resolution: width knobs over the built-in defaults, no
    /// configured wrap, the full default rule set, and no exclude filter.
    fn from_editor(editor: &EditorSettings) -> Self {
        Self {
            style: editor.to_format_style(),
            wrap_override: None,
            config_present: false,
            lint: LintConfig::default(),
            exclude: ExcludeFilter::none(),
        }
    }

    /// The active lint-rule set this config implies (unknown ids are dropped; the
    /// CLI surfaces them, the LSP has no good channel to yet).
    fn rule_selection(&self) -> RuleSelection {
        RuleSelection::resolve(self.lint.select.as_deref(), &self.lint.ignore).0
    }
}

impl GlobalState {
    /// Resolve (and cache) the [`ResolvedSettings`] for `uri`'s document: discover a
    /// `badness.toml` from the document's anchor directory (its parent), falling back
    /// to the editor settings when none is found. Cached by anchor dir, so repeated
    /// format/lint requests in a workspace pay the filesystem walk once.
    ///
    /// A non-`file` buffer (untitled) or a directory-less / unreadable / malformed
    /// config resolves to the editor settings and is **not** cached, so fixing a
    /// broken `badness.toml` takes effect on the next request without a restart.
    fn resolve_settings(&mut self, uri: &Uri) -> ResolvedSettings {
        let Some(anchor) = uri_to_fs_path(uri).and_then(|p| p.parent().map(Path::to_path_buf))
        else {
            return ResolvedSettings::from_editor(&self.editor_settings);
        };
        if let Some(cached) = self.config_cache.get(&anchor) {
            return cached.clone();
        }
        let resolved = match Config::resolve(None, false, &anchor) {
            Ok((config, source)) => {
                let present = source.is_some();
                let mut resolved =
                    ResolvedSettings::from_config(&config, present, &self.editor_settings);
                if present {
                    // Compile the sibling-discovery exclude filter, rooted at the
                    // config's directory (the same rule as the CLI's
                    // `build_exclude_filter`; the LSP contributes no `--exclude`).
                    // A malformed pattern leaves the exclude-nothing default rather
                    // than failing resolution — there is no good channel to report it.
                    let root = source.as_deref().and_then(Path::parent).unwrap_or(&anchor);
                    if let Ok(filter) = ExcludeFilter::new(root, &config.exclude_patterns(&[])) {
                        resolved.exclude = filter;
                    }
                }
                resolved
            }
            // No good channel to report a bad/unreadable config; fall back without
            // caching so a fix is picked up next time.
            Err(_) => return ResolvedSettings::from_editor(&self.editor_settings),
        };
        self.config_cache.insert(anchor, resolved.clone());
        resolved
    }
}

/// A job from the main loop to the worker thread.
enum WorkerJob {
    /// A buffer edit (from `didOpen` or `didChange`): write the full text into the
    /// db, then (re)analyze diagnostics.
    Edit {
        uri: Uri,
        path: PathBuf,
        text: String,
        version: i32,
        kind: FileKind,
        /// The document's resolved lint-rule selection, applied to the analyze.
        rules: RuleSelection,
        /// The document's resolved exclude filter, applied to sibling discovery
        /// ([`Worker::seed_dir`]). Built on the main side because the worker holds
        /// no config; exclude-nothing when no `badness.toml` governs.
        exclude: ExcludeFilter,
    },
    /// `didClose`: evict the file from the db. Diagnostics are cleared directly by
    /// the main loop.
    Close { path: PathBuf },
    /// A `workspace/didChangeWatchedFiles` event for a **non-open** `.tex`/`.bib`
    /// project file: re-read it from disk (or evict it on delete) and re-lint every
    /// open document, since a sibling's labels/cites may have changed. The main loop
    /// has already confirmed the path is not an open editor buffer (whose overlay text
    /// is authoritative), so this path deliberately re-reads disk.
    WatchedChange { path: PathBuf, deleted: bool },
    /// A formatting request: format on the read pool and reply to `id`.
    Format {
        id: RequestId,
        path: PathBuf,
        text: String,
        style: FormatStyle,
        kind: FileKind,
    },
    /// A range-formatting request: like [`WorkerJob::Format`] but bounded to the
    /// editor selection (expanded to whole top-level blocks on the read pool).
    RangeFormat {
        id: RequestId,
        path: PathBuf,
        text: String,
        style: FormatStyle,
        kind: FileKind,
        range: Range,
    },
    /// A document-symbol request: build the outline on the read pool and reply to
    /// `id`.
    Symbols {
        id: RequestId,
        path: PathBuf,
        text: String,
        kind: FileKind,
    },
    /// A `workspace/symbol` request: aggregate every tracked file's outline on the
    /// read pool and reply to `id` with the matches for `query`. Cross-file (it
    /// scans the whole project), so the worker snapshots project membership when it
    /// dispatches, like [`References`](Self::References).
    WorkspaceSymbols { id: RequestId, query: String },
    /// A folding-range request: compute foldable regions on the read pool and reply
    /// to `id`. Single-file like [`Symbols`](Self::Symbols), with no project snapshot.
    FoldingRange {
        id: RequestId,
        path: PathBuf,
        text: String,
        kind: FileKind,
    },
    /// A completion request: classify the cursor and build candidates on the read
    /// pool and reply to `id`. Carries the `uri` (the salsa-key path is derived from
    /// it) so file-path completion can read the document's on-disk directory.
    Completion {
        id: RequestId,
        uri: Uri,
        text: String,
        position: Position,
    },
    /// A completion-resolve request: attach lazy signature/citation detail to a
    /// highlighted item on the read pool and reply to `id`. The item's `data`
    /// payload is self-contained, so no document buffer is needed; but the lookup
    /// is cross-file (signature scope, project bibliography), so the worker
    /// snapshots project membership when it dispatches, like [`Hover`](Self::Hover).
    ResolveCompletion {
        id: RequestId,
        // Boxed: a `CompletionItem` is large and would bloat every `WorkerJob`.
        item: Box<CompletionItem>,
    },
    /// A hover request: describe the command/environment signature or `\cite` entry
    /// under the cursor on the read pool and reply to `id`. Cross-file (the signature
    /// scope folds in loaded packages, and a `\cite` resolves against the project
    /// bibliography), so the worker snapshots project membership when it dispatches,
    /// like [`GotoDefinition`](Self::GotoDefinition).
    Hover {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
    },
    /// A go-to-definition request: resolve the `\ref`/`\cite` under the cursor to
    /// its `\label`/bib entry on the read pool and reply to `id`. Cross-file, so
    /// the worker snapshots project membership when it dispatches (like an analyze).
    GotoDefinition {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
    },
    /// A find-references request: enumerate every `\ref`/`\cite` use of the
    /// label/key under the cursor on the read pool and reply to `id`. Cross-file
    /// (and invokable from a definition site), so the worker snapshots project
    /// membership when it dispatches, like [`GotoDefinition`](Self::GotoDefinition).
    References {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        include_declaration: bool,
    },
    /// A `documentHighlight` request: shade the cross-reference key under the cursor
    /// and every same-key occurrence in the *same* buffer. Single-file (the
    /// lightweight cousin of [`References`](Self::References)); dispatched to the read
    /// pool like the others to keep the threading model uniform.
    DocumentHighlight {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
    },
    /// A `prepareRename` request: confirm the cursor sits on a renameable label/cite
    /// key and reply with that key's range + placeholder. Resolved off a single
    /// parse of the cursor buffer; no cross-file work, but dispatched to the read
    /// pool like the others to keep the threading model uniform.
    PrepareRename {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
    },
    /// A `rename` request: build the project-wide [`WorkspaceEdit`] renaming the
    /// label/cite key under the cursor and every referencing command. Cross-file,
    /// so the worker snapshots project membership when it dispatches, like
    /// [`References`](Self::References).
    Rename {
        id: RequestId,
        path: PathBuf,
        text: String,
        position: Position,
        new_name: String,
    },
    /// A `textDocument/diagnostic` pull request: compute diagnostics **on demand**
    /// off a fresh snapshot and reply to `id`. Cross-file (like an analyze), so the
    /// worker snapshots project membership when it dispatches. Carries the live
    /// `text` only as the cancellation fallback's source — currency comes from the
    /// FIFO `job_tx`: the preceding `didChange`'s `Edit` upserts before this job is
    /// handled, so the snapshot is already current (no debounce, no staleness).
    Diagnostic {
        id: RequestId,
        path: PathBuf,
        text: String,
        kind: FileKind,
        previous_result_id: Option<String>,
        /// The document's resolved lint-rule selection, applied to the report.
        rules: RuleSelection,
    },
    /// A `textDocument/codeAction` request: re-lint the buffer off a fresh snapshot
    /// and reply with a quick-fix per fix-carrying finding overlapping `range`.
    /// Cross-file (like a [`Diagnostic`](Self::Diagnostic) pull), so the worker
    /// snapshots project membership when it dispatches; `uri` is needed to key the
    /// resulting [`WorkspaceEdit`].
    CodeAction {
        id: RequestId,
        uri: Uri,
        path: PathBuf,
        text: String,
        kind: FileKind,
        range: Range,
        /// The document's resolved lint-rule selection, applied to the findings.
        rules: RuleSelection,
    },
}

/// A result from a worker (the lint thread or a read-pool job) back to the main
/// loop, which forwards it to the client.
enum Outbound {
    /// Push diagnostics for `uri` at `version` (gated against the live buffer).
    Diagnostics {
        uri: Uri,
        version: i32,
        diags: Vec<Diagnostic>,
    },
    /// A request response (e.g. a formatting edit array).
    Response(Response),
    /// Project membership grew (the worker discovered on-disk siblings), so the
    /// cross-file resolution may have changed for *every* open document. Re-lint
    /// them all.
    RelintAll,
}

/// Map a document URI to the path the salsa file cache is keyed by. For a `file:`
/// URI this is the real filesystem path (percent-decoded), so `\input`/bib
/// resolution and on-disk sibling reads share one path space and a project can be
/// assembled. A non-`file` buffer (untitled, etc.) falls back to the URI string as
/// a synthetic key; it simply never joins a project.
fn uri_to_path(uri: &Uri) -> PathBuf {
    uri_to_fs_path(uri).unwrap_or_else(|| PathBuf::from(uri.as_str()))
}

/// Which language pipeline a document feeds, by its path extension. Defaults to
/// [`FileKind::Tex`] for anything that is not a `.bib` file (including unsaved
/// buffers with no extension), matching the conservative CLI/stdin behavior. The
/// resolution itself lives in [`file_kind_or_tex`], shared with the CLI's
/// `--stdin-filepath`.
fn file_kind_for(path: &Path) -> FileKind {
    file_kind_or_tex(path)
}

/// The current project membership of a read snapshot, as sorted-by-caller
/// [`ProjectMember`]s — the snapshot-side counterpart of
/// [`GlobalState`]'s `project_members`, used by a format read to intern a
/// `Project` for [`Analysis::scope_signatures`].
fn members_of(snapshot: &Analysis) -> Vec<ProjectMember> {
    snapshot
        .tracked_files()
        .into_iter()
        .map(|(path, file)| {
            let kind = file_kind_for(&path);
            ProjectMember { file, path, kind }
        })
        .collect()
}

/// Read the client's diagnostic capabilities from the `initialize` params, as
/// `(supports_pull, supports_refresh)`. Pointer-walks the JSON (like
/// [`EditorSettings::from_client_value`]) rather than deserializing the whole
/// `ClientCapabilities`: pull support is the mere presence of
/// `capabilities.textDocument.diagnostic`; refresh support is
/// `capabilities.workspace.diagnostic.refreshSupport == true`.
fn client_diagnostic_support(init_params: &serde_json::Value) -> (bool, bool) {
    let caps = init_params.get("capabilities");
    let supports_pull = caps
        .and_then(|c| c.get("textDocument"))
        .and_then(|t| t.get("diagnostic"))
        .is_some();
    let supports_refresh = caps
        .and_then(|c| c.get("workspace"))
        .and_then(|w| w.get("diagnostic"))
        .and_then(|d| d.get("refreshSupport"))
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);
    (supports_pull, supports_refresh)
}

/// Whether the client supports dynamically registered file watchers, i.e.
/// `capabilities.workspace.didChangeWatchedFiles.dynamicRegistration == true`.
/// Pointer-walks the JSON like [`client_diagnostic_support`]. When `false` we skip
/// registration and fall back to seed-on-open: on-disk edits to non-open includes go
/// unnoticed until something re-seeds the directory.
fn client_watched_files_support(init_params: &serde_json::Value) -> bool {
    init_params
        .get("capabilities")
        .and_then(|c| c.get("workspace"))
        .and_then(|w| w.get("didChangeWatchedFiles"))
        .and_then(|d| d.get("dynamicRegistration"))
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

/// The blocking message loop. Owns [`GlobalState`]; spawns the worker thread and
/// the read pool, then shuttles messages between the client and the workers.
fn main_loop(connection: Connection, init_params: serde_json::Value) -> Result<(), DynError> {
    let editor_settings = init_params
        .get("initializationOptions")
        .map(EditorSettings::from_client_value)
        .unwrap_or_default();
    let (supports_pull_diagnostics, supports_diagnostic_refresh) =
        client_diagnostic_support(&init_params);
    let supports_dynamic_watchers = client_watched_files_support(&init_params);
    let mut state = GlobalState {
        documents: HashMap::new(),
        editor_settings,
        config_cache: HashMap::new(),
        supports_pull_diagnostics,
        supports_diagnostic_refresh,
        supports_dynamic_watchers,
        next_request_id: 1,
    };

    // Register on-disk watchers now: `lsp-server`'s `Connection::initialize` already
    // consumed the client's `initialized` notification, so we never see it as a
    // notification — the post-handshake point here is the LSP-legal place to fire
    // dynamic registrations.
    register_file_watchers(&connection, &mut state);

    let read_pool = TaskPool::new("badness-lsp-read", read_pool_size());
    let (job_tx, job_rx) = unbounded::<WorkerJob>();
    let (out_tx, out_rx) = unbounded::<Outbound>();
    let worker = spawn_worker(job_rx, out_tx, read_pool.spawner());

    loop {
        select! {
            recv(connection.receiver) -> msg => {
                let Ok(msg) = msg else { break };
                match msg {
                    Message::Request(req) => {
                        // `handle_shutdown` answers `shutdown` and waits for the
                        // following `exit`, returning `true` once both are seen.
                        if connection.handle_shutdown(&req)? {
                            break;
                        }
                        match req.method.as_str() {
                            Formatting::METHOD => {
                                on_formatting(&connection, &mut state, &job_tx, req)
                            }
                            RangeFormatting::METHOD => {
                                on_range_formatting(&connection, &mut state, &job_tx, req)
                            }
                            DocumentSymbolRequest::METHOD => {
                                on_document_symbol(&connection, &state, &job_tx, req)
                            }
                            WorkspaceSymbolRequest::METHOD => {
                                on_workspace_symbol(&connection, &job_tx, req)
                            }
                            Completion::METHOD => on_completion(&connection, &state, &job_tx, req),
                            ResolveCompletionItem::METHOD => {
                                on_completion_resolve(&connection, &job_tx, req)
                            }
                            HoverRequest::METHOD => on_hover(&connection, &state, &job_tx, req),
                            GotoDefinition::METHOD => {
                                on_goto_definition(&connection, &state, &job_tx, req)
                            }
                            References::METHOD => on_references(&connection, &state, &job_tx, req),
                            DocumentHighlightRequest::METHOD => {
                                on_document_highlight(&connection, &state, &job_tx, req)
                            }
                            PrepareRenameRequest::METHOD => {
                                on_prepare_rename(&connection, &state, &job_tx, req)
                            }
                            Rename::METHOD => on_rename(&connection, &state, &job_tx, req),
                            FoldingRangeRequest::METHOD => {
                                on_folding_range(&connection, &state, &job_tx, req)
                            }
                            CodeActionRequest::METHOD => {
                                on_code_action(&connection, &mut state, &job_tx, req)
                            }
                            DocumentDiagnosticRequest::METHOD => {
                                on_document_diagnostic(&connection, &mut state, &job_tx, req)
                            }
                            _ => respond_unhandled(&connection, req),
                        }
                    }
                    Message::Notification(not) => {
                        on_notification(&connection, &mut state, &job_tx, not);
                    }
                    // The MVP issues no client-bound requests, so any response is
                    // unexpected.
                    Message::Response(_) => {}
                }
            }
            recv(out_rx) -> outbound => {
                let Ok(outbound) = outbound else { continue };
                forward_outbound(&connection, &mut state, &job_tx, outbound);
            }
        }
    }

    // Dropping `job_tx` disconnects the worker's receiver so it exits; the read
    // pool's workers exit when `read_pool` drops at the end of this scope.
    drop(job_tx);
    let _ = worker.join();
    Ok(())
}

/// Route a notification: edits and lifecycle to the worker, config inline.
fn on_notification(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    not: Notification,
) {
    match not.method.as_str() {
        DidOpenTextDocument::METHOD => {
            let Ok(params) = not.extract::<DidOpenTextDocumentParams>(DidOpenTextDocument::METHOD)
            else {
                return;
            };
            let doc = params.text_document;
            let uri = doc.uri;
            state.documents.insert(
                uri.clone(),
                Document {
                    text: doc.text.clone(),
                    version: doc.version,
                },
            );
            let path = uri_to_path(&uri);
            let kind = file_kind_for(&path);
            let resolved = state.resolve_settings(&uri);
            let _ = job_tx.send(WorkerJob::Edit {
                path,
                uri,
                text: doc.text,
                version: doc.version,
                kind,
                rules: resolved.rule_selection(),
                exclude: resolved.exclude,
            });
        }
        DidChangeTextDocument::METHOD => {
            let Ok(params) =
                not.extract::<DidChangeTextDocumentParams>(DidChangeTextDocument::METHOD)
            else {
                return;
            };
            let uri = params.text_document.uri;
            let version = params.text_document.version;
            let Some(doc) = state.documents.get_mut(&uri) else {
                return;
            };
            apply_content_changes(&mut doc.text, params.content_changes);
            doc.version = version;
            let text = doc.text.clone();
            let path = uri_to_path(&uri);
            let kind = file_kind_for(&path);
            let resolved = state.resolve_settings(&uri);
            let _ = job_tx.send(WorkerJob::Edit {
                path,
                uri,
                text,
                version,
                kind,
                rules: resolved.rule_selection(),
                exclude: resolved.exclude,
            });
        }
        DidCloseTextDocument::METHOD => {
            let Ok(params) =
                not.extract::<DidCloseTextDocumentParams>(DidCloseTextDocument::METHOD)
            else {
                return;
            };
            let uri = params.text_document.uri;
            state.documents.remove(&uri);
            let _ = job_tx.send(WorkerJob::Close {
                path: uri_to_path(&uri),
            });
            // Clear stale squiggles immediately; the worker just evicts the file.
            // In pull mode there is nothing to clear — the client drops a closed
            // file's diagnostics itself by ceasing to pull — and we never push.
            if !state.supports_pull_diagnostics {
                send_diagnostics(connection, uri, Vec::new(), None);
            }
        }
        DidChangeConfiguration::METHOD => {
            if let Ok(params) =
                not.extract::<DidChangeConfigurationParams>(DidChangeConfiguration::METHOD)
            {
                state.editor_settings = EditorSettings::from_client_value(&params.settings);
                // Drop cached resolutions so the new fallback is picked up on the
                // next request. A discovered `badness.toml` still wins, so docs in a
                // configured workspace are unaffected.
                state.config_cache.clear();
            }
        }
        DidChangeWatchedFiles::METHOD => {
            if let Ok(params) =
                not.extract::<DidChangeWatchedFilesParams>(DidChangeWatchedFiles::METHOD)
            {
                on_watched_files_change(connection, state, job_tx, params);
            }
        }
        _ => {}
    }
}

/// The id under which we register the watched-files capability, reused to deregister.
const WATCHED_FILES_REGISTRATION_ID: &str = "badness-watched-files";

/// Dynamically register file watchers for the project's on-disk leaves
/// (`**/*.{tex,bib}`) and the config file (`badness.toml`), so out-of-editor edits to
/// non-open includes reanalyze open documents. Called once right after the initialize
/// handshake. A no-op when the client lacks
/// `didChangeWatchedFiles.dynamicRegistration` (we then rely on seed-on-open). The
/// client's response is fire-and-forget — the main loop ignores it.
fn register_file_watchers(connection: &Connection, state: &mut GlobalState) {
    if !state.supports_dynamic_watchers {
        return;
    }
    let options = DidChangeWatchedFilesRegistrationOptions {
        watchers: vec![
            FileSystemWatcher {
                glob_pattern: GlobPattern::String("**/*.{tex,bib}".to_owned()),
                kind: None,
            },
            FileSystemWatcher {
                glob_pattern: GlobPattern::String("**/badness.toml".to_owned()),
                kind: None,
            },
        ],
    };
    let registration = Registration {
        id: WATCHED_FILES_REGISTRATION_ID.to_owned(),
        method: DidChangeWatchedFiles::METHOD.to_owned(),
        register_options: serde_json::to_value(options).ok(),
    };
    let params = RegistrationParams {
        registrations: vec![registration],
    };
    let Ok(params) = serde_json::to_value(params) else {
        return;
    };
    let id = state.next_request_id;
    state.next_request_id += 1;
    let _ = connection.sender.send(Message::Request(Request {
        id: RequestId::from(id),
        method: RegisterCapability::METHOD.to_owned(),
        params,
    }));
}

/// Handle a `workspace/didChangeWatchedFiles` batch. For each event on a **non-open**
/// file (an open buffer's overlay text is authoritative, so it is skipped — `didChange`
/// keeps it current): a `badness.toml` change clears the config cache and re-lints open
/// docs; a `.tex`/`.bib` change is forwarded to the worker to re-read/evict and re-lint.
fn on_watched_files_change(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    params: DidChangeWatchedFilesParams,
) {
    let mut config_changed = false;
    for event in params.changes {
        let path = uri_to_path(&event.uri);
        // An open buffer's truth is the editor overlay, not disk — leave it to
        // `didChange`. Compare by normalized path, since a watcher URI may be encoded
        // differently than the `didOpen` URI.
        if state.documents.keys().any(|open| uri_to_path(open) == path) {
            continue;
        }
        if path.file_name().is_some_and(|name| name == "badness.toml") {
            config_changed = true;
        } else {
            let _ = job_tx.send(WorkerJob::WatchedChange {
                path,
                deleted: event.typ == FileChangeType::DELETED,
            });
        }
    }
    if config_changed {
        // A discovered `badness.toml` changed on disk: drop cached resolutions so the
        // next analyze re-reads it, then re-lint open docs (mirrors
        // `didChangeConfiguration`, plus the relint a fresh config implies).
        state.config_cache.clear();
        relint_all_open(connection, state, job_tx);
    }
}

/// Apply a batch of `didChange` content changes to `text`, in order. A change
/// with no range replaces the whole buffer; a ranged change splices via the
/// (UTF-16-aware) [`LineIndex`]. The index is rebuilt per change because each
/// mutation shifts later offsets.
fn apply_content_changes(text: &mut String, changes: Vec<TextDocumentContentChangeEvent>) {
    for change in changes {
        match change.range {
            None => *text = change.text,
            Some(range) => {
                let idx = LineIndex::new(text);
                let start = idx.offset_at(text, range.start.line, range.start.character);
                let end = idx.offset_at(text, range.end.line, range.end.character);
                // Guard against a degenerate (start > end) range from a misbehaving
                // client: clamp rather than panic on `replace_range`.
                let (start, end) = (start.min(end), start.max(end));
                text.replace_range(start..end, &change.text);
            }
        }
    }
}

/// `textDocument/formatting`: build a format job for the worker, or reply `null`
/// when the document is unknown.
fn on_formatting(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<DocumentFormattingParams>(Formatting::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid formatting params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    if !state.documents.contains_key(&uri) {
        // Unknown document: nothing to format.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    }
    let resolved = state.resolve_settings(&uri);
    let mut style = resolved.style;
    // A discovered `badness.toml` wins outright; only when none
    // governs does the request's `tab_size` override the indent width.
    if !resolved.config_present && params.options.tab_size > 0 {
        style.indent_width = params.options.tab_size as usize;
    }
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    // `wrap` is decided per request: a configured `wrap` wins, else the file kind
    // (a package/class body is code, defaulting to `Preserve`).
    style.wrap = resolved.wrap_override.unwrap_or(kind.default_wrap());
    let text = state.documents[&uri].text.clone();
    let _ = job_tx.send(WorkerJob::Format {
        id,
        path,
        text,
        style,
        kind,
    });
}

/// `textDocument/rangeFormatting`: build a range-format job for the worker, or
/// reply `null` when the document is unknown. Mirrors [`on_formatting`]; the only
/// extra input is the selection `range`, resolved against the buffer on the read
/// pool.
fn on_range_formatting(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<DocumentRangeFormattingParams>(RangeFormatting::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid range formatting params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    if !state.documents.contains_key(&uri) {
        // Unknown document: nothing to format.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    }
    let resolved = state.resolve_settings(&uri);
    let mut style = resolved.style;
    if !resolved.config_present && params.options.tab_size > 0 {
        style.indent_width = params.options.tab_size as usize;
    }
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    style.wrap = resolved.wrap_override.unwrap_or(kind.default_wrap());
    let text = state.documents[&uri].text.clone();
    let _ = job_tx.send(WorkerJob::RangeFormat {
        id,
        path,
        text,
        style,
        kind,
        range: params.range,
    });
}

/// `textDocument/documentSymbol`: build an outline job for the worker, or reply
/// `null` when the document is unknown.
fn on_document_symbol(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<DocumentSymbolParams>(DocumentSymbolRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid documentSymbol params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: no symbols.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    let _ = job_tx.send(WorkerJob::Symbols {
        id,
        path,
        text: doc.text.clone(),
        kind,
    });
}

/// `workspace/symbol`: forward the query to the worker, which scans every tracked
/// project file. Unlike [`on_document_symbol`], it is not tied to an open buffer.
fn on_workspace_symbol(connection: &Connection, job_tx: &Sender<WorkerJob>, req: Request) {
    let id = req.id.clone();
    let params = match req.extract::<WorkspaceSymbolParams>(WorkspaceSymbolRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid workspace/symbol params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };
    let _ = job_tx.send(WorkerJob::WorkspaceSymbols {
        id,
        query: params.query,
    });
}

/// `textDocument/foldingRange`: build a folding job for the worker, or reply `null`
/// when the document is unknown.
fn on_folding_range(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<FoldingRangeParams>(FoldingRangeRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid foldingRange params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: no folds.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    let _ = job_tx.send(WorkerJob::FoldingRange {
        id,
        path,
        text: doc.text.clone(),
        kind,
    });
}

/// `textDocument/diagnostic`: build an on-demand diagnostic job for the worker.
///
/// Always replies with a *report* (never `null`): an empty full report when the
/// client is push-only (it should not be pulling) or the document is unknown,
/// otherwise a [`WorkerJob::Diagnostic`] that computes off a fresh snapshot. The
/// snapshot is current because the preceding edit's `Edit` job sits ahead of this
/// one on the FIFO `job_tx` (see [`WorkerJob::Diagnostic`]).
fn on_document_diagnostic(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<DocumentDiagnosticParams>(DocumentDiagnosticRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid diagnostic params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    // A push-only client should not be pulling; an unknown document has no buffer.
    // Either way, answer with an empty full report rather than leaving the request
    // hanging or replying `null`.
    if !state.supports_pull_diagnostics {
        reply_empty_diagnostic_report(connection, id);
        return;
    }
    let Some(doc) = state.documents.get(&uri) else {
        reply_empty_diagnostic_report(connection, id);
        return;
    };
    let text = doc.text.clone();
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    let rules = state.resolve_settings(&uri).rule_selection();
    let _ = job_tx.send(WorkerJob::Diagnostic {
        id,
        path,
        text,
        kind,
        previous_result_id: params.previous_result_id,
        rules,
    });
}

/// Reply to a `textDocument/diagnostic` request with an empty *full* report. Used
/// when there is nothing to compute (push-only client, unknown buffer) — the pull
/// protocol requires a report, so `null` is not an option.
fn reply_empty_diagnostic_report(connection: &Connection, id: RequestId) {
    let report = DocumentDiagnosticReportResult::Report(DocumentDiagnosticReport::Full(
        RelatedFullDocumentDiagnosticReport::default(),
    ));
    let value = serde_json::to_value(report).unwrap_or(serde_json::Value::Null);
    let _ = connection
        .sender
        .send(Message::Response(Response::new_ok(id, value)));
}

/// `textDocument/completion`: build a completion job for the worker, or reply
/// `null` when the document is unknown.
fn on_completion(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<CompletionParams>(Completion::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid completion params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position.text_document.uri;
    let position = params.text_document_position.position;
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: nothing to complete.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::Completion {
        id,
        uri,
        text: doc.text.clone(),
        position,
    });
}

/// `completionItem/resolve`: dispatch a resolve job for the worker. The item's
/// `data` is self-contained (it carries everything needed to recompute detail),
/// so there is no document to look up — only invalid params short-circuit here.
fn on_completion_resolve(connection: &Connection, job_tx: &Sender<WorkerJob>, req: Request) {
    let id = req.id.clone();
    let item = match req.extract::<CompletionItem>(ResolveCompletionItem::METHOD) {
        Ok((_, item)) => item,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid completion item".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };
    let _ = job_tx.send(WorkerJob::ResolveCompletion {
        id,
        item: Box::new(item),
    });
}

/// `textDocument/hover`: build a hover job for the worker, or reply `null` when the
/// document is unknown. A `.bib` cursor is not rejected — `compute_hover` simply finds
/// nothing there today (no bib-field hover yet), so it returns `null` on its own.
fn on_hover(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<HoverParams>(HoverRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid hover params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position_params.text_document.uri;
    let position = params.text_document_position_params.position;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: nothing to describe.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::Hover {
        id,
        path,
        text: doc.text.clone(),
        position,
    });
}

/// `textDocument/codeAction`: build a code-action job for the worker, or reply with
/// an empty action list when the document is unknown. Surfaces linter autofixes as
/// quick-fixes; a `.bib` cursor is handled too (its bib-lint fixes are surfaced the
/// same way).
fn on_code_action(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<CodeActionParams>(CodeActionRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid codeAction params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    let range = params.range;
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: no actions.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let text = doc.text.clone();
    let path = uri_to_path(&uri);
    let kind = file_kind_for(&path);
    let rules = state.resolve_settings(&uri).rule_selection();
    let _ = job_tx.send(WorkerJob::CodeAction {
        id,
        uri,
        path,
        text,
        kind,
        range,
        rules,
    });
}

/// `textDocument/definition`: build a go-to-definition job for the worker, or reply
/// `null` when the document is unknown or is a `.bib` (cite/ref sites live in
/// `.tex`, so a `.bib` cursor has nothing to jump *from*).
fn on_goto_definition(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<GotoDefinitionParams>(GotoDefinition::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid definition params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position_params.text_document.uri;
    let position = params.text_document_position_params.position;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: nothing to resolve.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    if file_kind_for(&path) == FileKind::Bib {
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    }
    let _ = job_tx.send(WorkerJob::GotoDefinition {
        id,
        path,
        text: doc.text.clone(),
        position,
    });
}

/// `textDocument/references`: build a find-references job for the worker, or reply
/// `null` when the document is unknown. Unlike go-to-definition, a `.bib` cursor is
/// *not* rejected — find-references can start on an `@entry` key and report its
/// `\cite` use sites.
fn on_references(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<ReferenceParams>(References::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid references params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position.text_document.uri;
    let position = params.text_document_position.position;
    let include_declaration = params.context.include_declaration;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: nothing to resolve.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::References {
        id,
        path,
        text: doc.text.clone(),
        position,
        include_declaration,
    });
}

/// `textDocument/documentHighlight`: build a document-highlight job for the worker,
/// or reply `null` when the document is unknown. Single-file, so no project membership
/// is captured — the worker shades the key under the cursor against the cursor buffer
/// alone.
fn on_document_highlight(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<DocumentHighlightParams>(DocumentHighlightRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid document-highlight params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position_params.text_document.uri;
    let position = params.text_document_position_params.position;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        // Unknown document: nothing to highlight.
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::DocumentHighlight {
        id,
        path,
        text: doc.text.clone(),
        position,
    });
}

/// `textDocument/prepareRename`: build a prepare-rename job, or reply `null` when
/// the document is unknown. The worker decides whether the cursor sits on a
/// renameable key (and returns its range + placeholder) or declines with `null`.
fn on_prepare_rename(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<TextDocumentPositionParams>(PrepareRenameRequest::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid prepareRename params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document.uri;
    let position = params.position;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::PrepareRename {
        id,
        path,
        text: doc.text.clone(),
        position,
    });
}

/// `textDocument/rename`: build a rename job, or reply `null` when the document is
/// unknown. The worker resolves the key under the cursor and answers with a
/// project-wide [`WorkspaceEdit`] (or `null` when the rename is declined).
fn on_rename(
    connection: &Connection,
    state: &GlobalState,
    job_tx: &Sender<WorkerJob>,
    req: Request,
) {
    let id = req.id.clone();
    let params = match req.extract::<RenameParams>(Rename::METHOD) {
        Ok((_, params)) => params,
        Err(_) => {
            let resp = Response::new_err(
                id,
                ErrorCode::InvalidParams as i32,
                "invalid rename params".to_owned(),
            );
            let _ = connection.sender.send(Message::Response(resp));
            return;
        }
    };

    let uri = params.text_document_position.text_document.uri;
    let position = params.text_document_position.position;
    let new_name = params.new_name;
    let path = uri_to_path(&uri);
    let Some(doc) = state.documents.get(&uri) else {
        let _ = connection.sender.send(Message::Response(Response::new_ok(
            id,
            serde_json::Value::Null,
        )));
        return;
    };
    let _ = job_tx.send(WorkerJob::Rename {
        id,
        path,
        text: doc.text.clone(),
        position,
        new_name,
    });
}

/// Forward a worker result to the client. Diagnostics are version-gated: a result
/// is sent only when its document is still open at exactly that version, so a
/// stale (superseded or post-close) analyze never repaints squiggles.
fn forward_outbound(
    connection: &Connection,
    state: &mut GlobalState,
    job_tx: &Sender<WorkerJob>,
    outbound: Outbound,
) {
    match outbound {
        Outbound::Diagnostics {
            uri,
            version,
            diags,
        } => {
            // Pull and push are mutually exclusive: a pull-capable client is served
            // exclusively via `textDocument/diagnostic`, so drop the push (the
            // analyze still ran, warming the salsa memos the pull reads).
            if state.supports_pull_diagnostics {
                return;
            }
            if state
                .documents
                .get(&uri)
                .is_some_and(|doc| doc.version == version)
            {
                send_diagnostics(connection, uri, diags, Some(version));
            }
        }
        Outbound::Response(resp) => {
            let _ = connection.sender.send(Message::Response(resp));
        }
        Outbound::RelintAll => relint_all_open(connection, state, job_tx),
    }
}

/// Re-lint every open document, because cross-file resolution may have changed for all
/// of them (a project member's content changed, membership grew, or the governing
/// config changed). A pull client learns this by re-pulling: nudge it with
/// `workspace/diagnostic/refresh`. A push client gets a fresh analyze re-queued per
/// open document at its current version. Shared by [`Outbound::RelintAll`] and the
/// `badness.toml` watched-change path.
fn relint_all_open(connection: &Connection, state: &mut GlobalState, job_tx: &Sender<WorkerJob>) {
    if state.supports_pull_diagnostics {
        if state.supports_diagnostic_refresh {
            let id = state.next_request_id;
            state.next_request_id += 1;
            let _ = connection.sender.send(Message::Request(Request {
                id: RequestId::from(id),
                method: WorkspaceDiagnosticRefresh::METHOD.to_owned(),
                params: serde_json::Value::Null,
            }));
        }
        return;
    }
    // Push mode: re-queue a fresh analyze for every open document at its current
    // version. The worker coalesces per-URI, so this is cheap; salsa memos make the
    // actual recompute incremental. A re-lint of a doc in an already-seeded directory
    // discovers no new members, so it can't re-trigger `RelintAll` (no loop). Snapshot
    // the buffers first so the per-document `resolve_settings` (`&mut self`) doesn't
    // alias the `documents` borrow.
    let snapshot: Vec<(Uri, String, i32)> = state
        .documents
        .iter()
        .map(|(uri, doc)| (uri.clone(), doc.text.clone(), doc.version))
        .collect();
    for (uri, text, version) in snapshot {
        let path = uri_to_path(&uri);
        let kind = file_kind_for(&path);
        let resolved = state.resolve_settings(&uri);
        let _ = job_tx.send(WorkerJob::Edit {
            uri,
            path,
            text,
            version,
            kind,
            rules: resolved.rule_selection(),
            exclude: resolved.exclude,
        });
    }
}

// ---------------------------------------------------------------------------
// Worker thread (sole database writer).
// ---------------------------------------------------------------------------

/// Signal from a finished analyze read-phase back to the worker: the analyze for
/// `uri`@`version` completed (or unwound on cancellation) and dropped its db
/// clone, so the in-flight slot is free.
struct AnalyzeDone {
    uri: Uri,
    version: i32,
}

/// The single in-flight analyze, if any.
struct InflightAnalyze {
    uri: Uri,
    version: i32,
}

/// A queued analyze request: the latest pending edit for a URI.
struct AnalyzeRequest {
    uri: Uri,
    path: PathBuf,
    version: i32,
    kind: FileKind,
    /// The document's resolved lint-rule selection, applied to the analyze.
    rules: RuleSelection,
}

/// What [`Worker::try_dispatch`] should do given the in-flight analyze and the
/// pending queue. Pure decision (see [`decide`]) so it can be unit-tested.
#[derive(Debug, PartialEq, Eq)]
enum DispatchAction {
    /// Idle with nothing queued, or busy with no newer edit for the in-flight
    /// URI: leave the running analyze and wait for its `done`.
    Wait,
    /// The slot is free; start a fresh analyze for this URI.
    Start(Uri),
    /// A strictly-newer edit for the *in-flight* URI arrived; cancel the running
    /// analyze and start this URI. Only ever the in-flight URI — a different
    /// pending URI must never cancel the in-flight one.
    SupersedeAndStart(Uri),
}

/// Decide the next dispatch action. `inflight` is the running analyze's
/// `(uri, version)`, if any; `pending` maps each queued URI to its latest
/// version. Cancel only on a strictly-newer edit of the *same* URI.
fn decide(inflight: Option<(&Uri, i32)>, pending: &HashMap<Uri, i32>) -> DispatchAction {
    match inflight {
        None => match pending.keys().next() {
            Some(uri) => DispatchAction::Start(uri.clone()),
            None => DispatchAction::Wait,
        },
        Some((uri, version)) => {
            if pending.get(uri).is_some_and(|&v| v > version) {
                DispatchAction::SupersedeAndStart(uri.clone())
            } else {
                DispatchAction::Wait
            }
        }
    }
}

/// Spawn the worker thread that owns the [`IncrementalDatabase`] (the sole
/// writer) and drives diagnostics analyzes onto the read pool.
fn spawn_worker(
    job_rx: Receiver<WorkerJob>,
    out_tx: Sender<Outbound>,
    read_spawner: Spawner,
) -> JoinHandle<()> {
    let (done_tx, done_rx) = unbounded::<AnalyzeDone>();
    std::thread::Builder::new()
        .name("badness-lsp-worker".to_owned())
        .spawn(move || {
            let mut worker = Worker {
                db: IncrementalDatabase::default(),
                out_tx,
                done_tx,
                read_spawner,
                inflight: None,
                pending: HashMap::new(),
                seeded_dirs: HashSet::new(),
            };
            worker.run(&job_rx, &done_rx);
        })
        .expect("spawn LSP worker thread")
}

struct Worker {
    db: IncrementalDatabase,
    out_tx: Sender<Outbound>,
    /// Read-phase workers signal completion here so the worker can free the
    /// in-flight slot and dispatch the next pending analyze.
    done_tx: Sender<AnalyzeDone>,
    read_spawner: Spawner,
    /// The single in-flight analyze, if any. At most one runs at a time: the
    /// write-phase needs exclusive `&mut db`, and salsa cancellation is global, so
    /// a second concurrent analyze couldn't be cancelled selectively.
    inflight: Option<InflightAnalyze>,
    /// Coalesced analyze queue: the latest pending request per URI.
    pending: HashMap<Uri, AnalyzeRequest>,
    /// Directories already walked for on-disk `.tex`/`.bib` siblings, so each is
    /// seeded at most once (the membership-discovery hot-path guard).
    seeded_dirs: HashSet<PathBuf>,
}

impl Worker {
    fn run(&mut self, job_rx: &Receiver<WorkerJob>, done_rx: &Receiver<AnalyzeDone>) {
        loop {
            select! {
                recv(job_rx) -> job => {
                    let Ok(job) = job else { break };  // main dropped `job_tx`
                    self.handle_job(job);
                    while let Ok(j) = job_rx.try_recv() {
                        self.handle_job(j);
                    }
                    self.try_dispatch();
                }
                recv(done_rx) -> done => {
                    let Ok(done) = done else { continue };
                    // Free the slot only if this `done` is for the *current*
                    // in-flight analyze — a late `done` from a superseded one must
                    // not clear the new analyze.
                    if matches!(&self.inflight, Some(f) if f.uri == done.uri && f.version == done.version)
                    {
                        self.inflight = None;
                    }
                    self.try_dispatch();
                }
            }
        }
    }

    fn handle_job(&mut self, job: WorkerJob) {
        match job {
            WorkerJob::Edit {
                uri,
                path,
                text,
                version,
                kind,
                rules,
                exclude,
            } => {
                // Write-phase: push the live buffer into the db. Cheap — the parse
                // is a lazy salsa query deferred to the analyze. Acquiring `&mut
                // db` blocks until any outstanding read snapshot drops (single
                // writer), which is how a fresher edit preempts an in-flight read.
                self.db.upsert_file(&path, text);
                // Lazily pull the rest of the project off disk so cross-file rules
                // can fire. If this grows the member set, every open document's
                // resolution may have changed — re-lint them all.
                if self.seed_dir(&path, &exclude) {
                    let _ = self.out_tx.send(Outbound::RelintAll);
                }
                self.enqueue(AnalyzeRequest {
                    uri,
                    path,
                    version,
                    kind,
                    rules,
                });
            }
            WorkerJob::Close { path } => {
                self.db.remove_file(&path);
            }
            WorkerJob::WatchedChange { path, deleted } => {
                if self.apply_watched_change(&path, deleted) {
                    let _ = self.out_tx.send(Outbound::RelintAll);
                }
            }
            WorkerJob::Format {
                id,
                path,
                text,
                style,
                kind,
            } => {
                // Format reads run on the read pool against a snapshot, concurrent
                // with the analyze slot (they are id-bound responses, not coalesced).
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner
                    .spawn(move || run_format(&snapshot, id, &path, &text, style, kind, &out_tx));
            }
            WorkerJob::RangeFormat {
                id,
                path,
                text,
                style,
                kind,
                range,
            } => {
                // Range formatting runs on the read pool against a snapshot, exactly
                // like `Format` (an id-bound response, not coalesced).
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_range_format(&snapshot, id, &path, &text, style, kind, range, &out_tx)
                });
            }
            WorkerJob::Symbols {
                id,
                path,
                text,
                kind,
            } => {
                // Symbol reads, like formatting, run on the read pool against a
                // snapshot (id-bound responses, not coalesced).
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner
                    .spawn(move || run_symbols(&snapshot, id, &path, &text, kind, &out_tx));
            }
            WorkerJob::WorkspaceSymbols { id, query } => {
                // Workspace symbols scan every tracked file, so — like
                // find-references — capture the membership snapshot on the write
                // side before the read job runs.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner
                    .spawn(move || run_workspace_symbols(&snapshot, id, &query, members, &out_tx));
            }
            WorkerJob::FoldingRange {
                id,
                path,
                text,
                kind,
            } => {
                // Folding reads run on the read pool against a snapshot, like
                // symbols (id-bound responses, not coalesced).
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner
                    .spawn(move || run_folding(&snapshot, id, &path, &text, kind, &out_tx));
            }
            WorkerJob::Completion {
                id,
                uri,
                text,
                position,
            } => {
                // Completion reads run on the read pool against a snapshot, like
                // formatting/symbols (id-bound responses, not coalesced). Cite-key
                // completion is cross-file, so — like go-to-def — we snapshot project
                // membership here on the write side.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_completion(&snapshot, id, &uri, &text, position, members, &out_tx)
                });
            }
            WorkerJob::ResolveCompletion { id, item } => {
                // Resolve is cross-file (signature scope, project bibliography),
                // so — like hover — snapshot project membership on the write side.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner
                    .spawn(move || run_completion_resolve(&snapshot, id, *item, members, &out_tx));
            }
            WorkerJob::Hover {
                id,
                path,
                text,
                position,
            } => {
                // Hover's signature scope and `\cite` resolution are both cross-file,
                // so — like go-to-def — snapshot project membership on the write side.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_hover(&snapshot, id, &path, &text, position, members, &out_tx)
                });
            }
            WorkerJob::GotoDefinition {
                id,
                path,
                text,
                position,
            } => {
                // Go-to-def is cross-file, so it needs the same membership snapshot
                // an analyze captures (open buffers plus seeded on-disk siblings),
                // taken on the write side so the read job interns the latest project.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_goto_definition(&snapshot, id, &path, &text, position, members, &out_tx)
                });
            }
            WorkerJob::References {
                id,
                path,
                text,
                position,
                include_declaration,
            } => {
                // Find-references is cross-file like go-to-def, so it captures the
                // same membership snapshot on the write side before the read job runs.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_references(
                        &snapshot,
                        id,
                        &path,
                        &text,
                        position,
                        members,
                        include_declaration,
                        &out_tx,
                    )
                });
            }
            WorkerJob::DocumentHighlight {
                id,
                path,
                text,
                position,
            } => {
                // Single-file like prepareRename: no project membership, just a db
                // snapshot to reach the cached model when the buffer is current.
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_document_highlight(&snapshot, id, &path, &text, position, &out_tx)
                });
            }
            WorkerJob::PrepareRename {
                id,
                path,
                text,
                position,
            } => {
                // prepareRename only inspects the cursor buffer, but still resolves
                // the key against the cached model when current, so it shares a db
                // snapshot like the other read jobs.
                let snapshot = self.db.snapshot();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_prepare_rename(&snapshot, id, &path, &text, position, &out_tx)
                });
            }
            WorkerJob::Rename {
                id,
                path,
                text,
                position,
                new_name,
            } => {
                // Rename is cross-file like find-references, so it captures the same
                // membership snapshot on the write side before the read job runs.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_rename(
                        &snapshot, id, &path, &text, position, &new_name, members, &out_tx,
                    )
                });
            }
            WorkerJob::Diagnostic {
                id,
                path,
                text,
                kind,
                previous_result_id,
                rules,
            } => {
                // On-demand pull: snapshot the db + membership on the write side
                // (like an analyze) so the read job interns the latest project. This
                // is a free, id-bound read — not the coalesced analyze slot — so it
                // never blocks or supersedes the push analyze.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_document_diagnostic(
                        &snapshot,
                        id,
                        &path,
                        &text,
                        kind,
                        members,
                        previous_result_id,
                        &rules,
                        &out_tx,
                    )
                });
            }
            WorkerJob::CodeAction {
                id,
                uri,
                path,
                text,
                kind,
                range,
                rules,
            } => {
                // On-demand re-lint, like the pull-diagnostics path: snapshot the db
                // + membership on the write side so the read job interns the latest
                // project, then build quick-fixes off the read pool.
                let snapshot = self.db.snapshot();
                let members = self.project_members();
                let out_tx = self.out_tx.clone();
                self.read_spawner.spawn(move || {
                    run_code_action(
                        &snapshot, id, &uri, &path, &text, kind, range, members, &rules, &out_tx,
                    )
                });
            }
        }
    }

    /// Walk the active file's directory once for `.tex`/`.bib` siblings, reading
    /// and upserting any not already tracked, so the cross-file resolvers see the
    /// whole project. Returns whether the member set grew.
    ///
    /// Skips unsaved/synthetic buffers (whose path isn't a real file) and the
    /// filesystem root, so we never walk `/`. A sibling that is already tracked —
    /// an open buffer, or one seeded earlier — keeps its live text (we never read
    /// it back from disk). Each directory is walked at most once (`seeded_dirs`).
    ///
    /// `exclude` is the document's resolved [`ExcludeFilter`] (built on the main
    /// side, where the config lives, and threaded through [`WorkerJob::Edit`]), so
    /// a `badness.toml` `exclude`/`extend-exclude` prunes the same siblings here as
    /// it does for the CLI. It is exclude-nothing when no config governs.
    fn seed_dir(&mut self, path: &Path, exclude: &ExcludeFilter) -> bool {
        if !path.is_file() {
            return false;
        }
        let Some(dir) = path.parent() else {
            return false;
        };
        // Never walk the filesystem root (a `/foo.tex` would otherwise walk all of `/`).
        if dir.parent().is_none() {
            return false;
        }
        let dir = dir.to_path_buf();
        if !self.seeded_dirs.insert(dir.clone()) {
            return false; // already walked
        }
        // A discovered `badness.toml` governs sibling discovery here too: the
        // document's resolved exclude filter is built on the main side (where the
        // config lives) and threaded in via `WorkerJob::Edit`, so the same
        // `exclude`/`extend-exclude` that scope the CLI's walk prune these siblings.
        let Ok(files) = collect_lint_files(&[dir], exclude) else {
            return false;
        };
        let mut grew = false;
        for (sibling, _kind) in files {
            if self.db.lookup_file(&sibling).is_some() {
                continue; // open buffer or already seeded — keep its live text
            }
            if let Ok(text) = std::fs::read_to_string(&sibling) {
                self.db.upsert_file(&sibling, text);
                grew = true;
            }
        }
        grew
    }

    /// Apply an on-disk change to a non-open `.tex`/`.bib` file (from a watched-files
    /// event): re-read and re-upsert it, or evict it on delete. Returns `true` when the
    /// db actually changed, so the caller can re-lint open documents only when it
    /// matters.
    ///
    /// Scoped to known projects: a change is acted on only when the file is already a
    /// tracked member, or it is a freshly-created sibling in a directory we have already
    /// seeded. The broad `**/*.{tex,bib}` glob also matches files in directories with no
    /// open document, and re-linting every open buffer for those would be pure waste.
    ///
    /// Unlike [`seed_dir`](Self::seed_dir), this deliberately re-reads a tracked file:
    /// the seed path keeps a tracked file's text precisely to avoid clobbering a live
    /// buffer, but the main loop has already excluded open buffers before dispatching
    /// here, so the file's truth is the disk.
    fn apply_watched_change(&mut self, path: &Path, deleted: bool) -> bool {
        let tracked = self.db.lookup_file(path);
        let in_seeded_dir = path
            .parent()
            .is_some_and(|dir| self.seeded_dirs.contains(dir));
        if tracked.is_none() && !in_seeded_dir {
            return false; // not part of any assembled project
        }
        if deleted {
            return self.db.remove_file(path).is_some();
        }
        let Ok(text) = std::fs::read_to_string(path) else {
            return false; // unreadable (e.g. a delete racing the event) — leave as-is
        };
        // Skip the relint when the content is identical to what we already track
        // (a `touch` or a metadata-only event), so we don't re-lint every open doc for
        // nothing. `upsert_file` itself also no-ops the salsa write on equal text.
        if tracked.is_some_and(|file| self.db.file_text(file) == text) {
            return false;
        }
        self.db.upsert_file(path, text);
        true
    }

    /// Snapshot the current project membership as sorted [`ProjectMember`]s, so a
    /// read job can intern a `Project` against its db snapshot.
    fn project_members(&self) -> Vec<ProjectMember> {
        self.db
            .tracked_files()
            .into_iter()
            .map(|(path, file)| {
                let kind = file_kind_for(&path);
                ProjectMember { file, path, kind }
            })
            .collect()
    }

    /// Add `req` to the pending queue, keeping the highest version per URI.
    fn enqueue(&mut self, req: AnalyzeRequest) {
        match self.pending.get(&req.uri) {
            Some(existing) if existing.version >= req.version => {}
            _ => {
                self.pending.insert(req.uri.clone(), req);
            }
        }
    }

    /// Start the next analyze if the slot is free, superseding the in-flight one
    /// only when a newer edit of the *same* URI is queued (see [`decide`]).
    fn try_dispatch(&mut self) {
        let versions: HashMap<Uri, i32> = self
            .pending
            .iter()
            .map(|(uri, req)| (uri.clone(), req.version))
            .collect();
        let inflight = self.inflight.as_ref().map(|f| (&f.uri, f.version));
        let uri = match decide(inflight, &versions) {
            DispatchAction::Wait => return,
            DispatchAction::Start(uri) => uri,
            DispatchAction::SupersedeAndStart(uri) => {
                // The write-phase already tripped cancellation on a real edit, but
                // make it explicit and robust: block until the old clone drops.
                // Safe — this thread holds no clone.
                self.db.trigger_cancellation();
                self.inflight = None;
                uri
            }
        };
        let Some(req) = self.pending.remove(&uri) else {
            return;
        };
        self.start_analyze(req);
    }

    /// Dispatch the diagnostics read-phase for `req` onto the read pool, holding a
    /// db clone. A superseding edit (or any write) trips `salsa::Cancelled`, caught
    /// so a cancelled analyze publishes nothing.
    fn start_analyze(&mut self, req: AnalyzeRequest) {
        let snapshot = self.db.snapshot();
        // Snapshot membership now (write side) so the read job interns the same
        // `Project` the latest edit produced.
        let members = self.project_members();
        let out_tx = self.out_tx.clone();
        let done_tx = self.done_tx.clone();
        let AnalyzeRequest {
            uri,
            path,
            version,
            kind,
            rules,
        } = req;
        self.inflight = Some(InflightAnalyze {
            uri: uri.clone(),
            version,
        });
        self.read_spawner.spawn(move || {
            let result = salsa::Cancelled::catch(AssertUnwindSafe(|| match kind {
                FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                    analyze_tex(&snapshot, &path, members, &rules)
                }
                FileKind::Bib => analyze_bib(&snapshot, &path, &rules),
            }));
            if let Ok(Some(diags)) = result {
                let _ = out_tx.send(Outbound::Diagnostics {
                    uri: uri.clone(),
                    version,
                    diags,
                });
            }
            // The clone MUST drop before we signal `done`: the next write-phase /
            // `trigger_cancellation` blocks until it's gone, so a premature `done`
            // could let the worker start a write that deadlocks on this clone.
            drop(snapshot);
            let _ = done_tx.send(AnalyzeDone { uri, version });
        });
    }
}

/// Compute diagnostics for a `.tex` file off the snapshot: parse diagnostics plus
/// lint-rule findings over the same salsa-cached tree + model, with cross-file
/// resolution from the `members` snapshot.
///
/// The `Project` is interned from the membership the worker captured (open buffers
/// plus lazily-read on-disk siblings); `resolved_labels` / `resolved_citations`
/// then drive `undefined-ref`, the cross-file branch of `duplicate-label`, and
/// `undefined-citation`. Their gates (closed, rooted namespace) keep a bare
/// fragment opened alone from being flagged.
fn analyze_tex(
    snapshot: &Analysis,
    path: &Path,
    members: Vec<ProjectMember>,
    rules: &RuleSelection,
) -> Option<Vec<Diagnostic>> {
    let file = snapshot.lookup_file(path)?;
    let text = snapshot.file_text(file).to_owned();
    // The file's normalized identity, which keys the cross-file resolvers (it
    // equals this file's `ProjectMember::path`).
    let lint_path = snapshot.file_path(file).to_path_buf();
    let idx = LineIndex::new(&text);
    let mut diags: Vec<Diagnostic> = snapshot
        .parse_diagnostics(file)
        .iter()
        .map(|d| Diagnostic {
            range: byte_range_to_lsp(&idx, &text, d.start, d.end),
            severity: Some(DiagnosticSeverity::ERROR),
            source: Some("badness".to_owned()),
            message: d.message.clone(),
            ..Default::default()
        })
        .collect();
    let root = snapshot.parsed_tree(file);
    let model = snapshot.semantic_model(file);
    let (resolution, citations) = snapshot.resolve_project(members);
    for d in lint_document(&lint_path, &root, model, Some(resolution), Some(citations)) {
        if rules.is_active(d.rule) {
            diags.push(lint_to_lsp(&idx, &text, d));
        }
    }
    Some(diags)
}

/// Compute diagnostics for a `.bib` file off the snapshot: bib parse diagnostics
/// plus bib lint-rule findings over the cached bib tree + model. The bib linter
/// has no cross-file resolution argument (no bib rule is cross-file-sensitive
/// yet).
fn analyze_bib(snapshot: &Analysis, path: &Path, rules: &RuleSelection) -> Option<Vec<Diagnostic>> {
    let file = snapshot.lookup_file(path)?;
    let text = snapshot.file_text(file).to_owned();
    let idx = LineIndex::new(&text);
    let mut diags: Vec<Diagnostic> = snapshot
        .bib_parse_diagnostics(file)
        .iter()
        .map(|d| Diagnostic {
            range: byte_range_to_lsp(&idx, &text, d.start, d.end),
            severity: Some(DiagnosticSeverity::ERROR),
            source: Some("badness".to_owned()),
            message: d.message.clone(),
            ..Default::default()
        })
        .collect();
    let root = snapshot.parsed_bib_tree(file);
    let model = snapshot.bib_semantic_model(file);
    for d in crate::bib::linter::lint_document(path, &root, model) {
        if rules.is_active(d.rule) {
            diags.push(lint_to_lsp(&idx, &text, d));
        }
    }
    Some(diags)
}

/// Map a linter [`crate::linter::Diagnostic`] (shared by the LaTeX and BibTeX
/// linters) onto an LSP [`Diagnostic`].
fn lint_to_lsp(idx: &LineIndex, text: &str, d: crate::linter::Diagnostic) -> Diagnostic {
    Diagnostic {
        range: byte_range_to_lsp(idx, text, d.start, d.end),
        severity: Some(severity_to_lsp(d.severity)),
        code: Some(NumberOrString::String(d.rule.to_owned())),
        source: Some("badness".to_owned()),
        message: d.message,
        ..Default::default()
    }
}

/// Compute a `textDocument/diagnostic` pull report on the read pool and reply.
///
/// Reuses the same per-file diagnostics the push path computes, then derives a
/// content-addressed `result_id` and returns either a `full` report (with items)
/// or, when `previous_result_id` matches, an `unchanged` report. `related_documents`
/// is always `None`: cross-file rules fire in the file that *holds* the reference,
/// so a single file's report is self-contained (the dependency is expressed by
/// `inter_file_dependencies`, not by foreign-file diagnostics).
#[allow(clippy::too_many_arguments)]
fn run_document_diagnostic(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    kind: FileKind,
    members: Vec<ProjectMember>,
    previous_result_id: Option<String>,
    rules: &RuleSelection,
    out_tx: &Sender<Outbound>,
) {
    let items = compute_diagnostics(snapshot, path, text, kind, members, rules);
    let result_id = result_id_for(&items);
    let report = if previous_result_id.as_deref() == Some(result_id.as_str()) {
        DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
            related_documents: None,
            unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport { result_id },
        })
    } else {
        DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
            related_documents: None,
            full_document_diagnostic_report: FullDocumentDiagnosticReport {
                result_id: Some(result_id),
                items,
            },
        })
    };
    let value = serde_json::to_value(DocumentDiagnosticReportResult::Report(report))
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, value)));
}

/// The diagnostics for a pull, computed **on demand**.
///
/// Fast path: reuse the snapshot's salsa-cached parse, model, and cross-file
/// resolution via [`analyze_tex`]/[`analyze_bib`]. The snapshot already reflects the
/// pulled buffer (the preceding `Edit` upserted ahead of this job on the FIFO
/// channel). On a racing write (`salsa::Cancelled`) or a missing file, fall back to a
/// single-file recompute from the captured `text` ([`fallback_diagnostics`]) so the
/// reply stays current — never a stale or empty flash (the bug panache fixed).
fn compute_diagnostics(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    kind: FileKind,
    members: Vec<ProjectMember>,
    rules: &RuleSelection,
) -> Vec<Diagnostic> {
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            analyze_tex(snapshot, path, members, rules)
        }
        FileKind::Bib => analyze_bib(snapshot, path, rules),
    }));
    match cached {
        Ok(Some(items)) => items,
        // `Ok(None)` = file not in the snapshot; `Err` = cancelled by a racing edit.
        // Either way recompute from the captured buffer (single-file: cross-file
        // findings, if any, arrive on the client's next pull after the edit settles).
        Ok(None) | Err(_) => fallback_diagnostics(path, text, kind, rules),
    }
}

/// Single-file diagnostics computed directly from `text`, bypassing the salsa cache.
/// The cancellation/cache-miss fallback for a pull — parse diagnostics plus
/// node-shape lint findings, with no cross-file resolution (`None` resolvers).
fn fallback_diagnostics(
    path: &Path,
    text: &str,
    kind: FileKind,
    rules: &RuleSelection,
) -> Vec<Diagnostic> {
    let idx = LineIndex::new(text);
    let mut diags: Vec<Diagnostic> = Vec::new();
    match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            let parsed = parse_with_flavor(text, kind.lex_config());
            for err in &parsed.errors {
                diags.push(Diagnostic {
                    range: byte_range_to_lsp(&idx, text, err.start, err.end),
                    severity: Some(DiagnosticSeverity::ERROR),
                    source: Some("badness".to_owned()),
                    message: err.message.clone(),
                    ..Default::default()
                });
            }
            let root = parsed.syntax();
            let model = SemanticModel::build(&root);
            for d in lint_document(path, &root, &model, None, None) {
                if rules.is_active(d.rule) {
                    diags.push(lint_to_lsp(&idx, text, d));
                }
            }
        }
        FileKind::Bib => {
            let parsed = bib_parse(text);
            for err in &parsed.errors {
                diags.push(Diagnostic {
                    range: byte_range_to_lsp(&idx, text, err.start, err.end),
                    severity: Some(DiagnosticSeverity::ERROR),
                    source: Some("badness".to_owned()),
                    message: err.message.clone(),
                    ..Default::default()
                });
            }
            let root = parsed.syntax();
            let model = BibModel::build(&root);
            for d in crate::bib::linter::lint_document(path, &root, &model) {
                if rules.is_active(d.rule) {
                    diags.push(lint_to_lsp(&idx, text, d));
                }
            }
        }
    }
    diags
}

/// Compute a `textDocument/codeAction` reply on the read pool: re-lint the buffer,
/// then surface each fix-carrying finding overlapping `range` as a quick-fix.
///
/// Reuses the same on-demand lint the pull-diagnostics path runs (cached off the
/// snapshot, single-file fallback on a racing write), but keeps the **raw** linter
/// findings — with byte ranges and fixes — that the LSP diagnostic conversion drops.
#[allow(clippy::too_many_arguments)]
fn run_code_action(
    snapshot: &Analysis,
    id: RequestId,
    uri: &Uri,
    path: &Path,
    text: &str,
    kind: FileKind,
    range: Range,
    members: Vec<ProjectMember>,
    rules: &RuleSelection,
    out_tx: &Sender<Outbound>,
) {
    let findings = compute_lint_findings(snapshot, path, text, kind, members, rules);
    let actions = code_action::code_actions_for_range(&findings, text, uri, range);
    let value = serde_json::to_value(actions).unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, value)));
}

/// The raw linter findings (byte ranges + fixes) for a pull/code-action, computed
/// **on demand**. The fix-carrying analog of [`compute_diagnostics`]: fast path off
/// the snapshot's salsa cache, single-file recompute on a racing write or cache miss.
fn compute_lint_findings(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    kind: FileKind,
    members: Vec<ProjectMember>,
    rules: &RuleSelection,
) -> Vec<crate::linter::Diagnostic> {
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        lint_findings(snapshot, path, kind, members, rules)
    }));
    match cached {
        Ok(Some(items)) => items,
        Ok(None) | Err(_) => fallback_lint_findings(path, text, kind, rules),
    }
}

/// Run the linter over the snapshot's cached tree + model, returning the raw
/// findings (with their fixes). The lint half of [`analyze_tex`]/[`analyze_bib`]
/// without the LSP conversion, so code actions can read each finding's `fix`.
fn lint_findings(
    snapshot: &Analysis,
    path: &Path,
    kind: FileKind,
    members: Vec<ProjectMember>,
    rules: &RuleSelection,
) -> Option<Vec<crate::linter::Diagnostic>> {
    let file = snapshot.lookup_file(path)?;
    let findings = match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            let lint_path = snapshot.file_path(file).to_path_buf();
            let root = snapshot.parsed_tree(file);
            let model = snapshot.semantic_model(file);
            let (resolution, citations) = snapshot.resolve_project(members);
            lint_document(&lint_path, &root, model, Some(resolution), Some(citations))
        }
        FileKind::Bib => {
            let root = snapshot.parsed_bib_tree(file);
            let model = snapshot.bib_semantic_model(file);
            crate::bib::linter::lint_document(path, &root, model)
        }
    };
    Some(retain_active(findings, rules))
}

/// Single-file raw findings computed directly from `text`, bypassing the salsa
/// cache — the cancellation/cache-miss fallback for [`compute_lint_findings`] (no
/// cross-file resolution, mirroring [`fallback_diagnostics`]).
fn fallback_lint_findings(
    path: &Path,
    text: &str,
    kind: FileKind,
    rules: &RuleSelection,
) -> Vec<crate::linter::Diagnostic> {
    let findings = match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            let parsed = parse_with_flavor(text, kind.lex_config());
            let root = parsed.syntax();
            let model = SemanticModel::build(&root);
            lint_document(path, &root, &model, None, None)
        }
        FileKind::Bib => {
            let parsed = bib_parse(text);
            let root = parsed.syntax();
            let model = BibModel::build(&root);
            crate::bib::linter::lint_document(path, &root, &model)
        }
    };
    retain_active(findings, rules)
}

/// Drop findings whose rule the config deselected (parse diagnostics always
/// survive — see [`RuleSelection::is_active`]). The raw-findings analog of the
/// inline `is_active` filter in [`analyze_tex`]/[`analyze_bib`], shared by the
/// code-action paths. Mirrors the CLI's `diagnostics.retain(|d| rules.is_active(..))`.
fn retain_active(
    mut findings: Vec<crate::linter::Diagnostic>,
    rules: &RuleSelection,
) -> Vec<crate::linter::Diagnostic> {
    findings.retain(|d| rules.is_active(d.rule));
    findings
}

/// Derive a stable, content-addressed `result_id` from a diagnostic set, so a
/// re-pull with no change reports `unchanged`. Hashes the JSON encoding because
/// [`Diagnostic`] is not `Hash`; the encoding is order-stable (serde field order +
/// deterministic diagnostic ordering), so identical diagnostics hash identically.
/// Mirrors panache's `result_id_for`.
fn result_id_for(items: &[Diagnostic]) -> String {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    serde_json::to_vec(items)
        .unwrap_or_default()
        .hash(&mut hasher);
    hasher.finish().to_string()
}

/// Format the buffer behind a [`WorkerJob::Format`] on the read pool and reply.
///
/// Fast path: reuse the snapshot's cached tree (no reparse). On a racing write
/// (`salsa::Cancelled`), a stale snapshot (`file_text != text`), or a cache miss,
/// recompute from the captured `text` via [`format_with_style`] (which itself
/// guards parse errors) so the client always gets a correct response.
fn run_format(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    style: FormatStyle,
    kind: FileKind,
    out_tx: &Sender<Outbound>,
) {
    let result = match compute_format(snapshot, path, text, style, kind) {
        Some(edit) => serde_json::to_value(vec![edit]).unwrap_or(serde_json::Value::Null),
        None => serde_json::Value::Null,
    };
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Produce the whole-document replacing edit, or `None` for a no-op / refusal /
/// unknown buffer. See [`run_format`] for the cancellation/fallback contract.
/// Routes to the LaTeX or BibTeX formatter by [`FileKind`].
fn compute_format(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    style: FormatStyle,
    kind: FileKind,
) -> Option<TextEdit> {
    // `Some(Some(s))` = formatted; `Some(None)` = clean refusal (parse/format
    // error); `None` = cache miss / stale snapshot (fall back to the captured text).
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        match kind {
            FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                if !snapshot.parse_diagnostics(file).is_empty() {
                    return Some(None);
                }
                // The cached tree was already parsed with the file's flavor (the
                // salsa `parsed_document` query flavors by path), so this needs no
                // flavor. The merged signature scope folds in the file's loaded
                // local packages (those tracked as project members).
                let root = snapshot.parsed_tree(file);
                let sigs = snapshot.scope_signatures(members_of(snapshot), file);
                Some(format_node_with_signatures(&root, style, sigs).ok())
            }
            FileKind::Bib => {
                if !snapshot.bib_parse_diagnostics(file).is_empty() {
                    return Some(None);
                }
                let root = snapshot.parsed_bib_tree(file);
                Some(bib_format_node(&root, style).ok())
            }
        }
    }));

    let formatted = match cached {
        Ok(Some(opt)) => opt,
        Ok(None) | Err(_) => match kind {
            FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
                format_with_style_flavored(text, style, kind.lex_config()).ok()
            }
            FileKind::Bib => bib_format_with_style(text, style).ok(),
        },
    }?;

    if formatted == text {
        return None;
    }
    let idx = LineIndex::new(text);
    let (end_line, end_col) = idx.utf16_position(text, text.len());
    Some(TextEdit {
        range: Range {
            start: Position::new(0, 0),
            end: Position::new(end_line, end_col),
        },
        new_text: formatted,
    })
}

/// Range-format the buffer behind a [`WorkerJob::RangeFormat`] on the read pool and
/// reply with the (possibly empty) edit array, or `null` on refusal / unknown
/// buffer. Mirrors [`run_format`]'s cancellation/fallback contract.
#[allow(clippy::too_many_arguments)]
fn run_range_format(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    style: FormatStyle,
    kind: FileKind,
    range: Range,
    out_tx: &Sender<Outbound>,
) {
    let result = match compute_range_format(snapshot, path, text, style, kind, range) {
        Some(edits) => serde_json::to_value(edits).unwrap_or(serde_json::Value::Null),
        None => serde_json::Value::Null,
    };
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Produce the minimal edits that range-format `sel_range`, `Some(vec![])` for a
/// no-op, or `None` for a refusal (parse errors), an unsupported kind, or a
/// selection touching no block. LaTeX-only for now; BibTeX returns `None`.
///
/// The whole document is formatted with an emission filter so only the in-range
/// top-level blocks are laid out (see [`format_node_range_with_signatures`]); the
/// formatted fragment is then diffed against the original block slice so the edits
/// are minimal. Shares [`compute_format`]'s salsa fast-path / reparse-fallback
/// shape.
fn compute_range_format(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    style: FormatStyle,
    kind: FileKind,
    sel_range: Range,
) -> Option<Vec<TextEdit>> {
    // Range formatting is LaTeX-only for now; bib falls back to no edits.
    match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {}
        FileKind::Bib => return None,
    }

    let idx = LineIndex::new(text);
    let start = idx.offset_at(text, sel_range.start.line, sel_range.start.character);
    let end = idx.offset_at(text, sel_range.end.line, sel_range.end.character);
    let (lo, hi) = (start.min(end), start.max(end));
    let sel = TextRange::new(
        TextSize::new(lo.min(u32::MAX as usize) as u32),
        TextSize::new(hi.min(u32::MAX as usize) as u32),
    );

    // `Some(Some(e))` = computed edits (possibly empty); `Some(None)` = clean
    // refusal (parse errors); `None` = cache miss / stale snapshot / cancellation
    // → reparse from the captured text.
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        if !snapshot.parse_diagnostics(file).is_empty() {
            return Some(None);
        }
        let root = snapshot.parsed_tree(file);
        let sigs = snapshot.scope_signatures(members_of(snapshot), file);
        Some(Some(range_edits_for_root(
            &root, text, &idx, sel, style, sigs,
        )))
    }));

    match cached {
        Ok(Some(Some(edits))) => edits,
        Ok(Some(None)) => None,
        Ok(None) | Err(_) => {
            let parsed = parse_with_flavor(text, kind.lex_config());
            if !parsed.errors.is_empty() {
                return None;
            }
            range_edits_for_root(
                &parsed.syntax(),
                text,
                &idx,
                sel,
                style,
                &SignatureDb::default(),
            )
        }
    }
}

/// Expand `sel` to top-level-block boundaries, format those blocks, and diff the
/// result against the original slice into minimal edits. `None` when the selection
/// touches no block or the formatter refuses; `Some(vec![])` when already
/// formatted.
fn range_edits_for_root(
    root: &SyntaxNode,
    text: &str,
    idx: &LineIndex,
    sel: TextRange,
    style: FormatStyle,
    external: &SignatureDb,
) -> Option<Vec<TextEdit>> {
    let block_range = expand_to_top_level_blocks(root, sel)?;
    let fragment = format_node_range_with_signatures(root, style, external, block_range).ok()?;
    let base = usize::from(block_range.start());
    let end = usize::from(block_range.end());
    if fragment == text[base..end] {
        return Some(Vec::new());
    }
    Some(diff_to_edits(idx, text, block_range, &fragment))
}

/// Build the document-symbol outline for a [`WorkerJob::Symbols`] on the read pool
/// and reply with a nested [`DocumentSymbolResponse`].
///
/// Fast path: reuse the snapshot's cached tree. On a racing write
/// (`salsa::Cancelled`), a stale snapshot (`file_text != text`), or a cache miss,
/// reparse the captured `text` directly. Best-effort — unlike formatting, a parse
/// error does *not* suppress the outline (the tree is error-tolerant).
fn run_symbols(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    kind: FileKind,
    out_tx: &Sender<Outbound>,
) {
    let symbols = match kind {
        FileKind::Tex | FileKind::Sty | FileKind::Cls | FileKind::Dtx | FileKind::Ins => {
            compute_symbols(snapshot, path, text, kind)
        }
        FileKind::Bib => compute_bib_symbols(snapshot, path, text),
    };
    let result = serde_json::to_value(DocumentSymbolResponse::Nested(symbols))
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Compute the LaTeX outline for `text`, preferring the snapshot's cached tree and
/// falling back to a direct reparse when it is unavailable or stale.
fn compute_symbols(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    kind: FileKind,
) -> Vec<DocumentSymbol> {
    let idx = LineIndex::new(text);
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        Some(outline(&snapshot.parsed_tree(file)))
    }));
    let items = match cached {
        Ok(Some(items)) => items,
        // Cache miss, stale snapshot, or a cancelled read: reparse the buffer. Flavor
        // by file kind so a `.dtx`'s docstrip vocabulary (and thus its documented
        // macros) still surfaces off the fallback path.
        Ok(None) | Err(_) => outline(&SyntaxNode::new_root(
            parse_with_flavor(text, kind.lex_config()).green,
        )),
    };
    items
        .iter()
        .map(|item| to_document_symbol(item, &idx, text))
        .collect()
}

/// Compute the BibTeX outline (a flat entry list) for `text`, preferring the
/// snapshot's cached bib model and falling back to a direct reparse when it is
/// unavailable or stale.
fn compute_bib_symbols(snapshot: &Analysis, path: &Path, text: &str) -> Vec<DocumentSymbol> {
    let idx = LineIndex::new(text);
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        Some(bib_outline(snapshot.bib_semantic_model(file)))
    }));
    let items = match cached {
        Ok(Some(items)) => items,
        // Cache miss, stale snapshot, or a cancelled read: reparse the buffer.
        Ok(None) | Err(_) => bib_outline(&BibModel::build(&bib_parse(text).syntax())),
    };
    items
        .iter()
        .map(|item| bib_to_document_symbol(item, &idx, text))
        .collect()
}

/// Aggregate every tracked LaTeX file's outline into a flat `workspace/symbol`
/// reply, keeping only entries whose name contains `query` (case-insensitive; an
/// empty query matches everything). `.bib` members are skipped — their cite keys
/// are reachable via go-to-def/references. A cancelled per-file read omits that
/// file rather than failing the whole response.
fn run_workspace_symbols(
    snapshot: &Analysis,
    id: RequestId,
    query: &str,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    let needle = query.to_ascii_lowercase();
    let mut symbols = Vec::new();
    for member in members {
        if member.kind == FileKind::Bib {
            continue;
        }
        let collected = salsa::Cancelled::catch(AssertUnwindSafe(|| {
            let text = snapshot.file_text(member.file);
            let idx = LineIndex::new(text);
            let items = outline(&snapshot.parsed_tree(member.file));
            // Group the picker by file via `container_name`.
            let container = member.path.file_stem().and_then(|s| s.to_str());
            let mut file_symbols = Vec::new();
            collect_workspace_symbols(
                &items,
                &member.path,
                &idx,
                text,
                &needle,
                container,
                &mut file_symbols,
            );
            file_symbols
        }));
        if let Ok(mut file_symbols) = collected {
            symbols.append(&mut file_symbols);
        }
    }
    let result = serde_json::to_value(WorkspaceSymbolResponse::Nested(symbols))
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Recursively flatten an [`OutlineItem`] tree into [`WorkspaceSymbol`]s, keeping
/// entries whose name contains `needle`. Children are always visited so a matching
/// label nested under a non-matching section still surfaces.
fn collect_workspace_symbols(
    items: &[OutlineItem],
    path: &Path,
    idx: &LineIndex,
    text: &str,
    needle: &str,
    container: Option<&str>,
    out: &mut Vec<WorkspaceSymbol>,
) {
    for item in items {
        let matches = needle.is_empty() || item.name.to_ascii_lowercase().contains(needle);
        if matches && let Some(location) = location_for(path, idx, text, item.selection_range) {
            out.push(WorkspaceSymbol {
                name: item.name.clone(),
                kind: outline_symbol_kind(item.kind),
                tags: None,
                container_name: container.map(str::to_owned),
                location: OneOf::Left(location),
                data: None,
            });
        }
        // Always recurse: a matching label can nest under a non-matching section.
        collect_workspace_symbols(&item.children, path, idx, text, needle, container, out);
    }
}

/// Compute folding ranges for a [`WorkerJob::FoldingRange`] on the read pool and
/// reply with a `Vec<FoldingRange>`. Same snapshot fast-path / reparse fallback as
/// [`run_symbols`].
fn run_folding(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    kind: FileKind,
    out_tx: &Sender<Outbound>,
) {
    let ranges = compute_folding(snapshot, path, text, kind);
    let result = serde_json::to_value(ranges).unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Compute LaTeX folding ranges for `text`, preferring the snapshot's cached tree and
/// falling back to a direct reparse when it is unavailable or stale. `.bib` files have
/// no LaTeX structure to fold (the LaTeX parser does not apply), so they yield none.
fn compute_folding(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    kind: FileKind,
) -> Vec<FoldingRange> {
    if kind == FileKind::Bib {
        return Vec::new();
    }
    let idx = LineIndex::new(text);
    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let file = snapshot.lookup_file(path)?;
        if snapshot.file_text(file) != text {
            return None;
        }
        Some(folding::folding_ranges(
            &snapshot.parsed_tree(file),
            &idx,
            text,
        ))
    }));
    match cached {
        Ok(Some(ranges)) => ranges,
        // Cache miss, stale snapshot, or a cancelled read: reparse the buffer.
        Ok(None) | Err(_) => {
            folding::folding_ranges(&SyntaxNode::new_root(parse(text).green), &idx, text)
        }
    }
}

/// Convert an [`OutlineItem`] tree into an LSP [`DocumentSymbol`], mapping byte
/// ranges through the (UTF-16-aware) [`LineIndex`].
/// Map an [`OutlineSymbol`] to its LSP [`SymbolKind`]. Shared by the per-file
/// `documentSymbol` ([`to_document_symbol`]) and project-wide `workspace/symbol`
/// ([`run_workspace_symbols`]) outputs so the two never drift.
fn outline_symbol_kind(kind: OutlineSymbol) -> SymbolKind {
    match kind {
        OutlineSymbol::Section => SymbolKind::MODULE,
        OutlineSymbol::Float => SymbolKind::OBJECT,
        OutlineSymbol::Theorem => SymbolKind::CLASS,
        OutlineSymbol::Label => SymbolKind::CONSTANT,
        OutlineSymbol::Macro => SymbolKind::FUNCTION,
        OutlineSymbol::Environment => SymbolKind::INTERFACE,
    }
}

#[allow(deprecated)] // `DocumentSymbol::deprecated` is a required struct field.
fn to_document_symbol(item: &OutlineItem, idx: &LineIndex, text: &str) -> DocumentSymbol {
    let kind = outline_symbol_kind(item.kind);
    let range = item.range;
    let selection = item.selection_range;
    let children: Vec<DocumentSymbol> = item
        .children
        .iter()
        .map(|child| to_document_symbol(child, idx, text))
        .collect();
    DocumentSymbol {
        name: item.name.clone(),
        detail: None,
        kind,
        tags: None,
        deprecated: None,
        range: byte_range_to_lsp(idx, text, range.start().into(), range.end().into()),
        selection_range: byte_range_to_lsp(
            idx,
            text,
            selection.start().into(),
            selection.end().into(),
        ),
        children: (!children.is_empty()).then_some(children),
    }
}

/// Convert a flat [`BibOutlineItem`] into an LSP [`DocumentSymbol`]. Bib entries
/// have no nesting, so there are never children; the cite key is the name and the
/// entry type the detail.
#[allow(deprecated)] // `DocumentSymbol::deprecated` is a required struct field.
fn bib_to_document_symbol(item: &BibOutlineItem, idx: &LineIndex, text: &str) -> DocumentSymbol {
    let range = item.range;
    let selection = item.selection_range;
    DocumentSymbol {
        name: item.name.clone(),
        detail: Some(item.detail.clone()),
        kind: SymbolKind::CONSTANT,
        tags: None,
        deprecated: None,
        range: byte_range_to_lsp(idx, text, range.start().into(), range.end().into()),
        selection_range: byte_range_to_lsp(
            idx,
            text,
            selection.start().into(),
            selection.end().into(),
        ),
        children: None,
    }
}

/// Build completion items for a [`WorkerJob::Completion`] on the read pool and
/// reply with a [`CompletionResponse`].
///
/// Fast path: reuse the snapshot's cached tree + the `document_signatures` /
/// `semantic_model` queries when the tracked buffer still matches `text`. On a
/// racing write (`salsa::Cancelled`), a stale snapshot, or a cache miss, reparse
/// the captured `text` and recompute the signatures/model directly. Best-effort —
/// like symbols, a parse error does not suppress completion (the tree is
/// error-tolerant).
fn run_completion(
    snapshot: &Analysis,
    id: RequestId,
    uri: &Uri,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    // The salsa-key path is derived from the URI (the same mapping `on_completion` uses).
    let path = uri_to_path(uri);
    let items = compute_completion(snapshot, uri, &path, text, position, members);
    // `is_incomplete`: command/label/key universes are prefix-filtered server-side, so
    // the client re-queries as the typed prefix narrows.
    let result = serde_json::to_value(CompletionResponse::List(CompletionList {
        is_incomplete: true,
        items,
    }))
    .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Resolve a highlighted [`CompletionItem`] on the read pool, attaching lazy
/// signature/citation detail (see [`completion_resolve`]) and replying to `id`. A
/// racing write (snapshot cancellation) replies with the item unchanged — the
/// client keeps the un-enriched item, never an error.
fn run_completion_resolve(
    snapshot: &Analysis,
    id: RequestId,
    item: CompletionItem,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    let resolved = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        completion_resolve::resolve(snapshot, item.clone(), members)
    }))
    .unwrap_or(item);
    let result = serde_json::to_value(resolved).unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Compute completion items at `position`. A `.bib` cursor goes through the bib
/// classifier; a `.tex` cursor through the LaTeX one, preferring the snapshot's cached
/// tree/queries and falling back to a direct reparse when unavailable or stale.
fn compute_completion(
    snapshot: &Analysis,
    uri: &Uri,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
) -> Vec<CompletionItem> {
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    if file_kind_for(path) == FileKind::Bib {
        return compute_bib_completion(text, offset);
    }
    compute_tex_completion(snapshot, uri, path, text, offset, members)
}

/// Bib completion: a fresh parse + model (sub-ms, and there is no cached bib tree
/// query) drives the bib classifier and candidate builder.
fn compute_bib_completion(text: &str, offset: usize) -> Vec<CompletionItem> {
    let root = bib_parse(text).syntax();
    let ctx = classify_bib_context(&root, offset);
    let model = BibModel::build(&root);
    bib_candidates(&ctx, &model)
        .into_iter()
        .map(bib_candidate_to_item)
        .collect()
}

/// The outcome of classifying a `.tex` cursor: either ready-to-send pure items, or a
/// cite-key context whose candidates need the cross-file bibliography (resolved
/// against the snapshot, like a file-path read).
enum TexCompletion {
    Items(Vec<CompletionItem>),
    Cite { prefix: String, lint_path: PathBuf },
}

/// LaTeX completion, mirroring go-to-def's cached-or-reparse-then-resolve shape: the
/// pure (command/env/label/file-path) contexts resolve immediately; a `\cite` context
/// defers to [`cite_completion_items`] against the project bibliography.
fn compute_tex_completion(
    snapshot: &Analysis,
    uri: &Uri,
    path: &Path,
    text: &str,
    offset: usize,
    members: Vec<ProjectMember>,
) -> Vec<CompletionItem> {
    // Classify off the cached tree when current; reparse on stale/miss. A cancelled
    // read also falls back to a reparse (`unwrap_or_else`) — neither touches `members`.
    let resolved = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        if let Some(file) = snapshot.lookup_file(path)
            && snapshot.file_text(file) == text
        {
            let root = snapshot.parsed_tree(file);
            let ctx = crate::completion::classify_context(&root, offset);
            return match ctx {
                CompletionContext::CitationKey { prefix } => TexCompletion::Cite {
                    prefix,
                    lint_path: snapshot.file_path(file).to_path_buf(),
                },
                _ => TexCompletion::Items(build_completion_items(
                    &ctx,
                    // The merged scope folds in loaded local packages' macros; the
                    // `members` clone leaves the original for the cite branch below.
                    snapshot.scope_signatures(members.clone(), file),
                    snapshot.semantic_model(file),
                    uri,
                )),
            };
        }
        reparse_tex_completion(text, offset, uri, path)
    }))
    .unwrap_or_else(|_| reparse_tex_completion(text, offset, uri, path));

    match resolved {
        TexCompletion::Items(items) => items,
        TexCompletion::Cite { prefix, lint_path } => {
            // Cross-file resolve against the db snapshot; a racing write yields none.
            salsa::Cancelled::catch(AssertUnwindSafe(|| {
                let (_, citations) = snapshot.resolve_project(members);
                cite_completion_items(snapshot, citations, &lint_path, &prefix)
            }))
            .unwrap_or_default()
        }
    }
}

/// Classify a `.tex` cursor off a fresh parse (the snapshot-free fallback). For a
/// `\cite` context this still defers resolution to the snapshot, keying off `path`.
fn reparse_tex_completion(text: &str, offset: usize, uri: &Uri, path: &Path) -> TexCompletion {
    let root = SyntaxNode::new_root(parse(text).green);
    let ctx = crate::completion::classify_context(&root, offset);
    match ctx {
        CompletionContext::CitationKey { prefix } => TexCompletion::Cite {
            prefix,
            lint_path: path.to_path_buf(),
        },
        _ => {
            let sigs = crate::semantic::scan_definitions(&root);
            let model = SemanticModel::build(&root);
            TexCompletion::Items(build_completion_items(&ctx, &sigs, &model, uri))
        }
    }
}

/// Cite-key candidates: every entry key in the citing file's bibliography namespace,
/// prefix-filtered (case-insensitive, as BibTeX folds key case) and deduped. Mirrors
/// [`resolve_citation_locations`] but collects all keys rather than matching a target.
fn cite_completion_items(
    snapshot: &Analysis,
    citations: &ResolvedCitations,
    lint_path: &Path,
    prefix: &str,
) -> Vec<CompletionItem> {
    let prefix = prefix.to_lowercase();
    let mut keys: Vec<SmolStr> = Vec::new();
    for bib_path in citations.bib_definers(lint_path) {
        let Some(file) = snapshot.lookup_file(bib_path) else {
            continue;
        };
        for entry in snapshot.bib_semantic_model(file).entries() {
            if entry.key.to_lowercase().starts_with(&prefix) {
                keys.push(entry.key.clone());
            }
        }
    }
    keys.sort();
    keys.dedup();
    keys.into_iter()
        .map(|key| CompletionItem {
            // Carry the citing file + key so `completionItem/resolve` can re-walk
            // the bibliography namespace and attach the entry card lazily.
            data: completion_resolve::CompletionResolveData::Citation {
                lint_path: lint_path.to_path_buf(),
                key: key.to_string(),
            }
            .into_value(),
            label: key.to_string(),
            kind: Some(CompletionItemKind::REFERENCE),
            ..Default::default()
        })
        .collect()
}

/// Map a neutral [`BibCompletionCandidate`] onto an `lsp_types::CompletionItem`.
fn bib_candidate_to_item(candidate: BibCompletionCandidate) -> CompletionItem {
    let kind = match candidate.kind {
        BibCandidateKind::EntryType => CompletionItemKind::STRUCT,
        BibCandidateKind::FieldName => CompletionItemKind::FIELD,
        BibCandidateKind::StringMacro => CompletionItemKind::CONSTANT,
    };
    CompletionItem {
        label: candidate.label,
        kind: Some(kind),
        ..Default::default()
    }
}

/// Describe the command/environment or `\cite` key under the cursor and reply with a
/// [`Hover`] (or `null` when nothing resolves).
fn run_hover(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    let result = hover::compute_hover(snapshot, path, text, position, members)
        .and_then(|hover| serde_json::to_value(hover).ok())
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Resolve the `\ref`/`\cite` under the cursor and reply with the matching
/// definition [`Location`]s (always an array — empty when nothing resolves).
fn run_goto_definition(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    let locations = compute_goto_definition(snapshot, path, text, position, members);
    let result = serde_json::to_value(GotoDefinitionResponse::Array(locations))
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Resolve the label/key under the cursor and reply with every use [`Location`]
/// across its namespace (always an array — empty when nothing resolves).
#[allow(clippy::too_many_arguments)]
fn run_references(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
    include_declaration: bool,
    out_tx: &Sender<Outbound>,
) {
    let locations =
        compute_references(snapshot, path, text, position, members, include_declaration);
    let result = serde_json::to_value(locations).unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Resolve the label/cite key under the cursor and reply with its key-token range +
/// placeholder, or `null` when the cursor isn't on a renameable key. The narrow
/// `key_range` (not the whole-command range) is what anchors the client's rename UI.
/// Resolve the cross-reference key under the cursor and reply with every same-key
/// occurrence in the buffer as `DocumentHighlight`s (an empty array when nothing
/// resolves), serialized to the read pool's outbound channel.
fn run_document_highlight(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    out_tx: &Sender<Outbound>,
) {
    let highlights = compute_document_highlight(snapshot, path, text, position);
    let result = serde_json::to_value(highlights).unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

fn run_prepare_rename(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    out_tx: &Sender<Outbound>,
) {
    let result = compute_prepare_rename(snapshot, path, text, position)
        .map(|(range, placeholder)| {
            serde_json::to_value(PrepareRenameResponse::RangeWithPlaceholder { range, placeholder })
                .unwrap_or(serde_json::Value::Null)
        })
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// Resolve the label/cite key under the cursor and reply with the project-wide
/// [`WorkspaceEdit`] renaming it (definition and every referencing command), or
/// `null` when nothing resolves or the new name is rejected.
#[allow(clippy::too_many_arguments)]
fn run_rename(
    snapshot: &Analysis,
    id: RequestId,
    path: &Path,
    text: &str,
    position: Position,
    new_name: &str,
    members: Vec<ProjectMember>,
    out_tx: &Sender<Outbound>,
) {
    let result = compute_rename(snapshot, path, text, position, new_name, members)
        .and_then(|edit| serde_json::to_value(edit).ok())
        .unwrap_or(serde_json::Value::Null);
    let _ = out_tx.send(Outbound::Response(Response::new_ok(id, result)));
}

/// What the cursor points at inside a `.tex` buffer: the keys whose command range
/// covers the offset. Refs and citations are kept distinct so each resolves against
/// its own namespace (labels vs. bibliography). A multi-key list command
/// (`\cref{a,b}`, `\cite{a,b}`) shares one range, so every key at that offset is
/// returned and resolved — per-key sub-ranges are deferred (see
/// [`crate::semantic::label::LabelRef::range`]).
#[derive(Debug)]
enum CursorTarget {
    Labels(Vec<SmolStr>),
    Citations(Vec<SmolStr>),
}

/// The renameable key under the cursor: which name(s) to rewrite project-wide
/// ([`target`](Self::target)), the precise key-token span the cursor sits on (for
/// the `prepareRename` range), and the current key text as the rename placeholder.
#[derive(Debug)]
struct RenameTarget {
    target: CursorTarget,
    span: TextRange,
    placeholder: SmolStr,
}

/// Compute the definition locations for a go-to-definition at `position`, preferring
/// the snapshot's cached model and falling back to a fresh parse when it is stale or
/// uncached. Cross-file resolution always runs against the db snapshot's resolvers
/// (`resolved_labels`/`resolved_citations`), interned from `members`.
fn compute_goto_definition(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
) -> Vec<Location> {
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    let cached = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        // Find the reference under the cursor (off the cached model when current,
        // else a fresh parse), then resolve cross-file against the db snapshot.
        let (target, lint_path) = match snapshot.lookup_file(path) {
            Some(file) if snapshot.file_text(file) == text => (
                reference_under_cursor(snapshot.semantic_model(file), offset),
                snapshot.file_path(file).to_path_buf(),
            ),
            _ => {
                let root = SyntaxNode::new_root(parse(text).green);
                let model = SemanticModel::build(&root);
                (reference_under_cursor(&model, offset), path.to_path_buf())
            }
        };
        let Some(target) = target else {
            return Vec::new();
        };
        let (resolution, citations) = snapshot.resolve_project(members);
        match target {
            CursorTarget::Labels(names) => {
                resolve_label_locations(snapshot, resolution, &lint_path, &names)
            }
            CursorTarget::Citations(names) => {
                resolve_citation_locations(snapshot, citations, &lint_path, &names)
            }
        }
    }));
    cached.unwrap_or_default()
}

/// The cite/ref keys whose command range covers `offset`, refs taking precedence
/// (a position is never both). Returns owned keys so the borrowed model can drop.
fn reference_under_cursor(model: &SemanticModel, offset: usize) -> Option<CursorTarget> {
    let at = TextSize::new(offset as u32);
    let label_names: Vec<SmolStr> = model
        .refs()
        .iter()
        .filter(|r| r.range.contains_inclusive(at))
        .map(|r| r.name.clone())
        .collect();
    if !label_names.is_empty() {
        return Some(CursorTarget::Labels(label_names));
    }
    let cite_names: Vec<SmolStr> = model
        .citations()
        .iter()
        .filter(|c| c.range.contains_inclusive(at))
        .map(|c| c.name.clone())
        .collect();
    (!cite_names.is_empty()).then_some(CursorTarget::Citations(cite_names))
}

/// Compute every use location for a find-references at `position`. The inverse of
/// [`compute_goto_definition`]: resolves a label/key (from a `\ref`/`\cite` use,
/// a `\label` definition, or — in a `.bib` buffer — an `@entry` key) to all of its
/// `\ref`/`\cite` use sites across the namespace. The cursor's own buffer is read
/// off the cached tree when current, else a fresh parse. `include_declaration`
/// appends the `\label`/`@entry` definition to the results.
fn compute_references(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
    members: Vec<ProjectMember>,
    include_declaration: bool,
) -> Vec<Location> {
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    let computed = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let (resolution, citations) = snapshot.resolve_project(members);

        // `.bib` origin: the `@entry` key under the cursor → its `\cite` uses. A
        // `.bib` path is not keyed in the citation `component_of`, so resolution
        // goes through `bib_citers`.
        if file_kind_for(path) == FileKind::Bib {
            let Some((key, key_range)) = bib_entry_under_cursor(snapshot, path, text, offset)
            else {
                return Vec::new();
            };
            let origin = snapshot
                .lookup_file(path)
                .map(|file| snapshot.file_path(file).to_path_buf())
                .unwrap_or_else(|| path.to_path_buf());
            let decl = if include_declaration {
                location_for(&origin, &idx, text, key_range)
            } else {
                None
            };
            return reference_citation_locations(
                snapshot,
                citations,
                &origin,
                FileKind::Bib,
                &[key],
                include_declaration,
                decl,
            );
        }

        // `.tex` origin: a `\ref`/`\cite` use *or* a `\label` definition.
        let (target, origin) = match snapshot.lookup_file(path) {
            Some(file) if snapshot.file_text(file) == text => (
                references_target_under_cursor(snapshot.semantic_model(file), offset),
                snapshot.file_path(file).to_path_buf(),
            ),
            _ => {
                let root = SyntaxNode::new_root(parse(text).green);
                let model = SemanticModel::build(&root);
                (
                    references_target_under_cursor(&model, offset),
                    path.to_path_buf(),
                )
            }
        };
        let Some(target) = target else {
            return Vec::new();
        };
        match target {
            CursorTarget::Labels(names) => reference_label_locations(
                snapshot,
                resolution,
                &origin,
                &names,
                include_declaration,
            ),
            CursorTarget::Citations(names) => reference_citation_locations(
                snapshot,
                citations,
                &origin,
                FileKind::Tex,
                &names,
                include_declaration,
                None,
            ),
        }
    }));
    computed.unwrap_or_default()
}

/// Like [`reference_under_cursor`] but also recognizes a `\label` *definition*
/// under the cursor, so find-references can be invoked from the definition site
/// (a `\ref` and a `\label` both resolve to the same label name). Precedence
/// matches [`reference_under_cursor`] (refs, then citations), with label defs
/// slotted last; a position is in at most one of the three.
fn references_target_under_cursor(model: &SemanticModel, offset: usize) -> Option<CursorTarget> {
    if let Some(target) = reference_under_cursor(model, offset) {
        return Some(target);
    }
    let at = TextSize::new(offset as u32);
    let label_names: Vec<SmolStr> = model
        .labels()
        .iter()
        .filter(|l| l.range.contains_inclusive(at))
        .map(|l| l.name.clone())
        .collect();
    (!label_names.is_empty()).then_some(CursorTarget::Labels(label_names))
}

/// The renameable key whose **key-token** range (not the whole-command range)
/// covers `offset`: a `\ref`/`\cite` use or a `\label` definition. Keyed on
/// `key_range` so the cursor must sit on the key itself — a position on the command
/// word, the braces, or a sibling key in a `\cref{a,b}` resolves to `None`, which is
/// what makes `prepareRename` decline outside a key. Precedence mirrors
/// [`reference_under_cursor`] (refs, then citations, then label defs); the spans are
/// disjoint, so at most one matches.
fn rename_target_under_cursor(model: &SemanticModel, offset: usize) -> Option<RenameTarget> {
    let at = TextSize::new(offset as u32);
    if let Some(r) = model
        .refs()
        .iter()
        .find(|r| r.key_range.contains_inclusive(at))
    {
        return Some(RenameTarget {
            target: CursorTarget::Labels(vec![r.name.clone()]),
            span: r.key_range,
            placeholder: r.name.clone(),
        });
    }
    if let Some(c) = model
        .citations()
        .iter()
        .find(|c| c.key_range.contains_inclusive(at))
    {
        return Some(RenameTarget {
            target: CursorTarget::Citations(vec![c.name.clone()]),
            span: c.key_range,
            placeholder: c.name.clone(),
        });
    }
    let label = model
        .labels()
        .iter()
        .find(|l| l.key_range.contains_inclusive(at))?;
    Some(RenameTarget {
        target: CursorTarget::Labels(vec![label.name.clone()]),
        span: label.key_range,
        placeholder: label.name.clone(),
    })
}

/// Compute the `prepareRename` range + placeholder at `position`: the key-token span
/// under the cursor and its current text. Reads the cached model when current, else a
/// fresh parse (the same guard as [`compute_references`]); a `.bib` cursor resolves
/// to its `@entry` key. `None` when the cursor isn't on a renameable key.
/// Compute the document highlights for `position`: the cross-reference key under the
/// cursor (a `\ref`/`\cite` use or a `\label` definition) and every same-key occurrence
/// in the *same* buffer. Single-file, so no project resolution — the `\label`
/// definition shades as [`DocumentHighlightKind::WRITE`] and every `\ref`/`\cite` use
/// as [`DocumentHighlightKind::READ`]. Strict key gating (via
/// [`rename_target_under_cursor`]): a cursor on the command word, the braces, or a
/// sibling key in `\cref{a,b}` highlights nothing for that key. `.bib` buffers yield no
/// highlights (an `@entry` key has no in-file uses).
fn compute_document_highlight(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
) -> Vec<DocumentHighlight> {
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    let computed = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        if file_kind_for(path) == FileKind::Bib {
            return Vec::new();
        }
        let collect = |model: &SemanticModel| -> Vec<DocumentHighlight> {
            let Some(target) = rename_target_under_cursor(model, offset) else {
                return Vec::new();
            };
            let highlight = |range: TextRange, kind: DocumentHighlightKind| DocumentHighlight {
                range: lsp_range(&idx, text, range),
                kind: Some(kind),
            };
            match &target.target {
                CursorTarget::Labels(_) => {
                    let name = &target.placeholder;
                    let defs = model
                        .labels()
                        .iter()
                        .filter(|l| &l.name == name)
                        .map(|l| highlight(l.key_range, DocumentHighlightKind::WRITE));
                    let uses = model
                        .refs()
                        .iter()
                        .filter(|r| &r.name == name)
                        .map(|r| highlight(r.key_range, DocumentHighlightKind::READ));
                    defs.chain(uses).collect()
                }
                CursorTarget::Citations(_) => {
                    let name = &target.placeholder;
                    model
                        .citations()
                        .iter()
                        .filter(|c| &c.name == name)
                        .map(|c| highlight(c.key_range, DocumentHighlightKind::READ))
                        .collect()
                }
            }
        };
        match snapshot.lookup_file(path) {
            Some(file) if snapshot.file_text(file) == text => {
                collect(snapshot.semantic_model(file))
            }
            _ => {
                let root = SyntaxNode::new_root(parse(text).green);
                collect(&SemanticModel::build(&root))
            }
        }
    }));
    computed.unwrap_or_default()
}

fn compute_prepare_rename(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
) -> Option<(Range, String)> {
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    let computed = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        // `.bib` origin: the `@entry` key under the cursor.
        if file_kind_for(path) == FileKind::Bib {
            let (key, key_range) = bib_entry_under_cursor(snapshot, path, text, offset)?;
            return Some((lsp_range(&idx, text, key_range), key.to_string()));
        }
        // `.tex` origin: a `\ref`/`\cite` use or a `\label` definition.
        let target = match snapshot.lookup_file(path) {
            Some(file) if snapshot.file_text(file) == text => {
                rename_target_under_cursor(snapshot.semantic_model(file), offset)
            }
            _ => {
                let root = SyntaxNode::new_root(parse(text).green);
                let model = SemanticModel::build(&root);
                rename_target_under_cursor(&model, offset)
            }
        }?;
        Some((
            lsp_range(&idx, text, target.span),
            target.placeholder.to_string(),
        ))
    }));
    computed.ok().flatten()
}

/// Compute the [`WorkspaceEdit`] renaming the key under the cursor to `new_name`
/// across its namespace — the write mirror of [`compute_references`]. Rewrites only
/// the per-key `key_range` of each occurrence (so a sibling key in `\cref{a,b}` is
/// untouched), always including the definition. Best-effort: every occurrence in the
/// *visible* namespace is rewritten (an unresolved/dynamic `\input` may hide a use we
/// cannot see). `None` when `new_name` is not a syntactically safe key, or nothing
/// resolves.
fn compute_rename(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    position: Position,
    new_name: &str,
    members: Vec<ProjectMember>,
) -> Option<WorkspaceEdit> {
    if !is_valid_key(new_name) {
        return None;
    }
    let idx = LineIndex::new(text);
    let offset = idx.offset_at(text, position.line, position.character);

    let changes = salsa::Cancelled::catch(AssertUnwindSafe(|| {
        let (resolution, citations) = snapshot.resolve_project(members);

        // `.bib` origin: the `@entry` key under the cursor → its `\cite` uses + the
        // entry itself.
        if file_kind_for(path) == FileKind::Bib {
            let Some((key, _)) = bib_entry_under_cursor(snapshot, path, text, offset) else {
                return HashMap::new();
            };
            let origin = snapshot
                .lookup_file(path)
                .map(|file| snapshot.file_path(file).to_path_buf())
                .unwrap_or_else(|| path.to_path_buf());
            return rename_citation_edits(
                snapshot,
                citations,
                &origin,
                FileKind::Bib,
                &[key],
                new_name,
            );
        }

        // `.tex` origin: a `\ref`/`\cite` use or a `\label` definition.
        let (target, origin) = match snapshot.lookup_file(path) {
            Some(file) if snapshot.file_text(file) == text => (
                rename_target_under_cursor(snapshot.semantic_model(file), offset),
                snapshot.file_path(file).to_path_buf(),
            ),
            _ => {
                let root = SyntaxNode::new_root(parse(text).green);
                let model = SemanticModel::build(&root);
                (
                    rename_target_under_cursor(&model, offset),
                    path.to_path_buf(),
                )
            }
        };
        let Some(target) = target else {
            return HashMap::new();
        };
        match target.target {
            CursorTarget::Labels(names) => {
                rename_label_edits(snapshot, resolution, &origin, &names, new_name)
            }
            CursorTarget::Citations(names) => rename_citation_edits(
                snapshot,
                citations,
                &origin,
                FileKind::Tex,
                &names,
                new_name,
            ),
        }
    }))
    .unwrap_or_default();
    finalize_rename(changes)
}

/// The cite key of the `@entry` whose key range covers `offset` in a `.bib`
/// buffer, with that key's byte range. Reads the cached model when current, else a
/// fresh bib parse (the bib analog of [`compute_references`]'s `.tex` guard).
fn bib_entry_under_cursor(
    snapshot: &Analysis,
    path: &Path,
    text: &str,
    offset: usize,
) -> Option<(SmolStr, TextRange)> {
    let at = TextSize::new(offset as u32);
    let find = |model: &BibModel| {
        model
            .entries()
            .iter()
            .find(|e| e.key_range.contains_inclusive(at))
            .map(|e| (e.key.clone(), e.key_range))
    };
    match snapshot.lookup_file(path) {
        Some(file) if snapshot.file_text(file) == text => find(snapshot.bib_semantic_model(file)),
        _ => find(&BibModel::build(&bib_parse(text).syntax())),
    }
}

/// Every `\ref`-family use of `names` across `origin`'s label namespace, plus the
/// `\label` definitions when `include_declaration`. The inverse of
/// [`resolve_label_locations`]: scans each namespace member's uses, not its defs.
fn reference_label_locations(
    snapshot: &Analysis,
    resolution: &ResolvedLabels,
    origin: &Path,
    names: &[SmolStr],
    include_declaration: bool,
) -> Vec<Location> {
    let mut locations = Vec::new();
    for member in resolution.namespace_members(origin) {
        let Some(file) = snapshot.lookup_file(member) else {
            continue;
        };
        let text = snapshot.file_text(file);
        let idx = LineIndex::new(text);
        let model = snapshot.semantic_model(file);
        for r in model.refs() {
            if names.contains(&r.name) {
                locations.push(location_for(member, &idx, text, r.range));
            }
        }
        if include_declaration {
            for label in model.labels() {
                if names.contains(&label.name) {
                    locations.push(location_for(member, &idx, text, label.range));
                }
            }
        }
    }
    dedup_locations(locations)
}

/// Every `\cite`-family use of `names` across `origin`'s citation namespace, plus
/// the bibliography `@entry` definitions when `include_declaration`. Use sites
/// live in `.tex` members — `bib_citers` for a `.bib` origin (whose path is not
/// keyed in the citation `component_of`), else `namespace_members`. The
/// declaration is the cursor's own entry (`decl_for_bib`) for a `.bib` origin, or
/// [`resolve_citation_locations`] for a `.tex` origin.
#[allow(clippy::too_many_arguments)]
fn reference_citation_locations(
    snapshot: &Analysis,
    citations: &ResolvedCitations,
    origin: &Path,
    kind: FileKind,
    names: &[SmolStr],
    include_declaration: bool,
    decl_for_bib: Option<Location>,
) -> Vec<Location> {
    let members = if kind == FileKind::Bib {
        citations.bib_citers(origin)
    } else {
        citations.namespace_members(origin)
    };
    let mut locations = Vec::new();
    for member in members {
        let Some(file) = snapshot.lookup_file(member) else {
            continue;
        };
        let text = snapshot.file_text(file);
        let idx = LineIndex::new(text);
        for c in snapshot.semantic_model(file).citations() {
            if names.iter().any(|n| n.eq_ignore_ascii_case(&c.name)) {
                locations.push(location_for(member, &idx, text, c.range));
            }
        }
    }
    let mut locations = dedup_locations(locations);
    if include_declaration {
        match kind {
            FileKind::Bib => locations.extend(decl_for_bib),
            _ => locations.extend(resolve_citation_locations(
                snapshot, citations, origin, names,
            )),
        }
    }
    locations
}

/// For each `\ref` key, the `\label{key}` definition sites across the file's
/// namespace: `resolution.definers` gives the defining files, each file's
/// `semantic_model` the matching `LabelDef.range`.
fn resolve_label_locations(
    snapshot: &Analysis,
    resolution: &ResolvedLabels,
    lint_path: &Path,
    names: &[SmolStr],
) -> Vec<Location> {
    let mut locations = Vec::new();
    for name in names {
        for def_path in resolution.definers(lint_path, name) {
            let Some(file) = snapshot.lookup_file(def_path) else {
                continue;
            };
            let text = snapshot.file_text(file);
            let idx = LineIndex::new(text);
            for label in snapshot.semantic_model(file).labels() {
                if &label.name == name {
                    locations.push(location_for(def_path, &idx, text, label.range));
                }
            }
        }
    }
    dedup_locations(locations)
}

/// For each `\cite` key, the `@entry{key,…}` sites in the `.bib` files of the
/// citation namespace: `citations.bib_definers` gives the analyzed bibliographies,
/// each `bib_semantic_model` the matching `Entry.key_range` (case-insensitive, as
/// BibTeX folds key case).
fn resolve_citation_locations(
    snapshot: &Analysis,
    citations: &ResolvedCitations,
    lint_path: &Path,
    names: &[SmolStr],
) -> Vec<Location> {
    let mut locations = Vec::new();
    for bib_path in citations.bib_definers(lint_path) {
        let Some(file) = snapshot.lookup_file(bib_path) else {
            continue;
        };
        let text = snapshot.file_text(file);
        let idx = LineIndex::new(text);
        for entry in snapshot.bib_semantic_model(file).entries() {
            if names.iter().any(|n| n.eq_ignore_ascii_case(&entry.key)) {
                locations.push(location_for(bib_path, &idx, text, entry.key_range));
            }
        }
    }
    dedup_locations(locations)
}

/// Build an LSP [`Location`] from a definer file's path and a byte range in its
/// text. A path that cannot form a `file://` URI yields `None` (skipped).
fn location_for(path: &Path, idx: &LineIndex, text: &str, range: TextRange) -> Option<Location> {
    Some(Location {
        uri: path_to_uri(path)?,
        range: byte_range_to_lsp(
            idx,
            text,
            usize::from(range.start()),
            usize::from(range.end()),
        ),
    })
}

/// Drop duplicate locations (same URI + range), which can arise when several keys
/// in a list command resolve to the same site.
fn dedup_locations(locations: Vec<Option<Location>>) -> Vec<Location> {
    let mut seen = HashSet::new();
    locations
        .into_iter()
        .flatten()
        .filter(|loc| seen.insert((loc.uri.as_str().to_owned(), loc.range.start, loc.range.end)))
        .collect()
}

/// Convert a byte [`TextRange`] (over `text`) to an LSP [`Range`] via `idx`.
fn lsp_range(idx: &LineIndex, text: &str, range: TextRange) -> Range {
    byte_range_to_lsp(
        idx,
        text,
        usize::from(range.start()),
        usize::from(range.end()),
    )
}

/// Every `\ref`-family use of `names` across `origin`'s label namespace, plus every
/// `\label` definition, each rewritten to `new_name` at its precise `key_range`. The
/// rename mirror of [`reference_label_locations`] — `TextEdit`s grouped by URI
/// instead of `Location`s, and the definition is *always* included (a rename rewrites
/// the def, unlike find-references' optional declaration).
fn rename_label_edits(
    snapshot: &Analysis,
    resolution: &ResolvedLabels,
    origin: &Path,
    names: &[SmolStr],
    new_name: &str,
) -> HashMap<Uri, Vec<TextEdit>> {
    let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
    for member in resolution.namespace_members(origin) {
        let Some(file) = snapshot.lookup_file(member) else {
            continue;
        };
        let Some(uri) = path_to_uri(member) else {
            continue;
        };
        let text = snapshot.file_text(file);
        let idx = LineIndex::new(text);
        let model = snapshot.semantic_model(file);
        for r in model.refs() {
            if names.contains(&r.name) {
                push_edit(&mut changes, &uri, &idx, text, r.key_range, new_name);
            }
        }
        for label in model.labels() {
            if names.contains(&label.name) {
                push_edit(&mut changes, &uri, &idx, text, label.key_range, new_name);
            }
        }
    }
    changes
}

/// Every `\cite`-family use of `names` across `origin`'s citation namespace, plus the
/// bibliography `@entry` keys, rewritten to `new_name` at each precise `key_range`.
/// The rename mirror of [`reference_citation_locations`]: `.tex` use sites come from
/// `bib_citers` (a `.bib` origin) or `namespace_members` (a `.tex` origin); the
/// definition sites are the origin bib itself (`.bib` origin) or `bib_definers` (a
/// `.tex` origin). Matching is case-insensitive, as BibTeX folds key case.
fn rename_citation_edits(
    snapshot: &Analysis,
    citations: &ResolvedCitations,
    origin: &Path,
    kind: FileKind,
    names: &[SmolStr],
    new_name: &str,
) -> HashMap<Uri, Vec<TextEdit>> {
    let mut changes: HashMap<Uri, Vec<TextEdit>> = HashMap::new();
    let tex_members = if kind == FileKind::Bib {
        citations.bib_citers(origin)
    } else {
        citations.namespace_members(origin)
    };
    for member in tex_members {
        let Some(file) = snapshot.lookup_file(member) else {
            continue;
        };
        let Some(uri) = path_to_uri(member) else {
            continue;
        };
        let text = snapshot.file_text(file);
        let idx = LineIndex::new(text);
        for c in snapshot.semantic_model(file).citations() {
            if names.iter().any(|n| n.eq_ignore_ascii_case(&c.name)) {
                push_edit(&mut changes, &uri, &idx, text, c.key_range, new_name);
            }
        }
    }
    match kind {
        // From a `.bib` cursor, rewrite the entry in the origin bibliography itself.
        FileKind::Bib => push_bib_entry_edits(snapshot, &mut changes, origin, names, new_name),
        _ => {
            for bib_path in citations.bib_definers(origin) {
                push_bib_entry_edits(snapshot, &mut changes, bib_path, names, new_name);
            }
        }
    }
    changes
}

/// Push the `@entry` key edits for `names` in the bibliography at `bib_path` (case-
/// insensitive match), rewriting each `key_range` to `new_name`.
fn push_bib_entry_edits(
    snapshot: &Analysis,
    changes: &mut HashMap<Uri, Vec<TextEdit>>,
    bib_path: &Path,
    names: &[SmolStr],
    new_name: &str,
) {
    let Some(file) = snapshot.lookup_file(bib_path) else {
        return;
    };
    let Some(uri) = path_to_uri(bib_path) else {
        return;
    };
    let text = snapshot.file_text(file);
    let idx = LineIndex::new(text);
    for entry in snapshot.bib_semantic_model(file).entries() {
        if names.iter().any(|n| n.eq_ignore_ascii_case(&entry.key)) {
            push_edit(changes, &uri, &idx, text, entry.key_range, new_name);
        }
    }
}

/// Append a `key_range → new_name` [`TextEdit`] to `uri`'s edit list.
fn push_edit(
    changes: &mut HashMap<Uri, Vec<TextEdit>>,
    uri: &Uri,
    idx: &LineIndex,
    text: &str,
    range: TextRange,
    new_name: &str,
) {
    changes.entry(uri.clone()).or_default().push(TextEdit {
        range: lsp_range(idx, text, range),
        new_text: new_name.to_owned(),
    });
}

/// Sort and dedup each file's edits, drop empty files, and wrap the rest in a
/// [`WorkspaceEdit`]. `None` when nothing is left to rewrite (so the handler replies
/// `null`).
fn finalize_rename(mut changes: HashMap<Uri, Vec<TextEdit>>) -> Option<WorkspaceEdit> {
    changes.retain(|_, edits| {
        edits.sort_by_key(|edit| (edit.range.start, edit.range.end));
        edits.dedup();
        !edits.is_empty()
    });
    (!changes.is_empty()).then(|| WorkspaceEdit {
        changes: Some(changes),
        ..Default::default()
    })
}

/// Whether `new_name` is a safe replacement key: non-empty after trimming and free of
/// characters that would break the surface syntax or the comma key-list split (so an
/// applied rename can never introduce a parse/format error). Conservative — a few
/// exotic-but-legal key characters are rejected rather than risk a corrupt edit.
fn is_valid_key(new_name: &str) -> bool {
    !new_name.trim().is_empty()
        && !new_name.chars().any(|c| {
            matches!(
                c,
                '{' | '}' | '%' | '\\' | ',' | '#' | '~' | '$' | '^' | '&' | '\n' | '\r'
            )
        })
}

/// Turn a classified [`CompletionContext`] into LSP items. Name/label contexts go
/// through the pure [`crate::completion::candidates`]; a file-path context reads
/// the document's directory off disk (see [`file_completion_items`]).
fn build_completion_items(
    ctx: &CompletionContext,
    sigs: &SignatureDb,
    model: &SemanticModel,
    uri: &Uri,
) -> Vec<CompletionItem> {
    match ctx {
        CompletionContext::FilePath { prefix, kind } => file_completion_items(uri, prefix, *kind),
        CompletionContext::None => Vec::new(),
        _ => {
            // The document path keys the scope-first signature lookup that
            // `completionItem/resolve` repeats; unsaved buffers have none.
            let file = uri_to_fs_path(uri);
            crate::completion::candidates(ctx, sigs, model)
                .into_iter()
                .map(|candidate| candidate_to_item(candidate, file.as_deref()))
                .collect()
        }
    }
}

/// Map a neutral [`CompletionCandidate`] onto an `lsp_types::CompletionItem`. A
/// command/environment carries resolve `data` (its name + originating `file`) so
/// its signature can be attached lazily; a label carries none.
fn candidate_to_item(candidate: CompletionCandidate, file: Option<&Path>) -> CompletionItem {
    let kind = match candidate.kind {
        CandidateKind::Command => CompletionItemKind::FUNCTION,
        CandidateKind::Environment => CompletionItemKind::CLASS,
        CandidateKind::Label => CompletionItemKind::REFERENCE,
    };
    let data = file.and_then(|file| {
        let payload = match candidate.kind {
            CandidateKind::Command => completion_resolve::CompletionResolveData::Command {
                name: candidate.label.clone(),
                file: file.to_path_buf(),
            },
            CandidateKind::Environment => completion_resolve::CompletionResolveData::Environment {
                name: candidate.label.clone(),
                file: file.to_path_buf(),
            },
            CandidateKind::Label => return None,
        };
        payload.into_value()
    });
    CompletionItem {
        label: candidate.label,
        kind: Some(kind),
        insert_text: candidate.insert_text,
        insert_text_format: candidate.snippet.then_some(InsertTextFormat::SNIPPET),
        data,
        ..Default::default()
    }
}

/// File-path candidates for a `\includegraphics`/`\input`/… argument: read the
/// directory the partial path points into (relative to the document's on-disk
/// directory) and offer matching files (by [`FileArgKind`] extension) and
/// subdirectories. Empty for an unsaved buffer (no `file://` path) or an
/// unreadable directory. The label is the bare entry name; editors treat `/` as a
/// word boundary, so completing after `img/` replaces only the trailing segment.
fn file_completion_items(uri: &Uri, prefix: &str, kind: FileArgKind) -> Vec<CompletionItem> {
    let Some(doc_path) = uri_to_fs_path(uri) else {
        return Vec::new();
    };
    let Some(doc_dir) = doc_path.parent() else {
        return Vec::new();
    };
    // Split the typed prefix into its directory part and the trailing filename
    // prefix; the directory part is resolved relative to the document.
    let (dir_part, file_prefix) = match prefix.rfind('/') {
        Some(slash) => (&prefix[..=slash], &prefix[slash + 1..]),
        None => ("", prefix),
    };
    let Ok(entries) = std::fs::read_dir(doc_dir.join(dir_part)) else {
        return Vec::new();
    };

    let mut items = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        // Skip hidden entries and those not matching the typed filename prefix.
        if name.starts_with('.') || !name.starts_with(file_prefix) {
            continue;
        }
        let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
        if is_dir {
            items.push(CompletionItem {
                label: name,
                kind: Some(CompletionItemKind::FOLDER),
                ..Default::default()
            });
        } else if has_extension(&name, kind.extensions()) {
            items.push(CompletionItem {
                label: name,
                kind: Some(CompletionItemKind::FILE),
                ..Default::default()
            });
        }
    }
    items
}

/// Whether `name`'s extension (case-insensitive) is one of `exts`.
fn has_extension(name: &str, exts: &[&str]) -> bool {
    match name.rsplit_once('.') {
        Some((_, ext)) => {
            let ext = ext.to_ascii_lowercase();
            exts.contains(&ext.as_str())
        }
        None => false,
    }
}

/// Convert a `file://` document URI to a filesystem path, percent-decoding the
/// path. Returns `None` for a non-`file` scheme (an in-memory/unsaved buffer),
/// so file-path completion simply yields nothing there. Minimal by design — local
/// `file:///abs/path` URIs only; no `file://host/...` authority handling (rare for
/// editor documents) and no new dependency.
fn uri_to_fs_path(uri: &Uri) -> Option<PathBuf> {
    let rest = uri.as_str().strip_prefix("file://")?;
    // An empty authority leaves `rest` starting at the absolute path's `/`. Drop a
    // non-empty authority defensively (everything up to the first `/`).
    let path = match rest.strip_prefix('/') {
        Some(_) => rest,
        None => rest.split_once('/').map(|(_, p)| p)?,
    };
    let path = percent_decode(path);
    // A Windows file URI carries the absolute path as `/C:/dir/...`; the leading
    // slash is URI syntax, not part of the filesystem path (`C:\dir`). Strip it
    // when a drive-letter component follows so `read_dir` sees a real path. On
    // Unix the leading `/` is the filesystem root and must stay.
    let path = strip_drive_letter_slash(&path);
    Some(PathBuf::from(path))
}

/// Strip the leading slash of a Windows drive-letter path (`/C:/dir` → `C:/dir`),
/// leaving any other path (including Unix absolute paths) untouched. Recognizes a
/// single ASCII-letter drive followed by `:` and a separator or the end.
fn strip_drive_letter_slash(path: &str) -> &str {
    let bytes = path.as_bytes();
    if let [b'/', drive, b':', rest @ ..] = bytes
        && drive.is_ascii_alphabetic()
        && matches!(rest, [] | [b'/', ..] | [b'\\', ..])
    {
        &path[1..]
    } else {
        path
    }
}

/// Percent-decode a URI path component (`%20` → space, …), leaving any malformed
/// escape verbatim. ASCII-oriented but UTF-8-safe for well-formed input.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let (Some(hi), Some(lo)) = (
                (bytes[i + 1] as char).to_digit(16),
                (bytes[i + 2] as char).to_digit(16),
            )
        {
            out.push((hi * 16 + lo) as u8);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Build a `file://` URI from a filesystem path — the inverse of [`uri_to_fs_path`],
/// for the `Location`s a go-to-definition reply carries. Normalizes separators to
/// `/`, ensures a leading `/` (so a Windows `C:\dir` becomes `file:///C:/dir`), and
/// percent-encodes path bytes that are not URI path characters (spaces, etc.).
/// Returns `None` if the result still does not parse, so a stray path is skipped
/// rather than crashing the read job.
fn path_to_uri(path: &Path) -> Option<Uri> {
    let mut s = path.display().to_string().replace('\\', "/");
    if !s.starts_with('/') {
        s.insert(0, '/');
    }
    format!("file://{}", percent_encode_path(&s)).parse().ok()
}

/// Percent-encode a filesystem path for use in a `file://` URI, leaving the path
/// structure (`/`), a Windows drive colon (`:`), and the URI-unreserved set
/// (`A–Z a–z 0–9 - . _ ~`) intact and escaping everything else (e.g. a space →
/// `%20`). The dual of [`percent_decode`].
fn percent_encode_path(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for &b in s.as_bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/' | b':') {
            out.push(b as char);
        } else {
            out.push('%');
            out.push(
                char::from_digit((b >> 4) as u32, 16)
                    .unwrap()
                    .to_ascii_uppercase(),
            );
            out.push(
                char::from_digit((b & 0xf) as u32, 16)
                    .unwrap()
                    .to_ascii_uppercase(),
            );
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Small helpers (unchanged from the single-threaded MVP).
// ---------------------------------------------------------------------------

/// Send a `publishDiagnostics` notification.
fn send_diagnostics(
    connection: &Connection,
    uri: Uri,
    diagnostics: Vec<Diagnostic>,
    version: Option<i32>,
) {
    let params = PublishDiagnosticsParams {
        uri,
        diagnostics,
        version,
    };
    let not = Notification::new(PublishDiagnostics::METHOD.to_owned(), params);
    let _ = connection.sender.send(Message::Notification(not));
}

/// Reply to an unhandled request with a method-not-found error.
fn respond_unhandled(connection: &Connection, req: Request) {
    let resp = Response::new_err(
        req.id,
        ErrorCode::MethodNotFound as i32,
        format!("unhandled request: {}", req.method),
    );
    let _ = connection.sender.send(Message::Response(resp));
}

/// Map a linter [`Severity`] onto the LSP severity. Parse diagnostics bypass
/// this (always `ERROR`); lint rules carry their own severity.
fn severity_to_lsp(severity: Severity) -> DiagnosticSeverity {
    match severity {
        Severity::Error => DiagnosticSeverity::ERROR,
        Severity::Warning => DiagnosticSeverity::WARNING,
        Severity::Info => DiagnosticSeverity::INFORMATION,
        Severity::Hint => DiagnosticSeverity::HINT,
    }
}

/// Convert a byte range into an LSP range via the (UTF-16-aware) [`LineIndex`].
fn byte_range_to_lsp(idx: &LineIndex, text: &str, start: usize, end: usize) -> Range {
    let (sl, sc) = idx.utf16_position(text, start);
    let (el, ec) = idx.utf16_position(text, end);
    Range {
        start: Position::new(sl, sc),
        end: Position::new(el, ec),
    }
}

/// Expand a selection to whole top-level-block boundaries: the cover of every
/// `ROOT` child *node* overlapping `sel`. This is range formatting's safe zone — a
/// partial selection always pulls in the whole structural units it touches, so the
/// formatter never lays out a fragment of a block. `root.children()` yields only
/// nodes (the top-level blocks), so inter-block trivia is naturally skipped.
/// Returns `None` when the selection touches no block (e.g. a cursor in blank space
/// between blocks), meaning there is nothing to format.
fn expand_to_top_level_blocks(root: &SyntaxNode, sel: TextRange) -> Option<TextRange> {
    let mut acc: Option<TextRange> = None;
    for child in root.children() {
        let r = child.text_range();
        // A cursor (empty selection) hits the block whose range contains it
        // (touch-inclusive, so a cursor at a block edge still selects it); a
        // non-empty selection hits any block it genuinely overlaps.
        let hit = if sel.is_empty() {
            r.contains_inclusive(sel.start())
        } else {
            sel.start() < r.end() && r.start() < sel.end()
        };
        if hit {
            acc = Some(acc.map_or(r, |a| a.cover(r)));
        }
    }
    acc
}

/// Diff the formatted `fragment` against the original `text[block_range]` slice and
/// emit one [`TextEdit`] per changed line hunk, mapped back into document
/// coordinates. A line-level LCS keeps the edits minimal (better editor
/// undo/cursor behavior than one wholesale block replacement). For a pathologically
/// large block the `O(n*m)` table is skipped in favor of a single replace.
fn diff_to_edits(
    idx: &LineIndex,
    text: &str,
    block_range: TextRange,
    fragment: &str,
) -> Vec<TextEdit> {
    let base = usize::from(block_range.start());
    let end = usize::from(block_range.end());
    let original = &text[base..end];

    // Lines keep their trailing `\n` (`split_inclusive`), so equality compares whole
    // lines and the byte offsets stay exact.
    let a: Vec<&str> = original.split_inclusive('\n').collect();
    let b: Vec<&str> = fragment.split_inclusive('\n').collect();
    let (n, m) = (a.len(), b.len());

    // Safety valve: cap the LCS table so a huge block cannot blow up; fall back to
    // one wholesale replace of the block range.
    if n.saturating_mul(m) > 4_000_000 {
        return vec![TextEdit {
            range: byte_range_to_lsp(idx, text, base, end),
            new_text: fragment.to_owned(),
        }];
    }

    // lcs[i][j] = length of the longest common subsequence of a[i..] and b[j..].
    let mut lcs = vec![vec![0u32; m + 1]; n + 1];
    for i in (0..n).rev() {
        for j in (0..m).rev() {
            lcs[i][j] = if a[i] == b[j] {
                lcs[i + 1][j + 1] + 1
            } else {
                lcs[i + 1][j].max(lcs[i][j + 1])
            };
        }
    }

    // Walk the table, coalescing each run of deletes/inserts into one replace edit.
    let mut edits = Vec::new();
    let (mut i, mut j) = (0usize, 0usize);
    let mut a_off = base; // byte offset of a[i] within `text`
    let mut del_start = base;
    let mut del_end = base;
    let mut ins = String::new();
    let mut in_hunk = false;
    while i < n || j < m {
        if i < n && j < m && a[i] == b[j] {
            if in_hunk {
                edits.push(TextEdit {
                    range: byte_range_to_lsp(idx, text, del_start, del_end),
                    new_text: std::mem::take(&mut ins),
                });
                in_hunk = false;
            }
            a_off += a[i].len();
            i += 1;
            j += 1;
        } else if j == m || (i < n && lcs[i + 1][j] >= lcs[i][j + 1]) {
            // delete a[i]
            if !in_hunk {
                del_start = a_off;
                in_hunk = true;
            }
            a_off += a[i].len();
            del_end = a_off;
            i += 1;
        } else {
            // insert b[j]
            if !in_hunk {
                del_start = a_off;
                del_end = a_off;
                in_hunk = true;
            }
            ins.push_str(b[j]);
            j += 1;
        }
    }
    if in_hunk {
        edits.push(TextEdit {
            range: byte_range_to_lsp(idx, text, del_start, del_end),
            new_text: ins,
        });
    }
    edits
}

#[cfg(test)]
mod tests {
    use super::*;

    fn uri(s: &str) -> Uri {
        s.parse().unwrap()
    }

    #[test]
    fn uri_to_fs_path_handles_unix_and_windows() {
        // Unix: the leading slash is the filesystem root and must be kept.
        assert_eq!(
            uri_to_fs_path(&uri("file:///tmp/dir/main.tex")),
            Some(PathBuf::from("/tmp/dir/main.tex"))
        );
        // Windows: the leading slash before the drive letter is URI syntax only.
        assert_eq!(
            uri_to_fs_path(&uri("file:///C:/Users/me/main.tex")),
            Some(PathBuf::from("C:/Users/me/main.tex"))
        );
        // Non-file scheme (unsaved buffer) → no path.
        assert_eq!(uri_to_fs_path(&uri("untitled:Untitled-1")), None);
    }

    #[test]
    fn strip_drive_letter_slash_only_strips_real_drives() {
        assert_eq!(strip_drive_letter_slash("/C:/dir"), "C:/dir");
        assert_eq!(strip_drive_letter_slash("/c:"), "c:");
        assert_eq!(strip_drive_letter_slash("/C:\\dir"), "C:\\dir");
        // Not a drive letter: leave untouched.
        assert_eq!(strip_drive_letter_slash("/tmp/dir"), "/tmp/dir");
        assert_eq!(strip_drive_letter_slash("/ab:/dir"), "/ab:/dir");
    }

    #[test]
    fn decide_starts_when_idle() {
        let mut pending = HashMap::new();
        pending.insert(uri("file:///a.tex"), 1);
        assert_eq!(
            decide(None, &pending),
            DispatchAction::Start(uri("file:///a.tex"))
        );
    }

    #[test]
    fn decide_waits_when_idle_and_empty() {
        assert_eq!(decide(None, &HashMap::new()), DispatchAction::Wait);
    }

    #[test]
    fn decide_supersedes_only_on_newer_same_uri() {
        let a = uri("file:///a.tex");
        let mut pending = HashMap::new();
        pending.insert(a.clone(), 5);
        assert_eq!(
            decide(Some((&a, 3)), &pending),
            DispatchAction::SupersedeAndStart(a.clone())
        );
        // Same version (not strictly newer): wait.
        assert_eq!(decide(Some((&a, 5)), &pending), DispatchAction::Wait);
    }

    #[test]
    fn decide_never_cancels_inflight_for_a_different_uri() {
        let a = uri("file:///a.tex");
        let b = uri("file:///b.tex");
        let mut pending = HashMap::new();
        pending.insert(b, 9);
        // A's analyze is in flight; only B is queued → wait, never cancel A.
        assert_eq!(decide(Some((&a, 1)), &pending), DispatchAction::Wait);
    }

    #[test]
    fn apply_content_changes_splices_ranged_edit() {
        // Replace "world" with "there" in "hello world".
        let mut text = "hello world\n".to_owned();
        let change = TextDocumentContentChangeEvent {
            range: Some(Range {
                start: Position::new(0, 6),
                end: Position::new(0, 11),
            }),
            range_length: None,
            text: "there".to_owned(),
        };
        apply_content_changes(&mut text, vec![change]);
        assert_eq!(text, "hello there\n");
    }

    #[test]
    fn apply_content_changes_full_replace_on_no_range() {
        let mut text = "old".to_owned();
        let change = TextDocumentContentChangeEvent {
            range: None,
            range_length: None,
            text: "new".to_owned(),
        };
        apply_content_changes(&mut text, vec![change]);
        assert_eq!(text, "new");
    }

    #[test]
    fn editor_settings_namespaced_and_bare() {
        let bare = serde_json::json!({ "lineWidth": 100, "indentWidth": 4 });
        let s = EditorSettings::from_client_value(&bare);
        assert_eq!(s.line_width, Some(100));
        assert_eq!(s.indent_width, Some(4));
        let style = s.to_format_style();
        assert_eq!(style.line_width, 100);
        assert_eq!(style.indent_width, 4);

        let namespaced = serde_json::json!({ "badness": { "lineWidth": 72 } });
        let s = EditorSettings::from_client_value(&namespaced);
        assert_eq!(s.line_width, Some(72));
        assert_eq!(s.indent_width, None);
    }

    /// A bare [`GlobalState`] with the given editor settings and an empty cache, for
    /// exercising [`GlobalState::resolve_settings`].
    fn state_with_editor(editor: EditorSettings) -> GlobalState {
        GlobalState {
            documents: HashMap::new(),
            editor_settings: editor,
            config_cache: HashMap::new(),
            supports_pull_diagnostics: false,
            supports_diagnostic_refresh: false,
            supports_dynamic_watchers: false,
            next_request_id: 1,
        }
    }

    /// A `file://` URI for `main.tex` inside `dir`.
    fn file_uri_in(dir: &Path) -> Uri {
        // Go through `path_to_uri` so the URI is well-formed on Windows too,
        // where `dir.display()` yields `C:\…` (backslashes, no leading slash).
        path_to_uri(&dir.join("main.tex")).expect("file uri")
    }

    #[test]
    fn resolve_settings_prefers_file_config_over_editor() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("badness.toml"),
            "[format]\nline-width = 100\nindent-width = 8\n",
        )
        .expect("write config");
        let mut state = state_with_editor(EditorSettings {
            line_width: Some(40),
            indent_width: Some(3),
        });
        let resolved = state.resolve_settings(&file_uri_in(dir.path()));
        assert!(resolved.config_present);
        assert_eq!(resolved.style.line_width, 100);
        assert_eq!(resolved.style.indent_width, 8);
    }

    #[test]
    fn resolve_settings_falls_back_to_editor_without_config() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut state = state_with_editor(EditorSettings {
            line_width: Some(40),
            indent_width: None,
        });
        let resolved = state.resolve_settings(&file_uri_in(dir.path()));
        assert!(!resolved.config_present);
        assert_eq!(resolved.style.line_width, 40);
        // Unset editor knob keeps the built-in default.
        assert_eq!(
            resolved.style.indent_width,
            FormatStyle::default().indent_width
        );
        assert!(resolved.wrap_override.is_none());
    }

    #[test]
    fn resolve_settings_wrap_override_from_config() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("badness.toml"),
            "[format]\nwrap = \"preserve\"\n",
        )
        .expect("write config");
        let mut state = state_with_editor(EditorSettings::default());
        let resolved = state.resolve_settings(&file_uri_in(dir.path()));
        assert_eq!(resolved.wrap_override, Some(WrapMode::Preserve));
    }

    #[test]
    fn resolve_settings_applies_lint_selection() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("badness.toml"),
            "[lint]\nselect = [\"duplicate-label\"]\n",
        )
        .expect("write config");
        let mut state = state_with_editor(EditorSettings::default());
        let rules = state
            .resolve_settings(&file_uri_in(dir.path()))
            .rule_selection();
        assert!(rules.is_active("duplicate-label"));
        assert!(!rules.is_active("deprecated-command"));
        // Parse diagnostics are never filtered out.
        assert!(rules.is_active("parse"));
    }

    #[test]
    fn resolve_settings_builds_exclude_filter_for_sibling_discovery() {
        // The resolved exclude filter is what `Worker::seed_dir` feeds to
        // `collect_lint_files`, so verify it prunes a configured directory while
        // keeping a normal sibling — the whole point of plumbing config into the
        // worker.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("badness.toml"), "exclude = [\"vendor/\"]\n")
            .expect("write config");
        std::fs::write(dir.path().join("main.tex"), "").expect("write main");
        std::fs::create_dir(dir.path().join("vendor")).expect("mkdir vendor");
        std::fs::write(dir.path().join("vendor").join("lib.tex"), "").expect("write lib");

        let mut state = state_with_editor(EditorSettings::default());
        let resolved = state.resolve_settings(&file_uri_in(dir.path()));

        let files =
            collect_lint_files(&[dir.path().to_path_buf()], &resolved.exclude).expect("collect");
        let names: Vec<_> = files
            .iter()
            .map(|(p, _)| p.strip_prefix(dir.path()).unwrap_or(p).to_path_buf())
            .collect();
        assert!(names.contains(&PathBuf::from("main.tex")));
        assert!(
            !names.iter().any(|p| p.starts_with("vendor")),
            "excluded sibling should be pruned, got {names:?}"
        );
    }

    #[test]
    fn resolve_settings_without_config_excludes_nothing() {
        // The editor-fallback path keeps the historical unfiltered walk: a
        // `vendor/` sibling is still discovered when no `badness.toml` governs.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("main.tex"), "").expect("write main");
        std::fs::create_dir(dir.path().join("vendor")).expect("mkdir vendor");
        std::fs::write(dir.path().join("vendor").join("lib.tex"), "").expect("write lib");

        let mut state = state_with_editor(EditorSettings::default());
        let resolved = state.resolve_settings(&file_uri_in(dir.path()));
        assert!(!resolved.config_present);

        let files =
            collect_lint_files(&[dir.path().to_path_buf()], &resolved.exclude).expect("collect");
        let names: Vec<_> = files
            .iter()
            .map(|(p, _)| p.strip_prefix(dir.path()).unwrap_or(p).to_path_buf())
            .collect();
        assert!(names.contains(&PathBuf::from("main.tex")));
        assert!(names.contains(&PathBuf::from("vendor/lib.tex")));
    }

    #[test]
    fn resolve_settings_caches_by_anchor_until_cleared() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut state = state_with_editor(EditorSettings {
            line_width: Some(40),
            indent_width: None,
        });
        let uri = file_uri_in(dir.path());
        assert_eq!(state.resolve_settings(&uri).style.line_width, 40);
        // A later editor change is masked by the cache until it is cleared (the
        // `didChangeConfiguration` handler clears it).
        state.editor_settings.line_width = Some(72);
        assert_eq!(state.resolve_settings(&uri).style.line_width, 40);
        state.config_cache.clear();
        assert_eq!(state.resolve_settings(&uri).style.line_width, 72);
    }

    #[test]
    fn resolve_settings_untitled_uses_editor_fallback_uncached() {
        let mut state = state_with_editor(EditorSettings {
            line_width: Some(55),
            indent_width: None,
        });
        let resolved = state.resolve_settings(&uri("untitled:Untitled-1"));
        assert!(!resolved.config_present);
        assert_eq!(resolved.style.line_width, 55);
        // A non-file buffer never joins the anchor-dir cache.
        assert!(state.config_cache.is_empty());
    }

    /// The byte offset of the first occurrence of `needle` in `text`.
    fn offset_of(text: &str, needle: &str) -> usize {
        text.find(needle).expect("needle present")
    }

    #[test]
    fn reference_under_cursor_finds_ref_and_cite() {
        let text = "\\label{a}\n\\ref{a}\n\\cite{k}\n";
        let model = SemanticModel::build(&SyntaxNode::new_root(parse(text).green));

        // Inside `\ref{a}` → the label key `a`.
        let at_ref = offset_of(text, "\\ref{a}") + 5; // on the `a`
        match reference_under_cursor(&model, at_ref) {
            Some(CursorTarget::Labels(names)) => assert_eq!(names, vec![SmolStr::new("a")]),
            other => panic!("expected a label target, got {other:?}"),
        }

        // Inside `\cite{k}` → the cite key `k`.
        let at_cite = offset_of(text, "\\cite{k}") + 6; // on the `k`
        match reference_under_cursor(&model, at_cite) {
            Some(CursorTarget::Citations(names)) => assert_eq!(names, vec![SmolStr::new("k")]),
            other => panic!("expected a citation target, got {other:?}"),
        }

        // On the `\label` definition (not a reference) → nothing to jump *from*.
        let at_label = offset_of(text, "\\label{a}") + 1;
        assert!(reference_under_cursor(&model, at_label).is_none());
    }

    #[test]
    fn reference_under_cursor_splits_cref_list() {
        let text = "\\cref{a,b,c}\n";
        let model = SemanticModel::build(&SyntaxNode::new_root(parse(text).green));
        // The whole command shares one range, so every key is returned (per-key
        // sub-ranges are deferred).
        let at = offset_of(text, "\\cref") + 2;
        match reference_under_cursor(&model, at) {
            Some(CursorTarget::Labels(names)) => assert_eq!(
                names,
                vec![SmolStr::new("a"), SmolStr::new("b"), SmolStr::new("c")]
            ),
            other => panic!("expected a label target, got {other:?}"),
        }
    }

    #[test]
    fn path_to_uri_round_trips_through_uri_to_fs_path() {
        let p = PathBuf::from("/tmp/my dir/main.tex");
        let u = path_to_uri(&p).expect("a file path forms a URI");
        // The space is percent-encoded in the URI text…
        assert!(u.as_str().contains("%20"), "got {}", u.as_str());
        // …and decodes back to the original filesystem path.
        assert_eq!(uri_to_fs_path(&u), Some(p));
    }
}