mirror of
https://github.com/helix-editor/helix.git
synced 2024-11-24 10:26:18 +04:00
Merge branch 'master' into reverse-query-precedence-ordering
This commit is contained in:
commit
d15fab75ea
12
.github/workflows/build.yml
vendored
12
.github/workflows/build.yml
vendored
@ -6,7 +6,7 @@ on:
|
||||
- master
|
||||
merge_group:
|
||||
schedule:
|
||||
- cron: '00 01 * * *'
|
||||
- cron: "00 01 * * *"
|
||||
|
||||
jobs:
|
||||
check:
|
||||
@ -16,11 +16,9 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install stable toolchain
|
||||
uses: helix-editor/rust-toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
override: true
|
||||
uses: dtolnay/rust-toolchain@1.70
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
@ -110,6 +108,9 @@ jobs:
|
||||
- name: Validate queries
|
||||
run: cargo xtask query-check
|
||||
|
||||
- name: Validate themes
|
||||
run: cargo xtask theme-check
|
||||
|
||||
- name: Generate docs
|
||||
run: cargo xtask docgen
|
||||
|
||||
@ -119,4 +120,3 @@ jobs:
|
||||
git diff-files --quiet \
|
||||
|| (echo "Run 'cargo xtask docgen', commit the changes and push again" \
|
||||
&& exit 1)
|
||||
|
||||
|
4
.github/workflows/cachix.yml
vendored
4
.github/workflows/cachix.yml
vendored
@ -14,10 +14,10 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install nix
|
||||
uses: cachix/install-nix-action@v26
|
||||
uses: cachix/install-nix-action@v30
|
||||
|
||||
- name: Authenticate with Cachix
|
||||
uses: cachix/cachix-action@v14
|
||||
uses: cachix/cachix-action@v15
|
||||
with:
|
||||
name: helix
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
|
204
CHANGELOG.md
204
CHANGELOG.md
@ -1,3 +1,207 @@
|
||||
# 24.07 (2024-07-14)
|
||||
|
||||
Thanks to all of the contributors! This release has changes from 160 contributors.
|
||||
|
||||
Breaking changes:
|
||||
|
||||
Features:
|
||||
|
||||
- Add a textobject for entries/elements of list-like things ([#8150](https://github.com/helix-editor/helix/pull/8150))
|
||||
- Add a picker showing files changed in VCS ([#5645](https://github.com/helix-editor/helix/pull/5645))
|
||||
- Use a temporary file for writes ([#9236](https://github.com/helix-editor/helix/pull/9236), [#10339](https://github.com/helix-editor/helix/pull/10339), [#10790](https://github.com/helix-editor/helix/pull/10790))
|
||||
- Allow cycling through LSP signature-help signatures with `A-n`/`A-p` ([#9974](https://github.com/helix-editor/helix/pull/9974), [#10654](https://github.com/helix-editor/helix/pull/10654), [#10655](https://github.com/helix-editor/helix/pull/10655))
|
||||
- Use tree-sitter when finding matching brackets and closest pairs ([#8294](https://github.com/helix-editor/helix/pull/8294), [#10613](https://github.com/helix-editor/helix/pull/10613), [#10777](https://github.com/helix-editor/helix/pull/10777))
|
||||
- Auto-save all buffers after a delay ([#10899](https://github.com/helix-editor/helix/pull/10899), [#11047](https://github.com/helix-editor/helix/pull/11047))
|
||||
|
||||
Commands:
|
||||
|
||||
- `select_all_siblings` (`A-a`) - select all siblings of each selection ([87c4161](https://github.com/helix-editor/helix/commit/87c4161))
|
||||
- `select_all_children` (`A-I`) - select all children of each selection ([fa67c5c](https://github.com/helix-editor/helix/commit/fa67c5c))
|
||||
- `:read` - insert the contents of the given file at each selection ([#10447](https://github.com/helix-editor/helix/pull/10447))
|
||||
|
||||
Usability improvements:
|
||||
|
||||
- Support scrolling popup contents using the mouse ([#10053](https://github.com/helix-editor/helix/pull/10053))
|
||||
- Sort the jumplist picker so that most recent items come first ([#10095](https://github.com/helix-editor/helix/pull/10095))
|
||||
- Improve `goto_file`'s (`gf`) automatic path detection strategy ([#9065](https://github.com/helix-editor/helix/pull/9065))
|
||||
- Respect language server definition order in code action menu ([#9590](https://github.com/helix-editor/helix/pull/9590))
|
||||
- Allow using a count with `goto_next_buffer` (`gn`) and `goto_previous_buffer` (`gp`) ([#10463](https://github.com/helix-editor/helix/pull/10463))
|
||||
- Improve the positioning of popups ([#10257](https://github.com/helix-editor/helix/pull/10257), [#10573](https://github.com/helix-editor/helix/pull/10573))
|
||||
- Reset all changes overlapped by selections in `:reset-diff-change` ([#10728](https://github.com/helix-editor/helix/pull/10728))
|
||||
- Await pending writes in the `suspend` command (`C-z`) ([#10797](https://github.com/helix-editor/helix/pull/10797))
|
||||
- Remove special handling of line ending characters in `replace` (`r`) ([#10786](https://github.com/helix-editor/helix/pull/10786))
|
||||
- Use the selected register as a history register for `rename_symbol` (`<space>r`) ([#10932](https://github.com/helix-editor/helix/pull/10932))
|
||||
- Use the configured insert-mode cursor for prompt entry ([#10945](https://github.com/helix-editor/helix/pull/10945))
|
||||
- Add tilted quotes to the matching brackets list ([#10971](https://github.com/helix-editor/helix/pull/10971))
|
||||
- Prevent improper files like `/dev/urandom` from being used as file arguments ([#10733](https://github.com/helix-editor/helix/pull/10733))
|
||||
- Allow multiple language servers to provide `:lsp-workspace-command`s ([#10176](https://github.com/helix-editor/helix/pull/10176), [#11105](https://github.com/helix-editor/helix/pull/11105))
|
||||
- Trim output of commands executed through `:pipe` ([#10952](https://github.com/helix-editor/helix/pull/10952))
|
||||
|
||||
Fixes:
|
||||
|
||||
- Use `lldb-dap` instead of `lldb-vscode` in default DAP configuration ([#10091](https://github.com/helix-editor/helix/pull/10091))
|
||||
- Fix creation of uneven splits when closing windows ([#10004](https://github.com/helix-editor/helix/pull/10004))
|
||||
- Avoid setting a register in `delete_selection_noyank`, fixing the command's use in command sequences ([#10050](https://github.com/helix-editor/helix/pull/10050), [#10148](https://github.com/helix-editor/helix/pull/10148))
|
||||
- Fix jump alphabet config resetting when using `:config-reload` ([#10156](https://github.com/helix-editor/helix/pull/10156))
|
||||
- Overlay LSP unnecessary/deprecated diagnostic tag highlights onto regular diagnostic highlights ([#10084](https://github.com/helix-editor/helix/pull/10084))
|
||||
- Fix crash on LSP text edits with invalid ranges ([#9649](https://github.com/helix-editor/helix/pull/9649))
|
||||
- Handle partial failure when sending multiple LSP `textDocument/didSave` notifications ([#10168](https://github.com/helix-editor/helix/pull/10168))
|
||||
- Fix off-by-one error for completion-replace option ([#10279](https://github.com/helix-editor/helix/pull/10279))
|
||||
- Fix mouse right-click selection behavior ([#10067](https://github.com/helix-editor/helix/pull/10067))
|
||||
- Fix scrolling to the end within a popup ([#10181](https://github.com/helix-editor/helix/pull/10181))
|
||||
- Fix jump label highlight locations when jumping in non-ascii text ([#10317](https://github.com/helix-editor/helix/pull/10317))
|
||||
- Fix crashes from tree-sitter query captures that return non-grapheme aligned ranges ([#10310](https://github.com/helix-editor/helix/pull/10310))
|
||||
- Include VCS change in `mi`/`ma` textobject infobox ([#10496](https://github.com/helix-editor/helix/pull/10496))
|
||||
- Override crossterm's support for `NO_COLOR` ([#10514](https://github.com/helix-editor/helix/pull/10514))
|
||||
- Respect mode when starting a search ([#10505](https://github.com/helix-editor/helix/pull/10505))
|
||||
- Simplify first-in-line computation for indent queries ([#10527](https://github.com/helix-editor/helix/pull/10527))
|
||||
- Ignore .svn version controlled files in file pickers ([#10536](https://github.com/helix-editor/helix/pull/10536))
|
||||
- Fix overloading language servers with `completionItem/resolve` requests ([38ee845](https://github.com/helix-editor/helix/commit/38ee845), [#10873](https://github.com/helix-editor/helix/pull/10873))
|
||||
- Specify direction for `select_next_sibling` / `select_prev_sibling` ([#10542](https://github.com/helix-editor/helix/pull/10542))
|
||||
- Fix restarting language servers ([#10614](https://github.com/helix-editor/helix/pull/10614))
|
||||
- Don't stop at the first URL in `goto_file` ([#10622](https://github.com/helix-editor/helix/pull/10622))
|
||||
- Fix overflows in window size calculations for small terminals ([#10620](https://github.com/helix-editor/helix/pull/10620))
|
||||
- Allow missing or empty completion lists in DAP ([#10332](https://github.com/helix-editor/helix/pull/10332))
|
||||
- Revert statusline refactor that could cause the statusline to blank out on files with long paths ([#10642](https://github.com/helix-editor/helix/pull/10642))
|
||||
- Synchronize files after writing ([#10735](https://github.com/helix-editor/helix/pull/10735))
|
||||
- Avoid `cnorm` for cursor-type detection in certain terminals ([#10769](https://github.com/helix-editor/helix/pull/10769))
|
||||
- Reset inlay hints when stopping or restarting a language server ([#10741](https://github.com/helix-editor/helix/pull/10741))
|
||||
- Fix logic for updating `--version` when development VCS HEAD changes ([#10896](https://github.com/helix-editor/helix/pull/10896))
|
||||
- Set a max value for the count ([#10930](https://github.com/helix-editor/helix/pull/10930))
|
||||
- Deserialize number IDs in DAP module types ([#10943](https://github.com/helix-editor/helix/pull/10943))
|
||||
- Fix the behavior of `jump_backwords` when the jumplist is at capacity ([#10968](https://github.com/helix-editor/helix/pull/10968))
|
||||
- Fix injection layer heritage tracking for reused tree-sitter injection layers ([#1098](https://github.com/helix-editor/helix/pull/1098))
|
||||
- Fix pluralization of "buffers" in the statusline for `:q`, `:q!`, `:wq` ([#11018](https://github.com/helix-editor/helix/pull/11018))
|
||||
- Declare LSP formatting client capabilities ([#11064](https://github.com/helix-editor/helix/pull/11064))
|
||||
- Commit uncommitted changes before attempting undo/earlier ([#11090](https://github.com/helix-editor/helix/pull/11090))
|
||||
- Expand tilde for selected paths in `goto_file` ([#10964](https://github.com/helix-editor/helix/pull/10964))
|
||||
- Commit undo checkpoints before `:write[-all]`, fixing the modification indicator ([#11062](https://github.com/helix-editor/helix/pull/11062))
|
||||
|
||||
Themes:
|
||||
|
||||
- Add jump label styles to `nightfox` ([#10052](https://github.com/helix-editor/helix/pull/10052))
|
||||
- Add jump label styles to Solarized themes ([#10056](https://github.com/helix-editor/helix/pull/10056))
|
||||
- Add jump label styles to `cyan_light` ([#10058](https://github.com/helix-editor/helix/pull/10058))
|
||||
- Add jump label styles to `onelight` ([#10061](https://github.com/helix-editor/helix/pull/10061))
|
||||
- Add `flexoki-dark` and `flexoki-light` ([#10002](https://github.com/helix-editor/helix/pull/10002))
|
||||
- Add default theme keys for LSP diagnostics tags to existing themes ([#10064](https://github.com/helix-editor/helix/pull/10064))
|
||||
- Add jump label styles to base16 themes ([#10076](https://github.com/helix-editor/helix/pull/10076))
|
||||
- Dim primary selection in `kanagawa` ([#10094](https://github.com/helix-editor/helix/pull/10094), [#10500](https://github.com/helix-editor/helix/pull/10500))
|
||||
- Add jump label styles to tokyonight themes ([#10106](https://github.com/helix-editor/helix/pull/10106))
|
||||
- Add jump label styles to papercolor themes ([#10104](https://github.com/helix-editor/helix/pull/10104))
|
||||
- Add jump label styles to Darcula themes ([#10116](https://github.com/helix-editor/helix/pull/10116))
|
||||
- Add jump label styles to `autumn` ([#10134](https://github.com/helix-editor/helix/pull/10134))
|
||||
- Add jump label styles to Ayu themes ([#10133](https://github.com/helix-editor/helix/pull/10133))
|
||||
- Add jump label styles to `dark_high_contrast` ([#10133](https://github.com/helix-editor/helix/pull/10133))
|
||||
- Update material themes ([#10290](https://github.com/helix-editor/helix/pull/10290))
|
||||
- Add jump label styles to `varua` ([#10299](https://github.com/helix-editor/helix/pull/10299))
|
||||
- Add ruler style to `adwaita-dark` ([#10260](https://github.com/helix-editor/helix/pull/10260))
|
||||
- Remove `ui.highlight` effects from `solarized_dark` ([#10261](https://github.com/helix-editor/helix/pull/10261))
|
||||
- Fix statusline color in material themes ([#10308](https://github.com/helix-editor/helix/pull/10308))
|
||||
- Brighten `nord` selection highlight ([#10307](https://github.com/helix-editor/helix/pull/10307))
|
||||
- Add inlay-hint styles to monokai themes ([#10334](https://github.com/helix-editor/helix/pull/10334))
|
||||
- Add bufferline and cursorline colors to `vim_dark_high_contrast` ([#10444](https://github.com/helix-editor/helix/pull/10444))
|
||||
- Switch themes with foreground rulers to background ([#10309](https://github.com/helix-editor/helix/pull/10309))
|
||||
- Fix statusline colors for `everblush` ([#10394](https://github.com/helix-editor/helix/pull/10394))
|
||||
- Use `yellow1` for `gruvbox` warning diagnostics ([#10506](https://github.com/helix-editor/helix/pull/10506))
|
||||
- Add jump label styles to Modus themes ([#10538](https://github.com/helix-editor/helix/pull/10538))
|
||||
- Refactor `dark_plus` and switch maintainers ([#10543](https://github.com/helix-editor/helix/pull/10543), [#10574](https://github.com/helix-editor/helix/pull/10574))
|
||||
- Add debug highlights to `dark_plus` ([#10593](https://github.com/helix-editor/helix/pull/10593))
|
||||
- Fix per-mode cursor colors in the default theme ([#10608](https://github.com/helix-editor/helix/pull/10608))
|
||||
- Add `tag` and `attribute` highlights to `dark_high_contrast` ([#10705](https://github.com/helix-editor/helix/pull/10705))
|
||||
- Improve readability of virtual text with `noctis` theme ([#10910](https://github.com/helix-editor/helix/pull/10910))
|
||||
- Sync `catppuccin` themes with upstream ([#10954](https://github.com/helix-editor/helix/pull/10954))
|
||||
- Improve jump colors for `github_dark` themes ([#10946](https://github.com/helix-editor/helix/pull/10946))
|
||||
- Add modeline and default virtual highlights to `base16_default` ([#10858](https://github.com/helix-editor/helix/pull/10858))
|
||||
- Add `iroaseta` ([#10381](https://github.com/helix-editor/helix/pull/10381))
|
||||
- Refactor `gruvbox` ([#10773](https://github.com/helix-editor/helix/pull/10773), [#11071](https://github.com/helix-editor/helix/pull/11071))
|
||||
- Add cursorcolumn and cursorline to `base16_transparent` ([#11099](https://github.com/helix-editor/helix/pull/11099))
|
||||
- Update cursorline color for `fleet_dark` ([#11046](https://github.com/helix-editor/helix/pull/11046))
|
||||
- Add `kanagawa-dragon` ([#10172](https://github.com/helix-editor/helix/pull/10172))
|
||||
|
||||
New languages:
|
||||
|
||||
- BitBake ([#10010](https://github.com/helix-editor/helix/pull/10010))
|
||||
- Earthfile ([#10111](https://github.com/helix-editor/helix/pull/10111), [#10489](https://github.com/helix-editor/helix/pull/10489), [#10779](https://github.com/helix-editor/helix/pull/10779))
|
||||
- TCL ([#9837](https://github.com/helix-editor/helix/pull/9837))
|
||||
- ADL ([#10029](https://github.com/helix-editor/helix/pull/10029))
|
||||
- LDIF ([#10330](https://github.com/helix-editor/helix/pull/10330))
|
||||
- XTC ([#10448](https://github.com/helix-editor/helix/pull/10448))
|
||||
- Move ([f06a166](https://github.com/helix-editor/helix/commit/f06a166))
|
||||
- Pest ([#10616](https://github.com/helix-editor/helix/pull/10616))
|
||||
- GJS/GTS ([#9940](https://github.com/helix-editor/helix/pull/9940))
|
||||
- Inko ([#10656](https://github.com/helix-editor/helix/pull/10656))
|
||||
- Mojo ([#10743](https://github.com/helix-editor/helix/pull/10743))
|
||||
- Elisp ([#10644](https://github.com/helix-editor/helix/pull/10644))
|
||||
|
||||
Updated languages and queries:
|
||||
|
||||
- Recognize `mkdn` files as markdown ([#10065](https://github.com/helix-editor/helix/pull/10065))
|
||||
- Add comment injections for Gleam ([#10062](https://github.com/helix-editor/helix/pull/10062))
|
||||
- Recognize BuildKite commands in YAML injections ([#10090](https://github.com/helix-editor/helix/pull/10090))
|
||||
- Add F# block comment token configuration ([#10108](https://github.com/helix-editor/helix/pull/10108))
|
||||
- Update tree-sitter-templ and queries ([#10114](https://github.com/helix-editor/helix/pull/10114))
|
||||
- Recognize `Tiltfile` as Starlark ([#10072](https://github.com/helix-editor/helix/pull/10072))
|
||||
- Remove `todo.txt` from files recognized as todotxt ([5fece00](https://github.com/helix-editor/helix/commit/5fece00))
|
||||
- Highlight `type` keyword in Python from PEP695 ([#10165](https://github.com/helix-editor/helix/pull/10165))
|
||||
- Update tree-sitter-koka, add language server config ([#10119](https://github.com/helix-editor/helix/pull/10119))
|
||||
- Recognize node and Python history files ([#10120](https://github.com/helix-editor/helix/pull/10120))
|
||||
- Recognize more shell files as bash ([#10120](https://github.com/helix-editor/helix/pull/10120))
|
||||
- Recognize the bun shebang as typescript ([#10120](https://github.com/helix-editor/helix/pull/10120))
|
||||
- Add a configuration for the angular language server ([#10166](https://github.com/helix-editor/helix/pull/10166))
|
||||
- Add textobject queries for Solidity ([#10318](https://github.com/helix-editor/helix/pull/10318))
|
||||
- Recognize `meson.options` as Meson ([#10323](https://github.com/helix-editor/helix/pull/10323))
|
||||
- Improve Solidity highlighting ([4fc0a4d](https://github.com/helix-editor/helix/commit/4fc0a4d))
|
||||
- Recognize `_.tpl` files as Helm ([#10344](https://github.com/helix-editor/helix/pull/10344))
|
||||
- Update tree-sitter-ld and highlights ([#10379](https://github.com/helix-editor/helix/pull/10379))
|
||||
- Add `lldb-dap` configuration for Odin ([#10175](https://github.com/helix-editor/helix/pull/10175))
|
||||
- Update tree-sitter-rust ([#10365](https://github.com/helix-editor/helix/pull/10365))
|
||||
- Update tree-sitter-typst ([#10321](https://github.com/helix-editor/helix/pull/10321))
|
||||
- Recognize `hyprpaper.conf`, `hypridle.conf` and `hyprlock.conf` as Hyprlang ([#10383](https://github.com/helix-editor/helix/pull/10383))
|
||||
- Improve HTML highlighting ([#10503](https://github.com/helix-editor/helix/pull/10503))
|
||||
- Add `rust-script` and `cargo` as shebangs for Rust ([#10484](https://github.com/helix-editor/helix/pull/10484))
|
||||
- Fix precedence of tag highlights in Svelte ([#10487](https://github.com/helix-editor/helix/pull/10487))
|
||||
- Update tree-sitter-bash ([#10526](https://github.com/helix-editor/helix/pull/10526))
|
||||
- Recognize `*.ignore` files as ignore ([#10579](https://github.com/helix-editor/helix/pull/10579))
|
||||
- Add configuration to enable inlay hints in metals ([#10597](https://github.com/helix-editor/helix/pull/10597))
|
||||
- Enable highlighting private members in ECMA languages ([#10554](https://github.com/helix-editor/helix/pull/10554))
|
||||
- Add comment injection to typst queries ([#10628](https://github.com/helix-editor/helix/pull/10628))
|
||||
- Add textobject queries for Hurl ([#10594](https://github.com/helix-editor/helix/pull/10594))
|
||||
- Add `try` keyword to Rust ([#10641](https://github.com/helix-editor/helix/pull/10641))
|
||||
- Add `is not` and `not in` to Python highlights ([#10647](https://github.com/helix-editor/helix/pull/10647))
|
||||
- Remove ' and ⟨⟩ from Lean autopair configuration ([#10688](https://github.com/helix-editor/helix/pull/10688))
|
||||
- Match TOML/YAML highlights for JSON keys ([#10676](https://github.com/helix-editor/helix/pull/10676))
|
||||
- Recognize WORKSPACE files as Starlark ([#10713](https://github.com/helix-editor/helix/pull/10713))
|
||||
- Switch Odin tree-sitter grammar and highlights ([#10698](https://github.com/helix-editor/helix/pull/10698))
|
||||
- Update `tree-sitter-slint` ([#10749](https://github.com/helix-editor/helix/pull/10749))
|
||||
- Add missing operators for Solidity highlights ([#10735](https://github.com/helix-editor/helix/pull/10735))
|
||||
- Update `tree-sitter-inko` ([#10805](https://github.com/helix-editor/helix/pull/10805))
|
||||
- Add `py`, `hs`, `rs` and `typ` injection regexes ([#10785](https://github.com/helix-editor/helix/pull/10785))
|
||||
- Update Swift grammar and queries ([#10802](https://github.com/helix-editor/helix/pull/10802))
|
||||
- Update Cairo grammar and queries ([#10919](https://github.com/helix-editor/helix/pull/10919), [#11067](https://github.com/helix-editor/helix/pull/11067))
|
||||
- Update Rust grammar ([#10973](https://github.com/helix-editor/helix/pull/10973))
|
||||
- Add block comment tokens for typst ([#10955](https://github.com/helix-editor/helix/pull/10955))
|
||||
- Recognize `jsonl` as JSON ([#11004](https://github.com/helix-editor/helix/pull/11004))
|
||||
- Add rulers and text-width at 100 columns for Lean language ([#10969](https://github.com/helix-editor/helix/pull/10969))
|
||||
- Improve VDHL highlights ([#10845](https://github.com/helix-editor/helix/pull/10845))
|
||||
- Recognize `hsc` as Haskell ([#11074](https://github.com/helix-editor/helix/pull/11074))
|
||||
- Fix heredoc and `$'<ansi_string>'` highlights in Bash ([#11118](https://github.com/helix-editor/helix/pull/11118))
|
||||
- Add LSP configuration for `basedpyright` ([#11121](https://github.com/helix-editor/helix/pull/11121))
|
||||
- Recognize `npmrc` and `.nmprc` files as INI ([#11131](https://github.com/helix-editor/helix/pull/11131))
|
||||
- Recognize `~/.config/git/ignore` as git-ignore ([#11131](https://github.com/helix-editor/helix/pull/11131))
|
||||
- Recognize `pdm.lock` and `uv.lock` as TOML ([#11131](https://github.com/helix-editor/helix/pull/11131))
|
||||
- Recognize `.yml` as well as `.yaml` for Helm chart templates ([#11135](https://github.com/helix-editor/helix/pull/11135))
|
||||
- Add regex injections for Bash ([#11112](https://github.com/helix-editor/helix/pull/11112))
|
||||
- Update tree-sitter-todo ([#11097](https://github.com/helix-editor/helix/pull/11097))
|
||||
|
||||
Packaging:
|
||||
|
||||
- Make `Helix.appdata.xml` spec-compliant ([#10051](https://github.com/helix-editor/helix/pull/10051))
|
||||
- Expose all flake outputs through flake-compat ([#10673](https://github.com/helix-editor/helix/pull/10673))
|
||||
- Bump the MSRV to 1.74.0 ([#10714](https://github.com/helix-editor/helix/pull/10714))
|
||||
- Improve FiSH completions ([#10853](https://github.com/helix-editor/helix/pull/10853))
|
||||
- Improve ZSH completions ([#10853](https://github.com/helix-editor/helix/pull/10853))
|
||||
|
||||
# 24.03 (2024-03-30)
|
||||
|
||||
As always, a big thank you to all of the contributors! This release saw changes from 125 contributors.
|
||||
|
1233
Cargo.lock
generated
1233
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -5,6 +5,7 @@ members = [
|
||||
"helix-view",
|
||||
"helix-term",
|
||||
"helix-tui",
|
||||
"helix-lsp-types",
|
||||
"helix-lsp",
|
||||
"helix-event",
|
||||
"helix-dap",
|
||||
@ -38,11 +39,12 @@ package.helix-term.opt-level = 2
|
||||
|
||||
[workspace.dependencies]
|
||||
tree-sitter = { version = "0.22" }
|
||||
nucleo = "0.2.0"
|
||||
nucleo = "0.5.0"
|
||||
slotmap = "1.0.7"
|
||||
thiserror = "1.0"
|
||||
|
||||
[workspace.package]
|
||||
version = "24.3.0"
|
||||
version = "24.7.0"
|
||||
edition = "2021"
|
||||
authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
|
||||
categories = ["editor"]
|
||||
|
@ -37,8 +37,8 @@ # Features
|
||||
- Built-in language server support
|
||||
- Smart, incremental syntax highlighting and code editing via tree-sitter
|
||||
|
||||
It's a terminal-based editor first, but I'd like to explore a custom renderer
|
||||
(similar to Emacs) in wgpu or skulpin.
|
||||
Although it's primarily a terminal-based editor, I am interested in exploring
|
||||
a custom renderer (similar to Emacs) using wgpu or skulpin.
|
||||
|
||||
Note: Only certain languages have indentation definitions at the moment. Check
|
||||
`runtime/queries/<lang>/` for `indents.scm`.
|
||||
@ -47,7 +47,7 @@ # Installation
|
||||
|
||||
[Installation documentation](https://docs.helix-editor.com/install.html).
|
||||
|
||||
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions)
|
||||
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix-editor.svg?exclude_unsupported=1)](https://repology.org/project/helix-editor/versions)
|
||||
|
||||
# Contributing
|
||||
|
||||
|
@ -28,6 +28,9 @@
|
||||
"label" = "magenta"
|
||||
"namespace" = "magenta"
|
||||
"ui.help" = { fg = "white", bg = "black" }
|
||||
"ui.statusline.insert" = { fg = "black", bg = "green" }
|
||||
"ui.statusline.select" = { fg = "black", bg = "blue" }
|
||||
"ui.virtual" = { fg = "gray", modifiers = ["italic"] }
|
||||
"ui.virtual.jump-label" = { fg = "blue", modifiers = ["bold", "underlined"] }
|
||||
"ui.virtual.ruler" = { bg = "black" }
|
||||
|
||||
|
@ -10,6 +10,7 @@ # Summary
|
||||
- [Surround](./surround.md)
|
||||
- [Textobjects](./textobjects.md)
|
||||
- [Syntax aware motions](./syntax-aware-motions.md)
|
||||
- [Pickers](./pickers.md)
|
||||
- [Keymap](./keymap.md)
|
||||
- [Commands](./commands.md)
|
||||
- [Language support](./lang-support.md)
|
||||
|
@ -148,6 +148,12 @@ ### Configure the desktop shortcut
|
||||
cp contrib/Helix.desktop ~/.local/share/applications
|
||||
cp contrib/helix.png ~/.icons # or ~/.local/share/icons
|
||||
```
|
||||
It is recommended to convert the links in the `.desktop` file to absolute paths to avoid potential problems:
|
||||
|
||||
```sh
|
||||
sed -i -e "s|Exec=hx %F|Exec=$(readlink -f ~/.cargo/bin/hx) %F|g" \
|
||||
-e "s|Icon=helix|Icon=$(readlink -f ~/.icons/helix.png)|g" ~/.local/share/applications/Helix.desktop
|
||||
```
|
||||
|
||||
To use another terminal than the system default, you can modify the `.desktop`
|
||||
file. For example, to use `kitty`:
|
||||
|
@ -16,6 +16,7 @@ ## Editor
|
||||
- [`[editor.gutters.spacer]` Section](#editorguttersspacer-section)
|
||||
- [`[editor.soft-wrap]` Section](#editorsoft-wrap-section)
|
||||
- [`[editor.smart-tab]` Section](#editorsmart-tab-section)
|
||||
- [`[editor.inline-diagnostics]` Section](#editorinline-diagnostics-section)
|
||||
|
||||
### `[editor]` Section
|
||||
|
||||
@ -32,7 +33,6 @@ ### `[editor]` Section
|
||||
| `gutters` | Gutters to display: Available are `diagnostics` and `diff` and `line-numbers` and `spacer`, note that `diagnostics` also includes other features like breakpoints, 1-width padding will be inserted if gutters is non-empty | `["diagnostics", "spacer", "line-numbers", "spacer", "diff"]` |
|
||||
| `auto-completion` | Enable automatic pop up of auto-completion | `true` |
|
||||
| `auto-format` | Enable automatic formatting on save | `true` |
|
||||
| `auto-save` | Enable automatic saving on the focus moving away from Helix. Requires [focus event support](https://github.com/helix-editor/helix/wiki/Terminal-Support) from your terminal | `false` |
|
||||
| `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. | `250` |
|
||||
| `completion-timeout` | Time in milliseconds after typing a word character before completions are shown, set to 5 for instant. | `250` |
|
||||
| `preview-completion-insert` | Whether to apply completion item instantly when selected | `true` |
|
||||
@ -51,6 +51,7 @@ ### `[editor]` Section
|
||||
| `popup-border` | Draw border around `popup`, `menu`, `all`, or `none` | `none` |
|
||||
| `indent-heuristic` | How the indentation for a newly inserted line is computed: `simple` just copies the indentation level from the previous line, `tree-sitter` computes the indentation based on the syntax tree and `hybrid` combines both approaches. If the chosen heuristic is not available, a different one will be used as a fallback (the fallback order being `hybrid` -> `tree-sitter` -> `simple`). | `hybrid`
|
||||
| `jump-label-alphabet` | The characters that are used to generate two character jump labels. Characters at the start of the alphabet are used first. | `"abcdefghijklmnopqrstuvwxyz"`
|
||||
| `end-of-line-diagnostics` | Minimum severity of diagnostics to render at the end of the line. Set to `disable` to disable entirely. Refer to the setting about `inline-diagnostics` for more details | "disable"
|
||||
|
||||
### `[editor.statusline]` Section
|
||||
|
||||
@ -222,6 +223,16 @@ ### `[editor.auto-pairs]` Section
|
||||
'<' = '>'
|
||||
```
|
||||
|
||||
### `[editor.auto-save]` Section
|
||||
|
||||
Control auto save behavior.
|
||||
|
||||
| Key | Description | Default |
|
||||
|--|--|---------|
|
||||
| `focus-lost` | Enable automatic saving on the focus moving away from Helix. Requires [focus event support](https://github.com/helix-editor/helix/wiki/Terminal-Support) from your terminal | `false` |
|
||||
| `after-delay.enable` | Enable automatic saving after `auto-save.after-delay.timeout` milliseconds have passed since last edit. | `false` |
|
||||
| `after-delay.timeout` | Time in milliseconds since last edit before auto save timer triggers. | `3000` |
|
||||
|
||||
### `[editor.search]` Section
|
||||
|
||||
Search specific options.
|
||||
@ -384,3 +395,41 @@ ### `[editor.smart-tab]` Section
|
||||
tab = "extend_parent_node_end"
|
||||
S-tab = "extend_parent_node_start"
|
||||
```
|
||||
|
||||
### `[editor.inline-diagnostics]` Section
|
||||
|
||||
Options for rendering diagnostics inside the text like shown below
|
||||
|
||||
```
|
||||
fn main() {
|
||||
let foo = bar;
|
||||
└─ no such value in this scope
|
||||
}
|
||||
````
|
||||
|
||||
| Key | Description | Default |
|
||||
|------------|-------------|---------|
|
||||
| `cursor-line` | The minimum severity that a diagnostic must have to be shown inline on the line that contains the primary cursor. Set to `disable` to not show any diagnostics inline. This option does not have any effect when in insert-mode and will only take effect 350ms after moving the cursor to a different line. | `"disable"` |
|
||||
| `other-lines` | The minimum severity that a diagnostic must have to be shown inline on a line that does not contain the cursor-line. Set to `disable` to not show any diagnostics inline. | `"disable"` |
|
||||
| `prefix-len` | How many horizontal bars `─` are rendered before the diagnostic text. | `1` |
|
||||
| `max-wrap` | Equivalent of the `editor.soft-wrap.max-wrap` option for diagnostics. | `20` |
|
||||
| `max-diagnostics` | Maximum number of diagnostics to render inline for a given line | `10` |
|
||||
|
||||
The (first) diagnostic with the highest severity that is not shown inline is rendered at the end of the line (as long as its severity is higher than the `end-of-line-diagnostics` config option):
|
||||
|
||||
```
|
||||
fn main() {
|
||||
let baz = 1;
|
||||
let foo = bar; a local variable with a similar name exists: baz
|
||||
└─ no such value in this scope
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
The new diagnostic rendering is not yet enabled by default. As soon as end of line or inline diagnostics are enabled the old diagnostics rendering is automatically disabled. The recommended default setting are:
|
||||
|
||||
```
|
||||
end-of-line-diagnostics = "hint"
|
||||
[editor.inline-diagnostics]
|
||||
cursor-line = "warning" # show warnings and errors on the cursorline inline
|
||||
```
|
||||
|
@ -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 | ✓ | | | |
|
||||
@ -19,6 +19,7 @@
|
||||
| cairo | ✓ | ✓ | ✓ | `cairo-language-server` |
|
||||
| capnp | ✓ | | ✓ | |
|
||||
| cel | ✓ | | | |
|
||||
| circom | ✓ | | | `circom-lsp` |
|
||||
| clojure | ✓ | | | `clojure-lsp` |
|
||||
| cmake | ✓ | ✓ | ✓ | `cmake-language-server` |
|
||||
| comment | ✓ | | | |
|
||||
@ -28,26 +29,29 @@
|
||||
| crystal | ✓ | ✓ | | `crystalline` |
|
||||
| css | ✓ | | ✓ | `vscode-css-language-server` |
|
||||
| cue | ✓ | | | `cuelsp` |
|
||||
| cylc | ✓ | ✓ | ✓ | |
|
||||
| d | ✓ | ✓ | ✓ | `serve-d` |
|
||||
| dart | ✓ | ✓ | ✓ | `dart` |
|
||||
| dbml | ✓ | | | |
|
||||
| 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 | ✓ | | | |
|
||||
| dune | ✓ | | | |
|
||||
| earthfile | ✓ | ✓ | ✓ | `earthlyls` |
|
||||
| edoc | ✓ | | | |
|
||||
| eex | ✓ | | | |
|
||||
| ejs | ✓ | | | |
|
||||
| elisp | ✓ | | | |
|
||||
| elixir | ✓ | ✓ | ✓ | `elixir-ls` |
|
||||
| elm | ✓ | ✓ | | `elm-language-server` |
|
||||
| elvish | ✓ | | | `elvish` |
|
||||
| env | ✓ | | | |
|
||||
| env | ✓ | ✓ | | |
|
||||
| erb | ✓ | | | |
|
||||
| erlang | ✓ | ✓ | | `erlang_ls` |
|
||||
| erlang | ✓ | ✓ | | `erlang_ls`, `elp` |
|
||||
| esdl | ✓ | | | |
|
||||
| fidl | ✓ | | | |
|
||||
| fish | ✓ | ✓ | ✓ | |
|
||||
@ -57,18 +61,19 @@
|
||||
| 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` |
|
||||
| gleam | ✓ | ✓ | | `gleam` |
|
||||
| glimmer | ✓ | | | `ember-language-server` |
|
||||
| glsl | ✓ | ✓ | ✓ | |
|
||||
| glsl | ✓ | ✓ | ✓ | `glsl_analyzer` |
|
||||
| gn | ✓ | | | |
|
||||
| go | ✓ | ✓ | ✓ | `gopls`, `golangci-lint-langserver` |
|
||||
| godot-resource | ✓ | | | |
|
||||
| godot-resource | ✓ | ✓ | | |
|
||||
| gomod | ✓ | | | `gopls` |
|
||||
| gotmpl | ✓ | | | `gopls` |
|
||||
| gowork | ✓ | | | `gopls` |
|
||||
@ -81,10 +86,10 @@
|
||||
| hcl | ✓ | ✓ | ✓ | `terraform-ls` |
|
||||
| heex | ✓ | ✓ | | `elixir-ls` |
|
||||
| helm | ✓ | | | `helm_ls` |
|
||||
| hocon | ✓ | | ✓ | |
|
||||
| hocon | ✓ | ✓ | ✓ | |
|
||||
| hoon | ✓ | | | |
|
||||
| hosts | ✓ | | | |
|
||||
| html | ✓ | | | `vscode-html-language-server` |
|
||||
| html | ✓ | | | `vscode-html-language-server`, `superhtml` |
|
||||
| hurl | ✓ | ✓ | ✓ | |
|
||||
| hyprlang | ✓ | | ✓ | |
|
||||
| idris | | | | `idris2-lsp` |
|
||||
@ -95,6 +100,8 @@
|
||||
| java | ✓ | ✓ | ✓ | `jdtls` |
|
||||
| javascript | ✓ | ✓ | ✓ | `typescript-language-server` |
|
||||
| jinja | ✓ | | | |
|
||||
| jjdescription | ✓ | | | |
|
||||
| jq | ✓ | ✓ | | `jq-lsp` |
|
||||
| jsdoc | ✓ | | | |
|
||||
| json | ✓ | ✓ | ✓ | `vscode-json-language-server` |
|
||||
| json5 | ✓ | | | |
|
||||
@ -123,7 +130,7 @@
|
||||
| markdown.inline | ✓ | | | |
|
||||
| matlab | ✓ | ✓ | ✓ | |
|
||||
| mermaid | ✓ | | | |
|
||||
| meson | ✓ | | ✓ | |
|
||||
| meson | ✓ | | ✓ | `mesonlsp` |
|
||||
| mint | | | | `mint` |
|
||||
| mojo | ✓ | ✓ | ✓ | `mojo-lsp-server` |
|
||||
| move | ✓ | | | |
|
||||
@ -131,7 +138,7 @@
|
||||
| nasm | ✓ | ✓ | | |
|
||||
| nickel | ✓ | | ✓ | `nls` |
|
||||
| nim | ✓ | ✓ | ✓ | `nimlangserver` |
|
||||
| nix | ✓ | ✓ | | `nil` |
|
||||
| nix | ✓ | ✓ | | `nil`, `nixd` |
|
||||
| nu | ✓ | | | `nu` |
|
||||
| nunjucks | ✓ | | | |
|
||||
| ocaml | ✓ | | ✓ | `ocamllsp` |
|
||||
@ -154,12 +161,12 @@
|
||||
| pod | ✓ | | | |
|
||||
| ponylang | ✓ | ✓ | ✓ | |
|
||||
| powershell | ✓ | | | |
|
||||
| prisma | ✓ | | | `prisma-language-server` |
|
||||
| prisma | ✓ | ✓ | | `prisma-language-server` |
|
||||
| prolog | | | | `swipl` |
|
||||
| protobuf | ✓ | ✓ | ✓ | `bufls`, `pb` |
|
||||
| prql | ✓ | | | |
|
||||
| purescript | ✓ | ✓ | | `purescript-language-server` |
|
||||
| python | ✓ | ✓ | ✓ | `pylsp` |
|
||||
| python | ✓ | ✓ | ✓ | `ruff`, `jedi-language-server`, `pylsp` |
|
||||
| qml | ✓ | | ✓ | `qmlls` |
|
||||
| r | ✓ | | | `R` |
|
||||
| racket | ✓ | | ✓ | `racket` |
|
||||
@ -180,16 +187,17 @@
|
||||
| smali | ✓ | | ✓ | |
|
||||
| smithy | ✓ | | | `cs` |
|
||||
| sml | ✓ | | | |
|
||||
| snakemake | ✓ | | ✓ | `pylsp` |
|
||||
| solidity | ✓ | ✓ | | `solc` |
|
||||
| spicedb | ✓ | | | |
|
||||
| sql | ✓ | | | |
|
||||
| sql | ✓ | ✓ | | |
|
||||
| sshclientconfig | ✓ | | | |
|
||||
| starlark | ✓ | ✓ | | |
|
||||
| strace | ✓ | | | |
|
||||
| supercollider | ✓ | | | |
|
||||
| svelte | ✓ | | ✓ | `svelteserver` |
|
||||
| sway | ✓ | ✓ | ✓ | `forc` |
|
||||
| swift | ✓ | | | `sourcekit-lsp` |
|
||||
| swift | ✓ | ✓ | | `sourcekit-lsp` |
|
||||
| t32 | ✓ | | | |
|
||||
| tablegen | ✓ | ✓ | ✓ | |
|
||||
| tact | ✓ | ✓ | ✓ | |
|
||||
@ -197,12 +205,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 | ✓ | | ✓ | |
|
||||
@ -222,6 +232,6 @@
|
||||
| xit | ✓ | | | |
|
||||
| xml | ✓ | | ✓ | |
|
||||
| xtc | ✓ | | | |
|
||||
| yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` |
|
||||
| yaml | ✓ | ✓ | ✓ | `yaml-language-server`, `ansible-language-server` |
|
||||
| yuck | ✓ | | | |
|
||||
| zig | ✓ | ✓ | ✓ | `zls` |
|
||||
|
@ -2,7 +2,7 @@
|
||||
| --- | --- |
|
||||
| `:quit`, `:q` | Close the current view. |
|
||||
| `:quit!`, `:q!` | Force close the current view, ignoring unsaved changes. |
|
||||
| `:open`, `:o` | Open a file from disk into the current view. |
|
||||
| `:open`, `:o`, `:edit`, `:e` | Open a file from disk into the current view. |
|
||||
| `:buffer-close`, `:bc`, `:bclose` | Close the current buffer. |
|
||||
| `:buffer-close!`, `:bc!`, `:bclose!` | Close the current buffer forcefully, ignoring unsaved changes. |
|
||||
| `:buffer-close-others`, `:bco`, `:bcloseother` | Close all buffers but the currently focused one. |
|
||||
@ -72,7 +72,7 @@
|
||||
| `:sort` | Sort ranges in selection. |
|
||||
| `:rsort` | Sort ranges in selection in reverse order. |
|
||||
| `:reflow` | Hard-wrap the current selection of lines to a given width. |
|
||||
| `:tree-sitter-subtree`, `:ts-subtree` | Display tree sitter subtree under cursor, primarily for debugging queries. |
|
||||
| `:tree-sitter-subtree`, `:ts-subtree` | Display the smallest tree-sitter subtree that spans the primary selection, primarily for debugging queries. |
|
||||
| `:config-reload` | Refresh user config. |
|
||||
| `:config-open` | Open the user config.toml file. |
|
||||
| `:config-open-workspace` | Open the workspace config.toml file. |
|
||||
@ -85,6 +85,6 @@
|
||||
| `:reset-diff-change`, `:diffget`, `:diffg` | Reset the diff change at the cursor position. |
|
||||
| `:clear-register` | Clear given register. If no argument is provided, clear all registers. |
|
||||
| `:redraw` | Clear and re-render the whole UI |
|
||||
| `:move` | Move the current buffer and its corresponding file to a different path |
|
||||
| `:move`, `:mv` | Move the current buffer and its corresponding file to a different path |
|
||||
| `:yank-diagnostic` | Yank diagnostic(s) under primary cursor to register, or clipboard by default |
|
||||
| `:read`, `:r` | Load a file into buffer |
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Adding new languages to Helix
|
||||
## Adding new languages to Helix
|
||||
|
||||
In order to add a new language to Helix, you will need to follow the steps
|
||||
below.
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Adding indent queries
|
||||
## Adding indent queries
|
||||
|
||||
Helix uses tree-sitter to correctly indent new lines. This requires a tree-
|
||||
sitter grammar and an `indent.scm` query file placed in `runtime/queries/
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Adding Injection Queries
|
||||
## Adding Injection Queries
|
||||
|
||||
Writing language injection queries allows one to highlight a specific node as a different language.
|
||||
In addition to the [standard][upstream-docs] language injection options used by tree-sitter, there
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Adding textobject queries
|
||||
## Adding textobject queries
|
||||
|
||||
Helix supports textobjects that are language specific, such as functions, classes, etc.
|
||||
These textobjects require an accompanying tree-sitter grammar and a `textobjects.scm` query file
|
||||
|
@ -14,6 +14,10 @@ # Installing Helix
|
||||
## 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.
|
||||
|
@ -25,7 +25,7 @@ ## Keymap
|
||||
|
||||
> 💡 Mappings marked (**TS**) require a tree-sitter grammar for the file type.
|
||||
|
||||
> ⚠️ Some terminals' default key mappings conflict with Helix's. If any of the mappings described on this page do not work as expected, check your terminal's mappings to ensure they do not conflict. See the (wiki)[https://github.com/helix-editor/helix/wiki/Terminal-Support] for known conflicts.
|
||||
> ⚠️ Some terminals' default key mappings conflict with Helix's. If any of the mappings described on this page do not work as expected, check your terminal's mappings to ensure they do not conflict. See the [wiki](https://github.com/helix-editor/helix/wiki/Terminal-Support) for known conflicts.
|
||||
|
||||
## Normal mode
|
||||
|
||||
@ -145,6 +145,9 @@ ### Selection manipulation
|
||||
| `Alt-i`, `Alt-down` | Shrink syntax tree object selection (**TS**) | `shrink_selection` |
|
||||
| `Alt-p`, `Alt-left` | Select previous sibling node in syntax tree (**TS**) | `select_prev_sibling` |
|
||||
| `Alt-n`, `Alt-right` | Select next sibling node in syntax tree (**TS**) | `select_next_sibling` |
|
||||
| `Alt-a` | Select all sibling nodes in syntax tree (**TS**) | `select_all_siblings` |
|
||||
| `Alt-e` | Move to end of parent node in syntax tree (**TS**) | `move_parent_node_end` |
|
||||
| `Alt-b` | Move to start of parent node in syntax tree (**TS**) | `move_parent_node_start` |
|
||||
|
||||
### Search
|
||||
|
||||
@ -233,8 +236,7 @@ #### Match mode
|
||||
|
||||
Accessed by typing `m` in [normal mode](#normal-mode).
|
||||
|
||||
See the relevant section in [Usage](./usage.md) for an explanation about
|
||||
[surround](./usage.md#surround) and [textobject](./usage.md#navigating-using-tree-sitter-textobjects) usage.
|
||||
Please refer to the relevant sections for detailed explanations about [surround](./surround.md) and [textobjects](./textobjects.md).
|
||||
|
||||
| Key | Description | Command |
|
||||
| ----- | ----------- | ------- |
|
||||
@ -321,10 +323,14 @@ ##### Completion Menu
|
||||
|
||||
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
|
||||
|
||||
@ -437,6 +443,8 @@ ## Select / extend mode
|
||||
## Picker
|
||||
|
||||
Keys to use within picker. Remapping currently not supported.
|
||||
See the documentation page on [pickers](./pickers.md) for more info.
|
||||
[Prompt](#prompt) keybinds also work in pickers, except where they conflict with picker keybinds.
|
||||
|
||||
| Key | Description |
|
||||
| ----- | ------------- |
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Language Support
|
||||
## Language Support
|
||||
|
||||
The following languages and Language Servers are supported. To use
|
||||
Language Server features, you must first [configure][lsp-config-wiki] the
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Languages
|
||||
## Languages
|
||||
|
||||
Language-specific settings and settings for language servers are configured
|
||||
in `languages.toml` files.
|
||||
|
@ -17,7 +17,7 @@ ## Package managers
|
||||
- [Chocolatey](#chocolatey)
|
||||
- [MSYS2](#msys2)
|
||||
|
||||
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions)
|
||||
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix-editor.svg)](https://repology.org/project/helix-editor/versions)
|
||||
|
||||
## Linux
|
||||
|
||||
|
11
book/src/pickers.md
Normal file
11
book/src/pickers.md
Normal file
@ -0,0 +1,11 @@
|
||||
## Using pickers
|
||||
|
||||
Helix has a variety of pickers, which are interactive windows used to select various kinds of items. These include a file picker, global search picker, and more. Most pickers are accessed via keybindings in [space mode](./keymap.md#space-mode). Pickers have their own [keymap](./keymap.md#picker) for navigation.
|
||||
|
||||
### Filtering Picker Results
|
||||
|
||||
Most pickers perform fuzzy matching using [fzf syntax](https://github.com/junegunn/fzf?tab=readme-ov-file#search-syntax). Two exceptions are the global search picker, which uses regex, and the workspace symbol picker, which passes search terms to the LSP. Note that OR operations (`|`) are not currently supported.
|
||||
|
||||
If a picker shows multiple columns, you may apply the filter to a specific column by prefixing the column name with `%`. Column names can be shortened to any prefix, so `%p`, `%pa` or `%pat` all mean the same as `%path`. For example, a query of `helix %p .toml !lang` in the global search picker searches for the term "helix" within files with paths ending in ".toml" but not including "lang".
|
||||
|
||||
You can insert the contents of a [register](./registers.md) using `Ctrl-r` followed by a register name. For example, one could insert the currently selected text using `Ctrl-r`-`.`, or the directory of the current file using `Ctrl-r`-`%` followed by `Ctrl-w` to remove the last path section. The global search picker will use the contents of the [search register](./registers.md#default-registers) if you press `Enter` without typing a filter. For example, pressing `*`-`Space-/`-`Enter` will start a global search for the currently selected text.
|
@ -1,4 +1,4 @@
|
||||
# Key remapping
|
||||
## Key remapping
|
||||
|
||||
Helix currently supports one-way key remapping through a simple TOML configuration
|
||||
file. (More powerful solutions such as rebinding via commands will be
|
||||
@ -75,5 +75,20 @@ ## Special keys and modifiers
|
||||
|
||||
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.
|
||||
|
@ -64,5 +64,3 @@ ## Moving the selection with syntax-aware motions
|
||||
selection to the "func" `identifier`.
|
||||
|
||||
[lang-support]: ./lang-support.md
|
||||
[unimpaired-keybinds]: ./keymap.md#unimpaired
|
||||
[tree-sitter-nav-demo]: https://user-images.githubusercontent.com/23398472/152332550-7dfff043-36a2-4aec-b8f2-77c13eb56d6f.gif
|
||||
|
@ -27,7 +27,7 @@ ## Selecting and manipulating text with textobjects
|
||||
|
||||
> 💡 `f`, `t`, etc. need a tree-sitter grammar active for the current
|
||||
document and a special tree-sitter query file to work properly. [Only
|
||||
some grammars][lang-support] currently have the query file implemented.
|
||||
some grammars](./lang-support.md) currently have the query file implemented.
|
||||
Contributions are welcome!
|
||||
|
||||
## Navigating using tree-sitter textobjects
|
||||
@ -37,9 +37,9 @@ ## Navigating using tree-sitter textobjects
|
||||
example to move to the next function use `]f`, to move to previous
|
||||
type use `[t`, and so on.
|
||||
|
||||
![Tree-sitter-nav-demo][tree-sitter-nav-demo]
|
||||
![Tree-sitter-nav-demo](https://user-images.githubusercontent.com/23398472/152332550-7dfff043-36a2-4aec-b8f2-77c13eb56d6f.gif)
|
||||
|
||||
For the full reference see the [unimpaired][unimpaired-keybinds] section of the key bind
|
||||
For the full reference see the [unimpaired](./keymap.html#unimpaired) section of the key bind
|
||||
documentation.
|
||||
|
||||
> 💡 This feature relies on tree-sitter textobjects
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Themes
|
||||
## Themes
|
||||
|
||||
To use a theme add `theme = "<name>"` to the top of your [`config.toml`](./configuration.md) file, or select it during runtime using `:theme <name>`.
|
||||
|
||||
@ -283,7 +283,6 @@ #### Interface
|
||||
| `ui.debug.active` | Indicator for the line at which debugging execution is paused at, found in the gutter |
|
||||
| `ui.gutter` | Gutter |
|
||||
| `ui.gutter.selected` | Gutter for the line the cursor is on |
|
||||
| `ui.highlight.frameline` | Line at which debugging execution is paused at |
|
||||
| `ui.linenr` | Line numbers |
|
||||
| `ui.linenr.selected` | Line number for the line the cursor is on |
|
||||
| `ui.statusline` | Statusline |
|
||||
@ -293,10 +292,13 @@ #### 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` | 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. |
|
||||
@ -317,6 +319,7 @@ #### Interface
|
||||
| `ui.selection` | For selections in the editing area |
|
||||
| `ui.selection.primary` | |
|
||||
| `ui.highlight` | Highlighted lines in the picker preview |
|
||||
| `ui.highlight.frameline` | Line at which debugging execution is paused at |
|
||||
| `ui.cursorline.primary` | The line of the primary cursor ([if cursorline is enabled][editor-section]) |
|
||||
| `ui.cursorline.secondary` | The lines of any other cursors ([if cursorline is enabled][editor-section]) |
|
||||
| `ui.cursorcolumn.primary` | The column of the primary cursor ([if cursorcolumn is enabled][editor-section]) |
|
||||
|
@ -7,3 +7,27 @@ # Using Helix
|
||||
> 💡 Currently, not all functionality is fully documented, please refer to the
|
||||
> [key mappings](./keymap.md) list.
|
||||
|
||||
## Modes
|
||||
|
||||
Helix is a modal editor, meaning it has different modes for different tasks. The main modes are:
|
||||
|
||||
* [Normal mode](./keymap.md#normal-mode): For navigation and editing commands. This is the default mode.
|
||||
* [Insert mode](./keymap.md#insert-mode): For typing text directly into the document. Access by typing `i` in normal mode.
|
||||
* [Select/extend mode](./keymap.md#select--extend-mode): For making selections and performing operations on them. Access by typing `v` in normal mode.
|
||||
|
||||
## Buffers
|
||||
|
||||
Buffers are in-memory representations of files. You can have multiple buffers open at once. Use [pickers](./pickers.md) or commands like `:buffer-next` and `:buffer-previous` to open buffers or switch between them.
|
||||
|
||||
## Selection-first editing
|
||||
|
||||
Inspired by [Kakoune](http://kakoune.org/), Helix follows the `selection → action` model. This means that whatever you are going to act on (a word, a paragraph, a line, etc.) is selected first and the action itself (delete, change, yank, etc.) comes second. A cursor is simply a single width selection.
|
||||
|
||||
## Multiple selections
|
||||
|
||||
Also inspired by Kakoune, multiple selections are a core mode of interaction in Helix. For example, the standard way of replacing multiple instance of a word is to first select all instances (so there is one selection per instance) and then use the change action (`c`) to edit them all at the same time.
|
||||
|
||||
## Motions
|
||||
|
||||
Motions are commands that move the cursor or modify selections. They're used for navigation and text manipulation. Examples include `w` to move to the next word, or `f` to find a character. See the [Movement](./keymap.md#movement) section of the keymap for more motions.
|
||||
|
||||
|
@ -47,6 +47,9 @@
|
||||
<content_rating type="oars-1.1" />
|
||||
|
||||
<releases>
|
||||
<release version="24.07" date="2024-07-14">
|
||||
<url>https://github.com/helix-editor/helix/releases/tag/24.07</url>
|
||||
</release>
|
||||
<release version="24.03" date="2024-03-30">
|
||||
<url>https://helix-editor.com/news/release-24-03-highlights/</url>
|
||||
</release>
|
||||
|
@ -2,23 +2,31 @@
|
||||
# Bash completion script for Helix editor
|
||||
|
||||
_hx() {
|
||||
# $1 command name
|
||||
# $2 word being completed
|
||||
# $3 word preceding
|
||||
local cur prev languages
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD - 1]}"
|
||||
|
||||
case "$3" in
|
||||
-g | --grammar)
|
||||
COMPREPLY="$(compgen -W 'fetch build' -- $2)"
|
||||
;;
|
||||
--health)
|
||||
local languages=$(hx --health |tail -n '+7' |awk '{print $1}' |sed 's/\x1b\[[0-9;]*m//g')
|
||||
COMPREPLY="$(compgen -W """$languages""" -- $2)"
|
||||
;;
|
||||
*)
|
||||
COMPREPLY="$(compgen -fd -W "-h --help --tutor -V --version -v -vv -vvv --health -g --grammar --vsplit --hsplit -c --config --log" -- """$2""")"
|
||||
;;
|
||||
esac
|
||||
case "$prev" in
|
||||
-g | --grammar)
|
||||
COMPREPLY=($(compgen -W 'fetch build' -- "$cur"))
|
||||
return 0
|
||||
;;
|
||||
--health)
|
||||
languages=$(hx --health | tail -n '+7' | awk '{print $1}' | sed 's/\x1b\[[0-9;]*m//g')
|
||||
COMPREPLY=($(compgen -W """$languages""" -- "$cur"))
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
local IFS=$'\n'
|
||||
COMPREPLY=($COMPREPLY)
|
||||
case "$2" in
|
||||
-*)
|
||||
COMPREPLY=($(compgen -W "-h --help --tutor -V --version -v -vv -vvv --health -g --grammar --vsplit --hsplit -c --config --log" -- """$2"""))
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
COMPREPLY=($(compgen -fd -- """$2"""))
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
} && complete -o filenames -F _hx hx
|
||||
|
@ -1,15 +1,18 @@
|
||||
#!/usr/bin/env fish
|
||||
# Fish completion script for Helix editor
|
||||
|
||||
set -l langs (hx --health |tail -n '+7' |awk '{print $1}' |sed 's/\x1b\[[0-9;]*m//g')
|
||||
|
||||
complete -c hx -s h -l help -d "Prints help information"
|
||||
complete -c hx -l tutor -d "Loads the tutorial"
|
||||
complete -c hx -l health -x -a "$langs" -d "Checks for errors in editor setup"
|
||||
complete -c hx -s g -l grammar -x -a "fetch build" -d "Fetches or builds tree-sitter grammars"
|
||||
complete -c hx -l health -xa "(__hx_langs_ops)" -d "Checks for errors"
|
||||
complete -c hx -s g -l grammar -x -a "fetch build" -d "Fetch or build tree-sitter grammars"
|
||||
complete -c hx -s v -o vv -o vvv -d "Increases logging verbosity"
|
||||
complete -c hx -s V -l version -d "Prints version information"
|
||||
complete -c hx -l vsplit -d "Splits all given files vertically into different windows"
|
||||
complete -c hx -l hsplit -d "Splits all given files horizontally into different windows"
|
||||
complete -c hx -s c -l config -r -d "Specifies a file to use for completion"
|
||||
complete -c hx -l log -r -d "Specifies a file to write log data into"
|
||||
complete -c hx -l vsplit -d "Splits all given files vertically"
|
||||
complete -c hx -l hsplit -d "Splits all given files horizontally"
|
||||
complete -c hx -s c -l config -r -d "Specifies a file to use for config"
|
||||
complete -c hx -l log -r -d "Specifies a file to use for logging"
|
||||
complete -c hx -s w -l working-dir -d "Specify initial working directory" -xa "(__fish_complete_directories)"
|
||||
|
||||
function __hx_langs_ops
|
||||
hx --health languages | tail -n '+2' | string replace -fr '^(\S+) .*' '$1'
|
||||
end
|
||||
|
29
contrib/completion/hx.nu
Normal file
29
contrib/completion/hx.nu
Normal file
@ -0,0 +1,29 @@
|
||||
# Completions for Helix: <https://github.com/helix-editor/helix>
|
||||
#
|
||||
# NOTE: the `+N` syntax is not supported in Nushell (https://github.com/nushell/nushell/issues/13418)
|
||||
# so it has not been specified here and will not be proposed in the autocompletion of Nushell.
|
||||
# The help message won't be overriden though, so it will still be present here
|
||||
|
||||
def health_categories [] {
|
||||
let languages = ^hx --health languages | detect columns | get Language | filter { $in != null }
|
||||
let completions = [ "all", "clipboard", "languages" ] | append $languages
|
||||
return $completions
|
||||
}
|
||||
|
||||
def grammar_categories [] { ["fetch", "build"] }
|
||||
|
||||
# A post-modern text editor.
|
||||
export extern hx [
|
||||
--help(-h), # Prints help information
|
||||
--tutor, # Loads the tutorial
|
||||
--health: string@health_categories, # Checks for potential errors in editor setup
|
||||
--grammar(-g): string@grammar_categories, # Fetches or builds tree-sitter grammars listed in `languages.toml`
|
||||
--config(-c): glob, # Specifies a file to use for configuration
|
||||
-v, # Increases logging verbosity each use for up to 3 times
|
||||
--log: glob, # Specifies a file to use for logging
|
||||
--version(-V), # Prints version information
|
||||
--vsplit, # Splits all given files vertically into different windows
|
||||
--hsplit, # Splits all given files horizontally into different windows
|
||||
--working-dir(-w): glob, # Specify an initial working directory
|
||||
...files: glob, # Sets the input file to use, position can also be specified via file[:row[:col]]
|
||||
]
|
@ -14,16 +14,18 @@ _hx() {
|
||||
"--health[Checks for errors in editor setup]:language:->health" \
|
||||
"-g[Fetches or builds tree-sitter grammars]:action:->grammar" \
|
||||
"--grammar[Fetches or builds tree-sitter grammars]:action:->grammar" \
|
||||
"--vsplit[Splits all given files vertically into different windows]" \
|
||||
"--hsplit[Splits all given files horizontally into different windows]" \
|
||||
"--vsplit[Splits all given files vertically]" \
|
||||
"--hsplit[Splits all given files horizontally]" \
|
||||
"-c[Specifies a file to use for configuration]" \
|
||||
"--config[Specifies a file to use for configuration]" \
|
||||
"--log[Specifies a file to write log data into]" \
|
||||
"-w[Specify initial working directory]" \
|
||||
"--working-dir[Specify initial working directory]" \
|
||||
"--log[Specifies a file to use for logging]" \
|
||||
"*:file:_files"
|
||||
|
||||
case "$state" in
|
||||
health)
|
||||
local languages=($(hx --health |tail -n '+7' |awk '{print $1}' |sed 's/\x1b\[[0-9;]*m//g'))
|
||||
local languages=($(hx --health | tail -n '+11' | awk '{print $1}' | sed 's/\x1b\[[0-9;]*m//g;s/[✘✓]//g'))
|
||||
_values 'language' $languages
|
||||
;;
|
||||
grammar)
|
||||
@ -31,4 +33,3 @@ _hx() {
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
|
@ -53,6 +53,10 @@ ## Integration tests
|
||||
[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.
|
||||
|
@ -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.
|
||||
|
@ -5,19 +5,18 @@ ## Checklist
|
||||
`22.05.1`. In these instructions we'll use `<tag>` as a placeholder for the tag
|
||||
being published.
|
||||
|
||||
* Merge the changelog PR
|
||||
* Add new `<release>` entry in `contrib/Helix.appdata.xml` with release information according to the [AppStream spec](https://www.freedesktop.org/software/appstream/docs/sect-Metadata-Releases.html)
|
||||
* Merge the PR with the release updates. That branch should:
|
||||
* Update the version:
|
||||
* Update the `workspace.package.version` key in `Cargo.toml`. Cargo only accepts
|
||||
SemVer versions so a CalVer version of `22.07` for example must be formatted
|
||||
as `22.7.0`. Patch/bugfix releases should increment the SemVer patch number. A
|
||||
patch release for 22.07 would be `22.7.1`.
|
||||
* Run `cargo check` and commit the resulting change to `Cargo.lock`
|
||||
* Add changelog notes to `CHANGELOG.md`
|
||||
* Add new `<release>` entry in `contrib/Helix.appdata.xml` with release information according to the [AppStream spec](https://www.freedesktop.org/software/appstream/docs/sect-Metadata-Releases.html)
|
||||
* Tag and push
|
||||
* `git tag -s -m "<tag>" -a <tag> && git push`
|
||||
* Make sure to switch to master and pull first
|
||||
* Edit the `Cargo.toml` file and change the date in the `version` field to the next planned release
|
||||
* Due to Cargo having a strict requirement on SemVer with 3 or more version
|
||||
numbers, a `0` is required in the micro version; however, unless we are
|
||||
publishing a patch release after a major release, the `.0` is dropped in
|
||||
the user facing version.
|
||||
* Releases are planned to happen every two months, so `22.05.0` would change to `22.07.0`
|
||||
* If we are pushing a patch/bugfix release in the same month as the previous
|
||||
release, bump the micro version, e.g. `22.07.0` to `22.07.1`
|
||||
* Switch to master and pull
|
||||
* `git tag -s -m "<tag>" -a <tag> && git push` (note the `-s` which signs the tag)
|
||||
* Wait for the Release CI to finish
|
||||
* It will automatically turn the git tag into a GitHub release when it uploads artifacts
|
||||
* Edit the new release
|
||||
@ -31,7 +30,7 @@ ## Checklist
|
||||
* Post to reddit
|
||||
* [Example post](https://www.reddit.com/r/rust/comments/uzp5ze/helix_editor_2205_released/)
|
||||
|
||||
[homebrew formula]: https://github.com/Homebrew/homebrew-core/blob/master/Formula/helix.rb
|
||||
[homebrew formula]: https://github.com/Homebrew/homebrew-core/blob/master/Formula/h/helix.rb
|
||||
|
||||
## Changelog Curation
|
||||
|
||||
|
32
flake.lock
32
flake.lock
@ -1,17 +1,12 @@
|
||||
{
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709610799,
|
||||
"narHash": "sha256-5jfLQx0U9hXbi2skYMGodDJkIgffrjIOgMRjZqms2QE=",
|
||||
"lastModified": 1727974419,
|
||||
"narHash": "sha256-WD0//20h+2/yPGkO88d2nYbb23WMWYvnRyDQ9Dx4UHg=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "81c393c776d5379c030607866afef6406ca1be57",
|
||||
"rev": "37e4f9f0976cb9281cd3f0c70081e5e0ecaee93f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -25,11 +20,11 @@
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709126324,
|
||||
"narHash": "sha256-q6EQdSeUZOG26WelxqkmR7kArjgWCdw5sfJVHPH/7j8=",
|
||||
"lastModified": 1726560853,
|
||||
"narHash": "sha256-X6rJYSESBVr3hBoH0WbKE5KvhPU5bloyZ2L4K60/fPQ=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "d465f4819400de7c8d874d50b982301f28a84605",
|
||||
"rev": "c1dfcf08411b08f6b8615f7d8971a2bfa81d5e8a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -40,11 +35,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1709479366,
|
||||
"narHash": "sha256-n6F0n8UV6lnTZbYPl1A9q1BS0p4hduAv1mGAP17CVd0=",
|
||||
"lastModified": 1728018373,
|
||||
"narHash": "sha256-NOiTvBbRLIOe5F6RbHaAh6++BNjsb149fGZd1T4+KBg=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "b8697e57f10292a6165a20f03d2f42920dfaf973",
|
||||
"rev": "bc947f541ae55e999ffdb4013441347d83b00feb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@ -64,19 +59,16 @@
|
||||
},
|
||||
"rust-overlay": {
|
||||
"inputs": {
|
||||
"flake-utils": [
|
||||
"flake-utils"
|
||||
],
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1709604635,
|
||||
"narHash": "sha256-le4fwmWmjGRYWwkho0Gr7mnnZndOOe4XGbLw68OvF40=",
|
||||
"lastModified": 1728268235,
|
||||
"narHash": "sha256-lJMFnMO4maJuNO6PQ5fZesrTmglze3UFTTBuKGwR1Nw=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "e86c0fb5d3a22a5f30d7f64ecad88643fe26449d",
|
||||
"rev": "25685cc2c7054efc31351c172ae77b21814f2d42",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
17
flake.nix
17
flake.nix
@ -6,15 +6,9 @@
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
rust-overlay = {
|
||||
url = "github:oxalica/rust-overlay";
|
||||
inputs = {
|
||||
nixpkgs.follows = "nixpkgs";
|
||||
flake-utils.follows = "flake-utils";
|
||||
};
|
||||
};
|
||||
crane = {
|
||||
url = "github:ipetkov/crane";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
crane.url = "github:ipetkov/crane";
|
||||
};
|
||||
|
||||
outputs = {
|
||||
@ -114,10 +108,7 @@
|
||||
if pkgs.stdenv.isLinux
|
||||
then pkgs.stdenv
|
||||
else pkgs.clangStdenv;
|
||||
rustFlagsEnv =
|
||||
if stdenv.isLinux
|
||||
then ''$RUSTFLAGS -C link-arg=-fuse-ld=lld -C target-cpu=native -Clink-arg=-Wl,--no-rosegment''
|
||||
else "$RUSTFLAGS";
|
||||
rustFlagsEnv = pkgs.lib.optionalString stdenv.isLinux "-C link-arg=-fuse-ld=lld -C target-cpu=native -Clink-arg=-Wl,--no-rosegment --cfg tokio_unstable";
|
||||
rustToolchain = pkgs.pkgsBuildHost.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
|
||||
craneLibMSRV = (crane.mkLib pkgs).overrideToolchain rustToolchain;
|
||||
craneLibStable = (crane.mkLib pkgs).overrideToolchain pkgs.pkgsBuildHost.rust-bin.stable.latest.default;
|
||||
@ -129,6 +120,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";
|
||||
@ -144,6 +136,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 {};
|
||||
@ -183,7 +176,7 @@
|
||||
shellHook = ''
|
||||
export HELIX_RUNTIME="$PWD/runtime"
|
||||
export RUST_BACKTRACE="1"
|
||||
export RUSTFLAGS="${rustFlagsEnv}"
|
||||
export RUSTFLAGS="''${RUSTFLAGS:-""} ${rustFlagsEnv}"
|
||||
'';
|
||||
};
|
||||
})
|
||||
|
@ -22,25 +22,31 @@ helix-loader = { path = "../helix-loader" }
|
||||
ropey = { version = "1.6.1", default-features = false, features = ["simd"] }
|
||||
smallvec = "1.13"
|
||||
smartstring = "1.0.1"
|
||||
unicode-segmentation = "1.11"
|
||||
unicode-width = "0.1"
|
||||
unicode-segmentation = "1.12"
|
||||
# unicode-width is changing width definitions
|
||||
# that both break our logic and disagree with common
|
||||
# width definitions in terminals, we need to replace it.
|
||||
# For now lets lock the version to avoid rendering glitches
|
||||
# when installing without `--locked`
|
||||
unicode-width = "=0.1.12"
|
||||
unicode-general-category = "0.6"
|
||||
slotmap.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
once_cell = "1.19"
|
||||
once_cell = "1.20"
|
||||
arc-swap = "1"
|
||||
regex = "1"
|
||||
bitflags = "2.5"
|
||||
bitflags = "2.6"
|
||||
ahash = "0.8.11"
|
||||
hashbrown = { version = "0.14.5", features = ["raw"] }
|
||||
dunce = "1.0"
|
||||
url = "2.5.0"
|
||||
|
||||
log = "0.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
toml = "0.8"
|
||||
|
||||
imara-diff = "0.1.0"
|
||||
imara-diff = "0.1.7"
|
||||
|
||||
encoding_rs = "0.8"
|
||||
|
||||
@ -51,7 +57,7 @@ textwrap = "0.16.1"
|
||||
|
||||
nucleo.workspace = true
|
||||
parking_lot = "0.12"
|
||||
globset = "0.4.14"
|
||||
globset = "0.4.15"
|
||||
|
||||
[dev-dependencies]
|
||||
quickcheck = { version = "1", default-features = false }
|
||||
|
@ -75,9 +75,9 @@ fn from((open, close): (&char, &char)) -> Self {
|
||||
|
||||
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<Item = A>,
|
||||
V: IntoIterator<Item = A> + 'a,
|
||||
A: Into<Pair>,
|
||||
{
|
||||
let mut auto_pairs = HashMap::new();
|
||||
|
@ -9,6 +9,24 @@
|
||||
use helix_stdx::rope::RopeSliceExt;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub const DEFAULT_COMMENT_TOKEN: &str = "//";
|
||||
|
||||
/// Returns the longest matching comment token of the given line (if it exists).
|
||||
pub fn get_comment_token<'a, S: AsRef<str>>(
|
||||
text: RopeSlice,
|
||||
tokens: &'a [S],
|
||||
line_num: usize,
|
||||
) -> Option<&'a str> {
|
||||
let line = text.line(line_num);
|
||||
let start = line.first_non_whitespace_char()?;
|
||||
|
||||
tokens
|
||||
.iter()
|
||||
.map(AsRef::as_ref)
|
||||
.filter(|token| line.slice(start..).starts_with(token))
|
||||
.max_by_key(|token| token.len())
|
||||
}
|
||||
|
||||
/// Given text, a comment token, and a set of line indices, returns the following:
|
||||
/// - Whether the given lines should be considered commented
|
||||
/// - If any of the lines are uncommented, all lines are considered as such.
|
||||
@ -28,21 +46,20 @@ fn find_line_comment(
|
||||
let mut min = usize::MAX; // minimum col for first_non_whitespace_char
|
||||
let mut margin = 1;
|
||||
let token_len = token.chars().count();
|
||||
|
||||
for line in lines {
|
||||
let line_slice = text.line(line);
|
||||
if let Some(pos) = line_slice.first_non_whitespace_char() {
|
||||
let len = line_slice.len_chars();
|
||||
|
||||
if pos < min {
|
||||
min = pos;
|
||||
}
|
||||
min = std::cmp::min(min, pos);
|
||||
|
||||
// line can be shorter than pos + token len
|
||||
let fragment = Cow::from(line_slice.slice(pos..std::cmp::min(pos + token.len(), len)));
|
||||
|
||||
// as soon as one of the non-blank lines doesn't have a comment, the whole block is
|
||||
// considered uncommented.
|
||||
if fragment != token {
|
||||
// as soon as one of the non-blank lines doesn't have a comment, the whole block is
|
||||
// considered uncommented.
|
||||
commented = false;
|
||||
}
|
||||
|
||||
@ -56,6 +73,7 @@ fn find_line_comment(
|
||||
to_change.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
(commented, to_change, min, margin)
|
||||
}
|
||||
|
||||
@ -63,7 +81,7 @@ fn find_line_comment(
|
||||
pub fn toggle_line_comments(doc: &Rope, selection: &Selection, token: Option<&str>) -> Transaction {
|
||||
let text = doc.slice(..);
|
||||
|
||||
let token = token.unwrap_or("//");
|
||||
let token = token.unwrap_or(DEFAULT_COMMENT_TOKEN);
|
||||
let comment = Tendril::from(format!("{} ", token));
|
||||
|
||||
let mut lines: Vec<usize> = Vec::with_capacity(selection.len());
|
||||
@ -317,56 +335,87 @@ pub fn split_lines_of_selection(text: RopeSlice, selection: &Selection) -> Selec
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_find_line_comment() {
|
||||
// four lines, two space indented, except for line 1 which is blank.
|
||||
let mut doc = Rope::from(" 1\n\n 2\n 3");
|
||||
// select whole document
|
||||
let mut selection = Selection::single(0, doc.len_chars() - 1);
|
||||
mod find_line_comment {
|
||||
use super::*;
|
||||
|
||||
let text = doc.slice(..);
|
||||
#[test]
|
||||
fn not_commented() {
|
||||
// four lines, two space indented, except for line 1 which is blank.
|
||||
let doc = Rope::from(" 1\n\n 2\n 3");
|
||||
|
||||
let res = find_line_comment("//", text, 0..3);
|
||||
// (commented = true, to_change = [line 0, line 2], min = col 2, margin = 0)
|
||||
assert_eq!(res, (false, vec![0, 2], 2, 0));
|
||||
let text = doc.slice(..);
|
||||
|
||||
// comment
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
let res = find_line_comment("//", text, 0..3);
|
||||
// (commented = false, to_change = [line 0, line 2], min = col 2, margin = 0)
|
||||
assert_eq!(res, (false, vec![0, 2], 2, 0));
|
||||
}
|
||||
|
||||
assert_eq!(doc, " // 1\n\n // 2\n // 3");
|
||||
#[test]
|
||||
fn is_commented() {
|
||||
// three lines where the second line is empty.
|
||||
let doc = Rope::from("// hello\n\n// there");
|
||||
|
||||
// uncomment
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
assert_eq!(doc, " 1\n\n 2\n 3");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
let res = find_line_comment("//", doc.slice(..), 0..3);
|
||||
|
||||
// 0 margin comments
|
||||
doc = Rope::from(" //1\n\n //2\n //3");
|
||||
// reset the selection.
|
||||
selection = Selection::single(0, doc.len_chars() - 1);
|
||||
// (commented = true, to_change = [line 0, line 2], min = col 0, margin = 1)
|
||||
assert_eq!(res, (true, vec![0, 2], 0, 1));
|
||||
}
|
||||
}
|
||||
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
assert_eq!(doc, " 1\n\n 2\n 3");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
// TODO: account for uncommenting with uneven comment indentation
|
||||
mod toggle_line_comment {
|
||||
use super::*;
|
||||
|
||||
// 0 margin comments, with no space
|
||||
doc = Rope::from("//");
|
||||
// reset the selection.
|
||||
selection = Selection::single(0, doc.len_chars() - 1);
|
||||
#[test]
|
||||
fn comment() {
|
||||
// four lines, two space indented, except for line 1 which is blank.
|
||||
let mut doc = Rope::from(" 1\n\n 2\n 3");
|
||||
// select whole document
|
||||
let selection = Selection::single(0, doc.len_chars() - 1);
|
||||
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
assert_eq!(doc, "");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
|
||||
// TODO: account for uncommenting with uneven comment indentation
|
||||
assert_eq!(doc, " // 1\n\n // 2\n // 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uncomment() {
|
||||
let mut doc = Rope::from(" // 1\n\n // 2\n // 3");
|
||||
let mut selection = Selection::single(0, doc.len_chars() - 1);
|
||||
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
|
||||
assert_eq!(doc, " 1\n\n 2\n 3");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uncomment_0_margin_comments() {
|
||||
let mut doc = Rope::from(" //1\n\n //2\n //3");
|
||||
let mut selection = Selection::single(0, doc.len_chars() - 1);
|
||||
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
|
||||
assert_eq!(doc, " 1\n\n 2\n 3");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uncomment_0_margin_comments_with_no_space() {
|
||||
let mut doc = Rope::from("//");
|
||||
let mut selection = Selection::single(0, doc.len_chars() - 1);
|
||||
|
||||
let transaction = toggle_line_comments(&doc, &selection, None);
|
||||
transaction.apply(&mut doc);
|
||||
selection = selection.map(transaction.changes());
|
||||
assert_eq!(doc, "");
|
||||
assert!(selection.len() == 1); // to ignore the selection unused warning
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -413,4 +462,32 @@ fn test_find_block_comments() {
|
||||
transaction.apply(&mut doc);
|
||||
assert_eq!(doc, "");
|
||||
}
|
||||
|
||||
/// Test, if `get_comment_tokens` works, even if the content of the file includes chars, whose
|
||||
/// byte size unequal the amount of chars
|
||||
#[test]
|
||||
fn test_get_comment_with_char_boundaries() {
|
||||
let rope = Rope::from("··");
|
||||
let tokens = ["//", "///"];
|
||||
|
||||
assert_eq!(
|
||||
super::get_comment_token(rope.slice(..), tokens.as_slice(), 0),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// Test for `get_comment_token`.
|
||||
///
|
||||
/// Assuming the comment tokens are stored as `["///", "//"]`, `get_comment_token` should still
|
||||
/// return `///` instead of `//` if the user is in a doc-comment section.
|
||||
#[test]
|
||||
fn test_use_longest_comment() {
|
||||
let text = Rope::from(" /// amogus");
|
||||
let tokens = ["///", "//"];
|
||||
|
||||
assert_eq!(
|
||||
super::get_comment_token(text.slice(..), tokens.as_slice(), 0),
|
||||
Some("///")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -4,7 +4,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Describes the severity level of a [`Diagnostic`].
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Severity {
|
||||
Hint,
|
||||
Info,
|
||||
@ -25,6 +26,12 @@ pub struct Range {
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Range {
|
||||
pub fn contains(self, pos: usize) -> bool {
|
||||
(self.start..self.end).contains(&pos)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)]
|
||||
pub enum NumberOrString {
|
||||
Number(i32),
|
||||
@ -71,3 +78,10 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{:?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Diagnostic {
|
||||
#[inline]
|
||||
pub fn severity(&self) -> Severity {
|
||||
self.severity.unwrap_or(Severity::Warning)
|
||||
}
|
||||
}
|
||||
|
@ -10,8 +10,9 @@
|
||||
//! called a "block" and the caller must advance it as needed.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt::Debug;
|
||||
use std::mem::{replace, take};
|
||||
use std::mem::replace;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test;
|
||||
@ -37,52 +38,104 @@ pub enum GraphemeSource {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FormattedGrapheme<'a> {
|
||||
pub grapheme: Grapheme<'a>,
|
||||
pub source: GraphemeSource,
|
||||
impl GraphemeSource {
|
||||
/// Returns whether this grapheme is virtual inline text
|
||||
pub fn is_virtual(self) -> bool {
|
||||
matches!(self, GraphemeSource::VirtualText { .. })
|
||||
}
|
||||
|
||||
pub fn is_eof(self) -> bool {
|
||||
// all doc chars except the EOF char have non-zero codepoints
|
||||
matches!(self, GraphemeSource::Document { codepoints: 0 })
|
||||
}
|
||||
|
||||
pub fn doc_chars(self) -> usize {
|
||||
match self {
|
||||
GraphemeSource::Document { codepoints } => codepoints as usize,
|
||||
GraphemeSource::VirtualText { .. } => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> FormattedGrapheme<'a> {
|
||||
pub fn new(
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FormattedGrapheme<'a> {
|
||||
pub raw: Grapheme<'a>,
|
||||
pub source: GraphemeSource,
|
||||
pub visual_pos: Position,
|
||||
/// Document line at the start of the grapheme
|
||||
pub line_idx: usize,
|
||||
/// Document char position at the start of the grapheme
|
||||
pub char_idx: usize,
|
||||
}
|
||||
|
||||
impl FormattedGrapheme<'_> {
|
||||
pub fn is_virtual(&self) -> bool {
|
||||
self.source.is_virtual()
|
||||
}
|
||||
|
||||
pub fn doc_chars(&self) -> usize {
|
||||
self.source.doc_chars()
|
||||
}
|
||||
|
||||
pub fn is_whitespace(&self) -> bool {
|
||||
self.raw.is_whitespace()
|
||||
}
|
||||
|
||||
pub fn width(&self) -> usize {
|
||||
self.raw.width()
|
||||
}
|
||||
|
||||
pub fn is_word_boundary(&self) -> bool {
|
||||
self.raw.is_word_boundary()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct GraphemeWithSource<'a> {
|
||||
grapheme: Grapheme<'a>,
|
||||
source: GraphemeSource,
|
||||
}
|
||||
|
||||
impl<'a> GraphemeWithSource<'a> {
|
||||
fn new(
|
||||
g: GraphemeStr<'a>,
|
||||
visual_x: usize,
|
||||
tab_width: u16,
|
||||
source: GraphemeSource,
|
||||
) -> FormattedGrapheme<'a> {
|
||||
FormattedGrapheme {
|
||||
) -> GraphemeWithSource<'a> {
|
||||
GraphemeWithSource {
|
||||
grapheme: Grapheme::new(g, visual_x, tab_width),
|
||||
source,
|
||||
}
|
||||
}
|
||||
/// Returns whether this grapheme is virtual inline text
|
||||
pub fn is_virtual(&self) -> bool {
|
||||
matches!(self.source, GraphemeSource::VirtualText { .. })
|
||||
}
|
||||
|
||||
pub fn placeholder() -> Self {
|
||||
FormattedGrapheme {
|
||||
fn placeholder() -> Self {
|
||||
GraphemeWithSource {
|
||||
grapheme: Grapheme::Other { g: " ".into() },
|
||||
source: GraphemeSource::Document { codepoints: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn doc_chars(&self) -> usize {
|
||||
match self.source {
|
||||
GraphemeSource::Document { codepoints } => codepoints as usize,
|
||||
GraphemeSource::VirtualText { .. } => 0,
|
||||
}
|
||||
fn doc_chars(&self) -> usize {
|
||||
self.source.doc_chars()
|
||||
}
|
||||
|
||||
pub fn is_whitespace(&self) -> bool {
|
||||
fn is_whitespace(&self) -> bool {
|
||||
self.grapheme.is_whitespace()
|
||||
}
|
||||
|
||||
pub fn width(&self) -> usize {
|
||||
fn is_newline(&self) -> bool {
|
||||
matches!(self.grapheme, Grapheme::Newline)
|
||||
}
|
||||
|
||||
fn is_eof(&self) -> bool {
|
||||
self.source.is_eof()
|
||||
}
|
||||
|
||||
fn width(&self) -> usize {
|
||||
self.grapheme.width()
|
||||
}
|
||||
|
||||
pub fn is_word_boundary(&self) -> bool {
|
||||
fn is_word_boundary(&self) -> bool {
|
||||
self.grapheme.is_word_boundary()
|
||||
}
|
||||
}
|
||||
@ -96,6 +149,7 @@ pub struct TextFormat {
|
||||
pub wrap_indicator: Box<str>,
|
||||
pub wrap_indicator_highlight: Option<Highlight>,
|
||||
pub viewport_width: u16,
|
||||
pub soft_wrap_at_text_width: bool,
|
||||
}
|
||||
|
||||
// test implementation is basically only used for testing or when softwrap is always disabled
|
||||
@ -109,6 +163,7 @@ fn default() -> Self {
|
||||
wrap_indicator: Box::from(" "),
|
||||
viewport_width: 17,
|
||||
wrap_indicator_highlight: None,
|
||||
soft_wrap_at_text_width: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -127,10 +182,7 @@ pub struct DocumentFormatter<'t> {
|
||||
line_pos: usize,
|
||||
exhausted: bool,
|
||||
|
||||
/// Line breaks to be reserved for virtual text
|
||||
/// at the next line break
|
||||
virtual_lines: usize,
|
||||
inline_anntoation_graphemes: Option<(Graphemes<'t>, Option<Highlight>)>,
|
||||
inline_annotation_graphemes: Option<(Graphemes<'t>, Option<Highlight>)>,
|
||||
|
||||
// softwrap specific
|
||||
/// The indentation of the current line
|
||||
@ -139,9 +191,9 @@ pub struct DocumentFormatter<'t> {
|
||||
indent_level: Option<usize>,
|
||||
/// In case a long word needs to be split a single grapheme might need to be wrapped
|
||||
/// while the rest of the word stays on the same line
|
||||
peeked_grapheme: Option<(FormattedGrapheme<'t>, usize)>,
|
||||
peeked_grapheme: Option<GraphemeWithSource<'t>>,
|
||||
/// A first-in first-out (fifo) buffer for the Graphemes of any given word
|
||||
word_buf: Vec<FormattedGrapheme<'t>>,
|
||||
word_buf: Vec<GraphemeWithSource<'t>>,
|
||||
/// The index of the next grapheme that will be yielded from the `word_buf`
|
||||
word_i: usize,
|
||||
}
|
||||
@ -157,35 +209,35 @@ pub fn new_at_prev_checkpoint(
|
||||
text_fmt: &'t TextFormat,
|
||||
annotations: &'t TextAnnotations,
|
||||
char_idx: usize,
|
||||
) -> (Self, usize) {
|
||||
) -> Self {
|
||||
// TODO divide long lines into blocks to avoid bad performance for long lines
|
||||
let block_line_idx = text.char_to_line(char_idx.min(text.len_chars()));
|
||||
let block_char_idx = text.line_to_char(block_line_idx);
|
||||
annotations.reset_pos(block_char_idx);
|
||||
(
|
||||
DocumentFormatter {
|
||||
text_fmt,
|
||||
annotations,
|
||||
visual_pos: Position { row: 0, col: 0 },
|
||||
graphemes: RopeGraphemes::new(text.slice(block_char_idx..)),
|
||||
char_pos: block_char_idx,
|
||||
exhausted: false,
|
||||
virtual_lines: 0,
|
||||
indent_level: None,
|
||||
peeked_grapheme: None,
|
||||
word_buf: Vec::with_capacity(64),
|
||||
word_i: 0,
|
||||
line_pos: block_line_idx,
|
||||
inline_anntoation_graphemes: None,
|
||||
},
|
||||
block_char_idx,
|
||||
)
|
||||
|
||||
DocumentFormatter {
|
||||
text_fmt,
|
||||
annotations,
|
||||
visual_pos: Position { row: 0, col: 0 },
|
||||
graphemes: RopeGraphemes::new(text.slice(block_char_idx..)),
|
||||
char_pos: block_char_idx,
|
||||
exhausted: false,
|
||||
indent_level: None,
|
||||
peeked_grapheme: None,
|
||||
word_buf: Vec::with_capacity(64),
|
||||
word_i: 0,
|
||||
line_pos: block_line_idx,
|
||||
inline_annotation_graphemes: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_inline_annotation_grapheme(&mut self) -> Option<(&'t str, Option<Highlight>)> {
|
||||
fn next_inline_annotation_grapheme(
|
||||
&mut self,
|
||||
char_pos: usize,
|
||||
) -> Option<(&'t str, Option<Highlight>)> {
|
||||
loop {
|
||||
if let Some(&mut (ref mut annotation, highlight)) =
|
||||
self.inline_anntoation_graphemes.as_mut()
|
||||
self.inline_annotation_graphemes.as_mut()
|
||||
{
|
||||
if let Some(grapheme) = annotation.next() {
|
||||
return Some((grapheme, highlight));
|
||||
@ -193,9 +245,9 @@ fn next_inline_annotation_grapheme(&mut self) -> Option<(&'t str, Option<Highlig
|
||||
}
|
||||
|
||||
if let Some((annotation, highlight)) =
|
||||
self.annotations.next_inline_annotation_at(self.char_pos)
|
||||
self.annotations.next_inline_annotation_at(char_pos)
|
||||
{
|
||||
self.inline_anntoation_graphemes = Some((
|
||||
self.inline_annotation_graphemes = Some((
|
||||
UnicodeSegmentation::graphemes(&*annotation.text, true),
|
||||
highlight,
|
||||
))
|
||||
@ -205,21 +257,19 @@ fn next_inline_annotation_grapheme(&mut self) -> Option<(&'t str, Option<Highlig
|
||||
}
|
||||
}
|
||||
|
||||
fn advance_grapheme(&mut self, col: usize) -> Option<FormattedGrapheme<'t>> {
|
||||
fn advance_grapheme(&mut self, col: usize, char_pos: usize) -> Option<GraphemeWithSource<'t>> {
|
||||
let (grapheme, source) =
|
||||
if let Some((grapheme, highlight)) = self.next_inline_annotation_grapheme() {
|
||||
if let Some((grapheme, highlight)) = self.next_inline_annotation_grapheme(char_pos) {
|
||||
(grapheme.into(), GraphemeSource::VirtualText { highlight })
|
||||
} else if let Some(grapheme) = self.graphemes.next() {
|
||||
self.virtual_lines += self.annotations.annotation_lines_at(self.char_pos);
|
||||
let codepoints = grapheme.len_chars() as u32;
|
||||
|
||||
let overlay = self.annotations.overlay_at(self.char_pos);
|
||||
let overlay = self.annotations.overlay_at(char_pos);
|
||||
let grapheme = match overlay {
|
||||
Some((overlay, _)) => overlay.grapheme.as_str().into(),
|
||||
None => Cow::from(grapheme).into(),
|
||||
};
|
||||
|
||||
self.char_pos += codepoints as usize;
|
||||
(grapheme, GraphemeSource::Document { codepoints })
|
||||
} else {
|
||||
if self.exhausted {
|
||||
@ -228,19 +278,19 @@ fn advance_grapheme(&mut self, col: usize) -> Option<FormattedGrapheme<'t>> {
|
||||
self.exhausted = true;
|
||||
// EOF grapheme is required for rendering
|
||||
// and correct position computations
|
||||
return Some(FormattedGrapheme {
|
||||
return Some(GraphemeWithSource {
|
||||
grapheme: Grapheme::Other { g: " ".into() },
|
||||
source: GraphemeSource::Document { codepoints: 0 },
|
||||
});
|
||||
};
|
||||
|
||||
let grapheme = FormattedGrapheme::new(grapheme, col, self.text_fmt.tab_width, source);
|
||||
let grapheme = GraphemeWithSource::new(grapheme, col, self.text_fmt.tab_width, source);
|
||||
|
||||
Some(grapheme)
|
||||
}
|
||||
|
||||
/// Move a word to the next visual line
|
||||
fn wrap_word(&mut self, virtual_lines_before_word: usize) -> usize {
|
||||
fn wrap_word(&mut self) -> usize {
|
||||
// softwrap this word to the next line
|
||||
let indent_carry_over = if let Some(indent) = self.indent_level {
|
||||
if indent as u16 <= self.text_fmt.max_indent_retain {
|
||||
@ -254,15 +304,17 @@ fn wrap_word(&mut self, virtual_lines_before_word: usize) -> usize {
|
||||
0
|
||||
};
|
||||
|
||||
let virtual_lines =
|
||||
self.annotations
|
||||
.virtual_lines_at(self.char_pos, self.visual_pos, self.line_pos);
|
||||
self.visual_pos.col = indent_carry_over as usize;
|
||||
self.virtual_lines -= virtual_lines_before_word;
|
||||
self.visual_pos.row += 1 + virtual_lines_before_word;
|
||||
self.visual_pos.row += 1 + virtual_lines;
|
||||
let mut i = 0;
|
||||
let mut word_width = 0;
|
||||
let wrap_indicator = UnicodeSegmentation::graphemes(&*self.text_fmt.wrap_indicator, true)
|
||||
.map(|g| {
|
||||
i += 1;
|
||||
let grapheme = FormattedGrapheme::new(
|
||||
let grapheme = GraphemeWithSource::new(
|
||||
g.into(),
|
||||
self.visual_pos.col + word_width,
|
||||
self.text_fmt.tab_width,
|
||||
@ -282,46 +334,71 @@ fn wrap_word(&mut self, virtual_lines_before_word: usize) -> usize {
|
||||
.change_position(visual_x, self.text_fmt.tab_width);
|
||||
word_width += grapheme.width();
|
||||
}
|
||||
if let Some(grapheme) = &mut self.peeked_grapheme {
|
||||
let visual_x = self.visual_pos.col + word_width;
|
||||
grapheme
|
||||
.grapheme
|
||||
.change_position(visual_x, self.text_fmt.tab_width);
|
||||
}
|
||||
word_width
|
||||
}
|
||||
|
||||
fn peek_grapheme(&mut self, col: usize, char_pos: usize) -> Option<&GraphemeWithSource<'t>> {
|
||||
if self.peeked_grapheme.is_none() {
|
||||
self.peeked_grapheme = self.advance_grapheme(col, char_pos);
|
||||
}
|
||||
self.peeked_grapheme.as_ref()
|
||||
}
|
||||
|
||||
fn next_grapheme(&mut self, col: usize, char_pos: usize) -> Option<GraphemeWithSource<'t>> {
|
||||
self.peek_grapheme(col, char_pos);
|
||||
self.peeked_grapheme.take()
|
||||
}
|
||||
|
||||
fn advance_to_next_word(&mut self) {
|
||||
self.word_buf.clear();
|
||||
let mut word_width = 0;
|
||||
let virtual_lines_before_word = self.virtual_lines;
|
||||
let mut virtual_lines_before_grapheme = self.virtual_lines;
|
||||
let mut word_chars = 0;
|
||||
|
||||
if self.exhausted {
|
||||
return;
|
||||
}
|
||||
|
||||
loop {
|
||||
// softwrap word if necessary
|
||||
if word_width + self.visual_pos.col >= self.text_fmt.viewport_width as usize {
|
||||
// wrapping this word would move too much text to the next line
|
||||
// split the word at the line end instead
|
||||
if word_width > self.text_fmt.max_wrap as usize {
|
||||
// Usually we stop accomulating graphemes as soon as softwrapping becomes necessary.
|
||||
// However if the last grapheme is multiple columns wide it might extend beyond the EOL.
|
||||
// The condition below ensures that this grapheme is not cutoff and instead wrapped to the next line
|
||||
if word_width + self.visual_pos.col > self.text_fmt.viewport_width as usize {
|
||||
self.peeked_grapheme = self.word_buf.pop().map(|grapheme| {
|
||||
(grapheme, self.virtual_lines - virtual_lines_before_grapheme)
|
||||
});
|
||||
self.virtual_lines = virtual_lines_before_grapheme;
|
||||
}
|
||||
let mut col = self.visual_pos.col + word_width;
|
||||
let char_pos = self.char_pos + word_chars;
|
||||
match col.cmp(&(self.text_fmt.viewport_width as usize)) {
|
||||
// The EOF char and newline chars are always selectable in helix. That means
|
||||
// that wrapping happens "too-early" if a word fits a line perfectly. This
|
||||
// is intentional so that all selectable graphemes are always visisble (and
|
||||
// therefore the cursor never dissapears). However if the user manually set a
|
||||
// lower softwrap width then this is undesirable. Just increasing the viewport-
|
||||
// width by one doesn't work because if a line is wrapped multiple times then
|
||||
// some words may extend past the specified width.
|
||||
//
|
||||
// So we special case a word that ends exactly at line bounds and is followed
|
||||
// by a newline/eof character here.
|
||||
Ordering::Equal
|
||||
if self.text_fmt.soft_wrap_at_text_width
|
||||
&& self.peek_grapheme(col, char_pos).map_or(false, |grapheme| {
|
||||
grapheme.is_newline() || grapheme.is_eof()
|
||||
}) => {}
|
||||
Ordering::Equal if word_width > self.text_fmt.max_wrap as usize => return,
|
||||
Ordering::Greater if word_width > self.text_fmt.max_wrap as usize => {
|
||||
self.peeked_grapheme = self.word_buf.pop();
|
||||
return;
|
||||
}
|
||||
|
||||
word_width = self.wrap_word(virtual_lines_before_word);
|
||||
Ordering::Equal | Ordering::Greater => {
|
||||
word_width = self.wrap_word();
|
||||
col = self.visual_pos.col + word_width;
|
||||
}
|
||||
Ordering::Less => (),
|
||||
}
|
||||
|
||||
virtual_lines_before_grapheme = self.virtual_lines;
|
||||
|
||||
let grapheme = if let Some((grapheme, virtual_lines)) = self.peeked_grapheme.take() {
|
||||
self.virtual_lines += virtual_lines;
|
||||
grapheme
|
||||
} else if let Some(grapheme) = self.advance_grapheme(self.visual_pos.col + word_width) {
|
||||
grapheme
|
||||
} else {
|
||||
let Some(grapheme) = self.next_grapheme(col, char_pos) else {
|
||||
return;
|
||||
};
|
||||
word_chars += grapheme.doc_chars();
|
||||
|
||||
// Track indentation
|
||||
if !grapheme.is_whitespace() && self.indent_level.is_none() {
|
||||
@ -340,19 +417,18 @@ fn advance_to_next_word(&mut self) {
|
||||
}
|
||||
}
|
||||
|
||||
/// returns the document line pos of the **next** grapheme that will be yielded
|
||||
pub fn line_pos(&self) -> usize {
|
||||
self.line_pos
|
||||
/// returns the char index at the end of the last yielded grapheme
|
||||
pub fn next_char_pos(&self) -> usize {
|
||||
self.char_pos
|
||||
}
|
||||
|
||||
/// returns the visual pos of the **next** grapheme that will be yielded
|
||||
pub fn visual_pos(&self) -> Position {
|
||||
/// returns the visual position at the end of the last yielded grapheme
|
||||
pub fn next_visual_pos(&self) -> Position {
|
||||
self.visual_pos
|
||||
}
|
||||
}
|
||||
|
||||
impl<'t> Iterator for DocumentFormatter<'t> {
|
||||
type Item = (FormattedGrapheme<'t>, Position);
|
||||
type Item = FormattedGrapheme<'t>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let grapheme = if self.text_fmt.soft_wrap {
|
||||
@ -362,23 +438,40 @@ fn next(&mut self) -> Option<Self::Item> {
|
||||
}
|
||||
let grapheme = replace(
|
||||
self.word_buf.get_mut(self.word_i)?,
|
||||
FormattedGrapheme::placeholder(),
|
||||
GraphemeWithSource::placeholder(),
|
||||
);
|
||||
self.word_i += 1;
|
||||
grapheme
|
||||
} else {
|
||||
self.advance_grapheme(self.visual_pos.col)?
|
||||
self.advance_grapheme(self.visual_pos.col, self.char_pos)?
|
||||
};
|
||||
|
||||
let pos = self.visual_pos;
|
||||
if grapheme.grapheme == Grapheme::Newline {
|
||||
self.visual_pos.row += 1;
|
||||
self.visual_pos.row += take(&mut self.virtual_lines);
|
||||
let grapheme = FormattedGrapheme {
|
||||
raw: grapheme.grapheme,
|
||||
source: grapheme.source,
|
||||
visual_pos: self.visual_pos,
|
||||
line_idx: self.line_pos,
|
||||
char_idx: self.char_pos,
|
||||
};
|
||||
|
||||
self.char_pos += grapheme.doc_chars();
|
||||
if !grapheme.is_virtual() {
|
||||
self.annotations.process_virtual_text_anchors(&grapheme);
|
||||
}
|
||||
if grapheme.raw == Grapheme::Newline {
|
||||
// move to end of newline char
|
||||
self.visual_pos.col += 1;
|
||||
let virtual_lines =
|
||||
self.annotations
|
||||
.virtual_lines_at(self.char_pos, self.visual_pos, self.line_pos);
|
||||
self.visual_pos.row += 1 + virtual_lines;
|
||||
self.visual_pos.col = 0;
|
||||
self.line_pos += 1;
|
||||
if !grapheme.is_virtual() {
|
||||
self.line_pos += 1;
|
||||
}
|
||||
} else {
|
||||
self.visual_pos.col += grapheme.width();
|
||||
}
|
||||
Some((grapheme, pos))
|
||||
Some(grapheme)
|
||||
}
|
||||
}
|
||||
|
@ -12,6 +12,7 @@ fn new_test(softwrap: bool) -> Self {
|
||||
wrap_indicator_highlight: None,
|
||||
// use a prime number to allow lining up too often with repeat
|
||||
viewport_width: 17,
|
||||
soft_wrap_at_text_width: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -21,20 +22,23 @@ fn collect_to_str(&mut self) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut res = String::new();
|
||||
let viewport_width = self.text_fmt.viewport_width;
|
||||
let soft_wrap_at_text_width = self.text_fmt.soft_wrap_at_text_width;
|
||||
let mut line = 0;
|
||||
|
||||
for (grapheme, pos) in self {
|
||||
if pos.row != line {
|
||||
for grapheme in self {
|
||||
if grapheme.visual_pos.row != line {
|
||||
line += 1;
|
||||
assert_eq!(pos.row, line);
|
||||
write!(res, "\n{}", ".".repeat(pos.col)).unwrap();
|
||||
assert_eq!(grapheme.visual_pos.row, line);
|
||||
write!(res, "\n{}", ".".repeat(grapheme.visual_pos.col)).unwrap();
|
||||
}
|
||||
if !soft_wrap_at_text_width {
|
||||
assert!(
|
||||
pos.col <= viewport_width as usize,
|
||||
grapheme.visual_pos.col <= viewport_width as usize,
|
||||
"softwrapped failed {}<={viewport_width}",
|
||||
pos.col
|
||||
grapheme.visual_pos.col
|
||||
);
|
||||
}
|
||||
write!(res, "{}", grapheme.grapheme).unwrap();
|
||||
write!(res, "{}", grapheme.raw).unwrap();
|
||||
}
|
||||
|
||||
res
|
||||
@ -48,7 +52,6 @@ fn softwrap_text(text: &str) -> String {
|
||||
&TextAnnotations::default(),
|
||||
0,
|
||||
)
|
||||
.0
|
||||
.collect_to_str()
|
||||
}
|
||||
|
||||
@ -99,6 +102,22 @@ fn long_word_softwrap() {
|
||||
);
|
||||
}
|
||||
|
||||
fn softwrap_text_at_text_width(text: &str) -> String {
|
||||
let mut text_fmt = TextFormat::new_test(true);
|
||||
text_fmt.soft_wrap_at_text_width = true;
|
||||
let annotations = TextAnnotations::default();
|
||||
let mut formatter =
|
||||
DocumentFormatter::new_at_prev_checkpoint(text.into(), &text_fmt, &annotations, 0);
|
||||
formatter.collect_to_str()
|
||||
}
|
||||
#[test]
|
||||
fn long_word_softwrap_text_width() {
|
||||
assert_eq!(
|
||||
softwrap_text_at_text_width("xxxxxxxx1xxxx2xxx\nxxxxxxxx1xxxx2xxx"),
|
||||
"xxxxxxxx1xxxx2xxx \nxxxxxxxx1xxxx2xxx "
|
||||
);
|
||||
}
|
||||
|
||||
fn overlay_text(text: &str, char_pos: usize, softwrap: bool, overlays: &[Overlay]) -> String {
|
||||
DocumentFormatter::new_at_prev_checkpoint(
|
||||
text.into(),
|
||||
@ -106,7 +125,6 @@ fn overlay_text(text: &str, char_pos: usize, softwrap: bool, overlays: &[Overlay
|
||||
TextAnnotations::default().add_overlay(overlays, None),
|
||||
char_pos,
|
||||
)
|
||||
.0
|
||||
.collect_to_str()
|
||||
}
|
||||
|
||||
@ -143,7 +161,6 @@ fn annotate_text(text: &str, softwrap: bool, annotations: &[InlineAnnotation]) -
|
||||
TextAnnotations::default().add_inline_annotations(annotations, None),
|
||||
0,
|
||||
)
|
||||
.0
|
||||
.collect_to_str()
|
||||
}
|
||||
|
||||
@ -182,7 +199,6 @@ fn annotation_and_overlay() {
|
||||
.add_overlay(overlay.as_slice(), None),
|
||||
0,
|
||||
)
|
||||
.0
|
||||
.collect_to_str(),
|
||||
"fooo bar "
|
||||
);
|
||||
|
@ -1,6 +1,6 @@
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use nucleo::pattern::{Atom, AtomKind, CaseMatching};
|
||||
use nucleo::pattern::{Atom, AtomKind, CaseMatching, Normalization};
|
||||
use nucleo::Config;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
@ -38,6 +38,12 @@ pub fn fuzzy_match<T: AsRef<str>>(
|
||||
if path {
|
||||
matcher.config.set_match_paths();
|
||||
}
|
||||
let pattern = Atom::new(pattern, CaseMatching::Smart, AtomKind::Fuzzy, false);
|
||||
let pattern = Atom::new(
|
||||
pattern,
|
||||
CaseMatching::Smart,
|
||||
Normalization::Smart,
|
||||
AtomKind::Fuzzy,
|
||||
false,
|
||||
);
|
||||
pattern.match_list(items, &mut matcher)
|
||||
}
|
||||
|
@ -28,6 +28,11 @@ pub enum Grapheme<'a> {
|
||||
}
|
||||
|
||||
impl<'a> Grapheme<'a> {
|
||||
pub fn new_decoration(g: &'static str) -> Grapheme<'a> {
|
||||
assert_ne!(g, "\t");
|
||||
Grapheme::new(g.into(), 0, 0)
|
||||
}
|
||||
|
||||
pub fn new(g: GraphemeStr<'a>, visual_x: usize, tab_width: u16) -> Grapheme<'a> {
|
||||
match g {
|
||||
g if g == "\t" => Grapheme::Tab {
|
||||
|
@ -265,7 +265,7 @@ fn is_first_in_line(node: Node, text: RopeSlice, new_line_byte_pos: Option<usize
|
||||
/// This is usually constructed in one of 2 ways:
|
||||
/// - Successively add indent captures to get the (added) indent from a single line
|
||||
/// - Successively add the indent results for each line
|
||||
/// The string that this indentation defines starts with the string contained in the align field (unless it is None), followed by:
|
||||
/// The string that this indentation defines starts with the string contained in the align field (unless it is None), followed by:
|
||||
/// - max(0, indent - outdent) tabs, if tabs are used for indentation
|
||||
/// - max(0, indent - outdent)*indent_width spaces, if spaces are used for indentation
|
||||
#[derive(Default, Debug, PartialEq, Eq, Clone)]
|
||||
@ -457,7 +457,7 @@ fn query_indents<'a>(
|
||||
// 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.
|
||||
|
@ -27,6 +27,7 @@
|
||||
pub mod text_annotations;
|
||||
pub mod textobject;
|
||||
mod transaction;
|
||||
pub mod uri;
|
||||
pub mod wrap;
|
||||
|
||||
pub mod unicode {
|
||||
@ -52,8 +53,8 @@ pub mod unicode {
|
||||
|
||||
pub use graphemes::RopeGraphemes;
|
||||
pub use position::{
|
||||
char_idx_at_visual_offset, coords_at_pos, pos_at_coords, visual_offset_from_anchor,
|
||||
visual_offset_from_block, Position, VisualOffsetError,
|
||||
char_idx_at_visual_offset, coords_at_pos, pos_at_coords, softwrapped_dimensions,
|
||||
visual_offset_from_anchor, visual_offset_from_block, Position, VisualOffsetError,
|
||||
};
|
||||
#[allow(deprecated)]
|
||||
pub use position::{pos_at_visual_coords, visual_coords_at_pos};
|
||||
@ -66,3 +67,5 @@ pub mod unicode {
|
||||
|
||||
pub use line_ending::{LineEnding, NATIVE_LINE_ENDING};
|
||||
pub use transaction::{Assoc, Change, ChangeSet, Deletion, Operation, Transaction};
|
||||
|
||||
pub use uri::Uri;
|
||||
|
@ -9,11 +9,13 @@
|
||||
const MAX_PLAINTEXT_SCAN: usize = 10000;
|
||||
const MATCH_LIMIT: usize = 16;
|
||||
|
||||
pub const BRACKETS: [(char, char); 7] = [
|
||||
pub const BRACKETS: [(char, char); 9] = [
|
||||
('(', ')'),
|
||||
('{', '}'),
|
||||
('[', ']'),
|
||||
('<', '>'),
|
||||
('‘', '’'),
|
||||
('“', '”'),
|
||||
('«', '»'),
|
||||
('「', '」'),
|
||||
('(', ')'),
|
||||
|
@ -79,19 +79,19 @@ pub fn move_vertically_visual(
|
||||
Direction::Backward => -(count as isize),
|
||||
};
|
||||
|
||||
// TODO how to handle inline annotations that span an entire visual line (very unlikely).
|
||||
|
||||
// Compute visual offset relative to block start to avoid trasversing the block twice
|
||||
row_off += visual_pos.row as isize;
|
||||
let new_pos = char_idx_at_visual_offset(
|
||||
let (mut new_pos, virtual_rows) = char_idx_at_visual_offset(
|
||||
slice,
|
||||
block_off,
|
||||
row_off,
|
||||
new_col as usize,
|
||||
text_fmt,
|
||||
annotations,
|
||||
)
|
||||
.0;
|
||||
);
|
||||
if dir == Direction::Forward {
|
||||
new_pos += (virtual_rows != 0) as usize;
|
||||
}
|
||||
|
||||
// Special-case to avoid moving to the end of the last non-empty line.
|
||||
if behaviour == Movement::Extend && slice.line(slice.char_to_line(new_pos)).len_chars() == 0 {
|
||||
@ -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 @@ fn range_to_target(&mut self, target: WordMotionTarget, origin: Range) -> Range
|
||||
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 @@ fn test_behaviour_when_moving_to_start_of_next_words() {
|
||||
}
|
||||
}
|
||||
|
||||
#[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 @@ fn test_behaviour_when_moving_to_start_of_previous_words() {
|
||||
}
|
||||
}
|
||||
|
||||
#[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 @@ fn test_behaviour_when_moving_to_end_of_previous_words() {
|
||||
}
|
||||
}
|
||||
|
||||
#[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 = [
|
||||
|
@ -1,4 +1,8 @@
|
||||
use std::{borrow::Cow, cmp::Ordering};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
cmp::Ordering,
|
||||
ops::{Add, AddAssign, Sub, SubAssign},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
chars::char_is_line_ending,
|
||||
@ -16,6 +20,38 @@ pub struct Position {
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
impl AddAssign for Position {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.row += rhs.row;
|
||||
self.col += rhs.col;
|
||||
}
|
||||
}
|
||||
|
||||
impl SubAssign for Position {
|
||||
fn sub_assign(&mut self, rhs: Self) {
|
||||
self.row -= rhs.row;
|
||||
self.col -= rhs.col;
|
||||
}
|
||||
}
|
||||
|
||||
impl Sub for Position {
|
||||
type Output = Position;
|
||||
|
||||
fn sub(mut self, rhs: Self) -> Self::Output {
|
||||
self -= rhs;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Add for Position {
|
||||
type Output = Position;
|
||||
|
||||
fn add(mut self, rhs: Self) -> Self::Output {
|
||||
self += rhs;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Position {
|
||||
pub const fn new(row: usize, col: usize) -> Self {
|
||||
Self { row, col }
|
||||
@ -121,22 +157,31 @@ pub fn visual_offset_from_block(
|
||||
annotations: &TextAnnotations,
|
||||
) -> (Position, usize) {
|
||||
let mut last_pos = Position::default();
|
||||
let (formatter, block_start) =
|
||||
let mut formatter =
|
||||
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
|
||||
let mut char_pos = block_start;
|
||||
let block_start = formatter.next_char_pos();
|
||||
|
||||
for (grapheme, vpos) in formatter {
|
||||
last_pos = vpos;
|
||||
char_pos += grapheme.doc_chars();
|
||||
|
||||
if char_pos > pos {
|
||||
return (last_pos, block_start);
|
||||
while let Some(grapheme) = formatter.next() {
|
||||
last_pos = grapheme.visual_pos;
|
||||
if formatter.next_char_pos() > pos {
|
||||
return (grapheme.visual_pos, block_start);
|
||||
}
|
||||
}
|
||||
|
||||
(last_pos, block_start)
|
||||
}
|
||||
|
||||
/// Returns the height of the given text when softwrapping
|
||||
pub fn softwrapped_dimensions(text: RopeSlice, text_fmt: &TextFormat) -> (usize, u16) {
|
||||
let last_pos =
|
||||
visual_offset_from_block(text, 0, usize::MAX, text_fmt, &TextAnnotations::default()).0;
|
||||
if last_pos.row == 0 {
|
||||
(1, last_pos.col as u16)
|
||||
} else {
|
||||
(last_pos.row + 1, text_fmt.viewport_width)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum VisualOffsetError {
|
||||
PosBeforeAnchorRow,
|
||||
@ -153,22 +198,21 @@ pub fn visual_offset_from_anchor(
|
||||
annotations: &TextAnnotations,
|
||||
max_rows: usize,
|
||||
) -> Result<(Position, usize), VisualOffsetError> {
|
||||
let (formatter, block_start) =
|
||||
let mut formatter =
|
||||
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
|
||||
let mut char_pos = block_start;
|
||||
let mut anchor_line = None;
|
||||
let mut found_pos = None;
|
||||
let mut last_pos = Position::default();
|
||||
|
||||
let block_start = formatter.next_char_pos();
|
||||
if pos < block_start {
|
||||
return Err(VisualOffsetError::PosBeforeAnchorRow);
|
||||
}
|
||||
|
||||
for (grapheme, vpos) in formatter {
|
||||
last_pos = vpos;
|
||||
char_pos += grapheme.doc_chars();
|
||||
while let Some(grapheme) = formatter.next() {
|
||||
last_pos = grapheme.visual_pos;
|
||||
|
||||
if char_pos > pos {
|
||||
if formatter.next_char_pos() > pos {
|
||||
if let Some(anchor_line) = anchor_line {
|
||||
last_pos.row -= anchor_line;
|
||||
return Ok((last_pos, block_start));
|
||||
@ -176,7 +220,7 @@ pub fn visual_offset_from_anchor(
|
||||
found_pos = Some(last_pos);
|
||||
}
|
||||
}
|
||||
if char_pos > anchor && anchor_line.is_none() {
|
||||
if formatter.next_char_pos() > anchor && anchor_line.is_none() {
|
||||
if let Some(mut found_pos) = found_pos {
|
||||
return if found_pos.row == last_pos.row {
|
||||
found_pos.row = 0;
|
||||
@ -190,7 +234,7 @@ pub fn visual_offset_from_anchor(
|
||||
}
|
||||
|
||||
if let Some(anchor_line) = anchor_line {
|
||||
if vpos.row >= anchor_line + max_rows {
|
||||
if grapheme.visual_pos.row >= anchor_line + max_rows {
|
||||
return Err(VisualOffsetError::PosAfterMaxRow);
|
||||
}
|
||||
}
|
||||
@ -368,39 +412,43 @@ pub fn char_idx_at_visual_block_offset(
|
||||
text_fmt: &TextFormat,
|
||||
annotations: &TextAnnotations,
|
||||
) -> (usize, usize) {
|
||||
let (formatter, mut char_idx) =
|
||||
let mut formatter =
|
||||
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
|
||||
let mut last_char_idx = char_idx;
|
||||
let mut last_char_idx_on_line = None;
|
||||
let mut last_char_idx = formatter.next_char_pos();
|
||||
let mut found_non_virtual_on_row = false;
|
||||
let mut last_row = 0;
|
||||
for (grapheme, grapheme_pos) in formatter {
|
||||
match grapheme_pos.row.cmp(&row) {
|
||||
for grapheme in &mut formatter {
|
||||
match grapheme.visual_pos.row.cmp(&row) {
|
||||
Ordering::Equal => {
|
||||
if grapheme_pos.col + grapheme.width() > column {
|
||||
if grapheme.visual_pos.col + grapheme.width() > column {
|
||||
if !grapheme.is_virtual() {
|
||||
return (char_idx, 0);
|
||||
} else if let Some(char_idx) = last_char_idx_on_line {
|
||||
return (char_idx, 0);
|
||||
return (grapheme.char_idx, 0);
|
||||
} else if found_non_virtual_on_row {
|
||||
return (last_char_idx, 0);
|
||||
}
|
||||
} else if !grapheme.is_virtual() {
|
||||
last_char_idx_on_line = Some(char_idx)
|
||||
found_non_virtual_on_row = true;
|
||||
last_char_idx = grapheme.char_idx;
|
||||
}
|
||||
}
|
||||
Ordering::Greater if found_non_virtual_on_row => return (last_char_idx, 0),
|
||||
Ordering::Greater => return (last_char_idx, row - last_row),
|
||||
_ => (),
|
||||
Ordering::Less => {
|
||||
if !grapheme.is_virtual() {
|
||||
last_row = grapheme.visual_pos.row;
|
||||
last_char_idx = grapheme.char_idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
last_char_idx = char_idx;
|
||||
last_row = grapheme_pos.row;
|
||||
char_idx += grapheme.doc_chars();
|
||||
}
|
||||
|
||||
(char_idx, 0)
|
||||
(formatter.next_char_pos(), 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::text_annotations::InlineAnnotation;
|
||||
use crate::Rope;
|
||||
|
||||
#[test]
|
||||
@ -761,6 +809,30 @@ fn test_pos_at_visual_coords() {
|
||||
assert_eq!(pos_at_visual_coords(slice, (10, 10).into(), 4), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_char_idx_at_visual_row_offset_inline_annotation() {
|
||||
let text = Rope::from("foo\nbar");
|
||||
let slice = text.slice(..);
|
||||
let mut text_fmt = TextFormat::default();
|
||||
let annotations = [InlineAnnotation {
|
||||
text: "x".repeat(100).into(),
|
||||
char_idx: 3,
|
||||
}];
|
||||
text_fmt.soft_wrap = true;
|
||||
|
||||
assert_eq!(
|
||||
char_idx_at_visual_offset(
|
||||
slice,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
&text_fmt,
|
||||
TextAnnotations::default().add_inline_annotations(&annotations, None)
|
||||
),
|
||||
(2, 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_char_idx_at_visual_row_offset() {
|
||||
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ\nfoo");
|
||||
|
@ -13,7 +13,7 @@
|
||||
};
|
||||
use helix_stdx::rope::{self, RopeSliceExt};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use std::borrow::Cow;
|
||||
use std::{borrow::Cow, iter, slice};
|
||||
use tree_sitter::Node;
|
||||
|
||||
/// A single selection range.
|
||||
@ -175,7 +175,7 @@ pub fn contains(&self, pos: usize) -> bool {
|
||||
/// function runs in O(N) (N is number of changes) and can therefore
|
||||
/// cause performance problems if run for a large number of ranges as the
|
||||
/// complexity is then O(MN) (for multicuror M=N usually). Instead use
|
||||
/// [Selection::map] or [ChangeSet::update_positions] instead
|
||||
/// [Selection::map] or [ChangeSet::update_positions].
|
||||
pub fn map(mut self, changes: &ChangeSet) -> Self {
|
||||
use std::cmp::Ordering;
|
||||
if changes.is_empty() {
|
||||
@ -184,16 +184,16 @@ pub fn map(mut self, changes: &ChangeSet) -> Self {
|
||||
|
||||
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 @@ pub fn map_no_normalize(mut self, changes: &ChangeSet) -> Self {
|
||||
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),
|
||||
],
|
||||
}
|
||||
});
|
||||
@ -503,6 +503,16 @@ pub fn ranges(&self) -> &[Range] {
|
||||
&self.ranges
|
||||
}
|
||||
|
||||
/// Returns an iterator over the line ranges of each range in the selection.
|
||||
///
|
||||
/// Adjacent and overlapping line ranges of the [Range]s in the selection are merged.
|
||||
pub fn line_ranges<'a>(&'a self, text: RopeSlice<'a>) -> LineRangeIter<'a> {
|
||||
LineRangeIter {
|
||||
ranges: self.ranges.iter().peekable(),
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn primary_index(&self) -> usize {
|
||||
self.primary_index
|
||||
}
|
||||
@ -531,6 +541,8 @@ pub fn point(pos: usize) -> Self {
|
||||
}
|
||||
|
||||
/// Normalizes a `Selection`.
|
||||
///
|
||||
/// Ranges are sorted by [Range::from], with overlapping ranges merged.
|
||||
fn normalize(mut self) -> Self {
|
||||
if self.len() < 2 {
|
||||
return self;
|
||||
@ -727,6 +739,33 @@ fn from(range: Range) -> Self {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LineRangeIter<'a> {
|
||||
ranges: iter::Peekable<slice::Iter<'a, Range>>,
|
||||
text: RopeSlice<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for LineRangeIter<'a> {
|
||||
type Item = (usize, usize);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let (start, mut end) = self.ranges.next()?.line_range(self.text);
|
||||
while let Some((next_start, next_end)) =
|
||||
self.ranges.peek().map(|range| range.line_range(self.text))
|
||||
{
|
||||
// Merge overlapping and adjacent ranges.
|
||||
// This subtraction cannot underflow because the ranges are sorted.
|
||||
if next_start - end <= 1 {
|
||||
end = next_end;
|
||||
self.ranges.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Some((start, end))
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: checkSelection -> check if valid for doc length && sorted
|
||||
|
||||
pub fn keep_or_remove_matches(
|
||||
@ -1165,6 +1204,32 @@ fn test_line_range() {
|
||||
assert_eq!(Range::new(12, 0).line_range(s), (0, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_line_ranges() {
|
||||
let (text, selection) = crate::test::print(
|
||||
r#" L0
|
||||
#[|these]# line #(|ranges)# are #(|merged)# L1
|
||||
L2
|
||||
single one-line #(|range)# L3
|
||||
L4
|
||||
single #(|multiline L5
|
||||
range)# L6
|
||||
L7
|
||||
these #(|multiline L8
|
||||
ranges)# are #(|also L9
|
||||
merged)# L10
|
||||
L11
|
||||
adjacent #(|ranges)# L12
|
||||
are merged #(|the same way)# L13
|
||||
"#,
|
||||
);
|
||||
let rope = Rope::from_str(&text);
|
||||
assert_eq!(
|
||||
vec![(1, 1), (3, 3), (5, 6), (8, 10), (12, 13)],
|
||||
selection.line_ranges(rope.slice(..)).collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cursor() {
|
||||
let r = Rope::from_str("\r\nHi\r\nthere!");
|
||||
|
@ -1025,9 +1025,10 @@ pub fn language_configuration_for_injection_string(
|
||||
match capture {
|
||||
InjectionLanguageMarker::Name(string) => self.language_config_for_name(string),
|
||||
InjectionLanguageMarker::Filename(file) => self.language_config_for_file_name(file),
|
||||
InjectionLanguageMarker::Shebang(shebang) => {
|
||||
self.language_config_for_language_id(shebang)
|
||||
}
|
||||
InjectionLanguageMarker::Shebang(shebang) => self
|
||||
.language_config_ids_by_shebang
|
||||
.get(shebang)
|
||||
.and_then(|&id| self.language_configs.get(id).cloned()),
|
||||
}
|
||||
}
|
||||
|
||||
@ -1363,13 +1364,14 @@ fn point_sub(a: Point, b: Point) -> Point {
|
||||
let depth = layer.depth + 1;
|
||||
// TODO: can't inline this since matches borrows self.layers
|
||||
for (config, ranges) in injections {
|
||||
let parent = Some(layer_id);
|
||||
let new_layer = LanguageLayer {
|
||||
tree: None,
|
||||
config,
|
||||
depth,
|
||||
ranges,
|
||||
flags: LayerUpdateFlags::empty(),
|
||||
parent: Some(layer_id),
|
||||
parent: None,
|
||||
};
|
||||
|
||||
// Find an identical existing layer
|
||||
@ -1381,6 +1383,7 @@ fn point_sub(a: Point, b: Point) -> Point {
|
||||
|
||||
// ...or insert a new one.
|
||||
let layer_id = layer.unwrap_or_else(|| self.layers.insert(new_layer));
|
||||
self.layers[layer_id].parent = parent;
|
||||
|
||||
queue.push_back(layer_id);
|
||||
}
|
||||
@ -1428,8 +1431,11 @@ pub fn highlight_iter<'a>(
|
||||
// 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));
|
||||
@ -1734,7 +1740,7 @@ fn traverse(point: Point, text: &Tendril) -> Point {
|
||||
}
|
||||
|
||||
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,
|
||||
@ -2688,6 +2694,8 @@ fn pretty_print_tree_impl<W: fmt::Write>(
|
||||
}
|
||||
|
||||
write!(fmt, "({}", node.kind())?;
|
||||
} else {
|
||||
write!(fmt, " \"{}\"", node.kind())?;
|
||||
}
|
||||
|
||||
// Handle children.
|
||||
@ -2946,7 +2954,7 @@ fn assert_pretty_print(
|
||||
#[test]
|
||||
fn test_pretty_print() {
|
||||
let source = r#"// Hello"#;
|
||||
assert_pretty_print("rust", source, "(line_comment)", 0, source.len());
|
||||
assert_pretty_print("rust", source, "(line_comment \"//\")", 0, source.len());
|
||||
|
||||
// A large tree should be indented with fields:
|
||||
let source = r#"fn main() {
|
||||
@ -2956,16 +2964,16 @@ fn test_pretty_print() {
|
||||
"rust",
|
||||
source,
|
||||
concat!(
|
||||
"(function_item\n",
|
||||
"(function_item \"fn\"\n",
|
||||
" name: (identifier)\n",
|
||||
" parameters: (parameters)\n",
|
||||
" body: (block\n",
|
||||
" parameters: (parameters \"(\" \")\")\n",
|
||||
" body: (block \"{\"\n",
|
||||
" (expression_statement\n",
|
||||
" (macro_invocation\n",
|
||||
" macro: (identifier)\n",
|
||||
" (token_tree\n",
|
||||
" (string_literal\n",
|
||||
" (string_content)))))))",
|
||||
" macro: (identifier) \"!\"\n",
|
||||
" (token_tree \"(\"\n",
|
||||
" (string_literal \"\"\"\n",
|
||||
" (string_content) \"\"\") \")\")) \";\") \"}\"))",
|
||||
),
|
||||
0,
|
||||
source.len(),
|
||||
@ -2977,7 +2985,7 @@ fn test_pretty_print() {
|
||||
|
||||
// Error nodes are printed as errors:
|
||||
let source = r#"}{"#;
|
||||
assert_pretty_print("rust", source, "(ERROR)", 0, source.len());
|
||||
assert_pretty_print("rust", source, "(ERROR \"}\" \"{\")", 0, source.len());
|
||||
|
||||
// Fields broken under unnamed nodes are determined correctly.
|
||||
// In the following source, `object` belongs to the `singleton_method`
|
||||
@ -2992,11 +3000,11 @@ fn test_pretty_print() {
|
||||
"ruby",
|
||||
source,
|
||||
concat!(
|
||||
"(singleton_method\n",
|
||||
" object: (self)\n",
|
||||
"(singleton_method \"def\"\n",
|
||||
" object: (self) \".\"\n",
|
||||
" name: (identifier)\n",
|
||||
" body: (body_statement\n",
|
||||
" (true)))"
|
||||
" (true)) \"end\")"
|
||||
),
|
||||
0,
|
||||
source.len(),
|
||||
|
@ -204,7 +204,7 @@ fn layer_id_containing_byte_range(&self, start: usize, end: usize) -> LayerId {
|
||||
|
||||
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)
|
||||
}
|
||||
|
@ -1,8 +1,12 @@
|
||||
use std::cell::Cell;
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt::Debug;
|
||||
use std::ops::Range;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use crate::doc_formatter::FormattedGrapheme;
|
||||
use crate::syntax::Highlight;
|
||||
use crate::Tendril;
|
||||
use crate::{Position, Tendril};
|
||||
|
||||
/// An inline annotation is continuous text shown
|
||||
/// on the screen before the grapheme that starts at
|
||||
@ -75,19 +79,98 @@ pub fn new(char_idx: usize, grapheme: impl Into<Tendril>) -> Self {
|
||||
}
|
||||
}
|
||||
|
||||
/// Line annotations allow for virtual text between normal
|
||||
/// text lines. They cause `height` empty lines to be inserted
|
||||
/// below the document line that contains `anchor_char_idx`.
|
||||
/// Line annotations allow inserting virtual text lines between normal text
|
||||
/// lines. These lines can be filled with text in the rendering code as their
|
||||
/// contents have no effect beyond visual appearance.
|
||||
///
|
||||
/// These lines can be filled with text in the rendering code
|
||||
/// as their contents have no effect beyond visual appearance.
|
||||
/// The height of virtual text is usually not known ahead of time as virtual
|
||||
/// text often requires softwrapping. Furthermore the height of some virtual
|
||||
/// text like side-by-side diffs depends on the height of the text (again
|
||||
/// influenced by softwrap) and other virtual text. Therefore line annotations
|
||||
/// are computed on the fly instead of ahead of time like other annotations.
|
||||
///
|
||||
/// To insert a line after a document line simply set
|
||||
/// `anchor_char_idx` to `doc.line_to_char(line_idx)`
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LineAnnotation {
|
||||
pub anchor_char_idx: usize,
|
||||
pub height: usize,
|
||||
/// The core of this trait `insert_virtual_lines` function. It is called at the
|
||||
/// end of every visual line and allows the `LineAnnotation` to insert empty
|
||||
/// virtual lines. Apart from that the `LineAnnotation` trait has multiple
|
||||
/// methods that allow it to track anchors in the document.
|
||||
///
|
||||
/// When a new traversal of a document starts `reset_pos` is called. Afterwards
|
||||
/// the other functions are called with indices that are larger then the
|
||||
/// one passed to `reset_pos`. This allows performing a binary search (use
|
||||
/// `partition_point`) in `reset_pos` once and then to only look at the next
|
||||
/// anchor during each method call.
|
||||
///
|
||||
/// The `reset_pos`, `skip_conceal` and `process_anchor` functions all return a
|
||||
/// `char_idx` anchor. This anchor is stored when transversing the document and
|
||||
/// when the grapheme at the anchor is traversed the `process_anchor` function
|
||||
/// is called.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// All functions only receive immutable references to `self`.
|
||||
/// `LineAnnotation`s that want to store an internal position or
|
||||
/// state of some kind should use `Cell`. Using interior mutability for
|
||||
/// caches is preferable as otherwise a lot of lifetimes become invariant
|
||||
/// which complicates APIs a lot.
|
||||
pub trait LineAnnotation {
|
||||
/// Resets the internal position to `char_idx`. This function is called
|
||||
/// when a new traversal of a document starts.
|
||||
///
|
||||
/// All `char_idx` passed to `insert_virtual_lines` are strictly monotonically increasing
|
||||
/// with the first `char_idx` greater or equal to the `char_idx`
|
||||
/// passed to this function.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
|
||||
/// replaces the currently registered anchor. Return `usize::MAX` to ignore
|
||||
fn reset_pos(&mut self, _char_idx: usize) -> usize {
|
||||
usize::MAX
|
||||
}
|
||||
|
||||
/// Called when a text is concealed that contains an anchor registered by this `LineAnnotation`.
|
||||
/// In this case the line decorations **must** ensure that virtual text anchored within that
|
||||
/// char range is skipped.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
|
||||
/// **after the end of conceal_end_char_idx**
|
||||
/// replaces the currently registered anchor. Return `usize::MAX` to ignore
|
||||
fn skip_concealed_anchors(&mut self, conceal_end_char_idx: usize) -> usize {
|
||||
self.reset_pos(conceal_end_char_idx)
|
||||
}
|
||||
|
||||
/// Process an anchor (horizontal position is provided) and returns the next anchor.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
|
||||
/// replaces the currently registered anchor. Return `usize::MAX` to ignore
|
||||
fn process_anchor(&mut self, _grapheme: &FormattedGrapheme) -> usize {
|
||||
usize::MAX
|
||||
}
|
||||
|
||||
/// This function is called at the end of a visual line to insert virtual text
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The number of additional virtual lines to reserve
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// The `line_end_visual_pos` parameter indicates the visual vertical distance
|
||||
/// from the start of block where the traversal starts. This includes the offset
|
||||
/// from other `LineAnnotations`. This allows inline annotations to consider
|
||||
/// the height of the text and "align" two different documents (like for side
|
||||
/// by side diffs). These annotations that want to "align" two documents should
|
||||
/// therefore be added last so that other virtual text is also considered while aligning
|
||||
fn insert_virtual_lines(
|
||||
&mut self,
|
||||
line_end_char_idx: usize,
|
||||
line_end_visual_pos: Position,
|
||||
doc_line: usize,
|
||||
) -> Position;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@ -143,13 +226,68 @@ fn reset_pos<A, M>(layers: &[Layer<A, M>], pos: usize, get_pos: impl Fn(&A) -> u
|
||||
}
|
||||
}
|
||||
|
||||
/// Safety: We store LineAnnotation in a NonNull pointer. This is necessary to work
|
||||
/// around an unfortunate inconsistency in rusts variance system that unnnecesarily
|
||||
/// makes the lifetime invariant if implemented with safe code. This makes the
|
||||
/// DocFormatter API very cumbersome/basically impossible to work with.
|
||||
///
|
||||
/// Normally object types `dyn Foo + 'a` are covariant so if we used `Box<dyn LineAnnotation + 'a>` below
|
||||
/// everything would be alright. However we want to use `Cell<Box<dyn LineAnnotation + 'a>>`
|
||||
/// to be able to call the mutable function on `LineAnnotation`. The problem is that
|
||||
/// some types like `Cell` make all their arguments invariant. This is important for soundness
|
||||
/// normally for the same reasons that `&'a mut T` is invariant over `T`
|
||||
/// (see <https://doc.rust-lang.org/nomicon/subtyping.html>). However for `&'a mut` (`dyn Foo + 'b`)
|
||||
/// there is a specical rule in the language to make `'b` covariant (otherwise trait objects would be
|
||||
/// super annoying to use). See <https://users.rust-lang.org/t/solved-variance-of-dyn-trait-a> for
|
||||
/// why this is sound. Sadly that rule doesn't apply to `Cell<Box<(dyn Foo + 'a)>`
|
||||
/// (or other invariant types like `UnsafeCell` or `*mut (dyn Foo + 'a)`).
|
||||
///
|
||||
/// We sidestep the problem by using `NonNull` which is covariant. In the
|
||||
/// special case of trait objects this is sound (easily checked by adding a
|
||||
/// `PhantomData<&'a mut Foo + 'a)>` field). We don't need an explicit `Cell`
|
||||
/// type here because we never hand out any refereces to the trait objects. That
|
||||
/// means any reference to the pointer can create a valid multable reference
|
||||
/// that is covariant over `'a` (or in other words it's a raw pointer, as long as
|
||||
/// we don't hand out references we are free to do whatever we want).
|
||||
struct RawBox<T: ?Sized>(NonNull<T>);
|
||||
|
||||
impl<T: ?Sized> RawBox<T> {
|
||||
/// Safety: Only a single mutable reference
|
||||
/// created by this function may exist at a given time.
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
unsafe fn get(&self) -> &mut T {
|
||||
&mut *self.0.as_ptr()
|
||||
}
|
||||
}
|
||||
impl<T: ?Sized> From<Box<T>> for RawBox<T> {
|
||||
fn from(box_: Box<T>) -> Self {
|
||||
// obviously safe because Box::into_raw never returns null
|
||||
unsafe { Self(NonNull::new_unchecked(Box::into_raw(box_))) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized> Drop for RawBox<T> {
|
||||
fn drop(&mut self) {
|
||||
unsafe { drop(Box::from_raw(self.0.as_ptr())) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Annotations that change that is displayed when the document is render.
|
||||
/// Also commonly called virtual text.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
#[derive(Default)]
|
||||
pub struct TextAnnotations<'a> {
|
||||
inline_annotations: Vec<Layer<'a, InlineAnnotation, Option<Highlight>>>,
|
||||
overlays: Vec<Layer<'a, Overlay, Option<Highlight>>>,
|
||||
line_annotations: Vec<Layer<'a, LineAnnotation, ()>>,
|
||||
line_annotations: Vec<(Cell<usize>, RawBox<dyn LineAnnotation + 'a>)>,
|
||||
}
|
||||
|
||||
impl Debug for TextAnnotations<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TextAnnotations")
|
||||
.field("inline_annotations", &self.inline_annotations)
|
||||
.field("overlays", &self.overlays)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> TextAnnotations<'a> {
|
||||
@ -157,9 +295,9 @@ impl<'a> TextAnnotations<'a> {
|
||||
pub fn reset_pos(&self, char_idx: usize) {
|
||||
reset_pos(&self.inline_annotations, char_idx, |annot| annot.char_idx);
|
||||
reset_pos(&self.overlays, char_idx, |annot| annot.char_idx);
|
||||
reset_pos(&self.line_annotations, char_idx, |annot| {
|
||||
annot.anchor_char_idx
|
||||
});
|
||||
for (next_anchor, layer) in &self.line_annotations {
|
||||
next_anchor.set(unsafe { layer.get().reset_pos(char_idx) });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_overlay_highlights(
|
||||
@ -196,7 +334,9 @@ pub fn add_inline_annotations(
|
||||
layer: &'a [InlineAnnotation],
|
||||
highlight: Option<Highlight>,
|
||||
) -> &mut Self {
|
||||
self.inline_annotations.push((layer, highlight).into());
|
||||
if !layer.is_empty() {
|
||||
self.inline_annotations.push((layer, highlight).into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@ -211,7 +351,9 @@ pub fn add_inline_annotations(
|
||||
/// If multiple layers contain overlay at the same position
|
||||
/// the overlay from the layer added last will be show.
|
||||
pub fn add_overlay(&mut self, layer: &'a [Overlay], highlight: Option<Highlight>) -> &mut Self {
|
||||
self.overlays.push((layer, highlight).into());
|
||||
if !layer.is_empty() {
|
||||
self.overlays.push((layer, highlight).into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@ -219,8 +361,9 @@ pub fn add_overlay(&mut self, layer: &'a [Overlay], highlight: Option<Highlight>
|
||||
///
|
||||
/// The line annotations **must be sorted** by their `char_idx`.
|
||||
/// Multiple line annotations with the same `char_idx` **are not allowed**.
|
||||
pub fn add_line_annotation(&mut self, layer: &'a [LineAnnotation]) -> &mut Self {
|
||||
self.line_annotations.push((layer, ()).into());
|
||||
pub fn add_line_annotation(&mut self, layer: Box<dyn LineAnnotation + 'a>) -> &mut Self {
|
||||
self.line_annotations
|
||||
.push((Cell::new(usize::MAX), layer.into()));
|
||||
self
|
||||
}
|
||||
|
||||
@ -250,21 +393,35 @@ pub(crate) fn overlay_at(&self, char_idx: usize) -> Option<(&Overlay, Option<Hig
|
||||
overlay
|
||||
}
|
||||
|
||||
pub(crate) fn annotation_lines_at(&self, char_idx: usize) -> usize {
|
||||
self.line_annotations
|
||||
.iter()
|
||||
.map(|layer| {
|
||||
let mut lines = 0;
|
||||
while let Some(annot) = layer.annotations.get(layer.current_index.get()) {
|
||||
if annot.anchor_char_idx == char_idx {
|
||||
layer.current_index.set(layer.current_index.get() + 1);
|
||||
lines += annot.height
|
||||
} else {
|
||||
break;
|
||||
pub(crate) fn process_virtual_text_anchors(&self, grapheme: &FormattedGrapheme) {
|
||||
for (next_anchor, layer) in &self.line_annotations {
|
||||
loop {
|
||||
match next_anchor.get().cmp(&grapheme.char_idx) {
|
||||
Ordering::Less => next_anchor
|
||||
.set(unsafe { layer.get().skip_concealed_anchors(grapheme.char_idx) }),
|
||||
Ordering::Equal => {
|
||||
next_anchor.set(unsafe { layer.get().process_anchor(grapheme) })
|
||||
}
|
||||
}
|
||||
lines
|
||||
})
|
||||
.sum()
|
||||
Ordering::Greater => break,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn virtual_lines_at(
|
||||
&self,
|
||||
char_idx: usize,
|
||||
line_end_visual_pos: Position,
|
||||
doc_line: usize,
|
||||
) -> usize {
|
||||
let mut virt_off = Position::new(0, 0);
|
||||
for (_, layer) in &self.line_annotations {
|
||||
virt_off += unsafe {
|
||||
layer
|
||||
.get()
|
||||
.insert_virtual_lines(char_idx, line_end_visual_pos + virt_off, doc_line)
|
||||
};
|
||||
}
|
||||
virt_off.row
|
||||
}
|
||||
}
|
||||
|
@ -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 @@ fn stay_at_gaps(self) -> bool {
|
||||
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 @@ macro_rules! map {
|
||||
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
|
||||
|
125
helix-core/src/uri.rs
Normal file
125
helix-core/src/uri.rs
Normal file
@ -0,0 +1,125 @@
|
||||
use std::{
|
||||
fmt,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
/// A generic pointer to a file location.
|
||||
///
|
||||
/// Currently this type only supports paths to local files.
|
||||
///
|
||||
/// Cloning this type is cheap: the internal representation uses an Arc.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[non_exhaustive]
|
||||
pub enum Uri {
|
||||
File(Arc<Path>),
|
||||
}
|
||||
|
||||
impl Uri {
|
||||
// This clippy allow mirrors url::Url::from_file_path
|
||||
#[allow(clippy::result_unit_err)]
|
||||
pub fn to_url(&self) -> Result<url::Url, ()> {
|
||||
match self {
|
||||
Uri::File(path) => url::Url::from_file_path(path),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_path(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::File(path) => Some(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PathBuf> for Uri {
|
||||
fn from(path: PathBuf) -> Self {
|
||||
Self::File(path.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Uri {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::File(path) => write!(f, "{}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UrlConversionError {
|
||||
source: url::Url,
|
||||
kind: UrlConversionErrorKind,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UrlConversionErrorKind {
|
||||
UnsupportedScheme,
|
||||
UnableToConvert,
|
||||
}
|
||||
|
||||
impl fmt::Display for UrlConversionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.kind {
|
||||
UrlConversionErrorKind::UnsupportedScheme => {
|
||||
write!(
|
||||
f,
|
||||
"unsupported scheme '{}' in URL {}",
|
||||
self.source.scheme(),
|
||||
self.source
|
||||
)
|
||||
}
|
||||
UrlConversionErrorKind::UnableToConvert => {
|
||||
write!(f, "unable to convert URL to file path: {}", self.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for UrlConversionError {}
|
||||
|
||||
fn convert_url_to_uri(url: &url::Url) -> Result<Uri, UrlConversionErrorKind> {
|
||||
if url.scheme() == "file" {
|
||||
url.to_file_path()
|
||||
.map(|path| Uri::File(helix_stdx::path::normalize(path).into()))
|
||||
.map_err(|_| UrlConversionErrorKind::UnableToConvert)
|
||||
} else {
|
||||
Err(UrlConversionErrorKind::UnsupportedScheme)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<url::Url> for Uri {
|
||||
type Error = UrlConversionError;
|
||||
|
||||
fn try_from(url: url::Url) -> Result<Self, Self::Error> {
|
||||
convert_url_to_uri(&url).map_err(|kind| Self::Error { source: url, kind })
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&url::Url> for Uri {
|
||||
type Error = UrlConversionError;
|
||||
|
||||
fn try_from(url: &url::Url) -> Result<Self, Self::Error> {
|
||||
convert_url_to_uri(url).map_err(|kind| Self::Error {
|
||||
source: url.clone(),
|
||||
kind,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use url::Url;
|
||||
|
||||
#[test]
|
||||
fn unknown_scheme() {
|
||||
let url = Url::parse("csharp:/metadata/foo/bar/Baz.cs").unwrap();
|
||||
assert!(matches!(
|
||||
Uri::try_from(url),
|
||||
Err(UrlConversionError {
|
||||
kind: UrlConversionErrorKind::UnsupportedScheme,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
}
|
@ -20,8 +20,8 @@ anyhow = "1.0"
|
||||
log = "0.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "net", "sync"] }
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
fern = "0.6"
|
||||
fern = "0.7"
|
||||
|
@ -157,8 +157,8 @@ async fn get_port() -> Option<u16> {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn starting_request_args(&self) -> &Option<Value> {
|
||||
&self.starting_request_args
|
||||
pub fn starting_request_args(&self) -> Option<&Value> {
|
||||
self.starting_request_args.as_ref()
|
||||
}
|
||||
|
||||
pub async fn tcp_process(
|
||||
|
@ -1,4 +1,4 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
@ -311,7 +311,8 @@ pub struct Variable {
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Module {
|
||||
pub id: String, // TODO: || number
|
||||
#[serde(deserialize_with = "from_number")]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<PathBuf>,
|
||||
@ -331,6 +332,23 @@ pub struct Module {
|
||||
pub address_range: Option<String>,
|
||||
}
|
||||
|
||||
fn from_number<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum NumberOrString {
|
||||
Number(i64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
match NumberOrString::deserialize(deserializer)? {
|
||||
NumberOrString::Number(n) => Ok(n.to_string()),
|
||||
NumberOrString::String(s) => Ok(s),
|
||||
}
|
||||
}
|
||||
|
||||
pub mod requests {
|
||||
use super::*;
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
|
||||
@ -887,4 +905,18 @@ pub struct Memory {
|
||||
pub offset: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_module_id_from_number() {
|
||||
let raw = r#"{"id": 0, "name": "Name"}"#;
|
||||
let module: super::Module = serde_json::from_str(raw).expect("Error!");
|
||||
assert_eq!(module.id, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_module_id_from_string() {
|
||||
let raw = r#"{"id": "0", "name": "Name"}"#;
|
||||
let module: super::Module = serde_json::from_str(raw).expect("Error!");
|
||||
assert_eq!(module.id, "0");
|
||||
}
|
||||
}
|
||||
|
@ -19,11 +19,11 @@ tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "p
|
||||
# setup new events on initialization, hardware-lock-elision hugely benefits this case
|
||||
# as it essentially makes the lock entirely free as long as there is no writes
|
||||
parking_lot = { version = "0.12", features = ["hardware-lock-elision"] }
|
||||
once_cell = "1.18"
|
||||
once_cell = "1.20"
|
||||
|
||||
anyhow = "1"
|
||||
log = "0.4"
|
||||
futures-executor = "0.3.28"
|
||||
futures-executor = "0.3.31"
|
||||
|
||||
[features]
|
||||
integration_test = []
|
||||
|
@ -28,7 +28,10 @@ fn spawn(self) -> mpsc::Sender<Self::Event> {
|
||||
// so it should only be reached in case of total CPU overload.
|
||||
// However, a bounded channel is much more efficient so it's nice to use here
|
||||
let (tx, rx) = mpsc::channel(128);
|
||||
tokio::spawn(run(self, rx));
|
||||
// only spawn worker if we are inside runtime to avoid having to spawn a runtime for unrelated unit tests
|
||||
if tokio::runtime::Handle::try_current().is_ok() {
|
||||
tokio::spawn(run(self, rx));
|
||||
}
|
||||
tx
|
||||
}
|
||||
}
|
||||
|
@ -34,7 +34,9 @@
|
||||
use anyhow::Result;
|
||||
pub use cancel::{cancelable_future, cancelation, CancelRx, CancelTx};
|
||||
pub use debounce::{send_blocking, AsyncHook};
|
||||
pub use redraw::{lock_frame, redraw_requested, request_redraw, start_frame, RenderLockGuard};
|
||||
pub use redraw::{
|
||||
lock_frame, redraw_requested, request_redraw, start_frame, RenderLockGuard, RequestRedrawOnDrop,
|
||||
};
|
||||
pub use registry::Event;
|
||||
|
||||
mod cancel;
|
||||
|
@ -51,3 +51,12 @@ pub fn start_frame() {
|
||||
pub fn lock_frame() -> RenderLockGuard {
|
||||
RENDER_LOCK.read()
|
||||
}
|
||||
|
||||
/// A zero sized type that requests a redraw via [request_redraw] when the type [Drop]s.
|
||||
pub struct RequestRedrawOnDrop;
|
||||
|
||||
impl Drop for RequestRedrawOnDrop {
|
||||
fn drop(&mut self) {
|
||||
request_redraw();
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
toml = "0.8"
|
||||
etcetera = "0.8"
|
||||
tree-sitter.workspace = true
|
||||
once_cell = "1.19"
|
||||
once_cell = "1.20"
|
||||
log = "0.4"
|
||||
|
||||
# TODO: these two should be on !wasm32 only
|
||||
@ -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.13.0"
|
||||
dunce = "1.0.5"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
libloading = "0.8"
|
||||
|
@ -50,6 +50,7 @@ fn main() {
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|x| String::from_utf8(x.stdout).ok())
|
||||
.map(|x| x.trim().to_string())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@ -67,6 +68,7 @@ fn main() {
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|x| String::from_utf8(x.stdout).ok())
|
||||
.map(|x| x.trim().to_string())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
@ -422,7 +422,7 @@ fn build_tree_sitter_library(
|
||||
}
|
||||
}
|
||||
|
||||
let recompile = needs_recompile(&library_path, &parser_path, &scanner_path)
|
||||
let recompile = needs_recompile(&library_path, &parser_path, scanner_path.as_ref())
|
||||
.context("Failed to compare source and binary timestamps")?;
|
||||
|
||||
if !recompile {
|
||||
@ -568,7 +568,7 @@ fn build_tree_sitter_library(
|
||||
fn needs_recompile(
|
||||
lib_path: &Path,
|
||||
parser_c_path: &Path,
|
||||
scanner_path: &Option<PathBuf>,
|
||||
scanner_path: Option<&PathBuf>,
|
||||
) -> Result<bool> {
|
||||
if !lib_path.exists() {
|
||||
return Ok(true);
|
||||
|
@ -225,13 +225,17 @@ fn get_name(v: &Value) -> Option<&str> {
|
||||
/// 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`, `.jj` 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(".jj").exists()
|
||||
|| ancestor.join(".helix").exists()
|
||||
{
|
||||
return (ancestor.to_owned(), false);
|
||||
}
|
||||
}
|
||||
|
176
helix-lsp-types/Cargo.lock
generated
Normal file
176
helix-lsp-types/Cargo.lock
generated
Normal file
@ -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",
|
||||
]
|
34
helix-lsp-types/Cargo.toml
Normal file
34
helix-lsp-types/Cargo.toml
Normal file
@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "helix-lsp-types"
|
||||
version = "0.95.1"
|
||||
authors = [
|
||||
# Original authors
|
||||
"Markus Westerlind <marwes91@gmail.com>",
|
||||
"Bruno Medeiros <bruno.do.medeiros@gmail.com>",
|
||||
# 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.132"
|
||||
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 = []
|
22
helix-lsp-types/LICENSE
Normal file
22
helix-lsp-types/LICENSE
Normal file
@ -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.
|
||||
|
3
helix-lsp-types/README.md
Normal file
3
helix-lsp-types/README.md
Normal file
@ -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.
|
127
helix-lsp-types/src/call_hierarchy.rs
Normal file
127
helix-lsp-types/src/call_hierarchy.rs
Normal file
@ -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<CallHierarchyOptions> for CallHierarchyServerCapability {
|
||||
fn from(from: CallHierarchyOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<Vec<SymbolTag>>,
|
||||
|
||||
/// More detail for this item, e.g. the signature of a function.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<String>,
|
||||
|
||||
/// 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<Value>,
|
||||
}
|
||||
|
||||
#[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<Range>,
|
||||
}
|
||||
|
||||
#[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<Range>,
|
||||
}
|
395
helix-lsp-types/src/code_action.rs
Normal file
395
helix-lsp-types/src/code_action.rs
Normal file
@ -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<CodeActionOptions> for CodeActionProviderCapability {
|
||||
fn from(from: CodeActionOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<bool>,
|
||||
|
||||
/// 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<CodeActionLiteralSupport>,
|
||||
|
||||
/// Whether code action supports the `isPreferred` property.
|
||||
///
|
||||
/// @since 3.15.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_preferred_support: Option<bool>,
|
||||
|
||||
/// Whether code action supports the `disabled` property.
|
||||
///
|
||||
/// @since 3.16.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub disabled_support: Option<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<CodeActionCapabilityResolveSupport>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
/// 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<CodeActionOrCommand>;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum CodeActionOrCommand {
|
||||
Command(Command),
|
||||
CodeAction(CodeAction),
|
||||
}
|
||||
|
||||
impl From<Command> for CodeActionOrCommand {
|
||||
fn from(command: Command) -> Self {
|
||||
CodeActionOrCommand::Command(command)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CodeAction> 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<String> 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<CodeActionKind>,
|
||||
|
||||
/// The diagnostics that this code action resolves.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub diagnostics: Option<Vec<Diagnostic>>,
|
||||
|
||||
/// The workspace edit this code action performs.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub edit: Option<WorkspaceEdit>,
|
||||
|
||||
/// 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<Command>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<CodeActionDisabled>,
|
||||
|
||||
/// 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<Value>,
|
||||
}
|
||||
|
||||
#[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<Diagnostic>,
|
||||
|
||||
/// 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<Vec<CodeActionKind>>,
|
||||
|
||||
/// The reason why code actions were requested.
|
||||
///
|
||||
/// @since 3.17.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub trigger_kind: Option<CodeActionTriggerKind>,
|
||||
}
|
||||
|
||||
#[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<Vec<CodeActionKind>>,
|
||||
|
||||
#[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<bool>,
|
||||
}
|
||||
|
||||
#[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"}]"#,
|
||||
)
|
||||
}
|
||||
}
|
66
helix-lsp-types/src/code_lens.rs
Normal file
66
helix-lsp-types/src/code_lens.rs
Normal file
@ -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<bool>,
|
||||
}
|
||||
|
||||
#[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<Command>,
|
||||
|
||||
/// 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<Value>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
}
|
122
helix-lsp-types/src/color.rs
Normal file
122
helix-lsp-types/src/color.rs
Normal file
@ -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<DocumentSelector>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ColorProviderCapability {
|
||||
Simple(bool),
|
||||
ColorProvider(ColorProviderOptions),
|
||||
Options(StaticTextDocumentColorProviderOptions),
|
||||
}
|
||||
|
||||
impl From<ColorProviderOptions> for ColorProviderCapability {
|
||||
fn from(from: ColorProviderOptions) -> Self {
|
||||
Self::ColorProvider(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<StaticTextDocumentColorProviderOptions> for ColorProviderCapability {
|
||||
fn from(from: StaticTextDocumentColorProviderOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<TextEdit>,
|
||||
|
||||
/// 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<Vec<TextEdit>>,
|
||||
}
|
622
helix-lsp-types/src/completion.rs
Normal file
622
helix-lsp-types/src/completion.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// Client supports commit characters on a completion item.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub commit_characters_support: Option<bool>,
|
||||
|
||||
/// 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<Vec<MarkupKind>>,
|
||||
|
||||
/// Client supports the deprecated property on a completion item.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub deprecated_support: Option<bool>,
|
||||
|
||||
/// Client supports the preselect property on a completion item.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preselect_support: Option<bool>,
|
||||
|
||||
/// 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<TagSupport<CompletionItemTag>>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<CompletionItemCapabilityResolveSupport>,
|
||||
|
||||
/// 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<InsertTextModeSupport>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InsertTextModeSupport {
|
||||
pub value_set: Vec<InsertTextMode>,
|
||||
}
|
||||
|
||||
/// 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><cursor><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<Vec<CompletionItemKind>>,
|
||||
}
|
||||
|
||||
#[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<Vec<String>>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// The client supports the following `CompletionItem` specific
|
||||
/// capabilities.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completion_item: Option<CompletionItemCapability>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completion_item_kind: Option<CompletionItemKindCapability>,
|
||||
|
||||
/// The client supports to send additional context information for a
|
||||
/// `textDocument/completion` request.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context_support: Option<bool>,
|
||||
|
||||
/// 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<InsertTextMode>,
|
||||
|
||||
/// The client supports the following `CompletionList` specific
|
||||
/// capabilities.
|
||||
///
|
||||
/// @since 3.17.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub completion_list: Option<CompletionListCapability>,
|
||||
}
|
||||
|
||||
/// 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<TextEdit> for CompletionTextEdit {
|
||||
fn from(edit: TextEdit) -> Self {
|
||||
CompletionTextEdit::Edit(edit)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InsertReplaceEdit> 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<bool>,
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
|
||||
#[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<CompletionOptionsCompletionItem>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
}
|
||||
|
||||
#[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<CompletionItem>),
|
||||
List(CompletionList),
|
||||
}
|
||||
|
||||
impl From<Vec<CompletionItem>> for CompletionResponse {
|
||||
fn from(items: Vec<CompletionItem>) -> Self {
|
||||
CompletionResponse::Array(items)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CompletionList> 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<CompletionContext>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
/// 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<CompletionItem>,
|
||||
}
|
||||
|
||||
#[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<CompletionItemLabelDetails>,
|
||||
|
||||
/// 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<CompletionItemKind>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// A human-readable string that represents a doc-comment.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub documentation: Option<Documentation>,
|
||||
|
||||
/// Indicates if this item is deprecated.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub deprecated: Option<bool>,
|
||||
|
||||
/// Select this item when showing.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub preselect: Option<bool>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<cursor position>` 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<String>,
|
||||
|
||||
/// 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<InsertTextFormat>,
|
||||
|
||||
/// 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<InsertTextMode>,
|
||||
|
||||
/// 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<CompletionTextEdit>,
|
||||
|
||||
/// 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<Vec<TextEdit>>,
|
||||
|
||||
/// 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<Command>,
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
|
||||
/// 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<Value>,
|
||||
|
||||
/// Tags for this completion item.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tags: Option<Vec<CompletionItemTag>>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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)
|
||||
);
|
||||
}
|
||||
}
|
269
helix-lsp-types/src/document_diagnostic.rs
Normal file
269
helix-lsp-types/src/document_diagnostic.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// Whether the clients supports related documents for document diagnostic pulls.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub related_document_support: Option<bool>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// The result ID of a previous response if provided.
|
||||
pub previous_result_id: Option<String>,
|
||||
|
||||
#[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<String>,
|
||||
|
||||
/// The actual items.
|
||||
pub items: Vec<Diagnostic>,
|
||||
}
|
||||
|
||||
/// 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<FullDocumentDiagnosticReport> for DocumentDiagnosticReportKind {
|
||||
fn from(from: FullDocumentDiagnosticReport) -> Self {
|
||||
DocumentDiagnosticReportKind::Full(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UnchangedDocumentDiagnosticReport> 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<HashMap<Url, DocumentDiagnosticReportKind>>,
|
||||
// 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<HashMap<Url, DocumentDiagnosticReportKind>>,
|
||||
// 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<RelatedFullDocumentDiagnosticReport> for DocumentDiagnosticReport {
|
||||
fn from(from: RelatedFullDocumentDiagnosticReport) -> Self {
|
||||
DocumentDiagnosticReport::Full(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RelatedUnchangedDocumentDiagnosticReport> 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<HashMap<Url, DocumentDiagnosticReportKind>>,
|
||||
// relatedDocuments?: { [uri: string]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; };
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
|
||||
#[serde(untagged)]
|
||||
pub enum DocumentDiagnosticReportResult {
|
||||
Report(DocumentDiagnosticReport),
|
||||
Partial(DocumentDiagnosticReportPartialResult),
|
||||
}
|
||||
|
||||
impl From<DocumentDiagnosticReport> for DocumentDiagnosticReportResult {
|
||||
fn from(from: DocumentDiagnosticReport) -> Self {
|
||||
DocumentDiagnosticReportResult::Report(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DocumentDiagnosticReportPartialResult> 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,
|
||||
}
|
||||
}
|
||||
}
|
51
helix-lsp-types/src/document_highlight.rs
Normal file
51
helix-lsp-types/src/document_highlight.rs
Normal file
@ -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<DocumentHighlightKind>,
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
67
helix-lsp-types/src/document_link.rs
Normal file
67
helix-lsp-types/src/document_link.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// Whether the client support the `tooltip` property on `DocumentLink`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tooltip_support: Option<bool>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
#[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<Url>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<Value>,
|
||||
}
|
134
helix-lsp-types/src/document_symbols.rs
Normal file
134
helix-lsp-types/src/document_symbols.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// Specific capabilities for the `SymbolKind`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub symbol_kind: Option<SymbolKindCapability>,
|
||||
|
||||
/// The client support hierarchical document symbols.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub hierarchical_document_symbol_support: Option<bool>,
|
||||
|
||||
/// 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<TagSupport<SymbolTag>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum DocumentSymbolResponse {
|
||||
Flat(Vec<SymbolInformation>),
|
||||
Nested(Vec<DocumentSymbol>),
|
||||
}
|
||||
|
||||
impl From<Vec<SymbolInformation>> for DocumentSymbolResponse {
|
||||
fn from(info: Vec<SymbolInformation>) -> Self {
|
||||
DocumentSymbolResponse::Flat(info)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<DocumentSymbol>> for DocumentSymbolResponse {
|
||||
fn from(symbols: Vec<DocumentSymbol>) -> 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<String>,
|
||||
/// 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<Vec<SymbolTag>>,
|
||||
/// Indicates if this symbol is deprecated.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[deprecated(note = "Use tags instead")]
|
||||
pub deprecated: Option<bool>,
|
||||
/// 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<Vec<DocumentSymbol>>,
|
||||
}
|
||||
|
||||
/// 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<Vec<SymbolTag>>,
|
||||
|
||||
/// Indicates if this symbol is deprecated.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[deprecated(note = "Use tags instead")]
|
||||
pub deprecated: Option<bool>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
54
helix-lsp-types/src/error_codes.rs
Normal file
54
helix-lsp-types/src/error_codes.rs
Normal file
@ -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;
|
213
helix-lsp-types/src/file_operations.rs
Normal file
213
helix-lsp-types/src/file_operations.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// The client has support for sending didCreateFiles notifications.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub did_create: Option<bool>,
|
||||
|
||||
/// The server is interested in receiving willCreateFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_create: Option<bool>,
|
||||
|
||||
/// The server is interested in receiving didRenameFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub did_rename: Option<bool>,
|
||||
|
||||
/// The server is interested in receiving willRenameFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_rename: Option<bool>,
|
||||
|
||||
/// The server is interested in receiving didDeleteFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub did_delete: Option<bool>,
|
||||
|
||||
/// The server is interested in receiving willDeleteFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_delete: Option<bool>,
|
||||
}
|
||||
|
||||
#[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<FileOperationRegistrationOptions>,
|
||||
|
||||
/// The server is interested in receiving willCreateFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_create: Option<FileOperationRegistrationOptions>,
|
||||
|
||||
/// The server is interested in receiving didRenameFiles
|
||||
/// notifications.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub did_rename: Option<FileOperationRegistrationOptions>,
|
||||
|
||||
/// The server is interested in receiving willRenameFiles requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_rename: Option<FileOperationRegistrationOptions>,
|
||||
|
||||
/// The server is interested in receiving didDeleteFiles file
|
||||
/// notifications.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub did_delete: Option<FileOperationRegistrationOptions>,
|
||||
|
||||
/// The server is interested in receiving willDeleteFiles file
|
||||
/// requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub will_delete: Option<FileOperationRegistrationOptions>,
|
||||
}
|
||||
|
||||
/// 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<FileOperationFilter>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
/// 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<FileOperationPatternKind>,
|
||||
|
||||
/// Additional options used during matching.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub options: Option<FileOperationPatternOptions>,
|
||||
}
|
||||
|
||||
/// 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<FileCreate>,
|
||||
}
|
||||
/// 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<FileRename>,
|
||||
}
|
||||
|
||||
/// 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<FileDelete>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
145
helix-lsp-types/src/folding_range.rs
Normal file
145
helix-lsp-types/src/folding_range.rs
Normal file
@ -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<StaticTextDocumentColorProviderOptions> for FoldingRangeProviderCapability {
|
||||
fn from(from: StaticTextDocumentColorProviderOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FoldingProviderOptions> for FoldingRangeProviderCapability {
|
||||
fn from(from: FoldingProviderOptions) -> Self {
|
||||
Self::FoldingProvider(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<Vec<FoldingRangeKind>>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// 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<u32>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// Specific options for the folding range kind.
|
||||
///
|
||||
/// @since 3.17.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub folding_range_kind: Option<FoldingRangeKindCapability>,
|
||||
|
||||
/// Specific options for the folding range.
|
||||
///
|
||||
/// @since 3.17.0
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub folding_range: Option<FoldingRangeCapability>,
|
||||
}
|
||||
|
||||
/// 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<u32>,
|
||||
|
||||
/// 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<u32>,
|
||||
|
||||
/// 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<FoldingRangeKind>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
153
helix-lsp-types/src/formatting.rs
Normal file
153
helix-lsp-types/src/formatting.rs
Normal file
@ -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<Vec<String>>,
|
||||
}
|
||||
|
||||
#[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<String, FormattingProperty>,
|
||||
|
||||
/// Trim trailing whitespace on a line.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub trim_trailing_whitespace: Option<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
#[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<DocumentSelector>,
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
}
|
||||
|
||||
#[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}"#,
|
||||
);
|
||||
}
|
||||
}
|
86
helix-lsp-types/src/hover.rs
Normal file
86
helix-lsp-types/src/hover.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// 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<Vec<MarkupKind>>,
|
||||
}
|
||||
|
||||
/// 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<HoverOptions> for HoverProviderCapability {
|
||||
fn from(from: HoverOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<Range>,
|
||||
}
|
||||
|
||||
/// 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<MarkedString>),
|
||||
Markup(MarkupContent),
|
||||
}
|
281
helix-lsp-types/src/inlay_hint.rs
Normal file
281
helix-lsp-types/src/inlay_hint.rs
Normal file
@ -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<bool>,
|
||||
|
||||
/// Indicates which properties a client can resolve lazily on a inlay
|
||||
/// hint.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub resolve_support: Option<InlayHintResolveClientCapabilities>,
|
||||
}
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
/// 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<InlayHintKind>,
|
||||
|
||||
/// 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<Vec<TextEdit>>,
|
||||
|
||||
/// 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<InlayHintTooltip>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<LSPAny>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum InlayHintLabel {
|
||||
String(String),
|
||||
LabelParts(Vec<InlayHintLabelPart>),
|
||||
}
|
||||
|
||||
impl From<String> for InlayHintLabel {
|
||||
#[inline]
|
||||
fn from(from: String) -> Self {
|
||||
Self::String(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<InlayHintLabelPart>> for InlayHintLabel {
|
||||
#[inline]
|
||||
fn from(from: Vec<InlayHintLabelPart>) -> Self {
|
||||
Self::LabelParts(from)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum InlayHintTooltip {
|
||||
String(String),
|
||||
MarkupContent(MarkupContent),
|
||||
}
|
||||
|
||||
impl From<String> for InlayHintTooltip {
|
||||
#[inline]
|
||||
fn from(from: String) -> Self {
|
||||
Self::String(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MarkupContent> 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<InlayHintLabelPartTooltip>,
|
||||
|
||||
/// 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<Location>,
|
||||
|
||||
/// 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<Command>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum InlayHintLabelPartTooltip {
|
||||
String(String),
|
||||
MarkupContent(MarkupContent),
|
||||
}
|
||||
|
||||
impl From<String> for InlayHintLabelPartTooltip {
|
||||
#[inline]
|
||||
fn from(from: String) -> Self {
|
||||
Self::String(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MarkupContent> 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<String>,
|
||||
}
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
// TODO(sno2): add tests once stabilized
|
162
helix-lsp-types/src/inline_completion.rs
Normal file
162
helix-lsp-types/src/inline_completion.rs
Normal file
@ -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<bool>,
|
||||
}
|
||||
|
||||
/// 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<SelectedCompletionInfo>,
|
||||
}
|
||||
|
||||
/// 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<InlineCompletionItem>),
|
||||
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<InlineCompletionItem>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// 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<Range>,
|
||||
/// An optional command that is executed *after* inserting this
|
||||
/// completion.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub command: Option<Command>,
|
||||
/// 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<InsertTextFormat>,
|
||||
}
|
218
helix-lsp-types/src/inline_value.rs
Normal file
218
helix-lsp-types/src/inline_value.rs
Normal file
@ -0,0 +1,218 @@
|
||||
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<String>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// 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<InlineValueText> for InlineValue {
|
||||
#[inline]
|
||||
fn from(from: InlineValueText) -> Self {
|
||||
Self::Text(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InlineValueVariableLookup> for InlineValue {
|
||||
#[inline]
|
||||
fn from(from: InlineValueVariableLookup) -> Self {
|
||||
Self::VariableLookup(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InlineValueEvaluatableExpression> 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<bool>,
|
||||
}
|
||||
|
||||
#[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}}}"#,
|
||||
);
|
||||
}
|
||||
}
|
2883
helix-lsp-types/src/lib.rs
Normal file
2883
helix-lsp-types/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
61
helix-lsp-types/src/linked_editing.rs
Normal file
61
helix-lsp-types/src/linked_editing.rs
Normal file
@ -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<Range>,
|
||||
|
||||
/// 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<String>,
|
||||
}
|
336
helix-lsp-types/src/lsif.rs
Normal file
336
helix-lsp-types/src/lsif.rs
Normal file
@ -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 <https://microsoft.github.io/language-server-protocol/specifications/lsif/0.6.0/specification/>
|
||||
|
||||
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<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
#[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<RangeBasedDocumentSymbol>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum DocumentSymbolOrRangeBasedVec {
|
||||
DocumentSymbol(Vec<crate::DocumentSymbol>),
|
||||
RangeBased(Vec<RangeBasedDocumentSymbol>),
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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),
|
||||
/// <https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#the-project-vertex>
|
||||
Project(Project),
|
||||
Document(Document),
|
||||
/// <https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#ranges>
|
||||
Range {
|
||||
#[serde(flatten)]
|
||||
range: Range,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
tag: Option<RangeTag>,
|
||||
},
|
||||
/// <https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set>
|
||||
ResultSet(ResultSet),
|
||||
Moniker(crate::Moniker),
|
||||
PackageInformation(PackageInformation),
|
||||
|
||||
#[serde(rename = "$event")]
|
||||
Event(Event),
|
||||
|
||||
DefinitionResult,
|
||||
DeclarationResult,
|
||||
TypeDefinitionResult,
|
||||
ReferenceResult,
|
||||
ImplementationResult,
|
||||
FoldingRangeResult {
|
||||
result: Vec<crate::FoldingRange>,
|
||||
},
|
||||
HoverResult {
|
||||
result: crate::Hover,
|
||||
},
|
||||
DocumentSymbolResult {
|
||||
result: DocumentSymbolOrRangeBasedVec,
|
||||
},
|
||||
DocumentLinkResult {
|
||||
result: Vec<crate::DocumentLink>,
|
||||
},
|
||||
DiagnosticResult {
|
||||
result: Vec<crate::Diagnostic>,
|
||||
},
|
||||
}
|
||||
|
||||
#[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<Id>,
|
||||
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<ItemKind>,
|
||||
#[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,
|
||||
}
|
||||
|
||||
/// <https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#result-set>
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResultSet {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub key: Option<String>,
|
||||
}
|
||||
|
||||
/// <https://github.com/Microsoft/language-server-protocol/blob/master/indexFormat/specification.md#the-project-vertex>
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Project {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub resource: Option<Url>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<String>,
|
||||
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 <https://semver.org/>. 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<ToolInfo>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<Url>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub content: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub repository: Option<Repository>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
}
|
92
helix-lsp-types/src/moniker.rs
Normal file
92
helix-lsp-types/src/moniker.rs
Normal file
@ -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<MonikerKind>,
|
||||
}
|
361
helix-lsp-types/src/notification.rs
Normal file
361
helix-lsp-types/src/notification.rs
Normal file
@ -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<LSPObject, LSPArray>;
|
||||
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<N>()
|
||||
where
|
||||
N: Notification,
|
||||
N::Params: serde::Serialize,
|
||||
{
|
||||
}
|
||||
|
||||
macro_rules! check_macro {
|
||||
($name:tt) => {
|
||||
// check whether the macro name matches the method
|
||||
assert_eq!(<lsp_notification!($name) as Notification>::METHOD, $name);
|
||||
// test whether type checking passes for each component
|
||||
fake_call::<lsp_notification!($name)>();
|
||||
};
|
||||
}
|
||||
|
||||
#[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() {}
|
||||
}
|
134
helix-lsp-types/src/progress.rs
Normal file
134
helix-lsp-types/src/progress.rs
Normal file
@ -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<bool>,
|
||||
}
|
||||
|
||||
/// 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<ProgressToken>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// 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<String>,
|
||||
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum WorkDoneProgress {
|
||||
Begin(WorkDoneProgressBegin),
|
||||
Report(WorkDoneProgressReport),
|
||||
End(WorkDoneProgressEnd),
|
||||
}
|
30
helix-lsp-types/src/references.rs
Normal file
30
helix-lsp-types/src/references.rs
Normal file
@ -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,
|
||||
}
|
88
helix-lsp-types/src/rename.rs
Normal file
88
helix-lsp-types/src/rename.rs
Normal file
@ -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<bool>,
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<PrepareSupportDefaultBehavior>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
#[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,
|
||||
},
|
||||
}
|
1068
helix-lsp-types/src/request.rs
Normal file
1068
helix-lsp-types/src/request.rs
Normal file
File diff suppressed because it is too large
Load Diff
86
helix-lsp-types/src/selection_range.rs
Normal file
86
helix-lsp-types/src/selection_range.rs
Normal file
@ -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<bool>,
|
||||
}
|
||||
|
||||
#[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<SelectionRangeRegistrationOptions> for SelectionRangeProviderCapability {
|
||||
fn from(from: SelectionRangeRegistrationOptions) -> Self {
|
||||
Self::RegistrationOptions(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SelectionRangeOptions> for SelectionRangeProviderCapability {
|
||||
fn from(from: SelectionRangeOptions) -> Self {
|
||||
Self::Options(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> 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<Position>,
|
||||
|
||||
#[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<Box<SelectionRange>>,
|
||||
}
|
734
helix-lsp-types/src/semantic_tokens.rs
Normal file
734
helix-lsp-types/src/semantic_tokens.rs
Normal file
@ -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<String> 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<String> 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<String> 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<SemanticTokenType>,
|
||||
|
||||
/// The token modifiers a server uses.
|
||||
pub token_modifiers: Vec<SemanticTokenModifier>,
|
||||
}
|
||||
|
||||
/// 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<Vec<SemanticToken>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let data = Vec::<u32>::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<S>(tokens: &[SemanticToken], serializer: S) -> Result<S::Ok, S::Error>
|
||||
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<Option<Vec<SemanticToken>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(transparent)]
|
||||
struct Wrapper {
|
||||
#[serde(deserialize_with = "SemanticToken::deserialize_tokens")]
|
||||
tokens: Vec<SemanticToken>,
|
||||
}
|
||||
|
||||
Ok(Option::<Wrapper>::deserialize(deserializer)?.map(|wrapper| wrapper.tokens))
|
||||
}
|
||||
|
||||
fn serialize_tokens_opt<S>(
|
||||
data: &Option<Vec<SemanticToken>>,
|
||||
serializer: S,
|
||||
) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
#[derive(Serialize)]
|
||||
#[serde(transparent)]
|
||||
struct Wrapper {
|
||||
#[serde(serialize_with = "SemanticToken::serialize_tokens")]
|
||||
tokens: Vec<SemanticToken>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
|
||||
/// The actual tokens. For a detailed description about how the data is
|
||||
/// structured please see
|
||||
/// <https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L71>
|
||||
#[serde(
|
||||
deserialize_with = "SemanticToken::deserialize_tokens",
|
||||
serialize_with = "SemanticToken::serialize_tokens"
|
||||
)]
|
||||
pub data: Vec<SemanticToken>,
|
||||
}
|
||||
|
||||
/// @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<SemanticToken>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum SemanticTokensResult {
|
||||
Tokens(SemanticTokens),
|
||||
Partial(SemanticTokensPartialResult),
|
||||
}
|
||||
|
||||
impl From<SemanticTokens> for SemanticTokensResult {
|
||||
fn from(from: SemanticTokens) -> Self {
|
||||
SemanticTokensResult::Tokens(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SemanticTokensPartialResult> 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<Vec<SemanticToken>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum SemanticTokensFullDeltaResult {
|
||||
Tokens(SemanticTokens),
|
||||
TokensDelta(SemanticTokensDelta),
|
||||
PartialTokensDelta { edits: Vec<SemanticTokensEdit> },
|
||||
}
|
||||
|
||||
impl From<SemanticTokens> for SemanticTokensFullDeltaResult {
|
||||
fn from(from: SemanticTokens) -> Self {
|
||||
SemanticTokensFullDeltaResult::Tokens(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SemanticTokensDelta> 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<String>,
|
||||
/// For a detailed description how these edits are structured please see
|
||||
/// <https://github.com/microsoft/vscode-extension-samples/blob/5ae1f7787122812dcc84e37427ca90af5ee09f14/semantic-tokens-sample/vscode.proposed.d.ts#L131>
|
||||
pub edits: Vec<SemanticTokensEdit>,
|
||||
}
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<SemanticTokenType>,
|
||||
|
||||
/// The token modifiers that the client supports.
|
||||
pub token_modifiers: Vec<SemanticTokenModifier>,
|
||||
|
||||
/// The token formats the clients supports.
|
||||
pub formats: Vec<TokenFormat>,
|
||||
|
||||
/// Whether the client supports tokens that can overlap each other.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub overlapping_token_support: Option<bool>,
|
||||
|
||||
/// Whether the client supports tokens that can span multiple lines.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub multiline_token_support: Option<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// 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<SemanticTokensFullOptions>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
},
|
||||
}
|
||||
|
||||
/// @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<bool>,
|
||||
|
||||
/// Server supports providing semantic tokens for a full document.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub full: Option<SemanticTokensFullOptions>,
|
||||
}
|
||||
|
||||
#[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<SemanticTokensOptions> for SemanticTokensServerCapabilities {
|
||||
fn from(from: SemanticTokensOptions) -> Self {
|
||||
SemanticTokensServerCapabilities::SemanticTokensOptions(from)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SemanticTokensRegistrationOptions> 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<bool>,
|
||||
}
|
||||
|
||||
#[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<SemanticTokens> for SemanticTokensRangeResult {
|
||||
fn from(tokens: SemanticTokens) -> Self {
|
||||
SemanticTokensRangeResult::Tokens(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SemanticTokensPartialResult> 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}"#,
|
||||
);
|
||||
}
|
||||
}
|
207
helix-lsp-types/src/signature_help.rs
Normal file
207
helix-lsp-types/src/signature_help.rs
Normal file
@ -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<Vec<MarkupKind>>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameter_information: Option<ParameterInformationSettings>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
}
|
||||
|
||||
#[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<bool>,
|
||||
|
||||
/// The client supports the following `SignatureInformation`
|
||||
/// specific properties.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub signature_information: Option<SignatureInformationSettings>,
|
||||
|
||||
/// 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<bool>,
|
||||
}
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
|
||||
/// 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<Vec<String>>,
|
||||
|
||||
#[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<SignatureHelpContext>,
|
||||
|
||||
#[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<String>,
|
||||
|
||||
/// `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<SignatureHelp>,
|
||||
}
|
||||
|
||||
/// 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<SignatureInformation>,
|
||||
|
||||
/// The active signature.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub active_signature: Option<u32>,
|
||||
|
||||
/// The active parameter of the active signature.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub active_parameter: Option<u32>,
|
||||
}
|
||||
|
||||
/// 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<Documentation>,
|
||||
|
||||
/// The parameters of this signature.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameters: Option<Vec<ParameterInformation>>,
|
||||
|
||||
/// 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<u32>,
|
||||
}
|
||||
|
||||
/// 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<Documentation>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum ParameterLabel {
|
||||
Simple(String),
|
||||
LabelOffsets([u32; 2]),
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user