mull 0.16.0

Organize your knowledge.
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
use crate::{
    analyzer::analyze,
    cancellation::{CancellationFlag, Outcome},
    error::{Error, SourceRange},
    parser,
    wiki::{DIRECTORY_LINK_PREFIX, FILE_LINK_PREFIX, Link, TextNode, Wiki},
};
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use std::{
    borrow::Cow,
    collections::HashMap,
    path::Path,
    sync::{Arc, Mutex, atomic::AtomicBool, atomic::Ordering},
    time::Duration,
};
use tokio::task::JoinHandle;
use tower_lsp_server::{
    Client, LanguageServer, LspService, Server,
    jsonrpc::{Error as JsonRpcError, Result},
    ls_types::{
        CompletionItem, CompletionItemKind, CompletionOptions, CompletionParams,
        CompletionResponse, CompletionTextEdit, Diagnostic, DiagnosticSeverity,
        DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
        DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlight,
        DocumentHighlightKind, DocumentHighlightParams, DocumentSymbol, DocumentSymbolParams,
        DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, Hover, HoverContents,
        HoverParams, HoverProviderCapability, InitializeParams, InitializeResult,
        InitializedParams, Location, LocationLink, MarkupContent, MarkupKind, MessageType, OneOf,
        Position, PositionEncodingKind, PrepareRenameResponse, Range, ReferenceParams,
        RenameOptions, RenameParams, ServerCapabilities, ServerInfo, SymbolInformation, SymbolKind,
        TextDocumentPositionParams, TextDocumentSyncCapability, TextDocumentSyncKind,
        TextDocumentSyncOptions, TextEdit, Uri, WorkDoneProgressOptions, WorkspaceEdit,
    },
};

// Wait briefly after edits so filesystem validation does not run on every keystroke.
const CHECK_DELAY: Duration = Duration::from_millis(250);

// This extension command reveals a source range for clickable text links in hover previews.
// Keep this in sync with [group:reveal_range_command].
const REVEAL_RANGE_COMMAND: &str = "mull.revealRange";

// This pairs a scheduled diagnostic task with the flag which stops its filesystem work.
#[derive(Debug)]
struct PendingCheck {
    handle: JoinHandle<()>,
    cancellation: CancellationFlag,
}

impl PendingCheck {
    // Stop the check whether or not it has started. Aborting the task stops it if it has not
    // started checking, and setting its flag stops it if it has already started.
    fn cancel(self) {
        self.cancellation.cancel();
        self.handle.abort();
    }
}

// This state associates the latest editor contents with a pending diagnostic update. The client
// assigns the version, which changes only when the contents do and is reported back with
// diagnostics. The server assigns the generation, which increases every time a snapshot is
// stored, including rechecks of unchanged contents after a save, so it identifies which snapshot
// stale work was computed from.
#[derive(Debug)]
struct OpenDocument {
    contents: String,
    version: i32,
    generation: u64,
    pending_check: Option<PendingCheck>,
}

// This backend checks each open wiki and publishes its errors to the language client.
#[derive(Debug)]
struct Backend {
    client: Client,
    documents: Arc<Mutex<HashMap<Uri, OpenDocument>>>,
    supports_hierarchical_document_symbols: AtomicBool,
}

impl Backend {
    // Construct a backend connected to the editor-side language client.
    fn new(client: Client) -> Self {
        Self {
            client,
            documents: Arc::new(Mutex::new(HashMap::new())),
            supports_hierarchical_document_symbols: AtomicBool::new(false),
        }
    }

    // Replace an editor snapshot and schedule diagnostics for its new generation.
    fn store_and_check_document(&self, uri: Uri, contents: String, version: i32, delay: Duration) {
        // Prepare the resources owned by the diagnostic task.
        let client = self.client.clone();
        let documents = Arc::clone(&self.documents);
        let diagnostic_uri = uri.clone();
        let diagnostic_contents = contents.clone();
        let cancellation = CancellationFlag::default();
        let check_cancellation = cancellation.clone();

        // Cancel the preceding task and assign a distinct generation to this snapshot.
        let mut open_documents = self
            .documents
            .lock()
            .expect("the open-document mutex should not be poisoned");
        let document = open_documents.entry(uri).or_insert_with(|| OpenDocument {
            contents: String::new(),
            version,
            generation: 0,
            pending_check: None,
        });
        if let Some(pending_check) = document.pending_check.take() {
            pending_check.cancel();
        }
        document.contents = contents;
        document.version = version;
        document.generation = document
            .generation
            .checked_add(1)
            .expect("a document generation should fit in a u64");
        let generation = document.generation;

        // Check outside the asynchronous executor and publish only if the snapshot is still
        // current.
        document.pending_check = Some(PendingCheck {
            handle: tokio::spawn(async move {
                if !delay.is_zero() {
                    tokio::time::sleep(delay).await;
                }
                let check_uri = diagnostic_uri.clone();
                let fallback_contents = diagnostic_contents.clone();

                // Publish nothing when a newer snapshot cancelled this check partway through.
                let Some(diagnostics) = tokio::task::spawn_blocking(move || {
                    diagnostics_for_document(&check_uri, &diagnostic_contents, &check_cancellation)
                })
                .await
                .unwrap_or_else(|error| {
                    Some(vec![diagnostic(
                        &fallback_contents,
                        None,
                        format!("Mull was unable to check the wiki: {error}."),
                    )])
                }) else {
                    return;
                };
                if documents
                    .lock()
                    .expect("the open-document mutex should not be poisoned")
                    .get(&diagnostic_uri)
                    .is_some_and(|document| document.generation == generation)
                {
                    client
                        .publish_diagnostics(diagnostic_uri, diagnostics, Some(version))
                        .await;
                }
            }),
            cancellation,
        });
    }

    // Recheck the most recent snapshot immediately after it is saved.
    fn recheck_saved_document(&self, uri: Uri, contents: Option<String>) {
        // Copy the snapshot before scheduling, without retaining the lock across that operation.
        let snapshot = self
            .documents
            .lock()
            .expect("the open-document mutex should not be poisoned")
            .get_mut(&uri)
            .map(|document| {
                if let Some(contents) = contents {
                    document.contents = contents;
                }
                (document.contents.clone(), document.version)
            });
        if let Some((contents, version)) = snapshot {
            self.store_and_check_document(uri, contents, version, Duration::ZERO);
        }
    }

    // Copy the current editor snapshot for a language feature request.
    fn document_contents(&self, uri: &Uri) -> Option<String> {
        self.documents
            .lock()
            .expect("the open-document mutex should not be poisoned")
            .get(uri)
            .map(|document| document.contents.clone())
    }
}

// Respond to protocol requests and notifications for document synchronization, diagnostics, and
// language features.
#[allow(
    clippy::unused_async_trait_impl,
    reason = "Some methods mirror the asynchronous language-server interface without awaiting."
)]
impl LanguageServer for Backend {
    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
        // Remember whether document symbols may carry separate full and selection ranges.
        self.supports_hierarchical_document_symbols.store(
            params
                .capabilities
                .text_document
                .as_ref()
                .and_then(|capabilities| capabilities.document_symbol.as_ref())
                .and_then(|capabilities| capabilities.hierarchical_document_symbol_support)
                .unwrap_or(false),
            Ordering::Relaxed,
        );

        // Advertise the language features implemented by this server.
        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                completion_provider: Some(CompletionOptions {
                    trigger_characters: Some(vec!["[".to_owned()]),
                    ..CompletionOptions::default()
                }),
                definition_provider: Some(OneOf::Left(true)),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                position_encoding: Some(PositionEncodingKind::UTF16),
                references_provider: Some(OneOf::Left(true)),
                document_highlight_provider: Some(OneOf::Left(true)),
                rename_provider: Some(OneOf::Right(RenameOptions {
                    prepare_provider: Some(true),
                    work_done_progress_options: WorkDoneProgressOptions::default(),
                })),
                document_formatting_provider: Some(OneOf::Left(true)),
                document_symbol_provider: Some(OneOf::Left(true)),
                text_document_sync: Some(TextDocumentSyncCapability::Options(
                    TextDocumentSyncOptions {
                        open_close: Some(true),
                        change: Some(TextDocumentSyncKind::FULL),
                        save: Some(true.into()),
                        ..TextDocumentSyncOptions::default()
                    },
                )),
                ..ServerCapabilities::default()
            },
            server_info: Some(ServerInfo {
                name: env!("CARGO_PKG_NAME").to_owned(),
                version: Some(env!("CARGO_PKG_VERSION").to_owned()),
            }),
            ..InitializeResult::default()
        })
    }

    async fn initialized(&self, _params: InitializedParams) {
        // Confirm that the server completed its initialization handshake.
        self.client
            .log_message(
                MessageType::INFO,
                format!(
                    "Mull {} language server initialized.",
                    env!("CARGO_PKG_VERSION"),
                ),
            )
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        // Confirm that the server began its shutdown handshake.
        self.client
            .log_message(MessageType::INFO, "Mull language server shutting down.")
            .await;
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        // Track the newly opened document and check it without waiting for further edits.
        self.store_and_check_document(
            params.text_document.uri,
            params.text_document.text,
            params.text_document.version,
            Duration::ZERO,
        );
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        // Full synchronization places the complete latest snapshot in the final change.
        if let Some(change) = params.content_changes.into_iter().next_back() {
            self.store_and_check_document(
                params.text_document.uri,
                change.text,
                params.text_document.version,
                CHECK_DELAY,
            );
        }
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        // Recheck the saved document immediately, adopting any contents the client included.
        self.recheck_saved_document(params.text_document.uri, params.text);
    }

    async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
        // Complete text links against the latest synchronized editor snapshot.
        let Some(contents) =
            self.document_contents(&params.text_document_position.text_document.uri)
        else {
            return Ok(None);
        };
        Ok(completion_for_document(
            &params.text_document_position.text_document.uri,
            &contents,
            params.text_document_position.position,
        )
        .map(CompletionResponse::Array))
    }

    async fn goto_definition(
        &self,
        params: GotoDefinitionParams,
    ) -> Result<Option<GotoDefinitionResponse>> {
        // Resolve the title or text link against the latest synchronized editor snapshot.
        let Some(contents) =
            self.document_contents(&params.text_document_position_params.text_document.uri)
        else {
            return Ok(None);
        };
        Ok(goto_definition_for_document(
            &params.text_document_position_params.text_document.uri,
            &contents,
            params.text_document_position_params.position,
        ))
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        // Preview the text-link target from the latest synchronized editor snapshot.
        let Some(contents) =
            self.document_contents(&params.text_document_position_params.text_document.uri)
        else {
            return Ok(None);
        };
        Ok(hover_for_document(
            &params.text_document_position_params.text_document.uri,
            &contents,
            params.text_document_position_params.position,
        ))
    }

    async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
        // Find references to the node under the cursor in the latest synchronized snapshot.
        let Some(contents) =
            self.document_contents(&params.text_document_position.text_document.uri)
        else {
            return Ok(None);
        };
        Ok(references_for_document(
            &params.text_document_position.text_document.uri,
            &contents,
            params.text_document_position.position,
            params.context.include_declaration,
        ))
    }

    async fn document_highlight(
        &self,
        params: DocumentHighlightParams,
    ) -> Result<Option<Vec<DocumentHighlight>>> {
        // Highlight the wiki occurrences related to the item under the cursor.
        let Some(contents) =
            self.document_contents(&params.text_document_position_params.text_document.uri)
        else {
            return Ok(None);
        };
        Ok(document_highlight_for_document(
            &params.text_document_position_params.text_document.uri,
            &contents,
            params.text_document_position_params.position,
        ))
    }

    async fn prepare_rename(
        &self,
        params: TextDocumentPositionParams,
    ) -> Result<Option<PrepareRenameResponse>> {
        // Identify the node occurrence that the editor should select for rename.
        let Some(contents) = self.document_contents(&params.text_document.uri) else {
            return Ok(None);
        };
        Ok(prepare_rename_for_document(
            &params.text_document.uri,
            &contents,
            params.position,
        ))
    }

    async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
        // Rename a node and all of its text-link occurrences in the latest snapshot.
        let Some(contents) =
            self.document_contents(&params.text_document_position.text_document.uri)
        else {
            return Ok(None);
        };
        rename_for_document(
            &params.text_document_position.text_document.uri,
            &contents,
            params.text_document_position.position,
            &params.new_name,
        )
        .map_err(JsonRpcError::invalid_params)
    }

    async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
        // Render the latest synchronized editor snapshot, leaving unparsable contents unchanged.
        let Some(contents) = self.document_contents(&params.text_document.uri) else {
            return Ok(None);
        };
        Ok(formatting_for_document(
            &params.text_document.uri,
            &contents,
        ))
    }

    async fn document_symbol(
        &self,
        params: DocumentSymbolParams,
    ) -> Result<Option<DocumentSymbolResponse>> {
        // Describe the nodes in the latest synchronized editor snapshot.
        let Some(contents) = self.document_contents(&params.text_document.uri) else {
            return Ok(None);
        };
        Ok(document_symbol_for_document(
            &params.text_document.uri,
            &contents,
            self.supports_hierarchical_document_symbols
                .load(Ordering::Relaxed),
        ))
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        // Cancel outstanding work before asking the client to clear this document's diagnostics.
        let document = self
            .documents
            .lock()
            .expect("the open-document mutex should not be poisoned")
            .remove(&params.text_document.uri);
        if let Some(pending_check) = document.and_then(|document| document.pending_check) {
            pending_check.cancel();
        }
        self.client
            .publish_diagnostics(params.text_document.uri, Vec::new(), None)
            .await;
    }
}

// Analyze an editor snapshot without checking its formatting.
fn diagnostics_for_document(
    uri: &Uri,
    source_contents: &str,
    cancellation: &CancellationFlag,
) -> Option<Vec<Diagnostic>> {
    // Report nothing for a cancelled check, whose errors may cover only part of the wiki.
    let Outcome::Completed(result) =
        analyze(local_path(uri).as_deref(), source_contents, cancellation)
    else {
        return None;
    };

    // Preserve independent Mull errors as independent editor diagnostics.
    Some(result.map_or_else(
        |errors| {
            errors
                .iter()
                .map(|error| diagnostic_from_error(source_contents, error))
                .collect()
        },
        |_wiki| Vec::new(),
    ))
}

// Complete the text-link target at an editor position with every node title.
fn completion_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
) -> Option<Vec<CompletionItem>> {
    // Parse either the original source or a temporary source with the active link closed.
    let (wiki, replacement_source_range) = completion_context(
        local_path(uri).as_deref(),
        source_contents,
        byte_offset(source_contents, cursor)?,
    )?;

    // Present node titles deterministically and replace the whole link, including its delimiters,
    // so the cursor ends up after the closing `]`.
    let replacement_range = lsp_range(source_contents, replacement_source_range);
    let mut titles = wiki.text_nodes.keys().collect::<Vec<_>>();
    titles.sort();
    Some(
        titles
            .into_iter()
            .map(|title| {
                let escaped_title = escape_text_link_title(title);
                CompletionItem {
                    label: title.clone(),
                    kind: Some(CompletionItemKind::REFERENCE),
                    filter_text: Some(format!("[{escaped_title}")),
                    text_edit: Some(CompletionTextEdit::Edit(TextEdit::new(
                        replacement_range,
                        format!("[{escaped_title}]"),
                    ))),
                    ..CompletionItem::default()
                }
            })
            .collect(),
    )
}

// Locate the node declared or linked at an editor position.
fn goto_definition_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
) -> Option<GotoDefinitionResponse> {
    // Parse only the wiki syntax because navigation does not require filesystem validation.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let (node, origin_source_range) = node_at(
        &wiki,
        source_contents,
        byte_offset(source_contents, cursor)?,
        LinkExtent::Whole,
    )?;

    // Identify the complete source link or title and the destination node while selecting its title
    // on arrival.
    Some(GotoDefinitionResponse::Link(vec![LocationLink {
        origin_selection_range: Some(lsp_range(source_contents, origin_source_range)),
        target_uri: uri.clone(),
        target_range: lsp_range(source_contents, node.source_range),
        target_selection_range: lsp_range(source_contents, node.title_source_range),
    }]))
}

// Preview the destination of a text link at an editor position.
fn hover_for_document(uri: &Uri, source_contents: &str, cursor: Position) -> Option<Hover> {
    // Parse only the wiki syntax because hovering does not require filesystem validation.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let (node, source_range) = node_at(
        &wiki,
        source_contents,
        byte_offset(source_contents, cursor)?,
        LinkExtent::Whole,
    )?;

    // Render the node as Markdown with commands that navigate its resolvable text links.
    Some(Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: node.to_markdown(|title| {
                reveal_range_command_url(
                    uri,
                    source_contents,
                    wiki.text_nodes.get(title)?.title_source_range,
                )
            }),
        }),
        range: Some(lsp_range(source_contents, source_range)),
    })
}

// Locate every text link to the node at an editor position.
fn references_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
    include_declaration: bool,
) -> Option<Vec<Location>> {
    // Parse only the wiki syntax because finding references does not require validation.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let (node, _source_range) = node_at(
        &wiki,
        source_contents,
        byte_offset(source_contents, cursor)?,
        LinkExtent::Whole,
    )?;

    // Include the declaration only when requested, then restore source order.
    let mut source_ranges = text_link_source_ranges(&wiki, &node.title);
    if include_declaration {
        source_ranges.push(node.title_source_range);
    }
    source_ranges.sort_by_key(|source_range| (source_range.start, source_range.end));

    // Return every occurrence in source order within the current wiki.
    Some(
        source_ranges
            .into_iter()
            .map(|source_range| {
                Location::new(uri.clone(), lsp_range(source_contents, source_range))
            })
            .collect(),
    )
}

// Highlight related node or filesystem-link occurrences at an editor position.
fn document_highlight_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
) -> Option<Vec<DocumentHighlight>> {
    // Parse only the wiki syntax because document highlights do not require validation.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let byte_offset = byte_offset(source_contents, cursor)?;

    // Distinguish a text-node declaration from its references.
    let mut highlights = if let Some((node, _source_range)) =
        node_at(&wiki, source_contents, byte_offset, LinkExtent::Whole)
    {
        let mut highlights = text_link_source_ranges(&wiki, &node.title)
            .into_iter()
            .map(|source_range| (source_range, DocumentHighlightKind::READ))
            .collect::<Vec<_>>();
        highlights.push((node.title_source_range, DocumentHighlightKind::WRITE));
        highlights
    } else {
        // Filesystem links have no declaration in the wiki, so every matching link is a reference.
        // A text link reaches this branch only when its target does not exist, so it has nothing
        // to highlight.
        let link = link_at(&wiki, byte_offset).filter(|link| !matches!(link, Link::Text { .. }))?;
        filesystem_link_source_ranges(&wiki, link)
            .into_iter()
            .map(|source_range| (source_range, DocumentHighlightKind::READ))
            .collect()
    };

    // Return every matching source occurrence in wiki order.
    highlights.sort_by_key(|(source_range, _kind)| (source_range.start, source_range.end));
    Some(
        highlights
            .into_iter()
            .map(|(source_range, kind)| DocumentHighlight {
                range: lsp_range(source_contents, source_range),
                kind: Some(kind),
            })
            .collect(),
    )
}

// Identify the source occurrence that should be selected before renaming a node.
fn prepare_rename_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
) -> Option<PrepareRenameResponse> {
    // Resolve either a title declaration or text link in a parseable editor snapshot.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let (node, source_range) = node_at(
        &wiki,
        source_contents,
        byte_offset(source_contents, cursor)?,
        LinkExtent::Target,
    )?;

    // Select only the title text and seed the rename prompt with its decoded value.
    Some(PrepareRenameResponse::RangeWithPlaceholder {
        range: lsp_range(source_contents, source_range),
        placeholder: node.title.clone(),
    })
}

// Rename one text node and every text link that targets it.
fn rename_for_document(
    uri: &Uri,
    source_contents: &str,
    cursor: Position,
    new_name: &str,
) -> std::result::Result<Option<WorkspaceEdit>, String> {
    // Resolve the requested node without requiring the wiki to pass semantic validation.
    let Some(wiki) = parser::parse(local_path(uri).as_deref(), source_contents).ok() else {
        return Ok(None);
    };
    let Some(byte_offset) = byte_offset(source_contents, cursor) else {
        return Ok(None);
    };
    let Some((node, _source_range)) =
        node_at(&wiki, source_contents, byte_offset, LinkExtent::Target)
    else {
        return Ok(None);
    };

    // Normalize surrounding whitespace, then reject titles that the parser would not accept: those
    // that span multiple lines, are empty, start with a filesystem-link prefix, or already exist.
    if new_name
        .chars()
        .any(|character| matches!(character, '\r' | '\n'))
    {
        return Err("A node title cannot contain a line break.".to_owned());
    }
    let new_title = new_name.trim();
    if new_title.is_empty() {
        return Err("A node title cannot be empty.".to_owned());
    }
    if new_title.starts_with(FILE_LINK_PREFIX) || new_title.starts_with(DIRECTORY_LINK_PREFIX) {
        return Err(format!(
            "A node title cannot start with `{FILE_LINK_PREFIX}` or `{DIRECTORY_LINK_PREFIX}`.",
        ));
    }
    if new_title != node.title && wiki.text_nodes.contains_key(new_title) {
        return Err(format!("Node `{new_title}` already exists."));
    }

    // Replace the declaration literally and encode the title inside every matching text link.
    let mut edits = vec![(node.title_source_range, new_title.to_owned())];
    for link in wiki.text_nodes.values().flat_map(|node| &node.links) {
        if let Link::Text {
            title,
            source_range,
        } = link
            && title == &node.title
            && let Some(target_source_range) =
                text_link_target_source_range(source_contents, *source_range)
        {
            edits.push((target_source_range, escape_text_link_title(new_title)));
        }
    }
    edits.sort_by_key(|(source_range, _new_text)| (source_range.start, source_range.end));

    // Return one non-overlapping edit for each occurrence in the current document.
    Ok(Some(WorkspaceEdit {
        changes: Some(HashMap::from([(
            uri.clone(),
            edits
                .into_iter()
                .map(|(source_range, new_text)| {
                    TextEdit::new(lsp_range(source_contents, source_range), new_text)
                })
                .collect(),
        )])),
        ..WorkspaceEdit::default()
    }))
}

// Produce a whole-document formatting edit for any wiki that parses, even if it is invalid.
fn formatting_for_document(uri: &Uri, source_contents: &str) -> Option<Vec<TextEdit>> {
    // Render the parsed wiki without reporting syntax errors, which diagnostics already cover.
    let rendered_wiki = parser::parse(local_path(uri).as_deref(), source_contents)
        .ok()?
        .to_string();

    // A successful request returns either one whole-document edit or an empty edit list.
    if source_contents == rendered_wiki {
        Some(Vec::new())
    } else {
        Some(vec![TextEdit::new(
            Range::new(
                Position::new(0, 0),
                lsp_position(source_contents, source_contents.len()),
            ),
            rendered_wiki,
        )])
    }
}

// Describe every parsed text node for editor outlines and document-symbol navigation.
#[allow(
    deprecated,
    reason = "The protocol's DocumentSymbol type retains a required legacy field."
)]
fn document_symbol_for_document(
    uri: &Uri,
    source_contents: &str,
    supports_hierarchy: bool,
) -> Option<DocumentSymbolResponse> {
    // Parse syntax without semantic validation so structurally valid nodes remain navigable.
    let wiki = parser::parse(local_path(uri).as_deref(), source_contents).ok()?;
    let mut nodes = wiki.text_nodes.values().collect::<Vec<_>>();
    nodes.sort_by_key(|node| node.source_range.start);

    // Use separate node and title ranges when the client supports hierarchical symbols, and locate
    // each flat symbol at its title otherwise.
    Some(if supports_hierarchy {
        DocumentSymbolResponse::Nested(
            nodes
                .into_iter()
                .map(|node| DocumentSymbol {
                    name: node.title.clone(),
                    detail: None,
                    kind: SymbolKind::OBJECT,
                    tags: None,
                    deprecated: None,
                    range: lsp_range(source_contents, node.source_range),
                    selection_range: lsp_range(source_contents, node.title_source_range),
                    children: None,
                })
                .collect(),
        )
    } else {
        DocumentSymbolResponse::Flat(
            nodes
                .into_iter()
                .map(|node| SymbolInformation {
                    name: node.title.clone(),
                    kind: SymbolKind::OBJECT,
                    tags: None,
                    deprecated: None,
                    location: Location::new(
                        uri.clone(),
                        lsp_range(source_contents, node.title_source_range),
                    ),
                    container_name: None,
                })
                .collect(),
        )
    })
}

// Parse enough of an active text link to identify the source range a completion should replace.
fn completion_context(
    source_path: Option<&Path>,
    source_contents: &str,
    byte_offset: usize,
) -> Option<(Wiki, SourceRange)> {
    // Prefer the unchanged source when the active link is already closed.
    if let Ok(wiki) = parser::parse(source_path, source_contents)
        && let Some(Link::Text { source_range, .. }) = link_at(&wiki, byte_offset)
    {
        let source_range = *source_range;
        return Some((wiki, source_range));
    }

    // Close a link at the cursor temporarily so completion works while it is being authored.
    let mut completed_source = source_contents.to_owned();
    completed_source.insert(byte_offset, ']');
    let wiki = parser::parse(source_path, &completed_source).ok()?;
    let Some(Link::Text { source_range, .. }) = link_at(&wiki, byte_offset) else {
        return None;
    };

    // Map the link's end back into the original source, which lacks the temporary delimiter.
    let source_range = SourceRange {
        start: source_range.start,
        end: source_range.end - ']'.len_utf8(),
    };
    Some((wiki, source_range))
}

// This describes which part of a resolved text link a caller considers relevant.
#[derive(Clone, Copy)]
enum LinkExtent {
    // The complete link, including its square-bracket delimiters.
    Whole,

    // The link's inner text, which excludes its delimiters.
    Target,
}

// Resolve the node denoted by a declaration or text link at a source offset.
fn node_at<'a>(
    wiki: &'a Wiki,
    source_contents: &str,
    byte_offset: usize,
    link_extent: LinkExtent,
) -> Option<(&'a TextNode, SourceRange)> {
    // Prefer a declaration, whose title is the only range it can contribute.
    if let Some(node) = wiki.text_nodes.values().find(|node| {
        node.title_source_range.start <= byte_offset && byte_offset < node.title_source_range.end
    }) {
        return Some((node, node.title_source_range));
    }

    // Resolve a reference, reporting whichever extent of the link the caller asked for.
    let Link::Text {
        title,
        source_range,
    } = link_at(wiki, byte_offset)?
    else {
        return None;
    };
    let source_range = *source_range;
    Some((
        wiki.text_nodes.get(title)?,
        match link_extent {
            LinkExtent::Whole => source_range,
            LinkExtent::Target => text_link_target_source_range(source_contents, source_range)?,
        },
    ))
}

// Find the link of any kind at a source offset without resolving its destination. Links never
// overlap, so at most one link can contain the offset.
fn link_at(wiki: &Wiki, byte_offset: usize) -> Option<&Link> {
    wiki.text_nodes.values().find_map(|node| {
        node.links.iter().find(|link| {
            let (Link::Text { source_range, .. }
            | Link::File { source_range, .. }
            | Link::Directory { source_range, .. }) = link;
            source_range.start <= byte_offset && byte_offset < source_range.end
        })
    })
}

// Exclude the delimiters from a source range known to represent a complete link.
fn text_link_target_source_range(
    source_contents: &str,
    source_range: SourceRange,
) -> Option<SourceRange> {
    // Confirm the parser-provided range still addresses square-bracket delimiters.
    let target_source = source_contents
        .get(source_range.start..source_range.end)?
        .strip_prefix('[')?
        .strip_suffix(']')?;
    let start = source_range.start + '['.len_utf8();
    Some(SourceRange {
        start,
        end: start + target_source.len(),
    })
}

// Collect every complete text-link range that resolves to a title.
fn text_link_source_ranges(wiki: &Wiki, title: &str) -> Vec<SourceRange> {
    // Links live on nodes in an unordered map, so sort their ranges into source order.
    let mut source_ranges = wiki
        .text_nodes
        .values()
        .flat_map(|node| &node.links)
        .filter_map(|link| match link {
            Link::Text {
                title: link_title,
                source_range,
            } if link_title == title => Some(*source_range),
            Link::Text { .. } | Link::File { .. } | Link::Directory { .. } => None,
        })
        .collect::<Vec<_>>();
    source_ranges.sort_by_key(|source_range| (source_range.start, source_range.end));
    source_ranges
}

// Collect every complete filesystem-link range with the same kind and path as a target.
fn filesystem_link_source_ranges(wiki: &Wiki, target: &Link) -> Vec<SourceRange> {
    // Match logical paths without resolving symlinks, just as filesystem validation does.
    wiki.text_nodes
        .values()
        .flat_map(|node| &node.links)
        .filter_map(|link| match (link, target) {
            (
                Link::File { path, source_range },
                Link::File {
                    path: target_path, ..
                },
            )
            | (
                Link::Directory { path, source_range },
                Link::Directory {
                    path: target_path, ..
                },
            ) if path == target_path => Some(*source_range),
            (
                Link::Text { .. } | Link::File { .. } | Link::Directory { .. },
                Link::Text { .. } | Link::File { .. } | Link::Directory { .. },
            ) => None,
        })
        .collect()
}

// Convert a zero-based LSP position measured in UTF-16 code units into a UTF-8 byte offset.
fn byte_offset(source_contents: &str, position: Position) -> Option<usize> {
    // Locate the requested line without counting its line terminator as editor content.
    let mut line_start = 0;
    for _ in 0..position.line {
        line_start += source_contents[line_start..].find('\n')? + '\n'.len_utf8();
    }
    let line_end = source_contents[line_start..]
        .find('\n')
        .map_or(source_contents.len(), |index| line_start + index);
    let content_end = if line_end > line_start
        && source_contents.as_bytes()[line_end - 1] == b'\r'
        && source_contents.as_bytes().get(line_end) == Some(&b'\n')
    {
        line_end - '\r'.len_utf8()
    } else {
        line_end
    };

    // Reject positions that split a surrogate pair or extend past the line's contents.
    let requested_character = usize::try_from(position.character).ok()?;
    let mut utf16_character = 0;
    for (index, character) in source_contents[line_start..content_end].char_indices() {
        if utf16_character == requested_character {
            return Some(line_start + index);
        }
        utf16_character += character.len_utf16();
        if utf16_character > requested_character {
            return None;
        }
    }
    (utf16_character == requested_character).then_some(content_end)
}

// Convert a UTF-8 byte offset into a zero-based LSP position measured in UTF-16 code units.
fn lsp_position(source_contents: &str, byte_offset: usize) -> Position {
    // Source ranges originate at character boundaries and cannot extend beyond the source.
    let byte_offset = byte_offset.min(source_contents.len());
    let prefix = source_contents
        .get(..byte_offset)
        .expect("source ranges should end on UTF-8 character boundaries");
    Position::new(
        u32::try_from(prefix.bytes().filter(|byte| *byte == b'\n').count()).unwrap_or(u32::MAX),
        u32::try_from(
            source_contents[prefix
                .rfind('\n')
                .map_or(0, |index| index + '\n'.len_utf8())
                ..byte_offset]
                .encode_utf16()
                .count(),
        )
        .unwrap_or(u32::MAX),
    )
}

// Convert a source range into the representation expected by the language server protocol.
fn lsp_range(source_contents: &str, source_range: SourceRange) -> Range {
    Range::new(
        lsp_position(source_contents, source_range.start),
        lsp_position(source_contents, source_range.end),
    )
}

// Encode an editor navigation command as a Markdown-safe URI.
fn reveal_range_command_url(
    uri: &Uri,
    source_contents: &str,
    source_range: SourceRange,
) -> Option<String> {
    // Pass the document URI and UTF-16 destination range as positional command arguments.
    let range = lsp_range(source_contents, source_range);
    Some(format!(
        "command:{REVEAL_RANGE_COMMAND}?{}",
        utf8_percent_encode(
            &serde_json::to_string(&(
                uri.as_str(),
                range.start.line,
                range.start.character,
                range.end.line,
                range.end.character,
            ))
            .ok()?,
            NON_ALPHANUMERIC,
        ),
    ))
}

// Escape delimiters so an arbitrary node title retains its meaning inside a text link.
fn escape_text_link_title(title: &str) -> String {
    title.replace('[', "\\[").replace(']', "\\]")
}

// Convert a structured Mull error into the representation expected by language clients.
fn diagnostic_from_error(source_contents: &str, error: &Error) -> Diagnostic {
    // Include an underlying reason without including terminal prefixes, paths, or source listings.
    diagnostic(
        source_contents,
        error.source_range(),
        error.reason().map_or_else(
            || error.message().to_owned(),
            |reason| format!("{}\n\nReason: {reason}", error.message()),
        ),
    )
}

// Construct a Mull error diagnostic at a source range or at the start of the document.
fn diagnostic(
    source_contents: &str,
    source_range: Option<crate::error::SourceRange>,
    message: String,
) -> Diagnostic {
    Diagnostic {
        range: lsp_range(
            source_contents,
            source_range.unwrap_or(crate::error::SourceRange { start: 0, end: 0 }),
        ),
        severity: Some(DiagnosticSeverity::ERROR),
        source: Some(env!("CARGO_PKG_NAME").to_owned()),
        message,
        ..Diagnostic::default()
    }
}

// Convert only file-scheme URIs because the URI library does not enforce this distinction.
fn local_path(uri: &Uri) -> Option<Cow<'_, Path>> {
    uri.scheme()
        .as_str()
        .eq_ignore_ascii_case("file")
        .then(|| uri.to_file_path())
        .flatten()
}

// Serve language-server requests over standard input and output until the client disconnects.
pub async fn run() {
    // Keep ANSI terminal escapes out of protocol diagnostics.
    colored::control::set_override(false);

    // Connect the backend to the standard streams reserved for LSP messages.
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();
    let (service, socket) = LspService::new(Backend::new);
    Server::new(stdin, stdout, socket).serve(service).await;
}

#[cfg(test)]
mod tests {
    use super::{
        byte_offset, completion_for_document, diagnostic_from_error, diagnostics_for_document,
        document_highlight_for_document, document_symbol_for_document, formatting_for_document,
        goto_definition_for_document, hover_for_document, lsp_position,
        prepare_rename_for_document, references_for_document, rename_for_document,
        reveal_range_command_url,
    };
    use crate::{cancellation::CancellationFlag, error::SourceRange, parser};
    use std::{
        fs,
        path::{Path, PathBuf},
        process,
        sync::atomic::{AtomicUsize, Ordering},
    };
    use tower_lsp_server::ls_types::{
        CompletionTextEdit, Diagnostic, DiagnosticSeverity, DocumentHighlight,
        DocumentHighlightKind, DocumentSymbolResponse, GotoDefinitionResponse, HoverContents,
        MarkupKind, Position, PrepareRenameResponse, Range, SymbolKind, Uri,
    };

    // Assign each formatting fixture a distinct directory when tests run concurrently.
    static NEXT_DIRECTORY: AtomicUsize = AtomicUsize::new(0);

    // Compute diagnostics for a check which nothing cancels.
    fn diagnostics(uri: &Uri, source_contents: &str) -> Vec<Diagnostic> {
        diagnostics_for_document(uri, source_contents, &CancellationFlag::default())
            .expect("a check without cancellation should complete")
    }

    // This guard owns a temporary wiki directory and removes it after each test.
    struct TestWiki(PathBuf);

    impl TestWiki {
        // Create a file-backed wiki so validation sees the same environment as the editor.
        fn new(source_contents: &str) -> Self {
            let sequence = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
            let directory = std::env::temp_dir()
                .join(format!("mull-language-server-{}-{sequence}", process::id()));
            fs::create_dir(&directory).unwrap();
            let wiki_path = directory.join("wiki.mull");
            fs::write(&wiki_path, source_contents).unwrap();
            Self(wiki_path)
        }

        // Expose the temporary wiki path to the formatter.
        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TestWiki {
        // Remove the complete fixture directory when the test finishes.
        fn drop(&mut self) {
            fs::remove_dir_all(self.0.parent().unwrap()).unwrap();
        }
    }

    // Construct the URI assigned to a new editor buffer before its first save.
    fn untitled_uri() -> Uri {
        "untitled:Untitled-1".parse().unwrap()
    }

    #[test]
    fn positions_use_utf16_code_units() {
        let source = "zero\n😀 café";

        assert_eq!(lsp_position(source, 0), Position::new(0, 0));
        assert_eq!(lsp_position(source, 5), Position::new(1, 0));
        assert_eq!(lsp_position(source, 9), Position::new(1, 2));
        assert_eq!(lsp_position(source, source.len()), Position::new(1, 7));
    }

    // Convert editor positions back to byte offsets without splitting Unicode characters.
    #[test]
    fn byte_offsets_use_utf16_code_units() {
        let source = "zero\n😀 café";

        assert_eq!(byte_offset(source, Position::new(0, 0)), Some(0));
        assert_eq!(byte_offset(source, Position::new(1, 0)), Some(5));
        assert_eq!(byte_offset(source, Position::new(1, 1)), None);
        assert_eq!(byte_offset(source, Position::new(1, 2)), Some(9));
        assert_eq!(byte_offset(source, Position::new(1, 7)), Some(source.len()));
        assert_eq!(byte_offset(source, Position::new(1, 8)), None);
        assert_eq!(byte_offset(source, Position::new(2, 0)), None);
    }

    // Encode a document URI and UTF-16 title range for the trusted editor command.
    #[test]
    fn reveal_range_commands_encode_destinations() {
        let source = "# Home";
        let url =
            reveal_range_command_url(&untitled_uri(), source, SourceRange { start: 2, end: 6 })
                .unwrap();

        assert_eq!(
            url,
            concat!(
                "command:mull.revealRange?",
                "%5B%22untitled%3AUntitled%2D1%22%2C0%2C2%2C0%2C6%5D",
            ),
        );
    }

    // Expose text nodes in source order for saved and untitled editor outlines.
    #[test]
    fn document_symbols_describe_text_nodes() {
        let source = "# Zebra\n\nFirst\n\n# Alpha\n\nSecond";
        let wiki = TestWiki::new(source);
        let uris = [untitled_uri(), Uri::from_file_path(wiki.path()).unwrap()];

        for uri in uris {
            let response = document_symbol_for_document(&uri, source, true).unwrap();
            let DocumentSymbolResponse::Nested(symbols) = response else {
                panic!("text nodes should be represented as nested document symbols");
            };
            assert_eq!(
                symbols
                    .iter()
                    .map(|symbol| symbol.name.as_str())
                    .collect::<Vec<_>>(),
                vec!["Zebra", "Alpha"],
            );
            assert!(symbols.iter().all(|symbol| {
                symbol.kind == SymbolKind::OBJECT
                    && symbol.detail.is_none()
                    && symbol.tags.is_none()
                    && symbol.children.is_none()
            }));
            assert_eq!(
                symbols[0].range,
                Range::new(Position::new(0, 0), Position::new(2, 5)),
            );
            assert_eq!(
                symbols[0].selection_range,
                Range::new(Position::new(0, 2), Position::new(0, 7)),
            );
            assert_eq!(
                symbols[1].range,
                Range::new(Position::new(4, 0), Position::new(6, 6)),
            );
            assert_eq!(
                symbols[1].selection_range,
                Range::new(Position::new(4, 2), Position::new(4, 7)),
            );

            // Fall back to universally supported flat symbols at each title range.
            let response = document_symbol_for_document(&uri, source, false).unwrap();
            let DocumentSymbolResponse::Flat(symbols) = response else {
                panic!("clients without hierarchy support should receive flat symbols");
            };
            assert_eq!(
                symbols
                    .iter()
                    .map(|symbol| symbol.name.as_str())
                    .collect::<Vec<_>>(),
                vec!["Zebra", "Alpha"],
            );
            assert_eq!(
                symbols[0].location.range,
                Range::new(Position::new(0, 2), Position::new(0, 7)),
            );
            assert_eq!(
                symbols[1].location.range,
                Range::new(Position::new(4, 2), Position::new(4, 7)),
            );
        }
    }

    // Analyze ordinary text-node structure in a new editor buffer.
    #[test]
    fn untitled_text_only_wikis_receive_diagnostics() {
        let source = "# Home\nSee [Missing].";
        let diagnostics = diagnostics(&untitled_uri(), source);

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "Node `Missing` not found.");
        assert_eq!(
            diagnostics[0].range,
            Range::new(Position::new(1, 4), Position::new(1, 13)),
        );
    }

    // Report parser errors from a new editor buffer at their exact source locations.
    #[test]
    fn untitled_syntax_errors_receive_diagnostics() {
        let source = "# Home\nUnexpected]";
        let diagnostics = diagnostics(&untitled_uri(), source);

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "Unexpected closing link delimiter.");
        assert_eq!(
            diagnostics[0].range,
            Range::new(Position::new(1, 10), Position::new(1, 11)),
        );
    }

    // Require a first save before resolving filesystem links from a new editor buffer.
    #[test]
    fn untitled_filesystem_links_receive_diagnostics() {
        let source = concat!("# Home\n[", "file:notes.txt] [", "dir:images]");
        let diagnostics = diagnostics(&untitled_uri(), source);

        assert_eq!(diagnostics.len(), 2);
        assert!(diagnostics.iter().all(|diagnostic| {
            diagnostic.message == "Save the wiki to validate this filesystem link."
        }));
        assert_eq!(
            diagnostics
                .iter()
                .map(|diagnostic| diagnostic.range)
                .collect::<Vec<_>>(),
            vec![
                Range::new(Position::new(1, 0), Position::new(1, 16)),
                Range::new(Position::new(1, 17), Position::new(1, 29)),
            ],
        );
    }

    // Navigate among text nodes without requiring a new editor buffer to have a path.
    #[test]
    fn untitled_wikis_support_navigation() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting";

        assert!(
            goto_definition_for_document(&untitled_uri(), source, Position::new(2, 4)).is_some(),
        );
        assert!(hover_for_document(&untitled_uri(), source, Position::new(2, 4)).is_some());
        assert!(
            references_for_document(&untitled_uri(), source, Position::new(2, 4), false).is_some(),
        );
    }

    // Complete a partial target by replacing the whole link, including its delimiters.
    #[test]
    fn completions_replace_closed_links() {
        let source = "# Home\n\n[Gr]\n\n# Greeting\n\n# Other";
        let completions =
            completion_for_document(&untitled_uri(), source, Position::new(2, 3)).unwrap();

        assert_eq!(
            completions
                .iter()
                .map(|completion| completion.label.as_str())
                .collect::<Vec<_>>(),
            vec!["Greeting", "Home", "Other"],
        );
        let Some(CompletionTextEdit::Edit(edit)) = &completions[0].text_edit else {
            panic!("a completion should replace the link");
        };
        let link_range = Range::new(Position::new(2, 0), Position::new(2, 4));
        assert_eq!(edit.range, link_range);
        assert_eq!(edit.new_text, "[Greeting]");

        // Replace the same link from a cursor before its opening delimiter.
        let completions =
            completion_for_document(&untitled_uri(), source, Position::new(2, 0)).unwrap();
        let Some(CompletionTextEdit::Edit(edit)) = &completions[0].text_edit else {
            panic!("a completion should replace the link");
        };
        assert_eq!(edit.range, link_range);
    }

    // Close an unfinished link temporarily while calculating its completions.
    #[test]
    fn completions_support_unfinished_links() {
        let source = "# Home\n\n[Gre\n\n# Greeting";
        let completions =
            completion_for_document(&untitled_uri(), source, Position::new(2, 4)).unwrap();
        let greeting = completions
            .iter()
            .find(|completion| completion.label == "Greeting")
            .unwrap();
        let Some(CompletionTextEdit::Edit(edit)) = &greeting.text_edit else {
            panic!("a completion should replace the unfinished link");
        };

        assert_eq!(
            edit.range,
            Range::new(Position::new(2, 0), Position::new(2, 4)),
        );
        assert_eq!(edit.new_text, "[Greeting]");
    }

    // Leave the cursor after a single closing delimiter once a completion has been applied.
    #[test]
    fn completions_do_not_duplicate_closing_delimiters() {
        // Model an editor that has already auto-closed the link the cursor sits inside.
        let source = "# Home\n\n[Gr]\n\n# Greeting";
        let completions =
            completion_for_document(&untitled_uri(), source, Position::new(2, 3)).unwrap();
        let greeting = completions
            .iter()
            .find(|completion| completion.label == "Greeting")
            .unwrap();
        let Some(CompletionTextEdit::Edit(edit)) = &greeting.text_edit else {
            panic!("a completion should replace the link");
        };

        // Apply the edit to confirm the link is closed exactly once.
        let start = byte_offset(source, edit.range.start).unwrap();
        let end = byte_offset(source, edit.range.end).unwrap();
        let mut applied = source.to_owned();
        applied.replace_range(start..end, &edit.new_text);
        assert_eq!(applied, "# Home\n\n[Greeting]\n\n# Greeting");
    }

    // Escape link delimiters when inserting a node title as a completion.
    #[test]
    fn completions_escape_title_delimiters() {
        let source = "# Home\n\n[]\n\n# A[B]";
        let completions =
            completion_for_document(&untitled_uri(), source, Position::new(2, 1)).unwrap();
        let bracketed = completions
            .iter()
            .find(|completion| completion.label == "A[B]")
            .unwrap();
        let Some(CompletionTextEdit::Edit(edit)) = &bracketed.text_edit else {
            panic!("a completion should encode the title as a text link");
        };

        assert_eq!(bracketed.filter_text.as_deref(), Some("[A\\[B\\]"));
        assert_eq!(edit.new_text, "[A\\[B\\]]");
    }

    // Offer text-node completions only while the cursor is inside a text link target.
    #[test]
    fn completions_ignore_other_contexts() {
        let source = concat!("# Home\n\nprose [", "file:notes.txt]");

        assert!(completion_for_document(&untitled_uri(), source, Position::new(2, 2)).is_none());
        assert!(completion_for_document(&untitled_uri(), source, Position::new(2, 10)).is_none());
        assert!(completion_for_document(&untitled_uri(), source, Position::new(0, 3)).is_none());
    }

    // Treat a title as its own definition, which lets editors fall back to finding references.
    #[test]
    fn definitions_of_titles_target_themselves() {
        let source = "# Home\n\n[Home]";
        let definition =
            goto_definition_for_document(&untitled_uri(), source, Position::new(0, 3)).unwrap();

        let GotoDefinitionResponse::Link(links) = definition else {
            panic!("a title should have one definition");
        };
        let [link] = links.as_slice() else {
            panic!("a title should have exactly one definition");
        };
        let title_range = Range::new(Position::new(0, 2), Position::new(0, 6));
        assert_eq!(link.origin_selection_range, Some(title_range));
        assert_eq!(link.target_selection_range, title_range);
    }

    // Jump from a text link to the title of its destination node.
    #[test]
    fn definitions_target_node_titles() {
        let source = "# Home\n\n😀 [Greeting]\n\n# Greeting\n\nHello!";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let definition = goto_definition_for_document(&uri, source, Position::new(2, 5)).unwrap();

        let GotoDefinitionResponse::Link(links) = definition else {
            panic!("a text link should have one definition");
        };
        let [link] = links.as_slice() else {
            panic!("a text link should have exactly one definition");
        };
        assert_eq!(link.target_uri, uri);
        assert_eq!(
            link.origin_selection_range,
            Some(Range::new(Position::new(2, 3), Position::new(2, 13))),
        );
        assert_eq!(
            link.target_range,
            Range::new(Position::new(4, 0), Position::new(6, 6)),
        );
        assert_eq!(
            link.target_selection_range,
            Range::new(Position::new(4, 2), Position::new(4, 10)),
        );
    }

    // Preview the complete destination node while highlighting the source link.
    #[test]
    fn hovers_preview_nodes() {
        let source = "# Home\n\n😀 [Greeting]\n\n# Greeting\n\nLiteral \\[brackets\\] and [Home].";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let hover = hover_for_document(&uri, source, Position::new(2, 5)).unwrap();

        let HoverContents::Markup(contents) = hover.contents else {
            panic!("a node preview should use markup content");
        };
        assert_eq!(contents.kind, MarkupKind::Markdown);
        let home_url =
            reveal_range_command_url(&uri, source, SourceRange { start: 2, end: 6 }).unwrap();
        assert_eq!(
            contents.value,
            format!(
                "# Greeting\n\nLiteral &#91;brackets&#93; and \
                    [&#91;Home&#93;]({home_url}).",
            ),
        );
        assert_eq!(
            hover.range,
            Some(Range::new(Position::new(2, 3), Position::new(2, 13))),
        );
    }

    // Preview a node directly from its title declaration.
    #[test]
    fn hovers_preview_node_titles() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting\n\nHello!";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let hover = hover_for_document(&uri, source, Position::new(4, 4)).unwrap();

        let HoverContents::Markup(contents) = hover.contents else {
            panic!("a node preview should use markup content");
        };
        assert_eq!(contents.kind, MarkupKind::Markdown);
        assert_eq!(contents.value, "# Greeting\n\nHello!");
        assert_eq!(
            hover.range,
            Some(Range::new(Position::new(4, 2), Position::new(4, 10))),
        );
    }

    // Find every text link from either a declaration or one of its references.
    #[test]
    fn references_find_text_links() {
        let source = concat!(
            "# Home\n\n",
            "[Greeting] and [Greeting].\n\n",
            "# Other\n\n",
            "[Greeting]\n\n",
            "# Greeting",
        );
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let from_title = references_for_document(&uri, source, Position::new(8, 3), false).unwrap();
        let from_link = references_for_document(&uri, source, Position::new(2, 3), false).unwrap();

        assert_eq!(from_title, from_link);
        assert!(from_title.iter().all(|location| location.uri == uri));
        assert_eq!(
            from_title
                .iter()
                .map(|location| location.range)
                .collect::<Vec<_>>(),
            vec![
                Range::new(Position::new(2, 0), Position::new(2, 10)),
                Range::new(Position::new(2, 15), Position::new(2, 25)),
                Range::new(Position::new(6, 0), Position::new(6, 10)),
            ],
        );
    }

    // Include the declaration only when the language client requests it.
    #[test]
    fn references_optionally_include_declarations() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let locations = references_for_document(&uri, source, Position::new(4, 3), true).unwrap();

        assert_eq!(
            locations
                .iter()
                .map(|location| location.range)
                .collect::<Vec<_>>(),
            vec![
                Range::new(Position::new(2, 0), Position::new(2, 10)),
                Range::new(Position::new(4, 2), Position::new(4, 10)),
            ],
        );
    }

    // Distinguish a known node with no references from a cursor that denotes no node.
    #[test]
    fn references_can_be_empty() {
        let source = "# Home";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert_eq!(
            references_for_document(&uri, source, Position::new(0, 3), false),
            Some(Vec::new()),
        );
        assert!(references_for_document(&uri, source, Position::new(0, 0), false).is_none());
    }

    // Highlight a node declaration and all its text links from either kind of occurrence.
    #[test]
    fn document_highlights_find_node_occurrences() {
        let source = concat!(
            "# Home\n\n",
            "[Greeting] and [Greeting].\n\n",
            "# Other\n\n",
            "[Greeting]\n\n",
            "# Greeting",
        );
        let uri = untitled_uri();
        let from_title =
            document_highlight_for_document(&uri, source, Position::new(8, 3)).unwrap();
        let from_link = document_highlight_for_document(&uri, source, Position::new(2, 3)).unwrap();
        let expected = vec![
            DocumentHighlight {
                range: Range::new(Position::new(2, 0), Position::new(2, 10)),
                kind: Some(DocumentHighlightKind::READ),
            },
            DocumentHighlight {
                range: Range::new(Position::new(2, 15), Position::new(2, 25)),
                kind: Some(DocumentHighlightKind::READ),
            },
            DocumentHighlight {
                range: Range::new(Position::new(6, 0), Position::new(6, 10)),
                kind: Some(DocumentHighlightKind::READ),
            },
            DocumentHighlight {
                range: Range::new(Position::new(8, 2), Position::new(8, 10)),
                kind: Some(DocumentHighlightKind::WRITE),
            },
        ];

        assert_eq!(from_title, expected);
        assert_eq!(from_link, expected);
    }

    // Highlight an unreferenced declaration while ignoring a cursor outside node occurrences.
    #[test]
    fn document_highlights_distinguish_unreferenced_nodes() {
        let source = "# Home";
        let uri = untitled_uri();

        assert_eq!(
            document_highlight_for_document(&uri, source, Position::new(0, 3)),
            Some(vec![DocumentHighlight {
                range: Range::new(Position::new(0, 2), Position::new(0, 6)),
                kind: Some(DocumentHighlightKind::WRITE),
            }]),
        );
        assert!(document_highlight_for_document(&uri, source, Position::new(0, 0)).is_none());
    }

    // Highlight nothing for a text link whose target does not exist.
    #[test]
    fn document_highlights_ignore_unresolved_text_links() {
        let source = "# Home\n\n[Missing]";

        assert!(
            document_highlight_for_document(&untitled_uri(), source, Position::new(2, 3)).is_none(),
        );
    }

    // Highlight matching filesystem links without conflating file and directory references.
    #[test]
    fn document_highlights_find_filesystem_links() {
        let source = concat!(
            "# Home\n\n",
            "[",
            "file:foo] [",
            "file:foo] [",
            "dir:bar]\n\n",
            "# Other\n\n",
            "[",
            "dir:bar]",
        );
        let uri = untitled_uri();
        let file_highlights =
            document_highlight_for_document(&uri, source, Position::new(2, 3)).unwrap();
        let directory_highlights =
            document_highlight_for_document(&uri, source, Position::new(2, 25)).unwrap();

        assert_eq!(
            file_highlights,
            vec![
                DocumentHighlight {
                    range: Range::new(Position::new(2, 0), Position::new(2, 10)),
                    kind: Some(DocumentHighlightKind::READ),
                },
                DocumentHighlight {
                    range: Range::new(Position::new(2, 11), Position::new(2, 21)),
                    kind: Some(DocumentHighlightKind::READ),
                },
            ],
        );
        assert_eq!(
            directory_highlights,
            vec![
                DocumentHighlight {
                    range: Range::new(Position::new(2, 22), Position::new(2, 31)),
                    kind: Some(DocumentHighlightKind::READ),
                },
                DocumentHighlight {
                    range: Range::new(Position::new(6, 0), Position::new(6, 9)),
                    kind: Some(DocumentHighlightKind::READ),
                },
            ],
        );
    }

    // Prepare rename from either a declaration or text link without selecting its delimiters.
    #[test]
    fn rename_preparation_selects_title_text() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting";
        let from_title =
            prepare_rename_for_document(&untitled_uri(), source, Position::new(4, 3)).unwrap();
        let from_link =
            prepare_rename_for_document(&untitled_uri(), source, Position::new(2, 4)).unwrap();

        assert_eq!(
            from_title,
            PrepareRenameResponse::RangeWithPlaceholder {
                range: Range::new(Position::new(4, 2), Position::new(4, 10)),
                placeholder: "Greeting".to_owned(),
            },
        );
        assert_eq!(
            from_link,
            PrepareRenameResponse::RangeWithPlaceholder {
                range: Range::new(Position::new(2, 1), Position::new(2, 9)),
                placeholder: "Greeting".to_owned(),
            },
        );
    }

    // Rename a declaration and every text link while trimming the requested title.
    #[test]
    fn rename_updates_every_occurrence() {
        let source = "# Home\n\n[Greeting] and [Greeting]\n\n# Greeting";
        let workspace_edit = rename_for_document(
            &untitled_uri(),
            source,
            Position::new(4, 3),
            "  Salutation\t",
        )
        .unwrap()
        .unwrap();
        let edits = &workspace_edit.changes.unwrap()[&untitled_uri()];

        assert_eq!(edits.len(), 3);
        assert_eq!(edits[0].new_text, "Salutation");
        assert_eq!(edits[0].range.start, Position::new(2, 1));
        assert_eq!(edits[1].new_text, "Salutation");
        assert_eq!(edits[1].range.start, Position::new(2, 16));
        assert_eq!(edits[2].new_text, "Salutation");
        assert_eq!(edits[2].range.start, Position::new(4, 2));
    }

    // Preserve renamed titles containing delimiters by escaping only their link occurrences.
    #[test]
    fn rename_escapes_link_delimiters() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting";
        let workspace_edit =
            rename_for_document(&untitled_uri(), source, Position::new(2, 4), "A[B]")
                .unwrap()
                .unwrap();
        let edits = &workspace_edit.changes.unwrap()[&untitled_uri()];

        assert_eq!(edits[0].new_text, "A\\[B\\]");
        assert_eq!(edits[1].new_text, "A[B]");
    }

    // Allow renaming the structural home node even though validation will report its absence.
    #[test]
    fn rename_allows_home() {
        let source = "# Home";
        let workspace_edit =
            rename_for_document(&untitled_uri(), source, Position::new(0, 3), "Start")
                .unwrap()
                .unwrap();
        let edits = &workspace_edit.changes.unwrap()[&untitled_uri()];

        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "Start");
    }

    // Reject only syntactically unusable or duplicate node titles during rename.
    #[test]
    fn rename_rejects_invalid_titles() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting";
        let cursor = Position::new(4, 3);

        assert_eq!(
            rename_for_document(&untitled_uri(), source, cursor, " \t").unwrap_err(),
            "A node title cannot be empty.",
        );
        assert_eq!(
            rename_for_document(&untitled_uri(), source, cursor, "Hello\nworld").unwrap_err(),
            "A node title cannot contain a line break.",
        );
        assert_eq!(
            rename_for_document(&untitled_uri(), source, cursor, "Home").unwrap_err(),
            "Node `Home` already exists.",
        );
        assert_eq!(
            rename_for_document(&untitled_uri(), source, cursor, "file:notes.txt").unwrap_err(),
            "A node title cannot start with `file:` or `dir:`.",
        );
    }

    // Leave filesystem links to ordinary editor and filesystem navigation.
    #[test]
    fn navigation_ignores_filesystem_links() {
        let source = concat!("# Home\n\n[", "file:notes.txt]");
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert!(goto_definition_for_document(&uri, source, Position::new(2, 4)).is_none());
        assert!(hover_for_document(&uri, source, Position::new(2, 4)).is_none());
        assert!(references_for_document(&uri, source, Position::new(2, 4), false).is_none());
    }

    // Omit navigation results when the deliberately simple parser cannot produce a wiki.
    #[test]
    fn navigation_requires_parseable_source() {
        let source = "# Home\n\n[Greeting]\n\n# Greeting\n\nUnexpected]";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert!(goto_definition_for_document(&uri, source, Position::new(2, 4)).is_none());
        assert!(hover_for_document(&uri, source, Position::new(2, 4)).is_none());
        assert!(references_for_document(&uri, source, Position::new(2, 4), false).is_none());
    }

    #[test]
    fn formatting_replaces_noncanonical_source() {
        let source = "# Zulu\n\n😀\n\n# Home\n\n[Zulu]";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let edits = formatting_for_document(&uri, source).unwrap();

        assert_eq!(edits.len(), 1);
        let edit = &edits[0];
        assert_eq!(
            edit.range,
            Range::new(Position::new(0, 0), Position::new(6, 6)),
        );
        assert_eq!(edit.new_text, "# Home\n\n[Zulu]\n\n# Zulu\n\n😀\n");
    }

    #[test]
    fn formatting_omits_edits_for_canonical_source() {
        let source = "# Home\n";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert!(formatting_for_document(&uri, source).unwrap().is_empty());
    }

    #[test]
    fn formatting_rejects_unparsable_source() {
        let source = "# Home\n😀 ]";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert!(formatting_for_document(&uri, source).is_none());
    }

    // Format wikis that parse but fail validation, such as one without a home node.
    #[test]
    fn formatting_supports_invalid_wikis() {
        let source = "# Zulu\n\n# Elsewhere";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();
        let edits = formatting_for_document(&uri, source).unwrap();

        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "# Elsewhere\n\n# Zulu\n");
    }

    // Format a new editor buffer without requiring a filesystem path.
    #[test]
    fn formatting_supports_untitled_wikis() {
        let source = "# Zulu\n\n# Home\n\n[Zulu]";
        let edits = formatting_for_document(&untitled_uri(), source).unwrap();

        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "# Home\n\n[Zulu]\n\n# Zulu\n");
    }

    #[test]
    fn formatting_differences_are_not_diagnostics() {
        let source = "# Zulu\n\n# Home\n\n[Zulu]";
        let wiki = TestWiki::new(source);
        let uri = Uri::from_file_path(wiki.path()).unwrap();

        assert!(diagnostics(&uri, source).is_empty());
    }

    #[test]
    fn source_errors_become_precise_diagnostics() {
        let source = "# Home\n😀 ]";
        let error = parser::parse(Some(Path::new("wiki.mull")), source)
            .unwrap_err()
            .into_iter()
            .next()
            .unwrap();
        let diagnostic = diagnostic_from_error(source, &error);

        assert_eq!(
            diagnostic.range,
            Range::new(Position::new(1, 3), Position::new(1, 4)),
        );
        assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::ERROR));
        assert_eq!(diagnostic.source.as_deref(), Some("mull"));
        assert_eq!(diagnostic.message, "Unexpected closing link delimiter.");
    }

    #[test]
    fn errors_without_ranges_point_to_document_start() {
        let error = crate::error::Error::new("Something went wrong.", None, None, None);
        let diagnostic = diagnostic_from_error("# Home\n", &error);

        assert_eq!(
            diagnostic.range,
            Range::new(Position::new(0, 0), Position::new(0, 0)),
        );
    }

    #[test]
    fn ranges_can_span_windows_line_endings() {
        let source = "first\r\nsecond";
        let error = crate::error::Error::new(
            "Something went wrong.",
            Some(Path::new("wiki.mull")),
            Some((source, SourceRange { start: 0, end: 9 })),
            None,
        );
        let diagnostic = diagnostic_from_error(source, &error);

        assert_eq!(
            diagnostic.range,
            Range::new(Position::new(0, 0), Position::new(1, 2)),
        );
    }
}