diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 529543781..286441b66 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -7,6 +7,14 @@ updates: directory: "/" schedule: interval: "weekly" + groups: + tree-sitter: + patterns: + - "tree-sitter*" + rust-dependencies: + update-types: + - "minor" + - "patch" - package-ecosystem: "github-actions" directory: "/" diff --git a/.github/workflows/cachix.yml b/.github/workflows/cachix.yml index 57f0a0db4..b8be02e16 100644 --- a/.github/workflows/cachix.yml +++ b/.github/workflows/cachix.yml @@ -14,10 +14,10 @@ jobs: uses: actions/checkout@v4 - name: Install nix - uses: cachix/install-nix-action@v25 + uses: cachix/install-nix-action@V27 - name: Authenticate with Cachix - uses: cachix/cachix-action@v14 + uses: cachix/cachix-action@v15 with: name: helix authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index ae2e5835e..39dc08982 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -14,7 +14,7 @@ jobs: - uses: actions/checkout@v4 - name: Setup mdBook - uses: peaceiris/actions-mdbook@v1 + uses: peaceiris/actions-mdbook@v2 with: mdbook-version: 'latest' # mdbook-version: '0.4.8' @@ -27,14 +27,14 @@ jobs: echo "OUTDIR=$OUTDIR" >> $GITHUB_ENV - name: Deploy stable - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 if: startswith(github.ref, 'refs/tags/') with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./book/book - name: Deploy - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./book/book diff --git a/CHANGELOG.md b/CHANGELOG.md index b5edbf72b..de15f143c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,256 @@ +# 24.03 (2024-03-30) + +As always, a big thank you to all of the contributors! This release saw changes from 125 contributors. + +Breaking changes: + +- `suffix` file-types in the `file-types` key in language configuration have been removed ([#8006](https://github.com/helix-editor/helix/pull/8006)) +- The `file-types` key in language configuration no longer matches full filenames without a glob pattern ([#8006](https://github.com/helix-editor/helix/pull/8006)) + +Features: + +- Open URLs with the `goto_file` command ([#5820](https://github.com/helix-editor/helix/pull/5820)) +- Support drawing a border around popups and menus ([#4313](https://github.com/helix-editor/helix/pull/4313), [#9508](https://github.com/helix-editor/helix/pull/9508)) +- Track long lived diagnostic sources like Clippy or `rustc` ([#6447](https://github.com/helix-editor/helix/pull/6447), [#9280](https://github.com/helix-editor/helix/pull/9280)) + - This improves the handling of diagnostics from sources that only update the diagnostic positions on save. +- Add support for LSP `window/showDocument` requests ([#8865](https://github.com/helix-editor/helix/pull/8865)) +- Refactor ad-hoc hooks to use a new generic event system ([#8021](https://github.com/helix-editor/helix/pull/8021), [#9668](https://github.com/helix-editor/helix/pull/9668), [#9660](https://github.com/helix-editor/helix/pull/9660)) + - This improves the behavior of autocompletions. For example navigating in insert mode no longer automatically triggers completions. +- Allow using globs in the language configuration `file-types` key ([#8006](https://github.com/helix-editor/helix/pull/8006)) +- Allow specifying required roots for situational LSP activation ([#8696](https://github.com/helix-editor/helix/pull/8696)) +- Extend selections using mouse clicks in select mode ([#5436](https://github.com/helix-editor/helix/pull/5436)) +- Toggle block comments ([#4718](https://github.com/helix-editor/helix/pull/4718), [#9894](https://github.com/helix-editor/helix/pull/9894)) +- Support LSP diagnostic tags ([#9780](https://github.com/helix-editor/helix/pull/9780)) +- Add a `file-absolute-path` statusline element ([#4535](https://github.com/helix-editor/helix/pull/4535)) +- Cross injection layers in tree-sitter motions (`A-p`/`A-o`/`A-i`/`A-n`) ([#5176](https://github.com/helix-editor/helix/pull/5176)) +- Add a Amp-editor-like jumping command ([#8875](https://github.com/helix-editor/helix/pull/8875)) + +Commands: + +- `:move` - move buffers with LSP support ([#8584](https://github.com/helix-editor/helix/pull/8584)) + - Also see [#8949](https://github.com/helix-editor/helix/pull/8949) which made path changes conform to the LSP spec and fixed the behavior of this command. +- `page_cursor_up`, `page_cursor_down`, `page_cursor_half_up`, `page_cursor_half_down` - commands for scrolling the cursor and page together ([#8015](https://github.com/helix-editor/helix/pull/8015)) +- `:yank-diagnostic` - yank the diagnostic(s) under the primary cursor ([#9640](https://github.com/helix-editor/helix/pull/9640)) +- `select_line_above` / `select_line_below` - extend or shrink a selection based on the direction and anchor ([#9080](https://github.com/helix-editor/helix/pull/9080)) + +Usability improvements: + +- Make `roots` key of `[[language]]` entries in `languages.toml` configuration optional ([#8803](https://github.com/helix-editor/helix/pull/8803)) +- Exit select mode in commands that modify the buffer ([#8689](https://github.com/helix-editor/helix/pull/8689)) +- Use crossterm cursor when out of focus ([#6858](https://github.com/helix-editor/helix/pull/6858), [#8934](https://github.com/helix-editor/helix/pull/8934)) +- Join empty lines with only one space in `join_selections` ([#8989](https://github.com/helix-editor/helix/pull/8989)) +- Introduce a hybrid tree-sitter and contextual indentation heuristic ([#8307](https://github.com/helix-editor/helix/pull/8307)) +- Allow configuring the indentation heuristic ([#8307](https://github.com/helix-editor/helix/pull/8307)) +- Check for LSP rename support before showing rename prompt ([#9277](https://github.com/helix-editor/helix/pull/9277)) +- Normalize `S-` keymaps to uppercase ascii ([#9213](https://github.com/helix-editor/helix/pull/9213)) +- Add formatter status to `--health` output ([#7986](https://github.com/helix-editor/helix/pull/7986)) +- Change path normalization strategy to not resolve symlinks ([#9330](https://github.com/helix-editor/helix/pull/9330)) +- Select subtree within injections in `:tree-sitter-subtree` ([#9309](https://github.com/helix-editor/helix/pull/9309)) +- Use tilde expansion and normalization for `$HELIX_RUNTIME` paths ([1bc7aac](https://github.com/helix-editor/helix/commit/1bc7aac)) +- Improve failure message for LSP goto references ([#9382](https://github.com/helix-editor/helix/pull/9382)) +- Use injection syntax trees for bracket matching ([5e0b3cc](https://github.com/helix-editor/helix/commit/5e0b3cc)) +- Respect injections in `:tree-sitter-highlight-name` ([8b6565c](https://github.com/helix-editor/helix/commit/8b6565c)) +- Respect injections in `move_parent_node_end` ([035b8ea](https://github.com/helix-editor/helix/commit/035b8ea)) +- Use `gix` pipeline filter instead of manual CRLF implementation ([#9503](https://github.com/helix-editor/helix/pull/9503)) +- Follow Neovim's truecolor detection ([#9577](https://github.com/helix-editor/helix/pull/9577)) +- Reload language configuration with `:reload`, SIGHUP ([#9415](https://github.com/helix-editor/helix/pull/9415)) +- Allow numbers as bindings ([#8471](https://github.com/helix-editor/helix/pull/8471), [#9887](https://github.com/helix-editor/helix/pull/9887)) +- Respect undercurl config when terminfo is not available ([#9897](https://github.com/helix-editor/helix/pull/9897)) +- Ignore `.pijul`, `.hg`, `.jj` in addition to `.git` in file pickers configured to show hidden files ([#9935](https://github.com/helix-editor/helix/pull/9935)) +- Add completion for registers to `:clear-register` and `:yank-diagnostic` ([#9936](https://github.com/helix-editor/helix/pull/9936)) +- Repeat last motion for goto next/prev diagnostic ([#9966](https://github.com/helix-editor/helix/pull/9966)) +- Allow configuring a character to use when rendering narrow no-breaking space ([#9604](https://github.com/helix-editor/helix/pull/9604)) +- Switch to a streaming regex engine (regex-cursor crate) to significantly speed up regex-based commands and features ([#9422](https://github.com/helix-editor/helix/pull/9422), [#9756](https://github.com/helix-editor/helix/pull/9756), [#9891](https://github.com/helix-editor/helix/pull/9891)) + +Fixes: + +- Swap `*` and `+` registers ([#8703](https://github.com/helix-editor/helix/pull/8703), [#8708](https://github.com/helix-editor/helix/pull/8708)) +- Use terminfo to reset terminal cursor style ([#8591](https://github.com/helix-editor/helix/pull/8591)) +- Fix precedence of `@align` captures in indentat computation ([#8659](https://github.com/helix-editor/helix/pull/8659)) +- Only render the preview if a Picker has a preview function ([#8667](https://github.com/helix-editor/helix/pull/8667)) +- Fix the precedence of `ui.virtual.whitespace` ([#8750](https://github.com/helix-editor/helix/pull/8750), [#8879](https://github.com/helix-editor/helix/pull/8879)) +- Fix crash in `:indent-style` ([#9087](https://github.com/helix-editor/helix/pull/9087)) +- Fix `didSave` text inclusion when sync capability is a kind variant ([#9101](https://github.com/helix-editor/helix/pull/9101)) +- Update the history of newly focused views ([#9271](https://github.com/helix-editor/helix/pull/9271)) +- Initialize diagnostics when opening a document ([#8873](https://github.com/helix-editor/helix/pull/8873)) +- Sync views when applying edits to unfocused views ([#9173](https://github.com/helix-editor/helix/pull/9173)) + - This fixes crashes that could occur from LSP workspace edits or `:write-all`. +- Treat non-numeric `+arg`s passed in the CLI args as filenames ([#9333](https://github.com/helix-editor/helix/pull/9333)) +- Fix crash when using `mm` on an empty plaintext file ([2fb7e50](https://github.com/helix-editor/helix/commit/2fb7e50)) +- Ignore empty tree-sitter nodes in match bracket ([445f7a2](https://github.com/helix-editor/helix/commit/445f7a2)) +- Exit a language server if it sends a message with invalid JSON ([#9332](https://github.com/helix-editor/helix/pull/9332)) +- Handle failures to enable bracketed paste ([#9353](https://github.com/helix-editor/helix/pull/9353)) +- Gate all captures in a pattern behind `#is-not? local` predicates ([#9390](https://github.com/helix-editor/helix/pull/9390)) +- Make path changes LSP spec conformant ([#8949](https://github.com/helix-editor/helix/pull/8949)) +- Use range positions to determine `insert_newline` motion ([#9448](https://github.com/helix-editor/helix/pull/9448)) +- Fix division by zero when prompt completion area is too small ([#9524](https://github.com/helix-editor/helix/pull/9524)) +- Add changes to history in clipboard replacement typable commands ([#9625](https://github.com/helix-editor/helix/pull/9625)) +- Fix a crash in DAP with an unspecified `line` in breakpoints ([#9632](https://github.com/helix-editor/helix/pull/9632)) +- Fix space handling for filenames in bash completion ([#9702](https://github.com/helix-editor/helix/pull/9702), [#9708](https://github.com/helix-editor/helix/pull/9708)) +- Key diagnostics off of paths instead of LSP URIs ([#7367](https://github.com/helix-editor/helix/pull/7367)) +- Fix panic when using `join_selections_space` ([#9783](https://github.com/helix-editor/helix/pull/9783)) +- Fix panic when using `surround_replace`, `surround_delete` ([#9796](https://github.com/helix-editor/helix/pull/9796)) +- Fix panic in `surround_replace`, `surround_delete` with nested surrounds and multiple cursors ([#9815](https://github.com/helix-editor/helix/pull/9815)) +- Fix panic in `select_textobject_around` ([#9832](https://github.com/helix-editor/helix/pull/9832)) +- Don't stop reloading documents when reloading fails in `:reload-all` ([#9870](https://github.com/helix-editor/helix/pull/9870)) +- Prevent `shell_keep_pipe` from stopping on nonzero exit status codes ([#9817](https://github.com/helix-editor/helix/pull/9817)) + +Themes: + +- Add `gruber-dark` ([#8598](https://github.com/helix-editor/helix/pull/8598)) +- Update `everblush` ([#8705](https://github.com/helix-editor/helix/pull/8705)) +- Update `papercolor` ([#8718](https://github.com/helix-editor/helix/pull/8718), [#8827](https://github.com/helix-editor/helix/pull/8827)) +- Add `polmandres` ([#8759](https://github.com/helix-editor/helix/pull/8759)) +- Add `starlight` ([#8787](https://github.com/helix-editor/helix/pull/8787)) +- Update `naysayer` ([#8838](https://github.com/helix-editor/helix/pull/8838)) +- Add modus operandi themes ([#8728](https://github.com/helix-editor/helix/pull/8728), [#9912](https://github.com/helix-editor/helix/pull/9912)) +- Update `rose_pine` ([#8946](https://github.com/helix-editor/helix/pull/8946)) +- Update `darcula` ([#8738](https://github.com/helix-editor/helix/pull/8738), [#9002](https://github.com/helix-editor/helix/pull/9002), [#9449](https://github.com/helix-editor/helix/pull/9449), [#9588](https://github.com/helix-editor/helix/pull/9588)) +- Add modus vivendi themes ([#8894](https://github.com/helix-editor/helix/pull/8894), [#9912](https://github.com/helix-editor/helix/pull/9912)) +- Add `horizon-dark` ([#9008](https://github.com/helix-editor/helix/pull/9008), [#9493](https://github.com/helix-editor/helix/pull/9493)) +- Update `noctis` ([#9123](https://github.com/helix-editor/helix/pull/9123)) +- Update `nord` ([#9135](https://github.com/helix-editor/helix/pull/9135)) +- Update monokai pro themes ([#9148](https://github.com/helix-editor/helix/pull/9148)) +- Update tokyonight themes ([#9099](https://github.com/helix-editor/helix/pull/9099), [#9724](https://github.com/helix-editor/helix/pull/9724), [#9789](https://github.com/helix-editor/helix/pull/9789)) +- Add `ttox` ([#8524](https://github.com/helix-editor/helix/pull/8524)) +- Add `voxed` ([#9164](https://github.com/helix-editor/helix/pull/9164)) +- Update `sonokai` ([#9370](https://github.com/helix-editor/helix/pull/9370), [#9376](https://github.com/helix-editor/helix/pull/9376), [#5379](https://github.com/helix-editor/helix/pull/5379)) +- Update `onedark`, `onedarker` ([#9397](https://github.com/helix-editor/helix/pull/9397)) +- Update `cyan_light` ([#9375](https://github.com/helix-editor/helix/pull/9375), [#9688](https://github.com/helix-editor/helix/pull/9688)) +- Add `gruvbox_light_soft`, `gruvbox_light_hard` ([#9266](https://github.com/helix-editor/helix/pull/9266)) +- Update GitHub themes ([#9487](https://github.com/helix-editor/helix/pull/9487)) +- Add `term16_dark`, `term16_light` ([#9477](https://github.com/helix-editor/helix/pull/9477)) +- Update Zed themes ([#9544](https://github.com/helix-editor/helix/pull/9544), [#9549](https://github.com/helix-editor/helix/pull/9549)) +- Add `curzon` ([#9553](https://github.com/helix-editor/helix/pull/9553)) +- Add `monokai_soda` ([#9651](https://github.com/helix-editor/helix/pull/9651)) +- Update catppuccin themes ([#9859](https://github.com/helix-editor/helix/pull/9859)) +- Update `rasmus` ([#9939](https://github.com/helix-editor/helix/pull/9939)) +- Update `dark_plus` ([#9949](https://github.com/helix-editor/helix/pull/9949), [628dcd5](https://github.com/helix-editor/helix/commit/628dcd5)) +- Update gruvbox themes ([#9960](https://github.com/helix-editor/helix/pull/9960)) +- Add jump label theming to `dracula` ([#9973](https://github.com/helix-editor/helix/pull/9973)) +- Add jump label theming to `horizon-dark` ([#9984](https://github.com/helix-editor/helix/pull/9984)) +- Add jump label theming to catppuccin themes ([2178adf](https://github.com/helix-editor/helix/commit/2178adf), [#9983](https://github.com/helix-editor/helix/pull/9983)) +- Add jump label theming to `onedark` themes ([da2dec1](https://github.com/helix-editor/helix/commit/da2dec1)) +- Add jump label theming to rose-pine themes ([#9981](https://github.com/helix-editor/helix/pull/9981)) +- Add jump label theming to Nord themes ([#10008](https://github.com/helix-editor/helix/pull/10008)) +- Add jump label theming to Monokai themes ([#10009](https://github.com/helix-editor/helix/pull/10009)) +- Add jump label theming to gruvbox themes ([#10012](https://github.com/helix-editor/helix/pull/10012)) +- Add jump label theming to `kanagawa` ([#10030](https://github.com/helix-editor/helix/pull/10030)) +- Update material themes ([#10043](https://github.com/helix-editor/helix/pull/10043)) +- Add `jetbrains_dark` ([#9967](https://github.com/helix-editor/helix/pull/9967)) + +New languages: + +- Typst ([#7474](https://github.com/helix-editor/helix/pull/7474)) +- LPF ([#8536](https://github.com/helix-editor/helix/pull/8536)) +- GN ([#6969](https://github.com/helix-editor/helix/pull/6969)) +- DBML ([#8860](https://github.com/helix-editor/helix/pull/8860)) +- log ([#8916](https://github.com/helix-editor/helix/pull/8916)) +- Janet ([#9081](https://github.com/helix-editor/helix/pull/9081), [#9247](https://github.com/helix-editor/helix/pull/9247)) +- Agda ([#8285](https://github.com/helix-editor/helix/pull/8285)) +- Avro ([#9113](https://github.com/helix-editor/helix/pull/9113)) +- Smali ([#9089](https://github.com/helix-editor/helix/pull/9089)) +- HOCON ([#9203](https://github.com/helix-editor/helix/pull/9203)) +- Tact ([#9512](https://github.com/helix-editor/helix/pull/9512)) +- PKL ([#9515](https://github.com/helix-editor/helix/pull/9515)) +- CEL ([#9296](https://github.com/helix-editor/helix/pull/9296)) +- SpiceDB ([#9296](https://github.com/helix-editor/helix/pull/9296)) +- Hoon ([#9190](https://github.com/helix-editor/helix/pull/9190)) +- DockerCompose ([#9661](https://github.com/helix-editor/helix/pull/9661), [#9916](https://github.com/helix-editor/helix/pull/9916)) +- Groovy ([#9350](https://github.com/helix-editor/helix/pull/9350), [#9681](https://github.com/helix-editor/helix/pull/9681), [#9677](https://github.com/helix-editor/helix/pull/9677)) +- FIDL ([#9713](https://github.com/helix-editor/helix/pull/9713)) +- Powershell ([#9827](https://github.com/helix-editor/helix/pull/9827)) +- ld ([#9835](https://github.com/helix-editor/helix/pull/9835)) +- Hyperland config ([#9899](https://github.com/helix-editor/helix/pull/9899)) +- JSONC ([#9906](https://github.com/helix-editor/helix/pull/9906)) +- PHP Blade ([#9513](https://github.com/helix-editor/helix/pull/9513)) +- SuperCollider ([#9329](https://github.com/helix-editor/helix/pull/9329)) +- Koka ([#8727](https://github.com/helix-editor/helix/pull/8727)) +- PKGBUILD ([#9909](https://github.com/helix-editor/helix/pull/9909), [#9943](https://github.com/helix-editor/helix/pull/9943)) +- Ada ([#9908](https://github.com/helix-editor/helix/pull/9908)) +- Helm charts ([#9900](https://github.com/helix-editor/helix/pull/9900)) +- Ember.js templates ([#9902](https://github.com/helix-editor/helix/pull/9902)) +- Ohm ([#9991](https://github.com/helix-editor/helix/pull/9991)) + +Updated languages and queries: + +- Add HTML injection queries for Rust ([#8603](https://github.com/helix-editor/helix/pull/8603)) +- Switch to tree-sitter-ron for RON ([#8624](https://github.com/helix-editor/helix/pull/8624)) +- Update and improve comment highlighting ([#8564](https://github.com/helix-editor/helix/pull/8564), [#9253](https://github.com/helix-editor/helix/pull/9253), [#9800](https://github.com/helix-editor/helix/pull/9800), [#10014](https://github.com/helix-editor/helix/pull/10014)) +- Highlight type parameters in Rust ([#8660](https://github.com/helix-editor/helix/pull/8660)) +- Change KDL tree-sitter parsers ([#8652](https://github.com/helix-editor/helix/pull/8652)) +- Update tree-sitter-markdown ([#8721](https://github.com/helix-editor/helix/pull/8721), [#10039](https://github.com/helix-editor/helix/pull/10039)) +- Update tree-sitter-purescript ([#8712](https://github.com/helix-editor/helix/pull/8712)) +- Add type parameter highlighting to TypeScript, Go, Haskell, OCaml and Kotlin ([#8718](https://github.com/helix-editor/helix/pull/8718)) +- Add indentation queries for Scheme and lisps using tree-sitter-scheme ([#8720](https://github.com/helix-editor/helix/pull/8720)) +- Recognize `meson_options.txt` as Meson ([#8794](https://github.com/helix-editor/helix/pull/8794)) +- Add language server configuration for Nushell ([#8878](https://github.com/helix-editor/helix/pull/8878)) +- Recognize `musicxml` as XML ([#8935](https://github.com/helix-editor/helix/pull/8935)) +- Update tree-sitter-rescript ([#8962](https://github.com/helix-editor/helix/pull/8962)) +- Update tree-sitter-python ([#8976](https://github.com/helix-editor/helix/pull/8976)) +- Recognize `.envrc.local` and `.envrc.private` as env ([#8988](https://github.com/helix-editor/helix/pull/8988)) +- Update tree-sitter-gleam ([#9003](https://github.com/helix-editor/helix/pull/9003), [9ceeea5](https://github.com/helix-editor/helix/commit/9ceeea5)) +- Update tree-sitter-d ([#9021](https://github.com/helix-editor/helix/pull/9021)) +- Fix R-markdown language name for LSP detection ([#9012](https://github.com/helix-editor/helix/pull/9012)) +- Add haskell-language-server LSP configuration ([#9111](https://github.com/helix-editor/helix/pull/9111)) +- Recognize `glif` as XML ([#9130](https://github.com/helix-editor/helix/pull/9130)) +- Recognize `.prettierrc` as JSON ([#9214](https://github.com/helix-editor/helix/pull/9214)) +- Add auto-pairs configuration for scheme ([#9232](https://github.com/helix-editor/helix/pull/9232)) +- Add textobject queries for Scala ([#9191](https://github.com/helix-editor/helix/pull/9191)) +- Add textobject queries for Protobuf ([#9184](https://github.com/helix-editor/helix/pull/9184)) +- Update tree-sitter-wren ([#8544](https://github.com/helix-editor/helix/pull/8544)) +- Add `spago.yaml` as an LSP root for PureScript ([#9362](https://github.com/helix-editor/helix/pull/9362)) +- Improve highlight and indent queries for Bash, Make and CSS ([#9393](https://github.com/helix-editor/helix/pull/9393)) +- Update tree-sitter-scala ([#9348](https://github.com/helix-editor/helix/pull/9348), [#9340](https://github.com/helix-editor/helix/pull/9340), [#9475](https://github.com/helix-editor/helix/pull/9475)) +- Recognize `.bash_history` as Bash ([#9401](https://github.com/helix-editor/helix/pull/9401)) +- Recognize Helix ignore files as ignore ([#9447](https://github.com/helix-editor/helix/pull/9447)) +- Inject SQL into Scala SQL strings ([#9428](https://github.com/helix-editor/helix/pull/9428)) +- Update gdscript textobjects ([#9288](https://github.com/helix-editor/helix/pull/9288)) +- Update Go queries ([#9510](https://github.com/helix-editor/helix/pull/9510), [#9525](https://github.com/helix-editor/helix/pull/9525)) +- Update tree-sitter-nushell ([#9502](https://github.com/helix-editor/helix/pull/9502)) +- Update tree-sitter-unison, add indent queries ([#9505](https://github.com/helix-editor/helix/pull/9505)) +- Update tree-sitter-slint ([#9551](https://github.com/helix-editor/helix/pull/9551), [#9698](https://github.com/helix-editor/helix/pull/9698)) +- Update tree-sitter-swift ([#9586](https://github.com/helix-editor/helix/pull/9586)) +- Add `fish_indent` as formatter for fish ([78ed3ad](https://github.com/helix-editor/helix/commit/78ed3ad)) +- Recognize `zon` as Zig ([#9582](https://github.com/helix-editor/helix/pull/9582)) +- Add a formatter for Odin ([#9537](https://github.com/helix-editor/helix/pull/9537)) +- Update tree-sitter-erlang ([#9627](https://github.com/helix-editor/helix/pull/9627), [fdcd461](https://github.com/helix-editor/helix/commit/fdcd461)) +- Capture Rust fields as argument textobjects ([#9637](https://github.com/helix-editor/helix/pull/9637)) +- Improve Dart textobjects ([#9644](https://github.com/helix-editor/helix/pull/9644)) +- Recognize `tmux.conf` as a bash file-type ([#9653](https://github.com/helix-editor/helix/pull/9653)) +- Add textobjects queries for Nix ([#9659](https://github.com/helix-editor/helix/pull/9659)) +- Add textobjects queries for HCL ([#9658](https://github.com/helix-editor/helix/pull/9658)) +- Recognize osm and osc extensions as XML ([#9697](https://github.com/helix-editor/helix/pull/9697)) +- Update tree-sitter-sql ([#9634](https://github.com/helix-editor/helix/pull/9634)) +- Recognize pde Processing files as Java ([#9741](https://github.com/helix-editor/helix/pull/9741)) +- Update tree-sitter-lua ([#9727](https://github.com/helix-editor/helix/pull/9727)) +- Switch tree-sitter-nim parsers ([#9722](https://github.com/helix-editor/helix/pull/9722)) +- Recognize GTK builder ui files as XML ([#9754](https://github.com/helix-editor/helix/pull/9754)) +- Add configuration for markdown-oxide language server ([#9758](https://github.com/helix-editor/helix/pull/9758)) +- Add a shebang for elvish ([#9779](https://github.com/helix-editor/helix/pull/9779)) +- Fix precedence of Svelte TypeScript injection ([#9777](https://github.com/helix-editor/helix/pull/9777)) +- Recognize common Dockerfile file types ([#9772](https://github.com/helix-editor/helix/pull/9772)) +- Recognize NUON files as Nu ([#9839](https://github.com/helix-editor/helix/pull/9839)) +- Add textobjects for Java native functions and constructors ([#9806](https://github.com/helix-editor/helix/pull/9806)) +- Fix "braket" typeo in JSX highlights ([#9910](https://github.com/helix-editor/helix/pull/9910)) +- Update tree-sitter-hurl ([#9775](https://github.com/helix-editor/helix/pull/9775)) +- Add textobjects queries for Vala ([#8541](https://github.com/helix-editor/helix/pull/8541)) +- Update tree-sitter-git-config ([9610254](https://github.com/helix-editor/helix/commit/9610254)) +- Recognize 'mmd' as Mermaid ([459eb9a](https://github.com/helix-editor/helix/commit/459eb9a)) +- Highlight Rust extern crate aliases ([c099dde](https://github.com/helix-editor/helix/commit/c099dde)) +- Improve parameter highlighting in C++ ([f5d95de](https://github.com/helix-editor/helix/commit/f5d95de)) +- Recognize 'rclone.conf' as INI ([#9959](https://github.com/helix-editor/helix/pull/9959)) +- Add injections for GraphQL and ERB in Ruby heredocs ([#10036](https://github.com/helix-editor/helix/pull/10036)) +- Add `main.odin` to Odin LSP roots ([#9968](https://github.com/helix-editor/helix/pull/9968)) + +Packaging: + +- Allow user overlays in Nix grammars build ([#8749](https://github.com/helix-editor/helix/pull/8749)) +- Set Cargo feature resolver to v2 ([#8917](https://github.com/helix-editor/helix/pull/8917)) +- Use workspace inheritance for common Cargo metadata ([#8925](https://github.com/helix-editor/helix/pull/8925)) +- Remove sourcehut-based tree-sitter grammars from default build ([#9316](https://github.com/helix-editor/helix/pull/9316), [#9326](https://github.com/helix-editor/helix/pull/9326)) +- Add icon to Windows executable ([#9104](https://github.com/helix-editor/helix/pull/9104)) + # 23.10 (2023-10-24) A big shout out to all the contributors! We had 118 contributors in this release. diff --git a/Cargo.lock b/Cargo.lock index fd74140a5..577298d8b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -62,15 +62,15 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.80" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "arc-swap" -version = "1.7.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b3d0060af21e8d11a926981cc00c6c1541aa91dd64b9f881985c3da1094425f" +checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" [[package]] name = "autocfg" @@ -101,9 +101,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.2" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bstr" @@ -116,15 +116,6 @@ dependencies = [ "serde", ] -[[package]] -name = "btoi" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" -dependencies = [ - "num-traits", -] - [[package]] name = "bumpalo" version = "3.12.0" @@ -145,9 +136,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" [[package]] name = "cc" -version = "1.0.88" +version = "1.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f341c093d19155a6e41631ce5971aac4e9a868262212153124c15fa22d1cdc" +checksum = "c891175c3fb232128f48de6590095e59198bbeb8620c310be349bfc3afd12c7b" [[package]] name = "cfg-if" @@ -168,9 +159,9 @@ dependencies = [ [[package]] name = "chrono" -version = "0.4.34" +version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bc015644b92d5890fab7489e49d21f879d5c990186827d42ec511919404f38b" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ "android-tzdata", "iana-time-zone", @@ -180,9 +171,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.2.0" +version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9a0700e0127ba15d1d52dd742097f821cd9c65939303a44d970465040a297" +checksum = "79f4473f5144e20d9aceaf2972478f06ddf687831eafeeb434fbaf0acc4144ad" dependencies = [ "error-code", ] @@ -282,7 +273,7 @@ version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "crossterm_winapi", "filedescriptor", "futures-core", @@ -347,6 +338,19 @@ dependencies = [ "syn 2.0.48", ] +[[package]] +name = "dashmap" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" +dependencies = [ + "cfg-if", + "hashbrown 0.12.3", + "lock_api", + "once_cell", + "parking_lot_core", +] + [[package]] name = "dunce" version = "1.0.4" @@ -361,9 +365,9 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "encoding_rs" -version = "0.8.33" +version = "0.8.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" +checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" dependencies = [ "cfg-if", ] @@ -415,15 +419,12 @@ name = "faster-hex" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2a2b11eda1d40935b26cf18f6833c526845ae8c41e58d09af6adeb6f0269183" -dependencies = [ - "serde", -] [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fern" @@ -467,6 +468,12 @@ dependencies = [ "miniz_oxide", ] +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "form_urlencoded" version = "1.2.1" @@ -531,9 +538,9 @@ checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" [[package]] name = "gix" -version = "0.58.0" +version = "0.63.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31887c304d9a935f3e5494fb5d6a0106c34e965168ec0db9b457424eedd0c741" +checksum = "984c5018adfa7a4536ade67990b3ebc6e11ab57b3d6cd9968de0947ca99b4b06" dependencies = [ "gix-actor", "gix-attributes", @@ -542,6 +549,7 @@ dependencies = [ "gix-config", "gix-date", "gix-diff", + "gix-dir", "gix-discover", "gix-features", "gix-filter", @@ -563,6 +571,7 @@ dependencies = [ "gix-revision", "gix-revwalk", "gix-sec", + "gix-status", "gix-submodule", "gix-tempfile", "gix-trace", @@ -579,13 +588,13 @@ dependencies = [ [[package]] name = "gix-actor" -version = "0.30.0" +version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a7bb9fad6125c81372987c06469601d37e1a2d421511adb69971b9083517a8a" +checksum = "d69c59d392c7e6c94385b6fd6089d6df0fe945f32b4357687989f3aee253cd7f" dependencies = [ "bstr", - "btoi", "gix-date", + "gix-utils", "itoa", "thiserror", "winnow", @@ -593,9 +602,9 @@ dependencies = [ [[package]] name = "gix-attributes" -version = "0.22.0" +version = "0.22.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "214ee3792e504ee1ce206b36dcafa4f328ca313d1e2ac0b41433d68ef4e14260" +checksum = "eefb48f42eac136a4a0023f49a54ec31be1c7a9589ed762c45dcb9b953f7ecc8" dependencies = [ "bstr", "gix-glob", @@ -610,27 +619,27 @@ dependencies = [ [[package]] name = "gix-bitmap" -version = "0.2.10" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b6cd0f246180034ddafac9b00a112f19178135b21eb031b3f79355891f7325" +checksum = "a371db66cbd4e13f0ed9dc4c0fea712d7276805fccc877f77e96374d317e87ae" dependencies = [ "thiserror", ] [[package]] name = "gix-chunk" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003ec6deacf68076a0c157271a127e0bb2c031c1a41f7168cbe5d248d9b85c78" +checksum = "45c8751169961ba7640b513c3b24af61aa962c967aaf04116734975cd5af0c52" dependencies = [ "thiserror", ] [[package]] name = "gix-command" -version = "0.3.3" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce1ffc7db3fb50b7dae6ecd937a3527cb725f444614df2ad8988d81806f13f09" +checksum = "6c22e086314095c43ffe5cdc5c0922d5439da4fd726f3b0438c56147c34dc225" dependencies = [ "bstr", "gix-path", @@ -640,9 +649,9 @@ dependencies = [ [[package]] name = "gix-commitgraph" -version = "0.24.0" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82dbd7fb959862e3df2583331f0ad032ac93533e8a52f1b0694bc517f5d292bc" +checksum = "f7b102311085da4af18823413b5176d7c500fb2272eaf391cfa8635d8bcb12c4" dependencies = [ "bstr", "gix-chunk", @@ -654,9 +663,9 @@ dependencies = [ [[package]] name = "gix-config" -version = "0.34.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e62bf2073b6ce3921ffa6d8326f645f30eec5fc4a8e8a4bc0fcb721a2f3f69dc" +checksum = "53fafe42957e11d98e354a66b6bd70aeea00faf2f62dd11164188224a507c840" dependencies = [ "bstr", "gix-config-value", @@ -675,11 +684,11 @@ dependencies = [ [[package]] name = "gix-config-value" -version = "0.14.4" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e7bfb37a46ed0b8468db37a6d8a0a61d56bdbe4603ae492cb322e5f3958" +checksum = "fbd06203b1a9b33a78c88252a625031b094d9e1b647260070c25b09910c0a804" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "bstr", "gix-path", "libc", @@ -688,9 +697,9 @@ dependencies = [ [[package]] name = "gix-date" -version = "0.8.3" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb7f3dfb72bebe3449b5e642be64e3c6ccbe9821c8b8f19f487cf5bfbbf4067e" +checksum = "367ee9093b0c2b04fd04c5c7c8b6a1082713534eab537597ae343663a518fa99" dependencies = [ "bstr", "itoa", @@ -700,21 +709,49 @@ dependencies = [ [[package]] name = "gix-diff" -version = "0.40.0" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbdcb5e49c4b9729dd1c361040ae5c3cd7c497b2260b18c954f62db3a63e98cf" +checksum = "40b9bd8b2d07b6675a840b56a6c177d322d45fa082672b0dad8f063b25baf0a4" dependencies = [ "bstr", + "gix-command", + "gix-filter", + "gix-fs", "gix-hash", "gix-object", + "gix-path", + "gix-tempfile", + "gix-trace", + "gix-worktree", + "imara-diff", + "thiserror", +] + +[[package]] +name = "gix-dir" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60c99f8c545abd63abe541d20ab6cda347de406c0a3f1c80aadc12d9b0e94974" +dependencies = [ + "bstr", + "gix-discover", + "gix-fs", + "gix-ignore", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-trace", + "gix-utils", + "gix-worktree", "thiserror", ] [[package]] name = "gix-discover" -version = "0.29.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4669218f3ec0cbbf8f16857b32200890f8ca585f36f5817242e4115fe4551af" +checksum = "fc27c699b63da66b50d50c00668bc0b7e90c3a382ef302865e891559935f3dbf" dependencies = [ "bstr", "dunce", @@ -728,9 +765,9 @@ dependencies = [ [[package]] name = "gix-features" -version = "0.38.0" +version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "184f7f7d4e45db0e2a362aeaf12c06c5e84817d0ef91d08e8e90170dad9f0b07" +checksum = "ac7045ac9fe5f9c727f38799d002a7ed3583cd777e3322a7c4b43e3cf437dc69" dependencies = [ "crc32fast", "flate2", @@ -747,9 +784,9 @@ dependencies = [ [[package]] name = "gix-filter" -version = "0.9.0" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9240862840fb740d209422937195e129e4ed3da49af212383260134bea8f6c1a" +checksum = "00ce6ea5ac8fca7adbc63c48a1b9e0492c222c386aa15f513405f1003f2f4ab2" dependencies = [ "bstr", "encoding_rs", @@ -768,21 +805,22 @@ dependencies = [ [[package]] name = "gix-fs" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4436e883d5769f9fb18677b8712b49228357815f9e4104174a6fc2d8461a437b" +checksum = "3f78f7d6dcda7a5809efd73a33b145e3dce7421c460df21f32126f9732736b0c" dependencies = [ + "fastrand", "gix-features", "gix-utils", ] [[package]] name = "gix-glob" -version = "0.16.0" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4965a1d06d0ab84a29d4a67697a97352ab14ae1da821084e5afb1fd6d8191ca0" +checksum = "682bdc43cb3c00dbedfcc366de2a849b582efd8d886215dbad2ea662ec156bb5" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "bstr", "gix-features", "gix-path", @@ -790,9 +828,9 @@ dependencies = [ [[package]] name = "gix-hash" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0ed89cdc1dce26685c80271c4287077901de3c3dd90234d5fa47c22b2268653" +checksum = "f93d7df7366121b5018f947a04d37f034717e113dcf9ccd85c34b58e57a74d5e" dependencies = [ "faster-hex", "thiserror", @@ -800,20 +838,20 @@ dependencies = [ [[package]] name = "gix-hashtable" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe47d8c0887f82355e2e9e16b6cecaa4d5e5346a7a474ca78ff94de1db35a5b" +checksum = "7ddf80e16f3c19ac06ce415a38b8591993d3f73aede049cb561becb5b3a8e242" dependencies = [ "gix-hash", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "parking_lot", ] [[package]] name = "gix-ignore" -version = "0.11.0" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7069aaca4a05784c4cb44e392f0eaf627c6e57e05d3100c0e2386a37a682f0" +checksum = "640dbeb4f5829f9fc14d31f654a34a0350e43a24e32d551ad130d99bf01f63f1" dependencies = [ "bstr", "gix-glob", @@ -824,14 +862,14 @@ dependencies = [ [[package]] name = "gix-index" -version = "0.29.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7152181ba8f0a3addc5075dd612cea31fc3e252b29c8be8c45f4892bf87426" +checksum = "2d8c5a5f1c58edcbc5692b174cda2703aba82ed17d7176ff4c1752eb48b1b167" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "bstr", - "btoi", "filetime", + "fnv", "gix-bitmap", "gix-features", "gix-fs", @@ -839,6 +877,9 @@ dependencies = [ "gix-lock", "gix-object", "gix-traverse", + "gix-utils", + "gix-validate", + "hashbrown 0.14.5", "itoa", "libc", "memmap2", @@ -849,9 +890,9 @@ dependencies = [ [[package]] name = "gix-lock" -version = "13.0.0" +version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "651e46174dc5e7d18b7b809d31937b6de3681b1debd78618c99162cc30fcf3e1" +checksum = "e3bc7fe297f1f4614774989c00ec8b1add59571dc9b024b4c00acb7dedd4e19d" dependencies = [ "gix-tempfile", "gix-utils", @@ -860,9 +901,9 @@ dependencies = [ [[package]] name = "gix-macros" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d75e7ab728059f595f6ddc1ad8771b8d6a231971ae493d9d5948ecad366ee8bb" +checksum = "999ce923619f88194171a67fb3e6d613653b8d4d6078b529b15a765da0edcc17" dependencies = [ "proc-macro2", "quote", @@ -871,16 +912,16 @@ dependencies = [ [[package]] name = "gix-object" -version = "0.41.0" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693ce9d30741506cb082ef2d8b797415b48e032cce0ab23eff894c19a7e4777b" +checksum = "1fe2dc4a41191c680c942e6ebd630c8107005983c4679214fdb1007dcf5ae1df" dependencies = [ "bstr", - "btoi", "gix-actor", "gix-date", "gix-features", "gix-hash", + "gix-utils", "gix-validate", "itoa", "smallvec", @@ -890,9 +931,9 @@ dependencies = [ [[package]] name = "gix-odb" -version = "0.57.0" +version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ba2fa9e81f2461b78b4d81a807867667326c84cdab48e0aed7b73a593aa1be4" +checksum = "e92b9790e2c919166865d0825b26cc440a387c175bed1b43a2fa99c0e9d45e98" dependencies = [ "arc-swap", "gix-date", @@ -910,9 +951,9 @@ dependencies = [ [[package]] name = "gix-pack" -version = "0.47.0" +version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da5f3e78c96b76c4e6fe5e8e06b76221e4a0ee9a255aa935ed1fdf68988dfd8" +checksum = "7a8da51212dbff944713edb2141ed7e002eea326b8992070374ce13a6cb610b3" dependencies = [ "clru", "gix-chunk", @@ -930,9 +971,9 @@ dependencies = [ [[package]] name = "gix-packetline-blocking" -version = "0.17.3" +version = "0.17.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca8ef6dd3ea50e26f3bf572e90c034d033c804d340cd1eb386392f184a9ba2f7" +checksum = "c31d42378a3d284732e4d589979930d0d253360eccf7ec7a80332e5ccb77e14a" dependencies = [ "bstr", "faster-hex", @@ -942,9 +983,9 @@ dependencies = [ [[package]] name = "gix-path" -version = "0.10.4" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14a6282621aed1becc3f83d64099a564b3b9063f22783d9a87ea502a3e9f2e40" +checksum = "23623cf0f475691a6d943f898c4d0b89f5c1a2a64d0f92bce0e0322ee6528783" dependencies = [ "bstr", "gix-trace", @@ -955,11 +996,11 @@ dependencies = [ [[package]] name = "gix-pathspec" -version = "0.6.0" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cbd49750edb26b0a691e5246fc635fa554d344da825cd20fa9ee0da9c1b761f" +checksum = "a76cab098dc10ba2d89f634f66bf196dea4d7db4bf10b75c7a9c201c55a2ee19" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "bstr", "gix-attributes", "gix-config-value", @@ -970,20 +1011,20 @@ dependencies = [ [[package]] name = "gix-quote" -version = "0.4.10" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7dc10303d73a960d10fb82f81188b036ac3e6b11b5795b20b1a60b51d1321f" +checksum = "cbff4f9b9ea3fa7a25a70ee62f545143abef624ac6aa5884344e70c8b0a1d9ff" dependencies = [ "bstr", - "btoi", + "gix-utils", "thiserror", ] [[package]] name = "gix-ref" -version = "0.41.0" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5818958994ad7879fa566f5441ebcc48f0926aa027b28948e6fbf6578894dc31" +checksum = "0b36752b448647acd59c9668fdd830b16d07db1e6d9c3b3af105c1605a6e23d9" dependencies = [ "gix-actor", "gix-date", @@ -1003,9 +1044,9 @@ dependencies = [ [[package]] name = "gix-refspec" -version = "0.22.0" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613aa4d93034c5791d13bdc635e530f4ddab1412ddfb4a8215f76213177b61c7" +checksum = "dde848865834a54fe4d9b4573f15d0e9a68eaf3d061b42d3ed52b4b8acf880b2" dependencies = [ "bstr", "gix-hash", @@ -1017,9 +1058,9 @@ dependencies = [ [[package]] name = "gix-revision" -version = "0.26.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "288f6549d7666db74dc3f169a9a333694fc28ecd2f5aa7b2c979c89eb556751a" +checksum = "63e08f8107ed1f93a83bcfbb4c38084c7cb3f6cd849793f1d5eec235f9b13b2b" dependencies = [ "bstr", "gix-date", @@ -1033,9 +1074,9 @@ dependencies = [ [[package]] name = "gix-revwalk" -version = "0.12.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9b4d91dfc5c14fee61a28c65113ded720403b65a0f46169c0460f731a5d03c" +checksum = "4181db9cfcd6d1d0fd258e91569dbb61f94cb788b441b5294dd7f1167a3e788f" dependencies = [ "gix-commitgraph", "gix-date", @@ -1048,21 +1089,43 @@ dependencies = [ [[package]] name = "gix-sec" -version = "0.10.4" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8d9bf462feaf05f2121cba7399dbc6c34d88a9cad58fc1e95027791d6a3c6d2" +checksum = "fddc27984a643b20dd03e97790555804f98cf07404e0e552c0ad8133266a79a1" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "gix-path", "libc", "windows-sys 0.52.0", ] +[[package]] +name = "gix-status" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4373d989713809554d136f51bc7da565adf45c91aa4d86ef6a79801621bfc8" +dependencies = [ + "bstr", + "filetime", + "gix-diff", + "gix-dir", + "gix-features", + "gix-filter", + "gix-fs", + "gix-hash", + "gix-index", + "gix-object", + "gix-path", + "gix-pathspec", + "gix-worktree", + "thiserror", +] + [[package]] name = "gix-submodule" -version = "0.8.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73182f6c1f5ed1ed94ba16581ac62593d5e29cd1c028b2af618f836283b8f8d4" +checksum = "921cd49924ac14b6611b22e5fb7bbba74d8780dc7ad26153304b64d1272460ac" dependencies = [ "bstr", "gix-config", @@ -1075,10 +1138,11 @@ dependencies = [ [[package]] name = "gix-tempfile" -version = "13.0.0" +version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d337955b7af00fb87120d053d87cdfb422a80b9ff7a3aa4057a99c79422dc30" +checksum = "d3b0e276cd08eb2a22e9f286a4f13a222a01be2defafa8621367515375644b99" dependencies = [ + "dashmap", "gix-fs", "libc", "once_cell", @@ -1088,16 +1152,17 @@ dependencies = [ [[package]] name = "gix-trace" -version = "0.1.7" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b202d766a7fefc596e2cc6a89cda8ad8ad733aed82da635ac120691112a9b1" +checksum = "f924267408915fddcd558e3f37295cc7d6a3e50f8bd8b606cee0808c3915157e" [[package]] name = "gix-traverse" -version = "0.37.0" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfc30c5b5e4e838683b59e1b0574ce6bc1c35916df9709aaab32bb7751daf08b" +checksum = "f20cb69b63eb3e4827939f42c05b7756e3488ef49c25c412a876691d568ee2a0" dependencies = [ + "bitflags 2.6.0", "gix-commitgraph", "gix-date", "gix-hash", @@ -1110,9 +1175,9 @@ dependencies = [ [[package]] name = "gix-url" -version = "0.27.0" +version = "0.27.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26f1981ecc700f4fd73ae62b9ca2da7c8816c8fd267f0185e3f8c21e967984ac" +checksum = "0db829ebdca6180fbe32be7aed393591df6db4a72dbbc0b8369162390954d1cf" dependencies = [ "bstr", "gix-features", @@ -1124,19 +1189,20 @@ dependencies = [ [[package]] name = "gix-utils" -version = "0.1.9" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56e839f3d0798b296411263da6bee780a176ef8008a5dfc31287f7eda9266ab8" +checksum = "35192df7fd0fa112263bad8021e2df7167df4cc2a6e6d15892e1e55621d3d4dc" dependencies = [ + "bstr", "fastrand", "unicode-normalization", ] [[package]] name = "gix-validate" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac7cc36f496bd5d96cdca0f9289bb684480725d40db60f48194aa7723b883854" +checksum = "82c27dd34a49b1addf193c92070bcbf3beaf6e10f16a78544de6372e146a0acf" dependencies = [ "bstr", "thiserror", @@ -1144,9 +1210,9 @@ dependencies = [ [[package]] name = "gix-worktree" -version = "0.30.0" +version = "0.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca36bb3dc54038c66507dc75c4d8edbee2d6d5cc45227b4eb508ad13dd60a006" +checksum = "53f6b7de83839274022aff92157d7505f23debf739d257984a300a35972ca94e" dependencies = [ "bstr", "gix-attributes", @@ -1158,6 +1224,7 @@ dependencies = [ "gix-index", "gix-object", "gix-path", + "gix-validate", ] [[package]] @@ -1218,9 +1285,9 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "hashbrown" -version = "0.14.3" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash", "allocator-api2", @@ -1228,17 +1295,17 @@ dependencies = [ [[package]] name = "helix-core" -version = "23.10.0" +version = "24.3.0" dependencies = [ "ahash", "arc-swap", - "bitflags 2.4.2", + "bitflags 2.6.0", "chrono", "dunce", "encoding_rs", "etcetera", "globset", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "helix-loader", "helix-stdx", "imara-diff", @@ -1265,7 +1332,7 @@ dependencies = [ [[package]] name = "helix-dap" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "fern", @@ -1280,12 +1347,12 @@ dependencies = [ [[package]] name = "helix-event" -version = "23.10.0" +version = "24.3.0" dependencies = [ "ahash", "anyhow", "futures-executor", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "log", "once_cell", "parking_lot", @@ -1294,7 +1361,7 @@ dependencies = [ [[package]] name = "helix-loader" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "cc", @@ -1313,7 +1380,7 @@ dependencies = [ [[package]] name = "helix-lsp" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "arc-swap", @@ -1329,6 +1396,7 @@ dependencies = [ "parking_lot", "serde", "serde_json", + "slotmap", "thiserror", "tokio", "tokio-stream", @@ -1336,23 +1404,26 @@ dependencies = [ [[package]] name = "helix-parsec" -version = "23.10.0" +version = "24.3.0" [[package]] name = "helix-stdx" -version = "23.10.0" +version = "24.3.0" dependencies = [ + "bitflags 2.6.0", "dunce", "etcetera", "regex-cursor", "ropey", + "rustix", "tempfile", "which", + "windows-sys 0.52.0", ] [[package]] name = "helix-term" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "arc-swap", @@ -1395,9 +1466,9 @@ dependencies = [ [[package]] name = "helix-tui" -version = "23.10.0" +version = "24.3.0" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "cassowary", "crossterm", "helix-core", @@ -1411,7 +1482,7 @@ dependencies = [ [[package]] name = "helix-vcs" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "arc-swap", @@ -1427,11 +1498,11 @@ dependencies = [ [[package]] name = "helix-view" -version = "23.10.0" +version = "24.3.0" dependencies = [ "anyhow", "arc-swap", - "bitflags 2.4.2", + "bitflags 2.6.0", "chardetng", "clipboard-win", "crossterm", @@ -1452,6 +1523,8 @@ dependencies = [ "serde", "serde_json", "slotmap", + "tempfile", + "thiserror", "tokio", "tokio-stream", "toml", @@ -1543,14 +1616,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ "equivalent", - "hashbrown 0.14.3", + "hashbrown 0.14.5", ] [[package]] name = "indoc" -version = "2.0.4" +version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" +checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" [[package]] name = "is-docker" @@ -1597,15 +1670,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.153" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2caa5afb8bf9f3a2652760ce7d4f62d21c4d5a423e68466fca30df82f2330164" +checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d" dependencies = [ "cfg-if", "windows-targets 0.52.0", @@ -1638,15 +1711,15 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "lsp-types" -version = "0.95.0" +version = "0.95.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "158c1911354ef73e8fe42da6b10c0484cb65c7f1007f28022e847706c1ab6984" +checksum = "8e34d33a8e9b006cd3fc4fe69a921affa097bae4bb65f76271f4644f9a334365" dependencies = [ "bitflags 1.3.2", "serde", @@ -1767,9 +1840,9 @@ checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "open" -version = "5.0.1" +version = "5.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90878fb664448b54c4e592455ad02831e23a3f7e157374a8b95654731aac7349" +checksum = "b5ca541f22b1c46d4bb9801014f234758ab4297e7870b904b6a8415b980a7388" dependencies = [ "is-wsl", "libc", @@ -1778,9 +1851,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", "parking_lot_core", @@ -1840,11 +1913,11 @@ checksum = "744a264d26b88a6a7e37cbad97953fa233b94d585236310bcbc88474b4092d79" [[package]] name = "pulldown-cmark" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce76ce678ffc8e5675b22aa1405de0b7037e2fdf8913fea40d1926c6fe1e6e7" +checksum = "8746739f11d39ce5ad5c2520a9b75285310dbfe78c541ccf832d38615765aec0" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "memchr", "unicase", ] @@ -1927,9 +2000,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.3" +version = "1.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" +checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" dependencies = [ "aho-corasick", "memchr", @@ -1950,9 +2023,9 @@ dependencies = [ [[package]] name = "regex-cursor" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a43718aa0040434d45728c43f56bd53bda75a91c46954cdf0f2ff4dbc8aabbe7" +checksum = "ae4327b5fde3ae6fda0152128d3d59b95a5aad7be91c405869300091720f7169" dependencies = [ "log", "memchr", @@ -1985,11 +2058,11 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustix" -version = "0.38.31" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.4.2", + "bitflags 2.6.0", "errno", "libc", "linux-raw-sys", @@ -2025,18 +2098,18 @@ checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" [[package]] name = "serde" -version = "1.0.197" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" dependencies = [ "proc-macro2", "quote", @@ -2045,9 +2118,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" dependencies = [ "itoa", "ryu", @@ -2067,9 +2140,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" dependencies = [ "serde", ] @@ -2148,9 +2221,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smartstring" @@ -2256,18 +2329,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.57" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.57" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", @@ -2329,9 +2402,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.36.0" +version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" dependencies = [ "backtrace", "bytes", @@ -2348,9 +2421,9 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" +checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" dependencies = [ "proc-macro2", "quote", @@ -2359,9 +2432,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" +checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af" dependencies = [ "futures-core", "pin-project-lite", @@ -2370,9 +2443,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.10" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a9aad4a3066010876e8dcf5a8a06e70a558751117a145c6ce2b82c2e2054290" +checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" dependencies = [ "serde", "serde_spanned", @@ -2382,18 +2455,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.22.4" +version = "0.22.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ffdf896f8daaabf9b66ba8e77ea1ed5ed0f72821b398aba62352e95062951" +checksum = "f21c7aaf97f1bd9ca9d4f9e73b0a6c74bd5afef56f2bc931943a6e1c37e04e38" dependencies = [ "indexmap", "serde", @@ -2404,8 +2477,9 @@ dependencies = [ [[package]] name = "tree-sitter" -version = "0.20.10" -source = "git+https://github.com/helix-editor/tree-sitter?rev=660481dbf71413eba5a928b0b0ab8da50c1109e0#660481dbf71413eba5a928b0b0ab8da50c1109e0" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df7cc499ceadd4dcdf7ec6d4cbc34ece92c3fa07821e287aedecd4416c516dca" dependencies = [ "cc", "regex", @@ -2422,9 +2496,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.13" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-bom" @@ -2467,15 +2541,15 @@ checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-width" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" +checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" [[package]] name = "url" -version = "2.5.0" +version = "2.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", "idna", @@ -2561,15 +2635,14 @@ checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" [[package]] name = "which" -version = "6.0.0" +version = "6.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fa5e0c10bf77f44aac573e498d1a82d5fbd5e91f6fc0a99e7be4b38e85e101c" +checksum = "8211e4f58a2b2805adfbefbc07bab82958fc91e3836339b1ab7ae32465dce0d7" dependencies = [ "either", "home", - "once_cell", "rustix", - "windows-sys 0.52.0", + "winsafe", ] [[package]] @@ -2812,16 +2885,22 @@ checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" [[package]] name = "winnow" -version = "0.5.28" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c830786f7720c2fd27a1a0e27a709dbd3c4d009b56d098fc742d4f4eab91fe2" +checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" dependencies = [ "memchr", ] +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + [[package]] name = "xtask" -version = "23.10.0" +version = "24.3.0" dependencies = [ "helix-core", "helix-loader", diff --git a/Cargo.toml b/Cargo.toml index 91f6e7cae..e3ee10319 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,11 +37,13 @@ package.helix-tui.opt-level = 2 package.helix-term.opt-level = 2 [workspace.dependencies] -tree-sitter = { version = "0.20", git = "https://github.com/helix-editor/tree-sitter", rev = "660481dbf71413eba5a928b0b0ab8da50c1109e0" } +tree-sitter = { version = "0.22" } nucleo = "0.2.0" +slotmap = "1.0.7" +thiserror = "1.0" [workspace.package] -version = "23.10.0" +version = "24.3.0" edition = "2021" authors = ["Blaž Hrastnik "] categories = ["editor"] diff --git a/base16_theme.toml b/base16_theme.toml index 268a38df6..ce03b9b65 100644 --- a/base16_theme.toml +++ b/base16_theme.toml @@ -28,6 +28,11 @@ "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" } "markup.heading" = "blue" "markup.list" = "red" diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index ba330cf77..027b885a8 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -3,12 +3,19 @@ [Helix](./title-page.md) - [Installation](./install.md) + - [Package Managers](./package-managers.md) + - [Building from source](./building-from-source.md) - [Usage](./usage.md) + - [Registers](./registers.md) + - [Surround](./surround.md) + - [Textobjects](./textobjects.md) + - [Syntax aware motions](./syntax-aware-motions.md) - [Keymap](./keymap.md) - [Commands](./commands.md) - [Language support](./lang-support.md) - [Migrating from Vim](./from-vim.md) - [Configuration](./configuration.md) + - [Editor](./editor.md) - [Themes](./themes.md) - [Key remapping](./remapping.md) - [Languages](./languages.md) diff --git a/book/src/building-from-source.md b/book/src/building-from-source.md new file mode 100644 index 000000000..666917ea4 --- /dev/null +++ b/book/src/building-from-source.md @@ -0,0 +1,158 @@ +## Building from source + +- [Configuring Helix's runtime files](#configuring-helixs-runtime-files) + - [Linux and macOS](#linux-and-macos) + - [Windows](#windows) + - [Multiple runtime directories](#multiple-runtime-directories) + - [Note to packagers](#note-to-packagers) +- [Validating the installation](#validating-the-installation) +- [Configure the desktop shortcut](#configure-the-desktop-shortcut) + +Requirements: + +Clone the Helix GitHub repository into a directory of your choice. The +examples in this documentation assume installation into either `~/src/` on +Linux and macOS, or `%userprofile%\src\` on Windows. + +- The [Rust toolchain](https://www.rust-lang.org/tools/install) +- The [Git version control system](https://git-scm.com/) +- A C++14 compatible compiler to build the tree-sitter grammars, for example GCC or Clang + +If you are using the `musl-libc` standard library instead of `glibc` the following environment variable must be set during the build to ensure tree-sitter grammars can be loaded correctly: + +```sh +RUSTFLAGS="-C target-feature=-crt-static" +``` + +1. Clone the repository: + + ```sh + git clone https://github.com/helix-editor/helix + cd helix + ``` + +2. Compile from source: + + ```sh + cargo install --path helix-term --locked + ``` + + This command will create the `hx` executable and construct the tree-sitter + grammars in the local `runtime` folder. + +> 💡 If you do not want to fetch or build grammars, set an environment variable `HELIX_DISABLE_AUTO_GRAMMAR_BUILD` + +> 💡 Tree-sitter grammars can be fetched and compiled if not pre-packaged. Fetch +> grammars with `hx --grammar fetch` and compile them with +> `hx --grammar build`. This will install them in +> the `runtime` directory within the user's helix config directory (more +> [details below](#multiple-runtime-directories)). + +### Configuring Helix's runtime files + +#### Linux and macOS + +The **runtime** directory is one below the Helix source, so either export a +`HELIX_RUNTIME` environment variable to point to that directory and add it to +your `~/.bashrc` or equivalent: + +```sh +export HELIX_RUNTIME=~/src/helix/runtime +``` + +Or, create a symbolic link: + +```sh +ln -Ts $PWD/runtime ~/.config/helix/runtime +``` + +If the above command fails to create a symbolic link because the file exists either move `~/.config/helix/runtime` to a new location or delete it, then run the symlink command above again. + +#### Windows + +Either set the `HELIX_RUNTIME` environment variable to point to the runtime files using the Windows setting (search for +`Edit environment variables for your account`) or use the `setx` command in +Cmd: + +```sh +setx HELIX_RUNTIME "%userprofile%\source\repos\helix\runtime" +``` + +> 💡 `%userprofile%` resolves to your user directory like +> `C:\Users\Your-Name\` for example. + +Or, create a symlink in `%appdata%\helix\` that links to the source code directory: + +| Method | Command | +| ---------- | -------------------------------------------------------------------------------------- | +| PowerShell | `New-Item -ItemType Junction -Target "runtime" -Path "$Env:AppData\helix\runtime"` | +| Cmd | `cd %appdata%\helix`
`mklink /D runtime "%userprofile%\src\helix\runtime"` | + +> 💡 On Windows, creating a symbolic link may require running PowerShell or +> Cmd as an administrator. + +#### Multiple runtime directories + +When Helix finds multiple runtime directories it will search through them for files in the +following order: + +1. `runtime/` sibling directory to `$CARGO_MANIFEST_DIR` directory (this is intended for + developing and testing helix only). +2. `runtime/` subdirectory of OS-dependent helix user config directory. +3. `$HELIX_RUNTIME` +4. Distribution-specific fallback directory (set at compile time—not run time— + with the `HELIX_DEFAULT_RUNTIME` environment variable) +5. `runtime/` subdirectory of path to Helix executable. + +This order also sets the priority for selecting which file will be used if multiple runtime +directories have files with the same name. + +#### Note to packagers + +If you are making a package of Helix for end users, to provide a good out of +the box experience, you should set the `HELIX_DEFAULT_RUNTIME` environment +variable at build time (before invoking `cargo build`) to a directory which +will store the final runtime files after installation. For example, say you want +to package the runtime into `/usr/lib/helix/runtime`. The rough steps a build +script could follow are: + +1. `export HELIX_DEFAULT_RUNTIME=/usr/lib/helix/runtime` +1. `cargo build --profile opt --locked --path helix-term` +1. `cp -r runtime $BUILD_DIR/usr/lib/helix/` +1. `cp target/opt/hx $BUILD_DIR/usr/bin/hx` + +This way the resulting `hx` binary will always look for its runtime directory in +`/usr/lib/helix/runtime` if the user has no custom runtime in `~/.config/helix` +or `HELIX_RUNTIME`. + +### Validating the installation + +To make sure everything is set up as expected you should run the Helix health +check: + +```sh +hx --health +``` + +For more information on the health check results refer to +[Health check](https://github.com/helix-editor/helix/wiki/Healthcheck). + +### Configure the desktop shortcut + +If your desktop environment supports the +[XDG desktop menu](https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html) +you can configure Helix to show up in the application menu by copying the +provided `.desktop` and icon files to their correct folders: + +```sh +cp contrib/Helix.desktop ~/.local/share/applications +cp contrib/helix.png ~/.icons # or ~/.local/share/icons +``` + +To use another terminal than the system default, you can modify the `.desktop` +file. For example, to use `kitty`: + +```sh +sed -i "s|Exec=hx %F|Exec=kitty hx %F|g" ~/.local/share/applications/Helix.desktop +sed -i "s|Terminal=true|Terminal=false|g" ~/.local/share/applications/Helix.desktop +``` diff --git a/book/src/configuration.md b/book/src/configuration.md index d87936457..0cd12568b 100644 --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -33,367 +33,3 @@ signal to the Helix process on Unix operating systems, such as by using the comm Finally, you can have a `config.toml` local to a project by putting it under a `.helix` directory in your repository. Its settings will be merged with the configuration directory `config.toml` and the built-in configuration. -## Editor - -### `[editor]` Section - -| Key | Description | Default | -|--|--|---------| -| `scrolloff` | Number of lines of padding around the edge of the screen when scrolling | `5` | -| `mouse` | Enable mouse mode | `true` | -| `middle-click-paste` | Middle click paste support | `true` | -| `scroll-lines` | Number of lines to scroll per scroll wheel step | `3` | -| `shell` | Shell to use when running external commands | Unix: `["sh", "-c"]`
Windows: `["cmd", "/C"]` | -| `line-number` | Line number display: `absolute` simply shows each line's number, while `relative` shows the distance from the current line. When unfocused or in insert mode, `relative` will still show absolute line numbers | `absolute` | -| `cursorline` | Highlight all lines with a cursor | `false` | -| `cursorcolumn` | Highlight all columns with a cursor | `false` | -| `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` | -| `completion-trigger-len` | The min-length of word under cursor to trigger autocompletion | `2` | -| `completion-replace` | Set to `true` to make completions always replace the entire word and not just the part before the cursor | `false` | -| `auto-info` | Whether to display info boxes | `true` | -| `true-color` | Set to `true` to override automatic detection of terminal truecolor support in the event of a false negative | `false` | -| `undercurl` | Set to `true` to override automatic detection of terminal undercurl support in the event of a false negative | `false` | -| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file | `[]` | -| `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` | -| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` | -| `text-width` | Maximum line length. Used for the `:reflow` command and soft-wrapping if `soft-wrap.wrap-at-text-width` is set | `80` | -| `workspace-lsp-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml` | `[]` | -| `default-line-ending` | The line ending to use for new documents. Can be `native`, `lf`, `crlf`, `ff`, `cr` or `nel`. `native` uses the platform's native line ending (`crlf` on Windows, otherwise `lf`). | `native` | -| `insert-final-newline` | Whether to automatically insert a trailing line-ending on write if missing | `true` | -| `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` - -### `[editor.statusline]` Section - -Allows configuring the statusline at the bottom of the editor. - -The configuration distinguishes between three areas of the status line: - -`[ ... ... LEFT ... ... | ... ... ... ... CENTER ... ... ... ... | ... ... RIGHT ... ... ]` - -Statusline elements can be defined as follows: - -```toml -[editor.statusline] -left = ["mode", "spinner"] -center = ["file-name"] -right = ["diagnostics", "selections", "position", "file-encoding", "file-line-ending", "file-type"] -separator = "│" -mode.normal = "NORMAL" -mode.insert = "INSERT" -mode.select = "SELECT" -``` -The `[editor.statusline]` key takes the following sub-keys: - -| Key | Description | Default | -| --- | --- | --- | -| `left` | A list of elements aligned to the left of the statusline | `["mode", "spinner", "file-name", "read-only-indicator", "file-modification-indicator"]` | -| `center` | A list of elements aligned to the middle of the statusline | `[]` | -| `right` | A list of elements aligned to the right of the statusline | `["diagnostics", "selections", "register", "position", "file-encoding"]` | -| `separator` | The character used to separate elements in the statusline | `"│"` | -| `mode.normal` | The text shown in the `mode` element for normal mode | `"NOR"` | -| `mode.insert` | The text shown in the `mode` element for insert mode | `"INS"` | -| `mode.select` | The text shown in the `mode` element for select mode | `"SEL"` | - -The following statusline elements can be configured: - -| Key | Description | -| ------ | ----------- | -| `mode` | The current editor mode (`mode.normal`/`mode.insert`/`mode.select`) | -| `spinner` | A progress spinner indicating LSP activity | -| `file-name` | The path/name of the opened file | -| `file-base-name` | The basename of the opened file | -| `file-modification-indicator` | The indicator to show whether the file is modified (a `[+]` appears when there are unsaved changes) | -| `file-encoding` | The encoding of the opened file if it differs from UTF-8 | -| `file-line-ending` | The file line endings (CRLF or LF) | -| `read-only-indicator` | An indicator that shows `[readonly]` when a file cannot be written | -| `total-line-numbers` | The total line numbers of the opened file | -| `file-type` | The type of the opened file | -| `diagnostics` | The number of warnings and/or errors | -| `workspace-diagnostics` | The number of warnings and/or errors on workspace | -| `selections` | The number of active selections | -| `primary-selection-length` | The number of characters currently in primary selection | -| `position` | The cursor position | -| `position-percentage` | The cursor position as a percentage of the total number of lines | -| `separator` | The string defined in `editor.statusline.separator` (defaults to `"│"`) | -| `spacer` | Inserts a space between elements (multiple/contiguous spacers may be specified) | -| `version-control` | The current branch name or detached commit hash of the opened workspace | -| `register` | The current selected register | - -### `[editor.lsp]` Section - -| Key | Description | Default | -| --- | ----------- | ------- | -| `enable` | Enables LSP integration. Setting to false will completely disable language servers regardless of language settings.| `true` | -| `display-messages` | Display LSP progress messages below statusline[^1] | `false` | -| `auto-signature-help` | Enable automatic popup of signature help (parameter hints) | `true` | -| `display-inlay-hints` | Display inlay hints[^2] | `false` | -| `display-signature-help-docs` | Display docs under signature help popup | `true` | -| `snippets` | Enables snippet completions. Requires a server restart (`:lsp-restart`) to take effect after `:config-reload`/`:set`. | `true` | -| `goto-reference-include-declaration` | Include declaration in the goto references popup. | `true` | - -[^1]: By default, a progress spinner is shown in the statusline beside the file path. - -[^2]: You may also have to activate them in the LSP config for them to appear, not just in Helix. Inlay hints in Helix are still being improved on and may be a little bit laggy/janky under some circumstances. Please report any bugs you see so we can fix them! - -### `[editor.cursor-shape]` Section - -Defines the shape of cursor in each mode. -Valid values for these options are `block`, `bar`, `underline`, or `hidden`. - -> 💡 Due to limitations of the terminal environment, only the primary cursor can -> change shape. - -| Key | Description | Default | -| --- | ----------- | ------- | -| `normal` | Cursor shape in [normal mode][normal mode] | `block` | -| `insert` | Cursor shape in [insert mode][insert mode] | `block` | -| `select` | Cursor shape in [select mode][select mode] | `block` | - -[normal mode]: ./keymap.md#normal-mode -[insert mode]: ./keymap.md#insert-mode -[select mode]: ./keymap.md#select--extend-mode - -### `[editor.file-picker]` Section - -Set options for file picker and global search. Ignoring a file means it is -not visible in the Helix file picker and global search. - -All git related options are only enabled in a git repository. - -| Key | Description | Default | -|--|--|---------| -|`hidden` | Enables ignoring hidden files | `true` -|`follow-symlinks` | Follow symlinks instead of ignoring them | `true` -|`deduplicate-links` | Ignore symlinks that point at files already shown in the picker | `true` -|`parents` | Enables reading ignore files from parent directories | `true` -|`ignore` | Enables reading `.ignore` files | `true` -|`git-ignore` | Enables reading `.gitignore` files | `true` -|`git-global` | Enables reading global `.gitignore`, whose path is specified in git's config: `core.excludesfile` option | `true` -|`git-exclude` | Enables reading `.git/info/exclude` files | `true` -|`max-depth` | Set with an integer value for maximum depth to recurse | Defaults to `None`. - -Ignore files can be placed locally as `.ignore` or put in your home directory as `~/.ignore`. They support the usual ignore and negative ignore (unignore) rules used in `.gitignore` files. - -Additionally, you can use Helix-specific ignore files by creating a local `.helix/ignore` file in the current workspace or a global `ignore` file located in your Helix config directory: -- Linux and Mac: `~/.config/helix/ignore` -- Windows: `%AppData%\helix\ignore` - -Example: - -```ini -# unignore in file picker and global search -!.github/ -!.gitignore -!.gitattributes -``` - -### `[editor.auto-pairs]` Section - -Enables automatic insertion of pairs to parentheses, brackets, etc. Can be a -simple boolean value, or a specific mapping of pairs of single characters. - -To disable auto-pairs altogether, set `auto-pairs` to `false`: - -```toml -[editor] -auto-pairs = false # defaults to `true` -``` - -The default pairs are (){}[]''""``, but these can be customized by -setting `auto-pairs` to a TOML table: - -```toml -[editor.auto-pairs] -'(' = ')' -'{' = '}' -'[' = ']' -'"' = '"' -'`' = '`' -'<' = '>' -``` - -Additionally, this setting can be used in a language config. Unless -the editor setting is `false`, this will override the editor config in -documents with this language. - -Example `languages.toml` that adds <> and removes '' - -```toml -[[language]] -name = "rust" - -[language.auto-pairs] -'(' = ')' -'{' = '}' -'[' = ']' -'"' = '"' -'`' = '`' -'<' = '>' -``` - -### `[editor.search]` Section - -Search specific options. - -| Key | Description | Default | -|--|--|---------| -| `smart-case` | Enable smart case regex searching (case-insensitive unless pattern contains upper case characters) | `true` | -| `wrap-around`| Whether the search should wrap after depleting the matches | `true` | - -### `[editor.whitespace]` Section - -Options for rendering whitespace with visible characters. Use `:set whitespace.render all` to temporarily enable visible whitespace. - -| Key | Description | Default | -|-----|-------------|---------| -| `render` | Whether to render whitespace. May either be `"all"` or `"none"`, or a table with sub-keys `space`, `nbsp`, `tab`, and `newline` | `"none"` | -| `characters` | Literal characters to use when rendering whitespace. Sub-keys may be any of `tab`, `space`, `nbsp`, `newline` or `tabpad` | See example below | - -Example - -```toml -[editor.whitespace] -render = "all" -# or control each character -[editor.whitespace.render] -space = "all" -tab = "all" -newline = "none" - -[editor.whitespace.characters] -space = "·" -nbsp = "⍽" -tab = "→" -newline = "⏎" -tabpad = "·" # Tabs will look like "→···" (depending on tab width) -``` - -### `[editor.indent-guides]` Section - -Options for rendering vertical indent guides. - -| Key | Description | Default | -| --- | --- | --- | -| `render` | Whether to render indent guides | `false` | -| `character` | Literal character to use for rendering the indent guide | `│` | -| `skip-levels` | Number of indent levels to skip | `0` | - -Example: - -```toml -[editor.indent-guides] -render = true -character = "╎" # Some characters that work well: "▏", "┆", "┊", "⸽" -skip-levels = 1 -``` - -### `[editor.gutters]` Section - -For simplicity, `editor.gutters` accepts an array of gutter types, which will -use default settings for all gutter components. - -```toml -[editor] -gutters = ["diff", "diagnostics", "line-numbers", "spacer"] -``` - -To customize the behavior of gutters, the `[editor.gutters]` section must -be used. This section contains top level settings, as well as settings for -specific gutter components as subsections. - -| Key | Description | Default | -| --- | --- | --- | -| `layout` | A vector of gutters to display | `["diagnostics", "spacer", "line-numbers", "spacer", "diff"]` | - -Example: - -```toml -[editor.gutters] -layout = ["diff", "diagnostics", "line-numbers", "spacer"] -``` - -#### `[editor.gutters.line-numbers]` Section - -Options for the line number gutter - -| Key | Description | Default | -| --- | --- | --- | -| `min-width` | The minimum number of characters to use | `3` | - -Example: - -```toml -[editor.gutters.line-numbers] -min-width = 1 -``` - -#### `[editor.gutters.diagnostics]` Section - -Currently unused - -#### `[editor.gutters.diff]` Section - -The `diff` gutter option displays colored bars indicating whether a `git` diff represents that a line was added, removed or changed. -These colors are controlled by the theme attributes `diff.plus`, `diff.minus` and `diff.delta`. - -Other diff providers will eventually be supported by a future plugin system. - -There are currently no options for this section. - -#### `[editor.gutters.spacer]` Section - -Currently unused - -### `[editor.soft-wrap]` Section - -Options for soft wrapping lines that exceed the view width: - -| Key | Description | Default | -| --- | --- | --- | -| `enable` | Whether soft wrapping is enabled. | `false` | -| `max-wrap` | Maximum free space left at the end of the line. | `20` | -| `max-indent-retain` | Maximum indentation to carry over when soft wrapping a line. | `40` | -| `wrap-indicator` | Text inserted before soft wrapped lines, highlighted with `ui.virtual.wrap` | `↪ ` | -| `wrap-at-text-width` | Soft wrap at `text-width` instead of using the full viewport size. | `false` | - -Example: - -```toml -[editor.soft-wrap] -enable = true -max-wrap = 25 # increase value to reduce forced mid-word wrapping -max-indent-retain = 0 -wrap-indicator = "" # set wrap-indicator to "" to hide it -``` - -### `[editor.smart-tab]` Section - -Options for navigating and editing using tab key. - -| Key | Description | Default | -|------------|-------------|---------| -| `enable` | If set to true, then when the cursor is in a position with non-whitespace to its left, instead of inserting a tab, it will run `move_parent_node_end`. If there is only whitespace to the left, then it inserts a tab as normal. With the default bindings, to explicitly insert a tab character, press Shift-tab. | `true` | -| `supersede-menu` | Normally, when a menu is on screen, such as when auto complete is triggered, the tab key is bound to cycling through the items. This means when menus are on screen, one cannot use the tab key to trigger the `smart-tab` command. If this option is set to true, the `smart-tab` command always takes precedence, which means one cannot use the tab key to cycle through menu items. One of the other bindings must be used instead, such as arrow keys or `C-n`/`C-p`. | `false` | - - -Due to lack of support for S-tab in some terminals, the default keybindings don't fully embrace smart-tab editing experience. If you enjoy smart-tab navigation and a terminal that supports the [Enhanced Keyboard protocol](https://github.com/helix-editor/helix/wiki/Terminal-Support#enhanced-keyboard-protocol), consider setting extra keybindings: - -``` -[keys.normal] -tab = "move_parent_node_end" -S-tab = "move_parent_node_start" - -[keys.insert] -S-tab = "move_parent_node_start" - -[keys.select] -tab = "extend_parent_node_end" -S-tab = "extend_parent_node_start" -``` diff --git a/book/src/editor.md b/book/src/editor.md new file mode 100644 index 000000000..ba03e90e5 --- /dev/null +++ b/book/src/editor.md @@ -0,0 +1,395 @@ +## Editor + +- [`[editor]` Section](#editor-section) +- [`[editor.statusline]` Section](#editorstatusline-section) +- [`[editor.lsp]` Section](#editorlsp-section) +- [`[editor.cursor-shape]` Section](#editorcursor-shape-section) +- [`[editor.file-picker]` Section](#editorfile-picker-section) +- [`[editor.auto-pairs]` Section](#editorauto-pairs-section) +- [`[editor.search]` Section](#editorsearch-section) +- [`[editor.whitespace]` Section](#editorwhitespace-section) +- [`[editor.indent-guides]` Section](#editorindent-guides-section) +- [`[editor.gutters]` Section](#editorgutters-section) + - [`[editor.gutters.line-numbers]` Section](#editorguttersline-numbers-section) + - [`[editor.gutters.diagnostics]` Section](#editorguttersdiagnostics-section) + - [`[editor.gutters.diff]` Section](#editorguttersdiff-section) + - [`[editor.gutters.spacer]` Section](#editorguttersspacer-section) +- [`[editor.soft-wrap]` Section](#editorsoft-wrap-section) +- [`[editor.smart-tab]` Section](#editorsmart-tab-section) + +### `[editor]` Section + +| Key | Description | Default | +|--|--|---------| +| `scrolloff` | Number of lines of padding around the edge of the screen when scrolling | `5` | +| `mouse` | Enable mouse mode | `true` | +| `middle-click-paste` | Middle click paste support | `true` | +| `scroll-lines` | Number of lines to scroll per scroll wheel step | `3` | +| `shell` | Shell to use when running external commands | Unix: `["sh", "-c"]`
Windows: `["cmd", "/C"]` | +| `line-number` | Line number display: `absolute` simply shows each line's number, while `relative` shows the distance from the current line. When unfocused or in insert mode, `relative` will still show absolute line numbers | `absolute` | +| `cursorline` | Highlight all lines with a cursor | `false` | +| `cursorcolumn` | Highlight all columns with a cursor | `false` | +| `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` | +| `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` | +| `completion-trigger-len` | The min-length of word under cursor to trigger autocompletion | `2` | +| `completion-replace` | Set to `true` to make completions always replace the entire word and not just the part before the cursor | `false` | +| `auto-info` | Whether to display info boxes | `true` | +| `true-color` | Set to `true` to override automatic detection of terminal truecolor support in the event of a false negative | `false` | +| `undercurl` | Set to `true` to override automatic detection of terminal undercurl support in the event of a false negative | `false` | +| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file | `[]` | +| `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` | +| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` | +| `text-width` | Maximum line length. Used for the `:reflow` command and soft-wrapping if `soft-wrap.wrap-at-text-width` is set | `80` | +| `workspace-lsp-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml` | `[]` | +| `default-line-ending` | The line ending to use for new documents. Can be `native`, `lf`, `crlf`, `ff`, `cr` or `nel`. `native` uses the platform's native line ending (`crlf` on Windows, otherwise `lf`). | `native` | +| `insert-final-newline` | Whether to automatically insert a trailing line-ending on write if missing | `true` | +| `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"` + +### `[editor.statusline]` Section + +Allows configuring the statusline at the bottom of the editor. + +The configuration distinguishes between three areas of the status line: + +`[ ... ... LEFT ... ... | ... ... ... CENTER ... ... ... | ... ... RIGHT ... ... ]` + +Statusline elements can be defined as follows: + +```toml +[editor.statusline] +left = ["mode", "spinner"] +center = ["file-name"] +right = ["diagnostics", "selections", "position", "file-encoding", "file-line-ending", "file-type"] +separator = "│" +mode.normal = "NORMAL" +mode.insert = "INSERT" +mode.select = "SELECT" +``` +The `[editor.statusline]` key takes the following sub-keys: + +| Key | Description | Default | +| --- | --- | --- | +| `left` | A list of elements aligned to the left of the statusline | `["mode", "spinner", "file-name", "read-only-indicator", "file-modification-indicator"]` | +| `center` | A list of elements aligned to the middle of the statusline | `[]` | +| `right` | A list of elements aligned to the right of the statusline | `["diagnostics", "selections", "register", "position", "file-encoding"]` | +| `separator` | The character used to separate elements in the statusline | `"│"` | +| `mode.normal` | The text shown in the `mode` element for normal mode | `"NOR"` | +| `mode.insert` | The text shown in the `mode` element for insert mode | `"INS"` | +| `mode.select` | The text shown in the `mode` element for select mode | `"SEL"` | + +The following statusline elements can be configured: + +| Key | Description | +| ------ | ----------- | +| `mode` | The current editor mode (`mode.normal`/`mode.insert`/`mode.select`) | +| `spinner` | A progress spinner indicating LSP activity | +| `file-name` | The path/name of the opened file | +| `file-absolute-path` | The absolute path/name of the opened file | +| `file-base-name` | The basename of the opened file | +| `file-modification-indicator` | The indicator to show whether the file is modified (a `[+]` appears when there are unsaved changes) | +| `file-encoding` | The encoding of the opened file if it differs from UTF-8 | +| `file-line-ending` | The file line endings (CRLF or LF) | +| `read-only-indicator` | An indicator that shows `[readonly]` when a file cannot be written | +| `total-line-numbers` | The total line numbers of the opened file | +| `file-type` | The type of the opened file | +| `diagnostics` | The number of warnings and/or errors | +| `workspace-diagnostics` | The number of warnings and/or errors on workspace | +| `selections` | The number of active selections | +| `primary-selection-length` | The number of characters currently in primary selection | +| `position` | The cursor position | +| `position-percentage` | The cursor position as a percentage of the total number of lines | +| `separator` | The string defined in `editor.statusline.separator` (defaults to `"│"`) | +| `spacer` | Inserts a space between elements (multiple/contiguous spacers may be specified) | +| `version-control` | The current branch name or detached commit hash of the opened workspace | +| `register` | The current selected register | + +### `[editor.lsp]` Section + +| Key | Description | Default | +| --- | ----------- | ------- | +| `enable` | Enables LSP integration. Setting to false will completely disable language servers regardless of language settings.| `true` | +| `display-messages` | Display LSP progress messages below statusline[^1] | `false` | +| `auto-signature-help` | Enable automatic popup of signature help (parameter hints) | `true` | +| `display-inlay-hints` | Display inlay hints[^2] | `false` | +| `display-signature-help-docs` | Display docs under signature help popup | `true` | +| `snippets` | Enables snippet completions. Requires a server restart (`:lsp-restart`) to take effect after `:config-reload`/`:set`. | `true` | +| `goto-reference-include-declaration` | Include declaration in the goto references popup. | `true` | + +[^1]: By default, a progress spinner is shown in the statusline beside the file path. + +[^2]: You may also have to activate them in the LSP config for them to appear, not just in Helix. Inlay hints in Helix are still being improved on and may be a little bit laggy/janky under some circumstances. Please report any bugs you see so we can fix them! + +### `[editor.cursor-shape]` Section + +Defines the shape of cursor in each mode. +Valid values for these options are `block`, `bar`, `underline`, or `hidden`. + +> 💡 Due to limitations of the terminal environment, only the primary cursor can +> change shape. + +| Key | Description | Default | +| --- | ----------- | ------- | +| `normal` | Cursor shape in [normal mode][normal mode] | `block` | +| `insert` | Cursor shape in [insert mode][insert mode] | `block` | +| `select` | Cursor shape in [select mode][select mode] | `block` | + +[normal mode]: ./keymap.md#normal-mode +[insert mode]: ./keymap.md#insert-mode +[select mode]: ./keymap.md#select--extend-mode + +### `[editor.file-picker]` Section + +Set options for file picker and global search. Ignoring a file means it is +not visible in the Helix file picker and global search. + +All git related options are only enabled in a git repository. + +| Key | Description | Default | +|--|--|---------| +|`hidden` | Enables ignoring hidden files | `true` +|`follow-symlinks` | Follow symlinks instead of ignoring them | `true` +|`deduplicate-links` | Ignore symlinks that point at files already shown in the picker | `true` +|`parents` | Enables reading ignore files from parent directories | `true` +|`ignore` | Enables reading `.ignore` files | `true` +|`git-ignore` | Enables reading `.gitignore` files | `true` +|`git-global` | Enables reading global `.gitignore`, whose path is specified in git's config: `core.excludesfile` option | `true` +|`git-exclude` | Enables reading `.git/info/exclude` files | `true` +|`max-depth` | Set with an integer value for maximum depth to recurse | Unset by default + +Ignore files can be placed locally as `.ignore` or put in your home directory as `~/.ignore`. They support the usual ignore and negative ignore (unignore) rules used in `.gitignore` files. + +Additionally, you can use Helix-specific ignore files by creating a local `.helix/ignore` file in the current workspace or a global `ignore` file located in your Helix config directory: +- Linux and Mac: `~/.config/helix/ignore` +- Windows: `%AppData%\helix\ignore` + +Example: + +```ini +# unignore in file picker and global search +!.github/ +!.gitignore +!.gitattributes +``` + +### `[editor.auto-pairs]` Section + +Enables automatic insertion of pairs to parentheses, brackets, etc. Can be a +simple boolean value, or a specific mapping of pairs of single characters. + +To disable auto-pairs altogether, set `auto-pairs` to `false`: + +```toml +[editor] +auto-pairs = false # defaults to `true` +``` + +The default pairs are (){}[]''""``, but these can be customized by +setting `auto-pairs` to a TOML table: + +```toml +[editor.auto-pairs] +'(' = ')' +'{' = '}' +'[' = ']' +'"' = '"' +'`' = '`' +'<' = '>' +``` + +Additionally, this setting can be used in a language config. Unless +the editor setting is `false`, this will override the editor config in +documents with this language. + +Example `languages.toml` that adds `<>` and removes `''` + +```toml +[[language]] +name = "rust" + +[language.auto-pairs] +'(' = ')' +'{' = '}' +'[' = ']' +'"' = '"' +'`' = '`' +'<' = '>' +``` + +### `[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. + +| Key | Description | Default | +|--|--|---------| +| `smart-case` | Enable smart case regex searching (case-insensitive unless pattern contains upper case characters) | `true` | +| `wrap-around`| Whether the search should wrap after depleting the matches | `true` | + +### `[editor.whitespace]` Section + +Options for rendering whitespace with visible characters. Use `:set whitespace.render all` to temporarily enable visible whitespace. + +| Key | Description | Default | +|-----|-------------|---------| +| `render` | Whether to render whitespace. May either be `all` or `none`, or a table with sub-keys `space`, `nbsp`, `nnbsp`, `tab`, and `newline` | `none` | +| `characters` | Literal characters to use when rendering whitespace. Sub-keys may be any of `tab`, `space`, `nbsp`, `nnbsp`, `newline` or `tabpad` | See example below | + +Example + +```toml +[editor.whitespace] +render = "all" +# or control each character +[editor.whitespace.render] +space = "all" +tab = "all" +nbsp = "none" +nnbsp = "none" +newline = "none" + +[editor.whitespace.characters] +space = "·" +nbsp = "⍽" +nnbsp = "␣" +tab = "→" +newline = "⏎" +tabpad = "·" # Tabs will look like "→···" (depending on tab width) +``` + +### `[editor.indent-guides]` Section + +Options for rendering vertical indent guides. + +| Key | Description | Default | +| --- | --- | --- | +| `render` | Whether to render indent guides | `false` | +| `character` | Literal character to use for rendering the indent guide | `│` | +| `skip-levels` | Number of indent levels to skip | `0` | + +Example: + +```toml +[editor.indent-guides] +render = true +character = "╎" # Some characters that work well: "▏", "┆", "┊", "⸽" +skip-levels = 1 +``` + +### `[editor.gutters]` Section + +For simplicity, `editor.gutters` accepts an array of gutter types, which will +use default settings for all gutter components. + +```toml +[editor] +gutters = ["diff", "diagnostics", "line-numbers", "spacer"] +``` + +To customize the behavior of gutters, the `[editor.gutters]` section must +be used. This section contains top level settings, as well as settings for +specific gutter components as subsections. + +| Key | Description | Default | +| --- | --- | --- | +| `layout` | A vector of gutters to display | `["diagnostics", "spacer", "line-numbers", "spacer", "diff"]` | + +Example: + +```toml +[editor.gutters] +layout = ["diff", "diagnostics", "line-numbers", "spacer"] +``` + +#### `[editor.gutters.line-numbers]` Section + +Options for the line number gutter + +| Key | Description | Default | +| --- | --- | --- | +| `min-width` | The minimum number of characters to use | `3` | + +Example: + +```toml +[editor.gutters.line-numbers] +min-width = 1 +``` + +#### `[editor.gutters.diagnostics]` Section + +Currently unused + +#### `[editor.gutters.diff]` Section + +The `diff` gutter option displays colored bars indicating whether a `git` diff represents that a line was added, removed or changed. +These colors are controlled by the theme attributes `diff.plus`, `diff.minus` and `diff.delta`. + +Other diff providers will eventually be supported by a future plugin system. + +There are currently no options for this section. + +#### `[editor.gutters.spacer]` Section + +Currently unused + +### `[editor.soft-wrap]` Section + +Options for soft wrapping lines that exceed the view width: + +| Key | Description | Default | +| --- | --- | --- | +| `enable` | Whether soft wrapping is enabled. | `false` | +| `max-wrap` | Maximum free space left at the end of the line. | `20` | +| `max-indent-retain` | Maximum indentation to carry over when soft wrapping a line. | `40` | +| `wrap-indicator` | Text inserted before soft wrapped lines, highlighted with `ui.virtual.wrap` | `↪ ` | +| `wrap-at-text-width` | Soft wrap at `text-width` instead of using the full viewport size. | `false` | + +Example: + +```toml +[editor.soft-wrap] +enable = true +max-wrap = 25 # increase value to reduce forced mid-word wrapping +max-indent-retain = 0 +wrap-indicator = "" # set wrap-indicator to "" to hide it +``` + +### `[editor.smart-tab]` Section + +Options for navigating and editing using tab key. + +| Key | Description | Default | +|------------|-------------|---------| +| `enable` | If set to true, then when the cursor is in a position with non-whitespace to its left, instead of inserting a tab, it will run `move_parent_node_end`. If there is only whitespace to the left, then it inserts a tab as normal. With the default bindings, to explicitly insert a tab character, press Shift-tab. | `true` | +| `supersede-menu` | Normally, when a menu is on screen, such as when auto complete is triggered, the tab key is bound to cycling through the items. This means when menus are on screen, one cannot use the tab key to trigger the `smart-tab` command. If this option is set to true, the `smart-tab` command always takes precedence, which means one cannot use the tab key to cycle through menu items. One of the other bindings must be used instead, such as arrow keys or `C-n`/`C-p`. | `false` | + + +Due to lack of support for S-tab in some terminals, the default keybindings don't fully embrace smart-tab editing experience. If you enjoy smart-tab navigation and a terminal that supports the [Enhanced Keyboard protocol](https://github.com/helix-editor/helix/wiki/Terminal-Support#enhanced-keyboard-protocol), consider setting extra keybindings: + +``` +[keys.normal] +tab = "move_parent_node_end" +S-tab = "move_parent_node_start" + +[keys.insert] +S-tab = "move_parent_node_start" + +[keys.select] +tab = "extend_parent_node_end" +S-tab = "extend_parent_node_start" +``` diff --git a/book/src/generated/lang-support.md b/book/src/generated/lang-support.md index c9668549e..5afde0972 100644 --- a/book/src/generated/lang-support.md +++ b/book/src/generated/lang-support.md @@ -1,5 +1,7 @@ | Language | Syntax Highlighting | Treesitter Textobjects | Auto Indent | Default LSP | | --- | --- | --- | --- | --- | +| ada | ✓ | ✓ | | `ada_language_server`, `ada_language_server` | +| adl | ✓ | ✓ | ✓ | | | agda | ✓ | | | | | astro | ✓ | | | | | awk | ✓ | ✓ | | `awk-language-server` | @@ -8,6 +10,8 @@ | beancount | ✓ | | | | | bibtex | ✓ | | | `texlab` | | bicep | ✓ | | | `bicep-langserver` | +| bitbake | ✓ | | | `bitbake-language-server` | +| blade | ✓ | | | | | blueprint | ✓ | | | `blueprint-compiler` | | c | ✓ | ✓ | ✓ | `clangd` | | c-sharp | ✓ | ✓ | | `OmniSharp` | @@ -30,13 +34,15 @@ | devicetree | ✓ | | | | | dhall | ✓ | ✓ | | `dhall-lsp-server` | | diff | ✓ | | | | -| docker-compose | ✓ | | ✓ | `docker-compose-langserver` | +| docker-compose | ✓ | | ✓ | `docker-compose-langserver`, `yaml-language-server` | | dockerfile | ✓ | | | `docker-langserver` | | dot | ✓ | | | `dot-language-server` | | dtd | ✓ | | | | +| earthfile | ✓ | ✓ | ✓ | `earthlyls` | | edoc | ✓ | | | | | eex | ✓ | | | | | ejs | ✓ | | | | +| elisp | ✓ | | | | | elixir | ✓ | ✓ | ✓ | `elixir-ls` | | elm | ✓ | ✓ | | `elm-language-server` | | elvish | ✓ | | | `elvish` | @@ -57,7 +63,9 @@ | git-config | ✓ | | | | | git-ignore | ✓ | | | | | git-rebase | ✓ | | | | +| gjs | ✓ | ✓ | ✓ | `typescript-language-server`, `vscode-eslint-language-server`, `ember-language-server` | | gleam | ✓ | ✓ | | `gleam` | +| glimmer | ✓ | | | `ember-language-server` | | glsl | ✓ | ✓ | ✓ | | | gn | ✓ | | | | | go | ✓ | ✓ | ✓ | `gopls`, `golangci-lint-langserver` | @@ -65,35 +73,43 @@ | gomod | ✓ | | | `gopls` | | gotmpl | ✓ | | | `gopls` | | gowork | ✓ | | | `gopls` | -| graphql | ✓ | | | `graphql-lsp` | +| graphql | ✓ | ✓ | | `graphql-lsp` | | groovy | ✓ | | | | +| gts | ✓ | ✓ | ✓ | `typescript-language-server`, `vscode-eslint-language-server`, `ember-language-server` | | hare | ✓ | | | | | haskell | ✓ | ✓ | | `haskell-language-server-wrapper` | | haskell-persistent | ✓ | | | | | hcl | ✓ | ✓ | ✓ | `terraform-ls` | | heex | ✓ | ✓ | | `elixir-ls` | +| helm | ✓ | | | `helm_ls` | | hocon | ✓ | | ✓ | | | hoon | ✓ | | | | | hosts | ✓ | | | | | html | ✓ | | | `vscode-html-language-server` | -| hurl | ✓ | | ✓ | | +| hurl | ✓ | ✓ | ✓ | | +| hyprlang | ✓ | | ✓ | | | idris | | | | `idris2-lsp` | | iex | ✓ | | | | | ini | ✓ | | | | +| inko | ✓ | ✓ | ✓ | | | janet | ✓ | | | | | java | ✓ | ✓ | ✓ | `jdtls` | | javascript | ✓ | ✓ | ✓ | `typescript-language-server` | | jinja | ✓ | | | | | jsdoc | ✓ | | | | -| json | ✓ | | ✓ | `vscode-json-language-server` | +| json | ✓ | ✓ | ✓ | `vscode-json-language-server` | | json5 | ✓ | | | | +| jsonc | ✓ | | ✓ | `vscode-json-language-server` | | jsonnet | ✓ | | | `jsonnet-language-server` | | jsx | ✓ | ✓ | ✓ | `typescript-language-server` | | julia | ✓ | ✓ | ✓ | `julia` | | just | ✓ | ✓ | ✓ | | | kdl | ✓ | ✓ | ✓ | | +| koka | ✓ | | ✓ | `koka` | | kotlin | ✓ | | | `kotlin-language-server` | | latex | ✓ | ✓ | | `texlab` | +| ld | ✓ | | ✓ | | +| ldif | ✓ | | | | | lean | ✓ | | | `lean` | | ledger | ✓ | | | | | llvm | ✓ | ✓ | ✓ | | @@ -110,6 +126,8 @@ | mermaid | ✓ | | | | | meson | ✓ | | ✓ | | | mint | | | | `mint` | +| mojo | ✓ | ✓ | ✓ | `mojo-lsp-server` | +| move | ✓ | | | | | msbuild | ✓ | | ✓ | | | nasm | ✓ | ✓ | | | | nickel | ✓ | | ✓ | `nls` | @@ -120,6 +138,7 @@ | ocaml | ✓ | | ✓ | `ocamllsp` | | ocaml-interface | ✓ | | | `ocamllsp` | | odin | ✓ | | ✓ | `ols` | +| ohm | ✓ | ✓ | ✓ | | | opencl | ✓ | ✓ | ✓ | `clangd` | | openscad | ✓ | | | `openscad-lsp` | | org | ✓ | | | | @@ -127,11 +146,15 @@ | passwd | ✓ | | | | | pem | ✓ | | | | | perl | ✓ | ✓ | ✓ | `perlnavigator` | +| pest | ✓ | ✓ | ✓ | `pest-language-server` | | php | ✓ | ✓ | ✓ | `intelephense` | +| php-only | ✓ | | | | +| pkgbuild | ✓ | ✓ | ✓ | `pkgbuild-language-server`, `bash-language-server` | | pkl | ✓ | | ✓ | | | po | ✓ | ✓ | | | | pod | ✓ | | | | | ponylang | ✓ | ✓ | ✓ | | +| powershell | ✓ | | | | | prisma | ✓ | | | `prisma-language-server` | | prolog | | | | `swipl` | | protobuf | ✓ | ✓ | ✓ | `bufls`, `pb` | @@ -158,33 +181,35 @@ | smali | ✓ | | ✓ | | | smithy | ✓ | | | `cs` | | sml | ✓ | | | | -| solidity | ✓ | | | `solc` | +| solidity | ✓ | ✓ | | `solc` | | spicedb | ✓ | | | | | sql | ✓ | | | | | sshclientconfig | ✓ | | | | | starlark | ✓ | ✓ | | | | strace | ✓ | | | | +| supercollider | ✓ | | | | | svelte | ✓ | | ✓ | `svelteserver` | | sway | ✓ | ✓ | ✓ | `forc` | -| swift | ✓ | | | `sourcekit-lsp` | +| swift | ✓ | ✓ | | `sourcekit-lsp` | | t32 | ✓ | | | | | tablegen | ✓ | ✓ | ✓ | | | tact | ✓ | ✓ | ✓ | | | task | ✓ | | | | +| tcl | ✓ | | ✓ | | | templ | ✓ | | | `templ` | | tfvars | ✓ | | ✓ | `terraform-ls` | | todotxt | ✓ | | | | -| toml | ✓ | | | `taplo` | +| toml | ✓ | ✓ | | `taplo` | | tsq | ✓ | | | | | tsx | ✓ | ✓ | ✓ | `typescript-language-server` | | twig | ✓ | | | | | typescript | ✓ | ✓ | ✓ | `typescript-language-server` | -| typst | ✓ | | | `typst-lsp` | +| typst | ✓ | | | `tinymist`, `typst-lsp` | | ungrammar | ✓ | | | | | unison | ✓ | | ✓ | | | uxntal | ✓ | | | | | v | ✓ | ✓ | ✓ | `v-analyzer` | -| vala | ✓ | | | `vala-language-server` | +| vala | ✓ | ✓ | | `vala-language-server` | | verilog | ✓ | ✓ | | `svlangserver` | | vhdl | ✓ | | | `vhdl_ls` | | vhs | ✓ | | | | @@ -197,6 +222,7 @@ | wren | ✓ | ✓ | ✓ | | | xit | ✓ | | | | | xml | ✓ | | ✓ | | +| xtc | ✓ | | | | | yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` | | yuck | ✓ | | | | | zig | ✓ | ✓ | ✓ | `zls` | diff --git a/book/src/generated/typable-cmd.md b/book/src/generated/typable-cmd.md index f4fcb6f62..cf1b550dc 100644 --- a/book/src/generated/typable-cmd.md +++ b/book/src/generated/typable-cmd.md @@ -86,3 +86,5 @@ | `: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 | +| `:yank-diagnostic` | Yank diagnostic(s) under primary cursor to register, or clipboard by default | +| `:read`, `:r` | Load a file into buffer | diff --git a/book/src/guides/adding_languages.md b/book/src/guides/adding_languages.md index 0763a3c5c..1a47b79c6 100644 --- a/book/src/guides/adding_languages.md +++ b/book/src/guides/adding_languages.md @@ -16,7 +16,7 @@ below. > 💡 If you are adding a new Language Server configuration, make sure to update > the -> [Language Server Wiki](https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers) +> [Language Server Wiki](https://github.com/helix-editor/helix/wiki/Language-Server-Configurations) > with the installation instructions. ## Grammar configuration diff --git a/book/src/guides/textobject.md b/book/src/guides/textobject.md index 405f11c1b..a31baef93 100644 --- a/book/src/guides/textobject.md +++ b/book/src/guides/textobject.md @@ -25,6 +25,8 @@ The following [captures][tree-sitter-captures] are recognized: | `parameter.inside` | | `comment.inside` | | `comment.around` | +| `entry.inside` | +| `entry.around` | [Example query files][textobject-examples] can be found in the helix GitHub repository. @@ -44,4 +46,4 @@ doesn't make sense in a navigation context. [tree-sitter-queries]: https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax [tree-sitter-captures]: https://tree-sitter.github.io/tree-sitter/using-parsers#capturing-nodes -[textobject-examples]: https://github.com/search?q=repo%3Ahelix-editor%2Fhelix+filename%3Atextobjects.scm&type=Code&ref=advsearch&l=&l= +[textobject-examples]: https://github.com/search?q=repo%3Ahelix-editor%2Fhelix+path%3A%2A%2A/textobjects.scm&type=Code&ref=advsearch&l=&l= diff --git a/book/src/install.md b/book/src/install.md index 07865e698..debc82b01 100644 --- a/book/src/install.md +++ b/book/src/install.md @@ -1,38 +1,10 @@ # Installing Helix - -- [Pre-built binaries](#pre-built-binaries) -- [Linux, macOS, Windows and OpenBSD packaging status](#linux-macos-windows-and-openbsd-packaging-status) -- [Linux](#linux) - - [Ubuntu](#ubuntu) - - [Fedora/RHEL](#fedorarhel) - - [Arch Linux extra](#arch-linux-extra) - - [NixOS](#nixos) - - [Flatpak](#flatpak) - - [Snap](#snap) - - [AppImage](#appimage) -- [macOS](#macos) - - [Homebrew Core](#homebrew-core) - - [MacPorts](#macports) -- [Windows](#windows) - - [Winget](#winget) - - [Scoop](#scoop) - - [Chocolatey](#chocolatey) - - [MSYS2](#msys2) -- [Building from source](#building-from-source) - - [Configuring Helix's runtime files](#configuring-helixs-runtime-files) - - [Linux and macOS](#linux-and-macos) - - [Windows](#windows) - - [Multiple runtime directories](#multiple-runtime-directories) - - [Validating the installation](#validating-the-installation) - - [Configure the desktop shortcut](#configure-the-desktop-shortcut) - - To install Helix, follow the instructions specific to your operating system. Note that: - To get the latest nightly version of Helix, you need to - [build from source](#building-from-source). + [build from source](./building-from-source.md). - To take full advantage of Helix, install the language servers for your preferred programming languages. See the @@ -41,291 +13,7 @@ Note that: ## Pre-built binaries -Download pre-built binaries from the -[GitHub Releases page](https://github.com/helix-editor/helix/releases). Add the binary to your system's `$PATH` to use it from the command -line. - -## Linux, macOS, Windows and OpenBSD packaging status - -[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions) - -## Linux - -The following third party repositories are available: - -### Ubuntu - -Add the `PPA` for Helix: - -```sh -sudo add-apt-repository ppa:maveonair/helix-editor -sudo apt update -sudo apt install helix -``` - -### Fedora/RHEL - -```sh -sudo dnf install helix -``` - -### Arch Linux extra - -Releases are available in the `extra` repository: - -```sh -sudo pacman -S helix -``` - -> 💡 When installed from the `extra` repository, run Helix with `helix` instead of `hx`. -> -> For example: -> ```sh -> helix --health -> ``` -> to check health - -Additionally, a [helix-git](https://aur.archlinux.org/packages/helix-git/) package is available -in the AUR, which builds the master branch. - -### NixOS - -Helix is available in [nixpkgs](https://github.com/nixos/nixpkgs) through the `helix` attribute, -the unstable channel usually carries the latest release. - -Helix is also available as a [flake](https://nixos.wiki/wiki/Flakes) in the project -root. Use `nix develop` to spin up a reproducible development shell. Outputs are -cached for each push to master using [Cachix](https://www.cachix.org/). The -flake is configured to automatically make use of this cache assuming the user -accepts the new settings on first use. - -If you are using a version of Nix without flakes enabled, -[install Cachix CLI](https://docs.cachix.org/installation) and use -`cachix use helix` to configure Nix to use cached outputs when possible. - -### Flatpak - -Helix is available on [Flathub](https://flathub.org/en-GB/apps/com.helix_editor.Helix): - -```sh -flatpak install flathub com.helix_editor.Helix -flatpak run com.helix_editor.Helix -``` - -### Snap - -Helix is available on [Snapcraft](https://snapcraft.io/helix) and can be installed with: - -```sh -snap install --classic helix -``` - -This will install Helix as both `/snap/bin/helix` and `/snap/bin/hx`, so make sure `/snap/bin` is in your `PATH`. - -### AppImage - -Install Helix using the Linux [AppImage](https://appimage.org/) format. -Download the official Helix AppImage from the [latest releases](https://github.com/helix-editor/helix/releases/latest) page. - -```sh -chmod +x helix-*.AppImage # change permission for executable mode -./helix-*.AppImage # run helix -``` - -## macOS - -### Homebrew Core - -```sh -brew install helix -``` - -### MacPorts - -```sh -port install helix -``` - -## Windows - -Install on Windows using [Winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/), [Scoop](https://scoop.sh/), [Chocolatey](https://chocolatey.org/) -or [MSYS2](https://msys2.org/). - -### Winget -Windows Package Manager winget command-line tool is by default available on Windows 11 and modern versions of Windows 10 as a part of the App Installer. -You can get [App Installer from the Microsoft Store](https://www.microsoft.com/p/app-installer/9nblggh4nns1#activetab=pivot:overviewtab). If it's already installed, make sure it is updated with the latest version. - -```sh -winget install Helix.Helix -``` - -### Scoop - -```sh -scoop install helix -``` - -### Chocolatey - -```sh -choco install helix -``` - -### MSYS2 - -For 64-bit Windows 8.1 or above: - -```sh -pacman -S mingw-w64-ucrt-x86_64-helix -``` - -## Building from source - -Requirements: - -Clone the Helix GitHub repository into a directory of your choice. The -examples in this documentation assume installation into either `~/src/` on -Linux and macOS, or `%userprofile%\src\` on Windows. - -- The [Rust toolchain](https://www.rust-lang.org/tools/install) -- The [Git version control system](https://git-scm.com/) -- A C++14 compatible compiler to build the tree-sitter grammars, for example GCC or Clang - -If you are using the `musl-libc` standard library instead of `glibc` the following environment variable must be set during the build to ensure tree-sitter grammars can be loaded correctly: - -```sh -RUSTFLAGS="-C target-feature=-crt-static" -``` - -1. Clone the repository: - - ```sh - git clone https://github.com/helix-editor/helix - cd helix - ``` - -2. Compile from source: - - ```sh - cargo install --path helix-term --locked - ``` - - This command will create the `hx` executable and construct the tree-sitter - grammars in the local `runtime` folder. - -> 💡 If you do not want to fetch or build grammars, set an environment variable `HELIX_DISABLE_AUTO_GRAMMAR_BUILD` - -> 💡 Tree-sitter grammars can be fetched and compiled if not pre-packaged. Fetch -> grammars with `hx --grammar fetch` and compile them with -> `hx --grammar build`. This will install them in -> the `runtime` directory within the user's helix config directory (more -> [details below](#multiple-runtime-directories)). - -### Configuring Helix's runtime files - -#### Linux and macOS - -The **runtime** directory is one below the Helix source, so either export a -`HELIX_RUNTIME` environment variable to point to that directory and add it to -your `~/.bashrc` or equivalent: - -```sh -export HELIX_RUNTIME=~/src/helix/runtime -``` - -Or, create a symbolic link: - -```sh -ln -Ts $PWD/runtime ~/.config/helix/runtime -``` - -If the above command fails to create a symbolic link because the file exists either move `~/.config/helix/runtime` to a new location or delete it, then run the symlink command above again. - -#### Windows - -Either set the `HELIX_RUNTIME` environment variable to point to the runtime files using the Windows setting (search for -`Edit environment variables for your account`) or use the `setx` command in -Cmd: - -```sh -setx HELIX_RUNTIME "%userprofile%\source\repos\helix\runtime" -``` - -> 💡 `%userprofile%` resolves to your user directory like -> `C:\Users\Your-Name\` for example. - -Or, create a symlink in `%appdata%\helix\` that links to the source code directory: - -| Method | Command | -| ---------- | -------------------------------------------------------------------------------------- | -| PowerShell | `New-Item -ItemType Junction -Target "runtime" -Path "$Env:AppData\helix\runtime"` | -| Cmd | `cd %appdata%\helix`
`mklink /D runtime "%userprofile%\src\helix\runtime"` | - -> 💡 On Windows, creating a symbolic link may require running PowerShell or -> Cmd as an administrator. - -#### Multiple runtime directories - -When Helix finds multiple runtime directories it will search through them for files in the -following order: - -1. `runtime/` sibling directory to `$CARGO_MANIFEST_DIR` directory (this is intended for - developing and testing helix only). -2. `runtime/` subdirectory of OS-dependent helix user config directory. -3. `$HELIX_RUNTIME` -4. Distribution-specific fallback directory (set at compile time—not run time— - with the `HELIX_DEFAULT_RUNTIME` environment variable) -5. `runtime/` subdirectory of path to Helix executable. - -This order also sets the priority for selecting which file will be used if multiple runtime -directories have files with the same name. - -#### Note to packagers - -If you are making a package of Helix for end users, to provide a good out of -the box experience, you should set the `HELIX_DEFAULT_RUNTIME` environment -variable at build time (before invoking `cargo build`) to a directory which -will store the final runtime files after installation. For example, say you want -to package the runtime into `/usr/lib/helix/runtime`. The rough steps a build -script could follow are: - -1. `export HELIX_DEFAULT_RUNTIME=/usr/lib/helix/runtime` -1. `cargo build --profile opt --locked --path helix-term` -1. `cp -r runtime $BUILD_DIR/usr/lib/helix/` -1. `cp target/opt/hx $BUILD_DIR/usr/bin/hx` - -This way the resulting `hx` binary will always look for its runtime directory in -`/usr/lib/helix/runtime` if the user has no custom runtime in `~/.config/helix` -or `HELIX_RUNTIME`. - -### Validating the installation - -To make sure everything is set up as expected you should run the Helix health -check: - -```sh -hx --health -``` - -For more information on the health check results refer to -[Health check](https://github.com/helix-editor/helix/wiki/Healthcheck). - -### Configure the desktop shortcut - -If your desktop environment supports the -[XDG desktop menu](https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html) -you can configure Helix to show up in the application menu by copying the -provided `.desktop` and icon files to their correct folders: - -```sh -cp contrib/Helix.desktop ~/.local/share/applications -cp contrib/helix.png ~/.icons # or ~/.local/share/icons -``` - -To use another terminal than the system default, you can modify the `.desktop` -file. For example, to use `kitty`: +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. -```sh -sed -i "s|Exec=hx %F|Exec=kitty hx %F|g" ~/.local/share/applications/Helix.desktop -sed -i "s|Terminal=true|Terminal=false|g" ~/.local/share/applications/Helix.desktop -``` diff --git a/book/src/keymap.md b/book/src/keymap.md index 2c58e0850..442f27ca3 100644 --- a/book/src/keymap.md +++ b/book/src/keymap.md @@ -1,4 +1,4 @@ -# Keymap +## Keymap - [Normal mode](#normal-mode) - [Movement](#movement) @@ -12,8 +12,9 @@ - [Match mode](#match-mode) - [Window mode](#window-mode) - [Space mode](#space-mode) - - [Comment mode](#comment-mode) - [Popup](#popup) + - [Completion Menu](#completion-menu) + - [Signature-help Popup](#signature-help-popup) - [Unimpaired](#unimpaired) - [Insert mode](#insert-mode) - [Select / extend mode](#select--extend-mode) @@ -24,6 +25,8 @@ > 💡 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. + ## Normal mode Normal mode is the default mode when you launch helix. You can return to it from other modes by pressing the `Escape` key. @@ -49,7 +52,7 @@ Normal mode is the default mode when you launch helix. You can return to it from | `T` | Find 'till previous char | `till_prev_char` | | `F` | Find previous char | `find_prev_char` | | `G` | Go to line number `` | `goto_line` | -| `Alt-.` | Repeat last motion (`f`, `t` or `m`) | `repeat_last_motion` | +| `Alt-.` | Repeat last motion (`f`, `t`, `m`, `[` or `]`) | `repeat_last_motion` | | `Home` | Move to the start of the line | `goto_line_start` | | `End` | Move to the end of the line | `goto_line_end` | | `Ctrl-b`, `PageUp` | Move page up | `page_up` | @@ -86,7 +89,7 @@ Normal mode is the default mode when you launch helix. You can return to it from | `"` `` | Select a register to yank to or paste from | `select_register` | | `>` | Indent selection | `indent` | | `<` | Unindent selection | `unindent` | -| `=` | Format selection (currently nonfunctional/disabled) (**LSP**) | `format_selections` | +| `=` | Format selection (**LSP**) | `format_selections` | | `d` | Delete selection | `delete_selection` | | `Alt-d` | Delete selection, without yanking | `delete_selection_noyank` | | `c` | Change selection (delete and enter insert mode) | `change_selection` | @@ -224,13 +227,13 @@ Jumps to various locations. | `.` | Go to last modification in current file | `goto_last_modification` | | `j` | Move down textual (instead of visual) line | `move_line_down` | | `k` | Move up textual (instead of visual) line | `move_line_up` | +| `w` | Show labels at each word and select the word that belongs to the entered labels | `goto_word` | #### 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 | | ----- | ----------- | ------- | @@ -279,7 +282,8 @@ This layer is a kludge of mappings, mostly pickers. | `F` | Open file picker at current working directory | `file_picker_in_current_directory` | | `b` | Open buffer picker | `buffer_picker` | | `j` | Open jumplist picker | `jumplist_picker` | -| `g` | Debug (experimental) | N/A | +| `g` | Open changed file picker | `changed_file_picker` | +| `G` | Debug (experimental) | N/A | | `k` | Show documentation for item under cursor in a [popup](#popup) (**LSP**) | `hover` | | `s` | Open document symbol picker (**LSP**) | `symbol_picker` | | `S` | Open workspace symbol picker (**LSP**) | `workspace_symbol_picker` | @@ -305,13 +309,31 @@ This layer is a kludge of mappings, mostly pickers. ##### Popup -Displays documentation for item under cursor. +Displays documentation for item under cursor. Remapping currently not supported. | Key | Description | | ---- | ----------- | | `Ctrl-u` | Scroll up | | `Ctrl-d` | Scroll down | +##### 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 | + +##### Signature-help Popup + +Displays the signature of the selected completion item. Remapping currently not supported. + +| Key | Description | +| ---- | ----------- | +| `Alt-p` | Previous signature | +| `Alt-n` | Next signature | + #### Unimpaired These mappings are in the style of [vim-unimpaired](https://github.com/tpope/vim-unimpaired). diff --git a/book/src/lang-support.md b/book/src/lang-support.md index 3f96673bc..aede33fa0 100644 --- a/book/src/lang-support.md +++ b/book/src/lang-support.md @@ -1,7 +1,7 @@ # Language Support The following languages and Language Servers are supported. To use -Language Server features, you must first [install][lsp-install-wiki] the +Language Server features, you must first [configure][lsp-config-wiki] the appropriate Language Server. You can check the language support in your installed helix version with `hx --health`. @@ -11,6 +11,6 @@ Languages][adding-languages] guide for more language configuration information. {{#include ./generated/lang-support.md}} -[lsp-install-wiki]: https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers +[lsp-config-wiki]: https://github.com/helix-editor/helix/wiki/Language-Server-Configurations [lang-config]: ./languages.md [adding-languages]: ./guides/adding_languages.md diff --git a/book/src/languages.md b/book/src/languages.md index dd93fec53..33ecbb92f 100644 --- a/book/src/languages.md +++ b/book/src/languages.md @@ -150,6 +150,8 @@ They have to be defined in the `[language-server]` table as described in the pre Different languages can use the same language server instance, e.g. `typescript-language-server` is used for javascript, jsx, tsx and typescript by default. +The definition order of language servers affects the order in the results list of code action menu. + In case multiple language servers are specified in the `language-servers` attribute of a `language`, it's often useful to only enable/disable certain language-server features for these language servers. diff --git a/book/src/package-managers.md b/book/src/package-managers.md new file mode 100644 index 000000000..3cfd31003 --- /dev/null +++ b/book/src/package-managers.md @@ -0,0 +1,150 @@ +## Package managers + +- [Linux](#linux) + - [Ubuntu](#ubuntu) + - [Fedora/RHEL](#fedorarhel) + - [Arch Linux extra](#arch-linux-extra) + - [NixOS](#nixos) + - [Flatpak](#flatpak) + - [Snap](#snap) + - [AppImage](#appimage) +- [macOS](#macos) + - [Homebrew Core](#homebrew-core) + - [MacPorts](#macports) +- [Windows](#windows) + - [Winget](#winget) + - [Scoop](#scoop) + - [Chocolatey](#chocolatey) + - [MSYS2](#msys2) + +[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions) + +## Linux + +The following third party repositories are available: + +### Ubuntu + +Add the `PPA` for Helix: + +```sh +sudo add-apt-repository ppa:maveonair/helix-editor +sudo apt update +sudo apt install helix +``` + +### Fedora/RHEL + +```sh +sudo dnf install helix +``` + +### Arch Linux extra + +Releases are available in the `extra` repository: + +```sh +sudo pacman -S helix +``` + +> 💡 When installed from the `extra` repository, run Helix with `helix` instead of `hx`. +> +> For example: +> ```sh +> helix --health +> ``` +> to check health + +Additionally, a [helix-git](https://aur.archlinux.org/packages/helix-git/) package is available +in the AUR, which builds the master branch. + +### NixOS + +Helix is available in [nixpkgs](https://github.com/nixos/nixpkgs) through the `helix` attribute, +the unstable channel usually carries the latest release. + +Helix is also available as a [flake](https://wiki.nixos.org/wiki/Flakes) in the project +root. Use `nix develop` to spin up a reproducible development shell. Outputs are +cached for each push to master using [Cachix](https://www.cachix.org/). The +flake is configured to automatically make use of this cache assuming the user +accepts the new settings on first use. + +If you are using a version of Nix without flakes enabled, +[install Cachix CLI](https://docs.cachix.org/installation) and use +`cachix use helix` to configure Nix to use cached outputs when possible. + +### Flatpak + +Helix is available on [Flathub](https://flathub.org/en-GB/apps/com.helix_editor.Helix): + +```sh +flatpak install flathub com.helix_editor.Helix +flatpak run com.helix_editor.Helix +``` + +### Snap + +Helix is available on [Snapcraft](https://snapcraft.io/helix) and can be installed with: + +```sh +snap install --classic helix +``` + +This will install Helix as both `/snap/bin/helix` and `/snap/bin/hx`, so make sure `/snap/bin` is in your `PATH`. + +### AppImage + +Install Helix using the Linux [AppImage](https://appimage.org/) format. +Download the official Helix AppImage from the [latest releases](https://github.com/helix-editor/helix/releases/latest) page. + +```sh +chmod +x helix-*.AppImage # change permission for executable mode +./helix-*.AppImage # run helix +``` + +## macOS + +### Homebrew Core + +```sh +brew install helix +``` + +### MacPorts + +```sh +port install helix +``` + +## Windows + +Install on Windows using [Winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/), [Scoop](https://scoop.sh/), [Chocolatey](https://chocolatey.org/) +or [MSYS2](https://msys2.org/). + +### Winget +Windows Package Manager winget command-line tool is by default available on Windows 11 and modern versions of Windows 10 as a part of the App Installer. +You can get [App Installer from the Microsoft Store](https://www.microsoft.com/p/app-installer/9nblggh4nns1#activetab=pivot:overviewtab). If it's already installed, make sure it is updated with the latest version. + +```sh +winget install Helix.Helix +``` + +### Scoop + +```sh +scoop install helix +``` + +### Chocolatey + +```sh +choco install helix +``` + +### MSYS2 + +For 64-bit Windows 8.1 or above: + +```sh +pacman -S mingw-w64-ucrt-x86_64-helix +``` diff --git a/book/src/registers.md b/book/src/registers.md new file mode 100644 index 000000000..2edf7e27a --- /dev/null +++ b/book/src/registers.md @@ -0,0 +1,54 @@ +## Registers + +- [User-defined registers](#user-defined-registers) +- [Default registers](#default-registers) +- [Special registers](#special-registers) + +In Helix, registers are storage locations for text and other data, such as the +result of a search. Registers can be used to cut, copy, and paste text, similar +to the clipboard in other text editors. Usage is similar to Vim, with `"` being +used to select a register. + +### User-defined registers + +Helix allows you to create your own named registers for storing text, for +example: + +- `"ay` - Yank the current selection to register `a`. +- `"op` - Paste the text in register `o` after the selection. + +If a register is selected before invoking a change or delete command, the selection will be stored in the register and the action will be carried out: + +- `"hc` - Store the selection in register `h` and then change it (delete and enter insert mode). +- `"md` - Store the selection in register `m` and delete it. + +### Default registers + +Commands that use registers, like yank (`y`), use a default register if none is specified. +These registers are used as defaults: + +| Register character | Contains | +| --- | --- | +| `/` | Last search | +| `:` | Last executed command | +| `"` | Last yanked text | +| `@` | Last recorded macro | + +### Special registers + +Some registers have special behavior when read from and written to. + +| Register character | When read | When written | +| --- | --- | --- | +| `_` | No values are returned | All values are discarded | +| `#` | Selection indices (first selection is `1`, second is `2`, etc.) | This register is not writable | +| `.` | Contents of the current selections | This register is not writable | +| `%` | Name of the current file | This register is not writable | +| `+` | Reads from the system clipboard | Joins and yanks to the system clipboard | +| `*` | Reads from the primary clipboard | Joins and yanks to the primary clipboard | + +When yanking multiple selections to the clipboard registers, the selections +are joined with newlines. Pasting from these registers will paste multiple +selections if the clipboard was last yanked to by the Helix session. Otherwise +the clipboard contents are pasted as one selection. + diff --git a/book/src/surround.md b/book/src/surround.md new file mode 100644 index 000000000..187d2876a --- /dev/null +++ b/book/src/surround.md @@ -0,0 +1,24 @@ +## Surround + +Helix includes built-in functionality similar to [vim-surround](https://github.com/tpope/vim-surround). +The keymappings have been inspired from [vim-sandwich](https://github.com/machakann/vim-sandwich): + +![Surround demo](https://user-images.githubusercontent.com/23398472/122865801-97073180-d344-11eb-8142-8f43809982c6.gif) + +| Key Sequence | Action | +| --------------------------------- | --------------------------------------- | +| `ms` (after selecting text) | Add surround characters to selection | +| `mr` | Replace the closest surround characters | +| `md` | Delete the closest surround characters | + +You can use counts to act on outer pairs. + +Surround can also act on multiple selections. For example, to change every occurrence of `(use)` to `[use]`: + +1. `%` to select the whole file +2. `s` to split the selections on a search term +3. Input `use` and hit Enter +4. `mr([` to replace the parentheses with square brackets + +Multiple characters are currently not supported, but planned for future release. + diff --git a/book/src/syntax-aware-motions.md b/book/src/syntax-aware-motions.md new file mode 100644 index 000000000..17f396fb4 --- /dev/null +++ b/book/src/syntax-aware-motions.md @@ -0,0 +1,66 @@ +## Moving the selection with syntax-aware motions + +`Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) allow you to move the +selection according to its location in the syntax tree. For example, many languages have the +following syntax for function calls: + +```js +func(arg1, arg2, arg3); +``` + +A function call might be parsed by tree-sitter into a tree like the following. + +```tsq +(call + function: (identifier) ; func + arguments: + (arguments ; (arg1, arg2, arg3) + (identifier) ; arg1 + (identifier) ; arg2 + (identifier))) ; arg3 +``` + +Use `:tree-sitter-subtree` to view the syntax tree of the primary selection. In +a more intuitive tree format: + +``` + ┌────┐ + │call│ + ┌─────┴────┴─────┐ + │ │ +┌─────▼────┐ ┌────▼────┐ +│identifier│ │arguments│ +│ "func" │ ┌────┴───┬─────┴───┐ +└──────────┘ │ │ │ + │ │ │ + ┌─────────▼┐ ┌────▼─────┐ ┌▼─────────┐ + │identifier│ │identifier│ │identifier│ + │ "arg1" │ │ "arg2" │ │ "arg3" │ + └──────────┘ └──────────┘ └──────────┘ +``` + +If you have a selection that wraps `arg1` (see the tree above), and you use +`Alt-n`, it will select the next sibling in the syntax tree: `arg2`. + +```js +// before +func([arg1], arg2, arg3) +// after +func(arg1, [arg2], arg3); +``` + +Similarly, `Alt-o` will expand the selection to the parent node, in this case, the +arguments node. + +```js +func[(arg1, arg2, arg3)]; +``` + +There is also some nuanced behavior that prevents you from getting stuck on a +node with no sibling. When using `Alt-p` with a selection on `arg1`, the previous +child node will be selected. In the event that `arg1` does not have a previous +sibling, the selection will move up the syntax tree and select the previous +element. As a result, using `Alt-p` with a selection on `arg1` will move the +selection to the "func" `identifier`. + +[lang-support]: ./lang-support.md diff --git a/book/src/textobjects.md b/book/src/textobjects.md new file mode 100644 index 000000000..541acab95 --- /dev/null +++ b/book/src/textobjects.md @@ -0,0 +1,47 @@ +## Selecting and manipulating text with textobjects + +In Helix, textobjects are a way to select, manipulate and operate on a piece of +text in a structured way. They allow you to refer to blocks of text based on +their structure or purpose, such as a word, sentence, paragraph, or even a +function or block of code. + +![Textobject demo](https://user-images.githubusercontent.com/23398472/124231131-81a4bb00-db2d-11eb-9d10-8e577ca7b177.gif) +![Textobject tree-sitter demo](https://user-images.githubusercontent.com/23398472/132537398-2a2e0a54-582b-44ab-a77f-eb818942203d.gif) + +- `ma` - Select around the object (`va` in Vim, `` in Kakoune) +- `mi` - Select inside the object (`vi` in Vim, `` in Kakoune) + +| Key after `mi` or `ma` | Textobject selected | +| --- | --- | +| `w` | Word | +| `W` | WORD | +| `p` | Paragraph | +| `(`, `[`, `'`, etc. | Specified surround pairs | +| `m` | The closest surround pair | +| `f` | Function | +| `t` | Type (or Class) | +| `a` | Argument/parameter | +| `c` | Comment | +| `T` | Test | +| `g` | Change | + +> 💡 `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.md) currently have the query file implemented. +Contributions are welcome! + +## Navigating using tree-sitter textobjects + +Navigating between functions, classes, parameters, and other elements is +possible using tree-sitter and textobject queries. For +example to move to the next function use `]f`, to move to previous +type use `[t`, and so on. + +![Tree-sitter-nav-demo](https://user-images.githubusercontent.com/23398472/152332550-7dfff043-36a2-4aec-b8f2-77c13eb56d6f.gif) + +For the full reference see the [unimpaired](./keymap.html#unimpaired) section of the key bind +documentation. + +> 💡 This feature relies on tree-sitter textobjects +> and requires the corresponding query file to work properly. + diff --git a/book/src/themes.md b/book/src/themes.md index 04d6a69b3..e3b95c0a7 100644 --- a/book/src/themes.md +++ b/book/src/themes.md @@ -36,13 +36,6 @@ For inspiration, you can find the default `theme.toml` user-submitted themes [here](https://github.com/helix-editor/helix/blob/master/runtime/themes). -### Using the linter - -Use the supplied linting tool to check for errors and missing scopes: - -```sh -cargo xtask themelint onedark # replace onedark with -``` ## The details of theme creation @@ -186,6 +179,7 @@ We use a similar set of scopes as - `parameter` - Function parameters - `other` - `member` - Fields of composite data types (e.g. structs, unions) + - `private` - Private fields that use a unique syntax (currently just ECMAScript-based languages) - `label` @@ -213,6 +207,7 @@ We use a similar set of scopes as - `function` - `builtin` - `method` + - `private` - Private methods that use a unique syntax (currently just ECMAScript-based languages) - `macro` - `special` (preprocessor in C) @@ -251,6 +246,7 @@ We use a similar set of scopes as - `gutter` - gutter indicator - `delta` - modifications - `moved` - renamed or moved files/changes + - `conflict` - merge conflicts - `gutter` - gutter indicator #### Interface @@ -314,6 +310,7 @@ These scopes are used for theming the editor interface: | `ui.virtual.inlay-hint.parameter` | Style for inlay hints of kind `parameter` (LSPs are not required to set a kind) | | `ui.virtual.inlay-hint.type` | Style for inlay hints of kind `type` (LSPs are not required to set a kind) | | `ui.virtual.wrap` | Soft-wrap indicator (see the [`editor.soft-wrap` config][editor-section]) | +| `ui.virtual.jump-label` | Style for virtual jump labels | | `ui.menu` | Code and command completion menus | | `ui.menu.selected` | Selected autocomplete item | | `ui.menu.scroll` | `fg` sets thumb color, `bg` sets track color of scrollbar | diff --git a/book/src/usage.md b/book/src/usage.md index e01482193..859cb6709 100644 --- a/book/src/usage.md +++ b/book/src/usage.md @@ -1,15 +1,5 @@ # Using Helix - -- [Registers](#registers) - - [User-defined registers](#user-defined-registers) - - [Special registers](#special-registers) -- [Surround](#surround) -- [Selecting and manipulating text with textobjects](#selecting-and-manipulating-text-with-textobjects) -- [Navigating using tree-sitter textobjects](#navigating-using-tree-sitter-textobjects) -- [Moving the selection with syntax-aware motions](#moving-the-selection-with-syntax-aware-motions) - - For a full interactive introduction to Helix, refer to the [tutor](https://github.com/helix-editor/helix/blob/master/runtime/tutor) which can be accessed via the command `hx --tutor` or `:tutor`. @@ -17,192 +7,3 @@ can be accessed via the command `hx --tutor` or `:tutor`. > 💡 Currently, not all functionality is fully documented, please refer to the > [key mappings](./keymap.md) list. -## Registers - -In Helix, registers are storage locations for text and other data, such as the -result of a search. Registers can be used to cut, copy, and paste text, similar -to the clipboard in other text editors. Usage is similar to Vim, with `"` being -used to select a register. - -### User-defined registers - -Helix allows you to create your own named registers for storing text, for -example: - -- `"ay` - Yank the current selection to register `a`. -- `"op` - Paste the text in register `o` after the selection. - -If a register is selected before invoking a change or delete command, the selection will be stored in the register and the action will be carried out: - -- `"hc` - Store the selection in register `h` and then change it (delete and enter insert mode). -- `"md` - Store the selection in register `m` and delete it. - -### Default registers - -Commands that use registers, like yank (`y`), use a default register if none is specified. -These registers are used as defaults: - -| Register character | Contains | -| --- | --- | -| `/` | Last search | -| `:` | Last executed command | -| `"` | Last yanked text | -| `@` | Last recorded macro | - -### Special registers - -Some registers have special behavior when read from and written to. - -| Register character | When read | When written | -| --- | --- | --- | -| `_` | No values are returned | All values are discarded | -| `#` | Selection indices (first selection is `1`, second is `2`, etc.) | This register is not writable | -| `.` | Contents of the current selections | This register is not writable | -| `%` | Name of the current file | This register is not writable | -| `+` | Reads from the system clipboard | Joins and yanks to the system clipboard | -| `*` | Reads from the primary clipboard | Joins and yanks to the primary clipboard | - -When yanking multiple selections to the clipboard registers, the selections -are joined with newlines. Pasting from these registers will paste multiple -selections if the clipboard was last yanked to by the Helix session. Otherwise -the clipboard contents are pasted as one selection. - -## Surround - -Helix includes built-in functionality similar to [vim-surround](https://github.com/tpope/vim-surround). -The keymappings have been inspired from [vim-sandwich](https://github.com/machakann/vim-sandwich): - -![Surround demo](https://user-images.githubusercontent.com/23398472/122865801-97073180-d344-11eb-8142-8f43809982c6.gif) - -| Key Sequence | Action | -| --------------------------------- | --------------------------------------- | -| `ms` (after selecting text) | Add surround characters to selection | -| `mr` | Replace the closest surround characters | -| `md` | Delete the closest surround characters | - -You can use counts to act on outer pairs. - -Surround can also act on multiple selections. For example, to change every occurrence of `(use)` to `[use]`: - -1. `%` to select the whole file -2. `s` to split the selections on a search term -3. Input `use` and hit Enter -4. `mr([` to replace the parentheses with square brackets - -Multiple characters are currently not supported, but planned for future release. - -## Selecting and manipulating text with textobjects - -In Helix, textobjects are a way to select, manipulate and operate on a piece of -text in a structured way. They allow you to refer to blocks of text based on -their structure or purpose, such as a word, sentence, paragraph, or even a -function or block of code. - -![Textobject demo](https://user-images.githubusercontent.com/23398472/124231131-81a4bb00-db2d-11eb-9d10-8e577ca7b177.gif) -![Textobject tree-sitter demo](https://user-images.githubusercontent.com/23398472/132537398-2a2e0a54-582b-44ab-a77f-eb818942203d.gif) - -- `ma` - Select around the object (`va` in Vim, `` in Kakoune) -- `mi` - Select inside the object (`vi` in Vim, `` in Kakoune) - -| Key after `mi` or `ma` | Textobject selected | -| --- | --- | -| `w` | Word | -| `W` | WORD | -| `p` | Paragraph | -| `(`, `[`, `'`, etc. | Specified surround pairs | -| `m` | The closest surround pair | -| `f` | Function | -| `t` | Type (or Class) | -| `a` | Argument/parameter | -| `c` | Comment | -| `T` | Test | -| `g` | Change | - -> 💡 `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. -Contributions are welcome! - -## Navigating using tree-sitter textobjects - -Navigating between functions, classes, parameters, and other elements is -possible using tree-sitter and textobject queries. For -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] - -For the full reference see the [unimpaired][unimpaired-keybinds] section of the key bind -documentation. - -> 💡 This feature relies on tree-sitter textobjects -> and requires the corresponding query file to work properly. - -## Moving the selection with syntax-aware motions - -`Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) allow you to move the -selection according to its location in the syntax tree. For example, many languages have the -following syntax for function calls: - -```js -func(arg1, arg2, arg3); -``` - -A function call might be parsed by tree-sitter into a tree like the following. - -```tsq -(call - function: (identifier) ; func - arguments: - (arguments ; (arg1, arg2, arg3) - (identifier) ; arg1 - (identifier) ; arg2 - (identifier))) ; arg3 -``` - -Use `:tree-sitter-subtree` to view the syntax tree of the primary selection. In -a more intuitive tree format: - -``` - ┌────┐ - │call│ - ┌─────┴────┴─────┐ - │ │ -┌─────▼────┐ ┌────▼────┐ -│identifier│ │arguments│ -│ "func" │ ┌────┴───┬─────┴───┐ -└──────────┘ │ │ │ - │ │ │ - ┌─────────▼┐ ┌────▼─────┐ ┌▼─────────┐ - │identifier│ │identifier│ │identifier│ - │ "arg1" │ │ "arg2" │ │ "arg3" │ - └──────────┘ └──────────┘ └──────────┘ -``` - -If you have a selection that wraps `arg1` (see the tree above), and you use -`Alt-n`, it will select the next sibling in the syntax tree: `arg2`. - -```js -// before -func([arg1], arg2, arg3) -// after -func(arg1, [arg2], arg3); -``` - -Similarly, `Alt-o` will expand the selection to the parent node, in this case, the -arguments node. - -```js -func[(arg1, arg2, arg3)]; -``` - -There is also some nuanced behavior that prevents you from getting stuck on a -node with no sibling. When using `Alt-p` with a selection on `arg1`, the previous -child node will be selected. In the event that `arg1` does not have a previous -sibling, the selection will move up the syntax tree and select the previous -element. As a result, using `Alt-p` with a selection on `arg1` will move the -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 diff --git a/contrib/Helix.appdata.xml b/contrib/Helix.appdata.xml index c455b242e..a46ef796b 100644 --- a/contrib/Helix.appdata.xml +++ b/contrib/Helix.appdata.xml @@ -6,27 +6,26 @@ Helix A post-modern text editor مُحَرِّرُ نُصُوصٍ سَابِقٌ لِعَهدِه + + Blaž Hrastnik +

Helix is a terminal-based text editor inspired by Kakoune / Neovim and written in Rust.

+

+ مُحَرِّرُ نُصُوصٍ يَعمَلُ فِي الطَّرَفِيَّة، مُستَلهَمٌ مِن Kakoune وَ Neovim وَمَكتُوبٌ بِلُغَةِ رَست البَرمَجِيَّة. +

  • Vim-like modal editing
  • +
  • تَحرِيرٌ وَضعِيٌّ شَبيهٌ بِـVim
  • Multiple selections
  • +
  • تَحدِيدَاتٌ لِلنَّصِ مُتَعَدِّدَة
  • Built-in language server support
  • +
  • دَعْمٌ مُدمَجٌ لِخَوادِمِ اللُّغَات
  • Smart, incremental syntax highlighting and code editing via tree-sitter
  • -
-
- -

- مُحَرِّرُ نُصُوصٍ يَعمَلُ فِي الطَّرَفِيَّة، مُستَلهَمٌ مِن Kakoune وَ Neovim وَمَكتُوبٌ بِلُغَةِ رَست البَرمَجِيَّة. -

-
    -
  • تَحرِيرٌ وَضعِيٌّ شَبيهٌ بِـVim
  • -
  • تَحدِيدَاتٌ لِلنَّصِ مُتَعَدِّدَة
  • -
  • دَعْمٌ مُدمَجٌ لِخَوادِمِ اللُّغَات
  • -
  • تَحرِيرُ التَّعلِيمَاتِ البَّرمَجِيَّةِ مَعَ تَمييزٍ لِلتَّركِيبِ النَّحُويِّ بِواسِطَةِ tree-sitter
  • +
  • تَحرِيرُ التَّعلِيمَاتِ البَّرمَجِيَّةِ مَعَ تَمييزٍ لِلتَّركِيبِ النَّحُويِّ بِواسِطَةِ tree-sitter
@@ -48,6 +47,9 @@ + + https://helix-editor.com/news/release-24-03-highlights/ + https://helix-editor.com/news/release-23-10-highlights/ @@ -71,9 +73,9 @@ - + keyboard - + Utility diff --git a/default.nix b/default.nix index 50e7e6819..d2c51ec3a 100644 --- a/default.nix +++ b/default.nix @@ -5,4 +5,4 @@ let sha256 = "sha256:1qc703yg0babixi6wshn5wm2kgl5y1drcswgszh4xxzbrwkk9sv7"; }; in - (import compat {src = ./.;}).defaultNix.default + (import compat {src = ./.;}).defaultNix diff --git a/docs/releases.md b/docs/releases.md index e39cfd910..2be14553a 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -31,7 +31,7 @@ being published. * 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 diff --git a/flake.nix b/flake.nix index e113d94b9..c230dc317 100644 --- a/flake.nix +++ b/flake.nix @@ -114,10 +114,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"; 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; @@ -183,7 +180,7 @@ shellHook = '' export HELIX_RUNTIME="$PWD/runtime" export RUST_BACKTRACE="1" - export RUSTFLAGS="${rustFlagsEnv}" + export RUSTFLAGS="''${RUSTFLAGS:-""} ${rustFlagsEnv}" ''; }; }) diff --git a/helix-core/Cargo.toml b/helix-core/Cargo.toml index 5e2dbd977..3d5d554fd 100644 --- a/helix-core/Cargo.toml +++ b/helix-core/Cargo.toml @@ -25,15 +25,14 @@ smartstring = "1.0.1" unicode-segmentation = "1.11" unicode-width = "0.1" unicode-general-category = "0.6" -# slab = "0.4.2" -slotmap = "1.0" +slotmap.workspace = true tree-sitter.workspace = true once_cell = "1.19" arc-swap = "1" regex = "1" -bitflags = "2.4" +bitflags = "2.6" ahash = "0.8.11" -hashbrown = { version = "0.14.3", features = ["raw"] } +hashbrown = { version = "0.14.5", features = ["raw"] } dunce = "1.0" log = "0.4" @@ -56,4 +55,4 @@ globset = "0.4.14" [dev-dependencies] quickcheck = { version = "1", default-features = false } -indoc = "2.0.4" +indoc = "2.0.5" diff --git a/helix-core/src/diagnostic.rs b/helix-core/src/diagnostic.rs index 52d77a9aa..d41119d38 100644 --- a/helix-core/src/diagnostic.rs +++ b/helix-core/src/diagnostic.rs @@ -1,4 +1,6 @@ //! LSP diagnostic utility types. +use std::fmt; + use serde::{Deserialize, Serialize}; /// Describes the severity level of a [`Diagnostic`]. @@ -47,8 +49,25 @@ pub struct Diagnostic { pub message: String, pub severity: Option, pub code: Option, - pub language_server_id: usize, + pub provider: DiagnosticProvider, pub tags: Vec, pub source: Option, pub data: Option, } + +// TODO turn this into an enum + feature flag when lsp becomes optional +pub type DiagnosticProvider = LanguageServerId; + +// while I would prefer having this in helix-lsp that necessitates a bunch of +// conversions I would rather not add. I think its fine since this just a very +// trivial newtype wrapper and we would need something similar once we define +// completions in core +slotmap::new_key_type! { + pub struct LanguageServerId; +} + +impl fmt::Display for LanguageServerId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.0) + } +} diff --git a/helix-core/src/doc_formatter.rs b/helix-core/src/doc_formatter.rs index c7dc9081f..cbe2da3b6 100644 --- a/helix-core/src/doc_formatter.rs +++ b/helix-core/src/doc_formatter.rs @@ -116,7 +116,7 @@ impl Default for TextFormat { #[derive(Debug)] pub struct DocumentFormatter<'t> { text_fmt: &'t TextFormat, - annotations: &'t TextAnnotations, + annotations: &'t TextAnnotations<'t>, /// The visual position at the end of the last yielded word boundary visual_pos: Position, diff --git a/helix-core/src/doc_formatter/test.rs b/helix-core/src/doc_formatter/test.rs index ac8918bb7..d2b6ddc74 100644 --- a/helix-core/src/doc_formatter/test.rs +++ b/helix-core/src/doc_formatter/test.rs @@ -1,5 +1,3 @@ -use std::rc::Rc; - use crate::doc_formatter::{DocumentFormatter, TextFormat}; use crate::text_annotations::{InlineAnnotation, Overlay, TextAnnotations}; @@ -105,7 +103,7 @@ fn overlay_text(text: &str, char_pos: usize, softwrap: bool, overlays: &[Overlay DocumentFormatter::new_at_prev_checkpoint( text.into(), &TextFormat::new_test(softwrap), - TextAnnotations::default().add_overlay(overlays.into(), None), + TextAnnotations::default().add_overlay(overlays, None), char_pos, ) .0 @@ -142,7 +140,7 @@ fn annotate_text(text: &str, softwrap: bool, annotations: &[InlineAnnotation]) - DocumentFormatter::new_at_prev_checkpoint( text.into(), &TextFormat::new_test(softwrap), - TextAnnotations::default().add_inline_annotations(annotations.into(), None), + TextAnnotations::default().add_inline_annotations(annotations, None), 0, ) .0 @@ -164,15 +162,24 @@ fn annotation() { "foo foo foo foo \n.foo foo foo foo \n.foo foo foo " ); } + #[test] fn annotation_and_overlay() { + let annotations = [InlineAnnotation { + char_idx: 0, + text: "fooo".into(), + }]; + let overlay = [Overlay { + char_idx: 0, + grapheme: "\t".into(), + }]; assert_eq!( DocumentFormatter::new_at_prev_checkpoint( "bbar".into(), &TextFormat::new_test(false), TextAnnotations::default() - .add_inline_annotations(Rc::new([InlineAnnotation::new(0, "fooo")]), None) - .add_overlay(Rc::new([Overlay::new(0, "\t")]), None), + .add_inline_annotations(annotations.as_slice(), None) + .add_overlay(overlay.as_slice(), None), 0, ) .0 diff --git a/helix-core/src/graphemes.rs b/helix-core/src/graphemes.rs index d9e5e0224..a02d6e4dd 100644 --- a/helix-core/src/graphemes.rs +++ b/helix-core/src/graphemes.rs @@ -278,23 +278,6 @@ pub fn ensure_grapheme_boundary_prev(slice: RopeSlice, char_idx: usize) -> usize } } -/// Returns the passed byte index if it's already a grapheme boundary, -/// or the next grapheme boundary byte index if not. -#[must_use] -#[inline] -pub fn ensure_grapheme_boundary_next_byte(slice: RopeSlice, byte_idx: usize) -> usize { - if byte_idx == 0 { - byte_idx - } else { - // TODO: optimize so we're not constructing grapheme cursor twice - if is_grapheme_boundary_byte(slice, byte_idx) { - byte_idx - } else { - next_grapheme_boundary_byte(slice, byte_idx) - } - } -} - /// Returns whether the given char position is a grapheme boundary. #[must_use] pub fn is_grapheme_boundary(slice: RopeSlice, char_idx: usize) -> bool { @@ -425,6 +408,85 @@ impl<'a> Iterator for RopeGraphemes<'a> { } } +/// An iterator over the graphemes of a `RopeSlice` in reverse. +#[derive(Clone)] +pub struct RevRopeGraphemes<'a> { + text: RopeSlice<'a>, + chunks: Chunks<'a>, + cur_chunk: &'a str, + cur_chunk_start: usize, + cursor: GraphemeCursor, +} + +impl<'a> fmt::Debug for RevRopeGraphemes<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RevRopeGraphemes") + .field("text", &self.text) + .field("chunks", &self.chunks) + .field("cur_chunk", &self.cur_chunk) + .field("cur_chunk_start", &self.cur_chunk_start) + // .field("cursor", &self.cursor) + .finish() + } +} + +impl<'a> RevRopeGraphemes<'a> { + #[must_use] + pub fn new(slice: RopeSlice) -> RevRopeGraphemes { + let (mut chunks, mut cur_chunk_start, _, _) = slice.chunks_at_byte(slice.len_bytes()); + chunks.reverse(); + let first_chunk = chunks.next().unwrap_or(""); + cur_chunk_start -= first_chunk.len(); + RevRopeGraphemes { + text: slice, + chunks, + cur_chunk: first_chunk, + cur_chunk_start, + cursor: GraphemeCursor::new(slice.len_bytes(), slice.len_bytes(), true), + } + } +} + +impl<'a> Iterator for RevRopeGraphemes<'a> { + type Item = RopeSlice<'a>; + + fn next(&mut self) -> Option> { + let a = self.cursor.cur_cursor(); + let b; + loop { + match self + .cursor + .prev_boundary(self.cur_chunk, self.cur_chunk_start) + { + Ok(None) => { + return None; + } + Ok(Some(n)) => { + b = n; + break; + } + Err(GraphemeIncomplete::PrevChunk) => { + self.cur_chunk = self.chunks.next().unwrap_or(""); + self.cur_chunk_start -= self.cur_chunk.len(); + } + Err(GraphemeIncomplete::PreContext(idx)) => { + let (chunk, byte_idx, _, _) = self.text.chunk_at_byte(idx.saturating_sub(1)); + self.cursor.provide_context(chunk, byte_idx); + } + _ => unreachable!(), + } + } + + if a >= self.cur_chunk_start + self.cur_chunk.len() { + Some(self.text.byte_slice(b..a)) + } else { + let a2 = a - self.cur_chunk_start; + let b2 = b - self.cur_chunk_start; + Some((&self.cur_chunk[b2..a2]).into()) + } + } +} + /// A highly compressed Cow<'a, str> that holds /// atmost u31::MAX bytes and is readonly pub struct GraphemeStr<'a> { diff --git a/helix-core/src/increment/date_time.rs b/helix-core/src/increment/date_time.rs index 2980bb58b..04cff6b47 100644 --- a/helix-core/src/increment/date_time.rs +++ b/helix-core/src/increment/date_time.rs @@ -27,7 +27,7 @@ pub fn increment(selected_text: &str, amount: i64) -> Option { let date_time = NaiveDateTime::parse_from_str(date_time, format.fmt).ok()?; Some( date_time - .checked_add_signed(Duration::minutes(amount))? + .checked_add_signed(Duration::try_minutes(amount)?)? .format(format.fmt) .to_string(), ) @@ -35,14 +35,15 @@ pub fn increment(selected_text: &str, amount: i64) -> Option { (true, false) => { let date = NaiveDate::parse_from_str(date_time, format.fmt).ok()?; Some( - date.checked_add_signed(Duration::days(amount))? + date.checked_add_signed(Duration::try_days(amount)?)? .format(format.fmt) .to_string(), ) } (false, true) => { let time = NaiveTime::parse_from_str(date_time, format.fmt).ok()?; - let (adjusted_time, _) = time.overflowing_add_signed(Duration::minutes(amount)); + let (adjusted_time, _) = + time.overflowing_add_signed(Duration::try_minutes(amount)?); Some(adjusted_time.format(format.fmt).to_string()) } (false, false) => None, diff --git a/helix-core/src/indent.rs b/helix-core/src/indent.rs index 2a0a3876c..fd2b6c959 100644 --- a/helix-core/src/indent.rs +++ b/helix-core/src/indent.rs @@ -247,41 +247,18 @@ fn add_indent_level( } } -/// Computes for node and all ancestors whether they are the first node on their line. -/// The first entry in the return value represents the root node, the last one the node itself -fn get_first_in_line(mut node: Node, new_line_byte_pos: Option) -> Vec { - let mut first_in_line = Vec::new(); - loop { - if let Some(prev) = node.prev_sibling() { - // If we insert a new line, the first node at/after the cursor is considered to be the first in its line - let first = prev.end_position().row != node.start_position().row - || new_line_byte_pos.map_or(false, |byte_pos| { - node.start_byte() >= byte_pos && prev.start_byte() < byte_pos - }); - first_in_line.push(Some(first)); - } else { - // Nodes that have no previous siblings are first in their line if and only if their parent is - // (which we don't know yet) - first_in_line.push(None); - } - if let Some(parent) = node.parent() { - node = parent; - } else { - break; - } - } - - let mut result = Vec::with_capacity(first_in_line.len()); - let mut parent_is_first = true; // The root node is by definition the first node in its line - for first in first_in_line.into_iter().rev() { - if let Some(first) = first { - result.push(first); - parent_is_first = first; - } else { - result.push(parent_is_first); +/// Return true if only whitespace comes before the node on its line. +/// If given, new_line_byte_pos is treated the same way as any existing newline. +fn is_first_in_line(node: Node, text: RopeSlice, new_line_byte_pos: Option) -> bool { + let mut line_start_byte_pos = text.line_to_byte(node.start_position().row); + if let Some(pos) = new_line_byte_pos { + if line_start_byte_pos < pos && pos <= node.start_byte() { + line_start_byte_pos = pos; } } - result + text.byte_slice(line_start_byte_pos..node.start_byte()) + .chars() + .all(|c| c.is_whitespace()) } /// The total indent for some line of code. @@ -763,7 +740,7 @@ fn init_indent_query<'a, 'b>( crate::syntax::PARSER.with(|ts_parser| { let mut ts_parser = ts_parser.borrow_mut(); - let mut cursor = ts_parser.cursors.pop().unwrap_or_else(QueryCursor::new); + let mut cursor = ts_parser.cursors.pop().unwrap_or_default(); let query_result = query_indents( query, syntax, @@ -852,7 +829,6 @@ pub fn treesitter_indent_for_pos<'a>( byte_pos, new_line_byte_pos, )?; - let mut first_in_line = get_first_in_line(node, new_line.then_some(byte_pos)); let mut result = Indentation::default(); // We always keep track of all the indent changes on one line, in order to only indent once @@ -861,9 +837,7 @@ pub fn treesitter_indent_for_pos<'a>( let mut indent_for_line_below = Indentation::default(); loop { - // This can safely be unwrapped because `first_in_line` contains - // one entry for each ancestor of the node (which is what we iterate over) - let is_first = *first_in_line.last().unwrap(); + let is_first = is_first_in_line(node, text, new_line_byte_pos); // Apply all indent definitions for this node. // Since we only iterate over each node once, we can remove the @@ -906,7 +880,6 @@ pub fn treesitter_indent_for_pos<'a>( } node = parent; - first_in_line.pop(); } else { // Only add the indentation for the line below if that line // is not after the line that the indentation is calculated for. diff --git a/helix-core/src/match_brackets.rs b/helix-core/src/match_brackets.rs index b8bcc28ca..7520d3e46 100644 --- a/helix-core/src/match_brackets.rs +++ b/helix-core/src/match_brackets.rs @@ -9,16 +9,34 @@ use crate::Syntax; const MAX_PLAINTEXT_SCAN: usize = 10000; const MATCH_LIMIT: usize = 16; -// Limit matching pairs to only ( ) { } [ ] < > ' ' " " -const PAIRS: &[(char, char)] = &[ +pub const BRACKETS: [(char, char); 9] = [ ('(', ')'), ('{', '}'), ('[', ']'), ('<', '>'), - ('\'', '\''), - ('\"', '\"'), + ('‘', '’'), + ('“', '”'), + ('«', '»'), + ('「', '」'), + ('(', ')'), ]; +// The difference between BRACKETS and PAIRS is that we can find matching +// BRACKETS in a plain text file, but we can't do the same for PAIRs. +// PAIRS also contains all BRACKETS. +pub const PAIRS: [(char, char); BRACKETS.len() + 3] = { + let mut pairs = [(' ', ' '); BRACKETS.len() + 3]; + let mut idx = 0; + while idx < BRACKETS.len() { + pairs[idx] = BRACKETS[idx]; + idx += 1; + } + pairs[idx] = ('"', '"'); + pairs[idx + 1] = ('\'', '\''); + pairs[idx + 2] = ('`', '`'); + pairs +}; + /// Returns the position of the matching bracket under cursor. /// /// If the cursor is on the opening bracket, the position of @@ -30,7 +48,7 @@ const PAIRS: &[(char, char)] = &[ /// If no matching bracket is found, `None` is returned. #[must_use] pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option { - if pos >= doc.len_chars() || !is_valid_bracket(doc.char(pos)) { + if pos >= doc.len_chars() || !is_valid_pair(doc.char(pos)) { return None; } find_pair(syntax, doc, pos, false) @@ -59,60 +77,64 @@ fn find_pair( ) -> Option { let pos = doc.char_to_byte(pos_); - let root = syntax.tree_for_byte_range(pos, pos + 1).root_node(); - let mut node = root.descendant_for_byte_range(pos, pos + 1)?; + let root = syntax.tree_for_byte_range(pos, pos).root_node(); + let mut node = root.descendant_for_byte_range(pos, pos)?; loop { - if node.is_named() { - let (start_byte, end_byte) = surrounding_bytes(doc, &node)?; - let (start_char, end_char) = (doc.byte_to_char(start_byte), doc.byte_to_char(end_byte)); - - if is_valid_pair(doc, start_char, end_char) { - if end_byte == pos { - return Some(start_char); - } - - // We return the end char if the cursor is either on the start char - // or at some arbitrary position between start and end char. - if traverse_parents || start_byte == pos { - return Some(end_char); + if node.is_named() && node.child_count() >= 2 { + let open = node.child(0).unwrap(); + let close = node.child(node.child_count() - 1).unwrap(); + + if let (Some((start_pos, open)), Some((end_pos, close))) = + (as_char(doc, &open), as_char(doc, &close)) + { + if PAIRS.contains(&(open, close)) { + if end_pos == pos_ { + return Some(start_pos); + } + + // We return the end char if the cursor is either on the start char + // or at some arbitrary position between start and end char. + if traverse_parents || start_pos == pos_ { + return Some(end_pos); + } } } } // this node itselt wasn't a pair but maybe its siblings are - // check if we are *on* the pair (special cased so we don't look - // at the current node twice and to jump to the start on that case) - if let Some(open) = as_close_pair(doc, &node) { - if let Some(pair_start) = find_pair_end(doc, node.prev_sibling(), open, Backward) { + if let Some((start_char, end_char)) = as_close_pair(doc, &node) { + if let Some(pair_start) = + find_pair_end(doc, node.prev_sibling(), start_char, end_char, Backward) + { return Some(pair_start); } } - - if !traverse_parents { - // check if we are *on* the opening pair (special cased here as - // an opptimization since we only care about bracket on the cursor - // here) - if let Some(close) = as_open_pair(doc, &node) { - if let Some(pair_end) = find_pair_end(doc, node.next_sibling(), close, Forward) { - return Some(pair_end); - } - } - if node.is_named() { - break; + if let Some((start_char, end_char)) = as_open_pair(doc, &node) { + if let Some(pair_end) = + find_pair_end(doc, node.next_sibling(), start_char, end_char, Forward) + { + return Some(pair_end); } } - for close in - iter::successors(node.next_sibling(), |node| node.next_sibling()).take(MATCH_LIMIT) - { - let Some(open) = as_close_pair(doc, &close) else { - continue; - }; - if find_pair_end(doc, Some(node), open, Backward).is_some() { - return doc.try_byte_to_char(close.start_byte()).ok(); + if traverse_parents { + for sibling in + iter::successors(node.next_sibling(), |node| node.next_sibling()).take(MATCH_LIMIT) + { + let Some((start_char, end_char)) = as_close_pair(doc, &sibling) else { + continue; + }; + if find_pair_end(doc, sibling.prev_sibling(), start_char, end_char, Backward) + .is_some() + { + return doc.try_byte_to_char(sibling.start_byte()).ok(); + } } + } else if node.is_named() { + break; } + let Some(parent) = node.parent() else { break; }; @@ -140,14 +162,22 @@ fn find_pair( /// If no matching bracket is found, `None` is returned. #[must_use] pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Option { - // Don't do anything when the cursor is not on top of a bracket. let bracket = doc.get_char(cursor_pos)?; + let matching_bracket = { + let pair = get_pair(bracket); + if pair.0 == bracket { + pair.1 + } else { + pair.0 + } + }; + // Don't do anything when the cursor is not on top of a bracket. if !is_valid_bracket(bracket) { return None; } // Determine the direction of the matching. - let is_fwd = is_forward_bracket(bracket); + let is_fwd = is_open_bracket(bracket); let chars_iter = if is_fwd { doc.chars_at(cursor_pos + 1) } else { @@ -159,19 +189,7 @@ pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Opt for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() { if candidate == bracket { open_cnt += 1; - } else if is_valid_pair( - doc, - if is_fwd { - cursor_pos - } else { - cursor_pos - i - 1 - }, - if is_fwd { - cursor_pos + i + 1 - } else { - cursor_pos - }, - ) { + } else if candidate == matching_bracket { // Return when all pending brackets have been closed. if open_cnt == 1 { return Some(if is_fwd { @@ -187,37 +205,55 @@ pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Opt None } -fn is_valid_bracket(c: char) -> bool { - PAIRS.iter().any(|(l, r)| *l == c || *r == c) +/// Returns the open and closing chars pair. If not found in +/// [`BRACKETS`] returns (ch, ch). +/// +/// ``` +/// use helix_core::match_brackets::get_pair; +/// +/// assert_eq!(get_pair('['), ('[', ']')); +/// assert_eq!(get_pair('}'), ('{', '}')); +/// assert_eq!(get_pair('"'), ('"', '"')); +/// ``` +pub fn get_pair(ch: char) -> (char, char) { + PAIRS + .iter() + .find(|(open, close)| *open == ch || *close == ch) + .copied() + .unwrap_or((ch, ch)) } -fn is_forward_bracket(c: char) -> bool { - PAIRS.iter().any(|(l, _)| *l == c) +pub fn is_open_bracket(ch: char) -> bool { + BRACKETS.iter().any(|(l, _)| *l == ch) } -fn is_valid_pair(doc: RopeSlice, start_char: usize, end_char: usize) -> bool { - PAIRS.contains(&(doc.char(start_char), doc.char(end_char))) +pub fn is_close_bracket(ch: char) -> bool { + BRACKETS.iter().any(|(_, r)| *r == ch) } -fn surrounding_bytes(doc: RopeSlice, node: &Node) -> Option<(usize, usize)> { - let len = doc.len_bytes(); +pub fn is_valid_bracket(ch: char) -> bool { + BRACKETS.iter().any(|(l, r)| *l == ch || *r == ch) +} - let start_byte = node.start_byte(); - let end_byte = node.end_byte().saturating_sub(1); +pub fn is_open_pair(ch: char) -> bool { + PAIRS.iter().any(|(l, _)| *l == ch) +} - if start_byte >= len || end_byte >= len { - return None; - } +pub fn is_close_pair(ch: char) -> bool { + PAIRS.iter().any(|(_, r)| *r == ch) +} - Some((start_byte, end_byte)) +pub fn is_valid_pair(ch: char) -> bool { + PAIRS.iter().any(|(l, r)| *l == ch || *r == ch) } /// Tests if this node is a pair close char and returns the expected open char -fn as_close_pair(doc: RopeSlice, node: &Node) -> Option { +/// and close char contained in this node +fn as_close_pair(doc: RopeSlice, node: &Node) -> Option<(char, char)> { let close = as_char(doc, node)?.1; PAIRS .iter() - .find_map(|&(open, close_)| (close_ == close).then_some(open)) + .find_map(|&(open, close_)| (close_ == close).then_some((close, open))) } /// Checks if `node` or its siblings (at most MATCH_LIMIT nodes) is the specified closing char @@ -228,6 +264,7 @@ fn as_close_pair(doc: RopeSlice, node: &Node) -> Option { fn find_pair_end( doc: RopeSlice, node: Option, + start_char: char, end_char: char, direction: Direction, ) -> Option { @@ -235,20 +272,30 @@ fn find_pair_end( Forward => Node::next_sibling, Backward => Node::prev_sibling, }; + let mut depth = 0; iter::successors(node, advance) .take(MATCH_LIMIT) .find_map(|node| { let (pos, c) = as_char(doc, &node)?; - (end_char == c).then_some(pos) + if c == end_char { + if depth == 0 { + return Some(pos); + } + depth -= 1; + } else if c == start_char { + depth += 1; + } + None }) } -/// Tests if this node is a pair close char and returns the expected open char -fn as_open_pair(doc: RopeSlice, node: &Node) -> Option { +/// Tests if this node is a pair open char and returns the expected close char +/// and open char contained in this node +fn as_open_pair(doc: RopeSlice, node: &Node) -> Option<(char, char)> { let open = as_char(doc, node)?.1; PAIRS .iter() - .find_map(|&(open_, close)| (open_ == open).then_some(close)) + .find_map(|&(open_, close)| (open_ == open).then_some((open, close))) } /// If node is a single char return it (and its char position) diff --git a/helix-core/src/object.rs b/helix-core/src/object.rs index d2d4fe70a..17a393caf 100644 --- a/helix-core/src/object.rs +++ b/helix-core/src/object.rs @@ -1,76 +1,137 @@ -use crate::{Range, RopeSlice, Selection, Syntax}; -use tree_sitter::Node; +use crate::{movement::Direction, syntax::TreeCursor, Range, RopeSlice, Selection, Syntax}; pub fn expand_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { - select_node_impl(syntax, text, selection, |mut node, from, to| { - while node.start_byte() == from && node.end_byte() == to { - node = node.parent()?; + let cursor = &mut syntax.walk(); + + selection.transform(|range| { + let from = text.char_to_byte(range.from()); + let to = text.char_to_byte(range.to()); + + let byte_range = from..to; + cursor.reset_to_byte_range(from, to); + + while cursor.node().byte_range() == byte_range { + if !cursor.goto_parent() { + break; + } } - Some(node) + + let node = cursor.node(); + let from = text.byte_to_char(node.start_byte()); + let to = text.byte_to_char(node.end_byte()); + + Range::new(to, from).with_direction(range.direction()) }) } pub fn shrink_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { - select_node_impl(syntax, text, selection, |descendant, _from, _to| { - descendant.child(0).or(Some(descendant)) - }) + select_node_impl( + syntax, + text, + selection, + |cursor| { + cursor.goto_first_child(); + }, + None, + ) } -pub fn select_sibling( - syntax: &Syntax, - text: RopeSlice, - selection: Selection, - sibling_fn: &F, -) -> Selection -where - F: Fn(Node) -> Option, -{ - select_node_impl(syntax, text, selection, |descendant, _from, _to| { - find_sibling_recursive(descendant, sibling_fn) +pub fn select_next_sibling(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { + select_node_impl( + syntax, + text, + selection, + |cursor| { + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + break; + } + } + }, + Some(Direction::Forward), + ) +} + +pub fn select_all_siblings(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { + selection.transform_iter(|range| { + let mut cursor = syntax.walk(); + let (from, to) = range.into_byte_range(text); + cursor.reset_to_byte_range(from, to); + + if !cursor.goto_parent_with(|parent| parent.child_count() > 1) { + return vec![range].into_iter(); + } + + select_children(&mut cursor, text, range).into_iter() }) } -fn find_sibling_recursive(node: Node, sibling_fn: F) -> Option -where - F: Fn(Node) -> Option, -{ - sibling_fn(node).or_else(|| { - node.parent() - .and_then(|node| find_sibling_recursive(node, sibling_fn)) +pub fn select_all_children(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { + selection.transform_iter(|range| { + let mut cursor = syntax.walk(); + let (from, to) = range.into_byte_range(text); + cursor.reset_to_byte_range(from, to); + select_children(&mut cursor, text, range).into_iter() }) } +fn select_children<'n>( + cursor: &'n mut TreeCursor<'n>, + text: RopeSlice, + range: Range, +) -> Vec { + let children = cursor + .named_children() + .map(|child| Range::from_node(child, text, range.direction())) + .collect::>(); + + if !children.is_empty() { + children + } else { + vec![range] + } +} + +pub fn select_prev_sibling(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { + select_node_impl( + syntax, + text, + selection, + |cursor| { + while !cursor.goto_prev_sibling() { + if !cursor.goto_parent() { + break; + } + } + }, + Some(Direction::Backward), + ) +} + fn select_node_impl( syntax: &Syntax, text: RopeSlice, selection: Selection, - select_fn: F, + motion: F, + direction: Option, ) -> Selection where - F: Fn(Node, usize, usize) -> Option, + F: Fn(&mut TreeCursor), { - let tree = syntax.tree(); + let cursor = &mut syntax.walk(); selection.transform(|range| { let from = text.char_to_byte(range.from()); let to = text.char_to_byte(range.to()); - let node = match tree - .root_node() - .descendant_for_byte_range(from, to) - .and_then(|node| select_fn(node, from, to)) - { - Some(node) => node, - None => return range, - }; + cursor.reset_to_byte_range(from, to); + motion(cursor); + + let node = cursor.node(); let from = text.byte_to_char(node.start_byte()); let to = text.byte_to_char(node.end_byte()); - if range.head < range.anchor { - Range::new(to, from) - } else { - Range::new(from, to) - } + Range::new(from, to).with_direction(direction.unwrap_or_else(|| range.direction())) }) } diff --git a/helix-core/src/selection.rs b/helix-core/src/selection.rs index bd252deb9..8995da8f9 100644 --- a/helix-core/src/selection.rs +++ b/helix-core/src/selection.rs @@ -13,7 +13,8 @@ use crate::{ }; 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. /// @@ -73,6 +74,12 @@ impl Range { Self::new(head, head) } + pub fn from_node(node: Node, text: RopeSlice, direction: Direction) -> Self { + let from = text.byte_to_char(node.start_byte()); + let to = text.byte_to_char(node.end_byte()); + Range::new(from, to).with_direction(direction) + } + /// Start of the range. #[inline] #[must_use] @@ -115,7 +122,7 @@ impl Range { } /// `Direction::Backward` when head < anchor. - /// `Direction::Backward` otherwise. + /// `Direction::Forward` otherwise. #[inline] #[must_use] pub fn direction(&self) -> Direction { @@ -376,6 +383,12 @@ impl Range { let second = graphemes.next(); first.is_some() && second.is_none() } + + /// Converts this char range into an in order byte range, discarding + /// direction. + pub fn into_byte_range(&self, text: RopeSlice) -> (usize, usize) { + (text.char_to_byte(self.from()), text.char_to_byte(self.to())) + } } impl From<(usize, usize)> for Range { @@ -490,6 +503,16 @@ impl Selection { &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 } @@ -705,6 +728,42 @@ impl IntoIterator for Selection { } } +impl From for Selection { + fn from(range: Range) -> Self { + Self { + ranges: smallvec![range], + primary_index: 0, + } + } +} + +pub struct LineRangeIter<'a> { + ranges: iter::Peekable>, + text: RopeSlice<'a>, +} + +impl<'a> Iterator for LineRangeIter<'a> { + type Item = (usize, usize); + + fn next(&mut self) -> Option { + 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( @@ -774,7 +833,9 @@ pub fn split_on_newline(text: RopeSlice, selection: &Selection) -> Selection { let mut start = sel_start; for line in sel.slice(text).lines() { - let Some(line_ending) = get_line_ending(&line) else { break }; + let Some(line_ending) = get_line_ending(&line) else { + break; + }; let line_end = start + line.len_chars(); // TODO: retain range direction result.push(Range::new(start, line_end - line_ending.len_chars())); @@ -1141,6 +1202,32 @@ mod test { 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::>(), + ); + } + #[test] fn test_cursor() { let r = Rope::from_str("\r\nHi\r\nthere!"); diff --git a/helix-core/src/surround.rs b/helix-core/src/surround.rs index 513f87493..e45346c92 100644 --- a/helix-core/src/surround.rs +++ b/helix-core/src/surround.rs @@ -1,18 +1,16 @@ use std::fmt::Display; -use crate::{movement::Direction, search, Range, Selection}; +use crate::{ + graphemes::next_grapheme_boundary, + match_brackets::{ + find_matching_bracket, find_matching_bracket_fuzzy, get_pair, is_close_bracket, + is_open_bracket, + }, + movement::Direction, + search, Range, Selection, Syntax, +}; use ropey::RopeSlice; -pub const PAIRS: &[(char, char)] = &[ - ('(', ')'), - ('[', ']'), - ('{', '}'), - ('<', '>'), - ('«', '»'), - ('「', '」'), - ('(', ')'), -]; - #[derive(Debug, PartialEq, Eq)] pub enum Error { PairNotFound, @@ -34,32 +32,68 @@ impl Display for Error { type Result = std::result::Result; -/// Given any char in [PAIRS], return the open and closing chars. If not found in -/// [PAIRS] return (ch, ch). +/// Finds the position of surround pairs of any [`crate::match_brackets::PAIRS`] +/// using tree-sitter when possible. /// -/// ``` -/// use helix_core::surround::get_pair; +/// # Returns /// -/// assert_eq!(get_pair('['), ('[', ']')); -/// assert_eq!(get_pair('}'), ('{', '}')); -/// assert_eq!(get_pair('"'), ('"', '"')); -/// ``` -pub fn get_pair(ch: char) -> (char, char) { - PAIRS - .iter() - .find(|(open, close)| *open == ch || *close == ch) - .copied() - .unwrap_or((ch, ch)) +/// Tuple `(anchor, head)`, meaning it is not always ordered. +pub fn find_nth_closest_pairs_pos( + syntax: Option<&Syntax>, + text: RopeSlice, + range: Range, + skip: usize, +) -> Result<(usize, usize)> { + match syntax { + Some(syntax) => find_nth_closest_pairs_ts(syntax, text, range, skip), + None => find_nth_closest_pairs_plain(text, range, skip), + } } -pub fn find_nth_closest_pairs_pos( +fn find_nth_closest_pairs_ts( + syntax: &Syntax, text: RopeSlice, range: Range, mut skip: usize, ) -> Result<(usize, usize)> { - let is_open_pair = |ch| PAIRS.iter().any(|(open, _)| *open == ch); - let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch); + let mut opening = range.from(); + // We want to expand the selection if we are already on the found pair, + // otherwise we would need to subtract "-1" from "range.to()". + let mut closing = range.to(); + + while skip > 0 { + closing = find_matching_bracket_fuzzy(syntax, text, closing).ok_or(Error::PairNotFound)?; + opening = find_matching_bracket(syntax, text, closing).ok_or(Error::PairNotFound)?; + // If we're already on a closing bracket "find_matching_bracket_fuzzy" will return + // the position of the opening bracket. + if closing < opening { + (opening, closing) = (closing, opening); + } + // In case found brackets are partially inside current selection. + if range.from() < opening || closing < range.to() - 1 { + closing = next_grapheme_boundary(text, closing); + } else { + skip -= 1; + if skip != 0 { + closing = next_grapheme_boundary(text, closing); + } + } + } + + // Keep the original direction. + if let Direction::Forward = range.direction() { + Ok((opening, closing)) + } else { + Ok((closing, opening)) + } +} + +fn find_nth_closest_pairs_plain( + text: RopeSlice, + range: Range, + mut skip: usize, +) -> Result<(usize, usize)> { let mut stack = Vec::with_capacity(2); let pos = range.from(); let mut close_pos = pos.saturating_sub(1); @@ -67,7 +101,7 @@ pub fn find_nth_closest_pairs_pos( for ch in text.chars_at(pos) { close_pos += 1; - if is_open_pair(ch) { + if is_open_bracket(ch) { // Track open pairs encountered so that we can step over // the corresponding close pairs that will come up further // down the loop. We want to find a lone close pair whose @@ -76,7 +110,7 @@ pub fn find_nth_closest_pairs_pos( continue; } - if !is_close_pair(ch) { + if !is_close_bracket(ch) { // We don't care if this character isn't a brace pair item, // so short circuit here. continue; @@ -157,7 +191,11 @@ pub fn find_nth_pairs_pos( ) }; - Option::zip(open, close).ok_or(Error::PairNotFound) + // preserve original direction + match range.direction() { + Direction::Forward => Option::zip(open, close).ok_or(Error::PairNotFound), + Direction::Backward => Option::zip(close, open).ok_or(Error::PairNotFound), + } } fn find_nth_open_pair( @@ -167,6 +205,10 @@ fn find_nth_open_pair( mut pos: usize, n: usize, ) -> Option { + if pos >= text.len_chars() { + return None; + } + let mut chars = text.chars_at(pos + 1); // Adjusts pos for the first iteration, and handles the case of the @@ -245,6 +287,7 @@ fn find_nth_close_pair( /// are automatically detected around each cursor (note that this may result /// in them selecting different surround characters for each selection). pub fn get_surround_pos( + syntax: Option<&Syntax>, text: RopeSlice, selection: &Selection, ch: Option, @@ -253,9 +296,13 @@ pub fn get_surround_pos( let mut change_pos = Vec::new(); for &range in selection { - let (open_pos, close_pos) = match ch { - Some(ch) => find_nth_pairs_pos(text, ch, range, skip)?, - None => find_nth_closest_pairs_pos(text, range, skip)?, + let (open_pos, close_pos) = { + let range_raw = match ch { + Some(ch) => find_nth_pairs_pos(text, ch, range, skip)?, + None => find_nth_closest_pairs_pos(syntax, text, range, skip)?, + }; + let range = Range::new(range_raw.0, range_raw.1); + (range.from(), range.to()) }; if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) { return Err(Error::CursorOverlap); @@ -284,7 +331,7 @@ mod test { ); assert_eq!( - get_surround_pos(doc.slice(..), &selection, Some('('), 1).unwrap(), + get_surround_pos(None, doc.slice(..), &selection, Some('('), 1).unwrap(), expectations ); } @@ -299,7 +346,7 @@ mod test { ); assert_eq!( - get_surround_pos(doc.slice(..), &selection, Some('('), 1), + get_surround_pos(None, doc.slice(..), &selection, Some('('), 1), Err(Error::PairNotFound) ); } @@ -314,7 +361,7 @@ mod test { ); assert_eq!( - get_surround_pos(doc.slice(..), &selection, Some('('), 1), + get_surround_pos(None, doc.slice(..), &selection, Some('('), 1), Err(Error::PairNotFound) // overlapping surround chars ); } @@ -329,7 +376,7 @@ mod test { ); assert_eq!( - get_surround_pos(doc.slice(..), &selection, Some('['), 1), + get_surround_pos(None, doc.slice(..), &selection, Some('['), 1), Err(Error::CursorOverlap) ); } @@ -383,6 +430,21 @@ mod test { ) } + #[test] + fn test_find_nth_closest_pairs_pos_index_range_panic() { + #[rustfmt::skip] + let (doc, selection, _) = + rope_with_selections_and_expectations( + "(a)c)", + "^^^^^" + ); + + assert_eq!( + find_nth_closest_pairs_pos(None, doc.slice(..), selection.primary(), 1), + Err(Error::PairNotFound) + ) + } + // Create a Rope and a matching Selection using a specification language. // ^ is a single-point selection. // _ is an expected index. These are returned as a Vec for use in assertions. diff --git a/helix-core/src/syntax.rs b/helix-core/src/syntax.rs index 3b224e1b2..93f618c09 100644 --- a/helix-core/src/syntax.rs +++ b/helix-core/src/syntax.rs @@ -1,3 +1,5 @@ +mod tree_cursor; + use crate::{ auto_pairs::AutoPairs, chars::char_is_line_ending, @@ -19,9 +21,9 @@ use std::{ borrow::Cow, cell::RefCell, collections::{HashMap, HashSet, VecDeque}, - fmt::{self, Display}, + fmt::{self, Display, Write}, hash::{Hash, Hasher}, - mem::{replace, transmute}, + mem::replace, path::{Path, PathBuf}, str::FromStr, sync::Arc, @@ -32,6 +34,8 @@ use serde::{ser::SerializeSeq, Deserialize, Serialize}; use helix_loader::grammar::{get_language, load_runtime_file}; +pub use tree_cursor::TreeCursor; + fn deserialize_regex<'de, D>(deserializer: D) -> Result, D::Error> where D: serde::Deserializer<'de>, @@ -506,6 +510,7 @@ pub enum DebugArgumentValue { pub struct DebugTemplate { pub name: String, pub request: String, + #[serde(default)] pub completion: Vec, pub args: HashMap, } @@ -724,8 +729,11 @@ pub fn read_query(language: &str, filename: &str) -> String { .replace_all(&query, |captures: ®ex::Captures| { captures[1] .split(',') - .map(|language| format!("\n{}\n", read_query(language, filename))) - .collect::() + .fold(String::new(), |mut output, language| { + // `write!` to a String cannot fail. + write!(output, "\n{}\n", read_query(language, filename)).unwrap(); + output + }) }) .to_string() } @@ -805,7 +813,7 @@ impl LanguageConfiguration { if query_text.is_empty() { return None; } - let lang = self.highlight_config.get()?.as_ref()?.language; + let lang = &self.highlight_config.get()?.as_ref()?.language; Query::new(lang, &query_text) .map_err(|e| { log::error!( @@ -1090,6 +1098,7 @@ impl Syntax { start_point: Point::new(0, 0), end_point: Point::new(usize::MAX, usize::MAX), }], + parent: None, }; // track scope_descriptor: a Vec of scopes for item in tree @@ -1239,7 +1248,7 @@ impl Syntax { PARSER.with(|ts_parser| { let ts_parser = &mut ts_parser.borrow_mut(); ts_parser.parser.set_timeout_micros(1000 * 500); // half a second is pretty generours - let mut cursor = ts_parser.cursors.pop().unwrap_or_else(QueryCursor::new); + let mut cursor = ts_parser.cursors.pop().unwrap_or_default(); // TODO: might need to set cursor range cursor.set_byte_range(0..usize::MAX); cursor.set_match_limit(TREE_SITTER_MATCH_LIMIT); @@ -1354,12 +1363,14 @@ impl Syntax { 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: None, }; // Find an identical existing layer @@ -1371,6 +1382,7 @@ impl Syntax { // ...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); } @@ -1412,7 +1424,7 @@ impl Syntax { // Reuse a cursor from the pool if available. let mut cursor = PARSER.with(|ts_parser| { let highlighter = &mut ts_parser.borrow_mut(); - highlighter.cursors.pop().unwrap_or_else(QueryCursor::new) + highlighter.cursors.pop().unwrap_or_default() }); // The `captures` iterator borrows the `Tree` and the `QueryCursor`, which @@ -1493,6 +1505,12 @@ impl Syntax { .descendant_for_byte_range(start, end) } + pub fn walk(&self) -> TreeCursor<'_> { + // data structure to find the smallest range that contains a point + // when some of the ranges in the structure can overlap. + TreeCursor::new(&self.layers, self.root) + } + // Commenting // comment_strings_for_pos // is_commented @@ -1525,6 +1543,7 @@ pub struct LanguageLayer { pub ranges: Vec, pub depth: u32, flags: LayerUpdateFlags, + parent: Option, } /// This PartialEq implementation only checks if that @@ -1544,13 +1563,7 @@ impl PartialEq for LanguageLayer { impl Hash for LanguageLayer { fn hash(&self, state: &mut H) { self.depth.hash(state); - // The transmute is necessary here because tree_sitter::Language does not derive Hash at the moment. - // However it does use #[repr] transparent so the transmute here is safe - // as `Language` (which `Grammar` is an alias for) is just a newtype wrapper around a (thin) pointer. - // This is also compatible with the PartialEq implementation of language - // as that is just a pointer comparison. - let language: *const () = unsafe { transmute(self.config.language) }; - language.hash(state); + self.config.language.hash(state); self.ranges.hash(state); } } @@ -1567,7 +1580,7 @@ impl LanguageLayer { .map_err(|_| Error::InvalidRanges)?; parser - .set_language(self.config.language) + .set_language(&self.config.language) .map_err(|_| Error::InvalidLanguage)?; // unsafe { syntax.parser.set_cancellation_flag(cancellation_flag) }; @@ -1726,7 +1739,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::{iter, mem, ops, str, usize}; use tree_sitter::{ Language as Grammar, Node, Parser, Point, Query, QueryCaptures, QueryCursor, QueryError, - QueryMatch, Range, TextProvider, Tree, TreeCursor, + QueryMatch, Range, TextProvider, Tree, }; const CANCELLATION_CHECK_INTERVAL: usize = 100; @@ -1867,7 +1880,7 @@ impl HighlightConfiguration { // Construct a single query by concatenating the three query strings, but record the // range of pattern indices that belong to each individual string. - let query = Query::new(language, &query_source)?; + let query = Query::new(&language, &query_source)?; let mut highlights_pattern_index = 0; for i in 0..(query.pattern_count()) { let pattern_offset = query.start_byte_for_pattern(i); @@ -1876,7 +1889,7 @@ impl HighlightConfiguration { } } - let injections_query = Query::new(language, injection_query)?; + let injections_query = Query::new(&language, injection_query)?; let combined_injections_patterns = (0..injections_query.pattern_count()) .filter(|&i| { injections_query @@ -2660,7 +2673,7 @@ pub fn pretty_print_tree(fmt: &mut W, node: Node) -> fmt::Result fn pretty_print_tree_impl( fmt: &mut W, - cursor: &mut TreeCursor, + cursor: &mut tree_sitter::TreeCursor, depth: usize, ) -> fmt::Result { let node = cursor.node(); @@ -2730,7 +2743,7 @@ mod test { .unwrap(); let language = get_language("rust").unwrap(); - let query = Query::new(language, query_str).unwrap(); + let query = Query::new(&language, query_str).unwrap(); let textobject = TextObjectQuery { query }; let mut cursor = QueryCursor::new(); @@ -2758,10 +2771,10 @@ mod test { ) }; - test("quantified_nodes", 1..36); + test("quantified_nodes", 1..37); // NOTE: Enable after implementing proper node group capturing - // test("quantified_nodes_grouped", 1..36); - // test("multiple_nodes_grouped", 1..36); + // test("quantified_nodes_grouped", 1..37); + // test("multiple_nodes_grouped", 1..37); } #[test] @@ -2932,7 +2945,7 @@ mod test { #[test] fn test_pretty_print() { - let source = r#"/// Hello"#; + let source = r#"// Hello"#; assert_pretty_print("rust", source, "(line_comment)", 0, source.len()); // A large tree should be indented with fields: @@ -2951,7 +2964,8 @@ mod test { " (macro_invocation\n", " macro: (identifier)\n", " (token_tree\n", - " (string_literal))))))", + " (string_literal\n", + " (string_content)))))))", ), 0, source.len(), @@ -2970,7 +2984,7 @@ mod test { // rule but `name` and `body` belong to an unnamed helper `_method_rest`. // This can cause a bug with a pretty-printing implementation that // uses `Node::field_name_for_child` to determine field names but is - // fixed when using `TreeCursor::field_name`. + // fixed when using `tree_sitter::TreeCursor::field_name`. let source = "def self.method_name true end"; diff --git a/helix-core/src/syntax/tree_cursor.rs b/helix-core/src/syntax/tree_cursor.rs new file mode 100644 index 000000000..692d5890a --- /dev/null +++ b/helix-core/src/syntax/tree_cursor.rs @@ -0,0 +1,264 @@ +use std::{cmp::Reverse, ops::Range}; + +use super::{LanguageLayer, LayerId}; + +use slotmap::HopSlotMap; +use tree_sitter::Node; + +/// The byte range of an injection layer. +/// +/// Injection ranges may overlap, but all overlapping parts are subsets of their parent ranges. +/// This allows us to sort the ranges ahead of time in order to efficiently find a range that +/// contains a point with maximum depth. +#[derive(Debug)] +struct InjectionRange { + start: usize, + end: usize, + layer_id: LayerId, + depth: u32, +} + +pub struct TreeCursor<'a> { + layers: &'a HopSlotMap, + root: LayerId, + current: LayerId, + injection_ranges: Vec, + // TODO: Ideally this would be a `tree_sitter::TreeCursor<'a>` but + // that returns very surprising results in testing. + cursor: Node<'a>, +} + +impl<'a> TreeCursor<'a> { + pub(super) fn new(layers: &'a HopSlotMap, root: LayerId) -> Self { + let mut injection_ranges = Vec::new(); + + for (layer_id, layer) in layers.iter() { + // Skip the root layer + if layer.parent.is_none() { + continue; + } + for byte_range in layer.ranges.iter() { + let range = InjectionRange { + start: byte_range.start_byte, + end: byte_range.end_byte, + layer_id, + depth: layer.depth, + }; + injection_ranges.push(range); + } + } + + injection_ranges.sort_unstable_by_key(|range| (range.end, Reverse(range.depth))); + + let cursor = layers[root].tree().root_node(); + + Self { + layers, + root, + current: root, + injection_ranges, + cursor, + } + } + + pub fn node(&self) -> Node<'a> { + self.cursor + } + + pub fn goto_parent(&mut self) -> bool { + if let Some(parent) = self.node().parent() { + self.cursor = parent; + return true; + } + + // If we are already on the root layer, we cannot ascend. + if self.current == self.root { + return false; + } + + // Ascend to the parent layer. + let range = self.node().byte_range(); + let parent_id = self.layers[self.current] + .parent + .expect("non-root layers have a parent"); + self.current = parent_id; + let root = self.layers[self.current].tree().root_node(); + self.cursor = root + .descendant_for_byte_range(range.start, range.end) + .unwrap_or(root); + + true + } + + pub fn goto_parent_with

(&mut self, predicate: P) -> bool + where + P: Fn(&Node) -> bool, + { + while self.goto_parent() { + if predicate(&self.node()) { + return true; + } + } + + false + } + + /// Finds the injection layer that has exactly the same range as the given `range`. + fn layer_id_of_byte_range(&self, search_range: Range) -> Option { + let start_idx = self + .injection_ranges + .partition_point(|range| range.end < search_range.end); + + self.injection_ranges[start_idx..] + .iter() + .take_while(|range| range.end == search_range.end) + .find_map(|range| (range.start == search_range.start).then_some(range.layer_id)) + } + + fn goto_first_child_impl(&mut self, named: bool) -> bool { + // Check if the current node's range is an exact injection layer range. + if let Some(layer_id) = self + .layer_id_of_byte_range(self.node().byte_range()) + .filter(|&layer_id| layer_id != self.current) + { + // Switch to the child layer. + self.current = layer_id; + self.cursor = self.layers[self.current].tree().root_node(); + return true; + } + + let child = if named { + self.cursor.named_child(0) + } else { + self.cursor.child(0) + }; + + if let Some(child) = child { + // Otherwise descend in the current tree. + self.cursor = child; + true + } else { + false + } + } + + pub fn goto_first_child(&mut self) -> bool { + self.goto_first_child_impl(false) + } + + pub fn goto_first_named_child(&mut self) -> bool { + self.goto_first_child_impl(true) + } + + fn goto_next_sibling_impl(&mut self, named: bool) -> bool { + let sibling = if named { + self.cursor.next_named_sibling() + } else { + self.cursor.next_sibling() + }; + + if let Some(sibling) = sibling { + self.cursor = sibling; + true + } else { + false + } + } + + pub fn goto_next_sibling(&mut self) -> bool { + self.goto_next_sibling_impl(false) + } + + pub fn goto_next_named_sibling(&mut self) -> bool { + self.goto_next_sibling_impl(true) + } + + fn goto_prev_sibling_impl(&mut self, named: bool) -> bool { + let sibling = if named { + self.cursor.prev_named_sibling() + } else { + self.cursor.prev_sibling() + }; + + if let Some(sibling) = sibling { + self.cursor = sibling; + true + } else { + false + } + } + + pub fn goto_prev_sibling(&mut self) -> bool { + self.goto_prev_sibling_impl(false) + } + + pub fn goto_prev_named_sibling(&mut self) -> bool { + self.goto_prev_sibling_impl(true) + } + + /// Finds the injection layer that contains the given start-end range. + fn layer_id_containing_byte_range(&self, start: usize, end: usize) -> LayerId { + let start_idx = self + .injection_ranges + .partition_point(|range| range.end < end); + + self.injection_ranges[start_idx..] + .iter() + .take_while(|range| range.start < end) + .find_map(|range| (range.start <= start).then_some(range.layer_id)) + .unwrap_or(self.root) + } + + pub fn reset_to_byte_range(&mut self, start: usize, end: usize) { + self.current = self.layer_id_containing_byte_range(start, end); + let root = self.layers[self.current].tree().root_node(); + self.cursor = root.descendant_for_byte_range(start, end).unwrap_or(root); + } + + /// Returns an iterator over the children of the node the TreeCursor is on + /// at the time this is called. + pub fn children(&'a mut self) -> ChildIter { + let parent = self.node(); + + ChildIter { + cursor: self, + parent, + named: false, + } + } + + /// Returns an iterator over the named children of the node the TreeCursor is on + /// at the time this is called. + pub fn named_children(&'a mut self) -> ChildIter { + let parent = self.node(); + + ChildIter { + cursor: self, + parent, + named: true, + } + } +} + +pub struct ChildIter<'n> { + cursor: &'n mut TreeCursor<'n>, + parent: Node<'n>, + named: bool, +} + +impl<'n> Iterator for ChildIter<'n> { + type Item = Node<'n>; + + fn next(&mut self) -> Option { + // first iteration, just visit the first child + if self.cursor.node() == self.parent { + self.cursor + .goto_first_child_impl(self.named) + .then(|| self.cursor.node()) + } else { + self.cursor + .goto_next_sibling_impl(self.named) + .then(|| self.cursor.node()) + } + } +} diff --git a/helix-core/src/text_annotations.rs b/helix-core/src/text_annotations.rs index 11d19d485..1576914e3 100644 --- a/helix-core/src/text_annotations.rs +++ b/helix-core/src/text_annotations.rs @@ -1,6 +1,5 @@ use std::cell::Cell; use std::ops::Range; -use std::rc::Rc; use crate::syntax::Highlight; use crate::Tendril; @@ -92,23 +91,23 @@ pub struct LineAnnotation { } #[derive(Debug)] -struct Layer { - annotations: Rc<[A]>, +struct Layer<'a, A, M> { + annotations: &'a [A], current_index: Cell, metadata: M, } -impl Clone for Layer { +impl Clone for Layer<'_, A, M> { fn clone(&self) -> Self { Layer { - annotations: self.annotations.clone(), + annotations: self.annotations, current_index: self.current_index.clone(), metadata: self.metadata.clone(), } } } -impl Layer { +impl Layer<'_, A, M> { pub fn reset_pos(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) { let new_index = self .annotations @@ -128,8 +127,8 @@ impl Layer { } } -impl From<(Rc<[A]>, M)> for Layer { - fn from((annotations, metadata): (Rc<[A]>, M)) -> Layer { +impl<'a, A, M> From<(&'a [A], M)> for Layer<'a, A, M> { + fn from((annotations, metadata): (&'a [A], M)) -> Layer { Layer { annotations, current_index: Cell::new(0), @@ -147,13 +146,13 @@ fn reset_pos(layers: &[Layer], pos: usize, get_pos: impl Fn(&A) -> u /// Annotations that change that is displayed when the document is render. /// Also commonly called virtual text. #[derive(Default, Debug, Clone)] -pub struct TextAnnotations { - inline_annotations: Vec>>, - overlays: Vec>>, - line_annotations: Vec>, +pub struct TextAnnotations<'a> { + inline_annotations: Vec>>, + overlays: Vec>>, + line_annotations: Vec>, } -impl TextAnnotations { +impl<'a> TextAnnotations<'a> { /// Prepare the TextAnnotations for iteration starting at char_idx pub fn reset_pos(&self, char_idx: usize) { reset_pos(&self.inline_annotations, char_idx, |annot| annot.char_idx); @@ -194,7 +193,7 @@ impl TextAnnotations { /// the annotations that belong to the layers added first will be shown first. pub fn add_inline_annotations( &mut self, - layer: Rc<[InlineAnnotation]>, + layer: &'a [InlineAnnotation], highlight: Option, ) -> &mut Self { self.inline_annotations.push((layer, highlight).into()); @@ -211,7 +210,7 @@ impl TextAnnotations { /// /// 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: Rc<[Overlay]>, highlight: Option) -> &mut Self { + pub fn add_overlay(&mut self, layer: &'a [Overlay], highlight: Option) -> &mut Self { self.overlays.push((layer, highlight).into()); self } @@ -220,7 +219,7 @@ impl TextAnnotations { /// /// 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: Rc<[LineAnnotation]>) -> &mut Self { + pub fn add_line_annotation(&mut self, layer: &'a [LineAnnotation]) -> &mut Self { self.line_annotations.push((layer, ()).into()); self } diff --git a/helix-core/src/textobject.rs b/helix-core/src/textobject.rs index bf00a4580..7576b3a78 100644 --- a/helix-core/src/textobject.rs +++ b/helix-core/src/textobject.rs @@ -7,9 +7,9 @@ use crate::chars::{categorize_char, char_is_whitespace, CharCategory}; use crate::graphemes::{next_grapheme_boundary, prev_grapheme_boundary}; use crate::line_ending::rope_is_line_ending; use crate::movement::Direction; -use crate::surround; use crate::syntax::LanguageConfiguration; use crate::Range; +use crate::{surround, Syntax}; fn find_word_boundary(slice: RopeSlice, mut pos: usize, direction: Direction, long: bool) -> usize { use CharCategory::{Eol, Whitespace}; @@ -199,25 +199,28 @@ pub fn textobject_paragraph( } pub fn textobject_pair_surround( + syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, ch: char, count: usize, ) -> Range { - textobject_pair_surround_impl(slice, range, textobject, Some(ch), count) + textobject_pair_surround_impl(syntax, slice, range, textobject, Some(ch), count) } pub fn textobject_pair_surround_closest( + syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, count: usize, ) -> Range { - textobject_pair_surround_impl(slice, range, textobject, None, count) + textobject_pair_surround_impl(syntax, slice, range, textobject, None, count) } fn textobject_pair_surround_impl( + syntax: Option<&Syntax>, slice: RopeSlice, range: Range, textobject: TextObject, @@ -226,8 +229,7 @@ fn textobject_pair_surround_impl( ) -> Range { let pair_pos = match ch { Some(ch) => surround::find_nth_pairs_pos(slice, ch, range, count), - // Automatically find the closest surround pairs - None => surround::find_nth_closest_pairs_pos(slice, range, count), + None => surround::find_nth_closest_pairs_pos(syntax, slice, range, count), }; pair_pos .map(|(anchor, head)| match textobject { @@ -574,7 +576,8 @@ mod test { let slice = doc.slice(..); for &case in scenario { let (pos, objtype, expected_range, ch, count) = case; - let result = textobject_pair_surround(slice, Range::point(pos), objtype, ch, count); + let result = + textobject_pair_surround(None, slice, Range::point(pos), objtype, ch, count); assert_eq!( result, expected_range.into(), diff --git a/helix-core/src/transaction.rs b/helix-core/src/transaction.rs index f5a49cc11..f24f20942 100644 --- a/helix-core/src/transaction.rs +++ b/helix-core/src/transaction.rs @@ -378,7 +378,9 @@ impl ChangeSet { macro_rules! map { ($map: expr, $i: expr) => { loop { - let Some((pos, assoc)) = positions.peek_mut() else { return; }; + let Some((pos, assoc)) = positions.peek_mut() else { + return; + }; if **pos < old_pos { // Positions are not sorted, revert to the last Operation that // contains this position and continue iterating from there. @@ -405,7 +407,10 @@ impl ChangeSet { debug_assert!(old_pos <= **pos, "Reverse Iter across changeset works"); continue 'outer; } - let Some(new_pos) = $map(**pos, *assoc) else { break; }; + #[allow(clippy::redundant_closure_call)] + let Some(new_pos) = $map(**pos, *assoc) else { + break; + }; **pos = new_pos; positions.next(); } diff --git a/helix-core/tests/indent.rs b/helix-core/tests/indent.rs index 31946c56e..56b4d2ba9 100644 --- a/helix-core/tests/indent.rs +++ b/helix-core/tests/indent.rs @@ -36,7 +36,7 @@ fn test_treesitter_indent_rust_helix() { .unwrap(); let files = String::from_utf8(files.stdout).unwrap(); - let ignored_files = vec![ + let ignored_files = [ // Contains many macros that tree-sitter does not parse in a meaningful way and is otherwise not very interesting "helix-term/src/health.rs", ]; @@ -45,6 +45,7 @@ fn test_treesitter_indent_rust_helix() { if ignored_files.contains(&file) { continue; } + #[allow(clippy::single_range_in_vec_init)] let ignored_lines: Vec> = match file { "helix-term/src/application.rs" => vec![ // We can't handle complicated indent rules inside macros (`json!` in this case) since diff --git a/helix-dap/Cargo.toml b/helix-dap/Cargo.toml index 3521f5890..c37340cc6 100644 --- a/helix-dap/Cargo.toml +++ b/helix-dap/Cargo.toml @@ -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" diff --git a/helix-dap/src/client.rs b/helix-dap/src/client.rs index 18af13ae7..2f5b3d0fc 100644 --- a/helix-dap/src/client.rs +++ b/helix-dap/src/client.rs @@ -2,7 +2,7 @@ use crate::{ requests::DisconnectArguments, transport::{Payload, Request, Response, Transport}, types::*, - Error, Result, ThreadId, + Error, Result, }; use helix_core::syntax::DebuggerQuirks; diff --git a/helix-dap/src/types.rs b/helix-dap/src/types.rs index bbaf53a60..9cec05e65 100644 --- a/helix-dap/src/types.rs +++ b/helix-dap/src/types.rs @@ -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, @@ -331,6 +332,23 @@ pub struct Module { pub address_range: Option, } +fn from_number<'de, D>(deserializer: D) -> Result +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 mod events { 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"); + } } diff --git a/helix-event/Cargo.toml b/helix-event/Cargo.toml index 616c323dc..e7c877355 100644 --- a/helix-event/Cargo.toml +++ b/helix-event/Cargo.toml @@ -13,7 +13,7 @@ homepage.workspace = true [dependencies] ahash = "0.8.11" -hashbrown = "0.14.0" +hashbrown = "0.14.5" tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "parking_lot", "macros"] } # the event registry is essentially read only but must be an rwlock so we can # setup new events on initialization, hardware-lock-elision hugely benefits this case diff --git a/helix-loader/build.rs b/helix-loader/build.rs index a4562c00c..ea0689839 100644 --- a/helix-loader/build.rs +++ b/helix-loader/build.rs @@ -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; }; diff --git a/helix-loader/src/lib.rs b/helix-loader/src/lib.rs index 93488e452..badb9bd64 100644 --- a/helix-loader/src/lib.rs +++ b/helix-loader/src/lib.rs @@ -126,7 +126,7 @@ pub fn config_dir() -> PathBuf { pub fn cache_dir() -> PathBuf { // TODO: allow env var override - let strategy = choose_base_strategy().expect("Unable to find the config directory!"); + let strategy = choose_base_strategy().expect("Unable to find the cache directory!"); let mut path = strategy.cache_dir(); path.push("helix"); path diff --git a/helix-lsp/Cargo.toml b/helix-lsp/Cargo.toml index 4284b0520..ab9251ebe 100644 --- a/helix-lsp/Cargo.toml +++ b/helix-lsp/Cargo.toml @@ -26,8 +26,9 @@ log = "0.4" lsp-types = { version = "0.95" } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -thiserror = "1.0" -tokio = { version = "1.36", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] } -tokio-stream = "0.1.14" -parking_lot = "0.12.1" +tokio = { version = "1.38", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] } +tokio-stream = "0.1.15" +parking_lot = "0.12.3" arc-swap = "1" +slotmap.workspace = true +thiserror.workspace = true diff --git a/helix-lsp/src/client.rs b/helix-lsp/src/client.rs index a7b3989dd..254625a3a 100644 --- a/helix-lsp/src/client.rs +++ b/helix-lsp/src/client.rs @@ -2,11 +2,11 @@ use crate::{ file_operations::FileOperationsInterest, find_lsp_workspace, jsonrpc, transport::{Payload, Transport}, - Call, Error, OffsetEncoding, Result, + Call, Error, LanguageServerId, OffsetEncoding, Result, }; use helix_core::{find_workspace, syntax::LanguageServerFeature, ChangeSet, Rope}; -use helix_loader::{self, VERSION_AND_GIT_HASH}; +use helix_loader::VERSION_AND_GIT_HASH; use helix_stdx::path; use lsp::{ notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, @@ -46,7 +46,7 @@ fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder { #[derive(Debug)] pub struct Client { - id: usize, + id: LanguageServerId, name: String, _process: Child, server_tx: UnboundedSender, @@ -179,10 +179,14 @@ impl Client { server_environment: HashMap, root_path: PathBuf, root_uri: Option, - id: usize, + id: LanguageServerId, name: String, req_timeout: u64, - ) -> Result<(Self, UnboundedReceiver<(usize, Call)>, Arc)> { + ) -> Result<( + Self, + UnboundedReceiver<(LanguageServerId, Call)>, + Arc, + )> { // Resolve path to the binary let cmd = helix_stdx::env::which(cmd)?; @@ -234,7 +238,7 @@ impl Client { &self.name } - pub fn id(&self) -> usize { + pub fn id(&self) -> LanguageServerId { self.id } @@ -393,6 +397,16 @@ impl Client { &self, params: R::Params, ) -> impl Future> + where + R::Params: serde::Serialize, + { + self.call_with_ref::(¶ms) + } + + fn call_with_ref( + &self, + params: &R::Params, + ) -> impl Future> where R::Params: serde::Serialize, { @@ -401,7 +415,7 @@ impl Client { fn call_with_timeout( &self, - params: R::Params, + params: &R::Params, timeout_secs: u64, ) -> impl Future> where @@ -410,17 +424,16 @@ impl Client { let server_tx = self.server_tx.clone(); let id = self.next_request_id(); + let params = serde_json::to_value(params); async move { use std::time::Duration; use tokio::time::timeout; - let params = serde_json::to_value(params)?; - let request = jsonrpc::MethodCall { jsonrpc: Some(jsonrpc::Version::V2), id: id.clone(), method: R::METHOD.to_string(), - params: Self::value_into_params(params), + params: Self::value_into_params(params?), }; let (tx, mut rx) = channel::>(1); @@ -737,7 +750,7 @@ impl Client { new_uri: url_from_path(new_path)?, }]; let request = self.call_with_timeout::( - lsp::RenameFilesParams { files }, + &lsp::RenameFilesParams { files }, 5, ); @@ -1022,21 +1035,10 @@ impl Client { pub fn resolve_completion_item( &self, - completion_item: lsp::CompletionItem, - ) -> Option>> { - let capabilities = self.capabilities.get().unwrap(); - - // Return early if the server does not support resolving completion items. - match capabilities.completion_provider { - Some(lsp::CompletionOptions { - resolve_provider: Some(true), - .. - }) => (), - _ => return None, - } - - let res = self.call::(completion_item); - Some(async move { Ok(serde_json::from_value(res.await?)?) }) + completion_item: &lsp::CompletionItem, + ) -> impl Future> { + let res = self.call_with_ref::(completion_item); + async move { Ok(serde_json::from_value(res.await?)?) } } pub fn resolve_code_action( diff --git a/helix-lsp/src/file_event.rs b/helix-lsp/src/file_event.rs index 93457fa55..c7297d67f 100644 --- a/helix-lsp/src/file_event.rs +++ b/helix-lsp/src/file_event.rs @@ -3,24 +3,24 @@ use std::{collections::HashMap, path::PathBuf, sync::Weak}; use globset::{GlobBuilder, GlobSetBuilder}; use tokio::sync::mpsc; -use crate::{lsp, Client}; +use crate::{lsp, Client, LanguageServerId}; enum Event { FileChanged { path: PathBuf, }, Register { - client_id: usize, + client_id: LanguageServerId, client: Weak, registration_id: String, options: lsp::DidChangeWatchedFilesRegistrationOptions, }, Unregister { - client_id: usize, + client_id: LanguageServerId, registration_id: String, }, RemoveClient { - client_id: usize, + client_id: LanguageServerId, }, } @@ -59,7 +59,7 @@ impl Handler { pub fn register( &self, - client_id: usize, + client_id: LanguageServerId, client: Weak, registration_id: String, options: lsp::DidChangeWatchedFilesRegistrationOptions, @@ -72,7 +72,7 @@ impl Handler { }); } - pub fn unregister(&self, client_id: usize, registration_id: String) { + pub fn unregister(&self, client_id: LanguageServerId, registration_id: String) { let _ = self.tx.send(Event::Unregister { client_id, registration_id, @@ -83,12 +83,12 @@ impl Handler { let _ = self.tx.send(Event::FileChanged { path }); } - pub fn remove_client(&self, client_id: usize) { + pub fn remove_client(&self, client_id: LanguageServerId) { let _ = self.tx.send(Event::RemoveClient { client_id }); } async fn run(mut rx: mpsc::UnboundedReceiver) { - let mut state: HashMap = HashMap::new(); + let mut state: HashMap = HashMap::new(); while let Some(event) = rx.recv().await { match event { Event::FileChanged { path } => { @@ -139,7 +139,7 @@ impl Handler { registration_id ); - let entry = state.entry(client_id).or_insert_with(ClientState::default); + let entry = state.entry(client_id).or_default(); entry.client = client; let mut builder = GlobSetBuilder::new(); diff --git a/helix-lsp/src/lib.rs b/helix-lsp/src/lib.rs index c58d967b6..ec89e1f82 100644 --- a/helix-lsp/src/lib.rs +++ b/helix-lsp/src/lib.rs @@ -17,6 +17,7 @@ use helix_core::syntax::{ LanguageConfiguration, LanguageServerConfiguration, LanguageServerFeatures, }; use helix_stdx::path; +use slotmap::SlotMap; use tokio::sync::mpsc::UnboundedReceiver; use std::{ @@ -28,8 +29,9 @@ use std::{ use thiserror::Error; use tokio_stream::wrappers::UnboundedReceiverStream; -pub type Result = core::result::Result; +pub type Result = core::result::Result; pub type LanguageServerName = String; +pub use helix_core::diagnostic::LanguageServerId; #[derive(Error, Debug)] pub enum Error { @@ -284,7 +286,8 @@ pub mod util { .chars_at(cursor) .skip(1) .take_while(|ch| chars::char_is_word(*ch)) - .count(); + .count() + + 1; } (start, end) } @@ -539,6 +542,16 @@ pub mod util { } else { return (0, 0, None); }; + + if start > end { + log::error!( + "Invalid LSP text edit start {:?} > end {:?}, discarding", + start, + end + ); + return (0, 0, None); + } + (start, end, replacement) }), ) @@ -640,38 +653,42 @@ impl Notification { #[derive(Debug)] pub struct Registry { - inner: HashMap>>, + inner: SlotMap>, + inner_by_name: HashMap>>, syn_loader: Arc>, - counter: usize, - pub incoming: SelectAll>, + pub incoming: SelectAll>, pub file_event_handler: file_event::Handler, } impl Registry { pub fn new(syn_loader: Arc>) -> Self { Self { - inner: HashMap::new(), + inner: SlotMap::with_key(), + inner_by_name: HashMap::new(), syn_loader, - counter: 0, incoming: SelectAll::new(), file_event_handler: file_event::Handler::new(), } } - pub fn get_by_id(&self, id: usize) -> Option<&Client> { - self.inner - .values() - .flatten() - .find(|client| client.id() == id) - .map(|client| &**client) + pub fn get_by_id(&self, id: LanguageServerId) -> Option<&Arc> { + self.inner.get(id) } - pub fn remove_by_id(&mut self, id: usize) { + pub fn remove_by_id(&mut self, id: LanguageServerId) { + let Some(client) = self.inner.remove(id) else { + log::error!("client was already removed"); + return; + }; self.file_event_handler.remove_client(id); - self.inner.retain(|_, language_servers| { - language_servers.retain(|ls| id != ls.id()); - !language_servers.is_empty() - }); + let instances = self + .inner_by_name + .get_mut(client.name()) + .expect("inner and inner_by_name must be synced"); + instances.retain(|ls| id != ls.id()); + if instances.is_empty() { + self.inner_by_name.remove(client.name()); + } } fn start_client( @@ -681,28 +698,28 @@ impl Registry { doc_path: Option<&std::path::PathBuf>, root_dirs: &[PathBuf], enable_snippets: bool, - ) -> Result>> { + ) -> Result, StartupError> { let syn_loader = self.syn_loader.load(); let config = syn_loader .language_server_configs() .get(&name) .ok_or_else(|| anyhow::anyhow!("Language server '{name}' not defined"))?; - let id = self.counter; - self.counter += 1; - if let Some(NewClient(client, incoming)) = start_client( - id, - name, - ls_config, - config, - doc_path, - root_dirs, - enable_snippets, - )? { - self.incoming.push(UnboundedReceiverStream::new(incoming)); - Ok(Some(client)) - } else { - Ok(None) - } + let id = self.inner.try_insert_with_key(|id| { + start_client( + id, + name, + ls_config, + config, + doc_path, + root_dirs, + enable_snippets, + ) + .map(|client| { + self.incoming.push(UnboundedReceiverStream::new(client.1)); + client.0 + }) + })?; + Ok(self.inner[id].clone()) } /// If this method is called, all documents that have a reference to language servers used by the language config have to refresh their language servers, @@ -719,41 +736,39 @@ impl Registry { .language_servers .iter() .filter_map(|LanguageServerFeatures { name, .. }| { - if self.inner.contains_key(name) { - let client = match self.start_client( - name.clone(), - language_config, - doc_path, - root_dirs, - enable_snippets, - ) { - Ok(client) => client?, - Err(error) => return Some(Err(error)), - }; - let old_clients = self - .inner - .insert(name.clone(), vec![client.clone()]) - .unwrap(); - + if let Some(old_clients) = self.inner_by_name.remove(name) { for old_client in old_clients { self.file_event_handler.remove_client(old_client.id()); + self.inner.remove(old_client.id()); tokio::spawn(async move { let _ = old_client.force_shutdown().await; }); } - - Some(Ok(client)) - } else { - None } + let client = match self.start_client( + name.clone(), + language_config, + doc_path, + root_dirs, + enable_snippets, + ) { + Ok(client) => client, + Err(StartupError::NoRequiredRootFound) => return None, + Err(StartupError::Error(err)) => return Some(Err(err)), + }; + self.inner_by_name + .insert(name.to_owned(), vec![client.clone()]); + + Some(Ok(client)) }) .collect() } pub fn stop(&mut self, name: &str) { - if let Some(clients) = self.inner.remove(name) { + if let Some(clients) = self.inner_by_name.remove(name) { for client in clients { self.file_event_handler.remove_client(client.id()); + self.inner.remove(client.id()); tokio::spawn(async move { let _ = client.force_shutdown().await; }); @@ -770,7 +785,7 @@ impl Registry { ) -> impl Iterator>)> + 'a { language_config.language_servers.iter().filter_map( move |LanguageServerFeatures { name, .. }| { - if let Some(clients) = self.inner.get(name) { + if let Some(clients) = self.inner_by_name.get(name) { if let Some((_, client)) = clients.iter().enumerate().find(|(i, client)| { client.try_add_doc(&language_config.roots, root_dirs, doc_path, *i == 0) }) { @@ -785,21 +800,21 @@ impl Registry { enable_snippets, ) { Ok(client) => { - let client = client?; - self.inner + self.inner_by_name .entry(name.to_owned()) .or_default() .push(client.clone()); Some((name.clone(), Ok(client))) } - Err(err) => Some((name.to_owned(), Err(err))), + Err(StartupError::NoRequiredRootFound) => None, + Err(StartupError::Error(err)) => Some((name.to_owned(), Err(err))), } }, ) } pub fn iter_clients(&self) -> impl Iterator> { - self.inner.values().flatten() + self.inner.values() } } @@ -822,7 +837,7 @@ impl ProgressStatus { /// Acts as a container for progress reported by language servers. Each server /// has a unique id assigned at creation through [`Registry`]. This id is then used /// to store the progress in this map. -pub struct LspProgressMap(HashMap>); +pub struct LspProgressMap(HashMap>); impl LspProgressMap { pub fn new() -> Self { @@ -830,28 +845,35 @@ impl LspProgressMap { } /// Returns a map of all tokens corresponding to the language server with `id`. - pub fn progress_map(&self, id: usize) -> Option<&HashMap> { + pub fn progress_map( + &self, + id: LanguageServerId, + ) -> Option<&HashMap> { self.0.get(&id) } - pub fn is_progressing(&self, id: usize) -> bool { + pub fn is_progressing(&self, id: LanguageServerId) -> bool { self.0.get(&id).map(|it| !it.is_empty()).unwrap_or_default() } /// Returns last progress status for a given server with `id` and `token`. - pub fn progress(&self, id: usize, token: &lsp::ProgressToken) -> Option<&ProgressStatus> { + pub fn progress( + &self, + id: LanguageServerId, + token: &lsp::ProgressToken, + ) -> Option<&ProgressStatus> { self.0.get(&id).and_then(|values| values.get(token)) } /// Checks if progress `token` for server with `id` is created. - pub fn is_created(&mut self, id: usize, token: &lsp::ProgressToken) -> bool { + pub fn is_created(&mut self, id: LanguageServerId, token: &lsp::ProgressToken) -> bool { self.0 .get(&id) .map(|values| values.get(token).is_some()) .unwrap_or_default() } - pub fn create(&mut self, id: usize, token: lsp::ProgressToken) { + pub fn create(&mut self, id: LanguageServerId, token: lsp::ProgressToken) { self.0 .entry(id) .or_default() @@ -861,7 +883,7 @@ impl LspProgressMap { /// Ends the progress by removing the `token` from server with `id`, if removed returns the value. pub fn end_progress( &mut self, - id: usize, + id: LanguageServerId, token: &lsp::ProgressToken, ) -> Option { self.0.get_mut(&id).and_then(|vals| vals.remove(token)) @@ -870,7 +892,7 @@ impl LspProgressMap { /// Updates the progress of `token` for server with `id` to `status`, returns the value replaced or `None`. pub fn update( &mut self, - id: usize, + id: LanguageServerId, token: lsp::ProgressToken, status: lsp::WorkDoneProgress, ) -> Option { @@ -881,19 +903,30 @@ impl LspProgressMap { } } -struct NewClient(Arc, UnboundedReceiver<(usize, Call)>); +struct NewClient(Arc, UnboundedReceiver<(LanguageServerId, Call)>); + +enum StartupError { + NoRequiredRootFound, + Error(Error), +} + +impl> From for StartupError { + fn from(value: T) -> Self { + StartupError::Error(value.into()) + } +} /// start_client takes both a LanguageConfiguration and a LanguageServerConfiguration to ensure that /// it is only called when it makes sense. fn start_client( - id: usize, + id: LanguageServerId, name: String, config: &LanguageConfiguration, ls_config: &LanguageServerConfiguration, doc_path: Option<&std::path::PathBuf>, root_dirs: &[PathBuf], enable_snippets: bool, -) -> Result> { +) -> Result { let (workspace, workspace_is_cwd) = helix_loader::find_workspace(); let workspace = path::normalize(workspace); let root = find_lsp_workspace( @@ -918,7 +951,7 @@ fn start_client( .map(|entry| entry.file_name()) .any(|entry| globset.is_match(entry)) { - return Ok(None); + return Err(StartupError::NoRequiredRootFound); } } @@ -970,7 +1003,7 @@ fn start_client( initialize_notify.notify_one(); }); - Ok(Some(NewClient(client, incoming))) + Ok(NewClient(client, incoming)) } /// Find an LSP workspace of a file using the following mechanism: diff --git a/helix-lsp/src/transport.rs b/helix-lsp/src/transport.rs index f2f35d6ab..bd671abe1 100644 --- a/helix-lsp/src/transport.rs +++ b/helix-lsp/src/transport.rs @@ -1,4 +1,4 @@ -use crate::{jsonrpc, Error, Result}; +use crate::{jsonrpc, Error, LanguageServerId, Result}; use anyhow::Context; use log::{error, info}; use serde::{Deserialize, Serialize}; @@ -37,7 +37,7 @@ enum ServerMessage { #[derive(Debug)] pub struct Transport { - id: usize, + id: LanguageServerId, name: String, pending_requests: Mutex>>>, } @@ -47,10 +47,10 @@ impl Transport { server_stdout: BufReader, server_stdin: BufWriter, server_stderr: BufReader, - id: usize, + id: LanguageServerId, name: String, ) -> ( - UnboundedReceiver<(usize, jsonrpc::Call)>, + UnboundedReceiver<(LanguageServerId, jsonrpc::Call)>, UnboundedSender, Arc, ) { @@ -194,7 +194,7 @@ impl Transport { async fn process_server_message( &self, - client_tx: &UnboundedSender<(usize, jsonrpc::Call)>, + client_tx: &UnboundedSender<(LanguageServerId, jsonrpc::Call)>, msg: ServerMessage, language_server_name: &str, ) -> Result<()> { @@ -251,7 +251,7 @@ impl Transport { async fn recv( transport: Arc, mut server_stdout: BufReader, - client_tx: UnboundedSender<(usize, jsonrpc::Call)>, + client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>, ) { let mut recv_buffer = String::new(); loop { @@ -329,7 +329,7 @@ impl Transport { async fn send( transport: Arc, mut server_stdin: BufWriter, - client_tx: UnboundedSender<(usize, jsonrpc::Call)>, + client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>, mut client_rx: UnboundedReceiver, initialize_notify: Arc, ) { diff --git a/helix-stdx/Cargo.toml b/helix-stdx/Cargo.toml index 5ac7c011f..5aef65905 100644 --- a/helix-stdx/Cargo.toml +++ b/helix-stdx/Cargo.toml @@ -16,7 +16,14 @@ dunce = "1.0" etcetera = "0.8" ropey = { version = "1.6.1", default-features = false } which = "6.0" -regex-cursor = "0.1.3" +regex-cursor = "0.1.4" +bitflags = "2.6" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.52", features = ["Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } + +[target.'cfg(unix)'.dependencies] +rustix = { version = "0.38", features = ["fs"] } [dev-dependencies] tempfile = "3.10" diff --git a/helix-stdx/src/env.rs b/helix-stdx/src/env.rs index 90a0aee87..51450d225 100644 --- a/helix-stdx/src/env.rs +++ b/helix-stdx/src/env.rs @@ -14,13 +14,23 @@ pub fn current_working_dir() -> PathBuf { return path.clone(); } - let path = std::env::current_dir() - .map(crate::path::normalize) - .expect("Couldn't determine current working directory"); - let mut cwd = CWD.write().unwrap(); - *cwd = Some(path.clone()); + // implementation of crossplatform pwd -L + // we want pwd -L so that symlinked directories are handled correctly + let mut cwd = std::env::current_dir().expect("Couldn't determine current working directory"); + + let pwd = std::env::var_os("PWD"); + #[cfg(windows)] + let pwd = pwd.or_else(|| std::env::var_os("CD")); + + if let Some(pwd) = pwd.map(PathBuf::from) { + if pwd.canonicalize().ok().as_ref() == Some(&cwd) { + cwd = pwd; + } + } + let mut dst = CWD.write().unwrap(); + *dst = Some(cwd.clone()); - path + cwd } pub fn set_current_working_dir(path: impl AsRef) -> std::io::Result<()> { @@ -42,8 +52,9 @@ pub fn binary_exists>(binary_name: T) -> bool { pub fn which>( binary_name: T, ) -> Result { - which::which(binary_name.as_ref()).map_err(|err| ExecutableNotFoundError { - command: binary_name.as_ref().to_string_lossy().into_owned(), + let binary_name = binary_name.as_ref(); + which::which(binary_name).map_err(|err| ExecutableNotFoundError { + command: binary_name.to_string_lossy().into_owned(), inner: err, }) } diff --git a/helix-stdx/src/faccess.rs b/helix-stdx/src/faccess.rs new file mode 100644 index 000000000..0270c1f8a --- /dev/null +++ b/helix-stdx/src/faccess.rs @@ -0,0 +1,459 @@ +//! From + +use std::io; +use std::path::Path; + +use bitflags::bitflags; + +// Licensed under MIT from faccess +bitflags! { + /// Access mode flags for `access` function to test for. + pub struct AccessMode: u8 { + /// Path exists + const EXISTS = 0b0001; + /// Path can likely be read + const READ = 0b0010; + /// Path can likely be written to + const WRITE = 0b0100; + /// Path can likely be executed + const EXECUTE = 0b1000; + } +} + +#[cfg(unix)] +mod imp { + use super::*; + + use rustix::fs::Access; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + pub fn access(p: &Path, mode: AccessMode) -> io::Result<()> { + let mut imode = Access::empty(); + + if mode.contains(AccessMode::EXISTS) { + imode |= Access::EXISTS; + } + + if mode.contains(AccessMode::READ) { + imode |= Access::READ_OK; + } + + if mode.contains(AccessMode::WRITE) { + imode |= Access::WRITE_OK; + } + + if mode.contains(AccessMode::EXECUTE) { + imode |= Access::EXEC_OK; + } + + rustix::fs::access(p, imode)?; + Ok(()) + } + + fn chown(p: &Path, uid: Option, gid: Option) -> io::Result<()> { + let uid = uid.map(|n| unsafe { rustix::fs::Uid::from_raw(n) }); + let gid = gid.map(|n| unsafe { rustix::fs::Gid::from_raw(n) }); + rustix::fs::chown(p, uid, gid)?; + Ok(()) + } + + pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { + let from_meta = std::fs::metadata(from)?; + let to_meta = std::fs::metadata(to)?; + let from_gid = from_meta.gid(); + let to_gid = to_meta.gid(); + + let mut perms = from_meta.permissions(); + perms.set_mode(perms.mode() & 0o0777); + if from_gid != to_gid && chown(to, None, Some(from_gid)).is_err() { + let new_perms = (perms.mode() & 0o0707) | ((perms.mode() & 0o07) << 3); + perms.set_mode(new_perms); + } + + std::fs::set_permissions(to, perms)?; + + Ok(()) + } +} + +// Licensed under MIT from faccess except for `chown`, `copy_metadata` and `is_acl_inherited` +#[cfg(windows)] +mod imp { + + use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, ERROR_SUCCESS, HANDLE, PSID}; + use windows_sys::Win32::Security::Authorization::{ + GetNamedSecurityInfoW, SetNamedSecurityInfoW, SE_FILE_OBJECT, + }; + use windows_sys::Win32::Security::{ + AccessCheck, AclSizeInformation, GetAce, GetAclInformation, GetSidIdentifierAuthority, + ImpersonateSelf, IsValidAcl, IsValidSid, MapGenericMask, RevertToSelf, + SecurityImpersonation, ACCESS_ALLOWED_CALLBACK_ACE, ACL, ACL_SIZE_INFORMATION, + DACL_SECURITY_INFORMATION, GENERIC_MAPPING, GROUP_SECURITY_INFORMATION, INHERITED_ACE, + LABEL_SECURITY_INFORMATION, OBJECT_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, + PRIVILEGE_SET, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, + SID_IDENTIFIER_AUTHORITY, TOKEN_DUPLICATE, TOKEN_QUERY, + }; + use windows_sys::Win32::Storage::FileSystem::{ + FILE_ACCESS_RIGHTS, FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, + FILE_GENERIC_WRITE, + }; + use windows_sys::Win32::System::Threading::{GetCurrentThread, OpenThreadToken}; + + use super::*; + + use std::ffi::c_void; + + use std::os::windows::{ffi::OsStrExt, fs::OpenOptionsExt}; + + struct SecurityDescriptor { + sd: PSECURITY_DESCRIPTOR, + owner: PSID, + group: PSID, + dacl: *mut ACL, + } + + impl Drop for SecurityDescriptor { + fn drop(&mut self) { + if !self.sd.is_null() { + unsafe { + LocalFree(self.sd); + } + } + } + } + + impl SecurityDescriptor { + fn for_path(p: &Path) -> io::Result { + let path = std::fs::canonicalize(p)?; + let pathos = path.into_os_string(); + let mut pathw: Vec = Vec::with_capacity(pathos.len() + 1); + pathw.extend(pathos.encode_wide()); + pathw.push(0); + + let mut sd = std::ptr::null_mut(); + let mut owner = std::ptr::null_mut(); + let mut group = std::ptr::null_mut(); + let mut dacl = std::ptr::null_mut(); + + let err = unsafe { + GetNamedSecurityInfoW( + pathw.as_ptr(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | DACL_SECURITY_INFORMATION + | LABEL_SECURITY_INFORMATION, + &mut owner, + &mut group, + &mut dacl, + std::ptr::null_mut(), + &mut sd, + ) + }; + + if err == ERROR_SUCCESS { + Ok(SecurityDescriptor { + sd, + owner, + group, + dacl, + }) + } else { + Err(io::Error::last_os_error()) + } + } + + fn is_acl_inherited(&self) -> bool { + let mut acl_info: ACL_SIZE_INFORMATION = unsafe { ::core::mem::zeroed() }; + let acl_info_ptr: *mut c_void = &mut acl_info as *mut _ as *mut c_void; + let mut ace: ACCESS_ALLOWED_CALLBACK_ACE = unsafe { ::core::mem::zeroed() }; + + unsafe { + GetAclInformation( + self.dacl, + acl_info_ptr, + std::mem::size_of_val(&acl_info) as u32, + AclSizeInformation, + ) + }; + + for i in 0..acl_info.AceCount { + let mut ptr = &mut ace as *mut _ as *mut c_void; + unsafe { GetAce(self.dacl, i, &mut ptr) }; + if (ace.Header.AceFlags as u32 & INHERITED_ACE) != 0 { + return true; + } + } + + false + } + + fn descriptor(&self) -> &PSECURITY_DESCRIPTOR { + &self.sd + } + + fn owner(&self) -> &PSID { + &self.owner + } + } + + struct ThreadToken(HANDLE); + impl Drop for ThreadToken { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + + impl ThreadToken { + fn new() -> io::Result { + unsafe { + if ImpersonateSelf(SecurityImpersonation) == 0 { + return Err(io::Error::last_os_error()); + } + + let token: *mut HANDLE = std::ptr::null_mut(); + let err = + OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY, 0, token); + + RevertToSelf(); + + if err == 0 { + return Err(io::Error::last_os_error()); + } + + Ok(Self(*token)) + } + } + + fn as_handle(&self) -> &HANDLE { + &self.0 + } + } + + // Based roughly on Tcl's NativeAccess() + // https://github.com/tcltk/tcl/blob/2ee77587e4dc2150deb06b48f69db948b4ab0584/win/tclWinFile.c + fn eaccess(p: &Path, mut mode: FILE_ACCESS_RIGHTS) -> io::Result<()> { + let md = p.metadata()?; + + if !md.is_dir() { + // Read Only is ignored for directories + if mode & FILE_GENERIC_WRITE == FILE_GENERIC_WRITE && md.permissions().readonly() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "File is read only", + )); + } + + // If it doesn't have the correct extension it isn't executable + if mode & FILE_GENERIC_EXECUTE == FILE_GENERIC_EXECUTE { + if let Some(ext) = p.extension().and_then(|s| s.to_str()) { + match ext { + "exe" | "com" | "bat" | "cmd" => (), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "File not executable", + )) + } + } + } + } + + return std::fs::OpenOptions::new() + .access_mode(mode) + .open(p) + .map(|_| ()); + } + + let sd = SecurityDescriptor::for_path(p)?; + + // Unmapped Samba users are assigned a top level authority of 22 + // ACL tests are likely to be misleading + const SAMBA_UNMAPPED: SID_IDENTIFIER_AUTHORITY = SID_IDENTIFIER_AUTHORITY { + Value: [0, 0, 0, 0, 0, 22], + }; + unsafe { + let owner = sd.owner(); + if IsValidSid(*owner) != 0 + && (*GetSidIdentifierAuthority(*owner)).Value == SAMBA_UNMAPPED.Value + { + return Ok(()); + } + } + + let token = ThreadToken::new()?; + + let mut privileges: PRIVILEGE_SET = unsafe { std::mem::zeroed() }; + let mut granted_access: u32 = 0; + let mut privileges_length = std::mem::size_of::() as u32; + let mut result = 0; + + let mut mapping = GENERIC_MAPPING { + GenericRead: FILE_GENERIC_READ, + GenericWrite: FILE_GENERIC_WRITE, + GenericExecute: FILE_GENERIC_EXECUTE, + GenericAll: FILE_ALL_ACCESS, + }; + + unsafe { MapGenericMask(&mut mode, &mut mapping) }; + + if unsafe { + AccessCheck( + *sd.descriptor(), + *token.as_handle(), + mode, + &mut mapping, + &mut privileges, + &mut privileges_length, + &mut granted_access, + &mut result, + ) + } != 0 + { + if result == 0 { + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Permission Denied", + )) + } else { + Ok(()) + } + } else { + Err(io::Error::last_os_error()) + } + } + + pub fn access(p: &Path, mode: AccessMode) -> io::Result<()> { + let mut imode = 0; + + if mode.contains(AccessMode::READ) { + imode |= FILE_GENERIC_READ; + } + + if mode.contains(AccessMode::WRITE) { + imode |= FILE_GENERIC_WRITE; + } + + if mode.contains(AccessMode::EXECUTE) { + imode |= FILE_GENERIC_EXECUTE; + } + + if imode == 0 { + if p.exists() { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::NotFound, "Not Found")) + } + } else { + eaccess(p, imode) + } + } + + fn chown(p: &Path, sd: SecurityDescriptor) -> io::Result<()> { + let path = std::fs::canonicalize(p)?; + let pathos = path.as_os_str(); + let mut pathw = Vec::with_capacity(pathos.len() + 1); + pathw.extend(pathos.encode_wide()); + pathw.push(0); + + let mut owner = std::ptr::null_mut(); + let mut group = std::ptr::null_mut(); + let mut dacl = std::ptr::null(); + + let mut si = OBJECT_SECURITY_INFORMATION::default(); + if unsafe { IsValidSid(sd.owner) } != 0 { + si |= OWNER_SECURITY_INFORMATION; + owner = sd.owner; + } + + if unsafe { IsValidSid(sd.group) } != 0 { + si |= GROUP_SECURITY_INFORMATION; + group = sd.group; + } + + if unsafe { IsValidAcl(sd.dacl) } != 0 { + si |= DACL_SECURITY_INFORMATION; + if !sd.is_acl_inherited() { + si |= PROTECTED_DACL_SECURITY_INFORMATION; + } + dacl = sd.dacl as *const _; + } + + let err = unsafe { + SetNamedSecurityInfoW( + pathw.as_ptr(), + SE_FILE_OBJECT, + si, + owner, + group, + dacl, + std::ptr::null(), + ) + }; + + if err == ERROR_SUCCESS { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { + let sd = SecurityDescriptor::for_path(from)?; + chown(to, sd)?; + + let meta = std::fs::metadata(from)?; + let perms = meta.permissions(); + + std::fs::set_permissions(to, perms)?; + + Ok(()) + } +} + +// Licensed under MIT from faccess except for `copy_metadata` +#[cfg(not(any(unix, windows)))] +mod imp { + use super::*; + + pub fn access(p: &Path, mode: AccessMode) -> io::Result<()> { + if mode.contains(AccessMode::WRITE) { + if std::fs::metadata(p)?.permissions().readonly() { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Path is read only", + )); + } else { + return Ok(()); + } + } + + if p.exists() { + Ok(()) + } else { + Err(io::Error::new(io::ErrorKind::NotFound, "Path not found")) + } + } + + pub fn copy_metadata(from: &path, to: &Path) -> io::Result<()> { + let meta = std::fs::metadata(from)?; + let perms = meta.permissions(); + std::fs::set_permissions(to, perms)?; + + Ok(()) + } +} + +pub fn readonly(p: &Path) -> bool { + match imp::access(p, AccessMode::WRITE) { + Ok(_) => false, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => true, + } +} + +pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { + imp::copy_metadata(from, to) +} diff --git a/helix-stdx/src/lib.rs b/helix-stdx/src/lib.rs index 68fe3ec37..19602c205 100644 --- a/helix-stdx/src/lib.rs +++ b/helix-stdx/src/lib.rs @@ -1,3 +1,4 @@ pub mod env; +pub mod faccess; pub mod path; pub mod rope; diff --git a/helix-stdx/src/path.rs b/helix-stdx/src/path.rs index 1dc4d0b24..968596a70 100644 --- a/helix-stdx/src/path.rs +++ b/helix-stdx/src/path.rs @@ -2,21 +2,30 @@ pub use etcetera::home_dir; use std::{ borrow::Cow, - path::{Component, Path, PathBuf}, + ffi::OsString, + path::{Component, Path, PathBuf, MAIN_SEPARATOR_STR}, }; use crate::env::current_working_dir; /// Replaces users home directory from `path` with tilde `~` if the directory /// is available, otherwise returns the path unchanged. -pub fn fold_home_dir(path: &Path) -> PathBuf { +pub fn fold_home_dir<'a, P>(path: P) -> Cow<'a, Path> +where + P: Into>, +{ + let path = path.into(); if let Ok(home) = home_dir() { if let Ok(stripped) = path.strip_prefix(&home) { - return PathBuf::from("~").join(stripped); + let mut path = OsString::with_capacity(2 + stripped.as_os_str().len()); + path.push("~"); + path.push(MAIN_SEPARATOR_STR); + path.push(stripped); + return Cow::Owned(PathBuf::from(path)); } } - path.to_path_buf() + path } /// Expands tilde `~` into users home directory if available, otherwise returns the path @@ -125,18 +134,21 @@ pub fn canonicalize(path: impl AsRef) -> PathBuf { normalize(path) } -pub fn get_relative_path(path: impl AsRef) -> PathBuf { - let path = PathBuf::from(path.as_ref()); - let path = if path.is_absolute() { +pub fn get_relative_path<'a, P>(path: P) -> Cow<'a, Path> +where + P: Into>, +{ + let path = path.into(); + if path.is_absolute() { let cwdir = normalize(current_working_dir()); - normalize(&path) - .strip_prefix(cwdir) - .map(PathBuf::from) - .unwrap_or(path) - } else { - path - }; - fold_home_dir(&path) + if let Ok(stripped) = normalize(&path).strip_prefix(cwdir) { + return Cow::Owned(PathBuf::from(stripped)); + } + + return fold_home_dir(path); + } + + path } /// Returns a truncated filepath where the basepart of the path is reduced to the first @@ -170,21 +182,20 @@ pub fn get_relative_path(path: impl AsRef) -> PathBuf { /// pub fn get_truncated_path(path: impl AsRef) -> PathBuf { let cwd = current_working_dir(); - let path = path - .as_ref() - .strip_prefix(cwd) - .unwrap_or_else(|_| path.as_ref()); + let path = path.as_ref(); + let path = path.strip_prefix(cwd).unwrap_or(path); let file = path.file_name().unwrap_or_default(); let base = path.parent().unwrap_or_else(|| Path::new("")); - let mut ret = PathBuf::new(); + let mut ret = PathBuf::with_capacity(file.len()); + // A char can't be directly pushed to a PathBuf + let mut first_char_buffer = String::new(); for d in base { - ret.push( - d.to_string_lossy() - .chars() - .next() - .unwrap_or_default() - .to_string(), - ); + let Some(first_char) = d.to_string_lossy().chars().next() else { + break; + }; + first_char_buffer.push(first_char); + ret.push(&first_char_buffer); + first_char_buffer.clear(); } ret.push(file); ret diff --git a/helix-stdx/src/rope.rs b/helix-stdx/src/rope.rs index 7e2549f5a..2695555e3 100644 --- a/helix-stdx/src/rope.rs +++ b/helix-stdx/src/rope.rs @@ -3,6 +3,7 @@ use std::ops::{Bound, RangeBounds}; pub use regex_cursor::engines::meta::{Builder as RegexBuilder, Regex}; pub use regex_cursor::regex_automata::util::syntax::Config; use regex_cursor::{Input as RegexInput, RopeyCursor}; +use ropey::str_utils::byte_to_char_idx; use ropey::RopeSlice; pub trait RopeSliceExt<'a>: Sized { @@ -16,6 +17,23 @@ pub trait RopeSliceExt<'a>: Sized { fn regex_input_at>(self, char_range: R) -> RegexInput>; fn first_non_whitespace_char(self) -> Option; fn last_non_whitespace_char(self) -> Option; + /// returns the char idx of `byte_idx`, if `byte_idx` is a char boundary + /// this function behaves the same as `byte_to_char` but if `byte_idx` is + /// not a valid char boundary (so within a char) this will return the next + /// char index. + /// + /// # Example + /// + /// ``` + /// # use ropey::RopeSlice; + /// # use helix_stdx::rope::RopeSliceExt; + /// let text = RopeSlice::from("😆"); + /// for i in 1..text.len_bytes() { + /// assert_eq!(text.byte_to_char(i), 0); + /// assert_eq!(text.byte_to_next_char(i), 1); + /// } + /// ``` + fn byte_to_next_char(self, byte_idx: usize) -> usize; } impl<'a> RopeSliceExt<'a> for RopeSlice<'a> { @@ -75,4 +93,48 @@ impl<'a> RopeSliceExt<'a> for RopeSlice<'a> { .position(|ch| !ch.is_whitespace()) .map(|pos| self.len_chars() - pos - 1) } + + /// returns the char idx of `byte_idx`, if `byte_idx` is + /// a char boundary this function behaves the same as `byte_to_char` + fn byte_to_next_char(self, mut byte_idx: usize) -> usize { + let (chunk, chunk_byte_off, chunk_char_off, _) = self.chunk_at_byte(byte_idx); + byte_idx -= chunk_byte_off; + let is_char_boundary = + is_utf8_char_boundary(chunk.as_bytes().get(byte_idx).copied().unwrap_or(0)); + chunk_char_off + byte_to_char_idx(chunk, byte_idx) + !is_char_boundary as usize + } +} + +// copied from std +#[inline] +const fn is_utf8_char_boundary(b: u8) -> bool { + // This is bit magic equivalent to: b < 128 || b >= 192 + (b as i8) >= -0x40 +} + +#[cfg(test)] +mod tests { + use ropey::RopeSlice; + + use crate::rope::RopeSliceExt; + + #[test] + fn next_char_at_byte() { + for i in 0..=6 { + assert_eq!(RopeSlice::from("foobar").byte_to_next_char(i), i); + } + for char_idx in 0..10 { + let len = "😆".len(); + assert_eq!( + RopeSlice::from("😆😆😆😆😆😆😆😆😆😆").byte_to_next_char(char_idx * len), + char_idx + ); + for i in 1..=len { + assert_eq!( + RopeSlice::from("😆😆😆😆😆😆😆😆😆😆").byte_to_next_char(char_idx * len + i), + char_idx + 1 + ); + } + } + } } diff --git a/helix-term/Cargo.toml b/helix-term/Cargo.toml index accde567e..99f966d31 100644 --- a/helix-term/Cargo.toml +++ b/helix-term/Cargo.toml @@ -14,7 +14,7 @@ homepage.workspace = true [features] default = ["git"] -unicode-lines = ["helix-core/unicode-lines"] +unicode-lines = ["helix-core/unicode-lines", "helix-view/unicode-lines"] integration = ["helix-event/integration_test"] git = ["helix-vcs/git"] @@ -41,7 +41,7 @@ crossterm = { version = "0.27", features = ["event-stream"] } signal-hook = "0.3" tokio-stream = "0.1" futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false } -arc-swap = { version = "1.7.0" } +arc-swap = { version = "1.7.1" } termini = "1" # Logging @@ -53,13 +53,13 @@ log = "0.4" nucleo.workspace = true ignore = "0.4" # markdown doc rendering -pulldown-cmark = { version = "0.10", default-features = false } +pulldown-cmark = { version = "0.11", default-features = false } # file type detection content_inspector = "0.2.4" # opening URLs -open = "5.0.1" -url = "2.5.0" +open = "5.1.4" +url = "2.5.2" # config toml = "0.8" @@ -73,7 +73,7 @@ grep-searcher = "0.1.13" [target.'cfg(not(windows))'.dependencies] # https://github.com/vorner/signal-hook/issues/100 signal-hook-tokio = { version = "0.3", features = ["futures-v0_3"] } -libc = "0.2.153" +libc = "0.2.155" [target.'cfg(target_os = "macos")'.dependencies] crossterm = { version = "0.27", features = ["event-stream", "use-dev-tty"] } @@ -83,5 +83,5 @@ helix-loader = { path = "../helix-loader" } [dev-dependencies] smallvec = "1.13" -indoc = "2.0.4" +indoc = "2.0.5" tempfile = "3.10.1" diff --git a/helix-term/src/application.rs b/helix-term/src/application.rs index 809393c7f..9adc764cc 100644 --- a/helix-term/src/application.rs +++ b/helix-term/src/application.rs @@ -4,12 +4,12 @@ use helix_core::{diagnostic::Severity, pos_at_coords, syntax, Selection}; use helix_lsp::{ lsp::{self, notification::Notification}, util::lsp_range_to_range, - LspProgressMap, + LanguageServerId, LspProgressMap, }; use helix_stdx::path::get_relative_path; use helix_view::{ align_view, - document::DocumentSavedEventResult, + document::{DocumentOpenError, DocumentSavedEventResult}, editor::{ConfigEvent, EditorEvent}, graphics::Rect, theme, @@ -186,9 +186,15 @@ impl Application { Some(Layout::Horizontal) => Action::HorizontalSplit, None => Action::Load, }; - let doc_id = editor - .open(&file, action) - .context(format!("open '{}'", file.to_string_lossy()))?; + let doc_id = match editor.open(&file, action) { + // Ignore irregular files during application init. + Err(DocumentOpenError::IrregularFile) => { + nr_of_files -= 1; + continue; + } + Err(err) => return Err(anyhow::anyhow!(err)), + Ok(doc_id) => doc_id, + }; // with Action::Load all documents have the same view // NOTE: this isn't necessarily true anymore. If // `--vsplit` or `--hsplit` are used, the file which is @@ -199,15 +205,21 @@ impl Application { doc.set_selection(view_id, pos); } } - editor.set_status(format!( - "Loaded {} file{}.", - nr_of_files, - if nr_of_files == 1 { "" } else { "s" } // avoid "Loaded 1 files." grammo - )); - // align the view to center after all files are loaded, - // does not affect views without pos since it is at the top - let (view, doc) = current!(editor); - align_view(doc, view, Align::Center); + + // if all files were invalid, replace with empty buffer + if nr_of_files == 0 { + editor.new_file(Action::VerticalSplit); + } else { + editor.set_status(format!( + "Loaded {} file{}.", + nr_of_files, + if nr_of_files == 1 { "" } else { "s" } // avoid "Loaded 1 files." grammo + )); + // align the view to center after all files are loaded, + // does not affect views without pos since it is at the top + let (view, doc) = current!(editor); + align_view(doc, view, Align::Center); + } } else { editor.new_file(Action::VerticalSplit); } @@ -655,7 +667,7 @@ impl Application { pub async fn handle_language_server_message( &mut self, call: helix_lsp::Call, - server_id: usize, + server_id: LanguageServerId, ) { use helix_lsp::{Call, MethodCall, Notification}; @@ -724,7 +736,7 @@ impl Application { } Notification::PublishDiagnostics(mut params) => { let path = match params.uri.to_file_path() { - Ok(path) => helix_stdx::path::normalize(&path), + Ok(path) => helix_stdx::path::normalize(path), Err(_) => { log::error!("Unsupported file URI: {}", params.uri); return; @@ -1030,12 +1042,7 @@ impl Application { Ok(json!(result)) } Ok(MethodCall::RegisterCapability(params)) => { - if let Some(client) = self - .editor - .language_servers - .iter_clients() - .find(|client| client.id() == server_id) - { + if let Some(client) = self.editor.language_servers.get_by_id(server_id) { for reg in params.registrations { match reg.method.as_str() { lsp::notification::DidChangeWatchedFiles::METHOD => { diff --git a/helix-term/src/commands.rs b/helix-term/src/commands.rs index 7cc9cf6dd..12b75cc16 100644 --- a/helix-term/src/commands.rs +++ b/helix-term/src/commands.rs @@ -3,20 +3,30 @@ pub(crate) mod lsp; pub(crate) mod typed; pub use dap::*; -use helix_stdx::rope::{self, RopeSliceExt}; -use helix_vcs::Hunk; +use helix_event::status; +use helix_stdx::{ + path::expand_tilde, + rope::{self, RopeSliceExt}, +}; +use helix_vcs::{FileChange, Hunk}; pub use lsp::*; -use tui::widgets::Row; +use tui::{ + text::Span, + widgets::{Cell, Row}, +}; pub use typed::*; use helix_core::{ - char_idx_at_visual_offset, comment, + char_idx_at_visual_offset, + chars::char_is_word, + comment, doc_formatter::TextFormat, - encoding, find_workspace, graphemes, + encoding, find_workspace, + graphemes::{self, next_grapheme_boundary, RevRopeGraphemes}, history::UndoKind, increment, indent, indent::IndentStyle, - line_ending::{get_line_ending_of_str, line_end_char_index, str_is_line_ending}, + line_ending::{get_line_ending_of_str, line_end_char_index}, match_brackets, movement::{self, move_vertically_visual, Direction}, object, pos_at_coords, @@ -24,12 +34,11 @@ use helix_core::{ search::{self, CharMatcher}, selection, shellwords, surround, syntax::{BlockCommentToken, LanguageServerFeature}, - text_annotations::TextAnnotations, + text_annotations::{Overlay, TextAnnotations}, textobject, - tree_sitter::Node, unicode::width::UnicodeWidthChar, visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes, - RopeReader, RopeSlice, Selection, SmallVec, Tendril, Transaction, + RopeReader, RopeSlice, Selection, SmallVec, Syntax, Tendril, Transaction, }; use helix_view::{ document::{FormatterError, Mode, SCRATCH_BUFFER_NAME}, @@ -37,6 +46,7 @@ use helix_view::{ info::Info, input::KeyEvent, keyboard::KeyCode, + theme::Style, tree, view::View, Document, DocumentId, Editor, ViewId, @@ -52,12 +62,14 @@ use crate::{ filter_picker_entry, job::Callback, keymap::ReverseKeymap, - ui::{self, overlay::overlaid, Picker, Popup, Prompt, PromptEvent}, + ui::{self, menu::Item, overlay::overlaid, Picker, Popup, Prompt, PromptEvent}, }; use crate::job::{self, Jobs}; use std::{ + cmp::Ordering, collections::{HashMap, HashSet}, + error::Error, fmt, future::Future, io::Read, @@ -131,6 +143,17 @@ impl<'a> Context<'a> { pub fn count(&self) -> usize { self.count.map_or(1, |v| v.get()) } + + /// Waits on all pending jobs, and then tries to flush all pending write + /// operations for all documents. + pub fn block_try_flush_writes(&mut self) -> anyhow::Result<()> { + compositor::Context { + editor: self.editor, + jobs: self.jobs, + scroll: None, + } + .block_try_flush_writes() + } } #[inline] @@ -300,6 +323,8 @@ impl MappableCommand { extend_line, "Select current line, if already selected, extend to another line based on the anchor", extend_line_below, "Select current line, if already selected, extend to next line", extend_line_above, "Select current line, if already selected, extend to previous line", + select_line_above, "Select current line, if already selected, extend or shrink line above based on the anchor", + select_line_below, "Select current line, if already selected, extend or shrink line below based on the anchor", extend_to_line_bounds, "Extend selection to line bounds", shrink_to_line_bounds, "Shrink selection to line bounds", delete_selection, "Delete selection", @@ -313,12 +338,13 @@ impl MappableCommand { append_mode, "Append after selection", command_mode, "Enter command mode", file_picker, "Open file picker", - file_picker_in_current_buffer_directory, "Open file picker at current buffers's directory", + file_picker_in_current_buffer_directory, "Open file picker at current buffer's directory", file_picker_in_current_directory, "Open file picker at current working directory", code_action, "Perform code action", buffer_picker, "Open buffer picker", jumplist_picker, "Open jumplist picker", symbol_picker, "Open symbol picker", + changed_file_picker, "Open changed file picker", select_references_to_symbol_under_cursor, "Select symbol references", workspace_symbol_picker, "Open workspace symbol picker", diagnostics_picker, "Open diagnostic picker", @@ -424,8 +450,10 @@ impl MappableCommand { reverse_selection_contents, "Reverse selections contents", expand_selection, "Expand selection to parent syntax node", shrink_selection, "Shrink selection to previously expanded syntax node", - select_next_sibling, "Select next sibling in syntax tree", - select_prev_sibling, "Select previous sibling in syntax tree", + select_next_sibling, "Select next sibling in the syntax tree", + select_prev_sibling, "Select previous sibling the in syntax tree", + select_all_siblings, "Select all siblings of the current node", + select_all_children, "Select all children of the current node", jump_forward, "Jump forward on jumplist", jump_backward, "Jump backward on jumplist", save_selection, "Save current selection to jumplist", @@ -472,6 +500,8 @@ impl MappableCommand { goto_prev_comment, "Goto previous comment", goto_next_test, "Goto next test", goto_prev_test, "Goto previous test", + goto_next_entry, "Goto next pairing", + goto_prev_entry, "Goto previous pairing", goto_next_paragraph, "Goto next paragraph", goto_prev_paragraph, "Goto previous paragraph", dap_launch, "Launch debug target", @@ -502,6 +532,8 @@ impl MappableCommand { record_macro, "Record macro", replay_macro, "Replay macro", command_palette, "Open command palette", + goto_word, "Jump to a two-character label", + extend_to_word, "Extend to a two-character label", ); } @@ -617,6 +649,7 @@ fn move_impl(cx: &mut Context, move_fn: MoveFn, dir: Direction, behaviour: Movem &mut annotations, ) }); + drop(annotations); doc.set_selection(view.id, selection); } @@ -780,28 +813,29 @@ fn goto_line_start(cx: &mut Context) { } fn goto_next_buffer(cx: &mut Context) { - goto_buffer(cx.editor, Direction::Forward); + goto_buffer(cx.editor, Direction::Forward, cx.count()); } fn goto_previous_buffer(cx: &mut Context) { - goto_buffer(cx.editor, Direction::Backward); + goto_buffer(cx.editor, Direction::Backward, cx.count()); } -fn goto_buffer(editor: &mut Editor, direction: Direction) { +fn goto_buffer(editor: &mut Editor, direction: Direction, count: usize) { let current = view!(editor).doc; let id = match direction { Direction::Forward => { let iter = editor.documents.keys(); - let mut iter = iter.skip_while(|id| *id != ¤t); - iter.next(); // skip current item - iter.next().or_else(|| editor.documents.keys().next()) + // skip 'count' times past current buffer + iter.cycle().skip_while(|id| *id != ¤t).nth(count) } Direction::Backward => { let iter = editor.documents.keys(); - let mut iter = iter.rev().skip_while(|id| *id != ¤t); - iter.next(); // skip current item - iter.next().or_else(|| editor.documents.keys().next_back()) + // skip 'count' times past current buffer + iter.rev() + .cycle() + .skip_while(|id| *id != ¤t) + .nth(count) } } .unwrap(); @@ -1182,25 +1216,51 @@ fn goto_file_impl(cx: &mut Context, action: Action) { let primary = selections.primary(); // Checks whether there is only one selection with a width of 1 if selections.len() == 1 && primary.len() == 1 { - let count = cx.count(); - let text_slice = text.slice(..); - // In this case it selects the WORD under the cursor - let current_word = textobject::textobject_word( - text_slice, - primary, - textobject::TextObject::Inside, - count, - true, - ); - // Trims some surrounding chars so that the actual file is opened. - let surrounding_chars: &[_] = &['\'', '"', '(', ')']; paths.clear(); - paths.push( - current_word - .fragment(text_slice) - .trim_matches(surrounding_chars) - .to_string(), - ); + + let is_valid_path_char = |c: &char| { + #[cfg(target_os = "windows")] + let valid_chars = &[ + '@', '/', '\\', '.', '-', '_', '+', '#', '$', '%', '{', '}', '[', ']', ':', '!', + '~', '=', + ]; + #[cfg(not(target_os = "windows"))] + let valid_chars = &['@', '/', '.', '-', '_', '+', '#', '$', '%', '~', '=', ':']; + + valid_chars.contains(c) || c.is_alphabetic() || c.is_numeric() + }; + + let cursor_pos = primary.cursor(text.slice(..)); + let pre_cursor_pos = cursor_pos.saturating_sub(1); + let post_cursor_pos = cursor_pos + 1; + let start_pos = if is_valid_path_char(&text.char(cursor_pos)) { + cursor_pos + } else if is_valid_path_char(&text.char(pre_cursor_pos)) { + pre_cursor_pos + } else { + post_cursor_pos + }; + + let prefix_len = text + .chars_at(start_pos) + .reversed() + .take_while(is_valid_path_char) + .count(); + + let postfix_len = text + .chars_at(start_pos) + .take_while(is_valid_path_char) + .count(); + + let path: Cow = text + .slice((start_pos - prefix_len)..(start_pos + postfix_len)) + .into(); + log::debug!("Goto file path: {}", path); + + match expand_tilde(PathBuf::from(path.as_ref())).to_str() { + Some(path) => paths.push(path.to_string()), + None => cx.editor.set_error("Couldn't get string out of path."), + }; } for sel in paths { @@ -1210,7 +1270,8 @@ fn goto_file_impl(cx: &mut Context, action: Action) { } if let Ok(url) = Url::parse(p) { - return open_url(cx, url, action); + open_url(cx, url, action); + continue; } let path = &rel_path.join(p); @@ -1547,19 +1608,11 @@ fn replace(cx: &mut Context) { if let Some(ch) = ch { let transaction = Transaction::change_by_selection(doc.text(), selection, |range| { if !range.is_empty() { - let text: String = + let text: Tendril = RopeGraphemes::new(doc.text().slice(range.from()..range.to())) - .map(|g| { - let cow: Cow = g.into(); - if str_is_line_ending(&cow) { - cow - } else { - ch.into() - } - }) + .map(|_g| ch) .collect(); - - (range.from(), range.to(), Some(text.into())) + (range.from(), range.to(), Some(text)) } else { // No change. (range.from(), range.to(), None) @@ -1637,7 +1690,7 @@ pub fn scroll(cx: &mut Context, offset: usize, direction: Direction, sync_cursor let doc_text = doc.text().slice(..); let viewport = view.inner_area(doc); let text_fmt = doc.text_format(viewport.width, None); - let mut annotations = view.text_annotations(doc, None); + let mut annotations = view.text_annotations(&*doc, None); (view.offset.anchor, view.offset.vertical_offset) = char_idx_at_visual_offset( doc_text, view.offset.anchor, @@ -1715,6 +1768,7 @@ pub fn scroll(cx: &mut Context, offset: usize, direction: Direction, sync_cursor let mut sel = doc.selection(view.id).clone(); let idx = sel.primary_index(); sel = sel.replace(idx, prim_sel); + drop(annotations); doc.set_selection(view.id, sel); } @@ -2033,6 +2087,11 @@ fn searcher(cx: &mut Context, direction: Direction) { let config = cx.editor.config(); let scrolloff = config.scrolloff; let wrap_around = config.search.wrap_around; + let movement = if cx.editor.mode() == Mode::Select { + Movement::Extend + } else { + Movement::Move + }; // TODO: could probably share with select_on_matches? let completions = search_completions(cx, Some(reg)); @@ -2057,7 +2116,7 @@ fn searcher(cx: &mut Context, direction: Direction) { search_impl( cx.editor, ®ex, - Movement::Move, + movement, direction, scrolloff, wrap_around, @@ -2437,7 +2496,6 @@ fn extend_line_below(cx: &mut Context) { fn extend_line_above(cx: &mut Context) { extend_line_impl(cx, Extend::Above); } - fn extend_line_impl(cx: &mut Context, extend: Extend) { let count = cx.count(); let (view, doc) = current!(cx.editor); @@ -2476,6 +2534,59 @@ fn extend_line_impl(cx: &mut Context, extend: Extend) { doc.set_selection(view.id, selection); } +fn select_line_below(cx: &mut Context) { + select_line_impl(cx, Extend::Below); +} +fn select_line_above(cx: &mut Context) { + select_line_impl(cx, Extend::Above); +} +fn select_line_impl(cx: &mut Context, extend: Extend) { + let mut count = cx.count(); + let (view, doc) = current!(cx.editor); + let text = doc.text(); + let saturating_add = |a: usize, b: usize| (a + b).min(text.len_lines()); + let selection = doc.selection(view.id).clone().transform(|range| { + let (start_line, end_line) = range.line_range(text.slice(..)); + let start = text.line_to_char(start_line); + let end = text.line_to_char(saturating_add(end_line, 1)); + let direction = range.direction(); + + // Extending to line bounds is counted as one step + if range.from() != start || range.to() != end { + count = count.saturating_sub(1) + } + let (anchor_line, head_line) = match (&extend, direction) { + (Extend::Above, Direction::Forward) => (start_line, end_line.saturating_sub(count)), + (Extend::Above, Direction::Backward) => (end_line, start_line.saturating_sub(count)), + (Extend::Below, Direction::Forward) => (start_line, saturating_add(end_line, count)), + (Extend::Below, Direction::Backward) => (end_line, saturating_add(start_line, count)), + }; + let (anchor, head) = match anchor_line.cmp(&head_line) { + Ordering::Less => ( + text.line_to_char(anchor_line), + text.line_to_char(saturating_add(head_line, 1)), + ), + Ordering::Equal => match extend { + Extend::Above => ( + text.line_to_char(saturating_add(anchor_line, 1)), + text.line_to_char(head_line), + ), + Extend::Below => ( + text.line_to_char(head_line), + text.line_to_char(saturating_add(anchor_line, 1)), + ), + }, + + Ordering::Greater => ( + text.line_to_char(saturating_add(anchor_line, 1)), + text.line_to_char(head_line), + ), + }; + Range::new(anchor, head) + }); + + doc.set_selection(view.id, selection); +} fn extend_to_line_bounds(cx: &mut Context) { let (view, doc) = current!(cx.editor); @@ -2550,14 +2661,19 @@ fn selection_is_linewise(selection: &Selection, text: &Rope) -> bool { }) } -fn delete_selection_impl(cx: &mut Context, op: Operation) { +enum YankAction { + Yank, + NoYank, +} + +fn delete_selection_impl(cx: &mut Context, op: Operation, yank: YankAction) { let (view, doc) = current!(cx.editor); let selection = doc.selection(view.id); let only_whole_lines = selection_is_linewise(selection, doc.text()); - if cx.register != Some('_') { - // first yank the selection + if cx.register != Some('_') && matches!(yank, YankAction::Yank) { + // yank the selection let text = doc.text().slice(..); let values: Vec = selection.fragments(text).map(Cow::into_owned).collect(); let reg_name = cx.register.unwrap_or('"'); @@ -2565,9 +2681,9 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) { cx.editor.set_error(err.to_string()); return; } - }; + } - // then delete + // delete the selection let transaction = Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to())); doc.apply(&transaction, view.id); @@ -2633,21 +2749,19 @@ fn delete_by_selection_insert_mode( } fn delete_selection(cx: &mut Context) { - delete_selection_impl(cx, Operation::Delete); + delete_selection_impl(cx, Operation::Delete, YankAction::Yank); } fn delete_selection_noyank(cx: &mut Context) { - cx.register = Some('_'); - delete_selection_impl(cx, Operation::Delete); + delete_selection_impl(cx, Operation::Delete, YankAction::NoYank); } fn change_selection(cx: &mut Context) { - delete_selection_impl(cx, Operation::Change); + delete_selection_impl(cx, Operation::Change, YankAction::Yank); } fn change_selection_noyank(cx: &mut Context) { - cx.register = Some('_'); - delete_selection_impl(cx, Operation::Change); + delete_selection_impl(cx, Operation::Change, YankAction::NoYank); } fn collapse_selection(cx: &mut Context) { @@ -2913,6 +3027,7 @@ fn jumplist_picker(cx: &mut Context) { .flat_map(|(view, _)| { view.jumps .iter() + .rev() .map(|(doc_id, selection)| new_meta(view, *doc_id, selection.clone())) }) .collect(), @@ -2935,6 +3050,94 @@ fn jumplist_picker(cx: &mut Context) { cx.push_layer(Box::new(overlaid(picker))); } +fn changed_file_picker(cx: &mut Context) { + pub struct FileChangeData { + cwd: PathBuf, + style_untracked: Style, + style_modified: Style, + style_conflict: Style, + style_deleted: Style, + style_renamed: Style, + } + + impl Item for FileChange { + type Data = FileChangeData; + + fn format(&self, data: &Self::Data) -> Row { + let process_path = |path: &PathBuf| { + path.strip_prefix(&data.cwd) + .unwrap_or(path) + .display() + .to_string() + }; + + let (sign, style, content) = match self { + Self::Untracked { path } => ("[+]", data.style_untracked, process_path(path)), + Self::Modified { path } => ("[~]", data.style_modified, process_path(path)), + Self::Conflict { path } => ("[x]", data.style_conflict, process_path(path)), + Self::Deleted { path } => ("[-]", data.style_deleted, process_path(path)), + Self::Renamed { from_path, to_path } => ( + "[>]", + data.style_renamed, + format!("{} -> {}", process_path(from_path), process_path(to_path)), + ), + }; + + Row::new([Cell::from(Span::styled(sign, style)), Cell::from(content)]) + } + } + + let cwd = helix_stdx::env::current_working_dir(); + if !cwd.exists() { + cx.editor + .set_error("Current working directory does not exist"); + return; + } + + let added = cx.editor.theme.get("diff.plus"); + let modified = cx.editor.theme.get("diff.delta"); + let conflict = cx.editor.theme.get("diff.delta.conflict"); + let deleted = cx.editor.theme.get("diff.minus"); + let renamed = cx.editor.theme.get("diff.delta.moved"); + + let picker = Picker::new( + Vec::new(), + FileChangeData { + cwd: cwd.clone(), + style_untracked: added, + style_modified: modified, + style_conflict: conflict, + style_deleted: deleted, + style_renamed: renamed, + }, + |cx, meta: &FileChange, action| { + let path_to_open = meta.path(); + if let Err(e) = cx.editor.open(path_to_open, action) { + let err = if let Some(err) = e.source() { + format!("{}", err) + } else { + format!("unable to open \"{}\"", path_to_open.display()) + }; + cx.editor.set_error(err); + } + }, + ) + .with_preview(|_editor, meta| Some((meta.path().to_path_buf().into(), None))); + let injector = picker.injector(); + + cx.editor + .diff_providers + .clone() + .for_each_changed_file(cwd, move |change| match change { + Ok(change) => injector.push(change).is_ok(), + Err(err) => { + status::report_blocking(err); + true + } + }); + cx.push_layer(Box::new(overlaid(picker))); +} + impl ui::menu::Item for MappableCommand { type Data = ReverseKeymap; @@ -3386,48 +3589,55 @@ fn goto_last_diag(cx: &mut Context) { } fn goto_next_diag(cx: &mut Context) { - let (view, doc) = current!(cx.editor); + let motion = move |editor: &mut Editor| { + let (view, doc) = current!(editor); - let cursor_pos = doc - .selection(view.id) - .primary() - .cursor(doc.text().slice(..)); + let cursor_pos = doc + .selection(view.id) + .primary() + .cursor(doc.text().slice(..)); - let diag = doc - .diagnostics() - .iter() - .find(|diag| diag.range.start > cursor_pos) - .or_else(|| doc.diagnostics().first()); + let diag = doc + .diagnostics() + .iter() + .find(|diag| diag.range.start > cursor_pos) + .or_else(|| doc.diagnostics().first()); - let selection = match diag { - Some(diag) => Selection::single(diag.range.start, diag.range.end), - None => return, + let selection = match diag { + Some(diag) => Selection::single(diag.range.start, diag.range.end), + None => return, + }; + doc.set_selection(view.id, selection); }; - doc.set_selection(view.id, selection); + + cx.editor.apply_motion(motion); } fn goto_prev_diag(cx: &mut Context) { - let (view, doc) = current!(cx.editor); + let motion = move |editor: &mut Editor| { + let (view, doc) = current!(editor); - let cursor_pos = doc - .selection(view.id) - .primary() - .cursor(doc.text().slice(..)); + let cursor_pos = doc + .selection(view.id) + .primary() + .cursor(doc.text().slice(..)); - let diag = doc - .diagnostics() - .iter() - .rev() - .find(|diag| diag.range.start < cursor_pos) - .or_else(|| doc.diagnostics().last()); - - let selection = match diag { - // NOTE: the selection is reversed because we're jumping to the - // previous diagnostic. - Some(diag) => Selection::single(diag.range.end, diag.range.start), - None => return, + let diag = doc + .diagnostics() + .iter() + .rev() + .find(|diag| diag.range.start < cursor_pos) + .or_else(|| doc.diagnostics().last()); + + let selection = match diag { + // NOTE: the selection is reversed because we're jumping to the + // previous diagnostic. + Some(diag) => Selection::single(diag.range.end, diag.range.start), + None => return, + }; + doc.set_selection(view.id, selection); }; - doc.set_selection(view.id, selection); + cx.editor.apply_motion(motion) } fn goto_first_change(cx: &mut Context) { @@ -4715,18 +4925,17 @@ fn shrink_selection(cx: &mut Context) { cx.editor.apply_motion(motion); } -fn select_sibling_impl(cx: &mut Context, sibling_fn: &'static F) +fn select_sibling_impl(cx: &mut Context, sibling_fn: F) where - F: Fn(Node) -> Option, + F: Fn(&helix_core::Syntax, RopeSlice, Selection) -> Selection + 'static, { - let motion = |editor: &mut Editor| { + let motion = move |editor: &mut Editor| { let (view, doc) = current!(editor); if let Some(syntax) = doc.syntax() { let text = doc.text().slice(..); let current_selection = doc.selection(view.id); - let selection = - object::select_sibling(syntax, text, current_selection.clone(), sibling_fn); + let selection = sibling_fn(syntax, text, current_selection.clone()); doc.set_selection(view.id, selection); } }; @@ -4734,11 +4943,11 @@ where } fn select_next_sibling(cx: &mut Context) { - select_sibling_impl(cx, &|node| Node::next_sibling(&node)) + select_sibling_impl(cx, object::select_next_sibling) } fn select_prev_sibling(cx: &mut Context) { - select_sibling_impl(cx, &|node| Node::prev_sibling(&node)) + select_sibling_impl(cx, object::select_prev_sibling) } fn move_node_bound_impl(cx: &mut Context, dir: Direction, movement: Movement) { @@ -4780,6 +4989,36 @@ pub fn extend_parent_node_start(cx: &mut Context) { move_node_bound_impl(cx, Direction::Backward, Movement::Extend) } +fn select_all_impl(editor: &mut Editor, select_fn: F) +where + F: Fn(&Syntax, RopeSlice, Selection) -> Selection, +{ + let (view, doc) = current!(editor); + + if let Some(syntax) = doc.syntax() { + let text = doc.text().slice(..); + let current_selection = doc.selection(view.id); + let selection = select_fn(syntax, text, current_selection.clone()); + doc.set_selection(view.id, selection); + } +} + +fn select_all_siblings(cx: &mut Context) { + let motion = |editor: &mut Editor| { + select_all_impl(editor, object::select_all_siblings); + }; + + cx.editor.apply_motion(motion); +} + +fn select_all_children(cx: &mut Context) { + let motion = |editor: &mut Editor| { + select_all_impl(editor, object::select_all_children); + }; + + cx.editor.apply_motion(motion); +} + fn match_brackets(cx: &mut Context) { let (view, doc) = current!(cx.editor); let is_select = cx.editor.mode == Mode::Select; @@ -5110,6 +5349,14 @@ fn goto_prev_test(cx: &mut Context) { goto_ts_object_impl(cx, "test", Direction::Backward) } +fn goto_next_entry(cx: &mut Context) { + goto_ts_object_impl(cx, "entry", Direction::Forward) +} + +fn goto_prev_entry(cx: &mut Context) { + goto_ts_object_impl(cx, "entry", Direction::Backward) +} + fn select_textobject_around(cx: &mut Context) { select_textobject(cx, textobject::TextObject::Around); } @@ -5174,15 +5421,25 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) { 'a' => textobject_treesitter("parameter", range), 'c' => textobject_treesitter("comment", range), 'T' => textobject_treesitter("test", range), + 'e' => textobject_treesitter("entry", range), 'p' => textobject::textobject_paragraph(text, range, objtype, count), 'm' => textobject::textobject_pair_surround_closest( - text, range, objtype, count, + doc.syntax(), + text, + range, + objtype, + count, ), 'g' => textobject_change(range), // TODO: cancel new ranges if inconsistent surround matches across lines - ch if !ch.is_ascii_alphanumeric() => { - textobject::textobject_pair_surround(text, range, objtype, ch, count) - } + ch if !ch.is_ascii_alphanumeric() => textobject::textobject_pair_surround( + doc.syntax(), + text, + range, + objtype, + ch, + count, + ), _ => range, } }); @@ -5206,7 +5463,9 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) { ("a", "Argument/parameter (tree-sitter)"), ("c", "Comment (tree-sitter)"), ("T", "Test (tree-sitter)"), - ("m", "Closest surrounding pair"), + ("e", "Data structure entry (tree-sitter)"), + ("m", "Closest surrounding pair (tree-sitter)"), + ("g", "Change"), (" ", "... or any character acting as a pair"), ]; @@ -5219,7 +5478,7 @@ fn surround_add(cx: &mut Context) { // surround_len is the number of new characters being added. let (open, close, surround_len) = match event.char() { Some(ch) => { - let (o, c) = surround::get_pair(ch); + let (o, c) = match_brackets::get_pair(ch); let mut open = Tendril::new(); open.push(o); let mut close = Tendril::new(); @@ -5270,13 +5529,14 @@ fn surround_replace(cx: &mut Context) { let text = doc.text().slice(..); let selection = doc.selection(view.id); - let change_pos = match surround::get_surround_pos(text, selection, surround_ch, count) { - Ok(c) => c, - Err(err) => { - cx.editor.set_error(err.to_string()); - return; - } - }; + let change_pos = + match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) { + Ok(c) => c, + Err(err) => { + cx.editor.set_error(err.to_string()); + return; + } + }; let selection = selection.clone(); let ranges: SmallVec<[Range; 1]> = change_pos.iter().map(|&p| Range::point(p)).collect(); @@ -5291,13 +5551,22 @@ fn surround_replace(cx: &mut Context) { Some(to) => to, None => return doc.set_selection(view.id, selection), }; - let (open, close) = surround::get_pair(to); + let (open, close) = match_brackets::get_pair(to); + + // the changeset has to be sorted to allow nested surrounds + let mut sorted_pos: Vec<(usize, char)> = Vec::new(); + for p in change_pos.chunks(2) { + sorted_pos.push((p[0], open)); + sorted_pos.push((p[1], close)); + } + sorted_pos.sort_unstable(); + let transaction = Transaction::change( doc.text(), - change_pos.iter().enumerate().map(|(i, &pos)| { + sorted_pos.iter().map(|&pos| { let mut t = Tendril::new(); - t.push(if i % 2 == 0 { open } else { close }); - (pos, pos + 1, Some(t)) + t.push(pos.1); + (pos.0, pos.0 + 1, Some(t)) }), ); doc.set_selection(view.id, selection); @@ -5319,14 +5588,15 @@ fn surround_delete(cx: &mut Context) { let text = doc.text().slice(..); let selection = doc.selection(view.id); - let change_pos = match surround::get_surround_pos(text, selection, surround_ch, count) { - Ok(c) => c, - Err(err) => { - cx.editor.set_error(err.to_string()); - return; - } - }; - + let mut change_pos = + match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) { + Ok(c) => c, + Err(err) => { + cx.editor.set_error(err.to_string()); + return; + } + }; + change_pos.sort_unstable(); // the changeset has to be sorted to allow nested surrounds let transaction = Transaction::change(doc.text(), change_pos.into_iter().map(|p| (p, p + 1, None))); doc.apply(&transaction, view.id); @@ -5382,16 +5652,9 @@ fn shell_keep_pipe(cx: &mut Context) { for (i, range) in selection.ranges().iter().enumerate() { let fragment = range.slice(text); - let (_output, success) = match shell_impl(shell, input, Some(fragment.into())) { - Ok(result) => result, - Err(err) => { - cx.editor.set_error(err.to_string()); - return; - } - }; - - // if the process exits successfully, keep the selection - if success { + if let Err(err) = shell_impl(shell, input, Some(fragment.into())) { + log::debug!("Shell command failed: {}", err); + } else { ranges.push(*range); if i >= old_index && index.is_none() { index = Some(ranges.len() - 1); @@ -5410,7 +5673,7 @@ fn shell_keep_pipe(cx: &mut Context) { ); } -fn shell_impl(shell: &[String], cmd: &str, input: Option) -> anyhow::Result<(Tendril, bool)> { +fn shell_impl(shell: &[String], cmd: &str, input: Option) -> anyhow::Result { tokio::task::block_in_place(|| helix_lsp::block_on(shell_impl_async(shell, cmd, input))) } @@ -5418,7 +5681,7 @@ async fn shell_impl_async( shell: &[String], cmd: &str, input: Option, -) -> anyhow::Result<(Tendril, bool)> { +) -> anyhow::Result { use std::process::Stdio; use tokio::process::Command; ensure!(!shell.is_empty(), "No shell set"); @@ -5481,7 +5744,7 @@ async fn shell_impl_async( let str = std::str::from_utf8(&output.stdout) .map_err(|_| anyhow!("Process did not output valid UTF-8"))?; let tendril = Tendril::from(str); - Ok((tendril, output.status.success())) + Ok(tendril) } fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) { @@ -5502,14 +5765,14 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) { let mut shell_output: Option = None; let mut offset = 0isize; for range in selection.ranges() { - let (output, success) = if let Some(output) = shell_output.as_ref() { - (output.clone(), true) + let output = if let Some(output) = shell_output.as_ref() { + output.clone() } else { let fragment = range.slice(text); match shell_impl(shell, cmd, pipe.then(|| fragment.into())) { Ok(result) => { if !pipe { - shell_output = Some(result.0.clone()); + shell_output = Some(result.clone()); } result } @@ -5520,11 +5783,6 @@ fn shell(cx: &mut compositor::Context, cmd: &str, behavior: &ShellBehavior) { } }; - if !success { - cx.editor.set_error("Command failed"); - return; - } - let output_len = output.chars().count(); let (from, to, deleted_len) = match behavior { @@ -5584,7 +5842,10 @@ fn shell_prompt(cx: &mut Context, prompt: Cow<'static, str>, behavior: ShellBeha fn suspend(_cx: &mut Context) { #[cfg(not(windows))] - signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP).unwrap(); + { + _cx.block_try_flush_writes().ok(); + signal_hook::low_level::raise(signal_hook::consts::signal::SIGTSTP).unwrap(); + } } fn add_newline_above(cx: &mut Context) { @@ -5765,3 +6026,188 @@ fn replay_macro(cx: &mut Context) { cx.editor.macro_replaying.pop(); })); } + +fn goto_word(cx: &mut Context) { + jump_to_word(cx, Movement::Move) +} + +fn extend_to_word(cx: &mut Context) { + jump_to_word(cx, Movement::Extend) +} + +fn jump_to_label(cx: &mut Context, labels: Vec, behaviour: Movement) { + let doc = doc!(cx.editor); + let alphabet = &cx.editor.config().jump_label_alphabet; + if labels.is_empty() { + return; + } + let alphabet_char = |i| { + let mut res = Tendril::new(); + res.push(alphabet[i]); + res + }; + + // Add label for each jump candidate to the View as virtual text. + let text = doc.text().slice(..); + let mut overlays: Vec<_> = labels + .iter() + .enumerate() + .flat_map(|(i, range)| { + [ + Overlay::new(range.from(), alphabet_char(i / alphabet.len())), + Overlay::new( + graphemes::next_grapheme_boundary(text, range.from()), + alphabet_char(i % alphabet.len()), + ), + ] + }) + .collect(); + overlays.sort_unstable_by_key(|overlay| overlay.char_idx); + let (view, doc) = current!(cx.editor); + doc.set_jump_labels(view.id, overlays); + + // Accept two characters matching a visible label. Jump to the candidate + // for that label if it exists. + let primary_selection = doc.selection(view.id).primary(); + let view = view.id; + let doc = doc.id(); + cx.on_next_key(move |cx, event| { + let alphabet = &cx.editor.config().jump_label_alphabet; + let Some(i) = event + .char() + .and_then(|ch| alphabet.iter().position(|&it| it == ch)) + else { + doc_mut!(cx.editor, &doc).remove_jump_labels(view); + return; + }; + let outer = i * alphabet.len(); + // Bail if the given character cannot be a jump label. + if outer > labels.len() { + doc_mut!(cx.editor, &doc).remove_jump_labels(view); + return; + } + cx.on_next_key(move |cx, event| { + doc_mut!(cx.editor, &doc).remove_jump_labels(view); + let alphabet = &cx.editor.config().jump_label_alphabet; + let Some(inner) = event + .char() + .and_then(|ch| alphabet.iter().position(|&it| it == ch)) + else { + return; + }; + if let Some(mut range) = labels.get(outer + inner).copied() { + range = if behaviour == Movement::Extend { + let anchor = if range.anchor < range.head { + let from = primary_selection.from(); + if range.anchor < from { + range.anchor + } else { + from + } + } else { + let to = primary_selection.to(); + if range.anchor > to { + range.anchor + } else { + to + } + }; + Range::new(anchor, range.head) + } else { + range.with_direction(Direction::Forward) + }; + doc_mut!(cx.editor, &doc).set_selection(view, range.into()); + } + }); + }); +} + +fn jump_to_word(cx: &mut Context, behaviour: Movement) { + // Calculate the jump candidates: ranges for any visible words with two or + // more characters. + let alphabet = &cx.editor.config().jump_label_alphabet; + let jump_label_limit = alphabet.len() * alphabet.len(); + let mut words = Vec::with_capacity(jump_label_limit); + let (view, doc) = current_ref!(cx.editor); + let text = doc.text().slice(..); + + // This is not necessarily exact if there is virtual text like soft wrap. + // It's ok though because the extra jump labels will not be rendered. + let start = text.line_to_char(text.char_to_line(view.offset.anchor)); + let end = text.line_to_char(view.estimate_last_doc_line(doc) + 1); + + let primary_selection = doc.selection(view.id).primary(); + let cursor = primary_selection.cursor(text); + let mut cursor_fwd = Range::point(cursor); + let mut cursor_rev = Range::point(cursor); + if text.get_char(cursor).is_some_and(|c| !c.is_whitespace()) { + let cursor_word_end = movement::move_next_word_end(text, cursor_fwd, 1); + // single grapheme words need a specical case + if cursor_word_end.anchor == cursor { + cursor_fwd = cursor_word_end; + } + let cursor_word_start = movement::move_prev_word_start(text, cursor_rev, 1); + if cursor_word_start.anchor == next_grapheme_boundary(text, cursor) { + cursor_rev = cursor_word_start; + } + } + 'outer: loop { + let mut changed = false; + while cursor_fwd.head < end { + cursor_fwd = movement::move_next_word_end(text, cursor_fwd, 1); + // The cursor is on a word that is atleast two graphemes long and + // madeup of word characters. The latter condition is needed because + // move_next_word_end simply treats a sequence of characters from + // the same char class as a word so `=<` would also count as a word. + let add_label = RevRopeGraphemes::new(text.slice(..cursor_fwd.head)) + .take(2) + .take_while(|g| g.chars().all(char_is_word)) + .count() + == 2; + if !add_label { + continue; + } + changed = true; + // skip any leading whitespace + cursor_fwd.anchor += text + .chars_at(cursor_fwd.anchor) + .take_while(|&c| !char_is_word(c)) + .count(); + words.push(cursor_fwd); + if words.len() == jump_label_limit { + break 'outer; + } + break; + } + while cursor_rev.head > start { + cursor_rev = movement::move_prev_word_start(text, cursor_rev, 1); + // The cursor is on a word that is atleast two graphemes long and + // madeup of word characters. The latter condition is needed because + // move_prev_word_start simply treats a sequence of characters from + // the same char class as a word so `=<` would also count as a word. + let add_label = RopeGraphemes::new(text.slice(cursor_rev.head..)) + .take(2) + .take_while(|g| g.chars().all(char_is_word)) + .count() + == 2; + if !add_label { + continue; + } + changed = true; + cursor_rev.anchor -= text + .chars_at(cursor_rev.anchor) + .reversed() + .take_while(|&c| !char_is_word(c)) + .count(); + words.push(cursor_rev); + if words.len() == jump_label_limit { + break 'outer; + } + break; + } + if !changed { + break; + } + } + jump_to_label(cx, words, behaviour) +} diff --git a/helix-term/src/commands/dap.rs b/helix-term/src/commands/dap.rs index d62b0a4e5..0e50377ac 100644 --- a/helix-term/src/commands/dap.rs +++ b/helix-term/src/commands/dap.rs @@ -8,7 +8,7 @@ use dap::{StackFrame, Thread, ThreadStates}; use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate}; use helix_dap::{self as dap, Client}; use helix_lsp::block_on; -use helix_view::{editor::Breakpoint, graphics::Margin}; +use helix_view::editor::Breakpoint; use serde_json::{to_value, Value}; use tokio_stream::wrappers::UnboundedReceiverStream; @@ -172,9 +172,9 @@ pub fn dap_start_impl( let mut args: HashMap<&str, Value> = HashMap::new(); - if let Some(params) = params { - for (k, t) in &template.args { - let mut value = t.clone(); + for (k, t) in &template.args { + let mut value = t.clone(); + if let Some(ref params) = params { for (i, x) in params.iter().enumerate() { let mut param = x.to_string(); if let Some(DebugConfigCompletion::Advanced(cfg)) = template.completion.get(i) { @@ -198,22 +198,22 @@ pub fn dap_start_impl( DebugArgumentValue::Boolean(_) => value, }; } + } - match value { - DebugArgumentValue::String(string) => { - if let Ok(integer) = string.parse::() { - args.insert(k, to_value(integer).unwrap()); - } else { - args.insert(k, to_value(string).unwrap()); - } - } - DebugArgumentValue::Array(arr) => { - args.insert(k, to_value(arr).unwrap()); - } - DebugArgumentValue::Boolean(bool) => { - args.insert(k, to_value(bool).unwrap()); + match value { + DebugArgumentValue::String(string) => { + if let Ok(integer) = string.parse::() { + args.insert(k, to_value(integer).unwrap()); + } else { + args.insert(k, to_value(string).unwrap()); } } + DebugArgumentValue::Array(arr) => { + args.insert(k, to_value(arr).unwrap()); + } + DebugArgumentValue::Boolean(bool) => { + args.insert(k, to_value(bool).unwrap()); + } } } @@ -272,17 +272,23 @@ pub fn dap_launch(cx: &mut Context) { templates, (), |cx, template, _action| { - let completions = template.completion.clone(); - let name = template.name.clone(); - let callback = Box::pin(async move { - let call: Callback = - Callback::EditorCompositor(Box::new(move |_editor, compositor| { - let prompt = debug_parameter_prompt(completions, name, Vec::new()); - compositor.push(Box::new(prompt)); - })); - Ok(call) - }); - cx.jobs.callback(callback); + if template.completion.is_empty() { + if let Err(err) = dap_start_impl(cx, Some(&template.name), None, None) { + cx.editor.set_error(err.to_string()); + } + } else { + let completions = template.completion.clone(); + let name = template.name.clone(); + let callback = Box::pin(async move { + let call: Callback = + Callback::EditorCompositor(Box::new(move |_editor, compositor| { + let prompt = debug_parameter_prompt(completions, name, Vec::new()); + compositor.push(Box::new(prompt)); + })); + Ok(call) + }); + cx.jobs.callback(callback); + } }, )))); } @@ -581,12 +587,7 @@ pub fn dap_variables(cx: &mut Context) { } let contents = Text::from(tui::text::Text::from(variables)); - let margin = if cx.editor.popup_border() { - Margin::all(1) - } else { - Margin::none() - }; - let popup = Popup::new("dap-variables", contents).margin(margin); + let popup = Popup::new("dap-variables", contents); cx.replace_or_push_layer("dap-variables", popup); } diff --git a/helix-term/src/commands/lsp.rs b/helix-term/src/commands/lsp.rs index b1c3fc64d..2098cebd0 100644 --- a/helix-term/src/commands/lsp.rs +++ b/helix-term/src/commands/lsp.rs @@ -1,4 +1,4 @@ -use futures_util::{stream::FuturesUnordered, FutureExt}; +use futures_util::{stream::FuturesOrdered, FutureExt}; use helix_lsp::{ block_on, lsp::{ @@ -6,7 +6,7 @@ use helix_lsp::{ NumberOrString, }, util::{diagnostic_to_lsp_diagnostic, lsp_range_to_range, range_to_lsp_range}, - Client, OffsetEncoding, + Client, LanguageServerId, OffsetEncoding, }; use tokio_stream::StreamExt; use tui::{ @@ -24,7 +24,6 @@ use helix_stdx::path; use helix_view::{ document::{DocumentInlayHints, DocumentInlayHintsId}, editor::Action, - graphics::Margin, handlers::lsp::SignatureHelpInvoked, theme::Style, Document, View, @@ -269,7 +268,7 @@ enum DiagnosticsFormat { fn diag_picker( cx: &Context, - diagnostics: BTreeMap>, + diagnostics: BTreeMap>, format: DiagnosticsFormat, ) -> Picker { // TODO: drop current_path comparison and instead use workspace: bool flag? @@ -344,7 +343,7 @@ pub fn symbol_picker(cx: &mut Context) { let mut seen_language_servers = HashSet::new(); - let mut futures: FuturesUnordered<_> = doc + let mut futures: FuturesOrdered<_> = doc .language_servers_with_feature(LanguageServerFeature::DocumentSymbols) .filter(|ls| seen_language_servers.insert(ls.id())) .map(|language_server| { @@ -419,7 +418,7 @@ pub fn workspace_symbol_picker(cx: &mut Context) { let get_symbols = move |pattern: String, editor: &mut Editor| { let doc = doc!(editor); let mut seen_language_servers = HashSet::new(); - let mut futures: FuturesUnordered<_> = doc + let mut futures: FuturesOrdered<_> = doc .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols) .filter(|ls| seen_language_servers.insert(ls.id())) .map(|language_server| { @@ -500,7 +499,7 @@ pub fn workspace_diagnostics_picker(cx: &mut Context) { struct CodeActionOrCommandItem { lsp_item: lsp::CodeActionOrCommand, - language_server_id: usize, + language_server_id: LanguageServerId, } impl ui::menu::Item for CodeActionOrCommandItem { @@ -577,7 +576,7 @@ pub fn code_action(cx: &mut Context) { let mut seen_language_servers = HashSet::new(); - let mut futures: FuturesUnordered<_> = doc + let mut futures: FuturesOrdered<_> = doc .language_servers_with_feature(LanguageServerFeature::CodeAction) .filter(|ls| seen_language_servers.insert(ls.id())) // TODO this should probably already been filtered in something like "language_servers_with_feature" @@ -736,15 +735,7 @@ pub fn code_action(cx: &mut Context) { }); picker.move_down(); // pre-select the first item - let margin = if editor.menu_border() { - Margin::vertical(1) - } else { - Margin::none() - }; - - let popup = Popup::new("code-action", picker) - .with_scrollbar(false) - .margin(margin); + let popup = Popup::new("code-action", picker).with_scrollbar(false); compositor.replace_or_push("code-action", popup); }; @@ -760,7 +751,11 @@ impl ui::menu::Item for lsp::Command { } } -pub fn execute_lsp_command(editor: &mut Editor, language_server_id: usize, cmd: lsp::Command) { +pub fn execute_lsp_command( + editor: &mut Editor, + language_server_id: LanguageServerId, + cmd: lsp::Command, +) { // the command is executed on the server and communicated back // to the client asynchronously using workspace edits let future = match editor @@ -1094,11 +1089,12 @@ pub fn rename_symbol(cx: &mut Context) { fn create_rename_prompt( editor: &Editor, prefill: String, - language_server_id: Option, + history_register: Option, + language_server_id: Option, ) -> Box { let prompt = ui::Prompt::new( "rename-to:".into(), - None, + history_register, ui::completers::none, move |cx: &mut compositor::Context, input: &str, event: PromptEvent| { if event != PromptEvent::Validate { @@ -1135,6 +1131,7 @@ pub fn rename_symbol(cx: &mut Context) { } let (view, doc) = current_ref!(cx.editor); + let history_register = cx.register; if doc .language_servers_with_feature(LanguageServerFeature::RenameSymbol) @@ -1177,14 +1174,14 @@ pub fn rename_symbol(cx: &mut Context) { } }; - let prompt = create_rename_prompt(editor, prefill, Some(ls_id)); + let prompt = create_rename_prompt(editor, prefill, history_register, Some(ls_id)); compositor.push(prompt); }, ); } else { let prefill = get_prefill_from_word_boundary(cx.editor); - let prompt = create_rename_prompt(cx.editor, prefill, None); + let prompt = create_rename_prompt(cx.editor, prefill, history_register, None); cx.push_layer(prompt); } } @@ -1375,11 +1372,11 @@ fn compute_inlay_hints_for_view( view_id, DocumentInlayHints { id: new_doc_inlay_hints_id, - type_inlay_hints: type_inlay_hints.into(), - parameter_inlay_hints: parameter_inlay_hints.into(), - other_inlay_hints: other_inlay_hints.into(), - padding_before_inlay_hints: padding_before_inlay_hints.into(), - padding_after_inlay_hints: padding_after_inlay_hints.into(), + type_inlay_hints, + parameter_inlay_hints, + other_inlay_hints, + padding_before_inlay_hints, + padding_after_inlay_hints, }, ); doc.inlay_hints_oudated = false; diff --git a/helix-term/src/commands/typed.rs b/helix-term/src/commands/typed.rs index 3d7ea3fc8..ab12fab10 100644 --- a/helix-term/src/commands/typed.rs +++ b/helix-term/src/commands/typed.rs @@ -1,4 +1,5 @@ use std::fmt::Write; +use std::io::BufReader; use std::ops::Deref; use crate::job::Job; @@ -7,9 +8,9 @@ use super::*; use helix_core::fuzzy::fuzzy_match; use helix_core::indent::MAX_INDENT; -use helix_core::{encoding, line_ending, shellwords::Shellwords}; -use helix_view::document::DEFAULT_LANGUAGE_NAME; -use helix_view::editor::{Action, CloseError, ConfigEvent}; +use helix_core::{line_ending, shellwords::Shellwords}; +use helix_view::document::{read_to_string, DEFAULT_LANGUAGE_NAME}; +use helix_view::editor::{CloseError, ConfigEvent}; use serde_json::Value; use ui::completers::{self, Completer}; @@ -163,9 +164,10 @@ fn buffer_close_by_ids_impl( cx.editor.switch(*first, Action::Replace); } bail!( - "{} unsaved buffer(s) remaining: {:?}", + "{} unsaved buffer{} remaining: {:?}", modified_names.len(), - modified_names + if modified_names.len() == 1 { "" } else { "s" }, + modified_names, ); } @@ -309,7 +311,7 @@ fn buffer_next( return Ok(()); } - goto_buffer(cx.editor, Direction::Forward); + goto_buffer(cx.editor, Direction::Forward, 1); Ok(()) } @@ -322,7 +324,7 @@ fn buffer_previous( return Ok(()); } - goto_buffer(cx.editor, Direction::Backward); + goto_buffer(cx.editor, Direction::Backward, 1); Ok(()) } @@ -657,9 +659,10 @@ pub(super) fn buffers_remaining_impl(editor: &mut Editor) -> anyhow::Result<()> editor.switch(*first, Action::Replace); } bail!( - "{} unsaved buffer(s) remaining: {:?}", + "{} unsaved buffer{} remaining: {:?}", modified_names.len(), - modified_names + if modified_names.len() == 1 { "" } else { "s" }, + modified_names, ); } Ok(()) @@ -1318,7 +1321,11 @@ fn reload_all( // Ensure that the view is synced with the document's history. view.sync_changes(doc); - doc.reload(view, &cx.editor.diff_providers)?; + if let Err(error) = doc.reload(view, &cx.editor.diff_providers) { + cx.editor.set_error(format!("{}", error)); + continue; + } + if let Some(path) = doc.path() { cx.editor .language_servers @@ -1490,6 +1497,8 @@ fn lsp_stop( for doc in cx.editor.documents_mut() { if let Some(client) = doc.remove_language_server_by_name(ls_name) { doc.clear_diagnostics(Some(client.id())); + doc.reset_all_inlay_hints(); + doc.inlay_hints_oudated = true; } } } @@ -2257,7 +2266,7 @@ fn run_shell_command( let args = args.join(" "); let callback = async move { - let (output, success) = shell_impl_async(&shell, &args, None).await?; + let output = shell_impl_async(&shell, &args, None).await?; let call: job::Callback = Callback::EditorCompositor(Box::new( move |editor: &mut Editor, compositor: &mut Compositor| { if !output.is_empty() { @@ -2270,11 +2279,7 @@ fn run_shell_command( )); compositor.replace_or_push("shell", popup); } - if success { - editor.set_status("Command succeeded"); - } else { - editor.set_error("Command failed"); - } + editor.set_status("Command succeeded"); }, )); Ok(call) @@ -2304,37 +2309,36 @@ fn reset_diff_change( let diff = handle.load(); let doc_text = doc.text().slice(..); - let line = doc.selection(view.id).primary().cursor_line(doc_text); - - let Some(hunk_idx) = diff.hunk_at(line as u32, true) else { - bail!("There is no change at the cursor") - }; - let hunk = diff.nth_hunk(hunk_idx); let diff_base = diff.diff_base(); - let before_start = diff_base.line_to_char(hunk.before.start as usize); - let before_end = diff_base.line_to_char(hunk.before.end as usize); - let text: Tendril = diff - .diff_base() - .slice(before_start..before_end) - .chunks() - .collect(); - let anchor = doc_text.line_to_char(hunk.after.start as usize); + let mut changes = 0; + let transaction = Transaction::change( doc.text(), - [( - anchor, - doc_text.line_to_char(hunk.after.end as usize), - (!text.is_empty()).then_some(text), - )] - .into_iter(), + diff.hunks_intersecting_line_ranges(doc.selection(view.id).line_ranges(doc_text)) + .map(|hunk| { + changes += 1; + let start = diff_base.line_to_char(hunk.before.start as usize); + let end = diff_base.line_to_char(hunk.before.end as usize); + let text: Tendril = diff_base.slice(start..end).chunks().collect(); + ( + doc_text.line_to_char(hunk.after.start as usize), + doc_text.line_to_char(hunk.after.end as usize), + (!text.is_empty()).then_some(text), + ) + }), ); + if changes == 0 { + bail!("There are no changes under any selection"); + } + drop(diff); // make borrow check happy doc.apply(&transaction, view.id); - // select inserted text - let text_len = before_end - before_start; - doc.set_selection(view.id, Selection::single(anchor, anchor + text_len)); doc.append_changes_to_history(view); view.ensure_cursor_in_view(doc, scrolloff); + cx.editor.set_status(format!( + "Reset {changes} change{}", + if changes == 1 { "" } else { "s" } + )); Ok(()) } @@ -2414,6 +2418,79 @@ fn move_buffer( Ok(()) } +fn yank_diagnostic( + cx: &mut compositor::Context, + args: &[Cow], + event: PromptEvent, +) -> anyhow::Result<()> { + if event != PromptEvent::Validate { + return Ok(()); + } + + let reg = match args.first() { + Some(s) => { + ensure!(s.chars().count() == 1, format!("Invalid register {s}")); + s.chars().next().unwrap() + } + None => '+', + }; + + let (view, doc) = current_ref!(cx.editor); + let primary = doc.selection(view.id).primary(); + + // Look only for diagnostics that intersect with the primary selection + let diag: Vec<_> = doc + .diagnostics() + .iter() + .filter(|d| primary.overlaps(&helix_core::Range::new(d.range.start, d.range.end))) + .map(|d| d.message.clone()) + .collect(); + let n = diag.len(); + if n == 0 { + bail!("No diagnostics under primary selection"); + } + + cx.editor.registers.write(reg, diag)?; + cx.editor.set_status(format!( + "Yanked {n} diagnostic{} to register {reg}", + if n == 1 { "" } else { "s" } + )); + Ok(()) +} + +fn read(cx: &mut compositor::Context, args: &[Cow], event: PromptEvent) -> anyhow::Result<()> { + if event != PromptEvent::Validate { + return Ok(()); + } + + let scrolloff = cx.editor.config().scrolloff; + let (view, doc) = current!(cx.editor); + + ensure!(!args.is_empty(), "file name is expected"); + ensure!(args.len() == 1, "only the file name is expected"); + + let filename = args.get(0).unwrap(); + let path = PathBuf::from(filename.to_string()); + ensure!( + path.exists() && path.is_file(), + "path is not a file: {:?}", + path + ); + + let file = std::fs::File::open(path).map_err(|err| anyhow!("error opening file: {}", err))?; + let mut reader = BufReader::new(file); + let (contents, _, _) = read_to_string(&mut reader, Some(doc.encoding())) + .map_err(|err| anyhow!("error reading file: {}", err))?; + let contents = Tendril::from(contents); + let selection = doc.selection(view.id); + let transaction = Transaction::insert(doc.text(), selection, contents); + doc.apply(&transaction, view.id); + doc.append_changes_to_history(view); + view.ensure_cursor_in_view(doc, scrolloff); + + Ok(()) +} + pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ TypableCommand { name: "quit", @@ -3005,7 +3082,7 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ aliases: &[], doc: "Clear given register. If no argument is provided, clear all registers.", fun: clear_register, - signature: CommandSignature::none(), + signature: CommandSignature::all(completers::register), }, TypableCommand { name: "redraw", @@ -3021,6 +3098,20 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[ fun: move_buffer, signature: CommandSignature::positional(&[completers::filename]), }, + TypableCommand { + name: "yank-diagnostic", + aliases: &[], + doc: "Yank diagnostic(s) under primary cursor to register, or clipboard by default", + fun: yank_diagnostic, + signature: CommandSignature::all(completers::register), + }, + TypableCommand { + name: "read", + aliases: &["r"], + doc: "Load a file into buffer", + fun: read, + signature: CommandSignature::positional(&[completers::filename]), + }, ]; pub static TYPABLE_COMMAND_MAP: Lazy> = diff --git a/helix-term/src/handlers.rs b/helix-term/src/handlers.rs index ef5369f85..fc9273137 100644 --- a/helix-term/src/handlers.rs +++ b/helix-term/src/handlers.rs @@ -5,14 +5,15 @@ use helix_event::AsyncHook; use crate::config::Config; use crate::events; +use crate::handlers::auto_save::AutoSaveHandler; use crate::handlers::completion::CompletionHandler; use crate::handlers::signature_help::SignatureHelpHandler; pub use completion::trigger_auto_completion; -pub use helix_view::handlers::lsp::SignatureHelpInvoked; pub use helix_view::handlers::Handlers; -mod completion; +mod auto_save; +pub mod completion; mod signature_help; pub fn setup(config: Arc>) -> Handlers { @@ -20,11 +21,16 @@ pub fn setup(config: Arc>) -> Handlers { let completions = CompletionHandler::new(config).spawn(); let signature_hints = SignatureHelpHandler::new().spawn(); + let auto_save = AutoSaveHandler::new().spawn(); + let handlers = Handlers { completions, signature_hints, + auto_save, }; + completion::register_hooks(&handlers); signature_help::register_hooks(&handlers); + auto_save::register_hooks(&handlers); handlers } diff --git a/helix-term/src/handlers/auto_save.rs b/helix-term/src/handlers/auto_save.rs new file mode 100644 index 000000000..4e154df80 --- /dev/null +++ b/helix-term/src/handlers/auto_save.rs @@ -0,0 +1,117 @@ +use std::{ + sync::{ + atomic::{self, AtomicBool}, + Arc, + }, + time::Duration, +}; + +use anyhow::Ok; +use arc_swap::access::Access; + +use helix_event::{register_hook, send_blocking}; +use helix_view::{ + document::Mode, + events::DocumentDidChange, + handlers::{AutoSaveEvent, Handlers}, + Editor, +}; +use tokio::time::Instant; + +use crate::{ + commands, compositor, + events::OnModeSwitch, + job::{self, Jobs}, +}; + +#[derive(Debug)] +pub(super) struct AutoSaveHandler { + save_pending: Arc, +} + +impl AutoSaveHandler { + pub fn new() -> AutoSaveHandler { + AutoSaveHandler { + save_pending: Default::default(), + } + } +} + +impl helix_event::AsyncHook for AutoSaveHandler { + type Event = AutoSaveEvent; + + fn handle_event( + &mut self, + event: Self::Event, + existing_debounce: Option, + ) -> Option { + match event { + Self::Event::DocumentChanged { save_after } => { + Some(Instant::now() + Duration::from_millis(save_after)) + } + Self::Event::LeftInsertMode => { + if existing_debounce.is_some() { + // If the change happened more recently than the debounce, let the + // debounce run down before saving. + existing_debounce + } else { + // Otherwise if there is a save pending, save immediately. + if self.save_pending.load(atomic::Ordering::Relaxed) { + self.finish_debounce(); + } + None + } + } + } + } + + fn finish_debounce(&mut self) { + let save_pending = self.save_pending.clone(); + job::dispatch_blocking(move |editor, _| { + if editor.mode() == Mode::Insert { + // Avoid saving while in insert mode since this mixes up + // the modification indicator and prevents future saves. + save_pending.store(true, atomic::Ordering::Relaxed); + } else { + request_auto_save(editor); + save_pending.store(false, atomic::Ordering::Relaxed); + } + }) + } +} + +fn request_auto_save(editor: &mut Editor) { + let context = &mut compositor::Context { + editor, + scroll: Some(0), + jobs: &mut Jobs::new(), + }; + + if let Err(e) = commands::typed::write_all_impl(context, false, false) { + context.editor.set_error(format!("{}", e)); + } +} + +pub(super) fn register_hooks(handlers: &Handlers) { + let tx = handlers.auto_save.clone(); + register_hook!(move |event: &mut DocumentDidChange<'_>| { + let config = event.doc.config.load(); + if config.auto_save.after_delay.enable { + send_blocking( + &tx, + AutoSaveEvent::DocumentChanged { + save_after: config.auto_save.after_delay.timeout, + }, + ); + } + Ok(()) + }); + + let tx = handlers.auto_save.clone(); + register_hook!(move |event: &mut OnModeSwitch<'_, '_>| { + if event.old_mode == Mode::Insert { + send_blocking(&tx, AutoSaveEvent::LeftInsertMode) + } + Ok(()) + }); +} diff --git a/helix-term/src/handlers/completion.rs b/helix-term/src/handlers/completion.rs index 491ca5638..68956c85f 100644 --- a/helix-term/src/handlers/completion.rs +++ b/helix-term/src/handlers/completion.rs @@ -30,6 +30,8 @@ use crate::ui::lsp::SignatureHelp; use crate::ui::{self, CompletionItem, Popup}; use super::Handlers; +pub use resolve::ResolveHandler; +mod resolve; #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum TriggerKind { @@ -251,7 +253,7 @@ fn request_completion( .into_iter() .map(|item| CompletionItem { item, - language_server_id, + provider: language_server_id, resolved: false, }) .collect(); diff --git a/helix-term/src/handlers/completion/resolve.rs b/helix-term/src/handlers/completion/resolve.rs new file mode 100644 index 000000000..0b2c90672 --- /dev/null +++ b/helix-term/src/handlers/completion/resolve.rs @@ -0,0 +1,175 @@ +use std::sync::Arc; + +use helix_lsp::lsp; +use tokio::sync::mpsc::Sender; +use tokio::time::{Duration, Instant}; + +use helix_event::{send_blocking, AsyncHook, CancelRx}; +use helix_view::Editor; + +use crate::handlers::completion::CompletionItem; +use crate::job; + +/// A hook for resolving incomplete completion items. +/// +/// From the [LSP spec](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion): +/// +/// > If computing full completion items is expensive, servers can additionally provide a +/// > handler for the completion item resolve request. ... +/// > A typical use case is for example: the `textDocument/completion` request doesn't fill +/// > in the `documentation` property for returned completion items since it is expensive +/// > to compute. When the item is selected in the user interface then a +/// > 'completionItem/resolve' request is sent with the selected completion item as a parameter. +/// > The returned completion item should have the documentation property filled in. +pub struct ResolveHandler { + last_request: Option>, + resolver: Sender, +} + +impl ResolveHandler { + pub fn new() -> ResolveHandler { + ResolveHandler { + last_request: None, + resolver: ResolveTimeout { + next_request: None, + in_flight: None, + } + .spawn(), + } + } + + pub fn ensure_item_resolved(&mut self, editor: &mut Editor, item: &mut CompletionItem) { + if item.resolved { + return; + } + // We consider an item to be fully resolved if it has non-empty, none-`None` details, + // docs and additional text-edits. Ideally we could use `is_some` instead of this + // check but some language servers send values like `Some([])` for additional text + // edits although the items need to be resolved. This is probably a consequence of + // how `null` works in the JavaScript world. + let is_resolved = item + .item + .documentation + .as_ref() + .is_some_and(|docs| match docs { + lsp::Documentation::String(text) => !text.is_empty(), + lsp::Documentation::MarkupContent(markup) => !markup.value.is_empty(), + }) + && item + .item + .detail + .as_ref() + .is_some_and(|detail| !detail.is_empty()) + && item + .item + .additional_text_edits + .as_ref() + .is_some_and(|edits| !edits.is_empty()); + if is_resolved { + item.resolved = true; + return; + } + if self.last_request.as_deref().is_some_and(|it| it == item) { + return; + } + let Some(ls) = editor.language_servers.get_by_id(item.provider).cloned() else { + item.resolved = true; + return; + }; + if matches!( + ls.capabilities().completion_provider, + Some(lsp::CompletionOptions { + resolve_provider: Some(true), + .. + }) + ) { + let item = Arc::new(item.clone()); + self.last_request = Some(item.clone()); + send_blocking(&self.resolver, ResolveRequest { item, ls }) + } else { + item.resolved = true; + } + } +} + +struct ResolveRequest { + item: Arc, + ls: Arc, +} + +#[derive(Default)] +struct ResolveTimeout { + next_request: Option, + in_flight: Option<(helix_event::CancelTx, Arc)>, +} + +impl AsyncHook for ResolveTimeout { + type Event = ResolveRequest; + + fn handle_event( + &mut self, + request: Self::Event, + timeout: Option, + ) -> Option { + if self + .next_request + .as_ref() + .is_some_and(|old_request| old_request.item == request.item) + { + timeout + } else if self + .in_flight + .as_ref() + .is_some_and(|(_, old_request)| old_request.item == request.item.item) + { + self.next_request = None; + None + } else { + self.next_request = Some(request); + Some(Instant::now() + Duration::from_millis(150)) + } + } + + fn finish_debounce(&mut self) { + let Some(request) = self.next_request.take() else { + return; + }; + let (tx, rx) = helix_event::cancelation(); + self.in_flight = Some((tx, request.item.clone())); + tokio::spawn(request.execute(rx)); + } +} + +impl ResolveRequest { + async fn execute(self, cancel: CancelRx) { + let future = self.ls.resolve_completion_item(&self.item.item); + let Some(resolved_item) = helix_event::cancelable_future(future, cancel).await else { + return; + }; + job::dispatch(move |_, compositor| { + if let Some(completion) = &mut compositor + .find::() + .unwrap() + .completion + { + let resolved_item = match resolved_item { + Ok(item) => CompletionItem { + item, + resolved: true, + ..*self.item + }, + Err(err) => { + log::error!("completion resolve request failed: {err}"); + // set item to resolved so we don't request it again + // we could also remove it but that oculd be odd ui + let mut item = (*self.item).clone(); + item.resolved = true; + item + } + }; + completion.replace_item(&self.item, resolved_item); + }; + }) + .await + } +} diff --git a/helix-term/src/handlers/signature_help.rs b/helix-term/src/handlers/signature_help.rs index 3c746548a..aaa97b9a0 100644 --- a/helix-term/src/handlers/signature_help.rs +++ b/helix-term/src/handlers/signature_help.rs @@ -5,7 +5,7 @@ use helix_core::syntax::LanguageServerFeature; use helix_event::{ cancelable_future, cancelation, register_hook, send_blocking, CancelRx, CancelTx, }; -use helix_lsp::lsp; +use helix_lsp::lsp::{self, SignatureInformation}; use helix_stdx::rope::RopeSliceExt; use helix_view::document::Mode; use helix_view::events::{DocumentDidChange, SelectionDidChange}; @@ -18,7 +18,7 @@ use crate::commands::Open; use crate::compositor::Compositor; use crate::events::{OnModeSwitch, PostInsertChar}; use crate::handlers::Handlers; -use crate::ui::lsp::SignatureHelp; +use crate::ui::lsp::{Signature, SignatureHelp}; use crate::ui::Popup; use crate::{job, ui}; @@ -82,6 +82,7 @@ impl helix_event::AsyncHook for SignatureHelpHandler { } } self.state = if open { State::Open } else { State::Closed }; + return timeout; } } @@ -118,8 +119,7 @@ pub fn request_signature_help( // Do not show the message if signature help was invoked // automatically on backspace, trigger characters, etc. if invoked == SignatureHelpInvoked::Manual { - editor - .set_error("No configured language server supports signature-help"); + editor.set_error("No configured language server supports signature-help"); } return; }; @@ -138,6 +138,31 @@ pub fn request_signature_help( }); } +fn active_param_range( + signature: &SignatureInformation, + response_active_parameter: Option, +) -> Option<(usize, usize)> { + let param_idx = signature + .active_parameter + .or(response_active_parameter) + .unwrap_or(0) as usize; + let param = signature.parameters.as_ref()?.get(param_idx)?; + match ¶m.label { + lsp::ParameterLabel::Simple(string) => { + let start = signature.label.find(string.as_str())?; + Some((start, start + string.len())) + } + lsp::ParameterLabel::LabelOffsets([start, end]) => { + // LS sends offsets based on utf-16 based string representation + // but highlighting in helix is done using byte offset. + use helix_core::str_utils::char_to_byte_idx; + let from = char_to_byte_idx(&signature.label, *start as usize); + let to = char_to_byte_idx(&signature.label, *end as usize); + Some((from, to)) + } + } +} + pub fn show_signature_help( editor: &mut Editor, compositor: &mut Compositor, @@ -184,54 +209,64 @@ pub fn show_signature_help( let doc = doc!(editor); let language = doc.language_name().unwrap_or(""); - let signature = match response - .signatures - .get(response.active_signature.unwrap_or(0) as usize) - { - Some(s) => s, - None => return, - }; - let mut contents = SignatureHelp::new( - signature.label.clone(), - language.to_string(), - Arc::clone(&editor.syn_loader), - ); + if response.signatures.is_empty() { + return; + } - let signature_doc = if config.lsp.display_signature_help_docs { - signature.documentation.as_ref().map(|doc| match doc { - lsp::Documentation::String(s) => s.clone(), - lsp::Documentation::MarkupContent(markup) => markup.value.clone(), + let signatures: Vec = response + .signatures + .into_iter() + .map(|s| { + let active_param_range = active_param_range(&s, response.active_parameter); + + let signature_doc = if config.lsp.display_signature_help_docs { + s.documentation.map(|doc| match doc { + lsp::Documentation::String(s) => s, + lsp::Documentation::MarkupContent(markup) => markup.value, + }) + } else { + None + }; + + Signature { + signature: s.label, + signature_doc, + active_param_range, + } }) - } else { - None - }; + .collect(); - contents.set_signature_doc(signature_doc); - - let active_param_range = || -> Option<(usize, usize)> { - let param_idx = signature - .active_parameter - .or(response.active_parameter) - .unwrap_or(0) as usize; - let param = signature.parameters.as_ref()?.get(param_idx)?; - match ¶m.label { - lsp::ParameterLabel::Simple(string) => { - let start = signature.label.find(string.as_str())?; - Some((start, start + string.len())) - } - lsp::ParameterLabel::LabelOffsets([start, end]) => { - // LS sends offsets based on utf-16 based string representation - // but highlighting in helix is done using byte offset. - use helix_core::str_utils::char_to_byte_idx; - let from = char_to_byte_idx(&signature.label, *start as usize); - let to = char_to_byte_idx(&signature.label, *end as usize); - Some((from, to)) + let old_popup = compositor.find_id::>(SignatureHelp::ID); + let lsp_signature = response.active_signature.map(|s| s as usize); + + // take the new suggested lsp signature if changed + // otherwise take the old signature if possible + // otherwise the last one (in case there is less signatures than before) + let active_signature = old_popup + .as_ref() + .map(|popup| { + let old_lsp_sig = popup.contents().lsp_signature(); + let old_sig = popup + .contents() + .active_signature() + .min(signatures.len() - 1); + + if old_lsp_sig != lsp_signature { + lsp_signature.unwrap_or(old_sig) + } else { + old_sig } - } - }; - contents.set_active_param_range(active_param_range()); + }) + .unwrap_or(lsp_signature.unwrap_or_default()); + + let contents = SignatureHelp::new( + language.to_string(), + Arc::clone(&editor.syn_loader), + active_signature, + lsp_signature, + signatures, + ); - let old_popup = compositor.find_id::>(SignatureHelp::ID); let mut popup = Popup::new(SignatureHelp::ID, contents) .position(old_popup.and_then(|p| p.get_position())) .position_bias(Open::Above) @@ -264,11 +299,11 @@ fn signature_help_post_insert_char_hook( let (view, doc) = current!(cx.editor); // TODO support multiple language servers (not just the first that is found), likely by merging UI somehow let Some(language_server) = doc - .language_servers_with_feature(LanguageServerFeature::SignatureHelp) - .next() - else { - return Ok(()); - }; + .language_servers_with_feature(LanguageServerFeature::SignatureHelp) + .next() + else { + return Ok(()); + }; let capabilities = language_server.capabilities(); diff --git a/helix-term/src/keymap/default.rs b/helix-term/src/keymap/default.rs index f91f6d69a..142cf0aeb 100644 --- a/helix-term/src/keymap/default.rs +++ b/helix-term/src/keymap/default.rs @@ -58,6 +58,7 @@ pub fn default() -> HashMap { "k" => move_line_up, "j" => move_line_down, "." => goto_last_modification, + "w" => goto_word, }, ":" => command_mode, @@ -86,10 +87,12 @@ pub fn default() -> HashMap { "A-;" => flip_selections, "A-o" | "A-up" => expand_selection, "A-i" | "A-down" => shrink_selection, + "A-I" | "A-S-down" => select_all_children, "A-p" | "A-left" => select_prev_sibling, "A-n" | "A-right" => select_next_sibling, "A-e" => move_parent_node_end, "A-b" => move_parent_node_start, + "A-a" => select_all_siblings, "%" => select_all, "x" => extend_line_below, @@ -114,6 +117,7 @@ pub fn default() -> HashMap { "t" => goto_prev_class, "a" => goto_prev_parameter, "c" => goto_prev_comment, + "e" => goto_prev_entry, "T" => goto_prev_test, "p" => goto_prev_paragraph, "space" => add_newline_above, @@ -128,6 +132,7 @@ pub fn default() -> HashMap { "t" => goto_next_class, "a" => goto_next_parameter, "c" => goto_next_comment, + "e" => goto_next_entry, "T" => goto_next_test, "p" => goto_next_paragraph, "space" => add_newline_below, @@ -224,9 +229,10 @@ pub fn default() -> HashMap { "S" => workspace_symbol_picker, "d" => diagnostics_picker, "D" => workspace_diagnostics_picker, + "g" => changed_file_picker, "a" => code_action, "'" => last_picker, - "g" => { "Debug (experimental)" sticky=true + "G" => { "Debug (experimental)" sticky=true "l" => dap_launch, "r" => dap_restart, "b" => dap_toggle_breakpoint, @@ -362,6 +368,7 @@ pub fn default() -> HashMap { "g" => { "Goto" "k" => extend_line_up, "j" => extend_line_down, + "w" => extend_to_word, }, })); let insert = keymap!({ "Insert mode" diff --git a/helix-term/src/lib.rs b/helix-term/src/lib.rs index cdde86ec5..cf4fbd9fa 100644 --- a/helix-term/src/lib.rs +++ b/helix-term/src/lib.rs @@ -20,8 +20,6 @@ mod handlers; use ignore::DirEntry; use url::Url; -pub use keymap::macros::*; - #[cfg(windows)] fn true_color() -> bool { true @@ -48,10 +46,13 @@ fn true_color() -> bool { /// Function used for filtering dir entries in the various file pickers. fn filter_picker_entry(entry: &DirEntry, root: &Path, dedup_symlinks: bool) -> bool { - // We always want to ignore the .git directory, otherwise if + // We always want to ignore popular VCS directories, otherwise if // `ignore` is turned off, we end up with a lot of noise // in our picker. - if entry.file_name() == ".git" { + if matches!( + entry.file_name().to_str(), + Some(".git" | ".pijul" | ".jj" | ".hg" | ".svn") + ) { return false; } diff --git a/helix-term/src/ui/completion.rs b/helix-term/src/ui/completion.rs index 6cbb5b109..372e3e5ef 100644 --- a/helix-term/src/ui/completion.rs +++ b/helix-term/src/ui/completion.rs @@ -1,28 +1,24 @@ use crate::{ compositor::{Component, Context, Event, EventResult}, - handlers::trigger_auto_completion, - job, + handlers::{completion::ResolveHandler, trigger_auto_completion}, }; -use helix_event::AsyncHook; use helix_view::{ document::SavePoint, editor::CompleteAction, - graphics::Margin, handlers::lsp::SignatureHelpInvoked, theme::{Modifier, Style}, ViewId, }; -use tokio::time::Instant; use tui::{buffer::Buffer as Surface, text::Span}; -use std::{borrow::Cow, sync::Arc, time::Duration}; +use std::{borrow::Cow, sync::Arc}; use helix_core::{chars, Change, Transaction}; use helix_view::{graphics::Rect, Document, Editor}; use crate::ui::{menu, Markdown, Menu, Popup, PromptEvent}; -use helix_lsp::{lsp, util, OffsetEncoding}; +use helix_lsp::{lsp, util, LanguageServerId, OffsetEncoding}; impl menu::Item for CompletionItem { type Data = (); @@ -94,7 +90,7 @@ impl menu::Item for CompletionItem { #[derive(Debug, PartialEq, Default, Clone)] pub struct CompletionItem { pub item: lsp::CompletionItem, - pub language_server_id: usize, + pub provider: LanguageServerId, pub resolved: bool, } @@ -104,7 +100,7 @@ pub struct Completion { #[allow(dead_code)] trigger_offset: usize, filter: String, - resolve_handler: tokio::sync::mpsc::Sender, + resolve_handler: ResolveHandler, } impl Completion { @@ -224,7 +220,7 @@ impl Completion { ($item:expr) => { match editor .language_servers - .get_by_id($item.language_server_id) + .get_by_id($item.provider) { Some(ls) => ls, None => { @@ -285,12 +281,6 @@ impl Completion { let language_server = language_server!(item); let offset_encoding = language_server.offset_encoding(); - let language_server = editor - .language_servers - .get_by_id(item.language_server_id) - .unwrap(); - - // resolve item if not yet resolved if !item.resolved { if let Some(resolved) = Self::resolve_completion_item(language_server, item.item.clone()) @@ -343,16 +333,9 @@ impl Completion { } }); - let margin = if editor.menu_border() { - Margin::vertical(1) - } else { - Margin::none() - }; - let popup = Popup::new(Self::ID, menu) .with_scrollbar(false) - .ignore_escape_key(true) - .margin(margin); + .ignore_escape_key(true); let (view, doc) = current_ref!(editor); let text = doc.text().slice(..); @@ -371,7 +354,7 @@ impl Completion { // TODO: expand nucleo api to allow moving straight to a Utf32String here // and avoid allocation during matching filter: String::from(fragment), - resolve_handler: ResolveHandler::default().spawn(), + resolve_handler: ResolveHandler::new(), }; // need to recompute immediately in case start_offset != trigger_offset @@ -389,7 +372,16 @@ impl Completion { language_server: &helix_lsp::Client, completion_item: lsp::CompletionItem, ) -> Option { - let future = language_server.resolve_completion_item(completion_item)?; + if !matches!( + language_server.capabilities().completion_provider, + Some(lsp::CompletionOptions { + resolve_provider: Some(true), + .. + }) + ) { + return None; + } + let future = language_server.resolve_completion_item(&completion_item); let response = helix_lsp::block_on(future); match response { Ok(item) => Some(item), @@ -422,7 +414,7 @@ impl Completion { self.popup.contents().is_empty() } - fn replace_item(&mut self, old_item: CompletionItem, new_item: CompletionItem) { + pub fn replace_item(&mut self, old_item: &CompletionItem, new_item: CompletionItem) { self.popup.contents_mut().replace_option(old_item, new_item); } @@ -444,12 +436,12 @@ impl Component for Completion { self.popup.render(area, surface, cx); // if we have a selection, render a markdown popup on top/below with info - let option = match self.popup.contents().selection() { + let option = match self.popup.contents_mut().selection_mut() { Some(option) => option, None => return, }; if !option.resolved { - helix_event::send_blocking(&self.resolve_handler, option.clone()); + self.resolve_handler.ensure_item_resolved(cx.editor, option); } // need to render: // option.detail @@ -498,12 +490,7 @@ impl Component for Completion { None => return, }; - let popup_area = { - let (popup_x, popup_y) = self.popup.get_rel_position(area, cx.editor); - let (popup_width, popup_height) = self.popup.get_size(); - Rect::new(popup_x, popup_y, popup_width, popup_height) - }; - + let popup_area = self.popup.area(area, cx.editor); let doc_width_available = area.width.saturating_sub(popup_area.right()); let doc_area = if doc_width_available > 30 { let mut doc_width = doc_width_available; @@ -545,95 +532,10 @@ impl Component for Completion { surface.clear_with(doc_area, background); if cx.editor.popup_border() { - use tui::widgets::{Block, Borders, Widget}; - Widget::render(Block::default().borders(Borders::ALL), doc_area, surface); + use tui::widgets::{Block, Widget}; + Widget::render(Block::bordered(), doc_area, surface); } markdown_doc.render(doc_area, surface, cx); } } - -/// A hook for resolving incomplete completion items. -/// -/// From the [LSP spec](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion): -/// -/// > If computing full completion items is expensive, servers can additionally provide a -/// > handler for the completion item resolve request. ... -/// > A typical use case is for example: the `textDocument/completion` request doesn't fill -/// > in the `documentation` property for returned completion items since it is expensive -/// > to compute. When the item is selected in the user interface then a -/// > 'completionItem/resolve' request is sent with the selected completion item as a parameter. -/// > The returned completion item should have the documentation property filled in. -#[derive(Debug, Default)] -struct ResolveHandler { - trigger: Option, - request: Option, -} - -impl AsyncHook for ResolveHandler { - type Event = CompletionItem; - - fn handle_event( - &mut self, - item: Self::Event, - timeout: Option, - ) -> Option { - if self - .trigger - .as_ref() - .is_some_and(|trigger| trigger == &item) - { - timeout - } else { - self.trigger = Some(item); - self.request = None; - Some(Instant::now() + Duration::from_millis(150)) - } - } - - fn finish_debounce(&mut self) { - let Some(item) = self.trigger.take() else { return }; - let (tx, rx) = helix_event::cancelation(); - self.request = Some(tx); - job::dispatch_blocking(move |editor, _| resolve_completion_item(editor, item, rx)) - } -} - -fn resolve_completion_item( - editor: &mut Editor, - item: CompletionItem, - cancel: helix_event::CancelRx, -) { - let Some(language_server) = editor.language_server_by_id(item.language_server_id) else { - return; - }; - - let Some(future) = language_server.resolve_completion_item(item.item.clone()) else { - return; - }; - - tokio::spawn(async move { - match helix_event::cancelable_future(future, cancel).await { - Some(Ok(resolved_item)) => { - job::dispatch(move |_, compositor| { - if let Some(completion) = &mut compositor - .find::() - .unwrap() - .completion - { - let resolved_item = CompletionItem { - item: resolved_item, - language_server_id: item.language_server_id, - resolved: true, - }; - - completion.replace_item(item, resolved_item); - }; - }) - .await - } - Some(Err(err)) => log::error!("completion resolve request failed: {err}"), - None => (), - } - }); -} diff --git a/helix-term/src/ui/document.rs b/helix-term/src/ui/document.rs index dc61ca2e3..bcbaa3519 100644 --- a/helix-term/src/ui/document.rs +++ b/helix-term/src/ui/document.rs @@ -7,6 +7,7 @@ use helix_core::syntax::Highlight; use helix_core::syntax::HighlightEvent; use helix_core::text_annotations::TextAnnotations; use helix_core::{visual_offset_from_block, Position, RopeSlice}; +use helix_stdx::rope::RopeSliceExt; use helix_view::editor::{WhitespaceConfig, WhitespaceRenderValue}; use helix_view::graphics::Rect; use helix_view::theme::Style; @@ -32,14 +33,27 @@ impl LineDecoration for F { } } +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum StyleIterKind { + /// base highlights (usually emitted by TS), byte indices (potentially not codepoint aligned) + BaseHighlights, + /// overlay highlights (emitted by custom code from selections), char indices + Overlay, +} + /// A wrapper around a HighlightIterator /// that merges the layered highlights to create the final text style /// and yields the active text style and the char_idx where the active /// style will have to be recomputed. +/// +/// TODO(ropey2): hopefully one day helix and ropey will operate entirely +/// on byte ranges and we can remove this struct StyleIter<'a, H: Iterator> { text_style: Style, active_highlights: Vec, highlight_iter: H, + kind: StyleIterKind, + text: RopeSlice<'a>, theme: &'a Theme, } @@ -54,7 +68,7 @@ impl> Iterator for StyleIter<'_, H> { HighlightEvent::HighlightEnd => { self.active_highlights.pop(); } - HighlightEvent::Source { start, end } => { + HighlightEvent::Source { start, mut end } => { if start == end { continue; } @@ -64,6 +78,9 @@ impl> Iterator for StyleIter<'_, H> { .fold(self.text_style, |acc, span| { acc.patch(self.theme.highlight(span.0)) }); + if self.kind == StyleIterKind::BaseHighlights { + end = self.text.byte_to_next_char(end); + } return Some((style, end)); } } @@ -185,13 +202,17 @@ pub fn render_text<'t>( text_style: renderer.text_style, active_highlights: Vec::with_capacity(64), highlight_iter: syntax_highlight_iter, + kind: StyleIterKind::BaseHighlights, theme, + text, }; let mut overlay_styles = StyleIter { text_style: Style::default(), active_highlights: Vec::with_capacity(64), highlight_iter: overlay_highlight_iter, + kind: StyleIterKind::Overlay, theme, + text, }; let mut last_line_pos = LinePos { @@ -341,6 +362,7 @@ pub struct TextRenderer<'a> { pub indent_guide_style: Style, pub newline: String, pub nbsp: String, + pub nnbsp: String, pub space: String, pub tab: String, pub virtual_tab: String, @@ -395,6 +417,11 @@ impl<'a> TextRenderer<'a> { } else { " ".to_owned() }; + let nnbsp = if ws_render.nnbsp() == WhitespaceRenderValue::All { + ws_chars.nnbsp.into() + } else { + " ".to_owned() + }; let text_style = theme.get("ui.text"); @@ -405,6 +432,7 @@ impl<'a> TextRenderer<'a> { indent_guide_char: editor_config.indent_guides.character.into(), newline, nbsp, + nnbsp, space, tab, virtual_tab, @@ -448,6 +476,7 @@ impl<'a> TextRenderer<'a> { let width = grapheme.width(); let space = if is_virtual { " " } else { &self.space }; let nbsp = if is_virtual { " " } else { &self.nbsp }; + let nnbsp = if is_virtual { " " } else { &self.nnbsp }; let tab = if is_virtual { &self.virtual_tab } else { @@ -461,6 +490,7 @@ impl<'a> TextRenderer<'a> { // TODO special rendering for other whitespaces? Grapheme::Other { ref g } if g == " " => space, Grapheme::Other { ref g } if g == "\u{00A0}" => nbsp, + Grapheme::Other { ref g } if g == "\u{202F}" => nnbsp, Grapheme::Other { ref g } => g, Grapheme::Newline => &self.newline, }; diff --git a/helix-term/src/ui/editor.rs b/helix-term/src/ui/editor.rs index f3bba5d1c..a071bfaa8 100644 --- a/helix-term/src/ui/editor.rs +++ b/helix-term/src/ui/editor.rs @@ -12,9 +12,7 @@ use crate::{ use helix_core::{ diagnostic::NumberOrString, - graphemes::{ - ensure_grapheme_boundary_next_byte, next_grapheme_boundary, prev_grapheme_boundary, - }, + graphemes::{next_grapheme_boundary, prev_grapheme_boundary}, movement::Direction, syntax::{self, HighlightEvent}, text_annotations::TextAnnotations, @@ -315,26 +313,14 @@ impl EditorView { let iter = syntax // TODO: range doesn't actually restrict source, just highlight range .highlight_iter(text.slice(..), Some(range), None) - .map(|event| event.unwrap()) - .map(move |event| match event { - // TODO: use byte slices directly - // convert byte offsets to char offset - HighlightEvent::Source { start, end } => { - let start = - text.byte_to_char(ensure_grapheme_boundary_next_byte(text, start)); - let end = - text.byte_to_char(ensure_grapheme_boundary_next_byte(text, end)); - HighlightEvent::Source { start, end } - } - event => event, - }); + .map(|event| event.unwrap()); Box::new(iter) } None => Box::new( [HighlightEvent::Source { - start: text.byte_to_char(range.start), - end: text.byte_to_char(range.end), + start: range.start, + end: range.end, }] .into_iter(), ), @@ -350,7 +336,8 @@ impl EditorView { let text = doc.text().slice(..); let row = text.char_to_line(anchor.min(text.len_chars())); - let range = Self::viewport_byte_range(text, row, height); + let mut range = Self::viewport_byte_range(text, row, height); + range = text.byte_to_char(range.start)..text.byte_to_char(range.end); text_annotations.collect_overlay_highlights(range) } @@ -359,8 +346,8 @@ impl EditorView { pub fn doc_diagnostics_highlights( doc: &Document, theme: &Theme, - ) -> [Vec<(usize, std::ops::Range)>; 5] { - use helix_core::diagnostic::{DiagnosticTag, Severity}; + ) -> [Vec<(usize, std::ops::Range)>; 7] { + use helix_core::diagnostic::{DiagnosticTag, Range, Severity}; let get_scope_of = |scope| { theme .find_scope_index_exact(scope) @@ -389,6 +376,25 @@ impl EditorView { let mut hint_vec = Vec::new(); let mut warning_vec = Vec::new(); let mut error_vec = Vec::new(); + let mut unnecessary_vec = Vec::new(); + let mut deprecated_vec = Vec::new(); + + let push_diagnostic = + |vec: &mut Vec<(usize, std::ops::Range)>, scope, range: Range| { + // If any diagnostic overlaps ranges with the prior diagnostic, + // merge the two together. Otherwise push a new span. + match vec.last_mut() { + Some((_, existing_range)) if range.start <= existing_range.end => { + // This branch merges overlapping diagnostics, assuming that the current + // diagnostic starts on range.start or later. If this assertion fails, + // we will discard some part of `diagnostic`. This implies that + // `doc.diagnostics()` is not sorted by `diagnostic.range`. + debug_assert!(existing_range.start <= range.start); + existing_range.end = range.end.max(existing_range.end) + } + _ => vec.push((scope, range.start..range.end)), + } + }; for diagnostic in doc.diagnostics() { // Separate diagnostics into different Vecs by severity. @@ -400,31 +406,44 @@ impl EditorView { _ => (&mut default_vec, r#default), }; - let scope = diagnostic - .tags - .first() - .and_then(|tag| match tag { - DiagnosticTag::Unnecessary => unnecessary, - DiagnosticTag::Deprecated => deprecated, - }) - .unwrap_or(scope); - - // If any diagnostic overlaps ranges with the prior diagnostic, - // merge the two together. Otherwise push a new span. - match vec.last_mut() { - Some((_, range)) if diagnostic.range.start <= range.end => { - // This branch merges overlapping diagnostics, assuming that the current - // diagnostic starts on range.start or later. If this assertion fails, - // we will discard some part of `diagnostic`. This implies that - // `doc.diagnostics()` is not sorted by `diagnostic.range`. - debug_assert!(range.start <= diagnostic.range.start); - range.end = diagnostic.range.end.max(range.end) + // If the diagnostic has tags and a non-warning/error severity, skip rendering + // the diagnostic as info/hint/default and only render it as unnecessary/deprecated + // instead. For warning/error diagnostics, render both the severity highlight and + // the tag highlight. + if diagnostic.tags.is_empty() + || matches!( + diagnostic.severity, + Some(Severity::Warning | Severity::Error) + ) + { + push_diagnostic(vec, scope, diagnostic.range); + } + + for tag in &diagnostic.tags { + match tag { + DiagnosticTag::Unnecessary => { + if let Some(scope) = unnecessary { + push_diagnostic(&mut unnecessary_vec, scope, diagnostic.range) + } + } + DiagnosticTag::Deprecated => { + if let Some(scope) = deprecated { + push_diagnostic(&mut deprecated_vec, scope, diagnostic.range) + } + } } - _ => vec.push((scope, diagnostic.range.start..diagnostic.range.end)), } } - [default_vec, info_vec, hint_vec, warning_vec, error_vec] + [ + default_vec, + unnecessary_vec, + deprecated_vec, + info_vec, + hint_vec, + warning_vec, + error_vec, + ] } /// Get highlight spans for selections in a document view. @@ -916,13 +935,19 @@ impl EditorView { fn command_mode(&mut self, mode: Mode, cxt: &mut commands::Context, event: KeyEvent) { match (event, cxt.editor.count) { - // count handling - (key!(i @ '0'), Some(_)) | (key!(i @ '1'..='9'), _) - if !self.keymaps.contains_key(mode, event) => - { + // If the count is already started and the input is a number, always continue the count. + (key!(i @ '0'..='9'), Some(count)) => { + let i = i.to_digit(10).unwrap() as usize; + let count = count.get() * 10 + i; + if count > 100_000_000 { + return; + } + cxt.editor.count = NonZeroUsize::new(count); + } + // A non-zero digit will start the count if that number isn't used by a keymap. + (key!(i @ '1'..='9'), None) if !self.keymaps.contains_key(mode, event) => { let i = i.to_digit(10).unwrap() as usize; - cxt.editor.count = - std::num::NonZeroUsize::new(cxt.editor.count.map_or(i, |c| c.get() * 10 + i)); + cxt.editor.count = NonZeroUsize::new(i); } // special handling for repeat operator (key!('.'), _) if self.keymaps.pending().is_empty() => { @@ -1013,7 +1038,6 @@ impl EditorView { self.last_insert.1.push(InsertEvent::TriggerCompletion); // TODO : propagate required size on resize to completion too - completion.required_size((size.width, size.height)); self.completion = Some(completion); Some(area) } @@ -1046,13 +1070,33 @@ impl EditorView { } impl EditorView { + /// must be called whenever the editor processed input that + /// is not a `KeyEvent`. In these cases any pending keys/on next + /// key callbacks must be canceled. + fn handle_non_key_input(&mut self, cxt: &mut commands::Context) { + cxt.editor.status_msg = None; + cxt.editor.reset_idle_timer(); + // HACKS: create a fake key event that will never trigger any actual map + // and therefore simply acts as "dismiss" + let null_key_event = KeyEvent { + code: KeyCode::Null, + modifiers: KeyModifiers::empty(), + }; + // dismiss any pending keys + if let Some(on_next_key) = self.on_next_key.take() { + on_next_key(cxt, null_key_event); + } + self.handle_keymap_event(cxt.editor.mode, cxt, null_key_event); + self.pseudo_pending.clear(); + } + fn handle_mouse_event( &mut self, event: &MouseEvent, cxt: &mut commands::Context, ) -> EventResult { if event.kind != MouseEventKind::Moved { - cxt.editor.reset_idle_timer(); + self.handle_non_key_input(cxt) } let config = cxt.editor.config(); @@ -1209,24 +1253,28 @@ impl EditorView { } MouseEventKind::Up(MouseButton::Right) => { - if let Some((coords, view_id)) = gutter_coords_and_view(cxt.editor, row, column) { + if let Some((pos, view_id)) = gutter_coords_and_view(cxt.editor, row, column) { cxt.editor.focus(view_id); - let (view, doc) = current!(cxt.editor); - if let Some(pos) = - view.pos_at_visual_coords(doc, coords.row as u16, coords.col as u16, true) - { - doc.set_selection(view_id, Selection::point(pos)); - if modifiers == KeyModifiers::ALT { - commands::MappableCommand::dap_edit_log.execute(cxt); - } else { - commands::MappableCommand::dap_edit_condition.execute(cxt); - } + if let Some((pos, _)) = pos_and_view(cxt.editor, row, column, true) { + doc_mut!(cxt.editor).set_selection(view_id, Selection::point(pos)); + } else { + let (view, doc) = current!(cxt.editor); - return EventResult::Consumed(None); + if let Some(pos) = view.pos_at_visual_coords(doc, pos.row as u16, 0, true) { + doc.set_selection(view_id, Selection::point(pos)); + match modifiers { + KeyModifiers::ALT => { + commands::MappableCommand::dap_edit_log.execute(cxt) + } + _ => commands::MappableCommand::dap_edit_condition.execute(cxt), + }; + } } - } + cxt.editor.ensure_cursor_in_view(view_id); + return EventResult::Consumed(None); + } EventResult::Ignored(None) } @@ -1277,6 +1325,7 @@ impl Component for EditorView { match event { Event::Paste(contents) => { + self.handle_non_key_input(&mut cx); cx.count = cx.editor.count; commands::paste_bracketed_value(&mut cx, contents.clone()); cx.editor.count = None; @@ -1406,7 +1455,7 @@ impl Component for EditorView { EventResult::Consumed(None) } Event::FocusLost => { - if context.editor.config().auto_save { + if context.editor.config().auto_save.focus_lost { if let Err(e) = commands::typed::write_all_impl(context, false, false) { context.editor.set_error(format!("{}", e)); } diff --git a/helix-term/src/ui/info.rs b/helix-term/src/ui/info.rs index 651e5ca93..217cee6b3 100644 --- a/helix-term/src/ui/info.rs +++ b/helix-term/src/ui/info.rs @@ -3,7 +3,7 @@ use helix_view::graphics::{Margin, Rect}; use helix_view::info::Info; use tui::buffer::Buffer as Surface; use tui::text::Text; -use tui::widgets::{Block, Borders, Paragraph, Widget}; +use tui::widgets::{Block, Paragraph, Widget}; impl Component for Info { fn render(&mut self, viewport: Rect, surface: &mut Surface, cx: &mut Context) { @@ -23,13 +23,12 @@ impl Component for Info { )); surface.clear_with(area, popup_style); - let block = Block::default() + let block = Block::bordered() .title(self.title.as_str()) - .borders(Borders::ALL) .border_style(popup_style); let margin = Margin::horizontal(1); - let inner = block.inner(area).inner(&margin); + let inner = block.inner(area).inner(margin); block.render(area, surface); Paragraph::new(&Text::from(self.text.as_str())) diff --git a/helix-term/src/ui/lsp.rs b/helix-term/src/ui/lsp.rs index a3698e38d..b6491085b 100644 --- a/helix-term/src/ui/lsp.rs +++ b/helix-term/src/ui/lsp.rs @@ -3,60 +3,102 @@ use std::sync::Arc; use arc_swap::ArcSwap; use helix_core::syntax; use helix_view::graphics::{Margin, Rect, Style}; +use helix_view::input::Event; use tui::buffer::Buffer; +use tui::layout::Alignment; +use tui::text::Text; use tui::widgets::{BorderType, Paragraph, Widget, Wrap}; -use crate::compositor::{Component, Compositor, Context}; +use crate::compositor::{Component, Compositor, Context, EventResult}; +use crate::alt; use crate::ui::Markdown; use super::Popup; -pub struct SignatureHelp { - signature: String, - signature_doc: Option, +pub struct Signature { + pub signature: String, + pub signature_doc: Option, /// Part of signature text - active_param_range: Option<(usize, usize)>, + pub active_param_range: Option<(usize, usize)>, +} +pub struct SignatureHelp { language: String, config_loader: Arc>, + active_signature: usize, + lsp_signature: Option, + signatures: Vec, } impl SignatureHelp { pub const ID: &'static str = "signature-help"; pub fn new( - signature: String, language: String, config_loader: Arc>, + active_signature: usize, + lsp_signature: Option, + signatures: Vec, ) -> Self { Self { - signature, - signature_doc: None, - active_param_range: None, language, config_loader, + active_signature, + lsp_signature, + signatures, } } - pub fn set_signature_doc(&mut self, signature_doc: Option) { - self.signature_doc = signature_doc; + pub fn active_signature(&self) -> usize { + self.active_signature } - pub fn set_active_param_range(&mut self, offset: Option<(usize, usize)>) { - self.active_param_range = offset; + pub fn lsp_signature(&self) -> Option { + self.lsp_signature } pub fn visible_popup(compositor: &mut Compositor) -> Option<&mut Popup> { compositor.find_id::>(Self::ID) } + + fn signature_index(&self) -> String { + format!("({}/{})", self.active_signature + 1, self.signatures.len()) + } } impl Component for SignatureHelp { + fn handle_event(&mut self, event: &Event, _cx: &mut Context) -> EventResult { + let Event::Key(event) = event else { + return EventResult::Ignored(None); + }; + + if self.signatures.len() <= 1 { + return EventResult::Ignored(None); + } + + match event { + alt!('p') => { + self.active_signature = self + .active_signature + .checked_sub(1) + .unwrap_or(self.signatures.len() - 1); + EventResult::Consumed(None) + } + alt!('n') => { + self.active_signature = (self.active_signature + 1) % self.signatures.len(); + EventResult::Consumed(None) + } + _ => EventResult::Ignored(None), + } + } + fn render(&mut self, area: Rect, surface: &mut Buffer, cx: &mut Context) { let margin = Margin::horizontal(1); - let active_param_span = self.active_param_range.map(|(start, end)| { + let signature = &self.signatures[self.active_signature]; + + let active_param_span = signature.active_param_range.map(|(start, end)| { vec![( cx.editor .theme @@ -66,21 +108,29 @@ impl Component for SignatureHelp { )] }); + let sig = &self.signatures[self.active_signature]; let sig_text = crate::ui::markdown::highlighted_code_block( - &self.signature, + sig.signature.as_str(), &self.language, Some(&cx.editor.theme), Arc::clone(&self.config_loader), active_param_span, ); + if self.signatures.len() > 1 { + let signature_index = self.signature_index(); + let text = Text::from(signature_index); + let paragraph = Paragraph::new(&text).alignment(Alignment::Right); + paragraph.render(area.clip_top(1).with_height(1).clip_right(1), surface); + } + let (_, sig_text_height) = crate::ui::text::required_size(&sig_text, area.width); let sig_text_area = area.clip_top(1).with_height(sig_text_height); - let sig_text_area = sig_text_area.inner(&margin).intersection(surface.area); + let sig_text_area = sig_text_area.inner(margin).intersection(surface.area); let sig_text_para = Paragraph::new(&sig_text).wrap(Wrap { trim: false }); sig_text_para.render(sig_text_area, surface); - if self.signature_doc.is_none() { + if sig.signature_doc.is_none() { return; } @@ -92,7 +142,7 @@ impl Component for SignatureHelp { } } - let sig_doc = match &self.signature_doc { + let sig_doc = match &sig.signature_doc { None => return, Some(doc) => Markdown::new(doc.clone(), Arc::clone(&self.config_loader)), }; @@ -103,20 +153,19 @@ impl Component for SignatureHelp { let sig_doc_para = Paragraph::new(&sig_doc) .wrap(Wrap { trim: false }) .scroll((cx.scroll.unwrap_or_default() as u16, 0)); - sig_doc_para.render(sig_doc_area.inner(&margin), surface); + sig_doc_para.render(sig_doc_area.inner(margin), surface); } fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> { const PADDING: u16 = 2; const SEPARATOR_HEIGHT: u16 = 1; - if PADDING >= viewport.1 || PADDING >= viewport.0 { - return None; - } - let max_text_width = (viewport.0 - PADDING).min(120); + let sig = &self.signatures[self.active_signature]; + + let max_text_width = viewport.0.saturating_sub(PADDING).clamp(10, 120); let signature_text = crate::ui::markdown::highlighted_code_block( - &self.signature, + sig.signature.as_str(), &self.language, None, Arc::clone(&self.config_loader), @@ -125,7 +174,7 @@ impl Component for SignatureHelp { let (sig_width, sig_height) = crate::ui::text::required_size(&signature_text, max_text_width); - let (width, height) = match self.signature_doc { + let (width, height) = match sig.signature_doc { Some(ref doc) => { let doc_md = Markdown::new(doc.clone(), Arc::clone(&self.config_loader)); let doc_text = doc_md.parse(None); @@ -139,6 +188,12 @@ impl Component for SignatureHelp { None => (sig_width, sig_height), }; - Some((width + PADDING, height + PADDING)) + let sig_index_width = if self.signatures.len() > 1 { + self.signature_index().len() + 1 + } else { + 0 + }; + + Some((width + PADDING + sig_index_width as u16, height + PADDING)) } } diff --git a/helix-term/src/ui/markdown.rs b/helix-term/src/ui/markdown.rs index 81499d039..96614443f 100644 --- a/helix-term/src/ui/markdown.rs +++ b/helix-term/src/ui/markdown.rs @@ -351,7 +351,7 @@ impl Component for Markdown { .scroll((cx.scroll.unwrap_or_default() as u16, 0)); let margin = Margin::all(1); - par.render(area.inner(&margin), surface); + par.render(area.inner(margin), surface); } fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> { diff --git a/helix-term/src/ui/menu.rs b/helix-term/src/ui/menu.rs index c0e60b33e..c5006f958 100644 --- a/helix-term/src/ui/menu.rs +++ b/helix-term/src/ui/menu.rs @@ -7,18 +7,11 @@ use crate::{ use helix_core::fuzzy::MATCHER; use nucleo::pattern::{Atom, AtomKind, CaseMatching}; use nucleo::{Config, Utf32Str}; -use tui::{ - buffer::Buffer as Surface, - widgets::{Block, Borders, Table, Widget}, -}; +use tui::{buffer::Buffer as Surface, widgets::Table}; pub use tui::widgets::{Cell, Row}; -use helix_view::{ - editor::SmartTabConfig, - graphics::{Margin, Rect}, - Editor, -}; +use helix_view::{editor::SmartTabConfig, graphics::Rect, Editor}; use tui::layout::Constraint; pub trait Item: Sync + Send + 'static { @@ -241,9 +234,9 @@ impl Menu { } impl Menu { - pub fn replace_option(&mut self, old_option: T, new_option: T) { + pub fn replace_option(&mut self, old_option: &T, new_option: T) { for option in &mut self.options { - if old_option == *option { + if old_option == option { *option = new_option; break; } @@ -341,16 +334,8 @@ impl Component for Menu { .try_get("ui.menu") .unwrap_or_else(|| theme.get("ui.text")); let selected = theme.get("ui.menu.selected"); - surface.clear_with(area, style); - - let render_borders = cx.editor.menu_border(); - let area = if render_borders { - Widget::render(Block::default().borders(Borders::ALL), area, surface); - area.inner(&Margin::vertical(1)) - } else { - area - }; + surface.clear_with(area, style); let scroll = self.scroll; diff --git a/helix-term/src/ui/mod.rs b/helix-term/src/ui/mod.rs index a4b148af3..6a4655fde 100644 --- a/helix-term/src/ui/mod.rs +++ b/helix-term/src/ui/mod.rs @@ -13,7 +13,7 @@ mod spinner; mod statusline; mod text; -use crate::compositor::{Component, Compositor}; +use crate::compositor::Compositor; use crate::filter_picker_entry; use crate::job::{self, Callback}; pub use completion::{Completion, CompletionItem}; @@ -29,7 +29,7 @@ pub use text::Text; use helix_view::Editor; -use std::path::PathBuf; +use std::{error::Error, path::PathBuf}; pub fn prompt( cx: &mut crate::commands::Context, @@ -143,14 +143,12 @@ pub fn raw_regex_prompt( move |_editor: &mut Editor, compositor: &mut Compositor| { let contents = Text::new(format!("{}", err)); let size = compositor.size(); - let mut popup = Popup::new("invalid-regex", contents) + let popup = Popup::new("invalid-regex", contents) .position(Some(helix_core::Position::new( size.height as usize - 2, // 2 = statusline + commandline 0, ))) .auto_close(true); - popup.required_size((size.width, size.height)); - compositor.replace_or_push("invalid-regex", popup); }, )); @@ -509,4 +507,18 @@ pub mod completers { files } } + + pub fn register(editor: &Editor, input: &str) -> Vec { + let iter = editor + .registers + .iter_preview() + // Exclude special registers that shouldn't be written to + .filter(|(ch, _)| !matches!(ch, '%' | '#' | '.')) + .map(|(ch, _)| ch.to_string()); + + fuzzy_match(input, iter, false) + .into_iter() + .map(|(name, _)| ((0..), name.into())) + .collect() + } } diff --git a/helix-term/src/ui/picker.rs b/helix-term/src/ui/picker.rs index c2728888a..b8ec57d51 100644 --- a/helix-term/src/ui/picker.rs +++ b/helix-term/src/ui/picker.rs @@ -17,7 +17,7 @@ use tui::{ buffer::Buffer as Surface, layout::Constraint, text::{Span, Spans}, - widgets::{Block, BorderType, Borders, Cell, Table}, + widgets::{Block, BorderType, Cell, Table}, }; use tui::widgets::Widget; @@ -539,13 +539,12 @@ impl Picker { let background = cx.editor.theme.get("ui.background"); surface.clear_with(area, background); - // don't like this but the lifetime sucks - let block = Block::default().borders(Borders::ALL); + const BLOCK: Block<'_> = Block::bordered(); // calculate the inner area inside the box - let inner = block.inner(area); + let inner = BLOCK.inner(area); - block.render(area, surface); + BLOCK.render(area, surface); // -- Render the input bar: @@ -690,15 +689,14 @@ impl Picker { let text = cx.editor.theme.get("ui.text"); surface.clear_with(area, background); - // don't like this but the lifetime sucks - let block = Block::default().borders(Borders::ALL); + const BLOCK: Block<'_> = Block::bordered(); // calculate the inner area inside the box - let inner = block.inner(area); + let inner = BLOCK.inner(area); // 1 column gap on either side let margin = Margin::horizontal(1); - let inner = inner.inner(&margin); - block.render(area, surface); + let inner = inner.inner(margin); + BLOCK.render(area, surface); if let Some((path, range)) = self.current_file(cx.editor) { let preview = self.get_preview(path, cx.editor); @@ -921,7 +919,7 @@ impl Component for Picker { } fn cursor(&self, area: Rect, editor: &Editor) -> (Option, CursorKind) { - let block = Block::default().borders(Borders::ALL); + let block = Block::bordered(); // calculate the inner area inside the box let inner = block.inner(area); diff --git a/helix-term/src/ui/popup.rs b/helix-term/src/ui/popup.rs index b38b8b6e3..2cefaf61b 100644 --- a/helix-term/src/ui/popup.rs +++ b/helix-term/src/ui/popup.rs @@ -5,26 +5,36 @@ use crate::{ }; use tui::{ buffer::Buffer as Surface, - widgets::{Block, Borders, Widget}, + widgets::{Block, Widget}, }; use helix_core::Position; use helix_view::{ graphics::{Margin, Rect}, + input::{MouseEvent, MouseEventKind}, Editor, }; +const MIN_HEIGHT: u16 = 6; +const MAX_HEIGHT: u16 = 26; +const MAX_WIDTH: u16 = 120; + +struct RenderInfo { + area: Rect, + child_height: u16, + render_borders: bool, + is_menu: bool, +} + // TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return // a width/height hint. maybe Popup(Box) pub struct Popup { contents: T, position: Option, - margin: Margin, - size: (u16, u16), - child_size: (u16, u16), + area: Rect, position_bias: Open, - scroll: usize, + scroll_half_pages: usize, auto_close: bool, ignore_escape_key: bool, id: &'static str, @@ -36,11 +46,9 @@ impl Popup { Self { contents, position: None, - margin: Margin::none(), - size: (0, 0), position_bias: Open::Below, - child_size: (0, 0), - scroll: 0, + area: Rect::new(0, 0, 0, 0), + scroll_half_pages: 0, auto_close: false, ignore_escape_key: false, id, @@ -70,11 +78,6 @@ impl Popup { self } - pub fn margin(mut self, margin: Margin) -> Self { - self.margin = margin; - self - } - pub fn auto_close(mut self, auto_close: bool) -> Self { self.auto_close = auto_close; self @@ -92,28 +95,65 @@ impl Popup { self } - /// Calculate the position where the popup should be rendered and return the coordinates of the - /// top left corner. - pub fn get_rel_position(&mut self, viewport: Rect, editor: &Editor) -> (u16, u16) { - let position = self + pub fn scroll_half_page_down(&mut self) { + self.scroll_half_pages += 1; + } + + pub fn scroll_half_page_up(&mut self) { + self.scroll_half_pages = self.scroll_half_pages.saturating_sub(1); + } + + /// Toggles the Popup's scrollbar. + /// Consider disabling the scrollbar in case the child + /// already has its own. + pub fn with_scrollbar(mut self, enable_scrollbar: bool) -> Self { + self.has_scrollbar = enable_scrollbar; + self + } + + pub fn contents(&self) -> &T { + &self.contents + } + + pub fn contents_mut(&mut self) -> &mut T { + &mut self.contents + } + + pub fn area(&mut self, viewport: Rect, editor: &Editor) -> Rect { + self.render_info(viewport, editor).area + } + + fn render_info(&mut self, viewport: Rect, editor: &Editor) -> RenderInfo { + let mut position = editor.cursor().0.unwrap_or_default(); + if let Some(old_position) = self .position - .get_or_insert_with(|| editor.cursor().0.unwrap_or_default()); + .filter(|old_position| old_position.row == position.row) + { + position = old_position; + } else { + self.position = Some(position); + } - let (width, height) = self.size; + let is_menu = self + .contents + .type_name() + .starts_with("helix_term::ui::menu::Menu"); - // if there's a orientation preference, use that - // if we're on the top part of the screen, do below - // if we're on the bottom part, do above + let mut render_borders = if is_menu { + editor.menu_border() + } else { + editor.popup_border() + }; // -- make sure frame doesn't stick out of bounds let mut rel_x = position.col as u16; let mut rel_y = position.row as u16; - if viewport.width <= rel_x + width { - rel_x = rel_x.saturating_sub((rel_x + width).saturating_sub(viewport.width)); - } - let can_put_below = viewport.height > rel_y + height; - let can_put_above = rel_y.checked_sub(height).is_some(); + // if there's a orientation preference, use that + // if we're on the top part of the screen, do below + // if we're on the bottom part, do above + let can_put_below = viewport.height > rel_y + MIN_HEIGHT; + let can_put_above = rel_y.checked_sub(MIN_HEIGHT).is_some(); let final_pos = match self.position_bias { Open::Below => match can_put_below { true => Open::Below, @@ -125,51 +165,87 @@ impl Popup { }, }; - rel_y = match final_pos { - Open::Above => rel_y.saturating_sub(height), - Open::Below => rel_y + 1, + // compute maximum space available for child + let mut max_height = match final_pos { + Open::Above => rel_y, + Open::Below => viewport.height.saturating_sub(1 + rel_y), }; + max_height = max_height.min(MAX_HEIGHT); + let mut max_width = viewport.width.saturating_sub(2).min(MAX_WIDTH); + render_borders = render_borders && max_height > 3 && max_width > 3; + if render_borders { + max_width -= 2; + max_height -= 2; + } - (rel_x, rel_y) - } - - pub fn get_size(&self) -> (u16, u16) { - (self.size.0, self.size.1) - } + // compute required child size and reclamp + let (mut width, child_height) = self + .contents + .required_size((max_width, max_height)) + .expect("Component needs required_size implemented in order to be embedded in a popup"); - pub fn scroll(&mut self, offset: usize, direction: bool) { - if direction { - let max_offset = self.child_size.1.saturating_sub(self.size.1); - self.scroll = (self.scroll + offset).min(max_offset as usize); + width = width.min(MAX_WIDTH); + let height = if render_borders { + (child_height + 2).min(MAX_HEIGHT) } else { - self.scroll = self.scroll.saturating_sub(offset); + child_height.min(MAX_HEIGHT) + }; + if render_borders { + width += 2; + } + if viewport.width <= rel_x + width + 2 { + rel_x = viewport.width.saturating_sub(width + 2); + width = viewport.width.saturating_sub(rel_x + 2) } - } - - /// Toggles the Popup's scrollbar. - /// Consider disabling the scrollbar in case the child - /// already has its own. - pub fn with_scrollbar(mut self, enable_scrollbar: bool) -> Self { - self.has_scrollbar = enable_scrollbar; - self - } - - pub fn contents(&self) -> &T { - &self.contents - } - pub fn contents_mut(&mut self) -> &mut T { - &mut self.contents + let area = match final_pos { + Open::Above => { + rel_y = rel_y.saturating_sub(height); + Rect::new(rel_x, rel_y, width, position.row as u16 - rel_y) + } + Open::Below => { + rel_y += 1; + let y_max = viewport.bottom().min(height + rel_y); + Rect::new(rel_x, rel_y, width, y_max - rel_y) + } + }; + RenderInfo { + area, + child_height, + render_borders, + is_menu, + } } - pub fn area(&mut self, viewport: Rect, editor: &Editor) -> Rect { - // trigger required_size so we recalculate if the child changed - self.required_size((viewport.width, viewport.height)); - - let (rel_x, rel_y) = self.get_rel_position(viewport, editor); + fn handle_mouse_event( + &mut self, + &MouseEvent { + kind, + column: x, + row: y, + .. + }: &MouseEvent, + ) -> EventResult { + let mouse_is_within_popup = x >= self.area.left() + && x < self.area.right() + && y >= self.area.top() + && y < self.area.bottom(); + + if !mouse_is_within_popup { + return EventResult::Ignored(None); + } - // clip to viewport - viewport.intersection(Rect::new(rel_x, rel_y, self.size.0, self.size.1)) + match kind { + MouseEventKind::ScrollDown if self.has_scrollbar => { + self.scroll_half_page_down(); + EventResult::Consumed(None) + } + MouseEventKind::ScrollUp if self.has_scrollbar => { + self.scroll_half_page_up(); + EventResult::Consumed(None) + } + _ => EventResult::Ignored(None), + } } } @@ -177,6 +253,7 @@ impl Component for Popup { fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult { let key = match event { Event::Key(event) => *event, + Event::Mouse(event) => return self.handle_mouse_event(event), Event::Resize(_, _) => { // TODO: calculate inner area, call component's handle_event with that area return EventResult::Ignored(None); @@ -200,11 +277,11 @@ impl Component for Popup { EventResult::Consumed(Some(close_fn)) } ctrl!('d') => { - self.scroll(self.size.1 as usize / 2, true); + self.scroll_half_page_down(); EventResult::Consumed(None) } ctrl!('u') => { - self.scroll(self.size.1 as usize / 2, false); + self.scroll_half_page_up(); EventResult::Consumed(None) } _ => { @@ -223,63 +300,48 @@ impl Component for Popup { // tab/enter/ctrl-k or whatever will confirm the selection/ ctrl-n/ctrl-p for scroll. } - fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> { - let max_width = 120.min(viewport.0); - let max_height = 26.min(viewport.1.saturating_sub(2)); // add some spacing in the viewport - - let inner = Rect::new(0, 0, max_width, max_height).inner(&self.margin); - - let (width, height) = self - .contents - .required_size((inner.width, inner.height)) - .expect("Component needs required_size implemented in order to be embedded in a popup"); - - self.child_size = (width, height); - self.size = ( - (width + self.margin.width()).min(max_width), - (height + self.margin.height()).min(max_height), - ); - - // re-clamp scroll offset - let max_offset = self.child_size.1.saturating_sub(self.size.1); - self.scroll = self.scroll.min(max_offset as usize); - - Some(self.size) - } - fn render(&mut self, viewport: Rect, surface: &mut Surface, cx: &mut Context) { - let area = self.area(viewport, cx.editor); - cx.scroll = Some(self.scroll); + let RenderInfo { + area, + child_height, + render_borders, + is_menu, + } = self.render_info(viewport, cx.editor); + self.area = area; // clear area - let background = cx.editor.theme.get("ui.popup"); - surface.clear_with(area, background); - - let render_borders = cx.editor.popup_border(); - - let inner = if self - .contents - .type_name() - .starts_with("helix_term::ui::menu::Menu") - { - area + let background = if is_menu { + // TODO: consistently style menu + cx.editor + .theme + .try_get("ui.menu") + .unwrap_or_else(|| cx.editor.theme.get("ui.text")) } else { - area.inner(&self.margin) + cx.editor.theme.get("ui.popup") }; + surface.clear_with(area, background); - let border = usize::from(render_borders); + let mut inner = area; if render_borders { - Widget::render(Block::default().borders(Borders::ALL), area, surface); + inner = area.inner(Margin::all(1)); + Widget::render(Block::bordered(), area, surface); } + let border = usize::from(render_borders); + let max_offset = child_height.saturating_sub(inner.height) as usize; + let half_page_size = (inner.height / 2) as usize; + let scroll = max_offset.min(self.scroll_half_pages * half_page_size); + if half_page_size > 0 { + self.scroll_half_pages = scroll / half_page_size; + } + cx.scroll = Some(scroll); self.contents.render(inner, surface, cx); // render scrollbar if contents do not fit if self.has_scrollbar { - let win_height = (inner.height as usize).saturating_sub(2 * border); - let len = (self.child_size.1 as usize).saturating_sub(2 * border); + let win_height = inner.height as usize; + let len = child_height as usize; let fits = len <= win_height; - let scroll = self.scroll; let scroll_style = cx.editor.theme.get("ui.menu.scroll"); const fn div_ceil(a: usize, b: usize) -> usize { @@ -293,7 +355,8 @@ impl Component for Popup { let mut cell; for i in 0..win_height { - cell = &mut surface[(inner.right() - 1, inner.top() + (border + i) as u16)]; + cell = + &mut surface[(inner.right() - 1 + border as u16, inner.top() + i as u16)]; let half_block = if render_borders { "▌" } else { "▐" }; diff --git a/helix-term/src/ui/prompt.rs b/helix-term/src/ui/prompt.rs index a6ee7f05d..14b242df6 100644 --- a/helix-term/src/ui/prompt.rs +++ b/helix-term/src/ui/prompt.rs @@ -2,12 +2,13 @@ use crate::compositor::{Component, Compositor, Context, Event, EventResult}; use crate::{alt, ctrl, key, shift, ui}; use arc_swap::ArcSwap; use helix_core::syntax; +use helix_view::document::Mode; use helix_view::input::KeyEvent; use helix_view::keyboard::KeyCode; use std::sync::Arc; use std::{borrow::Cow, ops::RangeFrom}; use tui::buffer::Buffer as Surface; -use tui::widgets::{Block, Borders, Widget}; +use tui::widgets::{Block, Widget}; use helix_core::{ unicode::segmentation::GraphemeCursor, unicode::width::UnicodeWidthStr, Position, @@ -457,12 +458,11 @@ impl Prompt { let background = theme.get("ui.help"); surface.clear_with(area, background); - let block = Block::default() + let block = Block::bordered() // .title(self.title.as_str()) - .borders(Borders::ALL) .border_style(background); - let inner = block.inner(area).inner(&Margin::horizontal(1)); + let inner = block.inner(area).inner(Margin::horizontal(1)); block.render(area, surface); text.render(inner, surface, cx); @@ -663,7 +663,7 @@ impl Component for Prompt { self.render_prompt(area, surface, cx) } - fn cursor(&self, area: Rect, _editor: &Editor) -> (Option, CursorKind) { + fn cursor(&self, area: Rect, editor: &Editor) -> (Option, CursorKind) { let line = area.height as usize - 1; ( Some(Position::new( @@ -672,7 +672,7 @@ impl Component for Prompt { + self.prompt.len() + UnicodeWidthStr::width(&self.line[..self.cursor]), )), - CursorKind::Block, + editor.config().cursor_shape.from_mode(Mode::Insert), ) } } diff --git a/helix-term/src/ui/spinner.rs b/helix-term/src/ui/spinner.rs index 379c4489f..9ce610555 100644 --- a/helix-term/src/ui/spinner.rs +++ b/helix-term/src/ui/spinner.rs @@ -1,16 +1,18 @@ use std::{collections::HashMap, time::Instant}; +use helix_lsp::LanguageServerId; + #[derive(Default, Debug)] pub struct ProgressSpinners { - inner: HashMap, + inner: HashMap, } impl ProgressSpinners { - pub fn get(&self, id: usize) -> Option<&Spinner> { + pub fn get(&self, id: LanguageServerId) -> Option<&Spinner> { self.inner.get(&id) } - pub fn get_or_create(&mut self, id: usize) -> &mut Spinner { + pub fn get_or_create(&mut self, id: LanguageServerId) -> &mut Spinner { self.inner.entry(id).or_default() } } diff --git a/helix-term/src/ui/statusline.rs b/helix-term/src/ui/statusline.rs index 9871828ee..7437cbd07 100644 --- a/helix-term/src/ui/statusline.rs +++ b/helix-term/src/ui/statusline.rs @@ -142,6 +142,7 @@ where helix_view::editor::StatusLineElement::Spinner => render_lsp_spinner, helix_view::editor::StatusLineElement::FileBaseName => render_file_base_name, helix_view::editor::StatusLineElement::FileName => render_file_name, + helix_view::editor::StatusLineElement::FileAbsolutePath => render_file_absolute_path, helix_view::editor::StatusLineElement::FileModificationIndicator => { render_file_modification_indicator } @@ -430,6 +431,22 @@ where write(context, title, None); } +fn render_file_absolute_path(context: &mut RenderContext, write: F) +where + F: Fn(&mut RenderContext, String, Option