mirror of https://github.com/helix-editor/helix
Merge branch 'helix-editor:master' into trim-colons-from-paths
commit
bc9c9cff61
@ -0,0 +1,164 @@
|
|||||||
|
## Building from source
|
||||||
|
|
||||||
|
- [Configuring Helix's runtime files](#configuring-helixs-runtime-files)
|
||||||
|
- [Linux and macOS](#linux-and-macos)
|
||||||
|
- [Windows](#windows)
|
||||||
|
- [Multiple runtime directories](#multiple-runtime-directories)
|
||||||
|
- [Note to packagers](#note-to-packagers)
|
||||||
|
- [Validating the installation](#validating-the-installation)
|
||||||
|
- [Configure the desktop shortcut](#configure-the-desktop-shortcut)
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
|
||||||
|
Clone the Helix GitHub repository into a directory of your choice. The
|
||||||
|
examples in this documentation assume installation into either `~/src/` on
|
||||||
|
Linux and macOS, or `%userprofile%\src\` on Windows.
|
||||||
|
|
||||||
|
- The [Rust toolchain](https://www.rust-lang.org/tools/install)
|
||||||
|
- The [Git version control system](https://git-scm.com/)
|
||||||
|
- A C++14 compatible compiler to build the tree-sitter grammars, for example GCC or Clang
|
||||||
|
|
||||||
|
If you are using the `musl-libc` standard library instead of `glibc` the following environment variable must be set during the build to ensure tree-sitter grammars can be loaded correctly:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
RUSTFLAGS="-C target-feature=-crt-static"
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Clone the repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git clone https://github.com/helix-editor/helix
|
||||||
|
cd helix
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Compile from source:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo install --path helix-term --locked
|
||||||
|
```
|
||||||
|
|
||||||
|
This command will create the `hx` executable and construct the tree-sitter
|
||||||
|
grammars in the local `runtime` folder.
|
||||||
|
|
||||||
|
> 💡 If you do not want to fetch or build grammars, set an environment variable `HELIX_DISABLE_AUTO_GRAMMAR_BUILD`
|
||||||
|
|
||||||
|
> 💡 Tree-sitter grammars can be fetched and compiled if not pre-packaged. Fetch
|
||||||
|
> grammars with `hx --grammar fetch` and compile them with
|
||||||
|
> `hx --grammar build`. This will install them in
|
||||||
|
> the `runtime` directory within the user's helix config directory (more
|
||||||
|
> [details below](#multiple-runtime-directories)).
|
||||||
|
|
||||||
|
### Configuring Helix's runtime files
|
||||||
|
|
||||||
|
#### Linux and macOS
|
||||||
|
|
||||||
|
The **runtime** directory is one below the Helix source, so either export a
|
||||||
|
`HELIX_RUNTIME` environment variable to point to that directory and add it to
|
||||||
|
your `~/.bashrc` or equivalent:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export HELIX_RUNTIME=~/src/helix/runtime
|
||||||
|
```
|
||||||
|
|
||||||
|
Or, create a symbolic link:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ln -Ts $PWD/runtime ~/.config/helix/runtime
|
||||||
|
```
|
||||||
|
|
||||||
|
If the above command fails to create a symbolic link because the file exists either move `~/.config/helix/runtime` to a new location or delete it, then run the symlink command above again.
|
||||||
|
|
||||||
|
#### Windows
|
||||||
|
|
||||||
|
Either set the `HELIX_RUNTIME` environment variable to point to the runtime files using the Windows setting (search for
|
||||||
|
`Edit environment variables for your account`) or use the `setx` command in
|
||||||
|
Cmd:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
setx HELIX_RUNTIME "%userprofile%\source\repos\helix\runtime"
|
||||||
|
```
|
||||||
|
|
||||||
|
> 💡 `%userprofile%` resolves to your user directory like
|
||||||
|
> `C:\Users\Your-Name\` for example.
|
||||||
|
|
||||||
|
Or, create a symlink in `%appdata%\helix\` that links to the source code directory:
|
||||||
|
|
||||||
|
| Method | Command |
|
||||||
|
| ---------- | -------------------------------------------------------------------------------------- |
|
||||||
|
| PowerShell | `New-Item -ItemType Junction -Target "runtime" -Path "$Env:AppData\helix\runtime"` |
|
||||||
|
| Cmd | `cd %appdata%\helix` <br/> `mklink /D runtime "%userprofile%\src\helix\runtime"` |
|
||||||
|
|
||||||
|
> 💡 On Windows, creating a symbolic link may require running PowerShell or
|
||||||
|
> Cmd as an administrator.
|
||||||
|
|
||||||
|
#### Multiple runtime directories
|
||||||
|
|
||||||
|
When Helix finds multiple runtime directories it will search through them for files in the
|
||||||
|
following order:
|
||||||
|
|
||||||
|
1. `runtime/` sibling directory to `$CARGO_MANIFEST_DIR` directory (this is intended for
|
||||||
|
developing and testing helix only).
|
||||||
|
2. `runtime/` subdirectory of OS-dependent helix user config directory.
|
||||||
|
3. `$HELIX_RUNTIME`
|
||||||
|
4. Distribution-specific fallback directory (set at compile time—not run time—
|
||||||
|
with the `HELIX_DEFAULT_RUNTIME` environment variable)
|
||||||
|
5. `runtime/` subdirectory of path to Helix executable.
|
||||||
|
|
||||||
|
This order also sets the priority for selecting which file will be used if multiple runtime
|
||||||
|
directories have files with the same name.
|
||||||
|
|
||||||
|
#### Note to packagers
|
||||||
|
|
||||||
|
If you are making a package of Helix for end users, to provide a good out of
|
||||||
|
the box experience, you should set the `HELIX_DEFAULT_RUNTIME` environment
|
||||||
|
variable at build time (before invoking `cargo build`) to a directory which
|
||||||
|
will store the final runtime files after installation. For example, say you want
|
||||||
|
to package the runtime into `/usr/lib/helix/runtime`. The rough steps a build
|
||||||
|
script could follow are:
|
||||||
|
|
||||||
|
1. `export HELIX_DEFAULT_RUNTIME=/usr/lib/helix/runtime`
|
||||||
|
1. `cargo build --profile opt --locked --path helix-term`
|
||||||
|
1. `cp -r runtime $BUILD_DIR/usr/lib/helix/`
|
||||||
|
1. `cp target/opt/hx $BUILD_DIR/usr/bin/hx`
|
||||||
|
|
||||||
|
This way the resulting `hx` binary will always look for its runtime directory in
|
||||||
|
`/usr/lib/helix/runtime` if the user has no custom runtime in `~/.config/helix`
|
||||||
|
or `HELIX_RUNTIME`.
|
||||||
|
|
||||||
|
### Validating the installation
|
||||||
|
|
||||||
|
To make sure everything is set up as expected you should run the Helix health
|
||||||
|
check:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
hx --health
|
||||||
|
```
|
||||||
|
|
||||||
|
For more information on the health check results refer to
|
||||||
|
[Health check](https://github.com/helix-editor/helix/wiki/Healthcheck).
|
||||||
|
|
||||||
|
### Configure the desktop shortcut
|
||||||
|
|
||||||
|
If your desktop environment supports the
|
||||||
|
[XDG desktop menu](https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html)
|
||||||
|
you can configure Helix to show up in the application menu by copying the
|
||||||
|
provided `.desktop` and icon files to their correct folders:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp contrib/Helix.desktop ~/.local/share/applications
|
||||||
|
cp contrib/helix.png ~/.icons # or ~/.local/share/icons
|
||||||
|
```
|
||||||
|
It is recommended to convert the links in the `.desktop` file to absolute paths to avoid potential problems:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sed -i -e "s|Exec=hx %F|Exec=$(readlink -f ~/.cargo/bin/hx) %F|g" \
|
||||||
|
-e "s|Icon=helix|Icon=$(readlink -f ~/.icons/helix.png)|g" ~/.local/share/applications/Helix.desktop
|
||||||
|
```
|
||||||
|
|
||||||
|
To use another terminal than the system default, you can modify the `.desktop`
|
||||||
|
file. For example, to use `kitty`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sed -i "s|Exec=hx %F|Exec=kitty hx %F|g" ~/.local/share/applications/Helix.desktop
|
||||||
|
sed -i "s|Terminal=true|Terminal=false|g" ~/.local/share/applications/Helix.desktop
|
||||||
|
```
|
@ -0,0 +1,435 @@
|
|||||||
|
## Editor
|
||||||
|
|
||||||
|
- [`[editor]` Section](#editor-section)
|
||||||
|
- [`[editor.statusline]` Section](#editorstatusline-section)
|
||||||
|
- [`[editor.lsp]` Section](#editorlsp-section)
|
||||||
|
- [`[editor.cursor-shape]` Section](#editorcursor-shape-section)
|
||||||
|
- [`[editor.file-picker]` Section](#editorfile-picker-section)
|
||||||
|
- [`[editor.auto-pairs]` Section](#editorauto-pairs-section)
|
||||||
|
- [`[editor.search]` Section](#editorsearch-section)
|
||||||
|
- [`[editor.whitespace]` Section](#editorwhitespace-section)
|
||||||
|
- [`[editor.indent-guides]` Section](#editorindent-guides-section)
|
||||||
|
- [`[editor.gutters]` Section](#editorgutters-section)
|
||||||
|
- [`[editor.gutters.line-numbers]` Section](#editorguttersline-numbers-section)
|
||||||
|
- [`[editor.gutters.diagnostics]` Section](#editorguttersdiagnostics-section)
|
||||||
|
- [`[editor.gutters.diff]` Section](#editorguttersdiff-section)
|
||||||
|
- [`[editor.gutters.spacer]` Section](#editorguttersspacer-section)
|
||||||
|
- [`[editor.soft-wrap]` Section](#editorsoft-wrap-section)
|
||||||
|
- [`[editor.smart-tab]` Section](#editorsmart-tab-section)
|
||||||
|
- [`[editor.inline-diagnostics]` Section](#editorinline-diagnostics-section)
|
||||||
|
|
||||||
|
### `[editor]` Section
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|--|--|---------|
|
||||||
|
| `scrolloff` | Number of lines of padding around the edge of the screen when scrolling | `5` |
|
||||||
|
| `mouse` | Enable mouse mode | `true` |
|
||||||
|
| `middle-click-paste` | Middle click paste support | `true` |
|
||||||
|
| `scroll-lines` | Number of lines to scroll per scroll wheel step | `3` |
|
||||||
|
| `shell` | Shell to use when running external commands | Unix: `["sh", "-c"]`<br/>Windows: `["cmd", "/C"]` |
|
||||||
|
| `line-number` | Line number display: `absolute` simply shows each line's number, while `relative` shows the distance from the current line. When unfocused or in insert mode, `relative` will still show absolute line numbers | `absolute` |
|
||||||
|
| `cursorline` | Highlight all lines with a cursor | `false` |
|
||||||
|
| `cursorcolumn` | Highlight all columns with a cursor | `false` |
|
||||||
|
| `gutters` | Gutters to display: Available are `diagnostics` and `diff` and `line-numbers` and `spacer`, note that `diagnostics` also includes other features like breakpoints, 1-width padding will be inserted if gutters is non-empty | `["diagnostics", "spacer", "line-numbers", "spacer", "diff"]` |
|
||||||
|
| `auto-completion` | Enable automatic pop up of auto-completion | `true` |
|
||||||
|
| `auto-format` | Enable automatic formatting on save | `true` |
|
||||||
|
| `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. | `250` |
|
||||||
|
| `completion-timeout` | Time in milliseconds after typing a word character before completions are shown, set to 5 for instant. | `250` |
|
||||||
|
| `preview-completion-insert` | Whether to apply completion item instantly when selected | `true` |
|
||||||
|
| `completion-trigger-len` | The min-length of word under cursor to trigger autocompletion | `2` |
|
||||||
|
| `completion-replace` | Set to `true` to make completions always replace the entire word and not just the part before the cursor | `false` |
|
||||||
|
| `auto-info` | Whether to display info boxes | `true` |
|
||||||
|
| `true-color` | Set to `true` to override automatic detection of terminal truecolor support in the event of a false negative | `false` |
|
||||||
|
| `undercurl` | Set to `true` to override automatic detection of terminal undercurl support in the event of a false negative | `false` |
|
||||||
|
| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file | `[]` |
|
||||||
|
| `bufferline` | Renders a line at the top of the editor displaying open buffers. Can be `always`, `never` or `multiple` (only shown if more than one buffer is in use) | `never` |
|
||||||
|
| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` |
|
||||||
|
| `text-width` | Maximum line length. Used for the `:reflow` command and soft-wrapping if `soft-wrap.wrap-at-text-width` is set | `80` |
|
||||||
|
| `workspace-lsp-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml` | `[]` |
|
||||||
|
| `default-line-ending` | The line ending to use for new documents. Can be `native`, `lf`, `crlf`, `ff`, `cr` or `nel`. `native` uses the platform's native line ending (`crlf` on Windows, otherwise `lf`). | `native` |
|
||||||
|
| `insert-final-newline` | Whether to automatically insert a trailing line-ending on write if missing | `true` |
|
||||||
|
| `popup-border` | Draw border around `popup`, `menu`, `all`, or `none` | `none` |
|
||||||
|
| `indent-heuristic` | How the indentation for a newly inserted line is computed: `simple` just copies the indentation level from the previous line, `tree-sitter` computes the indentation based on the syntax tree and `hybrid` combines both approaches. If the chosen heuristic is not available, a different one will be used as a fallback (the fallback order being `hybrid` -> `tree-sitter` -> `simple`). | `hybrid`
|
||||||
|
| `jump-label-alphabet` | The characters that are used to generate two character jump labels. Characters at the start of the alphabet are used first. | `"abcdefghijklmnopqrstuvwxyz"`
|
||||||
|
| `end-of-line-diagnostics` | Minimum severity of diagnostics to render at the end of the line. Set to `disable` to disable entirely. Refer to the setting about `inline-diagnostics` for more details | "disable"
|
||||||
|
|
||||||
|
### `[editor.statusline]` Section
|
||||||
|
|
||||||
|
Allows configuring the statusline at the bottom of the editor.
|
||||||
|
|
||||||
|
The configuration distinguishes between three areas of the status line:
|
||||||
|
|
||||||
|
`[ ... ... LEFT ... ... | ... ... ... CENTER ... ... ... | ... ... RIGHT ... ... ]`
|
||||||
|
|
||||||
|
Statusline elements can be defined as follows:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.statusline]
|
||||||
|
left = ["mode", "spinner"]
|
||||||
|
center = ["file-name"]
|
||||||
|
right = ["diagnostics", "selections", "position", "file-encoding", "file-line-ending", "file-type"]
|
||||||
|
separator = "│"
|
||||||
|
mode.normal = "NORMAL"
|
||||||
|
mode.insert = "INSERT"
|
||||||
|
mode.select = "SELECT"
|
||||||
|
```
|
||||||
|
The `[editor.statusline]` key takes the following sub-keys:
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `left` | A list of elements aligned to the left of the statusline | `["mode", "spinner", "file-name", "read-only-indicator", "file-modification-indicator"]` |
|
||||||
|
| `center` | A list of elements aligned to the middle of the statusline | `[]` |
|
||||||
|
| `right` | A list of elements aligned to the right of the statusline | `["diagnostics", "selections", "register", "position", "file-encoding"]` |
|
||||||
|
| `separator` | The character used to separate elements in the statusline | `"│"` |
|
||||||
|
| `mode.normal` | The text shown in the `mode` element for normal mode | `"NOR"` |
|
||||||
|
| `mode.insert` | The text shown in the `mode` element for insert mode | `"INS"` |
|
||||||
|
| `mode.select` | The text shown in the `mode` element for select mode | `"SEL"` |
|
||||||
|
|
||||||
|
The following statusline elements can be configured:
|
||||||
|
|
||||||
|
| Key | Description |
|
||||||
|
| ------ | ----------- |
|
||||||
|
| `mode` | The current editor mode (`mode.normal`/`mode.insert`/`mode.select`) |
|
||||||
|
| `spinner` | A progress spinner indicating LSP activity |
|
||||||
|
| `file-name` | The path/name of the opened file |
|
||||||
|
| `file-absolute-path` | The absolute path/name of the opened file |
|
||||||
|
| `file-base-name` | The basename of the opened file |
|
||||||
|
| `file-modification-indicator` | The indicator to show whether the file is modified (a `[+]` appears when there are unsaved changes) |
|
||||||
|
| `file-encoding` | The encoding of the opened file if it differs from UTF-8 |
|
||||||
|
| `file-line-ending` | The file line endings (CRLF or LF) |
|
||||||
|
| `read-only-indicator` | An indicator that shows `[readonly]` when a file cannot be written |
|
||||||
|
| `total-line-numbers` | The total line numbers of the opened file |
|
||||||
|
| `file-type` | The type of the opened file |
|
||||||
|
| `diagnostics` | The number of warnings and/or errors |
|
||||||
|
| `workspace-diagnostics` | The number of warnings and/or errors on workspace |
|
||||||
|
| `selections` | The number of active selections |
|
||||||
|
| `primary-selection-length` | The number of characters currently in primary selection |
|
||||||
|
| `position` | The cursor position |
|
||||||
|
| `position-percentage` | The cursor position as a percentage of the total number of lines |
|
||||||
|
| `separator` | The string defined in `editor.statusline.separator` (defaults to `"│"`) |
|
||||||
|
| `spacer` | Inserts a space between elements (multiple/contiguous spacers may be specified) |
|
||||||
|
| `version-control` | The current branch name or detached commit hash of the opened workspace |
|
||||||
|
| `register` | The current selected register |
|
||||||
|
|
||||||
|
### `[editor.lsp]` Section
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | ----------- | ------- |
|
||||||
|
| `enable` | Enables LSP integration. Setting to false will completely disable language servers regardless of language settings.| `true` |
|
||||||
|
| `display-messages` | Display LSP progress messages below statusline[^1] | `false` |
|
||||||
|
| `auto-signature-help` | Enable automatic popup of signature help (parameter hints) | `true` |
|
||||||
|
| `display-inlay-hints` | Display inlay hints[^2] | `false` |
|
||||||
|
| `display-signature-help-docs` | Display docs under signature help popup | `true` |
|
||||||
|
| `snippets` | Enables snippet completions. Requires a server restart (`:lsp-restart`) to take effect after `:config-reload`/`:set`. | `true` |
|
||||||
|
| `goto-reference-include-declaration` | Include declaration in the goto references popup. | `true` |
|
||||||
|
|
||||||
|
[^1]: By default, a progress spinner is shown in the statusline beside the file path.
|
||||||
|
|
||||||
|
[^2]: You may also have to activate them in the LSP config for them to appear, not just in Helix. Inlay hints in Helix are still being improved on and may be a little bit laggy/janky under some circumstances. Please report any bugs you see so we can fix them!
|
||||||
|
|
||||||
|
### `[editor.cursor-shape]` Section
|
||||||
|
|
||||||
|
Defines the shape of cursor in each mode.
|
||||||
|
Valid values for these options are `block`, `bar`, `underline`, or `hidden`.
|
||||||
|
|
||||||
|
> 💡 Due to limitations of the terminal environment, only the primary cursor can
|
||||||
|
> change shape.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | ----------- | ------- |
|
||||||
|
| `normal` | Cursor shape in [normal mode][normal mode] | `block` |
|
||||||
|
| `insert` | Cursor shape in [insert mode][insert mode] | `block` |
|
||||||
|
| `select` | Cursor shape in [select mode][select mode] | `block` |
|
||||||
|
|
||||||
|
[normal mode]: ./keymap.md#normal-mode
|
||||||
|
[insert mode]: ./keymap.md#insert-mode
|
||||||
|
[select mode]: ./keymap.md#select--extend-mode
|
||||||
|
|
||||||
|
### `[editor.file-picker]` Section
|
||||||
|
|
||||||
|
Set options for file picker and global search. Ignoring a file means it is
|
||||||
|
not visible in the Helix file picker and global search.
|
||||||
|
|
||||||
|
All git related options are only enabled in a git repository.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|--|--|---------|
|
||||||
|
|`hidden` | Enables ignoring hidden files | `true`
|
||||||
|
|`follow-symlinks` | Follow symlinks instead of ignoring them | `true`
|
||||||
|
|`deduplicate-links` | Ignore symlinks that point at files already shown in the picker | `true`
|
||||||
|
|`parents` | Enables reading ignore files from parent directories | `true`
|
||||||
|
|`ignore` | Enables reading `.ignore` files | `true`
|
||||||
|
|`git-ignore` | Enables reading `.gitignore` files | `true`
|
||||||
|
|`git-global` | Enables reading global `.gitignore`, whose path is specified in git's config: `core.excludesfile` option | `true`
|
||||||
|
|`git-exclude` | Enables reading `.git/info/exclude` files | `true`
|
||||||
|
|`max-depth` | Set with an integer value for maximum depth to recurse | Unset by default
|
||||||
|
|
||||||
|
Ignore files can be placed locally as `.ignore` or put in your home directory as `~/.ignore`. They support the usual ignore and negative ignore (unignore) rules used in `.gitignore` files.
|
||||||
|
|
||||||
|
Additionally, you can use Helix-specific ignore files by creating a local `.helix/ignore` file in the current workspace or a global `ignore` file located in your Helix config directory:
|
||||||
|
- Linux and Mac: `~/.config/helix/ignore`
|
||||||
|
- Windows: `%AppData%\helix\ignore`
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
# unignore in file picker and global search
|
||||||
|
!.github/
|
||||||
|
!.gitignore
|
||||||
|
!.gitattributes
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.auto-pairs]` Section
|
||||||
|
|
||||||
|
Enables automatic insertion of pairs to parentheses, brackets, etc. Can be a
|
||||||
|
simple boolean value, or a specific mapping of pairs of single characters.
|
||||||
|
|
||||||
|
To disable auto-pairs altogether, set `auto-pairs` to `false`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor]
|
||||||
|
auto-pairs = false # defaults to `true`
|
||||||
|
```
|
||||||
|
|
||||||
|
The default pairs are <code>(){}[]''""``</code>, but these can be customized by
|
||||||
|
setting `auto-pairs` to a TOML table:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.auto-pairs]
|
||||||
|
'(' = ')'
|
||||||
|
'{' = '}'
|
||||||
|
'[' = ']'
|
||||||
|
'"' = '"'
|
||||||
|
'`' = '`'
|
||||||
|
'<' = '>'
|
||||||
|
```
|
||||||
|
|
||||||
|
Additionally, this setting can be used in a language config. Unless
|
||||||
|
the editor setting is `false`, this will override the editor config in
|
||||||
|
documents with this language.
|
||||||
|
|
||||||
|
Example `languages.toml` that adds `<>` and removes `''`
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[[language]]
|
||||||
|
name = "rust"
|
||||||
|
|
||||||
|
[language.auto-pairs]
|
||||||
|
'(' = ')'
|
||||||
|
'{' = '}'
|
||||||
|
'[' = ']'
|
||||||
|
'"' = '"'
|
||||||
|
'`' = '`'
|
||||||
|
'<' = '>'
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.auto-save]` Section
|
||||||
|
|
||||||
|
Control auto save behavior.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|--|--|---------|
|
||||||
|
| `focus-lost` | Enable automatic saving on the focus moving away from Helix. Requires [focus event support](https://github.com/helix-editor/helix/wiki/Terminal-Support) from your terminal | `false` |
|
||||||
|
| `after-delay.enable` | Enable automatic saving after `auto-save.after-delay.timeout` milliseconds have passed since last edit. | `false` |
|
||||||
|
| `after-delay.timeout` | Time in milliseconds since last edit before auto save timer triggers. | `3000` |
|
||||||
|
|
||||||
|
### `[editor.search]` Section
|
||||||
|
|
||||||
|
Search specific options.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|--|--|---------|
|
||||||
|
| `smart-case` | Enable smart case regex searching (case-insensitive unless pattern contains upper case characters) | `true` |
|
||||||
|
| `wrap-around`| Whether the search should wrap after depleting the matches | `true` |
|
||||||
|
|
||||||
|
### `[editor.whitespace]` Section
|
||||||
|
|
||||||
|
Options for rendering whitespace with visible characters. Use `:set whitespace.render all` to temporarily enable visible whitespace.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|-----|-------------|---------|
|
||||||
|
| `render` | Whether to render whitespace. May either be `all` or `none`, or a table with sub-keys `space`, `nbsp`, `nnbsp`, `tab`, and `newline` | `none` |
|
||||||
|
| `characters` | Literal characters to use when rendering whitespace. Sub-keys may be any of `tab`, `space`, `nbsp`, `nnbsp`, `newline` or `tabpad` | See example below |
|
||||||
|
|
||||||
|
Example
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.whitespace]
|
||||||
|
render = "all"
|
||||||
|
# or control each character
|
||||||
|
[editor.whitespace.render]
|
||||||
|
space = "all"
|
||||||
|
tab = "all"
|
||||||
|
nbsp = "none"
|
||||||
|
nnbsp = "none"
|
||||||
|
newline = "none"
|
||||||
|
|
||||||
|
[editor.whitespace.characters]
|
||||||
|
space = "·"
|
||||||
|
nbsp = "⍽"
|
||||||
|
nnbsp = "␣"
|
||||||
|
tab = "→"
|
||||||
|
newline = "⏎"
|
||||||
|
tabpad = "·" # Tabs will look like "→···" (depending on tab width)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.indent-guides]` Section
|
||||||
|
|
||||||
|
Options for rendering vertical indent guides.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `render` | Whether to render indent guides | `false` |
|
||||||
|
| `character` | Literal character to use for rendering the indent guide | `│` |
|
||||||
|
| `skip-levels` | Number of indent levels to skip | `0` |
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.indent-guides]
|
||||||
|
render = true
|
||||||
|
character = "╎" # Some characters that work well: "▏", "┆", "┊", "⸽"
|
||||||
|
skip-levels = 1
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.gutters]` Section
|
||||||
|
|
||||||
|
For simplicity, `editor.gutters` accepts an array of gutter types, which will
|
||||||
|
use default settings for all gutter components.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor]
|
||||||
|
gutters = ["diff", "diagnostics", "line-numbers", "spacer"]
|
||||||
|
```
|
||||||
|
|
||||||
|
To customize the behavior of gutters, the `[editor.gutters]` section must
|
||||||
|
be used. This section contains top level settings, as well as settings for
|
||||||
|
specific gutter components as subsections.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `layout` | A vector of gutters to display | `["diagnostics", "spacer", "line-numbers", "spacer", "diff"]` |
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.gutters]
|
||||||
|
layout = ["diff", "diagnostics", "line-numbers", "spacer"]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `[editor.gutters.line-numbers]` Section
|
||||||
|
|
||||||
|
Options for the line number gutter
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `min-width` | The minimum number of characters to use | `3` |
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.gutters.line-numbers]
|
||||||
|
min-width = 1
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `[editor.gutters.diagnostics]` Section
|
||||||
|
|
||||||
|
Currently unused
|
||||||
|
|
||||||
|
#### `[editor.gutters.diff]` Section
|
||||||
|
|
||||||
|
The `diff` gutter option displays colored bars indicating whether a `git` diff represents that a line was added, removed or changed.
|
||||||
|
These colors are controlled by the theme attributes `diff.plus`, `diff.minus` and `diff.delta`.
|
||||||
|
|
||||||
|
Other diff providers will eventually be supported by a future plugin system.
|
||||||
|
|
||||||
|
There are currently no options for this section.
|
||||||
|
|
||||||
|
#### `[editor.gutters.spacer]` Section
|
||||||
|
|
||||||
|
Currently unused
|
||||||
|
|
||||||
|
### `[editor.soft-wrap]` Section
|
||||||
|
|
||||||
|
Options for soft wrapping lines that exceed the view width:
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `enable` | Whether soft wrapping is enabled. | `false` |
|
||||||
|
| `max-wrap` | Maximum free space left at the end of the line. | `20` |
|
||||||
|
| `max-indent-retain` | Maximum indentation to carry over when soft wrapping a line. | `40` |
|
||||||
|
| `wrap-indicator` | Text inserted before soft wrapped lines, highlighted with `ui.virtual.wrap` | `↪ ` |
|
||||||
|
| `wrap-at-text-width` | Soft wrap at `text-width` instead of using the full viewport size. | `false` |
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[editor.soft-wrap]
|
||||||
|
enable = true
|
||||||
|
max-wrap = 25 # increase value to reduce forced mid-word wrapping
|
||||||
|
max-indent-retain = 0
|
||||||
|
wrap-indicator = "" # set wrap-indicator to "" to hide it
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.smart-tab]` Section
|
||||||
|
|
||||||
|
Options for navigating and editing using tab key.
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|------------|-------------|---------|
|
||||||
|
| `enable` | If set to true, then when the cursor is in a position with non-whitespace to its left, instead of inserting a tab, it will run `move_parent_node_end`. If there is only whitespace to the left, then it inserts a tab as normal. With the default bindings, to explicitly insert a tab character, press Shift-tab. | `true` |
|
||||||
|
| `supersede-menu` | Normally, when a menu is on screen, such as when auto complete is triggered, the tab key is bound to cycling through the items. This means when menus are on screen, one cannot use the tab key to trigger the `smart-tab` command. If this option is set to true, the `smart-tab` command always takes precedence, which means one cannot use the tab key to cycle through menu items. One of the other bindings must be used instead, such as arrow keys or `C-n`/`C-p`. | `false` |
|
||||||
|
|
||||||
|
|
||||||
|
Due to lack of support for S-tab in some terminals, the default keybindings don't fully embrace smart-tab editing experience. If you enjoy smart-tab navigation and a terminal that supports the [Enhanced Keyboard protocol](https://github.com/helix-editor/helix/wiki/Terminal-Support#enhanced-keyboard-protocol), consider setting extra keybindings:
|
||||||
|
|
||||||
|
```
|
||||||
|
[keys.normal]
|
||||||
|
tab = "move_parent_node_end"
|
||||||
|
S-tab = "move_parent_node_start"
|
||||||
|
|
||||||
|
[keys.insert]
|
||||||
|
S-tab = "move_parent_node_start"
|
||||||
|
|
||||||
|
[keys.select]
|
||||||
|
tab = "extend_parent_node_end"
|
||||||
|
S-tab = "extend_parent_node_start"
|
||||||
|
```
|
||||||
|
|
||||||
|
### `[editor.inline-diagnostics]` Section
|
||||||
|
|
||||||
|
Options for rendering diagnostics inside the text like shown below
|
||||||
|
|
||||||
|
```
|
||||||
|
fn main() {
|
||||||
|
let foo = bar;
|
||||||
|
└─ no such value in this scope
|
||||||
|
}
|
||||||
|
````
|
||||||
|
|
||||||
|
| Key | Description | Default |
|
||||||
|
|------------|-------------|---------|
|
||||||
|
| `cursor-line` | The minimum severity that a diagnostic must have to be shown inline on the line that contains the primary cursor. Set to `disable` to not show any diagnostics inline. This option does not have any effect when in insert-mode and will only take effect 350ms after moving the cursor to a different line. | `"disable"` |
|
||||||
|
| `other-lines` | The minimum severity that a diagnostic must have to be shown inline on a line that does not contain the cursor-line. Set to `disable` to not show any diagnostics inline. | `"disable"` |
|
||||||
|
| `prefix-len` | How many horizontal bars `─` are rendered before the diagnostic text. | `1` |
|
||||||
|
| `max-wrap` | Equivalent of the `editor.soft-wrap.max-wrap` option for diagnostics. | `20` |
|
||||||
|
| `max-diagnostics` | Maximum number of diagnostics to render inline for a given line | `10` |
|
||||||
|
|
||||||
|
The (first) diagnostic with the highest severity that is not shown inline is rendered at the end of the line (as long as its severity is higher than the `end-of-line-diagnostics` config option):
|
||||||
|
|
||||||
|
```
|
||||||
|
fn main() {
|
||||||
|
let baz = 1;
|
||||||
|
let foo = bar; a local variable with a similar name exists: baz
|
||||||
|
└─ no such value in this scope
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
The new diagnostic rendering is not yet enabled by default. As soon as end of line or inline diagnostics are enabled the old diagnostics rendering is automatically disabled. The recommended default setting are:
|
||||||
|
|
||||||
|
```
|
||||||
|
end-of-line-diagnostics = "hint"
|
||||||
|
[editor.inline-diagnostics]
|
||||||
|
cursor-line = "warning" # show warnings and errors on the cursorline inline
|
||||||
|
```
|
@ -0,0 +1,150 @@
|
|||||||
|
## Package managers
|
||||||
|
|
||||||
|
- [Linux](#linux)
|
||||||
|
- [Ubuntu](#ubuntu)
|
||||||
|
- [Fedora/RHEL](#fedorarhel)
|
||||||
|
- [Arch Linux extra](#arch-linux-extra)
|
||||||
|
- [NixOS](#nixos)
|
||||||
|
- [Flatpak](#flatpak)
|
||||||
|
- [Snap](#snap)
|
||||||
|
- [AppImage](#appimage)
|
||||||
|
- [macOS](#macos)
|
||||||
|
- [Homebrew Core](#homebrew-core)
|
||||||
|
- [MacPorts](#macports)
|
||||||
|
- [Windows](#windows)
|
||||||
|
- [Winget](#winget)
|
||||||
|
- [Scoop](#scoop)
|
||||||
|
- [Chocolatey](#chocolatey)
|
||||||
|
- [MSYS2](#msys2)
|
||||||
|
|
||||||
|
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions)
|
||||||
|
|
||||||
|
## Linux
|
||||||
|
|
||||||
|
The following third party repositories are available:
|
||||||
|
|
||||||
|
### Ubuntu
|
||||||
|
|
||||||
|
Add the `PPA` for Helix:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo add-apt-repository ppa:maveonair/helix-editor
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fedora/RHEL
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo dnf install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### Arch Linux extra
|
||||||
|
|
||||||
|
Releases are available in the `extra` repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo pacman -S helix
|
||||||
|
```
|
||||||
|
|
||||||
|
> 💡 When installed from the `extra` repository, run Helix with `helix` instead of `hx`.
|
||||||
|
>
|
||||||
|
> For example:
|
||||||
|
> ```sh
|
||||||
|
> helix --health
|
||||||
|
> ```
|
||||||
|
> to check health
|
||||||
|
|
||||||
|
Additionally, a [helix-git](https://aur.archlinux.org/packages/helix-git/) package is available
|
||||||
|
in the AUR, which builds the master branch.
|
||||||
|
|
||||||
|
### NixOS
|
||||||
|
|
||||||
|
Helix is available in [nixpkgs](https://github.com/nixos/nixpkgs) through the `helix` attribute,
|
||||||
|
the unstable channel usually carries the latest release.
|
||||||
|
|
||||||
|
Helix is also available as a [flake](https://wiki.nixos.org/wiki/Flakes) in the project
|
||||||
|
root. Use `nix develop` to spin up a reproducible development shell. Outputs are
|
||||||
|
cached for each push to master using [Cachix](https://www.cachix.org/). The
|
||||||
|
flake is configured to automatically make use of this cache assuming the user
|
||||||
|
accepts the new settings on first use.
|
||||||
|
|
||||||
|
If you are using a version of Nix without flakes enabled,
|
||||||
|
[install Cachix CLI](https://docs.cachix.org/installation) and use
|
||||||
|
`cachix use helix` to configure Nix to use cached outputs when possible.
|
||||||
|
|
||||||
|
### Flatpak
|
||||||
|
|
||||||
|
Helix is available on [Flathub](https://flathub.org/en-GB/apps/com.helix_editor.Helix):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
flatpak install flathub com.helix_editor.Helix
|
||||||
|
flatpak run com.helix_editor.Helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### Snap
|
||||||
|
|
||||||
|
Helix is available on [Snapcraft](https://snapcraft.io/helix) and can be installed with:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
snap install --classic helix
|
||||||
|
```
|
||||||
|
|
||||||
|
This will install Helix as both `/snap/bin/helix` and `/snap/bin/hx`, so make sure `/snap/bin` is in your `PATH`.
|
||||||
|
|
||||||
|
### AppImage
|
||||||
|
|
||||||
|
Install Helix using the Linux [AppImage](https://appimage.org/) format.
|
||||||
|
Download the official Helix AppImage from the [latest releases](https://github.com/helix-editor/helix/releases/latest) page.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
chmod +x helix-*.AppImage # change permission for executable mode
|
||||||
|
./helix-*.AppImage # run helix
|
||||||
|
```
|
||||||
|
|
||||||
|
## macOS
|
||||||
|
|
||||||
|
### Homebrew Core
|
||||||
|
|
||||||
|
```sh
|
||||||
|
brew install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### MacPorts
|
||||||
|
|
||||||
|
```sh
|
||||||
|
port install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
## Windows
|
||||||
|
|
||||||
|
Install on Windows using [Winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/), [Scoop](https://scoop.sh/), [Chocolatey](https://chocolatey.org/)
|
||||||
|
or [MSYS2](https://msys2.org/).
|
||||||
|
|
||||||
|
### Winget
|
||||||
|
Windows Package Manager winget command-line tool is by default available on Windows 11 and modern versions of Windows 10 as a part of the App Installer.
|
||||||
|
You can get [App Installer from the Microsoft Store](https://www.microsoft.com/p/app-installer/9nblggh4nns1#activetab=pivot:overviewtab). If it's already installed, make sure it is updated with the latest version.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
winget install Helix.Helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scoop
|
||||||
|
|
||||||
|
```sh
|
||||||
|
scoop install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### Chocolatey
|
||||||
|
|
||||||
|
```sh
|
||||||
|
choco install helix
|
||||||
|
```
|
||||||
|
|
||||||
|
### MSYS2
|
||||||
|
|
||||||
|
For 64-bit Windows 8.1 or above:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pacman -S mingw-w64-ucrt-x86_64-helix
|
||||||
|
```
|
@ -0,0 +1,54 @@
|
|||||||
|
## Registers
|
||||||
|
|
||||||
|
- [User-defined registers](#user-defined-registers)
|
||||||
|
- [Default registers](#default-registers)
|
||||||
|
- [Special registers](#special-registers)
|
||||||
|
|
||||||
|
In Helix, registers are storage locations for text and other data, such as the
|
||||||
|
result of a search. Registers can be used to cut, copy, and paste text, similar
|
||||||
|
to the clipboard in other text editors. Usage is similar to Vim, with `"` being
|
||||||
|
used to select a register.
|
||||||
|
|
||||||
|
### User-defined registers
|
||||||
|
|
||||||
|
Helix allows you to create your own named registers for storing text, for
|
||||||
|
example:
|
||||||
|
|
||||||
|
- `"ay` - Yank the current selection to register `a`.
|
||||||
|
- `"op` - Paste the text in register `o` after the selection.
|
||||||
|
|
||||||
|
If a register is selected before invoking a change or delete command, the selection will be stored in the register and the action will be carried out:
|
||||||
|
|
||||||
|
- `"hc` - Store the selection in register `h` and then change it (delete and enter insert mode).
|
||||||
|
- `"md` - Store the selection in register `m` and delete it.
|
||||||
|
|
||||||
|
### Default registers
|
||||||
|
|
||||||
|
Commands that use registers, like yank (`y`), use a default register if none is specified.
|
||||||
|
These registers are used as defaults:
|
||||||
|
|
||||||
|
| Register character | Contains |
|
||||||
|
| --- | --- |
|
||||||
|
| `/` | Last search |
|
||||||
|
| `:` | Last executed command |
|
||||||
|
| `"` | Last yanked text |
|
||||||
|
| `@` | Last recorded macro |
|
||||||
|
|
||||||
|
### Special registers
|
||||||
|
|
||||||
|
Some registers have special behavior when read from and written to.
|
||||||
|
|
||||||
|
| Register character | When read | When written |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `_` | No values are returned | All values are discarded |
|
||||||
|
| `#` | Selection indices (first selection is `1`, second is `2`, etc.) | This register is not writable |
|
||||||
|
| `.` | Contents of the current selections | This register is not writable |
|
||||||
|
| `%` | Name of the current file | This register is not writable |
|
||||||
|
| `+` | Reads from the system clipboard | Joins and yanks to the system clipboard |
|
||||||
|
| `*` | Reads from the primary clipboard | Joins and yanks to the primary clipboard |
|
||||||
|
|
||||||
|
When yanking multiple selections to the clipboard registers, the selections
|
||||||
|
are joined with newlines. Pasting from these registers will paste multiple
|
||||||
|
selections if the clipboard was last yanked to by the Helix session. Otherwise
|
||||||
|
the clipboard contents are pasted as one selection.
|
||||||
|
|
@ -0,0 +1,24 @@
|
|||||||
|
## Surround
|
||||||
|
|
||||||
|
Helix includes built-in functionality similar to [vim-surround](https://github.com/tpope/vim-surround).
|
||||||
|
The keymappings have been inspired from [vim-sandwich](https://github.com/machakann/vim-sandwich):
|
||||||
|
|
||||||
|
![Surround demo](https://user-images.githubusercontent.com/23398472/122865801-97073180-d344-11eb-8142-8f43809982c6.gif)
|
||||||
|
|
||||||
|
| Key Sequence | Action |
|
||||||
|
| --------------------------------- | --------------------------------------- |
|
||||||
|
| `ms<char>` (after selecting text) | Add surround characters to selection |
|
||||||
|
| `mr<char_to_replace><new_char>` | Replace the closest surround characters |
|
||||||
|
| `md<char_to_delete>` | Delete the closest surround characters |
|
||||||
|
|
||||||
|
You can use counts to act on outer pairs.
|
||||||
|
|
||||||
|
Surround can also act on multiple selections. For example, to change every occurrence of `(use)` to `[use]`:
|
||||||
|
|
||||||
|
1. `%` to select the whole file
|
||||||
|
2. `s` to split the selections on a search term
|
||||||
|
3. Input `use` and hit Enter
|
||||||
|
4. `mr([` to replace the parentheses with square brackets
|
||||||
|
|
||||||
|
Multiple characters are currently not supported, but planned for future release.
|
||||||
|
|
@ -0,0 +1,66 @@
|
|||||||
|
## Moving the selection with syntax-aware motions
|
||||||
|
|
||||||
|
`Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) allow you to move the
|
||||||
|
selection according to its location in the syntax tree. For example, many languages have the
|
||||||
|
following syntax for function calls:
|
||||||
|
|
||||||
|
```js
|
||||||
|
func(arg1, arg2, arg3);
|
||||||
|
```
|
||||||
|
|
||||||
|
A function call might be parsed by tree-sitter into a tree like the following.
|
||||||
|
|
||||||
|
```tsq
|
||||||
|
(call
|
||||||
|
function: (identifier) ; func
|
||||||
|
arguments:
|
||||||
|
(arguments ; (arg1, arg2, arg3)
|
||||||
|
(identifier) ; arg1
|
||||||
|
(identifier) ; arg2
|
||||||
|
(identifier))) ; arg3
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `:tree-sitter-subtree` to view the syntax tree of the primary selection. In
|
||||||
|
a more intuitive tree format:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────┐
|
||||||
|
│call│
|
||||||
|
┌─────┴────┴─────┐
|
||||||
|
│ │
|
||||||
|
┌─────▼────┐ ┌────▼────┐
|
||||||
|
│identifier│ │arguments│
|
||||||
|
│ "func" │ ┌────┴───┬─────┴───┐
|
||||||
|
└──────────┘ │ │ │
|
||||||
|
│ │ │
|
||||||
|
┌─────────▼┐ ┌────▼─────┐ ┌▼─────────┐
|
||||||
|
│identifier│ │identifier│ │identifier│
|
||||||
|
│ "arg1" │ │ "arg2" │ │ "arg3" │
|
||||||
|
└──────────┘ └──────────┘ └──────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
If you have a selection that wraps `arg1` (see the tree above), and you use
|
||||||
|
`Alt-n`, it will select the next sibling in the syntax tree: `arg2`.
|
||||||
|
|
||||||
|
```js
|
||||||
|
// before
|
||||||
|
func([arg1], arg2, arg3)
|
||||||
|
// after
|
||||||
|
func(arg1, [arg2], arg3);
|
||||||
|
```
|
||||||
|
|
||||||
|
Similarly, `Alt-o` will expand the selection to the parent node, in this case, the
|
||||||
|
arguments node.
|
||||||
|
|
||||||
|
```js
|
||||||
|
func[(arg1, arg2, arg3)];
|
||||||
|
```
|
||||||
|
|
||||||
|
There is also some nuanced behavior that prevents you from getting stuck on a
|
||||||
|
node with no sibling. When using `Alt-p` with a selection on `arg1`, the previous
|
||||||
|
child node will be selected. In the event that `arg1` does not have a previous
|
||||||
|
sibling, the selection will move up the syntax tree and select the previous
|
||||||
|
element. As a result, using `Alt-p` with a selection on `arg1` will move the
|
||||||
|
selection to the "func" `identifier`.
|
||||||
|
|
||||||
|
[lang-support]: ./lang-support.md
|
@ -0,0 +1,47 @@
|
|||||||
|
## Selecting and manipulating text with textobjects
|
||||||
|
|
||||||
|
In Helix, textobjects are a way to select, manipulate and operate on a piece of
|
||||||
|
text in a structured way. They allow you to refer to blocks of text based on
|
||||||
|
their structure or purpose, such as a word, sentence, paragraph, or even a
|
||||||
|
function or block of code.
|
||||||
|
|
||||||
|
![Textobject demo](https://user-images.githubusercontent.com/23398472/124231131-81a4bb00-db2d-11eb-9d10-8e577ca7b177.gif)
|
||||||
|
![Textobject tree-sitter demo](https://user-images.githubusercontent.com/23398472/132537398-2a2e0a54-582b-44ab-a77f-eb818942203d.gif)
|
||||||
|
|
||||||
|
- `ma` - Select around the object (`va` in Vim, `<alt-a>` in Kakoune)
|
||||||
|
- `mi` - Select inside the object (`vi` in Vim, `<alt-i>` in Kakoune)
|
||||||
|
|
||||||
|
| Key after `mi` or `ma` | Textobject selected |
|
||||||
|
| --- | --- |
|
||||||
|
| `w` | Word |
|
||||||
|
| `W` | WORD |
|
||||||
|
| `p` | Paragraph |
|
||||||
|
| `(`, `[`, `'`, etc. | Specified surround pairs |
|
||||||
|
| `m` | The closest surround pair |
|
||||||
|
| `f` | Function |
|
||||||
|
| `t` | Type (or Class) |
|
||||||
|
| `a` | Argument/parameter |
|
||||||
|
| `c` | Comment |
|
||||||
|
| `T` | Test |
|
||||||
|
| `g` | Change |
|
||||||
|
|
||||||
|
> 💡 `f`, `t`, etc. need a tree-sitter grammar active for the current
|
||||||
|
document and a special tree-sitter query file to work properly. [Only
|
||||||
|
some grammars](./lang-support.md) currently have the query file implemented.
|
||||||
|
Contributions are welcome!
|
||||||
|
|
||||||
|
## Navigating using tree-sitter textobjects
|
||||||
|
|
||||||
|
Navigating between functions, classes, parameters, and other elements is
|
||||||
|
possible using tree-sitter and textobject queries. For
|
||||||
|
example to move to the next function use `]f`, to move to previous
|
||||||
|
type use `[t`, and so on.
|
||||||
|
|
||||||
|
![Tree-sitter-nav-demo](https://user-images.githubusercontent.com/23398472/152332550-7dfff043-36a2-4aec-b8f2-77c13eb56d6f.gif)
|
||||||
|
|
||||||
|
For the full reference see the [unimpaired](./keymap.html#unimpaired) section of the key bind
|
||||||
|
documentation.
|
||||||
|
|
||||||
|
> 💡 This feature relies on tree-sitter textobjects
|
||||||
|
> and requires the corresponding query file to work properly.
|
||||||
|
|
@ -1,15 +1,18 @@
|
|||||||
#!/usr/bin/env fish
|
#!/usr/bin/env fish
|
||||||
# Fish completion script for Helix editor
|
# Fish completion script for Helix editor
|
||||||
|
|
||||||
set -l langs (hx --health |tail -n '+7' |awk '{print $1}' |sed 's/\x1b\[[0-9;]*m//g')
|
|
||||||
|
|
||||||
complete -c hx -s h -l help -d "Prints help information"
|
complete -c hx -s h -l help -d "Prints help information"
|
||||||
complete -c hx -l tutor -d "Loads the tutorial"
|
complete -c hx -l tutor -d "Loads the tutorial"
|
||||||
complete -c hx -l health -x -a "$langs" -d "Checks for errors in editor setup"
|
complete -c hx -l health -xa "(__hx_langs_ops)" -d "Checks for errors"
|
||||||
complete -c hx -s g -l grammar -x -a "fetch build" -d "Fetches or builds tree-sitter grammars"
|
complete -c hx -s g -l grammar -x -a "fetch build" -d "Fetch or build tree-sitter grammars"
|
||||||
complete -c hx -s v -o vv -o vvv -d "Increases logging verbosity"
|
complete -c hx -s v -o vv -o vvv -d "Increases logging verbosity"
|
||||||
complete -c hx -s V -l version -d "Prints version information"
|
complete -c hx -s V -l version -d "Prints version information"
|
||||||
complete -c hx -l vsplit -d "Splits all given files vertically into different windows"
|
complete -c hx -l vsplit -d "Splits all given files vertically"
|
||||||
complete -c hx -l hsplit -d "Splits all given files horizontally into different windows"
|
complete -c hx -l hsplit -d "Splits all given files horizontally"
|
||||||
complete -c hx -s c -l config -r -d "Specifies a file to use for completion"
|
complete -c hx -s c -l config -r -d "Specifies a file to use for config"
|
||||||
complete -c hx -l log -r -d "Specifies a file to write log data into"
|
complete -c hx -l log -r -d "Specifies a file to use for logging"
|
||||||
|
complete -c hx -s w -l working-dir -d "Specify initial working directory" -xa "(__fish_complete_directories)"
|
||||||
|
|
||||||
|
function __hx_langs_ops
|
||||||
|
hx --health languages | tail -n '+2' | string replace -fr '^(\S+) .*' '$1'
|
||||||
|
end
|
||||||
|
@ -0,0 +1,122 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// A generic pointer to a file location.
|
||||||
|
///
|
||||||
|
/// Currently this type only supports paths to local files.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum Uri {
|
||||||
|
File(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Uri {
|
||||||
|
// This clippy allow mirrors url::Url::from_file_path
|
||||||
|
#[allow(clippy::result_unit_err)]
|
||||||
|
pub fn to_url(&self) -> Result<url::Url, ()> {
|
||||||
|
match self {
|
||||||
|
Uri::File(path) => url::Url::from_file_path(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_path(&self) -> Option<&Path> {
|
||||||
|
match self {
|
||||||
|
Self::File(path) => Some(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_path_buf(self) -> Option<PathBuf> {
|
||||||
|
match self {
|
||||||
|
Self::File(path) => Some(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<PathBuf> for Uri {
|
||||||
|
fn from(path: PathBuf) -> Self {
|
||||||
|
Self::File(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<Uri> for PathBuf {
|
||||||
|
type Error = ();
|
||||||
|
|
||||||
|
fn try_from(uri: Uri) -> Result<Self, Self::Error> {
|
||||||
|
match uri {
|
||||||
|
Uri::File(path) => Ok(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct UrlConversionError {
|
||||||
|
source: url::Url,
|
||||||
|
kind: UrlConversionErrorKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum UrlConversionErrorKind {
|
||||||
|
UnsupportedScheme,
|
||||||
|
UnableToConvert,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for UrlConversionError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self.kind {
|
||||||
|
UrlConversionErrorKind::UnsupportedScheme => {
|
||||||
|
write!(f, "unsupported scheme in URL: {}", self.source.scheme())
|
||||||
|
}
|
||||||
|
UrlConversionErrorKind::UnableToConvert => {
|
||||||
|
write!(f, "unable to convert URL to file path: {}", self.source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for UrlConversionError {}
|
||||||
|
|
||||||
|
fn convert_url_to_uri(url: &url::Url) -> Result<Uri, UrlConversionErrorKind> {
|
||||||
|
if url.scheme() == "file" {
|
||||||
|
url.to_file_path()
|
||||||
|
.map(|path| Uri::File(helix_stdx::path::normalize(path)))
|
||||||
|
.map_err(|_| UrlConversionErrorKind::UnableToConvert)
|
||||||
|
} else {
|
||||||
|
Err(UrlConversionErrorKind::UnsupportedScheme)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<url::Url> for Uri {
|
||||||
|
type Error = UrlConversionError;
|
||||||
|
|
||||||
|
fn try_from(url: url::Url) -> Result<Self, Self::Error> {
|
||||||
|
convert_url_to_uri(&url).map_err(|kind| Self::Error { source: url, kind })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&url::Url> for Uri {
|
||||||
|
type Error = UrlConversionError;
|
||||||
|
|
||||||
|
fn try_from(url: &url::Url) -> Result<Self, Self::Error> {
|
||||||
|
convert_url_to_uri(url).map_err(|kind| Self::Error {
|
||||||
|
source: url.clone(),
|
||||||
|
kind,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_scheme() {
|
||||||
|
let url = Url::parse("csharp:/metadata/foo/bar/Baz.cs").unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
Uri::try_from(url),
|
||||||
|
Err(UrlConversionError {
|
||||||
|
kind: UrlConversionErrorKind::UnsupportedScheme,
|
||||||
|
..
|
||||||
|
})
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,117 @@
|
|||||||
|
use std::{
|
||||||
|
sync::{
|
||||||
|
atomic::{self, AtomicBool},
|
||||||
|
Arc,
|
||||||
|
},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use anyhow::Ok;
|
||||||
|
use arc_swap::access::Access;
|
||||||
|
|
||||||
|
use helix_event::{register_hook, send_blocking};
|
||||||
|
use helix_view::{
|
||||||
|
document::Mode,
|
||||||
|
events::DocumentDidChange,
|
||||||
|
handlers::{AutoSaveEvent, Handlers},
|
||||||
|
Editor,
|
||||||
|
};
|
||||||
|
use tokio::time::Instant;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
commands, compositor,
|
||||||
|
events::OnModeSwitch,
|
||||||
|
job::{self, Jobs},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) struct AutoSaveHandler {
|
||||||
|
save_pending: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AutoSaveHandler {
|
||||||
|
pub fn new() -> AutoSaveHandler {
|
||||||
|
AutoSaveHandler {
|
||||||
|
save_pending: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl helix_event::AsyncHook for AutoSaveHandler {
|
||||||
|
type Event = AutoSaveEvent;
|
||||||
|
|
||||||
|
fn handle_event(
|
||||||
|
&mut self,
|
||||||
|
event: Self::Event,
|
||||||
|
existing_debounce: Option<tokio::time::Instant>,
|
||||||
|
) -> Option<Instant> {
|
||||||
|
match event {
|
||||||
|
Self::Event::DocumentChanged { save_after } => {
|
||||||
|
Some(Instant::now() + Duration::from_millis(save_after))
|
||||||
|
}
|
||||||
|
Self::Event::LeftInsertMode => {
|
||||||
|
if existing_debounce.is_some() {
|
||||||
|
// If the change happened more recently than the debounce, let the
|
||||||
|
// debounce run down before saving.
|
||||||
|
existing_debounce
|
||||||
|
} else {
|
||||||
|
// Otherwise if there is a save pending, save immediately.
|
||||||
|
if self.save_pending.load(atomic::Ordering::Relaxed) {
|
||||||
|
self.finish_debounce();
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_debounce(&mut self) {
|
||||||
|
let save_pending = self.save_pending.clone();
|
||||||
|
job::dispatch_blocking(move |editor, _| {
|
||||||
|
if editor.mode() == Mode::Insert {
|
||||||
|
// Avoid saving while in insert mode since this mixes up
|
||||||
|
// the modification indicator and prevents future saves.
|
||||||
|
save_pending.store(true, atomic::Ordering::Relaxed);
|
||||||
|
} else {
|
||||||
|
request_auto_save(editor);
|
||||||
|
save_pending.store(false, atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_auto_save(editor: &mut Editor) {
|
||||||
|
let context = &mut compositor::Context {
|
||||||
|
editor,
|
||||||
|
scroll: Some(0),
|
||||||
|
jobs: &mut Jobs::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = commands::typed::write_all_impl(context, false, false) {
|
||||||
|
context.editor.set_error(format!("{}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn register_hooks(handlers: &Handlers) {
|
||||||
|
let tx = handlers.auto_save.clone();
|
||||||
|
register_hook!(move |event: &mut DocumentDidChange<'_>| {
|
||||||
|
let config = event.doc.config.load();
|
||||||
|
if config.auto_save.after_delay.enable {
|
||||||
|
send_blocking(
|
||||||
|
&tx,
|
||||||
|
AutoSaveEvent::DocumentChanged {
|
||||||
|
save_after: config.auto_save.after_delay.timeout,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
let tx = handlers.auto_save.clone();
|
||||||
|
register_hook!(move |event: &mut OnModeSwitch<'_, '_>| {
|
||||||
|
if event.old_mode == Mode::Insert {
|
||||||
|
send_blocking(&tx, AutoSaveEvent::LeftInsertMode)
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
use helix_event::{register_hook, send_blocking};
|
||||||
|
use helix_view::document::Mode;
|
||||||
|
use helix_view::events::DiagnosticsDidChange;
|
||||||
|
use helix_view::handlers::diagnostics::DiagnosticEvent;
|
||||||
|
use helix_view::handlers::Handlers;
|
||||||
|
|
||||||
|
use crate::events::OnModeSwitch;
|
||||||
|
|
||||||
|
pub(super) fn register_hooks(_handlers: &Handlers) {
|
||||||
|
register_hook!(move |event: &mut DiagnosticsDidChange<'_>| {
|
||||||
|
if event.editor.mode != Mode::Insert {
|
||||||
|
for (view, _) in event.editor.tree.views_mut() {
|
||||||
|
send_blocking(&view.diagnostics_handler.events, DiagnosticEvent::Refresh)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
register_hook!(move |event: &mut OnModeSwitch<'_, '_>| {
|
||||||
|
for (view, _) in event.cx.editor.tree.views_mut() {
|
||||||
|
view.diagnostics_handler.active = event.new_mode != Mode::Insert;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,182 @@
|
|||||||
|
use std::{
|
||||||
|
path::Path,
|
||||||
|
sync::{atomic, Arc},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use helix_event::AsyncHook;
|
||||||
|
use tokio::time::Instant;
|
||||||
|
|
||||||
|
use crate::{job, ui::overlay::Overlay};
|
||||||
|
|
||||||
|
use super::{CachedPreview, DynQueryCallback, Picker};
|
||||||
|
|
||||||
|
pub(super) struct PreviewHighlightHandler<T: 'static + Send + Sync, D: 'static + Send + Sync> {
|
||||||
|
trigger: Option<Arc<Path>>,
|
||||||
|
phantom_data: std::marker::PhantomData<(T, D)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static + Send + Sync, D: 'static + Send + Sync> Default for PreviewHighlightHandler<T, D> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
trigger: None,
|
||||||
|
phantom_data: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static + Send + Sync, D: 'static + Send + Sync> AsyncHook
|
||||||
|
for PreviewHighlightHandler<T, D>
|
||||||
|
{
|
||||||
|
type Event = Arc<Path>;
|
||||||
|
|
||||||
|
fn handle_event(
|
||||||
|
&mut self,
|
||||||
|
path: Self::Event,
|
||||||
|
timeout: Option<tokio::time::Instant>,
|
||||||
|
) -> Option<tokio::time::Instant> {
|
||||||
|
if self
|
||||||
|
.trigger
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|trigger| trigger == &path)
|
||||||
|
{
|
||||||
|
// If the path hasn't changed, don't reset the debounce
|
||||||
|
timeout
|
||||||
|
} else {
|
||||||
|
self.trigger = Some(path);
|
||||||
|
Some(Instant::now() + Duration::from_millis(150))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_debounce(&mut self) {
|
||||||
|
let Some(path) = self.trigger.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
job::dispatch_blocking(move |editor, compositor| {
|
||||||
|
let Some(Overlay {
|
||||||
|
content: picker, ..
|
||||||
|
}) = compositor.find::<Overlay<Picker<T, D>>>()
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(CachedPreview::Document(ref mut doc)) = picker.preview_cache.get_mut(&path)
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
if doc.language_config().is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(language_config) = doc.detect_language_config(&editor.syn_loader.load())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
doc.language = Some(language_config.clone());
|
||||||
|
let text = doc.text().clone();
|
||||||
|
let loader = editor.syn_loader.clone();
|
||||||
|
|
||||||
|
tokio::task::spawn_blocking(move || {
|
||||||
|
let Some(syntax) = language_config
|
||||||
|
.highlight_config(&loader.load().scopes())
|
||||||
|
.and_then(|highlight_config| {
|
||||||
|
helix_core::Syntax::new(text.slice(..), highlight_config, loader)
|
||||||
|
})
|
||||||
|
else {
|
||||||
|
log::info!("highlighting picker item failed");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
job::dispatch_blocking(move |editor, compositor| {
|
||||||
|
let Some(Overlay {
|
||||||
|
content: picker, ..
|
||||||
|
}) = compositor.find::<Overlay<Picker<T, D>>>()
|
||||||
|
else {
|
||||||
|
log::info!("picker closed before syntax highlighting finished");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(CachedPreview::Document(ref mut doc)) =
|
||||||
|
picker.preview_cache.get_mut(&path)
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let diagnostics = helix_view::Editor::doc_diagnostics(
|
||||||
|
&editor.language_servers,
|
||||||
|
&editor.diagnostics,
|
||||||
|
doc,
|
||||||
|
);
|
||||||
|
doc.replace_diagnostics(diagnostics, &[], None);
|
||||||
|
doc.syntax = Some(syntax);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct DynamicQueryHandler<T: 'static + Send + Sync, D: 'static + Send + Sync> {
|
||||||
|
callback: Arc<DynQueryCallback<T, D>>,
|
||||||
|
// Duration used as a debounce.
|
||||||
|
// Defaults to 100ms if not provided via `Picker::with_dynamic_query`. Callers may want to set
|
||||||
|
// this higher if the dynamic query is expensive - for example global search.
|
||||||
|
debounce: Duration,
|
||||||
|
last_query: Arc<str>,
|
||||||
|
query: Option<Arc<str>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static + Send + Sync, D: 'static + Send + Sync> DynamicQueryHandler<T, D> {
|
||||||
|
pub(super) fn new(callback: DynQueryCallback<T, D>, duration_ms: Option<u64>) -> Self {
|
||||||
|
Self {
|
||||||
|
callback: Arc::new(callback),
|
||||||
|
debounce: Duration::from_millis(duration_ms.unwrap_or(100)),
|
||||||
|
last_query: "".into(),
|
||||||
|
query: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static + Send + Sync, D: 'static + Send + Sync> AsyncHook for DynamicQueryHandler<T, D> {
|
||||||
|
type Event = Arc<str>;
|
||||||
|
|
||||||
|
fn handle_event(&mut self, query: Self::Event, _timeout: Option<Instant>) -> Option<Instant> {
|
||||||
|
if query == self.last_query {
|
||||||
|
// If the search query reverts to the last one we requested, no need to
|
||||||
|
// make a new request.
|
||||||
|
self.query = None;
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
self.query = Some(query);
|
||||||
|
Some(Instant::now() + self.debounce)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_debounce(&mut self) {
|
||||||
|
let Some(query) = self.query.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.last_query = query.clone();
|
||||||
|
let callback = self.callback.clone();
|
||||||
|
|
||||||
|
job::dispatch_blocking(move |editor, compositor| {
|
||||||
|
let Some(Overlay {
|
||||||
|
content: picker, ..
|
||||||
|
}) = compositor.find::<Overlay<Picker<T, D>>>()
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// Increment the version number to cancel any ongoing requests.
|
||||||
|
picker.version.fetch_add(1, atomic::Ordering::Relaxed);
|
||||||
|
picker.matcher.restart(false);
|
||||||
|
let injector = picker.injector();
|
||||||
|
let get_options = (callback)(&query, editor, picker.editor_data.clone(), &injector);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(err) = get_options.await {
|
||||||
|
log::info!("Dynamic request failed: {err}");
|
||||||
|
}
|
||||||
|
// NOTE: the Drop implementation of Injector will request a redraw when the
|
||||||
|
// injector falls out of scope here, clearing the "running" indicator.
|
||||||
|
});
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,368 @@
|
|||||||
|
use std::{collections::HashMap, mem, ops::Range, sync::Arc};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) struct PickerQuery {
|
||||||
|
/// The column names of the picker.
|
||||||
|
column_names: Box<[Arc<str>]>,
|
||||||
|
/// The index of the primary column in `column_names`.
|
||||||
|
/// The primary column is selected by default unless another
|
||||||
|
/// field is specified explicitly with `%fieldname`.
|
||||||
|
primary_column: usize,
|
||||||
|
/// The mapping between column names and input in the query
|
||||||
|
/// for those columns.
|
||||||
|
inner: HashMap<Arc<str>, Arc<str>>,
|
||||||
|
/// The byte ranges of the input text which are used as input for each column.
|
||||||
|
/// This is calculated at parsing time for use in [Self::active_column].
|
||||||
|
/// This Vec is naturally sorted in ascending order and ranges do not overlap.
|
||||||
|
column_ranges: Vec<(Range<usize>, Option<Arc<str>>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq<HashMap<Arc<str>, Arc<str>>> for PickerQuery {
|
||||||
|
fn eq(&self, other: &HashMap<Arc<str>, Arc<str>>) -> bool {
|
||||||
|
self.inner.eq(other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PickerQuery {
|
||||||
|
pub(super) fn new<I: Iterator<Item = Arc<str>>>(
|
||||||
|
column_names: I,
|
||||||
|
primary_column: usize,
|
||||||
|
) -> Self {
|
||||||
|
let column_names: Box<[_]> = column_names.collect();
|
||||||
|
let inner = HashMap::with_capacity(column_names.len());
|
||||||
|
let column_ranges = vec![(0..usize::MAX, Some(column_names[primary_column].clone()))];
|
||||||
|
Self {
|
||||||
|
column_names,
|
||||||
|
primary_column,
|
||||||
|
inner,
|
||||||
|
column_ranges,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn get(&self, column: &str) -> Option<&Arc<str>> {
|
||||||
|
self.inner.get(column)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn parse(&mut self, input: &str) -> HashMap<Arc<str>, Arc<str>> {
|
||||||
|
let mut fields: HashMap<Arc<str>, String> = HashMap::new();
|
||||||
|
let primary_field = &self.column_names[self.primary_column];
|
||||||
|
let mut escaped = false;
|
||||||
|
let mut in_field = false;
|
||||||
|
let mut field = None;
|
||||||
|
let mut text = String::new();
|
||||||
|
self.column_ranges.clear();
|
||||||
|
self.column_ranges
|
||||||
|
.push((0..usize::MAX, Some(primary_field.clone())));
|
||||||
|
|
||||||
|
macro_rules! finish_field {
|
||||||
|
() => {
|
||||||
|
let key = field.take().unwrap_or(primary_field);
|
||||||
|
|
||||||
|
if let Some(pattern) = fields.get_mut(key) {
|
||||||
|
pattern.push(' ');
|
||||||
|
pattern.push_str(text.trim());
|
||||||
|
} else {
|
||||||
|
fields.insert(key.clone(), text.trim().to_string());
|
||||||
|
}
|
||||||
|
text.clear();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
for (idx, ch) in input.char_indices() {
|
||||||
|
match ch {
|
||||||
|
// Backslash escaping
|
||||||
|
_ if escaped => {
|
||||||
|
// '%' is the only character that is special cased.
|
||||||
|
// You can escape it to prevent parsing the text that
|
||||||
|
// follows it as a field name.
|
||||||
|
if ch != '%' {
|
||||||
|
text.push('\\');
|
||||||
|
}
|
||||||
|
text.push(ch);
|
||||||
|
escaped = false;
|
||||||
|
}
|
||||||
|
'\\' => escaped = !escaped,
|
||||||
|
'%' => {
|
||||||
|
if !text.is_empty() {
|
||||||
|
finish_field!();
|
||||||
|
}
|
||||||
|
let (range, _field) = self
|
||||||
|
.column_ranges
|
||||||
|
.last_mut()
|
||||||
|
.expect("column_ranges is non-empty");
|
||||||
|
range.end = idx;
|
||||||
|
in_field = true;
|
||||||
|
}
|
||||||
|
' ' if in_field => {
|
||||||
|
text.clear();
|
||||||
|
in_field = false;
|
||||||
|
}
|
||||||
|
_ if in_field => {
|
||||||
|
text.push(ch);
|
||||||
|
// Go over all columns and their indices, find all that starts with field key,
|
||||||
|
// select a column that fits key the most.
|
||||||
|
field = self
|
||||||
|
.column_names
|
||||||
|
.iter()
|
||||||
|
.filter(|col| col.starts_with(&text))
|
||||||
|
// select "fittest" column
|
||||||
|
.min_by_key(|col| col.len());
|
||||||
|
|
||||||
|
// Update the column range for this column.
|
||||||
|
if let Some((_range, current_field)) = self
|
||||||
|
.column_ranges
|
||||||
|
.last_mut()
|
||||||
|
.filter(|(range, _)| range.end == usize::MAX)
|
||||||
|
{
|
||||||
|
*current_field = field.cloned();
|
||||||
|
} else {
|
||||||
|
self.column_ranges.push((idx..usize::MAX, field.cloned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => text.push(ch),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !in_field && !text.is_empty() {
|
||||||
|
finish_field!();
|
||||||
|
}
|
||||||
|
|
||||||
|
let new_inner: HashMap<_, _> = fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|(field, query)| (field, query.as_str().into()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
mem::replace(&mut self.inner, new_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the column which the cursor is 'within' in the last parse.
|
||||||
|
///
|
||||||
|
/// The cursor is considered to be within a column when it is placed within any
|
||||||
|
/// of a column's text. See the `active_column_test` unit test below for examples.
|
||||||
|
///
|
||||||
|
/// `cursor` is a byte index that represents the location of the prompt's cursor.
|
||||||
|
pub fn active_column(&self, cursor: usize) -> Option<&Arc<str>> {
|
||||||
|
let point = self
|
||||||
|
.column_ranges
|
||||||
|
.partition_point(|(range, _field)| cursor > range.end);
|
||||||
|
|
||||||
|
self.column_ranges
|
||||||
|
.get(point)
|
||||||
|
.filter(|(range, _field)| cursor >= range.start && cursor <= range.end)
|
||||||
|
.and_then(|(_range, field)| field.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use helix_core::hashmap;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_query_test() {
|
||||||
|
let mut query = PickerQuery::new(
|
||||||
|
[
|
||||||
|
"primary".into(),
|
||||||
|
"field1".into(),
|
||||||
|
"field2".into(),
|
||||||
|
"another".into(),
|
||||||
|
"anode".into(),
|
||||||
|
]
|
||||||
|
.into_iter(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Basic field splitting
|
||||||
|
query.parse("hello world");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello world".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse("hello %field1 world %field2 !");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"field1".into() => "world".into(),
|
||||||
|
"field2".into() => "!".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse("%field1 abc %field2 def xyz");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"field1".into() => "abc".into(),
|
||||||
|
"field2".into() => "def xyz".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Trailing space is trimmed
|
||||||
|
query.parse("hello ");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Unknown fields are trimmed.
|
||||||
|
query.parse("hello %foo");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Multiple words in a field
|
||||||
|
query.parse("hello %field1 a b c");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"field1".into() => "a b c".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Escaping
|
||||||
|
query.parse(r#"hello\ world"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => r#"hello\ world"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"hello \%field1 world"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello %field1 world".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"%field1 hello\ world"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"field1".into() => r#"hello\ world"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"hello %field1 a\"b"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"field1".into() => r#"a\"b"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"%field1 hello\ world"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"field1".into() => r#"hello\ world"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"\bfoo\b"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => r#"\bfoo\b"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse(r#"\\n"#);
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => r#"\\n"#.into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Only the prefix of a field is required.
|
||||||
|
query.parse("hello %anot abc");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"another".into() => "abc".into(),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
// The shortest matching the prefix is selected.
|
||||||
|
query.parse("hello %ano abc");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"anode".into() => "abc".into()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
// Multiple uses of a column are concatenated with space separators.
|
||||||
|
query.parse("hello %field1 xyz %fie abc");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"field1".into() => "xyz abc".into()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
query.parse("hello %fie abc");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello".into(),
|
||||||
|
"field1".into() => "abc".into()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
// The primary column can be explicitly qualified.
|
||||||
|
query.parse("hello %fie abc %prim world");
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
hashmap!(
|
||||||
|
"primary".into() => "hello world".into(),
|
||||||
|
"field1".into() => "abc".into()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn active_column_test() {
|
||||||
|
fn active_column<'a>(query: &'a mut PickerQuery, input: &str) -> Option<&'a str> {
|
||||||
|
let cursor = input.find('|').expect("cursor must be indicated with '|'");
|
||||||
|
let input = input.replace('|', "");
|
||||||
|
query.parse(&input);
|
||||||
|
query.active_column(cursor).map(AsRef::as_ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut query = PickerQuery::new(
|
||||||
|
["primary".into(), "foo".into(), "bar".into()].into_iter(),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(active_column(&mut query, "|"), Some("primary"));
|
||||||
|
assert_eq!(active_column(&mut query, "hello| world"), Some("primary"));
|
||||||
|
assert_eq!(active_column(&mut query, "|%foo hello"), Some("primary"));
|
||||||
|
assert_eq!(active_column(&mut query, "%foo|"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "%|"), None);
|
||||||
|
assert_eq!(active_column(&mut query, "%baz|"), None);
|
||||||
|
assert_eq!(active_column(&mut query, "%quiz%|"), None);
|
||||||
|
assert_eq!(active_column(&mut query, "%foo hello| world"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "%foo hello world|"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "%foo| hello world"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "%|foo hello world"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "%f|oo hello world"), Some("foo"));
|
||||||
|
assert_eq!(active_column(&mut query, "hello %f|oo world"), Some("foo"));
|
||||||
|
assert_eq!(
|
||||||
|
active_column(&mut query, "hello %f|oo world %bar !"),
|
||||||
|
Some("foo")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
active_column(&mut query, "hello %foo wo|rld %bar !"),
|
||||||
|
Some("foo")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
active_column(&mut query, "hello %foo world %bar !|"),
|
||||||
|
Some("bar")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,175 @@
|
|||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
|
use helix_core::doc_formatter::FormattedGrapheme;
|
||||||
|
use helix_core::Position;
|
||||||
|
use helix_view::editor::CursorCache;
|
||||||
|
|
||||||
|
use crate::ui::document::{LinePos, TextRenderer};
|
||||||
|
|
||||||
|
pub use diagnostics::InlineDiagnostics;
|
||||||
|
|
||||||
|
mod diagnostics;
|
||||||
|
|
||||||
|
/// Decorations are the primary mechanism for extending the text rendering.
|
||||||
|
///
|
||||||
|
/// Any on-screen element which is anchored to the rendered text in some form
|
||||||
|
/// should be implemented using this trait. Translating char positions to
|
||||||
|
/// on-screen positions can be expensive and should not be done manually in the
|
||||||
|
/// ui loop. Instead such translations are automatically performed on the fly
|
||||||
|
/// while the text is being rendered. The results are provided to this trait by
|
||||||
|
/// the rendering infrastructure.
|
||||||
|
///
|
||||||
|
/// To reserve space for virtual text lines (which is then filled by this trait) emit appropriate
|
||||||
|
/// [`LineAnnotation`](helix_core::text_annotations::LineAnnotation)s in [`helix_view::View::text_annotations`]
|
||||||
|
pub trait Decoration {
|
||||||
|
/// Called **before** a **visual** line is rendered. A visual line does not
|
||||||
|
/// necessarily correspond to a single line in a document as soft wrapping can
|
||||||
|
/// spread a single document line across multiple visual lines.
|
||||||
|
///
|
||||||
|
/// This function is called before text is rendered as any decorations should
|
||||||
|
/// never overlap the document text. That means that setting the forground color
|
||||||
|
/// here is (essentially) useless as the text color is overwritten by the
|
||||||
|
/// rendered text. This _of course_ doesn't apply when rendering inside virtual lines
|
||||||
|
/// below the line reserved by `LineAnnotation`s as no text will be rendered here.
|
||||||
|
fn decorate_line(&mut self, _renderer: &mut TextRenderer, _pos: LinePos) {}
|
||||||
|
|
||||||
|
/// Called **after** a **visual** line is rendered. A visual line does not
|
||||||
|
/// necessarily correspond to a single line in a document as soft wrapping can
|
||||||
|
/// spread a single document line across multiple visual lines.
|
||||||
|
///
|
||||||
|
/// This function is called after text is rendered so that decorations can collect
|
||||||
|
/// horizontal positions on the line (see [`Decoration::decorate_grapheme`]) first and
|
||||||
|
/// use those positions` while rendering
|
||||||
|
/// virtual text.
|
||||||
|
/// That means that setting the forground color
|
||||||
|
/// here is (essentially) useless as the text color is overwritten by the
|
||||||
|
/// rendered text. This -ofcourse- doesn't apply when rendering inside virtual lines
|
||||||
|
/// below the line reserved by `LineAnnotation`s. e as no text will be rendered here.
|
||||||
|
/// **Note**: To avoid overlapping decorations in the virtual lines, each decoration
|
||||||
|
/// must return the number of virtual text lines it has taken up. Each `Decoration` recieves
|
||||||
|
/// an offset `virt_off` based on these return values where it can render virtual text:
|
||||||
|
///
|
||||||
|
/// That means that a `render_line` implementation that returns `X` can render virtual text
|
||||||
|
/// in the following area:
|
||||||
|
/// ``` no-compile
|
||||||
|
/// let start = inner.y + pos.virtual_line + virt_off;
|
||||||
|
/// start .. start + X
|
||||||
|
/// ````
|
||||||
|
fn render_virt_lines(
|
||||||
|
&mut self,
|
||||||
|
_renderer: &mut TextRenderer,
|
||||||
|
_pos: LinePos,
|
||||||
|
_virt_off: Position,
|
||||||
|
) -> Position {
|
||||||
|
Position::new(0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_pos(&mut self, _pos: usize) -> usize {
|
||||||
|
usize::MAX
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_concealed_anchor(&mut self, conceal_end_char_idx: usize) -> usize {
|
||||||
|
self.reset_pos(conceal_end_char_idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This function is called **before** the grapheme at `char_idx` is rendered.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// The char idx of the next grapheme that this function should be called for
|
||||||
|
fn decorate_grapheme(
|
||||||
|
&mut self,
|
||||||
|
_renderer: &mut TextRenderer,
|
||||||
|
_grapheme: &FormattedGrapheme,
|
||||||
|
) -> usize {
|
||||||
|
usize::MAX
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F: FnMut(&mut TextRenderer, LinePos)> Decoration for F {
|
||||||
|
fn decorate_line(&mut self, renderer: &mut TextRenderer, pos: LinePos) {
|
||||||
|
self(renderer, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct DecorationManager<'a> {
|
||||||
|
decorations: Vec<(Box<dyn Decoration + 'a>, usize)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> DecorationManager<'a> {
|
||||||
|
pub fn add_decoration(&mut self, decoration: impl Decoration + 'a) {
|
||||||
|
self.decorations.push((Box::new(decoration), 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare_for_rendering(&mut self, first_visible_char: usize) {
|
||||||
|
for (decoration, next_position) in &mut self.decorations {
|
||||||
|
*next_position = decoration.reset_pos(first_visible_char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decorate_grapheme(&mut self, renderer: &mut TextRenderer, grapheme: &FormattedGrapheme) {
|
||||||
|
for (decoration, hook_char_idx) in &mut self.decorations {
|
||||||
|
loop {
|
||||||
|
match (*hook_char_idx).cmp(&grapheme.char_idx) {
|
||||||
|
// this grapheme has been concealed or we are at the first grapheme
|
||||||
|
Ordering::Less => {
|
||||||
|
*hook_char_idx = decoration.skip_concealed_anchor(grapheme.char_idx)
|
||||||
|
}
|
||||||
|
Ordering::Equal => {
|
||||||
|
*hook_char_idx = decoration.decorate_grapheme(renderer, grapheme)
|
||||||
|
}
|
||||||
|
Ordering::Greater => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decorate_line(&mut self, renderer: &mut TextRenderer, pos: LinePos) {
|
||||||
|
for (decoration, _) in &mut self.decorations {
|
||||||
|
decoration.decorate_line(renderer, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_virtual_lines(
|
||||||
|
&mut self,
|
||||||
|
renderer: &mut TextRenderer,
|
||||||
|
pos: LinePos,
|
||||||
|
line_width: usize,
|
||||||
|
) {
|
||||||
|
let mut virt_off = Position::new(1, line_width); // start at 1 so the line is never overwritten
|
||||||
|
for (decoration, _) in &mut self.decorations {
|
||||||
|
virt_off += decoration.render_virt_lines(renderer, pos, virt_off);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cursor rendering is done externally so all the cursor decoration
|
||||||
|
/// does is save the position of primary cursor
|
||||||
|
pub struct Cursor<'a> {
|
||||||
|
pub cache: &'a CursorCache,
|
||||||
|
pub primary_cursor: usize,
|
||||||
|
}
|
||||||
|
impl Decoration for Cursor<'_> {
|
||||||
|
fn reset_pos(&mut self, pos: usize) -> usize {
|
||||||
|
if pos <= self.primary_cursor {
|
||||||
|
self.primary_cursor
|
||||||
|
} else {
|
||||||
|
usize::MAX
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decorate_grapheme(
|
||||||
|
&mut self,
|
||||||
|
renderer: &mut TextRenderer,
|
||||||
|
grapheme: &FormattedGrapheme,
|
||||||
|
) -> usize {
|
||||||
|
if renderer.column_in_bounds(grapheme.visual_pos.col)
|
||||||
|
&& renderer.offset.row < grapheme.visual_pos.row
|
||||||
|
{
|
||||||
|
let position = grapheme.visual_pos - renderer.offset;
|
||||||
|
self.cache.set(Some(position));
|
||||||
|
}
|
||||||
|
usize::MAX
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,305 @@
|
|||||||
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
|
use helix_core::diagnostic::Severity;
|
||||||
|
use helix_core::doc_formatter::{DocumentFormatter, FormattedGrapheme};
|
||||||
|
use helix_core::graphemes::Grapheme;
|
||||||
|
use helix_core::text_annotations::TextAnnotations;
|
||||||
|
use helix_core::{Diagnostic, Position};
|
||||||
|
use helix_view::annotations::diagnostics::{
|
||||||
|
DiagnosticFilter, InlineDiagnosticAccumulator, InlineDiagnosticsConfig,
|
||||||
|
};
|
||||||
|
|
||||||
|
use helix_view::theme::Style;
|
||||||
|
use helix_view::{Document, Theme};
|
||||||
|
|
||||||
|
use crate::ui::document::{LinePos, TextRenderer};
|
||||||
|
use crate::ui::text_decorations::Decoration;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Styles {
|
||||||
|
hint: Style,
|
||||||
|
info: Style,
|
||||||
|
warning: Style,
|
||||||
|
error: Style,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Styles {
|
||||||
|
fn new(theme: &Theme) -> Styles {
|
||||||
|
Styles {
|
||||||
|
hint: theme.get("hint"),
|
||||||
|
info: theme.get("info"),
|
||||||
|
warning: theme.get("warning"),
|
||||||
|
error: theme.get("error"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn severity_style(&self, severity: Severity) -> Style {
|
||||||
|
match severity {
|
||||||
|
Severity::Hint => self.hint,
|
||||||
|
Severity::Info => self.info,
|
||||||
|
Severity::Warning => self.warning,
|
||||||
|
Severity::Error => self.error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct InlineDiagnostics<'a> {
|
||||||
|
state: InlineDiagnosticAccumulator<'a>,
|
||||||
|
eol_diagnostics: DiagnosticFilter,
|
||||||
|
styles: Styles,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> InlineDiagnostics<'a> {
|
||||||
|
pub fn new(
|
||||||
|
doc: &'a Document,
|
||||||
|
theme: &Theme,
|
||||||
|
cursor: usize,
|
||||||
|
config: InlineDiagnosticsConfig,
|
||||||
|
eol_diagnostics: DiagnosticFilter,
|
||||||
|
) -> Self {
|
||||||
|
InlineDiagnostics {
|
||||||
|
state: InlineDiagnosticAccumulator::new(cursor, doc, config),
|
||||||
|
styles: Styles::new(theme),
|
||||||
|
eol_diagnostics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const BL_CORNER: &str = "┘";
|
||||||
|
const TR_CORNER: &str = "┌";
|
||||||
|
const BR_CORNER: &str = "└";
|
||||||
|
const STACK: &str = "├";
|
||||||
|
const MULTI: &str = "┴";
|
||||||
|
const HOR_BAR: &str = "─";
|
||||||
|
const VER_BAR: &str = "│";
|
||||||
|
|
||||||
|
struct Renderer<'a, 'b> {
|
||||||
|
renderer: &'a mut TextRenderer<'b>,
|
||||||
|
first_row: u16,
|
||||||
|
row: u16,
|
||||||
|
config: &'a InlineDiagnosticsConfig,
|
||||||
|
styles: &'a Styles,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Renderer<'_, '_> {
|
||||||
|
fn draw_decoration(&mut self, g: &'static str, severity: Severity, col: u16) {
|
||||||
|
self.draw_decoration_at(g, severity, col, self.row)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_decoration_at(&mut self, g: &'static str, severity: Severity, col: u16, row: u16) {
|
||||||
|
self.renderer.draw_decoration_grapheme(
|
||||||
|
Grapheme::new_decoration(g),
|
||||||
|
self.styles.severity_style(severity),
|
||||||
|
row,
|
||||||
|
col,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_eol_diagnostic(&mut self, diag: &Diagnostic, row: u16, col: usize) -> u16 {
|
||||||
|
let style = self.styles.severity_style(diag.severity());
|
||||||
|
let width = self.renderer.viewport.width;
|
||||||
|
if !self.renderer.column_in_bounds(col + 1) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let col = (col - self.renderer.offset.col) as u16;
|
||||||
|
let (new_col, _) = self.renderer.set_string_truncated(
|
||||||
|
self.renderer.viewport.x + col + 1,
|
||||||
|
row,
|
||||||
|
&diag.message,
|
||||||
|
width.saturating_sub(col + 1) as usize,
|
||||||
|
|_| style,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
new_col - col
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_diagnostic(&mut self, diag: &Diagnostic, col: u16, next_severity: Option<Severity>) {
|
||||||
|
let severity = diag.severity();
|
||||||
|
let (sym, sym_severity) = if let Some(next_severity) = next_severity {
|
||||||
|
(STACK, next_severity.max(severity))
|
||||||
|
} else {
|
||||||
|
(BR_CORNER, severity)
|
||||||
|
};
|
||||||
|
self.draw_decoration(sym, sym_severity, col);
|
||||||
|
for i in 0..self.config.prefix_len {
|
||||||
|
self.draw_decoration(HOR_BAR, severity, col + i + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let text_col = col + self.config.prefix_len + 1;
|
||||||
|
let text_fmt = self.config.text_fmt(text_col, self.renderer.viewport.width);
|
||||||
|
let annotations = TextAnnotations::default();
|
||||||
|
let formatter = DocumentFormatter::new_at_prev_checkpoint(
|
||||||
|
diag.message.as_str().trim().into(),
|
||||||
|
&text_fmt,
|
||||||
|
&annotations,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
let mut last_row = 0;
|
||||||
|
let style = self.styles.severity_style(severity);
|
||||||
|
for grapheme in formatter {
|
||||||
|
last_row = grapheme.visual_pos.row;
|
||||||
|
self.renderer.draw_decoration_grapheme(
|
||||||
|
grapheme.raw,
|
||||||
|
style,
|
||||||
|
self.row + grapheme.visual_pos.row as u16,
|
||||||
|
text_col + grapheme.visual_pos.col as u16,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.row += 1;
|
||||||
|
// height is last_row + 1 and extra_rows is height - 1
|
||||||
|
let extra_lines = last_row;
|
||||||
|
if let Some(next_severity) = next_severity {
|
||||||
|
for _ in 0..extra_lines {
|
||||||
|
self.draw_decoration(VER_BAR, next_severity, col);
|
||||||
|
self.row += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.row += extra_lines as u16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_multi_diagnostics(&mut self, stack: &mut Vec<(&Diagnostic, u16)>) {
|
||||||
|
let Some(&(last_diag, last_anchor)) = stack.last() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let start = self
|
||||||
|
.config
|
||||||
|
.max_diagnostic_start(self.renderer.viewport.width);
|
||||||
|
|
||||||
|
if last_anchor <= start {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut severity = last_diag.severity();
|
||||||
|
let mut last_anchor = last_anchor;
|
||||||
|
self.draw_decoration(BL_CORNER, severity, last_anchor);
|
||||||
|
let mut stacked_diagnostics = 1;
|
||||||
|
for &(diag, anchor) in stack.iter().rev().skip(1) {
|
||||||
|
let sym = match anchor.cmp(&start) {
|
||||||
|
Ordering::Less => break,
|
||||||
|
Ordering::Equal => STACK,
|
||||||
|
Ordering::Greater => MULTI,
|
||||||
|
};
|
||||||
|
stacked_diagnostics += 1;
|
||||||
|
severity = severity.max(diag.severity());
|
||||||
|
let old_severity = severity;
|
||||||
|
if anchor == last_anchor && severity == old_severity {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for col in (anchor + 1)..last_anchor {
|
||||||
|
self.draw_decoration(HOR_BAR, old_severity, col)
|
||||||
|
}
|
||||||
|
self.draw_decoration(sym, severity, anchor);
|
||||||
|
last_anchor = anchor;
|
||||||
|
}
|
||||||
|
|
||||||
|
// if no diagnostic anchor was found exactly at the start of the
|
||||||
|
// diagnostic text draw an upwards corner and ensure the last piece
|
||||||
|
// of the line is not missing
|
||||||
|
if last_anchor != start {
|
||||||
|
for col in (start + 1)..last_anchor {
|
||||||
|
self.draw_decoration(HOR_BAR, severity, col)
|
||||||
|
}
|
||||||
|
self.draw_decoration(TR_CORNER, severity, start)
|
||||||
|
}
|
||||||
|
self.row += 1;
|
||||||
|
let stacked_diagnostics = &stack[stack.len() - stacked_diagnostics..];
|
||||||
|
|
||||||
|
for (i, (diag, _)) in stacked_diagnostics.iter().rev().enumerate() {
|
||||||
|
let next_severity = stacked_diagnostics[..stacked_diagnostics.len() - i - 1]
|
||||||
|
.iter()
|
||||||
|
.map(|(diag, _)| diag.severity())
|
||||||
|
.max();
|
||||||
|
self.draw_diagnostic(diag, start, next_severity);
|
||||||
|
}
|
||||||
|
|
||||||
|
stack.truncate(stack.len() - stacked_diagnostics.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_diagnostics(&mut self, stack: &mut Vec<(&Diagnostic, u16)>) {
|
||||||
|
let mut stack = stack.drain(..).rev().peekable();
|
||||||
|
let mut last_anchor = self.renderer.viewport.width;
|
||||||
|
while let Some((diag, anchor)) = stack.next() {
|
||||||
|
if anchor != last_anchor {
|
||||||
|
for row in self.first_row..self.row {
|
||||||
|
self.draw_decoration_at(VER_BAR, diag.severity(), anchor, row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let next_severity = stack.peek().and_then(|&(diag, next_anchor)| {
|
||||||
|
(next_anchor == anchor).then_some(diag.severity())
|
||||||
|
});
|
||||||
|
self.draw_diagnostic(diag, anchor, next_severity);
|
||||||
|
last_anchor = anchor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Decoration for InlineDiagnostics<'_> {
|
||||||
|
fn render_virt_lines(
|
||||||
|
&mut self,
|
||||||
|
renderer: &mut TextRenderer,
|
||||||
|
pos: LinePos,
|
||||||
|
virt_off: Position,
|
||||||
|
) -> Position {
|
||||||
|
let mut col_off = 0;
|
||||||
|
let filter = self.state.filter();
|
||||||
|
let eol_diagnostic = match self.eol_diagnostics {
|
||||||
|
DiagnosticFilter::Enable(eol_filter) => {
|
||||||
|
let eol_diganogistcs = self
|
||||||
|
.state
|
||||||
|
.stack
|
||||||
|
.iter()
|
||||||
|
.filter(|(diag, _)| eol_filter <= diag.severity());
|
||||||
|
match filter {
|
||||||
|
DiagnosticFilter::Enable(filter) => eol_diganogistcs
|
||||||
|
.filter(|(diag, _)| filter > diag.severity())
|
||||||
|
.max_by_key(|(diagnostic, _)| diagnostic.severity),
|
||||||
|
DiagnosticFilter::Disable => {
|
||||||
|
eol_diganogistcs.max_by_key(|(diagnostic, _)| diagnostic.severity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DiagnosticFilter::Disable => None,
|
||||||
|
};
|
||||||
|
if let Some((eol_diagnostic, _)) = eol_diagnostic {
|
||||||
|
let mut renderer = Renderer {
|
||||||
|
renderer,
|
||||||
|
first_row: pos.visual_line,
|
||||||
|
row: pos.visual_line,
|
||||||
|
config: &self.state.config,
|
||||||
|
styles: &self.styles,
|
||||||
|
};
|
||||||
|
col_off = renderer.draw_eol_diagnostic(eol_diagnostic, pos.visual_line, virt_off.col);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.state.compute_line_diagnostics();
|
||||||
|
let mut renderer = Renderer {
|
||||||
|
renderer,
|
||||||
|
first_row: pos.visual_line + virt_off.row as u16,
|
||||||
|
row: pos.visual_line + virt_off.row as u16,
|
||||||
|
config: &self.state.config,
|
||||||
|
styles: &self.styles,
|
||||||
|
};
|
||||||
|
renderer.draw_multi_diagnostics(&mut self.state.stack);
|
||||||
|
renderer.draw_diagnostics(&mut self.state.stack);
|
||||||
|
let horizontal_off = renderer.row - renderer.first_row;
|
||||||
|
Position::new(horizontal_off as usize, col_off as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset_pos(&mut self, pos: usize) -> usize {
|
||||||
|
self.state.reset_pos(pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_concealed_anchor(&mut self, conceal_end_char_idx: usize) -> usize {
|
||||||
|
self.state.skip_concealed(conceal_end_char_idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decorate_grapheme(
|
||||||
|
&mut self,
|
||||||
|
renderer: &mut TextRenderer,
|
||||||
|
grapheme: &FormattedGrapheme,
|
||||||
|
) -> usize {
|
||||||
|
self.state
|
||||||
|
.proccess_anchor(grapheme, renderer.viewport.width, renderer.offset.col)
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue