ada_language_server_22.0.0_ef4bdf41/source/ada/lsp-ada_documents.adb

   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
------------------------------------------------------------------------------
--                         Language Server Protocol                         --
--                                                                          --
--                     Copyright (C) 2018-2021, AdaCore                     --
--                                                                          --
-- This is free software;  you can redistribute it  and/or modify it  under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
-- sion.  This software is distributed in the hope  that it will be useful, --
-- but WITHOUT ANY WARRANTY;  without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public --
-- License for  more details.  You should have  received  a copy of the GNU --
-- General  Public  License  distributed  with  this  software;   see  file --
-- COPYING3.  If not, go to http://www.gnu.org/licenses for a complete copy --
-- of the license.                                                          --
------------------------------------------------------------------------------

with Ada.Characters.Latin_1;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Unchecked_Deallocation;

with GNAT.Strings;

with GNATCOLL.Utils;

with VSS.Characters;
with VSS.Strings.Conversions;

with Langkit_Support.Symbols;
with Langkit_Support.Text;
with Libadalang.Analysis; use Libadalang.Analysis;
with Libadalang.Sources;
with Libadalang.Iterators;

with VSS.String_Vectors;
with VSS.Strings.Character_Iterators;
with VSS.Strings.Line_Iterators;
with VSS.Unicode;

with LSP.Ada_Contexts; use LSP.Ada_Contexts;
with LSP.Ada_Completions.Filters;
with LSP.Ada_Id_Iterators;
with LSP.Ada_Documents.LAL_Diagnostics;
with LSP.Common; use LSP.Common;
with LSP.Lal_Utils;

with Pp.Scanner;
with Utils.Char_Vectors;

package body LSP.Ada_Documents is

   Lal_PP_Output : constant GNATCOLL.Traces.Trace_Handle :=
     GNATCOLL.Traces.Create ("ALS.LAL_PP_OUTPUT_ON_FORMATTING",
                             GNATCOLL.Traces.Off);
   --  Logging lalpp output if On

   function Get_Profile
     (Node        : Libadalang.Analysis.Basic_Decl;
      Is_Function : out Boolean)
      return VSS.Strings.Virtual_String;
   --  Return the profile of Node.

   function Is_Declaration
     (Node : Libadalang.Analysis.Basic_Decl) return Boolean;

   function Get_Visibility
     (Node : Libadalang.Analysis.Basic_Decl)
      return LSP.Messages.Als_Visibility;

   function To_Completion_Kind
     (K : LSP.Messages.SymbolKind) return LSP.Messages.CompletionItemKind
   is
     (case K is
        when LSP.Messages.A_Function => LSP.Messages.A_Function,
        when LSP.Messages.Field      => LSP.Messages.Field,
        when LSP.Messages.Variable   => LSP.Messages.Variable,
        when LSP.Messages.A_Package  => LSP.Messages.Module,
        when LSP.Messages.Module     => LSP.Messages.Module,
        when LSP.Messages.Class      => LSP.Messages.Class,
        when LSP.Messages.Struct     => LSP.Messages.Class,
        when LSP.Messages.Number     => LSP.Messages.Value,
        when LSP.Messages.Enum       => LSP.Messages.Enum,
        when LSP.Messages.String     => LSP.Messages.Value,
        when LSP.Messages.A_Constant => LSP.Messages.Value,
        when others                  => LSP.Messages.Reference);
   --  Convert a SymbolKind to a CompletionItemKind.
   --  TODO: It might be better to have a unified kind, and then convert to
   --  specific kind types, but for the moment this is good enough.

   procedure Recompute_Indexes (Self : in out Document);
   --  Recompute the line-to-offset indexes in Self

   procedure Recompute_Markers
     (Self         : in out Document'Class;
      Low_Line     : LSP.Types.Line_Number;
      Start_Marker : VSS.Strings.Markers.Character_Marker;
      End_Marker   : VSS.Strings.Markers.Character_Marker);
   --  Recompute line-to-marker index starting from Start_Marker till
   --  End_Marker and filling index table starting at Low_Line. End_Marker
   --  may be invalid marker, in this case indexing down to the end of the
   --  text.

   procedure Span_To_Markers
     (Self : Document'Class;
      Span : LSP.Messages.Span;
      From : out VSS.Strings.Markers.Character_Marker;
      To   : out VSS.Strings.Markers.Character_Marker);

   function Get_Token_At
     (Self     : Document'Class;
      Context  : LSP.Ada_Contexts.Context;
      Position : LSP.Messages.Position)
      return Libadalang.Common.Token_Reference;
   --  Return a token at the given Position.

   -----------------------
   -- Recompute_Indexes --
   -----------------------

   procedure Recompute_Indexes (Self : in out Document) is
      use type VSS.Strings.Character_Count;

   begin
      Self.Line_To_Marker.Clear;

      --  To avoid too many reallocations during the initial filling
      --  of the index vector, pre-allocate it. Give a generous
      --  pre-allocation assuming that there is a line break every
      --  20 characters on average (this file has one line break
      --  every 33 characters).
      Self.Line_To_Marker.Reserve_Capacity
        (Ada.Containers.Count_Type (Self.Text.Character_Length / 20));

      declare
         J                    : VSS.Strings.Line_Iterators.Line_Iterator :=
           Self.Text.First_Line
             (Terminators     => LSP_New_Line_Function_Set,
              Keep_Terminator => True);
         Last_Line_Terminated : Boolean := False;

      begin
         if J.Has_Element then
            --  Update Line_Terminator of the document
            Self.Line_Terminator := Self.Text.Slice
              (J.Terminator_First_Marker, J.Terminator_Last_Marker);

            loop
               Self.Line_To_Marker.Append (J.First_Marker);
               Last_Line_Terminated := J.Has_Line_Terminator;

               exit when not J.Forward;
            end loop;

         else
            Last_Line_Terminated := True;
            --  Force to add one line for an empty document.
         end if;

         --  Append marker at the end of the text when the last line has line
         --  terminator sequence or text is empty. It allows to avoid checks
         --  for corner cases.

         if Last_Line_Terminated then
            Self.Line_To_Marker.Append (J.First_Marker);
         end if;
      end;
   end Recompute_Indexes;

   -----------------------
   -- Recompute_Markers --
   -----------------------

   procedure Recompute_Markers
     (Self         : in out Document'Class;
      Low_Line     : LSP.Types.Line_Number;
      Start_Marker : VSS.Strings.Markers.Character_Marker;
      End_Marker   : VSS.Strings.Markers.Character_Marker)
   is
      use type LSP.Types.Line_Number;
      use type VSS.Strings.Character_Count;

      M    : VSS.Strings.Markers.Character_Marker;
      J    : VSS.Strings.Line_Iterators.Line_Iterator :=
        Self.Text.Line
          (Position        => Start_Marker,
           Terminators     => LSP_New_Line_Function_Set,
           Keep_Terminator => True);
      Line : LSP.Types.Line_Number := Low_Line;

   begin
      if J.Has_Element then
         loop
            M := J.First_Marker;

            exit
              when End_Marker.Is_Valid
                and then M.Character_Index = End_Marker.Character_Index;

            Self.Line_To_Marker.Insert (Line, M);
            Line := Line + 1;

            exit when not J.Forward;
         end loop;

         if not End_Marker.Is_Valid then
            Self.Line_To_Marker.Append (J.First_Marker);
         end if;
      end if;
   end Recompute_Markers;

   -------------------
   -- Apply_Changes --
   -------------------

   procedure Apply_Changes
     (Self    : aliased in out Document;
      Version : LSP.Types.LSP_Number;
      Vector  : LSP.Messages.TextDocumentContentChangeEvent_Vector)
   is
      URI : constant String := Types.To_UTF_8_String (Self.URI);
      Dummy : Libadalang.Analysis.Analysis_Unit;
      use LSP.Types;
   begin
      Self.Trace.Trace ("Applying changes for document " & URI);

      Self.Version := Version;

      for Change of Vector loop
         if Change.span.Is_Set then
            --  We're replacing a range

            declare
               Low_Line    : LSP.Types.Line_Number :=
                 Change.span.Value.first.line;
               High_Line   : LSP.Types.Line_Number :=
                 Change.span.Value.last.line;
               Delete_High : LSP.Types.Line_Number := High_Line;
               Start_Index : LSP.Types.Line_Number;

               First_Marker : VSS.Strings.Markers.Character_Marker;
               Last_Marker  : VSS.Strings.Markers.Character_Marker;
               Start_Marker : VSS.Strings.Markers.Character_Marker;
               End_Marker   : VSS.Strings.Markers.Character_Marker;

            begin
               --  Do text replacement

               Self.Span_To_Markers
                 (Change.span.Value, First_Marker, Last_Marker);
               Self.Text.Replace
                 (First_Marker,
                  Last_Marker,
                  To_Virtual_String (Change.text));

               --  Markers inside modified range of lines need to be
               --  recomputed, markers outside of this range has been
               --  recomputed by call to Replace.

               --  Use marker of the line before the first modified line as
               --  start marker for recompute because marker of the first
               --  modified line may be ether invalidated or moved by Replace,
               --  or start from first character of the new text when first
               --  line was modified.

               if Low_Line /= Self.Line_To_Marker.First_Index then
                  Low_Line     := Low_Line - 1;
                  Start_Index  := Low_Line;
                  Start_Marker := Self.Line_To_Marker (Low_Line);

               else
                  Start_Index  := Self.Line_To_Marker.First_Index;
                  Start_Marker := Self.Text.First_Character.Marker;
               end if;

               --  Use marker of the line after the last modified line as end
               --  marker for recompute because marker of the last modified
               --  line may be ether invalidated or moved and not point to the
               --  beginning of the line, or use invalid marker when last line
               --  was modified.

               if High_Line /= Self.Line_To_Marker.Last_Index then
                  Delete_High := High_Line;
                  High_Line := High_Line + 1;
                  End_Marker := Self.Line_To_Marker (High_Line);
               end if;

               if Low_Line = Self.Line_To_Marker.First_Index
                 and then High_Line = Self.Line_To_Marker.Last_Index
               then
                  Self.Recompute_Indexes;

               else
                  if Delete_High >= Low_Line then
                     Self.Line_To_Marker.Delete
                       (Low_Line,
                        Ada.Containers.Count_Type
                          (Delete_High - Low_Line + 1));
                  end if;

                  Self.Recompute_Markers
                    (Start_Index, Start_Marker, End_Marker);
               end if;
            end;

         else
            Self.Text := To_Virtual_String (Change.text);

            --  We're setting the whole text: compute the indexes now.
            Self.Recompute_Indexes;
         end if;
      end loop;
      Self.Trace.Trace ("Done applying changes for document " & URI);
   end Apply_Changes;

   -----------------
   -- Get_Text_At --
   -----------------

   function Get_Text_At
     (Self      : Document;
      Start_Pos : LSP.Messages.Position;
      End_Pos   : LSP.Messages.Position) return VSS.Strings.Virtual_String
   is
      First_Marker : VSS.Strings.Markers.Character_Marker;
      Last_Marker  : VSS.Strings.Markers.Character_Marker;

   begin
      Self.Span_To_Markers
        ((Start_Pos, End_Pos), First_Marker, Last_Marker);

      return Self.Text.Slice (First_Marker, Last_Marker);
   end Get_Text_At;

   ----------
   -- Diff --
   ----------

   procedure Diff
     (Self     : Document;
      New_Text : VSS.Strings.Virtual_String;
      Old_Span : LSP.Messages.Span := LSP.Messages.Empty_Span;
      New_Span : LSP.Messages.Span := LSP.Messages.Empty_Span;
      Edit     : out LSP.Messages.TextEdit_Vector)
   is
      use LSP.Types;
      use LSP.Messages;

      Old_First_Line : Natural;
      New_First_Line : Natural;

      Old_Lines, New_Lines   : VSS.String_Vectors.Virtual_String_Vector;
      Old_Length, New_Length : Natural;

   begin
      Old_Lines :=
        Self.Text.Split_Lines
          (Terminators     => LSP_New_Line_Function_Set,
           Keep_Terminator => True);
      New_Lines :=
        New_Text.Split_Lines
          (Terminators     => LSP_New_Line_Function_Set,
           Keep_Terminator => True);

      if Old_Span = Empty_Span then
         Old_First_Line := 1;
         Old_Length     := Old_Lines.Length;

      else
         Old_First_Line := Natural (Old_Span.first.line + 1);
         Old_Length := Natural (Old_Span.last.line - Old_Span.first.line + 1);
      end if;

      if New_Span = Empty_Span then
         New_First_Line := 1;
         New_Length     := New_Lines.Length;
      else
         New_First_Line := Natural (New_Span.first.line + 1);
         New_Length := Natural (New_Span.last.line - New_Span.first.line + 1);
      end if;

      declare
         use type VSS.Strings.Virtual_String;

         type LCS_Array is array
           (Natural range 0 .. Old_Length,
            Natural range 0 .. New_Length) of Integer;
         type LCS_Array_Access is access all LCS_Array;

         procedure Free is
           new Ada.Unchecked_Deallocation (LCS_Array, LCS_Array_Access);

         LCS    : LCS_Array_Access := new LCS_Array;
         Match  : Integer;
         Delete : Integer;
         Insert : Integer;

         Old_Index : Natural := Old_Length;
         New_Index : Natural := New_Length;

         Old_Line_Number : Line_Number;
         --  needed to determine which line number in the old buffer is
         --  changed, deleted or before which new lines are inserted

         Changed_Block_Text : VSS.Strings.Virtual_String;
         Changed_Block_Span : LSP.Messages.Span := ((0, 0), (0, 0));

         procedure Prepare
           (Line : Line_Number;
            Text : VSS.Strings.Virtual_String);
         --  Store imformation for Text_Etid in New_String and Span

         procedure Add (From_Line : Line_Number);
         --  Add prepared New_String and Span into Text_Edit

         -------------
         -- Prepare --
         -------------

         procedure Prepare
           (Line : Line_Number;
            Text : VSS.Strings.Virtual_String) is
         begin
            if Changed_Block_Span.last = (0, 0) then
               --  it is the first portion of a changed block so store
               --  last position of the changes
               Changed_Block_Span.last := (Line, 0);
            end if;

            --  accumulating new text for the changed block
            Changed_Block_Text.Prepend (Text);
         end Prepare;

         ---------
         -- Add --
         ---------

         procedure Add (From_Line : Line_Number) is
         begin
            if Changed_Block_Span.last = (0, 0) then
               --  No information for Text_Edit
               return;
            end if;

            Changed_Block_Span.first :=
              (line      => From_Line,
               character => 0);

            LSP.Messages.Prepend
              (Edit, LSP.Messages.TextEdit'
                 (span    => Changed_Block_Span,
                  newText => To_LSP_String (Changed_Block_Text)));

            --  clearing
            Changed_Block_Text.Clear;
            Changed_Block_Span := ((0, 0), (0, 0));
         end Add;

      begin
         --  prepare LCS

         --  default values for line 0
         for Index in 0 .. Old_Length loop
            LCS (Index, 0) := -5 * Index;
         end loop;

         --  default values for the first column
         for Index in 0 .. New_Length loop
            LCS (0, Index) := -5 * Index;
         end loop;

         --  calculate LCS
         for Row in 1 .. Old_Length loop
            for Column in 1 .. New_Length loop
               Match := LCS (Row - 1, Column - 1) +
                 (if Old_Lines (Old_First_Line + Row - 1) =
                      New_Lines (New_First_Line + Column - 1)
                  then 10   --  +10 is the 'weight' for equal lines
                  else -1); --  and -1 for the different

               Delete := LCS (Row - 1, Column) - 5;
               Insert := LCS (Row, Column - 1) - 5;

               LCS (Row, Column) := Integer'Max (Match, Insert);
               LCS (Row, Column) := Integer'Max (LCS (Row, Column), Delete);
            end loop;
         end loop;

         --  iterate over LCS and create Text_Edit

         Old_Line_Number := Line_Number (Old_First_Line + Old_Length - 1);

         while Old_Index > 0
           and then New_Index > 0
         loop
            if LCS (Old_Index, New_Index) =
              LCS (Old_Index - 1, New_Index - 1) +
              (if Old_Lines (Old_First_Line + Old_Index - 1) =
                   New_Lines (New_First_Line + New_Index - 1)
               then 10
               else -1)
            then
               --  both has lines
               if New_Lines.Element (New_First_Line + New_Index - 1) =
                 Old_Lines.Element (Old_First_Line + Old_Index - 1)
               then
                  --  lines are equal, add Text_Edit after current line
                  --  if any is already prepared
                  Add (Old_Line_Number);
               else
                  --  lines are different, change old line by new one,
                  --  we deleted whole line so 'To' position will be
                  --  the beginning of the next line
                  Prepare
                    (Old_Line_Number,
                     New_Lines.Element (New_First_Line + New_Index - 1));
               end if;

               --  move lines cursor backward
               Old_Line_Number := Old_Line_Number - 1;

               New_Index := New_Index - 1;
               Old_Index := Old_Index - 1;

            elsif LCS (Old_Index, New_Index) =
              LCS (Old_Index - 1, New_Index) - 5
            then
               --  line has been deleted, move lines cursor backward
               Prepare (Old_Line_Number, VSS.Strings.Empty_Virtual_String);

               Old_Line_Number := Old_Line_Number - 1;
               Old_Index       := Old_Index - 1;

            elsif LCS (Old_Index, New_Index) =
              LCS (Old_Index, New_Index - 1) - 5
            then
               --  line has been inserted
               --  insert Text_Edit information with insertion after
               --  current line, do not move lines cursor because it is
               --  additional line not present in the old document
               Prepare
                 (Old_Line_Number,
                  New_Lines.Element (New_First_Line + New_Index - 1));

               New_Index := New_Index - 1;
            end if;
         end loop;

         while Old_Index > 0 loop
            --  deleted
            Prepare (Old_Line_Number, VSS.Strings.Empty_Virtual_String);

            Old_Line_Number := Old_Line_Number - 1;
            Old_Index       := Old_Index - 1;
         end loop;

         while New_Index > 0 loop
            --  inserted
            Prepare
              (Old_Line_Number,
               New_Lines.Element (New_First_Line + New_Index - 1));

            New_Index := New_Index - 1;
         end loop;

         Add (Old_Line_Number);
         Free (LCS);

         --  Handle the edge case where the last location of
         --  the edit is trying to affect a non existent line.
         --  The edits are ordered so we only need to check the last one.

         if not Edit.Is_Empty
            and then not Self.Line_To_Marker.Is_Empty
            and then Edit.Last_Element.span.last.line not in
              Self.Line_To_Marker.First_Index .. Self.Line_To_Marker.Last_Index
         then
            declare
               use type VSS.Unicode.UTF16_Code_Unit_Offset;

               Element   : LSP.Messages.TextEdit := Edit.Last_Element;
               Last_Line : constant VSS.Strings.Virtual_String :=
                 Old_Lines (Old_Lines.Length);
               Iterator  :
                 constant VSS.Strings.Character_Iterators.Character_Iterator :=
                   Last_Line.Last_Character;

            begin
               --  Replace the wrong location by the end of the buffer
               Element.span.last :=
                 (line      => Line_Number (Old_Lines.Length - 1),
                  character => Iterator.Last_UTF16_Offset + 1);
               Edit.Replace_Element (Edit.Last, Element);
            end;
         end if;

      exception
         when others =>
            Free (LCS);
            raise;
      end;
   end Diff;

   ----------------
   -- Formatting --
   ----------------

   function Formatting
     (Self     : Document;
      Context  : LSP.Ada_Contexts.Context;
      Span     : LSP.Messages.Span;
      Cmd      : Pp.Command_Lines.Cmd_Line;
      Edit     : out LSP.Messages.TextEdit_Vector)
      return Boolean
   is
      use Utils.Char_Vectors;
      use Utils.Char_Vectors.Char_Vectors;
      use LSP.Types;
      use LSP.Messages;
      use Langkit_Support.Slocs;
      use type LSP.Types.Line_Number;
      use type LSP.Types.UTF_16_Index;

      Input     : Char_Vector;
      Output    : Char_Vector;
      Out_Span  : LSP.Messages.Span;

      Messages  : Pp.Scanner.Source_Message_Vector;

      Sloc : constant Source_Location_Range :=
        (if Span = LSP.Messages.Empty_Span
         then No_Source_Location_Range
         else Make_Range (Self.Get_Source_Location (Span.first),
                          Self.Get_Source_Location (Span.last)));

      Out_Sloc : Source_Location_Range;
      S : GNAT.Strings.String_Access;
   begin
      if Span /= LSP.Messages.Empty_Span then
         --  Align Span to line bounds
         if Span.first.character /= 0 then
            return Self.Formatting
              (Context => Context,
               Span    => ((Span.first.line, 0), Span.last),
               Cmd     => Cmd,
               Edit    => Edit);
         elsif Span.last.character /= 0 then
            return Self.Formatting
              (Context => Context,
               Span    => (Span.first, (Span.last.line + 1, 0)),
               Cmd     => Cmd,
               Edit    => Edit);
         end if;
      end if;

      S := new String'(VSS.Strings.Conversions.To_UTF_8_String (Self.Text));
      Input.Append (S.all);
      GNAT.Strings.Free (S);

      LSP.Lal_Utils.Format_Vector
        (Cmd       => Cmd,
         Input     => Input,
         Node      => Self.Unit (Context).Root,
         In_Sloc   => Sloc,
         Output    => Output,
         Out_Sloc  => Out_Sloc,
         Messages  => Messages);

      if not Messages.Is_Empty then
         return False;
      end if;

      S := new String'(Output.To_Array);
      if Lal_PP_Output.Is_Active then
         Lal_PP_Output.Trace (S.all);
      end if;

      if Span = LSP.Messages.Empty_Span then
         --  diff for the whole document
         Diff
           (Self,
            VSS.Strings.Conversions.To_Virtual_String (S.all),
            Edit => Edit);

      elsif Out_Sloc = No_Source_Location_Range then
         --  Range formating fails. Do nothing, skip formating altogether
         null;
      else
         --  diff for a part of the document

         Out_Span := Self.To_LSP_Range (Out_Sloc);
         Diff
           (Self,
            VSS.Strings.Conversions.To_Virtual_String (S.all),
            Span,
            Out_Span,
            Edit);
      end if;

      GNAT.Strings.Free (S);
      return True;

   exception
      when others =>
         GNAT.Strings.Free (S);
         return False;
   end Formatting;

   ------------------------
   -- Get_Imported_Units --
   ------------------------

   procedure Get_Imported_Units
     (Self          : Document;
      Context       : LSP.Ada_Contexts.Context;
      Project_URI   : LSP.Types.LSP_URI;
      Show_Implicit : Boolean;
      Result        : out LSP.Messages.ALS_Unit_Description_Vector)
   is
      Unit     : constant Libadalang.Analysis.Analysis_Unit :=
        LSP.Ada_Documents.Unit (Self    => Self,
                                Context => Context);
      Root     : constant Ada_Node := Unit.Root;

      procedure Append_Units
        (Units : Libadalang.Analysis.Compilation_Unit_Array);

      ------------------
      -- Append_Units --
      ------------------

      procedure Append_Units
        (Units : Libadalang.Analysis.Compilation_Unit_Array) is
      begin
         for Unit of Units loop
            Result.Append
              (LSP.Messages.ALS_Unit_Description'
                 (uri        => LSP.Types.File_To_URI (Unit.Unit.Get_Filename),
                  projectUri => Project_URI));
         end loop;
      end Append_Units;

   begin

      case Root.Kind is
         when Libadalang.Common.Ada_Compilation_Unit_Range =>
            declare
               Comp_Unit    : constant Compilation_Unit :=
                 As_Compilation_Unit (Root);
               Units        : constant Compilation_Unit_Array :=
                 (if Show_Implicit then
                     Comp_Unit.P_Unit_Dependencies
                  else
                     Comp_Unit.P_Withed_Units);
            begin
               Append_Units (Units);
            end;

         when Libadalang.Common.Ada_Compilation_Unit_List_Range =>
            declare
               Comp_Unit_List : constant Compilation_Unit_List :=
                 As_Compilation_Unit_List (Root);
            begin
               for Comp_Unit of Comp_Unit_List loop
                  Append_Units
                    (if Show_Implicit then
                        Comp_Unit.P_Withed_Units
                     else
                        Comp_Unit.P_Unit_Dependencies);
               end loop;
            end;
         when others =>
            null;
      end case;
   end Get_Imported_Units;

   -------------------------
   -- Get_Importing_Units --
   -------------------------

   procedure Get_Importing_Units
     (Self          : Document;
      Context       : LSP.Ada_Contexts.Context;
      Project_URI   : LSP.Types.LSP_URI;
      Show_Implicit : Boolean;
      Result        : out LSP.Messages.ALS_Unit_Description_Vector)
   is

      Root : constant Ada_Node := Self.Unit (Context).Root;

      procedure Append_Units
        (Units : Libadalang.Analysis.Analysis_Unit_Array);

      ------------------
      -- Append_Units --
      ------------------

      procedure Append_Units
        (Units : Libadalang.Analysis.Analysis_Unit_Array) is
      begin
         for Unit of Units loop
            Result.Append
              (LSP.Messages.ALS_Unit_Description'
                 (uri        => LSP.Types.File_To_URI (Unit.Get_Filename),
                  projectUri => Project_URI));
         end loop;
      end Append_Units;

   begin

      case Root.Kind is
         when Libadalang.Common.Ada_Compilation_Unit_Range =>
            declare
               Comp_Unit : constant Compilation_Unit :=
                 As_Compilation_Unit (Root);
               Importing_Units  : constant
                 Libadalang.Analysis.Analysis_Unit_Array :=
                   Comp_Unit.P_Filter_Is_Imported_By
                     (Units      => Context.Analysis_Units,
                      Transitive => Show_Implicit);
            begin
               Append_Units (Importing_Units);
            end;

         when Libadalang.Common.Ada_Compilation_Unit_List_Range =>
            declare
               Comp_Unit_List : constant Compilation_Unit_List :=
                 As_Compilation_Unit_List (Root);
            begin
               for Comp_Unit of Comp_Unit_List loop
                  Append_Units
                    (Comp_Unit.P_Filter_Is_Imported_By
                       (Units      => Context.Analysis_Units,
                        Transitive => Show_Implicit));
               end loop;
            end;
         when others =>
            null;
      end case;
   end Get_Importing_Units;

   -------------------------
   -- Find_All_References --
   -------------------------

   procedure Find_All_References
     (Self       : Document;
      Context    : LSP.Ada_Contexts.Context;
      Definition : Libadalang.Analysis.Defining_Name;
      Callback   : not null access procedure
        (Base_Id : Libadalang.Analysis.Base_Id;
         Kind    : Libadalang.Common.Ref_Result_Kind;
         Cancel  : in out Boolean))
   is
      Units : constant Libadalang.Analysis.Analysis_Unit_Array :=
        (1 =>  LSP.Ada_Documents.Unit (Self    => Self,
                                       Context => Context));
   begin
      LSP.Ada_Id_Iterators.Find_All_References (Definition, Units, Callback);
   exception
      when E : Libadalang.Common.Property_Error =>
         Log (Self.Trace, E, "in Find_All_References");
   end Find_All_References;

   ----------------
   -- Get_Errors --
   ----------------

   procedure Get_Errors
     (Self    : Document;
      Context : LSP.Ada_Contexts.Context;
      Changed : out Boolean;
      Errors  : out LSP.Messages.Diagnostic_Vector) is
   begin
      Errors.Clear;
      Changed := (for some Source of Self.Diagnostic_Sources =>
                    Source.Has_New_Diagnostic (Context));

      if Changed then
         for Source of Self.Diagnostic_Sources loop
            Source.Get_Diagnostic (Context, Errors);
         end loop;
      end if;
   end Get_Errors;

   ---------------------
   -- Has_Diagnostics --
   ---------------------

   function Has_Diagnostics
     (Self    : Document;
      Context : LSP.Ada_Contexts.Context)
      return Boolean is
   begin
      return Self.Unit (Context).Has_Diagnostics;
   end Has_Diagnostics;

   --------------------------
   -- Get_Symbol_Hierarchy --
   --------------------------

   procedure Get_Symbol_Hierarchy
     (Self     : Document;
      Context  : LSP.Ada_Contexts.Context;
      Pattern  : LSP.Search.Search_Pattern'Class;
      Canceled : access function return Boolean;
      Result   : out LSP.Messages.Symbol_Vector)
   is
      use LSP.Messages;

      procedure Walk
        (Node         : Libadalang.Analysis.Ada_Node;
         Cursor       : LSP.Messages.DocumentSymbol_Trees.Cursor;
         Nested_Level : Integer;
         Tree         : in out LSP.Messages.DocumentSymbol_Tree);
      --  Traverse Node and all its children recursively. Find any defining
      --  name and construct corresponding symbol node, then append it to
      --  the Tree under a position pointed by the Cursor.

      ----------
      -- Walk --
      ----------

      procedure Walk
        (Node         : Libadalang.Analysis.Ada_Node;
         Cursor       : LSP.Messages.DocumentSymbol_Trees.Cursor;
         Nested_Level : Integer;
         Tree         : in out LSP.Messages.DocumentSymbol_Tree)
      is
         Next             : LSP.Messages.DocumentSymbol_Trees.Cursor := Cursor;
         Dummy            : LSP.Messages.DocumentSymbol_Trees.Cursor;
         --  Dummy is used for node which can't be parents like pragma and with
         --  statements
         New_Nested_Level : Integer := Nested_Level;
      begin
         if Node = No_Ada_Node
           or else Node.Kind in Libadalang.Common.Ada_Expr
           or else Canceled.all
         then
            return;
         end if;

         if Node.Kind in Libadalang.Common.Ada_Basic_Decl then
            declare
               Decl : constant Libadalang.Analysis.Basic_Decl :=
                 Node.As_Basic_Decl;

               Kind : constant LSP.Messages.SymbolKind :=
                 LSP.Lal_Utils.Get_Decl_Kind
                   (Decl, Ignore_Local => Nested_Level > 1);

            begin
               if Kind /= LSP.Messages.A_Null then
                  New_Nested_Level := New_Nested_Level + 1;
                  declare
                     Names : constant Libadalang.Analysis.Defining_Name_Array
                       := Decl.P_Defining_Names;
                  begin

                     for Name of Names loop
                        exit when Name = Libadalang.Analysis.No_Defining_Name;

                        if Pattern.Match
                          (LSP.Lal_Utils.To_Virtual_String (Name.Text))
                        then
                           declare
                              Is_Function : Boolean;
                              Profile : constant VSS.Strings.Virtual_String :=
                                Get_Profile (Decl, Is_Function);
                              Item : constant LSP.Messages.DocumentSymbol :=
                                (name              =>
                                   LSP.Lal_Utils.To_Virtual_String (Name.Text),
                                 detail            =>
                                   (Is_Set => True,
                                    Value  => LSP.Types.To_LSP_String
                                      (Profile)),
                                 kind              => Kind,
                                 deprecated        => (Is_Set => False),
                                 tags              => LSP.Messages.Empty,
                                 span              => LSP.Lal_Utils.To_Span
                                   (Node.Sloc_Range),
                                 selectionRange    => LSP.Lal_Utils.To_Span
                                   (Name.Sloc_Range),
                                 alsIsDeclaration  =>
                                   (Is_Set => True,
                                    Value  => Is_Declaration (Decl)),
                                 alsIsAdaProcedure =>
                                   (if Is_Function
                                    then (Is_Set => False)
                                    else (Is_Set => True, Value => True)),
                                 alsVisibility     =>
                                   (Is_Set => True,
                                    Value  => Get_Visibility (Decl)),
                                 children          => True);
                           begin
                              Tree.Insert_Child
                                (Parent   => Cursor,
                                 Before   =>
                                   Messages.DocumentSymbol_Trees.No_Element,
                                 New_Item => Item,
                                 Position => Next);
                           end;
                        end if;
                     end loop;
                  end;
               end if;
            end;

         elsif Pattern.Get_Kind /= Start_Word_Text
           and then Node.Kind in Libadalang.Common.Ada_With_Clause_Range
         then
            declare
               With_Node : constant Libadalang.Analysis.With_Clause :=
                 Node.As_With_Clause;
            begin
               for N of With_Node.F_Packages loop
                  declare
                     Item : constant LSP.Messages.DocumentSymbol :=
                       (name              =>
                          LSP.Lal_Utils.To_Virtual_String (N.Text),
                        detail            => (Is_Set => False),
                        kind              => Namespace,
                        tags              => LSP.Messages.Empty,
                        deprecated        => (Is_Set => False),
                        span              => LSP.Lal_Utils.To_Span
                          (Node.Sloc_Range),
                        selectionRange    => LSP.Lal_Utils.To_Span
                          (N.Sloc_Range),
                        alsIsDeclaration  => (Is_Set => False),
                        alsIsAdaProcedure => (Is_Set => False),
                        alsVisibility     => (Is_Set => False),
                        children          => False);
                  begin
                     Tree.Insert_Child
                       (Parent   => Next,
                        Before   =>
                          Messages.DocumentSymbol_Trees.No_Element,
                        New_Item => Item,
                        Position => Dummy);
                  end;
               end loop;
            end;

         elsif Pattern.Get_Kind /= Start_Word_Text
           and then Nested_Level <=  1
           and then Node.Kind in Libadalang.Common.Ada_Pragma_Node
         then
            declare
               Pragma_Node : constant Libadalang.Analysis.Pragma_Node :=
                 Node.As_Pragma_Node;
               Id          : constant Libadalang.Analysis.Identifier  :=
                 Pragma_Node.F_Id;
               Item : constant LSP.Messages.DocumentSymbol :=
                 (name              =>
                    LSP.Lal_Utils.To_Virtual_String (Id.Text),
                  detail            =>
                    (Is_Set => True,
                     Value  =>
                       LSP.Types.To_LSP_String
                         (LSP.Lal_Utils.To_Virtual_String
                              ("(" & (Pragma_Node.F_Args.Text & ")")))),
                  kind              => Property,
                  tags              => LSP.Messages.Empty,
                  deprecated        => (Is_Set => False),
                  span              => LSP.Lal_Utils.To_Span
                    (Node.Sloc_Range),
                  selectionRange    => LSP.Lal_Utils.To_Span
                    (Id.Sloc_Range),
                  alsIsDeclaration  => (Is_Set => False),
                  alsIsAdaProcedure => (Is_Set => False),
                  alsVisibility     => (Is_Set => False),
                  children          => False);
            begin
               Tree.Insert_Child
                 (Parent   => Next,
                  Before   =>
                    Messages.DocumentSymbol_Trees.No_Element,
                  New_Item => Item,
                  Position => Dummy);
            end;
         end if;

         for Child of Node.Children loop
            if Child not in Libadalang.Analysis.No_Ada_Node then
               Walk (Child, Next, New_Nested_Level, Tree);
               exit when Canceled.all;
            end if;
         end loop;
      end Walk;

      Root : constant Libadalang.Analysis.Ada_Node := Self.Unit (Context).Root;
   begin
      Result := (Is_Tree => True, others => <>);
      Walk (Root, Result.Tree.Root, 0, Result.Tree);
   end Get_Symbol_Hierarchy;

   -----------------
   -- Get_Symbols --
   -----------------

   procedure Get_Symbols
     (Self     : Document;
      Context  : LSP.Ada_Contexts.Context;
      Pattern  : LSP.Search.Search_Pattern'Class;
      Canceled : access function return Boolean;
      Result   : out LSP.Messages.Symbol_Vector)
   is
      use LSP.Messages;
      Element : Libadalang.Analysis.Ada_Node;

      Is_Defining_Name : constant Libadalang.Iterators.Ada_Node_Predicate :=
        Libadalang.Iterators.Kind_Is (Libadalang.Common.Ada_Defining_Name);
      --  This object will be deallocated by Cursor's finalization

      Cursor : Libadalang.Iterators.Traverse_Iterator'Class :=
        Libadalang.Iterators.Find
          (Self.Unit (Context).Root, Is_Defining_Name);

   begin
      Result := LSP.Messages.Symbol_Vector'
        (Is_Tree => False,
         Vector  => <>);

      while not Canceled.all
        and then Cursor.Next (Element)
      loop
         declare
            Item : LSP.Messages.SymbolInformation;
            Kind : constant LSP.Messages.SymbolKind :=
              LSP.Lal_Utils.Get_Decl_Kind
                (Element.As_Defining_Name.P_Basic_Decl, Ignore_Local => True);
         begin
            if Kind /= LSP.Messages.A_Null
              and then Pattern.Match
                (LSP.Lal_Utils.To_Virtual_String (Element.Text))
            then
               Item :=
                 (name              =>
                    LSP.Lal_Utils.To_Virtual_String (Element.Text),
                  kind              => Kind,
                  alsIsAdaProcedure => <>,
                  tags              => LSP.Messages.Empty,
                  deprecated        => <>,
                  location          =>
                    (uri     => Self.URI,
                     span    => LSP.Lal_Utils.To_Span (Element.Sloc_Range),
                     alsKind => LSP.Messages.Empty_Set),
                  containerName     => <>);

               Result.Vector.Append (Item);
            end if;
         end;
      end loop;
   end Get_Symbols;

   ---------------------
   -- Line_Terminator --
   ---------------------

   function Line_Terminator (Self : Document'Class) return String is
   begin
      if Self.Line_Terminator.Is_Empty then
         --  Document has no line terminator yet, return LF as most used
         return (1 => Ada.Characters.Latin_1.LF);
      else
         return VSS.Strings.Conversions.To_UTF_8_String (Self.Line_Terminator);
      end if;
   end Line_Terminator;

   -----------------
   -- Get_Node_At --
   -----------------

   function Get_Node_At
     (Self     : Document;
      Context  : LSP.Ada_Contexts.Context;
      Position : LSP.Messages.Position)
      return Libadalang.Analysis.Ada_Node
   is
      use Langkit_Support.Slocs;

      Unit : constant Libadalang.Analysis.Analysis_Unit := Self.Unit (Context);
      Sloc : constant Langkit_Support.Slocs.Source_Location :=
        Self.Get_Source_Location (Position);
   begin
      if Unit.Root = No_Ada_Node then
         return No_Ada_Node;
      end if;

      return Unit.Root.Lookup (Sloc);
   end Get_Node_At;

   ------------------------
   -- Get_Folding_Blocks --
   ------------------------

   procedure Get_Folding_Blocks
     (Self       : Document;
      Context    : LSP.Ada_Contexts.Context;
      Lines_Only : Boolean;
      Comments   : Boolean;
      Result     : out LSP.Messages.FoldingRange_Vector)
   is
      use Libadalang.Common;

      Location     : LSP.Messages.Location;
      foldingRange : LSP.Messages.FoldingRange;
      Have_With    : Boolean := False;

      function Parse (Node : Ada_Node'Class) return Visit_Status;
      --  Includes Node location to the result if the node has "proper" kind

      procedure Store_Span (Span : LSP.Messages.Span);
      --  Include Span to the result .

      -----------
      -- Parse --
      -----------

      function Parse (Node : Ada_Node'Class) return Visit_Status
      is

         procedure Store_With_Block;
         --  Store folding for with/use clauses as one folding block

         ----------------------
         -- Store_With_Block --
         ----------------------

         procedure Store_With_Block is
            use type LSP.Types.Line_Number;
         begin
            if not Have_With then
               return;
            end if;

            if foldingRange.startLine /= foldingRange.endLine then
               Result.Append (foldingRange);
            end if;

            Have_With := False;
         end Store_With_Block;

         Result : Visit_Status := Into;
      begin
--        Cat_Namespace,
--        Cat_Constructor,
--        Cat_Destructor,
--        Cat_Structure,
--        Cat_Case_Inside_Record,
--        Cat_Union,
--        Cat_Custom

         case Node.Kind is
            when Ada_Package_Decl |
                 Ada_Generic_Formal_Package |
                 Ada_Package_Body |
--        Cat_Package

                 Ada_Type_Decl |

                 Ada_Classwide_Type_Decl |
--        Cat_Class

                 Ada_Protected_Type_Decl |
--        Cat_Protected

                 Ada_Task_Type_Decl |
                 Ada_Single_Task_Type_Decl |
--        Cat_Task

                 Ada_Subp_Decl |
                 Ada_Subp_Body |
                 Ada_Generic_Formal_Subp_Decl |
                 Ada_Abstract_Subp_Decl |
                 Ada_Abstract_Formal_Subp_Decl |
                 Ada_Concrete_Formal_Subp_Decl |
                 Ada_Generic_Subp_Internal |
                 Ada_Null_Subp_Decl |
                 Ada_Subp_Renaming_Decl |
                 Ada_Subp_Body_Stub |
                 Ada_Generic_Subp_Decl |
                 Ada_Generic_Subp_Instantiation |
                 Ada_Generic_Subp_Renaming_Decl |
                 Ada_Subp_Kind_Function |
                 Ada_Subp_Kind_Procedure |
                 Ada_Access_To_Subp_Def |
--        Cat_Procedure
--        Cat_Function
--        Cat_Method

                 Ada_Case_Stmt |
--        Cat_Case_Statement

                 Ada_If_Stmt |
--        Cat_If_Statement

                 Ada_For_Loop_Stmt |
                 Ada_While_Loop_Stmt |
--        Cat_Loop_Statement

                 Ada_Begin_Block |
                 Ada_Decl_Block |
--        Cat_Declare_Block
--        Cat_Simple_Block

--                 Ada_Return_Stmt |
--                 Ada_Extended_Return_Stmt |
                 Ada_Extended_Return_Stmt_Object_Decl |
--        Cat_Return_Block

                 Ada_Select_Stmt |
--        Cat_Select_Statement

                 Ada_Entry_Body |
--        Cat_Entry

                 Ada_Exception_Handler |
--        Cat_Exception_Handler

                 Ada_Pragma_Node_List |
                 Ada_Pragma_Argument_Assoc |
                 Ada_Pragma_Node |
--        Cat_Pragma

                 Ada_Aspect_Spec =>
--        Cat_Aspect

               Store_With_Block;

               foldingRange.kind :=
                 (Is_Set => True, Value => LSP.Messages.Region);

               Location := LSP.Lal_Utils.Get_Node_Location (Ada_Node (Node));
               Store_Span (Location.span);

            when Ada_With_Clause |
                 Ada_Use_Package_Clause |
                 Ada_Use_Type_Clause =>

               Location := LSP.Lal_Utils.Get_Node_Location (Ada_Node (Node));

               if not Have_With then
                  Have_With := True;

                  foldingRange.kind :=
                    (Is_Set => True, Value => LSP.Messages.Imports);

                  foldingRange.startLine := Location.span.first.line;
               end if;

               foldingRange.endLine := Location.span.last.line;

               --  Do not step into with/use clause
               Result := Over;

            when others =>
               Store_With_Block;
         end case;

         return Result;
      end Parse;

      ----------------
      -- Store_Span --
      ----------------

      procedure Store_Span (Span : LSP.Messages.Span) is
         use type LSP.Types.Line_Number;
      begin
         if not Lines_Only
           or else Span.first.line /= Span.last.line
         then
            foldingRange.startLine := Span.first.line;
            foldingRange.endLine   := Span.last.line;

            if not Lines_Only then
               foldingRange.startCharacter :=
                 (Is_Set => True,
                  Value  => LSP.Types.LSP_Number (Span.first.character));

               foldingRange.startCharacter :=
                 (Is_Set => True,
                  Value  => LSP.Types.LSP_Number (Span.last.character));
            end if;

            Result.Append (foldingRange);
         end if;
      end Store_Span;

      Token : Token_Reference;
      Span  : LSP.Messages.Span;

   begin
      Traverse (Self.Unit (Context).Root, Parse'Access);

      if not Comments then
         --  do not process comments
         return;
      end if;

      --  Looking for comments
      foldingRange.kind := (Is_Set => False);
      Token             := First_Token (Self.Unit (Context));

      while Token /= No_Token loop
         case Kind (Data (Token)) is
            when Ada_Comment =>
               if not foldingRange.kind.Is_Set then
                  foldingRange.kind :=
                    (Is_Set => True, Value => LSP.Messages.Comment);
                  Span := LSP.Lal_Utils.Get_Token_Span (Token);
               else
                  Span.last := LSP.Lal_Utils.Get_Token_Span (Token).last;
               end if;

            when Ada_Whitespace =>
               null;

            when others =>
               if foldingRange.kind.Is_Set then
                  Store_Span (Span);
                  foldingRange.kind := (Is_Set => False);
               end if;
         end case;

         Token := Next (Token);
      end loop;
   end Get_Folding_Blocks;

   -----------------
   -- Get_Profile --
   -----------------

   function Get_Profile
     (Node        : Libadalang.Analysis.Basic_Decl;
      Is_Function : out Boolean) return VSS.Strings.Virtual_String
   is
      use Libadalang.Common;

      function To_Text
        (Node : Ada_Node'Class) return VSS.Strings.Virtual_String;
      --  Retrieve the node text and format it

      function To_Profile
        (Node : Libadalang.Analysis.Subp_Spec'Class)
         return VSS.Strings.Virtual_String;

      -------------
      -- To_Text --
      -------------

      function To_Text
        (Node : Ada_Node'Class) return VSS.Strings.Virtual_String
      is
         Node_Text : constant Langkit_Support.Text.Text_Type := Node.Text;
         Was_Space : Boolean := False;
         Result    : VSS.Strings.Virtual_String;

      begin
         for I in Node_Text'Range loop
            if Node_Text (I) = ' ' then
               --  Trim multiple whitespace to only keep one

               if not Was_Space then
                  Result.Append
                    (VSS.Characters.Virtual_Character (Node_Text (I)));
               end if;

               Was_Space := True;

               --  Remove the new line character

            elsif Node_Text (I) /= Ada.Characters.Wide_Wide_Latin_1.LF then
               Was_Space := False;
                  Result.Append
                    (VSS.Characters.Virtual_Character (Node_Text (I)));
            end if;
         end loop;

         return Result;
      end To_Text;

      ----------------
      -- To_Profile --
      ----------------

      function To_Profile
        (Node : Libadalang.Analysis.Subp_Spec'Class)
         return VSS.Strings.Virtual_String
      is
         Result  : VSS.Strings.Virtual_String;
         Params  : constant Param_Spec_Array := Node.P_Params;
         Returns : constant Type_Expr := Node.F_Subp_Returns;

      begin
         if Params'Length > 0 then
            Result.Append ('(');
         end if;

         for Param of Params loop
            declare
               use type VSS.Strings.Character_Count;

               Names : constant Defining_Name_List := Param.F_Ids;
               Init  : constant Expr := Param.F_Default_Expr;
               Item  : VSS.Strings.Virtual_String;

            begin
               Item.Append (" :");

               case Param.F_Mode is
                  when Ada_Mode_Default | Ada_Mode_In =>
                     Item.Append (" in ");
                  when Ada_Mode_In_Out =>
                     Item.Append (" in out ");
                  when Ada_Mode_Out =>
                     Item.Append (" out ");
               end case;

               Item.Append (To_Text (Param.F_Type_Expr));

               if not Init.Is_Null then
                  Item.Append (" := ");
                  Item.Append (To_Text (Init));
               end if;

               for J in Names.First_Child_Index .. Names.Last_Child_Index loop
                  if Result.Character_Length /= 1 then
                     Result.Append ("; ");
                  end if;

                  Result.Append (To_Text (Names.Child (J)));
                  Result.Append (Item);
               end loop;
            end;
         end loop;

         if Params'Length > 0 then
            Result.Append (')');
         end if;

         if not Returns.Is_Null then
            Is_Function := True;
            Result.Append (" return ");
            Result.Append (To_Text (Returns));
         end if;

         return Result;
      end To_Profile;

   begin
      Is_Function := False;

      case Node.Kind is
         when Ada_Classic_Subp_Decl =>
            return To_Profile (Node.As_Classic_Subp_Decl.F_Subp_Spec);
         when Ada_Base_Subp_Body    =>
            return To_Profile (Node.As_Base_Subp_Body.F_Subp_Spec);
         when Ada_Generic_Subp_Decl =>
            return To_Profile
              (Node.As_Generic_Subp_Decl.F_Subp_Decl.F_Subp_Spec);
         when others =>
            return VSS.Strings.Empty_Virtual_String;
      end case;
   end Get_Profile;

   --------------------
   -- Is_Declaration --
   --------------------

   function Is_Declaration
     (Node : Libadalang.Analysis.Basic_Decl) return Boolean
   is
      use Libadalang.Common;
   begin
      case Node.Kind is
         when Ada_Base_Package_Decl |
              Ada_Generic_Package_Decl |
              Ada_Generic_Package_Instantiation |
              Ada_Generic_Package_Renaming_Decl |
              Ada_Package_Renaming_Decl |
              Ada_Abstract_Subp_Decl |
              Ada_Formal_Subp_Decl |
              Ada_Subp_Decl |
              Ada_Subp_Renaming_Decl |
              Ada_Generic_Subp_Instantiation |
              Ada_Generic_Subp_Renaming_Decl |
              Ada_Generic_Subp_Decl |
              Ada_Null_Subp_Decl |
              Ada_Expr_Function |
              Ada_Protected_Type_Decl |
              Ada_Single_Protected_Decl |
              Ada_Entry_Decl |
              Ada_Type_Decl |
              Ada_Single_Task_Decl |
              Ada_Task_Type_Decl =>
            return True;
         when others =>
            return False;
      end case;
   end Is_Declaration;

   --------------------
   -- Get_Visibility --
   --------------------

   function Get_Visibility
     (Node : Libadalang.Analysis.Basic_Decl)
      return LSP.Messages.Als_Visibility
   is
      use Libadalang.Common;
   begin
      for Parent of Node.Parents loop
         if Parent.Kind = Ada_Private_Part then
            return LSP.Messages.Als_Private;
         elsif Parent.Kind in Ada_Protected_Body | Ada_Protected_Def then
            return LSP.Messages.Als_Protected;
         end if;
      end loop;
      return LSP.Messages.Als_Public;
   end Get_Visibility;

   -------------------------
   -- Get_Source_Location --
   -------------------------

   function Get_Source_Location
     (Self     : Document'Class;
      Position : LSP.Messages.Position)
      return Langkit_Support.Slocs.Source_Location
   is
      use type LSP.Types.Line_Number;
      use type VSS.Unicode.UTF16_Code_Unit_Offset;
      use type VSS.Strings.Character_Index;

      Iterator : VSS.Strings.Character_Iterators.Character_Iterator :=
        Self.Text.Character (Self.Line_To_Marker (Position.line));

      Line_Offset : constant VSS.Unicode.UTF16_Code_Unit_Offset :=
        Iterator.First_UTF16_Offset;

      Line_First_Character : constant VSS.Strings.Character_Index :=
        Iterator.Character_Index;
   begin
      while Iterator.First_UTF16_Offset - Line_Offset <= Position.character
        and then Iterator.Forward
      loop
         null;
      end loop;

      return ((Line   => Langkit_Support.Slocs.Line_Number (Position.line + 1),
               Column => Langkit_Support.Slocs.Column_Number
                 (Iterator.Character_Index - Line_First_Character)));
   end Get_Source_Location;

   ------------------
   -- Get_Token_At --
   ------------------

   function Get_Token_At
     (Self     : Document'Class;
      Context  : LSP.Ada_Contexts.Context;
      Position : LSP.Messages.Position)
      return Libadalang.Common.Token_Reference
   is
      Unit : constant Libadalang.Analysis.Analysis_Unit :=
        Self.Unit (Context);

      Token : constant Libadalang.Common.Token_Reference :=
        Unit.Lookup_Token (Self.Get_Source_Location (Position));
   begin
      return Token;
   end Get_Token_At;

   -----------------
   -- Get_Word_At --
   -----------------

   function Get_Word_At
     (Self     : Document;
      Context  : LSP.Ada_Contexts.Context;
      Position : LSP.Messages.Position)
      return VSS.Strings.Virtual_String
   is
      use Langkit_Support.Slocs;
      use all type Libadalang.Common.Token_Kind;

      Result : VSS.Strings.Virtual_String;

      Unit : constant Libadalang.Analysis.Analysis_Unit :=
        Self.Unit (Context);

      Origin : constant Source_Location := Self.Get_Source_Location (Position);
      Where : constant Source_Location := (Origin.Line, Origin.Column - 1);
      --  Compute the position we want for completion, which is one character
      --  before the cursor.

      Token : constant Libadalang.Common.Token_Reference :=
        Unit.Lookup_Token (Where);

      Data : constant Libadalang.Common.Token_Data_Type :=
        Libadalang.Common.Data (Token);

      Kind : constant Libadalang.Common.Token_Kind :=
        Libadalang.Common.Kind (Data);

      Text : constant Langkit_Support.Text.Text_Type :=
        Libadalang.Common.Text (Token);

      Sloc : constant Source_Location_Range :=
        Libadalang.Common.Sloc_Range (Data);

      Span : constant Integer :=
        Natural (Where.Column) - Natural (Sloc.Start_Column);

   begin
      if Kind in Ada_Identifier .. Ada_Xor
        and then Compare (Sloc, Where) = Inside
      then
         Result :=
           LSP.Lal_Utils.To_Virtual_String
             (Text (Text'First .. Text'First + Span));
      end if;

      return Result;
   end Get_Word_At;

   ----------------
   -- Initialize --
   ----------------

   procedure Initialize
     (Self       : in out Document;
      URI        : LSP.Messages.DocumentUri;
      Text       : VSS.Strings.Virtual_String;
      Diagnostic : LSP.Diagnostic_Sources.Diagnostic_Source_Access)
   is
   begin
      Self.URI  := URI;
      Self.Version := 1;
      Self.Text := Text;
      Self.Refresh_Symbol_Cache := True;
      Self.Diagnostic_Sources (1) := new
        LSP.Ada_Documents.LAL_Diagnostics.Diagnostic_Source
          (Self'Unchecked_Access);
      Self.Diagnostic_Sources (2) := Diagnostic;
      Recompute_Indexes (Self);
   end Initialize;

   ------------------------
   -- Reset_Symbol_Cache --
   ------------------------

   procedure Reset_Symbol_Cache (Self : in out Document'Class) is
   begin
      for Item of Self.Symbol_Cache loop
         --  We clear defining name vectors, but keep symbol map in hope, that
         --  we will reuse the same elements after reindexing in
         --  Refresh_Symbol_Cache call, so we avoid memory reallocation.
         Item.Clear;
      end loop;

      Self.Refresh_Symbol_Cache := True;
   end Reset_Symbol_Cache;

   -----------------------------
   -- Compute_Completion_Item --
   -----------------------------

   function Compute_Completion_Item
     (Context                  : LSP.Ada_Contexts.Context;
      BD                       : Libadalang.Analysis.Basic_Decl;
      Label                    : VSS.Strings.Virtual_String;
      Use_Snippets             : Boolean;
      Compute_Doc_And_Details  : Boolean;
      Named_Notation_Threshold : Natural;
      Is_Dot_Call              : Boolean;
      Is_Visible               : Boolean;
      Pos                      : Integer;
      Completions_Count        : Natural)
      return LSP.Messages.CompletionItem
   is
      use LSP.Types;
      use LSP.Messages;

      Item           : CompletionItem;
      Subp_Spec_Node : Base_Subp_Spec;
      Min_Width      : constant Natural := Completions_Count'Img'Length - 1;
      --  The -1 remove the whitespace added by 'Img

      function Get_Sort_text (Base_Label : LSP_String) return LSP_String;
      --  Return a suitable sortText according to the completion item's
      --  visibility and position in the completion list.

      -------------------
      -- Get_Sort_text --
      -------------------

      function Get_Sort_text (Base_Label : LSP_String) return LSP_String is
         Sort_Text : LSP_String := Empty_LSP_String;
      begin

         if Pos /= -1 then
            Sort_Text :=
              To_LSP_String
                (GNATCOLL.Utils.Image (Pos, Min_Width => Min_Width))
                & Sort_Text;
         end if;

         Sort_Text := Sort_Text & Base_Label;

         if not Is_Visible then
            Sort_Text := "~" & Sort_Text;
         end if;

         return Sort_Text;
      end Get_Sort_text;

   begin
      Item.label := Label;
      Item.kind := (True, To_Completion_Kind
                            (LSP.Lal_Utils.Get_Decl_Kind (BD)));

      declare
         Base_Label : constant LSP_String := LSP.Types.To_LSP_String
           (Item.label);
         Sort_Text  : constant LSP_String := Get_Sort_text (Base_Label);
      begin
         if not Is_Visible then
            Item.insertText := (True, Base_Label);
            Item.label.Append (" (invisible)");
            Item.filterText := (True, Base_Label);
         end if;

         --  Set the sortText if needed
         if Sort_Text /= Empty_LSP_String then
            Item.sortText := (True, Sort_Text);
         end if;
      end;

      Set_Completion_Item_Documentation
        (Context                 => Context,
         BD                      => BD,
         Item                    => Item,
         Compute_Doc_And_Details => Compute_Doc_And_Details);

      --  Return immediately if we should not use snippets (e.g: completion for
      --  invisible symbols).
      if not Use_Snippets then
         return Item;
      end if;

      --  Check if we are dealing with a subprogram and return a completion
      --  snippet that lists all the formal parameters if it's the case.

      Subp_Spec_Node := BD.P_Subp_Spec_Or_Null;

      if Subp_Spec_Node.Is_Null then
         return Item;
      end if;

      declare
         Insert_Text : VSS.Strings.Virtual_String := Label;
         All_Params  : constant Param_Spec_Array := Subp_Spec_Node.P_Params;

         Params      : constant Param_Spec_Array :=
           (if Is_Dot_Call then
               All_Params (All_Params'First + 1 .. All_Params'Last)
            else
               All_Params);
         --  Remove the first formal parameter from the list when the dotted
         --  notation is used.

         Idx                : Positive := 1;
         Nb_Params          : Natural := 0;
         Use_Named_Notation : Boolean := False;
      begin

         --  Create a completion snippet if the subprogram expects some
         --  parameters.

         if Params'Length /= 0 then
            Item.insertTextFormat := Optional_InsertTextFormat'
              (Is_Set => True,
               Value  => Snippet);

            Insert_Text.Append (" (");

            --  Compute number of params to know if named notation should be
            --  used.

            for Param of Params loop
               Nb_Params := Nb_Params + Param.F_Ids.Children_Count;
            end loop;

            Use_Named_Notation := Named_Notation_Threshold > 0
              and then Nb_Params >= Named_Notation_Threshold;

            for Param of Params loop
               for Id of Param.F_Ids loop
                  declare
                     Mode : constant Langkit_Support.Text.Text_Type :=
                       Param.F_Mode.Text;

                  begin
                     if Use_Named_Notation then
                        Insert_Text.Append
                          (LSP.Lal_Utils.To_Virtual_String (Id.Text));
                        Insert_Text.Append (" => ");
                        Insert_Text.Append ("${");
                        Insert_Text.Append
                          (VSS.Strings.Conversions.To_Virtual_String
                            (GNATCOLL.Utils.Image (Idx, Min_Width => 1)));
                        Insert_Text.Append (':');
                        Insert_Text.Append
                          (LSP.Lal_Utils.To_Virtual_String (Id.Text));
                        Insert_Text.Append (" : ");
                        Insert_Text.Append
                          ((if Mode /= ""
                             then LSP.Lal_Utils.To_Virtual_String (Mode & " ")
                             else ""));
                        Insert_Text.Append
                          (LSP.Lal_Utils.To_Virtual_String
                             (Param.F_Type_Expr.Text));
                        Insert_Text.Append ("}, ");

                     else
                        Insert_Text.Append ("${");
                        Insert_Text.Append
                          (VSS.Strings.Conversions.To_Virtual_String
                             (GNATCOLL.Utils.Image (Idx, Min_Width => 1)));
                        Insert_Text.Append (':');
                        Insert_Text.Append
                          (LSP.Lal_Utils.To_Virtual_String (Id.Text));
                        Insert_Text.Append (" : ");
                        Insert_Text.Append
                          ((if Mode /= ""
                             then LSP.Lal_Utils.To_Virtual_String (Mode & " ")
                             else ""));
                        Insert_Text.Append
                          (LSP.Lal_Utils.To_Virtual_String
                             (Param.F_Type_Expr.Text));
                        Insert_Text.Append ("}, ");
                     end if;

                     Idx := Idx + 1;
                  end;
               end loop;
            end loop;

            --  Remove the ", " substring that has been appended in the last
            --  loop iteration.

            declare
               First   : constant
                 VSS.Strings.Character_Iterators.Character_Iterator :=
                   Insert_Text.First_Character;
               Last    : VSS.Strings.Character_Iterators.Character_Iterator :=
                 Insert_Text.Last_Character;
               Success : Boolean with Unreferenced;

            begin
               Success := Last.Backward;
               Success := Last.Backward;

               Insert_Text := Insert_Text.Slice (First, Last);
               --  ??? May be replaced by "Head" like procedure when it will be
               --  implemented.
            end;

            --  Insert '$0' (i.e: the final tab stop) at the end.
            Insert_Text.Append (")$0");

            Item.insertText :=
              (Is_Set => True,
               Value  => LSP.Types.To_LSP_String (Insert_Text));
         end if;
      end;

      return Item;
   end Compute_Completion_Item;

   ---------------------------------------
   -- Set_Completion_Item_Documentation --
   ---------------------------------------

   procedure Set_Completion_Item_Documentation
     (Context                 : LSP.Ada_Contexts.Context;
      BD                      : Libadalang.Analysis.Basic_Decl;
      Item                    : in out LSP.Messages.CompletionItem;
      Compute_Doc_And_Details : Boolean)
   is
      use LSP.Messages;
   begin
      --  Compute the 'documentation' and 'detail' fields immediately if
      --  requested (i.e: when the client does not support lazy computation
      --  for these fields).
      if Compute_Doc_And_Details then
         Item.detail :=
           (True,
            LSP.Types.To_LSP_String
              (LSP.Lal_Utils.Compute_Completion_Detail (BD)));

         --  Property_Errors can occur when calling
         --  Get_Documentation on unsupported docstrings, so
         --  add an exception handler to catch them and recover.
         begin
            Item.documentation :=
              (Is_Set => True,
               Value  => String_Or_MarkupContent'
                 (Is_String => True,
                  String    => LSP.Lal_Utils.Compute_Completion_Doc (BD)));

         exception
            when E : Libadalang.Common.Property_Error =>
               LSP.Common.Log (Context.Trace, E);
               Item.documentation := (others => <>);
         end;
      else
         --  Set node's location to the 'data' field of the completion item, so
         --  that we can retrieve it in the completionItem/resolve handler.
         Item.data :=
           (True,
            (uri    => LSP.Types.File_To_URI (BD.Unit.Get_Filename),
             span   => LSP.Lal_Utils.To_Span (BD.Sloc_Range),
             others => <>));
      end if;
   end Set_Completion_Item_Documentation;

   --------------------
   -- Get_Any_Symbol --
   --------------------

   procedure Get_Any_Symbol
     (Self        : in out Document;
      Context     : LSP.Ada_Contexts.Context;
      Pattern     : LSP.Search.Search_Pattern'Class;
      Limit       : Ada.Containers.Count_Type;
      Only_Public : Boolean;
      Canceled    : access function return Boolean;
      Result      : in out LSP.Ada_Completions.Completion_Maps.Map)
   is
      use type LSP.Messages.Search_Kind;

      procedure Refresh_Symbol_Cache;
      procedure Insert (Item : Name_Information);

      --------------------------
      -- Refresh_Symbol_Cache --
      --------------------------

      procedure Refresh_Symbol_Cache is
         use Langkit_Support.Symbols;
         use Libadalang.Common;
         use Libadalang.Iterators;

         Node : Libadalang.Analysis.Ada_Node;

         Global_Visible : constant Libadalang.Iterators.Ada_Node_Predicate :=
           LSP.Lal_Utils.Is_Global_Visible;

         Restricted_Kind : constant Libadalang.Iterators.Ada_Node_Predicate :=
           LSP.Lal_Utils.Is_Restricted_Kind;

         --  Find all definings names excluding private parts and bodies
         It : Libadalang.Iterators.Traverse_Iterator'Class :=
           Libadalang.Iterators.Find
             (Self.Unit (Context).Root,
              Libadalang.Iterators.Kind_Is (Ada_Defining_Name)
                and not Restricted_Kind);

      begin
         while It.Next (Node) loop
            declare
               Token     : constant Token_Reference := Node.Token_End;
               Text      : constant Langkit_Support.Text.Text_Type :=
                 Libadalang.Common.Text (Token);
               Canonical : constant Symbolization_Result :=
                 Libadalang.Sources.Canonicalize (Text);
               Cursor    : Symbol_Maps.Cursor;
               Inserted  : Boolean;

            begin
               if Canonical.Success then
                  Self.Symbol_Cache.Insert
                    (LSP.Lal_Utils.To_Virtual_String (Canonical.Symbol),
                     Name_Vectors.Empty_Vector,
                     Cursor,
                     Inserted);

                  Self.Symbol_Cache (Cursor).Append
                    ((Node.As_Defining_Name,
                     Global_Visible.Unchecked_Get.Evaluate (Node)));
               end if;
            end;
         end loop;
      end Refresh_Symbol_Cache;

      procedure Insert (Item : Name_Information) is
      begin
         if not Result.Contains (Item.Name) and then
           (not Only_Public or else Item.Is_Public)
         then
            Result.Insert
              (Item.Name,
               (Is_Dot_Call  => False,
                Is_Visible   => False,
                Use_Snippets => False,
                Pos          => <>));
         end if;
      end Insert;

      Cursor      : Symbol_Maps.Cursor;
      Use_Celling : constant Boolean :=
        not Pattern.Get_Case_Sensitive
        and then not Pattern.Get_Negate
        and then ((Pattern.Get_Kind = LSP.Messages.Full_Text
                   and then Pattern.Get_Whole_Word)
                  or else Pattern.Get_Kind = LSP.Messages.Start_Word_Text);

   begin
      if Self.Refresh_Symbol_Cache then
         Refresh_Symbol_Cache;
         Self.Refresh_Symbol_Cache := False;
      end if;

      if Use_Celling then
         Cursor := Self.Symbol_Cache.Ceiling (Pattern.Get_Canonical_Pattern);
      else
         Cursor := Self.Symbol_Cache.First;
      end if;

      while Symbol_Maps.Has_Element (Cursor) loop
         if Pattern.Get_Case_Sensitive then
            --  Match each element individually because
            --  Symbol_Cache is case insensitive
            for Item of Self.Symbol_Cache (Cursor) loop
               if Pattern.Match
                 (LSP.Lal_Utils.To_Virtual_String
                    (Item.Name.As_Ada_Node.Text))
               then
                  Insert (Item);
               end if;

               exit when Canceled.all;
            end loop;

         elsif Pattern.Match (Symbol_Maps.Key (Cursor)) then
            --  Symbol_Cache is case insensitive so if the key is matched
            --  this means that all elements are also matched the pattern
            for Item of Self.Symbol_Cache (Cursor) loop
               Insert (Item);

               exit when Canceled.all;
            end loop;

         else
            --  Symbol_Cache is ordered so we will not find any
            --  matches more
            exit when Use_Celling or else Canceled.all;
         end if;

         Symbol_Maps.Next (Cursor);
      end loop;
   end Get_Any_Symbol;

   ------------------------
   -- Get_Completions_At --
   ------------------------

   procedure Get_Completions_At
     (Self      : Document;
      Providers : LSP.Ada_Completions.Completion_Provider_List;
      Context   : LSP.Ada_Contexts.Context;
      Position  : LSP.Messages.Position;
      Names     : out Ada_Completions.Completion_Maps.Map;
      Result    : out LSP.Messages.CompletionList)
   is
      use Libadalang.Common;

      function Completion_Token
        (Sloc  : Langkit_Support.Slocs.Source_Location)
         return Libadalang.Common.Token_Reference;
      --  Get token under completion for given cursor position.
      --  If cursor at the first symbol of a trivia return previous token:
      --  XXX___
      --     ^ cursor just after a token mean user is completion XXX token.

      ----------------------
      -- Completion_Token --
      ----------------------

      function Completion_Token
        (Sloc  : Langkit_Support.Slocs.Source_Location)
         return Libadalang.Common.Token_Reference
      is
         use type Langkit_Support.Slocs.Source_Location;

         Token : constant Libadalang.Common.Token_Reference :=
           Self.Get_Token_At (Context, Position);

         Prev  : constant Libadalang.Common.Token_Reference :=
           (if Token = Libadalang.Common.No_Token
            then Token
            else Libadalang.Common.Previous (Token));

      begin
         if Libadalang.Common.No_Token not in Token | Prev
           and then not Libadalang.Common.Is_Trivia (Prev)
         then
            declare
               Data  : constant Libadalang.Common.Token_Data_Type :=
                 Libadalang.Common.Data (Token);

               Start : constant Langkit_Support.Slocs.Source_Location :=
                 Langkit_Support.Slocs.Start_Sloc
                   (Libadalang.Common.Sloc_Range (Data));
            begin
               if Start = Sloc then
                  return Prev;
               end if;
            end;
         end if;

         return Token;
      end Completion_Token;

      Sloc  : constant Langkit_Support.Slocs.Source_Location :=
        Self.Get_Source_Location (Position);

      Token : constant Libadalang.Common.Token_Reference :=
        Completion_Token (Sloc);

      From  : constant Langkit_Support.Slocs.Source_Location :=
        Langkit_Support.Slocs.Start_Sloc
          (Libadalang.Common.Sloc_Range
             (Libadalang.Common.Data (Token)));

      Root  : constant Libadalang.Analysis.Ada_Node :=
        Self.Unit (Context).Root;

      Node  : constant Libadalang.Analysis.Ada_Node :=
        (if Root = No_Ada_Node then Root else Root.Lookup (From));

      Filter : LSP.Ada_Completions.Filters.Filter;
   begin
      if Node.Kind in Libadalang.Common.Ada_String_Literal_Range then
         --  Do nothing when inside a string
         return;
      end if;

      Context.Trace.Trace
        ("Getting completions, Pos = ("
         & Sloc.Line'Image & ", " & Sloc.Column'Image & ") Node = "
         & Image (Node));

      Filter.Initialize (Token, Node);

      for Provider of Providers loop
         Provider.Propose_Completion
           (Sloc   => Sloc,
            Token  => Token,
            Node   => Node,
            Filter => Filter,
            Names  => Names,
            Result => Result);
      end loop;

      Context.Trace.Trace
        ("Number of filtered completions : " & Names.Length'Image);
   end Get_Completions_At;

   ---------------------
   -- Span_To_Markers --
   ---------------------

   procedure Span_To_Markers
     (Self : Document'Class;
      Span : LSP.Messages.Span;
      From : out VSS.Strings.Markers.Character_Marker;
      To   : out VSS.Strings.Markers.Character_Marker)
   is
      use type VSS.Unicode.UTF16_Code_Unit_Offset;

      J1 : VSS.Strings.Character_Iterators.Character_Iterator :=
        Self.Text.Character (Self.Line_To_Marker (Span.first.line));
      U1 : constant VSS.Unicode.UTF16_Code_Unit_Offset :=
        J1.First_UTF16_Offset;

      J2 : VSS.Strings.Character_Iterators.Character_Iterator :=
        Self.Text.Character (Self.Line_To_Marker (Span.last.line));
      U2 : constant VSS.Unicode.UTF16_Code_Unit_Offset :=
        J2.First_UTF16_Offset;

      Dummy : Boolean;

   begin
      while Span.first.character /= J1.First_UTF16_Offset - U1
        and then J1.Forward
      loop
         null;
      end loop;

      From := J1.Marker;

      while Span.last.character /= J2.First_UTF16_Offset - U2
        and then J2.Forward
      loop
         null;
      end loop;

      Dummy := J2.Backward;
      To    := J2.Marker;
   end Span_To_Markers;

   ------------------
   -- To_LSP_Range --
   ------------------

   function To_LSP_Range
     (Self    : Document;
      Segment : Langkit_Support.Slocs.Source_Location_Range)
      return LSP.Messages.Span
   is

      use type LSP.Types.Line_Number;

      Start_Line      : constant LSP.Types.Line_Number :=
        LSP.Types.Line_Number (Segment.Start_Line) - 1;
      Start_Line_Text : constant VSS.Strings.Virtual_String :=
        Self.Text.Slice
          (Self.Line_To_Marker (Start_Line),
           Self.Line_To_Marker (Start_Line + 1));
      Start_Iterator  : VSS.Strings.Character_Iterators.Character_Iterator :=
        Start_Line_Text.First_Character;

      End_Line        : constant LSP.Types.Line_Number :=
        LSP.Types.Line_Number (Segment.End_Line) - 1;
      End_Line_Text   : constant VSS.Strings.Virtual_String :=
        Self.Text.Slice
          (Self.Line_To_Marker (End_Line),
           Self.Line_To_Marker (End_Line + 1));
      End_Iterator   : VSS.Strings.Character_Iterators.Character_Iterator :=
        End_Line_Text.First_Character;
      Success        : Boolean with Unreferenced;

   begin
      --  Iterating forward through the line of the start position, initial
      --  iterator points to the first characters, thus "starts" from the
      --  second one.

      for J in 2 .. Segment.Start_Column loop
         Success := Start_Iterator.Forward;
      end loop;

      --  Iterating forward through the line of the end position. For the same
      --  reason "starts" from second character.

      for J in 2 .. Segment.End_Column loop
         Success := End_Iterator.Forward;
      end loop;

      return
        (first =>
           (line      => Start_Line,
            character => Start_Iterator.First_UTF16_Offset),
         last =>
           (line      => End_Line,
            character => End_Iterator.Last_UTF16_Offset));
   end To_LSP_Range;

   ----------
   -- Unit --
   ----------

   function Unit
     (Self    : Document'Class;
      Context : LSP.Ada_Contexts.Context)
      return Libadalang.Analysis.Analysis_Unit
   is
      File : constant String := Context.URI_To_File (Self.URI);
   begin
      return Context.LAL_Context.Get_From_File
        (Filename => File,
         Charset  => Context.Charset,
         Reparse  => False);
   end Unit;

   --------------------------
   -- Versioned_Identifier --
   --------------------------

   function Versioned_Identifier
     (Self : Document) return LSP.Messages.VersionedTextDocumentIdentifier is
   begin
      return (uri     => Self.URI,
              version => Self.Version);
   end Versioned_Identifier;

end LSP.Ada_Documents;