Merge branch 'helix-editor:master' into trim-colons-from-paths

pull/9963/head
Christian Schneider 7 months ago committed by GitHub
commit b322752f04
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup mdBook - name: Setup mdBook
uses: peaceiris/actions-mdbook@v1 uses: peaceiris/actions-mdbook@v2
with: with:
mdbook-version: 'latest' mdbook-version: 'latest'
# mdbook-version: '0.4.8' # mdbook-version: '0.4.8'
@ -27,14 +27,14 @@ jobs:
echo "OUTDIR=$OUTDIR" >> $GITHUB_ENV echo "OUTDIR=$OUTDIR" >> $GITHUB_ENV
- name: Deploy stable - name: Deploy stable
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v4
if: startswith(github.ref, 'refs/tags/') if: startswith(github.ref, 'refs/tags/')
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book/book publish_dir: ./book/book
- name: Deploy - name: Deploy
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v4
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book/book publish_dir: ./book/book

@ -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-<lower-ascii>` 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) # 23.10 (2023-10-24)
A big shout out to all the contributors! We had 118 contributors in this release. A big shout out to all the contributors! We had 118 contributors in this release.

230
Cargo.lock generated

@ -62,15 +62,15 @@ dependencies = [
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.81" version = "1.0.82"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519"
[[package]] [[package]]
name = "arc-swap" name = "arc-swap"
version = "1.7.0" version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b3d0060af21e8d11a926981cc00c6c1541aa91dd64b9f881985c3da1094425f" checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457"
[[package]] [[package]]
name = "autocfg" name = "autocfg"
@ -136,9 +136,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.0.90" version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" checksum = "d32a725bc159af97c3e629873bb9f88fb8cf8a4867175f76dc987815ea07c83b"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
@ -159,9 +159,9 @@ dependencies = [
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.35" version = "0.4.38"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
dependencies = [ dependencies = [
"android-tzdata", "android-tzdata",
"iana-time-zone", "iana-time-zone",
@ -171,9 +171,9 @@ dependencies = [
[[package]] [[package]]
name = "clipboard-win" name = "clipboard-win"
version = "5.3.0" version = "5.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d517d4b86184dbb111d3556a10f1c8a04da7428d2987bf1081602bf11c3aa9ee" checksum = "79f4473f5144e20d9aceaf2972478f06ddf687831eafeeb434fbaf0acc4144ad"
dependencies = [ dependencies = [
"error-code", "error-code",
] ]
@ -338,6 +338,19 @@ dependencies = [
"syn 2.0.48", "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]] [[package]]
name = "dunce" name = "dunce"
version = "1.0.4" version = "1.0.4"
@ -352,9 +365,9 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]] [[package]]
name = "encoding_rs" name = "encoding_rs"
version = "0.8.33" version = "0.8.34"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
] ]
@ -525,9 +538,9 @@ checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e"
[[package]] [[package]]
name = "gix" name = "gix"
version = "0.61.0" version = "0.62.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4e0e59a44bf00de058ee98d6ecf3c9ed8f8842c1da642258ae4120d41ded8f7" checksum = "5631c64fb4cd48eee767bf98a3cbc5c9318ef3bb71074d4c099a2371510282b6"
dependencies = [ dependencies = [
"gix-actor", "gix-actor",
"gix-attributes", "gix-attributes",
@ -536,6 +549,7 @@ dependencies = [
"gix-config", "gix-config",
"gix-date", "gix-date",
"gix-diff", "gix-diff",
"gix-dir",
"gix-discover", "gix-discover",
"gix-features", "gix-features",
"gix-filter", "gix-filter",
@ -557,6 +571,7 @@ dependencies = [
"gix-revision", "gix-revision",
"gix-revwalk", "gix-revwalk",
"gix-sec", "gix-sec",
"gix-status",
"gix-submodule", "gix-submodule",
"gix-tempfile", "gix-tempfile",
"gix-trace", "gix-trace",
@ -648,9 +663,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-config" name = "gix-config"
version = "0.36.0" version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62129c75e4b6229fe15fb9838cdc00c655e87105b651e4edd7c183fc5288b5d1" checksum = "7580e05996e893347ad04e1eaceb92e1c0e6a3ffe517171af99bf6b6df0ca6e5"
dependencies = [ dependencies = [
"bstr", "bstr",
"gix-config-value", "gix-config-value",
@ -694,13 +709,41 @@ dependencies = [
[[package]] [[package]]
name = "gix-diff" name = "gix-diff"
version = "0.42.0" version = "0.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78e605593c2ef74980a534ade0909c7dc57cca72baa30cbb67d2dda621f99ac4" checksum = "a5fbc24115b957346cd23fb0f47d830eb799c46c89cdcf2f5acc9bf2938c2d01"
dependencies = [ dependencies = [
"bstr", "bstr",
"gix-command",
"gix-filter",
"gix-fs",
"gix-hash", "gix-hash",
"gix-object", "gix-object",
"gix-path",
"gix-tempfile",
"gix-trace",
"gix-worktree",
"imara-diff",
"thiserror",
]
[[package]]
name = "gix-dir"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6943a1f213ad7a060a0548ece229be53f3c2151534b126446ce3533eaf5f14c"
dependencies = [
"bstr",
"gix-discover",
"gix-fs",
"gix-ignore",
"gix-index",
"gix-object",
"gix-path",
"gix-pathspec",
"gix-trace",
"gix-utils",
"gix-worktree",
"thiserror", "thiserror",
] ]
@ -741,9 +784,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-filter" name = "gix-filter"
version = "0.11.0" version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd71bf3e64d8fb5d5635d4166ca5a36fe56b292ffff06eab1d93ea47fd5beb89" checksum = "5c0d1f01af62bfd2fb3dd291acc2b29d4ab3e96ad52a679174626508ce98ef12"
dependencies = [ dependencies = [
"bstr", "bstr",
"encoding_rs", "encoding_rs",
@ -762,9 +805,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-fs" name = "gix-fs"
version = "0.10.1" version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "634b8a743b0aae03c1a74ee0ea24e8c5136895efac64ce52b3ea106e1c6f0613" checksum = "e2184c40e7910529677831c8b481acf788ffd92427ed21fad65b6aa637e631b8"
dependencies = [ dependencies = [
"gix-features", "gix-features",
"gix-utils", "gix-utils",
@ -818,9 +861,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-index" name = "gix-index"
version = "0.31.1" version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "549621f13d9ccf325a7de45506a3266af0d08f915181c5687abb5e8669bfd2e6" checksum = "3383122cf18655ef4c097c0b935bba5eb56983947959aaf3b0ceb1949d4dd371"
dependencies = [ dependencies = [
"bitflags 2.5.0", "bitflags 2.5.0",
"bstr", "bstr",
@ -886,9 +929,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-odb" name = "gix-odb"
version = "0.59.0" version = "0.60.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81b55378c719693380f66d9dd21ce46721eed2981d8789fc698ec1ada6fa176e" checksum = "e8bbb43d2fefdc4701ffdf9224844d05b136ae1b9a73c2f90710c8dd27a93503"
dependencies = [ dependencies = [
"arc-swap", "arc-swap",
"gix-date", "gix-date",
@ -906,9 +949,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-pack" name = "gix-pack"
version = "0.49.0" version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6391aeaa030ad64aba346a9f5c69bb1c4e5c6fb4411705b03b40b49d8614ec30" checksum = "b58bad27c7677fa6b587aab3a1aca0b6c97373bd371a0a4290677c838c9bcaf1"
dependencies = [ dependencies = [
"clru", "clru",
"gix-chunk", "gix-chunk",
@ -926,9 +969,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-packetline-blocking" name = "gix-packetline-blocking"
version = "0.17.3" version = "0.17.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca8ef6dd3ea50e26f3bf572e90c034d033c804d340cd1eb386392f184a9ba2f7" checksum = "c31d42378a3d284732e4d589979930d0d253360eccf7ec7a80332e5ccb77e14a"
dependencies = [ dependencies = [
"bstr", "bstr",
"faster-hex", "faster-hex",
@ -951,9 +994,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-pathspec" name = "gix-pathspec"
version = "0.7.2" version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a96ed0e71ce9084a471fddfa74e842576a7cbf02fe8bd50388017ac461aed97" checksum = "d479789f3abd10f68a709454ce04cd68b54092ee882c8622ae3aa1bb9bf8496c"
dependencies = [ dependencies = [
"bitflags 2.5.0", "bitflags 2.5.0",
"bstr", "bstr",
@ -1054,6 +1097,28 @@ dependencies = [
"windows-sys 0.52.0", "windows-sys 0.52.0",
] ]
[[package]]
name = "gix-status"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50c413bfd2952e4ee92e48438dac3c696f3555e586a34d184a427f6bedd1e4f9"
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]] [[package]]
name = "gix-submodule" name = "gix-submodule"
version = "0.10.0" version = "0.10.0"
@ -1075,6 +1140,7 @@ version = "13.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d337955b7af00fb87120d053d87cdfb422a80b9ff7a3aa4057a99c79422dc30" checksum = "2d337955b7af00fb87120d053d87cdfb422a80b9ff7a3aa4057a99c79422dc30"
dependencies = [ dependencies = [
"dashmap",
"gix-fs", "gix-fs",
"libc", "libc",
"once_cell", "once_cell",
@ -1084,16 +1150,17 @@ dependencies = [
[[package]] [[package]]
name = "gix-trace" name = "gix-trace"
version = "0.1.8" version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b838b2db8f62c9447d483a4c28d251b67fee32741a82cb4d35e9eb4e9fdc5ab" checksum = "f924267408915fddcd558e3f37295cc7d6a3e50f8bd8b606cee0808c3915157e"
[[package]] [[package]]
name = "gix-traverse" name = "gix-traverse"
version = "0.38.0" version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95aef84bc777025403a09788b1e4815c06a19332e9e5d87a955e1ed7da9bf0cf" checksum = "f4029ec209b0cc480d209da3837a42c63801dd8548f09c1f4502c60accb62aeb"
dependencies = [ dependencies = [
"bitflags 2.5.0",
"gix-commitgraph", "gix-commitgraph",
"gix-date", "gix-date",
"gix-hash", "gix-hash",
@ -1106,9 +1173,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-url" name = "gix-url"
version = "0.27.2" version = "0.27.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f0b24f3ecc79a5a53539de9c2e99425d0ef23feacdcf3faac983aa9a2f26849" checksum = "0db829ebdca6180fbe32be7aed393591df6db4a72dbbc0b8369162390954d1cf"
dependencies = [ dependencies = [
"bstr", "bstr",
"gix-features", "gix-features",
@ -1120,10 +1187,11 @@ dependencies = [
[[package]] [[package]]
name = "gix-utils" name = "gix-utils"
version = "0.1.11" version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0066432d4c277f9877f091279a597ea5331f68ca410efc874f0bdfb1cd348f92" checksum = "35192df7fd0fa112263bad8021e2df7167df4cc2a6e6d15892e1e55621d3d4dc"
dependencies = [ dependencies = [
"bstr",
"fastrand", "fastrand",
"unicode-normalization", "unicode-normalization",
] ]
@ -1140,9 +1208,9 @@ dependencies = [
[[package]] [[package]]
name = "gix-worktree" name = "gix-worktree"
version = "0.32.0" version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe78e03af9eec168eb187e05463a981c57f0a915f64b1788685a776bd2ef969c" checksum = "359a87dfef695b5f91abb9a424c947edca82768f34acfc269659f66174a510b4"
dependencies = [ dependencies = [
"bstr", "bstr",
"gix-attributes", "gix-attributes",
@ -1224,7 +1292,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-core" name = "helix-core"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"ahash", "ahash",
"arc-swap", "arc-swap",
@ -1261,7 +1329,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-dap" name = "helix-dap"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"fern", "fern",
@ -1276,7 +1344,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-event" name = "helix-event"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"ahash", "ahash",
"anyhow", "anyhow",
@ -1290,7 +1358,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-loader" name = "helix-loader"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"cc", "cc",
@ -1309,7 +1377,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-lsp" name = "helix-lsp"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arc-swap", "arc-swap",
@ -1325,6 +1393,7 @@ dependencies = [
"parking_lot", "parking_lot",
"serde", "serde",
"serde_json", "serde_json",
"slotmap",
"thiserror", "thiserror",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@ -1332,23 +1401,26 @@ dependencies = [
[[package]] [[package]]
name = "helix-parsec" name = "helix-parsec"
version = "23.10.0" version = "24.3.0"
[[package]] [[package]]
name = "helix-stdx" name = "helix-stdx"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"bitflags 2.5.0",
"dunce", "dunce",
"etcetera", "etcetera",
"regex-cursor", "regex-cursor",
"ropey", "ropey",
"rustix",
"tempfile", "tempfile",
"which", "which",
"windows-sys 0.52.0",
] ]
[[package]] [[package]]
name = "helix-term" name = "helix-term"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arc-swap", "arc-swap",
@ -1391,7 +1463,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-tui" name = "helix-tui"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"bitflags 2.5.0", "bitflags 2.5.0",
"cassowary", "cassowary",
@ -1407,7 +1479,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-vcs" name = "helix-vcs"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arc-swap", "arc-swap",
@ -1423,7 +1495,7 @@ dependencies = [
[[package]] [[package]]
name = "helix-view" name = "helix-view"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"arc-swap", "arc-swap",
@ -1448,6 +1520,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"slotmap", "slotmap",
"tempfile",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
"toml", "toml",
@ -1544,9 +1617,9 @@ dependencies = [
[[package]] [[package]]
name = "indoc" name = "indoc"
version = "2.0.4" version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5"
[[package]] [[package]]
name = "is-docker" name = "is-docker"
@ -1923,9 +1996,9 @@ dependencies = [
[[package]] [[package]]
name = "regex" name = "regex"
version = "1.10.3" version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@ -1981,9 +2054,9 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.31" version = "0.38.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
dependencies = [ dependencies = [
"bitflags 2.5.0", "bitflags 2.5.0",
"errno", "errno",
@ -2021,18 +2094,18 @@ checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.197" version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.197" version = "1.0.198"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -2041,9 +2114,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.114" version = "1.0.116"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@ -2144,9 +2217,9 @@ dependencies = [
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.13.1" version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "smartstring" name = "smartstring"
@ -2325,9 +2398,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.36.0" version = "1.37.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931" checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"bytes", "bytes",
@ -2400,9 +2473,9 @@ dependencies = [
[[package]] [[package]]
name = "tree-sitter" name = "tree-sitter"
version = "0.22.2" version = "0.22.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdb9c9f15eae91dcd00ee0d86a281d16e6263786991b662b34fa9632c21a046b" checksum = "688200d842c76dd88f9a7719ecb0483f79f5a766fb1c100756d5d8a059abc71b"
dependencies = [ dependencies = [
"cc", "cc",
"regex", "regex",
@ -2558,15 +2631,14 @@ checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d"
[[package]] [[package]]
name = "which" name = "which"
version = "6.0.0" version = "6.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fa5e0c10bf77f44aac573e498d1a82d5fbd5e91f6fc0a99e7be4b38e85e101c" checksum = "8211e4f58a2b2805adfbefbc07bab82958fc91e3836339b1ab7ae32465dce0d7"
dependencies = [ dependencies = [
"either", "either",
"home", "home",
"once_cell",
"rustix", "rustix",
"windows-sys 0.52.0", "winsafe",
] ]
[[package]] [[package]]
@ -2816,9 +2888,15 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "winsafe"
version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
[[package]] [[package]]
name = "xtask" name = "xtask"
version = "23.10.0" version = "24.3.0"
dependencies = [ dependencies = [
"helix-core", "helix-core",
"helix-loader", "helix-loader",

@ -39,9 +39,10 @@ package.helix-term.opt-level = 2
[workspace.dependencies] [workspace.dependencies]
tree-sitter = { version = "0.22" } tree-sitter = { version = "0.22" }
nucleo = "0.2.0" nucleo = "0.2.0"
slotmap = "1.0.7"
[workspace.package] [workspace.package]
version = "23.10.0" version = "24.3.0"
edition = "2021" edition = "2021"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"] authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
categories = ["editor"] categories = ["editor"]

@ -28,6 +28,8 @@
"label" = "magenta" "label" = "magenta"
"namespace" = "magenta" "namespace" = "magenta"
"ui.help" = { fg = "white", bg = "black" } "ui.help" = { fg = "white", bg = "black" }
"ui.virtual.jump-label" = { fg = "blue", modifiers = ["bold", "underlined"] }
"ui.virtual.ruler" = { bg = "black" }
"markup.heading" = "blue" "markup.heading" = "blue"
"markup.list" = "red" "markup.list" = "red"

@ -68,6 +68,7 @@ Its settings will be merged with the configuration directory `config.toml` and t
| `insert-final-newline` | Whether to automatically insert a trailing line-ending on write if missing | `true` | | `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` | | `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` | `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 ### `[editor.statusline]` Section
@ -75,7 +76,7 @@ Allows configuring the statusline at the bottom of the editor.
The configuration distinguishes between three areas of the status line: The configuration distinguishes between three areas of the status line:
`[ ... ... LEFT ... ... | ... ... ... ... CENTER ... ... ... ... | ... ... RIGHT ... ... ]` `[ ... ... LEFT ... ... | ... ... ... CENTER ... ... ... | ... ... RIGHT ... ... ]`
Statusline elements can be defined as follows: Statusline elements can be defined as follows:
@ -178,7 +179,7 @@ All git related options are only enabled in a git repository.
|`git-ignore` | Enables reading `.gitignore` 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-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` |`git-exclude` | Enables reading `.git/info/exclude` files | `true`
|`max-depth` | Set with an integer value for maximum depth to recurse | Defaults to `None`. |`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. 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.
@ -224,7 +225,7 @@ Additionally, this setting can be used in a language config. Unless
the editor setting is `false`, this will override the editor config in the editor setting is `false`, this will override the editor config in
documents with this language. documents with this language.
Example `languages.toml` that adds <> and removes '' Example `languages.toml` that adds `<>` and removes `''`
```toml ```toml
[[language]] [[language]]
@ -254,8 +255,8 @@ Options for rendering whitespace with visible characters. Use `:set whitespace.r
| Key | Description | Default | | 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"` | | `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`, `newline` or `tabpad` | See example below | | `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 Example
@ -266,11 +267,14 @@ render = "all"
[editor.whitespace.render] [editor.whitespace.render]
space = "all" space = "all"
tab = "all" tab = "all"
nbsp = "none"
nnbsp = "none"
newline = "none" newline = "none"
[editor.whitespace.characters] [editor.whitespace.characters]
space = "·" space = "·"
nbsp = "⍽" nbsp = "⍽"
nnbsp = "␣"
tab = "→" tab = "→"
newline = "⏎" newline = "⏎"
tabpad = "·" # Tabs will look like "→···" (depending on tab width) tabpad = "·" # Tabs will look like "→···" (depending on tab width)

@ -1,6 +1,7 @@
| Language | Syntax Highlighting | Treesitter Textobjects | Auto Indent | Default LSP | | Language | Syntax Highlighting | Treesitter Textobjects | Auto Indent | Default LSP |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| ada | ✓ | ✓ | | `ada_language_server`, `ada_language_server` | | ada | ✓ | ✓ | | `ada_language_server`, `ada_language_server` |
| adl | ✓ | ✓ | ✓ | |
| agda | ✓ | | | | | agda | ✓ | | | |
| astro | ✓ | | | | | astro | ✓ | | | |
| awk | ✓ | ✓ | | `awk-language-server` | | awk | ✓ | ✓ | | `awk-language-server` |
@ -9,6 +10,7 @@
| beancount | ✓ | | | | | beancount | ✓ | | | |
| bibtex | ✓ | | | `texlab` | | bibtex | ✓ | | | `texlab` |
| bicep | ✓ | | | `bicep-langserver` | | bicep | ✓ | | | `bicep-langserver` |
| bitbake | ✓ | | | `bitbake-language-server` |
| blade | ✓ | | | | | blade | ✓ | | | |
| blueprint | ✓ | | | `blueprint-compiler` | | blueprint | ✓ | | | `blueprint-compiler` |
| c | ✓ | ✓ | ✓ | `clangd` | | c | ✓ | ✓ | ✓ | `clangd` |
@ -36,6 +38,7 @@
| dockerfile | ✓ | | | `docker-langserver` | | dockerfile | ✓ | | | `docker-langserver` |
| dot | ✓ | | | `dot-language-server` | | dot | ✓ | | | `dot-language-server` |
| dtd | ✓ | | | | | dtd | ✓ | | | |
| earthfile | ✓ | ✓ | ✓ | `earthlyls` |
| edoc | ✓ | | | | | edoc | ✓ | | | |
| eex | ✓ | | | | | eex | ✓ | | | |
| ejs | ✓ | | | | | ejs | ✓ | | | |
@ -68,7 +71,7 @@
| gomod | ✓ | | | `gopls` | | gomod | ✓ | | | `gopls` |
| gotmpl | ✓ | | | `gopls` | | gotmpl | ✓ | | | `gopls` |
| gowork | ✓ | | | `gopls` | | gowork | ✓ | | | `gopls` |
| graphql | ✓ | | | `graphql-lsp` | | graphql | ✓ | | | `graphql-lsp` |
| groovy | ✓ | | | | | groovy | ✓ | | | |
| hare | ✓ | | | | | hare | ✓ | | | |
| haskell | ✓ | ✓ | | `haskell-language-server-wrapper` | | haskell | ✓ | ✓ | | `haskell-language-server-wrapper` |
@ -80,7 +83,7 @@
| hoon | ✓ | | | | | hoon | ✓ | | | |
| hosts | ✓ | | | | | hosts | ✓ | | | |
| html | ✓ | | | `vscode-html-language-server` | | html | ✓ | | | `vscode-html-language-server` |
| hurl | ✓ | | ✓ | | | hurl | ✓ | | ✓ | |
| hyprlang | ✓ | | ✓ | | | hyprlang | ✓ | | ✓ | |
| idris | | | | `idris2-lsp` | | idris | | | | `idris2-lsp` |
| iex | ✓ | | | | | iex | ✓ | | | |
@ -90,7 +93,7 @@
| javascript | ✓ | ✓ | ✓ | `typescript-language-server` | | javascript | ✓ | ✓ | ✓ | `typescript-language-server` |
| jinja | ✓ | | | | | jinja | ✓ | | | |
| jsdoc | ✓ | | | | | jsdoc | ✓ | | | |
| json | ✓ | | ✓ | `vscode-json-language-server` | | json | ✓ | | ✓ | `vscode-json-language-server` |
| json5 | ✓ | | | | | json5 | ✓ | | | |
| jsonc | ✓ | | ✓ | `vscode-json-language-server` | | jsonc | ✓ | | ✓ | `vscode-json-language-server` |
| jsonnet | ✓ | | | `jsonnet-language-server` | | jsonnet | ✓ | | | `jsonnet-language-server` |
@ -98,10 +101,11 @@
| julia | ✓ | ✓ | ✓ | `julia` | | julia | ✓ | ✓ | ✓ | `julia` |
| just | ✓ | ✓ | ✓ | | | just | ✓ | ✓ | ✓ | |
| kdl | ✓ | ✓ | ✓ | | | kdl | ✓ | ✓ | ✓ | |
| koka | ✓ | | ✓ | | | koka | ✓ | | ✓ | `koka` |
| kotlin | ✓ | | | `kotlin-language-server` | | kotlin | ✓ | | | `kotlin-language-server` |
| latex | ✓ | ✓ | | `texlab` | | latex | ✓ | ✓ | | `texlab` |
| ld | ✓ | | ✓ | | | ld | ✓ | | ✓ | |
| ldif | ✓ | | | |
| lean | ✓ | | | `lean` | | lean | ✓ | | | `lean` |
| ledger | ✓ | | | | | ledger | ✓ | | | |
| llvm | ✓ | ✓ | ✓ | | | llvm | ✓ | ✓ | ✓ | |
@ -118,6 +122,7 @@
| mermaid | ✓ | | | | | mermaid | ✓ | | | |
| meson | ✓ | | ✓ | | | meson | ✓ | | ✓ | |
| mint | | | | `mint` | | mint | | | | `mint` |
| move | ✓ | | | |
| msbuild | ✓ | | ✓ | | | msbuild | ✓ | | ✓ | |
| nasm | ✓ | ✓ | | | | nasm | ✓ | ✓ | | |
| nickel | ✓ | | ✓ | `nls` | | nickel | ✓ | | ✓ | `nls` |
@ -128,6 +133,7 @@
| ocaml | ✓ | | ✓ | `ocamllsp` | | ocaml | ✓ | | ✓ | `ocamllsp` |
| ocaml-interface | ✓ | | | `ocamllsp` | | ocaml-interface | ✓ | | | `ocamllsp` |
| odin | ✓ | | ✓ | `ols` | | odin | ✓ | | ✓ | `ols` |
| ohm | ✓ | ✓ | ✓ | |
| opencl | ✓ | ✓ | ✓ | `clangd` | | opencl | ✓ | ✓ | ✓ | `clangd` |
| openscad | ✓ | | | `openscad-lsp` | | openscad | ✓ | | | `openscad-lsp` |
| org | ✓ | | | | | org | ✓ | | | |
@ -135,6 +141,7 @@
| passwd | ✓ | | | | | passwd | ✓ | | | |
| pem | ✓ | | | | | pem | ✓ | | | |
| perl | ✓ | ✓ | ✓ | `perlnavigator` | | perl | ✓ | ✓ | ✓ | `perlnavigator` |
| pest | ✓ | ✓ | ✓ | `pest-language-server` |
| php | ✓ | ✓ | ✓ | `intelephense` | | php | ✓ | ✓ | ✓ | `intelephense` |
| php-only | ✓ | | | | | php-only | ✓ | | | |
| pkgbuild | ✓ | ✓ | ✓ | `pkgbuild-language-server`, `bash-language-server` | | pkgbuild | ✓ | ✓ | ✓ | `pkgbuild-language-server`, `bash-language-server` |
@ -169,7 +176,7 @@
| smali | ✓ | | ✓ | | | smali | ✓ | | ✓ | |
| smithy | ✓ | | | `cs` | | smithy | ✓ | | | `cs` |
| sml | ✓ | | | | | sml | ✓ | | | |
| solidity | ✓ | | | `solc` | | solidity | ✓ | | | `solc` |
| spicedb | ✓ | | | | | spicedb | ✓ | | | |
| sql | ✓ | | | | | sql | ✓ | | | |
| sshclientconfig | ✓ | | | | | sshclientconfig | ✓ | | | |
@ -183,15 +190,16 @@
| tablegen | ✓ | ✓ | ✓ | | | tablegen | ✓ | ✓ | ✓ | |
| tact | ✓ | ✓ | ✓ | | | tact | ✓ | ✓ | ✓ | |
| task | ✓ | | | | | task | ✓ | | | |
| tcl | ✓ | | ✓ | |
| templ | ✓ | | | `templ` | | templ | ✓ | | | `templ` |
| tfvars | ✓ | | ✓ | `terraform-ls` | | tfvars | ✓ | | ✓ | `terraform-ls` |
| todotxt | ✓ | | | | | todotxt | ✓ | | | |
| toml | ✓ | | | `taplo` | | toml | ✓ | | | `taplo` |
| tsq | ✓ | | | | | tsq | ✓ | | | |
| tsx | ✓ | ✓ | ✓ | `typescript-language-server` | | tsx | ✓ | ✓ | ✓ | `typescript-language-server` |
| twig | ✓ | | | | | twig | ✓ | | | |
| typescript | ✓ | ✓ | ✓ | `typescript-language-server` | | typescript | ✓ | ✓ | ✓ | `typescript-language-server` |
| typst | ✓ | | | `typst-lsp` | | typst | ✓ | | | `tinymist`, `typst-lsp` |
| ungrammar | ✓ | | | | | ungrammar | ✓ | | | |
| unison | ✓ | | ✓ | | | unison | ✓ | | ✓ | |
| uxntal | ✓ | | | | | uxntal | ✓ | | | |
@ -209,6 +217,7 @@
| wren | ✓ | ✓ | ✓ | | | wren | ✓ | ✓ | ✓ | |
| xit | ✓ | | | | | xit | ✓ | | | |
| xml | ✓ | | ✓ | | | xml | ✓ | | ✓ | |
| xtc | ✓ | | | |
| yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` | | yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` |
| yuck | ✓ | | | | | yuck | ✓ | | | |
| zig | ✓ | ✓ | ✓ | `zls` | | zig | ✓ | ✓ | ✓ | `zls` |

@ -87,3 +87,4 @@
| `:redraw` | Clear and re-render the whole UI | | `:redraw` | Clear and re-render the whole UI |
| `:move` | Move the current buffer and its corresponding file to a different path | | `: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 | | `:yank-diagnostic` | Yank diagnostic(s) under primary cursor to register, or clipboard by default |
| `:read`, `:r` | Load a file into buffer |

@ -25,6 +25,8 @@ The following [captures][tree-sitter-captures] are recognized:
| `parameter.inside` | | `parameter.inside` |
| `comment.inside` | | `comment.inside` |
| `comment.around` | | `comment.around` |
| `entry.inside` |
| `entry.around` |
[Example query files][textobject-examples] can be found in the helix GitHub repository. [Example query files][textobject-examples] can be found in the helix GitHub repository.

@ -24,6 +24,8 @@
> 💡 Mappings marked (**TS**) require a tree-sitter grammar for the file type. > 💡 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
Normal mode is the default mode when you launch helix. You can return to it from other modes by pressing the `Escape` key. 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 +51,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` | | `T` | Find 'till previous char | `till_prev_char` |
| `F` | Find previous char | `find_prev_char` | | `F` | Find previous char | `find_prev_char` |
| `G` | Go to line number `<n>` | `goto_line` | | `G` | Go to line number `<n>` | `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` | | `Home` | Move to the start of the line | `goto_line_start` |
| `End` | Move to the end of the line | `goto_line_end` | | `End` | Move to the end of the line | `goto_line_end` |
| `Ctrl-b`, `PageUp` | Move page up | `page_up` | | `Ctrl-b`, `PageUp` | Move page up | `page_up` |
@ -224,6 +226,7 @@ Jumps to various locations.
| `.` | Go to last modification in current file | `goto_last_modification` | | `.` | Go to last modification in current file | `goto_last_modification` |
| `j` | Move down textual (instead of visual) line | `move_line_down` | | `j` | Move down textual (instead of visual) line | `move_line_down` |
| `k` | Move up textual (instead of visual) line | `move_line_up` | | `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 #### Match mode
@ -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` | | `F` | Open file picker at current working directory | `file_picker_in_current_directory` |
| `b` | Open buffer picker | `buffer_picker` | | `b` | Open buffer picker | `buffer_picker` |
| `j` | Open jumplist picker | `jumplist_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` | | `k` | Show documentation for item under cursor in a [popup](#popup) (**LSP**) | `hover` |
| `s` | Open document symbol picker (**LSP**) | `symbol_picker` | | `s` | Open document symbol picker (**LSP**) | `symbol_picker` |
| `S` | Open workspace symbol picker (**LSP**) | `workspace_symbol_picker` | | `S` | Open workspace symbol picker (**LSP**) | `workspace_symbol_picker` |

@ -1,7 +1,7 @@
# Language Support # Language Support
The following languages and Language Servers are supported. To use 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. appropriate Language Server.
You can check the language support in your installed helix version with `hx --health`. 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}} {{#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 [lang-config]: ./languages.md
[adding-languages]: ./guides/adding_languages.md [adding-languages]: ./guides/adding_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. 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`, 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. it's often useful to only enable/disable certain language-server features for these language servers.

@ -36,13 +36,6 @@ For inspiration, you can find the default `theme.toml`
user-submitted themes user-submitted themes
[here](https://github.com/helix-editor/helix/blob/master/runtime/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 <name>
```
## The details of theme creation ## The details of theme creation
@ -186,6 +179,7 @@ We use a similar set of scopes as
- `parameter` - Function parameters - `parameter` - Function parameters
- `other` - `other`
- `member` - Fields of composite data types (e.g. structs, unions) - `member` - Fields of composite data types (e.g. structs, unions)
- `private` - Private fields that use a unique syntax (currently just ECMAScript-based languages)
- `label` - `label`
@ -213,6 +207,7 @@ We use a similar set of scopes as
- `function` - `function`
- `builtin` - `builtin`
- `method` - `method`
- `private` - Private methods that use a unique syntax (currently just ECMAScript-based languages)
- `macro` - `macro`
- `special` (preprocessor in C) - `special` (preprocessor in C)
@ -251,6 +246,7 @@ We use a similar set of scopes as
- `gutter` - gutter indicator - `gutter` - gutter indicator
- `delta` - modifications - `delta` - modifications
- `moved` - renamed or moved files/changes - `moved` - renamed or moved files/changes
- `conflict` - merge conflicts
- `gutter` - gutter indicator - `gutter` - gutter indicator
#### Interface #### 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.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.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.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` | Code and command completion menus |
| `ui.menu.selected` | Selected autocomplete item | | `ui.menu.selected` | Selected autocomplete item |
| `ui.menu.scroll` | `fg` sets thumb color, `bg` sets track color of scrollbar | | `ui.menu.scroll` | `fg` sets thumb color, `bg` sets track color of scrollbar |

@ -6,27 +6,26 @@
<name>Helix</name> <name>Helix</name>
<summary>A post-modern text editor</summary> <summary>A post-modern text editor</summary>
<summary xml:lang="ar">مُحَرِّرُ نُصُوصٍ سَابِقٌ لِعَهدِه</summary> <summary xml:lang="ar">مُحَرِّرُ نُصُوصٍ سَابِقٌ لِعَهدِه</summary>
<developer id="com.helix_editor">
<name>Blaž Hrastnik</name>
</developer>
<description> <description>
<p> <p>
Helix is a terminal-based text editor inspired by Kakoune / Neovim and written in Rust. Helix is a terminal-based text editor inspired by Kakoune / Neovim and written in Rust.
</p> </p>
<p xml:lang="ar">
مُحَرِّرُ نُصُوصٍ يَعمَلُ فِي الطَّرَفِيَّة، مُستَلهَمٌ مِن Kakoune وَ Neovim وَمَكتُوبٌ بِلُغَةِ رَست البَرمَجِيَّة.
</p>
<ul> <ul>
<li>Vim-like modal editing</li> <li>Vim-like modal editing</li>
<li xml:lang="ar">تَحرِيرٌ وَضعِيٌّ شَبيهٌ بِـVim</li>
<li>Multiple selections</li> <li>Multiple selections</li>
<li xml:lang="ar">تَحدِيدَاتٌ لِلنَّصِ مُتَعَدِّدَة</li>
<li>Built-in language server support</li> <li>Built-in language server support</li>
<li xml:lang="ar">دَعْمٌ مُدمَجٌ لِخَوادِمِ اللُّغَات</li>
<li>Smart, incremental syntax highlighting and code editing via tree-sitter</li> <li>Smart, incremental syntax highlighting and code editing via tree-sitter</li>
</ul> <li xml:lang="ar">تَحرِيرُ التَّعلِيمَاتِ البَّرمَجِيَّةِ مَعَ تَمييزٍ لِلتَّركِيبِ النَّحُويِّ بِواسِطَةِ tree-sitter</li>
</description>
<description xml:lang="ar">
<p>
مُحَرِّرُ نُصُوصٍ يَعمَلُ فِي الطَّرَفِيَّة، مُستَلهَمٌ مِن Kakoune وَ Neovim وَمَكتُوبٌ بِلُغَةِ رَست البَرمَجِيَّة.
</p>
<ul>
<li>تَحرِيرٌ وَضعِيٌّ شَبيهٌ بِـVim</li>
<li>تَحدِيدَاتٌ لِلنَّصِ مُتَعَدِّدَة</li>
<li>دَعْمٌ مُدمَجٌ لِخَوادِمِ اللُّغَات</li>
<li>تَحرِيرُ التَّعلِيمَاتِ البَّرمَجِيَّةِ مَعَ تَمييزٍ لِلتَّركِيبِ النَّحُويِّ بِواسِطَةِ tree-sitter</li>
</ul> </ul>
</description> </description>
@ -48,6 +47,9 @@
<content_rating type="oars-1.1" /> <content_rating type="oars-1.1" />
<releases> <releases>
<release version="24.03" date="2024-03-30">
<url>https://helix-editor.com/news/release-24-03-highlights/</url>
</release>
<release version="23.10" date="2023-10-24"> <release version="23.10" date="2023-10-24">
<url>https://helix-editor.com/news/release-23-10-highlights/</url> <url>https://helix-editor.com/news/release-23-10-highlights/</url>
</release> </release>
@ -71,9 +73,9 @@
</release> </release>
</releases> </releases>
<requires> <recommends>
<control>keyboard</control> <control>keyboard</control>
</requires> </recommends>
<categories> <categories>
<category>Utility</category> <category>Utility</category>

@ -25,8 +25,7 @@ smartstring = "1.0.1"
unicode-segmentation = "1.11" unicode-segmentation = "1.11"
unicode-width = "0.1" unicode-width = "0.1"
unicode-general-category = "0.6" unicode-general-category = "0.6"
# slab = "0.4.2" slotmap.workspace = true
slotmap = "1.0"
tree-sitter.workspace = true tree-sitter.workspace = true
once_cell = "1.19" once_cell = "1.19"
arc-swap = "1" arc-swap = "1"
@ -56,4 +55,4 @@ globset = "0.4.14"
[dev-dependencies] [dev-dependencies]
quickcheck = { version = "1", default-features = false } quickcheck = { version = "1", default-features = false }
indoc = "2.0.4" indoc = "2.0.5"

@ -1,4 +1,6 @@
//! LSP diagnostic utility types. //! LSP diagnostic utility types.
use std::fmt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Describes the severity level of a [`Diagnostic`]. /// Describes the severity level of a [`Diagnostic`].
@ -47,8 +49,25 @@ pub struct Diagnostic {
pub message: String, pub message: String,
pub severity: Option<Severity>, pub severity: Option<Severity>,
pub code: Option<NumberOrString>, pub code: Option<NumberOrString>,
pub language_server_id: usize, pub provider: DiagnosticProvider,
pub tags: Vec<DiagnosticTag>, pub tags: Vec<DiagnosticTag>,
pub source: Option<String>, pub source: Option<String>,
pub data: Option<serde_json::Value>, pub data: Option<serde_json::Value>,
} }
// 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)
}
}

@ -116,7 +116,7 @@ impl Default for TextFormat {
#[derive(Debug)] #[derive(Debug)]
pub struct DocumentFormatter<'t> { pub struct DocumentFormatter<'t> {
text_fmt: &'t TextFormat, text_fmt: &'t TextFormat,
annotations: &'t TextAnnotations, annotations: &'t TextAnnotations<'t>,
/// The visual position at the end of the last yielded word boundary /// The visual position at the end of the last yielded word boundary
visual_pos: Position, visual_pos: Position,

@ -1,5 +1,3 @@
use std::rc::Rc;
use crate::doc_formatter::{DocumentFormatter, TextFormat}; use crate::doc_formatter::{DocumentFormatter, TextFormat};
use crate::text_annotations::{InlineAnnotation, Overlay, TextAnnotations}; 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( DocumentFormatter::new_at_prev_checkpoint(
text.into(), text.into(),
&TextFormat::new_test(softwrap), &TextFormat::new_test(softwrap),
TextAnnotations::default().add_overlay(overlays.into(), None), TextAnnotations::default().add_overlay(overlays, None),
char_pos, char_pos,
) )
.0 .0
@ -142,7 +140,7 @@ fn annotate_text(text: &str, softwrap: bool, annotations: &[InlineAnnotation]) -
DocumentFormatter::new_at_prev_checkpoint( DocumentFormatter::new_at_prev_checkpoint(
text.into(), text.into(),
&TextFormat::new_test(softwrap), &TextFormat::new_test(softwrap),
TextAnnotations::default().add_inline_annotations(annotations.into(), None), TextAnnotations::default().add_inline_annotations(annotations, None),
0, 0,
) )
.0 .0
@ -164,15 +162,24 @@ fn annotation() {
"foo foo foo foo \n.foo foo foo foo \n.foo foo foo " "foo foo foo foo \n.foo foo foo foo \n.foo foo foo "
); );
} }
#[test] #[test]
fn annotation_and_overlay() { fn annotation_and_overlay() {
let annotations = [InlineAnnotation {
char_idx: 0,
text: "fooo".into(),
}];
let overlay = [Overlay {
char_idx: 0,
grapheme: "\t".into(),
}];
assert_eq!( assert_eq!(
DocumentFormatter::new_at_prev_checkpoint( DocumentFormatter::new_at_prev_checkpoint(
"bbar".into(), "bbar".into(),
&TextFormat::new_test(false), &TextFormat::new_test(false),
TextAnnotations::default() TextAnnotations::default()
.add_inline_annotations(Rc::new([InlineAnnotation::new(0, "fooo")]), None) .add_inline_annotations(annotations.as_slice(), None)
.add_overlay(Rc::new([Overlay::new(0, "\t")]), None), .add_overlay(overlay.as_slice(), None),
0, 0,
) )
.0 .0

@ -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. /// Returns whether the given char position is a grapheme boundary.
#[must_use] #[must_use]
pub fn is_grapheme_boundary(slice: RopeSlice, char_idx: usize) -> bool { 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<RopeSlice<'a>> {
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 /// A highly compressed Cow<'a, str> that holds
/// atmost u31::MAX bytes and is readonly /// atmost u31::MAX bytes and is readonly
pub struct GraphemeStr<'a> { pub struct GraphemeStr<'a> {

@ -247,41 +247,18 @@ fn add_indent_level(
} }
} }
/// Computes for node and all ancestors whether they are the first node on their line. /// Return true if only whitespace comes before the node on its line.
/// The first entry in the return value represents the root node, the last one the node itself /// If given, new_line_byte_pos is treated the same way as any existing newline.
fn get_first_in_line(mut node: Node, new_line_byte_pos: Option<usize>) -> Vec<bool> { fn is_first_in_line(node: Node, text: RopeSlice, new_line_byte_pos: Option<usize>) -> bool {
let mut first_in_line = Vec::new(); let mut line_start_byte_pos = text.line_to_byte(node.start_position().row);
loop { if let Some(pos) = new_line_byte_pos {
if let Some(prev) = node.prev_sibling() { if line_start_byte_pos < pos && pos <= node.start_byte() {
// If we insert a new line, the first node at/after the cursor is considered to be the first in its line line_start_byte_pos = pos;
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 text.byte_slice(line_start_byte_pos..node.start_byte())
}); .chars()
first_in_line.push(Some(first)); .all(|c| c.is_whitespace())
} 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);
}
}
result
} }
/// The total indent for some line of code. /// The total indent for some line of code.
@ -852,7 +829,6 @@ pub fn treesitter_indent_for_pos<'a>(
byte_pos, byte_pos,
new_line_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(); let mut result = Indentation::default();
// We always keep track of all the indent changes on one line, in order to only indent once // 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(); let mut indent_for_line_below = Indentation::default();
loop { loop {
// This can safely be unwrapped because `first_in_line` contains let is_first = is_first_in_line(node, text, new_line_byte_pos);
// one entry for each ancestor of the node (which is what we iterate over)
let is_first = *first_in_line.last().unwrap();
// Apply all indent definitions for this node. // Apply all indent definitions for this node.
// Since we only iterate over each node once, we can remove the // 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; node = parent;
first_in_line.pop();
} else { } else {
// Only add the indentation for the line below if that line // Only add the indentation for the line below if that line
// is not after the line that the indentation is calculated for. // is not after the line that the indentation is calculated for.

@ -9,16 +9,32 @@ use crate::Syntax;
const MAX_PLAINTEXT_SCAN: usize = 10000; const MAX_PLAINTEXT_SCAN: usize = 10000;
const MATCH_LIMIT: usize = 16; const MATCH_LIMIT: usize = 16;
// Limit matching pairs to only ( ) { } [ ] < > ' ' " " pub const BRACKETS: [(char, char); 7] = [
const PAIRS: &[(char, char)] = &[
('(', ')'), ('(', ')'),
('{', '}'), ('{', '}'),
('[', ']'), ('[', ']'),
('<', '>'), ('<', '>'),
('\'', '\''), ('«', '»'),
('\"', '\"'), ('「', '」'),
('', ''),
]; ];
// 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. /// Returns the position of the matching bracket under cursor.
/// ///
/// If the cursor is on the opening bracket, the position of /// If the cursor is on the opening bracket, the position of
@ -30,7 +46,7 @@ const PAIRS: &[(char, char)] = &[
/// If no matching bracket is found, `None` is returned. /// If no matching bracket is found, `None` is returned.
#[must_use] #[must_use]
pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> { pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
if pos >= doc.len_chars() || !is_valid_bracket(doc.char(pos)) { if pos >= doc.len_chars() || !is_valid_pair(doc.char(pos)) {
return None; return None;
} }
find_pair(syntax, doc, pos, false) find_pair(syntax, doc, pos, false)
@ -67,7 +83,7 @@ fn find_pair(
let (start_byte, end_byte) = surrounding_bytes(doc, &node)?; 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)); 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 is_valid_pair_on_pos(doc, start_char, end_char) {
if end_byte == pos { if end_byte == pos {
return Some(start_char); return Some(start_char);
} }
@ -140,14 +156,22 @@ fn find_pair(
/// If no matching bracket is found, `None` is returned. /// If no matching bracket is found, `None` is returned.
#[must_use] #[must_use]
pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Option<usize> { pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Option<usize> {
// Don't do anything when the cursor is not on top of a bracket.
let bracket = doc.get_char(cursor_pos)?; 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) { if !is_valid_bracket(bracket) {
return None; return None;
} }
// Determine the direction of the matching. // 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 { let chars_iter = if is_fwd {
doc.chars_at(cursor_pos + 1) doc.chars_at(cursor_pos + 1)
} else { } else {
@ -159,19 +183,7 @@ pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Opt
for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() { for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() {
if candidate == bracket { if candidate == bracket {
open_cnt += 1; open_cnt += 1;
} else if is_valid_pair( } else if candidate == matching_bracket {
doc,
if is_fwd {
cursor_pos
} else {
cursor_pos - i - 1
},
if is_fwd {
cursor_pos + i + 1
} else {
cursor_pos
},
) {
// Return when all pending brackets have been closed. // Return when all pending brackets have been closed.
if open_cnt == 1 { if open_cnt == 1 {
return Some(if is_fwd { return Some(if is_fwd {
@ -187,15 +199,49 @@ pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Opt
None None
} }
fn is_valid_bracket(c: char) -> bool { /// Returns the open and closing chars pair. If not found in
PAIRS.iter().any(|(l, r)| *l == c || *r == c) /// [`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))
}
pub fn is_open_bracket(ch: char) -> bool {
BRACKETS.iter().any(|(l, _)| *l == ch)
}
pub fn is_close_bracket(ch: char) -> bool {
BRACKETS.iter().any(|(_, r)| *r == ch)
}
pub fn is_valid_bracket(ch: char) -> bool {
BRACKETS.iter().any(|(l, r)| *l == ch || *r == ch)
}
pub fn is_open_pair(ch: char) -> bool {
PAIRS.iter().any(|(l, _)| *l == ch)
}
pub fn is_close_pair(ch: char) -> bool {
PAIRS.iter().any(|(_, r)| *r == ch)
} }
fn is_forward_bracket(c: char) -> bool { pub fn is_valid_pair(ch: char) -> bool {
PAIRS.iter().any(|(l, _)| *l == c) PAIRS.iter().any(|(l, r)| *l == ch || *r == ch)
} }
fn is_valid_pair(doc: RopeSlice, start_char: usize, end_char: usize) -> bool { fn is_valid_pair_on_pos(doc: RopeSlice, start_char: usize, end_char: usize) -> bool {
PAIRS.contains(&(doc.char(start_char), doc.char(end_char))) PAIRS.contains(&(doc.char(start_char), doc.char(end_char)))
} }

@ -1,76 +1,137 @@
use crate::{Range, RopeSlice, Selection, Syntax}; use crate::{movement::Direction, syntax::TreeCursor, Range, RopeSlice, Selection, Syntax};
use tree_sitter::Node;
pub fn expand_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection { pub fn expand_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection {
select_node_impl(syntax, text, selection, |mut node, from, to| { let cursor = &mut syntax.walk();
while node.start_byte() == from && node.end_byte() == to {
node = node.parent()?; 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 { pub fn shrink_selection(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection {
select_node_impl(syntax, text, selection, |descendant, _from, _to| { select_node_impl(
descendant.child(0).or(Some(descendant)) syntax,
}) text,
selection,
|cursor| {
cursor.goto_first_child();
},
None,
)
} }
pub fn select_sibling<F>( pub fn select_next_sibling(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection {
syntax: &Syntax, select_node_impl(
text: RopeSlice, syntax,
selection: Selection, text,
sibling_fn: &F, selection,
) -> Selection |cursor| {
where while !cursor.goto_next_sibling() {
F: Fn(Node) -> Option<Node>, if !cursor.goto_parent() {
{ break;
select_node_impl(syntax, text, selection, |descendant, _from, _to| { }
find_sibling_recursive(descendant, sibling_fn) }
},
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<F>(node: Node, sibling_fn: F) -> Option<Node> pub fn select_all_children(syntax: &Syntax, text: RopeSlice, selection: Selection) -> Selection {
where selection.transform_iter(|range| {
F: Fn(Node) -> Option<Node>, let mut cursor = syntax.walk();
{ let (from, to) = range.into_byte_range(text);
sibling_fn(node).or_else(|| { cursor.reset_to_byte_range(from, to);
node.parent() select_children(&mut cursor, text, range).into_iter()
.and_then(|node| find_sibling_recursive(node, sibling_fn))
}) })
} }
fn select_children<'n>(
cursor: &'n mut TreeCursor<'n>,
text: RopeSlice,
range: Range,
) -> Vec<Range> {
let children = cursor
.named_children()
.map(|child| Range::from_node(child, text, range.direction()))
.collect::<Vec<_>>();
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<F>( fn select_node_impl<F>(
syntax: &Syntax, syntax: &Syntax,
text: RopeSlice, text: RopeSlice,
selection: Selection, selection: Selection,
select_fn: F, motion: F,
direction: Option<Direction>,
) -> Selection ) -> Selection
where where
F: Fn(Node, usize, usize) -> Option<Node>, F: Fn(&mut TreeCursor),
{ {
let tree = syntax.tree(); let cursor = &mut syntax.walk();
selection.transform(|range| { selection.transform(|range| {
let from = text.char_to_byte(range.from()); let from = text.char_to_byte(range.from());
let to = text.char_to_byte(range.to()); let to = text.char_to_byte(range.to());
let node = match tree cursor.reset_to_byte_range(from, to);
.root_node()
.descendant_for_byte_range(from, to) motion(cursor);
.and_then(|node| select_fn(node, from, to))
{
Some(node) => node,
None => return range,
};
let node = cursor.node();
let from = text.byte_to_char(node.start_byte()); let from = text.byte_to_char(node.start_byte());
let to = text.byte_to_char(node.end_byte()); let to = text.byte_to_char(node.end_byte());
if range.head < range.anchor { Range::new(from, to).with_direction(direction.unwrap_or_else(|| range.direction()))
Range::new(to, from)
} else {
Range::new(from, to)
}
}) })
} }

@ -14,6 +14,7 @@ use crate::{
use helix_stdx::rope::{self, RopeSliceExt}; use helix_stdx::rope::{self, RopeSliceExt};
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use std::borrow::Cow; use std::borrow::Cow;
use tree_sitter::Node;
/// A single selection range. /// A single selection range.
/// ///
@ -73,6 +74,12 @@ impl Range {
Self::new(head, head) 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. /// Start of the range.
#[inline] #[inline]
#[must_use] #[must_use]
@ -115,7 +122,7 @@ impl Range {
} }
/// `Direction::Backward` when head < anchor. /// `Direction::Backward` when head < anchor.
/// `Direction::Backward` otherwise. /// `Direction::Forward` otherwise.
#[inline] #[inline]
#[must_use] #[must_use]
pub fn direction(&self) -> Direction { pub fn direction(&self) -> Direction {
@ -376,6 +383,12 @@ impl Range {
let second = graphemes.next(); let second = graphemes.next();
first.is_some() && second.is_none() 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 { impl From<(usize, usize)> for Range {
@ -705,6 +718,15 @@ impl IntoIterator for Selection {
} }
} }
impl From<Range> for Selection {
fn from(range: Range) -> Self {
Self {
ranges: smallvec![range],
primary_index: 0,
}
}
}
// TODO: checkSelection -> check if valid for doc length && sorted // TODO: checkSelection -> check if valid for doc length && sorted
pub fn keep_or_remove_matches( pub fn keep_or_remove_matches(
@ -774,7 +796,9 @@ pub fn split_on_newline(text: RopeSlice, selection: &Selection) -> Selection {
let mut start = sel_start; let mut start = sel_start;
for line in sel.slice(text).lines() { 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(); let line_end = start + line.len_chars();
// TODO: retain range direction // TODO: retain range direction
result.push(Range::new(start, line_end - line_ending.len_chars())); result.push(Range::new(start, line_end - line_ending.len_chars()));

@ -1,18 +1,16 @@
use std::fmt::Display; 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; use ropey::RopeSlice;
pub const PAIRS: &[(char, char)] = &[
('(', ')'),
('[', ']'),
('{', '}'),
('<', '>'),
('«', '»'),
('「', '」'),
('', ''),
];
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum Error { pub enum Error {
PairNotFound, PairNotFound,
@ -34,32 +32,68 @@ impl Display for Error {
type Result<T> = std::result::Result<T, Error>; type Result<T> = std::result::Result<T, Error>;
/// Given any char in [PAIRS], return the open and closing chars. If not found in /// Finds the position of surround pairs of any [`crate::match_brackets::PAIRS`]
/// [PAIRS] return (ch, ch). /// using tree-sitter when possible.
/// ///
/// ``` /// # Returns
/// use helix_core::surround::get_pair;
/// ///
/// assert_eq!(get_pair('['), ('[', ']')); /// Tuple `(anchor, head)`, meaning it is not always ordered.
/// assert_eq!(get_pair('}'), ('{', '}')); pub fn find_nth_closest_pairs_pos(
/// assert_eq!(get_pair('"'), ('"', '"')); syntax: Option<&Syntax>,
/// ``` text: RopeSlice,
pub fn get_pair(ch: char) -> (char, char) { range: Range,
PAIRS skip: usize,
.iter() ) -> Result<(usize, usize)> {
.find(|(open, close)| *open == ch || *close == ch) match syntax {
.copied() Some(syntax) => find_nth_closest_pairs_ts(syntax, text, range, skip),
.unwrap_or((ch, ch)) 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, text: RopeSlice,
range: Range, range: Range,
mut skip: usize, mut skip: usize,
) -> Result<(usize, usize)> { ) -> Result<(usize, usize)> {
let is_open_pair = |ch| PAIRS.iter().any(|(open, _)| *open == ch); let mut opening = range.from();
let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch); // 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 mut stack = Vec::with_capacity(2);
let pos = range.from(); let pos = range.from();
let mut close_pos = pos.saturating_sub(1); 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) { for ch in text.chars_at(pos) {
close_pos += 1; close_pos += 1;
if is_open_pair(ch) { if is_open_bracket(ch) {
// Track open pairs encountered so that we can step over // Track open pairs encountered so that we can step over
// the corresponding close pairs that will come up further // the corresponding close pairs that will come up further
// down the loop. We want to find a lone close pair whose // down the loop. We want to find a lone close pair whose
@ -76,7 +110,7 @@ pub fn find_nth_closest_pairs_pos(
continue; continue;
} }
if !is_close_pair(ch) { if !is_close_bracket(ch) {
// We don't care if this character isn't a brace pair item, // We don't care if this character isn't a brace pair item,
// so short circuit here. // so short circuit here.
continue; 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( fn find_nth_open_pair(
@ -249,6 +287,7 @@ fn find_nth_close_pair(
/// are automatically detected around each cursor (note that this may result /// are automatically detected around each cursor (note that this may result
/// in them selecting different surround characters for each selection). /// in them selecting different surround characters for each selection).
pub fn get_surround_pos( pub fn get_surround_pos(
syntax: Option<&Syntax>,
text: RopeSlice, text: RopeSlice,
selection: &Selection, selection: &Selection,
ch: Option<char>, ch: Option<char>,
@ -257,9 +296,13 @@ pub fn get_surround_pos(
let mut change_pos = Vec::new(); let mut change_pos = Vec::new();
for &range in selection { for &range in selection {
let (open_pos, close_pos) = match ch { let (open_pos, close_pos) = {
let range_raw = match ch {
Some(ch) => find_nth_pairs_pos(text, ch, range, skip)?, Some(ch) => find_nth_pairs_pos(text, ch, range, skip)?,
None => find_nth_closest_pairs_pos(text, 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) { if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) {
return Err(Error::CursorOverlap); return Err(Error::CursorOverlap);
@ -288,7 +331,7 @@ mod test {
); );
assert_eq!( assert_eq!(
get_surround_pos(doc.slice(..), &selection, Some('('), 1).unwrap(), get_surround_pos(None, doc.slice(..), &selection, Some('('), 1).unwrap(),
expectations expectations
); );
} }
@ -303,7 +346,7 @@ mod test {
); );
assert_eq!( assert_eq!(
get_surround_pos(doc.slice(..), &selection, Some('('), 1), get_surround_pos(None, doc.slice(..), &selection, Some('('), 1),
Err(Error::PairNotFound) Err(Error::PairNotFound)
); );
} }
@ -318,7 +361,7 @@ mod test {
); );
assert_eq!( 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 Err(Error::PairNotFound) // overlapping surround chars
); );
} }
@ -333,7 +376,7 @@ mod test {
); );
assert_eq!( assert_eq!(
get_surround_pos(doc.slice(..), &selection, Some('['), 1), get_surround_pos(None, doc.slice(..), &selection, Some('['), 1),
Err(Error::CursorOverlap) Err(Error::CursorOverlap)
); );
} }
@ -397,7 +440,7 @@ mod test {
); );
assert_eq!( assert_eq!(
find_nth_closest_pairs_pos(doc.slice(..), selection.primary(), 1), find_nth_closest_pairs_pos(None, doc.slice(..), selection.primary(), 1),
Err(Error::PairNotFound) Err(Error::PairNotFound)
) )
} }

@ -1,3 +1,5 @@
mod tree_cursor;
use crate::{ use crate::{
auto_pairs::AutoPairs, auto_pairs::AutoPairs,
chars::char_is_line_ending, chars::char_is_line_ending,
@ -32,6 +34,8 @@ use serde::{ser::SerializeSeq, Deserialize, Serialize};
use helix_loader::grammar::{get_language, load_runtime_file}; use helix_loader::grammar::{get_language, load_runtime_file};
pub use tree_cursor::TreeCursor;
fn deserialize_regex<'de, D>(deserializer: D) -> Result<Option<Regex>, D::Error> fn deserialize_regex<'de, D>(deserializer: D) -> Result<Option<Regex>, D::Error>
where where
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
@ -1090,6 +1094,7 @@ impl Syntax {
start_point: Point::new(0, 0), start_point: Point::new(0, 0),
end_point: Point::new(usize::MAX, usize::MAX), end_point: Point::new(usize::MAX, usize::MAX),
}], }],
parent: None,
}; };
// track scope_descriptor: a Vec of scopes for item in tree // track scope_descriptor: a Vec of scopes for item in tree
@ -1360,6 +1365,7 @@ impl Syntax {
depth, depth,
ranges, ranges,
flags: LayerUpdateFlags::empty(), flags: LayerUpdateFlags::empty(),
parent: Some(layer_id),
}; };
// Find an identical existing layer // Find an identical existing layer
@ -1493,6 +1499,12 @@ impl Syntax {
.descendant_for_byte_range(start, end) .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 // Commenting
// comment_strings_for_pos // comment_strings_for_pos
// is_commented // is_commented
@ -1525,6 +1537,7 @@ pub struct LanguageLayer {
pub ranges: Vec<Range>, pub ranges: Vec<Range>,
pub depth: u32, pub depth: u32,
flags: LayerUpdateFlags, flags: LayerUpdateFlags,
parent: Option<LayerId>,
} }
/// This PartialEq implementation only checks if that /// This PartialEq implementation only checks if that
@ -1720,7 +1733,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::{iter, mem, ops, str, usize}; use std::{iter, mem, ops, str, usize};
use tree_sitter::{ use tree_sitter::{
Language as Grammar, Node, Parser, Point, Query, QueryCaptures, QueryCursor, QueryError, 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; const CANCELLATION_CHECK_INTERVAL: usize = 100;
@ -2654,7 +2667,7 @@ pub fn pretty_print_tree<W: fmt::Write>(fmt: &mut W, node: Node) -> fmt::Result
fn pretty_print_tree_impl<W: fmt::Write>( fn pretty_print_tree_impl<W: fmt::Write>(
fmt: &mut W, fmt: &mut W,
cursor: &mut TreeCursor, cursor: &mut tree_sitter::TreeCursor,
depth: usize, depth: usize,
) -> fmt::Result { ) -> fmt::Result {
let node = cursor.node(); let node = cursor.node();
@ -2752,10 +2765,10 @@ mod test {
) )
}; };
test("quantified_nodes", 1..36); test("quantified_nodes", 1..37);
// NOTE: Enable after implementing proper node group capturing // NOTE: Enable after implementing proper node group capturing
// test("quantified_nodes_grouped", 1..36); // test("quantified_nodes_grouped", 1..37);
// test("multiple_nodes_grouped", 1..36); // test("multiple_nodes_grouped", 1..37);
} }
#[test] #[test]
@ -2926,7 +2939,7 @@ mod test {
#[test] #[test]
fn test_pretty_print() { fn test_pretty_print() {
let source = r#"/// Hello"#; let source = r#"// Hello"#;
assert_pretty_print("rust", source, "(line_comment)", 0, source.len()); assert_pretty_print("rust", source, "(line_comment)", 0, source.len());
// A large tree should be indented with fields: // A large tree should be indented with fields:
@ -2945,7 +2958,8 @@ mod test {
" (macro_invocation\n", " (macro_invocation\n",
" macro: (identifier)\n", " macro: (identifier)\n",
" (token_tree\n", " (token_tree\n",
" (string_literal))))))", " (string_literal\n",
" (string_content)))))))",
), ),
0, 0,
source.len(), source.len(),
@ -2964,7 +2978,7 @@ mod test {
// rule but `name` and `body` belong to an unnamed helper `_method_rest`. // rule but `name` and `body` belong to an unnamed helper `_method_rest`.
// This can cause a bug with a pretty-printing implementation that // This can cause a bug with a pretty-printing implementation that
// uses `Node::field_name_for_child` to determine field names but is // 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 let source = "def self.method_name
true true
end"; end";

@ -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<LayerId, LanguageLayer>,
root: LayerId,
current: LayerId,
injection_ranges: Vec<InjectionRange>,
// 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<LayerId, LanguageLayer>, 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<P>(&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<usize>) -> Option<LayerId> {
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<Self::Item> {
// 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())
}
}
}

@ -1,6 +1,5 @@
use std::cell::Cell; use std::cell::Cell;
use std::ops::Range; use std::ops::Range;
use std::rc::Rc;
use crate::syntax::Highlight; use crate::syntax::Highlight;
use crate::Tendril; use crate::Tendril;
@ -92,23 +91,23 @@ pub struct LineAnnotation {
} }
#[derive(Debug)] #[derive(Debug)]
struct Layer<A, M> { struct Layer<'a, A, M> {
annotations: Rc<[A]>, annotations: &'a [A],
current_index: Cell<usize>, current_index: Cell<usize>,
metadata: M, metadata: M,
} }
impl<A, M: Clone> Clone for Layer<A, M> { impl<A, M: Clone> Clone for Layer<'_, A, M> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Layer { Layer {
annotations: self.annotations.clone(), annotations: self.annotations,
current_index: self.current_index.clone(), current_index: self.current_index.clone(),
metadata: self.metadata.clone(), metadata: self.metadata.clone(),
} }
} }
} }
impl<A, M> Layer<A, M> { impl<A, M> Layer<'_, A, M> {
pub fn reset_pos(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) { pub fn reset_pos(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) {
let new_index = self let new_index = self
.annotations .annotations
@ -128,8 +127,8 @@ impl<A, M> Layer<A, M> {
} }
} }
impl<A, M> From<(Rc<[A]>, M)> for Layer<A, M> { impl<'a, A, M> From<(&'a [A], M)> for Layer<'a, A, M> {
fn from((annotations, metadata): (Rc<[A]>, M)) -> Layer<A, M> { fn from((annotations, metadata): (&'a [A], M)) -> Layer<A, M> {
Layer { Layer {
annotations, annotations,
current_index: Cell::new(0), current_index: Cell::new(0),
@ -147,13 +146,13 @@ fn reset_pos<A, M>(layers: &[Layer<A, M>], pos: usize, get_pos: impl Fn(&A) -> u
/// Annotations that change that is displayed when the document is render. /// Annotations that change that is displayed when the document is render.
/// Also commonly called virtual text. /// Also commonly called virtual text.
#[derive(Default, Debug, Clone)] #[derive(Default, Debug, Clone)]
pub struct TextAnnotations { pub struct TextAnnotations<'a> {
inline_annotations: Vec<Layer<InlineAnnotation, Option<Highlight>>>, inline_annotations: Vec<Layer<'a, InlineAnnotation, Option<Highlight>>>,
overlays: Vec<Layer<Overlay, Option<Highlight>>>, overlays: Vec<Layer<'a, Overlay, Option<Highlight>>>,
line_annotations: Vec<Layer<LineAnnotation, ()>>, line_annotations: Vec<Layer<'a, LineAnnotation, ()>>,
} }
impl TextAnnotations { impl<'a> TextAnnotations<'a> {
/// Prepare the TextAnnotations for iteration starting at char_idx /// Prepare the TextAnnotations for iteration starting at char_idx
pub fn reset_pos(&self, char_idx: usize) { pub fn reset_pos(&self, char_idx: usize) {
reset_pos(&self.inline_annotations, char_idx, |annot| annot.char_idx); 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. /// the annotations that belong to the layers added first will be shown first.
pub fn add_inline_annotations( pub fn add_inline_annotations(
&mut self, &mut self,
layer: Rc<[InlineAnnotation]>, layer: &'a [InlineAnnotation],
highlight: Option<Highlight>, highlight: Option<Highlight>,
) -> &mut Self { ) -> &mut Self {
self.inline_annotations.push((layer, highlight).into()); self.inline_annotations.push((layer, highlight).into());
@ -211,7 +210,7 @@ impl TextAnnotations {
/// ///
/// If multiple layers contain overlay at the same position /// If multiple layers contain overlay at the same position
/// the overlay from the layer added last will be show. /// the overlay from the layer added last will be show.
pub fn add_overlay(&mut self, layer: Rc<[Overlay]>, highlight: Option<Highlight>) -> &mut Self { pub fn add_overlay(&mut self, layer: &'a [Overlay], highlight: Option<Highlight>) -> &mut Self {
self.overlays.push((layer, highlight).into()); self.overlays.push((layer, highlight).into());
self self
} }
@ -220,7 +219,7 @@ impl TextAnnotations {
/// ///
/// The line annotations **must be sorted** by their `char_idx`. /// The line annotations **must be sorted** by their `char_idx`.
/// Multiple line annotations with the same `char_idx` **are not allowed**. /// 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.line_annotations.push((layer, ()).into());
self self
} }

@ -7,9 +7,9 @@ use crate::chars::{categorize_char, char_is_whitespace, CharCategory};
use crate::graphemes::{next_grapheme_boundary, prev_grapheme_boundary}; use crate::graphemes::{next_grapheme_boundary, prev_grapheme_boundary};
use crate::line_ending::rope_is_line_ending; use crate::line_ending::rope_is_line_ending;
use crate::movement::Direction; use crate::movement::Direction;
use crate::surround;
use crate::syntax::LanguageConfiguration; use crate::syntax::LanguageConfiguration;
use crate::Range; use crate::Range;
use crate::{surround, Syntax};
fn find_word_boundary(slice: RopeSlice, mut pos: usize, direction: Direction, long: bool) -> usize { fn find_word_boundary(slice: RopeSlice, mut pos: usize, direction: Direction, long: bool) -> usize {
use CharCategory::{Eol, Whitespace}; use CharCategory::{Eol, Whitespace};
@ -199,25 +199,28 @@ pub fn textobject_paragraph(
} }
pub fn textobject_pair_surround( pub fn textobject_pair_surround(
syntax: Option<&Syntax>,
slice: RopeSlice, slice: RopeSlice,
range: Range, range: Range,
textobject: TextObject, textobject: TextObject,
ch: char, ch: char,
count: usize, count: usize,
) -> Range { ) -> 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( pub fn textobject_pair_surround_closest(
syntax: Option<&Syntax>,
slice: RopeSlice, slice: RopeSlice,
range: Range, range: Range,
textobject: TextObject, textobject: TextObject,
count: usize, count: usize,
) -> Range { ) -> 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( fn textobject_pair_surround_impl(
syntax: Option<&Syntax>,
slice: RopeSlice, slice: RopeSlice,
range: Range, range: Range,
textobject: TextObject, textobject: TextObject,
@ -226,8 +229,7 @@ fn textobject_pair_surround_impl(
) -> Range { ) -> Range {
let pair_pos = match ch { let pair_pos = match ch {
Some(ch) => surround::find_nth_pairs_pos(slice, ch, range, count), Some(ch) => surround::find_nth_pairs_pos(slice, ch, range, count),
// Automatically find the closest surround pairs None => surround::find_nth_closest_pairs_pos(syntax, slice, range, count),
None => surround::find_nth_closest_pairs_pos(slice, range, count),
}; };
pair_pos pair_pos
.map(|(anchor, head)| match textobject { .map(|(anchor, head)| match textobject {
@ -574,7 +576,8 @@ mod test {
let slice = doc.slice(..); let slice = doc.slice(..);
for &case in scenario { for &case in scenario {
let (pos, objtype, expected_range, ch, count) = case; 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!( assert_eq!(
result, result,
expected_range.into(), expected_range.into(),

@ -2,7 +2,7 @@ use crate::{
requests::DisconnectArguments, requests::DisconnectArguments,
transport::{Payload, Request, Response, Transport}, transport::{Payload, Request, Response, Transport},
types::*, types::*,
Error, Result, ThreadId, Error, Result,
}; };
use helix_core::syntax::DebuggerQuirks; use helix_core::syntax::DebuggerQuirks;

@ -126,7 +126,7 @@ pub fn config_dir() -> PathBuf {
pub fn cache_dir() -> PathBuf { pub fn cache_dir() -> PathBuf {
// TODO: allow env var override // 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(); let mut path = strategy.cache_dir();
path.push("helix"); path.push("helix");
path path

@ -27,7 +27,8 @@ lsp-types = { version = "0.95" }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
thiserror = "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 = { version = "1.37", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] }
tokio-stream = "0.1.15" tokio-stream = "0.1.15"
parking_lot = "0.12.1" parking_lot = "0.12.1"
arc-swap = "1" arc-swap = "1"
slotmap.workspace = true

@ -2,11 +2,11 @@ use crate::{
file_operations::FileOperationsInterest, file_operations::FileOperationsInterest,
find_lsp_workspace, jsonrpc, find_lsp_workspace, jsonrpc,
transport::{Payload, Transport}, transport::{Payload, Transport},
Call, Error, OffsetEncoding, Result, Call, Error, LanguageServerId, OffsetEncoding, Result,
}; };
use helix_core::{find_workspace, syntax::LanguageServerFeature, ChangeSet, Rope}; 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 helix_stdx::path;
use lsp::{ use lsp::{
notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport, notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport,
@ -46,7 +46,7 @@ fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder {
#[derive(Debug)] #[derive(Debug)]
pub struct Client { pub struct Client {
id: usize, id: LanguageServerId,
name: String, name: String,
_process: Child, _process: Child,
server_tx: UnboundedSender<Payload>, server_tx: UnboundedSender<Payload>,
@ -179,10 +179,14 @@ impl Client {
server_environment: HashMap<String, String>, server_environment: HashMap<String, String>,
root_path: PathBuf, root_path: PathBuf,
root_uri: Option<lsp::Url>, root_uri: Option<lsp::Url>,
id: usize, id: LanguageServerId,
name: String, name: String,
req_timeout: u64, req_timeout: u64,
) -> Result<(Self, UnboundedReceiver<(usize, Call)>, Arc<Notify>)> { ) -> Result<(
Self,
UnboundedReceiver<(LanguageServerId, Call)>,
Arc<Notify>,
)> {
// Resolve path to the binary // Resolve path to the binary
let cmd = helix_stdx::env::which(cmd)?; let cmd = helix_stdx::env::which(cmd)?;
@ -234,7 +238,7 @@ impl Client {
&self.name &self.name
} }
pub fn id(&self) -> usize { pub fn id(&self) -> LanguageServerId {
self.id self.id
} }
@ -393,6 +397,16 @@ impl Client {
&self, &self,
params: R::Params, params: R::Params,
) -> impl Future<Output = Result<Value>> ) -> impl Future<Output = Result<Value>>
where
R::Params: serde::Serialize,
{
self.call_with_ref::<R>(&params)
}
fn call_with_ref<R: lsp::request::Request>(
&self,
params: &R::Params,
) -> impl Future<Output = Result<Value>>
where where
R::Params: serde::Serialize, R::Params: serde::Serialize,
{ {
@ -401,7 +415,7 @@ impl Client {
fn call_with_timeout<R: lsp::request::Request>( fn call_with_timeout<R: lsp::request::Request>(
&self, &self,
params: R::Params, params: &R::Params,
timeout_secs: u64, timeout_secs: u64,
) -> impl Future<Output = Result<Value>> ) -> impl Future<Output = Result<Value>>
where where
@ -410,17 +424,16 @@ impl Client {
let server_tx = self.server_tx.clone(); let server_tx = self.server_tx.clone();
let id = self.next_request_id(); let id = self.next_request_id();
let params = serde_json::to_value(params);
async move { async move {
use std::time::Duration; use std::time::Duration;
use tokio::time::timeout; use tokio::time::timeout;
let params = serde_json::to_value(params)?;
let request = jsonrpc::MethodCall { let request = jsonrpc::MethodCall {
jsonrpc: Some(jsonrpc::Version::V2), jsonrpc: Some(jsonrpc::Version::V2),
id: id.clone(), id: id.clone(),
method: R::METHOD.to_string(), method: R::METHOD.to_string(),
params: Self::value_into_params(params), params: Self::value_into_params(params?),
}; };
let (tx, mut rx) = channel::<Result<Value>>(1); let (tx, mut rx) = channel::<Result<Value>>(1);
@ -737,7 +750,7 @@ impl Client {
new_uri: url_from_path(new_path)?, new_uri: url_from_path(new_path)?,
}]; }];
let request = self.call_with_timeout::<lsp::request::WillRenameFiles>( let request = self.call_with_timeout::<lsp::request::WillRenameFiles>(
lsp::RenameFilesParams { files }, &lsp::RenameFilesParams { files },
5, 5,
); );
@ -1022,21 +1035,10 @@ impl Client {
pub fn resolve_completion_item( pub fn resolve_completion_item(
&self, &self,
completion_item: lsp::CompletionItem, completion_item: &lsp::CompletionItem,
) -> Option<impl Future<Output = Result<lsp::CompletionItem>>> { ) -> impl Future<Output = Result<lsp::CompletionItem>> {
let capabilities = self.capabilities.get().unwrap(); let res = self.call_with_ref::<lsp::request::ResolveCompletionItem>(completion_item);
async move { Ok(serde_json::from_value(res.await?)?) }
// 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::<lsp::request::ResolveCompletionItem>(completion_item);
Some(async move { Ok(serde_json::from_value(res.await?)?) })
} }
pub fn resolve_code_action( pub fn resolve_code_action(

@ -3,24 +3,24 @@ use std::{collections::HashMap, path::PathBuf, sync::Weak};
use globset::{GlobBuilder, GlobSetBuilder}; use globset::{GlobBuilder, GlobSetBuilder};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use crate::{lsp, Client}; use crate::{lsp, Client, LanguageServerId};
enum Event { enum Event {
FileChanged { FileChanged {
path: PathBuf, path: PathBuf,
}, },
Register { Register {
client_id: usize, client_id: LanguageServerId,
client: Weak<Client>, client: Weak<Client>,
registration_id: String, registration_id: String,
options: lsp::DidChangeWatchedFilesRegistrationOptions, options: lsp::DidChangeWatchedFilesRegistrationOptions,
}, },
Unregister { Unregister {
client_id: usize, client_id: LanguageServerId,
registration_id: String, registration_id: String,
}, },
RemoveClient { RemoveClient {
client_id: usize, client_id: LanguageServerId,
}, },
} }
@ -59,7 +59,7 @@ impl Handler {
pub fn register( pub fn register(
&self, &self,
client_id: usize, client_id: LanguageServerId,
client: Weak<Client>, client: Weak<Client>,
registration_id: String, registration_id: String,
options: lsp::DidChangeWatchedFilesRegistrationOptions, 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 { let _ = self.tx.send(Event::Unregister {
client_id, client_id,
registration_id, registration_id,
@ -83,12 +83,12 @@ impl Handler {
let _ = self.tx.send(Event::FileChanged { path }); 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 }); let _ = self.tx.send(Event::RemoveClient { client_id });
} }
async fn run(mut rx: mpsc::UnboundedReceiver<Event>) { async fn run(mut rx: mpsc::UnboundedReceiver<Event>) {
let mut state: HashMap<usize, ClientState> = HashMap::new(); let mut state: HashMap<LanguageServerId, ClientState> = HashMap::new();
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
match event { match event {
Event::FileChanged { path } => { Event::FileChanged { path } => {

@ -17,6 +17,7 @@ use helix_core::syntax::{
LanguageConfiguration, LanguageServerConfiguration, LanguageServerFeatures, LanguageConfiguration, LanguageServerConfiguration, LanguageServerFeatures,
}; };
use helix_stdx::path; use helix_stdx::path;
use slotmap::SlotMap;
use tokio::sync::mpsc::UnboundedReceiver; use tokio::sync::mpsc::UnboundedReceiver;
use std::{ use std::{
@ -28,8 +29,9 @@ use std::{
use thiserror::Error; use thiserror::Error;
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T, E = Error> = core::result::Result<T, E>;
pub type LanguageServerName = String; pub type LanguageServerName = String;
pub use helix_core::diagnostic::LanguageServerId;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum Error { pub enum Error {
@ -284,7 +286,8 @@ pub mod util {
.chars_at(cursor) .chars_at(cursor)
.skip(1) .skip(1)
.take_while(|ch| chars::char_is_word(*ch)) .take_while(|ch| chars::char_is_word(*ch))
.count(); .count()
+ 1;
} }
(start, end) (start, end)
} }
@ -539,6 +542,16 @@ pub mod util {
} else { } else {
return (0, 0, None); 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) (start, end, replacement)
}), }),
) )
@ -640,38 +653,42 @@ impl Notification {
#[derive(Debug)] #[derive(Debug)]
pub struct Registry { pub struct Registry {
inner: HashMap<LanguageServerName, Vec<Arc<Client>>>, inner: SlotMap<LanguageServerId, Arc<Client>>,
inner_by_name: HashMap<LanguageServerName, Vec<Arc<Client>>>,
syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>, syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>,
counter: usize, pub incoming: SelectAll<UnboundedReceiverStream<(LanguageServerId, Call)>>,
pub incoming: SelectAll<UnboundedReceiverStream<(usize, Call)>>,
pub file_event_handler: file_event::Handler, pub file_event_handler: file_event::Handler,
} }
impl Registry { impl Registry {
pub fn new(syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>) -> Self { pub fn new(syn_loader: Arc<ArcSwap<helix_core::syntax::Loader>>) -> Self {
Self { Self {
inner: HashMap::new(), inner: SlotMap::with_key(),
inner_by_name: HashMap::new(),
syn_loader, syn_loader,
counter: 0,
incoming: SelectAll::new(), incoming: SelectAll::new(),
file_event_handler: file_event::Handler::new(), file_event_handler: file_event::Handler::new(),
} }
} }
pub fn get_by_id(&self, id: usize) -> Option<&Client> { pub fn get_by_id(&self, id: LanguageServerId) -> Option<&Arc<Client>> {
self.inner self.inner.get(id)
.values()
.flatten()
.find(|client| client.id() == id)
.map(|client| &**client)
} }
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.file_event_handler.remove_client(id);
self.inner.retain(|_, language_servers| { let instances = self
language_servers.retain(|ls| id != ls.id()); .inner_by_name
!language_servers.is_empty() .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( fn start_client(
@ -681,15 +698,14 @@ impl Registry {
doc_path: Option<&std::path::PathBuf>, doc_path: Option<&std::path::PathBuf>,
root_dirs: &[PathBuf], root_dirs: &[PathBuf],
enable_snippets: bool, enable_snippets: bool,
) -> Result<Option<Arc<Client>>> { ) -> Result<Arc<Client>, StartupError> {
let syn_loader = self.syn_loader.load(); let syn_loader = self.syn_loader.load();
let config = syn_loader let config = syn_loader
.language_server_configs() .language_server_configs()
.get(&name) .get(&name)
.ok_or_else(|| anyhow::anyhow!("Language server '{name}' not defined"))?; .ok_or_else(|| anyhow::anyhow!("Language server '{name}' not defined"))?;
let id = self.counter; let id = self.inner.try_insert_with_key(|id| {
self.counter += 1; start_client(
if let Some(NewClient(client, incoming)) = start_client(
id, id,
name, name,
ls_config, ls_config,
@ -697,12 +713,13 @@ impl Registry {
doc_path, doc_path,
root_dirs, root_dirs,
enable_snippets, enable_snippets,
)? { )
self.incoming.push(UnboundedReceiverStream::new(incoming)); .map(|client| {
Ok(Some(client)) self.incoming.push(UnboundedReceiverStream::new(client.1));
} else { client.0
Ok(None) })
} })?;
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, /// 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,7 +736,15 @@ impl Registry {
.language_servers .language_servers
.iter() .iter()
.filter_map(|LanguageServerFeatures { name, .. }| { .filter_map(|LanguageServerFeatures { name, .. }| {
if self.inner.contains_key(name) { 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;
});
}
}
let client = match self.start_client( let client = match self.start_client(
name.clone(), name.clone(),
language_config, language_config,
@ -727,33 +752,23 @@ impl Registry {
root_dirs, root_dirs,
enable_snippets, enable_snippets,
) { ) {
Ok(client) => client?, Ok(client) => client,
Err(error) => return Some(Err(error)), Err(StartupError::NoRequiredRootFound) => return None,
Err(StartupError::Error(err)) => return Some(Err(err)),
}; };
let old_clients = self self.inner_by_name
.inner .insert(name.to_owned(), vec![client.clone()]);
.insert(name.clone(), vec![client.clone()])
.unwrap();
for old_client in old_clients {
self.file_event_handler.remove_client(old_client.id());
tokio::spawn(async move {
let _ = old_client.force_shutdown().await;
});
}
Some(Ok(client)) Some(Ok(client))
} else {
None
}
}) })
.collect() .collect()
} }
pub fn stop(&mut self, name: &str) { 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 { for client in clients {
self.file_event_handler.remove_client(client.id()); self.file_event_handler.remove_client(client.id());
self.inner.remove(client.id());
tokio::spawn(async move { tokio::spawn(async move {
let _ = client.force_shutdown().await; let _ = client.force_shutdown().await;
}); });
@ -770,7 +785,7 @@ impl Registry {
) -> impl Iterator<Item = (LanguageServerName, Result<Arc<Client>>)> + 'a { ) -> impl Iterator<Item = (LanguageServerName, Result<Arc<Client>>)> + 'a {
language_config.language_servers.iter().filter_map( language_config.language_servers.iter().filter_map(
move |LanguageServerFeatures { name, .. }| { 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)| { if let Some((_, client)) = clients.iter().enumerate().find(|(i, client)| {
client.try_add_doc(&language_config.roots, root_dirs, doc_path, *i == 0) client.try_add_doc(&language_config.roots, root_dirs, doc_path, *i == 0)
}) { }) {
@ -785,21 +800,21 @@ impl Registry {
enable_snippets, enable_snippets,
) { ) {
Ok(client) => { Ok(client) => {
let client = client?; self.inner_by_name
self.inner
.entry(name.to_owned()) .entry(name.to_owned())
.or_default() .or_default()
.push(client.clone()); .push(client.clone());
Some((name.clone(), Ok(client))) 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<Item = &Arc<Client>> { pub fn iter_clients(&self) -> impl Iterator<Item = &Arc<Client>> {
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 /// 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 /// has a unique id assigned at creation through [`Registry`]. This id is then used
/// to store the progress in this map. /// to store the progress in this map.
pub struct LspProgressMap(HashMap<usize, HashMap<lsp::ProgressToken, ProgressStatus>>); pub struct LspProgressMap(HashMap<LanguageServerId, HashMap<lsp::ProgressToken, ProgressStatus>>);
impl LspProgressMap { impl LspProgressMap {
pub fn new() -> Self { pub fn new() -> Self {
@ -830,28 +845,35 @@ impl LspProgressMap {
} }
/// Returns a map of all tokens corresponding to the language server with `id`. /// Returns a map of all tokens corresponding to the language server with `id`.
pub fn progress_map(&self, id: usize) -> Option<&HashMap<lsp::ProgressToken, ProgressStatus>> { pub fn progress_map(
&self,
id: LanguageServerId,
) -> Option<&HashMap<lsp::ProgressToken, ProgressStatus>> {
self.0.get(&id) 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() self.0.get(&id).map(|it| !it.is_empty()).unwrap_or_default()
} }
/// Returns last progress status for a given server with `id` and `token`. /// 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)) self.0.get(&id).and_then(|values| values.get(token))
} }
/// Checks if progress `token` for server with `id` is created. /// 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 self.0
.get(&id) .get(&id)
.map(|values| values.get(token).is_some()) .map(|values| values.get(token).is_some())
.unwrap_or_default() .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 self.0
.entry(id) .entry(id)
.or_default() .or_default()
@ -861,7 +883,7 @@ impl LspProgressMap {
/// Ends the progress by removing the `token` from server with `id`, if removed returns the value. /// Ends the progress by removing the `token` from server with `id`, if removed returns the value.
pub fn end_progress( pub fn end_progress(
&mut self, &mut self,
id: usize, id: LanguageServerId,
token: &lsp::ProgressToken, token: &lsp::ProgressToken,
) -> Option<ProgressStatus> { ) -> Option<ProgressStatus> {
self.0.get_mut(&id).and_then(|vals| vals.remove(token)) 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`. /// Updates the progress of `token` for server with `id` to `status`, returns the value replaced or `None`.
pub fn update( pub fn update(
&mut self, &mut self,
id: usize, id: LanguageServerId,
token: lsp::ProgressToken, token: lsp::ProgressToken,
status: lsp::WorkDoneProgress, status: lsp::WorkDoneProgress,
) -> Option<ProgressStatus> { ) -> Option<ProgressStatus> {
@ -881,19 +903,30 @@ impl LspProgressMap {
} }
} }
struct NewClient(Arc<Client>, UnboundedReceiver<(usize, Call)>); struct NewClient(Arc<Client>, UnboundedReceiver<(LanguageServerId, Call)>);
enum StartupError {
NoRequiredRootFound,
Error(Error),
}
impl<T: Into<Error>> From<T> for StartupError {
fn from(value: T) -> Self {
StartupError::Error(value.into())
}
}
/// start_client takes both a LanguageConfiguration and a LanguageServerConfiguration to ensure that /// start_client takes both a LanguageConfiguration and a LanguageServerConfiguration to ensure that
/// it is only called when it makes sense. /// it is only called when it makes sense.
fn start_client( fn start_client(
id: usize, id: LanguageServerId,
name: String, name: String,
config: &LanguageConfiguration, config: &LanguageConfiguration,
ls_config: &LanguageServerConfiguration, ls_config: &LanguageServerConfiguration,
doc_path: Option<&std::path::PathBuf>, doc_path: Option<&std::path::PathBuf>,
root_dirs: &[PathBuf], root_dirs: &[PathBuf],
enable_snippets: bool, enable_snippets: bool,
) -> Result<Option<NewClient>> { ) -> Result<NewClient, StartupError> {
let (workspace, workspace_is_cwd) = helix_loader::find_workspace(); let (workspace, workspace_is_cwd) = helix_loader::find_workspace();
let workspace = path::normalize(workspace); let workspace = path::normalize(workspace);
let root = find_lsp_workspace( let root = find_lsp_workspace(
@ -918,7 +951,7 @@ fn start_client(
.map(|entry| entry.file_name()) .map(|entry| entry.file_name())
.any(|entry| globset.is_match(entry)) .any(|entry| globset.is_match(entry))
{ {
return Ok(None); return Err(StartupError::NoRequiredRootFound);
} }
} }
@ -970,7 +1003,7 @@ fn start_client(
initialize_notify.notify_one(); initialize_notify.notify_one();
}); });
Ok(Some(NewClient(client, incoming))) Ok(NewClient(client, incoming))
} }
/// Find an LSP workspace of a file using the following mechanism: /// Find an LSP workspace of a file using the following mechanism:

@ -1,4 +1,4 @@
use crate::{jsonrpc, Error, Result}; use crate::{jsonrpc, Error, LanguageServerId, Result};
use anyhow::Context; use anyhow::Context;
use log::{error, info}; use log::{error, info};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -37,7 +37,7 @@ enum ServerMessage {
#[derive(Debug)] #[derive(Debug)]
pub struct Transport { pub struct Transport {
id: usize, id: LanguageServerId,
name: String, name: String,
pending_requests: Mutex<HashMap<jsonrpc::Id, Sender<Result<Value>>>>, pending_requests: Mutex<HashMap<jsonrpc::Id, Sender<Result<Value>>>>,
} }
@ -47,10 +47,10 @@ impl Transport {
server_stdout: BufReader<ChildStdout>, server_stdout: BufReader<ChildStdout>,
server_stdin: BufWriter<ChildStdin>, server_stdin: BufWriter<ChildStdin>,
server_stderr: BufReader<ChildStderr>, server_stderr: BufReader<ChildStderr>,
id: usize, id: LanguageServerId,
name: String, name: String,
) -> ( ) -> (
UnboundedReceiver<(usize, jsonrpc::Call)>, UnboundedReceiver<(LanguageServerId, jsonrpc::Call)>,
UnboundedSender<Payload>, UnboundedSender<Payload>,
Arc<Notify>, Arc<Notify>,
) { ) {
@ -194,7 +194,7 @@ impl Transport {
async fn process_server_message( async fn process_server_message(
&self, &self,
client_tx: &UnboundedSender<(usize, jsonrpc::Call)>, client_tx: &UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
msg: ServerMessage, msg: ServerMessage,
language_server_name: &str, language_server_name: &str,
) -> Result<()> { ) -> Result<()> {
@ -251,7 +251,7 @@ impl Transport {
async fn recv( async fn recv(
transport: Arc<Self>, transport: Arc<Self>,
mut server_stdout: BufReader<ChildStdout>, mut server_stdout: BufReader<ChildStdout>,
client_tx: UnboundedSender<(usize, jsonrpc::Call)>, client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
) { ) {
let mut recv_buffer = String::new(); let mut recv_buffer = String::new();
loop { loop {
@ -329,7 +329,7 @@ impl Transport {
async fn send( async fn send(
transport: Arc<Self>, transport: Arc<Self>,
mut server_stdin: BufWriter<ChildStdin>, mut server_stdin: BufWriter<ChildStdin>,
client_tx: UnboundedSender<(usize, jsonrpc::Call)>, client_tx: UnboundedSender<(LanguageServerId, jsonrpc::Call)>,
mut client_rx: UnboundedReceiver<Payload>, mut client_rx: UnboundedReceiver<Payload>,
initialize_notify: Arc<Notify>, initialize_notify: Arc<Notify>,
) { ) {

@ -17,6 +17,13 @@ etcetera = "0.8"
ropey = { version = "1.6.1", default-features = false } ropey = { version = "1.6.1", default-features = false }
which = "6.0" which = "6.0"
regex-cursor = "0.1.4" regex-cursor = "0.1.4"
bitflags = "2.4"
[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] [dev-dependencies]
tempfile = "3.10" tempfile = "3.10"

@ -0,0 +1,459 @@
//! From <https://github.com/Freaky/faccess>
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<u32>, gid: Option<u32>) -> 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<SecurityDescriptor> {
let path = std::fs::canonicalize(p)?;
let pathos = path.into_os_string();
let mut pathw: Vec<u16> = 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<Self> {
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::<PRIVILEGE_SET>() 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)
}

@ -1,3 +1,4 @@
pub mod env; pub mod env;
pub mod faccess;
pub mod path; pub mod path;
pub mod rope; pub mod rope;

@ -3,7 +3,7 @@ pub use etcetera::home_dir;
use std::{ use std::{
borrow::Cow, borrow::Cow,
ffi::OsString, ffi::OsString,
path::{Component, Path, PathBuf}, path::{Component, Path, PathBuf, MAIN_SEPARATOR_STR},
}; };
use crate::env::current_working_dir; use crate::env::current_working_dir;
@ -18,7 +18,8 @@ where
if let Ok(home) = home_dir() { if let Ok(home) = home_dir() {
if let Ok(stripped) = path.strip_prefix(&home) { if let Ok(stripped) = path.strip_prefix(&home) {
let mut path = OsString::with_capacity(2 + stripped.as_os_str().len()); let mut path = OsString::with_capacity(2 + stripped.as_os_str().len());
path.push("~/"); path.push("~");
path.push(MAIN_SEPARATOR_STR);
path.push(stripped); path.push(stripped);
return Cow::Owned(PathBuf::from(path)); return Cow::Owned(PathBuf::from(path));
} }

@ -3,6 +3,7 @@ use std::ops::{Bound, RangeBounds};
pub use regex_cursor::engines::meta::{Builder as RegexBuilder, Regex}; pub use regex_cursor::engines::meta::{Builder as RegexBuilder, Regex};
pub use regex_cursor::regex_automata::util::syntax::Config; pub use regex_cursor::regex_automata::util::syntax::Config;
use regex_cursor::{Input as RegexInput, RopeyCursor}; use regex_cursor::{Input as RegexInput, RopeyCursor};
use ropey::str_utils::byte_to_char_idx;
use ropey::RopeSlice; use ropey::RopeSlice;
pub trait RopeSliceExt<'a>: Sized { pub trait RopeSliceExt<'a>: Sized {
@ -16,6 +17,23 @@ pub trait RopeSliceExt<'a>: Sized {
fn regex_input_at<R: RangeBounds<usize>>(self, char_range: R) -> RegexInput<RopeyCursor<'a>>; fn regex_input_at<R: RangeBounds<usize>>(self, char_range: R) -> RegexInput<RopeyCursor<'a>>;
fn first_non_whitespace_char(self) -> Option<usize>; fn first_non_whitespace_char(self) -> Option<usize>;
fn last_non_whitespace_char(self) -> Option<usize>; fn last_non_whitespace_char(self) -> Option<usize>;
/// 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> { impl<'a> RopeSliceExt<'a> for RopeSlice<'a> {
@ -75,4 +93,48 @@ impl<'a> RopeSliceExt<'a> for RopeSlice<'a> {
.position(|ch| !ch.is_whitespace()) .position(|ch| !ch.is_whitespace())
.map(|pos| self.len_chars() - pos - 1) .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
);
}
}
}
} }

@ -41,7 +41,7 @@ crossterm = { version = "0.27", features = ["event-stream"] }
signal-hook = "0.3" signal-hook = "0.3"
tokio-stream = "0.1" tokio-stream = "0.1"
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false } 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" termini = "1"
# Logging # Logging
@ -83,5 +83,5 @@ helix-loader = { path = "../helix-loader" }
[dev-dependencies] [dev-dependencies]
smallvec = "1.13" smallvec = "1.13"
indoc = "2.0.4" indoc = "2.0.5"
tempfile = "3.10.1" tempfile = "3.10.1"

@ -4,7 +4,7 @@ use helix_core::{diagnostic::Severity, pos_at_coords, syntax, Selection};
use helix_lsp::{ use helix_lsp::{
lsp::{self, notification::Notification}, lsp::{self, notification::Notification},
util::lsp_range_to_range, util::lsp_range_to_range,
LspProgressMap, LanguageServerId, LspProgressMap,
}; };
use helix_stdx::path::get_relative_path; use helix_stdx::path::get_relative_path;
use helix_view::{ use helix_view::{
@ -655,7 +655,7 @@ impl Application {
pub async fn handle_language_server_message( pub async fn handle_language_server_message(
&mut self, &mut self,
call: helix_lsp::Call, call: helix_lsp::Call,
server_id: usize, server_id: LanguageServerId,
) { ) {
use helix_lsp::{Call, MethodCall, Notification}; use helix_lsp::{Call, MethodCall, Notification};
@ -1030,12 +1030,7 @@ impl Application {
Ok(json!(result)) Ok(json!(result))
} }
Ok(MethodCall::RegisterCapability(params)) => { Ok(MethodCall::RegisterCapability(params)) => {
if let Some(client) = self if let Some(client) = self.editor.language_servers.get_by_id(server_id) {
.editor
.language_servers
.iter_clients()
.find(|client| client.id() == server_id)
{
for reg in params.registrations { for reg in params.registrations {
match reg.method.as_str() { match reg.method.as_str() {
lsp::notification::DidChangeWatchedFiles::METHOD => { lsp::notification::DidChangeWatchedFiles::METHOD => {

@ -3,16 +3,26 @@ pub(crate) mod lsp;
pub(crate) mod typed; pub(crate) mod typed;
pub use dap::*; pub use dap::*;
use helix_stdx::rope::{self, RopeSliceExt}; use helix_event::status;
use helix_vcs::Hunk; use helix_stdx::{
path::expand_tilde,
rope::{self, RopeSliceExt},
};
use helix_vcs::{FileChange, Hunk};
pub use lsp::*; pub use lsp::*;
use tui::widgets::Row; use tui::{
text::Span,
widgets::{Cell, Row},
};
pub use typed::*; pub use typed::*;
use helix_core::{ use helix_core::{
char_idx_at_visual_offset, comment, char_idx_at_visual_offset,
chars::char_is_word,
comment,
doc_formatter::TextFormat, doc_formatter::TextFormat,
encoding, find_workspace, graphemes, encoding, find_workspace,
graphemes::{self, next_grapheme_boundary, RevRopeGraphemes},
history::UndoKind, history::UndoKind,
increment, indent, increment, indent,
indent::IndentStyle, indent::IndentStyle,
@ -24,12 +34,11 @@ use helix_core::{
search::{self, CharMatcher}, search::{self, CharMatcher},
selection, shellwords, surround, selection, shellwords, surround,
syntax::{BlockCommentToken, LanguageServerFeature}, syntax::{BlockCommentToken, LanguageServerFeature},
text_annotations::TextAnnotations, text_annotations::{Overlay, TextAnnotations},
textobject, textobject,
tree_sitter::Node,
unicode::width::UnicodeWidthChar, unicode::width::UnicodeWidthChar,
visual_offset_from_block, Deletion, LineEnding, Position, Range, Rope, RopeGraphemes, 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::{ use helix_view::{
document::{FormatterError, Mode, SCRATCH_BUFFER_NAME}, document::{FormatterError, Mode, SCRATCH_BUFFER_NAME},
@ -37,6 +46,7 @@ use helix_view::{
info::Info, info::Info,
input::KeyEvent, input::KeyEvent,
keyboard::KeyCode, keyboard::KeyCode,
theme::Style,
tree, tree,
view::View, view::View,
Document, DocumentId, Editor, ViewId, Document, DocumentId, Editor, ViewId,
@ -52,7 +62,7 @@ use crate::{
filter_picker_entry, filter_picker_entry,
job::Callback, job::Callback,
keymap::ReverseKeymap, 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 crate::job::{self, Jobs};
@ -322,6 +332,7 @@ impl MappableCommand {
buffer_picker, "Open buffer picker", buffer_picker, "Open buffer picker",
jumplist_picker, "Open jumplist picker", jumplist_picker, "Open jumplist picker",
symbol_picker, "Open symbol picker", symbol_picker, "Open symbol picker",
changed_file_picker, "Open changed file picker",
select_references_to_symbol_under_cursor, "Select symbol references", select_references_to_symbol_under_cursor, "Select symbol references",
workspace_symbol_picker, "Open workspace symbol picker", workspace_symbol_picker, "Open workspace symbol picker",
diagnostics_picker, "Open diagnostic picker", diagnostics_picker, "Open diagnostic picker",
@ -427,8 +438,10 @@ impl MappableCommand {
reverse_selection_contents, "Reverse selections contents", reverse_selection_contents, "Reverse selections contents",
expand_selection, "Expand selection to parent syntax node", expand_selection, "Expand selection to parent syntax node",
shrink_selection, "Shrink selection to previously expanded syntax node", shrink_selection, "Shrink selection to previously expanded syntax node",
select_next_sibling, "Select next sibling in syntax tree", select_next_sibling, "Select next sibling in the syntax tree",
select_prev_sibling, "Select previous sibling in 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_forward, "Jump forward on jumplist",
jump_backward, "Jump backward on jumplist", jump_backward, "Jump backward on jumplist",
save_selection, "Save current selection to jumplist", save_selection, "Save current selection to jumplist",
@ -473,6 +486,8 @@ impl MappableCommand {
goto_prev_comment, "Goto previous comment", goto_prev_comment, "Goto previous comment",
goto_next_test, "Goto next test", goto_next_test, "Goto next test",
goto_prev_test, "Goto previous 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_next_paragraph, "Goto next paragraph",
goto_prev_paragraph, "Goto previous paragraph", goto_prev_paragraph, "Goto previous paragraph",
dap_launch, "Launch debug target", dap_launch, "Launch debug target",
@ -503,6 +518,8 @@ impl MappableCommand {
record_macro, "Record macro", record_macro, "Record macro",
replay_macro, "Replay macro", replay_macro, "Replay macro",
command_palette, "Open command palette", command_palette, "Open command palette",
goto_word, "Jump to a two-character label",
extend_to_word, "Extend to a two-character label",
); );
} }
@ -618,6 +635,7 @@ fn move_impl(cx: &mut Context, move_fn: MoveFn, dir: Direction, behaviour: Movem
&mut annotations, &mut annotations,
) )
}); });
drop(annotations);
doc.set_selection(view.id, selection); doc.set_selection(view.id, selection);
} }
@ -781,28 +799,29 @@ fn goto_line_start(cx: &mut Context) {
} }
fn goto_next_buffer(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) { 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 current = view!(editor).doc;
let id = match direction { let id = match direction {
Direction::Forward => { Direction::Forward => {
let iter = editor.documents.keys(); let iter = editor.documents.keys();
let mut iter = iter.skip_while(|id| *id != &current); // skip 'count' times past current buffer
iter.next(); // skip current item iter.cycle().skip_while(|id| *id != &current).nth(count)
iter.next().or_else(|| editor.documents.keys().next())
} }
Direction::Backward => { Direction::Backward => {
let iter = editor.documents.keys(); let iter = editor.documents.keys();
let mut iter = iter.rev().skip_while(|id| *id != &current); // skip 'count' times past current buffer
iter.next(); // skip current item iter.rev()
iter.next().or_else(|| editor.documents.keys().next_back()) .cycle()
.skip_while(|id| *id != &current)
.nth(count)
} }
} }
.unwrap(); .unwrap();
@ -1183,25 +1202,51 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
let primary = selections.primary(); let primary = selections.primary();
// Checks whether there is only one selection with a width of 1 // Checks whether there is only one selection with a width of 1
if selections.len() == 1 && primary.len() == 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.clear();
paths.push(
current_word let is_valid_path_char = |c: &char| {
.fragment(text_slice) #[cfg(target_os = "windows")]
.trim_matches(surrounding_chars) let valid_chars = &[
.to_string(), '@', '/', '\\', '.', '-', '_', '+', '#', '$', '%', '{', '}', '[', ']', ':', '!',
); '~', '=',
];
#[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<str> = 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 { for sel in paths {
@ -1211,7 +1256,8 @@ fn goto_file_impl(cx: &mut Context, action: Action) {
} }
if let Ok(url) = Url::parse(p) { 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); let path = &rel_path.join(p);
@ -1638,7 +1684,7 @@ pub fn scroll(cx: &mut Context, offset: usize, direction: Direction, sync_cursor
let doc_text = doc.text().slice(..); let doc_text = doc.text().slice(..);
let viewport = view.inner_area(doc); let viewport = view.inner_area(doc);
let text_fmt = doc.text_format(viewport.width, None); 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( (view.offset.anchor, view.offset.vertical_offset) = char_idx_at_visual_offset(
doc_text, doc_text,
view.offset.anchor, view.offset.anchor,
@ -1716,6 +1762,7 @@ pub fn scroll(cx: &mut Context, offset: usize, direction: Direction, sync_cursor
let mut sel = doc.selection(view.id).clone(); let mut sel = doc.selection(view.id).clone();
let idx = sel.primary_index(); let idx = sel.primary_index();
sel = sel.replace(idx, prim_sel); sel = sel.replace(idx, prim_sel);
drop(annotations);
doc.set_selection(view.id, sel); doc.set_selection(view.id, sel);
} }
@ -2034,6 +2081,11 @@ fn searcher(cx: &mut Context, direction: Direction) {
let config = cx.editor.config(); let config = cx.editor.config();
let scrolloff = config.scrolloff; let scrolloff = config.scrolloff;
let wrap_around = config.search.wrap_around; 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? // TODO: could probably share with select_on_matches?
let completions = search_completions(cx, Some(reg)); let completions = search_completions(cx, Some(reg));
@ -2058,7 +2110,7 @@ fn searcher(cx: &mut Context, direction: Direction) {
search_impl( search_impl(
cx.editor, cx.editor,
&regex, &regex,
Movement::Move, movement,
direction, direction,
scrolloff, scrolloff,
wrap_around, wrap_around,
@ -2603,14 +2655,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 (view, doc) = current!(cx.editor);
let selection = doc.selection(view.id); let selection = doc.selection(view.id);
let only_whole_lines = selection_is_linewise(selection, doc.text()); let only_whole_lines = selection_is_linewise(selection, doc.text());
if cx.register != Some('_') { if cx.register != Some('_') && matches!(yank, YankAction::Yank) {
// first yank the selection // yank the selection
let text = doc.text().slice(..); let text = doc.text().slice(..);
let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect(); let values: Vec<String> = selection.fragments(text).map(Cow::into_owned).collect();
let reg_name = cx.register.unwrap_or('"'); let reg_name = cx.register.unwrap_or('"');
@ -2618,9 +2675,9 @@ fn delete_selection_impl(cx: &mut Context, op: Operation) {
cx.editor.set_error(err.to_string()); cx.editor.set_error(err.to_string());
return; return;
} }
}; }
// then delete // delete the selection
let transaction = let transaction =
Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to())); Transaction::delete_by_selection(doc.text(), selection, |range| (range.from(), range.to()));
doc.apply(&transaction, view.id); doc.apply(&transaction, view.id);
@ -2686,21 +2743,19 @@ fn delete_by_selection_insert_mode(
} }
fn delete_selection(cx: &mut Context) { 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) { fn delete_selection_noyank(cx: &mut Context) {
cx.register = Some('_'); delete_selection_impl(cx, Operation::Delete, YankAction::NoYank);
delete_selection_impl(cx, Operation::Delete);
} }
fn change_selection(cx: &mut Context) { 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) { fn change_selection_noyank(cx: &mut Context) {
cx.register = Some('_'); delete_selection_impl(cx, Operation::Change, YankAction::NoYank);
delete_selection_impl(cx, Operation::Change);
} }
fn collapse_selection(cx: &mut Context) { fn collapse_selection(cx: &mut Context) {
@ -2966,6 +3021,7 @@ fn jumplist_picker(cx: &mut Context) {
.flat_map(|(view, _)| { .flat_map(|(view, _)| {
view.jumps view.jumps
.iter() .iter()
.rev()
.map(|(doc_id, selection)| new_meta(view, *doc_id, selection.clone())) .map(|(doc_id, selection)| new_meta(view, *doc_id, selection.clone()))
}) })
.collect(), .collect(),
@ -2988,6 +3044,94 @@ fn jumplist_picker(cx: &mut Context) {
cx.push_layer(Box::new(overlaid(picker))); 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 { impl ui::menu::Item for MappableCommand {
type Data = ReverseKeymap; type Data = ReverseKeymap;
@ -3439,7 +3583,8 @@ fn goto_last_diag(cx: &mut Context) {
} }
fn goto_next_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 let cursor_pos = doc
.selection(view.id) .selection(view.id)
@ -3457,10 +3602,14 @@ fn goto_next_diag(cx: &mut Context) {
None => return, 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) { 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 let cursor_pos = doc
.selection(view.id) .selection(view.id)
@ -3481,6 +3630,8 @@ fn goto_prev_diag(cx: &mut Context) {
None => return, 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) { fn goto_first_change(cx: &mut Context) {
@ -4768,18 +4919,17 @@ fn shrink_selection(cx: &mut Context) {
cx.editor.apply_motion(motion); cx.editor.apply_motion(motion);
} }
fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: &'static F) fn select_sibling_impl<F>(cx: &mut Context, sibling_fn: F)
where where
F: Fn(Node) -> Option<Node>, 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); let (view, doc) = current!(editor);
if let Some(syntax) = doc.syntax() { if let Some(syntax) = doc.syntax() {
let text = doc.text().slice(..); let text = doc.text().slice(..);
let current_selection = doc.selection(view.id); let current_selection = doc.selection(view.id);
let selection = let selection = sibling_fn(syntax, text, current_selection.clone());
object::select_sibling(syntax, text, current_selection.clone(), sibling_fn);
doc.set_selection(view.id, selection); doc.set_selection(view.id, selection);
} }
}; };
@ -4787,11 +4937,11 @@ where
} }
fn select_next_sibling(cx: &mut Context) { 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) { 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) { fn move_node_bound_impl(cx: &mut Context, dir: Direction, movement: Movement) {
@ -4833,6 +4983,36 @@ pub fn extend_parent_node_start(cx: &mut Context) {
move_node_bound_impl(cx, Direction::Backward, Movement::Extend) move_node_bound_impl(cx, Direction::Backward, Movement::Extend)
} }
fn select_all_impl<F>(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) { fn match_brackets(cx: &mut Context) {
let (view, doc) = current!(cx.editor); let (view, doc) = current!(cx.editor);
let is_select = cx.editor.mode == Mode::Select; let is_select = cx.editor.mode == Mode::Select;
@ -5155,6 +5335,14 @@ fn goto_prev_test(cx: &mut Context) {
goto_ts_object_impl(cx, "test", Direction::Backward) 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) { fn select_textobject_around(cx: &mut Context) {
select_textobject(cx, textobject::TextObject::Around); select_textobject(cx, textobject::TextObject::Around);
} }
@ -5219,15 +5407,25 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
'a' => textobject_treesitter("parameter", range), 'a' => textobject_treesitter("parameter", range),
'c' => textobject_treesitter("comment", range), 'c' => textobject_treesitter("comment", range),
'T' => textobject_treesitter("test", range), 'T' => textobject_treesitter("test", range),
'e' => textobject_treesitter("entry", range),
'p' => textobject::textobject_paragraph(text, range, objtype, count), 'p' => textobject::textobject_paragraph(text, range, objtype, count),
'm' => textobject::textobject_pair_surround_closest( 'm' => textobject::textobject_pair_surround_closest(
text, range, objtype, count, doc.syntax(),
text,
range,
objtype,
count,
), ),
'g' => textobject_change(range), 'g' => textobject_change(range),
// TODO: cancel new ranges if inconsistent surround matches across lines // TODO: cancel new ranges if inconsistent surround matches across lines
ch if !ch.is_ascii_alphanumeric() => { ch if !ch.is_ascii_alphanumeric() => textobject::textobject_pair_surround(
textobject::textobject_pair_surround(text, range, objtype, ch, count) doc.syntax(),
} text,
range,
objtype,
ch,
count,
),
_ => range, _ => range,
} }
}); });
@ -5251,7 +5449,9 @@ fn select_textobject(cx: &mut Context, objtype: textobject::TextObject) {
("a", "Argument/parameter (tree-sitter)"), ("a", "Argument/parameter (tree-sitter)"),
("c", "Comment (tree-sitter)"), ("c", "Comment (tree-sitter)"),
("T", "Test (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"), (" ", "... or any character acting as a pair"),
]; ];
@ -5264,7 +5464,7 @@ fn surround_add(cx: &mut Context) {
// surround_len is the number of new characters being added. // surround_len is the number of new characters being added.
let (open, close, surround_len) = match event.char() { let (open, close, surround_len) = match event.char() {
Some(ch) => { Some(ch) => {
let (o, c) = surround::get_pair(ch); let (o, c) = match_brackets::get_pair(ch);
let mut open = Tendril::new(); let mut open = Tendril::new();
open.push(o); open.push(o);
let mut close = Tendril::new(); let mut close = Tendril::new();
@ -5315,7 +5515,8 @@ fn surround_replace(cx: &mut Context) {
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection(view.id); let selection = doc.selection(view.id);
let change_pos = match surround::get_surround_pos(text, selection, surround_ch, count) { let change_pos =
match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
Ok(c) => c, Ok(c) => c,
Err(err) => { Err(err) => {
cx.editor.set_error(err.to_string()); cx.editor.set_error(err.to_string());
@ -5336,7 +5537,7 @@ fn surround_replace(cx: &mut Context) {
Some(to) => to, Some(to) => to,
None => return doc.set_selection(view.id, selection), 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 // the changeset has to be sorted to allow nested surrounds
let mut sorted_pos: Vec<(usize, char)> = Vec::new(); let mut sorted_pos: Vec<(usize, char)> = Vec::new();
@ -5373,7 +5574,8 @@ fn surround_delete(cx: &mut Context) {
let text = doc.text().slice(..); let text = doc.text().slice(..);
let selection = doc.selection(view.id); let selection = doc.selection(view.id);
let mut change_pos = match surround::get_surround_pos(text, selection, surround_ch, count) { let mut change_pos =
match surround::get_surround_pos(doc.syntax(), text, selection, surround_ch, count) {
Ok(c) => c, Ok(c) => c,
Err(err) => { Err(err) => {
cx.editor.set_error(err.to_string()); cx.editor.set_error(err.to_string());
@ -5807,3 +6009,188 @@ fn replay_macro(cx: &mut Context) {
cx.editor.macro_replaying.pop(); 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<Range>, 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)
}

@ -8,7 +8,7 @@ use dap::{StackFrame, Thread, ThreadStates};
use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate}; use helix_core::syntax::{DebugArgumentValue, DebugConfigCompletion, DebugTemplate};
use helix_dap::{self as dap, Client}; use helix_dap::{self as dap, Client};
use helix_lsp::block_on; use helix_lsp::block_on;
use helix_view::{editor::Breakpoint, graphics::Margin}; use helix_view::editor::Breakpoint;
use serde_json::{to_value, Value}; use serde_json::{to_value, Value};
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
@ -581,12 +581,7 @@ pub fn dap_variables(cx: &mut Context) {
} }
let contents = Text::from(tui::text::Text::from(variables)); let contents = Text::from(tui::text::Text::from(variables));
let margin = if cx.editor.popup_border() { let popup = Popup::new("dap-variables", contents);
Margin::all(1)
} else {
Margin::none()
};
let popup = Popup::new("dap-variables", contents).margin(margin);
cx.replace_or_push_layer("dap-variables", popup); cx.replace_or_push_layer("dap-variables", popup);
} }

@ -1,4 +1,4 @@
use futures_util::{stream::FuturesUnordered, FutureExt}; use futures_util::{stream::FuturesOrdered, FutureExt};
use helix_lsp::{ use helix_lsp::{
block_on, block_on,
lsp::{ lsp::{
@ -6,7 +6,7 @@ use helix_lsp::{
NumberOrString, NumberOrString,
}, },
util::{diagnostic_to_lsp_diagnostic, lsp_range_to_range, range_to_lsp_range}, util::{diagnostic_to_lsp_diagnostic, lsp_range_to_range, range_to_lsp_range},
Client, OffsetEncoding, Client, LanguageServerId, OffsetEncoding,
}; };
use tokio_stream::StreamExt; use tokio_stream::StreamExt;
use tui::{ use tui::{
@ -21,7 +21,6 @@ use helix_stdx::path;
use helix_view::{ use helix_view::{
document::{DocumentInlayHints, DocumentInlayHintsId}, document::{DocumentInlayHints, DocumentInlayHintsId},
editor::Action, editor::Action,
graphics::Margin,
handlers::lsp::SignatureHelpInvoked, handlers::lsp::SignatureHelpInvoked,
theme::Style, theme::Style,
Document, View, Document, View,
@ -266,7 +265,7 @@ enum DiagnosticsFormat {
fn diag_picker( fn diag_picker(
cx: &Context, cx: &Context,
diagnostics: BTreeMap<PathBuf, Vec<(lsp::Diagnostic, usize)>>, diagnostics: BTreeMap<PathBuf, Vec<(lsp::Diagnostic, LanguageServerId)>>,
format: DiagnosticsFormat, format: DiagnosticsFormat,
) -> Picker<PickerDiagnostic> { ) -> Picker<PickerDiagnostic> {
// TODO: drop current_path comparison and instead use workspace: bool flag? // TODO: drop current_path comparison and instead use workspace: bool flag?
@ -341,7 +340,7 @@ pub fn symbol_picker(cx: &mut Context) {
let mut seen_language_servers = HashSet::new(); let mut seen_language_servers = HashSet::new();
let mut futures: FuturesUnordered<_> = doc let mut futures: FuturesOrdered<_> = doc
.language_servers_with_feature(LanguageServerFeature::DocumentSymbols) .language_servers_with_feature(LanguageServerFeature::DocumentSymbols)
.filter(|ls| seen_language_servers.insert(ls.id())) .filter(|ls| seen_language_servers.insert(ls.id()))
.map(|language_server| { .map(|language_server| {
@ -416,7 +415,7 @@ pub fn workspace_symbol_picker(cx: &mut Context) {
let get_symbols = move |pattern: String, editor: &mut Editor| { let get_symbols = move |pattern: String, editor: &mut Editor| {
let doc = doc!(editor); let doc = doc!(editor);
let mut seen_language_servers = HashSet::new(); let mut seen_language_servers = HashSet::new();
let mut futures: FuturesUnordered<_> = doc let mut futures: FuturesOrdered<_> = doc
.language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols) .language_servers_with_feature(LanguageServerFeature::WorkspaceSymbols)
.filter(|ls| seen_language_servers.insert(ls.id())) .filter(|ls| seen_language_servers.insert(ls.id()))
.map(|language_server| { .map(|language_server| {
@ -497,7 +496,7 @@ pub fn workspace_diagnostics_picker(cx: &mut Context) {
struct CodeActionOrCommandItem { struct CodeActionOrCommandItem {
lsp_item: lsp::CodeActionOrCommand, lsp_item: lsp::CodeActionOrCommand,
language_server_id: usize, language_server_id: LanguageServerId,
} }
impl ui::menu::Item for CodeActionOrCommandItem { impl ui::menu::Item for CodeActionOrCommandItem {
@ -574,7 +573,7 @@ pub fn code_action(cx: &mut Context) {
let mut seen_language_servers = HashSet::new(); let mut seen_language_servers = HashSet::new();
let mut futures: FuturesUnordered<_> = doc let mut futures: FuturesOrdered<_> = doc
.language_servers_with_feature(LanguageServerFeature::CodeAction) .language_servers_with_feature(LanguageServerFeature::CodeAction)
.filter(|ls| seen_language_servers.insert(ls.id())) .filter(|ls| seen_language_servers.insert(ls.id()))
// TODO this should probably already been filtered in something like "language_servers_with_feature" // TODO this should probably already been filtered in something like "language_servers_with_feature"
@ -733,15 +732,7 @@ pub fn code_action(cx: &mut Context) {
}); });
picker.move_down(); // pre-select the first item picker.move_down(); // pre-select the first item
let margin = if editor.menu_border() { let popup = Popup::new("code-action", picker).with_scrollbar(false);
Margin::vertical(1)
} else {
Margin::none()
};
let popup = Popup::new("code-action", picker)
.with_scrollbar(false)
.margin(margin);
compositor.replace_or_push("code-action", popup); compositor.replace_or_push("code-action", popup);
}; };
@ -757,7 +748,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 // the command is executed on the server and communicated back
// to the client asynchronously using workspace edits // to the client asynchronously using workspace edits
let future = match editor let future = match editor
@ -1034,7 +1029,7 @@ pub fn rename_symbol(cx: &mut Context) {
fn create_rename_prompt( fn create_rename_prompt(
editor: &Editor, editor: &Editor,
prefill: String, prefill: String,
language_server_id: Option<usize>, language_server_id: Option<LanguageServerId>,
) -> Box<ui::Prompt> { ) -> Box<ui::Prompt> {
let prompt = ui::Prompt::new( let prompt = ui::Prompt::new(
"rename-to:".into(), "rename-to:".into(),
@ -1315,11 +1310,11 @@ fn compute_inlay_hints_for_view(
view_id, view_id,
DocumentInlayHints { DocumentInlayHints {
id: new_doc_inlay_hints_id, id: new_doc_inlay_hints_id,
type_inlay_hints: type_inlay_hints.into(), type_inlay_hints,
parameter_inlay_hints: parameter_inlay_hints.into(), parameter_inlay_hints,
other_inlay_hints: other_inlay_hints.into(), other_inlay_hints,
padding_before_inlay_hints: padding_before_inlay_hints.into(), padding_before_inlay_hints,
padding_after_inlay_hints: padding_after_inlay_hints.into(), padding_after_inlay_hints,
}, },
); );
doc.inlay_hints_oudated = false; doc.inlay_hints_oudated = false;

@ -1,4 +1,5 @@
use std::fmt::Write; use std::fmt::Write;
use std::io::BufReader;
use std::ops::Deref; use std::ops::Deref;
use crate::job::Job; use crate::job::Job;
@ -7,9 +8,9 @@ use super::*;
use helix_core::fuzzy::fuzzy_match; use helix_core::fuzzy::fuzzy_match;
use helix_core::indent::MAX_INDENT; use helix_core::indent::MAX_INDENT;
use helix_core::{encoding, line_ending, shellwords::Shellwords}; use helix_core::{line_ending, shellwords::Shellwords};
use helix_view::document::DEFAULT_LANGUAGE_NAME; use helix_view::document::{read_to_string, DEFAULT_LANGUAGE_NAME};
use helix_view::editor::{Action, CloseError, ConfigEvent}; use helix_view::editor::{CloseError, ConfigEvent};
use serde_json::Value; use serde_json::Value;
use ui::completers::{self, Completer}; use ui::completers::{self, Completer};
@ -309,7 +310,7 @@ fn buffer_next(
return Ok(()); return Ok(());
} }
goto_buffer(cx.editor, Direction::Forward); goto_buffer(cx.editor, Direction::Forward, 1);
Ok(()) Ok(())
} }
@ -322,7 +323,7 @@ fn buffer_previous(
return Ok(()); return Ok(());
} }
goto_buffer(cx.editor, Direction::Backward); goto_buffer(cx.editor, Direction::Backward, 1);
Ok(()) Ok(())
} }
@ -2454,6 +2455,39 @@ fn yank_diagnostic(
Ok(()) Ok(())
} }
fn read(cx: &mut compositor::Context, args: &[Cow<str>], 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] = &[ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
TypableCommand { TypableCommand {
name: "quit", name: "quit",
@ -3068,6 +3102,13 @@ pub const TYPABLE_COMMAND_LIST: &[TypableCommand] = &[
fun: yank_diagnostic, fun: yank_diagnostic,
signature: CommandSignature::all(completers::register), 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<HashMap<&'static str, &'static TypableCommand>> = pub static TYPABLE_COMMAND_MAP: Lazy<HashMap<&'static str, &'static TypableCommand>> =

@ -9,10 +9,9 @@ use crate::handlers::completion::CompletionHandler;
use crate::handlers::signature_help::SignatureHelpHandler; use crate::handlers::signature_help::SignatureHelpHandler;
pub use completion::trigger_auto_completion; pub use completion::trigger_auto_completion;
pub use helix_view::handlers::lsp::SignatureHelpInvoked;
pub use helix_view::handlers::Handlers; pub use helix_view::handlers::Handlers;
mod completion; pub mod completion;
mod signature_help; mod signature_help;
pub fn setup(config: Arc<ArcSwap<Config>>) -> Handlers { pub fn setup(config: Arc<ArcSwap<Config>>) -> Handlers {

@ -30,6 +30,8 @@ use crate::ui::lsp::SignatureHelp;
use crate::ui::{self, CompletionItem, Popup}; use crate::ui::{self, CompletionItem, Popup};
use super::Handlers; use super::Handlers;
pub use resolve::ResolveHandler;
mod resolve;
#[derive(Debug, PartialEq, Eq, Clone, Copy)] #[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum TriggerKind { enum TriggerKind {
@ -251,7 +253,7 @@ fn request_completion(
.into_iter() .into_iter()
.map(|item| CompletionItem { .map(|item| CompletionItem {
item, item,
language_server_id, provider: language_server_id,
resolved: false, resolved: false,
}) })
.collect(); .collect();

@ -0,0 +1,153 @@
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<Arc<CompletionItem>>,
resolver: Sender<ResolveRequest>,
}
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;
}
let needs_resolve = item.item.documentation.is_none()
|| item.item.detail.is_none()
|| item.item.additional_text_edits.is_none();
if !needs_resolve {
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<CompletionItem>,
ls: Arc<helix_lsp::Client>,
}
#[derive(Default)]
struct ResolveTimeout {
next_request: Option<ResolveRequest>,
in_flight: Option<(helix_event::CancelTx, Arc<CompletionItem>)>,
}
impl AsyncHook for ResolveTimeout {
type Event = ResolveRequest;
fn handle_event(
&mut self,
request: Self::Event,
timeout: Option<tokio::time::Instant>,
) -> Option<tokio::time::Instant> {
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::<crate::ui::EditorView>()
.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
}
}

@ -5,7 +5,7 @@ use helix_core::syntax::LanguageServerFeature;
use helix_event::{ use helix_event::{
cancelable_future, cancelation, register_hook, send_blocking, CancelRx, CancelTx, 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_stdx::rope::RopeSliceExt;
use helix_view::document::Mode; use helix_view::document::Mode;
use helix_view::events::{DocumentDidChange, SelectionDidChange}; use helix_view::events::{DocumentDidChange, SelectionDidChange};
@ -18,7 +18,7 @@ use crate::commands::Open;
use crate::compositor::Compositor; use crate::compositor::Compositor;
use crate::events::{OnModeSwitch, PostInsertChar}; use crate::events::{OnModeSwitch, PostInsertChar};
use crate::handlers::Handlers; use crate::handlers::Handlers;
use crate::ui::lsp::SignatureHelp; use crate::ui::lsp::{Signature, SignatureHelp};
use crate::ui::Popup; use crate::ui::Popup;
use crate::{job, ui}; use crate::{job, ui};
@ -82,6 +82,7 @@ impl helix_event::AsyncHook for SignatureHelpHandler {
} }
} }
self.state = if open { State::Open } else { State::Closed }; self.state = if open { State::Open } else { State::Closed };
return timeout; return timeout;
} }
} }
@ -138,6 +139,31 @@ pub fn request_signature_help(
}); });
} }
fn active_param_range(
signature: &SignatureInformation,
response_active_parameter: Option<u32>,
) -> 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 &param.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( pub fn show_signature_help(
editor: &mut Editor, editor: &mut Editor,
compositor: &mut Compositor, compositor: &mut Compositor,
@ -184,54 +210,50 @@ pub fn show_signature_help(
let doc = doc!(editor); let doc = doc!(editor);
let language = doc.language_name().unwrap_or(""); let language = doc.language_name().unwrap_or("");
let signature = match response if response.signatures.is_empty() {
return;
}
let signatures: Vec<Signature> = response
.signatures .signatures
.get(response.active_signature.unwrap_or(0) as usize) .into_iter()
{ .map(|s| {
Some(s) => s, let active_param_range = active_param_range(&s, response.active_parameter);
None => return,
};
let mut contents = SignatureHelp::new(
signature.label.clone(),
language.to_string(),
Arc::clone(&editor.syn_loader),
);
let signature_doc = if config.lsp.display_signature_help_docs { let signature_doc = if config.lsp.display_signature_help_docs {
signature.documentation.as_ref().map(|doc| match doc { s.documentation.map(|doc| match doc {
lsp::Documentation::String(s) => s.clone(), lsp::Documentation::String(s) => s,
lsp::Documentation::MarkupContent(markup) => markup.value.clone(), lsp::Documentation::MarkupContent(markup) => markup.value,
}) })
} else { } else {
None None
}; };
contents.set_signature_doc(signature_doc); Signature {
signature: s.label,
let active_param_range = || -> Option<(usize, usize)> { signature_doc,
let param_idx = signature active_param_range,
.active_parameter
.or(response.active_parameter)
.unwrap_or(0) as usize;
let param = signature.parameters.as_ref()?.get(param_idx)?;
match &param.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))
} }
} })
}; .collect();
contents.set_active_param_range(active_param_range());
let old_popup = compositor.find_id::<Popup<SignatureHelp>>(SignatureHelp::ID); let old_popup = compositor.find_id::<Popup<SignatureHelp>>(SignatureHelp::ID);
let mut active_signature = old_popup
.as_ref()
.map(|popup| popup.contents().active_signature())
.unwrap_or_else(|| response.active_signature.unwrap_or_default() as usize);
if active_signature >= signatures.len() {
active_signature = signatures.len() - 1;
}
let contents = SignatureHelp::new(
language.to_string(),
Arc::clone(&editor.syn_loader),
active_signature,
signatures,
);
let mut popup = Popup::new(SignatureHelp::ID, contents) let mut popup = Popup::new(SignatureHelp::ID, contents)
.position(old_popup.and_then(|p| p.get_position())) .position(old_popup.and_then(|p| p.get_position()))
.position_bias(Open::Above) .position_bias(Open::Above)

@ -58,6 +58,7 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"k" => move_line_up, "k" => move_line_up,
"j" => move_line_down, "j" => move_line_down,
"." => goto_last_modification, "." => goto_last_modification,
"w" => goto_word,
}, },
":" => command_mode, ":" => command_mode,
@ -86,10 +87,12 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"A-;" => flip_selections, "A-;" => flip_selections,
"A-o" | "A-up" => expand_selection, "A-o" | "A-up" => expand_selection,
"A-i" | "A-down" => shrink_selection, "A-i" | "A-down" => shrink_selection,
"A-I" | "A-S-down" => select_all_children,
"A-p" | "A-left" => select_prev_sibling, "A-p" | "A-left" => select_prev_sibling,
"A-n" | "A-right" => select_next_sibling, "A-n" | "A-right" => select_next_sibling,
"A-e" => move_parent_node_end, "A-e" => move_parent_node_end,
"A-b" => move_parent_node_start, "A-b" => move_parent_node_start,
"A-a" => select_all_siblings,
"%" => select_all, "%" => select_all,
"x" => extend_line_below, "x" => extend_line_below,
@ -113,6 +116,7 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"t" => goto_prev_class, "t" => goto_prev_class,
"a" => goto_prev_parameter, "a" => goto_prev_parameter,
"c" => goto_prev_comment, "c" => goto_prev_comment,
"e" => goto_prev_entry,
"T" => goto_prev_test, "T" => goto_prev_test,
"p" => goto_prev_paragraph, "p" => goto_prev_paragraph,
"space" => add_newline_above, "space" => add_newline_above,
@ -126,6 +130,7 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"t" => goto_next_class, "t" => goto_next_class,
"a" => goto_next_parameter, "a" => goto_next_parameter,
"c" => goto_next_comment, "c" => goto_next_comment,
"e" => goto_next_entry,
"T" => goto_next_test, "T" => goto_next_test,
"p" => goto_next_paragraph, "p" => goto_next_paragraph,
"space" => add_newline_below, "space" => add_newline_below,
@ -222,9 +227,10 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"S" => workspace_symbol_picker, "S" => workspace_symbol_picker,
"d" => diagnostics_picker, "d" => diagnostics_picker,
"D" => workspace_diagnostics_picker, "D" => workspace_diagnostics_picker,
"g" => changed_file_picker,
"a" => code_action, "a" => code_action,
"'" => last_picker, "'" => last_picker,
"g" => { "Debug (experimental)" sticky=true "G" => { "Debug (experimental)" sticky=true
"l" => dap_launch, "l" => dap_launch,
"r" => dap_restart, "r" => dap_restart,
"b" => dap_toggle_breakpoint, "b" => dap_toggle_breakpoint,
@ -360,6 +366,7 @@ pub fn default() -> HashMap<Mode, KeyTrie> {
"g" => { "Goto" "g" => { "Goto"
"k" => extend_line_up, "k" => extend_line_up,
"j" => extend_line_down, "j" => extend_line_down,
"w" => extend_to_word,
}, },
})); }));
let insert = keymap!({ "Insert mode" let insert = keymap!({ "Insert mode"

@ -20,8 +20,6 @@ mod handlers;
use ignore::DirEntry; use ignore::DirEntry;
use url::Url; use url::Url;
pub use keymap::macros::*;
#[cfg(windows)] #[cfg(windows)]
fn true_color() -> bool { fn true_color() -> bool {
true true
@ -53,7 +51,7 @@ fn filter_picker_entry(entry: &DirEntry, root: &Path, dedup_symlinks: bool) -> b
// in our picker. // in our picker.
if matches!( if matches!(
entry.file_name().to_str(), entry.file_name().to_str(),
Some(".git" | ".pijul" | ".jj" | ".hg") Some(".git" | ".pijul" | ".jj" | ".hg" | ".svn")
) { ) {
return false; return false;
} }

@ -1,28 +1,24 @@
use crate::{ use crate::{
compositor::{Component, Context, Event, EventResult}, compositor::{Component, Context, Event, EventResult},
handlers::trigger_auto_completion, handlers::{completion::ResolveHandler, trigger_auto_completion},
job,
}; };
use helix_event::AsyncHook;
use helix_view::{ use helix_view::{
document::SavePoint, document::SavePoint,
editor::CompleteAction, editor::CompleteAction,
graphics::Margin,
handlers::lsp::SignatureHelpInvoked, handlers::lsp::SignatureHelpInvoked,
theme::{Modifier, Style}, theme::{Modifier, Style},
ViewId, ViewId,
}; };
use tokio::time::Instant;
use tui::{buffer::Buffer as Surface, text::Span}; 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_core::{chars, Change, Transaction};
use helix_view::{graphics::Rect, Document, Editor}; use helix_view::{graphics::Rect, Document, Editor};
use crate::ui::{menu, Markdown, Menu, Popup, PromptEvent}; 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 { impl menu::Item for CompletionItem {
type Data = (); type Data = ();
@ -94,7 +90,7 @@ impl menu::Item for CompletionItem {
#[derive(Debug, PartialEq, Default, Clone)] #[derive(Debug, PartialEq, Default, Clone)]
pub struct CompletionItem { pub struct CompletionItem {
pub item: lsp::CompletionItem, pub item: lsp::CompletionItem,
pub language_server_id: usize, pub provider: LanguageServerId,
pub resolved: bool, pub resolved: bool,
} }
@ -104,7 +100,7 @@ pub struct Completion {
#[allow(dead_code)] #[allow(dead_code)]
trigger_offset: usize, trigger_offset: usize,
filter: String, filter: String,
resolve_handler: tokio::sync::mpsc::Sender<CompletionItem>, resolve_handler: ResolveHandler,
} }
impl Completion { impl Completion {
@ -224,7 +220,7 @@ impl Completion {
($item:expr) => { ($item:expr) => {
match editor match editor
.language_servers .language_servers
.get_by_id($item.language_server_id) .get_by_id($item.provider)
{ {
Some(ls) => ls, Some(ls) => ls,
None => { None => {
@ -285,12 +281,6 @@ impl Completion {
let language_server = language_server!(item); let language_server = language_server!(item);
let offset_encoding = language_server.offset_encoding(); 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 !item.resolved {
if let Some(resolved) = if let Some(resolved) =
Self::resolve_completion_item(language_server, item.item.clone()) 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) let popup = Popup::new(Self::ID, menu)
.with_scrollbar(false) .with_scrollbar(false)
.ignore_escape_key(true) .ignore_escape_key(true);
.margin(margin);
let (view, doc) = current_ref!(editor); let (view, doc) = current_ref!(editor);
let text = doc.text().slice(..); let text = doc.text().slice(..);
@ -371,7 +354,7 @@ impl Completion {
// TODO: expand nucleo api to allow moving straight to a Utf32String here // TODO: expand nucleo api to allow moving straight to a Utf32String here
// and avoid allocation during matching // and avoid allocation during matching
filter: String::from(fragment), filter: String::from(fragment),
resolve_handler: ResolveHandler::default().spawn(), resolve_handler: ResolveHandler::new(),
}; };
// need to recompute immediately in case start_offset != trigger_offset // need to recompute immediately in case start_offset != trigger_offset
@ -389,7 +372,16 @@ impl Completion {
language_server: &helix_lsp::Client, language_server: &helix_lsp::Client,
completion_item: lsp::CompletionItem, completion_item: lsp::CompletionItem,
) -> Option<lsp::CompletionItem> { ) -> Option<lsp::CompletionItem> {
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); let response = helix_lsp::block_on(future);
match response { match response {
Ok(item) => Some(item), Ok(item) => Some(item),
@ -422,7 +414,7 @@ impl Completion {
self.popup.contents().is_empty() 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); self.popup.contents_mut().replace_option(old_item, new_item);
} }
@ -444,12 +436,12 @@ impl Component for Completion {
self.popup.render(area, surface, cx); self.popup.render(area, surface, cx);
// if we have a selection, render a markdown popup on top/below with info // 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, Some(option) => option,
None => return, None => return,
}; };
if !option.resolved { if !option.resolved {
helix_event::send_blocking(&self.resolve_handler, option.clone()); self.resolve_handler.ensure_item_resolved(cx.editor, option);
} }
// need to render: // need to render:
// option.detail // option.detail
@ -498,12 +490,7 @@ impl Component for Completion {
None => return, None => return,
}; };
let popup_area = { let popup_area = self.popup.area(area, cx.editor);
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 doc_width_available = area.width.saturating_sub(popup_area.right()); let doc_width_available = area.width.saturating_sub(popup_area.right());
let doc_area = if doc_width_available > 30 { let doc_area = if doc_width_available > 30 {
let mut doc_width = doc_width_available; let mut doc_width = doc_width_available;
@ -552,88 +539,3 @@ impl Component for Completion {
markdown_doc.render(doc_area, surface, cx); 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<CompletionItem>,
request: Option<helix_event::CancelTx>,
}
impl AsyncHook for ResolveHandler {
type Event = CompletionItem;
fn handle_event(
&mut self,
item: Self::Event,
timeout: Option<tokio::time::Instant>,
) -> Option<tokio::time::Instant> {
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::<crate::ui::EditorView>()
.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 => (),
}
});
}

@ -7,6 +7,7 @@ use helix_core::syntax::Highlight;
use helix_core::syntax::HighlightEvent; use helix_core::syntax::HighlightEvent;
use helix_core::text_annotations::TextAnnotations; use helix_core::text_annotations::TextAnnotations;
use helix_core::{visual_offset_from_block, Position, RopeSlice}; use helix_core::{visual_offset_from_block, Position, RopeSlice};
use helix_stdx::rope::RopeSliceExt;
use helix_view::editor::{WhitespaceConfig, WhitespaceRenderValue}; use helix_view::editor::{WhitespaceConfig, WhitespaceRenderValue};
use helix_view::graphics::Rect; use helix_view::graphics::Rect;
use helix_view::theme::Style; use helix_view::theme::Style;
@ -32,14 +33,27 @@ impl<F: FnMut(&mut TextRenderer, LinePos)> 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 /// A wrapper around a HighlightIterator
/// that merges the layered highlights to create the final text style /// that merges the layered highlights to create the final text style
/// and yields the active text style and the char_idx where the active /// and yields the active text style and the char_idx where the active
/// style will have to be recomputed. /// 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<Item = HighlightEvent>> { struct StyleIter<'a, H: Iterator<Item = HighlightEvent>> {
text_style: Style, text_style: Style,
active_highlights: Vec<Highlight>, active_highlights: Vec<Highlight>,
highlight_iter: H, highlight_iter: H,
kind: StyleIterKind,
text: RopeSlice<'a>,
theme: &'a Theme, theme: &'a Theme,
} }
@ -54,7 +68,7 @@ impl<H: Iterator<Item = HighlightEvent>> Iterator for StyleIter<'_, H> {
HighlightEvent::HighlightEnd => { HighlightEvent::HighlightEnd => {
self.active_highlights.pop(); self.active_highlights.pop();
} }
HighlightEvent::Source { start, end } => { HighlightEvent::Source { start, mut end } => {
if start == end { if start == end {
continue; continue;
} }
@ -64,6 +78,9 @@ impl<H: Iterator<Item = HighlightEvent>> Iterator for StyleIter<'_, H> {
.fold(self.text_style, |acc, span| { .fold(self.text_style, |acc, span| {
acc.patch(self.theme.highlight(span.0)) acc.patch(self.theme.highlight(span.0))
}); });
if self.kind == StyleIterKind::BaseHighlights {
end = self.text.byte_to_next_char(end);
}
return Some((style, end)); return Some((style, end));
} }
} }
@ -185,13 +202,17 @@ pub fn render_text<'t>(
text_style: renderer.text_style, text_style: renderer.text_style,
active_highlights: Vec::with_capacity(64), active_highlights: Vec::with_capacity(64),
highlight_iter: syntax_highlight_iter, highlight_iter: syntax_highlight_iter,
kind: StyleIterKind::BaseHighlights,
theme, theme,
text,
}; };
let mut overlay_styles = StyleIter { let mut overlay_styles = StyleIter {
text_style: Style::default(), text_style: Style::default(),
active_highlights: Vec::with_capacity(64), active_highlights: Vec::with_capacity(64),
highlight_iter: overlay_highlight_iter, highlight_iter: overlay_highlight_iter,
kind: StyleIterKind::Overlay,
theme, theme,
text,
}; };
let mut last_line_pos = LinePos { let mut last_line_pos = LinePos {
@ -341,6 +362,7 @@ pub struct TextRenderer<'a> {
pub indent_guide_style: Style, pub indent_guide_style: Style,
pub newline: String, pub newline: String,
pub nbsp: String, pub nbsp: String,
pub nnbsp: String,
pub space: String, pub space: String,
pub tab: String, pub tab: String,
pub virtual_tab: String, pub virtual_tab: String,
@ -395,6 +417,11 @@ impl<'a> TextRenderer<'a> {
} else { } else {
" ".to_owned() " ".to_owned()
}; };
let nnbsp = if ws_render.nnbsp() == WhitespaceRenderValue::All {
ws_chars.nnbsp.into()
} else {
" ".to_owned()
};
let text_style = theme.get("ui.text"); let text_style = theme.get("ui.text");
@ -405,6 +432,7 @@ impl<'a> TextRenderer<'a> {
indent_guide_char: editor_config.indent_guides.character.into(), indent_guide_char: editor_config.indent_guides.character.into(),
newline, newline,
nbsp, nbsp,
nnbsp,
space, space,
tab, tab,
virtual_tab, virtual_tab,
@ -448,6 +476,7 @@ impl<'a> TextRenderer<'a> {
let width = grapheme.width(); let width = grapheme.width();
let space = if is_virtual { " " } else { &self.space }; let space = if is_virtual { " " } else { &self.space };
let nbsp = if is_virtual { " " } else { &self.nbsp }; let nbsp = if is_virtual { " " } else { &self.nbsp };
let nnbsp = if is_virtual { " " } else { &self.nnbsp };
let tab = if is_virtual { let tab = if is_virtual {
&self.virtual_tab &self.virtual_tab
} else { } else {
@ -461,6 +490,7 @@ impl<'a> TextRenderer<'a> {
// TODO special rendering for other whitespaces? // TODO special rendering for other whitespaces?
Grapheme::Other { ref g } if g == " " => space, Grapheme::Other { ref g } if g == " " => space,
Grapheme::Other { ref g } if g == "\u{00A0}" => nbsp, Grapheme::Other { ref g } if g == "\u{00A0}" => nbsp,
Grapheme::Other { ref g } if g == "\u{202F}" => nnbsp,
Grapheme::Other { ref g } => g, Grapheme::Other { ref g } => g,
Grapheme::Newline => &self.newline, Grapheme::Newline => &self.newline,
}; };

@ -12,9 +12,7 @@ use crate::{
use helix_core::{ use helix_core::{
diagnostic::NumberOrString, diagnostic::NumberOrString,
graphemes::{ graphemes::{next_grapheme_boundary, prev_grapheme_boundary},
ensure_grapheme_boundary_next_byte, next_grapheme_boundary, prev_grapheme_boundary,
},
movement::Direction, movement::Direction,
syntax::{self, HighlightEvent}, syntax::{self, HighlightEvent},
text_annotations::TextAnnotations, text_annotations::TextAnnotations,
@ -315,26 +313,14 @@ impl EditorView {
let iter = syntax let iter = syntax
// TODO: range doesn't actually restrict source, just highlight range // TODO: range doesn't actually restrict source, just highlight range
.highlight_iter(text.slice(..), Some(range), None) .highlight_iter(text.slice(..), Some(range), None)
.map(|event| event.unwrap()) .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,
});
Box::new(iter) Box::new(iter)
} }
None => Box::new( None => Box::new(
[HighlightEvent::Source { [HighlightEvent::Source {
start: text.byte_to_char(range.start), start: range.start,
end: text.byte_to_char(range.end), end: range.end,
}] }]
.into_iter(), .into_iter(),
), ),
@ -350,7 +336,8 @@ impl EditorView {
let text = doc.text().slice(..); let text = doc.text().slice(..);
let row = text.char_to_line(anchor.min(text.len_chars())); 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) text_annotations.collect_overlay_highlights(range)
} }
@ -359,8 +346,8 @@ impl EditorView {
pub fn doc_diagnostics_highlights( pub fn doc_diagnostics_highlights(
doc: &Document, doc: &Document,
theme: &Theme, theme: &Theme,
) -> [Vec<(usize, std::ops::Range<usize>)>; 5] { ) -> [Vec<(usize, std::ops::Range<usize>)>; 7] {
use helix_core::diagnostic::{DiagnosticTag, Severity}; use helix_core::diagnostic::{DiagnosticTag, Range, Severity};
let get_scope_of = |scope| { let get_scope_of = |scope| {
theme theme
.find_scope_index_exact(scope) .find_scope_index_exact(scope)
@ -389,6 +376,25 @@ impl EditorView {
let mut hint_vec = Vec::new(); let mut hint_vec = Vec::new();
let mut warning_vec = Vec::new(); let mut warning_vec = Vec::new();
let mut error_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<usize>)>, 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() { for diagnostic in doc.diagnostics() {
// Separate diagnostics into different Vecs by severity. // Separate diagnostics into different Vecs by severity.
@ -400,31 +406,44 @@ impl EditorView {
_ => (&mut default_vec, r#default), _ => (&mut default_vec, r#default),
}; };
let scope = diagnostic // If the diagnostic has tags and a non-warning/error severity, skip rendering
.tags // the diagnostic as info/hint/default and only render it as unnecessary/deprecated
.first() // instead. For warning/error diagnostics, render both the severity highlight and
.and_then(|tag| match tag { // the tag highlight.
DiagnosticTag::Unnecessary => unnecessary, if diagnostic.tags.is_empty()
DiagnosticTag::Deprecated => deprecated, || matches!(
}) diagnostic.severity,
.unwrap_or(scope); Some(Severity::Warning | Severity::Error)
)
{
push_diagnostic(vec, scope, diagnostic.range);
}
// If any diagnostic overlaps ranges with the prior diagnostic, for tag in &diagnostic.tags {
// merge the two together. Otherwise push a new span. match tag {
match vec.last_mut() { DiagnosticTag::Unnecessary => {
Some((_, range)) if diagnostic.range.start <= range.end => { if let Some(scope) = unnecessary {
// This branch merges overlapping diagnostics, assuming that the current push_diagnostic(&mut unnecessary_vec, scope, diagnostic.range)
// 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`. DiagnosticTag::Deprecated => {
debug_assert!(range.start <= diagnostic.range.start); if let Some(scope) = deprecated {
range.end = diagnostic.range.end.max(range.end) 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. /// Get highlight spans for selections in a document view.
@ -1015,7 +1034,6 @@ impl EditorView {
self.last_insert.1.push(InsertEvent::TriggerCompletion); self.last_insert.1.push(InsertEvent::TriggerCompletion);
// TODO : propagate required size on resize to completion too // TODO : propagate required size on resize to completion too
completion.required_size((size.width, size.height));
self.completion = Some(completion); self.completion = Some(completion);
Some(area) Some(area)
} }
@ -1048,13 +1066,33 @@ impl EditorView {
} }
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( fn handle_mouse_event(
&mut self, &mut self,
event: &MouseEvent, event: &MouseEvent,
cxt: &mut commands::Context, cxt: &mut commands::Context,
) -> EventResult { ) -> EventResult {
if event.kind != MouseEventKind::Moved { if event.kind != MouseEventKind::Moved {
cxt.editor.reset_idle_timer(); self.handle_non_key_input(cxt)
} }
let config = cxt.editor.config(); let config = cxt.editor.config();
@ -1211,24 +1249,28 @@ impl EditorView {
} }
MouseEventKind::Up(MouseButton::Right) => { 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); cxt.editor.focus(view_id);
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); 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) if let Some(pos) = view.pos_at_visual_coords(doc, pos.row as u16, 0, true) {
{
doc.set_selection(view_id, Selection::point(pos)); doc.set_selection(view_id, Selection::point(pos));
if modifiers == KeyModifiers::ALT { match modifiers {
commands::MappableCommand::dap_edit_log.execute(cxt); KeyModifiers::ALT => {
} else { commands::MappableCommand::dap_edit_log.execute(cxt)
commands::MappableCommand::dap_edit_condition.execute(cxt);
} }
_ => commands::MappableCommand::dap_edit_condition.execute(cxt),
return EventResult::Consumed(None); };
} }
} }
cxt.editor.ensure_cursor_in_view(view_id);
return EventResult::Consumed(None);
}
EventResult::Ignored(None) EventResult::Ignored(None)
} }
@ -1279,6 +1321,7 @@ impl Component for EditorView {
match event { match event {
Event::Paste(contents) => { Event::Paste(contents) => {
self.handle_non_key_input(&mut cx);
cx.count = cx.editor.count; cx.count = cx.editor.count;
commands::paste_bracketed_value(&mut cx, contents.clone()); commands::paste_bracketed_value(&mut cx, contents.clone());
cx.editor.count = None; cx.editor.count = None;

@ -3,60 +3,95 @@ use std::sync::Arc;
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use helix_core::syntax; use helix_core::syntax;
use helix_view::graphics::{Margin, Rect, Style}; use helix_view::graphics::{Margin, Rect, Style};
use helix_view::input::Event;
use tui::buffer::Buffer; use tui::buffer::Buffer;
use tui::layout::Alignment;
use tui::text::Text;
use tui::widgets::{BorderType, Paragraph, Widget, Wrap}; 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 crate::ui::Markdown;
use super::Popup; use super::Popup;
pub struct SignatureHelp { pub struct Signature {
signature: String, pub signature: String,
signature_doc: Option<String>, pub signature_doc: Option<String>,
/// Part of signature text /// Part of signature text
active_param_range: Option<(usize, usize)>, pub active_param_range: Option<(usize, usize)>,
}
pub struct SignatureHelp {
language: String, language: String,
config_loader: Arc<ArcSwap<syntax::Loader>>, config_loader: Arc<ArcSwap<syntax::Loader>>,
active_signature: usize,
signatures: Vec<Signature>,
} }
impl SignatureHelp { impl SignatureHelp {
pub const ID: &'static str = "signature-help"; pub const ID: &'static str = "signature-help";
pub fn new( pub fn new(
signature: String,
language: String, language: String,
config_loader: Arc<ArcSwap<syntax::Loader>>, config_loader: Arc<ArcSwap<syntax::Loader>>,
active_signature: usize,
signatures: Vec<Signature>,
) -> Self { ) -> Self {
Self { Self {
signature,
signature_doc: None,
active_param_range: None,
language, language,
config_loader, config_loader,
active_signature,
signatures,
} }
} }
pub fn set_signature_doc(&mut self, signature_doc: Option<String>) { pub fn active_signature(&self) -> usize {
self.signature_doc = signature_doc; self.active_signature
}
pub fn set_active_param_range(&mut self, offset: Option<(usize, usize)>) {
self.active_param_range = offset;
} }
pub fn visible_popup(compositor: &mut Compositor) -> Option<&mut Popup<Self>> { pub fn visible_popup(compositor: &mut Compositor) -> Option<&mut Popup<Self>> {
compositor.find_id::<Popup<Self>>(Self::ID) compositor.find_id::<Popup<Self>>(Self::ID)
} }
fn signature_index(&self) -> String {
format!("({}/{})", self.active_signature + 1, self.signatures.len())
}
} }
impl Component for SignatureHelp { 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) { fn render(&mut self, area: Rect, surface: &mut Buffer, cx: &mut Context) {
let margin = Margin::horizontal(1); 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![( vec![(
cx.editor cx.editor
.theme .theme
@ -66,21 +101,29 @@ impl Component for SignatureHelp {
)] )]
}); });
let sig = &self.signatures[self.active_signature];
let sig_text = crate::ui::markdown::highlighted_code_block( let sig_text = crate::ui::markdown::highlighted_code_block(
&self.signature, sig.signature.as_str(),
&self.language, &self.language,
Some(&cx.editor.theme), Some(&cx.editor.theme),
Arc::clone(&self.config_loader), Arc::clone(&self.config_loader),
active_param_span, 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_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 = 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 }); let sig_text_para = Paragraph::new(&sig_text).wrap(Wrap { trim: false });
sig_text_para.render(sig_text_area, surface); sig_text_para.render(sig_text_area, surface);
if self.signature_doc.is_none() { if sig.signature_doc.is_none() {
return; return;
} }
@ -92,7 +135,7 @@ impl Component for SignatureHelp {
} }
} }
let sig_doc = match &self.signature_doc { let sig_doc = match &sig.signature_doc {
None => return, None => return,
Some(doc) => Markdown::new(doc.clone(), Arc::clone(&self.config_loader)), Some(doc) => Markdown::new(doc.clone(), Arc::clone(&self.config_loader)),
}; };
@ -110,13 +153,12 @@ impl Component for SignatureHelp {
const PADDING: u16 = 2; const PADDING: u16 = 2;
const SEPARATOR_HEIGHT: u16 = 1; const SEPARATOR_HEIGHT: u16 = 1;
if PADDING >= viewport.1 || PADDING >= viewport.0 { let sig = &self.signatures[self.active_signature];
return None;
} let max_text_width = viewport.0.saturating_sub(PADDING).clamp(10, 120);
let max_text_width = (viewport.0 - PADDING).min(120);
let signature_text = crate::ui::markdown::highlighted_code_block( let signature_text = crate::ui::markdown::highlighted_code_block(
&self.signature, sig.signature.as_str(),
&self.language, &self.language,
None, None,
Arc::clone(&self.config_loader), Arc::clone(&self.config_loader),
@ -125,7 +167,7 @@ impl Component for SignatureHelp {
let (sig_width, sig_height) = let (sig_width, sig_height) =
crate::ui::text::required_size(&signature_text, max_text_width); 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) => { Some(ref doc) => {
let doc_md = Markdown::new(doc.clone(), Arc::clone(&self.config_loader)); let doc_md = Markdown::new(doc.clone(), Arc::clone(&self.config_loader));
let doc_text = doc_md.parse(None); let doc_text = doc_md.parse(None);
@ -139,6 +181,12 @@ impl Component for SignatureHelp {
None => (sig_width, sig_height), 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))
} }
} }

@ -7,18 +7,11 @@ use crate::{
use helix_core::fuzzy::MATCHER; use helix_core::fuzzy::MATCHER;
use nucleo::pattern::{Atom, AtomKind, CaseMatching}; use nucleo::pattern::{Atom, AtomKind, CaseMatching};
use nucleo::{Config, Utf32Str}; use nucleo::{Config, Utf32Str};
use tui::{ use tui::{buffer::Buffer as Surface, widgets::Table};
buffer::Buffer as Surface,
widgets::{Block, Borders, Table, Widget},
};
pub use tui::widgets::{Cell, Row}; pub use tui::widgets::{Cell, Row};
use helix_view::{ use helix_view::{editor::SmartTabConfig, graphics::Rect, Editor};
editor::SmartTabConfig,
graphics::{Margin, Rect},
Editor,
};
use tui::layout::Constraint; use tui::layout::Constraint;
pub trait Item: Sync + Send + 'static { pub trait Item: Sync + Send + 'static {
@ -241,9 +234,9 @@ impl<T: Item> Menu<T> {
} }
impl<T: Item + PartialEq> Menu<T> { impl<T: Item + PartialEq> Menu<T> {
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 { for option in &mut self.options {
if old_option == *option { if old_option == option {
*option = new_option; *option = new_option;
break; break;
} }
@ -341,16 +334,8 @@ impl<T: Item + 'static> Component for Menu<T> {
.try_get("ui.menu") .try_get("ui.menu")
.unwrap_or_else(|| theme.get("ui.text")); .unwrap_or_else(|| theme.get("ui.text"));
let selected = theme.get("ui.menu.selected"); let selected = theme.get("ui.menu.selected");
surface.clear_with(area, style);
let render_borders = cx.editor.menu_border();
let area = if render_borders { surface.clear_with(area, style);
Widget::render(Block::default().borders(Borders::ALL), area, surface);
area.inner(&Margin::vertical(1))
} else {
area
};
let scroll = self.scroll; let scroll = self.scroll;

@ -13,7 +13,7 @@ mod spinner;
mod statusline; mod statusline;
mod text; mod text;
use crate::compositor::{Component, Compositor}; use crate::compositor::Compositor;
use crate::filter_picker_entry; use crate::filter_picker_entry;
use crate::job::{self, Callback}; use crate::job::{self, Callback};
pub use completion::{Completion, CompletionItem}; pub use completion::{Completion, CompletionItem};
@ -143,14 +143,12 @@ pub fn raw_regex_prompt(
move |_editor: &mut Editor, compositor: &mut Compositor| { move |_editor: &mut Editor, compositor: &mut Compositor| {
let contents = Text::new(format!("{}", err)); let contents = Text::new(format!("{}", err));
let size = compositor.size(); 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( .position(Some(helix_core::Position::new(
size.height as usize - 2, // 2 = statusline + commandline size.height as usize - 2, // 2 = statusline + commandline
0, 0,
))) )))
.auto_close(true); .auto_close(true);
popup.required_size((size.width, size.height));
compositor.replace_or_push("invalid-regex", popup); compositor.replace_or_push("invalid-regex", popup);
}, },
)); ));

@ -11,20 +11,30 @@ use tui::{
use helix_core::Position; use helix_core::Position;
use helix_view::{ use helix_view::{
graphics::{Margin, Rect}, graphics::{Margin, Rect},
input::{MouseEvent, MouseEventKind},
Editor, 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 // TODO: share logic with Menu, it's essentially Popup(render_fn), but render fn needs to return
// a width/height hint. maybe Popup(Box<Component>) // a width/height hint. maybe Popup(Box<Component>)
pub struct Popup<T: Component> { pub struct Popup<T: Component> {
contents: T, contents: T,
position: Option<Position>, position: Option<Position>,
margin: Margin, area: Rect,
size: (u16, u16),
child_size: (u16, u16),
position_bias: Open, position_bias: Open,
scroll: usize, scroll_half_pages: usize,
auto_close: bool, auto_close: bool,
ignore_escape_key: bool, ignore_escape_key: bool,
id: &'static str, id: &'static str,
@ -36,11 +46,9 @@ impl<T: Component> Popup<T> {
Self { Self {
contents, contents,
position: None, position: None,
margin: Margin::none(),
size: (0, 0),
position_bias: Open::Below, position_bias: Open::Below,
child_size: (0, 0), area: Rect::new(0, 0, 0, 0),
scroll: 0, scroll_half_pages: 0,
auto_close: false, auto_close: false,
ignore_escape_key: false, ignore_escape_key: false,
id, id,
@ -70,11 +78,6 @@ impl<T: Component> Popup<T> {
self self
} }
pub fn margin(mut self, margin: Margin) -> Self {
self.margin = margin;
self
}
pub fn auto_close(mut self, auto_close: bool) -> Self { pub fn auto_close(mut self, auto_close: bool) -> Self {
self.auto_close = auto_close; self.auto_close = auto_close;
self self
@ -92,28 +95,65 @@ impl<T: Component> Popup<T> {
self self
} }
/// Calculate the position where the popup should be rendered and return the coordinates of the pub fn scroll_half_page_down(&mut self) {
/// top left corner. self.scroll_half_pages += 1;
pub fn get_rel_position(&mut self, viewport: Rect, editor: &Editor) -> (u16, u16) { }
let position = self
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 .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 let mut render_borders = if is_menu {
// if we're on the top part of the screen, do below editor.menu_border()
// if we're on the bottom part, do above } else {
editor.popup_border()
};
// -- make sure frame doesn't stick out of bounds // -- make sure frame doesn't stick out of bounds
let mut rel_x = position.col as u16; let mut rel_x = position.col as u16;
let mut rel_y = position.row 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; // if there's a orientation preference, use that
let can_put_above = rel_y.checked_sub(height).is_some(); // 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 { let final_pos = match self.position_bias {
Open::Below => match can_put_below { Open::Below => match can_put_below {
true => Open::Below, true => Open::Below,
@ -125,51 +165,87 @@ impl<T: Component> Popup<T> {
}, },
}; };
rel_y = match final_pos { // compute maximum space available for child
Open::Above => rel_y.saturating_sub(height), let mut max_height = match final_pos {
Open::Below => rel_y + 1, Open::Above => rel_y,
Open::Below => viewport.height.saturating_sub(1 + rel_y),
}; };
max_height = max_height.min(MAX_HEIGHT);
(rel_x, rel_y) 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;
} }
pub fn get_size(&self) -> (u16, u16) { // compute required child size and reclamp
(self.size.0, self.size.1) 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) { width = width.min(MAX_WIDTH);
if direction { let height = if render_borders {
let max_offset = self.child_size.1.saturating_sub(self.size.1); (child_height + 2).min(MAX_HEIGHT)
self.scroll = (self.scroll + offset).min(max_offset as usize);
} else { } 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. let area = match final_pos {
/// Consider disabling the scrollbar in case the child Open::Above => {
/// already has its own. rel_y = rel_y.saturating_sub(height);
pub fn with_scrollbar(mut self, enable_scrollbar: bool) -> Self { Rect::new(rel_x, rel_y, width, position.row as u16 - rel_y)
self.has_scrollbar = enable_scrollbar;
self
} }
Open::Below => {
pub fn contents(&self) -> &T { rel_y += 1;
&self.contents let y_max = viewport.bottom().min(height + rel_y);
Rect::new(rel_x, rel_y, width, y_max - rel_y)
} }
};
pub fn contents_mut(&mut self) -> &mut T { RenderInfo {
&mut self.contents area,
child_height,
render_borders,
is_menu,
}
}
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);
} }
pub fn area(&mut self, viewport: Rect, editor: &Editor) -> Rect { match kind {
// trigger required_size so we recalculate if the child changed MouseEventKind::ScrollDown if self.has_scrollbar => {
self.required_size((viewport.width, viewport.height)); self.scroll_half_page_down();
EventResult::Consumed(None)
let (rel_x, rel_y) = self.get_rel_position(viewport, editor); }
MouseEventKind::ScrollUp if self.has_scrollbar => {
// clip to viewport self.scroll_half_page_up();
viewport.intersection(Rect::new(rel_x, rel_y, self.size.0, self.size.1)) EventResult::Consumed(None)
}
_ => EventResult::Ignored(None),
}
} }
} }
@ -177,6 +253,7 @@ impl<T: Component> Component for Popup<T> {
fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult { fn handle_event(&mut self, event: &Event, cx: &mut Context) -> EventResult {
let key = match event { let key = match event {
Event::Key(event) => *event, Event::Key(event) => *event,
Event::Mouse(event) => return self.handle_mouse_event(event),
Event::Resize(_, _) => { Event::Resize(_, _) => {
// TODO: calculate inner area, call component's handle_event with that area // TODO: calculate inner area, call component's handle_event with that area
return EventResult::Ignored(None); return EventResult::Ignored(None);
@ -200,11 +277,11 @@ impl<T: Component> Component for Popup<T> {
EventResult::Consumed(Some(close_fn)) EventResult::Consumed(Some(close_fn))
} }
ctrl!('d') => { ctrl!('d') => {
self.scroll(self.size.1 as usize / 2, true); self.scroll_half_page_down();
EventResult::Consumed(None) EventResult::Consumed(None)
} }
ctrl!('u') => { ctrl!('u') => {
self.scroll(self.size.1 as usize / 2, false); self.scroll_half_page_up();
EventResult::Consumed(None) EventResult::Consumed(None)
} }
_ => { _ => {
@ -223,63 +300,48 @@ impl<T: Component> Component for Popup<T> {
// tab/enter/ctrl-k or whatever will confirm the selection/ ctrl-n/ctrl-p for scroll. // 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) { fn render(&mut self, viewport: Rect, surface: &mut Surface, cx: &mut Context) {
let area = self.area(viewport, cx.editor); let RenderInfo {
cx.scroll = Some(self.scroll); area,
child_height,
render_borders,
is_menu,
} = self.render_info(viewport, cx.editor);
self.area = area;
// clear area // clear area
let background = cx.editor.theme.get("ui.popup"); let background = if is_menu {
surface.clear_with(area, background); // TODO: consistently style menu
cx.editor
let render_borders = cx.editor.popup_border(); .theme
.try_get("ui.menu")
let inner = if self .unwrap_or_else(|| cx.editor.theme.get("ui.text"))
.contents
.type_name()
.starts_with("helix_term::ui::menu::Menu")
{
area
} else { } 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 { if render_borders {
inner = area.inner(&Margin::all(1));
Widget::render(Block::default().borders(Borders::ALL), area, surface); Widget::render(Block::default().borders(Borders::ALL), 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); self.contents.render(inner, surface, cx);
// render scrollbar if contents do not fit // render scrollbar if contents do not fit
if self.has_scrollbar { if self.has_scrollbar {
let win_height = (inner.height as usize).saturating_sub(2 * border); let win_height = inner.height as usize;
let len = (self.child_size.1 as usize).saturating_sub(2 * border); let len = child_height as usize;
let fits = len <= win_height; let fits = len <= win_height;
let scroll = self.scroll;
let scroll_style = cx.editor.theme.get("ui.menu.scroll"); let scroll_style = cx.editor.theme.get("ui.menu.scroll");
const fn div_ceil(a: usize, b: usize) -> usize { const fn div_ceil(a: usize, b: usize) -> usize {
@ -293,7 +355,8 @@ impl<T: Component> Component for Popup<T> {
let mut cell; let mut cell;
for i in 0..win_height { 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 { "▐" }; let half_block = if render_borders { "▌" } else { "▐" };

@ -544,10 +544,6 @@ impl Component for Prompt {
(self.callback_fn)(cx, &self.line, PromptEvent::Update); (self.callback_fn)(cx, &self.line, PromptEvent::Update);
} }
ctrl!('h') | key!(Backspace) | shift!(Backspace) => { ctrl!('h') | key!(Backspace) | shift!(Backspace) => {
if self.line.is_empty() {
(self.callback_fn)(cx, &self.line, PromptEvent::Abort);
return close_fn;
}
self.delete_char_backwards(cx.editor); self.delete_char_backwards(cx.editor);
(self.callback_fn)(cx, &self.line, PromptEvent::Update); (self.callback_fn)(cx, &self.line, PromptEvent::Update);
} }

@ -1,16 +1,18 @@
use std::{collections::HashMap, time::Instant}; use std::{collections::HashMap, time::Instant};
use helix_lsp::LanguageServerId;
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct ProgressSpinners { pub struct ProgressSpinners {
inner: HashMap<usize, Spinner>, inner: HashMap<LanguageServerId, Spinner>,
} }
impl ProgressSpinners { impl ProgressSpinners {
pub fn get(&self, id: usize) -> Option<&Spinner> { pub fn get(&self, id: LanguageServerId) -> Option<&Spinner> {
self.inner.get(&id) 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() self.inner.entry(id).or_default()
} }
} }

@ -173,7 +173,7 @@ fn render_mode<'a>(context: &RenderContext) -> Spans<'a> {
" ".into() " ".into()
}; };
let modename = format!(" {} ", modename); let modename = format!(" {} ", modename);
if config.color_modes { if visible && config.color_modes {
Span::styled( Span::styled(
modename, modename,
match context.editor.mode() { match context.editor.mode() {

@ -6,13 +6,13 @@ async fn auto_indent_c() -> anyhow::Result<()> {
AppBuilder::new().with_file("foo.c", None), AppBuilder::new().with_file("foo.c", None),
// switches to append mode? // switches to append mode?
( (
helpers::platform_line("void foo() {#[|}]#"), "void foo() {#[|}]#",
"i<ret><esc>", "i<ret><esc>",
helpers::platform_line(indoc! {"\ indoc! {"\
void foo() { void foo() {
#[|\n]#\ #[|\n]#\
} }
"}), "},
), ),
) )
.await?; .await?;

@ -19,6 +19,7 @@ async fn insert_basic() -> anyhow::Result<()> {
format!("#[{}|]#", LINE_END), format!("#[{}|]#", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("{}#[|{}]#{}", pair.0, pair.1, LINE_END), format!("{}#[|{}]#{}", pair.0, pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -46,6 +47,7 @@ async fn insert_configured_multi_byte_chars() -> anyhow::Result<()> {
format!("#[{}|]#", LINE_END), format!("#[{}|]#", LINE_END),
format!("i{}", open), format!("i{}", open),
format!("{}#[|{}]#{}", open, close, LINE_END), format!("{}#[|{}]#{}", open, close, LINE_END),
LineFeedHandling::AsIs,
), ),
) )
.await?; .await?;
@ -56,6 +58,7 @@ async fn insert_configured_multi_byte_chars() -> anyhow::Result<()> {
format!("{}#[{}|]#{}", open, close, LINE_END), format!("{}#[{}|]#{}", open, close, LINE_END),
format!("i{}", close), format!("i{}", close),
format!("{}{}#[|{}]#", open, close, LINE_END), format!("{}{}#[|{}]#", open, close, LINE_END),
LineFeedHandling::AsIs,
), ),
) )
.await?; .await?;
@ -71,6 +74,7 @@ async fn insert_after_word() -> anyhow::Result<()> {
format!("foo#[{}|]#", LINE_END), format!("foo#[{}|]#", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("foo{}#[|{}]#{}", pair.0, pair.1, LINE_END), format!("foo{}#[|{}]#{}", pair.0, pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -80,6 +84,7 @@ async fn insert_after_word() -> anyhow::Result<()> {
format!("foo#[{}|]#", LINE_END), format!("foo#[{}|]#", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("foo{}#[|{}]#", pair.0, LINE_END), format!("foo{}#[|{}]#", pair.0, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -94,6 +99,7 @@ async fn insert_before_word() -> anyhow::Result<()> {
format!("#[f|]#oo{}", LINE_END), format!("#[f|]#oo{}", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("{}#[|f]#oo{}", pair.0, LINE_END), format!("{}#[|f]#oo{}", pair.0, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -108,6 +114,7 @@ async fn insert_before_word_selection() -> anyhow::Result<()> {
format!("#[foo|]#{}", LINE_END), format!("#[foo|]#{}", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("{}#[|foo]#{}", pair.0, LINE_END), format!("{}#[|foo]#{}", pair.0, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -122,6 +129,7 @@ async fn insert_before_word_selection_trailing_word() -> anyhow::Result<()> {
format!("foo#[ wor|]#{}", LINE_END), format!("foo#[ wor|]#{}", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("foo{}#[|{} wor]#{}", pair.0, pair.1, LINE_END), format!("foo{}#[|{} wor]#{}", pair.0, pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -136,6 +144,7 @@ async fn insert_closer_selection_trailing_word() -> anyhow::Result<()> {
format!("foo{}#[|{} wor]#{}", pair.0, pair.1, LINE_END), format!("foo{}#[|{} wor]#{}", pair.0, pair.1, LINE_END),
format!("i{}", pair.1), format!("i{}", pair.1),
format!("foo{}{}#[| wor]#{}", pair.0, pair.1, LINE_END), format!("foo{}{}#[| wor]#{}", pair.0, pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -155,6 +164,7 @@ async fn insert_before_eol() -> anyhow::Result<()> {
open = pair.0, open = pair.0,
close = pair.1 close = pair.1
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -177,6 +187,7 @@ async fn insert_auto_pairs_disabled() -> anyhow::Result<()> {
format!("#[{}|]#", LINE_END), format!("#[{}|]#", LINE_END),
format!("i{}", pair.0), format!("i{}", pair.0),
format!("{}#[|{}]#", pair.0, LINE_END), format!("{}#[|{}]#", pair.0, LINE_END),
LineFeedHandling::AsIs,
), ),
) )
.await?; .await?;
@ -197,6 +208,7 @@ async fn insert_multi_range() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -211,6 +223,7 @@ async fn insert_before_multi_code_point_graphemes() -> anyhow::Result<()> {
format!("hello #[👨‍👩‍👧‍👦|]# goodbye{}", LINE_END), format!("hello #[👨‍👩‍👧‍👦|]# goodbye{}", LINE_END),
format!("i{}", pair.1), format!("i{}", pair.1),
format!("hello {}#[|👨‍👩‍👧‍👦]# goodbye{}", pair.1, LINE_END), format!("hello {}#[|👨‍👩‍👧‍👦]# goodbye{}", pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -226,6 +239,7 @@ async fn insert_at_end_of_document() -> anyhow::Result<()> {
in_keys: format!("i{}", pair.0), in_keys: format!("i{}", pair.0),
out_text: format!("{}{}{}", LINE_END, pair.0, pair.1), out_text: format!("{}{}{}", LINE_END, pair.0, pair.1),
out_selection: Selection::single(LINE_END.len() + 1, LINE_END.len() + 2), out_selection: Selection::single(LINE_END.len() + 1, LINE_END.len() + 2),
line_feed_handling: LineFeedHandling::AsIs,
}) })
.await?; .await?;
@ -235,6 +249,7 @@ async fn insert_at_end_of_document() -> anyhow::Result<()> {
in_keys: format!("i{}", pair.0), in_keys: format!("i{}", pair.0),
out_text: format!("foo{}{}{}", LINE_END, pair.0, pair.1), out_text: format!("foo{}{}{}", LINE_END, pair.0, pair.1),
out_selection: Selection::single(LINE_END.len() + 4, LINE_END.len() + 5), out_selection: Selection::single(LINE_END.len() + 4, LINE_END.len() + 5),
line_feed_handling: LineFeedHandling::AsIs,
}) })
.await?; .await?;
} }
@ -259,6 +274,7 @@ async fn insert_close_inside_pair() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -283,6 +299,7 @@ async fn insert_close_inside_pair_multi() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -307,6 +324,7 @@ async fn insert_nested_open_inside_pair() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -338,6 +356,7 @@ async fn insert_nested_open_inside_pair_multi() -> anyhow::Result<()> {
inner_close = inner_pair.1, inner_close = inner_pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -358,6 +377,7 @@ async fn append_basic() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -377,6 +397,7 @@ async fn append_multi_range() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -401,6 +422,7 @@ async fn append_close_inside_pair() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -425,6 +447,7 @@ async fn append_close_inside_pair_multi() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -444,6 +467,7 @@ async fn append_end_of_word() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -458,6 +482,7 @@ async fn append_middle_of_word() -> anyhow::Result<()> {
format!("#[wo|]#rd{}", LINE_END), format!("#[wo|]#rd{}", LINE_END),
format!("a{}", pair.1), format!("a{}", pair.1),
format!("#[wo{}r|]#d{}", pair.1, LINE_END), format!("#[wo{}r|]#d{}", pair.1, LINE_END),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -477,6 +502,7 @@ async fn append_end_of_word_multi() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -501,6 +527,7 @@ async fn append_inside_nested_pair() -> anyhow::Result<()> {
close = pair.1, close = pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }
@ -532,6 +559,7 @@ async fn append_inside_nested_pair_multi() -> anyhow::Result<()> {
inner_close = inner_pair.1, inner_close = inner_pair.1,
eol = LINE_END eol = LINE_END
), ),
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
} }

@ -9,89 +9,89 @@ mod write;
async fn test_selection_duplication() -> anyhow::Result<()> { async fn test_selection_duplication() -> anyhow::Result<()> {
// Forward // Forward
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[lo|]#rem #[lo|]#rem
ipsum ipsum
dolor dolor
"}), "},
"CC", "CC",
platform_line(indoc! {"\ indoc! {"\
#(lo|)#rem #(lo|)#rem
#(ip|)#sum #(ip|)#sum
#[do|]#lor #[do|]#lor
"}), "},
)) ))
.await?; .await?;
// Backward // Backward
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[|lo]#rem #[|lo]#rem
ipsum ipsum
dolor dolor
"}), "},
"CC", "CC",
platform_line(indoc! {"\ indoc! {"\
#(|lo)#rem #(|lo)#rem
#(|ip)#sum #(|ip)#sum
#[|do]#lor #[|do]#lor
"}), "},
)) ))
.await?; .await?;
// Copy the selection to previous line, skipping the first line in the file // Copy the selection to previous line, skipping the first line in the file
test(( test((
platform_line(indoc! {"\ indoc! {"\
test test
#[testitem|]# #[testitem|]#
"}), "},
"<A-C>", "<A-C>",
platform_line(indoc! {"\ indoc! {"\
test test
#[testitem|]# #[testitem|]#
"}), "},
)) ))
.await?; .await?;
// Copy the selection to previous line, including the first line in the file // Copy the selection to previous line, including the first line in the file
test(( test((
platform_line(indoc! {"\ indoc! {"\
test test
#[test|]# #[test|]#
"}), "},
"<A-C>", "<A-C>",
platform_line(indoc! {"\ indoc! {"\
#[test|]# #[test|]#
#(test|)# #(test|)#
"}), "},
)) ))
.await?; .await?;
// Copy the selection to next line, skipping the last line in the file // Copy the selection to next line, skipping the last line in the file
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[testitem|]# #[testitem|]#
test test
"}), "},
"C", "C",
platform_line(indoc! {"\ indoc! {"\
#[testitem|]# #[testitem|]#
test test
"}), "},
)) ))
.await?; .await?;
// Copy the selection to next line, including the last line in the file // Copy the selection to next line, including the last line in the file
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[test|]# #[test|]#
test test
"}), "},
"C", "C",
platform_line(indoc! {"\ indoc! {"\
#(test|)# #(test|)#
#[test|]# #[test|]#
"}), "},
)) ))
.await?; .await?;
Ok(()) Ok(())
@ -153,23 +153,45 @@ async fn test_goto_file_impl() -> anyhow::Result<()> {
) )
.await?; .await?;
// ';' is behind the path
test_key_sequence(
&mut AppBuilder::new().with_file(file.path(), None).build()?,
Some("iimport 'one.js';<esc>B;gf"),
Some(&|app| {
assert_eq!(1, match_paths(app, vec!["one.js"]));
}),
false,
)
.await?;
// allow numeric values in path
test_key_sequence(
&mut AppBuilder::new().with_file(file.path(), None).build()?,
Some("iimport 'one123.js'<esc>B;gf"),
Some(&|app| {
assert_eq!(1, match_paths(app, vec!["one123.js"]));
}),
false,
)
.await?;
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_multi_selection_paste() -> anyhow::Result<()> { async fn test_multi_selection_paste() -> anyhow::Result<()> {
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[|lorem]# #[|lorem]#
#(|ipsum)# #(|ipsum)#
#(|dolor)# #(|dolor)#
"}), "},
"yp", "yp",
platform_line(indoc! {"\ indoc! {"\
lorem#[|lorem]# lorem#[|lorem]#
ipsum#(|ipsum)# ipsum#(|ipsum)#
dolor#(|dolor)# dolor#(|dolor)#
"}), "},
)) ))
.await?; .await?;
@ -180,58 +202,58 @@ async fn test_multi_selection_paste() -> anyhow::Result<()> {
async fn test_multi_selection_shell_commands() -> anyhow::Result<()> { async fn test_multi_selection_shell_commands() -> anyhow::Result<()> {
// pipe // pipe
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[|lorem]# #[|lorem]#
#(|ipsum)# #(|ipsum)#
#(|dolor)# #(|dolor)#
"}), "},
"|echo foo<ret>", "|echo foo<ret>",
platform_line(indoc! {"\ indoc! {"\
#[|foo\n]# #[|foo\n]#
#(|foo\n)# #(|foo\n)#
#(|foo\n)# #(|foo\n)#
"}), "},
)) ))
.await?; .await?;
// insert-output // insert-output
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[|lorem]# #[|lorem]#
#(|ipsum)# #(|ipsum)#
#(|dolor)# #(|dolor)#
"}), "},
"!echo foo<ret>", "!echo foo<ret>",
platform_line(indoc! {"\ indoc! {"\
#[|foo\n]# #[|foo\n]#
lorem lorem
#(|foo\n)# #(|foo\n)#
ipsum ipsum
#(|foo\n)# #(|foo\n)#
dolor dolor
"}), "},
)) ))
.await?; .await?;
// append-output // append-output
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[|lorem]# #[|lorem]#
#(|ipsum)# #(|ipsum)#
#(|dolor)# #(|dolor)#
"}), "},
"<A-!>echo foo<ret>", "<A-!>echo foo<ret>",
platform_line(indoc! {"\ indoc! {"\
lorem#[|foo\n]# lorem#[|foo\n]#
ipsum#(|foo\n)# ipsum#(|foo\n)#
dolor#(|foo\n)# dolor#(|foo\n)#
"}), "},
)) ))
.await?; .await?;
@ -247,7 +269,13 @@ async fn test_undo_redo() -> anyhow::Result<()> {
// * u Undo the two newlines. We're now on line 1. // * u Undo the two newlines. We're now on line 1.
// * <C-o><C-i> Jump forward an back again in the jumplist. This would panic // * <C-o><C-i> Jump forward an back again in the jumplist. This would panic
// if the jumplist were not being updated correctly. // if the jumplist were not being updated correctly.
test(("#[|]#", "2[<space><C-s>u<C-o><C-i>", "#[|]#")).await?; test((
"#[|]#",
"2[<space><C-s>u<C-o><C-i>",
"#[|]#",
LineFeedHandling::AsIs,
))
.await?;
// A jumplist selection is passed through an edit and then an undo and then a redo. // A jumplist selection is passed through an edit and then an undo and then a redo.
// //
@ -258,10 +286,22 @@ async fn test_undo_redo() -> anyhow::Result<()> {
// * <C-o> Jump back in the jumplist. This would panic if the jumplist were not being // * <C-o> Jump back in the jumplist. This would panic if the jumplist were not being
// updated correctly. // updated correctly.
// * <C-i> Jump forward to line 1. // * <C-i> Jump forward to line 1.
test(("#[|]#", "[<space><C-s>kduU<C-o><C-i>", "#[|]#")).await?; test((
"#[|]#",
"[<space><C-s>kduU<C-o><C-i>",
"#[|]#",
LineFeedHandling::AsIs,
))
.await?;
// In this case we 'redo' manually to ensure that the transactions are composing correctly. // In this case we 'redo' manually to ensure that the transactions are composing correctly.
test(("#[|]#", "[<space>u[<space>u", "#[|]#")).await?; test((
"#[|]#",
"[<space>u[<space>u",
"#[|]#",
LineFeedHandling::AsIs,
))
.await?;
Ok(()) Ok(())
} }
@ -270,35 +310,35 @@ async fn test_undo_redo() -> anyhow::Result<()> {
async fn test_extend_line() -> anyhow::Result<()> { async fn test_extend_line() -> anyhow::Result<()> {
// extend with line selected then count // extend with line selected then count
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[l|]#orem #[l|]#orem
ipsum ipsum
dolor dolor
"}), "},
"x2x", "x2x",
platform_line(indoc! {"\ indoc! {"\
#[lorem #[lorem
ipsum ipsum
dolor\n|]# dolor\n|]#
"}), "},
)) ))
.await?; .await?;
// extend with count on partial selection // extend with count on partial selection
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[l|]#orem #[l|]#orem
ipsum ipsum
"}), "},
"2x", "2x",
platform_line(indoc! {"\ indoc! {"\
#[lorem #[lorem
ipsum\n|]# ipsum\n|]#
"}), "},
)) ))
.await?; .await?;
@ -366,16 +406,11 @@ async fn test_character_info() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_delete_char_backward() -> anyhow::Result<()> { async fn test_delete_char_backward() -> anyhow::Result<()> {
// don't panic when deleting overlapping ranges // don't panic when deleting overlapping ranges
test(("#(x|)# #[x|]#", "c<space><backspace><esc>", "#[\n|]#")).await?;
test(( test((
platform_line("#(x|)# #[x|]#"), "#( |)##( |)#a#( |)#axx#[x|]#a",
"c<space><backspace><esc>",
platform_line("#[\n|]#"),
))
.await?;
test((
platform_line("#( |)##( |)#a#( |)#axx#[x|]#a"),
"li<backspace><esc>", "li<backspace><esc>",
platform_line("#(a|)##(|a)#xx#[|a]#"), "#(a|)##(|a)#xx#[|a]#",
)) ))
.await?; .await?;
@ -385,43 +420,33 @@ async fn test_delete_char_backward() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_delete_word_backward() -> anyhow::Result<()> { async fn test_delete_word_backward() -> anyhow::Result<()> {
// don't panic when deleting overlapping ranges // don't panic when deleting overlapping ranges
test(( test(("fo#[o|]#ba#(r|)#", "a<C-w><esc>", "#[\n|]#")).await?;
platform_line("fo#[o|]#ba#(r|)#"),
"a<C-w><esc>",
platform_line("#[\n|]#"),
))
.await?;
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_delete_word_forward() -> anyhow::Result<()> { async fn test_delete_word_forward() -> anyhow::Result<()> {
// don't panic when deleting overlapping ranges // don't panic when deleting overlapping ranges
test(( test(("fo#[o|]#b#(|ar)#", "i<A-d><esc>", "fo#[\n|]#")).await?;
platform_line("fo#[o|]#b#(|ar)#"),
"i<A-d><esc>",
platform_line("fo#[\n|]#"),
))
.await?;
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_delete_char_forward() -> anyhow::Result<()> { async fn test_delete_char_forward() -> anyhow::Result<()> {
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[abc|]#def #[abc|]#def
#(abc|)#ef #(abc|)#ef
#(abc|)#f #(abc|)#f
#(abc|)# #(abc|)#
"}), "},
"a<del><esc>", "a<del><esc>",
platform_line(indoc! {"\ indoc! {"\
#[abc|]#ef #[abc|]#ef
#(abc|)#f #(abc|)#f
#(abc|)# #(abc|)#
#(abc|)# #(abc|)#
"}), "},
)) ))
.await?; .await?;
@ -430,33 +455,37 @@ async fn test_delete_char_forward() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_insert_with_indent() -> anyhow::Result<()> { async fn test_insert_with_indent() -> anyhow::Result<()> {
const INPUT: &str = "\ const INPUT: &str = indoc! { "
#[f|]#n foo() { #[f|]#n foo() {
if let Some(_) = None { if let Some(_) = None {
} }
\x20
}
fn bar() { }
fn bar() {
}"; }
"
};
// insert_at_line_start // insert_at_line_start
test(( test((
INPUT, INPUT,
":lang rust<ret>%<A-s>I", ":lang rust<ret>%<A-s>I",
"\ indoc! { "
#[f|]#n foo() { #[f|]#n foo() {
#(i|)#f let Some(_) = None { #(i|)#f let Some(_) = None {
#(\n|)#\ #(\n|)#
\x20 #(}|)# #(}|)#
#(\x20|)# #( |)#
#(}|)# #(}|)#
#(\n|)#\ #(\n|)#
#(f|)#n bar() { #(f|)#n bar() {
#(\n|)#\ #(\n|)#
#(}|)#", #(}|)#
"
},
)) ))
.await?; .await?;
@ -464,17 +493,19 @@ fn bar() {
test(( test((
INPUT, INPUT,
":lang rust<ret>%<A-s>A", ":lang rust<ret>%<A-s>A",
"\ indoc! { "
fn foo() {#[\n|]#\ fn foo() {#[\n|]#
\x20 if let Some(_) = None {#(\n|)#\ if let Some(_) = None {#(\n|)#
\x20 #(\n|)#\ #(\n|)#
\x20 }#(\n|)#\ }#(\n|)#
\x20#(\n|)#\ #(\n|)#
}#(\n|)#\ }#(\n|)#
#(\n|)#\ #(\n|)#
fn bar() {#(\n|)#\ fn bar() {#(\n|)#
\x20 #(\n|)#\ #(\n|)#
}#(|)#", }#(\n|)#
"
},
)) ))
.await?; .await?;
@ -485,42 +516,42 @@ fn bar() {#(\n|)#\
async fn test_join_selections() -> anyhow::Result<()> { async fn test_join_selections() -> anyhow::Result<()> {
// normal join // normal join
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"J", "J",
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc def #[a|]#bc def
"}), "},
)) ))
.await?; .await?;
// join with empty line // join with empty line
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"JJ", "JJ",
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc def #[a|]#bc def
"}), "},
)) ))
.await?; .await?;
// join with additional space in non-empty line // join with additional space in non-empty line
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"JJ", "JJ",
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc def #[a|]#bc def
"}), "},
)) ))
.await?; .await?;
@ -531,7 +562,7 @@ async fn test_join_selections() -> anyhow::Result<()> {
async fn test_join_selections_space() -> anyhow::Result<()> { async fn test_join_selections_space() -> anyhow::Result<()> {
// join with empty lines panic // join with empty lines panic
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a #[a
b b
@ -541,69 +572,153 @@ async fn test_join_selections_space() -> anyhow::Result<()> {
d d
e|]# e|]#
"}), "},
"<A-J>", "<A-J>",
platform_line(indoc! {"\ indoc! {"\
a#[ |]#b#( |)#c#( |)#d#( |)#e a#[ |]#b#( |)#c#( |)#d#( |)#e
"}), "},
)) ))
.await?; .await?;
// normal join // normal join
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"<A-J>", "<A-J>",
platform_line(indoc! {"\ indoc! {"\
abc#[ |]#def abc#[ |]#def
"}), "},
)) ))
.await?; .await?;
// join with empty line // join with empty line
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"<A-J>", "<A-J>",
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
)) ))
.await?; .await?;
// join with additional space in non-empty line // join with additional space in non-empty line
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[a|]#bc #[a|]#bc
def def
"}), "},
"<A-J><A-J>", "<A-J><A-J>",
platform_line(indoc! {"\ indoc! {"\
abc#[ |]#def abc#[ |]#def
"}), "},
)) ))
.await?; .await?;
// join with retained trailing spaces // join with retained trailing spaces
test(( test((
platform_line(indoc! {"\ indoc! {"\
#[aaa #[aaa
bb bb
c |]# c |]#
"}), "},
"<A-J>", "<A-J>",
platform_line(indoc! {"\ indoc! {"\
aaa #[ |]#bb #( |)#c aaa #[ |]#bb #( |)#c
"}), "},
))
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_read_file() -> anyhow::Result<()> {
let mut file = tempfile::NamedTempFile::new()?;
let contents_to_read = "some contents";
let output_file = helpers::temp_file_with_contents(contents_to_read)?;
test_key_sequence(
&mut helpers::AppBuilder::new()
.with_file(file.path(), None)
.build()?,
Some(&format!(":r {:?}<ret><esc>:w<ret>", output_file.path())),
Some(&|app| {
assert!(!app.editor.is_err(), "error: {:?}", app.editor.get_status());
}),
false,
)
.await?;
let expected_contents = LineFeedHandling::Native.apply(contents_to_read);
helpers::assert_file_has_content(&mut file, &expected_contents)?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn surround_delete() -> anyhow::Result<()> {
// Test `surround_delete` when head < anchor
test(("(#[| ]#)", "mdm", "#[| ]#")).await?;
test(("(#[| ]#)", "md(", "#[| ]#")).await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn surround_replace_ts() -> anyhow::Result<()> {
const INPUT: &str = r#"\
fn foo() {
if let Some(_) = None {
todo!("f#[|o]#o)");
}
}
"#;
test((
INPUT,
":lang rust<ret>mrm'",
r#"\
fn foo() {
if let Some(_) = None {
todo!('f#[|o]#o)');
}
}
"#,
))
.await?;
test((
INPUT,
":lang rust<ret>3mrm[",
r#"\
fn foo() {
if let Some(_) = None [
todo!("f#[|o]#o)");
]
}
"#,
))
.await?;
test((
INPUT,
":lang rust<ret>2mrm{",
r#"\
fn foo() {
if let Some(_) = None {
todo!{"f#[|o]#o)"};
}
}
"#,
)) ))
.await?; .await?;

@ -6,7 +6,7 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
// single cursor stays single cursor, first goes to end of current // single cursor stays single cursor, first goes to end of current
// node, then parent // node, then parent
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -14,9 +14,9 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
"no#["|]# "no#["|]#
} }
} }
"##}), "##},
"<A-e>", "<A-e>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -24,10 +24,10 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
\"no\"#[\n|]# \"no\"#[\n|]#
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -35,9 +35,9 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
\"no\"#[\n|]# \"no\"#[\n|]#
} }
} }
"}), "},
"<A-e>", "<A-e>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -45,11 +45,11 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#[\n|]# }#[\n|]#
} }
"}), "},
), ),
// select mode extends // select mode extends
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -57,9 +57,9 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
#["no"|]# #["no"|]#
} }
} }
"##}), "##},
"v<A-e><A-e>", "v<A-e><A-e>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -67,7 +67,7 @@ async fn test_move_parent_node_end() -> anyhow::Result<()> {
#[\"no\" #[\"no\"
}\n|]# }\n|]#
} }
"}), "},
), ),
]; ];
@ -84,7 +84,7 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
// single cursor stays single cursor, first goes to end of current // single cursor stays single cursor, first goes to end of current
// node, then parent // node, then parent
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -92,9 +92,9 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
"no#["|]# "no#["|]#
} }
} }
"##}), "##},
"<A-b>", "<A-b>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -102,10 +102,10 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
#[\"|]#no\" #[\"|]#no\"
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -113,9 +113,9 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
\"no\"#[\n|]# \"no\"#[\n|]#
} }
} }
"}), "},
"<A-b>", "<A-b>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -123,10 +123,10 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
\"no\" \"no\"
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -134,9 +134,9 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
\"no\" \"no\"
} }
} }
"}), "},
"<A-b>", "<A-b>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -144,11 +144,11 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
\"no\" \"no\"
} }
} }
"}), "},
), ),
// select mode extends // select mode extends
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -156,9 +156,9 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
#["no"|]# #["no"|]#
} }
} }
"##}), "##},
"v<A-b><A-b>", "v<A-b><A-b>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -166,10 +166,10 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
]#\"no\" ]#\"no\"
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -177,9 +177,9 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
#["no"|]# #["no"|]#
} }
} }
"##}), "##},
"v<A-b><A-b><A-b>", "v<A-b><A-b><A-b>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -187,7 +187,7 @@ async fn test_move_parent_node_start() -> anyhow::Result<()> {
]#\"no\" ]#\"no\"
} }
} }
"}), "},
), ),
]; ];
@ -204,7 +204,7 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
// single cursor stays single cursor, first goes to end of current // single cursor stays single cursor, first goes to end of current
// node, then parent // node, then parent
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
fn foo() { fn foo() {
let result = if true { let result = if true {
"yes" "yes"
@ -212,9 +212,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
"no#["|]# "no#["|]#
} }
} }
"##}), "##},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -222,10 +222,10 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"#[|\n]# \"no\"#[|\n]#
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -233,9 +233,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"#[\n|]# \"no\"#[\n|]#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -243,12 +243,12 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#[|\n]# }#[|\n]#
} }
"}), "},
), ),
// appending to the end of a line should still look at the current // appending to the end of a line should still look at the current
// line, not the next one // line, not the next one
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -256,9 +256,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no#[\"|]# \"no#[\"|]#
} }
} }
"}), "},
"a<tab>", "a<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -266,11 +266,11 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#[\n|]# }#[\n|]#
} }
"}), "},
), ),
// before cursor is all whitespace, so insert tab // before cursor is all whitespace, so insert tab
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -278,9 +278,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
#[\"no\"|]# #[\"no\"|]#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -288,12 +288,12 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
#[|\"no\"]# #[|\"no\"]#
} }
} }
"}), "},
), ),
// if selection spans multiple lines, it should still only look at the // if selection spans multiple lines, it should still only look at the
// line on which the head is // line on which the head is
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[\"yes\" #[\"yes\"
@ -301,9 +301,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"|]# \"no\"|]#
} }
} }
"}), "},
"a<tab>", "a<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -311,10 +311,10 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#[\n|]# }#[\n|]#
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[\"yes\" #[\"yes\"
@ -322,9 +322,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"|]# \"no\"|]#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[|\"yes\" #[|\"yes\"
@ -332,10 +332,10 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"]# \"no\"]#
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
#[l|]#et result = if true { #[l|]#et result = if true {
#(\"yes\" #(\"yes\"
@ -343,9 +343,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"|)# \"no\"|)#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
#[|l]#et result = if true { #[|l]#et result = if true {
#(|\"yes\" #(|\"yes\"
@ -353,10 +353,10 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\")# \"no\")#
} }
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\"#[\n|]# \"yes\"#[\n|]#
@ -364,9 +364,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\"#(\n|)# \"no\"#(\n|)#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -374,10 +374,10 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#(|\n)# }#(|\n)#
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[\"yes\"|]# #[\"yes\"|]#
@ -385,9 +385,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
#(\"no\"|)# #(\"no\"|)#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[|\"yes\"]# #[|\"yes\"]#
@ -395,12 +395,12 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
#(|\"no\")# #(|\"no\")#
} }
} }
"}), "},
), ),
// if any cursors are not preceded by all whitespace, then do the // if any cursors are not preceded by all whitespace, then do the
// smart_tab action // smart_tab action
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[\"yes\"\n|]# #[\"yes\"\n|]#
@ -408,9 +408,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no#(\"\n|)# \"no#(\"\n|)#
} }
} }
"}), "},
"i<tab>", "i<tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
\"yes\" \"yes\"
@ -418,11 +418,11 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no\" \"no\"
}#(|\n)# }#(|\n)#
} }
"}), "},
), ),
// Ctrl-tab always inserts a tab // Ctrl-tab always inserts a tab
( (
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[\"yes\"\n|]# #[\"yes\"\n|]#
@ -430,9 +430,9 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no#(\"\n|)# \"no#(\"\n|)#
} }
} }
"}), "},
"i<S-tab>", "i<S-tab>",
helpers::platform_line(indoc! {"\ indoc! {"\
fn foo() { fn foo() {
let result = if true { let result = if true {
#[|\"yes\"\n]# #[|\"yes\"\n]#
@ -440,7 +440,363 @@ async fn test_smart_tab_move_parent_node_end() -> anyhow::Result<()> {
\"no #(|\"\n)# \"no #(|\"\n)#
} }
} }
"}), "},
),
];
for test in tests {
test_with_config(AppBuilder::new().with_file("foo.rs", None), test).await?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn select_all_siblings() -> anyhow::Result<()> {
let tests = vec![
// basic tests
(
indoc! {r##"
let foo = bar(#[a|]#, b, c);
"##},
"<A-a>",
indoc! {r##"
let foo = bar(#[a|]#, #(b|)#, #(c|)#);
"##},
),
(
indoc! {r##"
let a = [
#[1|]#,
2,
3,
4,
5,
];
"##},
"<A-a>",
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
),
// direction is preserved
(
indoc! {r##"
let a = [
#[|1]#,
2,
3,
4,
5,
];
"##},
"<A-a>",
indoc! {r##"
let a = [
#[|1]#,
#(|2)#,
#(|3)#,
#(|4)#,
#(|5)#,
];
"##},
),
// can't pick any more siblings - selection stays the same
(
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
"<A-a>",
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
),
// each cursor does the sibling select independently
(
indoc! {r##"
let a = [
#[1|]#,
2,
3,
4,
5,
];
let b = [
#("one"|)#,
"two",
"three",
"four",
"five",
];
"##},
"<A-a>",
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
let b = [
#("one"|)#,
#("two"|)#,
#("three"|)#,
#("four"|)#,
#("five"|)#,
];
"##},
),
// conflicting sibling selections get normalized. Here, the primary
// selection would choose every list item, but because the secondary
// range covers more than one item, the descendent is the entire list,
// which means the sibling is the assignment. The list item ranges just
// get normalized out since the list itself becomes selected.
(
indoc! {r##"
let a = [
#[1|]#,
2,
#(3,
4|)#,
5,
];
"##},
"<A-a>",
indoc! {r##"
let #(a|)# = #[[
1,
2,
3,
4,
5,
]|]#;
"##},
),
];
for test in tests {
test_with_config(AppBuilder::new().with_file("foo.rs", None), test).await?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn select_all_children() -> anyhow::Result<()> {
let tests = vec![
// basic tests
(
indoc! {r##"
let foo = bar#[(a, b, c)|]#;
"##},
"<A-I>",
indoc! {r##"
let foo = bar(#[a|]#, #(b|)#, #(c|)#);
"##},
),
(
indoc! {r##"
let a = #[[
1,
2,
3,
4,
5,
]|]#;
"##},
"<A-I>",
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
),
// direction is preserved
(
indoc! {r##"
let a = #[|[
1,
2,
3,
4,
5,
]]#;
"##},
"<A-I>",
indoc! {r##"
let a = [
#[|1]#,
#(|2)#,
#(|3)#,
#(|4)#,
#(|5)#,
];
"##},
),
// can't pick any more children - selection stays the same
(
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
"<A-I>",
indoc! {r##"
let a = [
#[1|]#,
#(2|)#,
#(3|)#,
#(4|)#,
#(5|)#,
];
"##},
),
// each cursor does the sibling select independently
(
indoc! {r##"
let a = #[|[
1,
2,
3,
4,
5,
]]#;
let b = #([
"one",
"two",
"three",
"four",
"five",
]|)#;
"##},
"<A-I>",
indoc! {r##"
let a = [
#[|1]#,
#(|2)#,
#(|3)#,
#(|4)#,
#(|5)#,
];
let b = [
#("one"|)#,
#("two"|)#,
#("three"|)#,
#("four"|)#,
#("five"|)#,
];
"##},
),
];
for test in tests {
test_with_config(AppBuilder::new().with_file("foo.rs", None), test).await?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_select_next_sibling() -> anyhow::Result<()> {
let tests = vec![
// basic test
(
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 #[}|]#
fn dec(x: usize) -> usize { x - 1 }
fn ident(x: usize) -> usize { x }
"##},
"<A-n>",
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 }
#[fn dec(x: usize) -> usize { x - 1 }|]#
fn ident(x: usize) -> usize { x }
"##},
),
// direction is not preserved and is always forward.
(
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 #[}|]#
fn dec(x: usize) -> usize { x - 1 }
fn ident(x: usize) -> usize { x }
"##},
"<A-n><A-;><A-n>",
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 }
fn dec(x: usize) -> usize { x - 1 }
#[fn ident(x: usize) -> usize { x }|]#
"##},
),
];
for test in tests {
test_with_config(AppBuilder::new().with_file("foo.rs", None), test).await?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_select_prev_sibling() -> anyhow::Result<()> {
let tests = vec![
// basic test
(
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 }
fn dec(x: usize) -> usize { x - 1 }
#[|f]#n ident(x: usize) -> usize { x }
"##},
"<A-p>",
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 }
#[|fn dec(x: usize) -> usize { x - 1 }]#
fn ident(x: usize) -> usize { x }
"##},
),
// direction is not preserved and is always backward.
(
indoc! {r##"
fn inc(x: usize) -> usize { x + 1 }
fn dec(x: usize) -> usize { x - 1 }
#[|f]#n ident(x: usize) -> usize { x }
"##},
"<A-p><A-;><A-p>",
indoc! {r##"
#[|fn inc(x: usize) -> usize { x + 1 }]#
fn dec(x: usize) -> usize { x - 1 }
fn ident(x: usize) -> usize { x }
"##},
), ),
]; ];

@ -94,7 +94,10 @@ async fn test_buffer_close_concurrent() -> anyhow::Result<()> {
) )
.await?; .await?;
helpers::assert_file_has_content(file.as_file_mut(), &platform_line(&RANGE.end().to_string()))?; helpers::assert_file_has_content(
&mut file,
&LineFeedHandling::Native.apply(&RANGE.end().to_string()),
)?;
Ok(()) Ok(())
} }
@ -114,14 +117,12 @@ async fn test_write() -> anyhow::Result<()> {
) )
.await?; .await?;
file.as_file_mut().flush()?; reload_file(&mut file).unwrap();
file.as_file_mut().sync_all()?;
let mut file_content = String::new(); let mut file_content = String::new();
file.as_file_mut().read_to_string(&mut file_content)?; file.as_file_mut().read_to_string(&mut file_content)?;
assert_eq!( assert_eq!(
helpers::platform_line("the gostak distims the doshes"), LineFeedHandling::Native.apply("the gostak distims the doshes"),
file_content file_content
); );
@ -138,24 +139,18 @@ async fn test_overwrite_protection() -> anyhow::Result<()> {
helpers::run_event_loop_until_idle(&mut app).await; helpers::run_event_loop_until_idle(&mut app).await;
file.as_file_mut() file.as_file_mut()
.write_all(helpers::platform_line("extremely important content").as_bytes())?; .write_all("extremely important content".as_bytes())?;
file.as_file_mut().flush()?; file.as_file_mut().flush()?;
file.as_file_mut().sync_all()?; file.as_file_mut().sync_all()?;
test_key_sequence(&mut app, Some(":x<ret>"), None, false).await?; test_key_sequence(&mut app, Some(":x<ret>"), None, false).await?;
file.as_file_mut().flush()?; reload_file(&mut file).unwrap();
file.as_file_mut().sync_all()?;
file.rewind()?;
let mut file_content = String::new(); let mut file_content = String::new();
file.as_file_mut().read_to_string(&mut file_content)?; file.read_to_string(&mut file_content)?;
assert_eq!( assert_eq!("extremely important content", file_content);
helpers::platform_line("extremely important content"),
file_content
);
Ok(()) Ok(())
} }
@ -175,14 +170,13 @@ async fn test_write_quit() -> anyhow::Result<()> {
) )
.await?; .await?;
file.as_file_mut().flush()?; reload_file(&mut file).unwrap();
file.as_file_mut().sync_all()?;
let mut file_content = String::new(); let mut file_content = String::new();
file.as_file_mut().read_to_string(&mut file_content)?; file.read_to_string(&mut file_content)?;
assert_eq!( assert_eq!(
helpers::platform_line("the gostak distims the doshes"), LineFeedHandling::Native.apply("the gostak distims the doshes"),
file_content file_content
); );
@ -205,12 +199,13 @@ async fn test_write_concurrent() -> anyhow::Result<()> {
test_key_sequence(&mut app, Some(&command), None, false).await?; test_key_sequence(&mut app, Some(&command), None, false).await?;
file.as_file_mut().flush()?; reload_file(&mut file).unwrap();
file.as_file_mut().sync_all()?;
let mut file_content = String::new(); let mut file_content = String::new();
file.as_file_mut().read_to_string(&mut file_content)?; file.read_to_string(&mut file_content)?;
assert_eq!(platform_line(&RANGE.end().to_string()), file_content); assert_eq!(
LineFeedHandling::Native.apply(&RANGE.end().to_string()),
file_content
);
Ok(()) Ok(())
} }
@ -276,7 +271,7 @@ async fn test_write_scratch_to_new_path() -> anyhow::Result<()> {
) )
.await?; .await?;
helpers::assert_file_has_content(file.as_file_mut(), &helpers::platform_line("hello"))?; helpers::assert_file_has_content(&mut file, &LineFeedHandling::Native.apply("hello"))?;
Ok(()) Ok(())
} }
@ -321,7 +316,7 @@ async fn test_write_auto_format_fails_still_writes() -> anyhow::Result<()> {
test_key_sequences(&mut app, vec![(Some(":w<ret>"), None)], false).await?; test_key_sequences(&mut app, vec![(Some(":w<ret>"), None)], false).await?;
// file still saves // file still saves
helpers::assert_file_has_content(file.as_file_mut(), "let foo = 0;\n")?; helpers::assert_file_has_content(&mut file, "let foo = 0;\n")?;
Ok(()) Ok(())
} }
@ -360,13 +355,13 @@ async fn test_write_new_path() -> anyhow::Result<()> {
.await?; .await?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file1.as_file_mut(), &mut file1,
&helpers::platform_line("i can eat glass, it will not hurt me\n"), &LineFeedHandling::Native.apply("i can eat glass, it will not hurt me\n"),
)?; )?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file2.as_file_mut(), &mut file2,
&helpers::platform_line("i can eat glass, it will not hurt me\n"), &LineFeedHandling::Native.apply("i can eat glass, it will not hurt me\n"),
)?; )?;
Ok(()) Ok(())
@ -436,8 +431,8 @@ async fn test_write_insert_final_newline_added_if_missing() -> anyhow::Result<()
test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?; test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file.as_file_mut(), &mut file,
&helpers::platform_line("have you tried chamomile tea?\n"), &LineFeedHandling::Native.apply("have you tried chamomile tea?\n"),
)?; )?;
Ok(()) Ok(())
@ -448,14 +443,14 @@ async fn test_write_insert_final_newline_unchanged_if_not_missing() -> anyhow::R
let mut file = tempfile::NamedTempFile::new()?; let mut file = tempfile::NamedTempFile::new()?;
let mut app = helpers::AppBuilder::new() let mut app = helpers::AppBuilder::new()
.with_file(file.path(), None) .with_file(file.path(), None)
.with_input_text(&helpers::platform_line("#[t|]#en minutes, please\n")) .with_input_text(LineFeedHandling::Native.apply("#[t|]#en minutes, please\n"))
.build()?; .build()?;
test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?; test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file.as_file_mut(), &mut file,
&helpers::platform_line("ten minutes, please\n"), &LineFeedHandling::Native.apply("ten minutes, please\n"),
)?; )?;
Ok(()) Ok(())
@ -478,10 +473,8 @@ async fn test_write_insert_final_newline_unchanged_if_missing_and_false() -> any
test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?; test_key_sequence(&mut app, Some(":w<ret>"), None, false).await?;
helpers::assert_file_has_content( reload_file(&mut file).unwrap();
file.as_file_mut(), helpers::assert_file_has_content(&mut file, "the quiet rain continued through the night")?;
"the quiet rain continued through the night",
)?;
Ok(()) Ok(())
} }
@ -507,13 +500,13 @@ async fn test_write_all_insert_final_newline_add_if_missing_and_modified() -> an
.await?; .await?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file1.as_file_mut(), &mut file1,
&helpers::platform_line("we don't serve time travelers here\n"), &LineFeedHandling::Native.apply("we don't serve time travelers here\n"),
)?; )?;
helpers::assert_file_has_content( helpers::assert_file_has_content(
file2.as_file_mut(), &mut file2,
&helpers::platform_line("a time traveler walks into a bar\n"), &LineFeedHandling::Native.apply("a time traveler walks into a bar\n"),
)?; )?;
Ok(()) Ok(())
@ -531,7 +524,82 @@ async fn test_write_all_insert_final_newline_do_not_add_if_unmodified() -> anyho
test_key_sequence(&mut app, Some(":wa<ret>"), None, false).await?; test_key_sequence(&mut app, Some(":wa<ret>"), None, false).await?;
helpers::assert_file_has_content(file.as_file_mut(), "i lost on Jeopardy!")?; helpers::assert_file_has_content(&mut file, "i lost on Jeopardy!")?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_symlink_write() -> anyhow::Result<()> {
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(not(unix))]
use std::os::windows::fs::symlink_file as symlink;
let dir = tempfile::tempdir()?;
let mut file = tempfile::NamedTempFile::new_in(&dir)?;
let symlink_path = dir.path().join("linked");
symlink(file.path(), &symlink_path)?;
let mut app = helpers::AppBuilder::new()
.with_file(&symlink_path, None)
.build()?;
test_key_sequence(
&mut app,
Some("ithe gostak distims the doshes<ret><esc>:w<ret>"),
None,
false,
)
.await?;
reload_file(&mut file).unwrap();
let mut file_content = String::new();
file.as_file_mut().read_to_string(&mut file_content)?;
assert_eq!(
LineFeedHandling::Native.apply("the gostak distims the doshes"),
file_content
);
assert!(symlink_path.is_symlink());
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_symlink_write_fail() -> anyhow::Result<()> {
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(not(unix))]
use std::os::windows::fs::symlink_file as symlink;
let dir = tempfile::tempdir()?;
let file = helpers::new_readonly_tempfile_in_dir(&dir)?;
let symlink_path = dir.path().join("linked");
symlink(file.path(), &symlink_path)?;
let mut app = helpers::AppBuilder::new()
.with_file(&symlink_path, None)
.build()?;
test_key_sequence(
&mut app,
Some("ihello<esc>:wq<ret>"),
Some(&|app| {
let mut docs: Vec<_> = app.editor.documents().collect();
assert_eq!(1, docs.len());
let doc = docs.pop().unwrap();
assert_eq!(Some(&path::normalize(&symlink_path)), doc.path());
assert_eq!(&Severity::Error, app.editor.get_status().unwrap().1);
}),
false,
)
.await?;
assert!(symlink_path.is_symlink());
Ok(()) Ok(())
} }
@ -557,7 +625,7 @@ async fn edit_file_with_content(file_content: &[u8]) -> anyhow::Result<()> {
) )
.await?; .await?;
file.rewind()?; reload_file(&mut file).unwrap();
let mut new_file_content: Vec<u8> = Vec::new(); let mut new_file_content: Vec<u8> = Vec::new();
file.read_to_end(&mut new_file_content)?; file.read_to_end(&mut new_file_content)?;

@ -1,5 +1,4 @@
use std::{ use std::{
fs::File,
io::{Read, Write}, io::{Read, Write},
mem::replace, mem::replace,
path::PathBuf, path::PathBuf,
@ -14,6 +13,46 @@ use helix_view::{current_ref, doc, editor::LspConfig, input::parse_macro, Editor
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
/// Specify how to set up the input text with line feeds
#[derive(Clone, Debug)]
pub enum LineFeedHandling {
/// Replaces all LF chars with the system's appropriate line feed character,
/// and if one doesn't exist already, appends the system's appropriate line
/// ending to the end of a string.
Native,
/// Do not modify the input text in any way. What you give is what you test.
AsIs,
}
impl LineFeedHandling {
/// Apply the line feed handling to the input string, yielding a set of
/// resulting texts with the appropriate line feed substitutions.
pub fn apply(&self, text: &str) -> String {
let line_end = match self {
LineFeedHandling::Native => helix_core::NATIVE_LINE_ENDING,
LineFeedHandling::AsIs => return text.into(),
}
.as_str();
// we can assume that the source files in this code base will always
// be LF, so indoc strings will always insert LF
let mut output = text.replace('\n', line_end);
if !output.ends_with(line_end) {
output.push_str(line_end);
}
output
}
}
impl Default for LineFeedHandling {
fn default() -> Self {
Self::Native
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct TestCase { pub struct TestCase {
pub in_text: String, pub in_text: String,
@ -21,6 +60,8 @@ pub struct TestCase {
pub in_keys: String, pub in_keys: String,
pub out_text: String, pub out_text: String,
pub out_selection: Selection, pub out_selection: Selection,
pub line_feed_handling: LineFeedHandling,
} }
impl<S, R, V> From<(S, R, V)> for TestCase impl<S, R, V> From<(S, R, V)> for TestCase
@ -30,8 +71,19 @@ where
V: Into<String>, V: Into<String>,
{ {
fn from((input, keys, output): (S, R, V)) -> Self { fn from((input, keys, output): (S, R, V)) -> Self {
let (in_text, in_selection) = test::print(&input.into()); TestCase::from((input, keys, output, LineFeedHandling::default()))
let (out_text, out_selection) = test::print(&output.into()); }
}
impl<S, R, V> From<(S, R, V, LineFeedHandling)> for TestCase
where
S: Into<String>,
R: Into<String>,
V: Into<String>,
{
fn from((input, keys, output, line_feed_handling): (S, R, V, LineFeedHandling)) -> Self {
let (in_text, in_selection) = test::print(&line_feed_handling.apply(&input.into()));
let (out_text, out_selection) = test::print(&line_feed_handling.apply(&output.into()));
TestCase { TestCase {
in_text, in_text,
@ -39,6 +91,7 @@ where
in_keys: keys.into(), in_keys: keys.into(),
out_text, out_text,
out_selection, out_selection,
line_feed_handling,
} }
} }
} }
@ -137,6 +190,7 @@ pub async fn test_key_sequence_with_input_text<T: Into<TestCase>>(
should_exit: bool, should_exit: bool,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let test_case = test_case.into(); let test_case = test_case.into();
let mut app = match app { let mut app = match app {
Some(app) => app, Some(app) => app,
None => Application::new(Args::default(), test_config(), test_syntax_loader(None))?, None => Application::new(Args::default(), test_config(), test_syntax_loader(None))?,
@ -240,23 +294,6 @@ pub fn test_editor_config() -> helix_view::editor::Config {
} }
} }
/// Replaces all LF chars with the system's appropriate line feed
/// character, and if one doesn't exist already, appends the system's
/// appropriate line ending to the end of a string.
pub fn platform_line(input: &str) -> String {
let line_end = helix_core::NATIVE_LINE_ENDING.as_str();
// we can assume that the source files in this code base will always
// be LF, so indoc strings will always insert LF
let mut output = input.replace('\n', line_end);
if !output.ends_with(line_end) {
output.push_str(line_end);
}
output
}
/// Creates a new temporary file that is set to read only. Useful for /// Creates a new temporary file that is set to read only. Useful for
/// testing write failures. /// testing write failures.
pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> { pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
@ -268,6 +305,18 @@ pub fn new_readonly_tempfile() -> anyhow::Result<NamedTempFile> {
Ok(file) Ok(file)
} }
/// Creates a new temporary file in the directory that is set to read only. Useful for
/// testing write failures.
pub fn new_readonly_tempfile_in_dir(
dir: impl AsRef<std::path::Path>,
) -> anyhow::Result<NamedTempFile> {
let mut file = tempfile::NamedTempFile::new_in(dir)?;
let metadata = file.as_file().metadata()?;
let mut perms = metadata.permissions();
perms.set_readonly(true);
file.as_file_mut().set_permissions(perms)?;
Ok(file)
}
pub struct AppBuilder { pub struct AppBuilder {
args: Args, args: Args,
config: Config, config: Config,
@ -352,9 +401,8 @@ pub async fn run_event_loop_until_idle(app: &mut Application) {
app.event_loop_until_idle(&mut rx_stream).await; app.event_loop_until_idle(&mut rx_stream).await;
} }
pub fn assert_file_has_content(file: &mut File, content: &str) -> anyhow::Result<()> { pub fn assert_file_has_content(file: &mut NamedTempFile, content: &str) -> anyhow::Result<()> {
file.flush()?; reload_file(file)?;
file.sync_all()?;
let mut file_content = String::new(); let mut file_content = String::new();
file.read_to_string(&mut file_content)?; file.read_to_string(&mut file_content)?;
@ -368,3 +416,13 @@ pub fn assert_status_not_error(editor: &Editor) {
assert_ne!(&Severity::Error, sev); assert_ne!(&Severity::Error, sev);
} }
} }
pub fn reload_file(file: &mut NamedTempFile) -> anyhow::Result<()> {
let path = file.path();
let f = std::fs::OpenOptions::new()
.write(true)
.read(true)
.open(&path)?;
*file.as_file_mut() = f;
Ok(())
}

@ -6,30 +6,30 @@ async fn auto_indent() -> anyhow::Result<()> {
let enter_tests = [ let enter_tests = [
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
type Test struct {#[}|]# type Test struct {#[}|]#
"##}), "##},
"i<ret>", "i<ret>",
helpers::platform_line(indoc! {"\ indoc! {"\
type Test struct { type Test struct {
\t#[|\n]# \t#[|\n]#
} }
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
func main() { func main() {
\tswitch nil {#[}|]# \tswitch nil {#[}|]#
} }
"}), "},
"i<ret>", "i<ret>",
helpers::platform_line(indoc! {"\ indoc! {"\
func main() { func main() {
\tswitch nil { \tswitch nil {
\t\t#[|\n]# \t\t#[|\n]#
\t} \t}
} }
"}), "},
), ),
]; ];

@ -6,7 +6,7 @@ async fn auto_indent() -> anyhow::Result<()> {
let below_tests = [ let below_tests = [
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
#[t|]#op: #[t|]#op:
baz: foo baz: foo
bazi: bazi:
@ -17,9 +17,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
#[\n|]# #[\n|]#
baz: foo baz: foo
@ -31,10 +31,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
b#[a|]#z: foo b#[a|]#z: foo
bazi: bazi:
@ -45,9 +45,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
#[\n|]# #[\n|]#
@ -59,10 +59,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi#[:|]# bazi#[:|]#
@ -73,9 +73,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -87,10 +87,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi: bazi:
@ -101,9 +101,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -115,10 +115,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi: bazi:
@ -129,9 +129,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -143,10 +143,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -157,9 +157,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -171,10 +171,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -185,9 +185,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -199,10 +199,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -213,9 +213,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook:#[\n|]# fook:#[\n|]#
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -227,10 +227,10 @@ async fn auto_indent() -> anyhow::Result<()> {
bax: foox bax: foox
fook: fook:
#[\n|]# #[\n|]#
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: | bax: |
@ -239,9 +239,9 @@ async fn auto_indent() -> anyhow::Result<()> {
line line
string#[\n|]# string#[\n|]#
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: | bax: |
@ -251,10 +251,10 @@ async fn auto_indent() -> anyhow::Result<()> {
string string
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
@ -263,9 +263,9 @@ async fn auto_indent() -> anyhow::Result<()> {
line#[\n|]# line#[\n|]#
string string
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
@ -275,74 +275,74 @@ async fn auto_indent() -> anyhow::Result<()> {
#[\n|]# #[\n|]#
string string
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: >#[\n|]# bax: >#[\n|]#
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
- top:#[\n|]# - top:#[\n|]#
baz: foo baz: foo
bax: foox bax: foox
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
#[\n|]# #[\n|]#
baz: foo baz: foo
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo#[\n|]# baz: foo#[\n|]#
bax: foox bax: foox
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo baz: foo
#[\n|]# #[\n|]#
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo baz: foo
bax: foox#[\n|]# bax: foox#[\n|]#
fook: fook:
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: baz:
- one: two#[\n|]# - one: two#[\n|]#
@ -350,9 +350,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: baz:
- one: two - one: two
@ -361,42 +361,42 @@ async fn auto_indent() -> anyhow::Result<()> {
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
"}), "},
), ),
// yaml map without a key // yaml map without a key
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top:#[\n|]# top:#[\n|]#
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
#[\n|]# #[\n|]#
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top#[:|]# top#[:|]#
bottom: withvalue bottom: withvalue
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
#[\n|]# #[\n|]#
bottom: withvalue bottom: withvalue
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
bottom: withvalue bottom: withvalue
top#[:|]# top#[:|]#
"}), "},
"o", "o",
helpers::platform_line(indoc! {"\ indoc! {"\
bottom: withvalue bottom: withvalue
top: top:
#[\n|]# #[\n|]#
"}), "},
), ),
]; ];
@ -406,7 +406,7 @@ async fn auto_indent() -> anyhow::Result<()> {
let above_tests = [ let above_tests = [
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
#[t|]#op: #[t|]#op:
baz: foo baz: foo
bazi: bazi:
@ -417,9 +417,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
#[\n|]# #[\n|]#
top: top:
baz: foo baz: foo
@ -431,10 +431,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
b#[a|]#z: foo b#[a|]#z: foo
bazi: bazi:
@ -445,9 +445,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
#[\n|]# #[\n|]#
baz: foo baz: foo
@ -459,10 +459,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi#[:|]# bazi#[:|]#
@ -473,9 +473,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
#[\n|]# #[\n|]#
@ -487,10 +487,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi: bazi:
@ -501,9 +501,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -515,10 +515,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
top: top:
baz: foo baz: foo
bazi: bazi:
@ -529,9 +529,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"##}), "##},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -543,10 +543,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -557,9 +557,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -571,10 +571,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -585,9 +585,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -599,10 +599,10 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -613,9 +613,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- 2 - 2
bax: foox bax: foox
fook:#[\n|]# fook:#[\n|]#
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bazi: bazi:
@ -627,10 +627,10 @@ async fn auto_indent() -> anyhow::Result<()> {
bax: foox bax: foox
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: | bax: |
@ -639,9 +639,9 @@ async fn auto_indent() -> anyhow::Result<()> {
line line
string#[\n|]# string#[\n|]#
fook: fook:
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: | bax: |
@ -651,10 +651,10 @@ async fn auto_indent() -> anyhow::Result<()> {
#[\n|]# #[\n|]#
string string
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
@ -663,9 +663,9 @@ async fn auto_indent() -> anyhow::Result<()> {
line line
string string
fook: fook:
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
@ -675,58 +675,58 @@ async fn auto_indent() -> anyhow::Result<()> {
line line
string string
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
fook:#[\n|]# fook:#[\n|]#
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: foo baz: foo
bax: > bax: >
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo#[\n|]# baz: foo#[\n|]#
bax: foox bax: foox
fook: fook:
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
#[\n|]# #[\n|]#
baz: foo baz: foo
bax: foox bax: foox
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
fook:#[\n|]# fook:#[\n|]#
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
#[\n|]# #[\n|]#
fook: fook:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: baz:
- one: two#[\n|]# - one: two#[\n|]#
@ -734,9 +734,9 @@ async fn auto_indent() -> anyhow::Result<()> {
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
baz: baz:
#[\n|]# #[\n|]#
@ -745,42 +745,42 @@ async fn auto_indent() -> anyhow::Result<()> {
- top: - top:
baz: foo baz: foo
bax: foox bax: foox
"}), "},
), ),
// yaml map without a key // yaml map without a key
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top:#[\n|]# top:#[\n|]#
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
#[\n|]# #[\n|]#
top: top:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
bottom: withvalue bottom: withvalue
top#[:|]# top#[:|]#
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
bottom: withvalue bottom: withvalue
#[\n|]# #[\n|]#
top: top:
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
bottom:#[ |]#withvalue bottom:#[ |]#withvalue
"}), "},
"O", "O",
helpers::platform_line(indoc! {"\ indoc! {"\
top: top:
#[\n|]# #[\n|]#
bottom: withvalue bottom: withvalue
"}), "},
), ),
]; ];
@ -790,24 +790,24 @@ async fn auto_indent() -> anyhow::Result<()> {
let enter_tests = [ let enter_tests = [
( (
helpers::platform_line(indoc! {r##" indoc! {r##"
foo: #[b|]#ar foo: #[b|]#ar
"##}), "##},
"i<ret>", "i<ret>",
helpers::platform_line(indoc! {"\ indoc! {"\
foo: foo:
#[|b]#ar #[|b]#ar
"}), "},
), ),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
foo:#[\n|]# foo:#[\n|]#
"}), "},
"i<ret>", "i<ret>",
helpers::platform_line(indoc! {"\ indoc! {"\
foo: foo:
#[|\n]# #[|\n]#
"}), "},
), ),
]; ];

@ -8,6 +8,7 @@ async fn insert_mode_cursor_position() -> anyhow::Result<()> {
in_keys: "i".into(), in_keys: "i".into(),
out_text: String::new(), out_text: String::new(),
out_selection: Selection::single(0, 0), out_selection: Selection::single(0, 0),
line_feed_handling: LineFeedHandling::AsIs,
}) })
.await?; .await?;
@ -106,6 +107,14 @@ async fn surround_by_character() -> anyhow::Result<()> {
)) ))
.await?; .await?;
// Selection direction is preserved
test((
"(so [many {go#[|od]#} text] here)",
"mi{",
"(so [many {#[|good]#} text] here)",
))
.await?;
Ok(()) Ok(())
} }
@ -365,6 +374,41 @@ async fn surround_around_pair() -> anyhow::Result<()> {
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")]
async fn match_around_closest_ts() -> anyhow::Result<()> {
test_with_config(
AppBuilder::new().with_file("foo.rs", None),
(
r#"fn main() {todo!{"f#[|oo]#)"};}"#,
"mam",
r#"fn main() {todo!{#[|"foo)"]#};}"#,
),
)
.await?;
test_with_config(
AppBuilder::new().with_file("foo.rs", None),
(
r##"fn main() { let _ = ("#[|1]#23", "#(|1)#23"); } "##,
"3mam",
r##"fn main() #[|{ let _ = ("123", "123"); }]# "##,
),
)
.await?;
test_with_config(
AppBuilder::new().with_file("foo.rs", None),
(
r##" fn main() { let _ = ("12#[|3", "12]#3"); } "##,
"1mam",
r##" fn main() { let _ = #[|("123", "123")]#; } "##,
),
)
.await?;
Ok(())
}
/// Ensure the very initial cursor in an opened file is the width of /// Ensure the very initial cursor in an opened file is the width of
/// the first grapheme /// the first grapheme
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
@ -392,20 +436,10 @@ async fn cursor_position_newly_opened_file() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn cursor_position_append_eof() -> anyhow::Result<()> { async fn cursor_position_append_eof() -> anyhow::Result<()> {
// Selection is forwards // Selection is forwards
test(( test(("#[foo|]#", "abar<esc>", "#[foobar|]#\n")).await?;
"#[foo|]#",
"abar<esc>",
helpers::platform_line("#[foobar|]#\n"),
))
.await?;
// Selection is backwards // Selection is backwards
test(( test(("#[|foo]#", "abar<esc>", "#[foobar|]#\n")).await?;
"#[|foo]#",
"abar<esc>",
helpers::platform_line("#[foobar|]#\n"),
))
.await?;
Ok(()) Ok(())
} }
@ -415,19 +449,19 @@ async fn select_mode_tree_sitter_next_function_is_union_of_objects() -> anyhow::
test_with_config( test_with_config(
AppBuilder::new().with_file("foo.rs", None), AppBuilder::new().with_file("foo.rs", None),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
#[/|]#// Increments #[/|]#// Increments
fn inc(x: usize) -> usize { x + 1 } fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 } fn dec(x: usize) -> usize { x - 1 }
"}), "},
"]fv]f", "]fv]f",
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
#[fn inc(x: usize) -> usize { x + 1 } #[fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 }|]# fn dec(x: usize) -> usize { x - 1 }|]#
"}), "},
), ),
) )
.await?; .await?;
@ -440,19 +474,19 @@ async fn select_mode_tree_sitter_prev_function_unselects_object() -> anyhow::Res
test_with_config( test_with_config(
AppBuilder::new().with_file("foo.rs", None), AppBuilder::new().with_file("foo.rs", None),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
#[fn inc(x: usize) -> usize { x + 1 } #[fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 }|]# fn dec(x: usize) -> usize { x - 1 }|]#
"}), "},
"v[f", "v[f",
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
#[fn inc(x: usize) -> usize { x + 1 }|]# #[fn inc(x: usize) -> usize { x + 1 }|]#
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 } fn dec(x: usize) -> usize { x - 1 }
"}), "},
), ),
) )
.await?; .await?;
@ -466,23 +500,23 @@ async fn select_mode_tree_sitter_prev_function_goes_backwards_to_object() -> any
test_with_config( test_with_config(
AppBuilder::new().with_file("foo.rs", None), AppBuilder::new().with_file("foo.rs", None),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
fn inc(x: usize) -> usize { x + 1 } fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 } fn dec(x: usize) -> usize { x - 1 }
/// Identity /// Identity
#[fn ident(x: usize) -> usize { x }|]# #[fn ident(x: usize) -> usize { x }|]#
"}), "},
"v[f", "v[f",
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
fn inc(x: usize) -> usize { x + 1 } fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
#[|fn dec(x: usize) -> usize { x - 1 } #[|fn dec(x: usize) -> usize { x - 1 }
/// Identity /// Identity
]#fn ident(x: usize) -> usize { x } ]#fn ident(x: usize) -> usize { x }
"}), "},
), ),
) )
.await?; .await?;
@ -490,23 +524,23 @@ async fn select_mode_tree_sitter_prev_function_goes_backwards_to_object() -> any
test_with_config( test_with_config(
AppBuilder::new().with_file("foo.rs", None), AppBuilder::new().with_file("foo.rs", None),
( (
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
fn inc(x: usize) -> usize { x + 1 } fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 } fn dec(x: usize) -> usize { x - 1 }
/// Identity /// Identity
#[fn ident(x: usize) -> usize { x }|]# #[fn ident(x: usize) -> usize { x }|]#
"}), "},
"v[f[f", "v[f[f",
helpers::platform_line(indoc! {"\ indoc! {"\
/// Increments /// Increments
#[|fn inc(x: usize) -> usize { x + 1 } #[|fn inc(x: usize) -> usize { x + 1 }
/// Decrements /// Decrements
fn dec(x: usize) -> usize { x - 1 } fn dec(x: usize) -> usize { x - 1 }
/// Identity /// Identity
]#fn ident(x: usize) -> usize { x } ]#fn ident(x: usize) -> usize { x }
"}), "},
), ),
) )
.await?; .await?;
@ -517,36 +551,36 @@ async fn select_mode_tree_sitter_prev_function_goes_backwards_to_object() -> any
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn find_char_line_ending() -> anyhow::Result<()> { async fn find_char_line_ending() -> anyhow::Result<()> {
test(( test((
helpers::platform_line(indoc! { indoc! {
"\ "\
one one
#[|t]#wo #[|t]#wo
three" three"
}), },
"T<ret>gll2f<ret>", "T<ret>gll2f<ret>",
helpers::platform_line(indoc! { indoc! {
"\ "\
one one
two#[ two#[
|]#three" |]#three"
}), },
)) ))
.await?; .await?;
test(( test((
helpers::platform_line(indoc! { indoc! {
"\ "\
#[|o]#ne #[|o]#ne
two two
three" three"
}), },
"f<ret>2t<ret>ghT<ret>F<ret>", "f<ret>2t<ret>ghT<ret>F<ret>",
helpers::platform_line(indoc! { indoc! {
"\ "\
one#[| one#[|
t]#wo t]#wo
three" three"
}), },
)) ))
.await?; .await?;
@ -556,41 +590,41 @@ async fn find_char_line_ending() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_surround_replace() -> anyhow::Result<()> { async fn test_surround_replace() -> anyhow::Result<()> {
test(( test((
platform_line(indoc! {"\ indoc! {"\
(#[|a]#) (#[|a]#)
"}), "},
"mrm{", "mrm{",
platform_line(indoc! {"\ indoc! {"\
{#[|a]#} {#[|a]#}
"}), "},
)) ))
.await?; .await?;
test(( test((
platform_line(indoc! {"\ indoc! {"\
(#[a|]#) (#[a|]#)
"}), "},
"mrm{", "mrm{",
platform_line(indoc! {"\ indoc! {"\
{#[a|]#} {#[a|]#}
"}), "},
)) ))
.await?; .await?;
test(( test((
platform_line(indoc! {"\ indoc! {"\
{{ {{
#(}|)# #(}|)#
#[}|]# #[}|]#
"}), "},
"mrm)", "mrm)",
platform_line(indoc! {"\ indoc! {"\
(( ((
#()|)# #()|)#
#[)|]# #[)|]#
"}), "},
)) ))
.await?; .await?;
@ -600,38 +634,95 @@ async fn test_surround_replace() -> anyhow::Result<()> {
#[tokio::test(flavor = "multi_thread")] #[tokio::test(flavor = "multi_thread")]
async fn test_surround_delete() -> anyhow::Result<()> { async fn test_surround_delete() -> anyhow::Result<()> {
test(( test((
platform_line(indoc! {"\ indoc! {"\
(#[|a]#) (#[|a]#)
"}), "},
"mdm", "mdm",
platform_line(indoc! {"\ indoc! {"\
#[|a]# #[|a]#
"}), "},
)) ))
.await?; .await?;
test(( test((
platform_line(indoc! {"\ indoc! {"\
(#[a|]#) (#[a|]#)
"}), "},
"mdm", "mdm",
platform_line(indoc! {"\ indoc! {"\
#[a|]# #[a|]#
"}), "},
)) ))
.await?; .await?;
test(( test((
platform_line(indoc! {"\ indoc! {"\
{{ {{
#(}|)# #(}|)#
#[}|]# #[}|]#
"}), "},
"mdm", "mdm",
platform_line("\n\n#(\n|)##[\n|]#"), "\n\n#(\n|)##[\n|]#",
)) ))
.await?; .await?;
Ok(()) Ok(())
} }
#[tokio::test(flavor = "multi_thread")]
async fn tree_sitter_motions_work_across_injections() -> anyhow::Result<()> {
test_with_config(
AppBuilder::new().with_file("foo.html", None),
(
"<script>let #[|x]# = 1;</script>",
"<A-o>",
"<script>let #[|x = 1]#;</script>",
),
)
.await?;
// When the full injected layer is selected, expand_selection jumps to
// a more shallow layer.
test_with_config(
AppBuilder::new().with_file("foo.html", None),
(
"<script>#[|let x = 1;]#</script>",
"<A-o>",
"#[|<script>let x = 1;</script>]#",
),
)
.await?;
test_with_config(
AppBuilder::new().with_file("foo.html", None),
(
"<script>let #[|x = 1]#;</script>",
"<A-i>",
"<script>let #[|x]# = 1;</script>",
),
)
.await?;
test_with_config(
AppBuilder::new().with_file("foo.html", None),
(
"<script>let #[|x]# = 1;</script>",
"<A-n>",
"<script>let x #[=|]# 1;</script>",
),
)
.await?;
test_with_config(
AppBuilder::new().with_file("foo.html", None),
(
"<script>let #[|x]# = 1;</script>",
"<A-p>",
"<script>#[|let]# x = 1;</script>",
),
)
.await?;
Ok(())
}

@ -62,9 +62,9 @@ async fn test_split_write_quit_all() -> anyhow::Result<()> {
) )
.await?; .await?;
helpers::assert_file_has_content(file1.as_file_mut(), &platform_line("hello1"))?; helpers::assert_file_has_content(&mut file1, &LineFeedHandling::Native.apply("hello1"))?;
helpers::assert_file_has_content(file2.as_file_mut(), &platform_line("hello2"))?; helpers::assert_file_has_content(&mut file2, &LineFeedHandling::Native.apply("hello2"))?;
helpers::assert_file_has_content(file3.as_file_mut(), &platform_line("hello3"))?; helpers::assert_file_has_content(&mut file3, &LineFeedHandling::Native.apply("hello3"))?;
Ok(()) Ok(())
} }
@ -91,7 +91,7 @@ async fn test_split_write_quit_same_file() -> anyhow::Result<()> {
let doc = docs.pop().unwrap(); let doc = docs.pop().unwrap();
assert_eq!( assert_eq!(
helpers::platform_line("hello\ngoodbye"), LineFeedHandling::Native.apply("hello\ngoodbye"),
doc.text().to_string() doc.text().to_string()
); );
@ -110,7 +110,7 @@ async fn test_split_write_quit_same_file() -> anyhow::Result<()> {
let doc = docs.pop().unwrap(); let doc = docs.pop().unwrap();
assert_eq!( assert_eq!(
helpers::platform_line("hello\ngoodbye"), LineFeedHandling::Native.apply("hello\ngoodbye"),
doc.text().to_string() doc.text().to_string()
); );
@ -122,10 +122,7 @@ async fn test_split_write_quit_same_file() -> anyhow::Result<()> {
) )
.await?; .await?;
helpers::assert_file_has_content( helpers::assert_file_has_content(&mut file, &LineFeedHandling::Native.apply("hello\ngoodbye"))?;
file.as_file_mut(),
&helpers::platform_line("hello\ngoodbye"),
)?;
Ok(()) Ok(())
} }
@ -151,7 +148,13 @@ async fn test_changes_in_splits_apply_to_all_views() -> anyhow::Result<()> {
// //
// This panicked in the past because the jumplist entry on line 2 of window 2 // This panicked in the past because the jumplist entry on line 2 of window 2
// was not updated and after the `kd` step, pointed outside of the document. // was not updated and after the `kd` step, pointed outside of the document.
test(("#[|]#", "<C-w>v[<space><C-s><C-w>wkd<C-w>qd", "#[|]#")).await?; test((
"#[|]#",
"<C-w>v[<space><C-s><C-w>wkd<C-w>qd",
"#[|]#",
LineFeedHandling::AsIs,
))
.await?;
// Transactions are applied to the views for windows lazily when they are focused. // Transactions are applied to the views for windows lazily when they are focused.
// This case panics if the transactions and inversions are not applied in the // This case panics if the transactions and inversions are not applied in the
@ -160,6 +163,7 @@ async fn test_changes_in_splits_apply_to_all_views() -> anyhow::Result<()> {
"#[|]#", "#[|]#",
"[<space>[<space>[<space><C-w>vuuu<C-w>wUUU<C-w>quuu", "[<space>[<space>[<space><C-w>vuuu<C-w>wUUU<C-w>quuu",
"#[|]#", "#[|]#",
LineFeedHandling::AsIs,
)) ))
.await?; .await?;
@ -185,6 +189,7 @@ async fn test_changes_in_splits_apply_to_all_views() -> anyhow::Result<()> {
"#[|]#", "#[|]#",
"3[<space><C-w>v<C-s><C-w>wuu3[<space><C-w>q%d", "3[<space><C-w>v<C-s><C-w>wuu3[<space><C-w>q%d",
"#[|]#", "#[|]#",
LineFeedHandling::AsIs,
)) ))
.await?; .await?;

@ -91,6 +91,10 @@ where
W: Write, W: Write,
{ {
pub fn new(buffer: W, config: &EditorConfig) -> CrosstermBackend<W> { pub fn new(buffer: W, config: &EditorConfig) -> CrosstermBackend<W> {
// helix is not usable without colors, but crossterm will disable
// them by default if NO_COLOR is set in the environment. Override
// this behaviour.
crossterm::style::force_color_output(true);
CrosstermBackend { CrosstermBackend {
buffer, buffer,
capabilities: Capabilities::from_env_or_default(config), capabilities: Capabilities::from_env_or_default(config),

@ -4,6 +4,7 @@ use helix_core::unicode::width::UnicodeWidthStr;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
const NBSP: &str = "\u{00a0}"; const NBSP: &str = "\u{00a0}";
const NNBSP: &str = "\u{202f}";
/// A state machine to pack styled symbols into lines. /// A state machine to pack styled symbols into lines.
/// Cannot implement it as Iterator since it yields slices of the internal buffer (need streaming /// Cannot implement it as Iterator since it yields slices of the internal buffer (need streaming
@ -58,7 +59,8 @@ impl<'a, 'b> LineComposer<'a> for WordWrapper<'a, 'b> {
let mut symbols_exhausted = true; let mut symbols_exhausted = true;
for StyledGrapheme { symbol, style } in &mut self.symbols { for StyledGrapheme { symbol, style } in &mut self.symbols {
symbols_exhausted = false; symbols_exhausted = false;
let symbol_whitespace = symbol.chars().all(&char::is_whitespace) && symbol != NBSP; let symbol_whitespace =
symbol.chars().all(&char::is_whitespace) && symbol != NBSP && symbol != NNBSP;
// Ignore characters wider that the total max width. // Ignore characters wider that the total max width.
if symbol.width() as u16 > self.max_line_width if symbol.width() as u16 > self.max_line_width
@ -496,6 +498,20 @@ mod test {
assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]); assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]);
} }
#[test]
fn line_composer_word_wrapper_nnbsp() {
let width = 20;
let text = "AAAAAAAAAAAAAAA AAAA\u{202f}AAA";
let (word_wrapper, _) = run_composer(Composer::WordWrapper { trim: true }, text, width);
assert_eq!(word_wrapper, vec!["AAAAAAAAAAAAAAA", "AAAA\u{202f}AAA",]);
// Ensure that if the character was a regular space, it would be wrapped differently.
let text_space = text.replace('\u{202f}', " ");
let (word_wrapper_space, _) =
run_composer(Composer::WordWrapper { trim: true }, &text_space, width);
assert_eq!(word_wrapper_space, vec!["AAAAAAAAAAAAAAA AAAA", "AAA",]);
}
#[test] #[test]
fn line_composer_word_wrapper_preserve_indentation() { fn line_composer_word_wrapper_preserve_indentation() {
let width = 20; let width = 20;

@ -17,9 +17,9 @@ helix-event = { path = "../helix-event" }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "parking_lot", "macros"] } tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "parking_lot", "macros"] }
parking_lot = "0.12" parking_lot = "0.12"
arc-swap = { version = "1.7.0" } arc-swap = { version = "1.7.1" }
gix = { version = "0.61.0", features = ["attributes"], default-features = false, optional = true } gix = { version = "0.62.0", features = ["attributes", "status"], default-features = false, optional = true }
imara-diff = "0.1.5" imara-diff = "0.1.5"
anyhow = "1" anyhow = "1"

@ -5,19 +5,77 @@ use std::io::Read;
use std::path::Path; use std::path::Path;
use std::sync::Arc; use std::sync::Arc;
use gix::bstr::ByteSlice;
use gix::diff::Rewrites;
use gix::dir::entry::Status;
use gix::objs::tree::EntryKind; use gix::objs::tree::EntryKind;
use gix::sec::trust::DefaultForLevel; use gix::sec::trust::DefaultForLevel;
use gix::status::{
index_worktree::iter::Item,
plumbing::index_as_worktree::{Change, EntryStatus},
UntrackedFiles,
};
use gix::{Commit, ObjectId, Repository, ThreadSafeRepository}; use gix::{Commit, ObjectId, Repository, ThreadSafeRepository};
use crate::DiffProvider; use crate::FileChange;
#[cfg(test)] #[cfg(test)]
mod test; mod test;
pub struct Git; pub fn get_diff_base(file: &Path) -> Result<Vec<u8>> {
debug_assert!(!file.exists() || file.is_file());
debug_assert!(file.is_absolute());
// TODO cache repository lookup
let repo_dir = file.parent().context("file has no parent directory")?;
let repo = open_repo(repo_dir)
.context("failed to open git repo")?
.to_thread_local();
let head = repo.head_commit()?;
let file_oid = find_file_in_commit(&repo, &head, file)?;
impl Git { let file_object = repo.find_object(file_oid)?;
fn open_repo(path: &Path, ceiling_dir: Option<&Path>) -> Result<ThreadSafeRepository> { let data = file_object.detach().data;
// Get the actual data that git would make out of the git object.
// This will apply the user's git config or attributes like crlf conversions.
if let Some(work_dir) = repo.work_dir() {
let rela_path = file.strip_prefix(work_dir)?;
let rela_path = gix::path::try_into_bstr(rela_path)?;
let (mut pipeline, _) = repo.filter_pipeline(None)?;
let mut worktree_outcome =
pipeline.convert_to_worktree(&data, rela_path.as_ref(), Delay::Forbid)?;
let mut buf = Vec::with_capacity(data.len());
worktree_outcome.read_to_end(&mut buf)?;
Ok(buf)
} else {
Ok(data)
}
}
pub fn get_current_head_name(file: &Path) -> Result<Arc<ArcSwap<Box<str>>>> {
debug_assert!(!file.exists() || file.is_file());
debug_assert!(file.is_absolute());
let repo_dir = file.parent().context("file has no parent directory")?;
let repo = open_repo(repo_dir)
.context("failed to open git repo")?
.to_thread_local();
let head_ref = repo.head_ref()?;
let head_commit = repo.head_commit()?;
let name = match head_ref {
Some(reference) => reference.name().shorten().to_string(),
None => head_commit.id.to_hex_with_len(8).to_string(),
};
Ok(Arc::new(ArcSwap::from_pointee(name.into_boxed_str())))
}
pub fn for_each_changed_file(cwd: &Path, f: impl Fn(Result<FileChange>) -> bool) -> Result<()> {
status(&open_repo(cwd)?.to_thread_local(), f)
}
fn open_repo(path: &Path) -> Result<ThreadSafeRepository> {
// custom open options // custom open options
let mut git_open_opts_map = gix::sec::trust::Mapping::<gix::open::Options>::default(); let mut git_open_opts_map = gix::sec::trust::Mapping::<gix::open::Options>::default();
@ -46,9 +104,6 @@ impl Git {
}); });
let open_options = gix::discover::upwards::Options { let open_options = gix::discover::upwards::Options {
ceiling_dirs: ceiling_dir
.map(|dir| vec![dir.to_owned()])
.unwrap_or_default(),
dot_git_only: true, dot_git_only: true,
..Default::default() ..Default::default()
}; };
@ -60,58 +115,73 @@ impl Git {
)?; )?;
Ok(res) Ok(res)
}
} }
impl DiffProvider for Git { /// Emulates the result of running `git status` from the command line.
fn get_diff_base(&self, file: &Path) -> Result<Vec<u8>> { fn status(repo: &Repository, f: impl Fn(Result<FileChange>) -> bool) -> Result<()> {
debug_assert!(!file.exists() || file.is_file()); let work_dir = repo
debug_assert!(file.is_absolute()); .work_dir()
.ok_or_else(|| anyhow::anyhow!("working tree not found"))?
// TODO cache repository lookup .to_path_buf();
let repo_dir = file.parent().context("file has no parent directory")?; let status_platform = repo
let repo = Git::open_repo(repo_dir, None) .status(gix::progress::Discard)?
.context("failed to open git repo")? // Here we discard the `status.showUntrackedFiles` config, as it makes little sense in
.to_thread_local(); // our case to not list new (untracked) files. We could have respected this config
let head = repo.head_commit()?; // if the default value weren't `Collapsed` though, as this default value would render
let file_oid = find_file_in_commit(&repo, &head, file)?; // the feature unusable to many.
.untracked_files(UntrackedFiles::Files)
let file_object = repo.find_object(file_oid)?; // Turn on file rename detection, which is off by default.
let data = file_object.detach().data; .index_worktree_rewrites(Some(Rewrites {
// Get the actual data that git would make out of the git object. copies: None,
// This will apply the user's git config or attributes like crlf conversions. percentage: Some(0.5),
if let Some(work_dir) = repo.work_dir() { limit: 1000,
let rela_path = file.strip_prefix(work_dir)?; }));
let rela_path = gix::path::try_into_bstr(rela_path)?;
let (mut pipeline, _) = repo.filter_pipeline(None)?; // No filtering based on path
let mut worktree_outcome = let empty_patterns = vec![];
pipeline.convert_to_worktree(&data, rela_path.as_ref(), Delay::Forbid)?;
let mut buf = Vec::with_capacity(data.len()); let status_iter = status_platform.into_index_worktree_iter(empty_patterns)?;
worktree_outcome.read_to_end(&mut buf)?;
Ok(buf) for item in status_iter {
} else { let Ok(item) = item.map_err(|err| f(Err(err.into()))) else {
Ok(data) continue;
};
let change = match item {
Item::Modification {
rela_path, status, ..
} => {
let path = work_dir.join(rela_path.to_path()?);
match status {
EntryStatus::Conflict(_) => FileChange::Conflict { path },
EntryStatus::Change(Change::Removed) => FileChange::Deleted { path },
EntryStatus::Change(Change::Modification { .. }) => {
FileChange::Modified { path }
} }
_ => continue,
} }
}
fn get_current_head_name(&self, file: &Path) -> Result<Arc<ArcSwap<Box<str>>>> { Item::DirectoryContents { entry, .. } if entry.status == Status::Untracked => {
debug_assert!(!file.exists() || file.is_file()); FileChange::Untracked {
debug_assert!(file.is_absolute()); path: work_dir.join(entry.rela_path.to_path()?),
let repo_dir = file.parent().context("file has no parent directory")?; }
let repo = Git::open_repo(repo_dir, None) }
.context("failed to open git repo")? Item::Rewrite {
.to_thread_local(); source,
let head_ref = repo.head_ref()?; dirwalk_entry,
let head_commit = repo.head_commit()?; ..
} => FileChange::Renamed {
let name = match head_ref { from_path: work_dir.join(source.rela_path().to_path()?),
Some(reference) => reference.name().shorten().to_string(), to_path: work_dir.join(dirwalk_entry.rela_path.to_path()?),
None => head_commit.id.to_hex_with_len(8).to_string(), },
_ => continue,
}; };
if !f(Ok(change)) {
Ok(Arc::new(ArcSwap::from_pointee(name.into_boxed_str()))) break;
} }
}
Ok(())
} }
/// Finds the object that contains the contents of a file at a specific commit. /// Finds the object that contains the contents of a file at a specific commit.

@ -2,7 +2,7 @@ use std::{fs::File, io::Write, path::Path, process::Command};
use tempfile::TempDir; use tempfile::TempDir;
use crate::{DiffProvider, Git}; use crate::git;
fn exec_git_cmd(args: &str, git_dir: &Path) { fn exec_git_cmd(args: &str, git_dir: &Path) {
let res = Command::new("git") let res = Command::new("git")
@ -54,7 +54,7 @@ fn missing_file() {
let file = temp_git.path().join("file.txt"); let file = temp_git.path().join("file.txt");
File::create(&file).unwrap().write_all(b"foo").unwrap(); File::create(&file).unwrap().write_all(b"foo").unwrap();
assert!(Git.get_diff_base(&file).is_err()); assert!(git::get_diff_base(&file).is_err());
} }
#[test] #[test]
@ -64,7 +64,7 @@ fn unmodified_file() {
let contents = b"foo".as_slice(); let contents = b"foo".as_slice();
File::create(&file).unwrap().write_all(contents).unwrap(); File::create(&file).unwrap().write_all(contents).unwrap();
create_commit(temp_git.path(), true); create_commit(temp_git.path(), true);
assert_eq!(Git.get_diff_base(&file).unwrap(), Vec::from(contents)); assert_eq!(git::get_diff_base(&file).unwrap(), Vec::from(contents));
} }
#[test] #[test]
@ -76,7 +76,7 @@ fn modified_file() {
create_commit(temp_git.path(), true); create_commit(temp_git.path(), true);
File::create(&file).unwrap().write_all(b"bar").unwrap(); File::create(&file).unwrap().write_all(b"bar").unwrap();
assert_eq!(Git.get_diff_base(&file).unwrap(), Vec::from(contents)); assert_eq!(git::get_diff_base(&file).unwrap(), Vec::from(contents));
} }
/// Test that `get_file_head` does not return content for a directory. /// Test that `get_file_head` does not return content for a directory.
@ -95,7 +95,7 @@ fn directory() {
std::fs::remove_dir_all(&dir).unwrap(); std::fs::remove_dir_all(&dir).unwrap();
File::create(&dir).unwrap().write_all(b"bar").unwrap(); File::create(&dir).unwrap().write_all(b"bar").unwrap();
assert!(Git.get_diff_base(&dir).is_err()); assert!(git::get_diff_base(&dir).is_err());
} }
/// Test that `get_file_head` does not return content for a symlink. /// Test that `get_file_head` does not return content for a symlink.
@ -116,6 +116,6 @@ fn symlink() {
symlink("file.txt", &file_link).unwrap(); symlink("file.txt", &file_link).unwrap();
create_commit(temp_git.path(), true); create_commit(temp_git.path(), true);
assert!(Git.get_diff_base(&file_link).is_err()); assert!(git::get_diff_base(&file_link).is_err());
assert_eq!(Git.get_diff_base(&file).unwrap(), Vec::from(contents)); assert_eq!(git::get_diff_base(&file).unwrap(), Vec::from(contents));
} }

@ -1,11 +1,9 @@
use anyhow::{bail, Result}; use anyhow::{anyhow, bail, Result};
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use std::{path::Path, sync::Arc}; use std::{
path::{Path, PathBuf},
#[cfg(feature = "git")] sync::Arc,
pub use git::Git; };
#[cfg(not(feature = "git"))]
pub use Dummy as Git;
#[cfg(feature = "git")] #[cfg(feature = "git")]
mod git; mod git;
@ -14,29 +12,13 @@ mod diff;
pub use diff::{DiffHandle, Hunk}; pub use diff::{DiffHandle, Hunk};
pub trait DiffProvider { mod status;
/// Returns the data that a diff should be computed against
/// if this provider is used.
/// The data is returned as raw byte without any decoding or encoding performed
/// to ensure all file encodings are handled correctly.
fn get_diff_base(&self, file: &Path) -> Result<Vec<u8>>;
fn get_current_head_name(&self, file: &Path) -> Result<Arc<ArcSwap<Box<str>>>>;
}
#[doc(hidden)]
pub struct Dummy;
impl DiffProvider for Dummy {
fn get_diff_base(&self, _file: &Path) -> Result<Vec<u8>> {
bail!("helix was compiled without git support")
}
fn get_current_head_name(&self, _file: &Path) -> Result<Arc<ArcSwap<Box<str>>>> { pub use status::FileChange;
bail!("helix was compiled without git support")
}
}
#[derive(Clone)]
pub struct DiffProviderRegistry { pub struct DiffProviderRegistry {
providers: Vec<Box<dyn DiffProvider>>, providers: Vec<DiffProvider>,
} }
impl DiffProviderRegistry { impl DiffProviderRegistry {
@ -46,8 +28,8 @@ impl DiffProviderRegistry {
.find_map(|provider| match provider.get_diff_base(file) { .find_map(|provider| match provider.get_diff_base(file) {
Ok(res) => Some(res), Ok(res) => Some(res),
Err(err) => { Err(err) => {
log::info!("{err:#?}"); log::debug!("{err:#?}");
log::info!("failed to open diff base for {}", file.display()); log::debug!("failed to open diff base for {}", file.display());
None None
} }
}) })
@ -59,20 +41,82 @@ impl DiffProviderRegistry {
.find_map(|provider| match provider.get_current_head_name(file) { .find_map(|provider| match provider.get_current_head_name(file) {
Ok(res) => Some(res), Ok(res) => Some(res),
Err(err) => { Err(err) => {
log::info!("{err:#?}"); log::debug!("{err:#?}");
log::info!("failed to obtain current head name for {}", file.display()); log::debug!("failed to obtain current head name for {}", file.display());
None None
} }
}) })
} }
/// Fire-and-forget changed file iteration. Runs everything in a background task. Keeps
/// iteration until `on_change` returns `false`.
pub fn for_each_changed_file(
self,
cwd: PathBuf,
f: impl Fn(Result<FileChange>) -> bool + Send + 'static,
) {
tokio::task::spawn_blocking(move || {
if self
.providers
.iter()
.find_map(|provider| provider.for_each_changed_file(&cwd, &f).ok())
.is_none()
{
f(Err(anyhow!("no diff provider returns success")));
}
});
}
} }
impl Default for DiffProviderRegistry { impl Default for DiffProviderRegistry {
fn default() -> Self { fn default() -> Self {
// currently only git is supported // currently only git is supported
// TODO make this configurable when more providers are added // TODO make this configurable when more providers are added
let git: Box<dyn DiffProvider> = Box::new(Git); let providers = vec![
let providers = vec![git]; #[cfg(feature = "git")]
DiffProvider::Git,
];
DiffProviderRegistry { providers } DiffProviderRegistry { providers }
} }
} }
/// A union type that includes all types that implement [DiffProvider]. We need this type to allow
/// cloning [DiffProviderRegistry] as `Clone` cannot be used in trait objects.
///
/// `Copy` is simply to ensure the `clone()` call is the simplest it can be.
#[derive(Copy, Clone)]
pub enum DiffProvider {
#[cfg(feature = "git")]
Git,
None,
}
impl DiffProvider {
fn get_diff_base(&self, file: &Path) -> Result<Vec<u8>> {
match self {
#[cfg(feature = "git")]
Self::Git => git::get_diff_base(file),
Self::None => bail!("No diff support compiled in"),
}
}
fn get_current_head_name(&self, file: &Path) -> Result<Arc<ArcSwap<Box<str>>>> {
match self {
#[cfg(feature = "git")]
Self::Git => git::get_current_head_name(file),
Self::None => bail!("No diff support compiled in"),
}
}
fn for_each_changed_file(
&self,
cwd: &Path,
f: impl Fn(Result<FileChange>) -> bool,
) -> Result<()> {
match self {
#[cfg(feature = "git")]
Self::Git => git::for_each_changed_file(cwd, f),
Self::None => bail!("No diff support compiled in"),
}
}
}

@ -0,0 +1,32 @@
use std::path::{Path, PathBuf};
pub enum FileChange {
Untracked {
path: PathBuf,
},
Modified {
path: PathBuf,
},
Conflict {
path: PathBuf,
},
Deleted {
path: PathBuf,
},
Renamed {
from_path: PathBuf,
to_path: PathBuf,
},
}
impl FileChange {
pub fn path(&self) -> &Path {
match self {
Self::Untracked { path } => path,
Self::Modified { path } => path,
Self::Conflict { path } => path,
Self::Deleted { path } => path,
Self::Renamed { to_path, .. } => to_path,
}
}
}

@ -27,11 +27,13 @@ bitflags = "2.5"
anyhow = "1" anyhow = "1"
crossterm = { version = "0.27", optional = true } crossterm = { version = "0.27", optional = true }
tempfile = "3.9"
# Conversion traits # Conversion traits
once_cell = "1.19" once_cell = "1.19"
url = "2.5.0" url = "2.5.0"
arc-swap = { version = "1.7.0" } arc-swap = { version = "1.7.1" }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot"] } tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot"] }
tokio-stream = "0.1" tokio-stream = "0.1"

@ -156,7 +156,7 @@ pub mod provider {
#[cfg(feature = "term")] #[cfg(feature = "term")]
mod osc52 { mod osc52 {
use {super::ClipboardType, crate::base64, crossterm}; use {super::ClipboardType, crate::base64};
#[derive(Debug)] #[derive(Debug)]
pub struct SetClipboardCommand { pub struct SetClipboardCommand {
@ -255,7 +255,7 @@ pub mod provider {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub mod command { pub mod command {
use super::*; use super::*;
use anyhow::{bail, Context as _, Result}; use anyhow::{bail, Context as _};
#[cfg(not(any(windows, target_os = "macos")))] #[cfg(not(any(windows, target_os = "macos")))]
pub fn is_exit_success(program: &str, args: &[&str]) -> bool { pub fn is_exit_success(program: &str, args: &[&str]) -> bool {

@ -8,8 +8,9 @@ use helix_core::chars::char_is_word;
use helix_core::doc_formatter::TextFormat; use helix_core::doc_formatter::TextFormat;
use helix_core::encoding::Encoding; use helix_core::encoding::Encoding;
use helix_core::syntax::{Highlight, LanguageServerFeature}; use helix_core::syntax::{Highlight, LanguageServerFeature};
use helix_core::text_annotations::{InlineAnnotation, TextAnnotations}; use helix_core::text_annotations::{InlineAnnotation, Overlay};
use helix_lsp::util::lsp_pos_to_pos; use helix_lsp::util::lsp_pos_to_pos;
use helix_stdx::faccess::{copy_metadata, readonly};
use helix_vcs::{DiffHandle, DiffProviderRegistry}; use helix_vcs::{DiffHandle, DiffProviderRegistry};
use ::parking_lot::Mutex; use ::parking_lot::Mutex;
@ -21,7 +22,6 @@ use std::collections::HashMap;
use std::fmt::Display; use std::fmt::Display;
use std::future::Future; use std::future::Future;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::str::FromStr; use std::str::FromStr;
use std::sync::{Arc, Weak}; use std::sync::{Arc, Weak};
use std::time::SystemTime; use std::time::SystemTime;
@ -126,6 +126,7 @@ pub struct Document {
/// ///
/// To know if they're up-to-date, check the `id` field in `DocumentInlayHints`. /// To know if they're up-to-date, check the `id` field in `DocumentInlayHints`.
pub(crate) inlay_hints: HashMap<ViewId, DocumentInlayHints>, pub(crate) inlay_hints: HashMap<ViewId, DocumentInlayHints>,
pub(crate) jump_labels: HashMap<ViewId, Vec<Overlay>>,
/// Set to `true` when the document is updated, reset to `false` on the next inlay hints /// Set to `true` when the document is updated, reset to `false` on the next inlay hints
/// update from the LSP /// update from the LSP
pub inlay_hints_oudated: bool, pub inlay_hints_oudated: bool,
@ -200,22 +201,22 @@ pub struct DocumentInlayHints {
pub id: DocumentInlayHintsId, pub id: DocumentInlayHintsId,
/// Inlay hints of `TYPE` kind, if any. /// Inlay hints of `TYPE` kind, if any.
pub type_inlay_hints: Rc<[InlineAnnotation]>, pub type_inlay_hints: Vec<InlineAnnotation>,
/// Inlay hints of `PARAMETER` kind, if any. /// Inlay hints of `PARAMETER` kind, if any.
pub parameter_inlay_hints: Rc<[InlineAnnotation]>, pub parameter_inlay_hints: Vec<InlineAnnotation>,
/// Inlay hints that are neither `TYPE` nor `PARAMETER`. /// Inlay hints that are neither `TYPE` nor `PARAMETER`.
/// ///
/// LSPs are not required to associate a kind to their inlay hints, for example Rust-Analyzer /// LSPs are not required to associate a kind to their inlay hints, for example Rust-Analyzer
/// currently never does (February 2023) and the LSP spec may add new kinds in the future that /// currently never does (February 2023) and the LSP spec may add new kinds in the future that
/// we want to display even if we don't have some special highlighting for them. /// we want to display even if we don't have some special highlighting for them.
pub other_inlay_hints: Rc<[InlineAnnotation]>, pub other_inlay_hints: Vec<InlineAnnotation>,
/// Inlay hint padding. When creating the final `TextAnnotations`, the `before` padding must be /// Inlay hint padding. When creating the final `TextAnnotations`, the `before` padding must be
/// added first, then the regular inlay hints, then the `after` padding. /// added first, then the regular inlay hints, then the `after` padding.
pub padding_before_inlay_hints: Rc<[InlineAnnotation]>, pub padding_before_inlay_hints: Vec<InlineAnnotation>,
pub padding_after_inlay_hints: Rc<[InlineAnnotation]>, pub padding_after_inlay_hints: Vec<InlineAnnotation>,
} }
impl DocumentInlayHints { impl DocumentInlayHints {
@ -223,11 +224,11 @@ impl DocumentInlayHints {
pub fn empty_with_id(id: DocumentInlayHintsId) -> Self { pub fn empty_with_id(id: DocumentInlayHintsId) -> Self {
Self { Self {
id, id,
type_inlay_hints: Rc::new([]), type_inlay_hints: Vec::new(),
parameter_inlay_hints: Rc::new([]), parameter_inlay_hints: Vec::new(),
other_inlay_hints: Rc::new([]), other_inlay_hints: Vec::new(),
padding_before_inlay_hints: Rc::new([]), padding_before_inlay_hints: Vec::new(),
padding_after_inlay_hints: Rc::new([]), padding_after_inlay_hints: Vec::new(),
} }
} }
} }
@ -623,7 +624,7 @@ where
*mut_ref = f(mem::take(mut_ref)); *mut_ref = f(mem::take(mut_ref));
} }
use helix_lsp::{lsp, Client, LanguageServerName}; use helix_lsp::{lsp, Client, LanguageServerId, LanguageServerName};
use url::Url; use url::Url;
impl Document { impl Document {
@ -666,6 +667,7 @@ impl Document {
version_control_head: None, version_control_head: None,
focused_at: std::time::Instant::now(), focused_at: std::time::Instant::now(),
readonly: false, readonly: false,
jump_labels: HashMap::new(),
} }
} }
@ -869,7 +871,7 @@ impl Document {
// We encode the file according to the `Document`'s encoding. // We encode the file according to the `Document`'s encoding.
let future = async move { let future = async move {
use tokio::{fs, fs::File}; use tokio::fs;
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
// TODO: display a prompt asking the user if the directories should be created // TODO: display a prompt asking the user if the directories should be created
if !parent.exists() { if !parent.exists() {
@ -891,9 +893,66 @@ impl Document {
} }
} }
} }
let write_path = tokio::fs::read_link(&path)
.await
.unwrap_or_else(|_| path.clone());
if readonly(&write_path) {
bail!(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"Path is read only"
));
}
let backup = if path.exists() {
let path_ = write_path.clone();
// hacks: we use tempfile to handle the complex task of creating
// non clobbered temporary path for us we don't want
// the whole automatically delete path on drop thing
// since the path doesn't exist yet, we just want
// the path
tokio::task::spawn_blocking(move || -> Option<PathBuf> {
tempfile::Builder::new()
.prefix(path_.file_name()?)
.suffix(".bck")
.make_in(path_.parent()?, |backup| std::fs::rename(&path_, backup))
.ok()?
.into_temp_path()
.keep()
.ok()
})
.await
.ok()
.flatten()
} else {
None
};
let write_result: anyhow::Result<_> = async {
let mut dst = tokio::fs::File::create(&write_path).await?;
to_writer(&mut dst, encoding_with_bom_info, &text).await?;
Ok(())
}
.await;
let mut file = File::create(&path).await?; if let Some(backup) = backup {
to_writer(&mut file, encoding_with_bom_info, &text).await?; if write_result.is_err() {
// restore backup
let _ = tokio::fs::rename(&backup, &write_path)
.await
.map_err(|e| log::error!("Failed to restore backup on write failure: {e}"));
} else {
// copy metadata and delete backup
let _ = tokio::task::spawn_blocking(move || {
let _ = copy_metadata(&backup, &write_path)
.map_err(|e| log::error!("Failed to copy metadata on write: {e}"));
let _ = std::fs::remove_file(backup)
.map_err(|e| log::error!("Failed to remove backup file on write: {e}"));
})
.await;
}
}
write_result?;
let event = DocumentSavedEvent { let event = DocumentSavedEvent {
revision: current_rev, revision: current_rev,
@ -904,13 +963,14 @@ impl Document {
for (_, language_server) in language_servers { for (_, language_server) in language_servers {
if !language_server.is_initialized() { if !language_server.is_initialized() {
return Ok(event); continue;
} }
if let Some(identifier) = &identifier { if let Some(notification) = identifier
if let Some(notification) = .clone()
language_server.text_document_did_save(identifier.clone(), &text) .and_then(|id| language_server.text_document_did_save(id, &text))
{ {
notification.await?; if let Err(err) = notification.await {
log::error!("Failed to send textDocument/didSave: {err}");
} }
} }
} }
@ -954,35 +1014,12 @@ impl Document {
} }
} }
#[cfg(unix)]
// Detect if the file is readonly and change the readonly field if necessary (unix only) // Detect if the file is readonly and change the readonly field if necessary (unix only)
pub fn detect_readonly(&mut self) { pub fn detect_readonly(&mut self) {
use rustix::fs::{access, Access};
// Allows setting the flag for files the user cannot modify, like root files // Allows setting the flag for files the user cannot modify, like root files
self.readonly = match &self.path { self.readonly = match &self.path {
None => false, None => false,
Some(p) => match access(p, Access::WRITE_OK) { Some(p) => readonly(p),
Ok(_) => false,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
Err(_) => true,
},
};
}
#[cfg(not(unix))]
// Detect if the file is readonly and change the readonly field if necessary (non-unix os)
pub fn detect_readonly(&mut self) {
// TODO Use the Windows' function `CreateFileW` to check if a file is readonly
// Discussion: https://github.com/helix-editor/helix/pull/7740#issuecomment-1656806459
// Vim implementation: https://github.com/vim/vim/blob/4c0089d696b8d1d5dc40568f25ea5738fa5bbffb/src/os_win32.c#L7665
// Windows binding: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Storage/FileSystem/fn.CreateFileW.html
self.readonly = match &self.path {
None => false,
Some(p) => match std::fs::metadata(p) {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => false,
Err(_) => false,
Ok(metadata) => metadata.permissions().readonly(),
},
}; };
} }
@ -1139,6 +1176,7 @@ impl Document {
pub fn remove_view(&mut self, view_id: ViewId) { pub fn remove_view(&mut self, view_id: ViewId) {
self.selections.remove(&view_id); self.selections.remove(&view_id);
self.inlay_hints.remove(&view_id); self.inlay_hints.remove(&view_id);
self.jump_labels.remove(&view_id);
} }
/// Apply a [`Transaction`] to the [`Document`] to change its text. /// Apply a [`Transaction`] to the [`Document`] to change its text.
@ -1258,21 +1296,16 @@ impl Document {
}); });
self.diagnostics.sort_unstable_by_key(|diagnostic| { self.diagnostics.sort_unstable_by_key(|diagnostic| {
( (diagnostic.range, diagnostic.severity, diagnostic.provider)
diagnostic.range,
diagnostic.severity,
diagnostic.language_server_id,
)
}); });
// Update the inlay hint annotations' positions, helping ensure they are displayed in the proper place // Update the inlay hint annotations' positions, helping ensure they are displayed in the proper place
let apply_inlay_hint_changes = |annotations: &mut Rc<[InlineAnnotation]>| { let apply_inlay_hint_changes = |annotations: &mut Vec<InlineAnnotation>| {
if let Some(data) = Rc::get_mut(annotations) {
changes.update_positions( changes.update_positions(
data.iter_mut() annotations
.iter_mut()
.map(|annotation| (&mut annotation.char_idx, Assoc::After)), .map(|annotation| (&mut annotation.char_idx, Assoc::After)),
); );
}
}; };
self.inlay_hints_oudated = true; self.inlay_hints_oudated = true;
@ -1607,7 +1640,7 @@ impl Document {
}) })
} }
pub fn supports_language_server(&self, id: usize) -> bool { pub fn supports_language_server(&self, id: LanguageServerId) -> bool {
self.language_servers().any(|l| l.id() == id) self.language_servers().any(|l| l.id() == id)
} }
@ -1730,7 +1763,7 @@ impl Document {
text: &Rope, text: &Rope,
language_config: Option<&LanguageConfiguration>, language_config: Option<&LanguageConfiguration>,
diagnostic: &helix_lsp::lsp::Diagnostic, diagnostic: &helix_lsp::lsp::Diagnostic,
language_server_id: usize, language_server_id: LanguageServerId,
offset_encoding: helix_lsp::OffsetEncoding, offset_encoding: helix_lsp::OffsetEncoding,
) -> Option<Diagnostic> { ) -> Option<Diagnostic> {
use helix_core::diagnostic::{Range, Severity::*}; use helix_core::diagnostic::{Range, Severity::*};
@ -1807,7 +1840,7 @@ impl Document {
tags, tags,
source: diagnostic.source.clone(), source: diagnostic.source.clone(),
data: diagnostic.data.clone(), data: diagnostic.data.clone(),
language_server_id, provider: language_server_id,
}) })
} }
@ -1820,13 +1853,13 @@ impl Document {
&mut self, &mut self,
diagnostics: impl IntoIterator<Item = Diagnostic>, diagnostics: impl IntoIterator<Item = Diagnostic>,
unchanged_sources: &[String], unchanged_sources: &[String],
language_server_id: Option<usize>, language_server_id: Option<LanguageServerId>,
) { ) {
if unchanged_sources.is_empty() { if unchanged_sources.is_empty() {
self.clear_diagnostics(language_server_id); self.clear_diagnostics(language_server_id);
} else { } else {
self.diagnostics.retain(|d| { self.diagnostics.retain(|d| {
if language_server_id.map_or(false, |id| id != d.language_server_id) { if language_server_id.map_or(false, |id| id != d.provider) {
return true; return true;
} }
@ -1839,18 +1872,14 @@ impl Document {
} }
self.diagnostics.extend(diagnostics); self.diagnostics.extend(diagnostics);
self.diagnostics.sort_unstable_by_key(|diagnostic| { self.diagnostics.sort_unstable_by_key(|diagnostic| {
( (diagnostic.range, diagnostic.severity, diagnostic.provider)
diagnostic.range,
diagnostic.severity,
diagnostic.language_server_id,
)
}); });
} }
/// clears diagnostics for a given language server id if set, otherwise all diagnostics are cleared /// clears diagnostics for a given language server id if set, otherwise all diagnostics are cleared
pub fn clear_diagnostics(&mut self, language_server_id: Option<usize>) { pub fn clear_diagnostics(&mut self, language_server_id: Option<LanguageServerId>) {
if let Some(id) = language_server_id { if let Some(id) = language_server_id {
self.diagnostics.retain(|d| d.language_server_id != id); self.diagnostics.retain(|d| d.provider != id);
} else { } else {
self.diagnostics.clear(); self.diagnostics.clear();
} }
@ -1940,17 +1969,19 @@ impl Document {
} }
} }
/// Get the text annotations that apply to the whole document, those that do not apply to any
/// specific view.
pub fn text_annotations(&self, _theme: Option<&Theme>) -> TextAnnotations {
TextAnnotations::default()
}
/// Set the inlay hints for this document and `view_id`. /// Set the inlay hints for this document and `view_id`.
pub fn set_inlay_hints(&mut self, view_id: ViewId, inlay_hints: DocumentInlayHints) { pub fn set_inlay_hints(&mut self, view_id: ViewId, inlay_hints: DocumentInlayHints) {
self.inlay_hints.insert(view_id, inlay_hints); self.inlay_hints.insert(view_id, inlay_hints);
} }
pub fn set_jump_labels(&mut self, view_id: ViewId, labels: Vec<Overlay>) {
self.jump_labels.insert(view_id, labels);
}
pub fn remove_jump_labels(&mut self, view_id: ViewId) {
self.jump_labels.remove(&view_id);
}
/// Get the inlay hints for this document and `view_id`. /// Get the inlay hints for this document and `view_id`.
pub fn inlay_hints(&self, view_id: ViewId) -> Option<&DocumentInlayHints> { pub fn inlay_hints(&self, view_id: ViewId) -> Option<&DocumentInlayHints> {
self.inlay_hints.get(&view_id) self.inlay_hints.get(&view_id)

@ -16,13 +16,13 @@ use helix_vcs::DiffProviderRegistry;
use futures_util::stream::select_all::SelectAll; use futures_util::stream::select_all::SelectAll;
use futures_util::{future, StreamExt}; use futures_util::{future, StreamExt};
use helix_lsp::Call; use helix_lsp::{Call, LanguageServerId};
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
use std::{ use std::{
borrow::Cow, borrow::Cow,
cell::Cell, cell::Cell,
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap, HashSet},
fs, fs,
io::{self, stdin}, io::{self, stdin},
num::NonZeroUsize, num::NonZeroUsize,
@ -212,6 +212,31 @@ impl Default for FilePickerConfig {
} }
} }
fn serialize_alphabet<S>(alphabet: &[char], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let alphabet: String = alphabet.iter().collect();
serializer.serialize_str(&alphabet)
}
fn deserialize_alphabet<'de, D>(deserializer: D) -> Result<Vec<char>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
let str = String::deserialize(deserializer)?;
let chars: Vec<_> = str.chars().collect();
let unique_chars: HashSet<_> = chars.iter().copied().collect();
if unique_chars.len() != chars.len() {
return Err(<D::Error as Error>::custom(
"jump-label-alphabet must contain unique characters",
));
}
Ok(chars)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", default, deny_unknown_fields)] #[serde(rename_all = "kebab-case", default, deny_unknown_fields)]
pub struct Config { pub struct Config {
@ -305,6 +330,12 @@ pub struct Config {
/// Which indent heuristic to use when a new line is inserted /// Which indent heuristic to use when a new line is inserted
#[serde(default)] #[serde(default)]
pub indent_heuristic: IndentationHeuristic, pub indent_heuristic: IndentationHeuristic,
/// labels characters used in jumpmode
#[serde(
serialize_with = "serialize_alphabet",
deserialize_with = "deserialize_alphabet"
)]
pub jump_label_alphabet: Vec<char>,
} }
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Eq, PartialOrd, Ord)]
@ -682,6 +713,7 @@ pub enum WhitespaceRender {
default: Option<WhitespaceRenderValue>, default: Option<WhitespaceRenderValue>,
space: Option<WhitespaceRenderValue>, space: Option<WhitespaceRenderValue>,
nbsp: Option<WhitespaceRenderValue>, nbsp: Option<WhitespaceRenderValue>,
nnbsp: Option<WhitespaceRenderValue>,
tab: Option<WhitespaceRenderValue>, tab: Option<WhitespaceRenderValue>,
newline: Option<WhitespaceRenderValue>, newline: Option<WhitespaceRenderValue>,
}, },
@ -713,6 +745,14 @@ impl WhitespaceRender {
} }
} }
} }
pub fn nnbsp(&self) -> WhitespaceRenderValue {
match *self {
Self::Basic(val) => val,
Self::Specific { default, nnbsp, .. } => {
nnbsp.or(default).unwrap_or(WhitespaceRenderValue::None)
}
}
}
pub fn tab(&self) -> WhitespaceRenderValue { pub fn tab(&self) -> WhitespaceRenderValue {
match *self { match *self {
Self::Basic(val) => val, Self::Basic(val) => val,
@ -736,6 +776,7 @@ impl WhitespaceRender {
pub struct WhitespaceCharacters { pub struct WhitespaceCharacters {
pub space: char, pub space: char,
pub nbsp: char, pub nbsp: char,
pub nnbsp: char,
pub tab: char, pub tab: char,
pub tabpad: char, pub tabpad: char,
pub newline: char, pub newline: char,
@ -746,6 +787,7 @@ impl Default for WhitespaceCharacters {
Self { Self {
space: '·', // U+00B7 space: '·', // U+00B7
nbsp: '', // U+237D nbsp: '', // U+237D
nnbsp: '', // U+2423
tab: '', // U+2192 tab: '', // U+2192
newline: '', // U+23CE newline: '', // U+23CE
tabpad: ' ', tabpad: ' ',
@ -870,6 +912,7 @@ impl Default for Config {
smart_tab: Some(SmartTabConfig::default()), smart_tab: Some(SmartTabConfig::default()),
popup_border: PopupBorderConfig::None, popup_border: PopupBorderConfig::None,
indent_heuristic: IndentationHeuristic::default(), indent_heuristic: IndentationHeuristic::default(),
jump_label_alphabet: ('a'..='z').collect(),
} }
} }
} }
@ -917,7 +960,7 @@ pub struct Editor {
pub macro_recording: Option<(char, Vec<KeyEvent>)>, pub macro_recording: Option<(char, Vec<KeyEvent>)>,
pub macro_replaying: Vec<char>, pub macro_replaying: Vec<char>,
pub language_servers: helix_lsp::Registry, pub language_servers: helix_lsp::Registry,
pub diagnostics: BTreeMap<PathBuf, Vec<(lsp::Diagnostic, usize)>>, pub diagnostics: BTreeMap<PathBuf, Vec<(lsp::Diagnostic, LanguageServerId)>>,
pub diff_providers: DiffProviderRegistry, pub diff_providers: DiffProviderRegistry,
pub debugger: Option<dap::Client>, pub debugger: Option<dap::Client>,
@ -977,7 +1020,7 @@ pub type Motion = Box<dyn Fn(&mut Editor)>;
pub enum EditorEvent { pub enum EditorEvent {
DocumentSaved(DocumentSavedEventResult), DocumentSaved(DocumentSavedEventResult),
ConfigEvent(ConfigEvent), ConfigEvent(ConfigEvent),
LanguageServerMessage((usize, Call)), LanguageServerMessage((LanguageServerId, Call)),
DebuggerEvent(dap::Payload), DebuggerEvent(dap::Payload),
IdleTimer, IdleTimer,
Redraw, Redraw,
@ -1217,8 +1260,13 @@ impl Editor {
} }
#[inline] #[inline]
pub fn language_server_by_id(&self, language_server_id: usize) -> Option<&helix_lsp::Client> { pub fn language_server_by_id(
self.language_servers.get_by_id(language_server_id) &self,
language_server_id: LanguageServerId,
) -> Option<&helix_lsp::Client> {
self.language_servers
.get_by_id(language_server_id)
.map(|client| &**client)
} }
/// Refreshes the language server for a given document /// Refreshes the language server for a given document
@ -1818,7 +1866,7 @@ impl Editor {
/// Returns all supported diagnostics for the document /// Returns all supported diagnostics for the document
pub fn doc_diagnostics<'a>( pub fn doc_diagnostics<'a>(
language_servers: &'a helix_lsp::Registry, language_servers: &'a helix_lsp::Registry,
diagnostics: &'a BTreeMap<PathBuf, Vec<(lsp::Diagnostic, usize)>>, diagnostics: &'a BTreeMap<PathBuf, Vec<(lsp::Diagnostic, LanguageServerId)>>,
document: &Document, document: &Document,
) -> impl Iterator<Item = helix_core::Diagnostic> + 'a { ) -> impl Iterator<Item = helix_core::Diagnostic> + 'a {
Editor::doc_diagnostics_with_filter(language_servers, diagnostics, document, |_, _| true) Editor::doc_diagnostics_with_filter(language_servers, diagnostics, document, |_, _| true)
@ -1828,10 +1876,9 @@ impl Editor {
/// filtered by `filter` which is invocated with the raw `lsp::Diagnostic` and the language server id it came from /// filtered by `filter` which is invocated with the raw `lsp::Diagnostic` and the language server id it came from
pub fn doc_diagnostics_with_filter<'a>( pub fn doc_diagnostics_with_filter<'a>(
language_servers: &'a helix_lsp::Registry, language_servers: &'a helix_lsp::Registry,
diagnostics: &'a BTreeMap<PathBuf, Vec<(lsp::Diagnostic, usize)>>, diagnostics: &'a BTreeMap<PathBuf, Vec<(lsp::Diagnostic, LanguageServerId)>>,
document: &Document, document: &Document,
filter: impl Fn(&lsp::Diagnostic, usize) -> bool + 'a, filter: impl Fn(&lsp::Diagnostic, LanguageServerId) -> bool + 'a,
) -> impl Iterator<Item = helix_core::Diagnostic> + 'a { ) -> impl Iterator<Item = helix_core::Diagnostic> + 'a {
let text = document.text().clone(); let text = document.text().clone();
let language_config = document.language.clone(); let language_config = document.language.clone();

@ -71,7 +71,7 @@ pub fn diagnostic<'doc>(
d.line == line d.line == line
&& doc && doc
.language_servers_with_feature(LanguageServerFeature::Diagnostics) .language_servers_with_feature(LanguageServerFeature::Diagnostics)
.any(|ls| ls.id() == d.language_server_id) .any(|ls| ls.id() == d.provider)
}); });
diagnostics_on_line.max_by_key(|d| d.severity).map(|d| { diagnostics_on_line.max_by_key(|d| d.severity).map(|d| {
write!(out, "●").ok(); write!(out, "●").ok();

@ -214,33 +214,56 @@ impl Tree {
node node
} }
pub fn remove(&mut self, index: ViewId) { /// Get a mutable reference to a [Container] by index.
let mut stack = Vec::new(); /// # Panics
/// Panics if `index` is not in self.nodes, or if the node's content is not a [Content::Container].
if self.focus == index { fn container_mut(&mut self, index: ViewId) -> &mut Container {
// focus on something else match &mut self.nodes[index] {
self.focus = self.prev(); Node {
content: Content::Container(container),
..
} => container,
_ => unreachable!(),
}
} }
stack.push(index); fn remove_or_replace(&mut self, child: ViewId, replacement: Option<ViewId>) {
let parent = self.nodes[child].parent;
while let Some(index) = stack.pop() { self.nodes.remove(child);
let parent_id = self.nodes[index].parent;
if let Node { let container = self.container_mut(parent);
content: Content::Container(container), let pos = container
.. .children
} = &mut self.nodes[parent_id] .iter()
{ .position(|&item| item == child)
if let Some(pos) = container.children.iter().position(|&child| child == index) { .unwrap();
if let Some(new) = replacement {
container.children[pos] = new;
self.nodes[new].parent = parent;
} else {
container.children.remove(pos); container.children.remove(pos);
// TODO: if container now only has one child, remove it and place child in parent
if container.children.is_empty() && parent_id != self.root {
// if container now empty, remove it
stack.push(parent_id);
} }
} }
pub fn remove(&mut self, index: ViewId) {
if self.focus == index {
// focus on something else
self.focus = self.prev();
} }
self.nodes.remove(index);
let parent = self.nodes[index].parent;
let parent_is_root = parent == self.root;
self.remove_or_replace(index, None);
let parent_container = self.container_mut(parent);
if parent_container.children.len() == 1 && !parent_is_root {
// Lets merge the only child back to its grandparent so that Views
// are equally spaced.
let sibling = parent_container.children.pop().unwrap();
self.remove_or_replace(parent, Some(sibling));
} }
self.recalculate() self.recalculate()
@ -384,11 +407,13 @@ impl Tree {
} }
Layout::Vertical => { Layout::Vertical => {
let len = container.children.len(); let len = container.children.len();
let len_u16 = len as u16;
let width = area.width / len as u16;
let inner_gap = 1u16; let inner_gap = 1u16;
// let total_gap = inner_gap * (len as u16 - 1); let total_gap = inner_gap * len_u16.saturating_sub(2);
let used_area = area.width.saturating_sub(total_gap);
let width = used_area / len_u16;
let mut child_x = area.x; let mut child_x = area.x;
@ -873,4 +898,72 @@ mod test {
assert_eq!(doc_id(&tree, l2), Some(doc_r0)); assert_eq!(doc_id(&tree, l2), Some(doc_r0));
assert_eq!(doc_id(&tree, r0), Some(doc_l0)); assert_eq!(doc_id(&tree, r0), Some(doc_l0));
} }
#[test]
fn all_vertical_views_have_same_width() {
let tree_area_width = 180;
let mut tree = Tree::new(Rect {
x: 0,
y: 0,
width: tree_area_width,
height: 80,
});
let mut view = View::new(DocumentId::default(), GutterConfig::default());
view.area = Rect::new(0, 0, 180, 80);
tree.insert(view);
let view = View::new(DocumentId::default(), GutterConfig::default());
tree.split(view, Layout::Vertical);
let view = View::new(DocumentId::default(), GutterConfig::default());
tree.split(view, Layout::Horizontal);
tree.remove(tree.focus);
let view = View::new(DocumentId::default(), GutterConfig::default());
tree.split(view, Layout::Vertical);
// Make sure that we only have one level in the tree.
assert_eq!(3, tree.views().count());
assert_eq!(
vec![
tree_area_width / 3 - 1, // gap here
tree_area_width / 3 - 1, // gap here
tree_area_width / 3
],
tree.views()
.map(|(view, _)| view.area.width)
.collect::<Vec<_>>()
);
}
#[test]
fn vsplit_gap_rounding() {
let (tree_area_width, tree_area_height) = (80, 24);
let mut tree = Tree::new(Rect {
x: 0,
y: 0,
width: tree_area_width,
height: tree_area_height,
});
let mut view = View::new(DocumentId::default(), GutterConfig::default());
view.area = Rect::new(0, 0, tree_area_width, tree_area_height);
tree.insert(view);
for _ in 0..9 {
let view = View::new(DocumentId::default(), GutterConfig::default());
tree.split(view, Layout::Vertical);
}
assert_eq!(10, tree.views().count());
assert_eq!(
std::iter::repeat(7)
.take(9)
.chain(Some(8)) // Rounding in `recalculate`.
.collect::<Vec<_>>(),
tree.views()
.map(|(view, _)| view.area.width)
.collect::<Vec<_>>()
);
}
} }

@ -19,7 +19,6 @@ use helix_core::{
use std::{ use std::{
collections::{HashMap, VecDeque}, collections::{HashMap, VecDeque},
fmt, fmt,
rc::Rc,
}; };
const JUMP_LIST_CAPACITY: usize = 30; const JUMP_LIST_CAPACITY: usize = 30;
@ -80,7 +79,7 @@ impl JumpList {
self.jumps.retain(|(other_id, _)| other_id != doc_id); self.jumps.retain(|(other_id, _)| other_id != doc_id);
} }
pub fn iter(&self) -> impl Iterator<Item = &Jump> { pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Jump> {
self.jumps.iter() self.jumps.iter()
} }
@ -409,10 +408,19 @@ impl View {
} }
/// Get the text annotations to display in the current view for the given document and theme. /// Get the text annotations to display in the current view for the given document and theme.
pub fn text_annotations(&self, doc: &Document, theme: Option<&Theme>) -> TextAnnotations { pub fn text_annotations<'a>(
// TODO custom annotations for custom views like side by side diffs &self,
doc: &'a Document,
let mut text_annotations = doc.text_annotations(theme); theme: Option<&Theme>,
) -> TextAnnotations<'a> {
let mut text_annotations = TextAnnotations::default();
if let Some(labels) = doc.jump_labels.get(&self.id) {
let style = theme
.and_then(|t| t.find_scope_index("ui.virtual.jump-label"))
.map(Highlight);
text_annotations.add_overlay(labels, style);
}
let DocumentInlayHints { let DocumentInlayHints {
id: _, id: _,
@ -436,20 +444,15 @@ impl View {
.and_then(|t| t.find_scope_index("ui.virtual.inlay-hint")) .and_then(|t| t.find_scope_index("ui.virtual.inlay-hint"))
.map(Highlight); .map(Highlight);
let mut add_annotations = |annotations: &Rc<[_]>, style| {
if !annotations.is_empty() {
text_annotations.add_inline_annotations(Rc::clone(annotations), style);
}
};
// Overlapping annotations are ignored apart from the first so the order here is not random: // Overlapping annotations are ignored apart from the first so the order here is not random:
// types -> parameters -> others should hopefully be the "correct" order for most use cases, // types -> parameters -> others should hopefully be the "correct" order for most use cases,
// with the padding coming before and after as expected. // with the padding coming before and after as expected.
add_annotations(padding_before_inlay_hints, None); text_annotations
add_annotations(type_inlay_hints, type_style); .add_inline_annotations(padding_before_inlay_hints, None)
add_annotations(parameter_inlay_hints, parameter_style); .add_inline_annotations(type_inlay_hints, type_style)
add_annotations(other_inlay_hints, other_style); .add_inline_annotations(parameter_inlay_hints, parameter_style)
add_annotations(padding_after_inlay_hints, None); .add_inline_annotations(other_inlay_hints, other_style)
.add_inline_annotations(padding_after_inlay_hints, None);
text_annotations text_annotations
} }

@ -8,10 +8,12 @@ use-grammars = { except = [ "hare", "wren", "gemini" ] }
als = { command = "als" } als = { command = "als" }
ada-language-server = { command = "ada_language_server" } ada-language-server = { command = "ada_language_server" }
ada-gpr-language-server = {command = "ada_language_server", args = ["--language-gpr"]} ada-gpr-language-server = {command = "ada_language_server", args = ["--language-gpr"]}
angular = {command = "ngserver", args = ["--stdio", "--tsProbeLocations", ".", "--ngProbeLocations", ".",]}
awk-language-server = { command = "awk-language-server" } awk-language-server = { command = "awk-language-server" }
bash-language-server = { command = "bash-language-server", args = ["start"] } bash-language-server = { command = "bash-language-server", args = ["start"] }
bass = { command = "bass", args = ["--lsp"] } bass = { command = "bass", args = ["--lsp"] }
bicep-langserver = { command = "bicep-langserver" } bicep-langserver = { command = "bicep-langserver" }
bitbake-language-server = { command = "bitbake-language-server" }
bufls = { command = "bufls", args = ["serve"] } bufls = { command = "bufls", args = ["serve"] }
cairo-language-server = { command = "cairo-language-server", args = [] } cairo-language-server = { command = "cairo-language-server", args = [] }
cl-lsp = { command = "cl-lsp", args = [ "stdio" ] } cl-lsp = { command = "cl-lsp", args = [ "stdio" ] }
@ -27,6 +29,7 @@ dhall-lsp-server = { command = "dhall-lsp-server" }
docker-langserver = { command = "docker-langserver", args = ["--stdio"] } docker-langserver = { command = "docker-langserver", args = ["--stdio"] }
docker-compose-langserver = { command = "docker-compose-langserver", args = ["--stdio"]} docker-compose-langserver = { command = "docker-compose-langserver", args = ["--stdio"]}
dot-language-server = { command = "dot-language-server", args = ["--stdio"] } dot-language-server = { command = "dot-language-server", args = ["--stdio"] }
earthlyls = { command = "earthlyls" }
elixir-ls = { command = "elixir-ls", config = { elixirLS.dialyzerEnabled = false } } elixir-ls = { command = "elixir-ls", config = { elixirLS.dialyzerEnabled = false } }
elm-language-server = { command = "elm-language-server" } elm-language-server = { command = "elm-language-server" }
elvish = { command = "elvish", args = ["-lsp"] } elvish = { command = "elvish", args = ["-lsp"] }
@ -43,13 +46,14 @@ intelephense = { command = "intelephense", args = ["--stdio"] }
jdtls = { command = "jdtls" } jdtls = { command = "jdtls" }
jsonnet-language-server = { command = "jsonnet-language-server", args= ["-t", "--lint"] } jsonnet-language-server = { command = "jsonnet-language-server", args= ["-t", "--lint"] }
julia = { command = "julia", timeout = 60, args = [ "--startup-file=no", "--history-file=no", "--quiet", "-e", "using LanguageServer; runserver()", ] } julia = { command = "julia", timeout = 60, args = [ "--startup-file=no", "--history-file=no", "--quiet", "-e", "using LanguageServer; runserver()", ] }
koka = { command = "koka", args = ["--language-server", "--lsstdio"] }
kotlin-language-server = { command = "kotlin-language-server" } kotlin-language-server = { command = "kotlin-language-server" }
lean = { command = "lean", args = [ "--server" ] } lean = { command = "lean", args = [ "--server" ] }
ltex-ls = { command = "ltex-ls" } ltex-ls = { command = "ltex-ls" }
markdoc-ls = { command = "markdoc-ls", args = ["--stdio"] } markdoc-ls = { command = "markdoc-ls", args = ["--stdio"] }
markdown-oxide = { command = "markdown-oxide" } markdown-oxide = { command = "markdown-oxide" }
marksman = { command = "marksman", args = ["server"] } marksman = { command = "marksman", args = ["server"] }
metals = { command = "metals", config = { "isHttpEnabled" = true } } metals = { command = "metals", config = { "isHttpEnabled" = true, metals = { inlayHints = { typeParameters = {enable = true} , hintsInPatternMatch = {enable = true} } } } }
mint = { command = "mint", args = ["ls"] } mint = { command = "mint", args = ["ls"] }
nil = { command = "nil" } nil = { command = "nil" }
nimlangserver = { command = "nimlangserver" } nimlangserver = { command = "nimlangserver" }
@ -63,6 +67,7 @@ openscad-lsp = { command = "openscad-lsp", args = ["--stdio"] }
pasls = { command = "pasls", args = [] } pasls = { command = "pasls", args = [] }
pbkit = { command = "pb", args = [ "lsp" ] } pbkit = { command = "pb", args = [ "lsp" ] }
perlnavigator = { command = "perlnavigator", args= ["--stdio"] } perlnavigator = { command = "perlnavigator", args= ["--stdio"] }
pest-language-server = { command = "pest-language-server" }
prisma-language-server = { command = "prisma-language-server", args = ["--stdio"] } prisma-language-server = { command = "prisma-language-server", args = ["--stdio"] }
purescript-language-server = { command = "purescript-language-server", args = ["--stdio"] } purescript-language-server = { command = "purescript-language-server", args = ["--stdio"] }
pylsp = { command = "pylsp" } pylsp = { command = "pylsp" }
@ -98,6 +103,7 @@ yaml-language-server = { command = "yaml-language-server", args = ["--stdio"] }
zls = { command = "zls" } zls = { command = "zls" }
blueprint-compiler = { command = "blueprint-compiler", args = ["lsp"] } blueprint-compiler = { command = "blueprint-compiler", args = ["lsp"] }
typst-lsp = { command = "typst-lsp" } typst-lsp = { command = "typst-lsp" }
tinymist = { command = "tinymist" }
pkgbuild-language-server = { command = "pkgbuild-language-server" } pkgbuild-language-server = { command = "pkgbuild-language-server" }
helm_ls = { command = "helm_ls", args = ["serve"] } helm_ls = { command = "helm_ls", args = ["serve"] }
ember-language-server = { command = "ember-language-server", args = ["--stdio"] } ember-language-server = { command = "ember-language-server", args = ["--stdio"] }
@ -197,6 +203,7 @@ scope = "source.rust"
injection-regex = "rust" injection-regex = "rust"
file-types = ["rs"] file-types = ["rs"]
roots = ["Cargo.toml", "Cargo.lock"] roots = ["Cargo.toml", "Cargo.lock"]
shebangs = ["rust-script", "cargo"]
auto-format = true auto-format = true
comment-tokens = ["//", "///", "//!"] comment-tokens = ["//", "///", "//!"]
block-comment-tokens = [ block-comment-tokens = [
@ -216,9 +223,9 @@ persistent-diagnostic-sources = ["rustc", "clippy"]
'`' = '`' '`' = '`'
[language.debugger] [language.debugger]
name = "lldb-vscode" name = "lldb-dap"
transport = "stdio" transport = "stdio"
command = "lldb-vscode" command = "lldb-dap"
[[language.debugger.templates]] [[language.debugger.templates]]
name = "binary" name = "binary"
@ -246,7 +253,7 @@ args = { attachCommands = [ "platform select remote-gdb-server", "platform conne
[[grammar]] [[grammar]]
name = "rust" name = "rust"
source = { git = "https://github.com/tree-sitter/tree-sitter-rust", rev = "0431a2c60828731f27491ee9fdefe25e250ce9c9" } source = { git = "https://github.com/tree-sitter/tree-sitter-rust", rev = "473634230435c18033384bebaa6d6a17c2523281" }
[[language]] [[language]]
name = "sway" name = "sway"
@ -435,9 +442,9 @@ language-servers = [ "clangd" ]
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
[language.debugger] [language.debugger]
name = "lldb-vscode" name = "lldb-dap"
transport = "stdio" transport = "stdio"
command = "lldb-vscode" command = "lldb-dap"
[[language.debugger.templates]] [[language.debugger.templates]]
name = "binary" name = "binary"
@ -472,9 +479,9 @@ language-servers = [ "clangd" ]
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
[language.debugger] [language.debugger]
name = "lldb-vscode" name = "lldb-dap"
transport = "stdio" transport = "stdio"
command = "lldb-vscode" command = "lldb-dap"
[[language.debugger.templates]] [[language.debugger.templates]]
name = "binary" name = "binary"
@ -667,7 +674,7 @@ name = "javascript"
scope = "source.js" scope = "source.js"
injection-regex = "(js|javascript)" injection-regex = "(js|javascript)"
language-id = "javascript" language-id = "javascript"
file-types = ["js", "mjs", "cjs", "rules", "es6", "pac", { glob = "jakefile" }] file-types = ["js", "mjs", "cjs", "rules", "es6", "pac", { glob = ".node_repl_history" }, { glob = "jakefile" }]
shebangs = ["node"] shebangs = ["node"]
comment-token = "//" comment-token = "//"
block-comment-tokens = { start = "/*", end = "*/" } block-comment-tokens = { start = "/*", end = "*/" }
@ -706,9 +713,9 @@ grammar = "javascript"
name = "typescript" name = "typescript"
scope = "source.ts" scope = "source.ts"
injection-regex = "(ts|typescript)" injection-regex = "(ts|typescript)"
file-types = ["ts", "mts", "cts"]
language-id = "typescript" language-id = "typescript"
shebangs = ["deno", "ts-node"] file-types = ["ts", "mts", "cts"]
shebangs = ["deno", "bun", "ts-node"]
comment-token = "//" comment-token = "//"
block-comment-tokens = { start = "/*", end = "*/" } block-comment-tokens = { start = "/*", end = "*/" }
language-servers = [ "typescript-language-server" ] language-servers = [ "typescript-language-server" ]
@ -779,7 +786,7 @@ source = { git = "https://github.com/tree-sitter/tree-sitter-html", rev = "29f53
name = "python" name = "python"
scope = "source.python" scope = "source.python"
injection-regex = "python" injection-regex = "python"
file-types = ["py", "pyi", "py3", "pyw", "ptl", "rpy", "cpy", "ipy", "pyt", { glob = ".pythonstartup" }, { glob = ".pythonrc" }, { glob = "SConstruct" }, { glob = "SConscript" }] file-types = ["py", "pyi", "py3", "pyw", "ptl", "rpy", "cpy", "ipy", "pyt", { glob = ".python_history" }, { glob = ".pythonstartup" }, { glob = ".pythonrc" }, { glob = "SConstruct" }, { glob = "SConscript" }]
shebangs = ["python"] shebangs = ["python"]
roots = ["pyproject.toml", "setup.py", "poetry.lock", "pyrightconfig.json"] roots = ["pyproject.toml", "setup.py", "poetry.lock", "pyrightconfig.json"]
comment-token = "#" comment-token = "#"
@ -881,6 +888,10 @@ injection-regex = "(shell|bash|zsh|sh)"
file-types = [ file-types = [
"sh", "sh",
"bash", "bash",
"ash",
"dash",
"ksh",
"mksh",
"zsh", "zsh",
"zshenv", "zshenv",
"zlogin", "zlogin",
@ -892,7 +903,6 @@ file-types = [
"bazelrc", "bazelrc",
"Renviron", "Renviron",
"zsh-theme", "zsh-theme",
"ksh",
"cshrc", "cshrc",
"tcshrc", "tcshrc",
"bashrc_Apple_Terminal", "bashrc_Apple_Terminal",
@ -927,7 +937,7 @@ indent = { tab-width = 2, unit = " " }
[[grammar]] [[grammar]]
name = "bash" name = "bash"
source = { git = "https://github.com/tree-sitter/tree-sitter-bash", rev = "275effdfc0edce774acf7d481f9ea195c6c403cd" } source = { git = "https://github.com/tree-sitter/tree-sitter-bash", rev = "f8fb3274f72a30896075585b32b0c54cad65c086" }
[[language]] [[language]]
name = "php" name = "php"
@ -1262,9 +1272,9 @@ indent = { tab-width = 4, unit = " " }
formatter = { command = "zig" , args = ["fmt", "--stdin"] } formatter = { command = "zig" , args = ["fmt", "--stdin"] }
[language.debugger] [language.debugger]
name = "lldb-vscode" name = "lldb-dap"
transport = "stdio" transport = "stdio"
command = "lldb-vscode" command = "lldb-dap"
[[language.debugger.templates]] [[language.debugger.templates]]
name = "binary" name = "binary"
@ -1473,7 +1483,7 @@ source = { git = "https://github.com/Flakebi/tree-sitter-tablegen", rev = "568dd
name = "markdown" name = "markdown"
scope = "source.md" scope = "source.md"
injection-regex = "md|markdown" injection-regex = "md|markdown"
file-types = ["md", "markdown", "mkd", "mdwn", "mdown", "markdn", "mdtxt", "mdtext", "workbook", { glob = "PULLREQ_EDITMSG" }] file-types = ["md", "markdown", "mkd", "mkdn", "mdwn", "mdown", "markdn", "mdtxt", "mdtext", "workbook", { glob = "PULLREQ_EDITMSG" }]
roots = [".marksman.toml"] roots = [".marksman.toml"]
language-servers = [ "marksman", "markdown-oxide" ] language-servers = [ "marksman", "markdown-oxide" ]
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
@ -1481,7 +1491,7 @@ block-comment-tokens = { start = "<!--", end = "-->" }
[[grammar]] [[grammar]]
name = "markdown" name = "markdown"
source = { git = "https://github.com/MDeiml/tree-sitter-markdown", rev = "aaf76797aa8ecd9a5e78e0ec3681941de6c945ee", subpath = "tree-sitter-markdown" } source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-markdown", rev = "62516e8c78380e3b51d5b55727995d2c511436d8", subpath = "tree-sitter-markdown" }
[[language]] [[language]]
name = "markdown.inline" name = "markdown.inline"
@ -1492,7 +1502,7 @@ grammar = "markdown_inline"
[[grammar]] [[grammar]]
name = "markdown_inline" name = "markdown_inline"
source = { git = "https://github.com/MDeiml/tree-sitter-markdown", rev = "aaf76797aa8ecd9a5e78e0ec3681941de6c945ee", subpath = "tree-sitter-markdown-inline" } source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-markdown", rev = "62516e8c78380e3b51d5b55727995d2c511436d8", subpath = "tree-sitter-markdown-inline" }
[[language]] [[language]]
name = "dart" name = "dart"
@ -1634,7 +1644,7 @@ source = { git = "https://github.com/mtoohey31/tree-sitter-gitattributes", rev =
[[language]] [[language]]
name = "git-ignore" name = "git-ignore"
scope = "source.gitignore" scope = "source.gitignore"
file-types = [{ glob = ".gitignore" }, { glob = ".gitignore_global" }, { glob = ".ignore" }, { glob = ".prettierignore" }, { glob = ".eslintignore" }, { glob = ".npmignore"}, { glob = "CODEOWNERS" }, { glob = ".config/helix/ignore" }, { glob = ".helix/ignore" }] file-types = [{ glob = ".gitignore_global" }, { glob = ".ignore" }, { glob = "CODEOWNERS" }, { glob = ".config/helix/ignore" }, { glob = ".helix/ignore" }, { glob = ".*ignore" }]
injection-regex = "git-ignore" injection-regex = "git-ignore"
comment-token = "#" comment-token = "#"
grammar = "gitignore" grammar = "gitignore"
@ -1780,7 +1790,7 @@ language-servers = [ "solc" ]
[[grammar]] [[grammar]]
name = "solidity" name = "solidity"
source = { git = "https://github.com/JoranHonig/tree-sitter-solidity", rev = "9004b86531cb424bd379424cf7266a4585f2af7d" } source = { git = "https://github.com/JoranHonig/tree-sitter-solidity", rev = "08338dcee32603383fcef08f36321900bb7a354b" }
[[language]] [[language]]
name = "gleam" name = "gleam"
@ -2038,13 +2048,36 @@ name = "odin"
auto-format = true auto-format = true
scope = "source.odin" scope = "source.odin"
file-types = ["odin"] file-types = ["odin"]
roots = ["ols.json"] roots = ["ols.json", "main.odin"]
language-servers = [ "ols" ] language-servers = [ "ols" ]
comment-token = "//" comment-token = "//"
block-comment-tokens = { start = "/*", end = "*/" } block-comment-tokens = { start = "/*", end = "*/" }
indent = { tab-width = 4, unit = "\t" } indent = { tab-width = 4, unit = "\t" }
formatter = { command = "odinfmt", args = [ "-stdin", "true" ] } formatter = { command = "odinfmt", args = [ "-stdin", "true" ] }
[language.debugger]
name = "lldb-dap"
transport = "stdio"
command = "lldb-dap"
[[language.debugger.templates]]
name = "binary"
request = "launch"
completion = [ { name = "binary", completion = "filename" } ]
args = { console = "internalConsole", program = "{0}" }
[[language.debugger.templates]]
name = "attach"
request = "attach"
completion = [ "pid" ]
args = { console = "internalConsole", pid = "{0}" }
[[language.debugger.templates]]
name = "gdbserver attach"
request = "attach"
completion = [ { name = "lldb connect url", default = "connect://localhost:3333" }, { name = "file", completion = "filename" }, "pid" ]
args = { console = "internalConsole", attachCommands = [ "platform select remote-gdb-server", "platform connect {0}", "file {1}", "attach {2}" ] }
[[grammar]] [[grammar]]
name = "odin" name = "odin"
source = { git = "https://github.com/ap29600/tree-sitter-odin", rev = "b219207e49ffca2952529d33e94ed63b1b75c4f1" } source = { git = "https://github.com/ap29600/tree-sitter-odin", rev = "b219207e49ffca2952529d33e94ed63b1b75c4f1" }
@ -2053,7 +2086,7 @@ source = { git = "https://github.com/ap29600/tree-sitter-odin", rev = "b219207e4
name = "meson" name = "meson"
scope = "source.meson" scope = "source.meson"
injection-regex = "meson" injection-regex = "meson"
file-types = [{ glob = "meson.build" }, { glob = "meson_options.txt" }] file-types = [{ glob = "meson.build" }, { glob = "meson.options" }, { glob = "meson_options.txt" }]
comment-token = "#" comment-token = "#"
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
@ -2188,7 +2221,7 @@ source = { git = "https://github.com/sogaiu/tree-sitter-clojure", rev = "e57c569
name = "starlark" name = "starlark"
scope = "source.starlark" scope = "source.starlark"
injection-regex = "(starlark|bzl|bazel)" injection-regex = "(starlark|bzl|bazel)"
file-types = ["bzl", "bazel", "star", { glob = "BUILD" }, { glob = "BUILD.*" }] file-types = ["bzl", "bazel", "star", { glob = "BUILD" }, { glob = "BUILD.*" }, { glob = "Tiltfile" }]
comment-token = "#" comment-token = "#"
indent = { tab-width = 4, unit = " " } indent = { tab-width = 4, unit = " " }
grammar = "python" grammar = "python"
@ -3028,6 +3061,7 @@ roots = ["sln", "fsproj"]
injection-regex = "fsharp" injection-regex = "fsharp"
file-types = ["fs", "fsx", "fsi", "fsscript"] file-types = ["fs", "fsx", "fsi", "fsscript"]
comment-token = "//" comment-token = "//"
block-comment-tokens = { start = "(*", end = "*)" }
indent = { tab-width = 4, unit = " " } indent = { tab-width = 4, unit = " " }
auto-format = true auto-format = true
language-servers = ["fsharp-ls"] language-servers = ["fsharp-ls"]
@ -3063,7 +3097,7 @@ scope = "source.typst"
injection-regex = "typst" injection-regex = "typst"
file-types = ["typst", "typ"] file-types = ["typst", "typ"]
comment-token = "//" comment-token = "//"
language-servers = ["typst-lsp"] language-servers = ["tinymist", "typst-lsp"]
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
[language.auto-pairs] [language.auto-pairs]
@ -3075,7 +3109,7 @@ indent = { tab-width = 2, unit = " " }
[[grammar]] [[grammar]]
name = "typst" name = "typst"
source = { git = "https://github.com/uben0/tree-sitter-typst", rev = "ecf8596336857adfcd5f7cbb3b2aa11a67badc37" } source = { git = "https://github.com/uben0/tree-sitter-typst", rev = "13863ddcbaa7b68ee6221cea2e3143415e64aea4" }
[[language]] [[language]]
name = "nunjucks" name = "nunjucks"
@ -3132,7 +3166,8 @@ source = { git = "https://github.com/kylegoetz/tree-sitter-unison", rev = "1f505
[[language]] [[language]]
name = "todotxt" name = "todotxt"
scope = "text.todotxt" scope = "text.todotxt"
file-types = [{ glob = "todo.txt" }, { glob = "*.todo.txt" }, "todotxt"] # glob = "todo.txt" is too common and can conflict regular files, define in user config if necessary
file-types = [{ glob = "*.todo.txt" }, "todotxt"]
formatter = { command = "sort" } formatter = { command = "sort" }
auto-format = true auto-format = true
@ -3195,7 +3230,7 @@ language-servers = [ "templ" ]
[[grammar]] [[grammar]]
name = "templ" name = "templ"
source = { git = "https://github.com/vrischmann/tree-sitter-templ", rev = "ea56ac0655243490a4929a988f4eaa91dfccc995" } source = { git = "https://github.com/vrischmann/tree-sitter-templ", rev = "db662414ccd6f7c78b1e834e7abe11c224b04759" }
[[language]] [[language]]
name = "dbml" name = "dbml"
@ -3209,6 +3244,17 @@ indent = { tab-width = 2, unit = " " }
name = "dbml" name = "dbml"
source = { git = "https://github.com/dynamotn/tree-sitter-dbml", rev = "2e2fa5640268c33c3d3f27f7e676f631a9c68fd9" } source = { git = "https://github.com/dynamotn/tree-sitter-dbml", rev = "2e2fa5640268c33c3d3f27f7e676f631a9c68fd9" }
[[language]]
name = "bitbake"
language-servers = [ "bitbake-language-server" ]
scope = "source.bitbake"
file-types = ["bb", "bbappend", "bbclass", {glob = "conf/*.conf" }, {glob = "conf/*/*.{inc,conf}" }, { glob = "recipe-*/*/*.inc" }]
comment-token = "#"
[[grammar]]
name = "bitbake"
source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-bitbake", rev = "10bacac929ff36a1e8f4056503fe4f8717b21b94" }
[[language]] [[language]]
name = "log" name = "log"
scope = "source.log" scope = "source.log"
@ -3249,10 +3295,11 @@ injection-regex = "koka"
file-types = ["kk"] file-types = ["kk"]
comment-token = "//" comment-token = "//"
indent = { tab-width = 8, unit = " " } indent = { tab-width = 8, unit = " " }
language-servers = ["koka"]
[[grammar]] [[grammar]]
name = "koka" name = "koka"
source = { git = "https://github.com/mtoohey31/tree-sitter-koka", rev = "2527e152d4b6a79fd50aebd8d0b4b4336c94a034" } source = { git = "https://github.com/mtoohey31/tree-sitter-koka", rev = "96d070c3700692858035f3524cc0ad944cef2594" }
[[language]] [[language]]
name = "tact" name = "tact"
@ -3339,13 +3386,13 @@ indent = { tab-width = 2, unit = " " }
[[grammar]] [[grammar]]
name = "ld" name = "ld"
source = { git = "https://github.com/mtoohey31/tree-sitter-ld", rev = "81978cde3844bfc199851e39c80a20ec6444d35e" } source = { git = "https://github.com/mtoohey31/tree-sitter-ld", rev = "0e9695ae0ede47b8744a8e2ad44d4d40c5d4e4c9" }
[[language]] [[language]]
name = "hyprlang" name = "hyprlang"
scope = "source.hyprlang" scope = "source.hyprlang"
roots = ["hyprland.conf"] roots = ["hyprland.conf"]
file-types = [ { glob = "hyprland.conf"} ] file-types = [ { glob = "hyprland.conf" }, { glob = "hyprpaper.conf" }, { glob = "hypridle.conf" }, { glob = "hyprlock.conf" } ]
comment-token = "#" comment-token = "#"
grammar = "hyprlang" grammar = "hyprlang"
@ -3353,6 +3400,18 @@ grammar = "hyprlang"
name = "hyprlang" name = "hyprlang"
source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-hyprlang", rev = "27af9b74acf89fa6bed4fb8cb8631994fcb2e6f3"} source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-hyprlang", rev = "27af9b74acf89fa6bed4fb8cb8631994fcb2e6f3"}
[[language]]
name = "tcl"
scope = "source.tcl"
injection-regex = "tcl"
file-types = [ "tcl" ]
shebangs = [ "tclish", "jimsh", "wish" ]
comment-token = '#'
[[grammar]]
name = "tcl"
source = { git = "https://github.com/tree-sitter-grammars/tree-sitter-tcl", rev = "56ad1fa6a34ba800e5495d1025a9b0fda338d5b8" }
[[language]] [[language]]
name = "supercollider" name = "supercollider"
scope = "source.supercollider" scope = "source.supercollider"
@ -3385,7 +3444,7 @@ scope = "source.helm"
roots = ["Chart.yaml"] roots = ["Chart.yaml"]
comment-token = "#" comment-token = "#"
language-servers = ["helm_ls"] language-servers = ["helm_ls"]
file-types = [ { glob = "templates/*.yaml" }, { glob = "templates/_helpers.tpl"}, { glob = "templates/NOTES.txt" } ] file-types = [ { glob = "templates/*.yaml" }, { glob = "templates/_*.tpl"}, { glob = "templates/NOTES.txt" } ]
[[language]] [[language]]
name = "glimmer" name = "glimmer"
@ -3408,3 +3467,115 @@ formatter = { command = "prettier", args = ['--parser', 'glimmer'] }
[[grammar]] [[grammar]]
name = "glimmer" name = "glimmer"
source = { git = "https://github.com/ember-tooling/tree-sitter-glimmer", rev = "5dc6d1040e8ff8978ff3680e818d85447bbc10aa" } source = { git = "https://github.com/ember-tooling/tree-sitter-glimmer", rev = "5dc6d1040e8ff8978ff3680e818d85447bbc10aa" }
[[language]]
name = "ohm"
scope = "source.ohm"
injection-regex = "ohm"
file-types = ["ohm"]
comment-token = "//"
block-comment-tokens = [
{ start = "/*", end = "*/" },
{ start = "/**", end = "*/" },
]
indent = { tab-width = 2, unit = " " }
[language.auto-pairs]
'"' = '"'
'{' = '}'
'(' = ')'
'<' = '>'
[[grammar]]
name = "ohm"
source = { git = "https://github.com/novusnota/tree-sitter-ohm", rev = "80f14f0e477ddacc1e137d5ed8e830329e3fb7a3" }
[[language]]
name = "earthfile"
scope = "source.earthfile"
injection-regex = "earthfile"
roots = ["Earthfile"]
file-types = [
{ glob = "Earthfile" },
]
comment-token = "#"
indent = { tab-width = 2, unit = " " }
language-servers = ["earthlyls"]
[[grammar]]
name = "earthfile"
source = { git = "https://github.com/glehmann/tree-sitter-earthfile", rev = "a079e6c472eeedd6b9a1e03ca0b6c82cd6a112a4" }
[[language]]
name = "adl"
scope = "source.adl"
injection-regex = "adl"
file-types = ["adl"]
roots = []
comment-token = "//"
indent = { tab-width = 2, unit = " " }
[language.auto-pairs]
'"' = '"'
'{' = '}'
'<' = '>'
[[grammar]]
name = "adl"
source = { git = "https://github.com/adl-lang/tree-sitter-adl", rev = "2787d04beadfbe154d3f2da6e98dc45a1b134bbf" }
[[language]]
name = "ldif"
scope = "source.ldif"
injection-regex = "ldif"
file-types = ["ldif"]
comment-token = "#"
[[grammar]]
name = "ldif"
source = { git = "https://github.com/kepet19/tree-sitter-ldif", rev = "0a917207f65ba3e3acfa9cda16142ee39c4c1aaa" }
[[language]]
name = "xtc"
scope = "source.xtc"
# Accept Xena Traffic Configuration, Xena Port Configuration and Xena OpenAutomation
file-types = [ "xtc", "xpc", "xoa" ]
comment-token = ";"
[[grammar]]
name = "xtc"
source = { git = "https://github.com/Alexis-Lapierre/tree-sitter-xtc", rev = "7bc11b736250c45e25cfb0215db2f8393779957e" }
[[language]]
name = "move"
scope = "source.move"
injection-regex = "move"
roots = ["Move.toml"]
file-types = ["move"]
comment-token = "//"
indent = { tab-width = 4, unit = " " }
language-servers = []
[[grammar]]
name = "move"
source = { git = "https://github.com/tzakian/tree-sitter-move", rev = "8bc0d1692caa8763fef54d48068238d9bf3c0264" }
[[language]]
name = "pest"
scope = "source.pest"
injection-regex = "pest"
file-types = ["pest"]
comment-tokens = ["//", "///", "//!"]
block-comment-tokens = { start = "/*", end = "*/" }
indent = { tab-width = 4, unit = " " }
language-servers = ["pest-language-server"]
[language.auto-pairs]
'(' = ')'
'{' = '}'
'[' = ']'
'"' = '"'
[[grammar]]
name = "pest"
source = { git = "https://github.com/pest-parser/tree-sitter-pest", rev = "a8a98a824452b1ec4da7f508386a187a2f234b85" }

@ -4,3 +4,9 @@
(type_alias_declaration (type_alias_declaration
value: (_) @class.inside) value: (_) @class.inside)
] @class.around ] @class.around
(enum_body
(_) @entry.around)
(enum_assignment (_) @entry.inside)

@ -0,0 +1,37 @@
; adl
[
"module"
"struct"
"union"
"type"
"newtype"
"annotation"
] @keyword
(adl (scoped_name)) @namespace
(comment) @comment
(doc_comment) @comment.block.documentation
(name) @type
(fname) @variable.other.member
(type_expr (scoped_name) @type)
(type_expr_params (param (scoped_name) @type.parameter))
; json
(key) @string.special
(string) @string
(number) @constant.numeric
[
(null)
(true)
(false)
] @constant.builtin
(escape_sequence) @constant.character.escape

@ -0,0 +1,12 @@
[
(struct)
(union)
(array)
(object)
] @indent
; [
; "}"
; "]"
; ] @outdent

@ -0,0 +1 @@
(struct (_) @function.inside) @funtion.around

@ -60,7 +60,6 @@
">>" ">>"
"<" "<"
"|" "|"
(expansion_flags)
] @operator ] @operator
( (

@ -7,3 +7,6 @@
(comment) @comment.inside (comment) @comment.inside
(comment)+ @comment.around (comment)+ @comment.around
(array
(_) @entry.around)

@ -0,0 +1,82 @@
; variables
(variable_assignment (identifier) @variable.other.member)
(variable_assignment (concatenation (identifier) @variable.other.member))
(unset_statement (identifier) @variable.other.member)
(export_statement (identifier) @variable.other.member)
(variable_expansion (identifier) @variable.other.member)
(python_function_definition (parameters (python_identifier) @variable.other.member))
(variable_assignment (override) @keyword.storage.modifier)
(overrides_statement (identifier) @keyword.storage.modifier)
(flag) @keyword.storage.modifier
[
"="
"?="
"??="
":="
"=+"
"+="
".="
"=."
] @operator
(variable_expansion [ "${" "}" ] @punctuation.special)
[ "(" ")" "{" "}" "[" "]" ] @punctuation.bracket
[
"noexec"
"INHERIT"
"OVERRIDES"
"$BB_ENV_PASSTHROUGH"
"$BB_ENV_PASSTHROUGH_ADDITIONS"
] @variable.builtin
; functions
(python_function_definition (python_identifier) @function)
(anonymous_python_function (identifier) @function)
(function_definition (identifier) @function)
(export_functions_statement (identifier) @function)
(addtask_statement (identifier) @function)
(deltask_statement (identifier) @function)
(addhandler_statement (identifier) @function)
(function_definition (override) @keyword.storage.modifier)
[
"addtask"
"deltask"
"addhandler"
"unset"
"EXPORT_FUNCTIONS"
"python"
"def"
] @keyword.function
[
"append"
"prepend"
"remove"
"before"
"after"
] @keyword.operator
; imports
[
"inherit"
"include"
"require"
"export"
"import"
] @keyword.control.import
(inherit_path) @namespace
(include_path) @namespace
(string) @string
(comment) @comment

@ -0,0 +1,18 @@
((python_function_definition) @injection.content
(#set! injection.language "python")
(#set! injection.include-children))
((anonymous_python_function (block) @injection.content)
(#set! injection.language "python")
(#set! injection.include-children))
((inline_python) @injection.content
(#set! injection.language "python")
(#set! injection.include-children))
((function_definition) @injection.content
(#set! injection.language "bash")
(#set! injection.include-children))
((comment) @injection.content
(#set! injection.language "comment"))

@ -19,3 +19,9 @@
(comment) @comment.inside (comment) @comment.inside
(comment)+ @comment.around (comment)+ @comment.around
(enumerator
(_) @entry.inside) @entry.around
(initializer_list
(_) @entry.around)

@ -1,5 +1,3 @@
":" @punctuation.delimiter
; Hint level tags ; Hint level tags
((tag (name) @hint) ((tag (name) @hint)
(#match? @hint "^(HINT|MARK|PASSED|STUB|MOCK)$")) (#match? @hint "^(HINT|MARK|PASSED|STUB|MOCK)$"))

@ -0,0 +1,74 @@
(string_array "," @punctuation.delimiter)
(string_array ["[" "]"] @punctuation.bracket)
[
"ARG"
"AS LOCAL"
"BUILD"
"CACHE"
"CMD"
"COPY"
"DO"
"ENTRYPOINT"
"ENV"
"EXPOSE"
"FROM DOCKERFILE"
"FROM"
"FUNCTION"
"GIT CLONE"
"HOST"
"IMPORT"
"LABEL"
"LET"
"PROJECT"
"RUN"
"SAVE ARTIFACT"
"SAVE IMAGE"
"SET"
"USER"
"VERSION"
"VOLUME"
"WORKDIR"
] @keyword
(for_command ["FOR" "IN" "END"] @keyword.control.repeat)
(if_command ["IF" "END"] @keyword.control.conditional)
(elif_block ["ELSE IF"] @keyword.control.conditional)
(else_block ["ELSE"] @keyword.control.conditional)
(import_command ["IMPORT" "AS"] @keyword.control.import)
(try_command ["TRY" "FINALLY" "END"] @keyword.control.exception)
(wait_command ["WAIT" "END"] @keyword.control)
(with_docker_command ["WITH DOCKER" "END"] @keyword.control)
[
(comment)
(line_continuation_comment)
] @comment
(line_continuation) @operator
[
(target_ref)
(target_artifact)
(function_ref)
] @function
(target (identifier) @function)
[
(double_quoted_string)
(single_quoted_string)
] @string
(unquoted_string) @string.special
(escape_sequence) @constant.character.escape
(variable) @variable
(expansion ["$" "{" "}" "(" ")"] @punctuation.special)
(build_arg) @variable
(options (_) @variable.parameter)
"=" @operator

@ -0,0 +1,9 @@
((comment) @injection.content
(#set! injection.language "comment"))
((line_continuation_comment) @injection.content
(#set! injection.language "comment"))
((shell_fragment) @injection.content
(#set! injection.language "bash")
(#set! injection.include-children))

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save