diff --git a/Cargo.lock b/Cargo.lock index c54e481e0..d2f906698 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -136,9 +136,12 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" [[package]] name = "cc" -version = "1.1.6" +version = "1.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" +checksum = "57b6a275aa2903740dc87da01c62040406b8812552e97129a63ea8850a17c6e6" +dependencies = [ + "shlex", +] [[package]] name = "cfg-if" @@ -166,7 +169,7 @@ dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", - "windows-targets 0.52.0", + "windows-targets 0.52.6", ] [[package]] @@ -263,9 +266,9 @@ dependencies = [ [[package]] name = "crossterm" -version = "0.27.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ "bitflags 2.6.0", "crossterm_winapi", @@ -274,6 +277,7 @@ dependencies = [ "libc", "mio", "parking_lot", + "rustix", "signal-hook", "signal-hook-mio", "winapi", @@ -345,20 +349,11 @@ dependencies = [ "parking_lot_core", ] -[[package]] -name = "deranged" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" -dependencies = [ - "powerfmt", -] - [[package]] name = "dunce" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "either" @@ -541,9 +536,9 @@ checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" [[package]] name = "gix" -version = "0.63.0" +version = "0.66.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "984c5018adfa7a4536ade67990b3ebc6e11ab57b3d6cd9968de0947ca99b4b06" +checksum = "9048b8d1ae2104f045cb37e5c450fc49d5d8af22609386bfc739c11ba88995eb" dependencies = [ "gix-actor", "gix-attributes", @@ -563,7 +558,6 @@ dependencies = [ "gix-ignore", "gix-index", "gix-lock", - "gix-macros", "gix-object", "gix-odb", "gix-pack", @@ -584,16 +578,15 @@ dependencies = [ "gix-validate", "gix-worktree", "once_cell", - "parking_lot", "smallvec", "thiserror", ] [[package]] name = "gix-actor" -version = "0.31.2" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69c59d392c7e6c94385b6fd6089d6df0fe945f32b4357687989f3aee253cd7f" +checksum = "fc19e312cd45c4a66cd003f909163dc2f8e1623e30a0c0c6df3776e89b308665" dependencies = [ "bstr", "gix-date", @@ -605,9 +598,9 @@ dependencies = [ [[package]] name = "gix-attributes" -version = "0.22.3" +version = "0.22.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e37ce99c7e81288c28b703641b6d5d119aacc45c1a6b247156e6249afa486257" +checksum = "ebccbf25aa4a973dd352564a9000af69edca90623e8a16dad9cbc03713131311" dependencies = [ "bstr", "gix-glob", @@ -640,9 +633,9 @@ dependencies = [ [[package]] name = "gix-command" -version = "0.3.7" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c22e086314095c43ffe5cdc5c0922d5439da4fd726f3b0438c56147c34dc225" +checksum = "dff2e692b36bbcf09286c70803006ca3fd56551a311de450be317a0ab8ea92e7" dependencies = [ "bstr", "gix-path", @@ -652,9 +645,9 @@ dependencies = [ [[package]] name = "gix-commitgraph" -version = "0.24.2" +version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7b102311085da4af18823413b5176d7c500fb2272eaf391cfa8635d8bcb12c4" +checksum = "133b06f67f565836ec0c473e2116a60fb74f80b6435e21d88013ac0e3c60fc78" dependencies = [ "bstr", "gix-chunk", @@ -666,9 +659,9 @@ dependencies = [ [[package]] name = "gix-config" -version = "0.37.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fafe42957e11d98e354a66b6bd70aeea00faf2f62dd11164188224a507c840" +checksum = "78e797487e6ca3552491de1131b4f72202f282fb33f198b1c34406d765b42bb0" dependencies = [ "bstr", "gix-config-value", @@ -687,9 +680,9 @@ dependencies = [ [[package]] name = "gix-config-value" -version = "0.14.6" +version = "0.14.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbd06203b1a9b33a78c88252a625031b094d9e1b647260070c25b09910c0a804" +checksum = "03f76169faa0dec598eac60f83d7fcdd739ec16596eca8fb144c88973dbe6f8c" dependencies = [ "bitflags 2.6.0", "bstr", @@ -700,21 +693,21 @@ dependencies = [ [[package]] name = "gix-date" -version = "0.8.6" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "367ee9093b0c2b04fd04c5c7c8b6a1082713534eab537597ae343663a518fa99" +checksum = "35c84b7af01e68daf7a6bb8bb909c1ff5edb3ce4326f1f43063a5a96d3c3c8a5" dependencies = [ "bstr", "itoa", + "jiff", "thiserror", - "time", ] [[package]] name = "gix-diff" -version = "0.44.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40b9bd8b2d07b6675a840b56a6c177d322d45fa082672b0dad8f063b25baf0a4" +checksum = "92c9afd80fff00f8b38b1c1928442feb4cd6d2232a6ed806b6b193151a3d336c" dependencies = [ "bstr", "gix-command", @@ -732,9 +725,9 @@ dependencies = [ [[package]] name = "gix-dir" -version = "0.5.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60c99f8c545abd63abe541d20ab6cda347de406c0a3f1c80aadc12d9b0e94974" +checksum = "0ed3a9076661359a1c5a27c12ad6c3ebe2dd96b8b3c0af6488ab7c128b7bdd98" dependencies = [ "bstr", "gix-discover", @@ -752,9 +745,9 @@ dependencies = [ [[package]] name = "gix-discover" -version = "0.32.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc27c699b63da66b50d50c00668bc0b7e90c3a382ef302865e891559935f3dbf" +checksum = "0577366b9567376bc26e815fd74451ebd0e6218814e242f8e5b7072c58d956d2" dependencies = [ "bstr", "dunce", @@ -787,9 +780,9 @@ dependencies = [ [[package]] name = "gix-filter" -version = "0.11.2" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00ce6ea5ac8fca7adbc63c48a1b9e0492c222c386aa15f513405f1003f2f4ab2" +checksum = "4121790ae140066e5b953becc72e7496278138d19239be2e63b5067b0843119e" dependencies = [ "bstr", "encoding_rs", @@ -808,9 +801,9 @@ dependencies = [ [[package]] name = "gix-fs" -version = "0.11.0" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f78f7d6dcda7a5809efd73a33b145e3dce7421c460df21f32126f9732736b0c" +checksum = "f2bfe6249cfea6d0c0e0990d5226a4cb36f030444ba9e35e0639275db8f98575" dependencies = [ "fastrand", "gix-features", @@ -819,9 +812,9 @@ dependencies = [ [[package]] name = "gix-glob" -version = "0.16.4" +version = "0.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7df15afa265cc8abe92813cd354d522f1ac06b29ec6dfa163ad320575cb447" +checksum = "74908b4bbc0a0a40852737e5d7889f676f081e340d5451a16e5b4c50d592f111" dependencies = [ "bitflags 2.6.0", "bstr", @@ -852,9 +845,9 @@ dependencies = [ [[package]] name = "gix-ignore" -version = "0.11.2" +version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "640dbeb4f5829f9fc14d31f654a34a0350e43a24e32d551ad130d99bf01f63f1" +checksum = "e447cd96598460f5906a0f6c75e950a39f98c2705fc755ad2f2020c9e937fab7" dependencies = [ "bstr", "gix-glob", @@ -865,9 +858,9 @@ dependencies = [ [[package]] name = "gix-index" -version = "0.33.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d8c5a5f1c58edcbc5692b174cda2703aba82ed17d7176ff4c1752eb48b1b167" +checksum = "0cd4203244444017682176e65fd0180be9298e58ed90bd4a8489a357795ed22d" dependencies = [ "bitflags 2.6.0", "bstr", @@ -902,22 +895,11 @@ dependencies = [ "thiserror", ] -[[package]] -name = "gix-macros" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "999ce923619f88194171a67fb3e6d613653b8d4d6078b529b15a765da0edcc17" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.48", -] - [[package]] name = "gix-object" -version = "0.42.2" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fe2dc4a41191c680c942e6ebd630c8107005983c4679214fdb1007dcf5ae1df" +checksum = "2f5b801834f1de7640731820c2df6ba88d95480dc4ab166a5882f8ff12b88efa" dependencies = [ "bstr", "gix-actor", @@ -934,9 +916,9 @@ dependencies = [ [[package]] name = "gix-odb" -version = "0.61.0" +version = "0.63.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e92b9790e2c919166865d0825b26cc440a387c175bed1b43a2fa99c0e9d45e98" +checksum = "a3158068701c17df54f0ab2adda527f5a6aca38fd5fd80ceb7e3c0a2717ec747" dependencies = [ "arc-swap", "gix-date", @@ -954,9 +936,9 @@ dependencies = [ [[package]] name = "gix-pack" -version = "0.51.0" +version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a8da51212dbff944713edb2141ed7e002eea326b8992070374ce13a6cb610b3" +checksum = "3223aa342eee21e1e0e403cad8ae9caf9edca55ef84c347738d10681676fd954" dependencies = [ "clru", "gix-chunk", @@ -965,18 +947,16 @@ dependencies = [ "gix-hashtable", "gix-object", "gix-path", - "gix-tempfile", "memmap2", - "parking_lot", "smallvec", "thiserror", ] [[package]] name = "gix-packetline-blocking" -version = "0.17.4" +version = "0.17.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c31d42378a3d284732e4d589979930d0d253360eccf7ec7a80332e5ccb77e14a" +checksum = "b9802304baa798dd6f5ff8008a2b6516d54b74a69ca2d3a2b9e2d6c3b5556b40" dependencies = [ "bstr", "faster-hex", @@ -986,9 +966,9 @@ dependencies = [ [[package]] name = "gix-path" -version = "0.10.9" +version = "0.10.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d23d5bbda31344d8abc8de7c075b3cf26e5873feba7c4a15d916bce67382bd9" +checksum = "38d5b8722112fa2fa87135298780bc833b0e9f6c56cc82795d209804b3a03484" dependencies = [ "bstr", "gix-trace", @@ -999,9 +979,9 @@ dependencies = [ [[package]] name = "gix-pathspec" -version = "0.7.5" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76cab098dc10ba2d89f634f66bf196dea4d7db4bf10b75c7a9c201c55a2ee19" +checksum = "5d23bf239532b4414d0e63b8ab3a65481881f7237ed9647bb10c1e3cc54c5ceb" dependencies = [ "bitflags 2.6.0", "bstr", @@ -1025,12 +1005,11 @@ dependencies = [ [[package]] name = "gix-ref" -version = "0.44.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b36752b448647acd59c9668fdd830b16d07db1e6d9c3b3af105c1605a6e23d9" +checksum = "ae0d8406ebf9aaa91f55a57f053c5a1ad1a39f60fdf0303142b7be7ea44311e5" dependencies = [ "gix-actor", - "gix-date", "gix-features", "gix-fs", "gix-hash", @@ -1047,9 +1026,9 @@ dependencies = [ [[package]] name = "gix-refspec" -version = "0.23.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dde848865834a54fe4d9b4573f15d0e9a68eaf3d061b42d3ed52b4b8acf880b2" +checksum = "ebb005f82341ba67615ffdd9f7742c87787544441c88090878393d0682869ca6" dependencies = [ "bstr", "gix-hash", @@ -1061,25 +1040,23 @@ dependencies = [ [[package]] name = "gix-revision" -version = "0.27.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e08f8107ed1f93a83bcfbb4c38084c7cb3f6cd849793f1d5eec235f9b13b2b" +checksum = "ba4621b219ac0cdb9256883030c3d56a6c64a6deaa829a92da73b9a576825e1e" dependencies = [ "bstr", "gix-date", "gix-hash", - "gix-hashtable", "gix-object", "gix-revwalk", - "gix-trace", "thiserror", ] [[package]] name = "gix-revwalk" -version = "0.13.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4181db9cfcd6d1d0fd258e91569dbb61f94cb788b441b5294dd7f1167a3e788f" +checksum = "b41e72544b93084ee682ef3d5b31b1ba4d8fa27a017482900e5e044d5b1b3984" dependencies = [ "gix-commitgraph", "gix-date", @@ -1092,9 +1069,9 @@ dependencies = [ [[package]] name = "gix-sec" -version = "0.10.6" +version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fddc27984a643b20dd03e97790555804f98cf07404e0e552c0ad8133266a79a1" +checksum = "0fe4d52f30a737bbece5276fab5d3a8b276dc2650df963e293d0673be34e7a5f" dependencies = [ "bitflags 2.6.0", "gix-path", @@ -1104,9 +1081,9 @@ dependencies = [ [[package]] name = "gix-status" -version = "0.10.0" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4373d989713809554d136f51bc7da565adf45c91aa4d86ef6a79801621bfc8" +checksum = "f70d35ba639f0c16a6e4cca81aa374a05f07b23fa36ee8beb72c100d98b4ffea" dependencies = [ "bstr", "filetime", @@ -1121,14 +1098,15 @@ dependencies = [ "gix-path", "gix-pathspec", "gix-worktree", + "portable-atomic", "thiserror", ] [[package]] name = "gix-submodule" -version = "0.11.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "921cd49924ac14b6611b22e5fb7bbba74d8780dc7ad26153304b64d1272460ac" +checksum = "529d0af78cc2f372b3218f15eb1e3d1635a21c8937c12e2dd0b6fc80c2ca874b" dependencies = [ "bstr", "gix-config", @@ -1161,9 +1139,9 @@ checksum = "f924267408915fddcd558e3f37295cc7d6a3e50f8bd8b606cee0808c3915157e" [[package]] name = "gix-traverse" -version = "0.39.1" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f20cb69b63eb3e4827939f42c05b7756e3488ef49c25c412a876691d568ee2a0" +checksum = "030da39af94e4df35472e9318228f36530989327906f38e27807df305fccb780" dependencies = [ "bitflags 2.6.0", "gix-commitgraph", @@ -1178,9 +1156,9 @@ dependencies = [ [[package]] name = "gix-url" -version = "0.27.3" +version = "0.27.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0db829ebdca6180fbe32be7aed393591df6db4a72dbbc0b8369162390954d1cf" +checksum = "fd280c5e84fb22e128ed2a053a0daeacb6379469be6a85e3d518a0636e160c89" dependencies = [ "bstr", "gix-features", @@ -1203,9 +1181,9 @@ dependencies = [ [[package]] name = "gix-validate" -version = "0.8.5" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82c27dd34a49b1addf193c92070bcbf3beaf6e10f16a78544de6372e146a0acf" +checksum = "81f2badbb64e57b404593ee26b752c26991910fd0d81fe6f9a71c1a8309b6c86" dependencies = [ "bstr", "thiserror", @@ -1213,9 +1191,9 @@ dependencies = [ [[package]] name = "gix-worktree" -version = "0.34.0" +version = "0.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53f6b7de83839274022aff92157d7505f23debf739d257984a300a35972ca94e" +checksum = "c312ad76a3f2ba8e865b360d5cb3aa04660971d16dec6dd0ce717938d903149a" dependencies = [ "bstr", "gix-attributes", @@ -1393,10 +1371,10 @@ dependencies = [ "globset", "helix-core", "helix-loader", + "helix-lsp-types", "helix-parsec", "helix-stdx", "log", - "lsp-types", "parking_lot", "serde", "serde_json", @@ -1406,6 +1384,17 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "helix-lsp-types" +version = "0.95.1" +dependencies = [ + "bitflags 2.6.0", + "serde", + "serde_json", + "serde_repr", + "url", +] + [[package]] name = "helix-parsec" version = "24.7.0" @@ -1422,7 +1411,7 @@ dependencies = [ "rustix", "tempfile", "which", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -1546,6 +1535,12 @@ dependencies = [ "libc", ] +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + [[package]] name = "home" version = "0.5.9" @@ -1607,9 +1602,9 @@ dependencies = [ [[package]] name = "imara-diff" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af13c8ceb376860ff0c6a66d83a8cdd4ecd9e464da24621bbffcd02b49619434" +checksum = "fc9da1a252bd44cd341657203722352efc9bc0c847d06ea6d2dc1cd1135e0a01" dependencies = [ "ahash", "hashbrown 0.14.5", @@ -1656,6 +1651,31 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +[[package]] +name = "jiff" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ef8bc400f8312944a9f879db116fed372c4f0859af672eba2a80f79c767dd19" +dependencies = [ + "jiff-tzdb-platform", + "windows-sys 0.59.0", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05fac328b3df1c0f18a3c2ab6cb7e06e4e549f366017d796e3e66b6d6889abe6" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8da387d5feaf355954c2c122c194d6df9c57d865125a67984bb453db5336940" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "js-sys" version = "0.3.61" @@ -1676,9 +1696,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.155" +version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "libloading" @@ -1687,7 +1707,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ "cfg-if", - "windows-targets 0.48.0", + "windows-targets 0.52.6", ] [[package]] @@ -1721,19 +1741,6 @@ version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" -[[package]] -name = "lsp-types" -version = "0.95.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e34d33a8e9b006cd3fc4fe69a921affa097bae4bb65f76271f4644f9a334365" -dependencies = [ - "bitflags 1.3.2", - "serde", - "serde_json", - "serde_repr", - "url", -] - [[package]] name = "memchr" version = "2.6.3" @@ -1769,14 +1776,15 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.11" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4" dependencies = [ + "hermit-abi 0.3.9", "libc", "log", "wasi", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1800,12 +1808,6 @@ dependencies = [ "unicode-segmentation", ] -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - [[package]] name = "num-traits" version = "0.2.15" @@ -1821,16 +1823,7 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "num_threads" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" -dependencies = [ + "hermit-abi 0.2.6", "libc", ] @@ -1908,10 +1901,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] -name = "powerfmt" -version = "0.2.0" +name = "portable-atomic" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +checksum = "da544ee218f0d287a911e9c99a39a8c9bc8fcad3cb8db5959940044ecfc67265" [[package]] name = "proc-macro2" @@ -1930,9 +1923,9 @@ checksum = "744a264d26b88a6a7e37cbad97953fa233b94d585236310bcbc88474b4092d79" [[package]] name = "pulldown-cmark" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8746739f11d39ce5ad5c2520a9b75285310dbfe78c541ccf832d38615765aec0" +checksum = "4d31cbfcd94884c3a67ec210c83efb06cb43674043458b0ad59f6947f8462c23" dependencies = [ "bitflags 2.6.0", "memchr", @@ -2017,9 +2010,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.5" +version = "1.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" +checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" dependencies = [ "aho-corasick", "memchr", @@ -2115,18 +2108,18 @@ checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" [[package]] name = "serde" -version = "1.0.204" +version = "1.0.209" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" +checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.204" +version = "1.0.209" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" +checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170" dependencies = [ "proc-macro2", "quote", @@ -2135,20 +2128,21 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.120" +version = "1.0.127" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" +checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad" dependencies = [ "itoa", + "memchr", "ryu", "serde", ] [[package]] name = "serde_repr" -version = "0.1.12" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" dependencies = [ "proc-macro2", "quote", @@ -2157,9 +2151,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.6" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" +checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" dependencies = [ "serde", ] @@ -2176,6 +2170,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "signal-hook" version = "0.3.17" @@ -2188,9 +2188,9 @@ dependencies = [ [[package]] name = "signal-hook-mio" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" +checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd" dependencies = [ "libc", "mio", @@ -2305,14 +2305,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.10.1" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" dependencies = [ "cfg-if", "fastrand", + "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2373,39 +2374,6 @@ dependencies = [ "num_cpus", ] -[[package]] -name = "time" -version = "0.3.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" -dependencies = [ - "deranged", - "itoa", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" - -[[package]] -name = "time-macros" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tinyvec" version = "1.6.0" @@ -2423,28 +2391,27 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.38.1" +version = "1.39.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2caba9f80616f438e09748d5acda951967e1ea58508ef53d9c6402485a46df" +checksum = "9babc99b9923bfa4804bd74722ff02c0381021eafa4db9949217e3be8e84fff5" dependencies = [ "backtrace", "bytes", "libc", "mio", - "num_cpus", "parking_lot", "pin-project-lite", "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "tokio-macros" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", @@ -2464,9 +2431,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.15" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2caab0bf757388c6c0ae23b3293fdb463fee59434529014f85e3263b995c28" +checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" dependencies = [ "serde", "serde_spanned", @@ -2476,18 +2443,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.6" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" +checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.22.16" +version = "0.22.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "278f3d518e152219c994ce877758516bca5e118eaed6996192a774fb9fbf0788" +checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" dependencies = [ "indexmap", "serde", @@ -2656,9 +2623,9 @@ checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" [[package]] name = "which" -version = "6.0.1" +version = "6.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8211e4f58a2b2805adfbefbc07bab82958fc91e3836339b1ab7ae32465dce0d7" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" dependencies = [ "either", "home", @@ -2730,7 +2697,16 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -2765,17 +2741,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -2792,9 +2769,9 @@ checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" @@ -2810,9 +2787,9 @@ checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" @@ -2828,9 +2805,15 @@ checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" @@ -2846,9 +2829,9 @@ checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" @@ -2864,9 +2847,9 @@ checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" @@ -2882,9 +2865,9 @@ checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" @@ -2900,15 +2883,15 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.5" +version = "0.6.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" +checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" dependencies = [ "memchr", ] diff --git a/Cargo.toml b/Cargo.toml index e7f784428..763992480 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "helix-view", "helix-term", "helix-tui", + "helix-lsp-types", "helix-lsp", "helix-event", "helix-dap", diff --git a/book/src/generated/lang-support.md b/book/src/generated/lang-support.md index 686dec5e2..cb1c815f2 100644 --- a/book/src/generated/lang-support.md +++ b/book/src/generated/lang-support.md @@ -1,6 +1,6 @@ | Language | Syntax Highlighting | Treesitter Textobjects | Auto Indent | Default LSP | | --- | --- | --- | --- | --- | -| ada | ✓ | ✓ | | `ada_language_server`, `ada_language_server` | +| ada | ✓ | ✓ | | `ada_language_server` | | adl | ✓ | ✓ | ✓ | | | agda | ✓ | | | | | astro | ✓ | | | | @@ -34,8 +34,8 @@ | devicetree | ✓ | | | | | dhall | ✓ | ✓ | | `dhall-lsp-server` | | diff | ✓ | | | | -| docker-compose | ✓ | | ✓ | `docker-compose-langserver`, `yaml-language-server` | -| dockerfile | ✓ | | | `docker-langserver` | +| docker-compose | ✓ | ✓ | ✓ | `docker-compose-langserver`, `yaml-language-server` | +| dockerfile | ✓ | ✓ | | `docker-langserver` | | dot | ✓ | | | `dot-language-server` | | dtd | ✓ | | | | | earthfile | ✓ | ✓ | ✓ | `earthlyls` | @@ -46,7 +46,7 @@ | elixir | ✓ | ✓ | ✓ | `elixir-ls` | | elm | ✓ | ✓ | | `elm-language-server` | | elvish | ✓ | | | `elvish` | -| env | ✓ | | | | +| env | ✓ | ✓ | | | | erb | ✓ | | | | | erlang | ✓ | ✓ | | `erlang_ls` | | esdl | ✓ | | | | @@ -58,9 +58,10 @@ | gas | ✓ | ✓ | | | | gdscript | ✓ | ✓ | ✓ | | | gemini | ✓ | | | | +| gherkin | ✓ | | | | | git-attributes | ✓ | | | | | git-commit | ✓ | ✓ | | | -| git-config | ✓ | | | | +| git-config | ✓ | ✓ | | | | git-ignore | ✓ | | | | | git-rebase | ✓ | | | | | gjs | ✓ | ✓ | ✓ | `typescript-language-server`, `vscode-eslint-language-server`, `ember-language-server` | @@ -69,7 +70,7 @@ | glsl | ✓ | ✓ | ✓ | | | gn | ✓ | | | | | go | ✓ | ✓ | ✓ | `gopls`, `golangci-lint-langserver` | -| godot-resource | ✓ | | | | +| godot-resource | ✓ | ✓ | | | | gomod | ✓ | | | `gopls` | | gotmpl | ✓ | | | `gopls` | | gowork | ✓ | | | `gopls` | @@ -82,7 +83,7 @@ | hcl | ✓ | ✓ | ✓ | `terraform-ls` | | heex | ✓ | ✓ | | `elixir-ls` | | helm | ✓ | | | `helm_ls` | -| hocon | ✓ | | ✓ | | +| hocon | ✓ | ✓ | ✓ | | | hoon | ✓ | | | | | hosts | ✓ | | | | | html | ✓ | | | `vscode-html-language-server` | @@ -97,6 +98,7 @@ | javascript | ✓ | ✓ | ✓ | `typescript-language-server` | | jinja | ✓ | | | | | jjdescription | ✓ | | | | +| jq | ✓ | ✓ | | `jq-lsp` | | jsdoc | ✓ | | | | | json | ✓ | ✓ | ✓ | `vscode-json-language-server` | | json5 | ✓ | | | | @@ -125,7 +127,7 @@ | markdown.inline | ✓ | | | | | matlab | ✓ | ✓ | ✓ | | | mermaid | ✓ | | | | -| meson | ✓ | | ✓ | | +| meson | ✓ | | ✓ | `mesonlsp` | | mint | | | | `mint` | | mojo | ✓ | ✓ | ✓ | `mojo-lsp-server` | | move | ✓ | | | | @@ -133,7 +135,7 @@ | nasm | ✓ | ✓ | | | | nickel | ✓ | | ✓ | `nls` | | nim | ✓ | ✓ | ✓ | `nimlangserver` | -| nix | ✓ | ✓ | | `nil` | +| nix | ✓ | ✓ | | `nil`, `nixd` | | nu | ✓ | | | `nu` | | nunjucks | ✓ | | | | | ocaml | ✓ | | ✓ | `ocamllsp` | @@ -156,7 +158,7 @@ | pod | ✓ | | | | | ponylang | ✓ | ✓ | ✓ | | | powershell | ✓ | | | | -| prisma | ✓ | | | `prisma-language-server` | +| prisma | ✓ | ✓ | | `prisma-language-server` | | prolog | | | | `swipl` | | protobuf | ✓ | ✓ | ✓ | `bufls`, `pb` | | prql | ✓ | | | | @@ -184,7 +186,7 @@ | sml | ✓ | | | | | solidity | ✓ | ✓ | | `solc` | | spicedb | ✓ | | | | -| sql | ✓ | | | | +| sql | ✓ | ✓ | | | | sshclientconfig | ✓ | | | | | starlark | ✓ | ✓ | | | | strace | ✓ | | | | @@ -199,12 +201,14 @@ | tcl | ✓ | | ✓ | | | templ | ✓ | | | `templ` | | tfvars | ✓ | | ✓ | `terraform-ls` | +| thrift | ✓ | | | | | todotxt | ✓ | | | | | toml | ✓ | ✓ | | `taplo` | | tsq | ✓ | | | | | tsx | ✓ | ✓ | ✓ | `typescript-language-server` | | twig | ✓ | | | | | typescript | ✓ | ✓ | ✓ | `typescript-language-server` | +| typespec | ✓ | ✓ | ✓ | `tsp-server` | | typst | ✓ | | | `tinymist`, `typst-lsp` | | ungrammar | ✓ | | | | | unison | ✓ | | ✓ | | @@ -224,6 +228,6 @@ | xit | ✓ | | | | | xml | ✓ | | ✓ | | | xtc | ✓ | | | | -| yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` | +| yaml | ✓ | ✓ | ✓ | `yaml-language-server`, `ansible-language-server` | | yuck | ✓ | | | | | zig | ✓ | ✓ | ✓ | `zls` | diff --git a/book/src/install.md b/book/src/install.md index debc82b01..387b8b658 100644 --- a/book/src/install.md +++ b/book/src/install.md @@ -14,6 +14,10 @@ Note that: ## Pre-built binaries Download pre-built binaries from the [GitHub Releases page](https://github.com/helix-editor/helix/releases). -Add the `hx` binary to your system's `$PATH` to use it from the command line, and copy the `runtime` directory into the config directory (for example `~/.config/helix/runtime` on Linux/macOS). -The runtime location can be overriden via the HELIX_RUNTIME environment variable. +The tarball contents include an `hx` binary and a `runtime` directory. +To set up Helix: +1. Add the `hx` binary to your system's `$PATH` to allow it to be used from the command line. +2. Copy the `runtime` directory to a location that `hx` searches for runtime files. A typical location on Linux/macOS is `~/.config/helix/runtime`. + +To see the runtime directories that `hx` searches, run `hx --health`. If necessary, you can override the default runtime location by setting the `HELIX_RUNTIME` environment variable. diff --git a/book/src/keymap.md b/book/src/keymap.md index 0e60f2826..e7ae6ae47 100644 --- a/book/src/keymap.md +++ b/book/src/keymap.md @@ -320,10 +320,14 @@ Displays documentation for item under cursor. Remapping currently not supported. Displays documentation for the selected completion item. Remapping currently not supported. -| Key | Description | -| ---- | ----------- | -| `Shift-Tab`, `Ctrl-p`, `Up` | Previous entry | -| `Tab`, `Ctrl-n`, `Down` | Next entry | +| Key | Description | +| ---- | ----------- | +| `Shift-Tab`, `Ctrl-p`, `Up` | Previous entry | +| `Tab`, `Ctrl-n`, `Down` | Next entry | +| `Enter` | Close menu and accept completion | +| `Ctrl-c` | Close menu and reject completion | + +Any other keypresses result in the completion being accepted. ##### Signature-help Popup diff --git a/book/src/remapping.md b/book/src/remapping.md index 863c55570..e3efdf16f 100644 --- a/book/src/remapping.md +++ b/book/src/remapping.md @@ -75,5 +75,20 @@ Ctrl, Shift and Alt modifiers are encoded respectively with the prefixes Keys can be disabled by binding them to the `no_op` command. -A list of commands is available in the [Keymap](https://docs.helix-editor.com/keymap.html) documentation - and in the source code at [`helix-term/src/commands.rs`](https://github.com/helix-editor/helix/blob/master/helix-term/src/commands.rs) at the invocation of `static_commands!` macro and the `TypableCommandList`. +## Commands + +There are three kinds of commands that can be used in keymaps: + +* Static commands: commands like `move_char_right` which are usually bound to + keys and used for movement and editing. A list of static commands is + available in the [Keymap](./keymap.html) documentation and in the source code + in [`helix-term/src/commands.rs`](https://github.com/helix-editor/helix/blob/master/helix-term/src/commands.rs) + at the invocation of `static_commands!` macro and the `TypableCommandList`. +* Typable commands: commands that can be executed from command mode (`:`), for + example `:write!`. See the [Commands](./commands.html) documentation for a + list of available typeable commands. +* Macros: sequences of keys that are executed in order. These keybindings + start with `@` and then list any number of keys to be executed. For example + `@miw` can be used to select the surrounding word. For now, macro keybindings + are not allowed in keybinding sequences due to limitations in the way that + command sequences are executed. diff --git a/book/src/themes.md b/book/src/themes.md index f9f8393c3..1bc2627dd 100644 --- a/book/src/themes.md +++ b/book/src/themes.md @@ -293,12 +293,13 @@ These scopes are used for theming the editor interface: | `ui.statusline.select` | Statusline mode during select mode ([only if `editor.color-modes` is enabled][editor-section]) | | `ui.statusline.separator` | Separator character in statusline | | `ui.bufferline` | Style for the buffer line | -| `ui.bufferline.active` | Style for the active buffer in buffer line | +| `ui.bufferline.active` | Style for the active buffer in buffer line | | `ui.bufferline.background` | Style for bufferline background | | `ui.popup` | Documentation popups (e.g. Space + k) | | `ui.popup.info` | Prompt for multiple key options | -| `ui.picker.header` | Column names in pickers with multiple columns | -| `ui.picker.header.active` | The column name in pickers with multiple columns where the cursor is entering into. | +| `ui.picker.header` | Header row area in pickers with multiple columns | +| `ui.picker.header.column` | Column names in pickers with multiple columns | +| `ui.picker.header.column.active` | The column name in pickers with multiple columns where the cursor is entering into. | | `ui.window` | Borderlines separating splits | | `ui.help` | Description box for commands | | `ui.text` | Default text style, command prompts, popup text, etc. | diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 2be8f77c7..86caff717 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -53,6 +53,10 @@ Existing tests can be used as examples. Helpers can be found in [helpers.rs][helpers.rs]. The log level can be set with the `HELIX_LOG_LEVEL` environment variable, e.g. `HELIX_LOG_LEVEL=debug cargo integration-test`. +Contributors using MacOS might encounter `Too many open files (os error 24)` +failures while running integration tests. This can be resolved by increasing +the default value (e.g. to `10240` from `256`) by running `ulimit -n 10240`. + ## Minimum Stable Rust Version (MSRV) Policy Helix follows the MSRV of Firefox. diff --git a/docs/architecture.md b/docs/architecture.md index 5d33cbac0..0dd68ed38 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,13 +1,14 @@ -| Crate | Description | -| ----------- | ----------- | -| helix-core | Core editing primitives, functional. | -| helix-lsp | Language server client | -| helix-dap | Debug Adapter Protocol (DAP) client | -| helix-loader | Functions for building, fetching, and loading external resources | -| helix-view | UI abstractions for use in backends, imperative shell. | -| helix-term | Terminal UI | -| helix-tui | TUI primitives, forked from tui-rs, inspired by Cursive | +| Crate | Description | +| ----------- | ----------- | +| helix-core | Core editing primitives, functional. | +| helix-lsp | Language server client | +| helix-lsp-types | Language Server Protocol type definitions | +| helix-dap | Debug Adapter Protocol (DAP) client | +| helix-loader | Functions for building, fetching, and loading external resources | +| helix-view | UI abstractions for use in backends, imperative shell. | +| helix-term | Terminal UI | +| helix-tui | TUI primitives, forked from tui-rs, inspired by Cursive | This document contains a high-level overview of Helix internals. diff --git a/flake.nix b/flake.nix index c230dc317..c7e4fdce5 100644 --- a/flake.nix +++ b/flake.nix @@ -126,6 +126,7 @@ # disable fetching and building of tree-sitter grammars in the helix-term build.rs HELIX_DISABLE_AUTO_GRAMMAR_BUILD = "1"; buildInputs = [stdenv.cc.cc.lib]; + nativeBuildInputs = [pkgs.installShellFiles]; # disable tests doCheck = false; meta.mainProgram = "hx"; @@ -141,6 +142,7 @@ cp contrib/Helix.desktop $out/share/applications cp logo.svg $out/share/icons/hicolor/scalable/apps/helix.svg cp contrib/helix.png $out/share/icons/hicolor/256x256/apps + installShellCompletion contrib/completion/hx.{bash,fish,zsh} ''; }); helix = makeOverridableHelix self.packages.${system}.helix-unwrapped {}; diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml index 6608b69c8..90eb747a9 100644 --- a/helix-core/Cargo.toml +++ b/helix-core/Cargo.toml @@ -46,7 +46,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" toml = "0.8" -imara-diff = "0.1.6" +imara-diff = "0.1.7" encoding_rs = "0.8" diff --git a/helix-core/src/auto_pairs.rs b/helix-core/src/auto_pairs.rs index 31f9d3649..853290404 100644 --- a/helix-core/src/auto_pairs.rs +++ b/helix-core/src/auto_pairs.rs @@ -75,9 +75,9 @@ impl From<(&char, &char)> for Pair { impl AutoPairs { /// Make a new AutoPairs set with the given pairs and default conditions. - pub fn new<'a, V: 'a, A>(pairs: V) -> Self + pub fn new<'a, V, A>(pairs: V) -> Self where - V: IntoIterator, + V: IntoIterator + 'a, A: Into, { let mut auto_pairs = HashMap::new(); diff --git a/helix-core/src/indent.rs b/helix-core/src/indent.rs index fd2b6c959..ae26c13e0 100644 --- a/helix-core/src/indent.rs +++ b/helix-core/src/indent.rs @@ -265,7 +265,7 @@ fn is_first_in_line(node: Node, text: RopeSlice, new_line_byte_pos: Option( // Skip matches where not all custom predicates are fulfilled if !query.general_predicates(m.pattern_index).iter().all(|pred| { match pred.operator.as_ref() { - "not-kind-eq?" => match (pred.args.get(0), pred.args.get(1)) { + "not-kind-eq?" => match (pred.args.first(), pred.args.get(1)) { ( Some(QueryPredicateArg::Capture(capture_idx)), Some(QueryPredicateArg::String(kind)), @@ -473,7 +473,7 @@ fn query_indents<'a>( } }, "same-line?" | "not-same-line?" => { - match (pred.args.get(0), pred.args.get(1)) { + match (pred.args.first(), pred.args.get(1)) { ( Some(QueryPredicateArg::Capture(capt1)), Some(QueryPredicateArg::Capture(capt2)) @@ -495,7 +495,7 @@ fn query_indents<'a>( } } } - "one-line?" | "not-one-line?" => match pred.args.get(0) { + "one-line?" | "not-one-line?" => match pred.args.first() { Some(QueryPredicateArg::Capture(capture_idx)) => { let node = m.nodes_for_capture_index(*capture_idx).next(); @@ -786,6 +786,7 @@ fn init_indent_query<'a, 'b>( /// - The line after the node. This is defined by: /// - The scope `tail`. /// - The scope `all` if this node is not the first node on its line. +/// /// Intuitively, `all` applies to everything contained in this node while `tail` applies to everything except for the first line of the node. /// The indents from different nodes for the same line are then combined. /// The result [Indentation] is simply the sum of the [Indentation] for all lines. diff --git a/helix-core/src/movement.rs b/helix-core/src/movement.rs index f5c2b2ed5..e446d8cc4 100644 --- a/helix-core/src/movement.rs +++ b/helix-core/src/movement.rs @@ -197,13 +197,31 @@ pub fn move_prev_long_word_end(slice: RopeSlice, range: Range, count: usize) -> word_move(slice, range, count, WordMotionTarget::PrevLongWordEnd) } +pub fn move_next_sub_word_start(slice: RopeSlice, range: Range, count: usize) -> Range { + word_move(slice, range, count, WordMotionTarget::NextSubWordStart) +} + +pub fn move_next_sub_word_end(slice: RopeSlice, range: Range, count: usize) -> Range { + word_move(slice, range, count, WordMotionTarget::NextSubWordEnd) +} + +pub fn move_prev_sub_word_start(slice: RopeSlice, range: Range, count: usize) -> Range { + word_move(slice, range, count, WordMotionTarget::PrevSubWordStart) +} + +pub fn move_prev_sub_word_end(slice: RopeSlice, range: Range, count: usize) -> Range { + word_move(slice, range, count, WordMotionTarget::PrevSubWordEnd) +} + fn word_move(slice: RopeSlice, range: Range, count: usize, target: WordMotionTarget) -> Range { let is_prev = matches!( target, WordMotionTarget::PrevWordStart | WordMotionTarget::PrevLongWordStart + | WordMotionTarget::PrevSubWordStart | WordMotionTarget::PrevWordEnd | WordMotionTarget::PrevLongWordEnd + | WordMotionTarget::PrevSubWordEnd ); // Special-case early-out. @@ -383,6 +401,12 @@ pub enum WordMotionTarget { NextLongWordEnd, PrevLongWordStart, PrevLongWordEnd, + // A sub word is similar to a regular word, except it is also delimited by + // underscores and transitions from lowercase to uppercase. + NextSubWordStart, + NextSubWordEnd, + PrevSubWordStart, + PrevSubWordEnd, } pub trait CharHelpers { @@ -398,8 +422,10 @@ impl CharHelpers for Chars<'_> { target, WordMotionTarget::PrevWordStart | WordMotionTarget::PrevLongWordStart + | WordMotionTarget::PrevSubWordStart | WordMotionTarget::PrevWordEnd | WordMotionTarget::PrevLongWordEnd + | WordMotionTarget::PrevSubWordEnd ); // Reverse the iterator if needed for the motion direction. @@ -476,6 +502,25 @@ fn is_long_word_boundary(a: char, b: char) -> bool { } } +fn is_sub_word_boundary(a: char, b: char, dir: Direction) -> bool { + match (categorize_char(a), categorize_char(b)) { + (CharCategory::Word, CharCategory::Word) => { + if (a == '_') != (b == '_') { + return true; + } + + // Subword boundaries are directional: in 'fooBar', there is a + // boundary between 'o' and 'B', but not between 'B' and 'a'. + match dir { + Direction::Forward => a.is_lowercase() && b.is_uppercase(), + Direction::Backward => a.is_uppercase() && b.is_lowercase(), + } + } + (a, b) if a != b => true, + _ => false, + } +} + fn reached_target(target: WordMotionTarget, prev_ch: char, next_ch: char) -> bool { match target { WordMotionTarget::NextWordStart | WordMotionTarget::PrevWordEnd => { @@ -494,6 +539,22 @@ fn reached_target(target: WordMotionTarget, prev_ch: char, next_ch: char) -> boo is_long_word_boundary(prev_ch, next_ch) && (!prev_ch.is_whitespace() || char_is_line_ending(next_ch)) } + WordMotionTarget::NextSubWordStart => { + is_sub_word_boundary(prev_ch, next_ch, Direction::Forward) + && (char_is_line_ending(next_ch) || !(next_ch.is_whitespace() || next_ch == '_')) + } + WordMotionTarget::PrevSubWordEnd => { + is_sub_word_boundary(prev_ch, next_ch, Direction::Backward) + && (char_is_line_ending(next_ch) || !(next_ch.is_whitespace() || next_ch == '_')) + } + WordMotionTarget::NextSubWordEnd => { + is_sub_word_boundary(prev_ch, next_ch, Direction::Forward) + && (!(prev_ch.is_whitespace() || prev_ch == '_') || char_is_line_ending(next_ch)) + } + WordMotionTarget::PrevSubWordStart => { + is_sub_word_boundary(prev_ch, next_ch, Direction::Backward) + && (!(prev_ch.is_whitespace() || prev_ch == '_') || char_is_line_ending(next_ch)) + } } } @@ -1012,6 +1073,178 @@ mod test { } } + #[test] + fn test_behaviour_when_moving_to_start_of_next_sub_words() { + let tests = [ + ( + "NextSubwordStart", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 11)), + ], + ), + ( + "next_subword_start", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "Next_Subword_Start", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "NEXT_SUBWORD_START", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "next subword start", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "Next Subword Start", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "NEXT SUBWORD START", + vec![ + (1, Range::new(0, 0), Range::new(0, 5)), + (1, Range::new(4, 4), Range::new(5, 13)), + ], + ), + ( + "next__subword__start", + vec![ + (1, Range::new(0, 0), Range::new(0, 6)), + (1, Range::new(4, 4), Range::new(4, 6)), + (1, Range::new(5, 5), Range::new(6, 15)), + ], + ), + ( + "Next__Subword__Start", + vec![ + (1, Range::new(0, 0), Range::new(0, 6)), + (1, Range::new(4, 4), Range::new(4, 6)), + (1, Range::new(5, 5), Range::new(6, 15)), + ], + ), + ( + "NEXT__SUBWORD__START", + vec![ + (1, Range::new(0, 0), Range::new(0, 6)), + (1, Range::new(4, 4), Range::new(4, 6)), + (1, Range::new(5, 5), Range::new(6, 15)), + ], + ), + ]; + + for (sample, scenario) in tests { + for (count, begin, expected_end) in scenario.into_iter() { + let range = move_next_sub_word_start(Rope::from(sample).slice(..), begin, count); + assert_eq!(range, expected_end, "Case failed: [{}]", sample); + } + } + } + + #[test] + fn test_behaviour_when_moving_to_end_of_next_sub_words() { + let tests = [ + ( + "NextSubwordEnd", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 11)), + ], + ), + ( + "next subword end", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "Next Subword End", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "NEXT SUBWORD END", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "next_subword_end", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "Next_Subword_End", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "NEXT_SUBWORD_END", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 12)), + ], + ), + ( + "next__subword__end", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 13)), + (1, Range::new(5, 5), Range::new(5, 13)), + ], + ), + ( + "Next__Subword__End", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 13)), + (1, Range::new(5, 5), Range::new(5, 13)), + ], + ), + ( + "NEXT__SUBWORD__END", + vec![ + (1, Range::new(0, 0), Range::new(0, 4)), + (1, Range::new(4, 4), Range::new(4, 13)), + (1, Range::new(5, 5), Range::new(5, 13)), + ], + ), + ]; + + for (sample, scenario) in tests { + for (count, begin, expected_end) in scenario.into_iter() { + let range = move_next_sub_word_end(Rope::from(sample).slice(..), begin, count); + assert_eq!(range, expected_end, "Case failed: [{}]", sample); + } + } + } + #[test] fn test_behaviour_when_moving_to_start_of_next_long_words() { let tests = [ @@ -1181,6 +1414,92 @@ mod test { } } + #[test] + fn test_behaviour_when_moving_to_start_of_previous_sub_words() { + let tests = [ + ( + "PrevSubwordEnd", + vec![ + (1, Range::new(13, 13), Range::new(14, 11)), + (1, Range::new(11, 11), Range::new(11, 4)), + ], + ), + ( + "prev subword end", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "Prev Subword End", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "PREV SUBWORD END", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "prev_subword_end", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "Prev_Subword_End", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "PREV_SUBWORD_END", + vec![ + (1, Range::new(15, 15), Range::new(16, 13)), + (1, Range::new(12, 12), Range::new(13, 5)), + ], + ), + ( + "prev__subword__end", + vec![ + (1, Range::new(17, 17), Range::new(18, 15)), + (1, Range::new(13, 13), Range::new(14, 6)), + (1, Range::new(14, 14), Range::new(15, 6)), + ], + ), + ( + "Prev__Subword__End", + vec![ + (1, Range::new(17, 17), Range::new(18, 15)), + (1, Range::new(13, 13), Range::new(14, 6)), + (1, Range::new(14, 14), Range::new(15, 6)), + ], + ), + ( + "PREV__SUBWORD__END", + vec![ + (1, Range::new(17, 17), Range::new(18, 15)), + (1, Range::new(13, 13), Range::new(14, 6)), + (1, Range::new(14, 14), Range::new(15, 6)), + ], + ), + ]; + + for (sample, scenario) in tests { + for (count, begin, expected_end) in scenario.into_iter() { + let range = move_prev_sub_word_start(Rope::from(sample).slice(..), begin, count); + assert_eq!(range, expected_end, "Case failed: [{}]", sample); + } + } + } + #[test] fn test_behaviour_when_moving_to_start_of_previous_long_words() { let tests = [ @@ -1444,6 +1763,92 @@ mod test { } } + #[test] + fn test_behaviour_when_moving_to_end_of_previous_sub_words() { + let tests = [ + ( + "PrevSubwordEnd", + vec![ + (1, Range::new(13, 13), Range::new(14, 11)), + (1, Range::new(11, 11), Range::new(11, 4)), + ], + ), + ( + "prev subword end", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "Prev Subword End", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "PREV SUBWORD END", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "prev_subword_end", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "Prev_Subword_End", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "PREV_SUBWORD_END", + vec![ + (1, Range::new(15, 15), Range::new(16, 12)), + (1, Range::new(12, 12), Range::new(12, 4)), + ], + ), + ( + "prev__subword__end", + vec![ + (1, Range::new(17, 17), Range::new(18, 13)), + (1, Range::new(13, 13), Range::new(13, 4)), + (1, Range::new(14, 14), Range::new(15, 13)), + ], + ), + ( + "Prev__Subword__End", + vec![ + (1, Range::new(17, 17), Range::new(18, 13)), + (1, Range::new(13, 13), Range::new(13, 4)), + (1, Range::new(14, 14), Range::new(15, 13)), + ], + ), + ( + "PREV__SUBWORD__END", + vec![ + (1, Range::new(17, 17), Range::new(18, 13)), + (1, Range::new(13, 13), Range::new(13, 4)), + (1, Range::new(14, 14), Range::new(15, 13)), + ], + ), + ]; + + for (sample, scenario) in tests { + for (count, begin, expected_end) in scenario.into_iter() { + let range = move_prev_sub_word_end(Rope::from(sample).slice(..), begin, count); + assert_eq!(range, expected_end, "Case failed: [{}]", sample); + } + } + } + #[test] fn test_behaviour_when_moving_to_end_of_next_long_words() { let tests = [ diff --git a/helix-core/src/selection.rs b/helix-core/src/selection.rs index eff1fcd70..a382a7186 100644 --- a/helix-core/src/selection.rs +++ b/helix-core/src/selection.rs @@ -184,16 +184,16 @@ impl Range { let positions_to_map = match self.anchor.cmp(&self.head) { Ordering::Equal => [ - (&mut self.anchor, Assoc::After), - (&mut self.head, Assoc::After), + (&mut self.anchor, Assoc::AfterSticky), + (&mut self.head, Assoc::AfterSticky), ], Ordering::Less => [ - (&mut self.anchor, Assoc::After), - (&mut self.head, Assoc::Before), + (&mut self.anchor, Assoc::AfterSticky), + (&mut self.head, Assoc::BeforeSticky), ], Ordering::Greater => [ - (&mut self.head, Assoc::After), - (&mut self.anchor, Assoc::Before), + (&mut self.head, Assoc::AfterSticky), + (&mut self.anchor, Assoc::BeforeSticky), ], }; changes.update_positions(positions_to_map.into_iter()); @@ -482,16 +482,16 @@ impl Selection { range.old_visual_position = None; match range.anchor.cmp(&range.head) { Ordering::Equal => [ - (&mut range.anchor, Assoc::After), - (&mut range.head, Assoc::After), + (&mut range.anchor, Assoc::AfterSticky), + (&mut range.head, Assoc::AfterSticky), ], Ordering::Less => [ - (&mut range.anchor, Assoc::After), - (&mut range.head, Assoc::Before), + (&mut range.anchor, Assoc::AfterSticky), + (&mut range.head, Assoc::BeforeSticky), ], Ordering::Greater => [ - (&mut range.head, Assoc::After), - (&mut range.anchor, Assoc::Before), + (&mut range.head, Assoc::AfterSticky), + (&mut range.anchor, Assoc::BeforeSticky), ], } }); diff --git a/helix-core/src/syntax.rs b/helix-core/src/syntax.rs index ab6bcc1fb..7be512f52 100644 --- a/helix-core/src/syntax.rs +++ b/helix-core/src/syntax.rs @@ -1431,8 +1431,11 @@ impl Syntax { // The `captures` iterator borrows the `Tree` and the `QueryCursor`, which // prevents them from being moved. But both of these values are really just // pointers, so it's actually ok to move them. - let cursor_ref = - unsafe { mem::transmute::<_, &'static mut QueryCursor>(&mut cursor) }; + let cursor_ref = unsafe { + mem::transmute::<&mut tree_sitter::QueryCursor, &mut tree_sitter::QueryCursor>( + &mut cursor, + ) + }; // if reusing cursors & no range this resets to whole range cursor_ref.set_byte_range(range.clone().unwrap_or(0..usize::MAX)); @@ -1737,7 +1740,7 @@ pub(crate) fn generate_edits( } use std::sync::atomic::{AtomicUsize, Ordering}; -use std::{iter, mem, ops, str, usize}; +use std::{iter, mem, ops, str}; use tree_sitter::{ Language as Grammar, Node, Parser, Point, Query, QueryCaptures, QueryCursor, QueryError, QueryMatch, Range, TextProvider, Tree, diff --git a/helix-core/src/syntax/tree_cursor.rs b/helix-core/src/syntax/tree_cursor.rs index 692d5890a..bec4a1c6c 100644 --- a/helix-core/src/syntax/tree_cursor.rs +++ b/helix-core/src/syntax/tree_cursor.rs @@ -204,7 +204,7 @@ impl<'a> TreeCursor<'a> { self.injection_ranges[start_idx..] .iter() - .take_while(|range| range.start < end) + .take_while(|range| range.start < end || range.depth > 1) .find_map(|range| (range.start <= start).then_some(range.layer_id)) .unwrap_or(self.root) } diff --git a/helix-core/src/transaction.rs b/helix-core/src/transaction.rs index f24f20942..c5c94b750 100644 --- a/helix-core/src/transaction.rs +++ b/helix-core/src/transaction.rs @@ -29,6 +29,12 @@ pub enum Assoc { /// Acts like `Before` if a word character is inserted /// before the position, otherwise acts like `After` BeforeWord, + /// Acts like `Before` but if the position is within an exact replacement + /// (exact size) the offset to the start of the replacement is kept + BeforeSticky, + /// Acts like `After` but if the position is within an exact replacement + /// (exact size) the offset to the start of the replacement is kept + AfterSticky, } impl Assoc { @@ -40,13 +46,17 @@ impl Assoc { fn insert_offset(self, s: &str) -> usize { let chars = s.chars().count(); match self { - Assoc::After => chars, + Assoc::After | Assoc::AfterSticky => chars, Assoc::AfterWord => s.chars().take_while(|&c| char_is_word(c)).count(), // return position before inserted text - Assoc::Before => 0, + Assoc::Before | Assoc::BeforeSticky => 0, Assoc::BeforeWord => chars - s.chars().rev().take_while(|&c| char_is_word(c)).count(), } } + + pub fn sticky(self) -> bool { + matches!(self, Assoc::BeforeSticky | Assoc::AfterSticky) + } } #[derive(Debug, Default, Clone, PartialEq, Eq)] @@ -456,8 +466,14 @@ impl ChangeSet { if pos == old_pos && assoc.stay_at_gaps() { new_pos } else { - // place to end of insert - new_pos + assoc.insert_offset(s) + let ins = assoc.insert_offset(s); + // if the deleted and inserted text have the exact same size + // keep the relative offset into the new text + if *len == ins && assoc.sticky() { + new_pos + (pos - old_pos) + } else { + new_pos + assoc.insert_offset(s) + } } }), i diff --git a/helix-loader/Cargo.toml b/helix-loader/Cargo.toml index d15d87f95..f74829f30 100644 --- a/helix-loader/Cargo.toml +++ b/helix-loader/Cargo.toml @@ -30,8 +30,8 @@ log = "0.4" # cloning/compiling tree-sitter grammars cc = { version = "1" } threadpool = { version = "1.0" } -tempfile = "3.10.1" -dunce = "1.0.4" +tempfile = "3.12.0" +dunce = "1.0.5" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] libloading = "0.8" diff --git a/helix-loader/src/lib.rs b/helix-loader/src/lib.rs index badb9bd64..f36c76c4f 100644 --- a/helix-loader/src/lib.rs +++ b/helix-loader/src/lib.rs @@ -225,13 +225,16 @@ pub fn merge_toml_values(left: toml::Value, right: toml::Value, merge_depth: usi /// Used as a ceiling dir for LSP root resolution, the filepicker and potentially as a future filewatching root /// /// This function starts searching the FS upward from the CWD -/// and returns the first directory that contains either `.git` or `.helix`. +/// and returns the first directory that contains either `.git`, `.svn` or `.helix`. /// If no workspace was found returns (CWD, true). /// Otherwise (workspace, false) is returned pub fn find_workspace() -> (PathBuf, bool) { let current_dir = current_working_dir(); for ancestor in current_dir.ancestors() { - if ancestor.join(".git").exists() || ancestor.join(".helix").exists() { + if ancestor.join(".git").exists() + || ancestor.join(".svn").exists() + || ancestor.join(".helix").exists() + { return (ancestor.to_owned(), false); } } diff --git a/helix-lsp-types/Cargo.lock b/helix-lsp-types/Cargo.lock new file mode 100644 index 000000000..11ac87521 --- /dev/null +++ b/helix-lsp-types/Cargo.lock @@ -0,0 +1,176 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "form_urlencoded" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "idna" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "itoa" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" + +[[package]] +name = "lsp-types" +version = "0.95.1" +dependencies = [ + "bitflags", + "serde", + "serde_json", + "serde_repr", + "url", +] + +[[package]] +name = "percent-encoding" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" + +[[package]] +name = "serde" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728eb6351430bccb993660dfffc5a72f91ccc1295abaa8ce19b27ebe4f75568b" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fa1584d3d1bcacd84c277a0dfe21f5b0f6accf4a23d04d4c6d61f1af522b4c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41feea4228a6f1cd09ec7a3593a682276702cd67b5273544757dae23c096f074" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe39d9fbb0ebf5eb2c7cb7e2a47e4f462fad1379f1166b8ae49ad9eae89a7ca" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fcd952facd492f9be3ef0d0b7032a6e442ee9b361d4acc2b1d0c4aaa5f613a1" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "unicode-bidi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "url" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] diff --git a/helix-lsp-types/Cargo.toml b/helix-lsp-types/Cargo.toml new file mode 100644 index 000000000..1ecb3d810 --- /dev/null +++ b/helix-lsp-types/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "helix-lsp-types" +version = "0.95.1" +authors = [ + # Original authors + "Markus Westerlind ", + "Bruno Medeiros ", + # Since forking + "Helix contributors" +] +edition = "2018" +description = "Types for interaction with a language server, using VSCode's Language Server Protocol" + +repository = "https://github.com/gluon-lang/lsp-types" +documentation = "https://docs.rs/lsp-types" + +readme = "README.md" + +keywords = ["language", "server", "lsp", "vscode", "lsif"] + +license = "MIT" + +[dependencies] +bitflags = "2.6.0" +serde = { version = "1.0.209", features = ["derive"] } +serde_json = "1.0.127" +serde_repr = "0.1" +url = {version = "2.0.0", features = ["serde"]} + +[features] +default = [] +# Enables proposed LSP extensions. +# NOTE: No semver compatibility is guaranteed for types enabled by this feature. +proposed = [] diff --git a/helix-lsp-types/LICENSE b/helix-lsp-types/LICENSE new file mode 100644 index 000000000..32781d976 --- /dev/null +++ b/helix-lsp-types/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 Markus Westerlind + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/helix-lsp-types/README.md b/helix-lsp-types/README.md new file mode 100644 index 000000000..01803be17 --- /dev/null +++ b/helix-lsp-types/README.md @@ -0,0 +1,3 @@ +# Helix's `lsp-types` + +This is a fork of the [`lsp-types`](https://crates.io/crates/lsp-types) crate ([`gluon-lang/lsp-types`](https://github.com/gluon-lang/lsp-types)) taken at version v0.95.1 (commit [3e6daee](https://github.com/gluon-lang/lsp-types/commit/3e6daee771d14db4094a554b8d03e29c310dfcbe)). This fork focuses usability improvements that make the types easier to work with for the Helix codebase. For example the URL type - the `uri` crate at this version of `lsp-types` - will be replaced with a wrapper around a string. diff --git a/helix-lsp-types/src/call_hierarchy.rs b/helix-lsp-types/src/call_hierarchy.rs new file mode 100644 index 000000000..dea78803f --- /dev/null +++ b/helix-lsp-types/src/call_hierarchy.rs @@ -0,0 +1,127 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use url::Url; + +use crate::{ + DynamicRegistrationClientCapabilities, PartialResultParams, Range, SymbolKind, SymbolTag, + TextDocumentPositionParams, WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +pub type CallHierarchyClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize, Copy)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize, Copy)] +#[serde(untagged)] +pub enum CallHierarchyServerCapability { + Simple(bool), + Options(CallHierarchyOptions), +} + +impl From for CallHierarchyServerCapability { + fn from(from: CallHierarchyOptions) -> Self { + Self::Options(from) + } +} + +impl From for CallHierarchyServerCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyPrepareParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyItem { + /// The name of this item. + pub name: String, + + /// The kind of this item. + pub kind: SymbolKind, + + /// Tags for this item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, + + /// More detail for this item, e.g. the signature of a function. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + + /// The resource identifier of this item. + pub uri: Url, + + /// The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. + pub range: Range, + + /// The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. + /// Must be contained by the [`range`](#CallHierarchyItem.range). + pub selection_range: Range, + + /// A data entry field that is preserved between a call hierarchy prepare and incoming calls or outgoing calls requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyIncomingCallsParams { + pub item: CallHierarchyItem, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// Represents an incoming call, e.g. a caller of a method or constructor. +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyIncomingCall { + /// The item that makes the call. + pub from: CallHierarchyItem, + + /// The range at which at which the calls appears. This is relative to the caller + /// denoted by [`this.from`](#CallHierarchyIncomingCall.from). + pub from_ranges: Vec, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyOutgoingCallsParams { + pub item: CallHierarchyItem, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. +#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CallHierarchyOutgoingCall { + /// The item that is called. + pub to: CallHierarchyItem, + + /// The range at which this item is called. This is the range relative to the caller, e.g the item + /// passed to [`provideCallHierarchyOutgoingCalls`](#CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls) + /// and not [`this.to`](#CallHierarchyOutgoingCall.to). + pub from_ranges: Vec, +} diff --git a/helix-lsp-types/src/code_action.rs b/helix-lsp-types/src/code_action.rs new file mode 100644 index 000000000..6cc39e0d0 --- /dev/null +++ b/helix-lsp-types/src/code_action.rs @@ -0,0 +1,395 @@ +use crate::{ + Command, Diagnostic, PartialResultParams, Range, TextDocumentIdentifier, + WorkDoneProgressOptions, WorkDoneProgressParams, WorkspaceEdit, +}; +use serde::{Deserialize, Serialize}; + +use serde_json::Value; + +use std::borrow::Cow; +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum CodeActionProviderCapability { + Simple(bool), + Options(CodeActionOptions), +} + +impl From for CodeActionProviderCapability { + fn from(from: CodeActionOptions) -> Self { + Self::Options(from) + } +} + +impl From for CodeActionProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionClientCapabilities { + /// + /// This capability supports dynamic registration. + /// + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client support code action literals as a valid + /// response of the `textDocument/codeAction` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub code_action_literal_support: Option, + + /// Whether code action supports the `isPreferred` property. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub is_preferred_support: Option, + + /// Whether code action supports the `disabled` property. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled_support: Option, + + /// Whether code action supports the `data` property which is + /// preserved between a `textDocument/codeAction` and a + /// `codeAction/resolve` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub data_support: Option, + + /// Whether the client supports resolving additional code action + /// properties via a separate `codeAction/resolve` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_support: Option, + + /// Whether the client honors the change annotations in + /// text edits and resource operations returned via the + /// `CodeAction#edit` property by for example presenting + /// the workspace edit in the user interface and asking + /// for confirmation. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub honors_change_annotations: Option, +} + +/// Whether the client supports resolving additional code action +/// properties via a separate `codeAction/resolve` request. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionCapabilityResolveSupport { + /// The properties that a client can resolve lazily. + pub properties: Vec, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionLiteralSupport { + /// The code action kind is support with the following value set. + pub code_action_kind: CodeActionKindLiteralSupport, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionKindLiteralSupport { + /// The code action kind values the client supports. When this + /// property exists the client also guarantees that it will + /// handle values outside its set gracefully and falls back + /// to a default value when unknown. + pub value_set: Vec, +} + +/// Params for the CodeActionRequest +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionParams { + /// The document in which the command was invoked. + pub text_document: TextDocumentIdentifier, + + /// The range for which the command was invoked. + pub range: Range, + + /// Context carrying additional information. + pub context: CodeActionContext, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// response for CodeActionRequest +pub type CodeActionResponse = Vec; + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(untagged)] +pub enum CodeActionOrCommand { + Command(Command), + CodeAction(CodeAction), +} + +impl From for CodeActionOrCommand { + fn from(command: Command) -> Self { + CodeActionOrCommand::Command(command) + } +} + +impl From for CodeActionOrCommand { + fn from(action: CodeAction) -> Self { + CodeActionOrCommand::CodeAction(action) + } +} + +#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)] +pub struct CodeActionKind(Cow<'static, str>); + +impl CodeActionKind { + /// Empty kind. + pub const EMPTY: CodeActionKind = CodeActionKind::new(""); + + /// Base kind for quickfix actions: 'quickfix' + pub const QUICKFIX: CodeActionKind = CodeActionKind::new("quickfix"); + + /// Base kind for refactoring actions: 'refactor' + pub const REFACTOR: CodeActionKind = CodeActionKind::new("refactor"); + + /// Base kind for refactoring extraction actions: 'refactor.extract' + /// + /// Example extract actions: + /// + /// - Extract method + /// - Extract function + /// - Extract variable + /// - Extract interface from class + /// - ... + pub const REFACTOR_EXTRACT: CodeActionKind = CodeActionKind::new("refactor.extract"); + + /// Base kind for refactoring inline actions: 'refactor.inline' + /// + /// Example inline actions: + /// + /// - Inline function + /// - Inline variable + /// - Inline constant + /// - ... + pub const REFACTOR_INLINE: CodeActionKind = CodeActionKind::new("refactor.inline"); + + /// Base kind for refactoring rewrite actions: 'refactor.rewrite' + /// + /// Example rewrite actions: + /// + /// - Convert JavaScript function to class + /// - Add or remove parameter + /// - Encapsulate field + /// - Make method static + /// - Move method to base class + /// - ... + pub const REFACTOR_REWRITE: CodeActionKind = CodeActionKind::new("refactor.rewrite"); + + /// Base kind for source actions: `source` + /// + /// Source code actions apply to the entire file. + pub const SOURCE: CodeActionKind = CodeActionKind::new("source"); + + /// Base kind for an organize imports source action: `source.organizeImports` + pub const SOURCE_ORGANIZE_IMPORTS: CodeActionKind = + CodeActionKind::new("source.organizeImports"); + + /// Base kind for a 'fix all' source action: `source.fixAll`. + /// + /// 'Fix all' actions automatically fix errors that have a clear fix that + /// do not require user input. They should not suppress errors or perform + /// unsafe fixes such as generating new types or classes. + /// + /// @since 3.17.0 + pub const SOURCE_FIX_ALL: CodeActionKind = CodeActionKind::new("source.fixAll"); + + pub const fn new(tag: &'static str) -> Self { + CodeActionKind(Cow::Borrowed(tag)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for CodeActionKind { + fn from(from: String) -> Self { + CodeActionKind(Cow::from(from)) + } +} + +impl From<&'static str> for CodeActionKind { + fn from(from: &'static str) -> Self { + CodeActionKind::new(from) + } +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeAction { + /// A short, human-readable, title for this code action. + pub title: String, + + /// The kind of the code action. + /// Used to filter code actions. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + + /// The diagnostics that this code action resolves. + #[serde(skip_serializing_if = "Option::is_none")] + pub diagnostics: Option>, + + /// The workspace edit this code action performs. + #[serde(skip_serializing_if = "Option::is_none")] + pub edit: Option, + + /// A command this code action executes. If a code action + /// provides an edit and a command, first the edit is + /// executed and then the command. + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + + /// Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted + /// by keybindings. + /// A quick fix should be marked preferred if it properly addresses the underlying error. + /// A refactoring should be marked preferred if it is the most reasonable choice of actions to take. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub is_preferred: Option, + + /// Marks that the code action cannot currently be applied. + /// + /// Clients should follow the following guidelines regarding disabled code actions: + /// + /// - Disabled code actions are not shown in automatic + /// [lightbulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) + /// code action menu. + /// + /// - Disabled actions are shown as faded out in the code action menu when the user request + /// a more specific type of code action, such as refactorings. + /// + /// - If the user has a keybinding that auto applies a code action and only a disabled code + /// actions are returned, the client should show the user an error message with `reason` + /// in the editor. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled: Option, + + /// A data entry field that is preserved on a code action between + /// a `textDocument/codeAction` and a `codeAction/resolve` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionDisabled { + /// Human readable description of why the code action is currently disabled. + /// + /// This is displayed in the code actions UI. + pub reason: String, +} + +/// The reason why code actions were requested. +/// +/// @since 3.17.0 +#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +#[serde(transparent)] +pub struct CodeActionTriggerKind(i32); +lsp_enum! { +impl CodeActionTriggerKind { + /// Code actions were explicitly requested by the user or by an extension. + pub const INVOKED: CodeActionTriggerKind = CodeActionTriggerKind(1); + + /// Code actions were requested automatically. + /// + /// This typically happens when current selection in a file changes, but can + /// also be triggered when file content changes. + pub const AUTOMATIC: CodeActionTriggerKind = CodeActionTriggerKind(2); +} +} + +/// Contains additional diagnostic information about the context in which +/// a code action is run. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionContext { + /// An array of diagnostics. + pub diagnostics: Vec, + + /// Requested kind of actions to return. + /// + /// Actions not of this kind are filtered out by the client before being shown. So servers + /// can omit computing them. + #[serde(skip_serializing_if = "Option::is_none")] + pub only: Option>, + + /// The reason why code actions were requested. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger_kind: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct CodeActionOptions { + /// CodeActionKinds that this server may return. + /// + /// The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server + /// may list out every specific kind they provide. + #[serde(skip_serializing_if = "Option::is_none")] + pub code_action_kinds: Option>, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, + + /// The server provides support to resolve additional + /// information for a code action. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_serialization; + + #[test] + fn test_code_action_response() { + test_serialization( + &vec![ + CodeActionOrCommand::Command(Command { + title: "title".to_string(), + command: "command".to_string(), + arguments: None, + }), + CodeActionOrCommand::CodeAction(CodeAction { + title: "title".to_string(), + kind: Some(CodeActionKind::QUICKFIX), + command: None, + diagnostics: None, + edit: None, + is_preferred: None, + ..CodeAction::default() + }), + ], + r#"[{"title":"title","command":"command"},{"title":"title","kind":"quickfix"}]"#, + ) + } +} diff --git a/helix-lsp-types/src/code_lens.rs b/helix-lsp-types/src/code_lens.rs new file mode 100644 index 000000000..c4c9c904e --- /dev/null +++ b/helix-lsp-types/src/code_lens.rs @@ -0,0 +1,66 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::{ + Command, DynamicRegistrationClientCapabilities, PartialResultParams, Range, + TextDocumentIdentifier, WorkDoneProgressParams, +}; + +pub type CodeLensClientCapabilities = DynamicRegistrationClientCapabilities; + +/// Code Lens options. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize, Copy)] +#[serde(rename_all = "camelCase")] +pub struct CodeLensOptions { + /// Code lens has a resolve provider as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeLensParams { + /// The document to request code lens for. + pub text_document: TextDocumentIdentifier, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// A code lens represents a command that should be shown along with +/// source text, like the number of references, a way to run tests, etc. +/// +/// A code lens is _unresolved_ when no command is associated to it. For performance +/// reasons the creation of a code lens and resolving should be done in two stages. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeLens { + /// The range in which this code lens is valid. Should only span a single line. + pub range: Range, + + /// The command this code lens represents. + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + + /// A data entry field that is preserved on a code lens item between + /// a code lens and a code lens resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeLensWorkspaceClientCapabilities { + /// Whether the client implementation supports a refresh request sent from the + /// server to the client. + /// + /// Note that this event is global and will force the client to refresh all + /// code lenses currently shown. It should be used with absolute care and is + /// useful for situation where a server for example detect a project wide + /// change that requires such a calculation. + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_support: Option, +} diff --git a/helix-lsp-types/src/color.rs b/helix-lsp-types/src/color.rs new file mode 100644 index 000000000..584f979ee --- /dev/null +++ b/helix-lsp-types/src/color.rs @@ -0,0 +1,122 @@ +use crate::{ + DocumentSelector, DynamicRegistrationClientCapabilities, PartialResultParams, Range, + TextDocumentIdentifier, TextEdit, WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; + +pub type DocumentColorClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ColorProviderOptions {} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StaticTextDocumentColorProviderOptions { + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. + pub document_selector: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum ColorProviderCapability { + Simple(bool), + ColorProvider(ColorProviderOptions), + Options(StaticTextDocumentColorProviderOptions), +} + +impl From for ColorProviderCapability { + fn from(from: ColorProviderOptions) -> Self { + Self::ColorProvider(from) + } +} + +impl From for ColorProviderCapability { + fn from(from: StaticTextDocumentColorProviderOptions) -> Self { + Self::Options(from) + } +} + +impl From for ColorProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentColorParams { + /// The text document + pub text_document: TextDocumentIdentifier, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ColorInformation { + /// The range in the document where this color appears. + pub range: Range, + /// The actual color value for this color range. + pub color: Color, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Copy)] +#[serde(rename_all = "camelCase")] +pub struct Color { + /// The red component of this color in the range [0-1]. + pub red: f32, + /// The green component of this color in the range [0-1]. + pub green: f32, + /// The blue component of this color in the range [0-1]. + pub blue: f32, + /// The alpha component of this color in the range [0-1]. + pub alpha: f32, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ColorPresentationParams { + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The color information to request presentations for. + pub color: Color, + + /// The range where the color would be inserted. Serves as a context. + pub range: Range, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Default, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ColorPresentation { + /// The label of this color presentation. It will be shown on the color + /// picker header. By default this is also the text that is inserted when selecting + /// this color presentation. + pub label: String, + + /// An [edit](#TextEdit) which is applied to a document when selecting + /// this presentation for the color. When `falsy` the [label](#ColorPresentation.label) + /// is used. + #[serde(skip_serializing_if = "Option::is_none")] + pub text_edit: Option, + + /// An optional array of additional [text edits](#TextEdit) that are applied when + /// selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_text_edits: Option>, +} diff --git a/helix-lsp-types/src/completion.rs b/helix-lsp-types/src/completion.rs new file mode 100644 index 000000000..2555228a7 --- /dev/null +++ b/helix-lsp-types/src/completion.rs @@ -0,0 +1,622 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + Command, Documentation, MarkupKind, PartialResultParams, TagSupport, + TextDocumentPositionParams, TextDocumentRegistrationOptions, TextEdit, WorkDoneProgressOptions, + WorkDoneProgressParams, +}; + +use crate::Range; +use serde_json::Value; +use std::fmt::Debug; + +/// Defines how to interpret the insert text in a completion item +#[derive(Eq, PartialEq, Clone, Copy, Serialize, Deserialize)] +#[serde(transparent)] +pub struct InsertTextFormat(i32); +lsp_enum! { +impl InsertTextFormat { + pub const PLAIN_TEXT: InsertTextFormat = InsertTextFormat(1); + pub const SNIPPET: InsertTextFormat = InsertTextFormat(2); +} +} + +/// The kind of a completion entry. +#[derive(Eq, PartialEq, Clone, Copy, Serialize, Deserialize)] +#[serde(transparent)] +pub struct CompletionItemKind(i32); +lsp_enum! { +impl CompletionItemKind { + pub const TEXT: CompletionItemKind = CompletionItemKind(1); + pub const METHOD: CompletionItemKind = CompletionItemKind(2); + pub const FUNCTION: CompletionItemKind = CompletionItemKind(3); + pub const CONSTRUCTOR: CompletionItemKind = CompletionItemKind(4); + pub const FIELD: CompletionItemKind = CompletionItemKind(5); + pub const VARIABLE: CompletionItemKind = CompletionItemKind(6); + pub const CLASS: CompletionItemKind = CompletionItemKind(7); + pub const INTERFACE: CompletionItemKind = CompletionItemKind(8); + pub const MODULE: CompletionItemKind = CompletionItemKind(9); + pub const PROPERTY: CompletionItemKind = CompletionItemKind(10); + pub const UNIT: CompletionItemKind = CompletionItemKind(11); + pub const VALUE: CompletionItemKind = CompletionItemKind(12); + pub const ENUM: CompletionItemKind = CompletionItemKind(13); + pub const KEYWORD: CompletionItemKind = CompletionItemKind(14); + pub const SNIPPET: CompletionItemKind = CompletionItemKind(15); + pub const COLOR: CompletionItemKind = CompletionItemKind(16); + pub const FILE: CompletionItemKind = CompletionItemKind(17); + pub const REFERENCE: CompletionItemKind = CompletionItemKind(18); + pub const FOLDER: CompletionItemKind = CompletionItemKind(19); + pub const ENUM_MEMBER: CompletionItemKind = CompletionItemKind(20); + pub const CONSTANT: CompletionItemKind = CompletionItemKind(21); + pub const STRUCT: CompletionItemKind = CompletionItemKind(22); + pub const EVENT: CompletionItemKind = CompletionItemKind(23); + pub const OPERATOR: CompletionItemKind = CompletionItemKind(24); + pub const TYPE_PARAMETER: CompletionItemKind = CompletionItemKind(25); +} +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionItemCapability { + /// Client supports snippets as insert text. + /// + /// A snippet can define tab stops and placeholders with `$1`, `$2` + /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to + /// the end of the snippet. Placeholders with equal identifiers are linked, + /// that is typing in one will update others too. + #[serde(skip_serializing_if = "Option::is_none")] + pub snippet_support: Option, + + /// Client supports commit characters on a completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub commit_characters_support: Option, + + /// Client supports the follow content formats for the documentation + /// property. The order describes the preferred format of the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub documentation_format: Option>, + + /// Client supports the deprecated property on a completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated_support: Option, + + /// Client supports the preselect property on a completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub preselect_support: Option, + + /// Client supports the tag property on a completion item. Clients supporting + /// tags have to handle unknown tags gracefully. Clients especially need to + /// preserve unknown tags when sending a completion item back to the server in + /// a resolve call. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "TagSupport::deserialize_compat" + )] + pub tag_support: Option>, + + /// Client support insert replace edit to control different behavior if a + /// completion item is inserted in the text or should replace text. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_replace_support: Option, + + /// Indicates which properties a client can resolve lazily on a completion + /// item. Before version 3.16.0 only the predefined properties `documentation` + /// and `details` could be resolved lazily. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_support: Option, + + /// The client supports the `insertTextMode` property on + /// a completion item to override the whitespace handling mode + /// as defined by the client. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text_mode_support: Option, + + /// The client has support for completion item label + /// details (see also `CompletionItemLabelDetails`). + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub label_details_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionItemCapabilityResolveSupport { + /// The properties that a client can resolve lazily. + pub properties: Vec, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InsertTextModeSupport { + pub value_set: Vec, +} + +/// How whitespace and indentation is handled during completion +/// item insertion. +/// +/// @since 3.16.0 +#[derive(Eq, PartialEq, Clone, Copy, Serialize, Deserialize)] +#[serde(transparent)] +pub struct InsertTextMode(i32); +lsp_enum! { +impl InsertTextMode { + /// The insertion or replace strings is taken as it is. If the + /// value is multi line the lines below the cursor will be + /// inserted using the indentation defined in the string value. + /// The client will not apply any kind of adjustments to the + /// string. + pub const AS_IS: InsertTextMode = InsertTextMode(1); + + /// The editor adjusts leading whitespace of new lines so that + /// they match the indentation up to the cursor of the line for + /// which the item is accepted. + /// + /// Consider a line like this: `<2tabs><3tabs>foo`. Accepting a + /// multi line completion item is indented using 2 tabs all + /// following lines inserted will be indented using 2 tabs as well. + pub const ADJUST_INDENTATION: InsertTextMode = InsertTextMode(2); +} +} + +#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct CompletionItemTag(i32); +lsp_enum! { +impl CompletionItemTag { + pub const DEPRECATED: CompletionItemTag = CompletionItemTag(1); +} +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionItemKindCapability { + /// The completion item kind values the client supports. When this + /// property exists the client also guarantees that it will + /// handle values outside its set gracefully and falls back + /// to a default value when unknown. + /// + /// If this property is not present the client only supports + /// the completion items kinds from `Text` to `Reference` as defined in + /// the initial version of the protocol. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_set: Option>, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionListCapability { + /// The client supports the following itemDefaults on + /// a completion list. + /// + /// The value lists the supported property names of the + /// `CompletionList.itemDefaults` object. If omitted + /// no properties are supported. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub item_defaults: Option>, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionClientCapabilities { + /// Whether completion supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client supports the following `CompletionItem` specific + /// capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_item: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_item_kind: Option, + + /// The client supports to send additional context information for a + /// `textDocument/completion` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub context_support: Option, + + /// The client's default when the completion item doesn't provide a + /// `insertTextMode` property. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text_mode: Option, + + /// The client supports the following `CompletionList` specific + /// capabilities. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_list: Option, +} + +/// A special text edit to provide an insert and a replace operation. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InsertReplaceEdit { + /// The string to be inserted. + pub new_text: String, + + /// The range if the insert is requested + pub insert: Range, + + /// The range if the replace is requested. + pub replace: Range, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum CompletionTextEdit { + Edit(TextEdit), + InsertAndReplace(InsertReplaceEdit), +} + +impl From for CompletionTextEdit { + fn from(edit: TextEdit) -> Self { + CompletionTextEdit::Edit(edit) + } +} + +impl From for CompletionTextEdit { + fn from(edit: InsertReplaceEdit) -> Self { + CompletionTextEdit::InsertAndReplace(edit) + } +} + +/// Completion options. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionOptions { + /// The server provides support to resolve additional information for a completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, + + /// Most tools trigger completion request automatically without explicitly + /// requesting it using a keyboard shortcut (e.g. Ctrl+Space). Typically they + /// do so when the user starts to type an identifier. For example if the user + /// types `c` in a JavaScript file code complete will automatically pop up + /// present `console` besides others as a completion item. Characters that + /// make up identifiers don't need to be listed here. + /// + /// If code complete should automatically be trigger on characters not being + /// valid inside an identifier (for example `.` in JavaScript) list them in + /// `triggerCharacters`. + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger_characters: Option>, + + /// The list of all possible characters that commit a completion. This field + /// can be used if clients don't support individual commit characters per + /// completion item. See client capability + /// `completion.completionItem.commitCharactersSupport`. + /// + /// If a server provides both `allCommitCharacters` and commit characters on + /// an individual completion item the ones on the completion item win. + /// + /// @since 3.2.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub all_commit_characters: Option>, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, + + /// The server supports the following `CompletionItem` specific + /// capabilities. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_item: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionOptionsCompletionItem { + /// The server has support for completion item label + /// details (see also `CompletionItemLabelDetails`) when receiving + /// a completion item in a resolve call. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub label_details_support: Option, +} + +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +pub struct CompletionRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub completion_options: CompletionOptions, +} + +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum CompletionResponse { + Array(Vec), + List(CompletionList), +} + +impl From> for CompletionResponse { + fn from(items: Vec) -> Self { + CompletionResponse::Array(items) + } +} + +impl From for CompletionResponse { + fn from(list: CompletionList) -> Self { + CompletionResponse::List(list) + } +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionParams { + // This field was "mixed-in" from TextDocumentPositionParams + #[serde(flatten)] + pub text_document_position: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + // CompletionParams properties: + #[serde(skip_serializing_if = "Option::is_none")] + pub context: Option, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionContext { + /// How the completion was triggered. + pub trigger_kind: CompletionTriggerKind, + + /// The trigger character (a single character) that has trigger code complete. + /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger_character: Option, +} + +/// How a completion was triggered. +#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +#[serde(transparent)] +pub struct CompletionTriggerKind(i32); +lsp_enum! { +impl CompletionTriggerKind { + pub const INVOKED: CompletionTriggerKind = CompletionTriggerKind(1); + pub const TRIGGER_CHARACTER: CompletionTriggerKind = CompletionTriggerKind(2); + pub const TRIGGER_FOR_INCOMPLETE_COMPLETIONS: CompletionTriggerKind = CompletionTriggerKind(3); +} +} + +/// Represents a collection of [completion items](#CompletionItem) to be presented +/// in the editor. +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionList { + /// This list it not complete. Further typing should result in recomputing + /// this list. + pub is_incomplete: bool, + + /// The completion items. + pub items: Vec, +} + +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CompletionItem { + /// The label of this completion item. By default + /// also the text that is inserted when selecting + /// this completion. + pub label: String, + + /// Additional details for the label + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub label_details: Option, + + /// The kind of this completion item. Based of the kind + /// an icon is chosen by the editor. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + + /// A human-readable string with additional information + /// about this item, like type or symbol information. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + + /// A human-readable string that represents a doc-comment. + #[serde(skip_serializing_if = "Option::is_none")] + pub documentation: Option, + + /// Indicates if this item is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + pub deprecated: Option, + + /// Select this item when showing. + #[serde(skip_serializing_if = "Option::is_none")] + pub preselect: Option, + + /// A string that should be used when comparing this item + /// with other items. When `falsy` the label is used + /// as the sort text for this item. + #[serde(skip_serializing_if = "Option::is_none")] + pub sort_text: Option, + + /// A string that should be used when filtering a set of + /// completion items. When `falsy` the label is used as the + /// filter text for this item. + #[serde(skip_serializing_if = "Option::is_none")] + pub filter_text: Option, + + /// A string that should be inserted into a document when selecting + /// this completion. When `falsy` the label is used as the insert text + /// for this item. + /// + /// The `insertText` is subject to interpretation by the client side. + /// Some tools might not take the string literally. For example + /// VS Code when code complete is requested in this example + /// `con` and a completion item with an `insertText` of + /// `console` is provided it will only insert `sole`. Therefore it is + /// recommended to use `textEdit` instead since it avoids additional client + /// side interpretation. + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text: Option, + + /// The format of the insert text. The format applies to both the `insertText` property + /// and the `newText` property of a provided `textEdit`. If omitted defaults to `InsertTextFormat.PlainText`. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text_format: Option, + + /// How whitespace and indentation is handled during completion + /// item insertion. If not provided the client's default value depends on + /// the `textDocument.completion.insertTextMode` client capability. + /// + /// @since 3.16.0 + /// @since 3.17.0 - support for `textDocument.completion.insertTextMode` + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text_mode: Option, + + /// An edit which is applied to a document when selecting + /// this completion. When an edit is provided the value of + /// insertText is ignored. + /// + /// Most editors support two different operation when accepting a completion item. One is to insert a + + /// completion text and the other is to replace an existing text with a completion text. Since this can + /// usually not predetermined by a server it can report both ranges. Clients need to signal support for + /// `InsertReplaceEdits` via the `textDocument.completion.insertReplaceSupport` client capability + /// property. + /// + /// *Note 1:* The text edit's range as well as both ranges from a insert replace edit must be a + /// [single line] and they must contain the position at which completion has been requested. + /// *Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range must be a prefix of + /// the edit's replace range, that means it must be contained and starting at the same position. + /// + /// @since 3.16.0 additional type `InsertReplaceEdit` + #[serde(skip_serializing_if = "Option::is_none")] + pub text_edit: Option, + + /// An optional array of additional text edits that are applied when + /// selecting this completion. Edits must not overlap with the main edit + /// nor with themselves. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_text_edits: Option>, + + /// An optional command that is executed *after* inserting this completion. *Note* that + /// additional modifications to the current document should be described with the + /// additionalTextEdits-property. + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + + /// An optional set of characters that when pressed while this completion is + /// active will accept it first and then type that character. *Note* that all + /// commit characters should have `length=1` and that superfluous characters + /// will be ignored. + #[serde(skip_serializing_if = "Option::is_none")] + pub commit_characters: Option>, + + /// An data entry field that is preserved on a completion item between + /// a completion and a completion resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, + + /// Tags for this completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, +} + +impl CompletionItem { + /// Create a CompletionItem with the minimum possible info (label and detail). + pub fn new_simple(label: String, detail: String) -> CompletionItem { + CompletionItem { + label, + detail: Some(detail), + ..Self::default() + } + } +} + +/// Additional details for a completion item label. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct CompletionItemLabelDetails { + /// An optional string which is rendered less prominently directly after + /// {@link CompletionItemLabel.label label}, without any spacing. Should be + /// used for function signatures or type annotations. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + + /// An optional string which is rendered less prominently after + /// {@link CompletionItemLabel.detail}. Should be used for fully qualified + /// names or file path. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_deserialization; + + #[test] + fn test_tag_support_deserialization() { + let empty = CompletionItemCapability { + tag_support: None, + ..CompletionItemCapability::default() + }; + + test_deserialization(r#"{}"#, &empty); + test_deserialization(r#"{"tagSupport": false}"#, &empty); + + let t = CompletionItemCapability { + tag_support: Some(TagSupport { value_set: vec![] }), + ..CompletionItemCapability::default() + }; + test_deserialization(r#"{"tagSupport": true}"#, &t); + + let t = CompletionItemCapability { + tag_support: Some(TagSupport { + value_set: vec![CompletionItemTag::DEPRECATED], + }), + ..CompletionItemCapability::default() + }; + test_deserialization(r#"{"tagSupport": {"valueSet": [1]}}"#, &t); + } + + #[test] + fn test_debug_enum() { + assert_eq!(format!("{:?}", CompletionItemKind::TEXT), "Text"); + assert_eq!( + format!("{:?}", CompletionItemKind::TYPE_PARAMETER), + "TypeParameter" + ); + } + + #[test] + fn test_try_from_enum() { + use std::convert::TryInto; + assert_eq!("Text".try_into(), Ok(CompletionItemKind::TEXT)); + assert_eq!( + "TypeParameter".try_into(), + Ok(CompletionItemKind::TYPE_PARAMETER) + ); + } +} diff --git a/helix-lsp-types/src/document_diagnostic.rs b/helix-lsp-types/src/document_diagnostic.rs new file mode 100644 index 000000000..a2b5c41fa --- /dev/null +++ b/helix-lsp-types/src/document_diagnostic.rs @@ -0,0 +1,269 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::{ + Diagnostic, PartialResultParams, StaticRegistrationOptions, TextDocumentIdentifier, + TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +/// Client capabilities specific to diagnostic pull requests. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DiagnosticClientCapabilities { + /// Whether implementation supports dynamic registration. + /// + /// If this is set to `true` the client supports the new `(TextDocumentRegistrationOptions & + /// StaticRegistrationOptions)` return value for the corresponding server capability as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Whether the clients supports related documents for document diagnostic pulls. + #[serde(skip_serializing_if = "Option::is_none")] + pub related_document_support: Option, +} + +/// Diagnostic options. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DiagnosticOptions { + /// An optional identifier under which the diagnostics are + /// managed by the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub identifier: Option, + + /// Whether the language has inter file dependencies, meaning that editing code in one file can + /// result in a different diagnostic set in another file. Inter file dependencies are common + /// for most programming languages and typically uncommon for linters. + pub inter_file_dependencies: bool, + + /// The server provides support for workspace diagnostics as well. + pub workspace_diagnostics: bool, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +/// Diagnostic registration options. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DiagnosticRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub diagnostic_options: DiagnosticOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum DiagnosticServerCapabilities { + Options(DiagnosticOptions), + RegistrationOptions(DiagnosticRegistrationOptions), +} + +/// Parameters of the document diagnostic request. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentDiagnosticParams { + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The additional identifier provided during registration. + pub identifier: Option, + + /// The result ID of a previous response if provided. + pub previous_result_id: Option, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// A diagnostic report with a full set of problems. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct FullDocumentDiagnosticReport { + /// An optional result ID. If provided it will be sent on the next diagnostic request for the + /// same document. + #[serde(skip_serializing_if = "Option::is_none")] + pub result_id: Option, + + /// The actual items. + pub items: Vec, +} + +/// A diagnostic report indicating that the last returned report is still accurate. +/// +/// A server can only return `unchanged` if result ids are provided. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct UnchangedDocumentDiagnosticReport { + /// A result ID which will be sent on the next diagnostic request for the same document. + pub result_id: String, +} + +/// The document diagnostic report kinds. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum DocumentDiagnosticReportKind { + /// A diagnostic report with a full set of problems. + Full(FullDocumentDiagnosticReport), + /// A report indicating that the last returned report is still accurate. + Unchanged(UnchangedDocumentDiagnosticReport), +} + +impl From for DocumentDiagnosticReportKind { + fn from(from: FullDocumentDiagnosticReport) -> Self { + DocumentDiagnosticReportKind::Full(from) + } +} + +impl From for DocumentDiagnosticReportKind { + fn from(from: UnchangedDocumentDiagnosticReport) -> Self { + DocumentDiagnosticReportKind::Unchanged(from) + } +} + +/// A full diagnostic report with a set of related documents. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct RelatedFullDocumentDiagnosticReport { + /// Diagnostics of related documents. + /// + /// This information is useful in programming languages where code in a file A can generate + /// diagnostics in a file B which A depends on. An example of such a language is C/C++ where + /// macro definitions in a file `a.cpp` result in errors in a header file `b.hpp`. + /// + /// @since 3.17.0 + #[serde(with = "crate::url_map")] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub related_documents: Option>, + // relatedDocuments?: { [uri: string]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; }; + #[serde(flatten)] + pub full_document_diagnostic_report: FullDocumentDiagnosticReport, +} + +/// An unchanged diagnostic report with a set of related documents. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct RelatedUnchangedDocumentDiagnosticReport { + /// Diagnostics of related documents. + /// + /// This information is useful in programming languages where code in a file A can generate + /// diagnostics in a file B which A depends on. An example of such a language is C/C++ where + /// macro definitions in a file `a.cpp` result in errors in a header file `b.hpp`. + /// + /// @since 3.17.0 + #[serde(with = "crate::url_map")] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub related_documents: Option>, + // relatedDocuments?: { [uri: string]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; }; + #[serde(flatten)] + pub unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport, +} + +/// The result of a document diagnostic pull request. +/// +/// A report can either be a full report containing all diagnostics for the requested document or +/// an unchanged report indicating that nothing has changed in terms of diagnostics in comparison +/// to the last pull request. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum DocumentDiagnosticReport { + /// A diagnostic report with a full set of problems. + Full(RelatedFullDocumentDiagnosticReport), + /// A report indicating that the last returned report is still accurate. + Unchanged(RelatedUnchangedDocumentDiagnosticReport), +} + +impl From for DocumentDiagnosticReport { + fn from(from: RelatedFullDocumentDiagnosticReport) -> Self { + DocumentDiagnosticReport::Full(from) + } +} + +impl From for DocumentDiagnosticReport { + fn from(from: RelatedUnchangedDocumentDiagnosticReport) -> Self { + DocumentDiagnosticReport::Unchanged(from) + } +} + +/// A partial result for a document diagnostic report. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DocumentDiagnosticReportPartialResult { + #[serde(with = "crate::url_map")] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub related_documents: Option>, + // relatedDocuments?: { [uri: string]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; }; +} + +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(untagged)] +pub enum DocumentDiagnosticReportResult { + Report(DocumentDiagnosticReport), + Partial(DocumentDiagnosticReportPartialResult), +} + +impl From for DocumentDiagnosticReportResult { + fn from(from: DocumentDiagnosticReport) -> Self { + DocumentDiagnosticReportResult::Report(from) + } +} + +impl From for DocumentDiagnosticReportResult { + fn from(from: DocumentDiagnosticReportPartialResult) -> Self { + DocumentDiagnosticReportResult::Partial(from) + } +} + +/// Cancellation data returned from a diagnostic request. +/// +/// If no data is provided, it defaults to `{ retrigger_request: true }`. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct DiagnosticServerCancellationData { + pub retrigger_request: bool, +} + +impl Default for DiagnosticServerCancellationData { + fn default() -> Self { + DiagnosticServerCancellationData { + retrigger_request: true, + } + } +} diff --git a/helix-lsp-types/src/document_highlight.rs b/helix-lsp-types/src/document_highlight.rs new file mode 100644 index 000000000..f2954e6d9 --- /dev/null +++ b/helix-lsp-types/src/document_highlight.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + DynamicRegistrationClientCapabilities, PartialResultParams, Range, TextDocumentPositionParams, + WorkDoneProgressParams, +}; + +pub type DocumentHighlightClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentHighlightParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// A document highlight is a range inside a text document which deserves +/// special attention. Usually a document highlight is visualized by changing +/// the background color of its range. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct DocumentHighlight { + /// The range this highlight applies to. + pub range: Range, + + /// The highlight kind, default is DocumentHighlightKind.Text. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, +} + +/// A document highlight kind. +#[derive(Eq, PartialEq, Copy, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct DocumentHighlightKind(i32); +lsp_enum! { +impl DocumentHighlightKind { + /// A textual occurrence. + pub const TEXT: DocumentHighlightKind = DocumentHighlightKind(1); + + /// Read-access of a symbol, like reading a variable. + pub const READ: DocumentHighlightKind = DocumentHighlightKind(2); + + /// Write-access of a symbol, like writing to a variable. + pub const WRITE: DocumentHighlightKind = DocumentHighlightKind(3); +} +} diff --git a/helix-lsp-types/src/document_link.rs b/helix-lsp-types/src/document_link.rs new file mode 100644 index 000000000..1400dd96b --- /dev/null +++ b/helix-lsp-types/src/document_link.rs @@ -0,0 +1,67 @@ +use crate::{ + PartialResultParams, Range, TextDocumentIdentifier, WorkDoneProgressOptions, + WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use url::Url; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentLinkClientCapabilities { + /// Whether document link supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Whether the client support the `tooltip` property on `DocumentLink`. + #[serde(skip_serializing_if = "Option::is_none")] + pub tooltip_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentLinkOptions { + /// Document links have a resolve provider as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentLinkParams { + /// The document to provide document links for. + pub text_document: TextDocumentIdentifier, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// A document link is a range in a text document that links to an internal or external resource, like another +/// text document or a web site. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct DocumentLink { + /// The range this link applies to. + pub range: Range, + /// The uri this link points to. + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + + /// The tooltip text when you hover over this link. + /// + /// If a tooltip is provided, is will be displayed in a string that includes instructions on how to + /// trigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS, + /// user settings, and localization. + #[serde(skip_serializing_if = "Option::is_none")] + pub tooltip: Option, + + /// A data entry field that is preserved on a document link between a DocumentLinkRequest + /// and a DocumentLinkResolveRequest. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} diff --git a/helix-lsp-types/src/document_symbols.rs b/helix-lsp-types/src/document_symbols.rs new file mode 100644 index 000000000..3f482e166 --- /dev/null +++ b/helix-lsp-types/src/document_symbols.rs @@ -0,0 +1,134 @@ +use crate::{ + Location, PartialResultParams, Range, SymbolKind, SymbolKindCapability, TextDocumentIdentifier, + WorkDoneProgressParams, +}; + +use crate::{SymbolTag, TagSupport}; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentSymbolClientCapabilities { + /// This capability supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Specific capabilities for the `SymbolKind`. + #[serde(skip_serializing_if = "Option::is_none")] + pub symbol_kind: Option, + + /// The client support hierarchical document symbols. + #[serde(skip_serializing_if = "Option::is_none")] + pub hierarchical_document_symbol_support: Option, + + /// The client supports tags on `SymbolInformation`. Tags are supported on + /// `DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true. + /// Clients supporting tags have to handle unknown tags gracefully. + /// + /// @since 3.16.0 + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "TagSupport::deserialize_compat" + )] + pub tag_support: Option>, +} + +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DocumentSymbolResponse { + Flat(Vec), + Nested(Vec), +} + +impl From> for DocumentSymbolResponse { + fn from(info: Vec) -> Self { + DocumentSymbolResponse::Flat(info) + } +} + +impl From> for DocumentSymbolResponse { + fn from(symbols: Vec) -> Self { + DocumentSymbolResponse::Nested(symbols) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentSymbolParams { + /// The text document. + pub text_document: TextDocumentIdentifier, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// Represents programming constructs like variables, classes, interfaces etc. +/// that appear in a document. Document symbols can be hierarchical and they have two ranges: +/// one that encloses its definition and one that points to its most interesting range, +/// e.g. the range of an identifier. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentSymbol { + /// The name of this symbol. + pub name: String, + /// More detail for this symbol, e.g the signature of a function. If not provided the + /// name is used. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + /// The kind of this symbol. + pub kind: SymbolKind, + /// Tags for this completion item. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, + /// Indicates if this symbol is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + #[deprecated(note = "Use tags instead")] + pub deprecated: Option, + /// The range enclosing this symbol not including leading/trailing whitespace but everything else + /// like comments. This information is typically used to determine if the the clients cursor is + /// inside the symbol to reveal in the symbol in the UI. + pub range: Range, + /// The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. + /// Must be contained by the the `range`. + pub selection_range: Range, + /// Children of this symbol, e.g. properties of a class. + #[serde(skip_serializing_if = "Option::is_none")] + pub children: Option>, +} + +/// Represents information about programming constructs like variables, classes, +/// interfaces etc. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SymbolInformation { + /// The name of this symbol. + pub name: String, + + /// The kind of this symbol. + pub kind: SymbolKind, + + /// Tags for this completion item. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, + + /// Indicates if this symbol is deprecated. + #[serde(skip_serializing_if = "Option::is_none")] + #[deprecated(note = "Use tags instead")] + pub deprecated: Option, + + /// The location of this symbol. + pub location: Location, + + /// The name of the symbol containing this symbol. + #[serde(skip_serializing_if = "Option::is_none")] + pub container_name: Option, +} diff --git a/helix-lsp-types/src/error_codes.rs b/helix-lsp-types/src/error_codes.rs new file mode 100644 index 000000000..f09fae168 --- /dev/null +++ b/helix-lsp-types/src/error_codes.rs @@ -0,0 +1,54 @@ +//! In this module we only define constants for lsp specific error codes. +//! There are other error codes that are defined in the +//! [JSON RPC specification](https://www.jsonrpc.org/specification#error_object). + +/// Defined in the LSP specification but in the range reserved for JSON-RPC error codes, +/// namely the -32099 to -32000 "Reserved for implementation-defined server-errors." range. +/// The code has, nonetheless, been left in this range for backwards compatibility reasons. +pub const SERVER_NOT_INITIALIZED: i64 = -32002; + +/// Defined in the LSP specification but in the range reserved for JSON-RPC error codes, +/// namely the -32099 to -32000 "Reserved for implementation-defined server-errors." range. +/// The code has, nonetheless, left in this range for backwards compatibility reasons. +pub const UNKNOWN_ERROR_CODE: i64 = -32001; + +/// This is the start range of LSP reserved error codes. +/// It doesn't denote a real error code. +/// +/// @since 3.16.0 +pub const LSP_RESERVED_ERROR_RANGE_START: i64 = -32899; + +/// A request failed but it was syntactically correct, e.g the +/// method name was known and the parameters were valid. The error +/// message should contain human readable information about why +/// the request failed. +/// +/// @since 3.17.0 +pub const REQUEST_FAILED: i64 = -32803; + +/// The server cancelled the request. This error code should +/// only be used for requests that explicitly support being +/// server cancellable. +/// +/// @since 3.17.0 +pub const SERVER_CANCELLED: i64 = -32802; + +/// The server detected that the content of a document got +/// modified outside normal conditions. A server should +/// NOT send this error code if it detects a content change +/// in it unprocessed messages. The result even computed +/// on an older state might still be useful for the client. +/// +/// If a client decides that a result is not of any use anymore +/// the client should cancel the request. +pub const CONTENT_MODIFIED: i64 = -32801; + +/// The client has canceled a request and a server as detected +/// the cancel. +pub const REQUEST_CANCELLED: i64 = -32800; + +/// This is the end range of LSP reserved error codes. +/// It doesn't denote a real error code. +/// +/// @since 3.16.0 +pub const LSP_RESERVED_ERROR_RANGE_END: i64 = -32800; diff --git a/helix-lsp-types/src/file_operations.rs b/helix-lsp-types/src/file_operations.rs new file mode 100644 index 000000000..52572f931 --- /dev/null +++ b/helix-lsp-types/src/file_operations.rs @@ -0,0 +1,213 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFileOperationsClientCapabilities { + /// Whether the client supports dynamic registration for file + /// requests/notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client has support for sending didCreateFiles notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_create: Option, + + /// The server is interested in receiving willCreateFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_create: Option, + + /// The server is interested in receiving didRenameFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_rename: Option, + + /// The server is interested in receiving willRenameFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_rename: Option, + + /// The server is interested in receiving didDeleteFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_delete: Option, + + /// The server is interested in receiving willDeleteFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_delete: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFileOperationsServerCapabilities { + /// The server is interested in receiving didCreateFiles + /// notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_create: Option, + + /// The server is interested in receiving willCreateFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_create: Option, + + /// The server is interested in receiving didRenameFiles + /// notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_rename: Option, + + /// The server is interested in receiving willRenameFiles requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_rename: Option, + + /// The server is interested in receiving didDeleteFiles file + /// notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_delete: Option, + + /// The server is interested in receiving willDeleteFiles file + /// requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_delete: Option, +} + +/// The options to register for file operations. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileOperationRegistrationOptions { + /// The actual filters. + pub filters: Vec, +} + +/// A filter to describe in which file operation requests or notifications +/// the server is interested in. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileOperationFilter { + /// A Uri like `file` or `untitled`. + pub scheme: Option, + + /// The actual file operation pattern. + pub pattern: FileOperationPattern, +} + +/// A pattern kind describing if a glob pattern matches a file a folder or +/// both. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "lowercase")] +pub enum FileOperationPatternKind { + /// The pattern matches a file only. + File, + + /// The pattern matches a folder only. + Folder, +} + +/// Matching options for the file operation pattern. +/// +/// @since 3.16.0 +/// +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileOperationPatternOptions { + /// The pattern should be matched ignoring casing. + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore_case: Option, +} + +/// A pattern to describe in which file operation requests or notifications +/// the server is interested in. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileOperationPattern { + /// The glob pattern to match. Glob patterns can have the following syntax: + /// - `*` to match one or more characters in a path segment + /// - `?` to match on one character in a path segment + /// - `**` to match any number of path segments, including none + /// - `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript + /// and JavaScript files) + /// - `[]` to declare a range of characters to match in a path segment + /// (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) + /// - `[!...]` to negate a range of characters to match in a path segment + /// (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but + /// not `example.0`) + pub glob: String, + + /// Whether to match files or folders with this pattern. + /// + /// Matches both if undefined. + #[serde(skip_serializing_if = "Option::is_none")] + pub matches: Option, + + /// Additional options used during matching. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, +} + +/// The parameters sent in notifications/requests for user-initiated creation +/// of files. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateFilesParams { + /// An array of all files/folders created in this operation. + pub files: Vec, +} +/// Represents information on a file/folder create. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileCreate { + /// A file:// URI for the location of the file/folder being created. + pub uri: String, +} + +/// The parameters sent in notifications/requests for user-initiated renames +/// of files. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameFilesParams { + /// An array of all files/folders renamed in this operation. When a folder + /// is renamed, only the folder will be included, and not its children. + pub files: Vec, +} + +/// Represents information on a file/folder rename. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileRename { + /// A file:// URI for the original location of the file/folder being renamed. + pub old_uri: String, + + /// A file:// URI for the new location of the file/folder being renamed. + pub new_uri: String, +} + +/// The parameters sent in notifications/requests for user-initiated deletes +/// of files. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeleteFilesParams { + /// An array of all files/folders deleted in this operation. + pub files: Vec, +} + +/// Represents information on a file/folder delete. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileDelete { + /// A file:// URI for the location of the file/folder being deleted. + pub uri: String, +} diff --git a/helix-lsp-types/src/folding_range.rs b/helix-lsp-types/src/folding_range.rs new file mode 100644 index 000000000..c9109ebf3 --- /dev/null +++ b/helix-lsp-types/src/folding_range.rs @@ -0,0 +1,145 @@ +use crate::{ + PartialResultParams, StaticTextDocumentColorProviderOptions, TextDocumentIdentifier, + WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoldingRangeParams { + /// The text document. + pub text_document: TextDocumentIdentifier, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum FoldingRangeProviderCapability { + Simple(bool), + FoldingProvider(FoldingProviderOptions), + Options(StaticTextDocumentColorProviderOptions), +} + +impl From for FoldingRangeProviderCapability { + fn from(from: StaticTextDocumentColorProviderOptions) -> Self { + Self::Options(from) + } +} + +impl From for FoldingRangeProviderCapability { + fn from(from: FoldingProviderOptions) -> Self { + Self::FoldingProvider(from) + } +} + +impl From for FoldingRangeProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct FoldingProviderOptions {} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoldingRangeKindCapability { + /// The folding range kind values the client supports. When this + /// property exists the client also guarantees that it will + /// handle values outside its set gracefully and falls back + /// to a default value when unknown. + #[serde(skip_serializing_if = "Option::is_none")] + pub value_set: Option>, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoldingRangeCapability { + /// If set, the client signals that it supports setting collapsedText on + /// folding ranges to display custom labels instead of the default text. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub collapsed_text: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoldingRangeClientCapabilities { + /// Whether implementation supports dynamic registration for folding range providers. If this is set to `true` + /// the client supports the new `(FoldingRangeProviderOptions & TextDocumentRegistrationOptions & StaticRegistrationOptions)` + /// return value for the corresponding server capability as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The maximum number of folding ranges that the client prefers to receive per document. The value serves as a + /// hint, servers are free to follow the limit. + #[serde(skip_serializing_if = "Option::is_none")] + pub range_limit: Option, + + /// If set, the client signals that it only supports folding complete lines. If set, client will + /// ignore specified `startCharacter` and `endCharacter` properties in a FoldingRange. + #[serde(skip_serializing_if = "Option::is_none")] + pub line_folding_only: Option, + + /// Specific options for the folding range kind. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub folding_range_kind: Option, + + /// Specific options for the folding range. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub folding_range: Option, +} + +/// Enum of known range kinds +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "lowercase")] +pub enum FoldingRangeKind { + /// Folding range for a comment + Comment, + /// Folding range for a imports or includes + Imports, + /// Folding range for a region (e.g. `#region`) + Region, +} + +/// Represents a folding range. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FoldingRange { + /// The zero-based line number from where the folded range starts. + pub start_line: u32, + + /// The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. + #[serde(skip_serializing_if = "Option::is_none")] + pub start_character: Option, + + /// The zero-based line number where the folded range ends. + pub end_line: u32, + + /// The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. + #[serde(skip_serializing_if = "Option::is_none")] + pub end_character: Option, + + /// Describes the kind of the folding range such as `comment' or 'region'. The kind + /// is used to categorize folding ranges and used by commands like 'Fold all comments'. See + /// [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + + /// The text that the client should show when the specified range is + /// collapsed. If not defined or not supported by the client, a default + /// will be chosen by the client. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub collapsed_text: Option, +} diff --git a/helix-lsp-types/src/formatting.rs b/helix-lsp-types/src/formatting.rs new file mode 100644 index 000000000..4e5593c83 --- /dev/null +++ b/helix-lsp-types/src/formatting.rs @@ -0,0 +1,153 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + DocumentSelector, DynamicRegistrationClientCapabilities, Range, TextDocumentIdentifier, + TextDocumentPositionParams, WorkDoneProgressParams, +}; + +use std::collections::HashMap; + +pub type DocumentFormattingClientCapabilities = DynamicRegistrationClientCapabilities; +pub type DocumentRangeFormattingClientCapabilities = DynamicRegistrationClientCapabilities; +pub type DocumentOnTypeFormattingClientCapabilities = DynamicRegistrationClientCapabilities; + +/// Format document on type options +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentOnTypeFormattingOptions { + /// A character on which formatting should be triggered, like `}`. + pub first_trigger_character: String, + + /// More trigger characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub more_trigger_character: Option>, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentFormattingParams { + /// The document to format. + pub text_document: TextDocumentIdentifier, + + /// The format options. + pub options: FormattingOptions, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +/// Value-object describing what options formatting should use. +#[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FormattingOptions { + /// Size of a tab in spaces. + pub tab_size: u32, + + /// Prefer spaces over tabs. + pub insert_spaces: bool, + + /// Signature for further properties. + #[serde(flatten)] + pub properties: HashMap, + + /// Trim trailing whitespace on a line. + #[serde(skip_serializing_if = "Option::is_none")] + pub trim_trailing_whitespace: Option, + + /// Insert a newline character at the end of the file if one does not exist. + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_final_newline: Option, + + /// Trim all newlines after the final newline at the end of the file. + #[serde(skip_serializing_if = "Option::is_none")] + pub trim_final_newlines: Option, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum FormattingProperty { + Bool(bool), + Number(i32), + String(String), +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentRangeFormattingParams { + /// The document to format. + pub text_document: TextDocumentIdentifier, + + /// The range to format + pub range: Range, + + /// The format options + pub options: FormattingOptions, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentOnTypeFormattingParams { + /// Text Document and Position fields. + #[serde(flatten)] + pub text_document_position: TextDocumentPositionParams, + + /// The character that has been typed. + pub ch: String, + + /// The format options. + pub options: FormattingOptions, +} + +/// Extends TextDocumentRegistrationOptions +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentOnTypeFormattingRegistrationOptions { + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. + pub document_selector: Option, + + /// A character on which formatting should be triggered, like `}`. + pub first_trigger_character: String, + + /// More trigger characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub more_trigger_character: Option>, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_serialization; + + #[test] + fn formatting_options() { + test_serialization( + &FormattingOptions { + tab_size: 123, + insert_spaces: true, + properties: HashMap::new(), + trim_trailing_whitespace: None, + insert_final_newline: None, + trim_final_newlines: None, + }, + r#"{"tabSize":123,"insertSpaces":true}"#, + ); + + test_serialization( + &FormattingOptions { + tab_size: 123, + insert_spaces: true, + properties: vec![("prop".to_string(), FormattingProperty::Number(1))] + .into_iter() + .collect(), + trim_trailing_whitespace: None, + insert_final_newline: None, + trim_final_newlines: None, + }, + r#"{"tabSize":123,"insertSpaces":true,"prop":1}"#, + ); + } +} diff --git a/helix-lsp-types/src/hover.rs b/helix-lsp-types/src/hover.rs new file mode 100644 index 000000000..01bd2f8d1 --- /dev/null +++ b/helix-lsp-types/src/hover.rs @@ -0,0 +1,86 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + MarkedString, MarkupContent, MarkupKind, Range, TextDocumentPositionParams, + TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HoverClientCapabilities { + /// Whether completion supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Client supports the follow content formats for the content + /// property. The order describes the preferred format of the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub content_format: Option>, +} + +/// Hover options. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HoverOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HoverRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub hover_options: HoverOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum HoverProviderCapability { + Simple(bool), + Options(HoverOptions), +} + +impl From for HoverProviderCapability { + fn from(from: HoverOptions) -> Self { + Self::Options(from) + } +} + +impl From for HoverProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HoverParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +/// The result of a hover request. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct Hover { + /// The hover's content + pub contents: HoverContents, + /// An optional range is a range inside a text document + /// that is used to visualize a hover, e.g. by changing the background color. + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, +} + +/// Hover contents could be single entry or multiple entries. +#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum HoverContents { + Scalar(MarkedString), + Array(Vec), + Markup(MarkupContent), +} diff --git a/helix-lsp-types/src/inlay_hint.rs b/helix-lsp-types/src/inlay_hint.rs new file mode 100644 index 000000000..171f3c9d1 --- /dev/null +++ b/helix-lsp-types/src/inlay_hint.rs @@ -0,0 +1,281 @@ +use crate::{ + Command, LSPAny, Location, MarkupContent, Position, Range, StaticRegistrationOptions, + TextDocumentIdentifier, TextDocumentRegistrationOptions, TextEdit, WorkDoneProgressOptions, + WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum InlayHintServerCapabilities { + Options(InlayHintOptions), + RegistrationOptions(InlayHintRegistrationOptions), +} + +/// Inlay hint client capabilities. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintClientCapabilities { + /// Whether inlay hints support dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Indicates which properties a client can resolve lazily on a inlay + /// hint. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_support: Option, +} + +/// Inlay hint options used during static registration. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, + + /// The server provides support to resolve additional + /// information for an inlay hint item. + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, +} + +/// Inlay hint options used during static or dynamic registration. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintRegistrationOptions { + #[serde(flatten)] + pub inlay_hint_options: InlayHintOptions, + + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +/// A parameter literal used in inlay hint requests. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The visible document range for which inlay hints should be computed. + pub range: Range, +} + +/// Inlay hint information. +/// +/// @since 3.17.0 +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHint { + /// The position of this hint. + pub position: Position, + + /// The label of this hint. A human readable string or an array of + /// InlayHintLabelPart label parts. + /// + /// *Note* that neither the string nor the label part can be empty. + pub label: InlayHintLabel, + + /// The kind of this hint. Can be omitted in which case the client + /// should fall back to a reasonable default. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + + /// Optional text edits that are performed when accepting this inlay hint. + /// + /// *Note* that edits are expected to change the document so that the inlay + /// hint (or its nearest variant) is now part of the document and the inlay + /// hint itself is now obsolete. + /// + /// Depending on the client capability `inlayHint.resolveSupport` clients + /// might resolve this property late using the resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub text_edits: Option>, + + /// The tooltip text when you hover over this item. + /// + /// Depending on the client capability `inlayHint.resolveSupport` clients + /// might resolve this property late using the resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub tooltip: Option, + + /// Render padding before the hint. + /// + /// Note: Padding should use the editor's background color, not the + /// background color of the hint itself. That means padding can be used + /// to visually align/separate an inlay hint. + #[serde(skip_serializing_if = "Option::is_none")] + pub padding_left: Option, + + /// Render padding after the hint. + /// + /// Note: Padding should use the editor's background color, not the + /// background color of the hint itself. That means padding can be used + /// to visually align/separate an inlay hint. + #[serde(skip_serializing_if = "Option::is_none")] + pub padding_right: Option, + + /// A data entry field that is preserved on a inlay hint between + /// a `textDocument/inlayHint` and a `inlayHint/resolve` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InlayHintLabel { + String(String), + LabelParts(Vec), +} + +impl From for InlayHintLabel { + #[inline] + fn from(from: String) -> Self { + Self::String(from) + } +} + +impl From> for InlayHintLabel { + #[inline] + fn from(from: Vec) -> Self { + Self::LabelParts(from) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InlayHintTooltip { + String(String), + MarkupContent(MarkupContent), +} + +impl From for InlayHintTooltip { + #[inline] + fn from(from: String) -> Self { + Self::String(from) + } +} + +impl From for InlayHintTooltip { + #[inline] + fn from(from: MarkupContent) -> Self { + Self::MarkupContent(from) + } +} + +/// An inlay hint label part allows for interactive and composite labels +/// of inlay hints. +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintLabelPart { + /// The value of this label part. + pub value: String, + + /// The tooltip text when you hover over this label part. Depending on + /// the client capability `inlayHint.resolveSupport` clients might resolve + /// this property late using the resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub tooltip: Option, + + /// An optional source code location that represents this + /// label part. + /// + /// The editor will use this location for the hover and for code navigation + /// features: This part will become a clickable link that resolves to the + /// definition of the symbol at the given location (not necessarily the + /// location itself), it shows the hover that shows at the given location, + /// and it shows a context menu with further code navigation commands. + /// + /// Depending on the client capability `inlayHint.resolveSupport` clients + /// might resolve this property late using the resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub location: Option, + + /// An optional command for this label part. + /// + /// Depending on the client capability `inlayHint.resolveSupport` clients + /// might resolve this property late using the resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InlayHintLabelPartTooltip { + String(String), + MarkupContent(MarkupContent), +} + +impl From for InlayHintLabelPartTooltip { + #[inline] + fn from(from: String) -> Self { + Self::String(from) + } +} + +impl From for InlayHintLabelPartTooltip { + #[inline] + fn from(from: MarkupContent) -> Self { + Self::MarkupContent(from) + } +} + +/// Inlay hint kinds. +/// +/// @since 3.17.0 +#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] +#[serde(transparent)] +pub struct InlayHintKind(i32); +lsp_enum! { +impl InlayHintKind { + /// An inlay hint that for a type annotation. + pub const TYPE: InlayHintKind = InlayHintKind(1); + + /// An inlay hint that is for a parameter. + pub const PARAMETER: InlayHintKind = InlayHintKind(2); +} +} + +/// Inlay hint client capabilities. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintResolveClientCapabilities { + /// The properties that a client can resolve lazily. + pub properties: Vec, +} + +/// Client workspace capabilities specific to inlay hints. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlayHintWorkspaceClientCapabilities { + /// Whether the client implementation supports a refresh request sent from + /// the server to the client. + /// + /// Note that this event is global and will force the client to refresh all + /// inlay hints currently shown. It should be used with absolute care and + /// is useful for situation where a server for example detects a project wide + /// change that requires such a calculation. + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_support: Option, +} + +// TODO(sno2): add tests once stabilized diff --git a/helix-lsp-types/src/inline_completion.rs b/helix-lsp-types/src/inline_completion.rs new file mode 100644 index 000000000..8289858ad --- /dev/null +++ b/helix-lsp-types/src/inline_completion.rs @@ -0,0 +1,162 @@ +use crate::{ + Command, InsertTextFormat, Range, StaticRegistrationOptions, TextDocumentPositionParams, + TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; + +/// Client capabilities specific to inline completions. +/// +/// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineCompletionClientCapabilities { + /// Whether implementation supports dynamic registration for inline completion providers. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, +} + +/// Inline completion options used during static registration. +/// +/// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InlineCompletionOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +/// Inline completion options used during static or dynamic registration. +/// +// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InlineCompletionRegistrationOptions { + #[serde(flatten)] + pub inline_completion_options: InlineCompletionOptions, + + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +/// A parameter literal used in inline completion requests. +/// +/// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineCompletionParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub text_document_position: TextDocumentPositionParams, + + /// Additional information about the context in which inline completions were requested. + pub context: InlineCompletionContext, +} + +/// Describes how an [`InlineCompletionItemProvider`] was triggered. +/// +/// @since 3.18.0 +#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +pub struct InlineCompletionTriggerKind(i32); +lsp_enum! { +impl InlineCompletionTriggerKind { + /// Completion was triggered explicitly by a user gesture. + /// Return multiple completion items to enable cycling through them. + pub const Invoked: InlineCompletionTriggerKind = InlineCompletionTriggerKind(1); + + /// Completion was triggered automatically while editing. + /// It is sufficient to return a single completion item in this case. + pub const Automatic: InlineCompletionTriggerKind = InlineCompletionTriggerKind(2); +} +} + +/// Describes the currently selected completion item. +/// +/// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct SelectedCompletionInfo { + /// The range that will be replaced if this completion item is accepted. + pub range: Range, + /// The text the range will be replaced with if this completion is + /// accepted. + pub text: String, +} + +/// Provides information about the context in which an inline completion was +/// requested. +/// +/// @since 3.18.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineCompletionContext { + /// Describes how the inline completion was triggered. + pub trigger_kind: InlineCompletionTriggerKind, + /// Provides information about the currently selected item in the + /// autocomplete widget if it is visible. + /// + /// If set, provided inline completions must extend the text of the + /// selected item and use the same range, otherwise they are not shown as + /// preview. + /// As an example, if the document text is `console.` and the selected item + /// is `.log` replacing the `.` in the document, the inline completion must + /// also replace `.` and start with `.log`, for example `.log()`. + /// + /// Inline completion providers are requested again whenever the selected + /// item changes. + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_completion_info: Option, +} + +/// InlineCompletion response can be multiple completion items, or a list of completion items +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum InlineCompletionResponse { + Array(Vec), + List(InlineCompletionList), +} + +/// Represents a collection of [`InlineCompletionItem`] to be presented in the editor. +/// +/// @since 3.18.0 +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +pub struct InlineCompletionList { + /// The inline completion items + pub items: Vec, +} + +/// An inline completion item represents a text snippet that is proposed inline +/// to complete text that is being typed. +/// +/// @since 3.18.0 +#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineCompletionItem { + /// The text to replace the range with. Must be set. + /// Is used both for the preview and the accept operation. + pub insert_text: String, + /// A text that is used to decide if this inline completion should be + /// shown. When `falsy` the [`InlineCompletionItem::insertText`] is + /// used. + /// + /// An inline completion is shown if the text to replace is a prefix of the + /// filter text. + #[serde(skip_serializing_if = "Option::is_none")] + pub filter_text: Option, + /// The range to replace. + /// Must begin and end on the same line. + /// + /// Prefer replacements over insertions to provide a better experience when + /// the user deletes typed text. + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, + /// An optional command that is executed *after* inserting this + /// completion. + #[serde(skip_serializing_if = "Option::is_none")] + pub command: Option, + /// The format of the insert text. The format applies to the `insertText`. + /// If omitted defaults to `InsertTextFormat.PlainText`. + #[serde(skip_serializing_if = "Option::is_none")] + pub insert_text_format: Option, +} diff --git a/helix-lsp-types/src/inline_value.rs b/helix-lsp-types/src/inline_value.rs new file mode 100644 index 000000000..dd29fbbf9 --- /dev/null +++ b/helix-lsp-types/src/inline_value.rs @@ -0,0 +1,217 @@ +use crate::{ + DynamicRegistrationClientCapabilities, Range, StaticRegistrationOptions, + TextDocumentIdentifier, TextDocumentRegistrationOptions, WorkDoneProgressOptions, + WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; + +pub type InlineValueClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InlineValueServerCapabilities { + Options(InlineValueOptions), + RegistrationOptions(InlineValueRegistrationOptions), +} + +/// Inline value options used during static registration. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InlineValueOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +/// Inline value options used during static or dynamic registration. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InlineValueRegistrationOptions { + #[serde(flatten)] + pub inline_value_options: InlineValueOptions, + + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +/// A parameter literal used in inline value requests. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineValueParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The document range for which inline values should be computed. + pub range: Range, + + /// Additional information about the context in which inline values were + /// requested. + pub context: InlineValueContext, +} + +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineValueContext { + /// The stack frame (as a DAP Id) where the execution has stopped. + pub frame_id: i32, + + /// The document range where execution has stopped. + /// Typically the end position of the range denotes the line where the + /// inline values are shown. + pub stopped_location: Range, +} + +/// Provide inline value as text. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InlineValueText { + /// The document range for which the inline value applies. + pub range: Range, + + /// The text of the inline value. + pub text: String, +} + +/// Provide inline value through a variable lookup. +/// +/// If only a range is specified, the variable name will be extracted from +/// the underlying document. +/// +/// An optional variable name can be used to override the extracted name. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineValueVariableLookup { + /// The document range for which the inline value applies. + /// The range is used to extract the variable name from the underlying + /// document. + pub range: Range, + + /// If specified the name of the variable to look up. + #[serde(skip_serializing_if = "Option::is_none")] + pub variable_name: Option, + + /// How to perform the lookup. + pub case_sensitive_lookup: bool, +} + +/// Provide an inline value through an expression evaluation. +/// +/// If only a range is specified, the expression will be extracted from the +/// underlying document. +/// +/// An optional expression can be used to override the extracted expression. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InlineValueEvaluatableExpression { + /// The document range for which the inline value applies. + /// The range is used to extract the evaluatable expression from the + /// underlying document. + pub range: Range, + + /// If specified the expression overrides the extracted expression. + #[serde(skip_serializing_if = "Option::is_none")] + pub expression: Option, +} + +/// Inline value information can be provided by different means: +/// - directly as a text value (class InlineValueText). +/// - as a name to use for a variable lookup (class InlineValueVariableLookup) +/// - as an evaluatable expression (class InlineValueEvaluatableExpression) +/// The InlineValue types combines all inline value types into one type. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InlineValue { + Text(InlineValueText), + VariableLookup(InlineValueVariableLookup), + EvaluatableExpression(InlineValueEvaluatableExpression), +} + +impl From for InlineValue { + #[inline] + fn from(from: InlineValueText) -> Self { + Self::Text(from) + } +} + +impl From for InlineValue { + #[inline] + fn from(from: InlineValueVariableLookup) -> Self { + Self::VariableLookup(from) + } +} + +impl From for InlineValue { + #[inline] + fn from(from: InlineValueEvaluatableExpression) -> Self { + Self::EvaluatableExpression(from) + } +} + +/// Client workspace capabilities specific to inline values. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +/// +/// @since 3.17.0 +#[serde(rename_all = "camelCase")] +pub struct InlineValueWorkspaceClientCapabilities { + /// Whether the client implementation supports a refresh request sent from + /// the server to the client. + /// + /// Note that this event is global and will force the client to refresh all + /// inline values currently shown. It should be used with absolute care and + /// is useful for situation where a server for example detect a project wide + /// change that requires such a calculation. + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_support: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_serialization; + use crate::Position; + + #[test] + fn inline_values() { + test_serialization( + &InlineValueText { + range: Range::new(Position::new(0, 0), Position::new(0, 4)), + text: "one".to_owned(), + }, + r#"{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":4}},"text":"one"}"#, + ); + + test_serialization( + &InlineValue::VariableLookup(InlineValueVariableLookup { + range: Range::new(Position::new(1, 0), Position::new(1, 4)), + variable_name: None, + case_sensitive_lookup: false, + }), + r#"{"range":{"start":{"line":1,"character":0},"end":{"line":1,"character":4}},"caseSensitiveLookup":false}"#, + ); + + test_serialization( + &InlineValue::EvaluatableExpression(InlineValueEvaluatableExpression { + range: Range::new(Position::new(2, 0), Position::new(2, 4)), + expression: None, + }), + r#"{"range":{"start":{"line":2,"character":0},"end":{"line":2,"character":4}}}"#, + ); + } +} diff --git a/helix-lsp-types/src/lib.rs b/helix-lsp-types/src/lib.rs new file mode 100644 index 000000000..3ea1c0cd0 --- /dev/null +++ b/helix-lsp-types/src/lib.rs @@ -0,0 +1,2883 @@ +/*! + +Language Server Protocol types for Rust. + +Based on: + +This library uses the URL crate for parsing URIs. Note that there is +some confusion on the meaning of URLs vs URIs: +. According to that +information, on the classical sense of "URLs", "URLs" are a subset of +URIs, But on the modern/new meaning of URLs, they are the same as +URIs. The important take-away aspect is that the URL crate should be +able to parse any URI, such as `urn:isbn:0451450523`. + + +*/ +#![allow(non_upper_case_globals)] +#![forbid(unsafe_code)] +#[macro_use] +extern crate bitflags; + +use std::{collections::HashMap, fmt::Debug}; + +use serde::{de, de::Error as Error_, Deserialize, Serialize}; +use serde_json::Value; +pub use url::Url; + +// Large enough to contain any enumeration name defined in this crate +type PascalCaseBuf = [u8; 32]; +const fn fmt_pascal_case_const(name: &str) -> (PascalCaseBuf, usize) { + let mut buf = [0; 32]; + let mut buf_i = 0; + let mut name_i = 0; + let name = name.as_bytes(); + while name_i < name.len() { + let first = name[name_i]; + name_i += 1; + + buf[buf_i] = first; + buf_i += 1; + + while name_i < name.len() { + let rest = name[name_i]; + name_i += 1; + if rest == b'_' { + break; + } + + buf[buf_i] = rest.to_ascii_lowercase(); + buf_i += 1; + } + } + (buf, buf_i) +} + +fn fmt_pascal_case(f: &mut std::fmt::Formatter<'_>, name: &str) -> std::fmt::Result { + for word in name.split('_') { + let mut chars = word.chars(); + let first = chars.next().unwrap(); + write!(f, "{}", first)?; + for rest in chars { + write!(f, "{}", rest.to_lowercase())?; + } + } + Ok(()) +} + +macro_rules! lsp_enum { + (impl $typ: ident { $( $(#[$attr:meta])* pub const $name: ident : $enum_type: ty = $value: expr; )* }) => { + impl $typ { + $( + $(#[$attr])* + pub const $name: $enum_type = $value; + )* + } + + impl std::fmt::Debug for $typ { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + $( + Self::$name => crate::fmt_pascal_case(f, stringify!($name)), + )* + _ => write!(f, "{}({})", stringify!($typ), self.0), + } + } + } + + impl std::convert::TryFrom<&str> for $typ { + type Error = &'static str; + fn try_from(value: &str) -> Result { + match () { + $( + _ if { + const X: (crate::PascalCaseBuf, usize) = crate::fmt_pascal_case_const(stringify!($name)); + let (buf, len) = X; + &buf[..len] == value.as_bytes() + } => Ok(Self::$name), + )* + _ => Err("unknown enum variant"), + } + } + } + + } +} + +pub mod error_codes; +pub mod notification; +pub mod request; + +mod call_hierarchy; +pub use call_hierarchy::*; + +mod code_action; +pub use code_action::*; + +mod code_lens; +pub use code_lens::*; + +mod color; +pub use color::*; + +mod completion; +pub use completion::*; + +mod document_diagnostic; +pub use document_diagnostic::*; + +mod document_highlight; +pub use document_highlight::*; + +mod document_link; +pub use document_link::*; + +mod document_symbols; +pub use document_symbols::*; + +mod file_operations; +pub use file_operations::*; + +mod folding_range; +pub use folding_range::*; + +mod formatting; +pub use formatting::*; + +mod hover; +pub use hover::*; + +mod inlay_hint; +pub use inlay_hint::*; + +mod inline_value; +pub use inline_value::*; + +#[cfg(feature = "proposed")] +mod inline_completion; +#[cfg(feature = "proposed")] +pub use inline_completion::*; + +mod moniker; +pub use moniker::*; + +mod progress; +pub use progress::*; + +mod references; +pub use references::*; + +mod rename; +pub use rename::*; + +pub mod selection_range; +pub use selection_range::*; + +mod semantic_tokens; +pub use semantic_tokens::*; + +mod signature_help; +pub use signature_help::*; + +mod type_hierarchy; +pub use type_hierarchy::*; + +mod linked_editing; +pub use linked_editing::*; + +mod window; +pub use window::*; + +mod workspace_diagnostic; +pub use workspace_diagnostic::*; + +mod workspace_folders; +pub use workspace_folders::*; + +mod workspace_symbols; +pub use workspace_symbols::*; + +pub mod lsif; + +mod trace; +pub use trace::*; + +/* ----------------- Auxiliary types ----------------- */ + +#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum NumberOrString { + Number(i32), + String(String), +} + +/* ----------------- Cancel support ----------------- */ + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct CancelParams { + /// The request id to cancel. + pub id: NumberOrString, +} + +/* ----------------- Basic JSON Structures ----------------- */ + +/// The LSP any type +/// +/// @since 3.17.0 +pub type LSPAny = serde_json::Value; + +/// LSP object definition. +/// +/// @since 3.17.0 +pub type LSPObject = serde_json::Map; + +/// LSP arrays. +/// +/// @since 3.17.0 +pub type LSPArray = Vec; + +/// Position in a text document expressed as zero-based line and character offset. +/// A position is between two characters like an 'insert' cursor in a editor. +#[derive( + Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default, Deserialize, Serialize, Hash, +)] +pub struct Position { + /// Line position in a document (zero-based). + pub line: u32, + /// Character offset on a line in a document (zero-based). The meaning of this + /// offset is determined by the negotiated `PositionEncodingKind`. + /// + /// If the character value is greater than the line length it defaults back + /// to the line length. + pub character: u32, +} + +impl Position { + pub fn new(line: u32, character: u32) -> Position { + Position { line, character } + } +} + +/// A range in a text document expressed as (zero-based) start and end positions. +/// A range is comparable to a selection in an editor. Therefore the end position is exclusive. +#[derive(Debug, Eq, PartialEq, Copy, Clone, Default, Deserialize, Serialize, Hash)] +pub struct Range { + /// The range's start position. + pub start: Position, + /// The range's end position. + pub end: Position, +} + +impl Range { + pub fn new(start: Position, end: Position) -> Range { + Range { start, end } + } +} + +/// Represents a location inside a resource, such as a line inside a text file. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize, Hash)] +pub struct Location { + pub uri: Url, + pub range: Range, +} + +impl Location { + pub fn new(uri: Url, range: Range) -> Location { + Location { uri, range } + } +} + +/// Represents a link between a source and a target location. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LocationLink { + /// Span of the origin of this link. + /// + /// Used as the underlined span for mouse interaction. Defaults to the word range at + /// the mouse position. + #[serde(skip_serializing_if = "Option::is_none")] + pub origin_selection_range: Option, + + /// The target resource identifier of this link. + pub target_uri: Url, + + /// The full target range of this link. + pub target_range: Range, + + /// The span of this link. + pub target_selection_range: Range, +} + +/// A type indicating how positions are encoded, +/// specifically what column offsets mean. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)] +pub struct PositionEncodingKind(std::borrow::Cow<'static, str>); + +impl PositionEncodingKind { + /// Character offsets count UTF-8 code units. + pub const UTF8: PositionEncodingKind = PositionEncodingKind::new("utf-8"); + + /// Character offsets count UTF-16 code units. + /// + /// This is the default and must always be supported + /// by servers + pub const UTF16: PositionEncodingKind = PositionEncodingKind::new("utf-16"); + + /// Character offsets count UTF-32 code units. + /// + /// Implementation note: these are the same as Unicode code points, + /// so this `PositionEncodingKind` may also be used for an + /// encoding-agnostic representation of character offsets. + pub const UTF32: PositionEncodingKind = PositionEncodingKind::new("utf-32"); + + pub const fn new(tag: &'static str) -> Self { + PositionEncodingKind(std::borrow::Cow::Borrowed(tag)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for PositionEncodingKind { + fn from(from: String) -> Self { + PositionEncodingKind(std::borrow::Cow::from(from)) + } +} + +impl From<&'static str> for PositionEncodingKind { + fn from(from: &'static str) -> Self { + PositionEncodingKind::new(from) + } +} + +/// Represents a diagnostic, such as a compiler error or warning. +/// Diagnostic objects are only valid in the scope of a resource. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Diagnostic { + /// The range at which the message applies. + pub range: Range, + + /// The diagnostic's severity. Can be omitted. If omitted it is up to the + /// client to interpret diagnostics as error, warning, info or hint. + #[serde(skip_serializing_if = "Option::is_none")] + pub severity: Option, + + /// The diagnostic's code. Can be omitted. + #[serde(skip_serializing_if = "Option::is_none")] + pub code: Option, + + /// An optional property to describe the error code. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub code_description: Option, + + /// A human-readable string describing the source of this + /// diagnostic, e.g. 'typescript' or 'super lint'. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + + /// The diagnostic's message. + pub message: String, + + /// An array of related diagnostic information, e.g. when symbol-names within + /// a scope collide all definitions can be marked via this property. + #[serde(skip_serializing_if = "Option::is_none")] + pub related_information: Option>, + + /// Additional metadata about the diagnostic. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, + + /// A data entry field that is preserved between a `textDocument/publishDiagnostics` + /// notification and `textDocument/codeAction` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CodeDescription { + pub href: Url, +} + +impl Diagnostic { + pub fn new( + range: Range, + severity: Option, + code: Option, + source: Option, + message: String, + related_information: Option>, + tags: Option>, + ) -> Diagnostic { + Diagnostic { + range, + severity, + code, + source, + message, + related_information, + tags, + ..Diagnostic::default() + } + } + + pub fn new_simple(range: Range, message: String) -> Diagnostic { + Self::new(range, None, None, None, message, None, None) + } + + pub fn new_with_code_number( + range: Range, + severity: DiagnosticSeverity, + code_number: i32, + source: Option, + message: String, + ) -> Diagnostic { + let code = Some(NumberOrString::Number(code_number)); + Self::new(range, Some(severity), code, source, message, None, None) + } +} + +/// The protocol currently supports the following diagnostic severities: +#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Deserialize, Serialize)] +#[serde(transparent)] +pub struct DiagnosticSeverity(i32); +lsp_enum! { +impl DiagnosticSeverity { + /// Reports an error. + pub const ERROR: DiagnosticSeverity = DiagnosticSeverity(1); + /// Reports a warning. + pub const WARNING: DiagnosticSeverity = DiagnosticSeverity(2); + /// Reports an information. + pub const INFORMATION: DiagnosticSeverity = DiagnosticSeverity(3); + /// Reports a hint. + pub const HINT: DiagnosticSeverity = DiagnosticSeverity(4); +} +} + +/// Represents a related message and source code location for a diagnostic. This +/// should be used to point to code locations that cause or related to a +/// diagnostics, e.g when duplicating a symbol in a scope. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct DiagnosticRelatedInformation { + /// The location of this related diagnostic information. + pub location: Location, + + /// The message of this related diagnostic information. + pub message: String, +} + +/// The diagnostic tags. +#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct DiagnosticTag(i32); +lsp_enum! { +impl DiagnosticTag { + /// Unused or unnecessary code. + /// Clients are allowed to render diagnostics with this tag faded out instead of having + /// an error squiggle. + pub const UNNECESSARY: DiagnosticTag = DiagnosticTag(1); + + /// Deprecated or obsolete code. + /// Clients are allowed to rendered diagnostics with this tag strike through. + pub const DEPRECATED: DiagnosticTag = DiagnosticTag(2); +} +} + +/// Represents a reference to a command. Provides a title which will be used to represent a command in the UI. +/// Commands are identified by a string identifier. The recommended way to handle commands is to implement +/// their execution on the server side if the client and server provides the corresponding capabilities. +/// Alternatively the tool extension code could handle the command. +/// The protocol currently doesn’t specify a set of well-known commands. +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct Command { + /// Title of the command, like `save`. + pub title: String, + /// The identifier of the actual command handler. + pub command: String, + /// Arguments that the command handler should be + /// invoked with. + #[serde(skip_serializing_if = "Option::is_none")] + pub arguments: Option>, +} + +impl Command { + pub fn new(title: String, command: String, arguments: Option>) -> Command { + Command { + title, + command, + arguments, + } + } +} + +/// A textual edit applicable to a text document. +/// +/// If n `TextEdit`s are applied to a text document all text edits describe changes to the initial document version. +/// Execution wise text edits should applied from the bottom to the top of the text document. Overlapping text edits +/// are not supported. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextEdit { + /// The range of the text document to be manipulated. To insert + /// text into a document create a range where start === end. + pub range: Range, + /// The string to be inserted. For delete operations use an + /// empty string. + pub new_text: String, +} + +impl TextEdit { + pub fn new(range: Range, new_text: String) -> TextEdit { + TextEdit { range, new_text } + } +} + +/// An identifier referring to a change annotation managed by a workspace +/// edit. +/// +/// @since 3.16.0 +pub type ChangeAnnotationIdentifier = String; + +/// A special text edit with an additional change annotation. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AnnotatedTextEdit { + #[serde(flatten)] + pub text_edit: TextEdit, + + /// The actual annotation + pub annotation_id: ChangeAnnotationIdentifier, +} + +/// Describes textual changes on a single text document. The text document is referred to as a +/// `OptionalVersionedTextDocumentIdentifier` to allow clients to check the text document version before an +/// edit is applied. A `TextDocumentEdit` describes all changes on a version Si and after they are +/// applied move the document to version Si+1. So the creator of a `TextDocumentEdit` doesn't need to +/// sort the array or do any kind of ordering. However the edits must be non overlapping. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentEdit { + /// The text document to change. + pub text_document: OptionalVersionedTextDocumentIdentifier, + + /// The edits to be applied. + /// + /// @since 3.16.0 - support for AnnotatedTextEdit. This is guarded by the + /// client capability `workspace.workspaceEdit.changeAnnotationSupport` + pub edits: Vec>, +} + +/// Additional information that describes document changes. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChangeAnnotation { + /// A human-readable string describing the actual change. The string + /// is rendered prominent in the user interface. + pub label: String, + + /// A flag which indicates that user confirmation is needed + /// before applying the change. + #[serde(skip_serializing_if = "Option::is_none")] + pub needs_confirmation: Option, + + /// A human-readable string which is rendered less prominent in + /// the user interface. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChangeAnnotationWorkspaceEditClientCapabilities { + /// Whether the client groups edits with equal labels into tree nodes, + /// for instance all edits labelled with "Changes in Strings" would + /// be a tree node. + #[serde(skip_serializing_if = "Option::is_none")] + pub groups_on_label: Option, +} + +/// Options to create a file. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateFileOptions { + /// Overwrite existing file. Overwrite wins over `ignoreIfExists` + #[serde(skip_serializing_if = "Option::is_none")] + pub overwrite: Option, + /// Ignore if exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore_if_exists: Option, +} + +/// Create file operation +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateFile { + /// The resource to create. + pub uri: Url, + /// Additional options + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + + /// An optional annotation identifier describing the operation. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub annotation_id: Option, +} + +/// Rename file options +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameFileOptions { + /// Overwrite target if existing. Overwrite wins over `ignoreIfExists` + #[serde(skip_serializing_if = "Option::is_none")] + pub overwrite: Option, + /// Ignores if target exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore_if_exists: Option, +} + +/// Rename file operation +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameFile { + /// The old (existing) location. + pub old_uri: Url, + /// The new location. + pub new_uri: Url, + /// Rename options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + + /// An optional annotation identifier describing the operation. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub annotation_id: Option, +} + +/// Delete file options +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeleteFileOptions { + /// Delete the content recursively if a folder is denoted. + #[serde(skip_serializing_if = "Option::is_none")] + pub recursive: Option, + /// Ignore the operation if the file doesn't exist. + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore_if_not_exists: Option, + + /// An optional annotation identifier describing the operation. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub annotation_id: Option, +} + +/// Delete file operation +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeleteFile { + /// The file to delete. + pub uri: Url, + /// Delete options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, +} + +/// A workspace edit represents changes to many resources managed in the workspace. +/// The edit should either provide `changes` or `documentChanges`. +/// If the client can handle versioned document edits and if `documentChanges` are present, +/// the latter are preferred over `changes`. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceEdit { + /// Holds changes to existing resources. + #[serde(with = "url_map")] + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub changes: Option>>, // changes?: { [uri: string]: TextEdit[]; }; + + /// Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes + /// are either an array of `TextDocumentEdit`s to express changes to n different text documents + /// where each text document edit addresses a specific version of a text document. Or it can contain + /// above `TextDocumentEdit`s mixed with create, rename and delete file / folder operations. + /// + /// Whether a client supports versioned document edits is expressed via + /// `workspace.workspaceEdit.documentChanges` client capability. + /// + /// If a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then + /// only plain `TextEdit`s using the `changes` property are supported. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_changes: Option, + + /// A map of change annotations that can be referenced in + /// `AnnotatedTextEdit`s or create, rename and delete file / folder + /// operations. + /// + /// Whether clients honor this property depends on the client capability + /// `workspace.changeAnnotationSupport`. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub change_annotations: Option>, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum DocumentChanges { + Edits(Vec), + Operations(Vec), +} + +// TODO: Once https://github.com/serde-rs/serde/issues/912 is solved +// we can remove ResourceOp and switch to the following implementation +// of DocumentChangeOperation: +// +// #[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +// #[serde(tag = "kind", rename_all="lowercase" )] +// pub enum DocumentChangeOperation { +// Create(CreateFile), +// Rename(RenameFile), +// Delete(DeleteFile), +// +// #[serde(other)] +// Edit(TextDocumentEdit), +// } + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged, rename_all = "lowercase")] +pub enum DocumentChangeOperation { + Op(ResourceOp), + Edit(TextDocumentEdit), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum ResourceOp { + Create(CreateFile), + Rename(RenameFile), + Delete(DeleteFile), +} + +pub type DidChangeConfigurationClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigurationParams { + pub items: Vec, +} + +#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ConfigurationItem { + /// The scope to get the configuration section for. + #[serde(skip_serializing_if = "Option::is_none")] + pub scope_uri: Option, + + ///The configuration section asked for. + #[serde(skip_serializing_if = "Option::is_none")] + pub section: Option, +} + +mod url_map { + use std::fmt; + use std::marker::PhantomData; + + use super::*; + + pub fn deserialize<'de, D, V>(deserializer: D) -> Result>, D::Error> + where + D: serde::Deserializer<'de>, + V: de::DeserializeOwned, + { + struct UrlMapVisitor { + _marker: PhantomData, + } + + impl Default for UrlMapVisitor { + fn default() -> Self { + UrlMapVisitor { + _marker: PhantomData, + } + } + } + impl<'de, V: de::DeserializeOwned> de::Visitor<'de> for UrlMapVisitor { + type Value = HashMap; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("map") + } + + fn visit_map(self, mut visitor: M) -> Result + where + M: de::MapAccess<'de>, + { + let mut values = HashMap::with_capacity(visitor.size_hint().unwrap_or(0)); + + // While there are entries remaining in the input, add them + // into our map. + while let Some((key, value)) = visitor.next_entry::()? { + values.insert(key, value); + } + + Ok(values) + } + } + + struct OptionUrlMapVisitor { + _marker: PhantomData, + } + impl Default for OptionUrlMapVisitor { + fn default() -> Self { + OptionUrlMapVisitor { + _marker: PhantomData, + } + } + } + impl<'de, V: de::DeserializeOwned> de::Visitor<'de> for OptionUrlMapVisitor { + type Value = Option>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("option") + } + + #[inline] + fn visit_unit(self) -> Result + where + E: serde::de::Error, + { + Ok(None) + } + + #[inline] + fn visit_none(self) -> Result + where + E: serde::de::Error, + { + Ok(None) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + deserializer + .deserialize_map(UrlMapVisitor::::default()) + .map(Some) + } + } + + // Instantiate our Visitor and ask the Deserializer to drive + // it over the input data, resulting in an instance of MyMap. + deserializer.deserialize_option(OptionUrlMapVisitor::default()) + } + + pub fn serialize( + changes: &Option>, + serializer: S, + ) -> Result + where + S: serde::Serializer, + V: serde::Serialize, + { + use serde::ser::SerializeMap; + + match *changes { + Some(ref changes) => { + let mut map = serializer.serialize_map(Some(changes.len()))?; + for (k, v) in changes { + map.serialize_entry(k.as_str(), v)?; + } + map.end() + } + None => serializer.serialize_none(), + } + } +} + +impl WorkspaceEdit { + pub fn new(changes: HashMap>) -> WorkspaceEdit { + WorkspaceEdit { + changes: Some(changes), + document_changes: None, + ..Default::default() + } + } +} + +/// Text documents are identified using a URI. On the protocol level, URIs are passed as strings. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct TextDocumentIdentifier { + // !!!!!! Note: + // In the spec VersionedTextDocumentIdentifier extends TextDocumentIdentifier + // This modelled by "mixing-in" TextDocumentIdentifier in VersionedTextDocumentIdentifier, + // so any changes to this type must be effected in the sub-type as well. + /// The text document's URI. + pub uri: Url, +} + +impl TextDocumentIdentifier { + pub fn new(uri: Url) -> TextDocumentIdentifier { + TextDocumentIdentifier { uri } + } +} + +/// An item to transfer a text document from the client to the server. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentItem { + /// The text document's URI. + pub uri: Url, + + /// The text document's language identifier. + pub language_id: String, + + /// The version number of this document (it will strictly increase after each + /// change, including undo/redo). + pub version: i32, + + /// The content of the opened text document. + pub text: String, +} + +impl TextDocumentItem { + pub fn new(uri: Url, language_id: String, version: i32, text: String) -> TextDocumentItem { + TextDocumentItem { + uri, + language_id, + version, + text, + } + } +} + +/// An identifier to denote a specific version of a text document. This information usually flows from the client to the server. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct VersionedTextDocumentIdentifier { + // This field was "mixed-in" from TextDocumentIdentifier + /// The text document's URI. + pub uri: Url, + + /// The version number of this document. + /// + /// The version number of a document will increase after each change, + /// including undo/redo. The number doesn't need to be consecutive. + pub version: i32, +} + +impl VersionedTextDocumentIdentifier { + pub fn new(uri: Url, version: i32) -> VersionedTextDocumentIdentifier { + VersionedTextDocumentIdentifier { uri, version } + } +} + +/// An identifier which optionally denotes a specific version of a text document. This information usually flows from the server to the client +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct OptionalVersionedTextDocumentIdentifier { + // This field was "mixed-in" from TextDocumentIdentifier + /// The text document's URI. + pub uri: Url, + + /// The version number of this document. If an optional versioned text document + /// identifier is sent from the server to the client and the file is not + /// open in the editor (the server has not received an open notification + /// before) the server can send `null` to indicate that the version is + /// known and the content on disk is the master (as specified with document + /// content ownership). + /// + /// The version number of a document will increase after each change, + /// including undo/redo. The number doesn't need to be consecutive. + pub version: Option, +} + +impl OptionalVersionedTextDocumentIdentifier { + pub fn new(uri: Url, version: i32) -> OptionalVersionedTextDocumentIdentifier { + OptionalVersionedTextDocumentIdentifier { + uri, + version: Some(version), + } + } +} + +/// A parameter literal used in requests to pass a text document and a position inside that document. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentPositionParams { + // !!!!!! Note: + // In the spec ReferenceParams extends TextDocumentPositionParams + // This modelled by "mixing-in" TextDocumentPositionParams in ReferenceParams, + // so any changes to this type must be effected in sub-type as well. + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The position inside the text document. + pub position: Position, +} + +impl TextDocumentPositionParams { + pub fn new( + text_document: TextDocumentIdentifier, + position: Position, + ) -> TextDocumentPositionParams { + TextDocumentPositionParams { + text_document, + position, + } + } +} + +/// A document filter denotes a document through properties like language, schema or pattern. +/// Examples are a filter that applies to TypeScript files on disk or a filter the applies to JSON +/// files with name package.json: +/// +/// { language: 'typescript', scheme: 'file' } +/// { language: 'json', pattern: '**/package.json' } +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct DocumentFilter { + /// A language id, like `typescript`. + #[serde(skip_serializing_if = "Option::is_none")] + pub language: Option, + + /// A Uri [scheme](#Uri.scheme), like `file` or `untitled`. + #[serde(skip_serializing_if = "Option::is_none")] + pub scheme: Option, + + /// A glob pattern, like `*.{ts,js}`. + #[serde(skip_serializing_if = "Option::is_none")] + pub pattern: Option, +} + +/// A document selector is the combination of one or many document filters. +pub type DocumentSelector = Vec; + +// ========================= Actual Protocol ========================= + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub struct InitializeParams { + /// The process Id of the parent process that started + /// the server. Is null if the process has not been started by another process. + /// If the parent process is not alive then the server should exit (see exit notification) its process. + pub process_id: Option, + + /// The rootPath of the workspace. Is null + /// if no folder is open. + #[serde(skip_serializing_if = "Option::is_none")] + #[deprecated(note = "Use `root_uri` instead when possible")] + pub root_path: Option, + + /// The rootUri of the workspace. Is null if no + /// folder is open. If both `rootPath` and `rootUri` are set + /// `rootUri` wins. + #[serde(default)] + #[deprecated(note = "Use `workspace_folders` instead when possible")] + pub root_uri: Option, + + /// User provided initialization options. + #[serde(skip_serializing_if = "Option::is_none")] + pub initialization_options: Option, + + /// The capabilities provided by the client (editor or tool) + pub capabilities: ClientCapabilities, + + /// The initial trace setting. If omitted trace is disabled ('off'). + #[serde(default)] + #[serde(skip_serializing_if = "Option::is_none")] + pub trace: Option, + + /// The workspace folders configured in the client when the server starts. + /// This property is only available if the client supports workspace folders. + /// It can be `null` if the client supports workspace folders but none are + /// configured. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_folders: Option>, + + /// Information about the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_info: Option, + + /// The locale the client is currently showing the user interface + /// in. This must not necessarily be the locale of the operating + /// system. + /// + /// Uses IETF language tags as the value's syntax + /// (See ) + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub locale: Option, + + /// The LSP server may report about initialization progress to the client + /// by using the following work done token if it was passed by the client. + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +pub struct ClientInfo { + /// The name of the client as defined by the client. + pub name: String, + /// The client's version as defined by the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, PartialEq, Clone, Copy, Deserialize, Serialize)] +pub struct InitializedParams {} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct GenericRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub options: GenericOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct GenericOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct GenericParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DynamicRegistrationClientCapabilities { + /// This capability supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GotoCapability { + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client supports additional metadata in the form of definition links. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceEditClientCapabilities { + /// The client supports versioned document changes in `WorkspaceEdit`s + #[serde(skip_serializing_if = "Option::is_none")] + pub document_changes: Option, + + /// The resource operations the client supports. Clients should at least + /// support 'create', 'rename' and 'delete' files and folders. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_operations: Option>, + + /// The failure handling strategy of a client if applying the workspace edit fails. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_handling: Option, + + /// Whether the client normalizes line endings to the client specific + /// setting. + /// If set to `true` the client will normalize line ending characters + /// in a workspace edit to the client specific new line character(s). + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub normalizes_line_endings: Option, + + /// Whether the client in general supports change annotations on text edits, + /// create file, rename file and delete file changes. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub change_annotation_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)] +#[serde(rename_all = "lowercase")] +pub enum ResourceOperationKind { + Create, + Rename, + Delete, +} + +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)] +#[serde(rename_all = "camelCase")] +pub enum FailureHandlingKind { + Abort, + Transactional, + TextOnlyTransactional, + Undo, +} + +/// A symbol kind. +#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] +#[serde(transparent)] +pub struct SymbolKind(i32); +lsp_enum! { +impl SymbolKind { + pub const FILE: SymbolKind = SymbolKind(1); + pub const MODULE: SymbolKind = SymbolKind(2); + pub const NAMESPACE: SymbolKind = SymbolKind(3); + pub const PACKAGE: SymbolKind = SymbolKind(4); + pub const CLASS: SymbolKind = SymbolKind(5); + pub const METHOD: SymbolKind = SymbolKind(6); + pub const PROPERTY: SymbolKind = SymbolKind(7); + pub const FIELD: SymbolKind = SymbolKind(8); + pub const CONSTRUCTOR: SymbolKind = SymbolKind(9); + pub const ENUM: SymbolKind = SymbolKind(10); + pub const INTERFACE: SymbolKind = SymbolKind(11); + pub const FUNCTION: SymbolKind = SymbolKind(12); + pub const VARIABLE: SymbolKind = SymbolKind(13); + pub const CONSTANT: SymbolKind = SymbolKind(14); + pub const STRING: SymbolKind = SymbolKind(15); + pub const NUMBER: SymbolKind = SymbolKind(16); + pub const BOOLEAN: SymbolKind = SymbolKind(17); + pub const ARRAY: SymbolKind = SymbolKind(18); + pub const OBJECT: SymbolKind = SymbolKind(19); + pub const KEY: SymbolKind = SymbolKind(20); + pub const NULL: SymbolKind = SymbolKind(21); + pub const ENUM_MEMBER: SymbolKind = SymbolKind(22); + pub const STRUCT: SymbolKind = SymbolKind(23); + pub const EVENT: SymbolKind = SymbolKind(24); + pub const OPERATOR: SymbolKind = SymbolKind(25); + pub const TYPE_PARAMETER: SymbolKind = SymbolKind(26); +} +} + +/// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SymbolKindCapability { + /// The symbol kind values the client supports. When this + /// property exists the client also guarantees that it will + /// handle values outside its set gracefully and falls back + /// to a default value when unknown. + /// + /// If this property is not present the client only supports + /// the symbol kinds from `File` to `Array` as defined in + /// the initial version of the protocol. + pub value_set: Option>, +} + +/// Workspace specific client capabilities. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceClientCapabilities { + /// The client supports applying batch edits to the workspace by supporting + /// the request 'workspace/applyEdit' + #[serde(skip_serializing_if = "Option::is_none")] + pub apply_edit: Option, + + /// Capabilities specific to `WorkspaceEdit`s + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_edit: Option, + + /// Capabilities specific to the `workspace/didChangeConfiguration` notification. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_change_configuration: Option, + + /// Capabilities specific to the `workspace/didChangeWatchedFiles` notification. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_change_watched_files: Option, + + /// Capabilities specific to the `workspace/symbol` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub symbol: Option, + + /// Capabilities specific to the `workspace/executeCommand` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub execute_command: Option, + + /// The client has support for workspace folders. + /// + /// @since 3.6.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_folders: Option, + + /// The client supports `workspace/configuration` requests. + /// + /// @since 3.6.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub configuration: Option, + + /// Capabilities specific to the semantic token requests scoped to the workspace. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub semantic_tokens: Option, + + /// Capabilities specific to the code lens requests scoped to the workspace. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub code_lens: Option, + + /// The client has support for file requests/notifications. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub file_operations: Option, + + /// Client workspace capabilities specific to inline values. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inline_value: Option, + + /// Client workspace capabilities specific to inlay hints. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inlay_hint: Option, + + /// Client workspace capabilities specific to diagnostics. + /// since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub diagnostic: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentSyncClientCapabilities { + /// Whether text document synchronization supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client supports sending will save notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_save: Option, + + /// The client supports sending a will save request and + /// waits for a response providing text edits which will + /// be applied to the document before it is saved. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_save_wait_until: Option, + + /// The client supports did save notifications. + #[serde(skip_serializing_if = "Option::is_none")] + pub did_save: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublishDiagnosticsClientCapabilities { + /// Whether the clients accepts diagnostics with related information. + #[serde(skip_serializing_if = "Option::is_none")] + pub related_information: Option, + + /// Client supports the tag property to provide meta data about a diagnostic. + /// Clients supporting tags have to handle unknown tags gracefully. + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "TagSupport::deserialize_compat" + )] + pub tag_support: Option>, + + /// Whether the client interprets the version property of the + /// `textDocument/publishDiagnostics` notification's parameter. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub version_support: Option, + + /// Client supports a codeDescription property + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub code_description_support: Option, + + /// Whether code action supports the `data` property which is + /// preserved between a `textDocument/publishDiagnostics` and + /// `textDocument/codeAction` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub data_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TagSupport { + /// The tags supported by the client. + pub value_set: Vec, +} + +impl TagSupport { + /// Support for deserializing a boolean tag Support, in case it's present. + /// + /// This is currently the case for vscode 1.41.1 + fn deserialize_compat<'de, S>(serializer: S) -> Result>, S::Error> + where + S: serde::Deserializer<'de>, + T: serde::Deserialize<'de>, + { + Ok( + match Option::::deserialize(serializer).map_err(serde::de::Error::custom)? { + Some(Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(TagSupport { value_set: vec![] }), + Some(other) => { + Some(TagSupport::::deserialize(other).map_err(serde::de::Error::custom)?) + } + None => None, + }, + ) + } +} + +/// Text document specific client capabilities. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentClientCapabilities { + #[serde(skip_serializing_if = "Option::is_none")] + pub synchronization: Option, + /// Capabilities specific to the `textDocument/completion` + #[serde(skip_serializing_if = "Option::is_none")] + pub completion: Option, + + /// Capabilities specific to the `textDocument/hover` + #[serde(skip_serializing_if = "Option::is_none")] + pub hover: Option, + + /// Capabilities specific to the `textDocument/signatureHelp` + #[serde(skip_serializing_if = "Option::is_none")] + pub signature_help: Option, + + /// Capabilities specific to the `textDocument/references` + #[serde(skip_serializing_if = "Option::is_none")] + pub references: Option, + + /// Capabilities specific to the `textDocument/documentHighlight` + #[serde(skip_serializing_if = "Option::is_none")] + pub document_highlight: Option, + + /// Capabilities specific to the `textDocument/documentSymbol` + #[serde(skip_serializing_if = "Option::is_none")] + pub document_symbol: Option, + /// Capabilities specific to the `textDocument/formatting` + #[serde(skip_serializing_if = "Option::is_none")] + pub formatting: Option, + + /// Capabilities specific to the `textDocument/rangeFormatting` + #[serde(skip_serializing_if = "Option::is_none")] + pub range_formatting: Option, + + /// Capabilities specific to the `textDocument/onTypeFormatting` + #[serde(skip_serializing_if = "Option::is_none")] + pub on_type_formatting: Option, + + /// Capabilities specific to the `textDocument/declaration` + #[serde(skip_serializing_if = "Option::is_none")] + pub declaration: Option, + + /// Capabilities specific to the `textDocument/definition` + #[serde(skip_serializing_if = "Option::is_none")] + pub definition: Option, + + /// Capabilities specific to the `textDocument/typeDefinition` + #[serde(skip_serializing_if = "Option::is_none")] + pub type_definition: Option, + + /// Capabilities specific to the `textDocument/implementation` + #[serde(skip_serializing_if = "Option::is_none")] + pub implementation: Option, + + /// Capabilities specific to the `textDocument/codeAction` + #[serde(skip_serializing_if = "Option::is_none")] + pub code_action: Option, + + /// Capabilities specific to the `textDocument/codeLens` + #[serde(skip_serializing_if = "Option::is_none")] + pub code_lens: Option, + + /// Capabilities specific to the `textDocument/documentLink` + #[serde(skip_serializing_if = "Option::is_none")] + pub document_link: Option, + + /// Capabilities specific to the `textDocument/documentColor` and the + /// `textDocument/colorPresentation` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub color_provider: Option, + + /// Capabilities specific to the `textDocument/rename` + #[serde(skip_serializing_if = "Option::is_none")] + pub rename: Option, + + /// Capabilities specific to `textDocument/publishDiagnostics`. + #[serde(skip_serializing_if = "Option::is_none")] + pub publish_diagnostics: Option, + + /// Capabilities specific to `textDocument/foldingRange` requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub folding_range: Option, + + /// Capabilities specific to the `textDocument/selectionRange` request. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub selection_range: Option, + + /// Capabilities specific to `textDocument/linkedEditingRange` requests. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub linked_editing_range: Option, + + /// Capabilities specific to the various call hierarchy requests. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub call_hierarchy: Option, + + /// Capabilities specific to the `textDocument/semanticTokens/*` requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub semantic_tokens: Option, + + /// Capabilities specific to the `textDocument/moniker` request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub moniker: Option, + + /// Capabilities specific to the various type hierarchy requests. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub type_hierarchy: Option, + + /// Capabilities specific to the `textDocument/inlineValue` request. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inline_value: Option, + + /// Capabilities specific to the `textDocument/inlayHint` request. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inlay_hint: Option, + + /// Capabilities specific to the diagnostic pull model. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub diagnostic: Option, + + /// Capabilities specific to the `textDocument/inlineCompletion` request. + /// + /// @since 3.18.0 + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg(feature = "proposed")] + pub inline_completion: Option, +} + +/// Where ClientCapabilities are currently empty: +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ClientCapabilities { + /// Workspace specific client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace: Option, + + /// Text document specific client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub text_document: Option, + + /// Window specific client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub window: Option, + + /// General client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub general: Option, + + /// Unofficial UT8-offsets extension. + /// + /// See https://clangd.llvm.org/extensions.html#utf-8-offsets. + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg(feature = "proposed")] + pub offset_encoding: Option>, + + /// Experimental client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub experimental: Option, +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GeneralClientCapabilities { + /// Client capabilities specific to regular expressions. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub regular_expressions: Option, + + /// Client capabilities specific to the client's markdown parser. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub markdown: Option, + + /// Client capability that signals how the client handles stale requests (e.g. a request for + /// which the client will not process the response anymore since the information is outdated). + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub stale_request_support: Option, + + /// The position encodings supported by the client. Client and server + /// have to agree on the same position encoding to ensure that offsets + /// (e.g. character position in a line) are interpreted the same on both + /// side. + /// + /// To keep the protocol backwards compatible the following applies: if + /// the value 'utf-16' is missing from the array of position encodings + /// servers can assume that the client supports UTF-16. UTF-16 is + /// therefore a mandatory encoding. + /// + /// If omitted it defaults to ['utf-16']. + /// + /// Implementation considerations: since the conversion from one encoding + /// into another requires the content of the file / line the conversion + /// is best done where the file is read which is usually on the server + /// side. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub position_encodings: Option>, +} + +/// Client capability that signals how the client +/// handles stale requests (e.g. a request +/// for which the client will not process the response +/// anymore since the information is outdated). +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StaleRequestSupportClientCapabilities { + /// The client will actively cancel the request. + pub cancel: bool, + + /// The list of requests for which the client + /// will retry the request if it receives a + /// response with error code `ContentModified`` + pub retry_on_content_modified: Vec, +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RegularExpressionsClientCapabilities { + /// The engine's name. + pub engine: String, + + /// The engine's version + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MarkdownClientCapabilities { + /// The name of the parser. + pub parser: String, + + /// The version of the parser. + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + + /// A list of HTML tags that the client allows / supports in + /// Markdown. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_tags: Option>, +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct InitializeResult { + /// The capabilities the language server provides. + pub capabilities: ServerCapabilities, + + /// Information about the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub server_info: Option, + + /// Unofficial UT8-offsets extension. + /// + /// See https://clangd.llvm.org/extensions.html#utf-8-offsets. + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg(feature = "proposed")] + pub offset_encoding: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct ServerInfo { + /// The name of the server as defined by the server. + pub name: String, + /// The servers's version as defined by the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct InitializeError { + /// Indicates whether the client execute the following retry logic: + /// + /// - (1) show the message provided by the ResponseError to the user + /// - (2) user selects retry or cancel + /// - (3) if user selected retry the initialize method is sent again. + pub retry: bool, +} + +// The server can signal the following capabilities: + +/// Defines how the host (editor) should sync document changes to the language server. +#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +#[serde(transparent)] +pub struct TextDocumentSyncKind(i32); +lsp_enum! { +impl TextDocumentSyncKind { + /// Documents should not be synced at all. + pub const NONE: TextDocumentSyncKind = TextDocumentSyncKind(0); + + /// Documents are synced by always sending the full content of the document. + pub const FULL: TextDocumentSyncKind = TextDocumentSyncKind(1); + + /// Documents are synced by sending the full content on open. After that only + /// incremental updates to the document are sent. + pub const INCREMENTAL: TextDocumentSyncKind = TextDocumentSyncKind(2); +} +} + +pub type ExecuteCommandClientCapabilities = DynamicRegistrationClientCapabilities; + +/// Execute command options. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct ExecuteCommandOptions { + /// The commands to be executed on the server + pub commands: Vec, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +/// Save options. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveOptions { + /// The client is supposed to include the content on save. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_text: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum TextDocumentSyncSaveOptions { + Supported(bool), + SaveOptions(SaveOptions), +} + +impl From for TextDocumentSyncSaveOptions { + fn from(from: SaveOptions) -> Self { + Self::SaveOptions(from) + } +} + +impl From for TextDocumentSyncSaveOptions { + fn from(from: bool) -> Self { + Self::Supported(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentSyncOptions { + /// Open and close notifications are sent to the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub open_close: Option, + + /// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full + /// and TextDocumentSyncKindIncremental. + #[serde(skip_serializing_if = "Option::is_none")] + pub change: Option, + + /// Will save notifications are sent to the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_save: Option, + + /// Will save wait until requests are sent to the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub will_save_wait_until: Option, + + /// Save notifications are sent to the server. + #[serde(skip_serializing_if = "Option::is_none")] + pub save: Option, +} + +#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum OneOf { + Left(A), + Right(B), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum TextDocumentSyncCapability { + Kind(TextDocumentSyncKind), + Options(TextDocumentSyncOptions), +} + +impl From for TextDocumentSyncCapability { + fn from(from: TextDocumentSyncOptions) -> Self { + Self::Options(from) + } +} + +impl From for TextDocumentSyncCapability { + fn from(from: TextDocumentSyncKind) -> Self { + Self::Kind(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum ImplementationProviderCapability { + Simple(bool), + Options(StaticTextDocumentRegistrationOptions), +} + +impl From for ImplementationProviderCapability { + fn from(from: StaticTextDocumentRegistrationOptions) -> Self { + Self::Options(from) + } +} + +impl From for ImplementationProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum TypeDefinitionProviderCapability { + Simple(bool), + Options(StaticTextDocumentRegistrationOptions), +} + +impl From for TypeDefinitionProviderCapability { + fn from(from: StaticTextDocumentRegistrationOptions) -> Self { + Self::Options(from) + } +} + +impl From for TypeDefinitionProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerCapabilities { + /// The position encoding the server picked from the encodings offered + /// by the client via the client capability `general.positionEncodings`. + /// + /// If the client didn't provide any position encodings the only valid + /// value that a server can return is 'utf-16'. + /// + /// If omitted it defaults to 'utf-16'. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub position_encoding: Option, + + /// Defines how text documents are synced. + #[serde(skip_serializing_if = "Option::is_none")] + pub text_document_sync: Option, + + /// Capabilities specific to `textDocument/selectionRange` requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub selection_range_provider: Option, + + /// The server provides hover support. + #[serde(skip_serializing_if = "Option::is_none")] + pub hover_provider: Option, + + /// The server provides completion support. + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_provider: Option, + + /// The server provides signature help support. + #[serde(skip_serializing_if = "Option::is_none")] + pub signature_help_provider: Option, + + /// The server provides goto definition support. + #[serde(skip_serializing_if = "Option::is_none")] + pub definition_provider: Option>, + + /// The server provides goto type definition support. + #[serde(skip_serializing_if = "Option::is_none")] + pub type_definition_provider: Option, + + /// The server provides goto implementation support. + #[serde(skip_serializing_if = "Option::is_none")] + pub implementation_provider: Option, + + /// The server provides find references support. + #[serde(skip_serializing_if = "Option::is_none")] + pub references_provider: Option>, + + /// The server provides document highlight support. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_highlight_provider: Option>, + + /// The server provides document symbol support. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_symbol_provider: Option>, + + /// The server provides workspace symbol support. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_symbol_provider: Option>, + + /// The server provides code actions. + #[serde(skip_serializing_if = "Option::is_none")] + pub code_action_provider: Option, + + /// The server provides code lens. + #[serde(skip_serializing_if = "Option::is_none")] + pub code_lens_provider: Option, + + /// The server provides document formatting. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_formatting_provider: Option>, + + /// The server provides document range formatting. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_range_formatting_provider: Option>, + + /// The server provides document formatting on typing. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_on_type_formatting_provider: Option, + + /// The server provides rename support. + #[serde(skip_serializing_if = "Option::is_none")] + pub rename_provider: Option>, + + /// The server provides document link support. + #[serde(skip_serializing_if = "Option::is_none")] + pub document_link_provider: Option, + + /// The server provides color provider support. + #[serde(skip_serializing_if = "Option::is_none")] + pub color_provider: Option, + + /// The server provides folding provider support. + #[serde(skip_serializing_if = "Option::is_none")] + pub folding_range_provider: Option, + + /// The server provides go to declaration support. + #[serde(skip_serializing_if = "Option::is_none")] + pub declaration_provider: Option, + + /// The server provides execute command support. + #[serde(skip_serializing_if = "Option::is_none")] + pub execute_command_provider: Option, + + /// Workspace specific server capabilities + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace: Option, + + /// Call hierarchy provider capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub call_hierarchy_provider: Option, + + /// Semantic tokens server capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub semantic_tokens_provider: Option, + + /// Whether server provides moniker support. + #[serde(skip_serializing_if = "Option::is_none")] + pub moniker_provider: Option>, + + /// The server provides linked editing range support. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub linked_editing_range_provider: Option, + + /// The server provides inline values. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inline_value_provider: Option>, + + /// The server provides inlay hints. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub inlay_hint_provider: Option>, + + /// The server has support for pull model diagnostics. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub diagnostic_provider: Option, + + /// The server provides inline completions. + /// + /// @since 3.18.0 + #[serde(skip_serializing_if = "Option::is_none")] + #[cfg(feature = "proposed")] + pub inline_completion_provider: Option>, + + /// Experimental server capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub experimental: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceServerCapabilities { + /// The server supports workspace folder. + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace_folders: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub file_operations: Option, +} + +/// General parameters to to register for a capability. +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Registration { + /// The id used to register the request. The id can be used to deregister + /// the request again. + pub id: String, + + /// The method / capability to register for. + pub method: String, + + /// Options necessary for the registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub register_options: Option, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +pub struct RegistrationParams { + pub registrations: Vec, +} + +/// Since most of the registration options require to specify a document selector there is a base +/// interface that can be used. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentRegistrationOptions { + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. + pub document_selector: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum DeclarationCapability { + Simple(bool), + RegistrationOptions(DeclarationRegistrationOptions), + Options(DeclarationOptions), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeclarationRegistrationOptions { + #[serde(flatten)] + pub declaration_options: DeclarationOptions, + + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DeclarationOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StaticRegistrationOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +#[derive(Debug, Default, Eq, PartialEq, Clone, Deserialize, Serialize, Copy)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub work_done_progress: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentFormattingOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentRangeFormattingOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DefinitionOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentSymbolOptions { + /// A human-readable string that is shown when multiple outlines trees are + /// shown for the same document. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReferencesOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DocumentHighlightOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceSymbolOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, + + /// The server provides support to resolve additional + /// information for a workspace symbol. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_provider: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StaticTextDocumentRegistrationOptions { + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. + pub document_selector: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, +} + +/// General parameters to unregister a capability. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct Unregistration { + /// The id used to unregister the request or notification. Usually an id + /// provided during the register request. + pub id: String, + + /// The method / capability to unregister for. + pub method: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct UnregistrationParams { + pub unregisterations: Vec, +} + +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +pub struct DidChangeConfigurationParams { + /// The actual changed settings + pub settings: Value, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidOpenTextDocumentParams { + /// The document that was opened. + pub text_document: TextDocumentItem, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidChangeTextDocumentParams { + /// The document that did change. The version number points + /// to the version after all provided content changes have + /// been applied. + pub text_document: VersionedTextDocumentIdentifier, + /// The actual content changes. + pub content_changes: Vec, +} + +/// An event describing a change to a text document. If range and rangeLength are omitted +/// the new text is considered to be the full content of the document. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentContentChangeEvent { + /// The range of the document that changed. + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, + + /// The length of the range that got replaced. + /// + /// Deprecated: Use range instead + #[serde(skip_serializing_if = "Option::is_none")] + pub range_length: Option, + + /// The new text of the document. + pub text: String, +} + +/// Describe options to be used when registering for text document change events. +/// +/// Extends TextDocumentRegistrationOptions +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentChangeRegistrationOptions { + /// A document selector to identify the scope of the registration. If set to null + /// the document selector provided on the client side will be used. + pub document_selector: Option, + + /// How documents are synced to the server. See TextDocumentSyncKind.Full + /// and TextDocumentSyncKindIncremental. + pub sync_kind: i32, +} + +/// The parameters send in a will save text document notification. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WillSaveTextDocumentParams { + /// The document that will be saved. + pub text_document: TextDocumentIdentifier, + + /// The 'TextDocumentSaveReason'. + pub reason: TextDocumentSaveReason, +} + +/// Represents reasons why a text document is saved. +#[derive(Copy, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct TextDocumentSaveReason(i32); +lsp_enum! { +impl TextDocumentSaveReason { + /// Manually triggered, e.g. by the user pressing save, by starting debugging, + /// or by an API call. + pub const MANUAL: TextDocumentSaveReason = TextDocumentSaveReason(1); + + /// Automatic after a delay. + pub const AFTER_DELAY: TextDocumentSaveReason = TextDocumentSaveReason(2); + + /// When the editor lost focus. + pub const FOCUS_OUT: TextDocumentSaveReason = TextDocumentSaveReason(3); +} +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidCloseTextDocumentParams { + /// The document that was closed. + pub text_document: TextDocumentIdentifier, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidSaveTextDocumentParams { + /// The document that was saved. + pub text_document: TextDocumentIdentifier, + + /// Optional the content when saved. Depends on the includeText value + /// when the save notification was requested. + #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TextDocumentSaveRegistrationOptions { + /// The client is supposed to include the content on save. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_text: Option, + + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Copy, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidChangeWatchedFilesClientCapabilities { + /// Did change watched files notification supports dynamic registration. + /// Please note that the current protocol doesn't support static + /// configuration for file changes from the server side. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Whether the client has support for relative patterns + /// or not. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub relative_pattern_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct DidChangeWatchedFilesParams { + /// The actual file events. + pub changes: Vec, +} + +/// The file event type. +#[derive(Eq, PartialEq, Hash, Copy, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct FileChangeType(i32); +lsp_enum! { +impl FileChangeType { + /// The file got created. + pub const CREATED: FileChangeType = FileChangeType(1); + + /// The file got changed. + pub const CHANGED: FileChangeType = FileChangeType(2); + + /// The file got deleted. + pub const DELETED: FileChangeType = FileChangeType(3); +} +} + +/// An event describing a file change. +#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)] +pub struct FileEvent { + /// The file's URI. + pub uri: Url, + + /// The change type. + #[serde(rename = "type")] + pub typ: FileChangeType, +} + +impl FileEvent { + pub fn new(uri: Url, typ: FileChangeType) -> FileEvent { + FileEvent { uri, typ } + } +} + +/// Describe options to be used when registered for text document change events. +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)] +pub struct DidChangeWatchedFilesRegistrationOptions { + /// The watchers to register. + pub watchers: Vec, +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FileSystemWatcher { + /// The glob pattern to watch. See {@link GlobPattern glob pattern} + /// for more detail. + /// + /// @since 3.17.0 support for relative patterns. + pub glob_pattern: GlobPattern, + + /// The kind of events of interest. If omitted it defaults to WatchKind.Create | + /// WatchKind.Change | WatchKind.Delete which is 7. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, +} + +/// The glob pattern. Either a string pattern or a relative pattern. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum GlobPattern { + String(Pattern), + Relative(RelativePattern), +} + +impl From for GlobPattern { + #[inline] + fn from(from: Pattern) -> Self { + Self::String(from) + } +} + +impl From for GlobPattern { + #[inline] + fn from(from: RelativePattern) -> Self { + Self::Relative(from) + } +} + +/// A relative pattern is a helper to construct glob patterns that are matched +/// relatively to a base URI. The common value for a `baseUri` is a workspace +/// folder root, but it can be another absolute URI as well. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RelativePattern { + /// A workspace folder or a base URI to which this pattern will be matched + /// against relatively. + pub base_uri: OneOf, + + /// The actual glob pattern. + pub pattern: Pattern, +} + +/// The glob pattern to watch relative to the base path. Glob patterns can have +/// the following syntax: +/// - `*` to match one or more characters in a path segment +/// - `?` to match on one character in a path segment +/// - `**` to match any number of path segments, including none +/// - `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript +/// and JavaScript files) +/// - `[]` to declare a range of characters to match in a path segment +/// (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) +/// - `[!...]` to negate a range of characters to match in a path segment +/// (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, +/// but not `example.0`) +/// +/// @since 3.17.0 +pub type Pattern = String; + +bitflags! { +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)] +pub struct WatchKind: u8 { + /// Interested in create events. + const Create = 1; + /// Interested in change events + const Change = 2; + /// Interested in delete events + const Delete = 4; +} +} + +impl<'de> serde::Deserialize<'de> for WatchKind { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let i = u8::deserialize(deserializer)?; + WatchKind::from_bits(i).ok_or_else(|| { + D::Error::invalid_value(de::Unexpected::Unsigned(u64::from(i)), &"Unknown flag") + }) + } +} + +impl serde::Serialize for WatchKind { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_u8(self.bits()) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct PublishDiagnosticsParams { + /// The URI for which diagnostic information is reported. + pub uri: Url, + + /// An array of diagnostic information items. + pub diagnostics: Vec, + + /// Optional the version number of the document the diagnostics are published for. + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +impl PublishDiagnosticsParams { + pub fn new( + uri: Url, + diagnostics: Vec, + version: Option, + ) -> PublishDiagnosticsParams { + PublishDiagnosticsParams { + uri, + diagnostics, + version, + } + } +} + +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] +#[serde(untagged)] +pub enum Documentation { + String(String), + MarkupContent(MarkupContent), +} + +/// MarkedString can be used to render human readable text. It is either a +/// markdown string or a code-block that provides a language and a code snippet. +/// The language identifier is semantically equal to the optional language +/// identifier in fenced code blocks in GitHub issues. +/// +/// The pair of a language and a value is an equivalent to markdown: +/// +/// ```${language} +/// ${value} +/// ``` +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum MarkedString { + String(String), + LanguageString(LanguageString), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct LanguageString { + pub language: String, + pub value: String, +} + +impl MarkedString { + pub fn from_markdown(markdown: String) -> MarkedString { + MarkedString::String(markdown) + } + + pub fn from_language_code(language: String, code_block: String) -> MarkedString { + MarkedString::LanguageString(LanguageString { + language, + value: code_block, + }) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GotoDefinitionParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// GotoDefinition response can be single location, or multiple Locations or a link. +#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] +#[serde(untagged)] +pub enum GotoDefinitionResponse { + Scalar(Location), + Array(Vec), + Link(Vec), +} + +impl From for GotoDefinitionResponse { + fn from(location: Location) -> Self { + GotoDefinitionResponse::Scalar(location) + } +} + +impl From> for GotoDefinitionResponse { + fn from(locations: Vec) -> Self { + GotoDefinitionResponse::Array(locations) + } +} + +impl From> for GotoDefinitionResponse { + fn from(locations: Vec) -> Self { + GotoDefinitionResponse::Link(locations) + } +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct ExecuteCommandParams { + /// The identifier of the actual command handler. + pub command: String, + /// Arguments that the command should be invoked with. + #[serde(default)] + pub arguments: Vec, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +/// Execute command registration options. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct ExecuteCommandRegistrationOptions { + /// The commands to be executed on the server + pub commands: Vec, + + #[serde(flatten)] + pub execute_command_options: ExecuteCommandOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplyWorkspaceEditParams { + /// An optional label of the workspace edit. This label is + /// presented in the user interface for example on an undo + /// stack to undo the workspace edit. + #[serde(skip_serializing_if = "Option::is_none")] + pub label: Option, + + /// The edits to apply. + pub edit: WorkspaceEdit, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplyWorkspaceEditResponse { + /// Indicates whether the edit was applied or not. + pub applied: bool, + + /// An optional textual description for why the edit was not applied. + /// This may be used may be used by the server for diagnostic + /// logging or to provide a suitable error for a request that + /// triggered the edit + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, + + /// Depending on the client's failure handling strategy `failedChange` might + /// contain the index of the change that failed. This property is only available + /// if the client signals a `failureHandlingStrategy` in its client capabilities. + #[serde(skip_serializing_if = "Option::is_none")] + pub failed_change: Option, +} + +/// Describes the content type that a client supports in various +/// result literals like `Hover`, `ParameterInfo` or `CompletionItem`. +/// +/// Please note that `MarkupKinds` must not start with a `$`. This kinds +/// are reserved for internal usage. +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "lowercase")] +pub enum MarkupKind { + /// Plain text is supported as a content format + PlainText, + /// Markdown is supported as a content format + Markdown, +} + +/// A `MarkupContent` literal represents a string value which content can be represented in different formats. +/// Currently `plaintext` and `markdown` are supported formats. A `MarkupContent` is usually used in +/// documentation properties of result literals like `CompletionItem` or `SignatureInformation`. +/// If the format is `markdown` the content should follow the [GitHub Flavored Markdown Specification](https://github.github.com/gfm/). +/// +/// Here is an example how such a string can be constructed using JavaScript / TypeScript: +/// +/// ```ignore +/// let markdown: MarkupContent = { +/// kind: MarkupKind::Markdown, +/// value: [ +/// "# Header", +/// "Some text", +/// "```typescript", +/// "someCode();", +/// "```" +/// ] +/// .join("\n"), +/// }; +/// ``` +/// +/// Please *Note* that clients might sanitize the return markdown. A client could decide to +/// remove HTML from the markdown to avoid script execution. +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] +pub struct MarkupContent { + pub kind: MarkupKind, + pub value: String, +} + +/// A parameter literal used to pass a partial result token. +#[derive(Debug, Eq, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct PartialResultParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub partial_result_token: Option, +} + +/// Symbol tags are extra annotations that tweak the rendering of a symbol. +/// +/// @since 3.16.0 +#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct SymbolTag(i32); +lsp_enum! { +impl SymbolTag { + /// Render a symbol as obsolete, usually using a strike-out. + pub const DEPRECATED: SymbolTag = SymbolTag(1); +} +} + +#[cfg(test)] +mod tests { + use serde::{Deserialize, Serialize}; + + use super::*; + + pub(crate) fn test_serialization(ms: &SER, expected: &str) + where + SER: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug, + { + let json_str = serde_json::to_string(ms).unwrap(); + assert_eq!(&json_str, expected); + let deserialized: SER = serde_json::from_str(&json_str).unwrap(); + assert_eq!(&deserialized, ms); + } + + pub(crate) fn test_deserialization(json: &str, expected: &T) + where + T: for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug, + { + let value = serde_json::from_str::(json).unwrap(); + assert_eq!(&value, expected); + } + + #[test] + fn one_of() { + test_serialization(&OneOf::::Left(true), r#"true"#); + test_serialization(&OneOf::::Left("abcd".into()), r#""abcd""#); + test_serialization( + &OneOf::::Right(WorkDoneProgressOptions { + work_done_progress: Some(false), + }), + r#"{"workDoneProgress":false}"#, + ); + } + + #[test] + fn number_or_string() { + test_serialization(&NumberOrString::Number(123), r#"123"#); + + test_serialization(&NumberOrString::String("abcd".into()), r#""abcd""#); + } + + #[test] + fn marked_string() { + test_serialization(&MarkedString::from_markdown("xxx".into()), r#""xxx""#); + + test_serialization( + &MarkedString::from_language_code("lang".into(), "code".into()), + r#"{"language":"lang","value":"code"}"#, + ); + } + + #[test] + fn language_string() { + test_serialization( + &LanguageString { + language: "LL".into(), + value: "VV".into(), + }, + r#"{"language":"LL","value":"VV"}"#, + ); + } + + #[test] + fn workspace_edit() { + test_serialization( + &WorkspaceEdit { + changes: Some(vec![].into_iter().collect()), + document_changes: None, + ..Default::default() + }, + r#"{"changes":{}}"#, + ); + + test_serialization( + &WorkspaceEdit { + changes: None, + document_changes: None, + ..Default::default() + }, + r#"{}"#, + ); + + test_serialization( + &WorkspaceEdit { + changes: Some( + vec![(Url::parse("file://test").unwrap(), vec![])] + .into_iter() + .collect(), + ), + document_changes: None, + ..Default::default() + }, + r#"{"changes":{"file://test/":[]}}"#, + ); + } + + #[test] + fn root_uri_can_be_missing() { + serde_json::from_str::(r#"{ "capabilities": {} }"#).unwrap(); + } + + #[test] + fn test_watch_kind() { + test_serialization(&WatchKind::Create, "1"); + test_serialization(&(WatchKind::Create | WatchKind::Change), "3"); + test_serialization( + &(WatchKind::Create | WatchKind::Change | WatchKind::Delete), + "7", + ); + } + + #[test] + fn test_resource_operation_kind() { + test_serialization( + &vec![ + ResourceOperationKind::Create, + ResourceOperationKind::Rename, + ResourceOperationKind::Delete, + ], + r#"["create","rename","delete"]"#, + ); + } +} diff --git a/helix-lsp-types/src/linked_editing.rs b/helix-lsp-types/src/linked_editing.rs new file mode 100644 index 000000000..b23fb141f --- /dev/null +++ b/helix-lsp-types/src/linked_editing.rs @@ -0,0 +1,61 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + DynamicRegistrationClientCapabilities, Range, StaticRegistrationOptions, + TextDocumentPositionParams, TextDocumentRegistrationOptions, WorkDoneProgressOptions, + WorkDoneProgressParams, +}; + +pub type LinkedEditingRangeClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LinkedEditingRangeOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LinkedEditingRangeRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub linked_editing_range_options: LinkedEditingRangeOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum LinkedEditingRangeServerCapabilities { + Simple(bool), + Options(LinkedEditingRangeOptions), + RegistrationOptions(LinkedEditingRangeRegistrationOptions), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LinkedEditingRangeParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LinkedEditingRanges { + /// A list of ranges that can be renamed together. The ranges must have + /// identical length and contain identical text content. The ranges cannot overlap. + pub ranges: Vec, + + /// An optional word pattern (regular expression) that describes valid contents for + /// the given ranges. If no pattern is provided, the client configuration's word + /// pattern will be used. + #[serde(skip_serializing_if = "Option::is_none")] + pub word_pattern: Option, +} diff --git a/helix-lsp-types/src/lsif.rs b/helix-lsp-types/src/lsif.rs new file mode 100644 index 000000000..be6df6e58 --- /dev/null +++ b/helix-lsp-types/src/lsif.rs @@ -0,0 +1,336 @@ +//! Types of Language Server Index Format (LSIF). LSIF is a standard format +//! for language servers or other programming tools to dump their knowledge +//! about a workspace. +//! +//! Based on + +use crate::{Range, Url}; +use serde::{Deserialize, Serialize}; + +pub type Id = crate::NumberOrString; + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum LocationOrRangeId { + Location(crate::Location), + RangeId(Id), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + pub id: Id, + #[serde(flatten)] + pub data: Element, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "type")] +pub enum Element { + Vertex(Vertex), + Edge(Edge), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct ToolInfo { + pub name: String, + #[serde(default = "Default::default")] + #[serde(skip_serializing_if = "Vec::is_empty")] + pub args: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Copy)] +pub enum Encoding { + /// Currently only 'utf-16' is supported due to the limitations in LSP. + #[serde(rename = "utf-16")] + Utf16, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct RangeBasedDocumentSymbol { + pub id: Id, + #[serde(default = "Default::default")] + #[serde(skip_serializing_if = "Vec::is_empty")] + pub children: Vec, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum DocumentSymbolOrRangeBasedVec { + DocumentSymbol(Vec), + RangeBased(Vec), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DefinitionTag { + /// The text covered by the range + text: String, + /// The symbol kind. + kind: crate::SymbolKind, + /// Indicates if this symbol is deprecated. + #[serde(default)] + #[serde(skip_serializing_if = "std::ops::Not::not")] + deprecated: bool, + /// The full range of the definition not including leading/trailing whitespace but everything else, e.g comments and code. + /// The range must be included in fullRange. + full_range: Range, + /// Optional detail information for the definition. + #[serde(skip_serializing_if = "Option::is_none")] + detail: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeclarationTag { + /// The text covered by the range + text: String, + /// The symbol kind. + kind: crate::SymbolKind, + /// Indicates if this symbol is deprecated. + #[serde(default)] + deprecated: bool, + /// The full range of the definition not including leading/trailing whitespace but everything else, e.g comments and code. + /// The range must be included in fullRange. + full_range: Range, + /// Optional detail information for the definition. + #[serde(skip_serializing_if = "Option::is_none")] + detail: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReferenceTag { + text: String, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UnknownTag { + text: String, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "type")] +pub enum RangeTag { + Definition(DefinitionTag), + Declaration(DeclarationTag), + Reference(ReferenceTag), + Unknown(UnknownTag), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "label")] +pub enum Vertex { + MetaData(MetaData), + /// + Project(Project), + Document(Document), + /// + Range { + #[serde(flatten)] + range: Range, + #[serde(skip_serializing_if = "Option::is_none")] + tag: Option, + }, + /// + ResultSet(ResultSet), + Moniker(crate::Moniker), + PackageInformation(PackageInformation), + + #[serde(rename = "$event")] + Event(Event), + + DefinitionResult, + DeclarationResult, + TypeDefinitionResult, + ReferenceResult, + ImplementationResult, + FoldingRangeResult { + result: Vec, + }, + HoverResult { + result: crate::Hover, + }, + DocumentSymbolResult { + result: DocumentSymbolOrRangeBasedVec, + }, + DocumentLinkResult { + result: Vec, + }, + DiagnosticResult { + result: Vec, + }, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EventKind { + Begin, + End, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EventScope { + Document, + Project, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub struct Event { + pub kind: EventKind, + pub scope: EventScope, + pub data: Id, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "label")] +pub enum Edge { + Contains(EdgeDataMultiIn), + Moniker(EdgeData), + NextMoniker(EdgeData), + Next(EdgeData), + PackageInformation(EdgeData), + Item(Item), + + // Methods + #[serde(rename = "textDocument/definition")] + Definition(EdgeData), + #[serde(rename = "textDocument/declaration")] + Declaration(EdgeData), + #[serde(rename = "textDocument/hover")] + Hover(EdgeData), + #[serde(rename = "textDocument/references")] + References(EdgeData), + #[serde(rename = "textDocument/implementation")] + Implementation(EdgeData), + #[serde(rename = "textDocument/typeDefinition")] + TypeDefinition(EdgeData), + #[serde(rename = "textDocument/foldingRange")] + FoldingRange(EdgeData), + #[serde(rename = "textDocument/documentLink")] + DocumentLink(EdgeData), + #[serde(rename = "textDocument/documentSymbol")] + DocumentSymbol(EdgeData), + #[serde(rename = "textDocument/diagnostic")] + Diagnostic(EdgeData), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EdgeData { + pub in_v: Id, + pub out_v: Id, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EdgeDataMultiIn { + pub in_vs: Vec, + pub out_v: Id, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DefinitionResultType { + Scalar(LocationOrRangeId), + Array(LocationOrRangeId), +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ItemKind { + Declarations, + Definitions, + References, + ReferenceResults, + ImplementationResults, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Item { + pub document: Id, + #[serde(skip_serializing_if = "Option::is_none")] + pub property: Option, + #[serde(flatten)] + pub edge_data: EdgeDataMultiIn, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Document { + pub uri: Url, + pub language_id: String, +} + +/// +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ResultSet { + #[serde(skip_serializing_if = "Option::is_none")] + pub key: Option, +} + +/// +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Project { + #[serde(skip_serializing_if = "Option::is_none")] + pub resource: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option, + pub kind: String, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MetaData { + /// The version of the LSIF format using semver notation. See . Please note + /// the version numbers starting with 0 don't adhere to semver and adopters have to assume + /// that each new version is breaking. + pub version: String, + + /// The project root (in form of an URI) used to compute this dump. + pub project_root: Url, + + /// The string encoding used to compute line and character values in + /// positions and ranges. + pub position_encoding: Encoding, + + /// Information about the tool that created the dump + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_info: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Repository { + pub r#type: String, + pub url: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub commit_id: Option, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PackageInformation { + pub name: String, + pub manager: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub uri: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} diff --git a/helix-lsp-types/src/moniker.rs b/helix-lsp-types/src/moniker.rs new file mode 100644 index 000000000..74bf89553 --- /dev/null +++ b/helix-lsp-types/src/moniker.rs @@ -0,0 +1,92 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + DynamicRegistrationClientCapabilities, PartialResultParams, TextDocumentPositionParams, + TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +pub type MonikerClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum MonikerServerCapabilities { + Options(MonikerOptions), + RegistrationOptions(MonikerRegistrationOptions), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct MonikerOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MonikerRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub moniker_options: MonikerOptions, +} + +/// Moniker uniqueness level to define scope of the moniker. +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)] +#[serde(rename_all = "camelCase")] +pub enum UniquenessLevel { + /// The moniker is only unique inside a document + Document, + /// The moniker is unique inside a project for which a dump got created + Project, + /// The moniker is unique inside the group to which a project belongs + Group, + /// The moniker is unique inside the moniker scheme. + Scheme, + /// The moniker is globally unique + Global, +} + +/// The moniker kind. +#[derive(Debug, Eq, PartialEq, Deserialize, Serialize, Copy, Clone)] +#[serde(rename_all = "camelCase")] +pub enum MonikerKind { + /// The moniker represent a symbol that is imported into a project + Import, + /// The moniker represent a symbol that is exported into a project + Export, + /// The moniker represents a symbol that is local to a project (e.g. a local + /// variable of a function, a class not visible outside the project, ...) + Local, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MonikerParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// Moniker definition to match LSIF 0.5 moniker definition. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Moniker { + /// The scheme of the moniker. For example tsc or .Net + pub scheme: String, + + /// The identifier of the moniker. The value is opaque in LSIF however + /// schema owners are allowed to define the structure if they want. + pub identifier: String, + + /// The scope in which the moniker is unique + pub unique: UniquenessLevel, + + /// The moniker kind if known. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, +} diff --git a/helix-lsp-types/src/notification.rs b/helix-lsp-types/src/notification.rs new file mode 100644 index 000000000..aef011d36 --- /dev/null +++ b/helix-lsp-types/src/notification.rs @@ -0,0 +1,361 @@ +use super::*; + +use serde::{de::DeserializeOwned, Serialize}; + +pub trait Notification { + type Params: DeserializeOwned + Serialize + Send + Sync + 'static; + const METHOD: &'static str; +} + +#[macro_export] +macro_rules! lsp_notification { + ("$/cancelRequest") => { + $crate::notification::Cancel + }; + ("$/setTrace") => { + $crate::notification::SetTrace + }; + ("$/logTrace") => { + $crate::notification::LogTrace + }; + ("initialized") => { + $crate::notification::Initialized + }; + ("exit") => { + $crate::notification::Exit + }; + + ("window/showMessage") => { + $crate::notification::ShowMessage + }; + ("window/logMessage") => { + $crate::notification::LogMessage + }; + ("window/workDoneProgress/cancel") => { + $crate::notification::WorkDoneProgressCancel + }; + + ("telemetry/event") => { + $crate::notification::TelemetryEvent + }; + + ("textDocument/didOpen") => { + $crate::notification::DidOpenTextDocument + }; + ("textDocument/didChange") => { + $crate::notification::DidChangeTextDocument + }; + ("textDocument/willSave") => { + $crate::notification::WillSaveTextDocument + }; + ("textDocument/didSave") => { + $crate::notification::DidSaveTextDocument + }; + ("textDocument/didClose") => { + $crate::notification::DidCloseTextDocument + }; + ("textDocument/publishDiagnostics") => { + $crate::notification::PublishDiagnostics + }; + + ("workspace/didChangeConfiguration") => { + $crate::notification::DidChangeConfiguration + }; + ("workspace/didChangeWatchedFiles") => { + $crate::notification::DidChangeWatchedFiles + }; + ("workspace/didChangeWorkspaceFolders") => { + $crate::notification::DidChangeWorkspaceFolders + }; + ("$/progress") => { + $crate::notification::Progress + }; + ("workspace/didCreateFiles") => { + $crate::notification::DidCreateFiles + }; + ("workspace/didRenameFiles") => { + $crate::notification::DidRenameFiles + }; + ("workspace/didDeleteFiles") => { + $crate::notification::DidDeleteFiles + }; +} + +/// The base protocol now offers support for request cancellation. To cancel a request, +/// a notification message with the following properties is sent: +/// +/// A request that got canceled still needs to return from the server and send a response back. +/// It can not be left open / hanging. This is in line with the JSON RPC protocol that requires +/// that every request sends a response back. In addition it allows for returning partial results on cancel. +#[derive(Debug)] +pub enum Cancel {} + +impl Notification for Cancel { + type Params = CancelParams; + const METHOD: &'static str = "$/cancelRequest"; +} + +/// A notification that should be used by the client to modify the trace +/// setting of the server. +#[derive(Debug)] +pub enum SetTrace {} + +impl Notification for SetTrace { + type Params = SetTraceParams; + const METHOD: &'static str = "$/setTrace"; +} + +/// A notification to log the trace of the server’s execution. +/// The amount and content of these notifications depends on the current trace configuration. +/// +/// `LogTrace` should be used for systematic trace reporting. For single debugging messages, +/// the server should send `LogMessage` notifications. +#[derive(Debug)] +pub enum LogTrace {} + +impl Notification for LogTrace { + type Params = LogTraceParams; + const METHOD: &'static str = "$/logTrace"; +} + +/// The initialized notification is sent from the client to the server after the client received +/// the result of the initialize request but before the client is sending any other request or +/// notification to the server. The server can use the initialized notification for example to +/// dynamically register capabilities. +#[derive(Debug)] +pub enum Initialized {} + +impl Notification for Initialized { + type Params = InitializedParams; + const METHOD: &'static str = "initialized"; +} + +/// A notification to ask the server to exit its process. +/// The server should exit with success code 0 if the shutdown request has been received before; +/// otherwise with error code 1. +#[derive(Debug)] +pub enum Exit {} + +impl Notification for Exit { + type Params = (); + const METHOD: &'static str = "exit"; +} + +/// The show message notification is sent from a server to a client to ask the client to display a particular message +/// in the user interface. +#[derive(Debug)] +pub enum ShowMessage {} + +impl Notification for ShowMessage { + type Params = ShowMessageParams; + const METHOD: &'static str = "window/showMessage"; +} + +/// The log message notification is sent from the server to the client to ask the client to log a particular message. +#[derive(Debug)] +pub enum LogMessage {} + +impl Notification for LogMessage { + type Params = LogMessageParams; + const METHOD: &'static str = "window/logMessage"; +} + +/// The telemetry notification is sent from the server to the client to ask the client to log a telemetry event. +/// The protocol doesn't specify the payload since no interpretation of the data happens in the protocol. Most clients even don't handle +/// the event directly but forward them to the extensions owning the corresponding server issuing the event. +#[derive(Debug)] +pub enum TelemetryEvent {} + +impl Notification for TelemetryEvent { + type Params = OneOf; + const METHOD: &'static str = "telemetry/event"; +} + +/// A notification sent from the client to the server to signal the change of configuration settings. +#[derive(Debug)] +pub enum DidChangeConfiguration {} + +impl Notification for DidChangeConfiguration { + type Params = DidChangeConfigurationParams; + const METHOD: &'static str = "workspace/didChangeConfiguration"; +} + +/// The document open notification is sent from the client to the server to signal newly opened text documents. +/// The document's truth is now managed by the client and the server must not try to read the document's truth +/// using the document's uri. +#[derive(Debug)] +pub enum DidOpenTextDocument {} + +impl Notification for DidOpenTextDocument { + type Params = DidOpenTextDocumentParams; + const METHOD: &'static str = "textDocument/didOpen"; +} + +/// The document change notification is sent from the client to the server to signal changes to a text document. +/// In 2.0 the shape of the params has changed to include proper version numbers and language ids. +#[derive(Debug)] +pub enum DidChangeTextDocument {} + +impl Notification for DidChangeTextDocument { + type Params = DidChangeTextDocumentParams; + const METHOD: &'static str = "textDocument/didChange"; +} + +/// The document will save notification is sent from the client to the server before the document +/// is actually saved. +#[derive(Debug)] +pub enum WillSaveTextDocument {} + +impl Notification for WillSaveTextDocument { + type Params = WillSaveTextDocumentParams; + const METHOD: &'static str = "textDocument/willSave"; +} + +/// The document close notification is sent from the client to the server when the document got closed in the client. +/// The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri +/// the truth now exists on disk). +#[derive(Debug)] +pub enum DidCloseTextDocument {} + +impl Notification for DidCloseTextDocument { + type Params = DidCloseTextDocumentParams; + const METHOD: &'static str = "textDocument/didClose"; +} + +/// The document save notification is sent from the client to the server when the document was saved in the client. +#[derive(Debug)] +pub enum DidSaveTextDocument {} + +impl Notification for DidSaveTextDocument { + type Params = DidSaveTextDocumentParams; + const METHOD: &'static str = "textDocument/didSave"; +} + +/// The watched files notification is sent from the client to the server when the client detects changes to files and folders +/// watched by the language client (note although the name suggest that only file events are sent it is about file system events which include folders as well). +/// It is recommended that servers register for these file system events using the registration mechanism. +/// In former implementations clients pushed file events without the server actively asking for it. +#[derive(Debug)] +pub enum DidChangeWatchedFiles {} + +impl Notification for DidChangeWatchedFiles { + type Params = DidChangeWatchedFilesParams; + const METHOD: &'static str = "workspace/didChangeWatchedFiles"; +} + +/// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server to inform the server +/// about workspace folder configuration changes +#[derive(Debug)] +pub enum DidChangeWorkspaceFolders {} + +impl Notification for DidChangeWorkspaceFolders { + type Params = DidChangeWorkspaceFoldersParams; + const METHOD: &'static str = "workspace/didChangeWorkspaceFolders"; +} + +/// Diagnostics notification are sent from the server to the client to signal results of validation runs. +#[derive(Debug)] +pub enum PublishDiagnostics {} + +impl Notification for PublishDiagnostics { + type Params = PublishDiagnosticsParams; + const METHOD: &'static str = "textDocument/publishDiagnostics"; +} + +/// The progress notification is sent from the server to the client to ask +/// the client to indicate progress. +#[derive(Debug)] +pub enum Progress {} + +impl Notification for Progress { + type Params = ProgressParams; + const METHOD: &'static str = "$/progress"; +} + +/// The `window/workDoneProgress/cancel` notification is sent from the client +/// to the server to cancel a progress initiated on the server side using the `window/workDoneProgress/create`. +#[derive(Debug)] +pub enum WorkDoneProgressCancel {} + +impl Notification for WorkDoneProgressCancel { + type Params = WorkDoneProgressCancelParams; + const METHOD: &'static str = "window/workDoneProgress/cancel"; +} + +/// The did create files notification is sent from the client to the server when files were created from within the client. +#[derive(Debug)] +pub enum DidCreateFiles {} + +impl Notification for DidCreateFiles { + type Params = CreateFilesParams; + const METHOD: &'static str = "workspace/didCreateFiles"; +} + +/// The did rename files notification is sent from the client to the server when files were renamed from within the client. +#[derive(Debug)] +pub enum DidRenameFiles {} + +impl Notification for DidRenameFiles { + type Params = RenameFilesParams; + const METHOD: &'static str = "workspace/didRenameFiles"; +} + +/// The did delete files notification is sent from the client to the server when files were deleted from within the client. +#[derive(Debug)] +pub enum DidDeleteFiles {} + +impl Notification for DidDeleteFiles { + type Params = DeleteFilesParams; + const METHOD: &'static str = "workspace/didDeleteFiles"; +} + +#[cfg(test)] +mod test { + use super::*; + + fn fake_call() + where + N: Notification, + N::Params: serde::Serialize, + { + } + + macro_rules! check_macro { + ($name:tt) => { + // check whether the macro name matches the method + assert_eq!(::METHOD, $name); + // test whether type checking passes for each component + fake_call::(); + }; + } + + #[test] + fn check_macro_definitions() { + check_macro!("$/cancelRequest"); + check_macro!("$/progress"); + check_macro!("$/logTrace"); + check_macro!("$/setTrace"); + check_macro!("initialized"); + check_macro!("exit"); + check_macro!("window/showMessage"); + check_macro!("window/logMessage"); + check_macro!("window/workDoneProgress/cancel"); + check_macro!("telemetry/event"); + check_macro!("textDocument/didOpen"); + check_macro!("textDocument/didChange"); + check_macro!("textDocument/willSave"); + check_macro!("textDocument/didSave"); + check_macro!("textDocument/didClose"); + check_macro!("textDocument/publishDiagnostics"); + check_macro!("workspace/didChangeConfiguration"); + check_macro!("workspace/didChangeWatchedFiles"); + check_macro!("workspace/didChangeWorkspaceFolders"); + check_macro!("workspace/didCreateFiles"); + check_macro!("workspace/didRenameFiles"); + check_macro!("workspace/didDeleteFiles"); + } + + #[test] + #[cfg(feature = "proposed")] + fn check_proposed_macro_definitions() {} +} diff --git a/helix-lsp-types/src/progress.rs b/helix-lsp-types/src/progress.rs new file mode 100644 index 000000000..41fa74f9f --- /dev/null +++ b/helix-lsp-types/src/progress.rs @@ -0,0 +1,134 @@ +use serde::{Deserialize, Serialize}; + +use crate::NumberOrString; + +pub type ProgressToken = NumberOrString; + +/// The progress notification is sent from the server to the client to ask +/// the client to indicate progress. +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct ProgressParams { + /// The progress token provided by the client. + pub token: ProgressToken, + + /// The progress data. + pub value: ProgressParamsValue, +} + +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(untagged)] +pub enum ProgressParamsValue { + WorkDone(WorkDoneProgress), +} + +/// The `window/workDoneProgress/create` request is sent +/// from the server to the client to ask the client to create a work done progress. +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressCreateParams { + /// The token to be used to report progress. + pub token: ProgressToken, +} + +/// The `window/workDoneProgress/cancel` notification is sent from the client +/// to the server to cancel a progress initiated on the server side using the `window/workDoneProgress/create`. +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressCancelParams { + /// The token to be used to report progress. + pub token: ProgressToken, +} + +/// Options to signal work done progress support in server capabilities. +#[derive(Debug, Eq, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressOptions { + #[serde(skip_serializing_if = "Option::is_none")] + pub work_done_progress: Option, +} + +/// An optional token that a server can use to report work done progress +#[derive(Debug, Eq, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressParams { + #[serde(skip_serializing_if = "Option::is_none")] + pub work_done_token: Option, +} + +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressBegin { + /// Mandatory title of the progress operation. Used to briefly inform + /// about the kind of operation being performed. + /// Examples: "Indexing" or "Linking dependencies". + pub title: String, + + /// Controls if a cancel button should show to allow the user to cancel the + /// long running operation. Clients that don't support cancellation are allowed + /// to ignore the setting. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellable: Option, + + /// Optional, more detailed associated progress message. Contains + /// complementary information to the `title`. + /// + /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". + /// If unset, the previous progress message (if any) is still valid. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + + /// Optional progress percentage to display (value 100 is considered 100%). + /// If not provided infinite progress is assumed and clients are allowed + /// to ignore the `percentage` value in subsequent in report notifications. + /// + /// The value should be steadily rising. Clients are free to ignore values + /// that are not following this rule. The value range is [0, 100] + #[serde(skip_serializing_if = "Option::is_none")] + pub percentage: Option, +} + +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressReport { + /// Controls if a cancel button should show to allow the user to cancel the + /// long running operation. Clients that don't support cancellation are allowed + /// to ignore the setting. + #[serde(skip_serializing_if = "Option::is_none")] + pub cancellable: Option, + + /// Optional, more detailed associated progress message. Contains + /// complementary information to the `title`. + /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". + /// If unset, the previous progress message (if any) is still valid. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + + /// Optional progress percentage to display (value 100 is considered 100%). + /// If not provided infinite progress is assumed and clients are allowed + /// to ignore the `percentage` value in subsequent in report notifications. + /// + /// The value should be steadily rising. Clients are free to ignore values + /// that are not following this rule. The value range is [0, 100] + #[serde(skip_serializing_if = "Option::is_none")] + pub percentage: Option, +} + +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkDoneProgressEnd { + /// Optional, more detailed associated progress message. Contains + /// complementary information to the `title`. + /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". + /// If unset, the previous progress message (if any) is still valid. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum WorkDoneProgress { + Begin(WorkDoneProgressBegin), + Report(WorkDoneProgressReport), + End(WorkDoneProgressEnd), +} diff --git a/helix-lsp-types/src/references.rs b/helix-lsp-types/src/references.rs new file mode 100644 index 000000000..cb590d58e --- /dev/null +++ b/helix-lsp-types/src/references.rs @@ -0,0 +1,30 @@ +use crate::{ + DynamicRegistrationClientCapabilities, PartialResultParams, TextDocumentPositionParams, + WorkDoneProgressParams, +}; +use serde::{Deserialize, Serialize}; + +pub type ReferenceClientCapabilities = DynamicRegistrationClientCapabilities; +#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReferenceContext { + /// Include the declaration of the current symbol. + pub include_declaration: bool, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReferenceParams { + // Text Document and Position fields + #[serde(flatten)] + pub text_document_position: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + // ReferenceParams properties: + pub context: ReferenceContext, +} diff --git a/helix-lsp-types/src/rename.rs b/helix-lsp-types/src/rename.rs new file mode 100644 index 000000000..bb57e9afd --- /dev/null +++ b/helix-lsp-types/src/rename.rs @@ -0,0 +1,88 @@ +use crate::{Range, TextDocumentPositionParams, WorkDoneProgressOptions, WorkDoneProgressParams}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameParams { + /// Text Document and Position fields + #[serde(flatten)] + pub text_document_position: TextDocumentPositionParams, + + /// The new name of the symbol. If the given name is not valid the + /// request must return a [ResponseError](#ResponseError) with an + /// appropriate message set. + pub new_name: String, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameOptions { + /// Renames should be checked and tested before being executed. + #[serde(skip_serializing_if = "Option::is_none")] + pub prepare_provider: Option, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenameClientCapabilities { + /// Whether rename supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Client supports testing for validity of rename operations before execution. + /// + /// @since 3.12.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub prepare_support: Option, + + /// Client supports the default behavior result. + /// + /// The value indicates the default behavior used by the + /// client. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub prepare_support_default_behavior: Option, + + /// Whether the client honors the change annotations in + /// text edits and resource operations returned via the + /// rename request's workspace edit by for example presenting + /// the workspace edit in the user interface and asking + /// for confirmation. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub honors_change_annotations: Option, +} + +#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] +#[serde(transparent)] +pub struct PrepareSupportDefaultBehavior(i32); +lsp_enum! { +impl PrepareSupportDefaultBehavior { + /// The client's default behavior is to select the identifier + /// according the to language's syntax rule + pub const IDENTIFIER: PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior(1); +} +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +#[serde(rename_all = "camelCase")] +pub enum PrepareRenameResponse { + Range(Range), + RangeWithPlaceholder { + range: Range, + placeholder: String, + }, + #[serde(rename_all = "camelCase")] + DefaultBehavior { + default_behavior: bool, + }, +} diff --git a/helix-lsp-types/src/request.rs b/helix-lsp-types/src/request.rs new file mode 100644 index 000000000..7502546be --- /dev/null +++ b/helix-lsp-types/src/request.rs @@ -0,0 +1,1068 @@ +use super::*; + +use serde::{de::DeserializeOwned, Serialize}; + +pub trait Request { + type Params: DeserializeOwned + Serialize + Send + Sync + 'static; + type Result: DeserializeOwned + Serialize + Send + Sync + 'static; + const METHOD: &'static str; +} + +#[macro_export] +macro_rules! lsp_request { + ("initialize") => { + $crate::request::Initialize + }; + ("shutdown") => { + $crate::request::Shutdown + }; + + ("window/showMessageRequest") => { + $crate::request::ShowMessageRequest + }; + + ("client/registerCapability") => { + $crate::request::RegisterCapability + }; + ("client/unregisterCapability") => { + $crate::request::UnregisterCapability + }; + + ("workspace/symbol") => { + $crate::request::WorkspaceSymbolRequest + }; + ("workspaceSymbol/resolve") => { + $crate::request::WorkspaceSymbolResolve + }; + ("workspace/executeCommand") => { + $crate::request::ExecuteCommand + }; + + ("textDocument/willSaveWaitUntil") => { + $crate::request::WillSaveWaitUntil + }; + + ("textDocument/completion") => { + $crate::request::Completion + }; + ("completionItem/resolve") => { + $crate::request::ResolveCompletionItem + }; + ("textDocument/hover") => { + $crate::request::HoverRequest + }; + ("textDocument/signatureHelp") => { + $crate::request::SignatureHelpRequest + }; + ("textDocument/declaration") => { + $crate::request::GotoDeclaration + }; + ("textDocument/definition") => { + $crate::request::GotoDefinition + }; + ("textDocument/references") => { + $crate::request::References + }; + ("textDocument/documentHighlight") => { + $crate::request::DocumentHighlightRequest + }; + ("textDocument/documentSymbol") => { + $crate::request::DocumentSymbolRequest + }; + ("textDocument/codeAction") => { + $crate::request::CodeActionRequest + }; + ("textDocument/codeLens") => { + $crate::request::CodeLensRequest + }; + ("codeLens/resolve") => { + $crate::request::CodeLensResolve + }; + ("textDocument/documentLink") => { + $crate::request::DocumentLinkRequest + }; + ("documentLink/resolve") => { + $crate::request::DocumentLinkResolve + }; + ("workspace/applyEdit") => { + $crate::request::ApplyWorkspaceEdit + }; + ("textDocument/rangeFormatting") => { + $crate::request::RangeFormatting + }; + ("textDocument/onTypeFormatting") => { + $crate::request::OnTypeFormatting + }; + ("textDocument/formatting") => { + $crate::request::Formatting + }; + ("textDocument/rename") => { + $crate::request::Rename + }; + ("textDocument/documentColor") => { + $crate::request::DocumentColor + }; + ("textDocument/colorPresentation") => { + $crate::request::ColorPresentationRequest + }; + ("textDocument/foldingRange") => { + $crate::request::FoldingRangeRequest + }; + ("textDocument/prepareRename") => { + $crate::request::PrepareRenameRequest + }; + ("textDocument/implementation") => { + $crate::request::GotoImplementation + }; + ("textDocument/typeDefinition") => { + $crate::request::GotoTypeDefinition + }; + ("textDocument/selectionRange") => { + $crate::request::SelectionRangeRequest + }; + ("workspace/workspaceFolders") => { + $crate::request::WorkspaceFoldersRequest + }; + ("workspace/configuration") => { + $crate::request::WorkspaceConfiguration + }; + ("window/workDoneProgress/create") => { + $crate::request::WorkDoneProgressCreate + }; + ("callHierarchy/incomingCalls") => { + $crate::request::CallHierarchyIncomingCalls + }; + ("callHierarchy/outgoingCalls") => { + $crate::request::CallHierarchyOutgoingCalls + }; + ("textDocument/moniker") => { + $crate::request::MonikerRequest + }; + ("textDocument/linkedEditingRange") => { + $crate::request::LinkedEditingRange + }; + ("textDocument/prepareCallHierarchy") => { + $crate::request::CallHierarchyPrepare + }; + ("textDocument/prepareTypeHierarchy") => { + $crate::request::TypeHierarchyPrepare + }; + ("textDocument/semanticTokens/full") => { + $crate::request::SemanticTokensFullRequest + }; + ("textDocument/semanticTokens/full/delta") => { + $crate::request::SemanticTokensFullDeltaRequest + }; + ("textDocument/semanticTokens/range") => { + $crate::request::SemanticTokensRangeRequest + }; + ("textDocument/inlayHint") => { + $crate::request::InlayHintRequest + }; + ("textDocument/inlineValue") => { + $crate::request::InlineValueRequest + }; + ("textDocument/diagnostic") => { + $crate::request::DocumentDiagnosticRequest + }; + ("workspace/diagnostic") => { + $crate::request::WorkspaceDiagnosticRequest + }; + ("workspace/diagnostic/refresh") => { + $crate::request::WorkspaceDiagnosticRefresh + }; + ("typeHierarchy/supertypes") => { + $crate::request::TypeHierarchySupertypes + }; + ("typeHierarchy/subtypes") => { + $crate::request::TypeHierarchySubtypes + }; + ("workspace/willCreateFiles") => { + $crate::request::WillCreateFiles + }; + ("workspace/willRenameFiles") => { + $crate::request::WillRenameFiles + }; + ("workspace/willDeleteFiles") => { + $crate::request::WillDeleteFiles + }; + ("workspace/semanticTokens/refresh") => { + $crate::request::SemanticTokensRefresh + }; + ("workspace/codeLens/refresh") => { + $crate::request::CodeLensRefresh + }; + ("workspace/inlayHint/refresh") => { + $crate::request::InlayHintRefreshRequest + }; + ("workspace/inlineValue/refresh") => { + $crate::request::InlineValueRefreshRequest + }; + ("codeAction/resolve") => { + $crate::request::CodeActionResolveRequest + }; + ("inlayHint/resolve") => { + $crate::request::InlayHintResolveRequest + }; + ("window/showDocument") => { + $crate::request::ShowDocument + }; +} + +/// The initialize request is sent as the first request from the client to the server. +/// If the server receives request or notification before the `initialize` request it should act as follows: +/// +/// * for a request the respond should be errored with `code: -32001`. The message can be picked by the server. +/// * notifications should be dropped. +#[derive(Debug)] +pub enum Initialize {} + +impl Request for Initialize { + type Params = InitializeParams; + type Result = InitializeResult; + const METHOD: &'static str = "initialize"; +} + +/// The shutdown request is sent from the client to the server. It asks the server to shut down, +/// but to not exit (otherwise the response might not be delivered correctly to the client). +/// There is a separate exit notification that asks the server to exit. +#[derive(Debug)] +pub enum Shutdown {} + +impl Request for Shutdown { + type Params = (); + type Result = (); + const METHOD: &'static str = "shutdown"; +} + +/// The show message request is sent from a server to a client to ask the client to display a particular message +/// in the user interface. In addition to the show message notification the request allows to pass actions and to +/// wait for an answer from the client. +#[derive(Debug)] +pub enum ShowMessageRequest {} + +impl Request for ShowMessageRequest { + type Params = ShowMessageRequestParams; + type Result = Option; + const METHOD: &'static str = "window/showMessageRequest"; +} + +/// The client/registerCapability request is sent from the server to the client to register for a new capability +/// on the client side. Not all clients need to support dynamic capability registration. A client opts in via the +/// ClientCapabilities.GenericCapability property. +#[derive(Debug)] +pub enum RegisterCapability {} + +impl Request for RegisterCapability { + type Params = RegistrationParams; + type Result = (); + const METHOD: &'static str = "client/registerCapability"; +} + +/// The client/unregisterCapability request is sent from the server to the client to unregister a +/// previously register capability. +#[derive(Debug)] +pub enum UnregisterCapability {} + +impl Request for UnregisterCapability { + type Params = UnregistrationParams; + type Result = (); + const METHOD: &'static str = "client/unregisterCapability"; +} + +/// The Completion request is sent from the client to the server to compute completion items at a given cursor position. +/// Completion items are presented in the IntelliSense user interface. If computing full completion items is expensive, +/// servers can additionally provide a handler for the completion item resolve request ('completionItem/resolve'). +/// This request is sent when a completion item is selected in the user interface. A typical use case is for example: +/// the 'textDocument/completion' request doesn’t fill in the documentation property for returned completion items +/// since it is expensive to compute. When the item is selected in the user interface then a ‘completionItem/resolve’ +/// request is sent with the selected completion item as a param. The returned completion item should have the +/// documentation property filled in. The request can delay the computation of the detail and documentation properties. +/// However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, +/// and textEdit must be provided in the textDocument/completion request and must not be changed during resolve. +#[derive(Debug)] +pub enum Completion {} + +impl Request for Completion { + type Params = CompletionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/completion"; +} + +/// The request is sent from the client to the server to resolve additional information for a given completion item. +#[derive(Debug)] +pub enum ResolveCompletionItem {} + +impl Request for ResolveCompletionItem { + type Params = CompletionItem; + type Result = CompletionItem; + const METHOD: &'static str = "completionItem/resolve"; +} + +/// The hover request is sent from the client to the server to request hover information at a given text +/// document position. +#[derive(Debug)] +pub enum HoverRequest {} + +impl Request for HoverRequest { + type Params = HoverParams; + type Result = Option; + const METHOD: &'static str = "textDocument/hover"; +} + +/// The signature help request is sent from the client to the server to request signature information at +/// a given cursor position. +#[derive(Debug)] +pub enum SignatureHelpRequest {} + +impl Request for SignatureHelpRequest { + type Params = SignatureHelpParams; + type Result = Option; + const METHOD: &'static str = "textDocument/signatureHelp"; +} + +#[derive(Debug)] +pub enum GotoDeclaration {} +pub type GotoDeclarationParams = GotoDefinitionParams; +pub type GotoDeclarationResponse = GotoDefinitionResponse; + +/// The goto declaration request is sent from the client to the server to resolve the declaration location of +/// a symbol at a given text document position. +impl Request for GotoDeclaration { + type Params = GotoDeclarationParams; + type Result = Option; + const METHOD: &'static str = "textDocument/declaration"; +} + +/// The goto definition request is sent from the client to the server to resolve the definition location of +/// a symbol at a given text document position. +#[derive(Debug)] +pub enum GotoDefinition {} + +impl Request for GotoDefinition { + type Params = GotoDefinitionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/definition"; +} + +/// The references request is sent from the client to the server to resolve project-wide references for the +/// symbol denoted by the given text document position. +#[derive(Debug)] +pub enum References {} + +impl Request for References { + type Params = ReferenceParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/references"; +} + +/// The goto type definition request is sent from the client to the +/// server to resolve the type definition location of a symbol at a +/// given text document position. +#[derive(Debug)] +pub enum GotoTypeDefinition {} + +pub type GotoTypeDefinitionParams = GotoDefinitionParams; +pub type GotoTypeDefinitionResponse = GotoDefinitionResponse; + +impl Request for GotoTypeDefinition { + type Params = GotoTypeDefinitionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/typeDefinition"; +} + +/// The goto implementation request is sent from the client to the +/// server to resolve the implementation location of a symbol at a +/// given text document position. +#[derive(Debug)] +pub enum GotoImplementation {} + +pub type GotoImplementationParams = GotoTypeDefinitionParams; +pub type GotoImplementationResponse = GotoDefinitionResponse; + +impl Request for GotoImplementation { + type Params = GotoImplementationParams; + type Result = Option; + const METHOD: &'static str = "textDocument/implementation"; +} + +/// The document highlight request is sent from the client to the server to resolve a document highlights +/// for a given text document position. +/// For programming languages this usually highlights all references to the symbol scoped to this file. +/// However we kept 'textDocument/documentHighlight' and 'textDocument/references' separate requests since +/// the first one is allowed to be more fuzzy. +/// Symbol matches usually have a DocumentHighlightKind of Read or Write whereas fuzzy or textual matches +/// use Text as the kind. +#[derive(Debug)] +pub enum DocumentHighlightRequest {} + +impl Request for DocumentHighlightRequest { + type Params = DocumentHighlightParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/documentHighlight"; +} + +/// The document symbol request is sent from the client to the server to list all symbols found in a given +/// text document. +#[derive(Debug)] +pub enum DocumentSymbolRequest {} + +impl Request for DocumentSymbolRequest { + type Params = DocumentSymbolParams; + type Result = Option; + const METHOD: &'static str = "textDocument/documentSymbol"; +} + +/// The workspace symbol request is sent from the client to the server to list project-wide symbols +/// matching the query string. +#[derive(Debug)] +pub enum WorkspaceSymbolRequest {} + +impl Request for WorkspaceSymbolRequest { + type Params = WorkspaceSymbolParams; + type Result = Option; + const METHOD: &'static str = "workspace/symbol"; +} + +/// The `workspaceSymbol/resolve` request is sent from the client to the server to resolve +/// additional information for a given workspace symbol. +#[derive(Debug)] +pub enum WorkspaceSymbolResolve {} + +impl Request for WorkspaceSymbolResolve { + type Params = WorkspaceSymbol; + type Result = WorkspaceSymbol; + const METHOD: &'static str = "workspaceSymbol/resolve"; +} + +/// The workspace/executeCommand request is sent from the client to the server to trigger command execution on the server. +/// In most cases the server creates a WorkspaceEdit structure and applies the changes to the workspace using the request +/// workspace/applyEdit which is sent from the server to the client. +#[derive(Debug)] +pub enum ExecuteCommand {} + +impl Request for ExecuteCommand { + type Params = ExecuteCommandParams; + type Result = Option; + const METHOD: &'static str = "workspace/executeCommand"; +} + +/// The document will save request is sent from the client to the server before the document is +/// actually saved. The request can return an array of TextEdits which will be applied to the text +/// document before it is saved. Please note that clients might drop results if computing the text +/// edits took too long or if a server constantly fails on this request. This is done to keep the +/// save fast and reliable. +#[derive(Debug)] +pub enum WillSaveWaitUntil {} + +impl Request for WillSaveWaitUntil { + type Params = WillSaveTextDocumentParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/willSaveWaitUntil"; +} + +/// The workspace/applyEdit request is sent from the server to the client to modify resource on the +/// client side. +#[derive(Debug)] +pub enum ApplyWorkspaceEdit {} + +impl Request for ApplyWorkspaceEdit { + type Params = ApplyWorkspaceEditParams; + type Result = ApplyWorkspaceEditResponse; + const METHOD: &'static str = "workspace/applyEdit"; +} + +/// The workspace/configuration request is sent from the server to the client to fetch configuration settings +/// from the client. The request can fetch several configuration settings in one roundtrip. +/// The order of the returned configuration settings correspond to the order of the passed ConfigurationItems +/// (e.g. the first item in the response is the result for the first configuration item in the params). +/// +/// A ConfigurationItem consists of the configuration section to ask for and an additional scope URI. +/// The configuration section ask for is defined by the server and doesn’t necessarily need to correspond to +/// the configuration store used be the client. So a server might ask for a configuration cpp.formatterOptions +/// but the client stores the configuration in a XML store layout differently. +/// It is up to the client to do the necessary conversion. If a scope URI is provided the client should return +/// the setting scoped to the provided resource. If the client for example uses EditorConfig to manage its +/// settings the configuration should be returned for the passed resource URI. If the client can’t provide a +/// configuration setting for a given scope then null need to be present in the returned array. +#[derive(Debug)] +pub enum WorkspaceConfiguration {} + +impl Request for WorkspaceConfiguration { + type Params = ConfigurationParams; + type Result = Vec; + const METHOD: &'static str = "workspace/configuration"; +} + +/// The code action request is sent from the client to the server to compute commands for a given text document +/// and range. The request is triggered when the user moves the cursor into a problem marker in the editor or +/// presses the lightbulb associated with a marker. +#[derive(Debug)] +pub enum CodeActionRequest {} + +impl Request for CodeActionRequest { + type Params = CodeActionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/codeAction"; +} + +/// The request is sent from the client to the server to resolve additional information for a given code action. +/// This is usually used to compute the `edit` property of a code action to avoid its unnecessary computation +/// during the `textDocument/codeAction` request. +/// +/// @since 3.16.0 +#[derive(Debug)] +pub enum CodeActionResolveRequest {} + +impl Request for CodeActionResolveRequest { + type Params = CodeAction; + type Result = CodeAction; + const METHOD: &'static str = "codeAction/resolve"; +} + +/// The code lens request is sent from the client to the server to compute code lenses for a given text document. +#[derive(Debug)] +pub enum CodeLensRequest {} + +impl Request for CodeLensRequest { + type Params = CodeLensParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/codeLens"; +} + +/// The code lens resolve request is sent from the client to the server to resolve the command for a +/// given code lens item. +#[derive(Debug)] +pub enum CodeLensResolve {} + +impl Request for CodeLensResolve { + type Params = CodeLens; + type Result = CodeLens; + const METHOD: &'static str = "codeLens/resolve"; +} + +/// The document links request is sent from the client to the server to request the location of links in a document. +#[derive(Debug)] +pub enum DocumentLinkRequest {} + +impl Request for DocumentLinkRequest { + type Params = DocumentLinkParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/documentLink"; +} + +/// The document link resolve request is sent from the client to the server to resolve the target of +/// a given document link. +#[derive(Debug)] +pub enum DocumentLinkResolve {} + +impl Request for DocumentLinkResolve { + type Params = DocumentLink; + type Result = DocumentLink; + const METHOD: &'static str = "documentLink/resolve"; +} + +/// The document formatting request is sent from the server to the client to format a whole document. +#[derive(Debug)] +pub enum Formatting {} + +impl Request for Formatting { + type Params = DocumentFormattingParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/formatting"; +} + +/// The document range formatting request is sent from the client to the server to format a given range in a document. +#[derive(Debug)] +pub enum RangeFormatting {} + +impl Request for RangeFormatting { + type Params = DocumentRangeFormattingParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/rangeFormatting"; +} + +/// The document on type formatting request is sent from the client to the server to format parts of +/// the document during typing. +#[derive(Debug)] +pub enum OnTypeFormatting {} + +impl Request for OnTypeFormatting { + type Params = DocumentOnTypeFormattingParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/onTypeFormatting"; +} + +/// The linked editing request is sent from the client to the server to return for a given position in a document +/// the range of the symbol at the position and all ranges that have the same content. +/// Optionally a word pattern can be returned to describe valid contents. A rename to one of the ranges can be applied +/// to all other ranges if the new content is valid. If no result-specific word pattern is provided, the word pattern from +/// the client’s language configuration is used. +#[derive(Debug)] +pub enum LinkedEditingRange {} + +impl Request for LinkedEditingRange { + type Params = LinkedEditingRangeParams; + type Result = Option; + const METHOD: &'static str = "textDocument/linkedEditingRange"; +} + +/// The rename request is sent from the client to the server to perform a workspace-wide rename of a symbol. +#[derive(Debug)] +pub enum Rename {} + +impl Request for Rename { + type Params = RenameParams; + type Result = Option; + const METHOD: &'static str = "textDocument/rename"; +} + +/// The document color request is sent from the client to the server to list all color references found in a given text document. +/// Along with the range, a color value in RGB is returned. +#[derive(Debug)] +pub enum DocumentColor {} + +impl Request for DocumentColor { + type Params = DocumentColorParams; + type Result = Vec; + const METHOD: &'static str = "textDocument/documentColor"; +} + +/// The color presentation request is sent from the client to the server to obtain a list of presentations for a color value +/// at a given location. +#[derive(Debug)] +pub enum ColorPresentationRequest {} + +impl Request for ColorPresentationRequest { + type Params = ColorPresentationParams; + type Result = Vec; + const METHOD: &'static str = "textDocument/colorPresentation"; +} + +/// The folding range request is sent from the client to the server to return all folding ranges found in a given text document. +#[derive(Debug)] +pub enum FoldingRangeRequest {} + +impl Request for FoldingRangeRequest { + type Params = FoldingRangeParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/foldingRange"; +} + +/// The prepare rename request is sent from the client to the server to setup and test the validity of a rename operation +/// at a given location. +#[derive(Debug)] +pub enum PrepareRenameRequest {} + +impl Request for PrepareRenameRequest { + type Params = TextDocumentPositionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/prepareRename"; +} + +#[derive(Debug)] +#[cfg(feature = "proposed")] +pub enum InlineCompletionRequest {} + +#[cfg(feature = "proposed")] +impl Request for InlineCompletionRequest { + type Params = InlineCompletionParams; + type Result = Option; + const METHOD: &'static str = "textDocument/inlineCompletion"; +} + +/// The workspace/workspaceFolders request is sent from the server to the client to fetch the current open list of +/// workspace folders. Returns null in the response if only a single file is open in the tool. +/// Returns an empty array if a workspace is open but no folders are configured. +#[derive(Debug)] +pub enum WorkspaceFoldersRequest {} + +impl Request for WorkspaceFoldersRequest { + type Params = (); + type Result = Option>; + const METHOD: &'static str = "workspace/workspaceFolders"; +} + +/// The `window/workDoneProgress/create` request is sent from the server +/// to the client to ask the client to create a work done progress. +#[derive(Debug)] +pub enum WorkDoneProgressCreate {} + +impl Request for WorkDoneProgressCreate { + type Params = WorkDoneProgressCreateParams; + type Result = (); + const METHOD: &'static str = "window/workDoneProgress/create"; +} + +/// The selection range request is sent from the client to the server to return +/// suggested selection ranges at given positions. A selection range is a range +/// around the cursor position which the user might be interested in selecting. +/// +/// A selection range in the return array is for the position in the provided parameters at the same index. +/// Therefore `positions[i]` must be contained in `result[i].range`. +/// +/// Typically, but not necessary, selection ranges correspond to the nodes of the +/// syntax tree. +pub enum SelectionRangeRequest {} + +impl Request for SelectionRangeRequest { + type Params = SelectionRangeParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/selectionRange"; +} + +pub enum CallHierarchyPrepare {} + +impl Request for CallHierarchyPrepare { + type Params = CallHierarchyPrepareParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/prepareCallHierarchy"; +} + +pub enum CallHierarchyIncomingCalls {} + +impl Request for CallHierarchyIncomingCalls { + type Params = CallHierarchyIncomingCallsParams; + type Result = Option>; + const METHOD: &'static str = "callHierarchy/incomingCalls"; +} + +pub enum CallHierarchyOutgoingCalls {} + +impl Request for CallHierarchyOutgoingCalls { + type Params = CallHierarchyOutgoingCallsParams; + type Result = Option>; + const METHOD: &'static str = "callHierarchy/outgoingCalls"; +} + +pub enum SemanticTokensFullRequest {} + +impl Request for SemanticTokensFullRequest { + type Params = SemanticTokensParams; + type Result = Option; + const METHOD: &'static str = "textDocument/semanticTokens/full"; +} + +pub enum SemanticTokensFullDeltaRequest {} + +impl Request for SemanticTokensFullDeltaRequest { + type Params = SemanticTokensDeltaParams; + type Result = Option; + const METHOD: &'static str = "textDocument/semanticTokens/full/delta"; +} + +pub enum SemanticTokensRangeRequest {} + +impl Request for SemanticTokensRangeRequest { + type Params = SemanticTokensRangeParams; + type Result = Option; + const METHOD: &'static str = "textDocument/semanticTokens/range"; +} + +/// The `workspace/semanticTokens/refresh` request is sent from the server to the client. +/// Servers can use it to ask clients to refresh the editors for which this server provides semantic tokens. +/// As a result the client should ask the server to recompute the semantic tokens for these editors. +/// This is useful if a server detects a project wide configuration change which requires a re-calculation of all semantic tokens. +/// Note that the client still has the freedom to delay the re-calculation of the semantic tokens if for example an editor is currently not visible. +pub enum SemanticTokensRefresh {} + +impl Request for SemanticTokensRefresh { + type Params = (); + type Result = (); + const METHOD: &'static str = "workspace/semanticTokens/refresh"; +} + +/// The workspace/codeLens/refresh request is sent from the server to the client. +/// Servers can use it to ask clients to refresh the code lenses currently shown in editors. +/// As a result the client should ask the server to recompute the code lenses for these editors. +/// This is useful if a server detects a configuration change which requires a re-calculation of all code lenses. +/// Note that the client still has the freedom to delay the re-calculation of the code lenses if for example an editor is currently not visible. +pub enum CodeLensRefresh {} + +impl Request for CodeLensRefresh { + type Params = (); + type Result = (); + const METHOD: &'static str = "workspace/codeLens/refresh"; +} + +/// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Please note that clients might drop results if computing the edit took too long or if a server constantly fails on this request. This is done to keep creates fast and reliable. +pub enum WillCreateFiles {} + +impl Request for WillCreateFiles { + type Params = CreateFilesParams; + type Result = Option; + const METHOD: &'static str = "workspace/willCreateFiles"; +} + +/// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are renamed. Please note that clients might drop results if computing the edit took too long or if a server constantly fails on this request. This is done to keep renames fast and reliable. +pub enum WillRenameFiles {} + +impl Request for WillRenameFiles { + type Params = RenameFilesParams; + type Result = Option; + const METHOD: &'static str = "workspace/willRenameFiles"; +} + +/// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are deleted. Please note that clients might drop results if computing the edit took too long or if a server constantly fails on this request. This is done to keep deletes fast and reliable. +pub enum WillDeleteFiles {} + +impl Request for WillDeleteFiles { + type Params = DeleteFilesParams; + type Result = Option; + const METHOD: &'static str = "workspace/willDeleteFiles"; +} + +/// The show document request is sent from a server to a client to ask the client to display a particular document in the user interface. +pub enum ShowDocument {} + +impl Request for ShowDocument { + type Params = ShowDocumentParams; + type Result = ShowDocumentResult; + const METHOD: &'static str = "window/showDocument"; +} + +pub enum MonikerRequest {} + +impl Request for MonikerRequest { + type Params = MonikerParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/moniker"; +} + +/// The inlay hints request is sent from the client to the server to compute inlay hints for a given +/// [text document, range] tuple that may be rendered in the editor in place with other text. +pub enum InlayHintRequest {} + +impl Request for InlayHintRequest { + type Params = InlayHintParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/inlayHint"; +} + +/// The `inlayHint/resolve` request is sent from the client to the server to resolve additional +/// information for a given inlay hint. This is usually used to compute the tooltip, location or +/// command properties of a inlay hint’s label part to avoid its unnecessary computation during the +/// `textDocument/inlayHint` request. +pub enum InlayHintResolveRequest {} + +impl Request for InlayHintResolveRequest { + type Params = InlayHint; + type Result = InlayHint; + const METHOD: &'static str = "inlayHint/resolve"; +} + +/// The `workspace/inlayHint/refresh` request is sent from the server to the client. Servers can use +/// it to ask clients to refresh the inlay hints currently shown in editors. As a result the client +/// should ask the server to recompute the inlay hints for these editors. This is useful if a server +/// detects a configuration change which requires a re-calculation of all inlay hints. Note that the +/// client still has the freedom to delay the re-calculation of the inlay hints if for example an +/// editor is currently not visible. +pub enum InlayHintRefreshRequest {} + +impl Request for InlayHintRefreshRequest { + type Params = (); + type Result = (); + const METHOD: &'static str = "workspace/inlayHint/refresh"; +} + +/// The inline value request is sent from the client to the server to compute inline values for a +/// given text document that may be rendered in the editor at the end of lines. +pub enum InlineValueRequest {} + +impl Request for InlineValueRequest { + type Params = InlineValueParams; + type Result = Option; + const METHOD: &'static str = "textDocument/inlineValue"; +} + +/// The `workspace/inlineValue/refresh` request is sent from the server to the client. Servers can +/// use it to ask clients to refresh the inline values currently shown in editors. As a result the +/// client should ask the server to recompute the inline values for these editors. This is useful if +/// a server detects a configuration change which requires a re-calculation of all inline values. +/// Note that the client still has the freedom to delay the re-calculation of the inline values if +/// for example an editor is currently not visible. +pub enum InlineValueRefreshRequest {} + +impl Request for InlineValueRefreshRequest { + type Params = (); + type Result = (); + const METHOD: &'static str = "workspace/inlineValue/refresh"; +} + +/// The text document diagnostic request is sent from the client to the server to ask the server to +/// compute the diagnostics for a given document. As with other pull requests the server is asked +/// to compute the diagnostics for the currently synced version of the document. +#[derive(Debug)] +pub enum DocumentDiagnosticRequest {} + +impl Request for DocumentDiagnosticRequest { + type Params = DocumentDiagnosticParams; + type Result = DocumentDiagnosticReportResult; + const METHOD: &'static str = "textDocument/diagnostic"; +} + +/// The workspace diagnostic request is sent from the client to the server to ask the server to +/// compute workspace wide diagnostics which previously where pushed from the server to the client. +/// In contrast to the document diagnostic request the workspace request can be long running and is +/// not bound to a specific workspace or document state. If the client supports streaming for the +/// workspace diagnostic pull it is legal to provide a document diagnostic report multiple times +/// for the same document URI. The last one reported will win over previous reports. +#[derive(Debug)] +pub enum WorkspaceDiagnosticRequest {} + +impl Request for WorkspaceDiagnosticRequest { + type Params = WorkspaceDiagnosticParams; + const METHOD: &'static str = "workspace/diagnostic"; + type Result = WorkspaceDiagnosticReportResult; +} + +/// The `workspace/diagnostic/refresh` request is sent from the server to the client. Servers can +/// use it to ask clients to refresh all needed document and workspace diagnostics. This is useful +/// if a server detects a project wide configuration change which requires a re-calculation of all +/// diagnostics. +#[derive(Debug)] +pub enum WorkspaceDiagnosticRefresh {} + +impl Request for WorkspaceDiagnosticRefresh { + type Params = (); + type Result = (); + const METHOD: &'static str = "workspace/diagnostic/refresh"; +} + +/// The type hierarchy request is sent from the client to the server to return a type hierarchy for +/// the language element of given text document positions. Will return null if the server couldn’t +/// infer a valid type from the position. The type hierarchy requests are executed in two steps: +/// +/// 1. first a type hierarchy item is prepared for the given text document position. +/// 2. for a type hierarchy item the supertype or subtype type hierarchy items are resolved. +pub enum TypeHierarchyPrepare {} + +impl Request for TypeHierarchyPrepare { + type Params = TypeHierarchyPrepareParams; + type Result = Option>; + const METHOD: &'static str = "textDocument/prepareTypeHierarchy"; +} + +/// The `typeHierarchy/supertypes` request is sent from the client to the server to resolve the +/// supertypes for a given type hierarchy item. Will return null if the server couldn’t infer a +/// valid type from item in the params. The request doesn’t define its own client and server +/// capabilities. It is only issued if a server registers for the +/// `textDocument/prepareTypeHierarchy` request. +pub enum TypeHierarchySupertypes {} + +impl Request for TypeHierarchySupertypes { + type Params = TypeHierarchySupertypesParams; + type Result = Option>; + const METHOD: &'static str = "typeHierarchy/supertypes"; +} + +/// The `typeHierarchy/subtypes` request is sent from the client to the server to resolve the +/// subtypes for a given type hierarchy item. Will return null if the server couldn’t infer a valid +/// type from item in the params. The request doesn’t define its own client and server capabilities. +/// It is only issued if a server registers for the textDocument/prepareTypeHierarchy request. +pub enum TypeHierarchySubtypes {} + +impl Request for TypeHierarchySubtypes { + type Params = TypeHierarchySubtypesParams; + type Result = Option>; + const METHOD: &'static str = "typeHierarchy/subtypes"; +} + +#[cfg(test)] +mod test { + use super::*; + + fn fake_call() + where + R: Request, + R::Params: serde::Serialize, + R::Result: serde::de::DeserializeOwned, + { + } + + macro_rules! check_macro { + ($name:tt) => { + // check whether the macro name matches the method + assert_eq!(::METHOD, $name); + // test whether type checking passes for each component + fake_call::(); + }; + } + + #[test] + fn check_macro_definitions() { + check_macro!("initialize"); + check_macro!("shutdown"); + + check_macro!("window/showDocument"); + check_macro!("window/showMessageRequest"); + check_macro!("window/workDoneProgress/create"); + + check_macro!("client/registerCapability"); + check_macro!("client/unregisterCapability"); + + check_macro!("textDocument/willSaveWaitUntil"); + check_macro!("textDocument/completion"); + check_macro!("textDocument/hover"); + check_macro!("textDocument/signatureHelp"); + check_macro!("textDocument/declaration"); + check_macro!("textDocument/definition"); + check_macro!("textDocument/references"); + check_macro!("textDocument/documentHighlight"); + check_macro!("textDocument/documentSymbol"); + check_macro!("textDocument/codeAction"); + check_macro!("textDocument/codeLens"); + check_macro!("textDocument/documentLink"); + check_macro!("textDocument/rangeFormatting"); + check_macro!("textDocument/onTypeFormatting"); + check_macro!("textDocument/formatting"); + check_macro!("textDocument/rename"); + check_macro!("textDocument/documentColor"); + check_macro!("textDocument/colorPresentation"); + check_macro!("textDocument/foldingRange"); + check_macro!("textDocument/prepareRename"); + check_macro!("textDocument/implementation"); + check_macro!("textDocument/selectionRange"); + check_macro!("textDocument/typeDefinition"); + check_macro!("textDocument/moniker"); + check_macro!("textDocument/linkedEditingRange"); + check_macro!("textDocument/prepareCallHierarchy"); + check_macro!("textDocument/prepareTypeHierarchy"); + check_macro!("textDocument/semanticTokens/full"); + check_macro!("textDocument/semanticTokens/full/delta"); + check_macro!("textDocument/semanticTokens/range"); + check_macro!("textDocument/inlayHint"); + check_macro!("textDocument/inlineValue"); + check_macro!("textDocument/diagnostic"); + + check_macro!("workspace/applyEdit"); + check_macro!("workspace/symbol"); + check_macro!("workspace/executeCommand"); + check_macro!("workspace/configuration"); + check_macro!("workspace/diagnostic"); + check_macro!("workspace/diagnostic/refresh"); + check_macro!("workspace/willCreateFiles"); + check_macro!("workspace/willRenameFiles"); + check_macro!("workspace/willDeleteFiles"); + check_macro!("workspace/workspaceFolders"); + check_macro!("workspace/semanticTokens/refresh"); + check_macro!("workspace/codeLens/refresh"); + check_macro!("workspace/inlayHint/refresh"); + check_macro!("workspace/inlineValue/refresh"); + + check_macro!("callHierarchy/incomingCalls"); + check_macro!("callHierarchy/outgoingCalls"); + check_macro!("codeAction/resolve"); + check_macro!("codeLens/resolve"); + check_macro!("completionItem/resolve"); + check_macro!("documentLink/resolve"); + check_macro!("inlayHint/resolve"); + check_macro!("typeHierarchy/subtypes"); + check_macro!("typeHierarchy/supertypes"); + check_macro!("workspaceSymbol/resolve"); + } + + #[test] + #[cfg(feature = "proposed")] + fn check_proposed_macro_definitions() {} +} diff --git a/helix-lsp-types/src/selection_range.rs b/helix-lsp-types/src/selection_range.rs new file mode 100644 index 000000000..048df6f99 --- /dev/null +++ b/helix-lsp-types/src/selection_range.rs @@ -0,0 +1,86 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + PartialResultParams, Position, Range, StaticTextDocumentRegistrationOptions, + TextDocumentIdentifier, WorkDoneProgressOptions, WorkDoneProgressParams, +}; +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SelectionRangeClientCapabilities { + /// Whether implementation supports dynamic registration for selection range + /// providers. If this is set to `true` the client supports the new + /// `SelectionRangeRegistrationOptions` return value for the corresponding + /// server capability as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct SelectionRangeOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct SelectionRangeRegistrationOptions { + #[serde(flatten)] + pub selection_range_options: SelectionRangeOptions, + + #[serde(flatten)] + pub registration_options: StaticTextDocumentRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum SelectionRangeProviderCapability { + Simple(bool), + Options(SelectionRangeOptions), + RegistrationOptions(SelectionRangeRegistrationOptions), +} + +impl From for SelectionRangeProviderCapability { + fn from(from: SelectionRangeRegistrationOptions) -> Self { + Self::RegistrationOptions(from) + } +} + +impl From for SelectionRangeProviderCapability { + fn from(from: SelectionRangeOptions) -> Self { + Self::Options(from) + } +} + +impl From for SelectionRangeProviderCapability { + fn from(from: bool) -> Self { + Self::Simple(from) + } +} + +/// A parameter literal used in selection range requests. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SelectionRangeParams { + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The positions inside the text document. + pub positions: Vec, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// Represents a selection range. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SelectionRange { + /// Range of the selection. + pub range: Range, + + /// The parent selection range containing this range. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option>, +} diff --git a/helix-lsp-types/src/semantic_tokens.rs b/helix-lsp-types/src/semantic_tokens.rs new file mode 100644 index 000000000..842558bac --- /dev/null +++ b/helix-lsp-types/src/semantic_tokens.rs @@ -0,0 +1,734 @@ +use std::borrow::Cow; + +use serde::ser::SerializeSeq; +use serde::{Deserialize, Serialize}; + +use crate::{ + PartialResultParams, Range, StaticRegistrationOptions, TextDocumentIdentifier, + TextDocumentRegistrationOptions, WorkDoneProgressOptions, WorkDoneProgressParams, +}; +/// A set of predefined token types. This set is not fixed +/// and clients can specify additional token types via the +/// corresponding client capabilities. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)] +pub struct SemanticTokenType(Cow<'static, str>); + +impl SemanticTokenType { + pub const NAMESPACE: SemanticTokenType = SemanticTokenType::new("namespace"); + pub const TYPE: SemanticTokenType = SemanticTokenType::new("type"); + pub const CLASS: SemanticTokenType = SemanticTokenType::new("class"); + pub const ENUM: SemanticTokenType = SemanticTokenType::new("enum"); + pub const INTERFACE: SemanticTokenType = SemanticTokenType::new("interface"); + pub const STRUCT: SemanticTokenType = SemanticTokenType::new("struct"); + pub const TYPE_PARAMETER: SemanticTokenType = SemanticTokenType::new("typeParameter"); + pub const PARAMETER: SemanticTokenType = SemanticTokenType::new("parameter"); + pub const VARIABLE: SemanticTokenType = SemanticTokenType::new("variable"); + pub const PROPERTY: SemanticTokenType = SemanticTokenType::new("property"); + pub const ENUM_MEMBER: SemanticTokenType = SemanticTokenType::new("enumMember"); + pub const EVENT: SemanticTokenType = SemanticTokenType::new("event"); + pub const FUNCTION: SemanticTokenType = SemanticTokenType::new("function"); + pub const METHOD: SemanticTokenType = SemanticTokenType::new("method"); + pub const MACRO: SemanticTokenType = SemanticTokenType::new("macro"); + pub const KEYWORD: SemanticTokenType = SemanticTokenType::new("keyword"); + pub const MODIFIER: SemanticTokenType = SemanticTokenType::new("modifier"); + pub const COMMENT: SemanticTokenType = SemanticTokenType::new("comment"); + pub const STRING: SemanticTokenType = SemanticTokenType::new("string"); + pub const NUMBER: SemanticTokenType = SemanticTokenType::new("number"); + pub const REGEXP: SemanticTokenType = SemanticTokenType::new("regexp"); + pub const OPERATOR: SemanticTokenType = SemanticTokenType::new("operator"); + + /// @since 3.17.0 + pub const DECORATOR: SemanticTokenType = SemanticTokenType::new("decorator"); + + pub const fn new(tag: &'static str) -> Self { + SemanticTokenType(Cow::Borrowed(tag)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for SemanticTokenType { + fn from(from: String) -> Self { + SemanticTokenType(Cow::from(from)) + } +} + +impl From<&'static str> for SemanticTokenType { + fn from(from: &'static str) -> Self { + SemanticTokenType::new(from) + } +} + +/// A set of predefined token modifiers. This set is not fixed +/// and clients can specify additional token types via the +/// corresponding client capabilities. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)] +pub struct SemanticTokenModifier(Cow<'static, str>); + +impl SemanticTokenModifier { + pub const DECLARATION: SemanticTokenModifier = SemanticTokenModifier::new("declaration"); + pub const DEFINITION: SemanticTokenModifier = SemanticTokenModifier::new("definition"); + pub const READONLY: SemanticTokenModifier = SemanticTokenModifier::new("readonly"); + pub const STATIC: SemanticTokenModifier = SemanticTokenModifier::new("static"); + pub const DEPRECATED: SemanticTokenModifier = SemanticTokenModifier::new("deprecated"); + pub const ABSTRACT: SemanticTokenModifier = SemanticTokenModifier::new("abstract"); + pub const ASYNC: SemanticTokenModifier = SemanticTokenModifier::new("async"); + pub const MODIFICATION: SemanticTokenModifier = SemanticTokenModifier::new("modification"); + pub const DOCUMENTATION: SemanticTokenModifier = SemanticTokenModifier::new("documentation"); + pub const DEFAULT_LIBRARY: SemanticTokenModifier = SemanticTokenModifier::new("defaultLibrary"); + + pub const fn new(tag: &'static str) -> Self { + SemanticTokenModifier(Cow::Borrowed(tag)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for SemanticTokenModifier { + fn from(from: String) -> Self { + SemanticTokenModifier(Cow::from(from)) + } +} + +impl From<&'static str> for SemanticTokenModifier { + fn from(from: &'static str) -> Self { + SemanticTokenModifier::new(from) + } +} + +#[derive(Debug, Eq, PartialEq, Hash, PartialOrd, Clone, Deserialize, Serialize)] +pub struct TokenFormat(Cow<'static, str>); + +impl TokenFormat { + pub const RELATIVE: TokenFormat = TokenFormat::new("relative"); + + pub const fn new(tag: &'static str) -> Self { + TokenFormat(Cow::Borrowed(tag)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl From for TokenFormat { + fn from(from: String) -> Self { + TokenFormat(Cow::from(from)) + } +} + +impl From<&'static str> for TokenFormat { + fn from(from: &'static str) -> Self { + TokenFormat::new(from) + } +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensLegend { + /// The token types a server uses. + pub token_types: Vec, + + /// The token modifiers a server uses. + pub token_modifiers: Vec, +} + +/// The actual tokens. +#[derive(Debug, Eq, PartialEq, Copy, Clone, Default)] +pub struct SemanticToken { + pub delta_line: u32, + pub delta_start: u32, + pub length: u32, + pub token_type: u32, + pub token_modifiers_bitset: u32, +} + +impl SemanticToken { + fn deserialize_tokens<'de, D>(deserializer: D) -> Result, D::Error> + where + D: serde::Deserializer<'de>, + { + let data = Vec::::deserialize(deserializer)?; + let chunks = data.chunks_exact(5); + + if !chunks.remainder().is_empty() { + return Result::Err(serde::de::Error::custom("Length is not divisible by 5")); + } + + Result::Ok( + chunks + .map(|chunk| SemanticToken { + delta_line: chunk[0], + delta_start: chunk[1], + length: chunk[2], + token_type: chunk[3], + token_modifiers_bitset: chunk[4], + }) + .collect(), + ) + } + + fn serialize_tokens(tokens: &[SemanticToken], serializer: S) -> Result + where + S: serde::Serializer, + { + let mut seq = serializer.serialize_seq(Some(tokens.len() * 5))?; + for token in tokens.iter() { + seq.serialize_element(&token.delta_line)?; + seq.serialize_element(&token.delta_start)?; + seq.serialize_element(&token.length)?; + seq.serialize_element(&token.token_type)?; + seq.serialize_element(&token.token_modifiers_bitset)?; + } + seq.end() + } + + fn deserialize_tokens_opt<'de, D>( + deserializer: D, + ) -> Result>, D::Error> + where + D: serde::Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(transparent)] + struct Wrapper { + #[serde(deserialize_with = "SemanticToken::deserialize_tokens")] + tokens: Vec, + } + + Ok(Option::::deserialize(deserializer)?.map(|wrapper| wrapper.tokens)) + } + + fn serialize_tokens_opt( + data: &Option>, + serializer: S, + ) -> Result + where + S: serde::Serializer, + { + #[derive(Serialize)] + #[serde(transparent)] + struct Wrapper { + #[serde(serialize_with = "SemanticToken::serialize_tokens")] + tokens: Vec, + } + + let opt = data.as_ref().map(|t| Wrapper { tokens: t.to_vec() }); + + opt.serialize(serializer) + } +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokens { + /// An optional result id. If provided and clients support delta updating + /// the client will include the result id in the next semantic token request. + /// A server can then instead of computing all semantic tokens again simply + /// send a delta. + #[serde(skip_serializing_if = "Option::is_none")] + pub result_id: Option, + + /// The actual tokens. For a detailed description about how the data is + /// structured please see + /// + #[serde( + deserialize_with = "SemanticToken::deserialize_tokens", + serialize_with = "SemanticToken::serialize_tokens" + )] + pub data: Vec, +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensPartialResult { + #[serde( + deserialize_with = "SemanticToken::deserialize_tokens", + serialize_with = "SemanticToken::serialize_tokens" + )] + pub data: Vec, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum SemanticTokensResult { + Tokens(SemanticTokens), + Partial(SemanticTokensPartialResult), +} + +impl From for SemanticTokensResult { + fn from(from: SemanticTokens) -> Self { + SemanticTokensResult::Tokens(from) + } +} + +impl From for SemanticTokensResult { + fn from(from: SemanticTokensPartialResult) -> Self { + SemanticTokensResult::Partial(from) + } +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensEdit { + pub start: u32, + pub delete_count: u32, + + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "SemanticToken::deserialize_tokens_opt", + serialize_with = "SemanticToken::serialize_tokens_opt" + )] + pub data: Option>, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum SemanticTokensFullDeltaResult { + Tokens(SemanticTokens), + TokensDelta(SemanticTokensDelta), + PartialTokensDelta { edits: Vec }, +} + +impl From for SemanticTokensFullDeltaResult { + fn from(from: SemanticTokens) -> Self { + SemanticTokensFullDeltaResult::Tokens(from) + } +} + +impl From for SemanticTokensFullDeltaResult { + fn from(from: SemanticTokensDelta) -> Self { + SemanticTokensFullDeltaResult::TokensDelta(from) + } +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensDelta { + #[serde(skip_serializing_if = "Option::is_none")] + pub result_id: Option, + /// For a detailed description how these edits are structured please see + /// + pub edits: Vec, +} + +/// Capabilities specific to the `textDocument/semanticTokens/*` requests. +/// +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensClientCapabilities { + /// Whether implementation supports dynamic registration. If this is set to `true` + /// the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` + /// return value for the corresponding server capability as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Which requests the client supports and might send to the server + /// depending on the server's capability. Please note that clients might not + /// show semantic tokens or degrade some of the user experience if a range + /// or full request is advertised by the client but not provided by the + /// server. If for example the client capability `requests.full` and + /// `request.range` are both set to true but the server only provides a + /// range provider the client might not render a minimap correctly or might + /// even decide to not show any semantic tokens at all. + pub requests: SemanticTokensClientCapabilitiesRequests, + + /// The token types that the client supports. + pub token_types: Vec, + + /// The token modifiers that the client supports. + pub token_modifiers: Vec, + + /// The token formats the clients supports. + pub formats: Vec, + + /// Whether the client supports tokens that can overlap each other. + #[serde(skip_serializing_if = "Option::is_none")] + pub overlapping_token_support: Option, + + /// Whether the client supports tokens that can span multiple lines. + #[serde(skip_serializing_if = "Option::is_none")] + pub multiline_token_support: Option, + + /// Whether the client allows the server to actively cancel a + /// semantic token request, e.g. supports returning + /// ErrorCodes.ServerCancelled. If a server does the client + /// needs to retrigger the request. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub server_cancel_support: Option, + + /// Whether the client uses semantic tokens to augment existing + /// syntax tokens. If set to `true` client side created syntax + /// tokens and semantic tokens are both used for colorization. If + /// set to `false` the client only uses the returned semantic tokens + /// for colorization. + /// + /// If the value is `undefined` then the client behavior is not + /// specified. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub augments_syntax_tokens: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensClientCapabilitiesRequests { + /// The client will send the `textDocument/semanticTokens/range` request if the server provides a corresponding handler. + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, + + /// The client will send the `textDocument/semanticTokens/full` request if the server provides a corresponding handler. + #[serde(skip_serializing_if = "Option::is_none")] + pub full: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum SemanticTokensFullOptions { + Bool(bool), + Delta { + /// The client will send the `textDocument/semanticTokens/full/delta` request if the server provides a corresponding handler. + /// The server supports deltas for full documents. + #[serde(skip_serializing_if = "Option::is_none")] + delta: Option, + }, +} + +/// @since 3.16.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, + + /// The legend used by the server + pub legend: SemanticTokensLegend, + + /// Server supports providing semantic tokens for a specific range + /// of a document. + #[serde(skip_serializing_if = "Option::is_none")] + pub range: Option, + + /// Server supports providing semantic tokens for a full document. + #[serde(skip_serializing_if = "Option::is_none")] + pub full: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + + #[serde(flatten)] + pub semantic_tokens_options: SemanticTokensOptions, + + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum SemanticTokensServerCapabilities { + SemanticTokensOptions(SemanticTokensOptions), + SemanticTokensRegistrationOptions(SemanticTokensRegistrationOptions), +} + +impl From for SemanticTokensServerCapabilities { + fn from(from: SemanticTokensOptions) -> Self { + SemanticTokensServerCapabilities::SemanticTokensOptions(from) + } +} + +impl From for SemanticTokensServerCapabilities { + fn from(from: SemanticTokensRegistrationOptions) -> Self { + SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(from) + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensWorkspaceClientCapabilities { + /// Whether the client implementation supports a refresh request sent from + /// the server to the client. + /// + /// Note that this event is global and will force the client to refresh all + /// semantic tokens currently shown. It should be used with absolute care + /// and is useful for situation where a server for example detect a project + /// wide change that requires such a calculation. + pub refresh_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + /// The text document. + pub text_document: TextDocumentIdentifier, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensDeltaParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The result id of a previous response. The result Id can either point to a full response + /// or a delta response depending on what was received last. + pub previous_result_id: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SemanticTokensRangeParams { + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + /// The text document. + pub text_document: TextDocumentIdentifier, + + /// The range the semantic tokens are requested for. + pub range: Range, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +#[serde(untagged)] +pub enum SemanticTokensRangeResult { + Tokens(SemanticTokens), + Partial(SemanticTokensPartialResult), +} + +impl From for SemanticTokensRangeResult { + fn from(tokens: SemanticTokens) -> Self { + SemanticTokensRangeResult::Tokens(tokens) + } +} + +impl From for SemanticTokensRangeResult { + fn from(partial: SemanticTokensPartialResult) -> Self { + SemanticTokensRangeResult::Partial(partial) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{test_deserialization, test_serialization}; + + #[test] + fn test_semantic_tokens_support_serialization() { + test_serialization( + &SemanticTokens { + result_id: None, + data: vec![], + }, + r#"{"data":[]}"#, + ); + + test_serialization( + &SemanticTokens { + result_id: None, + data: vec![SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }], + }, + r#"{"data":[2,5,3,0,3]}"#, + ); + + test_serialization( + &SemanticTokens { + result_id: None, + data: vec![ + SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }, + SemanticToken { + delta_line: 0, + delta_start: 5, + length: 4, + token_type: 1, + token_modifiers_bitset: 0, + }, + ], + }, + r#"{"data":[2,5,3,0,3,0,5,4,1,0]}"#, + ); + } + + #[test] + fn test_semantic_tokens_support_deserialization() { + test_deserialization( + r#"{"data":[]}"#, + &SemanticTokens { + result_id: None, + data: vec![], + }, + ); + + test_deserialization( + r#"{"data":[2,5,3,0,3]}"#, + &SemanticTokens { + result_id: None, + data: vec![SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }], + }, + ); + + test_deserialization( + r#"{"data":[2,5,3,0,3,0,5,4,1,0]}"#, + &SemanticTokens { + result_id: None, + data: vec![ + SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }, + SemanticToken { + delta_line: 0, + delta_start: 5, + length: 4, + token_type: 1, + token_modifiers_bitset: 0, + }, + ], + }, + ); + } + + #[test] + #[should_panic] + fn test_semantic_tokens_support_deserialization_err() { + test_deserialization( + r#"{"data":[1]}"#, + &SemanticTokens { + result_id: None, + data: vec![], + }, + ); + } + + #[test] + fn test_semantic_tokens_edit_support_deserialization() { + test_deserialization( + r#"{"start":0,"deleteCount":1,"data":[2,5,3,0,3,0,5,4,1,0]}"#, + &SemanticTokensEdit { + start: 0, + delete_count: 1, + data: Some(vec![ + SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }, + SemanticToken { + delta_line: 0, + delta_start: 5, + length: 4, + token_type: 1, + token_modifiers_bitset: 0, + }, + ]), + }, + ); + + test_deserialization( + r#"{"start":0,"deleteCount":1}"#, + &SemanticTokensEdit { + start: 0, + delete_count: 1, + data: None, + }, + ); + } + + #[test] + fn test_semantic_tokens_edit_support_serialization() { + test_serialization( + &SemanticTokensEdit { + start: 0, + delete_count: 1, + data: Some(vec![ + SemanticToken { + delta_line: 2, + delta_start: 5, + length: 3, + token_type: 0, + token_modifiers_bitset: 3, + }, + SemanticToken { + delta_line: 0, + delta_start: 5, + length: 4, + token_type: 1, + token_modifiers_bitset: 0, + }, + ]), + }, + r#"{"start":0,"deleteCount":1,"data":[2,5,3,0,3,0,5,4,1,0]}"#, + ); + + test_serialization( + &SemanticTokensEdit { + start: 0, + delete_count: 1, + data: None, + }, + r#"{"start":0,"deleteCount":1}"#, + ); + } +} diff --git a/helix-lsp-types/src/signature_help.rs b/helix-lsp-types/src/signature_help.rs new file mode 100644 index 000000000..2466d1088 --- /dev/null +++ b/helix-lsp-types/src/signature_help.rs @@ -0,0 +1,207 @@ +use serde::{Deserialize, Serialize}; + +use crate::{ + Documentation, MarkupKind, TextDocumentPositionParams, TextDocumentRegistrationOptions, + WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureInformationSettings { + /// Client supports the follow content formats for the documentation + /// property. The order describes the preferred format of the client. + #[serde(skip_serializing_if = "Option::is_none")] + pub documentation_format: Option>, + + #[serde(skip_serializing_if = "Option::is_none")] + pub parameter_information: Option, + + /// The client support the `activeParameter` property on `SignatureInformation` + /// literal. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub active_parameter_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ParameterInformationSettings { + /// The client supports processing label offsets instead of a + /// simple label string. + /// + /// @since 3.14.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub label_offset_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelpClientCapabilities { + /// Whether completion supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// The client supports the following `SignatureInformation` + /// specific properties. + #[serde(skip_serializing_if = "Option::is_none")] + pub signature_information: Option, + + /// The client supports to send additional context information for a + /// `textDocument/signatureHelp` request. A client that opts into + /// contextSupport will also support the `retriggerCharacters` on + /// `SignatureHelpOptions`. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub context_support: Option, +} + +/// Signature help options. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelpOptions { + /// The characters that trigger signature help automatically. + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger_characters: Option>, + + /// List of characters that re-trigger signature help. + /// These trigger characters are only active when signature help is already showing. All trigger characters + /// are also counted as re-trigger characters. + #[serde(skip_serializing_if = "Option::is_none")] + pub retrigger_characters: Option>, + + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +/// Signature help options. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct SignatureHelpRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, +} + +/// Signature help options. +#[derive(Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(transparent)] +pub struct SignatureHelpTriggerKind(i32); +lsp_enum! { +impl SignatureHelpTriggerKind { + /// Signature help was invoked manually by the user or by a command. + pub const INVOKED: SignatureHelpTriggerKind = SignatureHelpTriggerKind(1); + /// Signature help was triggered by a trigger character. + pub const TRIGGER_CHARACTER: SignatureHelpTriggerKind = SignatureHelpTriggerKind(2); + /// Signature help was triggered by the cursor moving or by the document content changing. + pub const CONTENT_CHANGE: SignatureHelpTriggerKind = SignatureHelpTriggerKind(3); +} +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelpParams { + /// The signature help context. This is only available if the client specifies + /// to send this using the client capability `textDocument.signatureHelp.contextSupport === true` + #[serde(skip_serializing_if = "Option::is_none")] + pub context: Option, + + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelpContext { + /// Action that caused signature help to be triggered. + pub trigger_kind: SignatureHelpTriggerKind, + + /// Character that caused signature help to be triggered. + /// This is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter` + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger_character: Option, + + /// `true` if signature help was already showing when it was triggered. + /// Retriggers occur when the signature help is already active and can be caused by actions such as + /// typing a trigger character, a cursor move, or document content changes. + pub is_retrigger: bool, + + /// The currently active `SignatureHelp`. + /// The `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on + /// the user navigating through available signatures. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_signature_help: Option, +} + +/// Signature help represents the signature of something +/// callable. There can be multiple signature but only one +/// active and only one active parameter. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureHelp { + /// One or more signatures. + pub signatures: Vec, + + /// The active signature. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_signature: Option, + + /// The active parameter of the active signature. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_parameter: Option, +} + +/// Represents the signature of something callable. A signature +/// can have a label, like a function-name, a doc-comment, and +/// a set of parameters. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SignatureInformation { + /// The label of this signature. Will be shown in + /// the UI. + pub label: String, + + /// The human-readable doc-comment of this signature. Will be shown + /// in the UI but can be omitted. + #[serde(skip_serializing_if = "Option::is_none")] + pub documentation: Option, + + /// The parameters of this signature. + #[serde(skip_serializing_if = "Option::is_none")] + pub parameters: Option>, + + /// The index of the active parameter. + /// + /// If provided, this is used in place of `SignatureHelp.activeParameter`. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub active_parameter: Option, +} + +/// Represents a parameter of a callable-signature. A parameter can +/// have a label and a doc-comment. +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ParameterInformation { + /// The label of this parameter information. + /// + /// Either a string or an inclusive start and exclusive end offsets within its containing + /// signature label. (see SignatureInformation.label). *Note*: A label of type string must be + /// a substring of its containing signature label. + pub label: ParameterLabel, + + /// The human-readable doc-comment of this parameter. Will be shown + /// in the UI but can be omitted. + #[serde(skip_serializing_if = "Option::is_none")] + pub documentation: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum ParameterLabel { + Simple(String), + LabelOffsets([u32; 2]), +} diff --git a/helix-lsp-types/src/trace.rs b/helix-lsp-types/src/trace.rs new file mode 100644 index 000000000..7abcc5673 --- /dev/null +++ b/helix-lsp-types/src/trace.rs @@ -0,0 +1,77 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct SetTraceParams { + /// The new value that should be assigned to the trace setting. + pub value: TraceValue, +} + +/// A TraceValue represents the level of verbosity with which the server systematically +/// reports its execution trace using `LogTrace` notifications. +/// +/// The initial trace value is set by the client at initialization and can be modified +/// later using the `SetTrace` notification. +#[derive(Debug, Eq, PartialEq, Clone, Copy, Deserialize, Serialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum TraceValue { + /// The server should not send any `$/logTrace` notification + #[default] + Off, + /// The server should not add the 'verbose' field in the `LogTraceParams` + Messages, + Verbose, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LogTraceParams { + /// The message to be logged. + pub message: String, + /// Additional information that can be computed if the `trace` configuration + /// is set to `'verbose'` + #[serde(skip_serializing_if = "Option::is_none")] + pub verbose: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_serialization; + + #[test] + fn test_set_trace_params() { + test_serialization( + &SetTraceParams { + value: TraceValue::Off, + }, + r#"{"value":"off"}"#, + ); + } + + #[test] + fn test_log_trace_params() { + test_serialization( + &LogTraceParams { + message: "message".into(), + verbose: None, + }, + r#"{"message":"message"}"#, + ); + + test_serialization( + &LogTraceParams { + message: "message".into(), + verbose: Some("verbose".into()), + }, + r#"{"message":"message","verbose":"verbose"}"#, + ); + } + + #[test] + fn test_trace_value() { + test_serialization( + &vec![TraceValue::Off, TraceValue::Messages, TraceValue::Verbose], + r#"["off","messages","verbose"]"#, + ); + } +} diff --git a/helix-lsp-types/src/type_hierarchy.rs b/helix-lsp-types/src/type_hierarchy.rs new file mode 100644 index 000000000..568a03e25 --- /dev/null +++ b/helix-lsp-types/src/type_hierarchy.rs @@ -0,0 +1,90 @@ +use crate::{ + DynamicRegistrationClientCapabilities, LSPAny, PartialResultParams, Range, + StaticRegistrationOptions, SymbolKind, SymbolTag, TextDocumentPositionParams, + TextDocumentRegistrationOptions, Url, WorkDoneProgressOptions, WorkDoneProgressParams, +}; + +use serde::{Deserialize, Serialize}; + +pub type TypeHierarchyClientCapabilities = DynamicRegistrationClientCapabilities; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct TypeHierarchyOptions { + #[serde(flatten)] + pub work_done_progress_options: WorkDoneProgressOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct TypeHierarchyRegistrationOptions { + #[serde(flatten)] + pub text_document_registration_options: TextDocumentRegistrationOptions, + #[serde(flatten)] + pub type_hierarchy_options: TypeHierarchyOptions, + #[serde(flatten)] + pub static_registration_options: StaticRegistrationOptions, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct TypeHierarchyPrepareParams { + #[serde(flatten)] + pub text_document_position_params: TextDocumentPositionParams, + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct TypeHierarchySupertypesParams { + pub item: TypeHierarchyItem, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct TypeHierarchySubtypesParams { + pub item: TypeHierarchyItem, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TypeHierarchyItem { + /// The name of this item. + pub name: String, + + /// The kind of this item. + pub kind: SymbolKind, + + /// Tags for this item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option, + + /// More detail for this item, e.g. the signature of a function. + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + + /// The resource identifier of this item. + pub uri: Url, + + /// The range enclosing this symbol not including leading/trailing whitespace + /// but everything else, e.g. comments and code. + pub range: Range, + + /// The range that should be selected and revealed when this symbol is being + /// picked, e.g. the name of a function. Must be contained by the + /// [`range`](#TypeHierarchyItem.range). + pub selection_range: Range, + + /// A data entry field that is preserved between a type hierarchy prepare and + /// supertypes or subtypes requests. It could also be used to identify the + /// type hierarchy in the server, helping improve the performance on + /// resolving supertypes and subtypes. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} diff --git a/helix-lsp-types/src/window.rs b/helix-lsp-types/src/window.rs new file mode 100644 index 000000000..ac45e6083 --- /dev/null +++ b/helix-lsp-types/src/window.rs @@ -0,0 +1,173 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use serde_json::Value; + +use url::Url; + +use crate::Range; + +#[derive(Eq, PartialEq, Clone, Copy, Deserialize, Serialize)] +#[serde(transparent)] +pub struct MessageType(i32); +lsp_enum! { +impl MessageType { + /// An error message. + pub const ERROR: MessageType = MessageType(1); + /// A warning message. + pub const WARNING: MessageType = MessageType(2); + /// An information message; + pub const INFO: MessageType = MessageType(3); + /// A log message. + pub const LOG: MessageType = MessageType(4); +} +} + +/// Window specific client capabilities. +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WindowClientCapabilities { + /// Whether client supports handling progress notifications. If set + /// servers are allowed to report in `workDoneProgress` property in the + /// request specific server capabilities. + /// + /// @since 3.15.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub work_done_progress: Option, + + /// Capabilities specific to the showMessage request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub show_message: Option, + + /// Client capabilities for the show document request. + /// + /// @since 3.16.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub show_document: Option, +} + +/// Show message request client capabilities +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShowMessageRequestClientCapabilities { + /// Capabilities specific to the `MessageActionItem` type. + #[serde(skip_serializing_if = "Option::is_none")] + pub message_action_item: Option, +} + +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MessageActionItemCapabilities { + /// Whether the client supports additional attributes which + /// are preserved and send back to the server in the + /// request's response. + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_properties_support: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MessageActionItem { + /// A short title like 'Retry', 'Open Log' etc. + pub title: String, + + /// Additional attributes that the client preserves and + /// sends back to the server. This depends on the client + /// capability window.messageActionItem.additionalPropertiesSupport + #[serde(flatten)] + pub properties: HashMap, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum MessageActionItemProperty { + String(String), + Boolean(bool), + Integer(i32), + Object(Value), +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct LogMessageParams { + /// The message type. See {@link MessageType} + #[serde(rename = "type")] + pub typ: MessageType, + + /// The actual message + pub message: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct ShowMessageParams { + /// The message type. See {@link MessageType}. + #[serde(rename = "type")] + pub typ: MessageType, + + /// The actual message. + pub message: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct ShowMessageRequestParams { + /// The message type. See {@link MessageType} + #[serde(rename = "type")] + pub typ: MessageType, + + /// The actual message + pub message: String, + + /// The message action items to present. + #[serde(skip_serializing_if = "Option::is_none")] + pub actions: Option>, +} + +/// Client capabilities for the show document request. +#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShowDocumentClientCapabilities { + /// The client has support for the show document request. + pub support: bool, +} + +/// Params to show a document. +/// +/// @since 3.16.0 +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShowDocumentParams { + /// The document uri to show. + pub uri: Url, + + /// Indicates to show the resource in an external program. + /// To show for example `https://code.visualstudio.com/` + /// in the default WEB browser set `external` to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub external: Option, + + /// An optional property to indicate whether the editor + /// showing the document should take focus or not. + /// Clients might ignore this property if an external + /// program in started. + #[serde(skip_serializing_if = "Option::is_none")] + pub take_focus: Option, + + /// An optional selection range if the document is a text + /// document. Clients might ignore the property if an + /// external program is started or the file is not a text + /// file. + #[serde(skip_serializing_if = "Option::is_none")] + pub selection: Option, +} + +/// The result of an show document request. +/// +/// @since 3.16.0 +#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShowDocumentResult { + /// A boolean indicating if the show was successful. + pub success: bool, +} diff --git a/helix-lsp-types/src/workspace_diagnostic.rs b/helix-lsp-types/src/workspace_diagnostic.rs new file mode 100644 index 000000000..e8a7646b0 --- /dev/null +++ b/helix-lsp-types/src/workspace_diagnostic.rs @@ -0,0 +1,149 @@ +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::{ + FullDocumentDiagnosticReport, PartialResultParams, UnchangedDocumentDiagnosticReport, + WorkDoneProgressParams, +}; + +/// Workspace client capabilities specific to diagnostic pull requests. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DiagnosticWorkspaceClientCapabilities { + /// Whether the client implementation supports a refresh request sent from + /// the server to the client. + /// + /// Note that this event is global and will force the client to refresh all + /// pulled diagnostics currently shown. It should be used with absolute care + /// and is useful for situation where a server for example detects a project + /// wide change that requires such a calculation. + #[serde(skip_serializing_if = "Option::is_none")] + pub refresh_support: Option, +} + +/// A previous result ID in a workspace pull request. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct PreviousResultId { + /// The URI for which the client knows a result ID. + pub uri: Url, + + /// The value of the previous result ID. + pub value: String, +} + +/// Parameters of the workspace diagnostic request. +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceDiagnosticParams { + /// The additional identifier provided during registration. + pub identifier: Option, + + /// The currently known diagnostic reports with their + /// previous result ids. + pub previous_result_ids: Vec, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + #[serde(flatten)] + pub partial_result_params: PartialResultParams, +} + +/// A full document diagnostic report for a workspace diagnostic result. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFullDocumentDiagnosticReport { + /// The URI for which diagnostic information is reported. + pub uri: Url, + + /// The version number for which the diagnostics are reported. + /// + /// If the document is not marked as open, `None` can be provided. + pub version: Option, + + #[serde(flatten)] + pub full_document_diagnostic_report: FullDocumentDiagnosticReport, +} + +/// An unchanged document diagnostic report for a workspace diagnostic result. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceUnchangedDocumentDiagnosticReport { + /// The URI for which diagnostic information is reported. + pub uri: Url, + + /// The version number for which the diagnostics are reported. + /// + /// If the document is not marked as open, `None` can be provided. + pub version: Option, + + #[serde(flatten)] + pub unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport, +} + +/// A workspace diagnostic document report. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum WorkspaceDocumentDiagnosticReport { + Full(WorkspaceFullDocumentDiagnosticReport), + Unchanged(WorkspaceUnchangedDocumentDiagnosticReport), +} + +impl From for WorkspaceDocumentDiagnosticReport { + fn from(from: WorkspaceFullDocumentDiagnosticReport) -> Self { + WorkspaceDocumentDiagnosticReport::Full(from) + } +} + +impl From for WorkspaceDocumentDiagnosticReport { + fn from(from: WorkspaceUnchangedDocumentDiagnosticReport) -> Self { + WorkspaceDocumentDiagnosticReport::Unchanged(from) + } +} + +/// A workspace diagnostic report. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +pub struct WorkspaceDiagnosticReport { + pub items: Vec, +} + +/// A partial result for a workspace diagnostic report. +/// +/// @since 3.17.0 +#[derive(Debug, PartialEq, Default, Deserialize, Serialize, Clone)] +pub struct WorkspaceDiagnosticReportPartialResult { + pub items: Vec, +} + +#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)] +#[serde(untagged)] +pub enum WorkspaceDiagnosticReportResult { + Report(WorkspaceDiagnosticReport), + Partial(WorkspaceDiagnosticReportPartialResult), +} + +impl From for WorkspaceDiagnosticReportResult { + fn from(from: WorkspaceDiagnosticReport) -> Self { + WorkspaceDiagnosticReportResult::Report(from) + } +} + +impl From for WorkspaceDiagnosticReportResult { + fn from(from: WorkspaceDiagnosticReportPartialResult) -> Self { + WorkspaceDiagnosticReportResult::Partial(from) + } +} diff --git a/helix-lsp-types/src/workspace_folders.rs b/helix-lsp-types/src/workspace_folders.rs new file mode 100644 index 000000000..aeca89ffe --- /dev/null +++ b/helix-lsp-types/src/workspace_folders.rs @@ -0,0 +1,49 @@ +use serde::{Deserialize, Serialize}; +use url::Url; + +use crate::OneOf; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFoldersServerCapabilities { + /// The server has support for workspace folders + #[serde(skip_serializing_if = "Option::is_none")] + pub supported: Option, + + /// Whether the server wants to receive workspace folder + /// change notifications. + /// + /// If a string is provided, the string is treated as an ID + /// under which the notification is registered on the client + /// side. The ID can be used to unregister for these events + /// using the `client/unregisterCapability` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub change_notifications: Option>, +} + +#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFolder { + /// The associated URI for this workspace folder. + pub uri: Url, + /// The name of the workspace folder. Defaults to the uri's basename. + pub name: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct DidChangeWorkspaceFoldersParams { + /// The actual workspace folder change event. + pub event: WorkspaceFoldersChangeEvent, +} + +/// The workspace folder change event. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceFoldersChangeEvent { + /// The array of added workspace folders + pub added: Vec, + + /// The array of the removed workspace folders + pub removed: Vec, +} diff --git a/helix-lsp-types/src/workspace_symbols.rs b/helix-lsp-types/src/workspace_symbols.rs new file mode 100644 index 000000000..9ba80895b --- /dev/null +++ b/helix-lsp-types/src/workspace_symbols.rs @@ -0,0 +1,105 @@ +use crate::{ + LSPAny, Location, OneOf, PartialResultParams, SymbolInformation, SymbolKind, + SymbolKindCapability, SymbolTag, TagSupport, Url, WorkDoneProgressParams, +}; + +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceSymbolClientCapabilities { + /// This capability supports dynamic registration. + #[serde(skip_serializing_if = "Option::is_none")] + pub dynamic_registration: Option, + + /// Specific capabilities for the `SymbolKind` in the `workspace/symbol` request. + #[serde(skip_serializing_if = "Option::is_none")] + pub symbol_kind: Option, + + /// The client supports tags on `SymbolInformation`. + /// Clients supporting tags have to handle unknown tags gracefully. + /// + /// @since 3.16.0 + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "TagSupport::deserialize_compat" + )] + pub tag_support: Option>, + + /// The client support partial workspace symbols. The client will send the + /// request `workspaceSymbol/resolve` to the server to resolve additional + /// properties. + /// + /// @since 3.17.0 + #[serde(skip_serializing_if = "Option::is_none")] + pub resolve_support: Option, +} + +/// The parameters of a Workspace Symbol Request. +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct WorkspaceSymbolParams { + #[serde(flatten)] + pub partial_result_params: PartialResultParams, + + #[serde(flatten)] + pub work_done_progress_params: WorkDoneProgressParams, + + /// A non-empty query string + pub query: String, +} + +#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] +pub struct WorkspaceSymbolResolveSupportCapability { + /// The properties that a client can resolve lazily. Usually + /// `location.range` + pub properties: Vec, +} + +/// A special workspace symbol that supports locations without a range +/// +/// @since 3.17.0 +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceSymbol { + /// The name of this symbol. + pub name: String, + + /// The kind of this symbol. + pub kind: SymbolKind, + + /// Tags for this completion item. + #[serde(skip_serializing_if = "Option::is_none")] + pub tags: Option>, + + /// The name of the symbol containing this symbol. This information is for + /// user interface purposes (e.g. to render a qualifier in the user interface + /// if necessary). It can't be used to re-infer a hierarchy for the document + /// symbols. + #[serde(skip_serializing_if = "Option::is_none")] + pub container_name: Option, + + /// The location of this symbol. Whether a server is allowed to + /// return a location without a range depends on the client + /// capability `workspace.symbol.resolveSupport`. + /// + /// See also `SymbolInformation.location`. + pub location: OneOf, + + /// A data entry field that is preserved on a workspace symbol between a + /// workspace symbol request and a workspace symbol resolve request. + #[serde(skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] +pub struct WorkspaceLocation { + pub uri: Url, +} + +#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum WorkspaceSymbolResponse { + Flat(Vec), + Nested(Vec), +} diff --git a/helix-lsp/Cargo.toml b/helix-lsp/Cargo.toml index ab9251ebe..c4260be6d 100644 --- a/helix-lsp/Cargo.toml +++ b/helix-lsp/Cargo.toml @@ -17,16 +17,16 @@ helix-stdx = { path = "../helix-stdx" } helix-core = { path = "../helix-core" } helix-loader = { path = "../helix-loader" } helix-parsec = { path = "../helix-parsec" } +helix-lsp-types = { path = "../helix-lsp-types" } anyhow = "1.0" futures-executor = "0.3" futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false } globset = "0.4.14" log = "0.4" -lsp-types = { version = "0.95" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -tokio = { version = "1.38", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] } +tokio = { version = "1.39", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] } tokio-stream = "0.1.15" parking_lot = "0.12.3" arc-swap = "1" diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs index 643aa9a26..cc1c4ce8f 100644 --- a/helix-lsp/src/client.rs +++ b/helix-lsp/src/client.rs @@ -5,15 +5,14 @@ use crate::{ Call, Error, LanguageServerId, OffsetEncoding, Result, }; -use helix_core::{find_workspace, syntax::LanguageServerFeature, ChangeSet, Rope}; -use helix_loader::VERSION_AND_GIT_HASH; -use helix_stdx::path; -use lsp::{ - notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, +use crate::lsp::{ + self, notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, DidChangeWorkspaceFoldersParams, OneOf, PositionEncodingKind, SignatureHelp, Url, WorkspaceFolder, WorkspaceFoldersChangeEvent, }; -use lsp_types as lsp; +use helix_core::{find_workspace, syntax::LanguageServerFeature, ChangeSet, Rope}; +use helix_loader::VERSION_AND_GIT_HASH; +use helix_stdx::path; use parking_lot::Mutex; use serde::Deserialize; use serde_json::Value; @@ -994,7 +993,7 @@ impl Client { .. }) => match options.as_ref()? { lsp::TextDocumentSyncSaveOptions::Supported(true) => false, - lsp::TextDocumentSyncSaveOptions::SaveOptions(lsp_types::SaveOptions { + lsp::TextDocumentSyncSaveOptions::SaveOptions(lsp::SaveOptions { include_text, }) => include_text.unwrap_or(false), lsp::TextDocumentSyncSaveOptions::Supported(false) => return None, diff --git a/helix-lsp/src/lib.rs b/helix-lsp/src/lib.rs index 8e423e1c3..47f38bcf2 100644 --- a/helix-lsp/src/lib.rs +++ b/helix-lsp/src/lib.rs @@ -8,9 +8,9 @@ mod transport; use arc_swap::ArcSwap; pub use client::Client; pub use futures_executor::block_on; +pub use helix_lsp_types as lsp; pub use jsonrpc::Call; pub use lsp::{Position, Url}; -pub use lsp_types as lsp; use futures_util::stream::select_all::SelectAll; use helix_core::syntax::{ @@ -503,7 +503,7 @@ pub mod util { ) -> Transaction { // Sort edits by start range, since some LSPs (Omnisharp) send them // in reverse order. - edits.sort_unstable_by_key(|edit| edit.range.start); + edits.sort_by_key(|edit| edit.range.start); // Generate a diff if the edit is a full document replacement. #[allow(clippy::collapsible_if)] @@ -1113,7 +1113,7 @@ mod tests { #[test] fn emoji_format_gh_4791() { - use lsp_types::{Position, Range, TextEdit}; + use lsp::{Position, Range, TextEdit}; let edits = vec![ TextEdit { diff --git a/helix-lsp/src/transport.rs b/helix-lsp/src/transport.rs index bd671abe1..1bded598d 100644 --- a/helix-lsp/src/transport.rs +++ b/helix-lsp/src/transport.rs @@ -1,4 +1,8 @@ -use crate::{jsonrpc, Error, LanguageServerId, Result}; +use crate::{ + jsonrpc, + lsp::{self, notification::Notification as _}, + Error, LanguageServerId, Result, +}; use anyhow::Context; use log::{error, info}; use serde::{Deserialize, Serialize}; @@ -289,11 +293,10 @@ impl Transport { } // Hack: inject a terminated notification so we trigger code that needs to happen after exit - use lsp_types::notification::Notification as _; let notification = ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification { jsonrpc: None, - method: lsp_types::notification::Exit::METHOD.to_string(), + method: lsp::notification::Exit::METHOD.to_string(), params: jsonrpc::Params::None, })); match transport @@ -338,8 +341,8 @@ impl Transport { // Determine if a message is allowed to be sent early fn is_initialize(payload: &Payload) -> bool { - use lsp_types::{ - notification::{Initialized, Notification}, + use lsp::{ + notification::Initialized, request::{Initialize, Request}, }; match payload { @@ -357,7 +360,7 @@ impl Transport { } fn is_shutdown(payload: &Payload) -> bool { - use lsp_types::request::{Request, Shutdown}; + use lsp::request::{Request, Shutdown}; matches!(payload, Payload::Request { value: jsonrpc::MethodCall { method, .. }, .. } if method == Shutdown::METHOD) } @@ -370,12 +373,11 @@ impl Transport { // server successfully initialized is_pending = false; - use lsp_types::notification::Notification; // Hack: inject an initialized notification so we trigger code that needs to happen after init let notification = ServerMessage::Call(jsonrpc::Call::Notification(jsonrpc::Notification { jsonrpc: None, - method: lsp_types::notification::Initialized::METHOD.to_string(), + method: lsp::notification::Initialized::METHOD.to_string(), params: jsonrpc::Params::None, })); let language_server_name = &transport.name; diff --git a/helix-stdx/Cargo.toml b/helix-stdx/Cargo.toml index 5aef65905..1c0d06ab1 100644 --- a/helix-stdx/Cargo.toml +++ b/helix-stdx/Cargo.toml @@ -20,10 +20,10 @@ regex-cursor = "0.1.4" bitflags = "2.6" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.52", features = ["Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } +windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading"] } [target.'cfg(unix)'.dependencies] rustix = { version = "0.38", features = ["fs"] } [dev-dependencies] -tempfile = "3.10" +tempfile = "3.12" diff --git a/helix-stdx/src/faccess.rs b/helix-stdx/src/faccess.rs index c69571b68..e4c3daf25 100644 --- a/helix-stdx/src/faccess.rs +++ b/helix-stdx/src/faccess.rs @@ -85,7 +85,7 @@ mod imp { #[cfg(windows)] mod imp { - use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, ERROR_SUCCESS, HANDLE, PSID}; + use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, ERROR_SUCCESS, HANDLE}; use windows_sys::Win32::Security::Authorization::{ GetNamedSecurityInfoW, SetNamedSecurityInfoW, SE_FILE_OBJECT, }; @@ -95,7 +95,7 @@ mod imp { SecurityImpersonation, ACCESS_ALLOWED_CALLBACK_ACE, ACL, ACL_SIZE_INFORMATION, DACL_SECURITY_INFORMATION, GENERIC_MAPPING, GROUP_SECURITY_INFORMATION, INHERITED_ACE, LABEL_SECURITY_INFORMATION, OBJECT_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, - PRIVILEGE_SET, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, + PRIVILEGE_SET, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, SID_IDENTIFIER_AUTHORITY, TOKEN_DUPLICATE, TOKEN_QUERY, }; use windows_sys::Win32::Storage::FileSystem::{ @@ -295,21 +295,21 @@ mod imp { let mut privileges_length = std::mem::size_of::() as u32; let mut result = 0; - let mut mapping = GENERIC_MAPPING { + let mapping = GENERIC_MAPPING { GenericRead: FILE_GENERIC_READ, GenericWrite: FILE_GENERIC_WRITE, GenericExecute: FILE_GENERIC_EXECUTE, GenericAll: FILE_ALL_ACCESS, }; - unsafe { MapGenericMask(&mut mode, &mut mapping) }; + unsafe { MapGenericMask(&mut mode, &mapping) }; if unsafe { AccessCheck( *sd.descriptor(), *token.as_handle(), mode, - &mut mapping, + &mapping, &mut privileges, &mut privileges_length, &mut granted_access, @@ -419,7 +419,7 @@ mod imp { pub fn hardlink_count(p: &Path) -> std::io::Result { let file = std::fs::File::open(p)?; - let handle = file.as_raw_handle() as isize; + let handle = file.as_raw_handle(); let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 { diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml index 4887b0a27..5f691d44a 100644 --- a/helix-term/Cargo.toml +++ b/helix-term/Cargo.toml @@ -37,7 +37,7 @@ once_cell = "1.19" tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot"] } tui = { path = "../helix-tui", package = "helix-tui", default-features = false, features = ["crossterm"] } -crossterm = { version = "0.27", features = ["event-stream"] } +crossterm = { version = "0.28", features = ["event-stream"] } signal-hook = "0.3" tokio-stream = "0.1" futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false } @@ -53,7 +53,7 @@ log = "0.4" nucleo.workspace = true ignore = "0.4" # markdown doc rendering -pulldown-cmark = { version = "0.11", default-features = false } +pulldown-cmark = { version = "0.12", default-features = false } # file type detection content_inspector = "0.2.4" thiserror = "1.0" @@ -74,10 +74,10 @@ grep-searcher = "0.1.13" [target.'cfg(not(windows))'.dependencies] # https://github.com/vorner/signal-hook/issues/100 signal-hook-tokio = { version = "0.3", features = ["futures-v0_3"] } -libc = "0.2.155" +libc = "0.2.158" [target.'cfg(target_os = "macos")'.dependencies] -crossterm = { version = "0.27", features = ["event-stream", "use-dev-tty"] } +crossterm = { version = "0.28", features = ["event-stream", "use-dev-tty", "libc"] } [build-dependencies] helix-loader = { path = "../helix-loader" } @@ -85,5 +85,5 @@ helix-loader = { path = "../helix-loader" } [dev-dependencies] smallvec = "1.13" indoc = "2.0.5" -tempfile = "3.10.1" +tempfile = "3.12.0" same-file = "1.0.1" diff --git a/helix-term/build.rs b/helix-term/build.rs index 6bebf00c6..60a646590 100644 --- a/helix-term/build.rs +++ b/helix-term/build.rs @@ -66,18 +66,16 @@ mod windows_rc { .output(); match find_reg_key { - Err(find_reg_key) => { - return Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to run registry query: {}", find_reg_key), - )) - } + Err(find_reg_key) => Err(io::Error::new( + io::ErrorKind::Other, + format!("Failed to run registry query: {}", find_reg_key), + )), Ok(find_reg_key) => { if find_reg_key.status.code().unwrap() != 0 { - return Err(io::Error::new( + Err(io::Error::new( io::ErrorKind::Other, "Can not find Windows SDK", - )); + )) } else { let lines = String::from_utf8(find_reg_key.stdout) .expect("Should be able to parse the output"); diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index 7da96b08a..bd6b5a870 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -35,7 +35,9 @@ use log::{debug, error, info, warn}; use std::io::stdout; use std::{collections::btree_map::Entry, io::stdin, path::Path, sync::Arc}; -use anyhow::{Context, Error}; +#[cfg(not(windows))] +use anyhow::Context; +use anyhow::Error; use crossterm::{event::Event as CrosstermEvent, tty::IsTty}; #[cfg(not(windows))] diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 2c5d2783b..6e037a471 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -176,9 +176,16 @@ where use helix_view::{align_view, Align}; -/// A MappableCommand is either a static command like "jump_view_up" or a Typable command like -/// :format. It causes a side-effect on the state (usually by creating and applying a transaction). -/// Both of these types of commands can be mapped with keybindings in the config.toml. +/// MappableCommands are commands that can be bound to keys, executable in +/// normal, insert or select mode. +/// +/// There are three kinds: +/// +/// * Static: commands usually bound to keys and used for editing, movement, +/// etc., for example `move_char_left`. +/// * Typable: commands executable from command mode, prefixed with a `:`, +/// for example `:write!`. +/// * Macro: a sequence of keys to execute, for example `@miw`. #[derive(Clone)] pub enum MappableCommand { Typable { @@ -191,6 +198,10 @@ pub enum MappableCommand { fun: fn(cx: &mut Context), doc: &'static str, }, + Macro { + name: String, + keys: Vec, + }, } macro_rules! static_commands { @@ -227,6 +238,23 @@ impl MappableCommand { } } Self::Static { fun, .. } => (fun)(cx), + Self::Macro { keys, .. } => { + // Protect against recursive macros. + if cx.editor.macro_replaying.contains(&'@') { + cx.editor.set_error( + "Cannot execute macro because the [@] register is already playing a macro", + ); + return; + } + cx.editor.macro_replaying.push('@'); + let keys = keys.clone(); + cx.callback.push(Box::new(move |compositor, cx| { + for key in keys.into_iter() { + compositor.handle_event(&compositor::Event::Key(key), cx); + } + cx.editor.macro_replaying.pop(); + })); + } } } @@ -234,6 +262,7 @@ impl MappableCommand { match &self { Self::Typable { name, .. } => name, Self::Static { name, .. } => name, + Self::Macro { name, .. } => name, } } @@ -241,6 +270,7 @@ impl MappableCommand { match &self { Self::Typable { doc, .. } => doc, Self::Static { doc, .. } => doc, + Self::Macro { name, .. } => name, } } @@ -269,6 +299,10 @@ impl MappableCommand { move_prev_long_word_start, "Move to start of previous long word", move_next_long_word_end, "Move to end of next long word", move_prev_long_word_end, "Move to end of previous long word", + move_next_sub_word_start, "Move to start of next sub word", + move_prev_sub_word_start, "Move to start of previous sub word", + move_next_sub_word_end, "Move to end of next sub word", + move_prev_sub_word_end, "Move to end of previous sub word", move_parent_node_end, "Move to end of the parent node", move_parent_node_start, "Move to beginning of the parent node", extend_next_word_start, "Extend to start of next word", @@ -279,6 +313,10 @@ impl MappableCommand { extend_prev_long_word_start, "Extend to start of previous long word", extend_next_long_word_end, "Extend to end of next long word", extend_prev_long_word_end, "Extend to end of prev long word", + extend_next_sub_word_start, "Extend to start of next sub word", + extend_prev_sub_word_start, "Extend to start of previous sub word", + extend_next_sub_word_end, "Extend to end of next sub word", + extend_prev_sub_word_end, "Extend to end of prev sub word", extend_parent_node_end, "Extend to end of the parent node", extend_parent_node_start, "Extend to beginning of the parent node", find_till_char, "Move till next occurrence of char", @@ -543,6 +581,11 @@ impl fmt::Debug for MappableCommand { .field(name) .field(args) .finish(), + MappableCommand::Macro { name, keys, .. } => f + .debug_tuple("MappableCommand") + .field(name) + .field(keys) + .finish(), } } } @@ -573,6 +616,11 @@ impl std::str::FromStr for MappableCommand { args, }) .ok_or_else(|| anyhow!("No TypableCommand named '{}'", s)) + } else if let Some(suffix) = s.strip_prefix('@') { + helix_view::input::parse_macro(suffix).map(|keys| Self::Macro { + name: s.to_string(), + keys, + }) } else { MappableCommand::STATIC_COMMAND_LIST .iter() @@ -1126,6 +1174,22 @@ fn move_next_long_word_end(cx: &mut Context) { move_word_impl(cx, movement::move_next_long_word_end) } +fn move_next_sub_word_start(cx: &mut Context) { + move_word_impl(cx, movement::move_next_sub_word_start) +} + +fn move_prev_sub_word_start(cx: &mut Context) { + move_word_impl(cx, movement::move_prev_sub_word_start) +} + +fn move_prev_sub_word_end(cx: &mut Context) { + move_word_impl(cx, movement::move_prev_sub_word_end) +} + +fn move_next_sub_word_end(cx: &mut Context) { + move_word_impl(cx, movement::move_next_sub_word_end) +} + fn goto_para_impl(cx: &mut Context, move_fn: F) where F: Fn(RopeSlice, Range, usize, Movement) -> Range + 'static, @@ -1362,6 +1426,22 @@ fn extend_next_long_word_end(cx: &mut Context) { extend_word_impl(cx, movement::move_next_long_word_end) } +fn extend_next_sub_word_start(cx: &mut Context) { + extend_word_impl(cx, movement::move_next_sub_word_start) +} + +fn extend_prev_sub_word_start(cx: &mut Context) { + extend_word_impl(cx, movement::move_prev_sub_word_start) +} + +fn extend_prev_sub_word_end(cx: &mut Context) { + extend_word_impl(cx, movement::move_prev_sub_word_end) +} + +fn extend_next_sub_word_end(cx: &mut Context) { + extend_word_impl(cx, movement::move_next_sub_word_end) +} + /// Separate branch to find_char designed only for `` char. // // This is necessary because the one document can have different line endings inside. And we @@ -1939,6 +2019,8 @@ fn select_regex(cx: &mut Context) { selection::select_on_matches(text, doc.selection(view.id), ®ex) { doc.set_selection(view.id, selection); + } else { + cx.editor.set_error("nothing selected"); } }, ); @@ -3143,6 +3225,9 @@ pub fn command_palette(cx: &mut Context) { ui::PickerColumn::new("name", |item, _| match item { MappableCommand::Typable { name, .. } => format!(":{name}").into(), MappableCommand::Static { name, .. } => (*name).into(), + MappableCommand::Macro { .. } => { + unreachable!("macros aren't included in the command palette") + } }), ui::PickerColumn::new( "bindings", @@ -4624,6 +4709,8 @@ fn keep_or_remove_selections_impl(cx: &mut Context, remove: bool) { selection::keep_or_remove_matches(text, doc.selection(view.id), ®ex, remove) { doc.set_selection(view.id, selection); + } else { + cx.editor.set_error("no selections remaining"); } }, ) @@ -5051,6 +5138,8 @@ fn jump_forward(cx: &mut Context) { } doc.set_selection(view.id, selection); + // Document we switch to might not have been opened in the view before + doc.ensure_view_init(view.id); view.ensure_cursor_in_view_center(doc, config.scrolloff); }; } @@ -5071,6 +5160,8 @@ fn jump_backward(cx: &mut Context) { } doc.set_selection(view.id, selection); + // Document we switch to might not have been opened in the view before + doc.ensure_view_init(view.id); view.ensure_cursor_in_view_center(doc, config.scrolloff); }; } @@ -5716,27 +5807,24 @@ async fn shell_impl_async( process.wait_with_output().await? }; - if !output.status.success() { - if !output.stderr.is_empty() { - let err = String::from_utf8_lossy(&output.stderr).to_string(); - log::error!("Shell error: {}", err); - bail!("Shell error: {}", err); - } - match output.status.code() { - Some(exit_code) => bail!("Shell command failed: status {}", exit_code), - None => bail!("Shell command failed"), + let output = if !output.status.success() { + if output.stderr.is_empty() { + match output.status.code() { + Some(exit_code) => bail!("Shell command failed: status {}", exit_code), + None => bail!("Shell command failed"), + } } + String::from_utf8_lossy(&output.stderr) + // Prioritize `stderr` output over `stdout` } else if !output.stderr.is_empty() { - log::debug!( - "Command printed to stderr: {}", - String::from_utf8_lossy(&output.stderr).to_string() - ); - } + let stderr = String::from_utf8_lossy(&output.stderr); + log::debug!("Command printed to stderr: {stderr}"); + stderr + } else { + String::from_utf8_lossy(&output.stdout) + }; - let str = std::str::from_utf8(&output.stdout) - .map_err(|_| anyhow!("Process did not output valid UTF-8"))?; - let tendril = Tendril::from(str); - Ok(tendril) + Ok(Tendril::from(output)) } fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) { diff --git a/helix-term/src/commands/lsp.rs b/helix-term/src/commands/lsp.rs index 9194377c4..93ac2a849 100644 --- a/helix-term/src/commands/lsp.rs +++ b/helix-term/src/commands/lsp.rs @@ -34,7 +34,7 @@ use crate::{ use std::{ cmp::Ordering, collections::{BTreeMap, HashSet}, - fmt::Write, + fmt::{Display, Write}, future::Future, path::Path, }; @@ -832,13 +832,13 @@ pub enum ApplyEditErrorKind { // InvalidEdit, } -impl ToString for ApplyEditErrorKind { - fn to_string(&self) -> String { +impl Display for ApplyEditErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ApplyEditErrorKind::DocumentChanged => "document has changed".to_string(), - ApplyEditErrorKind::FileNotFound => "file not found".to_string(), - ApplyEditErrorKind::UnknownURISchema => "URI schema not supported".to_string(), - ApplyEditErrorKind::IoError(err) => err.to_string(), + ApplyEditErrorKind::DocumentChanged => f.write_str("document has changed"), + ApplyEditErrorKind::FileNotFound => f.write_str("file not found"), + ApplyEditErrorKind::UnknownURISchema => f.write_str("URI schema not supported"), + ApplyEditErrorKind::IoError(err) => f.write_str(&format!("{err}")), } } } @@ -1360,7 +1360,7 @@ fn compute_inlay_hints_for_view( // Most language servers will already send them sorted but ensure this is the case to // avoid errors on our end. - hints.sort_unstable_by_key(|inlay_hint| inlay_hint.position); + hints.sort_by_key(|inlay_hint| inlay_hint.position); let mut padding_before_inlay_hints = Vec::new(); let mut type_inlay_hints = Vec::new(); diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index 720d32ac8..7ad0369fc 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -2300,7 +2300,7 @@ fn run_shell_command( move |editor: &mut Editor, compositor: &mut Compositor| { if !output.is_empty() { let contents = ui::Markdown::new( - format!("```sh\n{}\n```", output), + format!("```sh\n{}\n```", output.trim_end()), editor.syn_loader.clone(), ); let popup = Popup::new("shell", contents).position(Some( @@ -2308,7 +2308,7 @@ fn run_shell_command( )); compositor.replace_or_push("shell", popup); } - editor.set_status("Command succeeded"); + editor.set_status("Command run"); }, )); Ok(call) @@ -2498,7 +2498,7 @@ fn read(cx: &mut compositor::Context, args: &[Cow], event: PromptEvent) -> ensure!(!args.is_empty(), "file name is expected"); ensure!(args.len() == 1, "only the file name is expected"); - let filename = args.get(0).unwrap(); + let filename = args.first().unwrap(); let path = PathBuf::from(filename.to_string()); ensure!( path.exists() && path.is_file(), diff --git a/helix-term/src/keymap.rs b/helix-term/src/keymap.rs index 975274ed1..020ecaf40 100644 --- a/helix-term/src/keymap.rs +++ b/helix-term/src/keymap.rs @@ -177,6 +177,19 @@ impl<'de> serde::de::Visitor<'de> for KeyTrieVisitor { .map_err(serde::de::Error::custom)?, ) } + + // Prevent macro keybindings from being used in command sequences. + // This is meant to be a temporary restriction pending a larger + // refactor of how command sequences are executed. + if commands + .iter() + .any(|cmd| matches!(cmd, MappableCommand::Macro { .. })) + { + return Err(serde::de::Error::custom( + "macro keybindings may not be used in command sequences", + )); + } + Ok(KeyTrie::Sequence(commands)) } @@ -199,6 +212,7 @@ impl KeyTrie { // recursively visit all nodes in keymap fn map_node(cmd_map: &mut ReverseKeymap, node: &KeyTrie, keys: &mut Vec) { match node { + KeyTrie::MappableCommand(MappableCommand::Macro { .. }) => {} KeyTrie::MappableCommand(cmd) => { let name = cmd.name(); if name != "no_op" { diff --git a/helix-term/src/main.rs b/helix-term/src/main.rs index fbe1a8460..a3a27a076 100644 --- a/helix-term/src/main.rs +++ b/helix-term/src/main.rs @@ -117,10 +117,9 @@ FLAGS: setup_logging(args.verbosity).context("failed to initialize logging")?; // Before setting the working directory, resolve all the paths in args.files - for (path, _) in args.files.iter_mut() { - *path = helix_stdx::path::canonicalize(&path); + for (path, _) in &mut args.files { + *path = helix_stdx::path::canonicalize(&*path); } - // NOTE: Set the working directory early so the correct configuration is loaded. Be aware that // Application::new() depends on this logic so it must be updated if this changes. if let Some(path) = &args.working_directory { diff --git a/helix-term/src/ui/picker.rs b/helix-term/src/ui/picker.rs index 118dafa77..82fe96891 100644 --- a/helix-term/src/ui/picker.rs +++ b/helix-term/src/ui/picker.rs @@ -799,21 +799,25 @@ impl Picker { if self.columns.len() > 1 { let active_column = self.query.active_column(self.prompt.position()); let header_style = cx.editor.theme.get("ui.picker.header"); + let header_column_style = cx.editor.theme.get("ui.picker.header.column"); - table = table.header(Row::new(self.columns.iter().map(|column| { - if column.hidden { - Cell::default() - } else { - let style = if active_column.is_some_and(|name| Arc::ptr_eq(name, &column.name)) - { - cx.editor.theme.get("ui.picker.header.active") + table = table.header( + Row::new(self.columns.iter().map(|column| { + if column.hidden { + Cell::default() } else { - header_style - }; + let style = + if active_column.is_some_and(|name| Arc::ptr_eq(name, &column.name)) { + cx.editor.theme.get("ui.picker.header.column.active") + } else { + header_column_style + }; - Cell::from(Span::styled(Cow::from(&*column.name), style)) - } - }))); + Cell::from(Span::styled(Cow::from(&*column.name), style)) + } + })) + .style(header_style), + ); } use tui::widgets::TableState; diff --git a/helix-term/src/ui/picker/query.rs b/helix-term/src/ui/picker/query.rs index e433a11fa..005ddee42 100644 --- a/helix-term/src/ui/picker/query.rs +++ b/helix-term/src/ui/picker/query.rs @@ -58,11 +58,16 @@ impl PickerQuery { () => { let key = field.take().unwrap_or(primary_field); + // Trims one space from the end, enabling leading and trailing + // spaces in search patterns, while also retaining spaces as separators + // between column filters. + let pat = text.strip_suffix(' ').unwrap_or(&text); + if let Some(pattern) = fields.get_mut(key) { pattern.push(' '); - pattern.push_str(text.trim()); + pattern.push_str(pat); } else { - fields.insert(key.clone(), text.trim().to_string()); + fields.insert(key.clone(), pat.to_string()); } text.clear(); }; diff --git a/helix-tui/Cargo.toml b/helix-tui/Cargo.toml index 2bdb494f6..ac56c7242 100644 --- a/helix-tui/Cargo.toml +++ b/helix-tui/Cargo.toml @@ -21,7 +21,7 @@ helix-core = { path = "../helix-core" } bitflags = "2.6" cassowary = "0.3" unicode-segmentation = "1.11" -crossterm = { version = "0.27", optional = true } +crossterm = { version = "0.28", optional = true } termini = "1.0" serde = { version = "1", "optional" = true, features = ["derive"]} once_cell = "1.19" diff --git a/helix-tui/src/backend/crossterm.rs b/helix-tui/src/backend/crossterm.rs index 0e60e3866..e8947ee08 100644 --- a/helix-tui/src/backend/crossterm.rs +++ b/helix-tui/src/backend/crossterm.rs @@ -8,8 +8,8 @@ use crossterm::{ }, execute, queue, style::{ - Attribute as CAttribute, Color as CColor, Print, SetAttribute, SetBackgroundColor, - SetForegroundColor, + Attribute as CAttribute, Color as CColor, Colors, Print, SetAttribute, SetBackgroundColor, + SetColors, SetForegroundColor, }, terminal::{self, Clear, ClearType}, Command, @@ -260,14 +260,12 @@ where diff.queue(&mut self.buffer)?; modifier = cell.modifier; } - if cell.fg != fg { - let color = CColor::from(cell.fg); - queue!(self.buffer, SetForegroundColor(color))?; + if cell.fg != fg || cell.bg != bg { + queue!( + self.buffer, + SetColors(Colors::new(cell.fg.into(), cell.bg.into())) + )?; fg = cell.fg; - } - if cell.bg != bg { - let color = CColor::from(cell.bg); - queue!(self.buffer, SetBackgroundColor(color))?; bg = cell.bg; } diff --git a/helix-tui/src/text.rs b/helix-tui/src/text.rs index 076766dd6..a5e8a68af 100644 --- a/helix-tui/src/text.rs +++ b/helix-tui/src/text.rs @@ -5,7 +5,7 @@ //! - A single line string where all graphemes have the same style is represented by a [`Span`]. //! - A single line string where each grapheme may have its own style is represented by [`Spans`]. //! - A multiple line string where each grapheme may have its own style is represented by a -//! [`Text`]. +//! [`Text`]. //! //! These types form a hierarchy: [`Spans`] is a collection of [`Span`] and each line of [`Text`] //! is a [`Spans`]. diff --git a/helix-vcs/Cargo.toml b/helix-vcs/Cargo.toml index bc8c5b7ba..245fdb8dc 100644 --- a/helix-vcs/Cargo.toml +++ b/helix-vcs/Cargo.toml @@ -19,8 +19,8 @@ tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "p parking_lot = "0.12" arc-swap = { version = "1.7.1" } -gix = { version = "0.63.0", features = ["attributes", "status"], default-features = false, optional = true } -imara-diff = "0.1.6" +gix = { version = "0.66.0", features = ["attributes", "status"], default-features = false, optional = true } +imara-diff = "0.1.7" anyhow = "1" log = "0.4" @@ -29,4 +29,4 @@ log = "0.4" git = ["gix"] [dev-dependencies] -tempfile = "3.10" +tempfile = "3.12" diff --git a/helix-vcs/src/diff.rs b/helix-vcs/src/diff.rs index 634b179b4..e49e171dd 100644 --- a/helix-vcs/src/diff.rs +++ b/helix-vcs/src/diff.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use helix_core::Rope; use helix_event::RenderLockGuard; use imara_diff::Algorithm; -use parking_lot::{Mutex, MutexGuard}; +use parking_lot::{RwLock, RwLockReadGuard}; use tokio::sync::mpsc::{unbounded_channel, UnboundedSender}; use tokio::task::JoinHandle; use tokio::time::Instant; @@ -37,7 +37,7 @@ struct DiffInner { #[derive(Clone, Debug)] pub struct DiffHandle { channel: UnboundedSender, - diff: Arc>, + diff: Arc>, inverted: bool, } @@ -48,7 +48,7 @@ impl DiffHandle { fn new_with_handle(diff_base: Rope, doc: Rope) -> (DiffHandle, JoinHandle<()>) { let (sender, receiver) = unbounded_channel(); - let diff: Arc> = Arc::default(); + let diff: Arc> = Arc::default(); let worker = DiffWorker { channel: receiver, diff: diff.clone(), @@ -70,7 +70,7 @@ impl DiffHandle { pub fn load(&self) -> Diff { Diff { - diff: self.diff.lock(), + diff: self.diff.read(), inverted: self.inverted, } } @@ -164,7 +164,7 @@ impl Hunk { /// non-overlapping order #[derive(Debug)] pub struct Diff<'a> { - diff: MutexGuard<'a, DiffInner>, + diff: RwLockReadGuard<'a, DiffInner>, inverted: bool, } diff --git a/helix-vcs/src/diff/worker.rs b/helix-vcs/src/diff/worker.rs index 3a9b6462c..578d8b8e7 100644 --- a/helix-vcs/src/diff/worker.rs +++ b/helix-vcs/src/diff/worker.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use helix_core::{Rope, RopeSlice}; use imara_diff::intern::InternedInput; -use parking_lot::Mutex; +use parking_lot::RwLock; use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::Notify; use tokio::time::{timeout, timeout_at, Duration}; @@ -21,7 +21,7 @@ mod test; pub(super) struct DiffWorker { pub channel: UnboundedReceiver, - pub diff: Arc>, + pub diff: Arc>, pub new_hunks: Vec, pub diff_finished_notify: Arc, } @@ -73,7 +73,7 @@ impl DiffWorker { /// `self.new_hunks` is always empty after this function runs. /// To improve performance this function tries to reuse the allocation of the old diff previously stored in `self.line_diffs` fn apply_hunks(&mut self, diff_base: Rope, doc: Rope) { - let mut diff = self.diff.lock(); + let mut diff = self.diff.write(); diff.diff_base = diff_base; diff.doc = doc; swap(&mut diff.hunks, &mut self.new_hunks); diff --git a/helix-vcs/src/diff/worker/test.rs b/helix-vcs/src/diff/worker/test.rs index a6cc89007..ab410bd82 100644 --- a/helix-vcs/src/diff/worker/test.rs +++ b/helix-vcs/src/diff/worker/test.rs @@ -12,7 +12,7 @@ impl DiffHandle { // dropping the channel terminates the task drop(self.channel); handle.await.unwrap(); - let diff = diff.lock(); + let diff = diff.read(); Vec::clone(&diff.hunks) } } diff --git a/helix-view/Cargo.toml b/helix-view/Cargo.toml index 81729af09..ddfa9f7e4 100644 --- a/helix-view/Cargo.toml +++ b/helix-view/Cargo.toml @@ -26,9 +26,9 @@ helix-vcs = { path = "../helix-vcs" } bitflags = "2.6" anyhow = "1" -crossterm = { version = "0.27", optional = true } +crossterm = { version = "0.28", optional = true } -tempfile = "3.9" +tempfile = "3.12" # Conversion traits once_cell = "1.19" diff --git a/helix-view/src/document.rs b/helix-view/src/document.rs index 885f33e8a..91ec27874 100644 --- a/helix-view/src/document.rs +++ b/helix-view/src/document.rs @@ -1080,22 +1080,21 @@ impl Document { } pub fn pickup_last_saved_time(&mut self) { - self.last_saved_time = match self.path.as_mut().unwrap().metadata() { - Ok(metadata) => match metadata.modified() { - Ok(mtime) => mtime, - Err(_) => { - log::error!( - "Use a system time instead of fs' mtime not supported on this platform" - ); + self.last_saved_time = match self.path() { + Some(path) => match path.metadata() { + Ok(metadata) => match metadata.modified() { + Ok(mtime) => mtime, + Err(err) => { + log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err); + SystemTime::now() + } + }, + Err(err) => { + log::debug!("Could not fetch file system's mtime, falling back to current system time: {}", err); SystemTime::now() } }, - Err(e) => { - log::error!( - "Use a system time instead of fs' mtime: failed to file's metadata: {e}" - ); - SystemTime::now() - } + None => SystemTime::now(), }; } @@ -1246,7 +1245,7 @@ impl Document { /// Initializes a new selection and view_data for the given view /// if it does not already have them. pub fn ensure_view_init(&mut self, view_id: ViewId) { - if self.selections.get(&view_id).is_none() { + if !self.selections.contains_key(&view_id) { self.reset_selection(view_id); } @@ -1921,12 +1920,15 @@ impl Document { return None; }; - let severity = diagnostic.severity.map(|severity| match severity { - lsp::DiagnosticSeverity::ERROR => Error, - lsp::DiagnosticSeverity::WARNING => Warning, - lsp::DiagnosticSeverity::INFORMATION => Info, - lsp::DiagnosticSeverity::HINT => Hint, - severity => unreachable!("unrecognized diagnostic severity: {:?}", severity), + let severity = diagnostic.severity.and_then(|severity| match severity { + lsp::DiagnosticSeverity::ERROR => Some(Error), + lsp::DiagnosticSeverity::WARNING => Some(Warning), + lsp::DiagnosticSeverity::INFORMATION => Some(Info), + lsp::DiagnosticSeverity::HINT => Some(Hint), + severity => { + log::error!("unrecognized diagnostic severity: {:?}", severity); + None + } }); if let Some(lang_conf) = language_config { diff --git a/helix-view/src/editor.rs b/helix-view/src/editor.rs index 4249db1d5..1708b3b4e 100644 --- a/helix-view/src/editor.rs +++ b/helix-view/src/editor.rs @@ -1376,6 +1376,11 @@ impl Editor { } let is_dir = new_path.is_dir(); for ls in self.language_servers.iter_clients() { + // A new language server might have been started in `set_doc_path` and won't + // be initialized yet. Skip the `did_rename` notification for this server. + if !ls.is_initialized() { + continue; + } if let Some(notification) = ls.did_rename(old_path, &new_path, is_dir) { tokio::spawn(notification); }; diff --git a/helix-view/src/handlers/dap.rs b/helix-view/src/handlers/dap.rs index a5fa0c29c..81766dd59 100644 --- a/helix-view/src/handlers/dap.rs +++ b/helix-view/src/handlers/dap.rs @@ -37,7 +37,7 @@ pub async fn select_thread_id(editor: &mut Editor, thread_id: ThreadId, force: b debugger.thread_id = Some(thread_id); fetch_stack_trace(debugger, thread_id).await; - let frame = debugger.stack_frames[&thread_id].get(0).cloned(); + let frame = debugger.stack_frames[&thread_id].first().cloned(); if let Some(frame) = &frame { jump_to_stack_frame(editor, frame); } diff --git a/helix-view/src/handlers/lsp.rs b/helix-view/src/handlers/lsp.rs index d817a4235..6aff2e50c 100644 --- a/helix-view/src/handlers/lsp.rs +++ b/helix-view/src/handlers/lsp.rs @@ -1,3 +1,5 @@ +use std::fmt::Display; + use crate::editor::Action; use crate::Editor; use crate::{DocumentId, ViewId}; @@ -73,13 +75,13 @@ impl From for ApplyEditErrorKind { } } -impl ToString for ApplyEditErrorKind { - fn to_string(&self) -> String { +impl Display for ApplyEditErrorKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ApplyEditErrorKind::DocumentChanged => "document has changed".to_string(), - ApplyEditErrorKind::FileNotFound => "file not found".to_string(), - ApplyEditErrorKind::InvalidUrl(err) => err.to_string(), - ApplyEditErrorKind::IoError(err) => err.to_string(), + ApplyEditErrorKind::DocumentChanged => f.write_str("document has changed"), + ApplyEditErrorKind::FileNotFound => f.write_str("file not found"), + ApplyEditErrorKind::InvalidUrl(err) => f.write_str(&format!("{err}")), + ApplyEditErrorKind::IoError(err) => f.write_str(&format!("{err}")), } } } diff --git a/languages.toml b/languages.toml index d51a18216..cc437f78c 100644 --- a/languages.toml +++ b/languages.toml @@ -44,6 +44,7 @@ haskell-language-server = { command = "haskell-language-server-wrapper", args = idris2-lsp = { command = "idris2-lsp" } intelephense = { command = "intelephense", args = ["--stdio"] } jdtls = { command = "jdtls" } +jq-lsp = { command = "jq-lsp" } jsonnet-language-server = { command = "jsonnet-language-server", args= ["-t", "--lint"] } julia = { command = "julia", timeout = 60, args = [ "--startup-file=no", "--history-file=no", "--quiet", "-e", "using LanguageServer; runserver()", ] } koka = { command = "koka", args = ["--language-server", "--lsstdio"] } @@ -54,11 +55,13 @@ markdoc-ls = { command = "markdoc-ls", args = ["--stdio"] } markdown-oxide = { command = "markdown-oxide" } marksman = { command = "marksman", args = ["server"] } metals = { command = "metals", config = { "isHttpEnabled" = true, metals = { inlayHints = { typeParameters = {enable = true} , hintsInPatternMatch = {enable = true} } } } } +mesonlsp = { command = "mesonlsp", args = ["--lsp"] } mint = { command = "mint", args = ["ls"] } mojo-lsp = { command = "mojo-lsp-server" } nil = { command = "nil" } nimlangserver = { command = "nimlangserver" } nimlsp = { command = "nimlsp" } +nixd = { command = "nixd" } nls = { command = "nls" } nu-lsp = { command = "nu", args = [ "--lsp" ] } ocamllsp = { command = "ocamllsp" } @@ -93,6 +96,7 @@ taplo = { command = "taplo", args = ["lsp", "stdio"] } templ = { command = "templ", args = ["lsp"] } terraform-ls = { command = "terraform-ls", args = ["serve"] } texlab = { command = "texlab" } +typespec = { command = "tsp-server", args = ["--stdio"] } vala-language-server = { command = "vala-language-server" } vhdl_ls = { command = "vhdl_ls", args = [] } vlang-language-server = { command = "v-analyzer" } @@ -766,6 +770,23 @@ indent = { tab-width = 2, unit = " " } name = "typescript" source = { git = "https://github.com/tree-sitter/tree-sitter-typescript", rev = "b1bf4825d9eaa0f3bdeb1e52f099533328acfbdf", subpath = "typescript" } +[[language]] +name = "typespec" +scope = "source.typespec" +injection-regex = "(tsp|typespec)" +language-id = "typespec" +file-types = ["tsp"] +roots = ["tspconfig.yaml"] +auto-format = true +comment-token = "//" +block-comment-tokens = { start = "/*", end = "*/" } +language-servers = ["typespec"] +indent = { tab-width = 2, unit = " " } + +[[grammar]] +name = "typespec" +source = { git = "https://github.com/happenslol/tree-sitter-typespec", rev = "0ee05546d73d8eb64635ed8125de6f35c77759fe" } + [[language]] name = "tsx" scope = "source.tsx" @@ -813,7 +834,7 @@ source = { git = "https://github.com/serenadeai/tree-sitter-scss", rev = "c478c6 name = "html" scope = "text.html.basic" injection-regex = "html" -file-types = ["html", "htm", "shtml", "xhtml", "xht", "jsp", "asp", "aspx", "jshtm", "volt", "rhtml"] +file-types = ["html", "htm", "shtml", "xhtml", "xht", "jsp", "asp", "aspx", "jshtm", "volt", "rhtml", "cshtml"] block-comment-tokens = { start = "" } language-servers = [ "vscode-html-language-server" ] auto-format = true @@ -866,7 +887,7 @@ injection-regex = "nix" file-types = ["nix"] shebangs = [] comment-token = "#" -language-servers = [ "nil" ] +language-servers = [ "nil", "nixd" ] indent = { tab-width = 2, unit = " " } [[grammar]] @@ -948,6 +969,8 @@ file-types = [ "tcshrc", "bashrc_Apple_Terminal", "zshrc_Apple_Terminal", + { glob = "i3/config" }, + { glob = "sway/config" }, { glob = "tmux.conf" }, { glob = ".bash_history" }, { glob = ".bash_login" }, @@ -1855,7 +1878,7 @@ auto-format = true [[grammar]] name = "gleam" -source = { git = "https://github.com/gleam-lang/tree-sitter-gleam", rev = "bcf9c45b56cbe46e9dac5eee0aee75df270000ac" } +source = { git = "https://github.com/gleam-lang/tree-sitter-gleam", rev = "426e67087fd62be5f4533581b5916b2cf010fb5b" } [[language]] name = "ron" @@ -1995,12 +2018,12 @@ shebangs = [] roots = ["project.godot"] auto-format = true formatter = { command = "gdformat", args = ["-"] } -comment-token = "#" +comment-tokens = ["#", "##"] indent = { tab-width = 4, unit = "\t" } [[grammar]] name = "gdscript" -source = { git = "https://github.com/PrestonKnopp/tree-sitter-gdscript", rev = "a4b57cc3bcbfc24550e858159647e9238e7ad1ac" } +source = { git = "https://github.com/PrestonKnopp/tree-sitter-gdscript", rev = "1f1e782fe2600f50ae57b53876505b8282388d77" } [[language]] name = "godot-resource" @@ -2015,7 +2038,7 @@ indent = { tab-width = 4, unit = "\t" } [[grammar]] name = "godot-resource" -source = { git = "https://github.com/PrestonKnopp/tree-sitter-godot-resource", rev = "b6ef0768711086a86b3297056f9ffb5cc1d77b4a" } +source = { git = "https://github.com/PrestonKnopp/tree-sitter-godot-resource", rev = "2ffb90de47417018651fc3b970e5f6b67214dc9d" } [[language]] name = "nu" @@ -2143,6 +2166,7 @@ injection-regex = "meson" file-types = [{ glob = "meson.build" }, { glob = "meson.options" }, { glob = "meson_options.txt" }] comment-token = "#" indent = { tab-width = 2, unit = " " } +language-servers = ["mesonlsp"] [[grammar]] name = "meson" @@ -3082,7 +3106,7 @@ indent = { tab-width = 4, unit = " " } [[grammar]] name = "just" -source = { git = "https://github.com/IndianBoy42/tree-sitter-just", rev = "379fbe36d1e441bc9414ea050ad0c85c9d6935ea" } +source = { git = "https://github.com/poliorcetics/tree-sitter-just", rev = "f58a8fd869035ac4653081401e6c2030251240ab" } [[language]] name = "gn" @@ -3139,7 +3163,7 @@ language-servers = ["fsharp-ls"] [[grammar]] name = "fsharp" -source = { git = "https://github.com/kaashyapan/tree-sitter-fsharp", rev = "18da392fd9bd5e79f357abcce13f61f3a15e3951" } +source = { git = "https://github.com/ionide/tree-sitter-fsharp", rev = "996ea9982bd4e490029f84682016b6793940113b" } [[language]] name = "t32" @@ -3216,6 +3240,19 @@ text-width = 72 name = "jjdescription" source = { git = "https://github.com/kareigu/tree-sitter-jjdescription", rev = "2ddec6cad07b366aee276a608e1daa2c29d3caf2" } +[[language]] +name = "jq" +scope = "source.jq" +injection-regex = "jq" +file-types = ["jq"] +comment-token = "#" +language-servers = ["jq-lsp"] +indent = { tab-width = 2, unit = " " } + +[[grammar]] +name = "jq" +source = { git = "https://github.com/flurie/tree-sitter-jq", rev = "13990f530e8e6709b7978503da9bc8701d366791" } + [[grammar]] name = "wren" source = { git = "https://git.sr.ht/~jummit/tree-sitter-wren", rev = "6748694be32f11e7ec6b5faeb1b48ca6156d4e06" } @@ -3490,7 +3527,7 @@ name = "tcl" scope = "source.tcl" injection-regex = "tcl" file-types = [ "tcl" ] -shebangs = [ "tclish", "jimsh", "wish" ] +shebangs = [ "tclsh", "tclish", "jimsh", "wish" ] comment-token = '#' [[grammar]] @@ -3726,3 +3763,26 @@ grammar = "typescript" "{" = "}" "(" = ")" '"' = '"' + +[[language]] +name = "gherkin" +scope = "source.feature" +file-types = ["feature"] +comment-token = "#" +indent = { tab-width = 2, unit = " " } + +[[grammar]] +name = "gherkin" +source = { git = "https://github.com/SamyAB/tree-sitter-gherkin", rev = "43873ee8de16476635b48d52c46f5b6407cb5c09" } + +[[language]] +name = "thrift" +scope = "source.thrift" +file-types = ["thrift"] +comment-token = "//" +block-comment-tokens = { start = "/*", end = "*/" } +indent = { tab-width = 2, unit = " " } + +[[grammar]] +name = "thrift" +source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-thrift" , rev = "68fd0d80943a828d9e6f49c58a74be1e9ca142cf" } \ No newline at end of file diff --git a/runtime/queries/docker-compose/textobjects.scm b/runtime/queries/docker-compose/textobjects.scm new file mode 100644 index 000000000..4ba254e82 --- /dev/null +++ b/runtime/queries/docker-compose/textobjects.scm @@ -0,0 +1 @@ +; inherits: yaml diff --git a/runtime/queries/dockerfile/textobjects.scm b/runtime/queries/dockerfile/textobjects.scm new file mode 100644 index 000000000..975fd4c5e --- /dev/null +++ b/runtime/queries/dockerfile/textobjects.scm @@ -0,0 +1,4 @@ +(comment) @comment.inside + +(comment)+ @comment.around + diff --git a/runtime/queries/env/textobjects.scm b/runtime/queries/env/textobjects.scm new file mode 100644 index 000000000..4bdbf5ec7 --- /dev/null +++ b/runtime/queries/env/textobjects.scm @@ -0,0 +1,6 @@ +(comment) @comment.inside + +(comment)+ @comment.around + +(variable_assignment + (_) @entry.inside) @entry.around diff --git a/runtime/queries/fsharp/highlights.scm b/runtime/queries/fsharp/highlights.scm index 68b70ba7d..43905c882 100644 --- a/runtime/queries/fsharp/highlights.scm +++ b/runtime/queries/fsharp/highlights.scm @@ -1,16 +1,176 @@ ;; ---------------------------------------------------------------------------- ;; Literals and comments -[ - (line_comment) - (block_comment) - (block_comment_content) -] @comment +(line_comment) @comment.line + +(block_comment) @comment.block + +(xml_doc) @comment.block.documentation + +(const + [ + (_) @constant + (unit) @constant.builtin + ]) +(primary_constr_args (_) @variable.parameter) + +((identifier_pattern (long_identifier (identifier) @special)) + (#match? @special "^\_.*")) + +((long_identifier + (identifier)+ + . + (identifier) @variable.other.member)) ;; ---------------------------------------------------------------------------- ;; Punctuation +(wildcard_pattern) @string.special + +(type_name type_name: (_) @type) + +[ + (type) + (atomic_type) +] @type + +(member_signature + . + (identifier) @function.method + (curried_spec + (arguments_spec + "*"* @operator + (argument_spec + (argument_name_spec + "?"? @special + name: (_) @variable.parameter))))) + +(union_type_case) @constant + +(rules + (rule + pattern: (_) @constant + block: (_))) + +(identifier_pattern + . + (_) @constant + . + (_) @variable) + +(fsi_directive_decl . (string) @namespace) + +(import_decl . (_) @namespace) +(named_module + name: (_) @namespace) +(namespace + name: (_) @namespace) +(module_defn + . + (_) @namespace) + +(ce_expression + . + (_) @function.macro) + +(field_initializer + field: (_) @variable.other.member) + +(record_fields + (record_field + . + (identifier) @variable.other.member)) + +(dot_expression + base: (_) @namespace + field: (_) @variable.other.member) + +(value_declaration_left . (_) @variable) + +(function_declaration_left + . (_) @function + [ + (argument_patterns) + (argument_patterns (long_identifier (identifier))) + ] @variable.parameter) + +(member_defn + (method_or_prop_defn + [ + (property_or_ident) @function + (property_or_ident + instance: (identifier) @variable.builtin + method: (identifier) @function.method) + ] + args: (_)* @variable.parameter)) + +(application_expression + . + [ + (long_identifier_or_op [ + (long_identifier (identifier)* (identifier) @function) + (identifier) @function + ]) + (typed_expression . (long_identifier_or_op (long_identifier (identifier)* . (identifier) @function.call))) + (dot_expression base: (_) @variable.other.member field: (_) @function) + ] @function) + +((infix_expression + . + (_) + . + (infix_op) @operator + . + (_) @function + ) + (#eq? @operator "|>") + ) + +((infix_expression + . + (_) @function + . + (infix_op) @operator + . + (_) + ) + (#eq? @operator "<|") + ) + +[ + (xint) + (int) + (int16) + (uint16) + (int32) + (uint32) + (int64) + (uint64) + (nativeint) + (unativeint) +] @constant.numeric.integer + +[ + (ieee32) + (ieee64) + (float) + (decimal) +] @constant.numeric.float + +(bool) @constant.builtin.boolean + +([ + (string) + (triple_quoted_string) + (verbatim_string) + (char) +] @string) + +(compiler_directive_decl) @keyword.directive + +(attribute) @attribute + [ "(" ")" @@ -20,31 +180,40 @@ "]" "[|" "|]" + "{|" + "|}" "[<" ">]" ] @punctuation.bracket +(format_string_eval + [ + "{" + "}" + ] @punctuation.special) + [ - "," + "," ";" ] @punctuation.delimiter [ - "|" + "|" "=" ">" "<" "-" "~" + "->" + "<-" + "&&" + "||" + ":>" + ":?>" (infix_op) (prefix_op) - (symbolic_op) ] @operator - - -(attribute) @attribute - [ "if" "then" @@ -53,22 +222,29 @@ "when" "match" "match!" +] @keyword.control.conditional + +[ "and" "or" - "&&" - "||" - "then" -] @keyword.control.conditional + "not" + "upcast" + "downcast" +] @keyword.operator [ "return" "return!" + "yield" + "yield!" ] @keyword.control.return [ "for" "while" -] @keyword.control.return + "downto" + "to" +] @keyword.control.repeat [ @@ -82,115 +258,93 @@ "delegate" "static" "inline" - "internal" "mutable" "override" - "private" - "public" "rec" + "global" + (access_modifier) ] @keyword.storage.modifier [ - "enum" "let" "let!" + "use" + "use!" "member" - "module" - "namespace" +] @keyword.function + +[ + "enum" "type" -] @keyword.storage + "inherit" + "interface" +] @keyword.storage.type + +(try_expression + [ + "try" + "with" + "finally" + ] @keyword.control.exception) + +((identifier) @keyword.control.exception + (#any-of? @keyword.control.exception "failwith" "failwithf" "raise" "reraise")) [ "as" "assert" "begin" + "end" + "done" "default" + "in" "do" "do!" - "done" - "downcast" - "downto" - "end" "event" "field" - "finally" "fun" "function" "get" - "global" - "inherit" - "interface" + "set" "lazy" "new" - "not" - "null" "of" "param" "property" - "set" "struct" - "try" - "upcast" - "use" - "use!" "val" + "module" + "namespace" "with" - "yield" - "yield!" ] @keyword [ - "true" - "false" - "unit" - ] @constant.builtin - -[ - (type) - (const) -] @constant - -[ - (union_type_case) - (rules (rule (identifier_pattern))) -] @type.enum - -(fsi_directive_decl (string) @namespace) - -[ - (import_decl (long_identifier)) - (named_module (long_identifier)) - (namespace (long_identifier)) - (named_module - name: (long_identifier) ) - (namespace - name: (long_identifier) ) -] @namespace + "null" +] @constant.builtin +(match_expression "with" @keyword.control.conditional) -(dot_expression - base: (long_identifier_or_op) @variable.other.member - field: (long_identifier_or_op) @function) +((type + (long_identifier (identifier) @type.builtin)) + (#any-of? @type.builtin "bool" "byte" "sbyte" "int16" "uint16" "int" "uint" "int64" "uint64" "nativeint" "unativeint" "decimal" "float" "double" "float32" "single" "char" "string" "unit")) -[ - ;;(value_declaration_left (identifier_pattern) ) - (function_declaration_left (identifier) ) - (call_expression (long_identifier_or_op (long_identifier))) - ;;(application_expression (long_identifier_or_op (long_identifier))) -] @function +(preproc_if + [ + "#if" @keyword.directive + "#endif" @keyword.directive + ] + condition: (_)? @keyword.directive) -[ - (string) - (triple_quoted_string) -] @string +(preproc_else + "#else" @keyword.directive) -[ - (int) - (int16) - (int32) - (int64) - (float) - (decimal) -] @constant.numeric +((long_identifier + (identifier)+ @namespace + . + (identifier))) +(long_identifier_or_op + (op_identifier) @operator) +((identifier) @namespace + (#any-of? @namespace "Array" "Async" "Directory" "File" "List" "Option" "Path" "Map" "Set" "Lazy" "Seq" "Task" "String" "Result" )) diff --git a/runtime/queries/fsharp/injections.scm b/runtime/queries/fsharp/injections.scm new file mode 100644 index 000000000..54b89c5aa --- /dev/null +++ b/runtime/queries/fsharp/injections.scm @@ -0,0 +1,8 @@ +([ + (line_comment) + (block_comment_content) +] @injection.content + (#set! injection.language "comment")) + +((xml_doc (xml_doc_content) @injection.content) + (#set! injection.language "xml")) diff --git a/runtime/queries/fsharp/locals.scm b/runtime/queries/fsharp/locals.scm index aa36755ef..db2291f26 100644 --- a/runtime/queries/fsharp/locals.scm +++ b/runtime/queries/fsharp/locals.scm @@ -1,25 +1,32 @@ -; Scopes -;------- +(identifier) @local.reference [ - (ce_expression) - (module_defn) - (for_expression) - (do_expression) - (fun_expression) - (function_expression) - (try_expression) - (match_expression) - (elif_expression) - (if_expression) + (namespace) + (named_module) + (function_or_value_defn) ] @local.scope -; Definitions -;------------ - -(function_or_value_defn) @local.definition +(value_declaration_left + . + [ + (_ (identifier) @local.definition) + (_ (_ (identifier) @local.definition)) + (_ (_ (_ (identifier) @local.definition))) + (_ (_ (_ (_ (identifier) @local.definition)))) + (_ (_ (_ (_ (_ (identifier) @local.definition))))) + (_ (_ (_ (_ (_ (_ (identifier) @local.definition)))))) + ]) -; References -;----------- - -(identifier) @local.reference +(function_declaration_left + . + ((_) @local.definition) + ((argument_patterns + [ + (_ (identifier) @local.definition) + (_ (_ (identifier) @local.definition)) + (_ (_ (_ (identifier) @local.definition))) + (_ (_ (_ (_ (identifier) @local.definition)))) + (_ (_ (_ (_ (_ (identifier) @local.definition))))) + (_ (_ (_ (_ (_ (_ (identifier) @local.definition)))))) + ]) + )) diff --git a/runtime/queries/gdscript/highlights.scm b/runtime/queries/gdscript/highlights.scm index 37aa3d62f..fee67dc9c 100644 --- a/runtime/queries/gdscript/highlights.scm +++ b/runtime/queries/gdscript/highlights.scm @@ -14,6 +14,7 @@ (attribute_call (identifier) @function) (base_call (identifier) @function) (call (identifier) @function) +(lambda (name) @function) ; Function definitions @@ -88,6 +89,7 @@ "<<" ">>" ":=" + ":" ] @operator (annotation (identifier) @keyword.storage.modifier) @@ -97,6 +99,7 @@ "else" "elif" "match" + "when" ] @keyword.control.conditional [ diff --git a/runtime/queries/gdscript/indents.scm b/runtime/queries/gdscript/indents.scm index c969eb7cf..3d49aec35 100644 --- a/runtime/queries/gdscript/indents.scm +++ b/runtime/queries/gdscript/indents.scm @@ -6,6 +6,7 @@ (pattern_section) (function_definition) + (lambda) (constructor_definition) (class_definition) (enum_definition) diff --git a/runtime/queries/gdscript/textobjects.scm b/runtime/queries/gdscript/textobjects.scm index 47512bba7..3a2775fe2 100644 --- a/runtime/queries/gdscript/textobjects.scm +++ b/runtime/queries/gdscript/textobjects.scm @@ -5,6 +5,8 @@ (function_definition (body) @function.inside) @function.around +(lambda (body) @function.inside) @function.around + (parameters [ (identifier) @@ -15,5 +17,12 @@ (arguments (_expression) @parameter.inside @parameter.around) +[ + (const_statement) + (variable_statement) + (pair) + (enumerator) +] @entry.around + (comment) @comment.inside (comment)+ @comment.around diff --git a/runtime/queries/gherkin/highlights.scm b/runtime/queries/gherkin/highlights.scm new file mode 100644 index 000000000..1a17e3819 --- /dev/null +++ b/runtime/queries/gherkin/highlights.scm @@ -0,0 +1,17 @@ +[ + (feature_keyword) + (rule_keyword) + (background_keyword) + (scenario_keyword) + (given_keyword) + (when_keyword) + (then_keyword) + (and_keyword) + (but_keyword) + (asterisk_keyword) +] @keyword + +(tag) @function +(doc_string) @string +(data_table) @special +(comment) @comment diff --git a/runtime/queries/git-config/textobjects.scm b/runtime/queries/git-config/textobjects.scm new file mode 100644 index 000000000..4335f1392 --- /dev/null +++ b/runtime/queries/git-config/textobjects.scm @@ -0,0 +1,6 @@ +(comment) @comment.inside + +(comment)+ @comment.around + +(variable + (_) @entry.inside) @entry.around diff --git a/runtime/queries/godot-resource/injections.scm b/runtime/queries/godot-resource/injections.scm index 7929d63cd..6e199f104 100644 --- a/runtime/queries/godot-resource/injections.scm +++ b/runtime/queries/godot-resource/injections.scm @@ -11,8 +11,41 @@ (property (path) @_is_code (string) @injection.content)) - (#match? @_type "type") + (#eq? @_type "type") (#match? @_is_shader "Shader") (#eq? @_is_code "code") (#set! injection.language "glsl") ) + +((section + (identifier) @_is_resource + (property + (path) @_is_code + (string) @injection.content)) + (#eq? @_is_resource "resource") + (#eq? @_is_code "code") + (#set! injection.language "glsl") +) + +((section + (identifier) @_id + (property + (path) @_is_expression + (string) @injection.content)) + (#eq? @_id "sub_resource") + (#eq? @_is_expression "expression") + (#set! injection.language "glsl") +) + +((section + (attribute + (identifier) @_type + (string) @_is_shader) + (property + (path) @_is_code + (string) @injection.content)) + (#eq? @_type "type") + (#match? @_is_shader "GDScript") + (#eq? @_is_code "script/source") + (#set! injection.language "gdscript") +) diff --git a/runtime/queries/godot-resource/textobjects.scm b/runtime/queries/godot-resource/textobjects.scm new file mode 100644 index 000000000..aeb4e3eb3 --- /dev/null +++ b/runtime/queries/godot-resource/textobjects.scm @@ -0,0 +1,23 @@ +(section + (identifier) + (_) + (property) @class.inside +) @class.around + +(attribute + (identifier) + (_) @parameter.inside) @parameter.around + +(property + (path) + (_) @entry.inside) @entry.around + +(pair + (_) @entry.inside) @entry.around + +(array + (_) @entry.around) + +(comment) @comment.inside + +(comment)+ @comment.around diff --git a/runtime/queries/hcl/textobjects.scm b/runtime/queries/hcl/textobjects.scm index 1e6505876..c5ee4ff2d 100644 --- a/runtime/queries/hcl/textobjects.scm +++ b/runtime/queries/hcl/textobjects.scm @@ -4,3 +4,8 @@ (function_arguments ((_) @parameter.inside . ","? @parameter.around) @parameter.around) +(attribute + (_) @entry.inside) @entry.around + +(tuple + (_) @entry.around) diff --git a/runtime/queries/hocon/textobjects.scm b/runtime/queries/hocon/textobjects.scm new file mode 100644 index 000000000..aa4583933 --- /dev/null +++ b/runtime/queries/hocon/textobjects.scm @@ -0,0 +1,10 @@ +(comment) @comment.inside + +(comment)+ @comment.around + +(pair + (_) @entry.inside) @entry.around + +(array + (_) @entry.around) + diff --git a/runtime/queries/html/highlights.scm b/runtime/queries/html/highlights.scm index 99f39c95b..5dd61b7c0 100644 --- a/runtime/queries/html/highlights.scm +++ b/runtime/queries/html/highlights.scm @@ -1,13 +1,39 @@ (tag_name) @tag -(erroneous_end_tag_name) @tag.error +(erroneous_end_tag_name) @error (doctype) @constant (attribute_name) @attribute (comment) @comment -[ - "\"" - (attribute_value) -] @string +((attribute + (attribute_name) @_attr + (quoted_attribute_value (attribute_value) @markup.link.url)) + (#any-of? @_attr "href" "src")) + +((element + (start_tag + (tag_name) @_tag) + (text) @markup.link.label) + (#eq? @_tag "a")) + +(attribute [(attribute_value) (quoted_attribute_value)] @string) + +((element + (start_tag + (tag_name) @_tag) + (text) @markup.bold) + (#any-of? @_tag "strong" "b")) + +((element + (start_tag + (tag_name) @_tag) + (text) @markup.italic) + (#any-of? @_tag "em" "i")) + +((element + (start_tag + (tag_name) @_tag) + (text) @markup.strikethrough) + (#any-of? @_tag "s" "del")) [ "<" diff --git a/runtime/queries/jq/highlights.scm b/runtime/queries/jq/highlights.scm new file mode 100644 index 000000000..8cec2be90 --- /dev/null +++ b/runtime/queries/jq/highlights.scm @@ -0,0 +1,160 @@ +;; From nvim-treesitter, contributed by @ObserverOfTime et al. + +; Variables +(variable) @variable + +((variable) @constant.builtin + (#eq? @constant.builtin "$ENV")) + +((variable) @constant.builtin + (#eq? @constant.builtin "$__loc__")) + +; Properties +(index + (identifier) @variable.other.member) + +; Labels +(query + label: (variable) @label) + +(query + break_statement: (variable) @label) + +; Literals +(number) @constant.numeric + +(string) @string + +[ + "true" + "false" +] @constant.builtin.boolean + +"null" @type.builtin + +; Interpolation +[ + "\\(" + ")" +] @special + +; Format +(format) @attribute + +; Functions +(funcdef + (identifier) @function) + +(funcdefargs + (identifier) @variable.parameter) + +[ + "reduce" + "foreach" +] @function.builtin + +((funcname) @function + . + "(") + +; jq -n 'builtins | map(split("/")[0]) | unique | .[]' +((funcname) @function.builtin + (#any-of? @function.builtin + "IN" "INDEX" "JOIN" "abs" "acos" "acosh" "add" "all" "any" "arrays" "ascii_downcase" + "ascii_upcase" "asin" "asinh" "atan" "atan2" "atanh" "booleans" "bsearch" "builtins" "capture" + "cbrt" "ceil" "combinations" "contains" "copysign" "cos" "cosh" "debug" "del" "delpaths" "drem" + "empty" "endswith" "env" "erf" "erfc" "error" "exp" "exp10" "exp2" "explode" "expm1" "fabs" + "fdim" "finites" "first" "flatten" "floor" "fma" "fmax" "fmin" "fmod" "format" "frexp" + "from_entries" "fromdate" "fromdateiso8601" "fromjson" "fromstream" "gamma" "get_jq_origin" + "get_prog_origin" "get_search_list" "getpath" "gmtime" "group_by" "gsub" "halt" "halt_error" + "has" "hypot" "implode" "in" "index" "indices" "infinite" "input" "input_filename" + "input_line_number" "inputs" "inside" "isempty" "isfinite" "isinfinite" "isnan" "isnormal" + "iterables" "j0" "j1" "jn" "join" "keys" "keys_unsorted" "last" "ldexp" "length" "lgamma" + "lgamma_r" "limit" "localtime" "log" "log10" "log1p" "log2" "logb" "ltrimstr" "map" "map_values" + "match" "max" "max_by" "min" "min_by" "mktime" "modf" "modulemeta" "nan" "nearbyint" "nextafter" + "nexttoward" "normals" "not" "now" "nth" "nulls" "numbers" "objects" "path" "paths" "pick" "pow" + "pow10" "range" "recurse" "remainder" "repeat" "reverse" "rindex" "rint" "round" "rtrimstr" + "scalars" "scalb" "scalbln" "scan" "select" "setpath" "significand" "sin" "sinh" "sort" + "sort_by" "split" "splits" "sqrt" "startswith" "stderr" "strflocaltime" "strftime" "strings" + "strptime" "sub" "tan" "tanh" "test" "tgamma" "to_entries" "todate" "todateiso8601" "tojson" + "tonumber" "tostream" "tostring" "transpose" "trunc" "truncate_stream" "type" "unique" + "unique_by" "until" "utf8bytelength" "values" "walk" "while" "with_entries" "y0" "y1" "yn")) + +; Keywords +[ + "def" + "as" + "label" + "module" + "break" +] @keyword + +[ + "import" + "include" +] @keyword.control.import + +[ + "if" + "then" + "elif" + "else" + "end" +] @keyword.control.conditional + +[ + "try" + "catch" +] @keyword.control.exception + +[ + "or" + "and" +] @keyword.operator + +; Operators +[ + "." + "==" + "!=" + ">" + ">=" + "<=" + "<" + "=" + "+" + "-" + "*" + "/" + "%" + "+=" + "-=" + "*=" + "/=" + "%=" + "//=" + "|" + "?" + "//" + "?//" + (recurse) ; ".." +] @operator + +; Punctuation +[ + ";" + "," + ":" +] @punctuation.delimiter + +[ + "[" + "]" + "{" + "}" + "(" + ")" +] @punctuation.bracket + +; Comments +(comment) @comment.line diff --git a/runtime/queries/jq/injections.scm b/runtime/queries/jq/injections.scm new file mode 100644 index 000000000..ddfe53c3b --- /dev/null +++ b/runtime/queries/jq/injections.scm @@ -0,0 +1,25 @@ +;; From nvim-treesitter, contributed by @ObserverOfTime et al. + +((comment) @injection.content + (#set! injection.language "comment")) + +; test(val) +(query + ((funcname) @_function + (#any-of? @_function "test" "match" "capture" "scan" "split" "splits" "sub" "gsub")) + (args + . + (query + (string) @injection.content + (#set! injection.language "regex")))) + +; test(regex; flags) +(query + ((funcname) @_function + (#any-of? @_function "test" "match" "capture" "scan" "split" "splits" "sub" "gsub")) + (args + . + (args + (query + (string) @injection.content + (#set! injection.language "regex"))))) diff --git a/runtime/queries/jq/locals.scm b/runtime/queries/jq/locals.scm new file mode 100644 index 000000000..40946e7c3 --- /dev/null +++ b/runtime/queries/jq/locals.scm @@ -0,0 +1,12 @@ +;; From nvim-treesitter, contributed by @ObserverOfTime et al. + +(funcdef + (identifier) @local.definition) + +(funcdefargs + (identifier) @local.definition) + +(funcname) @local.reference + +(index + (identifier) @local.reference) diff --git a/runtime/queries/jq/textobjects.scm b/runtime/queries/jq/textobjects.scm new file mode 100644 index 000000000..ff078cd14 --- /dev/null +++ b/runtime/queries/jq/textobjects.scm @@ -0,0 +1,8 @@ +(comment) @comment.inside +(comment)+ @comment.around + +(funcdef + (query) @function.inside) @function.around + +(objectkeyval + (_) @entry.inside) @entry.around diff --git a/runtime/queries/just/folds.scm b/runtime/queries/just/folds.scm index 77079fd4f..2640f4c4a 100644 --- a/runtime/queries/just/folds.scm +++ b/runtime/queries/just/folds.scm @@ -1,5 +1,3 @@ -; From - ; Define collapse points ([ diff --git a/runtime/queries/just/highlights.scm b/runtime/queries/just/highlights.scm index d5e5cc191..258fadb9e 100644 --- a/runtime/queries/just/highlights.scm +++ b/runtime/queries/just/highlights.scm @@ -1,5 +1,3 @@ -; From - ; This file specifies how matched syntax patterns should be highlighted [ @@ -26,35 +24,57 @@ (identifier) @variable) (alias - left: (identifier) @variable) + name: (identifier) @variable) (assignment - left: (identifier) @variable) + name: (identifier) @variable) -; Functions +(shell_variable_name) @variable -(recipe_header - name: (identifier) @function) +; Functions -(dependency +(recipe name: (identifier) @function) -(dependency_expression - name: (identifier) @function) +(recipe_dependency + name: (identifier) @function.call) (function_call - name: (identifier) @function) + name: (identifier) @function.builtin) ; Parameters -(parameter +(recipe_parameter name: (identifier) @variable.parameter) ; Namespaces -(module +(mod name: (identifier) @namespace) +; Paths + +(mod + (path) @string.special.path) + +(import + (path) @string.special.path) + +; Shebangs + +(shebang_line) @keyword.directive +(shebang_line + (shebang_shell) @string.special) + + +(shell_expanded_string + [ + (expansion_short_start) + (expansion_long_start) + (expansion_long_middle) + (expansion_long_end) + ] @punctuation.special) + ; Operators [ @@ -95,55 +115,31 @@ ; Literals -(boolean) @constant.builtin.boolean +; Booleans are not allowed anywhere except in settings +(setting + (boolean) @constant.builtin.boolean) [ (string) (external_command) ] @string -(escape_sequence) @constant.character.escape +[ + (escape_sequence) + (escape_variable_end) +] @constant.character.escape ; Comments (comment) @comment.line -(shebang) @keyword.directive - -; highlight known settings (filtering does not always work) +; highlight known settings (setting - left: (identifier) @keyword - (#any-of? @keyword - "allow-duplicate-recipes" - "dotenv-filename" - "dotenv-load" - "dotenv-path" - "export" - "fallback" - "ignore-comments" - "positional-arguments" - "shell" - "tempdi" - "windows-powershell" - "windows-shell")) - -; highlight known attributes (filtering does not always work) + name: (_) @keyword.function) + +; highlight known attributes (attribute - (identifier) @attribute - (#any-of? @attribute - "private" - "allow-duplicate-recipes" - "dotenv-filename" - "dotenv-load" - "dotenv-path" - "export" - "fallback" - "ignore-comments" - "positional-arguments" - "shell" - "tempdi" - "windows-powershell" - "windows-shell")) + name: (identifier) @attribute) ; Numbers are part of the syntax tree, even if disallowed (numeric_error) @error diff --git a/runtime/queries/just/indents.scm b/runtime/queries/just/indents.scm index 7cfca3d7e..c66dda4c3 100644 --- a/runtime/queries/just/indents.scm +++ b/runtime/queries/just/indents.scm @@ -1,5 +1,3 @@ -; From -; ; This query specifies how to auto-indent logical blocks. ; ; Better documentation with diagrams is in https://docs.helix-editor.com/guides/indent.html diff --git a/runtime/queries/just/injections.scm b/runtime/queries/just/injections.scm index 54393059b..39877be47 100644 --- a/runtime/queries/just/injections.scm +++ b/runtime/queries/just/injections.scm @@ -1,5 +1,3 @@ -; From -; ; Specify nested languages that live within a `justfile` ; ================ Always applicable ================ @@ -8,7 +6,7 @@ (#set! injection.language "comment")) ; Highlight the RHS of `=~` as regex -((regex_literal +((regex (_) @injection.content) (#set! injection.language "regex")) @@ -21,7 +19,7 @@ (#set! injection.include-children)) @injection.content (external_command - (command_body) @injection.content + (content) @injection.content (#set! injection.language "bash")) ; ================ Global language specified ================ @@ -43,7 +41,7 @@ ; they default to bash. Limitations... ; See https://github.com/tree-sitter/tree-sitter/issues/880 for more on that. -(source_file +(file (setting "shell" ":=" "[" (string) @_langstr (#match? @_langstr ".*(powershell|pwsh|cmd).*") (#set! injection.language "powershell")) @@ -57,10 +55,10 @@ (expression (value (external_command - (command_body) @injection.content)))) + (content) @injection.content)))) ]) -(source_file +(file (setting "shell" ":=" "[" (string) @injection.language (#not-match? @injection.language ".*(powershell|pwsh|cmd).*")) [ @@ -73,12 +71,12 @@ (expression (value (external_command - (command_body) @injection.content)))) + (content) @injection.content)))) ]) ; ================ Recipe language specified - Helix only ================ ; Set highlighting for recipes that specify a language using builtin shebang matching (recipe_body - (shebang) @injection.shebang + (shebang_line) @injection.shebang (#set! injection.include-children)) @injection.content diff --git a/runtime/queries/just/locals.scm b/runtime/queries/just/locals.scm index 827148a17..d612f5da4 100644 --- a/runtime/queries/just/locals.scm +++ b/runtime/queries/just/locals.scm @@ -1,5 +1,3 @@ -; From -; ; This file tells us about the scope of variables so e.g. local ; variables override global functions with the same name @@ -10,32 +8,29 @@ ; Definitions (alias - left: (identifier) @local.definition) + name: (identifier) @local.definition) (assignment - left: (identifier) @local.definition) + name: (identifier) @local.definition) -(module +(mod name: (identifier) @local.definition) -(parameter +(recipe_parameter name: (identifier) @local.definition) -(recipe_header +(recipe name: (identifier) @local.definition) ; References (alias - right: (identifier) @local.reference) - -(function_call name: (identifier) @local.reference) -(dependency +(function_call name: (identifier) @local.reference) -(dependency_expression +(recipe_dependency name: (identifier) @local.reference) (value diff --git a/runtime/queries/just/textobjects.scm b/runtime/queries/just/textobjects.scm index bb604178e..b60b11e4d 100644 --- a/runtime/queries/just/textobjects.scm +++ b/runtime/queries/just/textobjects.scm @@ -1,18 +1,19 @@ -; From -; ; Specify how to navigate around logical blocks in code +(assert_parameters + ((_) @parameter.inside . ","? @parameter.around)) @parameter.around + (recipe (recipe_body) @function.inside) @function.around -(parameters +(recipe_parameters ((_) @parameter.inside . ","? @parameter.around)) @parameter.around -(dependency_expression +(recipe_dependency (_) @parameter.inside) @parameter.around (function_call - arguments: (sequence - (expression) @parameter.inside) @parameter.around) @function.around + (function_parameters + ((_) @parameter.inside . ","? @parameter.around)) @parameter.around) @function.around (comment) @comment.around diff --git a/runtime/queries/nix/textobjects.scm b/runtime/queries/nix/textobjects.scm index 1508d4c2b..196ef46cb 100644 --- a/runtime/queries/nix/textobjects.scm +++ b/runtime/queries/nix/textobjects.scm @@ -7,3 +7,6 @@ (function_expression body: (_) @function.inside) @function.around +(binding + (_) @entry.inside) @entry.around + diff --git a/runtime/queries/prisma/textobjects.scm b/runtime/queries/prisma/textobjects.scm new file mode 100644 index 000000000..a59ac221c --- /dev/null +++ b/runtime/queries/prisma/textobjects.scm @@ -0,0 +1,17 @@ +(model_declaration + ((statement_block) @class.inside)) @class.around + +(call_expression + (arguments (_) @parameter.inside . ","? @parameter.around) @parameter.around) + +(column_declaration) @entry.around + +(array (_) @entry.around) + +(assignment_expression + (_) @entry.inside) @entry.around + +(developer_comment) @comment.inside + +(developer_comment)+ @comment.around + diff --git a/runtime/queries/rust/highlights.scm b/runtime/queries/rust/highlights.scm index 7997c5ea0..2981075fb 100644 --- a/runtime/queries/rust/highlights.scm +++ b/runtime/queries/rust/highlights.scm @@ -55,6 +55,55 @@ "'" @label (identifier) @label) +; --- +; Prelude +; --- + +((identifier) @type.enum.variant.builtin + (#any-of? @type.enum.variant.builtin "Some" "None" "Ok" "Err")) + + + +((type_identifier) @type.builtin + (#any-of? + @type.builtin + "Send" + "Sized" + "Sync" + "Unpin" + "Drop" + "Fn" + "FnMut" + "FnOnce" + "AsMut" + "AsRef" + "From" + "Into" + "DoubleEndedIterator" + "ExactSizeIterator" + "Extend" + "IntoIterator" + "Iterator" + "Option" + "Result" + "Clone" + "Copy" + "Debug" + "Default" + "Eq" + "Hash" + "Ord" + "PartialEq" + "PartialOrd" + "ToOwned" + "Box" + "String" + "ToString" + "Vec" + "FromIterator" + "TryFrom" + "TryInto")) + ; --- ; Punctuation ; --- diff --git a/runtime/queries/sql/textobjects.scm b/runtime/queries/sql/textobjects.scm new file mode 100644 index 000000000..975fd4c5e --- /dev/null +++ b/runtime/queries/sql/textobjects.scm @@ -0,0 +1,4 @@ +(comment) @comment.inside + +(comment)+ @comment.around + diff --git a/runtime/queries/thrift/folds.scm b/runtime/queries/thrift/folds.scm new file mode 100644 index 000000000..1361be1f8 --- /dev/null +++ b/runtime/queries/thrift/folds.scm @@ -0,0 +1,12 @@ +[ + (annotation_definition) + (enum_definition) + (exception_definition) + (function_definition) + (senum_definition) + (service_definition) + (struct_definition) + (union_definition) + + (comment) +] @fold diff --git a/runtime/queries/thrift/highlights.scm b/runtime/queries/thrift/highlights.scm new file mode 100644 index 000000000..567c3f9dc --- /dev/null +++ b/runtime/queries/thrift/highlights.scm @@ -0,0 +1,211 @@ +; Variables + +((identifier) @variable) + +; Includes + +[ + "include" + "cpp_include" +] @keyword + +; Function + +(function_definition + (identifier) @function) + +; Fields + +(field (identifier) @variable.other.member) + +; Parameters + +(function_definition + (parameters + (parameter (identifier) @variable.parameter))) + +(throws + (parameters + (parameter (identifier) @keyword.control.exception))) + +; Types + +(typedef_identifier) @type +(struct_definition + "struct" (identifier) @type) + +(union_definition + "union" (identifier) @type) + +(exception_definition + "exception" (identifier) @type) + +(service_definition + "service" (identifier) @type) + +(interaction_definition + "interaction" (identifier) @type) + +(type + type: (identifier) @type) + +(definition_type + type: (identifier) @type) + +; Constants + +(const_definition (identifier) @constant) + +(enum_definition "enum" + . (identifier) @type + "{" (identifier) @constant "}") + +; Builtin Types + +(primitive) @type.builtin + +[ + "list" + "map" + "set" + "sink" + "stream" + "void" +] @type.builtin + +; Namespace + +(namespace_declaration + (namespace_scope) @tag + [(namespace) @namespace (_ (identifier) @namespace)]) + +; Attributes + +(annotation_definition + (annotation_identifier (identifier) @attribute)) +(fb_annotation_definition + "@" @attribute (annotation_identifier (identifier) @attribute) + (identifier)? @attribute) +(namespace_uri (string) @attribute) + +; Operators + +[ + "=" + "&" +] @operator + +; Exceptions + +[ + "throws" +] @keyword.control.exception + +; Keywords + +[ + "enum" + "exception" + "extends" + "interaction" + "namespace" + "senum" + "service" + "struct" + "typedef" + "union" + "uri" +] @keyword + +; Deprecated Keywords + +[ + "cocoa_prefix" + "cpp_namespace" + "csharp_namespace" + "delphi_namespace" + "java_package" + "perl_package" + "php_namespace" + "py_module" + "ruby_namespace" + "smalltalk_category" + "smalltalk_prefix" + "xsd_all" + "xsd_attrs" + "xsd_namespace" + "xsd_nillable" + "xsd_optional" +] @keyword + +; Extended Kewords +[ + "package" + "performs" +] @keyword + +[ + "async" + "oneway" +] @keyword + +; Qualifiers + +[ + "client" + "const" + "idempotent" + "optional" + "permanent" + "readonly" + "required" + "safe" + "server" + "stateful" + "transient" +] @type.directive + +; Literals + +(string) @string + +(escape_sequence) @constant.character.escape + +(namespace_uri + (string) @string.special) + +(number) @constant.numeric.integer + +(double) @constant.numeric.float + +(boolean) @constant.builtin.boolean + +; Typedefs + +(typedef_identifier) @type.definition + +; Punctuation + +[ + "*" +] @punctuation.special + +["{" "}"] @punctuation.bracket + +["(" ")"] @punctuation.bracket + +["[" "]"] @punctuation.bracket + +["<" ">"] @punctuation.bracket + +[ + "." + "," + ";" + ":" +] @punctuation.delimiter + +; Comments + +(comment) @comment + diff --git a/runtime/queries/thrift/injections.scm b/runtime/queries/thrift/injections.scm new file mode 100644 index 000000000..321c90add --- /dev/null +++ b/runtime/queries/thrift/injections.scm @@ -0,0 +1,2 @@ +((comment) @injection.content + (#set! injection.language "comment")) diff --git a/runtime/queries/thrift/locals.scm b/runtime/queries/thrift/locals.scm new file mode 100644 index 000000000..538b49962 --- /dev/null +++ b/runtime/queries/thrift/locals.scm @@ -0,0 +1,51 @@ +; Scopes + +[ + (document) + (definition) +] @local.scope + +; References + +(identifier) @local.reference + +; Definitions + +(annotation_identifier) @local.definition + +; (const_definition (identifier) @definition.constant) + +; (enum_definition "enum" +; . (identifier) @definition.enum +; "{" (identifier) @definition.constant "}") + +; (senum_definition "senum" +; . (identifier) @definition.enum) + +; (field (identifier) @definition.field) + +; (function_definition (identifier) @definition.function) + +; (namespace_declaration +; "namespace" (namespace_scope) +; . (_) @definition.namespace +; (namespace_uri)?) + +; (parameter (identifier) @definition.parameter) + +; (struct_definition +; "struct" . (identifier) @definition.type) + +; (union_definition +; "union" . (identifier) @definition.type) + +; (exception_definition +; "exception" . (identifier) @definition.type) + +; (service_definition +; "service" . (identifier) @definition.type) + +; (interaction_definition +; "interaction" . (identifier) @definition.type) + +; (typedef_identifier) @definition.type diff --git a/runtime/queries/typespec/highlights.scm b/runtime/queries/typespec/highlights.scm new file mode 100644 index 000000000..8b8aa4c3d --- /dev/null +++ b/runtime/queries/typespec/highlights.scm @@ -0,0 +1,177 @@ +; Keywords + +[ + "is" + "extends" + "valueof" +] @keyword.operator + +[ + "namespace" + "scalar" + "interface" + "alias" +] @keyword + +[ + "model" + "enum" + "union" +] @keyword.storage.type + +[ + "op" + "fn" + "dec" +] @keyword.function + +"extern" @keyword.storage.modifier + +[ + "import" + "using" +] @keyword.control.import + +[ + "(" + ")" + "{" + "}" + "<" + ">" + "[" + "]" +] @punctuation.bracket + +[ + "," + ";" + "." + ":" +] @punctuation.delimiter + +[ + "|" + "&" + "=" + "..." +] @operator + +"?" @punctuation.special + +; Imports + +(import_statement + (quoted_string_literal) @string.special.path) + +; Namespaces + +(using_statement + module: (identifier_or_member_expression) @namespace) + +(namespace_statement + name: (identifier_or_member_expression) @namespace) + +; Comments + +[ + (single_line_comment) +] @comment.line + +[ + (multi_line_comment) +] @comment.block + +; Decorators + +(decorator + "@" @attribute + name: (identifier_or_member_expression) @attribute) + +(augment_decorator_statement + name: (identifier_or_member_expression) @attribute) + +(decorator + (decorator_arguments) @variable.parameter) + +; Scalars + +(scalar_statement + name: (identifier) @type) + +; Models + +(model_statement + name: (identifier) @type) + +(model_property + name: (identifier) @variable.other.member) + +; Operations + +(operation_statement + name: (identifier) @function.method) + +(operation_arguments + (model_property + name: (identifier) @variable.parameter)) + +(template_parameter + name: (identifier) @type.parameter) + +(function_parameter + name: (identifier) @variable.parameter) + +; Interfaces + +(interface_statement + name: (identifier) @type) + +(interface_statement + (interface_body + (interface_member + (identifier) @function.method))) + +; Enums + +(enum_statement + name: (identifier) @type.enum) + +(enum_member + name: (identifier) @constant) + +; Unions + +(union_statement + name: (identifier) @type) + +(union_variant + name: (identifier) @type.enum.variant) + +; Aliases + +(alias_statement + name: (identifier) @type) + +; Built-in types + +[ + (quoted_string_literal) + (triple_quoted_string_literal) +] @string + +(escape_sequence) @constant.character.escape + +(boolean_literal) @constant.builtin.boolean + +[ + (decimal_literal) + (hex_integer_literal) + (binary_integer_literal) +] @constant.numeric.integer + +(builtin_type) @type.builtin + +; Identifiers + +(identifier_or_member_expression) @type diff --git a/runtime/queries/typespec/indents.scm b/runtime/queries/typespec/indents.scm new file mode 100644 index 000000000..aee01f35a --- /dev/null +++ b/runtime/queries/typespec/indents.scm @@ -0,0 +1,18 @@ +[ + (model_expression) + (tuple_expression) + (namespace_body) + (interface_body) + (union_body) + (enum_body) + (template_arguments) + (template_parameters) + (operation_arguments) +] @indent.begin + +[ + "}" + ")" + ">" + "]" +] @indent.end diff --git a/runtime/queries/typespec/injections.scm b/runtime/queries/typespec/injections.scm new file mode 100644 index 000000000..81d7734cb --- /dev/null +++ b/runtime/queries/typespec/injections.scm @@ -0,0 +1,5 @@ +([ + (single_line_comment) + (multi_line_comment) +] @injection.content + (#set! injection.language "comment")) diff --git a/runtime/queries/typespec/textobjects.scm b/runtime/queries/typespec/textobjects.scm new file mode 100644 index 000000000..7ee1251c9 --- /dev/null +++ b/runtime/queries/typespec/textobjects.scm @@ -0,0 +1,51 @@ +; Classes + +(enum_statement + (enum_body) @class.inside) @class.around + +(model_statement + (model_expression) @class.inside) @class.around + +(union_statement + (union_body) @class.inside) @class.around + +; Interfaces + +(interface_statement + (interface_body + (interface_member) @function.around) @class.inside) @class.around + +; Comments + +[ + (single_line_comment) + (multi_line_comment) +] @comment.inside + +[ + (single_line_comment) + (multi_line_comment) +]+ @comment.around + +; Functions + +[ + (decorator) + (decorator_declaration_statement) + (function_declaration_statement) + (operation_statement) +] @function.around + +(function_parameter_list + (function_parameter)? @parameter.inside)* @function.inside + +(decorator_arguments + (expression_list + (_) @parameter.inside)*) @function.inside + +(operation_arguments + (model_property)? @parameter.inside)* @function.inside + +(template_parameters + (template_parameter_list + (template_parameter) @parameter.inside)) @function.inside diff --git a/runtime/queries/verilog/textobjects.scm b/runtime/queries/verilog/textobjects.scm index f940832ab..0a2034dc2 100644 --- a/runtime/queries/verilog/textobjects.scm +++ b/runtime/queries/verilog/textobjects.scm @@ -3,4 +3,8 @@ (function_body_declaration (function_identifier (function_identifier - (simple_identifier) @function.inside)))) @function.around \ No newline at end of file + (simple_identifier) @function.inside)))) @function.around + +(comment) @comment.inside + +(comment)+ @comment.around diff --git a/runtime/queries/yaml/textobjects.scm b/runtime/queries/yaml/textobjects.scm new file mode 100644 index 000000000..8b9bd0560 --- /dev/null +++ b/runtime/queries/yaml/textobjects.scm @@ -0,0 +1,7 @@ +(comment) @comment.inside + +(comment)+ @comment.around + +(block_mapping_pair + (_) @entry.inside) @entry.around + diff --git a/runtime/themes/ao.toml b/runtime/themes/ao.toml new file mode 100644 index 000000000..7313d9fa5 --- /dev/null +++ b/runtime/themes/ao.toml @@ -0,0 +1,165 @@ +# Theme: Ao +# Author: YardQuit + +# SYNTAX HIGHLIGHTING +"attribute" = { fg = "yellow" } +"type" = { fg = "white" } +"type.builtin" = { fg = "white" } +"type.parameter" = { fg = "white" } +"type.enum" = { fg = "white" } +"type.enum.variant" = { fg = "white" } +"constructor" = { fg = "orange" } +"constant" = { fg = "blue" } +"constant.character.escape" = { fg = "yellow" } +"string" = { fg = "blue" } +"string.regexp" = { fg = "yellow" } +"comment" = { fg = "gray" } +"variable" = { fg = "orange" } +"variable.parameter" = { fg = "yellow" } +"variable.other" = { fg = "green" } +"variable.other.member" = { fg = "green" } +"label" = { fg = "blue" } +"punctuation" = { fg = "white" } +"punctuation.bracket" = { fg = "orange" } +"punctuation.special" = { fg = "yellow" } +"keyword" = { fg = "red" } +"keyword.operator" = { fg = "blue" } +"keyword.directive" = { fg = "white" } +"keyword.function" = { fg = "red" } +"keyword.storage" = { fg = "red" } +"keyword.storage.modifier" = { fg = "green" } +"operator" = { fg = "white" } +"function" = { fg = "purple" } +"function.method" = { fg = "green" } +"function.macro" = { fg = "green" } +"function.special" = { fg = "yellow" } +"tag" = { fg = "green" } +"namespace" = { fg = "white" } +"diff" = { fg = "white" } +"diff.minus" = { fg = "red" } +"diff.delta" = { fg = "brown" } + +# MARKUP, SYNAX HIGHLIGHTING AND INTERFACE HYBRID +"markup.heading" = { fg = "blaze_orange" } +"markup.heading.1" = { fg = "crystal_blue", modifiers = ["bold"] } +"markup.heading.2" = { fg = "sky_blue", modifiers = ["bold"] } +"markup.heading.3" = { fg = "dreamy_blue", modifiers = ["bold"] } +"markup.heading.4" = { fg = "crystal_blue" } +"markup.heading.5" = { fg = "sky_blue" } +"markup.heading.6" = { fg = "dreamy_blue" } +"markup.list" = { fg = "blaze_orange" } +"markup.bold" = { fg = "crystal_blue", modifiers = ["bold"] } +"markup.italic" = { fg = "crystal_blue", modifiers = ["italic"] } +"markup.strikethrough" = { fg = "crystal_blue", modifiers = ["crossed_out"] } +"markup.link" = { fg = "crystal_blue", underline = { color = "light_purple", style = "line" } } +"markup.link.url" = { fg = "slate_purple", underline = { color = "slate_purple", style = "line" } } +"markup.link.label" = { fg = "crystal_blue" } +"markup.link.text" = { fg = "crystal_blue", modifiers = ["bold"] } +"markup.quote" = { fg = "winter_sky", modifiers = ["italic"] } +"markup.raw" = { fg = "winter_sky" } +"markup.raw.block" = { fg = "white" } + +# USER INTERFACE +"ui.background" = { bg = "deep_abyss"} # workspace background +"ui.background.separator" = { fg = "winter_sky" } # picker separator below input line (space + j) +"ui.gutter" = { bg = "deep_abyss" } # gutter +"ui.gutter.selected" = { bg = "pitch_black" } # gutter for the line the cursor is on +"ui.linenr" = { fg = "slate_gray" } # line numbers +"ui.linenr.selected" = { fg = "blaze_orange", modifiers = ["bold"] } # line number for the line the cursor is on +"ui.statusline" = { fg = "winter_sky", bg = "twilight_blue" } # statusline, fucused +"ui.statusline.inactive" = { fg = "slate_gray", bg = "pitch_black" } # statusline, unfocused +"ui.statusline.normal" = { fg = "deep_abyss", bg = "leafy_green", modifiers = ["bold"] } # statusline normal mode (if editor.color-modes is enabled) +"ui.statusline.insert" = { fg = "deep_abyss", bg = "blaze_orange", modifiers = ["bold"] } # statusline insert mode (if editor.color-modes is enabled) +"ui.statusline.select" = { fg = "deep_abyss", bg = "sky_blue", modifiers = ["bold"] } # statusline select mode (if editor.color-modes is enabled) +"ui.statusline.separator" = { fg = "winter_sky" } # separator character is statusline +"ui.bufferline" = { fg = "slate_gray", modifiers = ["bold"] } # bufferline inactive tab +"ui.bufferline.active" = { fg = "winter_sky", bg = "twilight_blue" } # bufferline active tab +"ui.bufferline.background" = { bg = "pitch_black" } # bufferline background +"ui.virtual.ruler" = { bg = "stormy_night" } # ruler columns +"ui.virtual.whitespace" = { fg = "stormy_night" } # whitespace characters +"ui.virtual.indent-guide" = { fg = "stormy_night" } # vertical indent width guides +"ui.virtual.inlay-hint" = { fg = "slate_gray" } # inlay hints of all kinds +"ui.virtual.inlay-hint.parameter" = { fg = "slate_gray" } # inlay hints of kind parameter (lsps are not required to set a kind) +"ui.virtual.inlay-hint.type" = { fg = "slate_gray" } # inlay hints of kind type (lsps are not required to set a kind) +"ui.virtual.wrap" = { fg = "slate_gray" } # soft-wrap indicator +"ui.virtual.jump-label" = { modifiers = ["reversed"] } # virtual jump labels (g + w) +"ui.selection" = { bg = "deep_purple" } # slave selections in the editing area +"ui.selection.primary" = { bg = "light_purple" } # primary selection in the editing area +"ui.cursor" = { modifiers = ["reversed"] } # only if "ui.cursor.primary.normal" isn't set +"ui.cursor.normal" = { fg = "winter_sky", bg = "twilight_blue" } # slave cursor block in normal mode +"ui.cursor.insert" = { bg = "rustic_red" } # slave cursor block in insert mode +"ui.cursor.select" = { bg = "deep_purple" } # slave cursor block in select mode +"ui.cursor.match" = { fg = "deep_abyss", bg = "blaze_orange", modifiers = ["bold"] } # matching bracket etc +"ui.cursor.primary" = { modifiers = ["reversed"] } # cursor with primary selection (has no effect due to "ui.cursor.primary.normal" is set) +"ui.cursor.primary.normal" = { fg = "deep_abyss", bg = "sky_blue" } # cursor block in normal mode +"ui.cursor.primary.insert" = { fg = "deep_abyss", bg = "ruby_glow" } # cursor block in insert mode +"ui.cursor.primary.select" = { fg = "winter_sky", bg = "deep_purple" } # cursor block in select mode (not the selected color) +"ui.cursorline.primary" = { bg = "nightfall_blue" } # line of the primary cursor +"ui.cursorline.secondary" = { bg = "midnight_thunder"} # lines of secondary cursors +"ui.cursorcolumn.primary" = { bg = "nightfall_blue" } # column of the primary cursor +"ui.cursorcolumn.secondary" = { bg = "midnight_thunder" } # columns of secondary cursors + +# USER INTERFACE - MENUS AND POPUP +"ui.popup" = { fg = "winter_sky", bg = "midnight_thunder" } # documentation popups (space + k) +"ui.popup.info" = { fg = "winter_sky", bg = "nightfall_blue" } # prompt for multiple key options, menu border (space, g, z, m, etc) +"ui.window" = { fg = "slate_gray" } # borderlines separating splits +"ui.help" = { fg = "winter_sky", bg = "nightfall_blue" } # description box for commands +"ui.text" = { fg = "white" } # default text style, command prompts, popup text, etc +"ui.text.focus" = { fg = "dreamy_blue" } # the currently selected line in the picker (space j, space f, space s, etc) +"ui.text.inactive" = { fg = "slate_gray" } # same as ui.text but when the text is inactive e.g. suggestions +"ui.text.info" = { fg = "winter_sky", bg = "nightfall_blue" } # the key: command in ui.popup.info boxes (space, g, z, m, etc) +"ui.menu" = { fg = "winter_sky", bg = "midnight_thunder" } # code and command completion menus ":" +"ui.menu.selected" = { fg = "winter_sky", bg = "twilight_blue" } # selected autocomplete item +"ui.menu.scroll" = { fg = "crystal_blue", bg = "moonlight_ocean" } # scrollbar +"ui.highlight" = { underline = { color = "sky_blue", style = "line" } } # highlighted lines in the picker preview + +# USER INTERFACE - DIAGNOSTICS +"warning" = { fg = "lemon_zest" } # diagnostics warning (gutter) +"error" = { fg = "ruby_glow" } # diagnostics error (gutter) +"info" = { fg = "sky_blue" } # diagnostics info (gutter) +"hint" = { fg = "walnut_brown" } # diagnostics hint (gutter) +"diagnostic" = { modifiers = ["reversed"] } # diagnostics fallback style (editing area) +"diagnostic.hint" = { fg = "deep_abyss", bg = "walnut_brown" } # diagnostics hint (editing area) +"diagnostic.info" = { fg = "winter_sky", bg = "twilight_blue" } # diagnostics info (editing area) +"diagnostic.warning" = { fg = "winter_sky", bg = "rustic_amber" } # diagnostics warning (editing area) +"diagnostic.error" = { fg = "winter_sky", bg = "rustic_red" } # diagnostics error (editing area) + +# COLOR NAMES +[palette] +# PALETTE USER INTERFACE +deep_abyss = "#080d15" +stormy_night = "#254862" +nightfall_blue = "#1f2937" +midnight_thunder = "#0d1526" +twilight_blue = "#2c5484" +pitch_black = "#000000" +winter_sky = "#f3f4f6" +slate_gray = "#838a97" +blaze_orange = "#ff9000" +lemon_zest = "#ffba00" +leafy_green = "#81be83" +dreamy_blue = "#6eb0ff" +crystal_blue = "#99c7ff" +sky_blue = "#45b1e8" +moonlight_ocean = "#0c1420" +rustic_red = "#540b0c" +ruby_glow = "#fa7970" +walnut_brown = "#987654" +rustic_amber = "#9d5800" +slate_purple = "#d2a8ff" +light_purple = "#7533bd" +deep_purple = "#4c1785" + +# SYNTAX HIGHLIGHTING +black = "#0d1117" +red = "#fa7970" +green = "#81be83" +yellow = "#ffba00" +orange = "#ff9000" +blue = "#45b1e8" +purple = "#d2a8ff" +brown = "#987654" +gray = "#838a97" +white = "#dadada" + + diff --git a/runtime/themes/dark_plus.toml b/runtime/themes/dark_plus.toml index 77b9b3e7c..813eebf3c 100644 --- a/runtime/themes/dark_plus.toml +++ b/runtime/themes/dark_plus.toml @@ -1,7 +1,7 @@ # Author: David Else <12832280+David-Else@users.noreply.github.com> # SYNTAX -"attribute" = "fn_declaration" +"attribute" = "variable" "comment" = "dark_green" "constant" = "constant" "constant.builtin" = "blue2" @@ -39,10 +39,10 @@ # MARKUP "markup.heading" = { fg = "blue2", modifiers = ["bold"] } "markup.list" = "blue3" -"markup.bold" = { fg = "blue2", modifiers = ["bold"] } +"markup.bold" = { modifiers = ["bold"] } "markup.italic" = { modifiers = ["italic"] } "markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { modifiers = ["underlined"] } +"markup.link.url" = { underline.style= "line" } "markup.link.text" = "orange" "markup.quote" = "dark_green" "markup.raw" = "orange" @@ -57,7 +57,7 @@ # TODO: Alternate bg colour for `ui.cursor.match` and `ui.selection`. "ui.cursor" = { fg = "cursor", modifiers = ["reversed"] } "ui.cursor.primary" = { fg = "cursor", modifiers = ["reversed"] } -"ui.cursor.match" = { bg = "#3a3d41", modifiers = ["underlined"] } +"ui.cursor.match" = { bg = "#3a3d41", underline.style = "line" } "ui.selection" = { bg = "#3a3d41" } "ui.selection.primary" = { bg = "dark_blue" } "ui.linenr" = { fg = "dark_gray" } @@ -80,6 +80,8 @@ "ui.highlight.frameline" = { bg = "#4b4b18" } "ui.debug.active" = { fg = "#ffcc00" } "ui.debug.breakpoint" = { fg = "#e51400" } +"ui.picker.header.column" = { underline.style = "line" } +"ui.picker.header.column.active" = { fg ="white", underline.style = "line" } "warning" = { fg = "gold2" } "error" = { fg = "red" } "info" = { fg = "light_blue" } diff --git a/runtime/themes/everforest_dark.toml b/runtime/themes/everforest_dark.toml index 37b6756f5..eed60df3f 100644 --- a/runtime/themes/everforest_dark.toml +++ b/runtime/themes/everforest_dark.toml @@ -65,7 +65,7 @@ "diff.minus" = "red" "ui.background" = { bg = "bg0" } -"ui.background.separator" = "bg_visual" +"ui.background.separator" = "grey0" "ui.cursor" = { fg = "bg1", bg = "grey2" } "ui.cursor.insert" = { fg = "bg0", bg = "grey1" } "ui.cursor.select" = { fg = "bg0", bg = "blue" } @@ -90,6 +90,7 @@ "bold", ] } "ui.popup" = { fg = "grey2", bg = "bg2" } +"ui.picker.header" = { modifiers = ["bold", "underlined"] } "ui.window" = { fg = "bg4", bg = "bg_dim" } "ui.help" = { fg = "fg", bg = "bg2" } "ui.text" = "fg" diff --git a/runtime/themes/everforest_light.toml b/runtime/themes/everforest_light.toml index b7448455c..04482c89d 100644 --- a/runtime/themes/everforest_light.toml +++ b/runtime/themes/everforest_light.toml @@ -64,7 +64,7 @@ "diff.minus" = "red" "ui.background" = { bg = "bg0" } -"ui.background.separator" = "bg_visual" +"ui.background.separator" = "grey0" "ui.cursor" = { fg = "bg1", bg = "grey2" } "ui.cursor.insert" = { fg = "bg0", bg = "grey1" } "ui.cursor.select" = { fg = "bg0", bg = "blue" } @@ -89,6 +89,7 @@ "bold", ] } "ui.popup" = { fg = "grey2", bg = "bg2" } +"ui.picker.header" = { modifiers = ["bold", "underlined"] } "ui.window" = { fg = "bg4", bg = "bg_dim" } "ui.help" = { fg = "fg", bg = "bg2" } "ui.text" = "fg" diff --git a/runtime/themes/gruvbox.toml b/runtime/themes/gruvbox.toml index 220843b50..e91b6f322 100644 --- a/runtime/themes/gruvbox.toml +++ b/runtime/themes/gruvbox.toml @@ -94,6 +94,8 @@ "ui.menu" = { fg = "fg1", bg = "bg2" } "ui.menu.selected" = { fg = "bg2", bg = "blue1", modifiers = ["bold"] } "ui.popup" = { bg = "bg1" } +"ui.picker.header.column" = { underline.style = "line" } +"ui.picker.header.column.active" = { modifiers = ["bold"], underline.style = "line" } "ui.selection" = { bg = "bg2" } "ui.selection.primary" = { bg = "bg3" } diff --git a/runtime/themes/iceberg-dark.toml b/runtime/themes/iceberg-dark.toml new file mode 100644 index 000000000..b6e0cf522 --- /dev/null +++ b/runtime/themes/iceberg-dark.toml @@ -0,0 +1,128 @@ +# Author : Chromo-residuum-opec + +"attribute" = { fg = "green" } +"boolean" = { fg = "purple" } +"character" = { fg = "purple" } +"comment" = { fg = "comment_fg" } +"conditional" = { fg = "blue" } +"constant" = { fg = "purple" } +"constructor" = { fg = "blue" } +"diagnostic.deprecated" = { modifiers = ["crossed_out"] } +"diagnostic.error" = { underline = { style = "curl", color = "red" } } +"diagnostic.hint" = { underline = { style = "curl", color = "comment_fg" } } +"diagnostic.info" = { underline = { style = "curl", color = "cyan" } } +"diagnostic.unnecessary" = { modifiers = ["dim"] } +"diagnostic.warning" = { underline = { style = "curl", color = "orange" } } +"diff.delta" = { fg = "blue" } +"diff.delta.gutter" = { fg = "cyan", bg = "linenr_bg" } +"diff.minus" = { fg = "red" } +"diff.minus.gutter" = { fg = "red", bg = "linenr_bg" } +"diff.plus" = { fg = "green" } +"diff.plus.gutter" = { fg = "green", bg = "linenr_bg" } +"error" = { fg = "red" } +"exception" = { fg = "blue" } +"field" = { fg = "background_fg" } +"float" = { fg = "purple" } +"function" = { fg = "pale" } +"function.macro" = { fg = "green" } +"hint" = { fg = "comment_fg" } +"identifier" = { fg = "blue" } +"info" = { fg = "cyan" } +"keyword" = { fg = "blue" } +"keyword.directive" = { fg = "green" } +"keyword.import" = { fg = "pale" } +"label" = { fg = "green" } +"markup.bold" = { modifiers = ["bold"] } +"markup.heading" = { fg = "blue", modifiers = ["bold"] } +"markup.italic" = { modifiers = ["italic"] } +"markup.link" = { fg = "blue", underline = { style = "line" } } +"markup.link.label" = { fg = "cyan" } +"markup.link.text" = { fg = "cyan" } +"markup.link.url" = { underline = { style = "line" } } +"markup.list" = { fg = "orange", modifiers = ["bold"] } +"markup.raw" = { fg = "cyan" } +"markup.raw.inline" = { bg = "black", fg = "blue" } +"markup.strikethrough" = { modifiers = ["crossed_out"] } +"method" = { fg = "pale" } +"namespace" = { fg = "blue" } +"number" = { fg = "purple" } +"operator" = { fg = "blue" } +"parameter" = { fg = "background_fg" } +"property" = { fg = "background_fg" } +"punctuation.bracket" = { fg = "background_fg" } +"punctuation.delimiter" = { fg = "background_fg" } +"punctuation.special" = { fg = "green" } +"repeat" = { fg = "blue" } +"special" = { fg = "green" } +"string" = { fg = "cyan" } +"string.escape" = { fg = "green" } +"string.special" = { fg = "green" } +"tag" = { fg = "blue" } +"tag.attribute" = { fg = "purple" } +"text" = { fg = "background_fg" } +"type" = { fg = "blue" } +"ui.background" = { fg = "background_fg", bg = "background_bg" } +"ui.background.separator" = { fg = "comment_fg" } +"ui.bufferline.active" = { fg = "pale" } +"ui.cursor.match" = { fg = "background_fg", bg = "matchparen_bg" } +"ui.cursor.normal" = { bg = "gray" } +"ui.cursor.primary" = { modifiers = ["reversed"] } +"ui.cursor.select" = { bg = "gray" } +"ui.gutter" = { fg = "linenr_fg", bg = "linenr_bg" } +"ui.help" = { fg = "background_fg", bg = "cursorlinenr_bg" } +"ui.linenr" = { fg = "linenr_fg", bg = "linenr_bg" } +"ui.menu" = { fg = "background_fg", bg = "cursorlinenr_bg" } +"ui.menu.border" = { fg = "comment_fg" } +"ui.menu.selected" = { fg = "menusel_fg", bg = "menusel_bg" } +"ui.popup" = { fg = "background_fg", bg = "cursorlinenr_bg" } +"ui.popup.info" = { fg = "blue" } +"ui.selection" = { bg = "sel_bg" } +"ui.statusline" = { bg = "statusline_bg", fg = "statusline_fg" } +"ui.statusline.insert" = { fg = "black", bg = "blue" } +"ui.statusline.select" = { fg = "black", bg = "green" } +"ui.text.focus" = { fg = "orange" } +"ui.virtual" = { fg = "linenr_fg" } +"ui.virtual.indent-guide" = { fg = "linenr_fg" } +"ui.virtual.jump-label" = { fg = "orange", modifiers = ["bold"] } +"ui.virtual.ruler" = { bg = "linenr_bg" } +"ui.virtual.whitespace" = { fg = "sel_bg" } +"ui.window" = { fg = "comment_fg", modifiers = ["bold"] } +"variable" = { fg = "background_fg" } +"variable.builtin" = { fg = "blue" } +"warning" = { fg = "orange" } + +[palette] + +orange = "#e2a578" +pale = "#a4aecc" +purple = "#a093c8" + +black = "#1e2132" +gray = "#6b7089" +red = "#e27878" +light-red = "#e98989" +green = "#b5bf82" +light-green = "#c0ca8e" +yellow = "#e2a478" +light-yellow = "#e9b189" +blue = "#85a0c7" +light-blue = "#91acd1" +magenta = "#a093c7" +light-magenta = "#ada0d3" +cyan = "#89b9c2" +light-cyan = "#95c4ce" +white = "#c6c8d1" +light-gray = "#d2d4de" + +background_bg = "#161822" +background_fg = "#c7c9d1" +comment_fg = "#6c7189" +cursorlinenr_bg = "#3d425c" +linenr_bg = "#1f2233" +linenr_fg = "#454d73" +matchparen_bg = "#3f455f" +menusel_bg = "#5c638a" +menusel_fg = "#f0f1f5" +sel_bg = "#282d43" +statusline_bg = "#0f1117" +statusline_fg = "#828597" diff --git a/runtime/themes/iceberg-light.toml b/runtime/themes/iceberg-light.toml new file mode 100644 index 000000000..2c7ca527d --- /dev/null +++ b/runtime/themes/iceberg-light.toml @@ -0,0 +1,39 @@ +# Author : Chromo-residuum-opec + +inherits = "iceberg-dark" +"ui.menu.selected" = { fg = "background_fg", bg = "menusel_bg" } + +[palette] + +orange = "#c67439" +pale = "#505695" +purple = "#785ab5" + +black = "#dcdfe7" +gray = "#8389a3" +red = "#cd517a" +light-red = "#cc3768" +green = "#668f3d" +light-green = "#598030" +yellow = "#c57339" +light-yellow = "#b6662d" +blue = "#2e539e" +light-blue = "#22478e" +magenta = "#7759b4" +light-magenta = "#6845ad" +cyan = "#3f84a6" +light-cyan = "#327698" +white = "#33374c" +light-gray = "#262a3f" + +background_bg = "#e9e9ed" +background_fg = "#33374d" +comment_fg = "#8489a4" +cursorlinenr_bg = "#cccfe0" +linenr_bg = "#dddfe9" +linenr_fg = "#a0a5c0" +matchparen_bg = "#bec0ca" +menusel_bg = "#a9afd1" +sel_bg = "#cacdd8" +statusline_bg = "#cad0de" +statusline_fg = "#757da3" diff --git a/runtime/tutor b/runtime/tutor index 431d24f8f..98b9f3af1 100644 --- a/runtime/tutor +++ b/runtime/tutor @@ -1044,8 +1044,8 @@ lines. 1. Move the cursor to the line marked '-->' below. 2. Select both lines with xx or 2x. 3. Type s to select, type "would" and enter. - 4. Use ( and ) to cycle the primary selection and remove the - very second "would" with Alt-, . + 4. Use ( and ) to cycle the primary selection and deselect + the second "would" with Alt-, . 5. Type c "wood" to change the remaining "would"s to "wood". --> How much would would a wouldchuck chuck diff --git a/xtask/src/docgen.rs b/xtask/src/docgen.rs index 034d9918e..18c145d50 100644 --- a/xtask/src/docgen.rs +++ b/xtask/src/docgen.rs @@ -1,9 +1,9 @@ use crate::helpers; use crate::path; use crate::DynError; - use helix_term::commands::TYPABLE_COMMAND_LIST; use helix_term::health::TsFeature; +use std::collections::HashSet; use std::fs; pub const TYPABLE_COMMANDS_MD_OUTPUT: &str = "typable-cmd.md"; @@ -95,14 +95,25 @@ pub fn lang_features() -> Result { .to_owned(), ); } - row.push( - lc.language_servers - .iter() - .filter_map(|ls| config.language_server.get(&ls.name)) - .map(|s| md_mono(&s.command.clone())) - .collect::>() - .join(", "), - ); + let mut seen_commands = HashSet::new(); + let mut commands = String::new(); + for ls_config in lc + .language_servers + .iter() + .filter_map(|ls| config.language_server.get(&ls.name)) + { + let command = &ls_config.command; + if !seen_commands.insert(command) { + continue; + } + + if !commands.is_empty() { + commands.push_str(", "); + } + + commands.push_str(&md_mono(command)); + } + row.push(commands); md.push_str(&md_table_row(&row)); row.clear();