Merge branch 'master' of github.com:helix-editor/helix into md/global-status-line

pull/8908/head
TornaxO7 1 year ago
commit 4e18938daf
No known key found for this signature in database
GPG Key ID: 2BCDBDF404CEDF55

@ -1,3 +1,3 @@
[alias] [alias]
xtask = "run --package xtask --" xtask = "run --package xtask --"
integration-test = "test --features integration --workspace --test integration" integration-test = "test --features integration --profile integration --workspace --test integration"

@ -32,7 +32,7 @@ body:
id: helix-log id: helix-log
attributes: attributes:
label: Helix log label: Helix log
description: See `hx -h` for log file path description: See `hx -h` for log file path. If you can reproduce the issue run `RUST_BACKTRACE=1 hx -vv` to generate a more detailed log file.
value: | value: |
<details><summary>~/.cache/helix/helix.log</summary> <details><summary>~/.cache/helix/helix.log</summary>
@ -55,13 +55,24 @@ body:
placeholder: wezterm 20220101-133340-7edc5b5a placeholder: wezterm 20220101-133340-7edc5b5a
validations: validations:
required: true required: true
- type: input
id: installation-method
attributes:
label: Installation Method
description: >
How you installed Helix - from a package manager like Homebrew or the
AUR, built from source, downloaded a binary from the releases page, etc.
placeholder: "source / brew / nixpkgs / flake / releases page"
validations:
required: true
- type: input - type: input
id: helix-version id: helix-version
attributes: attributes:
label: Helix Version label: Helix Version
description: > description: >
Helix version (`hx -V` if using a release, `git describe` if building Helix version (`hx -V` if using a release, `git describe` if building
from master) from master).
placeholder: "helix 0.6.0 (c0dbd6dc)" **Make sure that you are using the [latest helix release](https://github.com/helix-editor/helix/releases) or a newer master build**
placeholder: "helix 22.12 (5eaa6d97)"
validations: validations:
required: true required: true

@ -4,24 +4,17 @@ on:
push: push:
branches: branches:
- master - master
merge_group:
schedule: schedule:
- cron: '00 01 * * *' - cron: '00 01 * * *'
jobs: jobs:
check: check:
name: Check name: Check (msrv)
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
rust: [stable, msrv]
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Use MSRV rust toolchain
if: matrix.rust == 'msrv'
run: cp .github/workflows/msrv-rust-toolchain.toml rust-toolchain.toml
- name: Install stable toolchain - name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1 uses: helix-editor/rust-toolchain@v1
with: with:
@ -29,6 +22,8 @@ jobs:
override: true override: true
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with:
shared-key: "build"
- name: Run cargo check - name: Run cargo check
run: cargo check run: cargo check
@ -41,15 +36,14 @@ jobs:
HELIX_LOG_LEVEL: info HELIX_LOG_LEVEL: info
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Install stable toolchain - name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1 uses: dtolnay/rust-toolchain@1.70
with:
profile: minimal
override: true
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with:
shared-key: "build"
- name: Cache test tree-sitter grammar - name: Cache test tree-sitter grammar
uses: actions/cache@v3 uses: actions/cache@v3
@ -73,16 +67,16 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Install stable toolchain - name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1 uses: dtolnay/rust-toolchain@1.70
with: with:
profile: minimal
override: true
components: rustfmt, clippy components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with:
shared-key: "build"
- name: Run cargo fmt - name: Run cargo fmt
run: cargo fmt --all --check run: cargo fmt --all --check
@ -100,15 +94,17 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Install stable toolchain - name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1 uses: dtolnay/rust-toolchain@1.70
with:
profile: minimal
override: true
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
with:
shared-key: "build"
- name: Validate queries
run: cargo xtask query-check
- name: Generate docs - name: Generate docs
run: cargo xtask docgen run: cargo xtask docgen
@ -120,20 +116,3 @@ jobs:
|| (echo "Run 'cargo xtask docgen', commit the changes and push again" \ || (echo "Run 'cargo xtask docgen', commit the changes and push again" \
&& exit 1) && exit 1)
queries:
name: Tree-sitter queries
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v3
- name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1
with:
profile: minimal
override: true
- uses: Swatinem/rust-cache@v2
- name: Generate docs
run: cargo xtask query-check

@ -11,10 +11,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Install nix - name: Install nix
uses: cachix/install-nix-action@v18 uses: cachix/install-nix-action@v23
- name: Authenticate with Cachix - name: Authenticate with Cachix
uses: cachix/cachix-action@v12 uses: cachix/cachix-action@v12

@ -11,7 +11,7 @@ jobs:
deploy: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Setup mdBook - name: Setup mdBook
uses: peaceiris/actions-mdbook@v1 uses: peaceiris/actions-mdbook@v1
@ -26,16 +26,16 @@ jobs:
OUTDIR=$(basename ${{ github.ref }}) OUTDIR=$(basename ${{ github.ref }})
echo "OUTDIR=$OUTDIR" >> $GITHUB_ENV echo "OUTDIR=$OUTDIR" >> $GITHUB_ENV
- name: Deploy - name: Deploy stable
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v3
if: startswith(github.ref, 'refs/tags/')
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book/book publish_dir: ./book/book
destination_dir: ./${{ env.OUTDIR }}
- name: Deploy stable - name: Deploy
uses: peaceiris/actions-gh-pages@v3 uses: peaceiris/actions-gh-pages@v3
if: startswith(github.ref, 'refs/tags/')
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book/book publish_dir: ./book/book
destination_dir: ./${{ env.OUTDIR }}

@ -1,3 +0,0 @@
[toolchain]
channel = "1.61.0"
components = ["rustfmt", "rust-src"]

@ -23,13 +23,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Install stable toolchain - name: Install stable toolchain
uses: helix-editor/rust-toolchain@v1 uses: dtolnay/rust-toolchain@stable
with:
profile: minimal
override: true
- uses: Swatinem/rust-cache@v2 - uses: Swatinem/rust-cache@v2
@ -47,6 +44,16 @@ jobs:
dist: dist:
name: Dist name: Dist
needs: [fetch-grammars] needs: [fetch-grammars]
env:
# For some builds, we use cross to test on 32-bit and big-endian
# systems.
CARGO: cargo
# When CARGO is set to CROSS, this is set to `--target matrix.target`.
TARGET_FLAGS:
# When CARGO is set to CROSS, TARGET_DIR includes matrix.target.
TARGET_DIR: ./target
# Emit backtraces on panics.
RUST_BACKTRACE: 1
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false # don't fail other jobs if one fails fail-fast: false # don't fail other jobs if one fails
@ -54,30 +61,31 @@ jobs:
build: [x86_64-linux, x86_64-macos, x86_64-windows] #, x86_64-win-gnu, win32-msvc build: [x86_64-linux, x86_64-macos, x86_64-windows] #, x86_64-win-gnu, win32-msvc
include: include:
- build: x86_64-linux - build: x86_64-linux
os: ubuntu-20.04 os: ubuntu-latest
rust: stable rust: stable
target: x86_64-unknown-linux-gnu target: x86_64-unknown-linux-gnu
cross: false cross: false
- build: aarch64-linux - build: aarch64-linux
os: ubuntu-20.04 os: ubuntu-latest
rust: stable rust: stable
target: aarch64-unknown-linux-gnu target: aarch64-unknown-linux-gnu
cross: true cross: true
- build: riscv64-linux # - build: riscv64-linux
os: ubuntu-20.04 # os: ubuntu-latest
rust: stable # rust: stable
target: riscv64gc-unknown-linux-gnu # target: riscv64gc-unknown-linux-gnu
cross: true # cross: true
- build: x86_64-macos - build: x86_64-macos
os: macos-latest os: macos-latest
rust: stable rust: stable
target: x86_64-apple-darwin target: x86_64-apple-darwin
cross: false cross: false
- build: x86_64-windows - build: x86_64-windows
os: windows-2019 os: windows-latest
rust: stable rust: stable
target: x86_64-pc-windows-msvc target: x86_64-pc-windows-msvc
cross: false cross: false
# 23.03: build issues
- build: aarch64-macos - build: aarch64-macos
os: macos-latest os: macos-latest
rust: stable rust: stable
@ -95,7 +103,7 @@ jobs:
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download grammars - name: Download grammars
uses: actions/download-artifact@v3 uses: actions/download-artifact@v3
@ -106,13 +114,17 @@ jobs:
mkdir -p runtime/grammars/sources mkdir -p runtime/grammars/sources
tar xJf grammars/grammars.tar.xz -C runtime/grammars/sources tar xJf grammars/grammars.tar.xz -C runtime/grammars/sources
# The rust-toolchain action ignores rust-toolchain.toml files.
# Removing this before building with cargo ensures that the rust-toolchain
# is considered the same between installation and usage.
- name: Remove the rust-toolchain.toml file
run: rm rust-toolchain.toml
- name: Install ${{ matrix.rust }} toolchain - name: Install ${{ matrix.rust }} toolchain
uses: actions-rs/toolchain@v1 uses: dtolnay/rust-toolchain@master
with: with:
profile: minimal
toolchain: ${{ matrix.rust }} toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }} target: ${{ matrix.target }}
override: true
# Install a pre-release version of Cross # Install a pre-release version of Cross
# TODO: We need to pre-install Cross because we need cross-rs/cross#591 to # TODO: We need to pre-install Cross because we need cross-rs/cross#591 to
@ -120,15 +132,20 @@ jobs:
# 0.3.0, which includes cross-rs/cross#591, is released. # 0.3.0, which includes cross-rs/cross#591, is released.
- name: Install Cross - name: Install Cross
if: "matrix.cross" if: "matrix.cross"
run: cargo install cross --git https://github.com/cross-rs/cross.git --rev 47df5c76e7cba682823a0b6aa6d95c17b31ba63a run: |
cargo install cross --git https://github.com/cross-rs/cross.git --rev 47df5c76e7cba682823a0b6aa6d95c17b31ba63a
echo "CARGO=cross" >> $GITHUB_ENV
# echo "TARGET_FLAGS=--target ${{ matrix.target }}" >> $GITHUB_ENV
# echo "TARGET_DIR=./target/${{ matrix.target }}" >> $GITHUB_ENV
- name: Show command used for Cargo
run: |
echo "cargo command is: ${{ env.CARGO }}"
echo "target flag is: ${{ env.TARGET_FLAGS }}"
- name: Run cargo test - name: Run cargo test
uses: actions-rs/cargo@v1
if: "!matrix.skip_tests" if: "!matrix.skip_tests"
with: run: ${{ env.CARGO }} test --release --locked --target ${{ matrix.target }} --workspace
use-cross: ${{ matrix.cross }}
command: test
args: --release --locked --target ${{ matrix.target }} --workspace
- name: Set profile.release.strip = true - name: Set profile.release.strip = true
shell: bash shell: bash
@ -139,16 +156,16 @@ jobs:
EOF EOF
- name: Build release binary - name: Build release binary
uses: actions-rs/cargo@v1 run: ${{ env.CARGO }} build --release --locked --target ${{ matrix.target }}
with:
use-cross: ${{ matrix.cross }}
command: build
args: --release --locked --target ${{ matrix.target }}
- name: Build AppImage - name: Build AppImage
shell: bash shell: bash
if: matrix.build == 'aarch64-linux' || matrix.build == 'x86_64-linux' if: matrix.build == 'x86_64-linux'
run: | run: |
# Required as of 22.x https://github.com/AppImage/AppImageKit/wiki/FUSE
sudo add-apt-repository universe
sudo apt install libfuse2
mkdir dist mkdir dist
name=dev name=dev
@ -214,7 +231,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
@ -238,7 +255,7 @@ jobs:
exe=".exe" exe=".exe"
fi fi
pkgname=helix-$GITHUB_REF_NAME-$platform pkgname=helix-$GITHUB_REF_NAME-$platform
mkdir $pkgname mkdir -p $pkgname
cp $source/LICENSE $source/README.md $pkgname cp $source/LICENSE $source/README.md $pkgname
mkdir $pkgname/contrib mkdir $pkgname/contrib
cp -r $source/contrib/completion $pkgname/contrib cp -r $source/contrib/completion $pkgname/contrib
@ -246,7 +263,7 @@ jobs:
mv bins-$platform/hx$exe $pkgname mv bins-$platform/hx$exe $pkgname
chmod +x $pkgname/hx$exe chmod +x $pkgname/hx$exe
if [[ "$platform" = "aarch64-linux" || "$platform" = "x86_64-linux" ]]; then if [[ "$platform" = "x86_64-linux" ]]; then
mv bins-$platform/helix-*.AppImage* dist/ mv bins-$platform/helix-*.AppImage* dist/
fi fi

@ -1,5 +1,2 @@
# Things that we don't want ripgrep to search that we do want in git # Things that we don't want ripgrep to search that we do want in git
# https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md#automatic-filtering # https://github.com/BurntSushi/ripgrep/blob/master/GUIDE.md#automatic-filtering
# Minified JS vendored from mdbook
book/theme/highlight.js

@ -1,3 +1,653 @@
# 23.10 (2023-10-24)
A big shout out to all the contributors! We had 118 contributors in this release.
Breaking changes:
- Support multiple language servers per language ([#2507](https://github.com/helix-editor/helix/pull/2507))
- This is a breaking change to language configuration
Features:
- Support multiple language servers per language ([#2507](https://github.com/helix-editor/helix/pull/2507), [#7082](https://github.com/helix-editor/helix/pull/7082), [#7286](https://github.com/helix-editor/helix/pull/7286), [#8374](https://github.com/helix-editor/helix/pull/8374))
- Add a statusline element for the selected register ([#7222](https://github.com/helix-editor/helix/pull/7222))
- Add `%`, `#`, `.`, `*` and `+` special registers ([#6985](https://github.com/helix-editor/helix/pull/6985))
- Add initial support for LSP DidChangeWatchedFiles notifications ([#7665](https://github.com/helix-editor/helix/pull/7665))
- Search buffer contents in `global_search` ([#5652](https://github.com/helix-editor/helix/pull/5652))
- Add a "smart tab" command that intelligently jumps the cursor on tab ([#4443](https://github.com/helix-editor/helix/pull/4443))
- Add a statusline element for whether a file is read-only ([#7222](https://github.com/helix-editor/helix/pull/7222), [#7875](https://github.com/helix-editor/helix/pull/7875))
- Syntax highlight regex prompts ([#7738](https://github.com/helix-editor/helix/pull/7738))
- Allow defining alignment in indent queries ([#5355](https://github.com/helix-editor/helix/pull/5355))
- Show visual feedback in `surround_replace` ([#7588](https://github.com/helix-editor/helix/pull/7588))
- Switch to Nucleo for fuzzy matching ([#7814](https://github.com/helix-editor/helix/pull/7814), [#8148](https://github.com/helix-editor/helix/pull/8148), [#8192](https://github.com/helix-editor/helix/pull/8192), [#8194](https://github.com/helix-editor/helix/pull/8194))
- Insert a trailing newline on write ([#8157](https://github.com/helix-editor/helix/pull/8157))
- Add a `-w`/`--working-dir` CLI flag for specifying a working directory on startup ([#8223](https://github.com/helix-editor/helix/pull/8223), [#8498](https://github.com/helix-editor/helix/pull/8498), [#8520](https://github.com/helix-editor/helix/pull/8520))
- Accept a `+N` CLI argument to set the first file's line number ([#8521](https://github.com/helix-editor/helix/pull/8521))
- Accept Helix-specific ignore files in `.helix/ignore` and `~/.config/helix/ignore` ([#8099](https://github.com/helix-editor/helix/pull/8099))
Commands:
- `merge_selections` (`A-minus`) - merge all selections into one selection that covers all ranges ([#7053](https://github.com/helix-editor/helix/pull/7053))
- `move_prev_long_word_end` and `extend_prev_long_word_end` - move/extend to the end of the previous WORD ([#6905](https://github.com/helix-editor/helix/pull/6905))
- `reverse_selection_contents` - swaps the values of each selection so they are reversed ([#7329](https://github.com/helix-editor/helix/pull/7329))
- Add `:rl` and `:rla` aliases for `:reload` and `:reload-all` ([#7158](https://github.com/helix-editor/helix/pull/7158))
- `yank_joined` - join the selections and yank to the selected register ([#7195](https://github.com/helix-editor/helix/pull/7195))
- `:write-all!` (`:wa!`) - forcibly write all buffers to disk and create any necessary subdirectories ([#7577](https://github.com/helix-editor/helix/pull/7577))
- `:redraw` - clear re-render the UI ([#6949](https://github.com/helix-editor/helix/pull/6949))
- `:tree-sitter-highlight-name` - show the theme scope name of the highlight under the cursor ([#8170](https://github.com/helix-editor/helix/pull/8170))
Usability improvements:
- Allow cycling option values at runtime ([#4411](https://github.com/helix-editor/helix/pull/4411), [#7240](https://github.com/helix-editor/helix/pull/7240), [#7877](https://github.com/helix-editor/helix/pull/7877))
- Exit gracefully on termination signals ([#7236](https://github.com/helix-editor/helix/pull/7236))
- Add plaintext matching fallback to tree-sitter pair matching ([#4288](https://github.com/helix-editor/helix/pull/4288))
- Persist register selection in pending keymaps ([0e08349](https://github.com/helix-editor/helix/commit/0e08349))
- Propagate the count and register to command palette commands ([b394997](https://github.com/helix-editor/helix/commit/b394997))
- Auto indent on `insert_at_line_start` ([#5837](https://github.com/helix-editor/helix/pull/5837))
- Add a config option to control whether LSP completions are automatically inserted on preview ([#7189](https://github.com/helix-editor/helix/pull/7189))
- Add a config option for default line endings ([#5621](https://github.com/helix-editor/helix/pull/5621), [#7357](https://github.com/helix-editor/helix/pull/7357))
- Allow ANSI colors in themes ([#5119](https://github.com/helix-editor/helix/pull/5119))
- Match pairs that don't form a standalone tree-sitter node ([#7242](https://github.com/helix-editor/helix/pull/7242))
- Allow indent sizes of up to 16 columns ([#7429](https://github.com/helix-editor/helix/pull/7429))
- Improve performance of mapping positions through changes ([#7408](https://github.com/helix-editor/helix/pull/7408), [8d39a81](https://github.com/helix-editor/helix/commit/8d39a81), [#7471](https://github.com/helix-editor/helix/pull/7471))
- Mark buffers created from stdin as modified ([#7431](https://github.com/helix-editor/helix/pull/7431))
- Forcibly shut down uninitialized language servers ([#7449](https://github.com/helix-editor/helix/pull/7449))
- Add filename completer for shell prompts ([#7569](https://github.com/helix-editor/helix/pull/7569))
- Allow binding F13-F24 ([#7672](https://github.com/helix-editor/helix/pull/7672))
- Resolve LSP code actions ([#7677](https://github.com/helix-editor/helix/pull/7677), [#8421](https://github.com/helix-editor/helix/pull/8421))
- Save an undo checkpoint before accepting completions ([#7747](https://github.com/helix-editor/helix/pull/7747))
- Include gitignored files in debugger completions ([#7936](https://github.com/helix-editor/helix/pull/7936))
- Make editor remember the last search register ([#5244](https://github.com/helix-editor/helix/pull/5244))
- Open directories with `goto_file` ([#7909](https://github.com/helix-editor/helix/pull/7909))
- Use relative path to open buffer in `goto_file` (`gf`) ([#7965](https://github.com/helix-editor/helix/pull/7965))
- Support `default` color in themes ([#8083](https://github.com/helix-editor/helix/pull/8083), [#8114](https://github.com/helix-editor/helix/pull/8114))
- Toggle between relative and absolute line numbers when the terminal loses focus ([#7955](https://github.com/helix-editor/helix/pull/7955))
- Lower default idle-timeout to 250ms ([060e73a](https://github.com/helix-editor/helix/commit/060e73a))
- Allow theming diff gutters separately from other diff colors ([#8343](https://github.com/helix-editor/helix/pull/8343))
- Style bold/italic/strikethrough in markdown doc popups ([#8385](https://github.com/helix-editor/helix/pull/8385))
- Maintain the cursor position and view when splitting with `:hsplit`/`:vsplit` ([#8109](https://github.com/helix-editor/helix/pull/8109))
- Accept `-` in macros outside of `<`/`>` ([#8475](https://github.com/helix-editor/helix/pull/8475))
- Show all language servers for each language in `--health` ([#7315](https://github.com/helix-editor/helix/pull/7315))
- Don't break on hyphens in `:reflow` ([#8569](https://github.com/helix-editor/helix/pull/8569))
Fixes:
- Update diagnostics correctly on language server exit ([#7111](https://github.com/helix-editor/helix/pull/7111))
- Fix off-by-one in `select_references_to_symbol_under_cursor` ([#7132](https://github.com/helix-editor/helix/pull/7132))
- Extend selection with repeat-last-motion only if the original motion extended the selection ([#7159](https://github.com/helix-editor/helix/pull/7159))
- Fix undefined behavior in the diff gutter ([#7227](https://github.com/helix-editor/helix/pull/7227))
- Check that tab width is non-zero ([#7178](https://github.com/helix-editor/helix/pull/7178))
- Fix styles being overwritten in table rows with multiple cells ([#7281](https://github.com/helix-editor/helix/pull/7281))
- Add file for `--log` CLI arg in help text ([#7307](https://github.com/helix-editor/helix/pull/7307))
- Fix underflow when repeating a completion that has a negative shift position ([#7322](https://github.com/helix-editor/helix/pull/7322))
- Prefer longer matches in `select_next_sibling` and `select_prev_sibling` ([#7332](https://github.com/helix-editor/helix/pull/7332))
- Preview scratch buffers in the jumplist picker ([#7331](https://github.com/helix-editor/helix/pull/7331))
- Fix chunking by bytes in tree-sitter parsing ([#7417](https://github.com/helix-editor/helix/pull/7417))
- Discard LSP publishDiagnostic from uninitialized servers ([#7467](https://github.com/helix-editor/helix/pull/7467))
- Use negotiated position encoding for LSP workspace edits ([#7469](https://github.com/helix-editor/helix/pull/7469))
- Fix error message for unknown gutter types in config ([#7534](https://github.com/helix-editor/helix/pull/7534))
- Fix `:log-open` when `--log` CLI arg is specified ([#7573](https://github.com/helix-editor/helix/pull/7573), [#7585](https://github.com/helix-editor/helix/pull/7585))
- Fix debouncing of LSP messages to fix the last message sticking around ([#7538](https://github.com/helix-editor/helix/pull/7538), [#8023](https://github.com/helix-editor/helix/pull/8023))
- Fix crash when the current working directory is deleted ([#7185](https://github.com/helix-editor/helix/pull/7185))
- Fix piping to Helix on macOS ([#5468](https://github.com/helix-editor/helix/pull/5468))
- Fix crash when parsing overlapping injections ([#7621](https://github.com/helix-editor/helix/pull/7621))
- Clear the statusline when the prompt is visible ([#7646](https://github.com/helix-editor/helix/pull/7646))
- Fix range formatting error message typo ([#7823](https://github.com/helix-editor/helix/pull/7823))
- Skip rendering gutters when gutter width exceeds view width ([#7821](https://github.com/helix-editor/helix/pull/7821))
- Center the picker preview using visual lines ([#7837](https://github.com/helix-editor/helix/pull/7837))
- Align view correctly for background buffers opened with `A-ret` ([#7691](https://github.com/helix-editor/helix/pull/7691))
- Fix cursor resetting to block when quitting via a keybind ([#7931](https://github.com/helix-editor/helix/pull/7931))
- Remove path completions for the `:new` command ([#8010](https://github.com/helix-editor/helix/pull/8010))
- Use binary path resolved by `which` for formatter commands ([#8064](https://github.com/helix-editor/helix/pull/8064))
- Handle crossterm's `hidden` modifier ([#8120](https://github.com/helix-editor/helix/pull/8120))
- Clear completion when switching between windows with the mouse ([#8118](https://github.com/helix-editor/helix/pull/8118))
- Eagerly remove the last picker (`<space>'`) when the picker has many items ([#8127](https://github.com/helix-editor/helix/pull/8127))
- Fix find commands for buffers with non-LF line-endings ([#8111](https://github.com/helix-editor/helix/pull/8111))
- Detect the tmux clipboard provider on macOS ([#8182](https://github.com/helix-editor/helix/pull/8182))
- Fix syntax highlighting in dynamic picker preview pane ([#8206](https://github.com/helix-editor/helix/pull/8206))
- Recognize HTML code tags with attributes as code in markdown previews ([#8397](https://github.com/helix-editor/helix/pull/8397))
- Fix multicursor snippet placeholder directions ([#8423](https://github.com/helix-editor/helix/pull/8423))
- Only show diagnostic highlights when diagnostics are enabled for a language server ([#8551](https://github.com/helix-editor/helix/pull/8551))
Themes:
- Improve the selection color in `ferra` ([#7138](https://github.com/helix-editor/helix/pull/7138))
- Add `variable.other.member` theming to `spacebones_light` ([#7125](https://github.com/helix-editor/helix/pull/7125))
- Update `autumn` and theme the soft-wrap indicator ([#7229](https://github.com/helix-editor/helix/pull/7229))
- Add `gruvbox_dark_soft` ([#7139](https://github.com/helix-editor/helix/pull/7139))
- Add `merionette` ([#7186](https://github.com/helix-editor/helix/pull/7186))
- Add `zed_onedark` and `zed_onelight` ([#7250](https://github.com/helix-editor/helix/pull/7250))
- Use light-gray for `onedarker` inlay hint theming ([#7433](https://github.com/helix-editor/helix/pull/7433))
- Update the Nord theme to follow the style guidelines ([#7490](https://github.com/helix-editor/helix/pull/7490))
- Tune `dark_plus` inlay hint colors ([#7611](https://github.com/helix-editor/helix/pull/7611))
- Add `naysayer` ([#7570](https://github.com/helix-editor/helix/pull/7570))
- Add `kaolin-dark`, `kaolin-light` and `kaolin-valley-dark` ([#7151](https://github.com/helix-editor/helix/pull/7151))
- Fix selection highlighting in gruvbox variants ([#7717](https://github.com/helix-editor/helix/pull/7717))
- Add soft-wrap indicator to `gruvbox` ([#7736](https://github.com/helix-editor/helix/pull/7736))
- Add missing palette definitions in `everforest_dark` ([#7739](https://github.com/helix-editor/helix/pull/7739))
- Increase diagnostics clarity in `pop-dark` ([#7702](https://github.com/helix-editor/helix/pull/7702))
- Add `vim_dark_high_contrast` ([#7785](https://github.com/helix-editor/helix/pull/7785))
- Add `new_moon` ([#7834](https://github.com/helix-editor/helix/pull/7834))
- Add `yellowed` ([#7849](https://github.com/helix-editor/helix/pull/7849))
- Improve comment readability for `autumn` ([#7939](https://github.com/helix-editor/helix/pull/7939))
- Distinguish active bufferline buffer in `monokai` ([#7983](https://github.com/helix-editor/helix/pull/7983))
- Update ruler colors in `nord` ([#7995](https://github.com/helix-editor/helix/pull/7995))
- Update Catppuccin themes ([#8102](https://github.com/helix-editor/helix/pull/8102))
- Add text focus scope and diagnostics undercurls for `nord` ([#8165](https://github.com/helix-editor/helix/pull/8165))
- Add material theme collection ([#8211](https://github.com/helix-editor/helix/pull/8211))
- Improve indent line color in `dracula` ([#8266](https://github.com/helix-editor/helix/pull/8266))
- Clean up and refactor `papercolor` to use inheritance ([#8276](https://github.com/helix-editor/helix/pull/8276))
- Fix `zenburn` inlay hint color ([#8278](https://github.com/helix-editor/helix/pull/8278)a)
- Fix picker crash when previewing an invalid range ([e9d0bd7](https://github.com/helix-editor/helix/commit/e9d0bd7))
- Correctly center items in the picker preview ([13d4463](https://github.com/helix-editor/helix/commit/13d4463))
- Add `cyan_light` ([#8293](https://github.com/helix-editor/helix/pull/8293), [#8587](https://github.com/helix-editor/helix/pull/8587))
- Theme HTML tags in `onedark` ([#8409](https://github.com/helix-editor/helix/pull/8409))
- Refine `darcula` and `darcula-solid` themes ([#8412](https://github.com/helix-editor/helix/pull/8412))
- Improve `nord` highlights ([#8414](https://github.com/helix-editor/helix/pull/8414))
- Add `nord-night` ([#8549](https://github.com/helix-editor/helix/pull/8549))
New languages:
- Blueprint ([#7213](https://github.com/helix-editor/helix/pull/7213), [#8161](https://github.com/helix-editor/helix/pull/8161))
- Forth ([#7256](https://github.com/helix-editor/helix/pull/7256), [#7334](https://github.com/helix-editor/helix/pull/7334))
- t32 ([#7140](https://github.com/helix-editor/helix/pull/7140), [#7811](https://github.com/helix-editor/helix/pull/7811))
- WebC ([#7290](https://github.com/helix-editor/helix/pull/7290))
- Persistent DSL for Haskell ([#7261](https://github.com/helix-editor/helix/pull/7261))
- F# ([#7619](https://github.com/helix-editor/helix/pull/7619), [#8024](https://github.com/helix-editor/helix/pull/8024))
- Wren ([#7765](https://github.com/helix-editor/helix/pull/7765), [#7819](https://github.com/helix-editor/helix/pull/7819))
- Unison ([#7724](https://github.com/helix-editor/helix/pull/7724))
- Todo.txt ([#7835](https://github.com/helix-editor/helix/pull/7835))
- Jinja and Handlebars ([#7233](https://github.com/helix-editor/helix/pull/7233))
- Pod ([#7907](https://github.com/helix-editor/helix/pull/7907))
- Strace ([#7928](https://github.com/helix-editor/helix/pull/7928))
- Gemini ([#8070](https://github.com/helix-editor/helix/pull/8070))
- GNU Assembler (GAS) ([#8291](https://github.com/helix-editor/helix/pull/8291))
- JSON5 ([#8473](https://github.com/helix-editor/helix/pull/8473))
- TEMPL ([#8540](https://github.com/helix-editor/helix/pull/8540))
Updated languages and queries:
- Add one to the ruler numbers for git-commit ([#7072](https://github.com/helix-editor/helix/pull/7072))
- Recognize XAML files as XML ([#7083](https://github.com/helix-editor/helix/pull/7083))
- Recognize `Cargo.lock` as TOML ([#7095](https://github.com/helix-editor/helix/pull/7095))
- Use Rust grammar for Cairo ([c6d1430](https://github.com/helix-editor/helix/commit/c6d1430))
- Update tree-sitter-nickel ([#7059](https://github.com/helix-editor/helix/pull/7059), [#7551](https://github.com/helix-editor/helix/pull/7551))
- Tune auto-pair characters for Nickel ([#7059](https://github.com/helix-editor/helix/pull/7059))
- Recognize `Vagrantfile` as Ruby ([#7112](https://github.com/helix-editor/helix/pull/7112))
- Recognize hidden justfiles as Just ([#7088](https://github.com/helix-editor/helix/pull/7088))
- Update Java and TypeScript highlight queries ([#7145](https://github.com/helix-editor/helix/pull/7145))
- Recognize `.zimrc` as Bash ([#7146](https://github.com/helix-editor/helix/pull/7146))
- Recognize `.gir` as XML ([#7152](https://github.com/helix-editor/helix/pull/7152))
- Update tree-sitter-scala ([#7147](https://github.com/helix-editor/helix/pull/7147))
- Recognize make file-type as Makefile ([#7212](https://github.com/helix-editor/helix/pull/7212))
- Update tree-sitter-verilog ([#7262](https://github.com/helix-editor/helix/pull/7262))
- Update tree-sitter-cpp ([#7285](https://github.com/helix-editor/helix/pull/7285))
- Support core mode for delve debugger ([#7300](https://github.com/helix-editor/helix/pull/7300))
- Add Fortran comment injections ([#7305](https://github.com/helix-editor/helix/pull/7305))
- Switch Vue language server to `vue-language-server` ([#7312](https://github.com/helix-editor/helix/pull/7312))
- Update tree-sitter-sql ([#7387](https://github.com/helix-editor/helix/pull/7387), [#8464](https://github.com/helix-editor/helix/pull/8464))
- Replace the MATLAB tre-sitter grammar ([#7388](https://github.com/helix-editor/helix/pull/7388), [#7442](https://github.com/helix-editor/helix/pull/7442), [#7491](https://github.com/helix-editor/helix/pull/7491), [#7493](https://github.com/helix-editor/helix/pull/7493), [#7511](https://github.com/helix-editor/helix/pull/7511), [#7532](https://github.com/helix-editor/helix/pull/7532), [#8040](https://github.com/helix-editor/helix/pull/8040))
- Highlight TOML table headers ([#7441](https://github.com/helix-editor/helix/pull/7441))
- Recognize `cppm` file-type as C++ ([#7492](https://github.com/helix-editor/helix/pull/7492))
- Refactor ecma language queries into private and public queries ([#7207](https://github.com/helix-editor/helix/pull/7207))
- Update tree-sitter-dart ([#7576](https://github.com/helix-editor/helix/pull/7576))
- Add shebang for nushell files ([#7606](https://github.com/helix-editor/helix/pull/7606))
- Recognize systemd files as INI ([#7592](https://github.com/helix-editor/helix/pull/7592))
- Update TypeScript, TSX and Svelte grammars ([#6874](https://github.com/helix-editor/helix/pull/6874))
- Enable inlay hints in the Svelte language server ([#7622](https://github.com/helix-editor/helix/pull/7622))
- Recognize `Brewfile`s as Ruby ([#7629](https://github.com/helix-editor/helix/pull/7629))
- Add more file-types for R ([#7633](https://github.com/helix-editor/helix/pull/7633))
- Switch tree-sitter-perl to official upstream parser ([#7644](https://github.com/helix-editor/helix/pull/7644), [#7947](https://github.com/helix-editor/helix/pull/7947))
- Fix predicate typo in comment highlights ([#7732](https://github.com/helix-editor/helix/pull/7732))
- Update tree-sitter-prql ([#7771](https://github.com/helix-editor/helix/pull/7771))
- Recognize `.gitf` as JSON ([#7781](https://github.com/helix-editor/helix/pull/7781))
- Switch V language server to `v-analyzer` ([#7760](https://github.com/helix-editor/helix/pull/7760))
- Add protobuf language servers ([#7796](https://github.com/helix-editor/helix/pull/7796))
- Update tree-sitter-zig ([#7803](https://github.com/helix-editor/helix/pull/7803))
- Update tree-sitter-hare ([#7784](https://github.com/helix-editor/helix/pull/7784))
- Add Java indent queries ([#7844](https://github.com/helix-editor/helix/pull/7844))
- Update tree-sitter-scheme ([979933b](https://github.com/helix-editor/helix/commit/979933b))
- Recognize `scm` as Scheme instead of TSQ ([5707151](https://github.com/helix-editor/helix/commit/5707151))
- Update tree-sitter-git-commit ([#7831](https://github.com/helix-editor/helix/pull/7831))
- Update JavaScript, TypeScript and TSX grammars ([#7852](https://github.com/helix-editor/helix/pull/7852))
- Update tree-sitter-nu ([#7873](https://github.com/helix-editor/helix/pull/7873))
- Fix YAML indentation ([#6768](https://github.com/helix-editor/helix/pull/6768))
- Add `csharp-ls`, Pyright, Pylyzer and add roots for Python ([#7897](https://github.com/helix-editor/helix/pull/7897), [#8032](https://github.com/helix-editor/helix/pull/8032))
- Update tree-sitter-slint ([#7893](https://github.com/helix-editor/helix/pull/7893))
- Recognize more ZSH file-types as Bash ([#7930](https://github.com/helix-editor/helix/pull/7930))
- Recognize `star` extension as Starlark ([#7922](https://github.com/helix-editor/helix/pull/7922))
- Fix inline HTML tag highlighting in markdown ([#7960](https://github.com/helix-editor/helix/pull/7960))
- Update tree-sitter-robot ([#7970](https://github.com/helix-editor/helix/pull/7970))
- Highlight Dart 3 `sealed` and `base` keywords ([#7974](https://github.com/helix-editor/helix/pull/7974))
- Add configuration for `ltex-ls` to the default `languages.toml` ([#7838](https://github.com/helix-editor/helix/pull/7838))
- Update tree-sitter-strace ([#8087](https://github.com/helix-editor/helix/pull/8087))
- Update tree-sitter-gleam, enable auto-format ([#8085](https://github.com/helix-editor/helix/pull/8085))
- Update tree-sitter-esdl ([#8222](https://github.com/helix-editor/helix/pull/8222))
- Expand ignore file-types ([#8220](https://github.com/helix-editor/helix/pull/8220))
- Recognize feed related formats as XML ([#8232](https://github.com/helix-editor/helix/pull/8232))
- Improve YAML injections ([#8217](https://github.com/helix-editor/helix/pull/8217))
- Add shebangs for TypeScript, Julia, Java and OCaml ([95e994a](https://github.com/helix-editor/helix/commit/95e994a))
- Highlight abbreviations in Scheme ([ef23847](https://github.com/helix-editor/helix/commit/ef23847))
- Remove backtic auto-pair in OCaml ([#8260](https://github.com/helix-editor/helix/pull/8260))
- Recognize `flake.lock` as JSON ([#8304](https://github.com/helix-editor/helix/pull/8304))
- Add Python test script injection for Nix ([b4494e1](https://github.com/helix-editor/helix/commit/b4494e1))
- Fix Nix comment injection precedence ([37e48f4](https://github.com/helix-editor/helix/commit/37e48f4))
- Recognize editorconfig files as INI ([#8308](https://github.com/helix-editor/helix/pull/8308))
- Recognize `.babelrc` as JSON ([#8309](https://github.com/helix-editor/helix/pull/8309))
- Switch Purescript to its own tree-sitter parser ([#8306](https://github.com/helix-editor/helix/pull/8306), [#8338](https://github.com/helix-editor/helix/pull/8338), [#8527](https://github.com/helix-editor/helix/pull/8527))
- Update Unison highlights ([#8315](https://github.com/helix-editor/helix/pull/8315))
- Recognize `.webmanifest` as JSON ([#8342](https://github.com/helix-editor/helix/pull/8342))
- Recognize polkit policy files as XML ([#8369](https://github.com/helix-editor/helix/pull/8369))
- Recognize polkit rules files as JavaScript ([#8370](https://github.com/helix-editor/helix/pull/8370))
- Update Go highlight queries ([#8399](https://github.com/helix-editor/helix/pull/8399))
- Add shebangs for Makefiles ([#8410](https://github.com/helix-editor/helix/pull/8410))
- Add file-type associations from VSCode ([#8388](https://github.com/helix-editor/helix/pull/8388))
- Add validation to JSON/CSS language server configs ([#8433](https://github.com/helix-editor/helix/pull/8433))
- Add a configuration for the tailwind language server ([#8442](https://github.com/helix-editor/helix/pull/8442))
- Add a configuration for the ansible language server ([#7973](https://github.com/helix-editor/helix/pull/7973))
- Add a configuration for the GraphQL language server ([#8492](https://github.com/helix-editor/helix/pull/8492))
- Indent while statements in Bash ([#8528](https://github.com/helix-editor/helix/pull/8528))
- Update tree-sitter-haskell and queries ([#8558](https://github.com/helix-editor/helix/pull/8558))
Packaging:
- Add an overlay to the Nix flake ([#7078](https://github.com/helix-editor/helix/pull/7078))
- Check for `git` before fetching or building grammars ([#7320](https://github.com/helix-editor/helix/pull/7320))
- Refactor Nix flake to use Crane ([#7763](https://github.com/helix-editor/helix/pull/7763))
- Remove the aarch64 appimage from the release CI ([#7832](https://github.com/helix-editor/helix/pull/7832))
- Add desktop and icon files to Nix flake output ([#7979](https://github.com/helix-editor/helix/pull/7979))
- Build flake packages with the latest stable Rust ([#8133](https://github.com/helix-editor/helix/pull/8133))
# 23.05 (2023-05-18)
23.05 is a smaller release focusing on fixes. There were 88 contributors in this release. Thank you all!
Features:
- Add a config option to exclude declaration from LSP references request ([#6886](https://github.com/helix-editor/helix/pull/6886))
- Enable injecting languages based on their file extension and shebang ([#3970](https://github.com/helix-editor/helix/pull/3970))
- Sort the buffer picker by most recent access ([#2980](https://github.com/helix-editor/helix/pull/2980))
- Perform syntax highlighting in the picker asynchronously ([#7028](https://github.com/helix-editor/helix/pull/7028))
Commands:
- `:update` is now aliased as `:u` ([#6835](https://github.com/helix-editor/helix/pull/6835))
- Add `extend_to_first_nonwhitespace` which acts the same as `goto_first_nonwhitespace` but always extends ([#6837](https://github.com/helix-editor/helix/pull/6837))
- Add `:clear-register` for clearing the given register or all registers ([#5695](https://github.com/helix-editor/helix/pull/5695))
- Add `:write-buffer-close` and `:write-buffer-close!` ([#6947](https://github.com/helix-editor/helix/pull/6947))
Fixes:
- Normalize LSP workspace paths ([#6517](https://github.com/helix-editor/helix/pull/6517))
- Robustly handle invalid LSP ranges ([#6512](https://github.com/helix-editor/helix/pull/6512))
- Fix line number display for LSP goto pickers ([#6559](https://github.com/helix-editor/helix/pull/6559))
- Fix toggling of `soft-wrap.enable` option ([#6656](https://github.com/helix-editor/helix/pull/6656), [58e457a](https://github.com/helix-editor/helix/commit/58e457a), [#6742](https://github.com/helix-editor/helix/pull/6742))
- Handle `workspace/configuration` requests from stopped language servers ([#6693](https://github.com/helix-editor/helix/pull/6693))
- Fix possible crash from opening the jumplist picker ([#6672](https://github.com/helix-editor/helix/pull/6672))
- Fix theme preview returning to current theme on line and word deletions ([#6694](https://github.com/helix-editor/helix/pull/6694))
- Re-run crate build scripts on changes to revision and grammar repositories ([#6743](https://github.com/helix-editor/helix/pull/6743))
- Fix crash on opening from suspended state ([#6764](https://github.com/helix-editor/helix/pull/6764))
- Fix unwrap bug in DAP ([#6786](https://github.com/helix-editor/helix/pull/6786))
- Always build tree-sitter parsers with C++14 and C11 ([#6792](https://github.com/helix-editor/helix/pull/6792), [#6834](https://github.com/helix-editor/helix/pull/6834), [#6845](https://github.com/helix-editor/helix/pull/6845))
- Exit with a non-zero statuscode when tree-sitter parser builds fail ([#6795](https://github.com/helix-editor/helix/pull/6795))
- Flip symbol range in LSP goto commands ([#6794](https://github.com/helix-editor/helix/pull/6794))
- Fix runtime toggling of the `mouse` option ([#6675](https://github.com/helix-editor/helix/pull/6675))
- Fix panic in inlay hint computation when view anchor is out of bounds ([#6883](https://github.com/helix-editor/helix/pull/6883))
- Significantly improve performance of git discovery on slow file systems ([#6890](https://github.com/helix-editor/helix/pull/6890))
- Downgrade gix log level to info ([#6915](https://github.com/helix-editor/helix/pull/6915))
- Conserve BOM and properly support saving UTF16 files ([#6497](https://github.com/helix-editor/helix/pull/6497))
- Correctly handle completion re-request ([#6594](https://github.com/helix-editor/helix/pull/6594))
- Fix offset encoding in LSP `didChange` notifications ([#6921](https://github.com/helix-editor/helix/pull/6921))
- Change `gix` logging level to info ([#6915](https://github.com/helix-editor/helix/pull/6915))
- Improve error message when writes fail because parent directories do not exist ([#7014](https://github.com/helix-editor/helix/pull/7014))
- Replace DAP variables popup instead of pushing more popups ([#7034](https://github.com/helix-editor/helix/pull/7034))
- Disable tree-sitter for files after parsing for 500ms ([#7028](https://github.com/helix-editor/helix/pull/7028))
- Fix crash when deleting with multiple cursors ([#6024](https://github.com/helix-editor/helix/pull/6024))
- Fix selection sliding when deleting forwards in append mode ([#6024](https://github.com/helix-editor/helix/pull/6024))
- Fix completion on paths containing spaces ([#6779](https://github.com/helix-editor/helix/pull/6779))
Themes:
- Style inlay hints in `dracula` theme ([#6515](https://github.com/helix-editor/helix/pull/6515))
- Style inlay hints in `onedark` theme ([#6503](https://github.com/helix-editor/helix/pull/6503))
- Style inlay hints and the soft-wrap indicator in `varua` ([#6568](https://github.com/helix-editor/helix/pull/6568), [#6589](https://github.com/helix-editor/helix/pull/6589))
- Style inlay hints in `emacs` theme ([#6569](https://github.com/helix-editor/helix/pull/6569))
- Update `base16_transparent` and `dark_high_contrast` themes ([#6577](https://github.com/helix-editor/helix/pull/6577))
- Style inlay hints for `mellow` and `rasmus` themes ([#6583](https://github.com/helix-editor/helix/pull/6583))
- Dim pane divider for `base16_transparent` theme ([#6534](https://github.com/helix-editor/helix/pull/6534))
- Style inlay hints in `zenburn` theme ([#6593](https://github.com/helix-editor/helix/pull/6593))
- Style inlay hints in `boo_berry` theme ([#6625](https://github.com/helix-editor/helix/pull/6625))
- Add `ferra` theme ([#6619](https://github.com/helix-editor/helix/pull/6619), [#6776](https://github.com/helix-editor/helix/pull/6776))
- Style inlay hints in `nightfox` theme ([#6655](https://github.com/helix-editor/helix/pull/6655))
- Fix `ayu` theme family markup code block background ([#6538](https://github.com/helix-editor/helix/pull/6538))
- Improve whitespace and search match colors in `rose_pine` theme ([#6679](https://github.com/helix-editor/helix/pull/6679))
- Highlight selected items in `base16_transparent` theme ([#6716](https://github.com/helix-editor/helix/pull/6716))
- Adjust everforest to resemble original more closely ([#5866](https://github.com/helix-editor/helix/pull/5866))
- Refactor `dracula` theme ([#6552](https://github.com/helix-editor/helix/pull/6552), [#6767](https://github.com/helix-editor/helix/pull/6767), [#6855](https://github.com/helix-editor/helix/pull/6855), [#6987](https://github.com/helix-editor/helix/pull/6987))
- Style inlay hints in `darcula` theme ([#6732](https://github.com/helix-editor/helix/pull/6732))
- Style inlay hints in `kanagawa` theme ([#6773](https://github.com/helix-editor/helix/pull/6773))
- Improve `ayu_dark` theme ([#6622](https://github.com/helix-editor/helix/pull/6622))
- Refactor `noctis` theme multiple cursor highlighting ([96720e7](https://github.com/helix-editor/helix/commit/96720e7))
- Refactor `noctis` theme whitespace rendering and indent guides ([f2ccc03](https://github.com/helix-editor/helix/commit/f2ccc03))
- Add `amberwood` theme ([#6924](https://github.com/helix-editor/helix/pull/6924))
- Update `nightfox` theme ([#7061](https://github.com/helix-editor/helix/pull/7061))
Language support:
- R language server: use the `--no-echo` flag to silence output ([#6570](https://github.com/helix-editor/helix/pull/6570))
- Recognize CUDA files as C++ ([#6521](https://github.com/helix-editor/helix/pull/6521))
- Add support for Hurl ([#6450](https://github.com/helix-editor/helix/pull/6450))
- Add textobject queries for Julia ([#6588](https://github.com/helix-editor/helix/pull/6588))
- Update Ruby highlight queries ([#6587](https://github.com/helix-editor/helix/pull/6587))
- Add xsd to XML file-types ([#6631](https://github.com/helix-editor/helix/pull/6631))
- Support Robot Framework ([#6611](https://github.com/helix-editor/helix/pull/6611))
- Update Gleam tree-sitter parser ([#6641](https://github.com/helix-editor/helix/pull/6641))
- Update git-commit tree-sitter parser ([#6692](https://github.com/helix-editor/helix/pull/6692))
- Update Haskell tree-sitter parser ([#6317](https://github.com/helix-editor/helix/pull/6317))
- Add injection queries for Haskell quasiquotes ([#6474](https://github.com/helix-editor/helix/pull/6474))
- Highlight C/C++ escape sequences ([#6724](https://github.com/helix-editor/helix/pull/6724))
- Support Markdoc ([#6432](https://github.com/helix-editor/helix/pull/6432))
- Support OpenCL ([#6473](https://github.com/helix-editor/helix/pull/6473))
- Support DTD ([#6644](https://github.com/helix-editor/helix/pull/6644))
- Fix constant highlighting in Python queries ([#6751](https://github.com/helix-editor/helix/pull/6751))
- Support Just ([#6453](https://github.com/helix-editor/helix/pull/6453))
- Fix Go locals query for `var_spec` identifiers ([#6763](https://github.com/helix-editor/helix/pull/6763))
- Update Markdown tree-sitter parser ([#6785](https://github.com/helix-editor/helix/pull/6785))
- Fix Haskell workspace root for cabal projects ([#6828](https://github.com/helix-editor/helix/pull/6828))
- Avoid extra indentation in Go switches ([#6817](https://github.com/helix-editor/helix/pull/6817))
- Fix Go workspace roots ([#6884](https://github.com/helix-editor/helix/pull/6884))
- Set PerlNavigator as the default Perl language server ([#6860](https://github.com/helix-editor/helix/pull/6860))
- Highlight more sqlx macros in Rust ([#6793](https://github.com/helix-editor/helix/pull/6793))
- Switch Odin tree-sitter grammar ([#6766](https://github.com/helix-editor/helix/pull/6766))
- Recognize `poetry.lock` as TOML ([#6928](https://github.com/helix-editor/helix/pull/6928))
- Recognize Jupyter notebooks as JSON ([#6927](https://github.com/helix-editor/helix/pull/6927))
- Add language server configuration for Crystal ([#6948](https://github.com/helix-editor/helix/pull/6948))
- Add `build.gradle.kts` to Java and Scala roots ([#6970](https://github.com/helix-editor/helix/pull/6970))
- Recognize `sty` and `cls` files as latex ([#6986](https://github.com/helix-editor/helix/pull/6986))
- Update Dockerfile tree-sitter grammar ([#6895](https://github.com/helix-editor/helix/pull/6895))
- Add comment injections for Odin ([#7027](https://github.com/helix-editor/helix/pull/7027))
- Recognize `gml` as XML ([#7055](https://github.com/helix-editor/helix/pull/7055))
- Recognize `geojson` as JSON ([#7054](https://github.com/helix-editor/helix/pull/7054))
Packaging:
- Update the Nix flake dependencies, remove a deprecated option ([#6546](https://github.com/helix-editor/helix/pull/6546))
- Fix and re-enable aarch64-macos release binary builds ([#6504](https://github.com/helix-editor/helix/pull/6504))
- The git dependency on `tree-sitter` has been replaced with a regular crates.io dependency ([#6608](https://github.com/helix-editor/helix/pull/6608))
# 23.03 (2023-03-31)
23.03 brings some long-awaited and exciting features. Thank you to everyone involved! This release saw changes from 102 contributors.
For the full log, check out the [git log](https://github.com/helix-editor/helix/compare/22.12..23.03).
Also check out the [release notes](https://helix-editor.com/news/release-23-03-highlights/) for more commentary on larger features.
Breaking changes:
- Select diagnostic range in `goto_*_diag` commands ([#4713](https://github.com/helix-editor/helix/pull/4713), [#5164](https://github.com/helix-editor/helix/pull/5164), [#6193](https://github.com/helix-editor/helix/pull/6193))
- Remove jump behavior from `increment`/`decrement` ([#4123](https://github.com/helix-editor/helix/pull/4123), [#5929](https://github.com/helix-editor/helix/pull/5929))
- Select change range in `goto_*_change` commands ([#5206](https://github.com/helix-editor/helix/pull/5206))
- Split file modification indicator from filename statusline elements ([#4731](https://github.com/helix-editor/helix/pull/4731), [#6036](https://github.com/helix-editor/helix/pull/6036))
- Jump to symbol ranges in LSP goto commands ([#5986](https://github.com/helix-editor/helix/pull/5986))
- Workspace detection now stops at the first `.helix/` directory (merging multiple `.helix/languages.toml` configurations is no longer supported) ([#5748](https://github.com/helix-editor/helix/pull/5748))
Features:
- Dynamic workspace symbol picker ([#5055](https://github.com/helix-editor/helix/pull/5055))
- Soft-wrap ([#5420](https://github.com/helix-editor/helix/pull/5420), [#5786](https://github.com/helix-editor/helix/pull/5786), [#5893](https://github.com/helix-editor/helix/pull/5893), [#6142](https://github.com/helix-editor/helix/pull/6142), [#6440](https://github.com/helix-editor/helix/pull/6440))
- Initial support for LSP snippet completions ([#5864](https://github.com/helix-editor/helix/pull/5864), [b1f7528](https://github.com/helix-editor/helix/commit/b1f7528), [#6263](https://github.com/helix-editor/helix/pull/6263), [bbf4800](https://github.com/helix-editor/helix/commit/bbf4800), [90348b8](https://github.com/helix-editor/helix/commit/90348b8), [f87299f](https://github.com/helix-editor/helix/commit/f87299f), [#6371](https://github.com/helix-editor/helix/pull/6371), [9fe3adc](https://github.com/helix-editor/helix/commit/9fe3adc))
- Add a statusline element for showing the current version control HEAD ([#5682](https://github.com/helix-editor/helix/pull/5682))
- Display LSP type hints ([#5420](https://github.com/helix-editor/helix/pull/5420), [#5934](https://github.com/helix-editor/helix/pull/5934), [#6312](https://github.com/helix-editor/helix/pull/6312))
- Enable the Kitty keyboard protocol on terminals with support ([#4939](https://github.com/helix-editor/helix/pull/4939), [#6170](https://github.com/helix-editor/helix/pull/6170), [#6194](https://github.com/helix-editor/helix/pull/6194), [#6438](https://github.com/helix-editor/helix/pull/6438))
- Add a statusline element for the basename of the current file ([#5318](https://github.com/helix-editor/helix/pull/5318))
- Add substring matching syntax for the picker ([#5658](https://github.com/helix-editor/helix/pull/5658))
- Support LSP `textDocument/prepareRename` ([#6103](https://github.com/helix-editor/helix/pull/6103))
- Allow multiple runtime directories with priorities ([#5411](https://github.com/helix-editor/helix/pull/5411))
- Allow configuring whether to insert or replace completions ([#5728](https://github.com/helix-editor/helix/pull/5728))
- Allow per-workspace config file `.helix/config.toml` ([#5748](https://github.com/helix-editor/helix/pull/5748))
- Add `workspace-lsp-roots` config option to support multiple LSP roots for use with monorepos ([#5748](https://github.com/helix-editor/helix/pull/5748))
Commands:
- `:pipe-to` which pipes selections into a shell command and ignores output ([#4931](https://github.com/helix-editor/helix/pull/4931))
- `merge_consecutive_selections` (`A-_`) combines all consecutive selections ([#5047](https://github.com/helix-editor/helix/pull/5047))
- `rotate_view_reverse` which focuses the previous view ([#5356](https://github.com/helix-editor/helix/pull/5356))
- `goto_declaration` (`gD`, requires LSP) which jumps to a symbol's declaration ([#5646](https://github.com/helix-editor/helix/pull/5646))
- `file_picker_in_current_buffer_directory` ([#4666](https://github.com/helix-editor/helix/pull/4666))
- `:character-info` which shows information about the character under the cursor ([#4000](https://github.com/helix-editor/helix/pull/4000))
- `:toggle-option` for toggling config options at runtime ([#4085](https://github.com/helix-editor/helix/pull/4085))
- `dap_restart` for restarting a debug session in DAP ([#5651](https://github.com/helix-editor/helix/pull/5651))
- `:lsp-stop` to stop the language server of the current buffer ([#5964](https://github.com/helix-editor/helix/pull/5964))
- `:reset-diff-change` for resetting a diff hunk to its original text ([#4974](https://github.com/helix-editor/helix/pull/4974))
- `:config-open-workspace` for opening the config file local to the current workspace ([#5748](https://github.com/helix-editor/helix/pull/5748))
Usability improvements:
- Remove empty detail section in completion menu when LSP doesn't send details ([#4902](https://github.com/helix-editor/helix/pull/4902))
- Pass client information on LSP initialization ([#4904](https://github.com/helix-editor/helix/pull/4904))
- Allow specifying environment variables for language servers in language config ([#4004](https://github.com/helix-editor/helix/pull/4004))
- Allow detached git worktrees to be recognized as root paths ([#5097](https://github.com/helix-editor/helix/pull/5097))
- Improve error message handling for theme loading failures ([#5073](https://github.com/helix-editor/helix/pull/5073))
- Print the names of binaries required for LSP/DAP in health-check ([#5195](https://github.com/helix-editor/helix/pull/5195))
- Improve sorting in the picker in cases of ties ([#5169](https://github.com/helix-editor/helix/pull/5169))
- Add theming for prompt suggestions ([#5104](https://github.com/helix-editor/helix/pull/5104))
- Open a file picker when using `:open` on directories ([#2707](https://github.com/helix-editor/helix/pull/2707), [#5278](https://github.com/helix-editor/helix/pull/5278))
- Reload language config with `:config-reload` ([#5239](https://github.com/helix-editor/helix/pull/5239), [#5381](https://github.com/helix-editor/helix/pull/5381), [#5431](https://github.com/helix-editor/helix/pull/5431))
- Improve indent queries for python when the tree is errored ([#5332](https://github.com/helix-editor/helix/pull/5332))
- Picker: Open files without closing the picker with `A-ret` ([#4435](https://github.com/helix-editor/helix/pull/4435))
- Allow theming cursors by primary/secondary and by mode ([#5130](https://github.com/helix-editor/helix/pull/5130))
- Allow configuration of the minimum width for the line-numbers gutter ([#4724](https://github.com/helix-editor/helix/pull/4724), [#5696](https://github.com/helix-editor/helix/pull/5696))
- Use filename completer for `:run-shell-command` command ([#5729](https://github.com/helix-editor/helix/pull/5729))
- Surround with line-endings with `ms<ret>` ([#4571](https://github.com/helix-editor/helix/pull/4571))
- Hide duplicate symlinks in file pickers ([#5658](https://github.com/helix-editor/helix/pull/5658))
- Tabulate buffer picker contents ([#5777](https://github.com/helix-editor/helix/pull/5777))
- Add an option to disable LSP ([#4425](https://github.com/helix-editor/helix/pull/4425))
- Short-circuit tree-sitter and word object motions ([#5851](https://github.com/helix-editor/helix/pull/5851))
- Add exit code to failed command message ([#5898](https://github.com/helix-editor/helix/pull/5898))
- Make `m` textobject look for pairs enclosing selections ([#3344](https://github.com/helix-editor/helix/pull/3344))
- Negotiate LSP position encoding ([#5894](https://github.com/helix-editor/helix/pull/5894), [a48d1a4](https://github.com/helix-editor/helix/commit/a48d1a4))
- Display deprecated LSP completions with strikethrough ([#5932](https://github.com/helix-editor/helix/pull/5932))
- Add JSONRPC request ID to failed LSP/DAP request log messages ([#6010](https://github.com/helix-editor/helix/pull/6010), [#6018](https://github.com/helix-editor/helix/pull/6018))
- Ignore case when filtering LSP completions ([#6008](https://github.com/helix-editor/helix/pull/6008))
- Show current language when no arguments are passed to `:set-language` ([#5895](https://github.com/helix-editor/helix/pull/5895))
- Refactor and rewrite all book documentation ([#5534](https://github.com/helix-editor/helix/pull/5534))
- Separate diagnostic picker message and code ([#6095](https://github.com/helix-editor/helix/pull/6095))
- Add a config option to bypass undercurl detection ([#6253](https://github.com/helix-editor/helix/pull/6253))
- Only complete appropriate arguments for typed commands ([#5966](https://github.com/helix-editor/helix/pull/5966))
- Discard outdated LSP diagnostics ([3c9d5d0](https://github.com/helix-editor/helix/commit/3c9d5d0))
- Discard outdated LSP workspace edits ([b6a4927](https://github.com/helix-editor/helix/commit/b6a4927))
- Run shell commands asynchronously ([#6373](https://github.com/helix-editor/helix/pull/6373))
- Show diagnostic codes in LSP diagnostic messages ([#6378](https://github.com/helix-editor/helix/pull/6378))
- Highlight the current line in a DAP debug session ([#5957](https://github.com/helix-editor/helix/pull/5957))
- Hide signature help if it overlaps with the completion menu ([#5523](https://github.com/helix-editor/helix/pull/5523), [7a69c40](https://github.com/helix-editor/helix/commit/7a69c40))
Fixes:
- Fix behavior of `auto-completion` flag for completion-on-trigger ([#5042](https://github.com/helix-editor/helix/pull/5042))
- Reset editor mode when changing buffers ([#5072](https://github.com/helix-editor/helix/pull/5072))
- Respect scrolloff settings in mouse movements ([#5255](https://github.com/helix-editor/helix/pull/5255))
- Avoid trailing `s` when only one file is opened ([#5189](https://github.com/helix-editor/helix/pull/5189))
- Fix erroneous indent between closers of auto-pairs ([#5330](https://github.com/helix-editor/helix/pull/5330))
- Expand `~` when parsing file paths in `:open` ([#5329](https://github.com/helix-editor/helix/pull/5329))
- Fix theme inheritance for default themes ([#5218](https://github.com/helix-editor/helix/pull/5218))
- Fix `extend_line` with a count when the current line(s) are selected ([#5288](https://github.com/helix-editor/helix/pull/5288))
- Prompt: Fix autocompletion for paths containing periods ([#5175](https://github.com/helix-editor/helix/pull/5175))
- Skip serializing JSONRPC params if params is null ([#5471](https://github.com/helix-editor/helix/pull/5471))
- Fix interaction with the `xclip` clipboard provider ([#5426](https://github.com/helix-editor/helix/pull/5426))
- Fix undo/redo execution from the command palette ([#5294](https://github.com/helix-editor/helix/pull/5294))
- Fix highlighting of non-block cursors ([#5575](https://github.com/helix-editor/helix/pull/5575))
- Fix panic when nooping in `join_selections` and `join_selections_space` ([#5423](https://github.com/helix-editor/helix/pull/5423))
- Fix selecting a changed file in global search ([#5639](https://github.com/helix-editor/helix/pull/5639))
- Fix initial syntax highlight layer sort order ([#5196](https://github.com/helix-editor/helix/pull/5196))
- Fix UTF-8 length handling for shellwords ([#5738](https://github.com/helix-editor/helix/pull/5738))
- Remove C-j and C-k bindings from the completion menu ([#5070](https://github.com/helix-editor/helix/pull/5070))
- Always commit to history when pasting ([#5790](https://github.com/helix-editor/helix/pull/5790))
- Properly handle LSP position encoding ([#5711](https://github.com/helix-editor/helix/pull/5711))
- Fix infinite loop in `copy_selection_on_prev_line` ([#5888](https://github.com/helix-editor/helix/pull/5888))
- Fix completion popup positioning ([#5842](https://github.com/helix-editor/helix/pull/5842))
- Fix a panic when uncommenting a line with only a comment token ([#5933](https://github.com/helix-editor/helix/pull/5933))
- Fix panic in `goto_window_center` at EOF ([#5987](https://github.com/helix-editor/helix/pull/5987))
- Ignore invalid file URIs sent by a language server ([#6000](https://github.com/helix-editor/helix/pull/6000))
- Decode LSP URIs for the workspace diagnostics picker ([#6016](https://github.com/helix-editor/helix/pull/6016))
- Fix incorrect usages of `tab_width` with `indent_width` ([#5918](https://github.com/helix-editor/helix/pull/5918))
- DAP: Send Disconnect if the Terminated event is received ([#5532](https://github.com/helix-editor/helix/pull/5532))
- DAP: Validate key and index exist when requesting variables ([#5628](https://github.com/helix-editor/helix/pull/5628))
- Check LSP renaming support before prompting for rename text ([#6257](https://github.com/helix-editor/helix/pull/6257))
- Fix indent guide rendering ([#6136](https://github.com/helix-editor/helix/pull/6136))
- Fix division by zero panic ([#6155](https://github.com/helix-editor/helix/pull/6155))
- Fix lacking space panic ([#6109](https://github.com/helix-editor/helix/pull/6109))
- Send error replies for malformed and unhandled LSP requests ([#6058](https://github.com/helix-editor/helix/pull/6058))
- Fix table column calculations for dynamic pickers ([#5920](https://github.com/helix-editor/helix/pull/5920))
- Skip adding jumplist entries for `:<n>` line number previews ([#5751](https://github.com/helix-editor/helix/pull/5751))
- Fix completion race conditions ([#6173](https://github.com/helix-editor/helix/pull/6173))
- Fix `shrink_selection` with multiple cursors ([#6093](https://github.com/helix-editor/helix/pull/6093))
- Fix indentation calculation for lines with mixed tabs/spaces ([#6278](https://github.com/helix-editor/helix/pull/6278))
- No-op `client/registerCapability` LSP requests ([#6258](https://github.com/helix-editor/helix/pull/6258))
- Send the STOP signal to all processes in the process group ([#3546](https://github.com/helix-editor/helix/pull/3546))
- Fix workspace edit client capabilities declaration ([7bf168d](https://github.com/helix-editor/helix/commit/7bf168d))
- Fix highlighting in picker results with multiple columns ([#6333](https://github.com/helix-editor/helix/pull/6333))
- Canonicalize paths before stripping the current dir as a prefix ([#6290](https://github.com/helix-editor/helix/pull/6290))
- Fix truncation behavior for long path names in the file picker ([#6410](https://github.com/helix-editor/helix/pull/6410), [67783dd](https://github.com/helix-editor/helix/commit/67783dd))
- Fix theme reloading behavior in `:config-reload` ([ab819d8](https://github.com/helix-editor/helix/commit/ab819d8))
Themes:
- Update `serika` ([#5038](https://github.com/helix-editor/helix/pull/5038), [#6344](https://github.com/helix-editor/helix/pull/6344))
- Update `flatwhite` ([#5036](https://github.com/helix-editor/helix/pull/5036), [#6323](https://github.com/helix-editor/helix/pull/6323))
- Update `autumn` ([#5051](https://github.com/helix-editor/helix/pull/5051), [#5397](https://github.com/helix-editor/helix/pull/5397), [#6280](https://github.com/helix-editor/helix/pull/6280), [#6316](https://github.com/helix-editor/helix/pull/6316))
- Update `acme` ([#5019](https://github.com/helix-editor/helix/pull/5019), [#5486](https://github.com/helix-editor/helix/pull/5486), [#5488](https://github.com/helix-editor/helix/pull/5488))
- Update `gruvbox` themes ([#5066](https://github.com/helix-editor/helix/pull/5066), [#5333](https://github.com/helix-editor/helix/pull/5333), [#5540](https://github.com/helix-editor/helix/pull/5540), [#6285](https://github.com/helix-editor/helix/pull/6285), [#6295](https://github.com/helix-editor/helix/pull/6295))
- Update `base16_transparent` ([#5105](https://github.com/helix-editor/helix/pull/5105))
- Update `dark_high_contrast` ([#5105](https://github.com/helix-editor/helix/pull/5105))
- Update `dracula` ([#5236](https://github.com/helix-editor/helix/pull/5236), [#5627](https://github.com/helix-editor/helix/pull/5627), [#6414](https://github.com/helix-editor/helix/pull/6414))
- Update `monokai_pro_spectrum` ([#5250](https://github.com/helix-editor/helix/pull/5250), [#5602](https://github.com/helix-editor/helix/pull/5602))
- Update `rose_pine` ([#5267](https://github.com/helix-editor/helix/pull/5267), [#5489](https://github.com/helix-editor/helix/pull/5489), [#6384](https://github.com/helix-editor/helix/pull/6384))
- Update `kanagawa` ([#5273](https://github.com/helix-editor/helix/pull/5273), [#5571](https://github.com/helix-editor/helix/pull/5571), [#6085](https://github.com/helix-editor/helix/pull/6085))
- Update `emacs` ([#5334](https://github.com/helix-editor/helix/pull/5334))
- Add `github` themes ([#5353](https://github.com/helix-editor/helix/pull/5353), [efeec12](https://github.com/helix-editor/helix/commit/efeec12))
- Dark themes: `github_dark`, `github_dark_colorblind`, `github_dark_dimmed`, `github_dark_high_contrast`, `github_dark_tritanopia`
- Light themes: `github_light`, `github_light_colorblind`, `github_light_dimmed`, `github_light_high_contrast`, `github_light_tritanopia`
- Update `solarized` variants ([#5445](https://github.com/helix-editor/helix/pull/5445), [#6327](https://github.com/helix-editor/helix/pull/6327))
- Update `catppuccin` variants ([#5404](https://github.com/helix-editor/helix/pull/5404), [#6107](https://github.com/helix-editor/helix/pull/6107), [#6269](https://github.com/helix-editor/helix/pull/6269), [#6464](https://github.com/helix-editor/helix/pull/6464))
- Use curly underlines in built-in themes ([#5419](https://github.com/helix-editor/helix/pull/5419))
- Update `zenburn` ([#5573](https://github.com/helix-editor/helix/pull/5573))
- Rewrite `snazzy` ([#3971](https://github.com/helix-editor/helix/pull/3971))
- Add `monokai_aqua` ([#5578](https://github.com/helix-editor/helix/pull/5578))
- Add `markup.strikethrough` to existing themes ([#5619](https://github.com/helix-editor/helix/pull/5619))
- Update `sonokai` ([#5440](https://github.com/helix-editor/helix/pull/5440))
- Update `onedark` ([#5755](https://github.com/helix-editor/helix/pull/5755))
- Add `ayu_evolve` ([#5638](https://github.com/helix-editor/helix/pull/5638), [#6028](https://github.com/helix-editor/helix/pull/6028), [#6225](https://github.com/helix-editor/helix/pull/6225))
- Add `jellybeans` ([#5719](https://github.com/helix-editor/helix/pull/5719))
- Update `fleet_dark` ([#5605](https://github.com/helix-editor/helix/pull/5605), [#6266](https://github.com/helix-editor/helix/pull/6266), [#6324](https://github.com/helix-editor/helix/pull/6324), [#6375](https://github.com/helix-editor/helix/pull/6375))
- Add `darcula-solid` ([#5778](https://github.com/helix-editor/helix/pull/5778))
- Remove text background from monokai themes ([#6009](https://github.com/helix-editor/helix/pull/6009))
- Update `pop_dark` ([#5992](https://github.com/helix-editor/helix/pull/5992), [#6208](https://github.com/helix-editor/helix/pull/6208), [#6227](https://github.com/helix-editor/helix/pull/6227), [#6292](https://github.com/helix-editor/helix/pull/6292))
- Add `everblush` ([#6086](https://github.com/helix-editor/helix/pull/6086))
- Add `adwaita-dark` ([#6042](https://github.com/helix-editor/helix/pull/6042), [#6342](https://github.com/helix-editor/helix/pull/6342))
- Update `papercolor` ([#6162](https://github.com/helix-editor/helix/pull/6162))
- Update `onelight` ([#6192](https://github.com/helix-editor/helix/pull/6192), [#6276](https://github.com/helix-editor/helix/pull/6276))
- Add `molokai` ([#6260](https://github.com/helix-editor/helix/pull/6260))
- Update `ayu` variants ([#6329](https://github.com/helix-editor/helix/pull/6329))
- Update `tokyonight` variants ([#6349](https://github.com/helix-editor/helix/pull/6349))
- Update `nord` variants ([#6376](https://github.com/helix-editor/helix/pull/6376))
New languages:
- BibTeX ([#5064](https://github.com/helix-editor/helix/pull/5064))
- Mermaid.js ([#5147](https://github.com/helix-editor/helix/pull/5147))
- Crystal ([#4993](https://github.com/helix-editor/helix/pull/4993), [#5205](https://github.com/helix-editor/helix/pull/5205))
- MATLAB/Octave ([#5192](https://github.com/helix-editor/helix/pull/5192))
- `tfvars` (uses HCL) ([#5396](https://github.com/helix-editor/helix/pull/5396))
- Ponylang ([#5416](https://github.com/helix-editor/helix/pull/5416))
- DHall ([1f6809c](https://github.com/helix-editor/helix/commit/1f6809c))
- Sagemath ([#5649](https://github.com/helix-editor/helix/pull/5649))
- MSBuild ([#5793](https://github.com/helix-editor/helix/pull/5793))
- pem ([#5797](https://github.com/helix-editor/helix/pull/5797))
- passwd ([#4959](https://github.com/helix-editor/helix/pull/4959))
- hosts ([#4950](https://github.com/helix-editor/helix/pull/4950), [#5914](https://github.com/helix-editor/helix/pull/5914))
- uxntal ([#6047](https://github.com/helix-editor/helix/pull/6047))
- Yuck ([#6064](https://github.com/helix-editor/helix/pull/6064), [#6242](https://github.com/helix-editor/helix/pull/6242))
- GNU gettext PO ([#5996](https://github.com/helix-editor/helix/pull/5996))
- Sway ([#6023](https://github.com/helix-editor/helix/pull/6023))
- NASM ([#6068](https://github.com/helix-editor/helix/pull/6068))
- PRQL ([#6126](https://github.com/helix-editor/helix/pull/6126))
- reStructuredText ([#6180](https://github.com/helix-editor/helix/pull/6180))
- Smithy ([#6370](https://github.com/helix-editor/helix/pull/6370))
- VHDL ([#5826](https://github.com/helix-editor/helix/pull/5826))
- Rego (OpenPolicy Agent) ([#6415](https://github.com/helix-editor/helix/pull/6415))
- Nim ([#6123](https://github.com/helix-editor/helix/pull/6123))
Updated languages and queries:
- Use diff syntax for patch files ([#5085](https://github.com/helix-editor/helix/pull/5085))
- Add Haskell textobjects ([#5061](https://github.com/helix-editor/helix/pull/5061))
- Fix commonlisp configuration ([#5091](https://github.com/helix-editor/helix/pull/5091))
- Update Scheme ([bae890d](https://github.com/helix-editor/helix/commit/bae890d))
- Add indent queries for Bash ([#5149](https://github.com/helix-editor/helix/pull/5149))
- Recognize `c++` as a C++ extension ([#5183](https://github.com/helix-editor/helix/pull/5183))
- Enable HTTP server in `metals` (Scala) config ([#5551](https://github.com/helix-editor/helix/pull/5551))
- Change V-lang language server to `v ls` from `vls` ([#5677](https://github.com/helix-editor/helix/pull/5677))
- Inject comment grammar into Nix ([#5208](https://github.com/helix-editor/helix/pull/5208))
- Update Rust highlights ([#5238](https://github.com/helix-editor/helix/pull/5238), [#5349](https://github.com/helix-editor/helix/pull/5349))
- Fix HTML injection within Markdown ([#5265](https://github.com/helix-editor/helix/pull/5265))
- Fix comment token for godot ([#5276](https://github.com/helix-editor/helix/pull/5276))
- Expand injections for Vue ([#5268](https://github.com/helix-editor/helix/pull/5268))
- Add `.bash_aliases` as a Bash file-type ([#5347](https://github.com/helix-editor/helix/pull/5347))
- Fix comment token for sshclientconfig ([#5351](https://github.com/helix-editor/helix/pull/5351))
- Update Prisma ([#5417](https://github.com/helix-editor/helix/pull/5417))
- Update C++ ([#5457](https://github.com/helix-editor/helix/pull/5457))
- Add more file-types for Python ([#5593](https://github.com/helix-editor/helix/pull/5593))
- Update tree-sitter-scala ([#5576](https://github.com/helix-editor/helix/pull/5576))
- Add an injection regex for Lua ([#5606](https://github.com/helix-editor/helix/pull/5606))
- Add `build.gradle` to java roots configuration ([#5641](https://github.com/helix-editor/helix/pull/5641))
- Add Hub PR files to markdown file-types ([#5634](https://github.com/helix-editor/helix/pull/5634))
- Add an external formatter configuration for Cue ([#5679](https://github.com/helix-editor/helix/pull/5679))
- Add injections for builders and writers to Nix ([#5629](https://github.com/helix-editor/helix/pull/5629))
- Update tree-sitter-xml to fix whitespace parsing ([#5685](https://github.com/helix-editor/helix/pull/5685))
- Add `Justfile` to the make file-types configuration ([#5687](https://github.com/helix-editor/helix/pull/5687))
- Update tree-sitter-sql and highlight queries ([#5683](https://github.com/helix-editor/helix/pull/5683), [#5772](https://github.com/helix-editor/helix/pull/5772))
- Use the bash grammar and queries for env language ([#5720](https://github.com/helix-editor/helix/pull/5720))
- Add podspec files to ruby file-types ([#5811](https://github.com/helix-editor/helix/pull/5811))
- Recognize `.C` and `.H` file-types as C++ ([#5808](https://github.com/helix-editor/helix/pull/5808))
- Recognize plist and mobileconfig files as XML ([#5863](https://github.com/helix-editor/helix/pull/5863))
- Fix `select` indentation in Go ([#5713](https://github.com/helix-editor/helix/pull/5713))
- Check for external file modifications when writing ([#5805](https://github.com/helix-editor/helix/pull/5805))
- Recognize containerfiles as dockerfile syntax ([#5873](https://github.com/helix-editor/helix/pull/5873))
- Update godot grammar and queries ([#5944](https://github.com/helix-editor/helix/pull/5944), [#6186](https://github.com/helix-editor/helix/pull/6186))
- Improve DHall highlights ([#5959](https://github.com/helix-editor/helix/pull/5959))
- Recognize `.env.dist` and `source.env` as env language ([#6003](https://github.com/helix-editor/helix/pull/6003))
- Update tree-sitter-git-rebase ([#6030](https://github.com/helix-editor/helix/pull/6030), [#6094](https://github.com/helix-editor/helix/pull/6094))
- Improve SQL highlights ([#6041](https://github.com/helix-editor/helix/pull/6041))
- Improve markdown highlights and inject LaTeX ([#6100](https://github.com/helix-editor/helix/pull/6100))
- Add textobject queries for Elm ([#6084](https://github.com/helix-editor/helix/pull/6084))
- Recognize graphql schema file type ([#6159](https://github.com/helix-editor/helix/pull/6159))
- Improve highlighting in comments ([#6143](https://github.com/helix-editor/helix/pull/6143))
- Improve highlighting for JavaScript/TypeScript/ECMAScript languages ([#6205](https://github.com/helix-editor/helix/pull/6205))
- Improve PHP highlights ([#6203](https://github.com/helix-editor/helix/pull/6203), [#6250](https://github.com/helix-editor/helix/pull/6250), [#6299](https://github.com/helix-editor/helix/pull/6299))
- Improve Go highlights ([#6204](https://github.com/helix-editor/helix/pull/6204))
- Highlight unchecked sqlx functions as SQL in Rust ([#6256](https://github.com/helix-editor/helix/pull/6256))
- Improve Erlang highlights ([cdd6c8d](https://github.com/helix-editor/helix/commit/cdd6c8d))
- Improve Nix highlights ([fb4d703](https://github.com/helix-editor/helix/commit/fb4d703))
- Improve gdscript highlights ([#6311](https://github.com/helix-editor/helix/pull/6311))
- Improve Vlang highlights ([#6279](https://github.com/helix-editor/helix/pull/6279))
- Improve Makefile highlights ([#6339](https://github.com/helix-editor/helix/pull/6339))
- Remove auto-pair for `'` in OCaml ([#6381](https://github.com/helix-editor/helix/pull/6381))
- Fix indents in switch statements in ECMA languages ([#6369](https://github.com/helix-editor/helix/pull/6369))
- Recognize xlb and storyboard file-types as XML ([#6407](https://github.com/helix-editor/helix/pull/6407))
- Recognize cts and mts file-types as TypeScript ([#6424](https://github.com/helix-editor/helix/pull/6424))
- Recognize SVG file-type as XML ([#6431](https://github.com/helix-editor/helix/pull/6431))
- Add theme scopes for (un)checked list item markup scopes ([#6434](https://github.com/helix-editor/helix/pull/6434))
- Update git commit grammar and add the comment textobject ([#6439](https://github.com/helix-editor/helix/pull/6439), [#6493](https://github.com/helix-editor/helix/pull/6493))
- Recognize ARB file-type as JSON ([#6452](https://github.com/helix-editor/helix/pull/6452))
- Inject markdown into markdown strings in Julia ([#6489](https://github.com/helix-editor/helix/pull/6489))
Packaging:
- Fix Nix flake devShell for darwin hosts ([#5368](https://github.com/helix-editor/helix/pull/5368))
- Add Appstream metadata file to `contrib/` ([#5643](https://github.com/helix-editor/helix/pull/5643))
- Increase the MSRV to 1.65 ([#5570](https://github.com/helix-editor/helix/pull/5570), [#6185](https://github.com/helix-editor/helix/pull/6185))
- Expose the Nix flake's `wrapper` ([#5994](https://github.com/helix-editor/helix/pull/5994))
# 22.12 (2022-12-06) # 22.12 (2022-12-06)
This is a great big release filled with changes from a 99 contributors. A big _thank you_ to you all! This is a great big release filled with changes from a 99 contributors. A big _thank you_ to you all!
@ -1206,7 +1856,7 @@ to distinguish it in bug reports..
- The `runtime/` directory is now properly detected on binary releases and - The `runtime/` directory is now properly detected on binary releases and
on cargo run. `~/.config/helix/runtime` can also be used. on cargo run. `~/.config/helix/runtime` can also be used.
- Registers can now be selected via " (for example `"ay`) - Registers can now be selected via " (for example, `"ay`)
- Support for Nix files was added - Support for Nix files was added
- Movement is now fully tested and matches Kakoune implementation - Movement is now fully tested and matches Kakoune implementation
- A per-file LSP symbol picker was added to space+s - A per-file LSP symbol picker was added to space+s

1820
Cargo.lock generated

File diff suppressed because it is too large Load Diff

@ -5,9 +5,11 @@ members = [
"helix-term", "helix-term",
"helix-tui", "helix-tui",
"helix-lsp", "helix-lsp",
"helix-event",
"helix-dap", "helix-dap",
"helix-loader", "helix-loader",
"helix-vcs", "helix-vcs",
"helix-parsec",
"xtask", "xtask",
] ]
@ -25,3 +27,13 @@ lto = "fat"
codegen-units = 1 codegen-units = 1
# strip = "debuginfo" # TODO: or strip = true # strip = "debuginfo" # TODO: or strip = true
opt-level = 3 opt-level = 3
[profile.integration]
inherits = "test"
package.helix-core.opt-level = 2
package.helix-tui.opt-level = 2
package.helix-term.opt-level = 2
[workspace.dependencies]
tree-sitter = { version = "0.20", git = "https://github.com/tree-sitter/tree-sitter", rev = "ab09ae20d640711174b8da8a654f6b3dec93da1a" }
nucleo = "0.2.0"

@ -45,92 +45,10 @@ Note: Only certain languages have indentation definitions at the moment. Check
# Installation # Installation
Packages are available for various distributions (see [Installation docs](https://docs.helix-editor.com/install.html)). [Installation documentation](https://docs.helix-editor.com/install.html).
If you would like to build from source:
```shell
git clone https://github.com/helix-editor/helix
cd helix
cargo install --path helix-term
```
This will install the `hx` binary to `$HOME/.cargo/bin` and build tree-sitter grammars in `./runtime/grammars`.
Helix needs its runtime files so make sure to copy/symlink the `runtime/` directory into the
config directory (for example `~/.config/helix/runtime` on Linux/macOS, or `%AppData%/helix/runtime` on Windows).
| OS | Command |
| -------------------- | ------------------------------------------------ |
| Windows (Cmd) | `xcopy /e /i runtime %AppData%\helix\runtime` |
| Windows (PowerShell) | `xcopy /e /i runtime $Env:AppData\helix\runtime` |
| Linux / macOS | `ln -s $PWD/runtime ~/.config/helix/runtime` |
Starting with Windows Vista you can also create symbolic links on Windows. Note that this requires
elevated privileges - i.e. PowerShell or Cmd must be run as administrator.
**PowerShell:**
```powershell
New-Item -ItemType SymbolicLink -Target "runtime" -Path "$Env:AppData\helix\runtime"
```
**Cmd:**
```cmd
cd %appdata%\helix
mklink /D runtime "<helix-repo>\runtime"
```
The runtime location can be overridden via the `HELIX_RUNTIME` environment variable.
> NOTE: if `HELIX_RUNTIME` is set prior to calling `cargo install --path helix-term`,
> tree-sitter grammars will be built in `$HELIX_RUNTIME/grammars`.
If you plan on keeping the repo locally, an alternative to copying/symlinking
runtime files is to set `HELIX_RUNTIME=/path/to/helix/runtime`
(`HELIX_RUNTIME=$PWD/runtime` if you're in the helix repo directory).
Packages already solve this for you by wrapping the `hx` binary with a wrapper
that sets the variable to the install dir.
> NOTE: running via cargo also doesn't require setting explicit `HELIX_RUNTIME` path, it will automatically
> detect the `runtime` directory in the project root.
If you want to customize your `languages.toml` config,
tree-sitter grammars may be manually fetched and built with `hx --grammar fetch` and `hx --grammar build`.
In order to use LSP features like auto-complete, you will need to
[install the appropriate Language Server](https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers)
for a language.
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions) [![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions)
## Adding Helix to your desktop environment
If installing from source, to use Helix in desktop environments that supports [XDG desktop menu](https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html), including Gnome and KDE, copy the provided `.desktop` file to the correct folder:
```bash
cp contrib/Helix.desktop ~/.local/share/applications
```
To use another terminal than the default, you will need to modify the `.desktop` file. For example, to use `kitty`:
```bash
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
```
Please note: there is no icon for Helix yet, so the system default will be used.
## macOS
Helix can be installed on macOS through homebrew:
```
brew install helix
```
# Contributing # Contributing
Contributing guidelines can be found [here](./docs/CONTRIBUTING.md). Contributing guidelines can be found [here](./docs/CONTRIBUTING.md).
@ -143,4 +61,4 @@ Discuss the project on the community [Matrix Space](https://matrix.to/#/#helix-c
# Credits # Credits
Thanks to [@JakeHL](https://github.com/JakeHL) for designing the logo! Thanks to [@jakenvac](https://github.com/jakenvac) for designing the logo!

@ -1 +1 @@
22.12 23.10

@ -7,6 +7,7 @@
"ui.linenr.selected" = { fg = "white", bg = "black", modifiers = ["bold"] } "ui.linenr.selected" = { fg = "white", bg = "black", modifiers = ["bold"] }
"ui.selection" = { fg = "black", bg = "blue" } "ui.selection" = { fg = "black", bg = "blue" }
"ui.selection.primary" = { fg = "white", bg = "blue" } "ui.selection.primary" = { fg = "white", bg = "blue" }
"ui.text.inactive" = { fg = "gray" }
"comment" = { fg = "gray" } "comment" = { fg = "gray" }
"ui.statusline" = { fg = "black", bg = "white" } "ui.statusline" = { fg = "black", bg = "white" }
"ui.statusline.inactive" = { fg = "gray", bg = "white" } "ui.statusline.inactive" = { fg = "gray", bg = "white" }

@ -3,9 +3,14 @@ authors = ["Blaž Hrastnik"]
language = "en" language = "en"
multilingual = false multilingual = false
src = "src" src = "src"
edit-url-template = "https://github.com/helix-editor/helix/tree/master/book/{path}?mode=edit"
[output.html] [output.html]
cname = "docs.helix-editor.com" cname = "docs.helix-editor.com"
default-theme = "colibri" default-theme = "colibri"
preferred-dark-theme = "colibri" preferred-dark-theme = "colibri"
git-repository-url = "https://github.com/helix-editor/helix"
edit-url-template = "https://github.com/helix-editor/helix/edit/master/book/{path}"
additional-css = ["custom.css"]
[output.html.search]
use-boolean-and = true

@ -0,0 +1,231 @@
html {
font-family: "Inter", sans-serif;
}
.sidebar .sidebar-scrollbox {
padding: 0;
}
.chapter {
margin: 0.25rem 0;
}
.chapter li.chapter-item {
line-height: initial;
margin: 0;
padding: 1rem 1.5rem;
}
.chapter .section li.chapter-item {
line-height: inherit;
padding: .5rem .5rem 0 .5rem;
}
.content {
overflow-y: auto;
padding: 0 15px;
padding-bottom: 50px;
}
/* 2 1.75 1.5 1.25 1 .875 */
.content h1 { font-size: 2em }
.content h2 { font-size: 1.75em }
.content h3 { font-size: 1.5em }
.content h4 { font-size: 1.25em }
.content h5 { font-size: 1em }
.content h6 { font-size: .875em }
.content h1,
.content h2,
.content h3,
.content h4 {
font-weight: 500;
margin-top: 1.275em;
margin-bottom: .875em;
}
.content p,
.content ol,
.content ul,
.content table {
margin-top: 0;
margin-bottom: .875em;
}
.content ul li {
margin-bottom: .25rem;
}
.content ul {
list-style-type: square;
}
.content ul ul,
.content ol ul {
margin-bottom: .5rem;
}
.content li p {
margin-bottom: .5em;
}
blockquote {
margin: 1.5rem 0;
padding: 1rem 1.5rem;
color: var(--fg);
opacity: .9;
background-color: var(--quote-bg);
border-left: 4px solid var(--quote-border);
border-top: none;
border-bottom: none;
}
blockquote *:last-child {
margin-bottom: 0;
}
table {
width: 100%;
}
table thead th {
padding: .75rem;
text-align: left;
font-weight: 500;
line-height: 1.5;
width: auto;
}
table td {
padding: .75rem;
border: none;
}
table thead tr {
border: none;
border-bottom: 2px var(--table-border-color) solid;
}
table tbody tr {
border-bottom: 1px var(--table-border-line) solid;
}
table tbody tr:nth-child(2n) {
background: unset;
}
pre code.hljs {
display: block;
overflow-x: auto;
padding: 1em;
}
code.hljs {
padding: 3px 5px;
}
.colibri {
--bg: #3b224c;
--fg: #bcbdd0;
--heading-fg: #fff;
--sidebar-bg: #281733;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #505274;
--sidebar-active: #a4a0e8;
--sidebar-spacer: #2d334f;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #b7b9cc;
/* --links: #a4a0e8; */
--links: #ECCDBA;
--inline-code-color: hsl(48.7, 7.8%, 70%);
--theme-popup-bg: #161923;
--theme-popup-border: #737480;
--theme-hover: rgba(0, 0, 0, .2);
--quote-bg: #281733;
--quote-border: hsl(226, 15%, 22%);
--table-border-color: hsl(226, 23%, 76%);
--table-header-bg: hsla(226, 23%, 31%, 0);
--table-alternate-bg: hsl(226, 23%, 14%);
--table-border-line: hsla(201deg, 20%, 92%, 0.2);
--searchbar-border-color: #aaa;
--searchbar-bg: #aeaec6;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #5f5f71;
--searchresults-border-color: #5c5c68;
--searchresults-li-bg: #242430;
--search-mark-bg: #a2cff5;
}
.colibri .content .header {
color: #fff;
}
/* highlight.js theme, :where() is used to avoid increasing specificity */
:where(.colibri) .hljs {
background: #2f1e2e;
color: #a39e9b;
}
:where(.colibri) .hljs-comment,
:where(.colibri) .hljs-quote {
color: #8d8687;
}
:where(.colibri) .hljs-link,
:where(.colibri) .hljs-meta,
:where(.colibri) .hljs-name,
:where(.colibri) .hljs-regexp,
:where(.colibri) .hljs-selector-class,
:where(.colibri) .hljs-selector-id,
:where(.colibri) .hljs-tag,
:where(.colibri) .hljs-template-variable,
:where(.colibri) .hljs-variable {
color: #ef6155;
}
:where(.colibri) .hljs-built_in,
:where(.colibri) .hljs-deletion,
:where(.colibri) .hljs-literal,
:where(.colibri) .hljs-number,
:where(.colibri) .hljs-params,
:where(.colibri) .hljs-type {
color: #f99b15;
}
:where(.colibri) .hljs-attribute,
:where(.colibri) .hljs-section,
:where(.colibri) .hljs-title {
color: #fec418;
}
:where(.colibri) .hljs-addition,
:where(.colibri) .hljs-bullet,
:where(.colibri) .hljs-string,
:where(.colibri) .hljs-symbol {
color: #48b685;
}
:where(.colibri) .hljs-keyword,
:where(.colibri) .hljs-selector-tag {
color: #815ba4;
}
:where(.colibri) .hljs-emphasis {
font-style: italic;
}
:where(.colibri) .hljs-strong {
font-weight: 700;
}

@ -6,13 +6,14 @@
- [Usage](./usage.md) - [Usage](./usage.md)
- [Keymap](./keymap.md) - [Keymap](./keymap.md)
- [Commands](./commands.md) - [Commands](./commands.md)
- [Language Support](./lang-support.md) - [Language support](./lang-support.md)
- [Migrating from Vim](./from-vim.md) - [Migrating from Vim](./from-vim.md)
- [Configuration](./configuration.md) - [Configuration](./configuration.md)
- [Themes](./themes.md) - [Themes](./themes.md)
- [Key Remapping](./remapping.md) - [Key remapping](./remapping.md)
- [Languages](./languages.md) - [Languages](./languages.md)
- [Guides](./guides/README.md) - [Guides](./guides/README.md)
- [Adding Languages](./guides/adding_languages.md) - [Adding languages](./guides/adding_languages.md)
- [Adding Textobject Queries](./guides/textobject.md) - [Adding textobject queries](./guides/textobject.md)
- [Adding Indent Queries](./guides/indent.md) - [Adding indent queries](./guides/indent.md)
- [Adding injection queries](./guides/injection.md)

@ -1,5 +1,5 @@
# Commands # Commands
Command mode can be activated by pressing `:`, similar to Vim. Built-in commands: Command mode can be activated by pressing `:`. The built-in commands are:
{{#include ./generated/typable-cmd.md}} {{#include ./generated/typable-cmd.md}}

@ -2,10 +2,10 @@
To override global configuration parameters, create a `config.toml` file located in your config directory: To override global configuration parameters, create a `config.toml` file located in your config directory:
* Linux and Mac: `~/.config/helix/config.toml` - Linux and Mac: `~/.config/helix/config.toml`
* Windows: `%AppData%\helix\config.toml` - Windows: `%AppData%\helix\config.toml`
> Hint: You can easily open the config file by typing `:config-open` within Helix normal mode. > 💡 You can easily open the config file by typing `:config-open` within Helix normal mode.
Example config: Example config:
@ -25,12 +25,13 @@ select = "underline"
hidden = false hidden = false
``` ```
You may also specify a file to use for configuration with the `-c` or You can use a custom configuration file by specifying it with the `-c` or
`--config` CLI argument: `hx -c path/to/custom-config.toml`. `--config` command line argument, for example `hx -c path/to/custom-config.toml`.
Additionally, you can reload the configuration file by sending the USR1
signal to the Helix process on Unix operating systems, such as by using the command `pkill -USR1 hx`.
It is also possible to trigger configuration file reloading by sending the `USR1` Finally, you can have a `config.toml` local to a project by putting it under a `.helix` directory in your repository.
signal to the helix process, e.g. via `pkill -USR1 hx`. This is only supported Its settings will be merged with the configuration directory `config.toml` and the built-in configuration.
on unix operating systems.
## Editor ## Editor
@ -38,25 +39,32 @@ on unix operating systems.
| Key | Description | Default | | Key | Description | Default |
|--|--|---------| |--|--|---------|
| `scrolloff` | Number of lines of padding around the edge of the screen when scrolling. | `5` | | `scrolloff` | Number of lines of padding around the edge of the screen when scrolling | `5` |
| `mouse` | Enable mouse mode. | `true` | | `mouse` | Enable mouse mode | `true` |
| `middle-click-paste` | Middle click paste support. | `true` | | `middle-click-paste` | Middle click paste support | `true` |
| `scroll-lines` | Number of lines to scroll per scroll wheel step. | `3` | | `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"]` | | `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` | | `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` | | `cursorline` | Highlight all lines with a cursor | `false` |
| `cursorcolumn` | Highlight all columns 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"]` | | `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-completion` | Enable automatic pop up of auto-completion | `true` |
| `auto-format` | Enable automatic formatting on save. | `true` | | `auto-format` | Enable automatic formatting on save | `true` |
| `auto-save` | Enable automatic saving on focus moving away from Helix. Requires [focus event support](https://github.com/helix-editor/helix/wiki/Terminal-Support) from your terminal. | `false` | | `auto-save` | Enable automatic saving on the focus moving away from Helix. Requires [focus event support](https://github.com/helix-editor/helix/wiki/Terminal-Support) from your terminal | `false` |
| `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. Used for autocompletion, set to 0 for instant. | `400` | | `idle-timeout` | Time in milliseconds since last keypress before idle timers trigger. Used for autocompletion, set to 0 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-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` | | `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` | | `true-color` | Set to `true` to override automatic detection of terminal truecolor 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. | `[]` | | `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` | | `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` | | `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` |
### `[editor.statusline]` Section ### `[editor.statusline]` Section
@ -82,9 +90,9 @@ The `[editor.statusline]` key takes the following sub-keys:
| Key | Description | Default | | Key | Description | Default |
| --- | --- | --- | | --- | --- | --- |
| `left` | A list of elements aligned to the left of the statusline | `["mode", "spinner", "file-name"]` | | `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 | `[]` | | `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", "position", "file-encoding"]` | | `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 | `"│"` | | `separator` | The character used to separate elements in the statusline | `"│"` |
| `mode.normal` | The text shown in the `mode` element for normal mode | `"NOR"` | | `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.insert` | The text shown in the `mode` element for insert mode | `"INS"` |
@ -97,8 +105,11 @@ The following statusline elements can be configured:
| `mode` | The current editor mode (`mode.normal`/`mode.insert`/`mode.select`) | | `mode` | The current editor mode (`mode.normal`/`mode.insert`/`mode.select`) |
| `spinner` | A progress spinner indicating LSP activity | | `spinner` | A progress spinner indicating LSP activity |
| `file-name` | The path/name of the opened file | | `file-name` | The path/name of the opened file |
| `file-base-name` | The basename of the opened file |
| `file-modification-indicator` | The indicator to show whether the file is modified (a `[+]` appears when there are unsaved changes) |
| `file-encoding` | The encoding of the opened file if it differs from UTF-8 | | `file-encoding` | The encoding of the opened file if it differs from UTF-8 |
| `file-line-ending` | The file line endings (CRLF or LF) | | `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 | | `total-line-numbers` | The total line numbers of the opened file |
| `file-type` | The type of the opened file | | `file-type` | The type of the opened file |
| `diagnostics` | The number of warnings and/or errors | | `diagnostics` | The number of warnings and/or errors |
@ -109,23 +120,33 @@ The following statusline elements can be configured:
| `position-percentage` | The cursor position as a percentage of the total number of lines | | `position-percentage` | The cursor position as a percentage of the total number of lines |
| `separator` | The string defined in `editor.statusline.separator` (defaults to `"│"`) | | `separator` | The string defined in `editor.statusline.separator` (defaults to `"│"`) |
| `spacer` | Inserts a space between elements (multiple/contiguous spacers may be specified) | | `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 ### `[editor.lsp]` Section
| Key | Description | Default | | 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` | | `display-messages` | Display LSP progress messages below statusline[^1] | `false` |
| `auto-signature-help` | Enable automatic popup of signature help (parameter hints) | `true` | | `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` | | `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. [^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 ### `[editor.cursor-shape]` Section
Defines the shape of cursor in each mode. Note that due to limitations Defines the shape of cursor in each mode.
of the terminal environment, only the primary cursor can change shape.
Valid values for these options are `block`, `bar`, `underline`, or `hidden`. 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 | | Key | Description | Default |
| --- | ----------- | ------- | | --- | ----------- | ------- |
| `normal` | Cursor shape in [normal mode][normal mode] | `block` | | `normal` | Cursor shape in [normal mode][normal mode] | `block` |
@ -138,23 +159,22 @@ Valid values for these options are `block`, `bar`, `underline`, or `hidden`.
### `[editor.file-picker]` Section ### `[editor.file-picker]` Section
Sets options for file picker and global search. All but the last key listed in Set options for file picker and global search. Ignoring a file means it is
the default file-picker configuration below are IgnoreOptions: whether hidden not visible in the Helix file picker and global search.
files and files listed within ignore files are ignored by (not visible in) the
helix file picker and global search. There is also one other key, `max-depth`
available, which is not defined by default.
All git related options are only enabled in a git repository. All git related options are only enabled in a git repository.
| Key | Description | Default | | Key | Description | Default |
|--|--|---------| |--|--|---------|
|`hidden` | Enables ignoring hidden files. | true |`hidden` | Enables ignoring hidden files | `true`
|`parents` | Enables reading ignore files from parent directories. | true |`follow-symlinks` | Follow symlinks instead of ignoring them | `true`
|`ignore` | Enables reading `.ignore` files. | true |`deduplicate-links` | Ignore symlinks that point at files already shown in the picker | `true`
|`git-ignore` | Enables reading `.gitignore` files. | true |`parents` | Enables reading ignore files from parent directories | `true`
|`git-global` | Enables reading global .gitignore, whose path is specified in git's config: `core.excludefile` option. | true |`ignore` | Enables reading `.ignore` files | `true`
|`git-exclude` | Enables reading `.git/info/exclude` files. | true |`git-ignore` | Enables reading `.gitignore` files | `true`
|`max-depth` | Set with an integer value for maximum depth to recurse. | Defaults to `None`. |`git-global` | Enables reading global `.gitignore`, whose path is specified in git's config: `core.excludefile` option | `true`
|`git-exclude` | Enables reading `.git/info/exclude` files | `true`
|`max-depth` | Set with an integer value for maximum depth to recurse | Defaults to `None`.
### `[editor.auto-pairs]` Section ### `[editor.auto-pairs]` Section
@ -206,7 +226,7 @@ Search specific options.
| Key | Description | Default | | Key | Description | Default |
|--|--|---------| |--|--|---------|
| `smart-case` | Enable smart case regex searching (case insensitive unless pattern contains upper case characters) | `true` | | `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` | | `wrap-around`| Whether the search should wrap after depleting the matches | `true` |
### `[editor.whitespace]` Section ### `[editor.whitespace]` Section
@ -215,7 +235,7 @@ Options for rendering whitespace with visible characters. Use `:set whitespace.r
| Key | Description | Default | | Key | Description | Default |
|-----|-------------|---------| |-----|-------------|---------|
| `render` | Whether to render whitespace. May either be `"all"` or `"none"`, or a table with sub-keys `space`, `tab`, and `newline`. | `"none"` | | `render` | Whether to render whitespace. May either be `"all"` or `"none"`, or a table with sub-keys `space`, `nbsp`, `tab`, and `newline` | `"none"` |
| `characters` | Literal characters to use when rendering whitespace. Sub-keys may be any of `tab`, `space`, `nbsp`, `newline` or `tabpad` | See example below | | `characters` | Literal characters to use when rendering whitespace. Sub-keys may be any of `tab`, `space`, `nbsp`, `newline` or `tabpad` | See example below |
Example Example
@ -243,7 +263,7 @@ Options for rendering vertical indent guides.
| Key | Description | Default | | Key | Description | Default |
| --- | --- | --- | | --- | --- | --- |
| `render` | Whether to render indent guides. | `false` | | `render` | Whether to render indent guides | `false` |
| `character` | Literal character to use for rendering the indent guide | `│` | | `character` | Literal character to use for rendering the indent guide | `│` |
| `skip-levels` | Number of indent levels to skip | `0` | | `skip-levels` | Number of indent levels to skip | `0` |
@ -255,3 +275,85 @@ render = true
character = "╎" # Some characters that work well: "▏", "┆", "┊", "⸽" character = "╎" # Some characters that work well: "▏", "┆", "┊", "⸽"
skip-levels = 1 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
Currently unused
#### `[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
| 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` |

@ -2,9 +2,9 @@
Helix's editing model is strongly inspired from Vim and Kakoune, and a notable Helix's editing model is strongly inspired from Vim and Kakoune, and a notable
difference from Vim (and the most striking similarity to Kakoune) is that Helix difference from Vim (and the most striking similarity to Kakoune) is that Helix
follows the `selection → action` model. This means that the whatever you are follows the `selection → action` model. This means that whatever you are
going to act on (a word, a paragraph, a line, etc) is selected first and the going to act on (a word, a paragraph, a line, etc.) is selected first and the
action itself (delete, change, yank, etc) comes second. A cursor is simply a action itself (delete, change, yank, etc.) comes second. A cursor is simply a
single width selection. single width selection.
See also Kakoune's [Migrating from Vim](https://github.com/mawww/kakoune/wiki/Migrating-from-Vim) and Helix's [Migrating from Vim](https://github.com/helix-editor/helix/wiki/Migrating-from-Vim). See also Kakoune's [Migrating from Vim](https://github.com/mawww/kakoune/wiki/Migrating-from-Vim) and Helix's [Migrating from Vim](https://github.com/helix-editor/helix/wiki/Migrating-from-Vim).

@ -2,70 +2,88 @@
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| astro | ✓ | | | | | astro | ✓ | | | |
| awk | ✓ | ✓ | | `awk-language-server` | | awk | ✓ | ✓ | | `awk-language-server` |
| bash | ✓ | | | `bash-language-server` | | bash | ✓ | | | `bash-language-server` |
| bass | ✓ | | | `bass` | | bass | ✓ | | | `bass` |
| beancount | ✓ | | | | | beancount | ✓ | | | |
| bibtex | ✓ | | | `texlab` | | bibtex | ✓ | | | `texlab` |
| bicep | ✓ | | | `bicep-langserver` | | bicep | ✓ | | | `bicep-langserver` |
| blueprint | ✓ | | | `blueprint-compiler` |
| c | ✓ | ✓ | ✓ | `clangd` | | c | ✓ | ✓ | ✓ | `clangd` |
| c-sharp | ✓ | ✓ | | `OmniSharp` | | c-sharp | ✓ | ✓ | | `OmniSharp` |
| cairo | ✓ | | | | | cabal | | | | |
| cairo | ✓ | ✓ | ✓ | `cairo-language-server` |
| capnp | ✓ | | ✓ | |
| clojure | ✓ | | | `clojure-lsp` | | clojure | ✓ | | | `clojure-lsp` |
| cmake | ✓ | ✓ | ✓ | `cmake-language-server` | | cmake | ✓ | ✓ | ✓ | `cmake-language-server` |
| comment | ✓ | | | | | comment | ✓ | | | |
| common-lisp | ✓ | | | `cl-lsp` | | common-lisp | ✓ | | | `cl-lsp` |
| cpon | ✓ | | ✓ | | | cpon | ✓ | | ✓ | |
| cpp | ✓ | ✓ | ✓ | `clangd` | | cpp | ✓ | ✓ | ✓ | `clangd` |
| crystal | ✓ | ✓ | | `crystalline` |
| css | ✓ | | | `vscode-css-language-server` | | css | ✓ | | | `vscode-css-language-server` |
| cue | ✓ | | | `cuelsp` | | cue | ✓ | | | `cuelsp` |
| d | ✓ | ✓ | ✓ | `serve-d` | | d | ✓ | ✓ | ✓ | `serve-d` |
| dart | ✓ | | ✓ | `dart` | | dart | ✓ | | ✓ | `dart` |
| dbml | ✓ | | | |
| devicetree | ✓ | | | | | devicetree | ✓ | | | |
| dhall | ✓ | ✓ | | `dhall-lsp-server` |
| diff | ✓ | | | | | diff | ✓ | | | |
| dockerfile | ✓ | | | `docker-langserver` | | dockerfile | ✓ | | | `docker-langserver` |
| dot | ✓ | | | `dot-language-server` | | dot | ✓ | | | `dot-language-server` |
| dtd | ✓ | | | |
| edoc | ✓ | | | | | edoc | ✓ | | | |
| eex | ✓ | | | | | eex | ✓ | | | |
| ejs | ✓ | | | | | ejs | ✓ | | | |
| elixir | ✓ | ✓ | ✓ | `elixir-ls` | | elixir | ✓ | ✓ | ✓ | `elixir-ls` |
| elm | ✓ | | | `elm-language-server` | | elm | ✓ | | | `elm-language-server` |
| elvish | ✓ | | | `elvish` | | elvish | ✓ | | | `elvish` |
| env | ✓ | | | | | env | ✓ | | | |
| erb | ✓ | | | | | erb | ✓ | | | |
| erlang | ✓ | ✓ | | `erlang_ls` | | erlang | ✓ | ✓ | | `erlang_ls` |
| esdl | ✓ | | | | | esdl | ✓ | | | |
| fish | ✓ | ✓ | ✓ | | | fish | ✓ | ✓ | ✓ | |
| forth | ✓ | | | `forth-lsp` |
| fortran | ✓ | | ✓ | `fortls` | | fortran | ✓ | | ✓ | `fortls` |
| gdscript | ✓ | ✓ | | | | fsharp | ✓ | | | `fsautocomplete` |
| gas | ✓ | ✓ | | |
| gdscript | ✓ | ✓ | ✓ | |
| gemini | ✓ | | | |
| git-attributes | ✓ | | | | | git-attributes | ✓ | | | |
| git-commit | ✓ | | | | | git-commit | ✓ | | | |
| git-config | ✓ | | | | | git-config | ✓ | | | |
| git-ignore | ✓ | | | | | git-ignore | ✓ | | | |
| git-rebase | ✓ | | | | | git-rebase | ✓ | | | |
| gleam | ✓ | ✓ | | `gleam` | | gleam | ✓ | ✓ | | `gleam` |
| glsl | ✓ | ✓ | ✓ | | | glsl | ✓ | ✓ | ✓ | |
| go | ✓ | ✓ | ✓ | `gopls` | | gn | ✓ | | | |
| go | ✓ | ✓ | ✓ | `gopls`, `golangci-lint-langserver` |
| godot-resource | ✓ | | | | | godot-resource | ✓ | | | |
| gomod | ✓ | | | `gopls` | | gomod | ✓ | | | `gopls` |
| gotmpl | ✓ | | | `gopls` | | gotmpl | ✓ | | | `gopls` |
| gowork | ✓ | | | `gopls` | | gowork | ✓ | | | `gopls` |
| graphql | ✓ | | | | | graphql | ✓ | | | `graphql-lsp` |
| hare | ✓ | | | | | hare | ✓ | | | |
| haskell | ✓ | | | `haskell-language-server-wrapper` | | haskell | ✓ | ✓ | | `haskell-language-server-wrapper` |
| haskell-persistent | ✓ | | | |
| hcl | ✓ | | ✓ | `terraform-ls` | | hcl | ✓ | | ✓ | `terraform-ls` |
| heex | ✓ | ✓ | | `elixir-ls` | | heex | ✓ | ✓ | | `elixir-ls` |
| hosts | ✓ | | | |
| html | ✓ | | | `vscode-html-language-server` | | html | ✓ | | | `vscode-html-language-server` |
| hurl | ✓ | | ✓ | |
| idris | | | | `idris2-lsp` | | idris | | | | `idris2-lsp` |
| iex | ✓ | | | | | iex | ✓ | | | |
| ini | ✓ | | | | | ini | ✓ | | | |
| java | ✓ | ✓ | | `jdtls` | | java | ✓ | ✓ | | `jdtls` |
| javascript | ✓ | ✓ | ✓ | `typescript-language-server` | | javascript | ✓ | ✓ | ✓ | `typescript-language-server` |
| jinja | ✓ | | | |
| jsdoc | ✓ | | | | | jsdoc | ✓ | | | |
| json | ✓ | | ✓ | `vscode-json-language-server` | | json | ✓ | | ✓ | `vscode-json-language-server` |
| json5 | ✓ | | | |
| jsonnet | ✓ | | | `jsonnet-language-server` | | jsonnet | ✓ | | | `jsonnet-language-server` |
| jsx | ✓ | ✓ | ✓ | `typescript-language-server` | | jsx | ✓ | ✓ | ✓ | `typescript-language-server` |
| julia | ✓ | | | `julia` | | julia | ✓ | ✓ | ✓ | `julia` |
| kdl | ✓ | | | | | just | ✓ | ✓ | ✓ | |
| kdl | ✓ | ✓ | ✓ | |
| kotlin | ✓ | | | `kotlin-language-server` | | kotlin | ✓ | | | `kotlin-language-server` |
| latex | ✓ | ✓ | | `texlab` | | latex | ✓ | ✓ | | `texlab` |
| lean | ✓ | | | `lean` | | lean | ✓ | | | `lean` |
@ -73,67 +91,99 @@
| llvm | ✓ | ✓ | ✓ | | | llvm | ✓ | ✓ | ✓ | |
| llvm-mir | ✓ | ✓ | ✓ | | | llvm-mir | ✓ | ✓ | ✓ | |
| llvm-mir-yaml | ✓ | | ✓ | | | llvm-mir-yaml | ✓ | | ✓ | |
| lpf | ✓ | | | |
| lua | ✓ | ✓ | ✓ | `lua-language-server` | | lua | ✓ | ✓ | ✓ | `lua-language-server` |
| make | ✓ | | | | | make | ✓ | | | |
| markdoc | ✓ | | | `markdoc-ls` |
| markdown | ✓ | | | `marksman` | | markdown | ✓ | | | `marksman` |
| markdown.inline | ✓ | | | | | markdown.inline | ✓ | | | |
| matlab | ✓ | ✓ | ✓ | |
| mermaid | ✓ | | | |
| meson | ✓ | | ✓ | | | meson | ✓ | | ✓ | |
| mint | | | | `mint` | | mint | | | | `mint` |
| msbuild | ✓ | | ✓ | |
| nasm | ✓ | ✓ | | |
| nickel | ✓ | | ✓ | `nls` | | nickel | ✓ | | ✓ | `nls` |
| nim | ✓ | ✓ | ✓ | `nimlangserver` |
| nix | ✓ | | | `nil` | | nix | ✓ | | | `nil` |
| nu | ✓ | | | | | nu | ✓ | | | `nu` |
| nunjucks | ✓ | | | |
| ocaml | ✓ | | ✓ | `ocamllsp` | | ocaml | ✓ | | ✓ | `ocamllsp` |
| ocaml-interface | ✓ | | | `ocamllsp` | | ocaml-interface | ✓ | | | `ocamllsp` |
| odin | ✓ | | | `ols` | | odin | ✓ | | ✓ | `ols` |
| opencl | ✓ | ✓ | ✓ | `clangd` |
| openscad | ✓ | | | `openscad-lsp` | | openscad | ✓ | | | `openscad-lsp` |
| org | ✓ | | | | | org | ✓ | | | |
| pascal | ✓ | ✓ | | `pasls` | | pascal | ✓ | ✓ | | `pasls` |
| perl | ✓ | ✓ | ✓ | | | passwd | ✓ | | | |
| pem | ✓ | | | |
| perl | ✓ | ✓ | ✓ | `perlnavigator` |
| php | ✓ | ✓ | ✓ | `intelephense` | | php | ✓ | ✓ | ✓ | `intelephense` |
| po | ✓ | ✓ | | |
| pod | ✓ | | | |
| ponylang | ✓ | ✓ | ✓ | |
| prisma | ✓ | | | `prisma-language-server` | | prisma | ✓ | | | `prisma-language-server` |
| prolog | | | | `swipl` | | prolog | | | | `swipl` |
| protobuf | ✓ | | ✓ | | | protobuf | ✓ | | ✓ | `bufls`, `pb` |
| purescript | ✓ | | | `purescript-language-server` | | prql | ✓ | | | |
| purescript | ✓ | ✓ | | `purescript-language-server` |
| python | ✓ | ✓ | ✓ | `pylsp` | | python | ✓ | ✓ | ✓ | `pylsp` |
| qml | ✓ | | ✓ | `qmlls` | | qml | ✓ | | ✓ | `qmlls` |
| r | ✓ | | | `R` | | r | ✓ | | | `R` |
| racket | ✓ | | | `racket` | | racket | ✓ | | | `racket` |
| regex | ✓ | | | | | regex | ✓ | | | |
| rego | ✓ | | | `regols` |
| rescript | ✓ | ✓ | | `rescript-language-server` | | rescript | ✓ | ✓ | | `rescript-language-server` |
| rmarkdown | ✓ | | ✓ | `R` | | rmarkdown | ✓ | | ✓ | `R` |
| robot | ✓ | | | `robotframework_ls` |
| ron | ✓ | | ✓ | | | ron | ✓ | | ✓ | |
| rst | ✓ | | | |
| ruby | ✓ | ✓ | ✓ | `solargraph` | | ruby | ✓ | ✓ | ✓ | `solargraph` |
| rust | ✓ | ✓ | ✓ | `rust-analyzer` | | rust | ✓ | ✓ | ✓ | `rust-analyzer` |
| sage | ✓ | ✓ | | |
| scala | ✓ | | ✓ | `metals` | | scala | ✓ | | ✓ | `metals` |
| scheme | ✓ | | | | | scheme | ✓ | | | |
| scss | ✓ | | | `vscode-css-language-server` | | scss | ✓ | | | `vscode-css-language-server` |
| slint | ✓ | | ✓ | `slint-lsp` | | slint | ✓ | | ✓ | `slint-lsp` |
| smithy | ✓ | | | `cs` |
| sml | ✓ | | | | | sml | ✓ | | | |
| solidity | ✓ | | | `solc` | | solidity | ✓ | | | `solc` |
| sql | ✓ | | | | | sql | ✓ | | | |
| sshclientconfig | ✓ | | | | | sshclientconfig | ✓ | | | |
| starlark | ✓ | ✓ | | | | starlark | ✓ | ✓ | | |
| svelte | ✓ | | | `svelteserver` | | strace | ✓ | | | |
| svelte | ✓ | | ✓ | `svelteserver` |
| sway | ✓ | ✓ | ✓ | `forc` |
| swift | ✓ | | | `sourcekit-lsp` | | swift | ✓ | | | `sourcekit-lsp` |
| t32 | ✓ | | | |
| tablegen | ✓ | ✓ | ✓ | | | tablegen | ✓ | ✓ | ✓ | |
| task | ✓ | | | | | task | ✓ | | | |
| tfvars | | | | `terraform-ls` | | templ | ✓ | | | `templ` |
| tfvars | ✓ | | ✓ | `terraform-ls` |
| todotxt | ✓ | | | |
| toml | ✓ | | | `taplo` | | toml | ✓ | | | `taplo` |
| tsq | ✓ | | | | | tsq | ✓ | | | |
| tsx | ✓ | ✓ | ✓ | `typescript-language-server` | | tsx | ✓ | ✓ | ✓ | `typescript-language-server` |
| twig | ✓ | | | | | twig | ✓ | | | |
| typescript | ✓ | ✓ | ✓ | `typescript-language-server` | | typescript | ✓ | ✓ | ✓ | `typescript-language-server` |
| typst | ✓ | | | `typst-lsp` |
| ungrammar | ✓ | | | | | ungrammar | ✓ | | | |
| v | ✓ | | | `vls` | | unison | ✓ | | | |
| uxntal | ✓ | | | |
| v | ✓ | ✓ | ✓ | `v-analyzer` |
| vala | ✓ | | | `vala-language-server` | | vala | ✓ | | | `vala-language-server` |
| verilog | ✓ | ✓ | | `svlangserver` | | verilog | ✓ | ✓ | | `svlangserver` |
| vhdl | ✓ | | | `vhdl_ls` |
| vhs | ✓ | | | | | vhs | ✓ | | | |
| vue | ✓ | | | `vls` | | vue | ✓ | | | `vue-language-server` |
| wast | ✓ | | | | | wast | ✓ | | | |
| wat | ✓ | | | | | wat | ✓ | | | |
| webc | ✓ | | | |
| wgsl | ✓ | | | `wgsl_analyzer` | | wgsl | ✓ | | | `wgsl_analyzer` |
| wit | ✓ | | ✓ | | | wit | ✓ | | ✓ | |
| wren | ✓ | ✓ | ✓ | |
| xit | ✓ | | | | | xit | ✓ | | | |
| xml | ✓ | | ✓ | | | xml | ✓ | | ✓ | |
| yaml | ✓ | | ✓ | `yaml-language-server` | | yaml | ✓ | | ✓ | `yaml-language-server`, `ansible-language-server` |
| yuck | ✓ | | | |
| zig | ✓ | ✓ | ✓ | `zls` | | zig | ✓ | ✓ | ✓ | `zls` |

@ -12,7 +12,9 @@
| `:buffer-next`, `:bn`, `:bnext` | Goto next buffer. | | `:buffer-next`, `:bn`, `:bnext` | Goto next buffer. |
| `:buffer-previous`, `:bp`, `:bprev` | Goto previous buffer. | | `:buffer-previous`, `:bp`, `:bprev` | Goto previous buffer. |
| `:write`, `:w` | Write changes to disk. Accepts an optional path (:write some/path.txt) | | `:write`, `:w` | Write changes to disk. Accepts an optional path (:write some/path.txt) |
| `:write!`, `:w!` | Force write changes to disk creating necessary subdirectories. Accepts an optional path (:write some/path.txt) | | `:write!`, `:w!` | Force write changes to disk creating necessary subdirectories. Accepts an optional path (:write! some/path.txt) |
| `:write-buffer-close`, `:wbc` | Write changes to disk and closes the buffer. Accepts an optional path (:write-buffer-close some/path.txt) |
| `:write-buffer-close!`, `:wbc!` | Force write changes to disk creating necessary subdirectories and closes the buffer. Accepts an optional path (:write-buffer-close! some/path.txt) |
| `:new`, `:n` | Create a new scratch buffer. | | `:new`, `:n` | Create a new scratch buffer. |
| `:format`, `:fmt` | Format the file using the LSP formatter. | | `:format`, `:fmt` | Format the file using the LSP formatter. |
| `:indent-style` | Set the indentation style for editing. ('t' for tabs or 1-8 for number of spaces.) | | `:indent-style` | Set the indentation style for editing. ('t' for tabs or 1-8 for number of spaces.) |
@ -22,6 +24,7 @@
| `:write-quit`, `:wq`, `:x` | Write changes to disk and close the current view. Accepts an optional path (:wq some/path.txt) | | `:write-quit`, `:wq`, `:x` | Write changes to disk and close the current view. Accepts an optional path (:wq some/path.txt) |
| `:write-quit!`, `:wq!`, `:x!` | Write changes to disk and close the current view forcefully. Accepts an optional path (:wq! some/path.txt) | | `:write-quit!`, `:wq!`, `:x!` | Write changes to disk and close the current view forcefully. Accepts an optional path (:wq! some/path.txt) |
| `:write-all`, `:wa` | Write changes from all buffers to disk. | | `:write-all`, `:wa` | Write changes from all buffers to disk. |
| `:write-all!`, `:wa!` | Forcefully write changes from all buffers to disk creating necessary subdirectories. |
| `:write-quit-all`, `:wqa`, `:xa` | Write changes from all buffers to disk and close all views. | | `:write-quit-all`, `:wqa`, `:xa` | Write changes from all buffers to disk and close all views. |
| `:write-quit-all!`, `:wqa!`, `:xa!` | Write changes from all buffers to disk and close all views forcefully (ignoring unsaved changes). | | `:write-quit-all!`, `:wqa!`, `:xa!` | Write changes from all buffers to disk and close all views forcefully (ignoring unsaved changes). |
| `:quit-all`, `:qa` | Close all views. | | `:quit-all`, `:qa` | Close all views. |
@ -29,6 +32,7 @@
| `:cquit`, `:cq` | Quit with exit code (default 1). Accepts an optional integer exit code (:cq 2). | | `:cquit`, `:cq` | Quit with exit code (default 1). Accepts an optional integer exit code (:cq 2). |
| `:cquit!`, `:cq!` | Force quit with exit code (default 1) ignoring unsaved changes. Accepts an optional integer exit code (:cq! 2). | | `:cquit!`, `:cq!` | Force quit with exit code (default 1) ignoring unsaved changes. Accepts an optional integer exit code (:cq! 2). |
| `:theme` | Change the editor theme (show current theme if no name specified). | | `:theme` | Change the editor theme (show current theme if no name specified). |
| `:yank-join` | Yank joined selections. A separator can be provided as first argument. Default value is newline. |
| `:clipboard-yank` | Yank main selection into system clipboard. | | `:clipboard-yank` | Yank main selection into system clipboard. |
| `:clipboard-yank-join` | Yank joined selections into system clipboard. A separator can be provided as first argument. Default value is newline. | | `:clipboard-yank-join` | Yank joined selections into system clipboard. A separator can be provided as first argument. Default value is newline. |
| `:primary-clipboard-yank` | Yank main selection into system primary clipboard. | | `:primary-clipboard-yank` | Yank main selection into system primary clipboard. |
@ -43,12 +47,15 @@
| `:change-current-directory`, `:cd` | Change the current working directory. | | `:change-current-directory`, `:cd` | Change the current working directory. |
| `:show-directory`, `:pwd` | Show the current working directory. | | `:show-directory`, `:pwd` | Show the current working directory. |
| `:encoding` | Set encoding. Based on `https://encoding.spec.whatwg.org`. | | `:encoding` | Set encoding. Based on `https://encoding.spec.whatwg.org`. |
| `:reload` | Discard changes and reload from the source file. | | `:character-info`, `:char` | Get info about the character under the primary cursor. |
| `:reload-all` | Discard changes and reload all documents from the source files. | | `:reload`, `:rl` | Discard changes and reload from the source file. |
| `:update` | Write changes only if the file has been modified. | | `:reload-all`, `:rla` | Discard changes and reload all documents from the source files. |
| `:update`, `:u` | Write changes only if the file has been modified. |
| `:lsp-workspace-command` | Open workspace command picker | | `:lsp-workspace-command` | Open workspace command picker |
| `:lsp-restart` | Restarts the Language Server that is in use by the current doc | | `:lsp-restart` | Restarts the language servers used by the current doc |
| `:lsp-stop` | Stops the language servers that are used by the current doc |
| `:tree-sitter-scopes` | Display tree sitter scopes, primarily for theming and development. | | `:tree-sitter-scopes` | Display tree sitter scopes, primarily for theming and development. |
| `:tree-sitter-highlight-name` | Display name of tree-sitter highlight scope under the cursor. |
| `:debug-start`, `:dbg` | Start a debug session from a given template with given parameters. | | `:debug-start`, `:dbg` | Start a debug session from a given template with given parameters. |
| `:debug-remote`, `:dbg-tcp` | Connect to a debug adapter by TCP address and start a debugging session from a given template with given parameters. | | `:debug-remote`, `:dbg-tcp` | Connect to a debug adapter by TCP address and start a debugging session from a given template with given parameters. |
| `:debug-eval` | Evaluate expression in current debug context. | | `:debug-eval` | Evaluate expression in current debug context. |
@ -58,8 +65,9 @@
| `:hsplit-new`, `:hnew` | Open a scratch buffer in a horizontal split. | | `:hsplit-new`, `:hnew` | Open a scratch buffer in a horizontal split. |
| `:tutor` | Open the tutorial. | | `:tutor` | Open the tutorial. |
| `:goto`, `:g` | Goto line number. | | `:goto`, `:g` | Goto line number. |
| `:set-language`, `:lang` | Set the language of current buffer. | | `:set-language`, `:lang` | Set the language of current buffer (show current language if no value specified). |
| `:set-option`, `:set` | Set a config option at runtime.<br>For example to disable smart case search, use `:set search.smart-case false`. | | `:set-option`, `:set` | Set a config option at runtime.<br>For example to disable smart case search, use `:set search.smart-case false`. |
| `:toggle-option`, `:toggle` | Toggle a boolean config option at runtime.<br>For example to toggle smart case search, use `:toggle search.smart-case`. |
| `:get-option`, `:get` | Get the current value of a config option. | | `:get-option`, `:get` | Get the current value of a config option. |
| `:sort` | Sort ranges in selection. | | `:sort` | Sort ranges in selection. |
| `:rsort` | Sort ranges in selection in reverse order. | | `:rsort` | Sort ranges in selection in reverse order. |
@ -67,8 +75,14 @@
| `:tree-sitter-subtree`, `:ts-subtree` | Display tree sitter subtree under cursor, primarily for debugging queries. | | `:tree-sitter-subtree`, `:ts-subtree` | Display tree sitter subtree under cursor, primarily for debugging queries. |
| `:config-reload` | Refresh user config. | | `:config-reload` | Refresh user config. |
| `:config-open` | Open the user config.toml file. | | `:config-open` | Open the user config.toml file. |
| `:config-open-workspace` | Open the workspace config.toml file. |
| `:log-open` | Open the helix log file. | | `:log-open` | Open the helix log file. |
| `:insert-output` | Run shell command, inserting output before each selection. | | `:insert-output` | Run shell command, inserting output before each selection. |
| `:append-output` | Run shell command, appending output after each selection. | | `:append-output` | Run shell command, appending output after each selection. |
| `:pipe` | Pipe each selection to the shell command. | | `:pipe` | Pipe each selection to the shell command. |
| `:pipe-to` | Pipe each selection to the shell command, ignoring output. |
| `:run-shell-command`, `:sh` | Run a shell command | | `:run-shell-command`, `:sh` | Run a shell command |
| `:reset-diff-change`, `:diffget`, `:diffg` | Reset the diff change at the cursor position. |
| `:clear-register` | Clear given register. If no argument is provided, clear all registers. |
| `:redraw` | Clear and re-render the whole UI |
| `:move` | Move the current buffer and its corresponding file to a different path |

@ -1,4 +1,4 @@
# Guides # Guides
This section contains guides for adding new language server configurations, This section contains guides for adding new language server configurations,
tree-sitter grammars, textobject queries, etc. tree-sitter grammars, textobject queries, and other similar items.

@ -1,45 +1,53 @@
# Adding languages # Adding new languages to Helix
In order to add a new language to Helix, you will need to follow the steps
below.
## Language configuration ## Language configuration
To add a new language, you need to add a `[[language]]` entry to the 1. Add a new `[[language]]` entry in the `languages.toml` file and provide the
`languages.toml` (see the [language configuration section]). necessary configuration for the new language. For more information on
language configuration, refer to the
[language configuration section](../languages.md) of the documentation.
A new language server can be added by extending the `[language-server]` table in the same file.
2. If you are adding a new language or updating an existing language server
configuration, run the command `cargo xtask docgen` to update the
[Language Support](../lang-support.md) documentation.
When adding a new language or Language Server configuration for an existing > 💡 If you are adding a new Language Server configuration, make sure to update
language, run `cargo xtask docgen` to add the new configuration to the > the
[Language Support][lang-support] docs before creating a pull request. > [Language Server Wiki](https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers)
When adding a Language Server configuration, be sure to update the > with the installation instructions.
[Language Server Wiki][install-lsp-wiki] with installation notes.
## Grammar configuration ## Grammar configuration
If a tree-sitter grammar is available for the language, add a new `[[grammar]]` 1. If a tree-sitter grammar is available for the new language, add a new
entry to `languages.toml`. `[[grammar]]` entry to the `languages.toml` file.
2. If you are testing the grammar locally, you can use the `source.path` key
You may use the `source.path` key rather than `source.git` with an absolute path with an absolute path to the grammar. However, before submitting a pull
to a locally available grammar for testing, but switch to `source.git` before request, make sure to switch to using `source.git`.
submitting a pull request.
## Queries ## Queries
For a language to have syntax-highlighting and indentation among 1. In order to provide syntax highlighting and indentation for the new language,
other things, you have to add queries. Add a directory for your you will need to add queries.
language with the path `runtime/queries/<name>/`. The tree-sitter 2. Create a new directory for the language with the path
[website](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#queries) `runtime/queries/<name>/`.
gives more info on how to write queries. 3. Refer to the
[tree-sitter website](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#queries)
> NOTE: When evaluating queries, the first matching query takes for more information on writing queries.
precedence, which is different from other editors like Neovim where
the last matching query supersedes the ones before it. See > 💡 In Helix, the first matching query takes precedence when evaluating
[this issue][neovim-query-precedence] for an example. > queries, which is different from other editors such as Neovim where the last
> matching query supersedes the ones before it. See
## Common Issues > [this issue](https://github.com/helix-editor/helix/pull/1170#issuecomment-997294090)
> for an example.
- If you get errors when running after switching branches, you may have to update the tree-sitter grammars. Run `hx --grammar fetch` to fetch the grammars and `hx --grammar build` to build any out-of-date grammars.
## Common issues
- If a parser is segfaulting or you want to remove the parser, make sure to remove the compiled parser in `runtime/grammar/<name>.so`
- If you encounter errors when running Helix after switching branches, you may
[language configuration section]: ../languages.md need to update the tree-sitter grammars. Run the command `hx --grammar fetch`
[neovim-query-precedence]: https://github.com/helix-editor/helix/pull/1170#issuecomment-997294090 to fetch the grammars and `hx --grammar build` to build any out-of-date
[install-lsp-wiki]: https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers grammars.
[lang-support]: ../lang-support.md - If a parser is causing a segfault, or you want to remove it, make sure to
remove the compiled parser located at `runtime/grammars/<name>.so`.

@ -1,76 +1,299 @@
# Adding Indent Queries # Adding indent queries
Helix uses tree-sitter to correctly indent new lines. This requires Helix uses tree-sitter to correctly indent new lines. This requires a tree-
a tree-sitter grammar and an `indent.scm` query file placed in sitter grammar and an `indent.scm` query file placed in `runtime/queries/
`runtime/queries/{language}/indents.scm`. The indentation for a line {language}/indents.scm`. The indentation for a line is calculated by traversing
is calculated by traversing the syntax tree from the lowest node at the the syntax tree from the lowest node at the beginning of the new line (see
beginning of the new line. Each of these nodes contributes to the total [Indent queries](#indent-queries)). Each of these nodes contributes to the total
indent when it is captured by the query (in what way depends on the name indent when it is captured by the query (in what way depends on the name of
of the capture). the capture.
Note that it matters where these added indents begin. For example, Note that it matters where these added indents begin. For example,
multiple indent level increases that start on the same line only increase multiple indent level increases that start on the same line only increase
the total indent level by 1. the total indent level by 1. See [Capture types](#capture-types).
## Scopes ## Indent queries
Added indents don't always apply to the whole node. For example, in most When Helix is inserting a new line through `o`, `O`, or `<ret>`, to determine
cases when a node should be indented, we actually only want everything the indent level for the new line, the query in `indents.scm` is run on the
except for its first line to be indented. For this, there are several document. The starting position of the query is the end of the line above where
scopes (more scopes may be added in the future if required): a new line will be inserted.
- `all`: For `o`, the inserted line is the line below the cursor, so that starting
This scope applies to the whole captured node. This is only different from position of the query is the end of the current line.
`tail` when the captured node is the first node on its line.
- `tail`: ```rust
This scope applies to everything except for the first line of the fn need_hero(some_hero: Hero, life: Life) -> {
captured node. matches!(some_hero, Hero { // ←─────────────────╮
strong: true,//←╮ ↑ ↑ │
fast: true, // │ │ ╰── query start │
sure: true, // │ ╰───── cursor ├─ traversal
soon: true, // ╰──────── new line inserted │ start node
}) && // │
// ↑ │
// ╰───────────────────────────────────────────────╯
some_hero > life
}
```
Every capture type has a default scope which should do the right thing For `O`, the newly inserted line is the *current* line, so the starting position
in most situations. When a different scope is required, this can be of the query is the end of the line above the cursor.
changed by using a `#set!` declaration anywhere in the pattern:
```scm ```rust
(assignment_expression fn need_hero(some_hero: Hero, life: Life) -> { // ←─╮
right: (_) @indent matches!(some_hero, Hero { // ←╮ ↑ │
(#set! "scope" "all")) strong: true,// ↑ ╭───╯ │ │
fast: true, // │ │ query start ─╯ │
sure: true, // ╰───┼ cursor ├─ traversal
soon: true, // ╰ new line inserted │ start node
}) && // │
some_hero > life // │
} // ←──────────────────────────────────────────────╯
``` ```
## Capture Types From this starting node, the syntax tree is traversed up until the root node.
Each indent capture is collected along the way, and then combined according to
their [capture types](#capture-types) and [scopes](#scopes) to a final indent
level for the line.
- `@indent` (default scope `tail`): ### Capture types
Increase the indent level by 1. Multiple occurrences in the same line
don't stack. If there is at least one `@indent` and one `@outdent`
capture on the same line, the indent level isn't changed at all.
- `@indent` (default scope `tail`):
Increase the indent level by 1. Multiple occurrences in the same line *do not*
stack. If there is at least one `@indent` and one `@outdent` capture on the
same line, the indent level isn't changed at all.
- `@outdent` (default scope `all`): - `@outdent` (default scope `all`):
Decrease the indent level by 1. The same rules as for `@indent` apply. Decrease the indent level by 1. The same rules as for `@indent` apply.
- `@indent.always` (default scope `tail`):
Increase the indent level by 1. Multiple occurrences on the same line *do*
stack. The final indent level is `@indent.always` `@outdent.always`. If
an `@indent` and an `@indent.always` are on the same line, the `@indent` is
ignored.
- `@outdent.always` (default scope `all`):
Decrease the indent level by 1. The same rules as for `@indent.always` apply.
- `@align` (default scope `all`):
Align everything inside this node to some anchor. The anchor is given
by the start of the node captured by `@anchor` in the same pattern.
Every pattern with an `@align` should contain exactly one `@anchor`.
Indent (and outdent) for nodes below (in terms of their starting line)
the `@align` node is added to the indentation required for alignment.
- `@extend`: - `@extend`:
Extend the range of this node to the end of the line and to lines that Extend the range of this node to the end of the line and to lines that are
are indented more than the line that this node starts on. This is useful indented more than the line that this node starts on. This is useful for
for languages like Python, where for the purpose of indentation some nodes languages like Python, where for the purpose of indentation some nodes (like
(like functions or classes) should also contain indented lines that follow them. functions or classes) should also contain indented lines that follow them.
- `@extend.prevent-once`: - `@extend.prevent-once`:
Prevents the first extension of an ancestor of this node. For example, in Python Prevents the first extension of an ancestor of this node. For example, in Python
a return expression always ends the block that it is in. Note that this only stops the a return expression always ends the block that it is in. Note that this only
extension of the next `@extend` capture. If multiple ancestors are captured, stops the extension of the next `@extend` capture. If multiple ancestors are
only the extension of the innermost one is prevented. All other ancestors are unaffected captured, only the extension of the innermost one is prevented. All other
(regardless of whether the innermost ancestor would actually have been extended). ancestors are unaffected (regardless of whether the innermost ancestor would
actually have been extended).
#### `@indent` / `@outdent`
Consider this example:
```rust
fn shout(things: Vec<Thing>) {
// ↑
// ├───────────────────────╮ indent level
// @indent ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄
// │
let it_all = |out| { things.filter(|thing| { // │ 1
// ↑ ↑ │
// ├───────────────────────┼─────┼┄┄┄┄┄┄┄┄┄┄┄┄┄┄
// @indent @indent
// │ 2
thing.can_do_with(out) // │
})}; // ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄
//↑↑↑ │ 1
} //╰┼┴──────────────────────────────────────────────┴┄┄┄┄┄┄┄┄┄┄┄┄┄┄
// 3x @outdent
```
```scm
((block) @indent)
["}" ")"] @outdent
```
Note how on the second line, we have two blocks begin on the same line. In this
case, since both captures occur on the same line, they are combined and only
result in a net increase of 1. Also note that the closing `}`s are part of the
`@indent` captures, but the 3 `@outdent`s also combine into 1 and result in that
line losing one indent level.
#### `@extend` / `@extend.prevent-once`
For an example of where `@extend` can be useful, consider Python, which is
whitespace-sensitive.
```scm
]
(parenthesized_expression)
(function_definition)
(class_definition)
] @indent
```
```python
class Hero:
def __init__(self, strong, fast, sure, soon):# ←─╮
self.is_strong = strong # │
self.is_fast = fast # ╭─── query start │
self.is_sure = sure # │ ╭─ cursor │
self.is_soon = soon # │ │ │
# ↑ ↑ │ │ │
# │ ╰──────╯ │ │
# ╰─────────────────────╯ │
# ├─ traversal
def need_hero(self, life): # │ start node
return ( # │
self.is_strong # │
and self.is_fast # │
and self.is_sure # │
and self.is_soon # │
and self > life # │
) # ←─────────────────────────────────────────╯
```
Without braces to catch the scope of the function, the smallest descendant of
the cursor on a line feed ends up being the entire inside of the class. Because
of this, it will miss the entire function node and its indent capture, leading
to an indent level one too small.
To address this case, `@extend` tells helix to "extend" the captured node's span
to the line feed and every consecutive line that has a greater indent level than
the line of the node.
```scm
(parenthesized_expression) @indent
]
(function_definition)
(class_definition)
] @indent @extend
```
```python
class Hero:
def __init__(self, strong, fast, sure, soon):# ←─╮
self.is_strong = strong # │
self.is_fast = fast # ╭─── query start ├─ traversal
self.is_sure = sure # │ ╭─ cursor │ start node
self.is_soon = soon # │ │ ←───────────────╯
# ↑ ↑ │ │
# │ ╰──────╯ │
# ╰─────────────────────╯
def need_hero(self, life):
return (
self.is_strong
and self.is_fast
and self.is_sure
and self.is_soon
and self > life
)
```
Furthermore, there are some cases where extending to everything with a greater
indent level may not be desirable. Consider the `need_hero` function above. If
our cursor is on the last line of the returned expression.
```python
class Hero:
def __init__(self, strong, fast, sure, soon):
self.is_strong = strong
self.is_fast = fast
self.is_sure = sure
self.is_soon = soon
def need_hero(self, life):
return (
self.is_strong
and self.is_fast
and self.is_sure
and self.is_soon
and self > life
) # ←─── cursor
#←────────── where cursor should go on new line
```
In Python, the are a few tokens that will always end a scope, such as a return
statement. Since the scope ends, so should the indent level. But because the
function span is extended to every line with a greater indent level, a new line
would just continue on the same level. And an `@outdent` would not help us here
either, since it would cause everything in the parentheses to become outdented
as well.
To help, we need to signal an end to the extension. We can do this with
`@extend.prevent-once`.
```scm
(parenthesized_expression) @indent
]
(function_definition)
(class_definition)
] @indent @extend
(return_statement) @extend.prevent-once
```
#### `@indent.always` / `@outdent.always`
As mentioned before, normally if there is more than one `@indent` or `@outdent`
capture on the same line, they are combined.
Sometimes, there are cases when you may want to ensure that every indent capture
is additive, regardless of how many occur on the same line. Consider this
example in YAML.
```yaml
- foo: bar
# ↑ ↑
# │ ╰─────────────── start of map
# ╰───────────────── start of list element
baz: quux # ←─── cursor
# ←───────────── where the cursor should go on a new line
garply: waldo
- quux:
bar: baz
xyzzy: thud
fred: plugh
```
In YAML, you often have lists of maps. In these cases, the syntax is such that
the list element and the map both start on the same line. But we really do want
to start an indentation for each of these so that subsequent keys in the map
hang over the list and align properly. This is where `@indent.always` helps.
```scm
((block_sequence_item) @item @indent.always @extend
(#not-one-line? @item))
((block_mapping_pair
key: (_) @key
value: (_) @val
(#not-same-line? @key @val)
) @indent.always @extend
)
```
## Predicates ## Predicates
In some cases, an S-expression cannot express exactly what pattern should be matched. In some cases, an S-expression cannot express exactly what pattern should be matched.
For that, tree-sitter allows for predicates to appear anywhere within a pattern, For that, tree-sitter allows for predicates to appear anywhere within a pattern,
similar to how `#set!` declarations work: similar to how `#set!` declarations work:
```scm ```scm
(some_kind (some_kind
(child_kind) @indent (child_kind) @indent
(#predicate? arg1 arg2 ...) (#predicate? arg1 arg2 ...)
) )
``` ```
The number of arguments depends on the predicate that's used. The number of arguments depends on the predicate that's used.
Each argument is either a capture (`@name`) or a string (`"some string"`). Each argument is either a capture (`@name`) or a string (`"some string"`).
The following predicates are supported by tree-sitter: The following predicates are supported by tree-sitter:
@ -91,3 +314,47 @@ argument (a string).
- `#same-line?`/`#not-same-line?`: - `#same-line?`/`#not-same-line?`:
The captures given by the 2 arguments must/must not start on the same line. The captures given by the 2 arguments must/must not start on the same line.
- `#one-line?`/`#not-one-line?`:
The captures given by the fist argument must/must span a total of one line.
### Scopes
Added indents don't always apply to the whole node. For example, in most
cases when a node should be indented, we actually only want everything
except for its first line to be indented. For this, there are several
scopes (more scopes may be added in the future if required):
- `tail`:
This scope applies to everything except for the first line of the
captured node.
- `all`:
This scope applies to the whole captured node. This is only different from
`tail` when the captured node is the first node on its line.
For example, imagine we have the following function
```rust
fn aha() { // ←─────────────────────────────────────╮
let take = "on me"; // ←──────────────╮ scope: │
let take = "me on"; // ├─ "tail" ├─ (block) @indent
let ill = be_gone_days(1 || 2); // │ │
} // ←───────────────────────────────────┴──────────┴─ "}" @outdent
// scope: "all"
```
We can write the following query with the `#set!` declaration:
```scm
((block) @indent
(#set! "scope" "tail"))
("}" @outdent
(#set! "scope" "all"))
```
As we can see, the "tail" scope covers the node, except for the first line.
Everything up to and including the closing brace gets an indent level of 1.
Then, on the closing brace, we encounter an outdent with a scope of "all", which
means the first line is included, and the indent level is cancelled out on this
line. (Note these scopes are the defaults for `@indent` and `@outdent`—they are
written explicitly for demonstration.)

@ -0,0 +1,57 @@
# Adding Injection Queries
Writing language injection queries allows one to highlight a specific node as a different language.
In addition to the [standard][upstream-docs] language injection options used by tree-sitter, there
are a few Helix specific extensions that allow for more control.
And example of a simple query that would highlight all strings as bash in Nix:
```scm
((string_expression (string_fragment) @injection.content)
(#set! injection.language "bash"))
```
## Capture Types
- `@injection.language` (standard):
The captured node may contain the language name used to highlight the node captured by
`@injection.content`.
- `@injection.content` (standard):
Marks the content to be highlighted as the language captured with `@injection.language` _et al_.
- `@injection.filename` (extension):
The captured node may contain a filename with a file-extension known to Helix,
highlighting `@injection.content` as that language. This uses the language extensions defined in
both the default languages.toml distributed with Helix, as well as user defined languages.
- `@injection.shebang` (extension):
The captured node may contain a shebang used to choose a language to highlight as. This also uses
the shebangs defined in the default and user `languages.toml`.
## Settings
- `injection.combined` (standard):
Indicates that all the matching nodes in the tree should have their content parsed as one
nested document.
- `injection.language` (standard):
Forces the captured content to be highlighted as the given language
- `injection.include-children` (standard):
Indicates that the content nodes entire text should be re-parsed, including the text of its child
nodes. By default, child nodes text will be excluded from the injected document.
- `injection.include-unnamed-children` (extension):
Same as `injection.include-children` but only for unnamed child nodes.
## Predicates
- `#eq?` (standard):
The first argument (a capture) must be equal to the second argument
(a capture or a string).
- `#match?` (standard):
The first argument (a capture) must match the regex given in the
second argument (a string).
[upstream-docs]: http://tree-sitter.github.io/tree-sitter/syntax-highlighting#language-injection

@ -1,14 +1,14 @@
# Adding Textobject Queries # Adding textobject queries
Textobjects that are language specific ([like functions, classes, etc][textobjects]) Helix supports textobjects that are language specific, such as functions, classes, etc.
require an accompanying tree-sitter grammar and a `textobjects.scm` query file These textobjects require an accompanying tree-sitter grammar and a `textobjects.scm` query file
to work properly. Tree-sitter allows us to query the source code syntax tree to work properly. Tree-sitter allows us to query the source code syntax tree
and capture specific parts of it. The queries are written in a lisp dialect. and capture specific parts of it. The queries are written in a lisp dialect.
More information on how to write queries can be found in the [official tree-sitter More information on how to write queries can be found in the [official tree-sitter
documentation][tree-sitter-queries]. documentation][tree-sitter-queries].
Query files should be placed in `runtime/queries/{language}/textobjects.scm` Query files should be placed in `runtime/queries/{language}/textobjects.scm`
when contributing. Note that to test the query files locally you should put when contributing to Helix. Note that to test the query files locally you should put
them under your local runtime directory (`~/.config/helix/runtime` on Linux them under your local runtime directory (`~/.config/helix/runtime` on Linux
for example). for example).
@ -28,9 +28,9 @@ The following [captures][tree-sitter-captures] are recognized:
[Example query files][textobject-examples] can be found in the helix GitHub repository. [Example query files][textobject-examples] can be found in the helix GitHub repository.
## Queries for Textobject Based Navigation ## Queries for textobject based navigation
[Tree-sitter based navigation][textobjects-nav] is done using captures in the Tree-sitter based navigation in Helix is done using captures in the
following order: following order:
- `object.movement` - `object.movement`
@ -38,12 +38,10 @@ following order:
- `object.inside` - `object.inside`
For example if a `function.around` capture has been already defined for a language For example if a `function.around` capture has been already defined for a language
in it's `textobjects.scm` file, function navigation should also work automatically. in its `textobjects.scm` file, function navigation should also work automatically.
`function.movement` should be defined only if the node captured by `function.around` `function.movement` should be defined only if the node captured by `function.around`
doesn't make sense in a navigation context. doesn't make sense in a navigation context.
[textobjects]: ../usage.md#textobjects
[textobjects-nav]: ../usage.md#tree-sitter-textobject-based-navigation
[tree-sitter-queries]: https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax [tree-sitter-queries]: https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax
[tree-sitter-captures]: https://tree-sitter.github.io/tree-sitter/using-parsers#capturing-nodes [tree-sitter-captures]: https://tree-sitter.github.io/tree-sitter/using-parsers#capturing-nodes
[textobject-examples]: https://github.com/search?q=repo%3Ahelix-editor%2Fhelix+filename%3Atextobjects.scm&type=Code&ref=advsearch&l=&l= [textobject-examples]: https://github.com/search?q=repo%3Ahelix-editor%2Fhelix+filename%3Atextobjects.scm&type=Code&ref=advsearch&l=&l=

@ -1,167 +1,320 @@
# Installation # Installing Helix
We provide pre-built binaries on the [GitHub Releases page](https://github.com/helix-editor/helix/releases). <!--toc:start-->
- [Pre-built binaries](#pre-built-binaries)
- [Linux, macOS, Windows and OpenBSD packaging status](#linux-macos-windows-and-openbsd-packaging-status)
- [Linux](#linux)
- [Ubuntu](#ubuntu)
- [Fedora/RHEL](#fedorarhel)
- [Arch Linux extra](#arch-linux-extra)
- [NixOS](#nixos)
- [Flatpak](#flatpak)
- [Snap](#snap)
- [AppImage](#appimage)
- [macOS](#macos)
- [Homebrew Core](#homebrew-core)
- [MacPorts](#macports)
- [Windows](#windows)
- [Winget](#winget)
- [Scoop](#scoop)
- [Chocolatey](#chocolatey)
- [MSYS2](#msys2)
- [Building from source](#building-from-source)
- [Configuring Helix's runtime files](#configuring-helixs-runtime-files)
- [Linux and macOS](#linux-and-macos)
- [Windows](#windows)
- [Multiple runtime directories](#multiple-runtime-directories)
- [Validating the installation](#validating-the-installation)
- [Configure the desktop shortcut](#configure-the-desktop-shortcut)
<!--toc:end-->
To install Helix, follow the instructions specific to your operating system.
Note that:
- To get the latest nightly version of Helix, you need to
[build from source](#building-from-source).
- To take full advantage of Helix, install the language servers for your
preferred programming languages. See the
[wiki](https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers)
for instructions.
## Pre-built binaries
Download pre-built binaries from the
[GitHub Releases page](https://github.com/helix-editor/helix/releases). Add the binary to your system's `$PATH` to use it from the command
line.
## Linux, macOS, Windows and OpenBSD packaging status
[![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions) [![Packaging status](https://repology.org/badge/vertical-allrepos/helix.svg)](https://repology.org/project/helix/versions)
## OSX ## Linux
The following third party repositories are available:
### Ubuntu
Helix is available in homebrew-core: Add the `PPA` for Helix:
```sh
sudo add-apt-repository ppa:maveonair/helix-editor
sudo apt update
sudo apt install helix
``` ```
brew install helix
### Fedora/RHEL
```sh
sudo dnf install helix
``` ```
## Linux ### Arch Linux extra
Releases are available in the `extra` repository:
```sh
sudo pacman -S helix
```
Additionally, a [helix-git](https://aur.archlinux.org/packages/helix-git/) package is available
in the AUR, which builds the master branch.
### NixOS ### NixOS
A [flake](https://nixos.wiki/wiki/Flakes) containing the package is available in Helix is available in [nixpkgs](https://github.com/nixos/nixpkgs) through the `helix` attribute,
the project root. The flake can also be used to spin up a reproducible development the unstable channel usually carries the latest release.
shell for working on Helix with `nix develop`.
Flake outputs are cached for each push to master using Helix is also available as a [flake](https://nixos.wiki/wiki/Flakes) in the project
[Cachix](https://www.cachix.org/). The flake is configured to root. Use `nix develop` to spin up a reproducible development shell. Outputs are
automatically make use of this cache assuming the user accepts cached for each push to master using [Cachix](https://www.cachix.org/). The
the new settings on first use. 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 you can If you are using a version of Nix without flakes enabled,
[install Cachix cli](https://docs.cachix.org/installation); `cachix use helix` will [install Cachix CLI](https://docs.cachix.org/installation) and use
configure Nix to use cached outputs when possible. `cachix use helix` to configure Nix to use cached outputs when possible.
### Arch Linux ### Flatpak
Releases are available in the `community` repository. Helix is available on [Flathub](https://flathub.org/en-GB/apps/com.helix_editor.Helix):
A [helix-git](https://aur.archlinux.org/packages/helix-git/) package is also available on the AUR, which builds the master branch. ```sh
flatpak install flathub com.helix_editor.Helix
flatpak run com.helix_editor.Helix
```
### Fedora Linux ### Snap
You can install the COPR package for Helix via Helix is available on [Snapcraft](https://snapcraft.io/helix) and can be installed with:
```sh
snap install --classic helix
``` ```
sudo dnf copr enable varlad/helix
sudo dnf install 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
``` ```
### Void Linux ## macOS
### Homebrew Core
```sh
brew install helix
``` ```
sudo xbps-install helix
### MacPorts
```sh
port install helix
``` ```
## Windows ## Windows
Helix can be installed using [Scoop](https://scoop.sh/), [Chocolatey](https://chocolatey.org/) 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/). or [MSYS2](https://msys2.org/).
**Scoop:** ### 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 scoop install helix
``` ```
**Chocolatey:** ### Chocolatey
``` ```sh
choco install helix choco install helix
``` ```
**MSYS2:** ### MSYS2
``` For 64-bit Windows 8.1 or above:
pacman -S mingw-w64-i686-helix
```sh
pacman -S mingw-w64-ucrt-x86_64-helix
``` ```
or ## Building from source
``` Requirements:
pacman -S mingw-w64-x86_64-helix
```
or 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)
pacman -S mingw-w64-ucrt-x86_64-helix - 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
## Build from source 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 git clone https://github.com/helix-editor/helix
cd helix cd helix
cargo install --path helix-term
``` ```
This will install the `hx` binary to `$HOME/.cargo/bin` and build tree-sitter grammars in `./runtime/grammars`. 2. Compile from source:
Helix also needs its runtime files so make sure to copy/symlink the `runtime/` directory into the ```sh
config directory (for example `~/.config/helix/runtime` on Linux/macOS). This location can be overridden cargo install --path helix-term --locked
via the `HELIX_RUNTIME` environment variable. ```
| OS | Command | This command will create the `hx` executable and construct the tree-sitter
| -------------------- | ------------------------------------------------ | grammars in the local `runtime` folder.
| Windows (Cmd) | `xcopy /e /i runtime %AppData%\helix\runtime` |
| Windows (PowerShell) | `xcopy /e /i runtime $Env:AppData\helix\runtime` |
| Linux / macOS | `ln -s $PWD/runtime ~/.config/helix/runtime` |
Starting with Windows Vista you can also create symbolic links on Windows. Note that this requires > 💡 Tree-sitter grammars can be fetched and compiled if not pre-packaged. Fetch
elevated privileges - i.e. PowerShell or Cmd must be run as administrator. > 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)).
**PowerShell:** ### Configuring Helix's runtime files
```powershell #### Linux and macOS
New-Item -ItemType SymbolicLink -Target "runtime" -Path "$Env:AppData\helix\runtime"
```
**Cmd:** The **runtime** directory is one below the Helix source, so either set a
`HELIX_RUNTIME` environment variable to point to that directory and add it to
your `~/.bashrc` or equivalent:
```cmd ```sh
cd %appdata%\helix HELIX_RUNTIME=~/src/helix/runtime
mklink /D runtime "<helix-repo>\runtime"
``` ```
The runtime location can be overridden via the `HELIX_RUNTIME` environment variable. Or, create a symbolic link:
> NOTE: if `HELIX_RUNTIME` is set prior to calling `cargo install --path helix-term`, ```sh
> tree-sitter grammars will be built in `$HELIX_RUNTIME/grammars`. ln -Ts $PWD/runtime ~/.config/helix/runtime
```
If you plan on keeping the repo locally, an alternative to copying/symlinking 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.
runtime files is to set `HELIX_RUNTIME=/path/to/helix/runtime`
(`HELIX_RUNTIME=$PWD/runtime` if you're in the helix repo directory).
To use Helix in desktop environments that supports [XDG desktop menu](https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html), including Gnome and KDE, copy the provided `.desktop` file to the correct folder: #### Windows
```bash Either set the `HELIX_RUNTIME` environment variable to point to the runtime files using the Windows setting (search for
cp contrib/Helix.desktop ~/.local/share/applications `Edit environment variables for your account`) or use the `setx` command in
Cmd:
```sh
setx HELIX_RUNTIME "%userprofile%\source\repos\helix\runtime"
``` ```
To use another terminal than the default, you will need to modify the `.desktop` file. For example, to use `kitty`: > 💡 `%userprofile%` resolves to your user directory like
> `C:\Users\Your-Name\` for example.
```bash Or, create a symlink in `%appdata%\helix\` that links to the source code directory:
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
```
Please note: there is no icon for Helix yet, so the system default will be used. | 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"` |
## Finishing up the installation > 💡 On Windows, creating a symbolic link may require running PowerShell or
> Cmd as an administrator.
To make sure everything is set up as expected you should finally run the helix healthcheck via #### 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 hx --health
``` ```
For more information on the information displayed in the health check results refer to [Healthcheck](https://github.com/helix-editor/helix/wiki/Healthcheck). For more information on the health check results refer to
[Health check](https://github.com/helix-editor/helix/wiki/Healthcheck).
### Configure the desktop shortcut
### Building tree-sitter grammars 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:
Tree-sitter grammars must be fetched and compiled if not pre-packaged. ```sh
Fetch grammars with `hx --grammar fetch` (requires `git`) and compile them cp contrib/Helix.desktop ~/.local/share/applications
with `hx --grammar build` (requires a C++ compiler). cp contrib/helix.png ~/.icons # or ~/.local/share/icons
```
### Installing language servers To use another terminal than the system default, you can modify the `.desktop`
file. For example, to use `kitty`:
Language servers can optionally be installed if you want their features (auto-complete, diagnostics etc.). ```sh
Follow the [instructions on the wiki page](https://github.com/helix-editor/helix/wiki/How-to-install-the-default-language-servers) to add your language servers of choice. 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
```

@ -14,7 +14,7 @@
- [Space mode](#space-mode) - [Space mode](#space-mode)
- [Popup](#popup) - [Popup](#popup)
- [Unimpaired](#unimpaired) - [Unimpaired](#unimpaired)
- [Insert Mode](#insert-mode) - [Insert mode](#insert-mode)
- [Select / extend mode](#select--extend-mode) - [Select / extend mode](#select--extend-mode)
- [Picker](#picker) - [Picker](#picker)
- [Prompt](#prompt) - [Prompt](#prompt)
@ -25,6 +25,8 @@
## Normal mode ## Normal mode
Normal mode is the default mode when you launch helix. Return to it from other modes by typing `Escape`.
### Movement ### Movement
> NOTE: Unlike Vim, `f`, `F`, `t` and `T` are not confined to the current line. > NOTE: Unlike Vim, `f`, `F`, `t` and `T` are not confined to the current line.
@ -32,8 +34,8 @@
| Key | Description | Command | | Key | Description | Command |
| ----- | ----------- | ------- | | ----- | ----------- | ------- |
| `h`, `Left` | Move left | `move_char_left` | | `h`, `Left` | Move left | `move_char_left` |
| `j`, `Down` | Move down | `move_line_down` | | `j`, `Down` | Move down | `move_visual_line_down` |
| `k`, `Up` | Move up | `move_line_up` | | `k`, `Up` | Move up | `move_visual_line_up` |
| `l`, `Right` | Move right | `move_char_right` | | `l`, `Right` | Move right | `move_char_right` |
| `w` | Move next word start | `move_next_word_start` | | `w` | Move next word start | `move_next_word_start` |
| `b` | Move previous word start | `move_prev_word_start` | | `b` | Move previous word start | `move_prev_word_start` |
@ -111,6 +113,8 @@
| `s` | Select all regex matches inside selections | `select_regex` | | `s` | Select all regex matches inside selections | `select_regex` |
| `S` | Split selection into sub selections on regex matches | `split_selection` | | `S` | Split selection into sub selections on regex matches | `split_selection` |
| `Alt-s` | Split selection on newlines | `split_selection_on_newline` | | `Alt-s` | Split selection on newlines | `split_selection_on_newline` |
| `Alt-minus` | Merge selections | `merge_selections` |
| `Alt-_` | Merge consecutive selections | `merge_consecutive_selections` |
| `&` | Align selection in columns | `align_selections` | | `&` | Align selection in columns | `align_selections` |
| `_` | Trim whitespace from the selection | `trim_selections` | | `_` | Trim whitespace from the selection | `trim_selections` |
| `;` | Collapse selection onto a single cursor | `collapse_selection` | | `;` | Collapse selection onto a single cursor | `collapse_selection` |
@ -129,7 +133,7 @@
| `X` | Extend selection to line bounds (line-wise selection) | `extend_to_line_bounds` | | `X` | Extend selection to line bounds (line-wise selection) | `extend_to_line_bounds` |
| `Alt-x` | Shrink selection to line bounds (line-wise selection) | `shrink_to_line_bounds` | | `Alt-x` | Shrink selection to line bounds (line-wise selection) | `shrink_to_line_bounds` |
| `J` | Join lines inside selection | `join_selections` | | `J` | Join lines inside selection | `join_selections` |
| `Alt-J` | Join lines inside selection and select space | `join_selections_space` | | `Alt-J` | Join lines inside selection and select the inserted space | `join_selections_space` |
| `K` | Keep selections matching the regex | `keep_selections` | | `K` | Keep selections matching the regex | `keep_selections` |
| `Alt-K` | Remove selections matching the regex | `remove_selections` | | `Alt-K` | Remove selections matching the regex | `remove_selections` |
| `Ctrl-c` | Comment/uncomment the selections | `toggle_comments` | | `Ctrl-c` | Comment/uncomment the selections | `toggle_comments` |
@ -140,7 +144,7 @@
### Search ### Search
Search commands all operate on the `/` register by default. Use `"<char>` to operate on a different one. Search commands all operate on the `/` register by default. To use a different register, use `"<char>`.
| Key | Description | Command | | Key | Description | Command |
| ----- | ----------- | ------- | | ----- | ----------- | ------- |
@ -165,15 +169,17 @@ These sub-modes are accessible from normal mode and typically switch back to nor
| `Ctrl-w` | Enter [window mode](#window-mode) | N/A | | `Ctrl-w` | Enter [window mode](#window-mode) | N/A |
| `Space` | Enter [space mode](#space-mode) | N/A | | `Space` | Enter [space mode](#space-mode) | N/A |
These modes (except command mode) can be configured by
[remapping keys](https://docs.helix-editor.com/remapping.html#minor-modes).
#### View mode #### View mode
Accessed by typing `z` in [normal mode](#normal-mode). Accessed by typing `z` in [normal mode](#normal-mode).
View mode is intended for scrolling and manipulating the view without changing View mode is intended for scrolling and manipulating the view without changing
the selection. The "sticky" variant of this mode (accessed by typing `Z` in the selection. The "sticky" variant of this mode (accessed by typing `Z` in
normal mode) is persistent; use the Escape key to return to normal mode after normal mode) is persistent and can be exited using the escape key. This is
usage (useful when you're simply looking over text and not actively editing useful when you're simply looking over text and not actively editing it.
it).
| Key | Description | Command | | Key | Description | Command |
@ -215,13 +221,15 @@ Jumps to various locations.
| `n` | Go to next buffer | `goto_next_buffer` | | `n` | Go to next buffer | `goto_next_buffer` |
| `p` | Go to previous buffer | `goto_previous_buffer` | | `p` | Go to previous buffer | `goto_previous_buffer` |
| `.` | Go to last modification in current file | `goto_last_modification` | | `.` | Go to last modification in current file | `goto_last_modification` |
| `j` | Move down textual (instead of visual) line | `move_line_down` |
| `k` | Move up textual (instead of visual) line | `move_line_up` |
#### Match mode #### Match mode
Accessed by typing `m` in [normal mode](#normal-mode). Accessed by typing `m` in [normal mode](#normal-mode).
See the relevant section in [Usage](./usage.md) for an explanation about See the relevant section in [Usage](./usage.md) for an explanation about
[surround](./usage.md#surround) and [textobject](./usage.md#textobjects) usage. [surround](./usage.md#surround) and [textobject](./usage.md#navigating-using-tree-sitter-textobjects) usage.
| Key | Description | Command | | Key | Description | Command |
| ----- | ----------- | ------- | | ----- | ----------- | ------- |
@ -238,7 +246,7 @@ TODO: Mappings for selecting syntax nodes (a superset of `[`).
Accessed by typing `Ctrl-w` in [normal mode](#normal-mode). Accessed by typing `Ctrl-w` in [normal mode](#normal-mode).
This layer is similar to Vim keybindings as Kakoune does not support window. This layer is similar to Vim keybindings as Kakoune does not support windows.
| Key | Description | Command | | Key | Description | Command |
| ----- | ------------- | ------- | | ----- | ------------- | ------- |
@ -270,6 +278,7 @@ This layer is a kludge of mappings, mostly pickers.
| `F` | Open file picker at current working directory | `file_picker_in_current_directory` | | `F` | Open file picker at current working directory | `file_picker_in_current_directory` |
| `b` | Open buffer picker | `buffer_picker` | | `b` | Open buffer picker | `buffer_picker` |
| `j` | Open jumplist picker | `jumplist_picker` | | `j` | Open jumplist picker | `jumplist_picker` |
| `g` | Debug (experimental) | N/A |
| `k` | Show documentation for item under cursor in a [popup](#popup) (**LSP**) | `hover` | | `k` | Show documentation for item under cursor in a [popup](#popup) (**LSP**) | `hover` |
| `s` | Open document symbol picker (**LSP**) | `symbol_picker` | | `s` | Open document symbol picker (**LSP**) | `symbol_picker` |
| `S` | Open workspace symbol picker (**LSP**) | `workspace_symbol_picker` | | `S` | Open workspace symbol picker (**LSP**) | `workspace_symbol_picker` |
@ -277,17 +286,18 @@ This layer is a kludge of mappings, mostly pickers.
| `D` | Open workspace diagnostics picker (**LSP**) | `workspace_diagnostics_picker` | | `D` | Open workspace diagnostics picker (**LSP**) | `workspace_diagnostics_picker` |
| `r` | Rename symbol (**LSP**) | `rename_symbol` | | `r` | Rename symbol (**LSP**) | `rename_symbol` |
| `a` | Apply code action (**LSP**) | `code_action` | | `a` | Apply code action (**LSP**) | `code_action` |
| `h` | Select symbol references (**LSP**) | `select_references_to_symbol_under_cursor` |
| `'` | Open last fuzzy picker | `last_picker` | | `'` | Open last fuzzy picker | `last_picker` |
| `w` | Enter [window mode](#window-mode) | N/A | | `w` | Enter [window mode](#window-mode) | N/A |
| `p` | Paste system clipboard after selections | `paste_clipboard_after` | | `p` | Paste system clipboard after selections | `paste_clipboard_after` |
| `P` | Paste system clipboard before selections | `paste_clipboard_before` | | `P` | Paste system clipboard before selections | `paste_clipboard_before` |
| `y` | Join and yank selections to clipboard | `yank_joined_to_clipboard` | | `y` | Yank selections to clipboard | `yank_to_clipboard` |
| `Y` | Yank main selection to clipboard | `yank_main_selection_to_clipboard` | | `Y` | Yank main selection to clipboard | `yank_main_selection_to_clipboard` |
| `R` | Replace selections by clipboard contents | `replace_selections_with_clipboard` | | `R` | Replace selections by clipboard contents | `replace_selections_with_clipboard` |
| `/` | Global search in workspace folder | `global_search` | | `/` | Global search in workspace folder | `global_search` |
| `?` | Open command palette | `command_palette` | | `?` | Open command palette | `command_palette` |
> TIP: Global search displays results in a fuzzy picker, use `Space + '` to bring it back up after opening a file. > 💡 Global search displays results in a fuzzy picker, use `Space + '` to bring it back up after opening a file.
##### Popup ##### Popup
@ -300,14 +310,14 @@ Displays documentation for item under cursor.
#### Unimpaired #### Unimpaired
Mappings in the style of [vim-unimpaired](https://github.com/tpope/vim-unimpaired). These mappings are in the style of [vim-unimpaired](https://github.com/tpope/vim-unimpaired).
| Key | Description | Command | | Key | Description | Command |
| ----- | ----------- | ------- | | ----- | ----------- | ------- |
| `[d` | Go to previous diagnostic (**LSP**) | `goto_prev_diag` |
| `]d` | Go to next diagnostic (**LSP**) | `goto_next_diag` | | `]d` | Go to next diagnostic (**LSP**) | `goto_next_diag` |
| `[D` | Go to first diagnostic in document (**LSP**) | `goto_first_diag` | | `[d` | Go to previous diagnostic (**LSP**) | `goto_prev_diag` |
| `]D` | Go to last diagnostic in document (**LSP**) | `goto_last_diag` | | `]D` | Go to last diagnostic in document (**LSP**) | `goto_last_diag` |
| `[D` | Go to first diagnostic in document (**LSP**) | `goto_first_diag` |
| `]f` | Go to next function (**TS**) | `goto_next_function` | | `]f` | Go to next function (**TS**) | `goto_next_function` |
| `[f` | Go to previous function (**TS**) | `goto_prev_function` | | `[f` | Go to previous function (**TS**) | `goto_prev_function` |
| `]t` | Go to next type definition (**TS**) | `goto_next_class` | | `]t` | Go to next type definition (**TS**) | `goto_next_class` |
@ -317,24 +327,27 @@ Mappings in the style of [vim-unimpaired](https://github.com/tpope/vim-unimpaire
| `]c` | Go to next comment (**TS**) | `goto_next_comment` | | `]c` | Go to next comment (**TS**) | `goto_next_comment` |
| `[c` | Go to previous comment (**TS**) | `goto_prev_comment` | | `[c` | Go to previous comment (**TS**) | `goto_prev_comment` |
| `]T` | Go to next test (**TS**) | `goto_next_test` | | `]T` | Go to next test (**TS**) | `goto_next_test` |
| `]T` | Go to previous test (**TS**) | `goto_prev_test` | | `[T` | Go to previous test (**TS**) | `goto_prev_test` |
| `]p` | Go to next paragraph | `goto_next_paragraph` | | `]p` | Go to next paragraph | `goto_next_paragraph` |
| `[p` | Go to previous paragraph | `goto_prev_paragraph` | | `[p` | Go to previous paragraph | `goto_prev_paragraph` |
| `]g` | Go to next change | `goto_next_change` | | `]g` | Go to next change | `goto_next_change` |
| `[g` | Go to previous change | `goto_prev_change` | | `[g` | Go to previous change | `goto_prev_change` |
| `]G` | Go to first change | `goto_first_change` | | `]G` | Go to last change | `goto_last_change` |
| `[G` | Go to last change | `goto_last_change` | | `[G` | Go to first change | `goto_first_change` |
| `[Space` | Add newline above | `add_newline_above` |
| `]Space` | Add newline below | `add_newline_below` | | `]Space` | Add newline below | `add_newline_below` |
| `[Space` | Add newline above | `add_newline_above` |
## Insert mode ## Insert mode
Insert mode bindings are somewhat minimal by default. Helix is designed to Accessed by typing `i` in [normal mode](#normal-mode).
Insert mode bindings are minimal by default. Helix is designed to
be a modal editor, and this is reflected in the user experience and internal be a modal editor, and this is reflected in the user experience and internal
mechanics. For example, changes to the text are only saved for undos when mechanics. Changes to the text are only saved for undos when
escaping from insert mode to normal mode. For this reason, new users are escaping from insert mode to normal mode.
strongly encouraged to learn the modal editing paradigm to get the smoothest
experience. > 💡 New users are strongly encouraged to learn the modal editing paradigm
> to get the smoothest experience.
| Key | Description | Command | | Key | Description | Command |
| ----- | ----------- | ------- | | ----- | ----------- | ------- |
@ -346,7 +359,7 @@ experience.
| `Alt-d`, `Alt-Delete` | Delete next word | `delete_word_forward` | | `Alt-d`, `Alt-Delete` | Delete next word | `delete_word_forward` |
| `Ctrl-u` | Delete to start of line | `kill_to_line_start` | | `Ctrl-u` | Delete to start of line | `kill_to_line_start` |
| `Ctrl-k` | Delete to end of line | `kill_to_line_end` | | `Ctrl-k` | Delete to end of line | `kill_to_line_end` |
| `Ctrl-h`, `Backspace` | Delete previous char | `delete_char_backward` | | `Ctrl-h`, `Backspace`, `Shift-Backspace` | Delete previous char | `delete_char_backward` |
| `Ctrl-d`, `Delete` | Delete next char | `delete_char_forward` | | `Ctrl-d`, `Delete` | Delete next char | `delete_char_forward` |
| `Ctrl-j`, `Enter` | Insert new line | `insert_newline` | | `Ctrl-j`, `Enter` | Insert new line | `insert_newline` |
@ -364,8 +377,8 @@ with modal editors.
| `Home` | Move to line start | `goto_line_start` | | `Home` | Move to line start | `goto_line_start` |
| `End` | Move to line end | `goto_line_end_newline` | | `End` | Move to line end | `goto_line_end_newline` |
If you want to disable them in insert mode as you become more comfortable with modal editing, you can use As you become more comfortable with modal editing, you may want to disable some
the following in your `config.toml`: insert mode bindings. You can do this by editing your `config.toml` file.
```toml ```toml
[keys.insert] [keys.insert]
@ -381,9 +394,11 @@ end = "no_op"
## Select / extend mode ## Select / extend mode
This mode echoes Normal mode, but changes any movements to extend Accessed by typing `v` in [normal mode](#normal-mode).
Select mode echoes Normal mode, but changes any movements to extend
selections rather than replace them. Goto motions are also changed to selections rather than replace them. Goto motions are also changed to
extend, so that `vgl` for example extends the selection to the end of extend, so that `vgl`, for example, extends the selection to the end of
the line. the line.
Search is also affected. By default, `n` and `N` will remove the current Search is also affected. By default, `n` and `N` will remove the current
@ -405,6 +420,7 @@ Keys to use within picker. Remapping currently not supported.
| `Home` | Go to first entry | | `Home` | Go to first entry |
| `End` | Go to last entry | | `End` | Go to last entry |
| `Enter` | Open selected | | `Enter` | Open selected |
| `Alt-Enter` | Open selected in the background without closing the picker |
| `Ctrl-s` | Open horizontally | | `Ctrl-s` | Open horizontally |
| `Ctrl-v` | Open vertically | | `Ctrl-v` | Open vertically |
| `Ctrl-t` | Toggle preview | | `Ctrl-t` | Toggle preview |
@ -427,7 +443,7 @@ Keys to use within prompt, Remapping currently not supported.
| `Alt-d`, `Alt-Delete`, `Ctrl-Delete` | Delete next word | | `Alt-d`, `Alt-Delete`, `Ctrl-Delete` | Delete next word |
| `Ctrl-u` | Delete to start of line | | `Ctrl-u` | Delete to start of line |
| `Ctrl-k` | Delete to end of line | | `Ctrl-k` | Delete to end of line |
| `Backspace`, `Ctrl-h` | Delete previous char | | `Backspace`, `Ctrl-h`, `Shift-Backspace` | Delete previous char |
| `Delete`, `Ctrl-d` | Delete next char | | `Delete`, `Ctrl-d` | Delete next char |
| `Ctrl-s` | Insert a word under doc cursor, may be changed to Ctrl-r Ctrl-w later | | `Ctrl-s` | Insert a word under doc cursor, may be changed to Ctrl-r Ctrl-w later |
| `Ctrl-p`, `Up` | Select previous history | | `Ctrl-p`, `Up` | Select previous history |

@ -1,10 +1,10 @@
# Language Support # Language Support
The following languages and Language Servers are supported. In order to use The following languages and Language Servers are supported. To use
Language Server features, you must first [install][lsp-install-wiki] the Language Server features, you must first [install][lsp-install-wiki] the
appropriate Language Server. appropriate Language Server.
Check the language support in your installed helix version with `hx --health`. You can check the language support in your installed helix version with `hx --health`.
Also see the [Language Configuration][lang-config] docs and the [Adding Also see the [Language Configuration][lang-config] docs and the [Adding
Languages][adding-languages] guide for more language configuration information. Languages][adding-languages] guide for more language configuration information.

@ -5,26 +5,31 @@ in `languages.toml` files.
## `languages.toml` files ## `languages.toml` files
There are three possible `languages.toml` files. The first is compiled into There are three possible locations for a `languages.toml` file:
Helix and lives in the [Helix repository](https://github.com/helix-editor/helix/blob/master/languages.toml).
This provides the default configurations for languages and language servers.
You may define a `languages.toml` in your [configuration directory](./configuration.md) 1. In the Helix source code, which lives in the
which overrides values from the built-in language configuration. For example [Helix repository](https://github.com/helix-editor/helix/blob/master/languages.toml).
to disable auto-LSP-formatting in Rust: It provides the default configurations for languages and language servers.
2. In your [configuration directory](./configuration.md). This overrides values
from the built-in language configuration. For example, to disable
auto-LSP-formatting in Rust:
```toml ```toml
# in <config_dir>/helix/languages.toml # in <config_dir>/helix/languages.toml
[language-server.mylang-lsp]
command = "mylang-lsp"
[[language]] [[language]]
name = "rust" name = "rust"
auto-format = false auto-format = false
``` ```
Language configuration may also be overridden local to a project by creating 3. In a `.helix` folder in your project. Language configuration may also be
a `languages.toml` file under a `.helix` directory. Its settings will be merged overridden local to a project by creating a `languages.toml` file in a
with the language configuration in the configuration directory and the built-in `.helix` folder. Its settings will be merged with the language configuration
configuration. in the configuration directory and the built-in configuration.
## Language configuration ## Language configuration
@ -35,12 +40,12 @@ Each language is configured by adding a `[[language]]` section to a
[[language]] [[language]]
name = "mylang" name = "mylang"
scope = "source.mylang" scope = "source.mylang"
injection-regex = "^mylang$" injection-regex = "mylang"
file-types = ["mylang", "myl"] file-types = ["mylang", "myl"]
comment-token = "#" comment-token = "#"
indent = { tab-width = 2, unit = " " } indent = { tab-width = 2, unit = " " }
language-server = { command = "mylang-lsp", args = ["--stdio"], environment = { "ENV1" = "value1", "ENV2" = "value2" } }
formatter = { command = "mylang-formatter" , args = ["--stdin"] } formatter = { command = "mylang-formatter" , args = ["--stdin"] }
language-servers = [ "mylang-lsp" ]
``` ```
These configuration keys are available: These configuration keys are available:
@ -48,6 +53,7 @@ These configuration keys are available:
| Key | Description | | Key | Description |
| ---- | ----------- | | ---- | ----------- |
| `name` | The name of the language | | `name` | The name of the language |
| `language-id` | The language-id for language servers, checkout the table at [TextDocumentItem](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocumentItem) for the right id |
| `scope` | A string like `source.js` that identifies the language. Currently, we strive to match the scope names used by popular TextMate grammars and by the Linguist library. Usually `source.<name>` or `text.<name>` in case of markup languages | | `scope` | A string like `source.js` that identifies the language. Currently, we strive to match the scope names used by popular TextMate grammars and by the Linguist library. Usually `source.<name>` or `text.<name>` in case of markup languages |
| `injection-regex` | regex pattern that will be tested against a language name in order to determine whether this language should be used for a potential [language injection][treesitter-language-injection] site. | | `injection-regex` | regex pattern that will be tested against a language name in order to determine whether this language should be used for a potential [language injection][treesitter-language-injection] site. |
| `file-types` | The filetypes of the language, for example `["yml", "yaml"]`. See the file-type detection section below. | | `file-types` | The filetypes of the language, for example `["yml", "yaml"]`. See the file-type detection section below. |
@ -56,16 +62,17 @@ These configuration keys are available:
| `auto-format` | Whether to autoformat this language when saving | | `auto-format` | Whether to autoformat this language when saving |
| `diagnostic-severity` | Minimal severity of diagnostic for it to be displayed. (Allowed values: `Error`, `Warning`, `Info`, `Hint`) | | `diagnostic-severity` | Minimal severity of diagnostic for it to be displayed. (Allowed values: `Error`, `Warning`, `Info`, `Hint`) |
| `comment-token` | The token to use as a comment-token | | `comment-token` | The token to use as a comment-token |
| `indent` | The indent to use. Has sub keys `tab-width` and `unit` | | `indent` | The indent to use. Has sub keys `unit` (the text inserted into the document when indenting; usually set to N spaces or `"\t"` for tabs) and `tab-width` (the number of spaces rendered for a tab) |
| `language-server` | The Language Server to run. See the Language Server configuration section below. | | `language-servers` | The Language Servers used for this language. See below for more information in the section [Configuring Language Servers for a language](#configuring-language-servers-for-a-language) |
| `config` | Language Server configuration |
| `grammar` | The tree-sitter grammar to use (defaults to the value of `name`) | | `grammar` | The tree-sitter grammar to use (defaults to the value of `name`) |
| `formatter` | The formatter for the language, it will take precedence over the lsp when defined. The formatter must be able to take the original file as input from stdin and write the formatted file to stdout | | `formatter` | The formatter for the language, it will take precedence over the lsp when defined. The formatter must be able to take the original file as input from stdin and write the formatted file to stdout |
| `max-line-length` | Maximum line length. Used for the `:reflow` command | | `soft-wrap` | [editor.softwrap](./configuration.md#editorsoft-wrap-section)
| `text-width` | Maximum line length. Used for the `:reflow` command and soft-wrapping if `soft-wrap.wrap-at-text-width` is set, defaults to `editor.text-width` |
| `workspace-lsp-roots` | Directories relative to the workspace root that are treated as LSP roots. Should only be set in `.helix/config.toml`. Overwrites the setting of the same name in `config.toml` if set. |
### File-type detection and the `file-types` key ### File-type detection and the `file-types` key
Helix determines which language configuration to use with the `file-types` key Helix determines which language configuration to use based on the `file-types` key
from the above section. `file-types` is a list of strings or tables, for from the above section. `file-types` is a list of strings or tables, for
example: example:
@ -89,31 +96,102 @@ with the following priorities:
replaced at runtime with the appropriate path separator for the operating replaced at runtime with the appropriate path separator for the operating
system, so this rule would match against `.git\config` files on Windows. system, so this rule would match against `.git\config` files on Windows.
### Language Server configuration ## Language Server configuration
Language servers are configured separately in the table `language-server` in the same file as the languages `languages.toml`
For example:
The `language-server` field takes the following keys: ```toml
[language-server.mylang-lsp]
command = "mylang-lsp"
args = ["--stdio"]
config = { provideFormatter = true }
environment = { "ENV1" = "value1", "ENV2" = "value2" }
[language-server.efm-lsp-prettier]
command = "efm-langserver"
[language-server.efm-lsp-prettier.config]
documentFormatting = true
languages = { typescript = [ { formatCommand ="prettier --stdin-filepath ${INPUT}", formatStdin = true } ] }
```
These are the available options for a language server.
| Key | Description | | Key | Description |
| --- | ----------- | | ---- | ----------- |
| `command` | The name of the language server binary to execute. Binaries must be in `$PATH` | | `command` | The name or path of the language server binary to execute. Binaries must be in `$PATH` |
| `args` | A list of arguments to pass to the language server binary | | `args` | A list of arguments to pass to the language server binary |
| `config` | LSP initialization options |
| `timeout` | The maximum time a request to the language server may take, in seconds. Defaults to `20` | | `timeout` | The maximum time a request to the language server may take, in seconds. Defaults to `20` |
| `language-id` | The language name to pass to the language server. Some language servers support multiple languages and use this field to determine which one is being served in a buffer |
| `environment` | Any environment variables that will be used when starting the language server `{ "KEY1" = "Value1", "KEY2" = "Value2" }` | | `environment` | Any environment variables that will be used when starting the language server `{ "KEY1" = "Value1", "KEY2" = "Value2" }` |
The top-level `config` field is used to configure the LSP initialization options. A `format` A `format` sub-table within `config` can be used to pass extra formatting options to
sub-table within `config` can be used to pass extra formatting options to [Document Formatting Requests](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting).
[Document Formatting Requests](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/specification-3-16.md#document-formatting-request--leftwards_arrow_with_hook). For example, with typescript:
For example with typescript:
```toml ```toml
[[language]] [language-server.typescript-language-server]
name = "typescript"
auto-format = true
# pass format options according to https://github.com/typescript-language-server/typescript-language-server#workspacedidchangeconfiguration omitting the "[language].format." prefix. # pass format options according to https://github.com/typescript-language-server/typescript-language-server#workspacedidchangeconfiguration omitting the "[language].format." prefix.
config = { format = { "semicolons" = "insert", "insertSpaceBeforeFunctionParenthesis" = true } } config = { format = { "semicolons" = "insert", "insertSpaceBeforeFunctionParenthesis" = true } }
``` ```
### Configuring Language Servers for a language
The `language-servers` attribute in a language tells helix which language servers are used for this language.
They have to be defined in the `[language-server]` table as described in the previous section.
Different languages can use the same language server instance, e.g. `typescript-language-server` is used for javascript, jsx, tsx and typescript by default.
In case multiple language servers are specified in the `language-servers` attribute of a `language`,
it's often useful to only enable/disable certain language-server features for these language servers.
As an example, `efm-lsp-prettier` of the previous example is used only with a formatting command `prettier`,
so everything else should be handled by the `typescript-language-server` (which is configured by default).
The language configuration for typescript could look like this:
```toml
[[language]]
name = "typescript"
language-servers = [ { name = "efm-lsp-prettier", only-features = [ "format" ] }, "typescript-language-server" ]
```
or equivalent:
```toml
[[language]]
name = "typescript"
language-servers = [ { name = "typescript-language-server", except-features = [ "format" ] }, "efm-lsp-prettier" ]
```
Each requested LSP feature is prioritized in the order of the `language-servers` array.
For example, the first `goto-definition` supported language server (in this case `typescript-language-server`) will be taken for the relevant LSP request (command `goto_definition`).
The features `diagnostics`, `code-action`, `completion`, `document-symbols` and `workspace-symbols` are an exception to that rule, as they are working for all language servers at the same time and are merged together, if enabled for the language.
If no `except-features` or `only-features` is given, all features for the language server are enabled.
If a language server itself doesn't support a feature, the next language server array entry will be tried (and so on).
The list of supported features is:
- `format`
- `goto-definition`
- `goto-declaration`
- `goto-type-definition`
- `goto-reference`
- `goto-implementation`
- `signature-help`
- `hover`
- `document-highlight`
- `completion`
- `code-action`
- `workspace-command`
- `document-symbols`
- `workspace-symbols`
- `diagnostics`
- `rename-symbol`
- `inlay-hints`
## Tree-sitter grammar configuration ## Tree-sitter grammar configuration
The source for a language's tree-sitter grammar is specified in a `[[grammar]]` The source for a language's tree-sitter grammar is specified in a `[[grammar]]`

@ -1,18 +1,18 @@
# Key Remapping # Key remapping
One-way key remapping is temporarily supported via a simple TOML configuration Helix currently supports one-way key remapping through a simple TOML configuration
file. (More powerful solutions such as rebinding via commands will be file. (More powerful solutions such as rebinding via commands will be
available in the future). available in the future).
To remap keys, write a `config.toml` file in your `helix` configuration To remap keys, create a `config.toml` file in your `helix` configuration
directory (default `~/.config/helix` in Linux systems) with a structure like directory (default `~/.config/helix` on Linux systems) with a structure like
this: this:
```toml ```toml
# At most one section each of 'keys.normal', 'keys.insert' and 'keys.select' # At most one section each of 'keys.normal', 'keys.insert' and 'keys.select'
[keys.normal] [keys.normal]
C-s = ":w" # Maps the Ctrl-s to the typable command :w which is an alias for :write (save file) C-s = ":w" # Maps Ctrl-s to the typable command :w which is an alias for :write (save file)
C-o = ":open ~/.config/helix/config.toml" # Maps the Ctrl-o to opening of the helix config file C-o = ":open ~/.config/helix/config.toml" # Maps Ctrl-o to opening of the helix config file
a = "move_char_left" # Maps the 'a' key to the move_char_left command a = "move_char_left" # Maps the 'a' key to the move_char_left command
w = "move_line_up" # Maps the 'w' key move_line_up w = "move_line_up" # Maps the 'w' key move_line_up
"C-S-esc" = "extend_line" # Maps Ctrl-Shift-Escape to extend_line "C-S-esc" = "extend_line" # Maps Ctrl-Shift-Escape to extend_line
@ -23,7 +23,32 @@ g = { a = "code_action" } # Maps `ga` to show possible code actions
"A-x" = "normal_mode" # Maps Alt-X to enter normal mode "A-x" = "normal_mode" # Maps Alt-X to enter normal mode
j = { k = "normal_mode" } # Maps `jk` to exit insert mode j = { k = "normal_mode" } # Maps `jk` to exit insert mode
``` ```
> NOTE: Typable commands can also be remapped, remember to keep the `:` prefix to indicate it's a typable command.
## Minor modes
Minor modes are accessed by pressing a key (usually from normal mode), giving access to dedicated bindings. Bindings
can be modified or added by nesting definitions.
```toml
[keys.insert.j]
k = "normal_mode" # Maps `jk` to exit insert mode
[keys.normal.g]
a = "code_action" # Maps `ga` to show possible code actions
# invert `j` and `k` in view mode
[keys.normal.z]
j = "scroll_up"
k = "scroll_down"
# create a new minor mode bound to `+`
[keys.normal."+"]
m = ":run-shell-command make"
c = ":run-shell-command cargo build"
t = ":run-shell-command cargo test"
```
## Special keys and modifiers
Ctrl, Shift and Alt modifiers are encoded respectively with the prefixes Ctrl, Shift and Alt modifiers are encoded respectively with the prefixes
`C-`, `S-` and `A-`. Special keys are encoded as follows: `C-`, `S-` and `A-`. Special keys are encoded as follows:
@ -50,5 +75,5 @@ Ctrl, Shift and Alt modifiers are encoded respectively with the prefixes
Keys can be disabled by binding them to the `no_op` command. Keys can be disabled by binding them to the `no_op` command.
Commands can be found at [Keymap](https://docs.helix-editor.com/keymap.html) Commands. A list of commands is available in the [Keymap](https://docs.helix-editor.com/keymap.html) documentation
> Commands can also be found in the source code at [`helix-term/src/commands.rs`](https://github.com/helix-editor/helix/blob/master/helix-term/src/commands.rs) at the invocation of `static_commands!` macro and the `TypableCommandList`. and in the source code at [`helix-term/src/commands.rs`](https://github.com/helix-editor/helix/blob/master/helix-term/src/commands.rs) at the invocation of `static_commands!` macro and the `TypableCommandList`.

@ -1,14 +1,15 @@
# Themes # Themes
To use a theme add `theme = "<name>"` to your [`config.toml`](./configuration.md) at the very top of the file before the first section or select it during runtime using `:theme <name>`. To use a theme add `theme = "<name>"` to the top of your [`config.toml`](./configuration.md) file, or select it during runtime using `:theme <name>`.
## Creating a theme ## Creating a theme
Create a file with the name of your theme as file name (i.e `mytheme.toml`) and place it in your `themes` directory (i.e `~/.config/helix/themes`). The directory might have to be created beforehand. Create a file with the name of your theme as the file name (i.e `mytheme.toml`) and place it in your `themes` directory (i.e `~/.config/helix/themes` or `%AppData%\helix\themes` on Windows). The directory might have to be created beforehand.
The names "default" and "base16_default" are reserved for the builtin themes and cannot be overridden by user defined themes. > 💡 The names "default" and "base16_default" are reserved for built-in themes
> and cannot be overridden by user-defined themes.
The default theme.toml can be found [here](https://github.com/helix-editor/helix/blob/master/theme.toml), and user submitted themes [here](https://github.com/helix-editor/helix/blob/master/runtime/themes). ### Overview
Each line in the theme file is specified as below: Each line in the theme file is specified as below:
@ -16,7 +17,7 @@ Each line in the theme file is specified as below:
key = { fg = "#ffffff", bg = "#000000", underline = { color = "#ff0000", style = "curl"}, modifiers = ["bold", "italic"] } key = { fg = "#ffffff", bg = "#000000", underline = { color = "#ff0000", style = "curl"}, modifiers = ["bold", "italic"] }
``` ```
where `key` represents what you want to style, `fg` specifies the foreground color, `bg` the background color, `underline` the underline `style`/`color`, and `modifiers` is a list of style modifiers. `bg`, `underline` and `modifiers` can be omitted to defer to the defaults. Where `key` represents what you want to style, `fg` specifies the foreground color, `bg` the background color, `underline` the underline `style`/`color`, and `modifiers` is a list of style modifiers. `bg`, `underline` and `modifiers` can be omitted to defer to the defaults.
To specify only the foreground color: To specify only the foreground color:
@ -24,15 +25,30 @@ To specify only the foreground color:
key = "#ffffff" key = "#ffffff"
``` ```
if the key contains a dot `'.'`, it must be quoted to prevent it being parsed as a [dotted key](https://toml.io/en/v1.0.0#keys). If the key contains a dot `'.'`, it must be quoted to prevent it being parsed as a [dotted key](https://toml.io/en/v1.0.0#keys).
```toml ```toml
"key.key" = "#ffffff" "key.key" = "#ffffff"
``` ```
For inspiration, you can find the default `theme.toml`
[here](https://github.com/helix-editor/helix/blob/master/theme.toml) and
user-submitted themes
[here](https://github.com/helix-editor/helix/blob/master/runtime/themes).
### Using the linter
Use the supplied linting tool to check for errors and missing scopes:
```sh
cargo xtask themelint onedark # replace onedark with <name>
```
## The details of theme creation
### Color palettes ### Color palettes
It's recommended define a palette of named colors, and refer to them from the It's recommended to define a palette of named colors, and refer to them in the
configuration values in your theme. To do this, add a table called configuration values in your theme. To do this, add a table called
`palette` to your theme file: `palette` to your theme file:
@ -45,8 +61,8 @@ white = "#ffffff"
black = "#000000" black = "#000000"
``` ```
Remember that the `[palette]` table includes all keys after its header, Keep in mind that the `[palette]` table includes all keys after its header,
so you should define the palette after normal theme options. so it should be defined after the normal theme options.
The default palette uses the terminal's default 16 colors, and the colors names The default palette uses the terminal's default 16 colors, and the colors names
are listed below. The `[palette]` section in the config file takes precedence are listed below. The `[palette]` section in the config file takes precedence
@ -54,6 +70,7 @@ over it and is merged into the default palette.
| Color Name | | Color Name |
| --- | | --- |
| `default` |
| `black` | | `black` |
| `red` | | `red` |
| `green` | | `green` |
@ -73,9 +90,8 @@ over it and is merged into the default palette.
### Modifiers ### Modifiers
The following values may be used as modifiers. The following values may be used as modifier, provided they are supported by
your terminal emulator.
Less common modifiers might not be supported by your terminal emulator.
| Modifier | | Modifier |
| --- | | --- |
@ -89,27 +105,26 @@ Less common modifiers might not be supported by your terminal emulator.
| `hidden` | | `hidden` |
| `crossed_out` | | `crossed_out` |
> Note: The `underlined` modifier is deprecated and only available for backwards compatibility. > 💡 The `underlined` modifier is deprecated and only available for backwards compatibility.
> Its behavior is equivalent to setting `underline.style="line"`. > Its behavior is equivalent to setting `underline.style="line"`.
### Underline Style ### Underline style
One of the following values may be used as a value for `underline.style`. One of the following values may be used as a value for `underline.style`, providing it is
supported by your terminal emulator.
Some styles might not be supported by your terminal emulator.
| Modifier | | Modifier |
| --- | | --- |
| `line` | | `line` |
| `curl` | | `curl` |
| `dashed` | | `dashed` |
| `dot` | | `dotted` |
| `double_line` | | `double_line` |
### Inheritance ### Inheritance
Extend upon other themes by setting the `inherits` property to an existing theme. Extend other themes by setting the `inherits` property to an existing theme.
```toml ```toml
inherits = "boo_berry" inherits = "boo_berry"
@ -124,25 +139,28 @@ berry = "#2A2A4D"
### Scopes ### Scopes
The following is a list of scopes available to use for styling. The following is a list of scopes available to use for styling:
#### Syntax highlighting #### Syntax highlighting
These keys match [tree-sitter scopes](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#theme). These keys match [tree-sitter scopes](https://tree-sitter.github.io/tree-sitter/syntax-highlighting#theme).
For a given highlight produced, styling will be determined based on the longest matching theme key. For example, the highlight `function.builtin.static` would match the key `function.builtin` rather than `function`. When determining styling for a highlight, the longest matching theme key will be used. For example, if the highlight is `function.builtin.static`, the key `function.builtin` will be used instead of `function`.
We use a similar set of scopes as We use a similar set of scopes as
[Sublime Text](https://www.sublimetext.com/docs/scope_naming.html). See also [Sublime Text](https://www.sublimetext.com/docs/scope_naming.html). See also
[TextMate](https://macromates.com/manual/en/language_grammars) scopes. [TextMate](https://macromates.com/manual/en/language_grammars) scopes.
- `attribute` - Class attributes, html tag attributes - `attribute` - Class attributes, HTML tag attributes
- `type` - Types - `type` - Types
- `builtin` - Primitive types provided by the language (`int`, `usize`) - `builtin` - Primitive types provided by the language (`int`, `usize`)
- `parameter` - Generic type parameters (`T`)
- `enum`
- `variant`
- `constructor` - `constructor`
- `constant` (TODO: constant.other.placeholder for %v) - `constant` (TODO: constant.other.placeholder for `%v`)
- `builtin` Special constants provided by the language (`true`, `false`, `nil` etc) - `builtin` Special constants provided by the language (`true`, `false`, `nil` etc)
- `boolean` - `boolean`
- `character` - `character`
@ -164,7 +182,7 @@ We use a similar set of scopes as
- `documentation` - Documentation comments (e.g. `///` in Rust) - `documentation` - Documentation comments (e.g. `///` in Rust)
- `variable` - Variables - `variable` - Variables
- `builtin` - Reserved language variables (`self`, `this`, `super`, etc) - `builtin` - Reserved language variables (`self`, `this`, `super`, etc.)
- `parameter` - Function parameters - `parameter` - Function parameters
- `other` - `other`
- `member` - Fields of composite data types (e.g. structs, unions) - `member` - Fields of composite data types (e.g. structs, unions)
@ -199,9 +217,12 @@ We use a similar set of scopes as
- `special` (preprocessor in C) - `special` (preprocessor in C)
- `tag` - Tags (e.g. `<body>` in HTML) - `tag` - Tags (e.g. `<body>` in HTML)
- `builtin`
- `namespace` - `namespace`
- `special`
- `markup` - `markup`
- `heading` - `heading`
- `marker` - `marker`
@ -209,12 +230,15 @@ We use a similar set of scopes as
- `list` - `list`
- `unnumbered` - `unnumbered`
- `numbered` - `numbered`
- `checked`
- `unchecked`
- `bold` - `bold`
- `italic` - `italic`
- `strikethrough`
- `link` - `link`
- `url` - urls pointed to by links - `url` - URLs pointed to by links
- `label` - non-url link references - `label` - non-URL link references
- `text` - url and image descriptions in links - `text` - URL and image descriptions in links
- `quote` - `quote`
- `raw` - `raw`
- `inline` - `inline`
@ -222,25 +246,28 @@ We use a similar set of scopes as
- `diff` - version control changes - `diff` - version control changes
- `plus` - additions - `plus` - additions
- `gutter` - gutter indicator
- `minus` - deletions - `minus` - deletions
- `gutter` - gutter indicator
- `delta` - modifications - `delta` - modifications
- `moved` - renamed or moved files/changes - `moved` - renamed or moved files/changes
- `gutter` - gutter indicator
#### Interface #### Interface
These scopes are used for theming the editor interface. These scopes are used for theming the editor interface:
- `markup` - `markup`
- `normal` - `normal`
- `completion` - for completion doc popup ui - `completion` - for completion doc popup UI
- `hover` - for hover popup ui - `hover` - for hover popup UI
- `heading` - `heading`
- `completion` - for completion doc popup ui - `completion` - for completion doc popup UI
- `hover` - for hover popup ui - `hover` - for hover popup UI
- `raw` - `raw`
- `inline` - `inline`
- `completion` - for completion doc popup ui - `completion` - for completion doc popup UI
- `hover` - for hover popup ui - `hover` - for hover popup UI
| Key | Notes | | Key | Notes |
@ -248,12 +275,19 @@ These scopes are used for theming the editor interface.
| `ui.background` | | | `ui.background` | |
| `ui.background.separator` | Picker separator below input line | | `ui.background.separator` | Picker separator below input line |
| `ui.cursor` | | | `ui.cursor` | |
| `ui.cursor.normal` | |
| `ui.cursor.insert` | | | `ui.cursor.insert` | |
| `ui.cursor.select` | | | `ui.cursor.select` | |
| `ui.cursor.match` | Matching bracket etc. | | `ui.cursor.match` | Matching bracket etc. |
| `ui.cursor.primary` | Cursor with primary selection | | `ui.cursor.primary` | Cursor with primary selection |
| `ui.cursor.primary.normal` | |
| `ui.cursor.primary.insert` | |
| `ui.cursor.primary.select` | |
| `ui.debug.breakpoint` | Breakpoint indicator, found in the gutter |
| `ui.debug.active` | Indicator for the line at which debugging execution is paused at, found in the gutter |
| `ui.gutter` | Gutter | | `ui.gutter` | Gutter |
| `ui.gutter.selected` | Gutter for the line the cursor is on | | `ui.gutter.selected` | Gutter for the line the cursor is on |
| `ui.highlight.frameline` | Line at which debugging execution is paused at |
| `ui.linenr` | Line numbers | | `ui.linenr` | Line numbers |
| `ui.linenr.selected` | Line number for the line the cursor is on | | `ui.linenr.selected` | Line number for the line the cursor is on |
| `ui.statusline` | Statusline | | `ui.statusline` | Statusline |
@ -262,21 +296,30 @@ These scopes are used for theming the editor interface.
| `ui.statusline.insert` | Statusline mode during insert mode ([only if `editor.color-modes` is enabled][editor-section]) | | `ui.statusline.insert` | Statusline mode during insert mode ([only if `editor.color-modes` is enabled][editor-section]) |
| `ui.statusline.select` | Statusline mode during select mode ([only if `editor.color-modes` is enabled][editor-section]) | | `ui.statusline.select` | Statusline mode during select mode ([only if `editor.color-modes` is enabled][editor-section]) |
| `ui.statusline.separator` | Separator character in statusline | | `ui.statusline.separator` | Separator character in statusline |
| `ui.popup` | Documentation popups (e.g Space + k) | | `ui.bufferline` | Style for the buffer line |
| `ui.bufferline.active` | Style for the active buffer in buffer line |
| `ui.bufferline.background` | Style for bufferline background |
| `ui.popup` | Documentation popups (e.g. Space + k) |
| `ui.popup.info` | Prompt for multiple key options | | `ui.popup.info` | Prompt for multiple key options |
| `ui.window` | Borderlines separating splits | | `ui.window` | Borderlines separating splits |
| `ui.help` | Description box for commands | | `ui.help` | Description box for commands |
| `ui.text` | Command prompts, popup text, etc. | | `ui.text` | Default text style, command prompts, popup text, etc. |
| `ui.text.focus` | | | `ui.text.focus` | The currently selected line in the picker |
| `ui.text.inactive` | Same as `ui.text` but when the text is inactive (e.g. suggestions) |
| `ui.text.info` | The key: command text in `ui.popup.info` boxes | | `ui.text.info` | The key: command text in `ui.popup.info` boxes |
| `ui.virtual.ruler` | Ruler columns (see the [`editor.rulers` config][editor-section]) | | `ui.virtual.ruler` | Ruler columns (see the [`editor.rulers` config][editor-section]) |
| `ui.virtual.whitespace` | Visible whitespace characters | | `ui.virtual.whitespace` | Visible whitespace characters |
| `ui.virtual.indent-guide` | Vertical indent width guides | | `ui.virtual.indent-guide` | Vertical indent width guides |
| `ui.virtual.inlay-hint` | Default style for inlay hints of all kinds |
| `ui.virtual.inlay-hint.parameter` | Style for inlay hints of kind `parameter` (LSPs are not required to set a kind) |
| `ui.virtual.inlay-hint.type` | Style for inlay hints of kind `type` (LSPs are not required to set a kind) |
| `ui.virtual.wrap` | Soft-wrap indicator (see the [`editor.soft-wrap` config][editor-section]) |
| `ui.menu` | Code and command completion menus | | `ui.menu` | Code and command completion menus |
| `ui.menu.selected` | Selected autocomplete item | | `ui.menu.selected` | Selected autocomplete item |
| `ui.menu.scroll` | `fg` sets thumb color, `bg` sets track color of scrollbar | | `ui.menu.scroll` | `fg` sets thumb color, `bg` sets track color of scrollbar |
| `ui.selection` | For selections in the editing area | | `ui.selection` | For selections in the editing area |
| `ui.selection.primary` | | | `ui.selection.primary` | |
| `ui.highlight` | Highlighted lines in the picker preview |
| `ui.cursorline.primary` | The line of the primary cursor ([if cursorline is enabled][editor-section]) | | `ui.cursorline.primary` | The line of the primary cursor ([if cursorline is enabled][editor-section]) |
| `ui.cursorline.secondary` | The lines of any other cursors ([if cursorline is enabled][editor-section]) | | `ui.cursorline.secondary` | The lines of any other cursors ([if cursorline is enabled][editor-section]) |
| `ui.cursorcolumn.primary` | The column of the primary cursor ([if cursorcolumn is enabled][editor-section]) | | `ui.cursorcolumn.primary` | The column of the primary cursor ([if cursorcolumn is enabled][editor-section]) |
@ -291,10 +334,4 @@ These scopes are used for theming the editor interface.
| `diagnostic.warning` | Diagnostics warning (editing area) | | `diagnostic.warning` | Diagnostics warning (editing area) |
| `diagnostic.error` | Diagnostics error (editing area) | | `diagnostic.error` | Diagnostics error (editing area) |
You can check compliance to spec with
```shell
cargo xtask themelint onedark # replace onedark with <name>
```
[editor-section]: ./configuration.md#editor-section [editor-section]: ./configuration.md#editor-section

@ -1,65 +1,151 @@
# Usage # Using Helix
(Currently not fully documented, see the [keymappings](./keymap.md) list for more.) <!--toc:start-->
- [Registers](#registers)
- [User-defined registers](#user-defined-registers)
- [Special registers](#special-registers)
- [Surround](#surround)
- [Selecting and manipulating text with textobjects](#selecting-and-manipulating-text-with-textobjects)
- [Navigating using tree-sitter textobjects](#navigating-using-tree-sitter-textobjects)
- [Moving the selection with syntax-aware motions](#moving-the-selection-with-syntax-aware-motions)
<!--toc:end-->
See [tutor](https://github.com/helix-editor/helix/blob/master/runtime/tutor) (accessible via `hx --tutor` or `:tutor`) for a vimtutor-like introduction. For a full interactive introduction to Helix, refer to the
[tutor](https://github.com/helix-editor/helix/blob/master/runtime/tutor) which
can be accessed via the command `hx --tutor` or `:tutor`.
> 💡 Currently, not all functionality is fully documented, please refer to the
> [key mappings](./keymap.md) list.
## Registers ## Registers
Vim-like registers can be used to yank and store text to be pasted later. Usage is similar, with `"` being used to select a register: 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`. - `"ay` - Yank the current selection to register `a`.
- `"op` - Paste the text in register `o` after the selection. - `"op` - Paste the text in register `o` after the selection.
If there is a selected register before invoking a change or delete command, the selection will be stored in the register and the action will be carried out: 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). - `"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. - `"md` - Store the selection in register `m` and delete it.
### Special Registers ### 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 | | Register character | Contains |
| --- | --- | | --- | --- |
| `/` | Last search | | `/` | Last search |
| `:` | Last executed command | | `:` | Last executed command |
| `"` | Last yanked text | | `"` | Last yanked text |
| `_` | Black hole | | `@` | Last recorded macro |
### Special registers
> There is no special register for copying to system clipboard, instead special commands and keybindings are provided. See the [keymap](keymap.md#space-mode) for the specifics. Some registers have special behavior when read from and written to.
> The black hole register works as a no-op register, meaning no data will be written to / read from it.
| Register character | When read | When written |
| --- | --- | --- |
| `_` | No values are returned | All values are discarded |
| `#` | Selection indices (first selection is `1`, second is `2`, etc.) | This register is not writable |
| `.` | Contents of the current selections | This register is not writable |
| `%` | Name of the current file | This register is not writable |
| `+` | Reads from the system clipboard | Joins and yanks to the system clipboard |
| `*` | Reads from the primary clipboard | Joins and yanks to the primary clipboard |
When yanking multiple selections to the clipboard registers, the selections
are joined with newlines. Pasting from these registers will paste multiple
selections if the clipboard was last yanked to by the Helix session. Otherwise
the clipboard contents are pasted as one selection.
## Surround ## Surround
Functionality similar to [vim-surround](https://github.com/tpope/vim-surround) is built into Helix includes built-in functionality similar to [vim-surround](https://github.com/tpope/vim-surround).
helix. The keymappings have been inspired from [vim-sandwich](https://github.com/machakann/vim-sandwich): 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) ![Surround demo](https://user-images.githubusercontent.com/23398472/122865801-97073180-d344-11eb-8142-8f43809982c6.gif)
- `ms` - Add surround characters | Key Sequence | Action |
- `mr` - Replace surround characters | --------------------------------- | --------------------------------------- |
- `md` - Delete surround characters | `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 |
`ms` acts on a selection, so select the text first and use `ms<char>`. `mr` and `md` work You can use counts to act on outer pairs.
on the closest pairs found and selections are not required; use counts to act in outer pairs.
It can also act on multiple selections (yay!). For example, to change every occurrence of `(use)` to `[use]`: Surround can also act on multiple selections. For example, to change every occurrence of `(use)` to `[use]`:
- `%` to select the whole file 1. `%` to select the whole file
- `s` to split the selections on a search term 2. `s` to split the selections on a search term
- Input `use` and hit Enter 3. Input `use` and hit Enter
- `mr([` to replace the parens with square brackets 4. `mr([` to replace the parentheses with square brackets
Multiple characters are currently not supported, but planned. Multiple characters are currently not supported, but planned for future release.
## Syntax-tree Motions ## Selecting and manipulating text with textobjects
`Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) move the primary In Helix, textobjects are a way to select, manipulate and operate on a piece of
selection according to the selection's place in the syntax tree. Let's walk text in a structured way. They allow you to refer to blocks of text based on
through an example to get familiar with them. Many languages have a syntax like their structure or purpose, such as a word, sentence, paragraph, or even a
so for function calls: function or block of code.
``` ![Textobject demo](https://user-images.githubusercontent.com/23398472/124231131-81a4bb00-db2d-11eb-9d10-8e577ca7b177.gif)
func(arg1, arg2, arg3) ![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] currently have the query file implemented.
Contributions are welcome!
## Navigating using tree-sitter textobjects
Navigating between functions, classes, parameters, and other elements is
possible using tree-sitter and textobject queries. For
example to move to the next function use `]f`, to move to previous
type use `[t`, and so on.
![Tree-sitter-nav-demo][tree-sitter-nav-demo]
For the full reference see the [unimpaired][unimpaired-keybinds] section of the key bind
documentation.
> 💡 This feature relies on tree-sitter textobjects
> and requires the corresponding query file to work properly.
## Moving the selection with syntax-aware motions
`Alt-p`, `Alt-o`, `Alt-i`, and `Alt-n` (or `Alt` and arrow keys) allow you to move the
selection according to its location in the syntax tree. For example, many languages have the
following syntax for function calls:
```js
func(arg1, arg2, arg3);
``` ```
A function call might be parsed by tree-sitter into a tree like the following. A function call might be parsed by tree-sitter into a tree like the following.
@ -93,77 +179,29 @@ a more intuitive tree format:
└──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
``` ```
Say we have a selection that wraps `arg1`. The selection is on the `arg1` leaf If you have a selection that wraps `arg1` (see the tree above), and you use
in the tree above. `Alt-n`, it will select the next sibling in the syntax tree: `arg2`.
``` ```js
// before
func([arg1], arg2, arg3) func([arg1], arg2, arg3)
// after
func(arg1, [arg2], arg3);
``` ```
Using `Alt-n` would select the next sibling in the syntax tree: `arg2`. Similarly, `Alt-o` will expand the selection to the parent node, in this case, the
arguments node.
``` ```js
func(arg1, [arg2], arg3) func[(arg1, arg2, arg3)];
```
While `Alt-o` would expand the selection to the parent node. In the tree above we
can see that we would select the `arguments` node.
```
func[(arg1, arg2, arg3)]
``` ```
There is also some nuanced behavior that prevents you from getting stuck on a There is also some nuanced behavior that prevents you from getting stuck on a
node with no sibling. If we have a selection on `arg1`, `Alt-p` would bring us node with no sibling. When using `Alt-p` with a selection on `arg1`, the previous
to the previous child node. Since `arg1` doesn't have a sibling to its left, child node will be selected. In the event that `arg1` does not have a previous
though, we climb the syntax tree and then take the previous selection. So sibling, the selection will move up the syntax tree and select the previous
`Alt-p` will move the selection over to the "func" `identifier`. element. As a result, using `Alt-p` with a selection on `arg1` will move the
selection to the "func" `identifier`.
```
[func](arg1, arg2, arg3)
```
## Textobjects
![textobject-demo](https://user-images.githubusercontent.com/23398472/124231131-81a4bb00-db2d-11eb-9d10-8e577ca7b177.gif)
![textobject-treesitter-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` | Closest surround pair |
| `f` | Function |
| `c` | Class |
| `a` | Argument/parameter |
| `o` | Comment |
| `t` | Test |
| `g` | Change |
> NOTE: `f`, `c`, etc need a tree-sitter grammar active for the current
document and a special tree-sitter query file to work properly. [Only
some grammars][lang-support] currently have the query file implemented.
Contributions are welcome!
## Tree-sitter Textobject Based Navigation
Navigating between functions, classes, parameters, etc is made
possible by leveraging tree-sitter and textobjects queries. For
example to move to the next function use `]f`, to move to previous
class use `[c`, and so on.
![tree-sitter-nav-demo][tree-sitter-nav-demo]
See the [unimpaired][unimpaired-keybinds] section of the keybind
documentation for the full reference.
> NOTE: This feature is dependent on tree-sitter based textobjects
and therefore requires the corresponding query file to work properly.
[lang-support]: ./lang-support.md [lang-support]: ./lang-support.md
[unimpaired-keybinds]: ./keymap.md#unimpaired [unimpaired-keybinds]: ./keymap.md#unimpaired

@ -1,660 +0,0 @@
"use strict";
// Fix back button cache problem
window.onunload = function () { };
// Global variable, shared between modules
function playground_text(playground) {
let code_block = playground.querySelector("code");
if (window.ace && code_block.classList.contains("editable")) {
let editor = window.ace.edit(code_block);
return editor.getValue();
} else {
return code_block.textContent;
}
}
(function codeSnippets() {
function fetch_with_timeout(url, options, timeout = 6000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
]);
}
var playgrounds = Array.from(document.querySelectorAll(".playground"));
if (playgrounds.length > 0) {
fetch_with_timeout("https://play.rust-lang.org/meta/crates", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
})
.then(response => response.json())
.then(response => {
// get list of crates available in the rust playground
let playground_crates = response.crates.map(item => item["id"]);
playgrounds.forEach(block => handle_crate_list_update(block, playground_crates));
});
}
function handle_crate_list_update(playground_block, playground_crates) {
// update the play buttons after receiving the response
update_play_button(playground_block, playground_crates);
// and install on change listener to dynamically update ACE editors
if (window.ace) {
let code_block = playground_block.querySelector("code");
if (code_block.classList.contains("editable")) {
let editor = window.ace.edit(code_block);
editor.addEventListener("change", function (e) {
update_play_button(playground_block, playground_crates);
});
// add Ctrl-Enter command to execute rust code
editor.commands.addCommand({
name: "run",
bindKey: {
win: "Ctrl-Enter",
mac: "Ctrl-Enter"
},
exec: _editor => run_rust_code(playground_block)
});
}
}
}
// updates the visibility of play button based on `no_run` class and
// used crates vs ones available on http://play.rust-lang.org
function update_play_button(pre_block, playground_crates) {
var play_button = pre_block.querySelector(".play-button");
// skip if code is `no_run`
if (pre_block.querySelector('code').classList.contains("no_run")) {
play_button.classList.add("hidden");
return;
}
// get list of `extern crate`'s from snippet
var txt = playground_text(pre_block);
var re = /extern\s+crate\s+([a-zA-Z_0-9]+)\s*;/g;
var snippet_crates = [];
var item;
while (item = re.exec(txt)) {
snippet_crates.push(item[1]);
}
// check if all used crates are available on play.rust-lang.org
var all_available = snippet_crates.every(function (elem) {
return playground_crates.indexOf(elem) > -1;
});
if (all_available) {
play_button.classList.remove("hidden");
} else {
play_button.classList.add("hidden");
}
}
function run_rust_code(code_block) {
var result_block = code_block.querySelector(".result");
if (!result_block) {
result_block = document.createElement('code');
result_block.className = 'result hljs language-bash';
code_block.append(result_block);
}
let text = playground_text(code_block);
let classes = code_block.querySelector('code').classList;
let has_2018 = classes.contains("edition2018");
let edition = has_2018 ? "2018" : "2015";
var params = {
version: "stable",
optimize: "0",
code: text,
edition: edition
};
if (text.indexOf("#![feature") !== -1) {
params.version = "nightly";
}
result_block.innerText = "Running...";
fetch_with_timeout("https://play.rust-lang.org/evaluate.json", {
headers: {
'Content-Type': "application/json",
},
method: 'POST',
mode: 'cors',
body: JSON.stringify(params)
})
.then(response => response.json())
.then(response => result_block.innerText = response.result)
.catch(error => result_block.innerText = "Playground Communication: " + error.message);
}
// Syntax highlighting Configuration
hljs.configure({
tabReplace: ' ', // 4 spaces
languages: [], // Languages used for auto-detection
});
let code_nodes = Array
.from(document.querySelectorAll('code'))
// Don't highlight `inline code` blocks in headers.
.filter(function (node) {return !node.parentElement.classList.contains("header"); });
if (window.ace) {
// language-rust class needs to be removed for editable
// blocks or highlightjs will capture events
Array
.from(document.querySelectorAll('code.editable'))
.forEach(function (block) { block.classList.remove('language-rust'); });
Array
.from(document.querySelectorAll('code:not(.editable)'))
.forEach(function (block) { hljs.highlightBlock(block); });
} else {
code_nodes.forEach(function (block) { hljs.highlightBlock(block); });
}
// Adding the hljs class gives code blocks the color css
// even if highlighting doesn't apply
code_nodes.forEach(function (block) { block.classList.add('hljs'); });
Array.from(document.querySelectorAll("code.language-rust")).forEach(function (block) {
var lines = Array.from(block.querySelectorAll('.boring'));
// If no lines were hidden, return
if (!lines.length) { return; }
block.classList.add("hide-boring");
var buttons = document.createElement('div');
buttons.className = 'buttons';
buttons.innerHTML = "<button class=\"fa fa-eye\" title=\"Show hidden lines\" aria-label=\"Show hidden lines\"></button>";
// add expand button
var pre_block = block.parentNode;
pre_block.insertBefore(buttons, pre_block.firstChild);
pre_block.querySelector('.buttons').addEventListener('click', function (e) {
if (e.target.classList.contains('fa-eye')) {
e.target.classList.remove('fa-eye');
e.target.classList.add('fa-eye-slash');
e.target.title = 'Hide lines';
e.target.setAttribute('aria-label', e.target.title);
block.classList.remove('hide-boring');
} else if (e.target.classList.contains('fa-eye-slash')) {
e.target.classList.remove('fa-eye-slash');
e.target.classList.add('fa-eye');
e.target.title = 'Show hidden lines';
e.target.setAttribute('aria-label', e.target.title);
block.classList.add('hide-boring');
}
});
});
if (window.playground_copyable) {
Array.from(document.querySelectorAll('pre code')).forEach(function (block) {
var pre_block = block.parentNode;
if (!pre_block.classList.contains('playground')) {
var buttons = pre_block.querySelector(".buttons");
if (!buttons) {
buttons = document.createElement('div');
buttons.className = 'buttons';
pre_block.insertBefore(buttons, pre_block.firstChild);
}
var clipButton = document.createElement('button');
clipButton.className = 'fa fa-copy clip-button';
clipButton.title = 'Copy to clipboard';
clipButton.setAttribute('aria-label', clipButton.title);
clipButton.innerHTML = '<i class=\"tooltiptext\"></i>';
buttons.insertBefore(clipButton, buttons.firstChild);
}
});
}
// Process playground code blocks
Array.from(document.querySelectorAll(".playground")).forEach(function (pre_block) {
// Add play button
var buttons = pre_block.querySelector(".buttons");
if (!buttons) {
buttons = document.createElement('div');
buttons.className = 'buttons';
pre_block.insertBefore(buttons, pre_block.firstChild);
}
var runCodeButton = document.createElement('button');
runCodeButton.className = 'fa fa-play play-button';
runCodeButton.hidden = true;
runCodeButton.title = 'Run this code';
runCodeButton.setAttribute('aria-label', runCodeButton.title);
buttons.insertBefore(runCodeButton, buttons.firstChild);
runCodeButton.addEventListener('click', function (e) {
run_rust_code(pre_block);
});
if (window.playground_copyable) {
var copyCodeClipboardButton = document.createElement('button');
copyCodeClipboardButton.className = 'fa fa-copy clip-button';
copyCodeClipboardButton.innerHTML = '<i class="tooltiptext"></i>';
copyCodeClipboardButton.title = 'Copy to clipboard';
copyCodeClipboardButton.setAttribute('aria-label', copyCodeClipboardButton.title);
buttons.insertBefore(copyCodeClipboardButton, buttons.firstChild);
}
let code_block = pre_block.querySelector("code");
if (window.ace && code_block.classList.contains("editable")) {
var undoChangesButton = document.createElement('button');
undoChangesButton.className = 'fa fa-history reset-button';
undoChangesButton.title = 'Undo changes';
undoChangesButton.setAttribute('aria-label', undoChangesButton.title);
buttons.insertBefore(undoChangesButton, buttons.firstChild);
undoChangesButton.addEventListener('click', function () {
let editor = window.ace.edit(code_block);
editor.setValue(editor.originalCode);
editor.clearSelection();
});
}
});
})();
(function themes() {
var html = document.querySelector('html');
var themeToggleButton = document.getElementById('theme-toggle');
var themePopup = document.getElementById('theme-list');
var themeColorMetaTag = document.querySelector('meta[name="theme-color"]');
var stylesheets = {
ayuHighlight: document.querySelector("[href$='ayu-highlight.css']"),
tomorrowNight: document.querySelector("[href$='tomorrow-night.css']"),
highlight: document.querySelector("[href$='highlight.css']"),
};
function showThemes() {
themePopup.style.display = 'block';
themeToggleButton.setAttribute('aria-expanded', true);
themePopup.querySelector("button#" + get_theme()).focus();
}
function hideThemes() {
themePopup.style.display = 'none';
themeToggleButton.setAttribute('aria-expanded', false);
themeToggleButton.focus();
}
function get_theme() {
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch (e) { }
if (theme === null || theme === undefined) {
return default_theme;
} else {
return theme;
}
}
function set_theme(theme, store = true) {
let ace_theme;
if (theme == 'coal' || theme == 'navy') {
stylesheets.ayuHighlight.disabled = true;
stylesheets.tomorrowNight.disabled = false;
stylesheets.highlight.disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else if (theme == 'ayu') {
stylesheets.ayuHighlight.disabled = false;
stylesheets.tomorrowNight.disabled = true;
stylesheets.highlight.disabled = true;
ace_theme = "ace/theme/tomorrow_night";
} else {
stylesheets.ayuHighlight.disabled = true;
stylesheets.tomorrowNight.disabled = true;
stylesheets.highlight.disabled = false;
ace_theme = "ace/theme/dawn";
}
setTimeout(function () {
themeColorMetaTag.content = getComputedStyle(document.body).backgroundColor;
}, 1);
if (window.ace && window.editors) {
window.editors.forEach(function (editor) {
editor.setTheme(ace_theme);
});
}
var previousTheme = get_theme();
if (store) {
try { localStorage.setItem('mdbook-theme', theme); } catch (e) { }
}
html.classList.remove(previousTheme);
html.classList.add(theme);
}
// Set theme
var theme = get_theme();
set_theme(theme, false);
themeToggleButton.addEventListener('click', function () {
if (themePopup.style.display === 'block') {
hideThemes();
} else {
showThemes();
}
});
themePopup.addEventListener('click', function (e) {
var theme = e.target.id || e.target.parentElement.id;
set_theme(theme);
});
themePopup.addEventListener('focusout', function(e) {
// e.relatedTarget is null in Safari and Firefox on macOS (see workaround below)
if (!!e.relatedTarget && !themeToggleButton.contains(e.relatedTarget) && !themePopup.contains(e.relatedTarget)) {
hideThemes();
}
});
// Should not be needed, but it works around an issue on macOS & iOS: https://github.com/rust-lang/mdBook/issues/628
document.addEventListener('click', function(e) {
if (themePopup.style.display === 'block' && !themeToggleButton.contains(e.target) && !themePopup.contains(e.target)) {
hideThemes();
}
});
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
if (!themePopup.contains(e.target)) { return; }
switch (e.key) {
case 'Escape':
e.preventDefault();
hideThemes();
break;
case 'ArrowUp':
e.preventDefault();
var li = document.activeElement.parentElement;
if (li && li.previousElementSibling) {
li.previousElementSibling.querySelector('button').focus();
}
break;
case 'ArrowDown':
e.preventDefault();
var li = document.activeElement.parentElement;
if (li && li.nextElementSibling) {
li.nextElementSibling.querySelector('button').focus();
}
break;
case 'Home':
e.preventDefault();
themePopup.querySelector('li:first-child button').focus();
break;
case 'End':
e.preventDefault();
themePopup.querySelector('li:last-child button').focus();
break;
}
});
})();
(function sidebar() {
var html = document.querySelector("html");
var sidebar = document.getElementById("sidebar");
var sidebarLinks = document.querySelectorAll('#sidebar a');
var sidebarToggleButton = document.getElementById("sidebar-toggle");
var sidebarResizeHandle = document.getElementById("sidebar-resize-handle");
var firstContact = null;
function showSidebar() {
html.classList.remove('sidebar-hidden')
html.classList.add('sidebar-visible');
Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', 0);
});
sidebarToggleButton.setAttribute('aria-expanded', true);
sidebar.setAttribute('aria-hidden', false);
try { localStorage.setItem('mdbook-sidebar', 'visible'); } catch (e) { }
}
var sidebarAnchorToggles = document.querySelectorAll('#sidebar a.toggle');
function toggleSection(ev) {
ev.currentTarget.parentElement.classList.toggle('expanded');
}
Array.from(sidebarAnchorToggles).forEach(function (el) {
el.addEventListener('click', toggleSection);
});
function hideSidebar() {
html.classList.remove('sidebar-visible')
html.classList.add('sidebar-hidden');
Array.from(sidebarLinks).forEach(function (link) {
link.setAttribute('tabIndex', -1);
});
sidebarToggleButton.setAttribute('aria-expanded', false);
sidebar.setAttribute('aria-hidden', true);
try { localStorage.setItem('mdbook-sidebar', 'hidden'); } catch (e) { }
}
// Toggle sidebar
sidebarToggleButton.addEventListener('click', function sidebarToggle() {
if (html.classList.contains("sidebar-hidden")) {
var current_width = parseInt(
document.documentElement.style.getPropertyValue('--sidebar-width'), 10);
if (current_width < 150) {
document.documentElement.style.setProperty('--sidebar-width', '150px');
}
showSidebar();
} else if (html.classList.contains("sidebar-visible")) {
hideSidebar();
} else {
if (getComputedStyle(sidebar)['transform'] === 'none') {
hideSidebar();
} else {
showSidebar();
}
}
});
sidebarResizeHandle.addEventListener('mousedown', initResize, false);
function initResize(e) {
window.addEventListener('mousemove', resize, false);
window.addEventListener('mouseup', stopResize, false);
html.classList.add('sidebar-resizing');
}
function resize(e) {
var pos = (e.clientX - sidebar.offsetLeft);
if (pos < 20) {
hideSidebar();
} else {
if (html.classList.contains("sidebar-hidden")) {
showSidebar();
}
pos = Math.min(pos, window.innerWidth - 100);
document.documentElement.style.setProperty('--sidebar-width', pos + 'px');
}
}
//on mouseup remove windows functions mousemove & mouseup
function stopResize(e) {
html.classList.remove('sidebar-resizing');
window.removeEventListener('mousemove', resize, false);
window.removeEventListener('mouseup', stopResize, false);
}
document.addEventListener('touchstart', function (e) {
firstContact = {
x: e.touches[0].clientX,
time: Date.now()
};
}, { passive: true });
document.addEventListener('touchmove', function (e) {
if (!firstContact)
return;
var curX = e.touches[0].clientX;
var xDiff = curX - firstContact.x,
tDiff = Date.now() - firstContact.time;
if (tDiff < 250 && Math.abs(xDiff) >= 150) {
if (xDiff >= 0 && firstContact.x < Math.min(document.body.clientWidth * 0.25, 300))
showSidebar();
else if (xDiff < 0 && curX < 300)
hideSidebar();
firstContact = null;
}
}, { passive: true });
// Scroll sidebar to current active section
var activeSection = document.getElementById("sidebar").querySelector(".active");
if (activeSection) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
activeSection.scrollIntoView({ block: 'center' });
}
})();
(function chapterNavigation() {
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) { return; }
if (window.search && window.search.hasFocus()) { return; }
switch (e.key) {
case 'ArrowRight':
e.preventDefault();
var nextButton = document.querySelector('.nav-chapters.next');
if (nextButton) {
window.location.href = nextButton.href;
}
break;
case 'ArrowLeft':
e.preventDefault();
var previousButton = document.querySelector('.nav-chapters.previous');
if (previousButton) {
window.location.href = previousButton.href;
}
break;
}
});
})();
(function clipboard() {
var clipButtons = document.querySelectorAll('.clip-button');
function hideTooltip(elem) {
elem.firstChild.innerText = "";
elem.className = 'fa fa-copy clip-button';
}
function showTooltip(elem, msg) {
elem.firstChild.innerText = msg;
elem.className = 'fa fa-copy tooltipped';
}
var clipboardSnippets = new ClipboardJS('.clip-button', {
text: function (trigger) {
hideTooltip(trigger);
let playground = trigger.closest("pre");
return playground_text(playground);
}
});
Array.from(clipButtons).forEach(function (clipButton) {
clipButton.addEventListener('mouseout', function (e) {
hideTooltip(e.currentTarget);
});
});
clipboardSnippets.on('success', function (e) {
e.clearSelection();
showTooltip(e.trigger, "Copied!");
});
clipboardSnippets.on('error', function (e) {
showTooltip(e.trigger, "Clipboard error!");
});
})();
(function scrollToTop () {
var menuTitle = document.querySelector('.menu-title');
menuTitle.addEventListener('click', function () {
document.scrollingElement.scrollTo({ top: 0, behavior: 'smooth' });
});
})();
(function controlMenu() {
var menu = document.getElementById('menu-bar');
(function controlPosition() {
var scrollTop = document.scrollingElement.scrollTop;
var prevScrollTop = scrollTop;
var minMenuY = -menu.clientHeight - 50;
// When the script loads, the page can be at any scroll (e.g. if you reforesh it).
menu.style.top = scrollTop + 'px';
// Same as parseInt(menu.style.top.slice(0, -2), but faster
var topCache = menu.style.top.slice(0, -2);
menu.classList.remove('sticky');
var stickyCache = false; // Same as menu.classList.contains('sticky'), but faster
document.addEventListener('scroll', function () {
scrollTop = Math.max(document.scrollingElement.scrollTop, 0);
// `null` means that it doesn't need to be updated
var nextSticky = null;
var nextTop = null;
var scrollDown = scrollTop > prevScrollTop;
var menuPosAbsoluteY = topCache - scrollTop;
if (scrollDown) {
nextSticky = false;
if (menuPosAbsoluteY > 0) {
nextTop = prevScrollTop;
}
} else {
if (menuPosAbsoluteY > 0) {
nextSticky = true;
} else if (menuPosAbsoluteY < minMenuY) {
nextTop = prevScrollTop + minMenuY;
}
}
if (nextSticky === true && stickyCache === false) {
menu.classList.add('sticky');
stickyCache = true;
} else if (nextSticky === false && stickyCache === true) {
menu.classList.remove('sticky');
stickyCache = false;
}
if (nextTop !== null) {
menu.style.top = nextTop + 'px';
topCache = nextTop;
}
prevScrollTop = scrollTop;
}, { passive: true });
})();
(function controlBorder() {
menu.classList.remove('bordered');
document.addEventListener('scroll', function () {
if (menu.offsetTop === 0) {
menu.classList.remove('bordered');
} else {
menu.classList.add('bordered');
}
}, { passive: true });
})();
})();

@ -1,499 +0,0 @@
/* CSS for UI elements (a.k.a. chrome) */
@import 'variables.css';
::-webkit-scrollbar {
background: var(--bg);
}
::-webkit-scrollbar-thumb {
background: var(--scrollbar);
}
html {
scrollbar-color: var(--scrollbar) var(--bg);
}
#searchresults a,
.content a:link,
a:visited,
a > .hljs {
color: var(--links);
}
.content a:hover {
text-decoration: underline;
}
/* Menu Bar */
#menu-bar,
#menu-bar-hover-placeholder {
z-index: 101;
margin: auto calc(0px - var(--page-padding));
}
#menu-bar {
position: relative;
display: flex;
flex-wrap: wrap;
background-color: var(--bg);
border-bottom-color: var(--bg);
border-bottom-width: 1px;
border-bottom-style: solid;
}
#menu-bar.sticky,
.js #menu-bar-hover-placeholder:hover + #menu-bar,
.js #menu-bar:hover,
.js.sidebar-visible #menu-bar {
position: -webkit-sticky;
position: sticky;
top: 0 !important;
}
#menu-bar-hover-placeholder {
position: sticky;
position: -webkit-sticky;
top: 0;
height: var(--menu-bar-height);
}
#menu-bar.bordered {
border-bottom-color: var(--table-border-color);
}
#menu-bar i, #menu-bar .icon-button {
position: relative;
padding: 0 8px;
z-index: 10;
line-height: var(--menu-bar-height);
cursor: pointer;
transition: color 0.5s;
}
@media only screen and (max-width: 420px) {
#menu-bar i, #menu-bar .icon-button {
padding: 0 5px;
}
}
.icon-button {
border: none;
background: none;
padding: 0;
color: inherit;
}
.icon-button i {
margin: 0;
}
.right-buttons {
margin: 0 15px;
}
.right-buttons a {
text-decoration: none;
}
.left-buttons {
display: flex;
margin: 0 5px;
}
.no-js .left-buttons {
display: none;
}
.menu-title {
display: inline-block;
font-weight: 200;
font-size: 2.4rem;
line-height: var(--menu-bar-height);
text-align: center;
margin: 0;
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.js .menu-title {
cursor: pointer;
}
.menu-bar,
.menu-bar:visited,
.nav-chapters,
.nav-chapters:visited,
.mobile-nav-chapters,
.mobile-nav-chapters:visited,
.menu-bar .icon-button,
.menu-bar a i {
color: var(--icons);
}
.menu-bar i:hover,
.menu-bar .icon-button:hover,
.nav-chapters:hover,
.mobile-nav-chapters i:hover {
color: var(--icons-hover);
}
/* Nav Icons */
.nav-chapters {
font-size: 2.5em;
text-align: center;
text-decoration: none;
position: fixed;
top: 0;
bottom: 0;
margin: 0;
max-width: 150px;
min-width: 90px;
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
transition: color 0.5s, background-color 0.5s;
}
.nav-chapters:hover {
text-decoration: none;
background-color: var(--theme-hover);
transition: background-color 0.15s, color 0.15s;
}
.nav-wrapper {
margin-top: 50px;
display: none;
}
.mobile-nav-chapters {
font-size: 2.5em;
text-align: center;
text-decoration: none;
width: 90px;
border-radius: 5px;
background-color: var(--sidebar-bg);
}
.previous {
float: left;
}
.next {
float: right;
right: var(--page-padding);
}
@media only screen and (max-width: 1080px) {
.nav-wide-wrapper { display: none; }
.nav-wrapper { display: block; }
}
@media only screen and (max-width: 1380px) {
.sidebar-visible .nav-wide-wrapper { display: none; }
.sidebar-visible .nav-wrapper { display: block; }
}
/* Inline code */
:not(pre) > .hljs {
display: inline;
padding: 0.1em 0.3em;
border-radius: 3px;
}
:not(pre):not(a):not(td):not(p) > .hljs {
color: var(--inline-code-color);
overflow-x: initial;
}
a:hover > .hljs {
text-decoration: underline;
}
pre {
position: relative;
}
pre > .buttons {
position: absolute;
z-index: 100;
right: 5px;
top: 5px;
color: var(--sidebar-fg);
cursor: pointer;
}
pre > .buttons :hover {
color: var(--sidebar-active);
}
pre > .buttons i {
margin-left: 8px;
}
pre > .buttons button {
color: inherit;
background: transparent;
border: none;
cursor: inherit;
}
pre > .result {
margin-top: 10px;
}
/* Search */
#searchresults a {
text-decoration: none;
}
mark {
border-radius: 2px;
padding: 0 3px 1px 3px;
margin: 0 -3px -1px -3px;
background-color: var(--search-mark-bg);
transition: background-color 300ms linear;
cursor: pointer;
}
mark.fade-out {
background-color: rgba(0,0,0,0) !important;
cursor: auto;
}
.searchbar-outer {
margin-left: auto;
margin-right: auto;
max-width: var(--content-max-width);
}
#searchbar {
width: 100%;
margin: 5px auto 0px auto;
padding: 10px 16px;
transition: box-shadow 300ms ease-in-out;
border: 1px solid var(--searchbar-border-color);
border-radius: 3px;
background-color: var(--searchbar-bg);
color: var(--searchbar-fg);
}
#searchbar:focus,
#searchbar.active {
box-shadow: 0 0 3px var(--searchbar-shadow-color);
}
.searchresults-header {
font-weight: bold;
font-size: 1em;
padding: 18px 0 0 5px;
color: var(--searchresults-header-fg);
}
.searchresults-outer {
margin-left: auto;
margin-right: auto;
max-width: var(--content-max-width);
border-bottom: 1px dashed var(--searchresults-border-color);
}
ul#searchresults {
list-style: none;
padding-left: 20px;
}
ul#searchresults li {
margin: 10px 0px;
padding: 2px;
border-radius: 2px;
}
ul#searchresults li.focus {
background-color: var(--searchresults-li-bg);
}
ul#searchresults span.teaser {
display: block;
clear: both;
margin: 5px 0 0 20px;
font-size: 0.8em;
}
ul#searchresults span.teaser em {
font-weight: bold;
font-style: normal;
}
/* Sidebar */
.sidebar {
position: fixed;
left: 0;
top: 0;
bottom: 0;
width: var(--sidebar-width);
font-size: 0.875em;
box-sizing: border-box;
-webkit-overflow-scrolling: touch;
overscroll-behavior-y: contain;
background-color: var(--sidebar-bg);
color: var(--sidebar-fg);
}
.sidebar-resizing {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
.js:not(.sidebar-resizing) .sidebar {
transition: transform 0.3s; /* Animation: slide away */
}
.sidebar code {
line-height: 2em;
}
.sidebar .sidebar-scrollbox {
overflow-y: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.sidebar .sidebar-resize-handle {
position: absolute;
cursor: col-resize;
width: 0;
right: 0;
top: 0;
bottom: 0;
}
.js .sidebar .sidebar-resize-handle {
cursor: col-resize;
width: 5px;
}
.sidebar-hidden .sidebar {
transform: translateX(calc(0px - var(--sidebar-width)));
}
.sidebar::-webkit-scrollbar {
background: var(--sidebar-bg);
}
.sidebar::-webkit-scrollbar-thumb {
background: var(--scrollbar);
}
.sidebar-visible .page-wrapper {
transform: translateX(var(--sidebar-width));
}
@media only screen and (min-width: 620px) {
.sidebar-visible .page-wrapper {
transform: none;
margin-left: var(--sidebar-width);
}
}
.chapter {
list-style: none outside none;
padding-left: 0;
margin: .25rem 0;
}
.chapter ol {
width: 100%;
}
.chapter li {
display: flex;
color: var(--sidebar-non-existent);
}
.chapter li a {
display: block;
text-decoration: none;
color: var(--sidebar-fg);
}
.chapter li a:hover {
color: var(--sidebar-active);
}
.chapter li a.active {
color: var(--sidebar-active);
}
.chapter li > a.toggle {
cursor: pointer;
display: block;
margin-left: auto;
padding: 0 10px;
user-select: none;
opacity: 0.68;
}
.chapter li > a.toggle div {
transition: transform 0.5s;
}
/* collapse the section */
.chapter li:not(.expanded) + li > ol {
display: none;
}
.chapter li.chapter-item {
padding: 1rem 1.5rem;
}
.chapter .section li.chapter-item {
padding: .5rem .5rem 0 .5rem;
}
.chapter li.expanded > a.toggle div {
transform: rotate(90deg);
}
.spacer {
width: 100%;
height: 3px;
margin: 5px 0px;
}
.chapter .spacer {
background-color: var(--sidebar-spacer);
}
@media (-moz-touch-enabled: 1), (pointer: coarse) {
.chapter li a { padding: 5px 0; }
.spacer { margin: 10px 0; }
}
.section {
list-style: none outside none;
padding-left: 2rem;
line-height: 1.9em;
}
/* Theme Menu Popup */
.theme-popup {
position: absolute;
left: 10px;
top: var(--menu-bar-height);
z-index: 1000;
border-radius: 4px;
font-size: 0.7em;
color: var(--fg);
background: var(--theme-popup-bg);
border: 1px solid var(--theme-popup-border);
margin: 0;
padding: 0;
list-style: none;
display: none;
}
.theme-popup .default {
color: var(--icons);
}
.theme-popup .theme {
width: 100%;
border: 0;
margin: 0;
padding: 2px 10px;
line-height: 25px;
white-space: nowrap;
text-align: left;
cursor: pointer;
color: inherit;
background: inherit;
font-size: inherit;
}
.theme-popup .theme:hover {
background-color: var(--theme-hover);
}
.theme-popup .theme:hover:first-child,
.theme-popup .theme:hover:last-child {
border-top-left-radius: inherit;
border-top-right-radius: inherit;
}

@ -1,233 +0,0 @@
/* Base styles and content styles */
@import 'variables.css';
:root {
/* Browser default font-size is 16px, this way 1 rem = 10px */
font-size: 62.5%;
}
/* TODO: replace with self hosted fonts */
html {
font-family: "Inter", sans-serif;
color: var(--fg);
background-color: var(--bg);
text-size-adjust: none;
}
/* @supports (font-variation-settings: normal) { */
/* html { font-family: 'Inter var', sans-serif; } */
/* } */
body {
margin: 0;
font-size: 1.6rem;
overflow-x: hidden;
}
code {
font-family: "Source Code Pro", Consolas, "Ubuntu Mono", Menlo, "DejaVu Sans Mono", monospace, monospace !important;
font-size: 0.875em; /* please adjust the ace font size accordingly in editor.js */
}
/* Don't change font size in headers. */
h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
font-size: unset;
}
.left { float: left; }
.right { float: right; }
.boring { opacity: 0.6; }
.hide-boring .boring { display: none; }
.hidden { display: none !important; }
h2, h3 { margin-top: 2.5em; }
h4, h5 { margin-top: 2em; }
.header + .header h3,
.header + .header h4,
.header + .header h5 {
margin-top: 1em;
}
h1:target::before,
h2:target::before,
h3:target::before,
h4:target::before,
h5:target::before,
h6:target::before {
display: inline-block;
content: "»";
margin-left: -30px;
width: 30px;
}
/* This is broken on Safari as of version 14, but is fixed
in Safari Technology Preview 117 which I think will be Safari 14.2.
https://bugs.webkit.org/show_bug.cgi?id=218076
*/
:target {
scroll-margin-top: calc(var(--menu-bar-height) + 0.5em);
}
.page {
outline: 0;
padding: 0 var(--page-padding);
margin-top: calc(0px - var(--menu-bar-height)); /* Compensate for the #menu-bar-hover-placeholder */
}
.page-wrapper {
box-sizing: border-box;
}
.js:not(.sidebar-resizing) .page-wrapper {
transition: margin-left 0.3s ease, transform 0.3s ease; /* Animation: slide away */
}
.content {
overflow-y: auto;
padding: 0 15px;
padding-bottom: 50px;
}
.content main {
margin-left: auto;
margin-right: auto;
max-width: var(--content-max-width);
}
/* 2 1.75 1.5 1.25 1 .875 */
.content h1 { font-size: 2em }
.content h2 { font-size: 1.75em }
.content h3 { font-size: 1.5em }
.content h4 { font-size: 1.25em }
.content h5 { font-size: 1em }
.content h6 { font-size: .875em }
.content h1, .content h2, .content h3, .content h4 {
font-weight: 500;
margin-top: 1.275em;
margin-bottom: .875em;
}
.content p, .content ol, .content ul, .content table {
margin-top: 0;
margin-bottom: .875em;
}
.content ul li {
margin-bottom: .25rem;
}
.content ul {
list-style-type: square;
}
.content ul ul, .content ol ul {
margin-bottom: .5rem;
}
.content li p {
margin-bottom: .5em;
}
.content p { line-height: 1.45em; }
.content ol { line-height: 1.45em; }
.content ul { line-height: 1.45em; }
.content a { text-decoration: none; }
.content a:hover { text-decoration: underline; }
.content img { max-width: 100%; }
.content .header:link,
.content .header:visited {
color: var(--fg);
color: var(--heading-fg);
}
.content .header:link,
.content .header:visited:hover {
text-decoration: none;
}
table {
margin: 0 auto;
border-collapse: collapse;
width: 100%;
}
table td {
padding: .75rem;
width: auto;
}
table thead {
background: var(--table-header-bg);
}
table thead td {
font-weight: 700;
border: none;
}
table thead th {
padding: .75rem;
text-align: left;
font-weight: 500;
line-height: 1.5;
width: auto;
}
table thead tr {
border-bottom: 2px var(--table-border-color) solid;
}
table tbody tr {
border-bottom: 1px var(--table-border-line) solid;
}
/* Alternate background colors for rows */
table tbody tr:nth-child(2n) {
/* background: var(--table-alternate-bg); */
}
blockquote {
margin: 1.5rem 0;
padding: 1rem 1.5rem;
color: var(--fg);
opacity: .9;
background-color: var(--quote-bg);
border-left: 4px solid var(--quote-border);
}
blockquote *:last-child {
margin-bottom: 0;
}
:not(.footnote-definition) + .footnote-definition,
.footnote-definition + :not(.footnote-definition) {
margin-top: 2em;
}
.footnote-definition {
font-size: 0.9em;
margin: 0.5em 0;
}
.footnote-definition p {
display: inline;
}
.tooltiptext {
position: absolute;
visibility: hidden;
color: #fff;
background-color: #333;
transform: translateX(-50%); /* Center by moving tooltip 50% of its width left */
left: -8px; /* Half of the width of the icon */
top: -35px;
font-size: 0.8em;
text-align: center;
border-radius: 6px;
padding: 5px 8px;
margin: 5px;
z-index: 1000;
}
.tooltipped .tooltiptext {
visibility: visible;
}
.chapter li.part-title {
color: var(--sidebar-fg);
margin: 5px 0px;
font-weight: bold;
}
.result-no-output {
font-style: italic;
}

@ -1,54 +0,0 @@
#sidebar,
#menu-bar,
.nav-chapters,
.mobile-nav-chapters {
display: none;
}
#page-wrapper.page-wrapper {
transform: none;
margin-left: 0px;
overflow-y: initial;
}
#content {
max-width: none;
margin: 0;
padding: 0;
}
.page {
overflow-y: initial;
}
code {
background-color: #666666;
border-radius: 5px;
/* Force background to be printed in Chrome */
-webkit-print-color-adjust: exact;
}
pre > .buttons {
z-index: 2;
}
a, a:visited, a:active, a:hover {
color: #4183c4;
text-decoration: none;
}
h1, h2, h3, h4, h5, h6 {
page-break-inside: avoid;
page-break-after: avoid;
}
pre, code {
page-break-inside: avoid;
white-space: pre-wrap;
}
.fa {
display: none !important;
}

@ -1,342 +0,0 @@
/* Globals */
:root {
--sidebar-width: 300px;
--page-padding: 15px;
--content-max-width: 750px;
--menu-bar-height: 50px;
}
/* Themes */
.ayu {
--bg: hsl(210, 25%, 8%);
--fg: #c5c5c5;
--sidebar-bg: #14191f;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #5c6773;
--sidebar-active: #ffb454;
--sidebar-spacer: #2d334f;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #b7b9cc;
--links: #0096cf;
--inline-code-color: #ffb454;
--theme-popup-bg: #14191f;
--theme-popup-border: #5c6773;
--theme-hover: #191f26;
--quote-bg: hsl(226, 15%, 17%);
--quote-border: hsl(226, 15%, 22%);
--table-border-color: hsl(210, 25%, 13%);
--table-header-bg: hsl(210, 25%, 28%);
--table-alternate-bg: hsl(210, 25%, 11%);
--searchbar-border-color: #848484;
--searchbar-bg: #424242;
--searchbar-fg: #fff;
--searchbar-shadow-color: #d4c89f;
--searchresults-header-fg: #666;
--searchresults-border-color: #888;
--searchresults-li-bg: #252932;
--search-mark-bg: #e3b171;
}
.coal {
--bg: hsl(200, 7%, 8%);
--fg: #98a3ad;
--sidebar-bg: #292c2f;
--sidebar-fg: #a1adb8;
--sidebar-non-existent: #505254;
--sidebar-active: #3473ad;
--sidebar-spacer: #393939;
--scrollbar: var(--sidebar-fg);
--icons: #43484d;
--icons-hover: #b3c0cc;
--links: #2b79a2;
--inline-code-color: #c5c8c6;
--theme-popup-bg: #141617;
--theme-popup-border: #43484d;
--theme-hover: #1f2124;
--quote-bg: hsl(234, 21%, 18%);
--quote-border: hsl(234, 21%, 23%);
--table-border-color: hsl(200, 7%, 13%);
--table-header-bg: hsl(200, 7%, 28%);
--table-alternate-bg: hsl(200, 7%, 11%);
--searchbar-border-color: #aaa;
--searchbar-bg: #b7b7b7;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #666;
--searchresults-border-color: #98a3ad;
--searchresults-li-bg: #2b2b2f;
--search-mark-bg: #355c7d;
}
.light {
--bg: hsl(0, 0%, 100%);
--fg: hsl(0, 0%, 0%);
--sidebar-bg: #fafafa;
--sidebar-fg: hsl(0, 0%, 0%);
--sidebar-non-existent: #aaaaaa;
--sidebar-active: #1f1fff;
--sidebar-spacer: #f4f4f4;
--scrollbar: #8F8F8F;
--icons: #747474;
--icons-hover: #000000;
--links: #20609f;
--inline-code-color: #301900;
--theme-popup-bg: #fafafa;
--theme-popup-border: #cccccc;
--theme-hover: #e6e6e6;
--quote-bg: hsl(197, 37%, 96%);
--quote-border: hsl(197, 37%, 91%);
--table-border-color: hsl(0, 0%, 95%);
--table-header-bg: hsl(0, 0%, 80%);
--table-alternate-bg: hsl(0, 0%, 97%);
--searchbar-border-color: #aaa;
--searchbar-bg: #fafafa;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #666;
--searchresults-border-color: #888;
--searchresults-li-bg: #e4f2fe;
--search-mark-bg: #a2cff5;
}
.navy {
--bg: hsl(226, 23%, 11%);
--fg: #bcbdd0;
--sidebar-bg: #282d3f;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #505274;
--sidebar-active: #2b79a2;
--sidebar-spacer: #2d334f;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #b7b9cc;
--links: #2b79a2;
--inline-code-color: #c5c8c6;
--theme-popup-bg: #161923;
--theme-popup-border: #737480;
--theme-hover: #282e40;
--quote-bg: hsl(226, 15%, 17%);
--quote-border: hsl(226, 15%, 22%);
--table-border-color: hsl(226, 23%, 16%);
--table-header-bg: hsl(226, 23%, 31%);
--table-alternate-bg: hsl(226, 23%, 14%);
--searchbar-border-color: #aaa;
--searchbar-bg: #aeaec6;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #5f5f71;
--searchresults-border-color: #5c5c68;
--searchresults-li-bg: #242430;
--search-mark-bg: #a2cff5;
}
.rust {
--bg: hsl(60, 9%, 87%);
--fg: #262625;
--sidebar-bg: #3b2e2a;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #505254;
--sidebar-active: #e69f67;
--sidebar-spacer: #45373a;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #262625;
--links: #2b79a2;
--inline-code-color: #6e6b5e;
--theme-popup-bg: #e1e1db;
--theme-popup-border: #b38f6b;
--theme-hover: #99908a;
--quote-bg: hsl(60, 5%, 75%);
--quote-border: hsl(60, 5%, 70%);
--table-border-color: hsl(60, 9%, 82%);
--table-header-bg: #b3a497;
--table-alternate-bg: hsl(60, 9%, 84%);
--searchbar-border-color: #aaa;
--searchbar-bg: #fafafa;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #666;
--searchresults-border-color: #888;
--searchresults-li-bg: #dec2a2;
--search-mark-bg: #e69f67;
}
@media (prefers-color-scheme: dark) {
.light.no-js {
--bg: hsl(200, 7%, 8%);
--fg: #98a3ad;
--sidebar-bg: #292c2f;
--sidebar-fg: #a1adb8;
--sidebar-non-existent: #505254;
--sidebar-active: #3473ad;
--sidebar-spacer: #393939;
--scrollbar: var(--sidebar-fg);
--icons: #43484d;
--icons-hover: #b3c0cc;
--links: #2b79a2;
--inline-code-color: #c5c8c6;
--theme-popup-bg: #141617;
--theme-popup-border: #43484d;
--theme-hover: #1f2124;
--quote-bg: hsl(234, 21%, 18%);
--quote-border: hsl(234, 21%, 23%);
--table-border-color: hsl(200, 7%, 13%);
--table-header-bg: hsl(200, 7%, 28%);
--table-alternate-bg: hsl(200, 7%, 11%);
--searchbar-border-color: #aaa;
--searchbar-bg: #b7b7b7;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #666;
--searchresults-border-color: #98a3ad;
--searchresults-li-bg: #2b2b2f;
--search-mark-bg: #355c7d;
}
}
.colibri {
--bg: #3b224c;
--fg: #bcbdd0;
--heading-fg: #fff;
--sidebar-bg: #281733;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #505274;
--sidebar-active: #a4a0e8;
--sidebar-spacer: #2d334f;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #b7b9cc;
/* --links: #a4a0e8; */
--links: #ECCDBA;
--inline-code-color: hsl(48.7, 7.8%, 70%);
--theme-popup-bg: #161923;
--theme-popup-border: #737480;
--theme-hover: rgba(0,0,0, .2);
--quote-bg: #281733;
--quote-border: hsl(226, 15%, 22%);
--table-border-color: hsl(226, 23%, 76%);
--table-header-bg: hsla(226, 23%, 31%, 0);
--table-alternate-bg: hsl(226, 23%, 14%);
--table-border-line: hsla(201deg, 20%, 92%, 0.2);
--searchbar-border-color: #aaa;
--searchbar-bg: #aeaec6;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #5f5f71;
--searchresults-border-color: #5c5c68;
--searchresults-li-bg: #242430;
--search-mark-bg: #a2cff5;
}
.colibri {
/*
--bg: #ffffff;
--fg: #452859;
--fg: #5a5977;
--heading-fg: #281733;
--sidebar-bg: #281733;
--sidebar-fg: #c8c9db;
--sidebar-non-existent: #505274;
--sidebar-active: #a4a0e8;
--sidebar-spacer: #2d334f;
--scrollbar: var(--sidebar-fg);
--icons: #737480;
--icons-hover: #b7b9cc;
--links: #6F44F0;
--inline-code-color: #a39e9b;
--theme-popup-bg: #161923;
--theme-popup-border: #737480;
--theme-hover: rgba(0,0,0, .2);
--quote-bg: rgba(0, 0, 0, 0);
--quote-border: hsl(226, 15%, 75%);
--table-border-color: #5a5977;
--table-border-color: hsl(201deg 10% 67%);
--table-header-bg: hsl(0, 0%, 100%);
--table-alternate-bg: hsl(0, 0%, 97%);
--table-border-line: hsl(201deg, 20%, 92%);
--searchbar-border-color: #aaa;
--searchbar-bg: #aeaec6;
--searchbar-fg: #000;
--searchbar-shadow-color: #aaa;
--searchresults-header-fg: #5f5f71;
--searchresults-border-color: #5c5c68;
--searchresults-li-bg: #242430;
--search-mark-bg: #a2cff5;
*/
}

@ -1,56 +0,0 @@
pre code.hljs {
display:block;
overflow-x:auto;
padding:1em
}
code.hljs {
padding:3px 5px
}
.hljs {
background:#2f1e2e;
color:#a39e9b
}
.hljs-comment,
.hljs-quote {
color:#8d8687
}
.hljs-link,
.hljs-meta,
.hljs-name,
.hljs-regexp,
.hljs-selector-class,
.hljs-selector-id,
.hljs-tag,
.hljs-template-variable,
.hljs-variable {
color:#ef6155
}
.hljs-built_in,
.hljs-deletion,
.hljs-literal,
.hljs-number,
.hljs-params,
.hljs-type {
color:#f99b15
}
.hljs-attribute,
.hljs-section,
.hljs-title {
color:#fec418
}
.hljs-addition,
.hljs-bullet,
.hljs-string,
.hljs-symbol {
color:#48b685
}
.hljs-keyword,
.hljs-selector-tag {
color:#815ba4
}
.hljs-emphasis {
font-style:italic
}
.hljs-strong {
font-weight:700
}

File diff suppressed because one or more lines are too long

@ -1,11 +1,11 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html lang="{{ language }}" class="sidebar-visible no-js {{ default_theme }}"> <html lang="{{ language }}" class="{{ default_theme }}" dir="{{ text_direction }}">
<head> <head>
<!-- Book generated using mdBook --> <!-- Book generated using mdBook -->
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>{{ title }}</title> <title>{{ title }}</title>
{{#if is_print }} {{#if is_print }}
<meta name="robots" content="noindex" /> <meta name="robots" content="noindex">
{{/if}} {{/if}}
{{#if base_url}} {{#if base_url}}
<base href="{{ base_url }}"> <base href="{{ base_url }}">
@ -15,10 +15,9 @@
<!-- Custom HTML head --> <!-- Custom HTML head -->
{{> head}} {{> head}}
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="{{ description }}"> <meta name="description" content="{{ description }}">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff" /> <meta name="theme-color" content="#ffffff">
{{#if favicon_svg}} {{#if favicon_svg}}
<link rel="icon" href="{{ path_to_root }}favicon.svg"> <link rel="icon" href="{{ path_to_root }}favicon.svg">
@ -35,8 +34,6 @@
<!-- Fonts --> <!-- Fonts -->
<link rel="stylesheet" href="{{ path_to_root }}FontAwesome/css/font-awesome.css"> <link rel="stylesheet" href="{{ path_to_root }}FontAwesome/css/font-awesome.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@200;400;500;700&display=swap" rel="stylesheet">
{{#if copy_fonts}} {{#if copy_fonts}}
<link rel="stylesheet" href="{{ path_to_root }}fonts/fonts.css"> <link rel="stylesheet" href="{{ path_to_root }}fonts/fonts.css">
{{/if}} {{/if}}
@ -53,18 +50,19 @@
{{#if mathjax_support}} {{#if mathjax_support}}
<!-- MathJax --> <!-- MathJax -->
<script async type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{{/if}} {{/if}}
</head> </head>
<body> <body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript --> <!-- Provide site root to javascript -->
<script type="text/javascript"> <script>
var path_to_root = "{{ path_to_root }}"; var path_to_root = "{{ path_to_root }}";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "{{ preferred_dark_theme }}" : "{{ default_theme }}"; var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "{{ preferred_dark_theme }}" : "{{ default_theme }}";
</script> </script>
<!-- Work around some values being stored in localStorage wrapped in quotes --> <!-- Work around some values being stored in localStorage wrapped in quotes -->
<script type="text/javascript"> <script>
try { try {
var theme = localStorage.getItem('mdbook-theme'); var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar'); var sidebar = localStorage.getItem('mdbook-sidebar');
@ -80,27 +78,34 @@
</script> </script>
<!-- Set the theme before any content is loaded, prevents flash --> <!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript"> <script>
var theme; var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; } if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html'); var html = document.querySelector('html');
html.classList.remove('no-js')
html.classList.remove('{{ default_theme }}') html.classList.remove('{{ default_theme }}')
html.classList.add(theme); html.classList.add(theme);
html.classList.add('js'); var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script> </script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed --> <!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript"> <script>
var html = document.querySelector('html'); var body = document.querySelector('body');
var sidebar = 'hidden'; var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) { if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible'; sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
} }
html.classList.remove('sidebar-visible'); sidebar_toggle.checked = sidebar === 'visible';
html.classList.add("sidebar-" + sidebar); body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script> </script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents"> <nav id="sidebar" class="sidebar" aria-label="Table of contents">
@ -110,26 +115,48 @@
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div> <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
</nav> </nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper"> <div id="page-wrapper" class="page-wrapper">
<div class="page"> <div class="page">
{{> header}} {{> header}}
<div id="menu-bar-hover-placeholder"></div> <div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky bordered"> <div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons"> <div class="left-buttons">
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar"> <label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i> <i class="fa fa-bars"></i>
</button> </label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list"> <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i> <i class="fa fa-paint-brush"></i>
</button> </button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">{{ theme_option "Light" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">{{ theme_option "Rust" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">{{ theme_option "Coal" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">{{ theme_option "Navy" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">{{ theme_option "Ayu" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
<li role="none"><button role="menuitem" class="theme" id="colibri">{{ theme_option "Colibri" }}</button></li> <li role="none"><button role="menuitem" class="theme" id="colibri">Colibri</button></li>
</ul> </ul>
{{#if search_enabled}} {{#if search_enabled}}
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar"> <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
@ -151,13 +178,19 @@
<i id="git-repository-button" class="fa {{git_repository_icon}}"></i> <i id="git-repository-button" class="fa {{git_repository_icon}}"></i>
</a> </a>
{{/if}} {{/if}}
{{#if git_repository_edit_url}}
<a href="{{git_repository_edit_url}}" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
{{/if}}
</div> </div>
</div> </div>
{{#if search_enabled}} {{#if search_enabled}}
<div id="search-wrapper" class="hidden"> <div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer"> <form id="searchbar-outer" class="searchbar-outer">
<input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form> </form>
<div id="searchresults-outer" class="searchresults-outer hidden"> <div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div> <div id="searchresults-header" class="searchresults-header"></div>
@ -168,7 +201,7 @@
{{/if}} {{/if}}
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script type="text/javascript"> <script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
@ -190,7 +223,7 @@
{{/previous}} {{/previous}}
{{#next}} {{#next}}
<a rel="next" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i> <i class="fa fa-angle-right"></i>
</a> </a>
{{/next}} {{/next}}
@ -208,7 +241,7 @@
{{/previous}} {{/previous}}
{{#next}} {{#next}}
<a rel="next" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <a rel="next prefetch" href="{{ path_to_root }}{{link}}" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i> <i class="fa fa-angle-right"></i>
</a> </a>
{{/next}} {{/next}}
@ -216,10 +249,12 @@
</div> </div>
{{#if livereload}} {{#if live_reload_endpoint}}
<!-- Livereload script (if served using the cli tool) --> <!-- Livereload script (if served using the cli tool) -->
<script type="text/javascript"> <script>
var socket = new WebSocket("{{{livereload}}}"); const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsAddress = wsProtocol + "//" + location.host + "/" + "{{{live_reload_endpoint}}}";
const socket = new WebSocket(wsAddress);
socket.onmessage = function (event) { socket.onmessage = function (event) {
if (event.data === "reload") { if (event.data === "reload") {
socket.close(); socket.close();
@ -235,7 +270,7 @@
{{#if google_analytics}} {{#if google_analytics}}
<!-- Google Analytics Tag --> <!-- Google Analytics Tag -->
<script type="text/javascript"> <script>
var localAddrs = ["localhost", "127.0.0.1", ""]; var localAddrs = ["localhost", "127.0.0.1", ""];
// make sure we don't activate google analytics if the developer is // make sure we don't activate google analytics if the developer is
@ -253,43 +288,43 @@
{{/if}} {{/if}}
{{#if playground_line_numbers}} {{#if playground_line_numbers}}
<script type="text/javascript"> <script>
window.playground_line_numbers = true; window.playground_line_numbers = true;
</script> </script>
{{/if}} {{/if}}
{{#if playground_copyable}} {{#if playground_copyable}}
<script type="text/javascript"> <script>
window.playground_copyable = true; window.playground_copyable = true;
</script> </script>
{{/if}} {{/if}}
{{#if playground_js}} {{#if playground_js}}
<script src="{{ path_to_root }}ace.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}ace.js"></script>
<script src="{{ path_to_root }}editor.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}editor.js"></script>
<script src="{{ path_to_root }}mode-rust.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}mode-rust.js"></script>
<script src="{{ path_to_root }}theme-dawn.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}theme-dawn.js"></script>
<script src="{{ path_to_root }}theme-tomorrow_night.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}theme-tomorrow_night.js"></script>
{{/if}} {{/if}}
{{#if search_js}} {{#if search_js}}
<script src="{{ path_to_root }}elasticlunr.min.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}elasticlunr.min.js"></script>
<script src="{{ path_to_root }}mark.min.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}mark.min.js"></script>
<script src="{{ path_to_root }}searcher.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}searcher.js"></script>
{{/if}} {{/if}}
<script src="{{ path_to_root }}clipboard.min.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}clipboard.min.js"></script>
<script src="{{ path_to_root }}highlight.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}highlight.js"></script>
<script src="{{ path_to_root }}book.js" type="text/javascript" charset="utf-8"></script> <script src="{{ path_to_root }}book.js"></script>
<!-- Custom JS scripts --> <!-- Custom JS scripts -->
{{#each additional_js}} {{#each additional_js}}
<script type="text/javascript" src="{{ ../path_to_root }}{{this}}"></script> <script src="{{ ../path_to_root }}{{this}}"></script>
{{/each}} {{/each}}
{{#if is_print}} {{#if is_print}}
{{#if mathjax_support}} {{#if mathjax_support}}
<script type="text/javascript"> <script>
window.addEventListener('load', function() { window.addEventListener('load', function() {
MathJax.Hub.Register.StartupHook('End', function() { MathJax.Hub.Register.StartupHook('End', function() {
window.setTimeout(window.print, 100); window.setTimeout(window.print, 100);
@ -297,7 +332,7 @@
}); });
</script> </script>
{{else}} {{else}}
<script type="text/javascript"> <script>
window.addEventListener('load', function() { window.addEventListener('load', function() {
window.setTimeout(window.print, 100); window.setTimeout(window.print, 100);
}); });
@ -305,5 +340,6 @@
{{/if}} {{/if}}
{{/if}} {{/if}}
</div>
</body> </body>
</html> </html>

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>com.helix_editor.Helix</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>MPL-2.0</project_license>
<name>Helix</name>
<summary>A post-modern text editor</summary>
<summary xml:lang="ar">مُحَرِّرُ نُصُوصٍ سَابِقٌ لِعَهدِه</summary>
<description>
<p>
Helix is a terminal-based text editor inspired by Kakoune / Neovim and written in Rust.
</p>
<ul>
<li>Vim-like modal editing</li>
<li>Multiple selections</li>
<li>Built-in language server support</li>
<li>Smart, incremental syntax highlighting and code editing via tree-sitter</li>
</ul>
</description>
<description xml:lang="ar">
<p>
مُحَرِّرُ نُصُوصٍ يَعمَلُ فِي الطَّرَفِيَّة، مُستَلهَمٌ مِن Kakoune وَ Neovim وَمَكتُوبٌ بِلُغَةِ رَست البَرمَجِيَّة.
</p>
<ul>
<li>تَحرِيرٌ وَضعِيٌّ شَبيهٌ بِـVim</li>
<li>تَحدِيدَاتٌ لِلنَّصِ مُتَعَدِّدَة</li>
<li>دَعْمٌ مُدمَجٌ لِخَوادِمِ اللُّغَات</li>
<li>تَحرِيرُ التَّعلِيمَاتِ البَّرمَجِيَّةِ مَعَ تَمييزٍ لِلتَّركِيبِ النَّحُويِّ بِواسِطَةِ tree-sitter</li>
</ul>
</description>
<launchable type="desktop-id">Helix.desktop</launchable>
<screenshots>
<screenshot type="default">
<caption>Helix with default theme</caption>
<image>https://github.com/helix-editor/helix/raw/d4565b4404cabc522bd60822abd374755581d751/screenshot.png</image>
</screenshot>
</screenshots>
<url type="homepage">https://helix-editor.com/</url>
<url type="donation">https://opencollective.com/helix-editor</url>
<url type="help">https://docs.helix-editor.com/</url>
<url type="vcs-browser">https://github.com/helix-editor/helix</url>
<url type="bugtracker">https://github.com/helix-editor/helix/issues</url>
<content_rating type="oars-1.1" />
<releases>
<release version="23.10" date="2023-10-24">
<url>https://helix-editor.com/news/release-23-10-highlights/</url>
</release>
<release version="23.05" date="2023-05-18">
<url>https://github.com/helix-editor/helix/releases/tag/23.05</url>
</release>
<release version="23.03" date="2023-03-31">
<url>https://helix-editor.com/news/release-23-03-highlights/</url>
</release>
<release version="22.12" date="2022-12-6">
<url>https://helix-editor.com/news/release-22-12-highlights/</url>
</release>
<release version="22.08" date="2022-8-31">
<url>https://helix-editor.com/news/release-22-08-highlights/</url>
</release>
<release version="22.05" date="2022-5-28">
<url>https://helix-editor.com/news/release-22-05-highlights/</url>
</release>
<release version="22.03" date="2022-3-28">
<url>https://helix-editor.com/news/release-22-03-highlights/</url>
</release>
</releases>
<requires>
<control>keyboard</control>
</requires>
<categories>
<category>Utility</category>
<category>TextEditor</category>
</categories>
<keywords>
<keyword>text</keyword>
<keyword>editor</keyword>
<keyword>development</keyword>
<keyword>programming</keyword>
</keywords>
<provides>
<binary>hx</binary>
<mediatype>text/english</mediatype>
<mediatype>text/plain</mediatype>
<mediatype>text/x-makefile</mediatype>
<mediatype>text/x-c++hdr</mediatype>
<mediatype>text/x-c++src</mediatype>
<mediatype>text/x-chdr</mediatype>
<mediatype>text/x-csrc</mediatype>
<mediatype>text/x-java</mediatype>
<mediatype>text/x-moc</mediatype>
<mediatype>text/x-pascal</mediatype>
<mediatype>text/x-tcl</mediatype>
<mediatype>text/x-tex</mediatype>
<mediatype>application/x-shellscript</mediatype>
<mediatype>text/x-c</mediatype>
<mediatype>text/x-c++</mediatype>
</provides>
</component>

@ -1,6 +1,7 @@
[Desktop Entry] [Desktop Entry]
Name=Helix Name=Helix
GenericName=Text Editor GenericName=Text Editor
GenericName[ar]=مُحَرِّرُ نُصُوص
GenericName[de]=Texteditor GenericName[de]=Texteditor
GenericName[fr]=Éditeur de texte GenericName[fr]=Éditeur de texte
GenericName[ru]=Текстовый редактор GenericName[ru]=Текстовый редактор
@ -9,7 +10,7 @@ GenericName[tr]=Metin Düzenleyici
Comment=Edit text files Comment=Edit text files
Comment[af]=Redigeer tekslêers Comment[af]=Redigeer tekslêers
Comment[am]=የጽሑፍ ፋይሎች ያስተካክሉ Comment[am]=የጽሑፍ ፋይሎች ያስተካክሉ
Comment[ar]=حرّر ملفات نصية Comment[ar]=مُحَرِّرُ مِلَفَّاتٍ نَصِّيَّة
Comment[az]=Mətn fayllarını redaktə edin Comment[az]=Mətn fayllarını redaktə edin
Comment[be]=Рэдагаваньне тэкставых файлаў Comment[be]=Рэдагаваньне тэкставых файлаў
Comment[bg]=Редактиране на текстови файлове Comment[bg]=Редактиране на текстови файлове
@ -79,6 +80,7 @@ Exec=hx %F
Terminal=true Terminal=true
Type=Application Type=Application
Keywords=Text;editor; Keywords=Text;editor;
Keywords[ar]=نص;نصوص;محرر;
Keywords[fr]=Texte;éditeur; Keywords[fr]=Texte;éditeur;
Keywords[ru]=текст;текстовый редактор; Keywords[ru]=текст;текстовый редактор;
Keywords[sr]=Текст;едитор; Keywords[sr]=Текст;едитор;

@ -8,7 +8,10 @@ Some suggestions to get started:
- Help with packaging on various distributions needed! - Help with packaging on various distributions needed!
- To use print debugging to the [Helix log file][log-file], you must: - To use print debugging to the [Helix log file][log-file], you must:
* Print using `log::info!`, `warn!`, or `error!`. (`log::info!("helix!")`) * Print using `log::info!`, `warn!`, or `error!`. (`log::info!("helix!")`)
* Pass the appropriate verbosity level option for the desired log level. (`hx -v <file>` for info, more `v`s for higher severity inclusive) * Pass the appropriate verbosity level option for the desired log level. (`hx -v <file>` for info, more `v`s for higher verbosity)
* Want to display the logs in a separate file instead of using the `:log-open` command in your compiled Helix editor? Start your debug version with `cargo run -- --log foo.log` and in a new terminal use `tail -f foo.log`
- Instead of running a release version of Helix, while developing you may want to run in debug mode with `cargo run` which is way faster to compile
- Looking for even faster compile times? Give a try to [mold](https://github.com/rui314/mold)
- If your preferred language is missing, integrating a tree-sitter grammar for - If your preferred language is missing, integrating a tree-sitter grammar for
it and defining syntax highlight queries for it is straight forward and it and defining syntax highlight queries for it is straight forward and
doesn't require much knowledge of the internals. doesn't require much knowledge of the internals.
@ -26,11 +29,23 @@ files, run
cargo xtask docgen cargo xtask docgen
``` ```
inside the project. We use [xtask][xtask] as an ad-hoc task runner and inside the project. We use [xtask][xtask] as an ad-hoc task runner.
thus do not require any dependencies other than `cargo` (You don't have
to `cargo install` anything either).
# Integration tests To preview the book itself, install [mdbook][mdbook]. Then, run
```shell
mdbook serve book
```
and visit [http://localhost:3000](http://localhost:3000).
# Testing
## Unit tests/Documentation tests
Run `cargo test --workspace` to run unit tests and documentation tests in all packages.
## Integration tests
Integration tests for helix-term can be run with `cargo integration-test`. Code Integration tests for helix-term can be run with `cargo integration-test`. Code
contributors are strongly encouraged to write integration tests for their code. contributors are strongly encouraged to write integration tests for their code.
@ -49,4 +64,5 @@ The current MSRV and future changes to the MSRV are listed in the [Firefox docum
[architecture.md]: ./architecture.md [architecture.md]: ./architecture.md
[docs]: https://docs.helix-editor.com/ [docs]: https://docs.helix-editor.com/
[xtask]: https://github.com/matklad/cargo-xtask [xtask]: https://github.com/matklad/cargo-xtask
[mdbook]: https://rust-lang.github.io/mdBook/guide/installation.html
[helpers.rs]: ../helix-term/tests/test/helpers.rs [helpers.rs]: ../helix-term/tests/test/helpers.rs

@ -1,10 +1,11 @@
## Checklist ## Checklist
Helix releases are versioned in the Calendar Versioning scheme: Helix releases are versioned in the Calendar Versioning scheme:
`YY.0M(.MICRO)`, for example `22.05` for May of 2022. In these instructions `YY.0M(.MICRO)`, for example, `22.05` for May of 2022. In these instructions
we'll use `<tag>` as a placeholder for the tag being published. we'll use `<tag>` as a placeholder for the tag being published.
* Merge the changelog PR * Merge the changelog PR
* Add new `<release>` entry in `contrib/Helix.appdata.xml` with release information according to the [AppStream spec](https://www.freedesktop.org/software/appstream/docs/sect-Metadata-Releases.html)
* Tag and push * Tag and push
* `git tag -s -m "<tag>" -a <tag> && git push` * `git tag -s -m "<tag>" -a <tag> && git push`
* Make sure to switch to master and pull first * Make sure to switch to master and pull first
@ -29,7 +30,7 @@ we'll use `<tag>` as a placeholder for the tag being published.
The changelog is currently created manually by reading through commits in the The changelog is currently created manually by reading through commits in the
log since the last release. GitHub's compare view is a nice way to approach log since the last release. GitHub's compare view is a nice way to approach
this. For example when creating the 22.07 release notes, this compare link this. For example, when creating the 22.07 release notes, this compare link
may be used may be used
``` ```

@ -20,5 +20,5 @@ Vision statements are all well and good, but are also vague and subjective. Her
* **Built-in tools** for working with code bases efficiently. Most projects aren't a single file, and an editor should handle that as a first-class use case. In Helix's case, this means (among other things) a fuzzy-search file navigator and LSP support. * **Built-in tools** for working with code bases efficiently. Most projects aren't a single file, and an editor should handle that as a first-class use case. In Helix's case, this means (among other things) a fuzzy-search file navigator and LSP support.
* **Edit anything** that comes up when coding, within reason. Whether it's a 200 MB XML file, a megabyte of minified javascript on a single line, or Japanese text encoded in ShiftJIS, you should be able to open it and edit it without problems. (Note: this doesn't mean handle every esoteric use case. Sometimes you do just need a specialized tool, and Helix isn't that.) * **Edit anything** that comes up when coding, within reason. Whether it's a 200 MB XML file, a megabyte of minified javascript on a single line, or Japanese text encoded in ShiftJIS, you should be able to open it and edit it without problems. (Note: this doesn't mean handle every esoteric use case. Sometimes you do just need a specialized tool, and Helix isn't that.)
* **Configurable**, within reason. Although the defaults should be good, not everyone will agree on what "good" is. Within the bounds of Helix's core interaction models, it should be reasonably configurable so that it can be "good" for more people. This means, for example, custom key maps among other things. * **Configurable**, within reason. Although the defaults should be good, not everyone will agree on what "good" is. Within the bounds of Helix's core interaction models, it should be reasonably configurable so that it can be "good" for more people. This means, for example, custom key maps among other things.
* **Extensible**, within reason. Although we want Helix to be productive out-of-the-box, it's not practical or desirable to cram every useful feature and use case into the core editor. The basics should be built-in, but you should be able to extend it with additional functionality as needed. Right now we're thinking Wasm-based plugins. * **Extensible**, within reason. Although we want Helix to be productive out-of-the-box, it's not practical or desirable to cram every useful feature and use case into the core editor. The basics should be built-in, but you should be able to extend it with additional functionality as needed.
* **Clean code base.** Sometimes other factors (e.g. significant performance gains, important features, correctness, etc.) will trump strict readability, but we nevertheless want to keep the code base straightforward and easy to understand to the extent we can. * **Clean code base.** Sometimes other factors (e.g. significant performance gains, important features, correctness, etc.) will trump strict readability, but we nevertheless want to keep the code base straightforward and easy to understand to the extent we can.

@ -1,13 +1,24 @@
{ {
"nodes": { "nodes": {
"crane": { "crane": {
"flake": false, "inputs": {
"flake-compat": "flake-compat",
"flake-utils": [
"flake-utils"
],
"nixpkgs": [
"nixpkgs"
],
"rust-overlay": [
"rust-overlay"
]
},
"locked": { "locked": {
"lastModified": 1661875961, "lastModified": 1688772518,
"narHash": "sha256-f1h/2c6Teeu1ofAHWzrS8TwBPcnN+EEu+z1sRVmMQTk=", "narHash": "sha256-ol7gZxwvgLnxNSZwFTDJJ49xVY5teaSvF7lzlo3YQfM=",
"owner": "ipetkov", "owner": "ipetkov",
"repo": "crane", "repo": "crane",
"rev": "d9f394e4e20e97c2a60c3ad82c2b6ef99be19e24", "rev": "8b08e96c9af8c6e3a2b69af5a7fa168750fcf88e",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -16,79 +27,32 @@
"type": "github" "type": "github"
} }
}, },
"devshell": { "flake-compat": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1667210711, "lastModified": 1673956053,
"narHash": "sha256-IoErjXZAkzYWHEpQqwu/DeRNJGFdR7X2OGbkhMqMrpw=", "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=",
"owner": "numtide", "owner": "edolstra",
"repo": "devshell", "repo": "flake-compat",
"rev": "96a9dd12b8a447840cc246e17a47b81a4268bba7", "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "numtide", "owner": "edolstra",
"repo": "devshell", "repo": "flake-compat",
"type": "github" "type": "github"
} }
}, },
"dream2nix": { "flake-utils": {
"inputs": { "inputs": {
"alejandra": [ "systems": "systems"
"nci"
],
"all-cabal-json": [
"nci"
],
"crane": "crane",
"devshell": [
"nci",
"devshell"
],
"flake-utils-pre-commit": [
"nci"
],
"ghc-utils": [
"nci"
],
"gomod2nix": [
"nci"
],
"mach-nix": [
"nci"
],
"nixpkgs": [
"nci",
"nixpkgs"
],
"poetry2nix": [
"nci"
],
"pre-commit-hooks": [
"nci"
]
},
"locked": {
"lastModified": 1668851003,
"narHash": "sha256-X7RCQQynbxStZR2m7HW38r/msMQwVl3afD6UXOCtvx4=",
"owner": "nix-community",
"repo": "dream2nix",
"rev": "c77e8379d8fe01213ba072e40946cbfb7b58e628",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "dream2nix",
"type": "github"
}
}, },
"flake-utils": {
"locked": { "locked": {
"lastModified": 1659877975, "lastModified": 1689068808,
"narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", "narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", "rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -97,38 +61,13 @@
"type": "github" "type": "github"
} }
}, },
"nci": {
"inputs": {
"devshell": "devshell",
"dream2nix": "dream2nix",
"nixpkgs": [
"nixpkgs"
],
"rust-overlay": [
"rust-overlay"
]
},
"locked": {
"lastModified": 1669011203,
"narHash": "sha256-Lymj4HktNEFmVXtwI0Os7srDXHZbZW0Nzw3/+5Hf8ko=",
"owner": "yusdacra",
"repo": "nix-cargo-integration",
"rev": "c5133b91fc1d549087c91228bd213f2518728a4b",
"type": "github"
},
"original": {
"owner": "yusdacra",
"repo": "nix-cargo-integration",
"type": "github"
}
},
"nixpkgs": { "nixpkgs": {
"locked": { "locked": {
"lastModified": 1668905981, "lastModified": 1690272529,
"narHash": "sha256-RBQa/+9Uk1eFTqIOXBSBezlEbA3v5OkgP+qptQs1OxY=", "narHash": "sha256-MakzcKXEdv/I4qJUtq/k/eG+rVmyOZLnYNC2w1mB59Y=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "690ffff026b4e635b46f69002c0f4e81c65dfc2e", "rev": "ef99fa5c5ed624460217c31ac4271cfb5cb2502c",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -140,24 +79,27 @@
}, },
"root": { "root": {
"inputs": { "inputs": {
"nci": "nci", "crane": "crane",
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs", "nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay" "rust-overlay": "rust-overlay"
} }
}, },
"rust-overlay": { "rust-overlay": {
"inputs": { "inputs": {
"flake-utils": "flake-utils", "flake-utils": [
"flake-utils"
],
"nixpkgs": [ "nixpkgs": [
"nixpkgs" "nixpkgs"
] ]
}, },
"locked": { "locked": {
"lastModified": 1668998422, "lastModified": 1690424156,
"narHash": "sha256-G/BklIplCHZEeDIabaaxqgITdIXtMolRGlwxn9jG2/Q=", "narHash": "sha256-Bpml+L280tHTQpwpC5/BJbU4HSvEzMvW8IZ4gAXimhE=",
"owner": "oxalica", "owner": "oxalica",
"repo": "rust-overlay", "repo": "rust-overlay",
"rev": "68ab029c93f8f8eed4cf3ce9a89a9fd4504b2d6e", "rev": "f335a0213504c7e6481c359dc1009be9cf34432c",
"type": "github" "type": "github"
}, },
"original": { "original": {
@ -165,6 +107,21 @@
"repo": "rust-overlay", "repo": "rust-overlay",
"type": "github" "type": "github"
} }
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
} }
}, },
"root": "root", "root": "root",

@ -3,25 +3,35 @@
inputs = { inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay = { rust-overlay = {
url = "github:oxalica/rust-overlay"; url = "github:oxalica/rust-overlay";
inputs.nixpkgs.follows = "nixpkgs"; inputs = {
nixpkgs.follows = "nixpkgs";
flake-utils.follows = "flake-utils";
}; };
nci = { };
url = "github:yusdacra/nix-cargo-integration"; crane = {
inputs.nixpkgs.follows = "nixpkgs"; url = "github:ipetkov/crane";
inputs.rust-overlay.follows = "rust-overlay"; inputs.rust-overlay.follows = "rust-overlay";
inputs.flake-utils.follows = "flake-utils";
inputs.nixpkgs.follows = "nixpkgs";
}; };
}; };
outputs = { outputs = {
self, self,
nixpkgs, nixpkgs,
nci, crane,
flake-utils,
rust-overlay,
... ...
}: let }:
lib = nixpkgs.lib; flake-utils.lib.eachDefaultSystem (system: let
ncl = nci.lib.nci-lib; pkgs = import nixpkgs {
inherit system;
overlays = [(import rust-overlay)];
};
mkRootPath = rel: mkRootPath = rel:
builtins.path { builtins.path {
path = "${toString ./.}/${rel}"; path = "${toString ./.}/${rel}";
@ -32,10 +42,14 @@
".envrc" ".envrc"
".ignore" ".ignore"
".github" ".github"
".gitignore"
"logo_dark.svg"
"logo_light.svg"
"rust-toolchain.toml"
"rustfmt.toml"
"runtime" "runtime"
"screenshot.png" "screenshot.png"
"book" "book"
"contrib"
"docs" "docs"
"README.md" "README.md"
"CHANGELOG.md" "CHANGELOG.md"
@ -46,6 +60,7 @@
"flake.lock" "flake.lock"
]; ];
ignorePaths = path: type: let ignorePaths = path: type: let
inherit (nixpkgs) lib;
# split the nix store path into its components # split the nix store path into its components
components = lib.splitString "/" path; components = lib.splitString "/" path;
# drop off the `/nix/hash-source` section from the path # drop off the `/nix/hash-source` section from the path
@ -61,52 +76,6 @@
# filter out unnecessary paths # filter out unnecessary paths
filter = ignorePaths; filter = ignorePaths;
}; };
outputs = nci.lib.makeOutputs {
root = ./.;
config = common: {
outputs = {
# rename helix-term to helix since it's our main package
rename = {"helix-term" = "helix";};
# Set default app to hx (binary is from helix-term release build)
# Set default package to helix-term release build
defaults = {
app = "hx";
package = "helix";
};
};
cCompiler.package = with common.pkgs;
if stdenv.isLinux
then gcc
else clang;
shell = {
packages = with common.pkgs;
[lld_13 cargo-flamegraph rust-analyzer]
++ (lib.optional (stdenv.isx86_64 && stdenv.isLinux) cargo-tarpaulin)
++ (lib.optional stdenv.isLinux lldb);
env = [
{
name = "HELIX_RUNTIME";
eval = "$PWD/runtime";
}
{
name = "RUST_BACKTRACE";
value = "1";
}
{
name = "RUSTFLAGS";
value =
if common.pkgs.stdenv.isLinux
then "-C link-arg=-fuse-ld=lld -C target-cpu=native -Clink-arg=-Wl,--no-rosegment"
else "";
}
];
};
};
pkgConfig = common: {
helix-term = {
# Wrap helix with runtime
wrapper = _: old: let
inherit (common) pkgs;
makeOverridableHelix = old: config: let makeOverridableHelix = old: config: let
grammars = pkgs.callPackage ./grammars.nix config; grammars = pkgs.callPackage ./grammars.nix config;
runtimeDir = pkgs.runCommand "helix-runtime" {} '' runtimeDir = pkgs.runCommand "helix-runtime" {} ''
@ -116,61 +85,114 @@
ln -s ${grammars} $out/grammars ln -s ${grammars} $out/grammars
''; '';
helix-wrapped = helix-wrapped =
common.internal.pkgsSet.utils.wrapDerivation old pkgs.runCommand
old.name
{ {
inherit (old) pname version;
meta = old.meta or {};
passthru =
(old.passthru or {})
// {
unwrapped = old;
};
nativeBuildInputs = [pkgs.makeWrapper]; nativeBuildInputs = [pkgs.makeWrapper];
makeWrapperArgs = config.makeWrapperArgs or []; makeWrapperArgs = config.makeWrapperArgs or [];
} }
'' ''
rm -rf $out/bin cp -rs --no-preserve=mode,ownership ${old} $out
mkdir -p $out/bin
ln -sf ${old}/bin/* $out/bin/
wrapProgram "$out/bin/hx" ''${makeWrapperArgs[@]} --set HELIX_RUNTIME "${runtimeDir}" wrapProgram "$out/bin/hx" ''${makeWrapperArgs[@]} --set HELIX_RUNTIME "${runtimeDir}"
''; '';
in in
helix-wrapped helix-wrapped
// {override = makeOverridableHelix old;}; // {
in override = makeOverridableHelix old;
makeOverridableHelix old {}; passthru =
overrides.fix-build.overrideAttrs = prev: { helix-wrapped.passthru
// {
wrapper = old: makeOverridableHelix old config;
};
};
stdenv =
if pkgs.stdenv.isLinux
then pkgs.stdenv
else pkgs.clangStdenv;
rustFlagsEnv =
if stdenv.isLinux
then ''$RUSTFLAGS -C link-arg=-fuse-ld=lld -C target-cpu=native -Clink-arg=-Wl,--no-rosegment''
else "$RUSTFLAGS";
rustToolchain = pkgs.pkgsBuildHost.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
craneLibMSRV = (crane.mkLib pkgs).overrideToolchain rustToolchain;
craneLibStable = (crane.mkLib pkgs).overrideToolchain pkgs.pkgsBuildHost.rust-bin.stable.latest.default;
commonArgs =
{
inherit stdenv;
src = filteredSource; src = filteredSource;
# disable fetching and building of tree-sitter grammars in the helix-term build.rs # disable fetching and building of tree-sitter grammars in the helix-term build.rs
HELIX_DISABLE_AUTO_GRAMMAR_BUILD = "1"; HELIX_DISABLE_AUTO_GRAMMAR_BUILD = "1";
buildInputs = [stdenv.cc.cc.lib];
buildInputs = ncl.addBuildInputs prev [common.config.cCompiler.package.cc.lib]; # disable tests
doCheck = false;
# link languages and theme toml files since helix-term expects them (for tests) meta.mainProgram = "hx";
preConfigure = ''
${prev.preConfigure or ""}
${
lib.concatMapStringsSep
"\n"
(path: "ln -sf ${mkRootPath path} ..")
["languages.toml" "theme.toml" "base16_theme.toml"]
} }
// craneLibMSRV.crateNameFromCargoToml {cargoToml = ./helix-term/Cargo.toml;};
cargoArtifacts = craneLibMSRV.buildDepsOnly commonArgs;
in {
packages = {
helix-unwrapped = craneLibStable.buildPackage (commonArgs
// {
cargoArtifacts = craneLibStable.buildDepsOnly commonArgs;
postInstall = ''
mkdir -p $out/share/applications $out/share/icons/hicolor/scalable/apps $out/share/icons/hicolor/256x256/apps
cp contrib/Helix.desktop $out/share/applications
cp logo.svg $out/share/icons/hicolor/scalable/apps/helix.svg
cp contrib/helix.png $out/share/icons/hicolor/256x256/apps
''; '';
checkPhase = ":"; });
helix = makeOverridableHelix self.packages.${system}.helix-unwrapped {};
meta.mainProgram = "hx"; default = self.packages.${system}.helix;
};
}; };
checks = {
# Build the crate itself
inherit (self.packages.${system}) helix;
clippy = craneLibMSRV.cargoClippy (commonArgs
// {
inherit cargoArtifacts;
cargoClippyExtraArgs = "--all-targets -- --deny warnings";
});
fmt = craneLibMSRV.cargoFmt commonArgs;
doc = craneLibMSRV.cargoDoc (commonArgs
// {
inherit cargoArtifacts;
});
test = craneLibMSRV.cargoTest (commonArgs
// {
inherit cargoArtifacts;
});
}; };
devShells.default = pkgs.mkShell {
inputsFrom = builtins.attrValues self.checks.${system};
nativeBuildInputs = with pkgs;
[lld_13 cargo-flamegraph rust-analyzer]
++ (lib.optional (stdenv.isx86_64 && stdenv.isLinux) pkgs.cargo-tarpaulin)
++ (lib.optional stdenv.isLinux pkgs.lldb)
++ (lib.optional stdenv.isDarwin pkgs.darwin.apple_sdk.frameworks.CoreFoundation);
shellHook = ''
export HELIX_RUNTIME="$PWD/runtime"
export RUST_BACKTRACE="1"
export RUSTFLAGS="${rustFlagsEnv}"
'';
}; };
in })
outputs
// { // {
packages = overlays.default = final: prev: {
lib.mapAttrs inherit (self.packages.${final.system}) helix;
( };
system: packages:
packages
// {
helix-unwrapped = packages.helix.passthru.unwrapped;
helix-unwrapped-dev = packages.helix-dev.passthru.unwrapped;
}
)
outputs.packages;
}; };
nixConfig = { nixConfig = {

@ -5,6 +5,7 @@
runCommand, runCommand,
yj, yj,
includeGrammarIf ? _: true, includeGrammarIf ? _: true,
grammarOverlays ? [],
... ...
}: let }: let
# HACK: nix < 2.6 has a bug in the toml parser, so we convert to JSON # HACK: nix < 2.6 has a bug in the toml parser, so we convert to JSON
@ -48,22 +49,22 @@
then sourceGitHub then sourceGitHub
else sourceGit; else sourceGit;
in in
stdenv.mkDerivation rec { stdenv.mkDerivation {
# see https://github.com/NixOS/nixpkgs/blob/fbdd1a7c0bc29af5325e0d7dd70e804a972eb465/pkgs/development/tools/parsing/tree-sitter/grammar.nix # see https://github.com/NixOS/nixpkgs/blob/fbdd1a7c0bc29af5325e0d7dd70e804a972eb465/pkgs/development/tools/parsing/tree-sitter/grammar.nix
pname = "helix-tree-sitter-${grammar.name}"; pname = "helix-tree-sitter-${grammar.name}";
version = grammar.source.rev; version = grammar.source.rev;
src = src = source;
if builtins.hasAttr "subpath" grammar.source sourceRoot = if builtins.hasAttr "subpath" grammar.source then
then "${source}/${grammar.source.subpath}" "source/${grammar.source.subpath}"
else source; else
"source";
dontUnpack = true;
dontConfigure = true; dontConfigure = true;
FLAGS = [ FLAGS = [
"-I${src}/src" "-Isrc"
"-g" "-g"
"-O3" "-O3"
"-fPIC" "-fPIC"
@ -76,13 +77,13 @@
buildPhase = '' buildPhase = ''
runHook preBuild runHook preBuild
if [[ -e "$src/src/scanner.cc" ]]; then if [[ -e src/scanner.cc ]]; then
$CXX -c "$src/src/scanner.cc" -o scanner.o $FLAGS $CXX -c src/scanner.cc -o scanner.o $FLAGS
elif [[ -e "$src/src/scanner.c" ]]; then elif [[ -e src/scanner.c ]]; then
$CC -c "$src/src/scanner.c" -o scanner.o $FLAGS $CC -c src/scanner.c -o scanner.o $FLAGS
fi fi
$CC -c "$src/src/parser.c" -o parser.o $FLAGS $CC -c src/parser.c -o parser.o $FLAGS
$CXX -shared -o $NAME.so *.o $CXX -shared -o $NAME.so *.o
ls -al ls -al
@ -105,15 +106,17 @@
''; '';
}; };
grammarsToBuild = builtins.filter includeGrammarIf gitGrammars; grammarsToBuild = builtins.filter includeGrammarIf gitGrammars;
builtGrammars = builtGrammars = builtins.map (grammar: {
builtins.map (grammar: {
inherit (grammar) name; inherit (grammar) name;
artifact = buildGrammar grammar; value = buildGrammar grammar;
}) }) grammarsToBuild;
grammarsToBuild; extensibleGrammars =
grammarLinks = lib.makeExtensible (self: builtins.listToAttrs builtGrammars);
builtins.map (grammar: "ln -s ${grammar.artifact}/${grammar.name}.so $out/${grammar.name}.so") overlayedGrammars = lib.pipe extensibleGrammars
builtGrammars; (builtins.map (overlay: grammar: grammar.extend overlay) grammarOverlays);
grammarLinks = lib.mapAttrsToList
(name: artifact: "ln -s ${artifact}/${name}.so $out/${name}.so")
(lib.filterAttrs (n: v: lib.isDerivation v) overlayedGrammars);
in in
runCommand "consolidated-helix-grammars" {} '' runCommand "consolidated-helix-grammars" {} ''
mkdir -p $out mkdir -p $out

@ -17,26 +17,27 @@ integration = []
[dependencies] [dependencies]
helix-loader = { version = "0.6", path = "../helix-loader" } helix-loader = { version = "0.6", path = "../helix-loader" }
ropey = { version = "1.5.1-alpha", default-features = false, features = ["simd"] } ropey = { version = "1.6.1", default-features = false, features = ["simd"] }
smallvec = "1.10" smallvec = "1.11"
smartstring = "1.0.1" smartstring = "1.0.1"
unicode-segmentation = "1.10" unicode-segmentation = "1.10"
unicode-width = "0.1" unicode-width = "0.1"
unicode-general-category = "0.6" unicode-general-category = "0.6"
# slab = "0.4.2" # slab = "0.4.2"
slotmap = "1.0" slotmap = "1.0"
tree-sitter = "0.20" tree-sitter.workspace = true
once_cell = "1.16" once_cell = "1.18"
arc-swap = "1" arc-swap = "1"
regex = "1" regex = "1"
bitflags = "1.3" bitflags = "2.4"
ahash = "0.8.2" ahash = "0.8.6"
hashbrown = { version = "0.13.1", features = ["raw"] } hashbrown = { version = "0.14.2", features = ["raw"] }
dunce = "1.0"
log = "0.4" log = "0.4"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
toml = "0.5" toml = "0.7"
imara-diff = "0.1.0" imara-diff = "0.1.0"
@ -44,8 +45,12 @@ encoding_rs = "0.8"
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] } chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
etcetera = "0.4" etcetera = "0.8"
textwrap = "0.16.0" textwrap = "0.16.0"
nucleo.workspace = true
parking_lot = "0.12"
[dev-dependencies] [dev-dependencies]
quickcheck = { version = "1", default-features = false } quickcheck = { version = "1", default-features = false }
indoc = "2.0.4"

@ -17,7 +17,7 @@ pub const DEFAULT_PAIRS: &[(char, char)] = &[
]; ];
/// The type that represents the collection of auto pairs, /// The type that represents the collection of auto pairs,
/// keyed by the opener. /// keyed by both opener and closer.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AutoPairs(HashMap<char, Pair>); pub struct AutoPairs(HashMap<char, Pair>);

@ -45,7 +45,7 @@ fn find_line_comment(
// determine margin of 0 or 1 for uncommenting; if any comment token is not followed by a space, // determine margin of 0 or 1 for uncommenting; if any comment token is not followed by a space,
// a margin of 0 is used for all lines. // a margin of 0 is used for all lines.
if matches!(line_slice.get_char(pos + token_len), Some(c) if c != ' ') { if !matches!(line_slice.get_char(pos + token_len), Some(c) if c == ' ') {
margin = 0; margin = 0;
} }
@ -68,7 +68,7 @@ pub fn toggle_line_comments(doc: &Rope, selection: &Selection, token: Option<&st
let mut min_next_line = 0; let mut min_next_line = 0;
for selection in selection { for selection in selection {
let (start, end) = selection.line_range(text); let (start, end) = selection.line_range(text);
let start = start.max(min_next_line).min(text.len_lines()); let start = start.clamp(min_next_line, text.len_lines());
let end = (end + 1).min(text.len_lines()); let end = (end + 1).min(text.len_lines());
lines.extend(start..end); lines.extend(start..end);
@ -108,8 +108,8 @@ mod test {
let text = doc.slice(..); let text = doc.slice(..);
let res = find_line_comment("//", text, 0..3); let res = find_line_comment("//", text, 0..3);
// (commented = true, to_change = [line 0, line 2], min = col 2, margin = 1) // (commented = true, to_change = [line 0, line 2], min = col 2, margin = 0)
assert_eq!(res, (false, vec![0, 2], 2, 1)); assert_eq!(res, (false, vec![0, 2], 2, 0));
// comment // comment
let transaction = toggle_line_comments(&doc, &selection, None); let transaction = toggle_line_comments(&doc, &selection, None);
@ -136,6 +136,17 @@ mod test {
assert_eq!(doc, " 1\n\n 2\n 3"); assert_eq!(doc, " 1\n\n 2\n 3");
assert!(selection.len() == 1); // to ignore the selection unused warning assert!(selection.len() == 1); // to ignore the selection unused warning
// 0 margin comments, with no space
doc = Rope::from("//");
// reset the selection.
selection = Selection::single(0, doc.len_chars() - 1);
let transaction = toggle_line_comments(&doc, &selection, None);
transaction.apply(&mut doc);
selection = selection.map(transaction.changes());
assert_eq!(doc, "");
assert!(selection.len() == 1); // to ignore the selection unused warning
// TODO: account for uncommenting with uneven comment indentation // TODO: account for uncommenting with uneven comment indentation
} }
} }

@ -35,7 +35,7 @@ pub enum DiagnosticTag {
Deprecated, Deprecated,
} }
/// Corresponds to [`lsp_types::Diagnostic`](https://docs.rs/lsp-types/0.91.0/lsp_types/struct.Diagnostic.html) /// Corresponds to [`lsp_types::Diagnostic`](https://docs.rs/lsp-types/0.94.0/lsp_types/struct.Diagnostic.html)
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Diagnostic { pub struct Diagnostic {
pub range: Range, pub range: Range,
@ -43,6 +43,7 @@ pub struct Diagnostic {
pub message: String, pub message: String,
pub severity: Option<Severity>, pub severity: Option<Severity>,
pub code: Option<NumberOrString>, pub code: Option<NumberOrString>,
pub language_server_id: usize,
pub tags: Vec<DiagnosticTag>, pub tags: Vec<DiagnosticTag>,
pub source: Option<String>, pub source: Option<String>,
pub data: Option<serde_json::Value>, pub data: Option<serde_json::Value>,

@ -0,0 +1,384 @@
//! The `DocumentFormatter` forms the bridge between the raw document text
//! and onscreen positioning. It yields the text graphemes as an iterator
//! and traverses (part) of the document text. During that traversal it
//! handles grapheme detection, softwrapping and annotations.
//! It yields `FormattedGrapheme`s and their corresponding visual coordinates.
//!
//! As both virtual text and softwrapping can insert additional lines into the document
//! it is generally not possible to find the start of the previous visual line.
//! Instead the `DocumentFormatter` starts at the last "checkpoint" (usually a linebreak)
//! called a "block" and the caller must advance it as needed.
use std::borrow::Cow;
use std::fmt::Debug;
use std::mem::{replace, take};
#[cfg(test)]
mod test;
use unicode_segmentation::{Graphemes, UnicodeSegmentation};
use crate::graphemes::{Grapheme, GraphemeStr};
use crate::syntax::Highlight;
use crate::text_annotations::TextAnnotations;
use crate::{Position, RopeGraphemes, RopeSlice};
/// TODO make Highlight a u32 to reduce the size of this enum to a single word.
#[derive(Debug, Clone, Copy)]
pub enum GraphemeSource {
Document {
codepoints: u32,
},
/// Inline virtual text can not be highlighted with a `Highlight` iterator
/// because it's not part of the document. Instead the `Highlight`
/// is emitted right by the document formatter
VirtualText {
highlight: Option<Highlight>,
},
}
#[derive(Debug, Clone)]
pub struct FormattedGrapheme<'a> {
pub grapheme: Grapheme<'a>,
pub source: GraphemeSource,
}
impl<'a> FormattedGrapheme<'a> {
pub fn new(
g: GraphemeStr<'a>,
visual_x: usize,
tab_width: u16,
source: GraphemeSource,
) -> FormattedGrapheme<'a> {
FormattedGrapheme {
grapheme: Grapheme::new(g, visual_x, tab_width),
source,
}
}
/// Returns whether this grapheme is virtual inline text
pub fn is_virtual(&self) -> bool {
matches!(self.source, GraphemeSource::VirtualText { .. })
}
pub fn placeholder() -> Self {
FormattedGrapheme {
grapheme: Grapheme::Other { g: " ".into() },
source: GraphemeSource::Document { codepoints: 0 },
}
}
pub fn doc_chars(&self) -> usize {
match self.source {
GraphemeSource::Document { codepoints } => codepoints as usize,
GraphemeSource::VirtualText { .. } => 0,
}
}
pub fn is_whitespace(&self) -> bool {
self.grapheme.is_whitespace()
}
pub fn width(&self) -> usize {
self.grapheme.width()
}
pub fn is_word_boundary(&self) -> bool {
self.grapheme.is_word_boundary()
}
}
#[derive(Debug, Clone)]
pub struct TextFormat {
pub soft_wrap: bool,
pub tab_width: u16,
pub max_wrap: u16,
pub max_indent_retain: u16,
pub wrap_indicator: Box<str>,
pub wrap_indicator_highlight: Option<Highlight>,
pub viewport_width: u16,
}
// test implementation is basically only used for testing or when softwrap is always disabled
impl Default for TextFormat {
fn default() -> Self {
TextFormat {
soft_wrap: false,
tab_width: 4,
max_wrap: 3,
max_indent_retain: 4,
wrap_indicator: Box::from(" "),
viewport_width: 17,
wrap_indicator_highlight: None,
}
}
}
#[derive(Debug)]
pub struct DocumentFormatter<'t> {
text_fmt: &'t TextFormat,
annotations: &'t TextAnnotations,
/// The visual position at the end of the last yielded word boundary
visual_pos: Position,
graphemes: RopeGraphemes<'t>,
/// The character pos of the `graphemes` iter used for inserting annotations
char_pos: usize,
/// The line pos of the `graphemes` iter used for inserting annotations
line_pos: usize,
exhausted: bool,
/// Line breaks to be reserved for virtual text
/// at the next line break
virtual_lines: usize,
inline_anntoation_graphemes: Option<(Graphemes<'t>, Option<Highlight>)>,
// softwrap specific
/// The indentation of the current line
/// Is set to `None` if the indentation level is not yet known
/// because no non-whitespace graphemes have been encountered yet
indent_level: Option<usize>,
/// In case a long word needs to be split a single grapheme might need to be wrapped
/// while the rest of the word stays on the same line
peeked_grapheme: Option<(FormattedGrapheme<'t>, usize)>,
/// A first-in first-out (fifo) buffer for the Graphemes of any given word
word_buf: Vec<FormattedGrapheme<'t>>,
/// The index of the next grapheme that will be yielded from the `word_buf`
word_i: usize,
}
impl<'t> DocumentFormatter<'t> {
/// Creates a new formatter at the last block before `char_idx`.
/// A block is a chunk which always ends with a linebreak.
/// This is usually just a normal line break.
/// However very long lines are always wrapped at constant intervals that can be cheaply calculated
/// to avoid pathological behaviour.
pub fn new_at_prev_checkpoint(
text: RopeSlice<'t>,
text_fmt: &'t TextFormat,
annotations: &'t TextAnnotations,
char_idx: usize,
) -> (Self, usize) {
// TODO divide long lines into blocks to avoid bad performance for long lines
let block_line_idx = text.char_to_line(char_idx.min(text.len_chars()));
let block_char_idx = text.line_to_char(block_line_idx);
annotations.reset_pos(block_char_idx);
(
DocumentFormatter {
text_fmt,
annotations,
visual_pos: Position { row: 0, col: 0 },
graphemes: RopeGraphemes::new(text.slice(block_char_idx..)),
char_pos: block_char_idx,
exhausted: false,
virtual_lines: 0,
indent_level: None,
peeked_grapheme: None,
word_buf: Vec::with_capacity(64),
word_i: 0,
line_pos: block_line_idx,
inline_anntoation_graphemes: None,
},
block_char_idx,
)
}
fn next_inline_annotation_grapheme(&mut self) -> Option<(&'t str, Option<Highlight>)> {
loop {
if let Some(&mut (ref mut annotation, highlight)) =
self.inline_anntoation_graphemes.as_mut()
{
if let Some(grapheme) = annotation.next() {
return Some((grapheme, highlight));
}
}
if let Some((annotation, highlight)) =
self.annotations.next_inline_annotation_at(self.char_pos)
{
self.inline_anntoation_graphemes = Some((
UnicodeSegmentation::graphemes(&*annotation.text, true),
highlight,
))
} else {
return None;
}
}
}
fn advance_grapheme(&mut self, col: usize) -> Option<FormattedGrapheme<'t>> {
let (grapheme, source) =
if let Some((grapheme, highlight)) = self.next_inline_annotation_grapheme() {
(grapheme.into(), GraphemeSource::VirtualText { highlight })
} else if let Some(grapheme) = self.graphemes.next() {
self.virtual_lines += self.annotations.annotation_lines_at(self.char_pos);
let codepoints = grapheme.len_chars() as u32;
let overlay = self.annotations.overlay_at(self.char_pos);
let grapheme = match overlay {
Some((overlay, _)) => overlay.grapheme.as_str().into(),
None => Cow::from(grapheme).into(),
};
self.char_pos += codepoints as usize;
(grapheme, GraphemeSource::Document { codepoints })
} else {
if self.exhausted {
return None;
}
self.exhausted = true;
// EOF grapheme is required for rendering
// and correct position computations
return Some(FormattedGrapheme {
grapheme: Grapheme::Other { g: " ".into() },
source: GraphemeSource::Document { codepoints: 0 },
});
};
let grapheme = FormattedGrapheme::new(grapheme, col, self.text_fmt.tab_width, source);
Some(grapheme)
}
/// Move a word to the next visual line
fn wrap_word(&mut self, virtual_lines_before_word: usize) -> usize {
// softwrap this word to the next line
let indent_carry_over = if let Some(indent) = self.indent_level {
if indent as u16 <= self.text_fmt.max_indent_retain {
indent as u16
} else {
0
}
} else {
// ensure the indent stays 0
self.indent_level = Some(0);
0
};
self.visual_pos.col = indent_carry_over as usize;
self.virtual_lines -= virtual_lines_before_word;
self.visual_pos.row += 1 + virtual_lines_before_word;
let mut i = 0;
let mut word_width = 0;
let wrap_indicator = UnicodeSegmentation::graphemes(&*self.text_fmt.wrap_indicator, true)
.map(|g| {
i += 1;
let grapheme = FormattedGrapheme::new(
g.into(),
self.visual_pos.col + word_width,
self.text_fmt.tab_width,
GraphemeSource::VirtualText {
highlight: self.text_fmt.wrap_indicator_highlight,
},
);
word_width += grapheme.width();
grapheme
});
self.word_buf.splice(0..0, wrap_indicator);
for grapheme in &mut self.word_buf[i..] {
let visual_x = self.visual_pos.col + word_width;
grapheme
.grapheme
.change_position(visual_x, self.text_fmt.tab_width);
word_width += grapheme.width();
}
word_width
}
fn advance_to_next_word(&mut self) {
self.word_buf.clear();
let mut word_width = 0;
let virtual_lines_before_word = self.virtual_lines;
let mut virtual_lines_before_grapheme = self.virtual_lines;
loop {
// softwrap word if necessary
if word_width + self.visual_pos.col >= self.text_fmt.viewport_width as usize {
// wrapping this word would move too much text to the next line
// split the word at the line end instead
if word_width > self.text_fmt.max_wrap as usize {
// Usually we stop accomulating graphemes as soon as softwrapping becomes necessary.
// However if the last grapheme is multiple columns wide it might extend beyond the EOL.
// The condition below ensures that this grapheme is not cutoff and instead wrapped to the next line
if word_width + self.visual_pos.col > self.text_fmt.viewport_width as usize {
self.peeked_grapheme = self.word_buf.pop().map(|grapheme| {
(grapheme, self.virtual_lines - virtual_lines_before_grapheme)
});
self.virtual_lines = virtual_lines_before_grapheme;
}
return;
}
word_width = self.wrap_word(virtual_lines_before_word);
}
virtual_lines_before_grapheme = self.virtual_lines;
let grapheme = if let Some((grapheme, virtual_lines)) = self.peeked_grapheme.take() {
self.virtual_lines += virtual_lines;
grapheme
} else if let Some(grapheme) = self.advance_grapheme(self.visual_pos.col + word_width) {
grapheme
} else {
return;
};
// Track indentation
if !grapheme.is_whitespace() && self.indent_level.is_none() {
self.indent_level = Some(self.visual_pos.col);
} else if grapheme.grapheme == Grapheme::Newline {
self.indent_level = None;
}
let is_word_boundary = grapheme.is_word_boundary();
word_width += grapheme.width();
self.word_buf.push(grapheme);
if is_word_boundary {
return;
}
}
}
/// returns the document line pos of the **next** grapheme that will be yielded
pub fn line_pos(&self) -> usize {
self.line_pos
}
/// returns the visual pos of the **next** grapheme that will be yielded
pub fn visual_pos(&self) -> Position {
self.visual_pos
}
}
impl<'t> Iterator for DocumentFormatter<'t> {
type Item = (FormattedGrapheme<'t>, Position);
fn next(&mut self) -> Option<Self::Item> {
let grapheme = if self.text_fmt.soft_wrap {
if self.word_i >= self.word_buf.len() {
self.advance_to_next_word();
self.word_i = 0;
}
let grapheme = replace(
self.word_buf.get_mut(self.word_i)?,
FormattedGrapheme::placeholder(),
);
self.word_i += 1;
grapheme
} else {
self.advance_grapheme(self.visual_pos.col)?
};
let pos = self.visual_pos;
if grapheme.grapheme == Grapheme::Newline {
self.visual_pos.row += 1;
self.visual_pos.row += take(&mut self.virtual_lines);
self.visual_pos.col = 0;
self.line_pos += 1;
} else {
self.visual_pos.col += grapheme.width();
}
Some((grapheme, pos))
}
}

@ -0,0 +1,182 @@
use std::rc::Rc;
use crate::doc_formatter::{DocumentFormatter, TextFormat};
use crate::text_annotations::{InlineAnnotation, Overlay, TextAnnotations};
impl TextFormat {
fn new_test(softwrap: bool) -> Self {
TextFormat {
soft_wrap: softwrap,
tab_width: 2,
max_wrap: 3,
max_indent_retain: 4,
wrap_indicator: ".".into(),
wrap_indicator_highlight: None,
// use a prime number to allow lining up too often with repeat
viewport_width: 17,
}
}
}
impl<'t> DocumentFormatter<'t> {
fn collect_to_str(&mut self) -> String {
use std::fmt::Write;
let mut res = String::new();
let viewport_width = self.text_fmt.viewport_width;
let mut line = 0;
for (grapheme, pos) in self {
if pos.row != line {
line += 1;
assert_eq!(pos.row, line);
write!(res, "\n{}", ".".repeat(pos.col)).unwrap();
assert!(
pos.col <= viewport_width as usize,
"softwrapped failed {}<={viewport_width}",
pos.col
);
}
write!(res, "{}", grapheme.grapheme).unwrap();
}
res
}
}
fn softwrap_text(text: &str) -> String {
DocumentFormatter::new_at_prev_checkpoint(
text.into(),
&TextFormat::new_test(true),
&TextAnnotations::default(),
0,
)
.0
.collect_to_str()
}
#[test]
fn basic_softwrap() {
assert_eq!(
softwrap_text(&"foo ".repeat(10)),
"foo foo foo foo \n.foo foo foo foo \n.foo foo "
);
assert_eq!(
softwrap_text(&"fooo ".repeat(10)),
"fooo fooo fooo \n.fooo fooo fooo \n.fooo fooo fooo \n.fooo "
);
// check that we don't wrap unnecessarily
assert_eq!(softwrap_text("\t\txxxx1xxxx2xx\n"), " xxxx1xxxx2xx \n ");
}
#[test]
fn softwrap_indentation() {
assert_eq!(
softwrap_text("\t\tfoo1 foo2 foo3 foo4 foo5 foo6\n"),
" foo1 foo2 \n.....foo3 foo4 \n.....foo5 foo6 \n "
);
assert_eq!(
softwrap_text("\t\t\tfoo1 foo2 foo3 foo4 foo5 foo6\n"),
" foo1 foo2 \n.foo3 foo4 foo5 \n.foo6 \n "
);
}
#[test]
fn long_word_softwrap() {
assert_eq!(
softwrap_text("\t\txxxx1xxxx2xxxx3xxxx4xxxx5xxxx6xxxx7xxxx8xxxx9xxx\n"),
" xxxx1xxxx2xxx\n.....x3xxxx4xxxx5\n.....xxxx6xxxx7xx\n.....xx8xxxx9xxx \n "
);
assert_eq!(
softwrap_text("xxxxxxxx1xxxx2xxx\n"),
"xxxxxxxx1xxxx2xxx\n. \n "
);
assert_eq!(
softwrap_text("\t\txxxx1xxxx 2xxxx3xxxx4xxxx5xxxx6xxxx7xxxx8xxxx9xxx\n"),
" xxxx1xxxx \n.....2xxxx3xxxx4x\n.....xxx5xxxx6xxx\n.....x7xxxx8xxxx9\n.....xxx \n "
);
assert_eq!(
softwrap_text("\t\txxxx1xxx 2xxxx3xxxx4xxxx5xxxx6xxxx7xxxx8xxxx9xxx\n"),
" xxxx1xxx 2xxx\n.....x3xxxx4xxxx5\n.....xxxx6xxxx7xx\n.....xx8xxxx9xxx \n "
);
}
fn overlay_text(text: &str, char_pos: usize, softwrap: bool, overlays: &[Overlay]) -> String {
DocumentFormatter::new_at_prev_checkpoint(
text.into(),
&TextFormat::new_test(softwrap),
TextAnnotations::default().add_overlay(overlays.into(), None),
char_pos,
)
.0
.collect_to_str()
}
#[test]
fn overlay() {
assert_eq!(
overlay_text(
"foobar",
0,
false,
&[Overlay::new(0, "X"), Overlay::new(2, "\t")],
),
"Xo bar "
);
assert_eq!(
overlay_text(
&"foo ".repeat(10),
0,
true,
&[
Overlay::new(2, "\t"),
Overlay::new(5, "\t"),
Overlay::new(16, "X"),
]
),
"fo f o foo \n.foo Xoo foo foo \n.foo foo foo "
);
}
fn annotate_text(text: &str, softwrap: bool, annotations: &[InlineAnnotation]) -> String {
DocumentFormatter::new_at_prev_checkpoint(
text.into(),
&TextFormat::new_test(softwrap),
TextAnnotations::default().add_inline_annotations(annotations.into(), None),
0,
)
.0
.collect_to_str()
}
#[test]
fn annotation() {
assert_eq!(
annotate_text("bar", false, &[InlineAnnotation::new(0, "foo")]),
"foobar "
);
assert_eq!(
annotate_text(
&"foo ".repeat(10),
true,
&[InlineAnnotation::new(0, "foo ")]
),
"foo foo foo foo \n.foo foo foo foo \n.foo foo foo "
);
}
#[test]
fn annotation_and_overlay() {
assert_eq!(
DocumentFormatter::new_at_prev_checkpoint(
"bbar".into(),
&TextFormat::new_test(false),
TextAnnotations::default()
.add_inline_annotations(Rc::new([InlineAnnotation::new(0, "fooo")]), None)
.add_overlay(Rc::new([Overlay::new(0, "\t")]), None),
0,
)
.0
.collect_to_str(),
"fooo bar "
);
}

@ -0,0 +1,43 @@
use std::ops::DerefMut;
use nucleo::pattern::{Atom, AtomKind, CaseMatching};
use nucleo::Config;
use parking_lot::Mutex;
pub struct LazyMutex<T> {
inner: Mutex<Option<T>>,
init: fn() -> T,
}
impl<T> LazyMutex<T> {
pub const fn new(init: fn() -> T) -> Self {
Self {
inner: Mutex::new(None),
init,
}
}
pub fn lock(&self) -> impl DerefMut<Target = T> + '_ {
parking_lot::MutexGuard::map(self.inner.lock(), |val| val.get_or_insert_with(self.init))
}
}
pub static MATCHER: LazyMutex<nucleo::Matcher> = LazyMutex::new(nucleo::Matcher::default);
/// convenience function to easily fuzzy match
/// on a (relatively small list of inputs). This is not recommended for building a full tui
/// application that can match large numbers of matches as all matching is done on the current
/// thread, effectively blocking the UI
pub fn fuzzy_match<T: AsRef<str>>(
pattern: &str,
items: impl IntoIterator<Item = T>,
path: bool,
) -> Vec<(T, u16)> {
let mut matcher = MATCHER.lock();
matcher.config = Config::DEFAULT;
if path {
matcher.config.set_match_paths();
}
let pattern = Atom::new(pattern, CaseMatching::Smart, AtomKind::Fuzzy, false);
pattern.match_list(items, &mut matcher)
}

@ -5,7 +5,88 @@ use ropey::{iter::Chunks, str_utils::byte_to_char_idx, RopeSlice};
use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete}; use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
use std::fmt; use std::borrow::Cow;
use std::fmt::{self, Debug, Display};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;
use std::{slice, str};
use crate::chars::{char_is_whitespace, char_is_word};
use crate::LineEnding;
#[inline]
pub fn tab_width_at(visual_x: usize, tab_width: u16) -> usize {
tab_width as usize - (visual_x % tab_width as usize)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Grapheme<'a> {
Newline,
Tab { width: usize },
Other { g: GraphemeStr<'a> },
}
impl<'a> Grapheme<'a> {
pub fn new(g: GraphemeStr<'a>, visual_x: usize, tab_width: u16) -> Grapheme<'a> {
match g {
g if g == "\t" => Grapheme::Tab {
width: tab_width_at(visual_x, tab_width),
},
_ if LineEnding::from_str(&g).is_some() => Grapheme::Newline,
_ => Grapheme::Other { g },
}
}
pub fn change_position(&mut self, visual_x: usize, tab_width: u16) {
if let Grapheme::Tab { width } = self {
*width = tab_width_at(visual_x, tab_width)
}
}
/// Returns the a visual width of this grapheme,
#[inline]
pub fn width(&self) -> usize {
match *self {
// width is not cached because we are dealing with
// ASCII almost all the time which already has a fastpath
// it's okay to convert to u16 here because no codepoint has a width larger
// than 2 and graphemes are usually atmost two visible codepoints wide
Grapheme::Other { ref g } => grapheme_width(g),
Grapheme::Tab { width } => width,
Grapheme::Newline => 1,
}
}
pub fn is_whitespace(&self) -> bool {
!matches!(&self, Grapheme::Other { g } if !g.chars().all(char_is_whitespace))
}
// TODO currently word boundaries are used for softwrapping.
// This works best for programming languages and well for prose.
// This could however be improved in the future by considering unicode
// character classes but
pub fn is_word_boundary(&self) -> bool {
!matches!(&self, Grapheme::Other { g,.. } if g.chars().all(char_is_word))
}
}
impl Display for Grapheme<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Grapheme::Newline => write!(f, " "),
Grapheme::Tab { width } => {
for _ in 0..width {
write!(f, " ")?;
}
Ok(())
}
Grapheme::Other { ref g } => {
write!(f, "{g}")
}
}
}
}
#[must_use] #[must_use]
pub fn grapheme_width(g: &str) -> usize { pub fn grapheme_width(g: &str) -> usize {
@ -27,6 +108,8 @@ pub fn grapheme_width(g: &str) -> usize {
// We use max(1) here because all grapeheme clusters--even illformed // We use max(1) here because all grapeheme clusters--even illformed
// ones--should have at least some width so they can be edited // ones--should have at least some width so they can be edited
// properly. // properly.
// TODO properly handle unicode width for all codepoints
// example of where unicode width is currently wrong: 🤦🏼‍♂️ (taken from https://hsivonen.fi/string-length/)
UnicodeWidthStr::width(g).max(1) UnicodeWidthStr::width(g).max(1)
} }
} }
@ -341,3 +424,101 @@ impl<'a> Iterator for RopeGraphemes<'a> {
} }
} }
} }
/// A highly compressed Cow<'a, str> that holds
/// atmost u31::MAX bytes and is readonly
pub struct GraphemeStr<'a> {
ptr: NonNull<u8>,
len: u32,
phantom: PhantomData<&'a str>,
}
impl GraphemeStr<'_> {
const MASK_OWNED: u32 = 1 << 31;
fn compute_len(&self) -> usize {
(self.len & !Self::MASK_OWNED) as usize
}
}
impl Deref for GraphemeStr<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
unsafe {
let bytes = slice::from_raw_parts(self.ptr.as_ptr(), self.compute_len());
str::from_utf8_unchecked(bytes)
}
}
}
impl Drop for GraphemeStr<'_> {
fn drop(&mut self) {
if self.len & Self::MASK_OWNED != 0 {
// free allocation
unsafe {
drop(Box::from_raw(slice::from_raw_parts_mut(
self.ptr.as_ptr(),
self.compute_len(),
)));
}
}
}
}
impl<'a> From<&'a str> for GraphemeStr<'a> {
fn from(g: &'a str) -> Self {
GraphemeStr {
ptr: unsafe { NonNull::new_unchecked(g.as_bytes().as_ptr() as *mut u8) },
len: i32::try_from(g.len()).unwrap() as u32,
phantom: PhantomData,
}
}
}
impl<'a> From<String> for GraphemeStr<'a> {
fn from(g: String) -> Self {
let len = g.len();
let ptr = Box::into_raw(g.into_bytes().into_boxed_slice()) as *mut u8;
GraphemeStr {
ptr: unsafe { NonNull::new_unchecked(ptr) },
len: (i32::try_from(len).unwrap() as u32) | Self::MASK_OWNED,
phantom: PhantomData,
}
}
}
impl<'a> From<Cow<'a, str>> for GraphemeStr<'a> {
fn from(g: Cow<'a, str>) -> Self {
match g {
Cow::Borrowed(g) => g.into(),
Cow::Owned(g) => g.into(),
}
}
}
impl<T: Deref<Target = str>> PartialEq<T> for GraphemeStr<'_> {
fn eq(&self, other: &T) -> bool {
self.deref() == other.deref()
}
}
impl PartialEq<str> for GraphemeStr<'_> {
fn eq(&self, other: &str) -> bool {
self.deref() == other
}
}
impl Eq for GraphemeStr<'_> {}
impl Debug for GraphemeStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(self.deref(), f)
}
}
impl Display for GraphemeStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(self.deref(), f)
}
}
impl Clone for GraphemeStr<'_> {
fn clone(&self) -> Self {
self.deref().to_owned().into()
}
}

@ -72,8 +72,8 @@ impl Default for History {
revisions: vec![Revision { revisions: vec![Revision {
parent: 0, parent: 0,
last_child: None, last_child: None,
transaction: Transaction::from(ChangeSet::new(&Rope::new())), transaction: Transaction::from(ChangeSet::new("".into())),
inversion: Transaction::from(ChangeSet::new(&Rope::new())), inversion: Transaction::from(ChangeSet::new("".into())),
timestamp: Instant::now(), timestamp: Instant::now(),
}], }],
current: 0, current: 0,

@ -1,114 +1,53 @@
use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Timelike}; use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use ropey::RopeSlice;
use std::borrow::Cow;
use std::cmp;
use std::fmt::Write; use std::fmt::Write;
use super::Increment; /// Increment a Date or DateTime
use crate::{Range, Tendril}; ///
/// If just a Date is selected the day will be incremented.
#[derive(Debug, PartialEq, Eq)] /// If a DateTime is selected the second will be incremented.
pub struct DateTimeIncrementor { pub fn increment(selected_text: &str, amount: i64) -> Option<String> {
date_time: NaiveDateTime, if selected_text.is_empty() {
range: Range,
fmt: &'static str,
field: DateField,
}
impl DateTimeIncrementor {
pub fn from_range(text: RopeSlice, range: Range) -> Option<DateTimeIncrementor> {
let range = if range.is_empty() {
if range.anchor < text.len_chars() {
// Treat empty range as a cursor range.
range.put_cursor(text, range.anchor + 1, true)
} else {
// The range is empty and at the end of the text.
return None; return None;
} }
} else {
range
};
FORMATS.iter().find_map(|format| { FORMATS.iter().find_map(|format| {
let from = range.from().saturating_sub(format.max_len); let captures = format.regex.captures(selected_text)?;
let to = (range.from() + format.max_len).min(text.len_chars());
let (from_in_text, to_in_text) = (range.from() - from, range.to() - from);
let text: Cow<str> = text.slice(from..to).into();
let captures = format.regex.captures(&text)?;
if captures.len() - 1 != format.fields.len() { if captures.len() - 1 != format.fields.len() {
return None; return None;
} }
let date_time = captures.get(0)?; let date_time = captures.get(0)?;
let offset = range.from() - from_in_text;
let range = Range::new(date_time.start() + offset, date_time.end() + offset);
let field = captures
.iter()
.skip(1)
.enumerate()
.find_map(|(i, capture)| {
let capture = capture?;
let capture_range = capture.range();
if capture_range.contains(&from_in_text)
&& capture_range.contains(&(to_in_text - 1))
{
Some(format.fields[i])
} else {
None
}
})?;
let has_date = format.fields.iter().any(|f| f.unit.is_date()); let has_date = format.fields.iter().any(|f| f.unit.is_date());
let has_time = format.fields.iter().any(|f| f.unit.is_time()); let has_time = format.fields.iter().any(|f| f.unit.is_time());
let date_time = &selected_text[date_time.start()..date_time.end()];
let date_time = &text[date_time.start()..date_time.end()]; match (has_date, has_time) {
let date_time = match (has_date, has_time) { (true, true) => {
(true, true) => NaiveDateTime::parse_from_str(date_time, format.fmt).ok()?, let date_time = NaiveDateTime::parse_from_str(date_time, format.fmt).ok()?;
Some(
date_time
.checked_add_signed(Duration::minutes(amount))?
.format(format.fmt)
.to_string(),
)
}
(true, false) => { (true, false) => {
let date = NaiveDate::parse_from_str(date_time, format.fmt).ok()?; let date = NaiveDate::parse_from_str(date_time, format.fmt).ok()?;
Some(
date.and_hms_opt(0, 0, 0).unwrap() date.checked_add_signed(Duration::days(amount))?
.format(format.fmt)
.to_string(),
)
} }
(false, true) => { (false, true) => {
let time = NaiveTime::parse_from_str(date_time, format.fmt).ok()?; let time = NaiveTime::parse_from_str(date_time, format.fmt).ok()?;
let (adjusted_time, _) = time.overflowing_add_signed(Duration::minutes(amount));
NaiveDate::from_ymd_opt(0, 1, 1).unwrap().and_time(time) Some(adjusted_time.format(format.fmt).to_string())
}
(false, false) => return None,
};
Some(DateTimeIncrementor {
date_time,
range,
fmt: format.fmt,
field,
})
})
}
} }
(false, false) => None,
impl Increment for DateTimeIncrementor {
fn increment(&self, amount: i64) -> (Range, Tendril) {
let date_time = match self.field.unit {
DateUnit::Years => add_years(self.date_time, amount),
DateUnit::Months => add_months(self.date_time, amount),
DateUnit::Days => add_duration(self.date_time, Duration::days(amount)),
DateUnit::Hours => add_duration(self.date_time, Duration::hours(amount)),
DateUnit::Minutes => add_duration(self.date_time, Duration::minutes(amount)),
DateUnit::Seconds => add_duration(self.date_time, Duration::seconds(amount)),
DateUnit::AmPm => toggle_am_pm(self.date_time),
}
.unwrap_or(self.date_time);
(self.range, date_time.format(self.fmt).to_string().into())
} }
})
} }
static FORMATS: Lazy<Vec<Format>> = Lazy::new(|| { static FORMATS: Lazy<Vec<Format>> = Lazy::new(|| {
@ -144,7 +83,7 @@ impl Format {
fn new(fmt: &'static str) -> Self { fn new(fmt: &'static str) -> Self {
let mut remaining = fmt; let mut remaining = fmt;
let mut fields = Vec::new(); let mut fields = Vec::new();
let mut regex = String::new(); let mut regex = "^".to_string();
let mut max_len = 0; let mut max_len = 0;
while let Some(i) = remaining.find('%') { while let Some(i) = remaining.find('%') {
@ -166,6 +105,7 @@ impl Format {
write!(regex, "({})", field.regex).unwrap(); write!(regex, "({})", field.regex).unwrap();
remaining = &after[spec_len..]; remaining = &after[spec_len..];
} }
regex += "$";
let regex = Regex::new(&regex).unwrap(); let regex = Regex::new(&regex).unwrap();
@ -305,155 +245,47 @@ impl DateUnit {
} }
} }
fn ndays_in_month(year: i32, month: u32) -> u32 {
// The first day of the next month...
let (y, m) = if month == 12 {
(year + 1, 1)
} else {
(year, month + 1)
};
let d = NaiveDate::from_ymd_opt(y, m, 1).unwrap();
// ...is preceded by the last day of the original month.
d.pred_opt().unwrap().day()
}
fn add_months(date_time: NaiveDateTime, amount: i64) -> Option<NaiveDateTime> {
let month = (date_time.month0() as i64).checked_add(amount)?;
let year = date_time.year() + i32::try_from(month / 12).ok()?;
let year = if month.is_negative() { year - 1 } else { year };
// Normalize month
let month = month % 12;
let month = if month.is_negative() {
month + 12
} else {
month
} as u32
+ 1;
let day = cmp::min(date_time.day(), ndays_in_month(year, month));
NaiveDate::from_ymd_opt(year, month, day).map(|date| date.and_time(date_time.time()))
}
fn add_years(date_time: NaiveDateTime, amount: i64) -> Option<NaiveDateTime> {
let year = i32::try_from((date_time.year() as i64).checked_add(amount)?).ok()?;
let ndays = ndays_in_month(year, date_time.month());
if date_time.day() > ndays {
NaiveDate::from_ymd_opt(year, date_time.month(), ndays)
.and_then(|date| date.succ_opt().map(|date| date.and_time(date_time.time())))
} else {
date_time.with_year(year)
}
}
fn add_duration(date_time: NaiveDateTime, duration: Duration) -> Option<NaiveDateTime> {
date_time.checked_add_signed(duration)
}
fn toggle_am_pm(date_time: NaiveDateTime) -> Option<NaiveDateTime> {
if date_time.hour() < 12 {
add_duration(date_time, Duration::hours(12))
} else {
add_duration(date_time, Duration::hours(-12))
}
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
use crate::Rope;
#[test] #[test]
fn test_increment_date_times() { fn test_increment_date_times() {
let tests = [ let tests = [
// (original, cursor, amount, expected) // (original, cursor, amount, expected)
("2020-02-28", 0, 1, "2021-02-28"), ("2020-02-28", 1, "2020-02-29"),
("2020-02-29", 0, 1, "2021-03-01"), ("2020-02-29", 1, "2020-03-01"),
("2020-01-31", 5, 1, "2020-02-29"), ("2020-01-31", 1, "2020-02-01"),
("2020-01-20", 5, 1, "2020-02-20"), ("2020-01-20", 1, "2020-01-21"),
("2021-01-01", 5, -1, "2020-12-01"), ("2021-01-01", -1, "2020-12-31"),
("2021-01-31", 5, -2, "2020-11-30"), ("2021-01-31", -2, "2021-01-29"),
("2020-02-28", 8, 1, "2020-02-29"), ("2020-02-28", 1, "2020-02-29"),
("2021-02-28", 8, 1, "2021-03-01"), ("2021-02-28", 1, "2021-03-01"),
("2021-02-28", 0, -1, "2020-02-28"), ("2021-03-01", -1, "2021-02-28"),
("2021-03-01", 0, -1, "2020-03-01"), ("2020-02-29", -1, "2020-02-28"),
("2020-02-29", 5, -1, "2020-01-29"), ("2020-02-20", -1, "2020-02-19"),
("2020-02-20", 5, -1, "2020-01-20"), ("2021-03-01", -1, "2021-02-28"),
("2020-02-29", 8, -1, "2020-02-28"), ("1980/12/21", 100, "1981/03/31"),
("2021-03-01", 8, -1, "2021-02-28"), ("1980/12/21", -100, "1980/09/12"),
("1980/12/21", 8, 100, "1981/03/31"), ("1980/12/21", 1000, "1983/09/17"),
("1980/12/21", 8, -100, "1980/09/12"), ("1980/12/21", -1000, "1978/03/27"),
("1980/12/21", 8, 1000, "1983/09/17"), ("2021-11-24 07:12:23", 1, "2021-11-24 07:13:23"),
("1980/12/21", 8, -1000, "1978/03/27"), ("2021-11-24 07:12", 1, "2021-11-24 07:13"),
("2021-11-24 07:12:23", 0, 1, "2022-11-24 07:12:23"), ("Wed Nov 24 2021", 1, "Thu Nov 25 2021"),
("2021-11-24 07:12:23", 5, 1, "2021-12-24 07:12:23"), ("24-Nov-2021", 1, "25-Nov-2021"),
("2021-11-24 07:12:23", 8, 1, "2021-11-25 07:12:23"), ("2021 Nov 24", 1, "2021 Nov 25"),
("2021-11-24 07:12:23", 11, 1, "2021-11-24 08:12:23"), ("Nov 24, 2021", 1, "Nov 25, 2021"),
("2021-11-24 07:12:23", 14, 1, "2021-11-24 07:13:23"), ("7:21:53 am", 1, "7:22:53 am"),
("2021-11-24 07:12:23", 17, 1, "2021-11-24 07:12:24"), ("7:21:53 AM", 1, "7:22:53 AM"),
("2021/11/24 07:12:23", 0, 1, "2022/11/24 07:12:23"), ("7:21 am", 1, "7:22 am"),
("2021/11/24 07:12:23", 5, 1, "2021/12/24 07:12:23"), ("23:24:23", 1, "23:25:23"),
("2021/11/24 07:12:23", 8, 1, "2021/11/25 07:12:23"), ("23:24", 1, "23:25"),
("2021/11/24 07:12:23", 11, 1, "2021/11/24 08:12:23"), ("23:59", 1, "00:00"),
("2021/11/24 07:12:23", 14, 1, "2021/11/24 07:13:23"), ("23:59:59", 1, "00:00:59"),
("2021/11/24 07:12:23", 17, 1, "2021/11/24 07:12:24"),
("2021-11-24 07:12", 0, 1, "2022-11-24 07:12"),
("2021-11-24 07:12", 5, 1, "2021-12-24 07:12"),
("2021-11-24 07:12", 8, 1, "2021-11-25 07:12"),
("2021-11-24 07:12", 11, 1, "2021-11-24 08:12"),
("2021-11-24 07:12", 14, 1, "2021-11-24 07:13"),
("2021/11/24 07:12", 0, 1, "2022/11/24 07:12"),
("2021/11/24 07:12", 5, 1, "2021/12/24 07:12"),
("2021/11/24 07:12", 8, 1, "2021/11/25 07:12"),
("2021/11/24 07:12", 11, 1, "2021/11/24 08:12"),
("2021/11/24 07:12", 14, 1, "2021/11/24 07:13"),
("Wed Nov 24 2021", 0, 1, "Thu Nov 25 2021"),
("Wed Nov 24 2021", 4, 1, "Fri Dec 24 2021"),
("Wed Nov 24 2021", 8, 1, "Thu Nov 25 2021"),
("Wed Nov 24 2021", 11, 1, "Thu Nov 24 2022"),
("24-Nov-2021", 0, 1, "25-Nov-2021"),
("24-Nov-2021", 3, 1, "24-Dec-2021"),
("24-Nov-2021", 7, 1, "24-Nov-2022"),
("2021 Nov 24", 0, 1, "2022 Nov 24"),
("2021 Nov 24", 5, 1, "2021 Dec 24"),
("2021 Nov 24", 9, 1, "2021 Nov 25"),
("Nov 24, 2021", 0, 1, "Dec 24, 2021"),
("Nov 24, 2021", 4, 1, "Nov 25, 2021"),
("Nov 24, 2021", 8, 1, "Nov 24, 2022"),
("7:21:53 am", 0, 1, "8:21:53 am"),
("7:21:53 am", 3, 1, "7:22:53 am"),
("7:21:53 am", 5, 1, "7:21:54 am"),
("7:21:53 am", 8, 1, "7:21:53 pm"),
("7:21:53 AM", 0, 1, "8:21:53 AM"),
("7:21:53 AM", 3, 1, "7:22:53 AM"),
("7:21:53 AM", 5, 1, "7:21:54 AM"),
("7:21:53 AM", 8, 1, "7:21:53 PM"),
("7:21 am", 0, 1, "8:21 am"),
("7:21 am", 3, 1, "7:22 am"),
("7:21 am", 5, 1, "7:21 pm"),
("7:21 AM", 0, 1, "8:21 AM"),
("7:21 AM", 3, 1, "7:22 AM"),
("7:21 AM", 5, 1, "7:21 PM"),
("23:24:23", 1, 1, "00:24:23"),
("23:24:23", 3, 1, "23:25:23"),
("23:24:23", 6, 1, "23:24:24"),
("23:24", 1, 1, "00:24"),
("23:24", 3, 1, "23:25"),
]; ];
for (original, cursor, amount, expected) in tests { for (original, amount, expected) in tests {
let rope = Rope::from_str(original); assert_eq!(increment(original, amount).unwrap(), expected);
let range = Range::new(cursor, cursor + 1);
assert_eq!(
DateTimeIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
} }
} }
@ -482,10 +314,7 @@ mod test {
]; ];
for invalid in tests { for invalid in tests {
let rope = Rope::from_str(invalid); assert_eq!(increment(invalid, 1), None)
let range = Range::new(0, 1);
assert_eq!(DateTimeIncrementor::from_range(rope.slice(..), range), None)
} }
} }
} }

@ -0,0 +1,235 @@
const SEPARATOR: char = '_';
/// Increment an integer.
///
/// Supported bases:
/// 2 with prefix 0b
/// 8 with prefix 0o
/// 10 with no prefix
/// 16 with prefix 0x
///
/// An integer can contain `_` as a separator but may not start or end with a separator.
/// Base 10 integers can go negative, but bases 2, 8, and 16 cannot.
/// All addition and subtraction is saturating.
pub fn increment(selected_text: &str, amount: i64) -> Option<String> {
if selected_text.is_empty()
|| selected_text.ends_with(SEPARATOR)
|| selected_text.starts_with(SEPARATOR)
{
return None;
}
let radix = if selected_text.starts_with("0x") {
16
} else if selected_text.starts_with("0o") {
8
} else if selected_text.starts_with("0b") {
2
} else {
10
};
// Get separator indexes from right to left.
let separator_rtl_indexes: Vec<usize> = selected_text
.chars()
.rev()
.enumerate()
.filter_map(|(i, c)| if c == SEPARATOR { Some(i) } else { None })
.collect();
let word: String = selected_text.chars().filter(|&c| c != SEPARATOR).collect();
let mut new_text = if radix == 10 {
let number = &word;
let value = i128::from_str_radix(number, radix).ok()?;
let new_value = value.saturating_add(amount as i128);
let format_length = match (value.is_negative(), new_value.is_negative()) {
(true, false) => number.len() - 1,
(false, true) => number.len() + 1,
_ => number.len(),
} - separator_rtl_indexes.len();
if number.starts_with('0') || number.starts_with("-0") {
format!("{:01$}", new_value, format_length)
} else {
format!("{}", new_value)
}
} else {
let number = &word[2..];
let value = u128::from_str_radix(number, radix).ok()?;
let new_value = (value as i128).saturating_add(amount as i128);
let new_value = if new_value < 0 { 0 } else { new_value };
let format_length = selected_text.len() - 2 - separator_rtl_indexes.len();
match radix {
2 => format!("0b{:01$b}", new_value, format_length),
8 => format!("0o{:01$o}", new_value, format_length),
16 => {
let (lower_count, upper_count): (usize, usize) =
number.chars().fold((0, 0), |(lower, upper), c| {
(
lower + c.is_ascii_lowercase() as usize,
upper + c.is_ascii_uppercase() as usize,
)
});
if upper_count > lower_count {
format!("0x{:01$X}", new_value, format_length)
} else {
format!("0x{:01$x}", new_value, format_length)
}
}
_ => unimplemented!("radix not supported: {}", radix),
}
};
// Add separators from original number.
for &rtl_index in &separator_rtl_indexes {
if rtl_index < new_text.len() {
let new_index = new_text.len().saturating_sub(rtl_index);
if new_index > 0 {
new_text.insert(new_index, SEPARATOR);
}
}
}
// Add in additional separators if necessary.
if new_text.len() > selected_text.len() && !separator_rtl_indexes.is_empty() {
let spacing = match separator_rtl_indexes.as_slice() {
[.., b, a] => a - b - 1,
_ => separator_rtl_indexes[0],
};
let prefix_length = if radix == 10 { 0 } else { 2 };
if let Some(mut index) = new_text.find(SEPARATOR) {
while index - prefix_length > spacing {
index -= spacing;
new_text.insert(index, SEPARATOR);
}
}
}
Some(new_text)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_increment_basic_decimal_numbers() {
let tests = [
("100", 1, "101"),
("100", -1, "99"),
("99", 1, "100"),
("100", 1000, "1100"),
("100", -1000, "-900"),
("-1", 1, "0"),
("-1", 2, "1"),
("1", -1, "0"),
("1", -2, "-1"),
];
for (original, amount, expected) in tests {
assert_eq!(increment(original, amount).unwrap(), expected);
}
}
#[test]
fn test_increment_basic_hexadecimal_numbers() {
let tests = [
("0x0100", 1, "0x0101"),
("0x0100", -1, "0x00ff"),
("0x0001", -1, "0x0000"),
("0x0000", -1, "0x0000"),
("0xffffffffffffffff", 1, "0x10000000000000000"),
("0xffffffffffffffff", 2, "0x10000000000000001"),
("0xffffffffffffffff", -1, "0xfffffffffffffffe"),
("0xABCDEF1234567890", 1, "0xABCDEF1234567891"),
("0xabcdef1234567890", 1, "0xabcdef1234567891"),
];
for (original, amount, expected) in tests {
assert_eq!(increment(original, amount).unwrap(), expected);
}
}
#[test]
fn test_increment_basic_octal_numbers() {
let tests = [
("0o0107", 1, "0o0110"),
("0o0110", -1, "0o0107"),
("0o0001", -1, "0o0000"),
("0o7777", 1, "0o10000"),
("0o1000", -1, "0o0777"),
("0o0107", 10, "0o0121"),
("0o0000", -1, "0o0000"),
("0o1777777777777777777777", 1, "0o2000000000000000000000"),
("0o1777777777777777777777", 2, "0o2000000000000000000001"),
("0o1777777777777777777777", -1, "0o1777777777777777777776"),
];
for (original, amount, expected) in tests {
assert_eq!(increment(original, amount).unwrap(), expected);
}
}
#[test]
fn test_increment_basic_binary_numbers() {
let tests = [
("0b00000100", 1, "0b00000101"),
("0b00000100", -1, "0b00000011"),
("0b00000100", 2, "0b00000110"),
("0b00000100", -2, "0b00000010"),
("0b00000001", -1, "0b00000000"),
("0b00111111", 10, "0b01001001"),
("0b11111111", 1, "0b100000000"),
("0b10000000", -1, "0b01111111"),
("0b0000", -1, "0b0000"),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
1,
"0b10000000000000000000000000000000000000000000000000000000000000000",
),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
2,
"0b10000000000000000000000000000000000000000000000000000000000000001",
),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
-1,
"0b1111111111111111111111111111111111111111111111111111111111111110",
),
];
for (original, amount, expected) in tests {
assert_eq!(increment(original, amount).unwrap(), expected);
}
}
#[test]
fn test_increment_with_separators() {
let tests = [
("999_999", 1, "1_000_000"),
("1_000_000", -1, "999_999"),
("-999_999", -1, "-1_000_000"),
("0x0000_0000_0001", 0x1_ffff_0000, "0x0001_ffff_0001"),
("0x0000_0000", -1, "0x0000_0000"),
("0x0000_0000_0000", -1, "0x0000_0000_0000"),
("0b01111111_11111111", 1, "0b10000000_00000000"),
("0b11111111_11111111", 1, "0b1_00000000_00000000"),
];
for (original, amount, expected) in tests {
assert_eq!(increment(original, amount).unwrap(), expected);
}
}
#[test]
fn test_leading_and_trailing_separators_arent_a_match() {
assert_eq!(increment("9_", 1), None);
assert_eq!(increment("_9", 1), None);
assert_eq!(increment("_9_", 1), None);
}
}

@ -1,8 +1,10 @@
pub mod date_time; mod date_time;
pub mod number; mod integer;
use crate::{Range, Tendril}; pub fn integer(selected_text: &str, amount: i64) -> Option<String> {
integer::increment(selected_text, amount)
}
pub trait Increment { pub fn date_time(selected_text: &str, amount: i64) -> Option<String> {
fn increment(&self, amount: i64) -> (Range, Tendril); date_time::increment(selected_text, amount)
} }

@ -1,507 +0,0 @@
use std::borrow::Cow;
use ropey::RopeSlice;
use super::Increment;
use crate::{
textobject::{textobject_word, TextObject},
Range, Tendril,
};
#[derive(Debug, PartialEq, Eq)]
pub struct NumberIncrementor<'a> {
value: i64,
radix: u32,
range: Range,
text: RopeSlice<'a>,
}
impl<'a> NumberIncrementor<'a> {
/// Return information about number under rang if there is one.
pub fn from_range(text: RopeSlice, range: Range) -> Option<NumberIncrementor> {
// If the cursor is on the minus sign of a number we want to get the word textobject to the
// right of it.
let range = if range.to() < text.len_chars()
&& range.to() - range.from() <= 1
&& text.char(range.from()) == '-'
{
Range::new(range.from() + 1, range.to() + 1)
} else {
range
};
let range = textobject_word(text, range, TextObject::Inside, 1, false);
// If there is a minus sign to the left of the word object, we want to include it in the range.
let range = if range.from() > 0 && text.char(range.from() - 1) == '-' {
range.extend(range.from() - 1, range.from())
} else {
range
};
let word: String = text
.slice(range.from()..range.to())
.chars()
.filter(|&c| c != '_')
.collect();
let (radix, prefixed) = if word.starts_with("0x") {
(16, true)
} else if word.starts_with("0o") {
(8, true)
} else if word.starts_with("0b") {
(2, true)
} else {
(10, false)
};
let number = if prefixed { &word[2..] } else { &word };
let value = i128::from_str_radix(number, radix).ok()?;
if (value.is_positive() && value.leading_zeros() < 64)
|| (value.is_negative() && value.leading_ones() < 64)
{
return None;
}
let value = value as i64;
Some(NumberIncrementor {
range,
value,
radix,
text,
})
}
}
impl<'a> Increment for NumberIncrementor<'a> {
fn increment(&self, amount: i64) -> (Range, Tendril) {
let old_text: Cow<str> = self.text.slice(self.range.from()..self.range.to()).into();
let old_length = old_text.len();
let new_value = self.value.wrapping_add(amount);
// Get separator indexes from right to left.
let separator_rtl_indexes: Vec<usize> = old_text
.chars()
.rev()
.enumerate()
.filter_map(|(i, c)| if c == '_' { Some(i) } else { None })
.collect();
let format_length = if self.radix == 10 {
match (self.value.is_negative(), new_value.is_negative()) {
(true, false) => old_length - 1,
(false, true) => old_length + 1,
_ => old_text.len(),
}
} else {
old_text.len() - 2
} - separator_rtl_indexes.len();
let mut new_text = match self.radix {
2 => format!("0b{:01$b}", new_value, format_length),
8 => format!("0o{:01$o}", new_value, format_length),
10 if old_text.starts_with('0') || old_text.starts_with("-0") => {
format!("{:01$}", new_value, format_length)
}
10 => format!("{}", new_value),
16 => {
let (lower_count, upper_count): (usize, usize) =
old_text.chars().skip(2).fold((0, 0), |(lower, upper), c| {
(
lower + usize::from(c.is_ascii_lowercase()),
upper + usize::from(c.is_ascii_uppercase()),
)
});
if upper_count > lower_count {
format!("0x{:01$X}", new_value, format_length)
} else {
format!("0x{:01$x}", new_value, format_length)
}
}
_ => unimplemented!("radix not supported: {}", self.radix),
};
// Add separators from original number.
for &rtl_index in &separator_rtl_indexes {
if rtl_index < new_text.len() {
let new_index = new_text.len() - rtl_index;
new_text.insert(new_index, '_');
}
}
// Add in additional separators if necessary.
if new_text.len() > old_length && !separator_rtl_indexes.is_empty() {
let spacing = match separator_rtl_indexes.as_slice() {
[.., b, a] => a - b - 1,
_ => separator_rtl_indexes[0],
};
let prefix_length = if self.radix == 10 { 0 } else { 2 };
if let Some(mut index) = new_text.find('_') {
while index - prefix_length > spacing {
index -= spacing;
new_text.insert(index, '_');
}
}
}
(self.range, new_text.into())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::Rope;
#[test]
fn test_decimal_at_point() {
let rope = Rope::from_str("Test text 12345 more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 15),
value: 12345,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_uppercase_hexadecimal_at_point() {
let rope = Rope::from_str("Test text 0x123ABCDEF more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 21),
value: 0x123ABCDEF,
radix: 16,
text: rope.slice(..),
})
);
}
#[test]
fn test_lowercase_hexadecimal_at_point() {
let rope = Rope::from_str("Test text 0xfa3b4e more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 18),
value: 0xfa3b4e,
radix: 16,
text: rope.slice(..),
})
);
}
#[test]
fn test_octal_at_point() {
let rope = Rope::from_str("Test text 0o1074312 more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 19),
value: 0o1074312,
radix: 8,
text: rope.slice(..),
})
);
}
#[test]
fn test_binary_at_point() {
let rope = Rope::from_str("Test text 0b10111010010101 more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 26),
value: 0b10111010010101,
radix: 2,
text: rope.slice(..),
})
);
}
#[test]
fn test_negative_decimal_at_point() {
let rope = Rope::from_str("Test text -54321 more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 16),
value: -54321,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_decimal_with_leading_zeroes_at_point() {
let rope = Rope::from_str("Test text 000045326 more text.");
let range = Range::point(12);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 19),
value: 45326,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_negative_decimal_cursor_on_minus_sign() {
let rope = Rope::from_str("Test text -54321 more text.");
let range = Range::point(10);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(10, 16),
value: -54321,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_number_under_range_start_of_rope() {
let rope = Rope::from_str("100");
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(0, 3),
value: 100,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_number_under_range_end_of_rope() {
let rope = Rope::from_str("100");
let range = Range::point(2);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(0, 3),
value: 100,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_number_surrounded_by_punctuation() {
let rope = Rope::from_str(",100;");
let range = Range::point(1);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range),
Some(NumberIncrementor {
range: Range::new(1, 4),
value: 100,
radix: 10,
text: rope.slice(..),
})
);
}
#[test]
fn test_not_a_number_point() {
let rope = Rope::from_str("Test text 45326 more text.");
let range = Range::point(6);
assert_eq!(NumberIncrementor::from_range(rope.slice(..), range), None);
}
#[test]
fn test_number_too_large_at_point() {
let rope = Rope::from_str("Test text 0xFFFFFFFFFFFFFFFFF more text.");
let range = Range::point(12);
assert_eq!(NumberIncrementor::from_range(rope.slice(..), range), None);
}
#[test]
fn test_number_cursor_one_right_of_number() {
let rope = Rope::from_str("100 ");
let range = Range::point(3);
assert_eq!(NumberIncrementor::from_range(rope.slice(..), range), None);
}
#[test]
fn test_number_cursor_one_left_of_number() {
let rope = Rope::from_str(" 100");
let range = Range::point(0);
assert_eq!(NumberIncrementor::from_range(rope.slice(..), range), None);
}
#[test]
fn test_increment_basic_decimal_numbers() {
let tests = [
("100", 1, "101"),
("100", -1, "99"),
("99", 1, "100"),
("100", 1000, "1100"),
("100", -1000, "-900"),
("-1", 1, "0"),
("-1", 2, "1"),
("1", -1, "0"),
("1", -2, "-1"),
];
for (original, amount, expected) in tests {
let rope = Rope::from_str(original);
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
}
}
#[test]
fn test_increment_basic_hexadecimal_numbers() {
let tests = [
("0x0100", 1, "0x0101"),
("0x0100", -1, "0x00ff"),
("0x0001", -1, "0x0000"),
("0x0000", -1, "0xffffffffffffffff"),
("0xffffffffffffffff", 1, "0x0000000000000000"),
("0xffffffffffffffff", 2, "0x0000000000000001"),
("0xffffffffffffffff", -1, "0xfffffffffffffffe"),
("0xABCDEF1234567890", 1, "0xABCDEF1234567891"),
("0xabcdef1234567890", 1, "0xabcdef1234567891"),
];
for (original, amount, expected) in tests {
let rope = Rope::from_str(original);
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
}
}
#[test]
fn test_increment_basic_octal_numbers() {
let tests = [
("0o0107", 1, "0o0110"),
("0o0110", -1, "0o0107"),
("0o0001", -1, "0o0000"),
("0o7777", 1, "0o10000"),
("0o1000", -1, "0o0777"),
("0o0107", 10, "0o0121"),
("0o0000", -1, "0o1777777777777777777777"),
("0o1777777777777777777777", 1, "0o0000000000000000000000"),
("0o1777777777777777777777", 2, "0o0000000000000000000001"),
("0o1777777777777777777777", -1, "0o1777777777777777777776"),
];
for (original, amount, expected) in tests {
let rope = Rope::from_str(original);
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
}
}
#[test]
fn test_increment_basic_binary_numbers() {
let tests = [
("0b00000100", 1, "0b00000101"),
("0b00000100", -1, "0b00000011"),
("0b00000100", 2, "0b00000110"),
("0b00000100", -2, "0b00000010"),
("0b00000001", -1, "0b00000000"),
("0b00111111", 10, "0b01001001"),
("0b11111111", 1, "0b100000000"),
("0b10000000", -1, "0b01111111"),
(
"0b0000",
-1,
"0b1111111111111111111111111111111111111111111111111111111111111111",
),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
1,
"0b0000000000000000000000000000000000000000000000000000000000000000",
),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
2,
"0b0000000000000000000000000000000000000000000000000000000000000001",
),
(
"0b1111111111111111111111111111111111111111111111111111111111111111",
-1,
"0b1111111111111111111111111111111111111111111111111111111111111110",
),
];
for (original, amount, expected) in tests {
let rope = Rope::from_str(original);
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
}
}
#[test]
fn test_increment_with_separators() {
let tests = [
("999_999", 1, "1_000_000"),
("1_000_000", -1, "999_999"),
("-999_999", -1, "-1_000_000"),
("0x0000_0000_0001", 0x1_ffff_0000, "0x0001_ffff_0001"),
("0x0000_0000_0001", 0x1_ffff_0000, "0x0001_ffff_0001"),
("0x0000_0000_0001", 0x1_ffff_0000, "0x0001_ffff_0001"),
("0x0000_0000", -1, "0xffff_ffff_ffff_ffff"),
("0x0000_0000_0000", -1, "0xffff_ffff_ffff_ffff"),
("0b01111111_11111111", 1, "0b10000000_00000000"),
("0b11111111_11111111", 1, "0b1_00000000_00000000"),
];
for (original, amount, expected) in tests {
let rope = Rope::from_str(original);
let range = Range::point(0);
assert_eq!(
NumberIncrementor::from_range(rope.slice(..), range)
.unwrap()
.increment(amount)
.1,
Tendril::from(expected)
);
}
}
}

@ -1,12 +1,13 @@
use std::collections::HashMap; use std::{borrow::Cow, collections::HashMap};
use tree_sitter::{Query, QueryCursor, QueryPredicateArg}; use tree_sitter::{Query, QueryCursor, QueryPredicateArg};
use crate::{ use crate::{
chars::{char_is_line_ending, char_is_whitespace}, chars::{char_is_line_ending, char_is_whitespace},
graphemes::{grapheme_width, tab_width_at},
syntax::{LanguageConfiguration, RopeProvider, Syntax}, syntax::{LanguageConfiguration, RopeProvider, Syntax},
tree_sitter::Node, tree_sitter::Node,
Rope, RopeSlice, Rope, RopeGraphemes, RopeSlice,
}; };
/// Enum representing indentation style. /// Enum representing indentation style.
@ -18,6 +19,10 @@ pub enum IndentStyle {
Spaces(u8), Spaces(u8),
} }
// 16 spaces
const INDENTS: &str = " ";
const MAX_INDENT: u8 = 16;
impl IndentStyle { impl IndentStyle {
/// Creates an `IndentStyle` from an indentation string. /// Creates an `IndentStyle` from an indentation string.
/// ///
@ -26,10 +31,10 @@ impl IndentStyle {
#[inline] #[inline]
pub fn from_str(indent: &str) -> Self { pub fn from_str(indent: &str) -> Self {
// XXX: do we care about validating the input more than this? Probably not...? // XXX: do we care about validating the input more than this? Probably not...?
debug_assert!(!indent.is_empty() && indent.len() <= 8); debug_assert!(!indent.is_empty() && indent.len() <= MAX_INDENT as usize);
if indent.starts_with(' ') { if indent.starts_with(' ') {
IndentStyle::Spaces(indent.len() as u8) IndentStyle::Spaces(indent.len().clamp(1, MAX_INDENT as usize) as u8)
} else { } else {
IndentStyle::Tabs IndentStyle::Tabs
} }
@ -39,23 +44,24 @@ impl IndentStyle {
pub fn as_str(&self) -> &'static str { pub fn as_str(&self) -> &'static str {
match *self { match *self {
IndentStyle::Tabs => "\t", IndentStyle::Tabs => "\t",
IndentStyle::Spaces(1) => " ",
IndentStyle::Spaces(2) => " ",
IndentStyle::Spaces(3) => " ",
IndentStyle::Spaces(4) => " ",
IndentStyle::Spaces(5) => " ",
IndentStyle::Spaces(6) => " ",
IndentStyle::Spaces(7) => " ",
IndentStyle::Spaces(8) => " ",
// Unsupported indentation style. This should never happen,
// but just in case fall back to two spaces.
IndentStyle::Spaces(n) => { IndentStyle::Spaces(n) => {
debug_assert!(n > 0 && n <= 8); // Always triggers. `debug_panic!()` wanted. // Unsupported indentation style. This should never happen,
" " debug_assert!(n > 0 && n <= MAX_INDENT);
// Either way, clamp to the nearest supported value
let closest_n = n.clamp(1, MAX_INDENT) as usize;
&INDENTS[0..closest_n]
} }
} }
} }
#[inline]
pub fn indent_width(&self, tab_width: usize) -> usize {
match *self {
IndentStyle::Tabs => tab_width,
IndentStyle::Spaces(width) => width as usize,
}
}
} }
/// Attempts to detect the indentation style used in a document. /// Attempts to detect the indentation style used in a document.
@ -66,9 +72,9 @@ pub fn auto_detect_indent_style(document_text: &Rope) -> Option<IndentStyle> {
// Build a histogram of the indentation *increases* between // Build a histogram of the indentation *increases* between
// subsequent lines, ignoring lines that are all whitespace. // subsequent lines, ignoring lines that are all whitespace.
// //
// Index 0 is for tabs, the rest are 1-8 spaces. // Index 0 is for tabs, the rest are 1-MAX_INDENT spaces.
let histogram: [usize; 9] = { let histogram: [usize; MAX_INDENT as usize + 1] = {
let mut histogram = [0; 9]; let mut histogram = [0; MAX_INDENT as usize + 1];
let mut prev_line_is_tabs = false; let mut prev_line_is_tabs = false;
let mut prev_line_leading_count = 0usize; let mut prev_line_leading_count = 0usize;
@ -127,7 +133,7 @@ pub fn auto_detect_indent_style(document_text: &Rope) -> Option<IndentStyle> {
histogram[0] += 1; histogram[0] += 1;
} else { } else {
let amount = leading_count - prev_line_leading_count; let amount = leading_count - prev_line_leading_count;
if amount <= 8 { if amount <= MAX_INDENT as usize {
histogram[amount] += 1; histogram[amount] += 1;
} }
} }
@ -177,17 +183,17 @@ pub fn auto_detect_indent_style(document_text: &Rope) -> Option<IndentStyle> {
/// To determine indentation of a newly inserted line, figure out the indentation at the last col /// To determine indentation of a newly inserted line, figure out the indentation at the last col
/// of the previous line. /// of the previous line.
pub fn indent_level_for_line(line: RopeSlice, tab_width: usize) -> usize { pub fn indent_level_for_line(line: RopeSlice, tab_width: usize, indent_width: usize) -> usize {
let mut len = 0; let mut len = 0;
for ch in line.chars() { for ch in line.chars() {
match ch { match ch {
'\t' => len += tab_width, '\t' => len += tab_width_at(len, tab_width as u16),
' ' => len += 1, ' ' => len += 1,
_ => break, _ => break,
} }
} }
len / tab_width len / indent_width
} }
/// Computes for node and all ancestors whether they are the first node on their line. /// Computes for node and all ancestors whether they are the first node on their line.
@ -231,68 +237,121 @@ fn get_first_in_line(mut node: Node, new_line_byte_pos: Option<usize>) -> Vec<bo
/// This is usually constructed in one of 2 ways: /// This is usually constructed in one of 2 ways:
/// - Successively add indent captures to get the (added) indent from a single line /// - Successively add indent captures to get the (added) indent from a single line
/// - Successively add the indent results for each line /// - Successively add the indent results for each line
#[derive(Default)] /// The string that this indentation defines starts with the string contained in the align field (unless it is None), followed by:
/// - max(0, indent - outdent) tabs, if tabs are used for indentation
/// - max(0, indent - outdent)*indent_width spaces, if spaces are used for indentation
#[derive(Default, Debug, PartialEq, Eq, Clone)]
pub struct Indentation { pub struct Indentation {
/// The total indent (the number of indent levels) is defined as max(0, indent-outdent).
/// The string that this results in depends on the indent style (spaces or tabs, etc.)
indent: usize, indent: usize,
indent_always: usize,
outdent: usize, outdent: usize,
outdent_always: usize,
/// The alignment, as a string containing only tabs & spaces. Storing this as a string instead of e.g.
/// the (visual) width ensures that the alignment is preserved even if the tab width changes.
align: Option<String>,
} }
impl Indentation { impl Indentation {
/// Add some other [Indentation] to this. /// Add some other [Indentation] to this.
/// The added indent should be the total added indent from one line /// The added indent should be the total added indent from one line.
fn add_line(&mut self, added: &Indentation) { /// Indent should always be added starting from the bottom (or equivalently, the innermost tree-sitter node).
if added.indent > 0 && added.outdent == 0 { fn add_line(&mut self, added: Indentation) {
self.indent += 1; // Align overrides the indent from outer scopes.
} else if added.outdent > 0 && added.indent == 0 { if self.align.is_some() {
self.outdent += 1; return;
} }
if added.align.is_some() {
self.align = added.align;
return;
}
self.indent += added.indent;
self.indent_always += added.indent_always;
self.outdent += added.outdent;
self.outdent_always += added.outdent_always;
} }
/// Add an indent capture to this indent. /// Add an indent capture to this indent.
/// All the captures that are added in this way should be on the same line. /// Only captures that apply to the same line should be added together in this way (otherwise use `add_line`)
/// and the captures should be added starting from the innermost tree-sitter node (currently this only matters
/// if multiple `@align` patterns occur on the same line).
fn add_capture(&mut self, added: IndentCaptureType) { fn add_capture(&mut self, added: IndentCaptureType) {
match added { match added {
IndentCaptureType::Indent => { IndentCaptureType::Indent => {
if self.indent_always == 0 {
self.indent = 1; self.indent = 1;
} }
}
IndentCaptureType::IndentAlways => {
// any time we encounter an `indent.always` on the same line, we
// want to cancel out all regular indents
self.indent_always += 1;
self.indent = 0;
}
IndentCaptureType::Outdent => { IndentCaptureType::Outdent => {
if self.outdent_always == 0 {
self.outdent = 1; self.outdent = 1;
} }
} }
IndentCaptureType::OutdentAlways => {
self.outdent_always += 1;
self.outdent = 0;
}
IndentCaptureType::Align(align) => {
if self.align.is_none() {
self.align = Some(align);
}
} }
fn as_string(&self, indent_style: &IndentStyle) -> String { }
let indent_level = if self.indent >= self.outdent { }
self.indent - self.outdent fn into_string(self, indent_style: &IndentStyle) -> String {
let indent = self.indent_always + self.indent;
let outdent = self.outdent_always + self.outdent;
let indent_level = if indent >= outdent {
indent - outdent
} else { } else {
log::warn!("Encountered more outdent than indent nodes while calculating indentation: {} outdent, {} indent", self.outdent, self.indent); log::warn!("Encountered more outdent than indent nodes while calculating indentation: {} outdent, {} indent", self.outdent, self.indent);
0 0
}; };
indent_style.as_str().repeat(indent_level) let mut indent_string = if let Some(align) = self.align {
align
} else {
String::new()
};
indent_string.push_str(&indent_style.as_str().repeat(indent_level));
indent_string
} }
} }
/// An indent definition which corresponds to a capture from the indent query /// An indent definition which corresponds to a capture from the indent query
#[derive(Debug)]
struct IndentCapture { struct IndentCapture {
capture_type: IndentCaptureType, capture_type: IndentCaptureType,
scope: IndentScope, scope: IndentScope,
} }
#[derive(Clone, Copy)] #[derive(Debug, Clone, PartialEq)]
enum IndentCaptureType { enum IndentCaptureType {
Indent, Indent,
IndentAlways,
Outdent, Outdent,
OutdentAlways,
/// Alignment given as a string of whitespace
Align(String),
} }
impl IndentCaptureType { impl IndentCaptureType {
fn default_scope(&self) -> IndentScope { fn default_scope(&self) -> IndentScope {
match self { match self {
IndentCaptureType::Indent => IndentScope::Tail, IndentCaptureType::Indent | IndentCaptureType::IndentAlways => IndentScope::Tail,
IndentCaptureType::Outdent => IndentScope::All, IndentCaptureType::Outdent | IndentCaptureType::OutdentAlways => IndentScope::All,
IndentCaptureType::Align(_) => IndentScope::All,
} }
} }
} }
/// This defines which part of a node an [IndentCapture] applies to. /// This defines which part of a node an [IndentCapture] applies to.
/// Each [IndentCaptureType] has a default scope, but the scope can be changed /// Each [IndentCaptureType] has a default scope, but the scope can be changed
/// with `#set!` property declarations. /// with `#set!` property declarations.
#[derive(Clone, Copy)] #[derive(Debug, Clone, Copy)]
enum IndentScope { enum IndentScope {
/// The indent applies to the whole node /// The indent applies to the whole node
All, All,
@ -302,6 +361,7 @@ enum IndentScope {
/// A capture from the indent query which does not define an indent but extends /// A capture from the indent query which does not define an indent but extends
/// the range of a node. This is used before the indent is calculated. /// the range of a node. This is used before the indent is calculated.
#[derive(Debug)]
enum ExtendCapture { enum ExtendCapture {
Extend, Extend,
PreventOnce, PreventOnce,
@ -310,24 +370,41 @@ enum ExtendCapture {
/// The result of running a tree-sitter indent query. This stores for /// The result of running a tree-sitter indent query. This stores for
/// each node (identified by its ID) the relevant captures (already filtered /// each node (identified by its ID) the relevant captures (already filtered
/// by predicates). /// by predicates).
#[derive(Debug)]
struct IndentQueryResult { struct IndentQueryResult {
indent_captures: HashMap<usize, Vec<IndentCapture>>, indent_captures: HashMap<usize, Vec<IndentCapture>>,
extend_captures: HashMap<usize, Vec<ExtendCapture>>, extend_captures: HashMap<usize, Vec<ExtendCapture>>,
} }
fn get_node_start_line(node: Node, new_line_byte_pos: Option<usize>) -> usize {
let mut node_line = node.start_position().row;
// Adjust for the new line that will be inserted
if new_line_byte_pos.map_or(false, |pos| node.start_byte() >= pos) {
node_line += 1;
}
node_line
}
fn get_node_end_line(node: Node, new_line_byte_pos: Option<usize>) -> usize {
let mut node_line = node.end_position().row;
// Adjust for the new line that will be inserted (with a strict inequality since end_byte is exclusive)
if new_line_byte_pos.map_or(false, |pos| node.end_byte() > pos) {
node_line += 1;
}
node_line
}
fn query_indents( fn query_indents(
query: &Query, query: &Query,
syntax: &Syntax, syntax: &Syntax,
cursor: &mut QueryCursor, cursor: &mut QueryCursor,
text: RopeSlice, text: RopeSlice,
range: std::ops::Range<usize>, range: std::ops::Range<usize>,
// Position of the (optional) newly inserted line break. new_line_byte_pos: Option<usize>,
// Given as (line, byte_pos)
new_line_break: Option<(usize, usize)>,
) -> IndentQueryResult { ) -> IndentQueryResult {
let mut indent_captures: HashMap<usize, Vec<IndentCapture>> = HashMap::new(); let mut indent_captures: HashMap<usize, Vec<IndentCapture>> = HashMap::new();
let mut extend_captures: HashMap<usize, Vec<ExtendCapture>> = HashMap::new(); let mut extend_captures: HashMap<usize, Vec<ExtendCapture>> = HashMap::new();
cursor.set_byte_range(range); cursor.set_byte_range(range);
// Iterate over all captures from the query // Iterate over all captures from the query
for m in cursor.matches(query, syntax.tree().root_node(), RopeProvider(text)) { for m in cursor.matches(query, syntax.tree().root_node(), RopeProvider(text)) {
// Skip matches where not all custom predicates are fulfilled // Skip matches where not all custom predicates are fulfilled
@ -354,21 +431,13 @@ fn query_indents(
Some(QueryPredicateArg::Capture(capt1)), Some(QueryPredicateArg::Capture(capt1)),
Some(QueryPredicateArg::Capture(capt2)) Some(QueryPredicateArg::Capture(capt2))
) => { ) => {
let get_line_num = |node: Node| {
let mut node_line = node.start_position().row;
// Adjust for the new line that will be inserted
if let Some((line, byte)) = new_line_break {
if node_line==line && node.start_byte()>=byte {
node_line += 1;
}
}
node_line
};
let n1 = m.nodes_for_capture_index(*capt1).next(); let n1 = m.nodes_for_capture_index(*capt1).next();
let n2 = m.nodes_for_capture_index(*capt2).next(); let n2 = m.nodes_for_capture_index(*capt2).next();
match (n1, n2) { match (n1, n2) {
(Some(n1), Some(n2)) => { (Some(n1), Some(n2)) => {
let same_line = get_line_num(n1)==get_line_num(n2); let n1_line = get_node_start_line(n1, new_line_byte_pos);
let n2_line = get_node_start_line(n2, new_line_byte_pos);
let same_line = n1_line == n2_line;
same_line==(pred.operator.as_ref()=="same-line?") same_line==(pred.operator.as_ref()=="same-line?")
} }
_ => true, _ => true,
@ -379,6 +448,23 @@ fn query_indents(
} }
} }
} }
"one-line?" | "not-one-line?" => match pred.args.get(0) {
Some(QueryPredicateArg::Capture(capture_idx)) => {
let node = m.nodes_for_capture_index(*capture_idx).next();
match node {
Some(node) => {
let (start_line, end_line) = (get_node_start_line(node,new_line_byte_pos), get_node_end_line(node, new_line_byte_pos));
let one_line = end_line == start_line;
one_line != (pred.operator.as_ref() == "not-one-line?")
},
_ => true,
}
}
_ => {
panic!("Invalid indent query: Arguments to \"not-kind-eq?\" must be a capture and a string");
}
},
_ => { _ => {
panic!( panic!(
"Invalid indent query: Unknown predicate (\"{}\")", "Invalid indent query: Unknown predicate (\"{}\")",
@ -389,11 +475,28 @@ fn query_indents(
}) { }) {
continue; continue;
} }
// A list of pairs (node_id, indent_capture) that are added by this match.
// They cannot be added to indent_captures immediately since they may depend on other captures (such as an @anchor).
let mut added_indent_captures: Vec<(usize, IndentCapture)> = Vec::new();
// The row/column position of the optional anchor in this query
let mut anchor: Option<tree_sitter::Node> = None;
for capture in m.captures { for capture in m.captures {
let capture_name = query.capture_names()[capture.index as usize].as_str(); let capture_name = query.capture_names()[capture.index as usize].as_str();
let capture_type = match capture_name { let capture_type = match capture_name {
"indent" => IndentCaptureType::Indent, "indent" => IndentCaptureType::Indent,
"indent.always" => IndentCaptureType::IndentAlways,
"outdent" => IndentCaptureType::Outdent, "outdent" => IndentCaptureType::Outdent,
"outdent.always" => IndentCaptureType::OutdentAlways,
// The alignment will be updated to the correct value at the end, when the anchor is known.
"align" => IndentCaptureType::Align(String::from("")),
"anchor" => {
if anchor.is_some() {
log::error!("Invalid indent query: Encountered more than one @anchor in the same match.")
} else {
anchor = Some(capture.node);
}
continue;
}
"extend" => { "extend" => {
extend_captures extend_captures
.entry(capture.node.id()) .entry(capture.node.id())
@ -443,17 +546,52 @@ fn query_indents(
} }
} }
} }
added_indent_captures.push((capture.node.id(), indent_capture))
}
for (node_id, mut capture) in added_indent_captures {
// Set the anchor for all align queries.
if let IndentCaptureType::Align(_) = capture.capture_type {
let anchor = match anchor {
None => {
log::error!(
"Invalid indent query: @align requires an accompanying @anchor."
);
continue;
}
Some(anchor) => anchor,
};
// Create a string of tabs & spaces that should have the same width
// as the string that precedes the anchor (independent of the tab width).
let mut align = String::new();
for grapheme in RopeGraphemes::new(
text.line(anchor.start_position().row)
.byte_slice(0..anchor.start_position().column),
) {
if grapheme == "\t" {
align.push('\t');
} else {
align.extend(
std::iter::repeat(' ').take(grapheme_width(&Cow::from(grapheme))),
);
}
}
capture.capture_type = IndentCaptureType::Align(align);
}
indent_captures indent_captures
.entry(capture.node.id()) .entry(node_id)
// Most entries only need to contain a single IndentCapture
.or_insert_with(|| Vec::with_capacity(1)) .or_insert_with(|| Vec::with_capacity(1))
.push(indent_capture); .push(capture);
} }
} }
IndentQueryResult {
let result = IndentQueryResult {
indent_captures, indent_captures,
extend_captures, extend_captures,
} };
log::trace!("indent result = {:?}", result);
result
} }
/// Handle extend queries. deepest_preceding is the deepest descendant of node that directly precedes the cursor position. /// Handle extend queries. deepest_preceding is the deepest descendant of node that directly precedes the cursor position.
@ -466,6 +604,7 @@ fn extend_nodes<'a>(
text: RopeSlice, text: RopeSlice,
line: usize, line: usize,
tab_width: usize, tab_width: usize,
indent_width: usize,
) { ) {
let mut stop_extend = false; let mut stop_extend = false;
@ -490,10 +629,12 @@ fn extend_nodes<'a>(
if deepest_preceding.end_position().row == line { if deepest_preceding.end_position().row == line {
extend_node = true; extend_node = true;
} else { } else {
let cursor_indent = indent_level_for_line(text.line(line), tab_width); let cursor_indent =
indent_level_for_line(text.line(line), tab_width, indent_width);
let node_indent = indent_level_for_line( let node_indent = indent_level_for_line(
text.line(deepest_preceding.start_position().row), text.line(deepest_preceding.start_position().row),
tab_width, tab_width,
indent_width,
); );
if cursor_indent > node_indent { if cursor_indent > node_indent {
extend_node = true; extend_node = true;
@ -562,18 +703,21 @@ pub fn treesitter_indent_for_pos(
syntax: &Syntax, syntax: &Syntax,
indent_style: &IndentStyle, indent_style: &IndentStyle,
tab_width: usize, tab_width: usize,
indent_width: usize,
text: RopeSlice, text: RopeSlice,
line: usize, line: usize,
pos: usize, pos: usize,
new_line: bool, new_line: bool,
) -> Option<String> { ) -> Option<String> {
let byte_pos = text.char_to_byte(pos); let byte_pos = text.char_to_byte(pos);
let new_line_byte_pos = new_line.then_some(byte_pos);
// The innermost tree-sitter node which is considered for the indent // The innermost tree-sitter node which is considered for the indent
// computation. It may change if some predeceding node is extended // computation. It may change if some predeceding node is extended
let mut node = syntax let mut node = syntax
.tree() .tree()
.root_node() .root_node()
.descendant_for_byte_range(byte_pos, byte_pos)?; .descendant_for_byte_range(byte_pos, byte_pos)?;
let (query_result, deepest_preceding) = { let (query_result, deepest_preceding) = {
// The query range should intersect with all nodes directly preceding // The query range should intersect with all nodes directly preceding
// the position of the indent query in case one of them is extended. // the position of the indent query in case one of them is extended.
@ -604,13 +748,13 @@ pub fn treesitter_indent_for_pos(
&mut cursor, &mut cursor,
text, text,
query_range, query_range,
new_line.then(|| (line, byte_pos)), new_line_byte_pos,
); );
ts_parser.cursors.push(cursor); ts_parser.cursors.push(cursor);
(query_result, deepest_preceding) (query_result, deepest_preceding)
}) })
}; };
let indent_captures = query_result.indent_captures; let mut indent_captures = query_result.indent_captures;
let extend_captures = query_result.extend_captures; let extend_captures = query_result.extend_captures;
// Check for extend captures, potentially changing the node that the indent calculation starts with // Check for extend captures, potentially changing the node that the indent calculation starts with
@ -622,21 +766,26 @@ pub fn treesitter_indent_for_pos(
text, text,
line, line,
tab_width, tab_width,
indent_width,
); );
} }
let mut first_in_line = get_first_in_line(node, new_line.then(|| byte_pos)); let mut first_in_line = get_first_in_line(node, new_line.then_some(byte_pos));
let mut result = Indentation::default(); let mut result = Indentation::default();
// We always keep track of all the indent changes on one line, in order to only indent once // We always keep track of all the indent changes on one line, in order to only indent once
// even if there are multiple "indent" nodes on the same line // even if there are multiple "indent" nodes on the same line
let mut indent_for_line = Indentation::default(); let mut indent_for_line = Indentation::default();
let mut indent_for_line_below = Indentation::default(); let mut indent_for_line_below = Indentation::default();
loop { loop {
// This can safely be unwrapped because `first_in_line` contains // This can safely be unwrapped because `first_in_line` contains
// one entry for each ancestor of the node (which is what we iterate over) // one entry for each ancestor of the node (which is what we iterate over)
let is_first = *first_in_line.last().unwrap(); let is_first = *first_in_line.last().unwrap();
// Apply all indent definitions for this node
if let Some(definitions) = indent_captures.get(&node.id()) { // Apply all indent definitions for this node.
// Since we only iterate over each node once, we can remove the
// corresponding captures from the HashMap to avoid cloning them.
if let Some(definitions) = indent_captures.remove(&node.id()) {
for definition in definitions { for definition in definitions {
match definition.scope { match definition.scope {
IndentScope::All => { IndentScope::All => {
@ -654,28 +803,22 @@ pub fn treesitter_indent_for_pos(
} }
if let Some(parent) = node.parent() { if let Some(parent) = node.parent() {
let mut node_line = node.start_position().row; let node_line = get_node_start_line(node, new_line_byte_pos);
let mut parent_line = parent.start_position().row; let parent_line = get_node_start_line(parent, new_line_byte_pos);
if node_line == line && new_line {
// Also consider the line that will be inserted
if node.start_byte() >= byte_pos {
node_line += 1;
}
if parent.start_byte() >= byte_pos {
parent_line += 1;
}
};
if node_line != parent_line { if node_line != parent_line {
if node_line < line + (new_line as usize) {
// Don't add indent for the line below the line of the query // Don't add indent for the line below the line of the query
result.add_line(&indent_for_line_below); if node_line < line + (new_line as usize) {
result.add_line(indent_for_line_below);
} }
if node_line == parent_line + 1 { if node_line == parent_line + 1 {
indent_for_line_below = indent_for_line; indent_for_line_below = indent_for_line;
} else { } else {
result.add_line(&indent_for_line); result.add_line(indent_for_line);
indent_for_line_below = Indentation::default(); indent_for_line_below = Indentation::default();
} }
indent_for_line = Indentation::default(); indent_for_line = Indentation::default();
} }
@ -687,13 +830,13 @@ pub fn treesitter_indent_for_pos(
if (node.start_position().row < line) if (node.start_position().row < line)
|| (new_line && node.start_position().row == line && node.start_byte() < byte_pos) || (new_line && node.start_position().row == line && node.start_byte() < byte_pos)
{ {
result.add_line(&indent_for_line_below); result.add_line(indent_for_line_below);
} }
result.add_line(&indent_for_line); result.add_line(indent_for_line);
break; break;
} }
} }
Some(result.as_string(indent_style)) Some(result.into_string(indent_style))
} }
/// Returns the indentation for a new line. /// Returns the indentation for a new line.
@ -709,6 +852,7 @@ pub fn indent_for_newline(
line_before_end_pos: usize, line_before_end_pos: usize,
current_line: usize, current_line: usize,
) -> String { ) -> String {
let indent_width = indent_style.indent_width(tab_width);
if let (Some(query), Some(syntax)) = ( if let (Some(query), Some(syntax)) = (
language_config.and_then(|config| config.indent_query()), language_config.and_then(|config| config.indent_query()),
syntax, syntax,
@ -718,6 +862,7 @@ pub fn indent_for_newline(
syntax, syntax,
indent_style, indent_style,
tab_width, tab_width,
indent_width,
text, text,
line_before, line_before,
line_before_end_pos, line_before_end_pos,
@ -726,7 +871,7 @@ pub fn indent_for_newline(
return indent; return indent;
}; };
} }
let indent_level = indent_level_for_line(text.line(current_line), tab_width); let indent_level = indent_level_for_line(text.line(current_line), tab_width, indent_width);
indent_style.as_str().repeat(indent_level) indent_style.as_str().repeat(indent_level)
} }
@ -763,12 +908,156 @@ mod test {
#[test] #[test]
fn test_indent_level() { fn test_indent_level() {
let tab_width = 4; let tab_width = 4;
let indent_width = 4;
let line = Rope::from(" fn new"); // 8 spaces let line = Rope::from(" fn new"); // 8 spaces
assert_eq!(indent_level_for_line(line.slice(..), tab_width), 2); assert_eq!(
indent_level_for_line(line.slice(..), tab_width, indent_width),
2
);
let line = Rope::from("\t\t\tfn new"); // 3 tabs let line = Rope::from("\t\t\tfn new"); // 3 tabs
assert_eq!(indent_level_for_line(line.slice(..), tab_width), 3); assert_eq!(
indent_level_for_line(line.slice(..), tab_width, indent_width),
3
);
// mixed indentation // mixed indentation
let line = Rope::from("\t \tfn new"); // 1 tab, 4 spaces, tab let line = Rope::from("\t \tfn new"); // 1 tab, 4 spaces, tab
assert_eq!(indent_level_for_line(line.slice(..), tab_width), 3); assert_eq!(
indent_level_for_line(line.slice(..), tab_width, indent_width),
3
);
}
#[test]
fn test_large_indent_level() {
let tab_width = 16;
let indent_width = 16;
let line = Rope::from(" fn new"); // 16 spaces
assert_eq!(
indent_level_for_line(line.slice(..), tab_width, indent_width),
1
);
let line = Rope::from(" fn new"); // 32 spaces
assert_eq!(
indent_level_for_line(line.slice(..), tab_width, indent_width),
2
);
}
#[test]
fn add_capture() {
let indent = || Indentation {
indent: 1,
..Default::default()
};
let indent_always = || Indentation {
indent_always: 1,
..Default::default()
};
let outdent = || Indentation {
outdent: 1,
..Default::default()
};
let outdent_always = || Indentation {
outdent_always: 1,
..Default::default()
};
let add_capture = |mut indent: Indentation, capture| {
indent.add_capture(capture);
indent
};
// adding an indent to no indent makes an indent
assert_eq!(
indent(),
add_capture(Indentation::default(), IndentCaptureType::Indent)
);
assert_eq!(
indent_always(),
add_capture(Indentation::default(), IndentCaptureType::IndentAlways)
);
assert_eq!(
outdent(),
add_capture(Indentation::default(), IndentCaptureType::Outdent)
);
assert_eq!(
outdent_always(),
add_capture(Indentation::default(), IndentCaptureType::OutdentAlways)
);
// adding an indent to an already indented has no effect
assert_eq!(indent(), add_capture(indent(), IndentCaptureType::Indent));
assert_eq!(
outdent(),
add_capture(outdent(), IndentCaptureType::Outdent)
);
// adding an always to a regular makes it always
assert_eq!(
indent_always(),
add_capture(indent(), IndentCaptureType::IndentAlways)
);
assert_eq!(
outdent_always(),
add_capture(outdent(), IndentCaptureType::OutdentAlways)
);
// adding an always to an always is additive
assert_eq!(
Indentation {
indent_always: 2,
..Default::default()
},
add_capture(indent_always(), IndentCaptureType::IndentAlways)
);
assert_eq!(
Indentation {
outdent_always: 2,
..Default::default()
},
add_capture(outdent_always(), IndentCaptureType::OutdentAlways)
);
// adding regular to always should be associative
assert_eq!(
Indentation {
indent_always: 1,
..Default::default()
},
add_capture(
add_capture(indent(), IndentCaptureType::Indent),
IndentCaptureType::IndentAlways
)
);
assert_eq!(
Indentation {
indent_always: 1,
..Default::default()
},
add_capture(
add_capture(indent(), IndentCaptureType::IndentAlways),
IndentCaptureType::Indent
)
);
assert_eq!(
Indentation {
outdent_always: 1,
..Default::default()
},
add_capture(
add_capture(outdent(), IndentCaptureType::Outdent),
IndentCaptureType::OutdentAlways
)
);
assert_eq!(
Indentation {
outdent_always: 1,
..Default::default()
},
add_capture(
add_capture(outdent(), IndentCaptureType::OutdentAlways),
IndentCaptureType::Outdent
)
);
} }
} }

@ -6,6 +6,8 @@ pub mod comment;
pub mod config; pub mod config;
pub mod diagnostic; pub mod diagnostic;
pub mod diff; pub mod diff;
pub mod doc_formatter;
pub mod fuzzy;
pub mod graphemes; pub mod graphemes;
pub mod history; pub mod history;
pub mod increment; pub mod increment;
@ -17,13 +19,13 @@ pub mod movement;
pub mod object; pub mod object;
pub mod path; pub mod path;
mod position; mod position;
pub mod register;
pub mod search; pub mod search;
pub mod selection; pub mod selection;
pub mod shellwords; pub mod shellwords;
pub mod surround; pub mod surround;
pub mod syntax; pub mod syntax;
pub mod test; pub mod test;
pub mod text_annotations;
pub mod textobject; pub mod textobject;
mod transaction; mod transaction;
pub mod wrap; pub mod wrap;
@ -34,55 +36,14 @@ pub mod unicode {
pub use unicode_width as width; pub use unicode_width as width;
} }
pub use helix_loader::find_workspace;
pub fn find_first_non_whitespace_char(line: RopeSlice) -> Option<usize> { pub fn find_first_non_whitespace_char(line: RopeSlice) -> Option<usize> {
line.chars().position(|ch| !ch.is_whitespace()) line.chars().position(|ch| !ch.is_whitespace())
} }
mod rope_reader;
/// Find project root. pub use rope_reader::RopeReader;
///
/// Order of detection:
/// * Top-most folder containing a root marker in current git repository
/// * Git repository root if no marker detected
/// * Top-most folder containing a root marker if not git repository detected
/// * Current working directory as fallback
pub fn find_root(root: Option<&str>, root_markers: &[String]) -> std::path::PathBuf {
let current_dir = std::env::current_dir().expect("unable to determine current directory");
let root = match root {
Some(root) => {
let root = std::path::Path::new(root);
if root.is_absolute() {
root.to_path_buf()
} else {
current_dir.join(root)
}
}
None => current_dir.clone(),
};
let mut top_marker = None;
for ancestor in root.ancestors() {
if root_markers
.iter()
.any(|marker| ancestor.join(marker).exists())
{
top_marker = Some(ancestor);
}
if ancestor.join(".git").is_dir() {
// Top marker is repo root if not root marker was detected yet
if top_marker.is_none() {
top_marker = Some(ancestor);
}
// Don't go higher than repo if we're in one
break;
}
}
// Return the found top marker or the current_dir as fallback
top_marker.map_or(current_dir, |a| a.to_path_buf())
}
pub use ropey::{self, str_utils, Rope, RopeBuilder, RopeSlice}; pub use ropey::{self, str_utils, Rope, RopeBuilder, RopeSlice};
// pub use tendril::StrTendril as Tendril; // pub use tendril::StrTendril as Tendril;
@ -95,13 +56,17 @@ pub use {regex, tree_sitter};
pub use graphemes::RopeGraphemes; pub use graphemes::RopeGraphemes;
pub use position::{ pub use position::{
coords_at_pos, pos_at_coords, pos_at_visual_coords, visual_coords_at_pos, Position, char_idx_at_visual_offset, coords_at_pos, pos_at_coords, visual_offset_from_anchor,
visual_offset_from_block, Position, VisualOffsetError,
}; };
#[allow(deprecated)]
pub use position::{pos_at_visual_coords, visual_coords_at_pos};
pub use selection::{Range, Selection}; pub use selection::{Range, Selection};
pub use smallvec::{smallvec, SmallVec}; pub use smallvec::{smallvec, SmallVec};
pub use syntax::Syntax; pub use syntax::Syntax;
pub use diagnostic::Diagnostic; pub use diagnostic::Diagnostic;
pub use line_ending::{LineEnding, DEFAULT_LINE_ENDING}; pub use line_ending::{LineEnding, NATIVE_LINE_ENDING};
pub use transaction::{Assoc, Change, ChangeSet, Operation, Transaction}; pub use transaction::{Assoc, Change, ChangeSet, Deletion, Operation, Transaction};

@ -1,9 +1,9 @@
use crate::{Rope, RopeSlice}; use crate::{Rope, RopeSlice};
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub const DEFAULT_LINE_ENDING: LineEnding = LineEnding::Crlf; pub const NATIVE_LINE_ENDING: LineEnding = LineEnding::Crlf;
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
pub const DEFAULT_LINE_ENDING: LineEnding = LineEnding::LF; pub const NATIVE_LINE_ENDING: LineEnding = LineEnding::LF;
/// Represents one of the valid Unicode line endings. /// Represents one of the valid Unicode line endings.
#[derive(PartialEq, Eq, Copy, Clone, Debug)] #[derive(PartialEq, Eq, Copy, Clone, Debug)]
@ -203,6 +203,13 @@ pub fn line_end_char_index(slice: &RopeSlice, line: usize) -> usize {
.unwrap_or(0) .unwrap_or(0)
} }
pub fn line_end_byte_index(slice: &RopeSlice, line: usize) -> usize {
slice.line_to_byte(line + 1)
- get_line_ending(&slice.line(line))
.map(|le| le.as_str().len())
.unwrap_or(0)
}
/// Fetches line `line_idx` from the passed rope slice, sans any line ending. /// Fetches line `line_idx` from the passed rope slice, sans any line ending.
pub fn line_without_line_ending<'a>(slice: &'a RopeSlice, line_idx: usize) -> RopeSlice<'a> { pub fn line_without_line_ending<'a>(slice: &'a RopeSlice, line_idx: usize) -> RopeSlice<'a> {
let start = slice.line_to_char(line_idx); let start = slice.line_to_char(line_idx);

@ -1,7 +1,15 @@
use std::iter;
use ropey::RopeSlice;
use tree_sitter::Node; use tree_sitter::Node;
use crate::{Rope, Syntax}; use crate::movement::Direction::{self, Backward, Forward};
use crate::Syntax;
const MAX_PLAINTEXT_SCAN: usize = 10000;
const MATCH_LIMIT: usize = 16;
// Limit matching pairs to only ( ) { } [ ] < > ' ' " "
const PAIRS: &[(char, char)] = &[ const PAIRS: &[(char, char)] = &[
('(', ')'), ('(', ')'),
('{', '}'), ('{', '}'),
@ -11,17 +19,17 @@ const PAIRS: &[(char, char)] = &[
('\"', '\"'), ('\"', '\"'),
]; ];
// limit matching pairs to only ( ) { } [ ] < > ' ' " " /// Returns the position of the matching bracket under cursor.
///
// Returns the position of the matching bracket under cursor. /// If the cursor is on the opening bracket, the position of
// /// the closing bracket is returned. If the cursor on the closing
// If the cursor is one the opening bracket, the position of /// bracket, the position of the opening bracket is returned.
// the closing bracket is returned. If the cursor in the closing ///
// bracket, the position of the opening bracket is returned. /// If the cursor is not on a bracket, `None` is returned.
// ///
// If the cursor is not on a bracket, `None` is returned. /// If no matching bracket is found, `None` is returned.
#[must_use] #[must_use]
pub fn find_matching_bracket(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<usize> { pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
if pos >= doc.len_chars() || !is_valid_bracket(doc.char(pos)) { if pos >= doc.len_chars() || !is_valid_bracket(doc.char(pos)) {
return None; return None;
} }
@ -39,17 +47,23 @@ pub fn find_matching_bracket(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<
// //
// If no surrounding scope is found, the function returns `None`. // If no surrounding scope is found, the function returns `None`.
#[must_use] #[must_use]
pub fn find_matching_bracket_fuzzy(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<usize> { pub fn find_matching_bracket_fuzzy(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
find_pair(syntax, doc, pos, true) find_pair(syntax, doc, pos, true)
} }
fn find_pair(syntax: &Syntax, doc: &Rope, pos: usize, traverse_parents: bool) -> Option<usize> { fn find_pair(
syntax: &Syntax,
doc: RopeSlice,
pos_: usize,
traverse_parents: bool,
) -> Option<usize> {
let tree = syntax.tree(); let tree = syntax.tree();
let pos = doc.char_to_byte(pos); let pos = doc.char_to_byte(pos_);
let mut node = tree.root_node().named_descendant_for_byte_range(pos, pos)?; let mut node = tree.root_node().descendant_for_byte_range(pos, pos)?;
loop { loop {
if node.is_named() {
let (start_byte, end_byte) = surrounding_bytes(doc, &node)?; let (start_byte, end_byte) = surrounding_bytes(doc, &node)?;
let (start_char, end_char) = (doc.byte_to_char(start_byte), doc.byte_to_char(end_byte)); let (start_char, end_char) = (doc.byte_to_char(start_byte), doc.byte_to_char(end_byte));
@ -57,28 +71,135 @@ fn find_pair(syntax: &Syntax, doc: &Rope, pos: usize, traverse_parents: bool) ->
if end_byte == pos { if end_byte == pos {
return Some(start_char); return Some(start_char);
} }
// We return the end char if the cursor is either on the start char // We return the end char if the cursor is either on the start char
// or at some arbitrary position between start and end char. // or at some arbitrary position between start and end char.
if traverse_parents || start_byte == pos {
return Some(end_char); return Some(end_char);
} }
}
}
// this node itselt wasn't a pair but maybe its siblings are
if traverse_parents { // check if we are *on* the pair (special cased so we don't look
node = node.parent()?; // at the current node twice and to jump to the start on that case)
} else { if let Some(open) = as_close_pair(doc, &node) {
if let Some(pair_start) = find_pair_end(doc, node.prev_sibling(), open, Backward) {
return Some(pair_start);
}
}
if !traverse_parents {
// check if we are *on* the opening pair (special cased here as
// an opptimization since we only care about bracket on the cursor
// here)
if let Some(close) = as_open_pair(doc, &node) {
if let Some(pair_end) = find_pair_end(doc, node.next_sibling(), close, Forward) {
return Some(pair_end);
}
}
if node.is_named() {
break;
}
}
for close in
iter::successors(node.next_sibling(), |node| node.next_sibling()).take(MATCH_LIMIT)
{
let Some(open) = as_close_pair(doc, &close) else {
continue;
};
if find_pair_end(doc, Some(node), open, Backward).is_some() {
return doc.try_byte_to_char(close.start_byte()).ok();
}
}
let Some(parent) = node.parent() else {
break;
};
node = parent;
}
let node = tree.root_node().named_descendant_for_byte_range(pos, pos)?;
if node.child_count() != 0 {
return None;
}
let node_start = doc.byte_to_char(node.start_byte());
find_matching_bracket_plaintext(doc.byte_slice(node.byte_range()), pos_ - node_start)
.map(|pos| pos + node_start)
}
/// Returns the position of the matching bracket under cursor.
/// This function works on plain text and ignores tree-sitter grammar.
/// The search is limited to `MAX_PLAINTEXT_SCAN` characters
///
/// If the cursor is on the opening bracket, the position of
/// the closing bracket is returned. If the cursor on the closing
/// bracket, the position of the opening bracket is returned.
///
/// If the cursor is not on a bracket, `None` is returned.
///
/// If no matching bracket is found, `None` is returned.
#[must_use]
pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Option<usize> {
// Don't do anything when the cursor is not on top of a bracket.
let bracket = doc.char(cursor_pos);
if !is_valid_bracket(bracket) {
return None; return None;
} }
// Determine the direction of the matching.
let is_fwd = is_forward_bracket(bracket);
let chars_iter = if is_fwd {
doc.chars_at(cursor_pos + 1)
} else {
doc.chars_at(cursor_pos).reversed()
};
let mut open_cnt = 1;
for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() {
if candidate == bracket {
open_cnt += 1;
} else if is_valid_pair(
doc,
if is_fwd {
cursor_pos
} else {
cursor_pos - i - 1
},
if is_fwd {
cursor_pos + i + 1
} else {
cursor_pos
},
) {
// Return when all pending brackets have been closed.
if open_cnt == 1 {
return Some(if is_fwd {
cursor_pos + i + 1
} else {
cursor_pos - i - 1
});
}
open_cnt -= 1;
}
} }
None
} }
fn is_valid_bracket(c: char) -> bool { fn is_valid_bracket(c: char) -> bool {
PAIRS.iter().any(|(l, r)| *l == c || *r == c) PAIRS.iter().any(|(l, r)| *l == c || *r == c)
} }
fn is_valid_pair(doc: &Rope, start_char: usize, end_char: usize) -> bool { fn is_forward_bracket(c: char) -> bool {
PAIRS.iter().any(|(l, _)| *l == c)
}
fn is_valid_pair(doc: RopeSlice, start_char: usize, end_char: usize) -> bool {
PAIRS.contains(&(doc.char(start_char), doc.char(end_char))) PAIRS.contains(&(doc.char(start_char), doc.char(end_char)))
} }
fn surrounding_bytes(doc: &Rope, node: &Node) -> Option<(usize, usize)> { fn surrounding_bytes(doc: RopeSlice, node: &Node) -> Option<(usize, usize)> {
let len = doc.len_bytes(); let len = doc.len_bytes();
let start_byte = node.start_byte(); let start_byte = node.start_byte();
@ -90,3 +211,85 @@ fn surrounding_bytes(doc: &Rope, node: &Node) -> Option<(usize, usize)> {
Some((start_byte, end_byte)) Some((start_byte, end_byte))
} }
/// Tests if this node is a pair close char and returns the expected open char
fn as_close_pair(doc: RopeSlice, node: &Node) -> Option<char> {
let close = as_char(doc, node)?.1;
PAIRS
.iter()
.find_map(|&(open, close_)| (close_ == close).then_some(open))
}
/// Checks if `node` or its siblings (at most MATCH_LIMIT nodes) is the specified closing char
///
/// # Returns
///
/// The position of the found node or `None` otherwise
fn find_pair_end(
doc: RopeSlice,
node: Option<Node>,
end_char: char,
direction: Direction,
) -> Option<usize> {
let advance = match direction {
Forward => Node::next_sibling,
Backward => Node::prev_sibling,
};
iter::successors(node, advance)
.take(MATCH_LIMIT)
.find_map(|node| {
let (pos, c) = as_char(doc, &node)?;
(end_char == c).then_some(pos)
})
}
/// Tests if this node is a pair close char and returns the expected open char
fn as_open_pair(doc: RopeSlice, node: &Node) -> Option<char> {
let open = as_char(doc, node)?.1;
PAIRS
.iter()
.find_map(|&(open_, close)| (open_ == open).then_some(close))
}
/// If node is a single char return it (and its char position)
fn as_char(doc: RopeSlice, node: &Node) -> Option<(usize, char)> {
// TODO: multi char/non ASCII pairs
if node.byte_range().len() != 1 {
return None;
}
let pos = doc.try_byte_to_char(node.start_byte()).ok()?;
Some((pos, doc.char(pos)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_find_matching_bracket_current_line_plaintext() {
let assert = |input: &str, pos, expected| {
let input = RopeSlice::from(input);
let actual = find_matching_bracket_plaintext(input, pos);
assert_eq!(expected, actual.unwrap());
let actual = find_matching_bracket_plaintext(input, expected);
assert_eq!(pos, actual.unwrap(), "expected symmetrical behaviour");
};
assert("(hello)", 0, 6);
assert("((hello))", 0, 8);
assert("((hello))", 1, 7);
assert("(((hello)))", 2, 8);
assert("key: ${value}", 6, 12);
assert("key: ${value} # (some comment)", 16, 29);
assert("(paren (paren {bracket}))", 0, 24);
assert("(paren (paren {bracket}))", 7, 23);
assert("(paren (paren {bracket}))", 14, 22);
assert("(prev line\n ) (middle) ( \n next line)", 0, 12);
assert("(prev line\n ) (middle) ( \n next line)", 14, 21);
assert("(prev line\n ) (middle) ( \n next line)", 23, 36);
}
}

@ -1,19 +1,22 @@
use std::iter; use std::{cmp::Reverse, iter};
use ropey::iter::Chars; use ropey::iter::Chars;
use tree_sitter::{Node, QueryCursor}; use tree_sitter::{Node, QueryCursor};
use crate::{ use crate::{
char_idx_at_visual_offset,
chars::{categorize_char, char_is_line_ending, CharCategory}, chars::{categorize_char, char_is_line_ending, CharCategory},
doc_formatter::TextFormat,
graphemes::{ graphemes::{
next_grapheme_boundary, nth_next_grapheme_boundary, nth_prev_grapheme_boundary, next_grapheme_boundary, nth_next_grapheme_boundary, nth_prev_grapheme_boundary,
prev_grapheme_boundary, prev_grapheme_boundary,
}, },
line_ending::rope_is_line_ending, line_ending::rope_is_line_ending,
pos_at_visual_coords, position::char_idx_at_visual_block_offset,
syntax::LanguageConfiguration, syntax::LanguageConfiguration,
text_annotations::TextAnnotations,
textobject::TextObject, textobject::TextObject,
visual_coords_at_pos, Position, Range, RopeSlice, visual_offset_from_block, Range, RopeSlice, Selection, Syntax,
}; };
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
@ -34,7 +37,8 @@ pub fn move_horizontally(
dir: Direction, dir: Direction,
count: usize, count: usize,
behaviour: Movement, behaviour: Movement,
_: usize, _: &TextFormat,
_: &mut TextAnnotations,
) -> Range { ) -> Range {
let pos = range.cursor(slice); let pos = range.cursor(slice);
@ -48,35 +52,116 @@ pub fn move_horizontally(
range.put_cursor(slice, new_pos, behaviour == Movement::Extend) range.put_cursor(slice, new_pos, behaviour == Movement::Extend)
} }
pub fn move_vertically_visual(
slice: RopeSlice,
range: Range,
dir: Direction,
count: usize,
behaviour: Movement,
text_fmt: &TextFormat,
annotations: &mut TextAnnotations,
) -> Range {
if !text_fmt.soft_wrap {
return move_vertically(slice, range, dir, count, behaviour, text_fmt, annotations);
}
annotations.clear_line_annotations();
let pos = range.cursor(slice);
// Compute the current position's 2d coordinates.
let (visual_pos, block_off) = visual_offset_from_block(slice, pos, pos, text_fmt, annotations);
let new_col = range
.old_visual_position
.map_or(visual_pos.col as u32, |(_, col)| col);
// Compute the new position.
let mut row_off = match dir {
Direction::Forward => count as isize,
Direction::Backward => -(count as isize),
};
// TODO how to handle inline annotations that span an entire visual line (very unlikely).
// Compute visual offset relative to block start to avoid trasversing the block twice
row_off += visual_pos.row as isize;
let new_pos = char_idx_at_visual_offset(
slice,
block_off,
row_off,
new_col as usize,
text_fmt,
annotations,
)
.0;
// Special-case to avoid moving to the end of the last non-empty line.
if behaviour == Movement::Extend && slice.line(slice.char_to_line(new_pos)).len_chars() == 0 {
return range;
}
let mut new_range = range.put_cursor(slice, new_pos, behaviour == Movement::Extend);
new_range.old_visual_position = Some((0, new_col));
new_range
}
pub fn move_vertically( pub fn move_vertically(
slice: RopeSlice, slice: RopeSlice,
range: Range, range: Range,
dir: Direction, dir: Direction,
count: usize, count: usize,
behaviour: Movement, behaviour: Movement,
tab_width: usize, text_fmt: &TextFormat,
annotations: &mut TextAnnotations,
) -> Range { ) -> Range {
annotations.clear_line_annotations();
let pos = range.cursor(slice); let pos = range.cursor(slice);
let line_idx = slice.char_to_line(pos);
let line_start = slice.line_to_char(line_idx);
// Compute the current position's 2d coordinates. // Compute the current position's 2d coordinates.
let Position { row, col } = visual_coords_at_pos(slice, pos, tab_width); let visual_pos = visual_offset_from_block(slice, line_start, pos, text_fmt, annotations).0;
let horiz = range.horiz.unwrap_or(col as u32); let (mut new_row, new_col) = range
.old_visual_position
.map_or((visual_pos.row as u32, visual_pos.col as u32), |pos| pos);
new_row = new_row.max(visual_pos.row as u32);
let line_idx = slice.char_to_line(pos);
// Compute the new position. // Compute the new position.
let new_row = match dir { let mut new_line_idx = match dir {
Direction::Forward => (row + count).min(slice.len_lines().saturating_sub(1)), Direction::Forward => line_idx.saturating_add(count),
Direction::Backward => row.saturating_sub(count), Direction::Backward => line_idx.saturating_sub(count),
};
let line = if new_line_idx >= slice.len_lines() - 1 {
// there is no line terminator for the last line
// so the logic below is not necessary here
new_line_idx = slice.len_lines() - 1;
slice
} else {
// char_idx_at_visual_block_offset returns a one-past-the-end index
// in case it reaches the end of the slice
// to avoid moving to the nextline in that case the line terminator is removed from the line
let new_line_end = prev_grapheme_boundary(slice, slice.line_to_char(new_line_idx + 1));
slice.slice(..new_line_end)
}; };
let new_col = col.max(horiz as usize);
let new_pos = pos_at_visual_coords(slice, Position::new(new_row, new_col), tab_width); let new_line_start = line.line_to_char(new_line_idx);
let (new_pos, _) = char_idx_at_visual_block_offset(
line,
new_line_start,
new_row as usize,
new_col as usize,
text_fmt,
annotations,
);
// Special-case to avoid moving to the end of the last non-empty line. // Special-case to avoid moving to the end of the last non-empty line.
if behaviour == Movement::Extend && slice.line(new_row).len_chars() == 0 { if behaviour == Movement::Extend && slice.line(new_line_idx).len_chars() == 0 {
return range; return range;
} }
let mut new_range = range.put_cursor(slice, new_pos, behaviour == Movement::Extend); let mut new_range = range.put_cursor(slice, new_pos, behaviour == Movement::Extend);
new_range.horiz = Some(horiz); new_range.old_visual_position = Some((new_row, new_col));
new_range new_range
} }
@ -92,6 +177,10 @@ pub fn move_prev_word_start(slice: RopeSlice, range: Range, count: usize) -> Ran
word_move(slice, range, count, WordMotionTarget::PrevWordStart) word_move(slice, range, count, WordMotionTarget::PrevWordStart)
} }
pub fn move_prev_word_end(slice: RopeSlice, range: Range, count: usize) -> Range {
word_move(slice, range, count, WordMotionTarget::PrevWordEnd)
}
pub fn move_next_long_word_start(slice: RopeSlice, range: Range, count: usize) -> Range { pub fn move_next_long_word_start(slice: RopeSlice, range: Range, count: usize) -> Range {
word_move(slice, range, count, WordMotionTarget::NextLongWordStart) word_move(slice, range, count, WordMotionTarget::NextLongWordStart)
} }
@ -104,8 +193,8 @@ pub fn move_prev_long_word_start(slice: RopeSlice, range: Range, count: usize) -
word_move(slice, range, count, WordMotionTarget::PrevLongWordStart) word_move(slice, range, count, WordMotionTarget::PrevLongWordStart)
} }
pub fn move_prev_word_end(slice: RopeSlice, range: Range, count: usize) -> Range { pub fn move_prev_long_word_end(slice: RopeSlice, range: Range, count: usize) -> Range {
word_move(slice, range, count, WordMotionTarget::PrevWordEnd) word_move(slice, range, count, WordMotionTarget::PrevLongWordEnd)
} }
fn word_move(slice: RopeSlice, range: Range, count: usize, target: WordMotionTarget) -> Range { fn word_move(slice: RopeSlice, range: Range, count: usize, target: WordMotionTarget) -> Range {
@ -114,6 +203,7 @@ fn word_move(slice: RopeSlice, range: Range, count: usize, target: WordMotionTar
WordMotionTarget::PrevWordStart WordMotionTarget::PrevWordStart
| WordMotionTarget::PrevLongWordStart | WordMotionTarget::PrevLongWordStart
| WordMotionTarget::PrevWordEnd | WordMotionTarget::PrevWordEnd
| WordMotionTarget::PrevLongWordEnd
); );
// Special-case early-out. // Special-case early-out.
@ -142,9 +232,15 @@ fn word_move(slice: RopeSlice, range: Range, count: usize, target: WordMotionTar
}; };
// Do the main work. // Do the main work.
(0..count).fold(start_range, |r, _| { let mut range = start_range;
slice.chars_at(r.head).range_to_target(target, r) for _ in 0..count {
}) let next_range = slice.chars_at(range.head).range_to_target(target, range);
if range == next_range {
break;
}
range = next_range;
}
range
} }
pub fn move_prev_paragraph( pub fn move_prev_paragraph(
@ -166,6 +262,7 @@ pub fn move_prev_paragraph(
let mut lines = slice.lines_at(line); let mut lines = slice.lines_at(line);
lines.reverse(); lines.reverse();
let mut lines = lines.map(rope_is_line_ending).peekable(); let mut lines = lines.map(rope_is_line_ending).peekable();
let mut last_line = line;
for _ in 0..count { for _ in 0..count {
while lines.next_if(|&e| e).is_some() { while lines.next_if(|&e| e).is_some() {
line -= 1; line -= 1;
@ -173,6 +270,10 @@ pub fn move_prev_paragraph(
while lines.next_if(|&e| !e).is_some() { while lines.next_if(|&e| !e).is_some() {
line -= 1; line -= 1;
} }
if line == last_line {
break;
}
last_line = line;
} }
let head = slice.line_to_char(line); let head = slice.line_to_char(line);
@ -208,6 +309,7 @@ pub fn move_next_paragraph(
line += 1; line += 1;
} }
let mut lines = slice.lines_at(line).map(rope_is_line_ending).peekable(); let mut lines = slice.lines_at(line).map(rope_is_line_ending).peekable();
let mut last_line = line;
for _ in 0..count { for _ in 0..count {
while lines.next_if(|&e| !e).is_some() { while lines.next_if(|&e| !e).is_some() {
line += 1; line += 1;
@ -215,6 +317,10 @@ pub fn move_next_paragraph(
while lines.next_if(|&e| e).is_some() { while lines.next_if(|&e| e).is_some() {
line += 1; line += 1;
} }
if line == last_line {
break;
}
last_line = line;
} }
let head = slice.line_to_char(line); let head = slice.line_to_char(line);
let anchor = if behavior == Movement::Move { let anchor = if behavior == Movement::Move {
@ -276,6 +382,7 @@ pub enum WordMotionTarget {
NextLongWordStart, NextLongWordStart,
NextLongWordEnd, NextLongWordEnd,
PrevLongWordStart, PrevLongWordStart,
PrevLongWordEnd,
} }
pub trait CharHelpers { pub trait CharHelpers {
@ -292,6 +399,7 @@ impl CharHelpers for Chars<'_> {
WordMotionTarget::PrevWordStart WordMotionTarget::PrevWordStart
| WordMotionTarget::PrevLongWordStart | WordMotionTarget::PrevLongWordStart
| WordMotionTarget::PrevWordEnd | WordMotionTarget::PrevWordEnd
| WordMotionTarget::PrevLongWordEnd
); );
// Reverse the iterator if needed for the motion direction. // Reverse the iterator if needed for the motion direction.
@ -378,7 +486,7 @@ fn reached_target(target: WordMotionTarget, prev_ch: char, next_ch: char) -> boo
is_word_boundary(prev_ch, next_ch) is_word_boundary(prev_ch, next_ch)
&& (!prev_ch.is_whitespace() || char_is_line_ending(next_ch)) && (!prev_ch.is_whitespace() || char_is_line_ending(next_ch))
} }
WordMotionTarget::NextLongWordStart => { WordMotionTarget::NextLongWordStart | WordMotionTarget::PrevLongWordEnd => {
is_long_word_boundary(prev_ch, next_ch) is_long_word_boundary(prev_ch, next_ch)
&& (char_is_line_ending(next_ch) || !next_ch.is_whitespace()) && (char_is_line_ending(next_ch) || !next_ch.is_whitespace())
} }
@ -419,10 +527,10 @@ pub fn goto_treesitter_object(
let node = match dir { let node = match dir {
Direction::Forward => nodes Direction::Forward => nodes
.filter(|n| n.start_byte() > byte_pos) .filter(|n| n.start_byte() > byte_pos)
.min_by_key(|n| n.start_byte())?, .min_by_key(|n| (n.start_byte(), Reverse(n.end_byte())))?,
Direction::Backward => nodes Direction::Backward => nodes
.filter(|n| n.end_byte() < byte_pos) .filter(|n| n.end_byte() < byte_pos)
.max_by_key(|n| n.end_byte())?, .max_by_key(|n| (n.end_byte(), Reverse(n.start_byte())))?,
}; };
let len = slice.len_bytes(); let len = slice.len_bytes();
@ -438,7 +546,93 @@ pub fn goto_treesitter_object(
// head of range should be at beginning // head of range should be at beginning
Some(Range::new(start_char, end_char)) Some(Range::new(start_char, end_char))
}; };
(0..count).fold(range, |range, _| get_range(range).unwrap_or(range)) let mut last_range = range;
for _ in 0..count {
match get_range(last_range) {
Some(r) if r != last_range => last_range = r,
_ => break,
}
}
last_range
}
fn find_parent_start(mut node: Node) -> Option<Node> {
let start = node.start_byte();
while node.start_byte() >= start || !node.is_named() {
node = node.parent()?;
}
Some(node)
}
pub fn move_parent_node_end(
syntax: &Syntax,
text: RopeSlice,
selection: Selection,
dir: Direction,
movement: Movement,
) -> Selection {
let tree = syntax.tree();
selection.transform(|range| {
let start_from = text.char_to_byte(range.from());
let start_to = text.char_to_byte(range.to());
let mut node = match tree
.root_node()
.named_descendant_for_byte_range(start_from, start_to)
{
Some(node) => node,
None => {
log::debug!(
"no descendant found for byte range: {} - {}",
start_from,
start_to
);
return range;
}
};
let mut end_head = match dir {
// moving forward, we always want to move one past the end of the
// current node, so use the end byte of the current node, which is an exclusive
// end of the range
Direction::Forward => text.byte_to_char(node.end_byte()),
// moving backward, we want the cursor to land on the start char of
// the current node, or if it is already at the start of a node, to traverse up to
// the parent
Direction::Backward => {
let end_head = text.byte_to_char(node.start_byte());
// if we're already on the beginning, look up to the parent
if end_head == range.cursor(text) {
node = find_parent_start(node).unwrap_or(node);
text.byte_to_char(node.start_byte())
} else {
end_head
}
}
};
if movement == Movement::Move {
// preserve direction of original range
if range.direction() == Direction::Forward {
Range::new(end_head, end_head + 1)
} else {
Range::new(end_head + 1, end_head)
}
} else {
// if we end up with a forward range, then adjust it to be one past
// where we want
if end_head >= range.anchor {
end_head += 1;
}
Range::new(range.anchor, end_head)
}
})
} }
#[cfg(test)] #[cfg(test)]
@ -473,7 +667,16 @@ mod test {
assert_eq!( assert_eq!(
coords_at_pos( coords_at_pos(
slice, slice,
move_vertically(slice, range, Direction::Forward, 1, Movement::Move, 4).head move_vertically_visual(
slice,
range,
Direction::Forward,
1,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
)
.head
), ),
(1, 3).into() (1, 3).into()
); );
@ -497,7 +700,15 @@ mod test {
]; ];
for ((direction, amount), coordinates) in moves_and_expected_coordinates { for ((direction, amount), coordinates) in moves_and_expected_coordinates {
range = move_horizontally(slice, range, direction, amount, Movement::Move, 0); range = move_horizontally(
slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
);
assert_eq!(coords_at_pos(slice, range.head), coordinates.into()) assert_eq!(coords_at_pos(slice, range.head), coordinates.into())
} }
} }
@ -523,7 +734,15 @@ mod test {
]; ];
for ((direction, amount), coordinates) in moves_and_expected_coordinates { for ((direction, amount), coordinates) in moves_and_expected_coordinates {
range = move_horizontally(slice, range, direction, amount, Movement::Move, 0); range = move_horizontally(
slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
);
assert_eq!(coords_at_pos(slice, range.head), coordinates.into()); assert_eq!(coords_at_pos(slice, range.head), coordinates.into());
assert_eq!(range.head, range.anchor); assert_eq!(range.head, range.anchor);
} }
@ -545,7 +764,15 @@ mod test {
]; ];
for (direction, amount) in moves { for (direction, amount) in moves {
range = move_horizontally(slice, range, direction, amount, Movement::Extend, 0); range = move_horizontally(
slice,
range,
direction,
amount,
Movement::Extend,
&TextFormat::default(),
&mut TextAnnotations::default(),
);
assert_eq!(range.anchor, original_anchor); assert_eq!(range.anchor, original_anchor);
} }
} }
@ -569,7 +796,15 @@ mod test {
]; ];
for ((direction, amount), coordinates) in moves_and_expected_coordinates { for ((direction, amount), coordinates) in moves_and_expected_coordinates {
range = move_vertically(slice, range, direction, amount, Movement::Move, 4); range = move_vertically_visual(
slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
);
assert_eq!(coords_at_pos(slice, range.head), coordinates.into()); assert_eq!(coords_at_pos(slice, range.head), coordinates.into());
assert_eq!(range.head, range.anchor); assert_eq!(range.head, range.anchor);
} }
@ -603,8 +838,24 @@ mod test {
for ((axis, direction, amount), coordinates) in moves_and_expected_coordinates { for ((axis, direction, amount), coordinates) in moves_and_expected_coordinates {
range = match axis { range = match axis {
Axis::H => move_horizontally(slice, range, direction, amount, Movement::Move, 0), Axis::H => move_horizontally(
Axis::V => move_vertically(slice, range, direction, amount, Movement::Move, 4), slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
),
Axis::V => move_vertically_visual(
slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
),
}; };
assert_eq!(coords_at_pos(slice, range.head), coordinates.into()); assert_eq!(coords_at_pos(slice, range.head), coordinates.into());
assert_eq!(range.head, range.anchor); assert_eq!(range.head, range.anchor);
@ -638,8 +889,24 @@ mod test {
for ((axis, direction, amount), coordinates) in moves_and_expected_coordinates { for ((axis, direction, amount), coordinates) in moves_and_expected_coordinates {
range = match axis { range = match axis {
Axis::H => move_horizontally(slice, range, direction, amount, Movement::Move, 0), Axis::H => move_horizontally(
Axis::V => move_vertically(slice, range, direction, amount, Movement::Move, 4), slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
),
Axis::V => move_vertically_visual(
slice,
range,
direction,
amount,
Movement::Move,
&TextFormat::default(),
&mut TextAnnotations::default(),
),
}; };
assert_eq!(coords_at_pos(slice, range.head), coordinates.into()); assert_eq!(coords_at_pos(slice, range.head), coordinates.into());
assert_eq!(range.head, range.anchor); assert_eq!(range.head, range.anchor);
@ -1264,6 +1531,100 @@ mod test {
} }
} }
#[test]
fn test_behaviour_when_moving_to_end_of_prev_long_words() {
let tests = [
(
"Basic backward motion from the middle of a word",
vec![(1, Range::new(3, 3), Range::new(4, 0))],
),
("Starting from after boundary retreats the anchor",
vec![(1, Range::new(0, 9), Range::new(8, 0))],
),
(
"Jump to end of a word succeeded by whitespace",
vec![(1, Range::new(10, 10), Range::new(10, 4))],
),
(
" Jump to start of line from end of word preceded by whitespace",
vec![(1, Range::new(3, 4), Range::new(4, 0))],
),
("Previous anchor is irrelevant for backward motions",
vec![(1, Range::new(12, 5), Range::new(6, 0))]),
(
" Starting from whitespace moves to first space in sequence",
vec![(1, Range::new(0, 4), Range::new(4, 0))],
),
("Identifiers_with_underscores are considered a single word",
vec![(1, Range::new(0, 20), Range::new(20, 0))]),
(
"Jumping\n \nback through a newline selects whitespace",
vec![(1, Range::new(0, 13), Range::new(12, 8))],
),
(
"Jumping to start of word from the end selects the word",
vec![(1, Range::new(6, 7), Range::new(7, 0))],
),
(
"alphanumeric.!,and.?=punctuation are treated exactly the same",
vec![(1, Range::new(29, 30), Range::new(30, 0))],
),
(
"... ... punctuation and spaces behave as expected",
vec![
(1, Range::new(0, 10), Range::new(9, 3)),
(1, Range::new(10, 6), Range::new(7, 3)),
],
),
(".._.._ punctuation is joined by underscores into a single block",
vec![(1, Range::new(0, 6), Range::new(6, 0))]),
(
"Newlines\n\nare bridged seamlessly.",
vec![(1, Range::new(0, 10), Range::new(8, 0))],
),
(
"Jumping \n\n\n\n\nback from within a newline group selects previous block",
vec![(1, Range::new(0, 13), Range::new(11, 7))],
),
(
"Failed motions do not modify the range",
vec![(0, Range::new(3, 0), Range::new(3, 0))],
),
(
"Multiple motions at once resolve correctly",
vec![(3, Range::new(19, 19), Range::new(8, 0))],
),
(
"Excessive motions are performed partially",
vec![(999, Range::new(40, 40), Range::new(9, 0))],
),
(
"", // Edge case of moving backwards in empty string
vec![(1, Range::new(0, 0), Range::new(0, 0))],
),
(
"\n\n\n\n\n", // Edge case of moving backwards in all newlines
vec![(1, Range::new(5, 5), Range::new(0, 0))],
),
(" \n \nJumping back through alternated space blocks and newlines selects the space blocks",
vec![
(1, Range::new(0, 8), Range::new(7, 4)),
(1, Range::new(7, 4), Range::new(3, 0)),
]),
("ヒーリ..クス multibyte characters behave as normal characters, including when interacting with punctuation",
vec![
(1, Range::new(0, 8), Range::new(7, 0)),
]),
];
for (sample, scenario) in tests {
for (count, begin, expected_end) in scenario.into_iter() {
let range = move_prev_long_word_end(Rope::from(sample).slice(..), begin, count);
assert_eq!(range, expected_end, "Case failed: [{}]", sample);
}
}
}
#[test] #[test]
fn test_behaviour_when_moving_to_prev_paragraph_single() { fn test_behaviour_when_moving_to_prev_paragraph_single() {
let tests = [ let tests = [
@ -1293,7 +1654,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = let selection =
selection.transform(|r| move_prev_paragraph(text.slice(..), r, 1, Movement::Move)); selection.transform(|r| move_prev_paragraph(text.slice(..), r, 1, Movement::Move));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -1316,7 +1677,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = let selection =
selection.transform(|r| move_prev_paragraph(text.slice(..), r, 2, Movement::Move)); selection.transform(|r| move_prev_paragraph(text.slice(..), r, 2, Movement::Move));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -1339,7 +1700,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = selection let selection = selection
.transform(|r| move_prev_paragraph(text.slice(..), r, 1, Movement::Extend)); .transform(|r| move_prev_paragraph(text.slice(..), r, 1, Movement::Extend));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -1359,7 +1720,7 @@ mod test {
"a\nb\n\n#[goto\nthird\n\n|]#paragraph", "a\nb\n\n#[goto\nthird\n\n|]#paragraph",
), ),
( (
"a\nb#[\n|]#\ngoto\nsecond\n\nparagraph", "a\nb#[\n|]#\n\ngoto\nsecond\n\nparagraph",
"a\nb#[\n\n|]#goto\nsecond\n\nparagraph", "a\nb#[\n\n|]#goto\nsecond\n\nparagraph",
), ),
( (
@ -1381,7 +1742,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = let selection =
selection.transform(|r| move_next_paragraph(text.slice(..), r, 1, Movement::Move)); selection.transform(|r| move_next_paragraph(text.slice(..), r, 1, Movement::Move));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -1404,7 +1765,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = let selection =
selection.transform(|r| move_next_paragraph(text.slice(..), r, 2, Movement::Move)); selection.transform(|r| move_next_paragraph(text.slice(..), r, 2, Movement::Move));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -1427,7 +1788,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = selection let selection = selection
.transform(|r| move_next_paragraph(text.slice(..), r, 1, Movement::Extend)); .transform(|r| move_next_paragraph(text.slice(..), r, 1, Movement::Extend));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }

@ -40,6 +40,21 @@ pub fn expand_tilde(path: &Path) -> PathBuf {
/// needs to improve on. /// needs to improve on.
/// Copied from cargo: <https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81> /// Copied from cargo: <https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81>
pub fn get_normalized_path(path: &Path) -> PathBuf { pub fn get_normalized_path(path: &Path) -> PathBuf {
// normalization strategy is to canonicalize first ancestor path that exists (i.e., canonicalize as much as possible),
// then run handrolled normalization on the non-existent remainder
let (base, path) = path
.ancestors()
.find_map(|base| {
let canonicalized_base = dunce::canonicalize(base).ok()?;
let remainder = path.strip_prefix(base).ok()?.into();
Some((canonicalized_base, remainder))
})
.unwrap_or_else(|| (PathBuf::new(), PathBuf::from(path)));
if path.as_os_str().is_empty() {
return base;
}
let mut components = path.components().peekable(); let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next(); components.next();
@ -63,32 +78,36 @@ pub fn get_normalized_path(path: &Path) -> PathBuf {
} }
} }
} }
ret base.join(ret)
} }
/// Returns the canonical, absolute form of a path with all intermediate components normalized. /// Returns the canonical, absolute form of a path with all intermediate components normalized.
/// ///
/// This function is used instead of `std::fs::canonicalize` because we don't want to verify /// This function is used instead of `std::fs::canonicalize` because we don't want to verify
/// here if the path exists, just normalize it's components. /// here if the path exists, just normalize it's components.
pub fn get_canonicalized_path(path: &Path) -> std::io::Result<PathBuf> { pub fn get_canonicalized_path(path: &Path) -> PathBuf {
let path = expand_tilde(path); let path = expand_tilde(path);
let path = if path.is_relative() { let path = if path.is_relative() {
std::env::current_dir().map(|current_dir| current_dir.join(path))? helix_loader::current_working_dir().join(path)
} else { } else {
path path
}; };
Ok(get_normalized_path(path.as_path())) get_normalized_path(path.as_path())
} }
pub fn get_relative_path(path: &Path) -> PathBuf { pub fn get_relative_path(path: &Path) -> PathBuf {
let path = PathBuf::from(path);
let path = if path.is_absolute() { let path = if path.is_absolute() {
let cwdir = std::env::current_dir().expect("couldn't determine current directory"); let cwdir = get_normalized_path(&helix_loader::current_working_dir());
path.strip_prefix(cwdir).unwrap_or(path) get_normalized_path(&path)
.strip_prefix(cwdir)
.map(PathBuf::from)
.unwrap_or(path)
} else { } else {
path path
}; };
fold_home_dir(path) fold_home_dir(&path)
} }
/// Returns a truncated filepath where the basepart of the path is reduced to the first /// Returns a truncated filepath where the basepart of the path is reduced to the first
@ -121,7 +140,7 @@ pub fn get_relative_path(path: &Path) -> PathBuf {
/// ``` /// ```
/// ///
pub fn get_truncated_path<P: AsRef<Path>>(path: P) -> PathBuf { pub fn get_truncated_path<P: AsRef<Path>>(path: P) -> PathBuf {
let cwd = std::env::current_dir().unwrap_or_default(); let cwd = helix_loader::current_working_dir();
let path = path let path = path
.as_ref() .as_ref()
.strip_prefix(cwd) .strip_prefix(cwd)

@ -1,9 +1,11 @@
use std::borrow::Cow; use std::{borrow::Cow, cmp::Ordering};
use crate::{ use crate::{
chars::char_is_line_ending, chars::char_is_line_ending,
doc_formatter::{DocumentFormatter, TextFormat},
graphemes::{ensure_grapheme_boundary_prev, grapheme_width, RopeGraphemes}, graphemes::{ensure_grapheme_boundary_prev, grapheme_width, RopeGraphemes},
line_ending::line_end_char_index, line_ending::line_end_char_index,
text_annotations::TextAnnotations,
RopeSlice, RopeSlice,
}; };
@ -73,6 +75,13 @@ pub fn coords_at_pos(text: RopeSlice, pos: usize) -> Position {
/// Takes \t, double-width characters (CJK) into account as well as text /// Takes \t, double-width characters (CJK) into account as well as text
/// not in the document in the future. /// not in the document in the future.
/// See [`coords_at_pos`] for an "objective" one. /// See [`coords_at_pos`] for an "objective" one.
///
/// This function should be used very rarely. Usually `visual_offset_from_anchor`
/// or `visual_offset_from_block` is preferable. However when you want to compute the
/// actual visual row/column in the text (not what is actually shown on screen)
/// then you should use this function. For example aligning text should ignore virtual
/// text and softwrap.
#[deprecated = "Doesn't account for softwrap or decorations, use visual_offset_from_anchor instead"]
pub fn visual_coords_at_pos(text: RopeSlice, pos: usize, tab_width: usize) -> Position { pub fn visual_coords_at_pos(text: RopeSlice, pos: usize, tab_width: usize) -> Position {
let line = text.char_to_line(pos); let line = text.char_to_line(pos);
@ -93,6 +102,106 @@ pub fn visual_coords_at_pos(text: RopeSlice, pos: usize, tab_width: usize) -> Po
Position::new(line, col) Position::new(line, col)
} }
/// Returns the visual offset from the start of the first visual line
/// in the block that contains anchor.
/// Text is always wrapped at blocks, they usually correspond to
/// actual line breaks but for very long lines
/// softwrapping positions are estimated with an O(1) algorithm
/// to ensure consistent performance for large lines (currently unimplemented)
///
/// Usually you want to use `visual_offset_from_anchor` instead but this function
/// can be useful (and faster) if
/// * You already know the visual position of the block
/// * You only care about the horizontal offset (column) and not the vertical offset (row)
pub fn visual_offset_from_block(
text: RopeSlice,
anchor: usize,
pos: usize,
text_fmt: &TextFormat,
annotations: &TextAnnotations,
) -> (Position, usize) {
let mut last_pos = Position::default();
let (formatter, block_start) =
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
let mut char_pos = block_start;
for (grapheme, vpos) in formatter {
last_pos = vpos;
char_pos += grapheme.doc_chars();
if char_pos > pos {
return (last_pos, block_start);
}
}
(last_pos, block_start)
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum VisualOffsetError {
PosBeforeAnchorRow,
PosAfterMaxRow,
}
/// Returns the visual offset from the start of the visual line
/// that contains anchor.
pub fn visual_offset_from_anchor(
text: RopeSlice,
anchor: usize,
pos: usize,
text_fmt: &TextFormat,
annotations: &TextAnnotations,
max_rows: usize,
) -> Result<(Position, usize), VisualOffsetError> {
let (formatter, block_start) =
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
let mut char_pos = block_start;
let mut anchor_line = None;
let mut found_pos = None;
let mut last_pos = Position::default();
if pos < block_start {
return Err(VisualOffsetError::PosBeforeAnchorRow);
}
for (grapheme, vpos) in formatter {
last_pos = vpos;
char_pos += grapheme.doc_chars();
if char_pos > pos {
if let Some(anchor_line) = anchor_line {
last_pos.row -= anchor_line;
return Ok((last_pos, block_start));
} else {
found_pos = Some(last_pos);
}
}
if char_pos > anchor && anchor_line.is_none() {
if let Some(mut found_pos) = found_pos {
return if found_pos.row == last_pos.row {
found_pos.row = 0;
Ok((found_pos, block_start))
} else {
Err(VisualOffsetError::PosBeforeAnchorRow)
};
} else {
anchor_line = Some(last_pos.row);
}
}
if let Some(anchor_line) = anchor_line {
if vpos.row >= anchor_line + max_rows {
return Err(VisualOffsetError::PosAfterMaxRow);
}
}
}
let anchor_line = anchor_line.unwrap_or(last_pos.row);
last_pos.row -= anchor_line;
Ok((last_pos, block_start))
}
/// Convert (line, column) coordinates to a character index. /// Convert (line, column) coordinates to a character index.
/// ///
/// If the `line` coordinate is beyond the end of the file, the EOF /// If the `line` coordinate is beyond the end of the file, the EOF
@ -140,6 +249,11 @@ pub fn pos_at_coords(text: RopeSlice, coords: Position, limit_before_line_ending
/// If the `column` coordinate is past the end of the given line, the /// If the `column` coordinate is past the end of the given line, the
/// line-end position (in this case, just before the line ending /// line-end position (in this case, just before the line ending
/// character) will be returned. /// character) will be returned.
/// This function should be used very rarely. Usually `char_idx_at_visual_offset` is preferable.
/// However when you want to compute a char position from the visual row/column in the text
/// (not what is actually shown on screen) then you should use this function.
/// For example aligning text should ignore virtual text and softwrap.
#[deprecated = "Doesn't account for softwrap or decorations, use char_idx_at_visual_offset instead"]
pub fn pos_at_visual_coords(text: RopeSlice, coords: Position, tab_width: usize) -> usize { pub fn pos_at_visual_coords(text: RopeSlice, coords: Position, tab_width: usize) -> usize {
let Position { mut row, col } = coords; let Position { mut row, col } = coords;
row = row.min(text.len_lines() - 1); row = row.min(text.len_lines() - 1);
@ -169,6 +283,121 @@ pub fn pos_at_visual_coords(text: RopeSlice, coords: Position, tab_width: usize)
line_start + col_char_offset line_start + col_char_offset
} }
/// Returns the char index on the visual line `row_offset` below the visual line of
/// the provided char index `anchor` that is closest to the supplied visual `column`.
///
/// If the targeted visual line is entirely covered by virtual text the last
/// char position before the virtual text and a virtual offset is returned instead.
///
/// If no (text) grapheme starts at exactly at the specified column the
/// start of the grapheme to the left is returned. If there is no grapheme
/// to the left (for example if the line starts with virtual text) then the positioning
/// of the next grapheme to the right is returned.
///
/// If the `line` coordinate is beyond the end of the file, the EOF
/// position will be returned.
///
/// If the `column` coordinate is past the end of the given line, the
/// line-end position (in this case, just before the line ending
/// character) will be returned.
///
/// # Returns
///
/// `(real_char_idx, virtual_lines)`
///
/// The nearest character idx "closest" (see above) to the specified visual offset
/// on the visual line is returned if the visual line contains any text:
/// If the visual line at the specified offset is a virtual line generated by a `LineAnnotation`
/// the previous char_index is returned, together with the remaining vertical offset (`virtual_lines`)
pub fn char_idx_at_visual_offset(
text: RopeSlice,
mut anchor: usize,
mut row_offset: isize,
column: usize,
text_fmt: &TextFormat,
annotations: &TextAnnotations,
) -> (usize, usize) {
let mut pos = anchor;
// convert row relative to visual line containing anchor to row relative to a block containing anchor (anchor may change)
loop {
let (visual_pos_in_block, block_char_offset) =
visual_offset_from_block(text, anchor, pos, text_fmt, annotations);
row_offset += visual_pos_in_block.row as isize;
anchor = block_char_offset;
if row_offset >= 0 {
break;
}
if block_char_offset == 0 {
row_offset = 0;
break;
}
// the row_offset is negative so we need to look at the previous block
// set the anchor to the last char before the current block so that we can compute
// the distance of this block from the start of the previous block
pos = anchor;
anchor -= 1;
}
char_idx_at_visual_block_offset(
text,
anchor,
row_offset as usize,
column,
text_fmt,
annotations,
)
}
/// This function behaves the same as `char_idx_at_visual_offset`, except that
/// the vertical offset `row` is always computed relative to the block that contains `anchor`
/// instead of the visual line that contains `anchor`.
/// Usually `char_idx_at_visual_offset` is more useful but this function can be
/// used in some situations as an optimization when `visual_offset_from_block` was used
///
/// # Returns
///
/// `(real_char_idx, virtual_lines)`
///
/// See `char_idx_at_visual_offset` for details
pub fn char_idx_at_visual_block_offset(
text: RopeSlice,
anchor: usize,
row: usize,
column: usize,
text_fmt: &TextFormat,
annotations: &TextAnnotations,
) -> (usize, usize) {
let (formatter, mut char_idx) =
DocumentFormatter::new_at_prev_checkpoint(text, text_fmt, annotations, anchor);
let mut last_char_idx = char_idx;
let mut last_char_idx_on_line = None;
let mut last_row = 0;
for (grapheme, grapheme_pos) in formatter {
match grapheme_pos.row.cmp(&row) {
Ordering::Equal => {
if grapheme_pos.col + grapheme.width() > column {
if !grapheme.is_virtual() {
return (char_idx, 0);
} else if let Some(char_idx) = last_char_idx_on_line {
return (char_idx, 0);
}
} else if !grapheme.is_virtual() {
last_char_idx_on_line = Some(char_idx)
}
}
Ordering::Greater => return (last_char_idx, row - last_row),
_ => (),
}
last_char_idx = char_idx;
last_row = grapheme_pos.row;
char_idx += grapheme.doc_chars();
}
(char_idx, 0)
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
@ -228,6 +457,7 @@ mod test {
} }
#[test] #[test]
#[allow(deprecated)]
fn test_visual_coords_at_pos() { fn test_visual_coords_at_pos() {
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ"); let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
let slice = text.slice(..); let slice = text.slice(..);
@ -275,6 +505,130 @@ mod test {
assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 9).into()); assert_eq!(visual_coords_at_pos(slice, 2, 8), (0, 9).into());
} }
#[test]
fn test_visual_off_from_block() {
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
let slice = text.slice(..);
let annot = TextAnnotations::default();
let text_fmt = TextFormat::default();
assert_eq!(
visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
(0, 0).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
(0, 5).into()
); // position on \n
assert_eq!(
visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
(1, 0).into()
); // position on w
assert_eq!(
visual_offset_from_block(slice, 0, 7, &text_fmt, &annot).0,
(1, 1).into()
); // position on o
assert_eq!(
visual_offset_from_block(slice, 0, 10, &text_fmt, &annot).0,
(1, 4).into()
); // position on d
// Test with wide characters.
let text = Rope::from("今日はいい\n");
let slice = text.slice(..);
assert_eq!(
visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
(0, 0).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 1, &text_fmt, &annot).0,
(0, 2).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
(0, 4).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 3, &text_fmt, &annot).0,
(0, 6).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 4, &text_fmt, &annot).0,
(0, 8).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
(0, 10).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
(1, 0).into()
);
// Test with grapheme clusters.
let text = Rope::from("a̐éö̲\r\n");
let slice = text.slice(..);
assert_eq!(
visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
(0, 0).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
(0, 1).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 4, &text_fmt, &annot).0,
(0, 2).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 7, &text_fmt, &annot).0,
(0, 3).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 9, &text_fmt, &annot).0,
(1, 0).into()
);
// Test with wide-character grapheme clusters.
// TODO: account for cluster.
let text = Rope::from("किमपि\n");
let slice = text.slice(..);
assert_eq!(
visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
(0, 0).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
(0, 2).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 3, &text_fmt, &annot).0,
(0, 3).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 5, &text_fmt, &annot).0,
(0, 5).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 6, &text_fmt, &annot).0,
(1, 0).into()
);
// Test with tabs.
let text = Rope::from("\tHello\n");
let slice = text.slice(..);
assert_eq!(
visual_offset_from_block(slice, 0, 0, &text_fmt, &annot).0,
(0, 0).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 1, &text_fmt, &annot).0,
(0, 4).into()
);
assert_eq!(
visual_offset_from_block(slice, 0, 2, &text_fmt, &annot).0,
(0, 5).into()
);
}
#[test] #[test]
fn test_pos_at_coords() { fn test_pos_at_coords() {
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ"); let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
@ -341,6 +695,7 @@ mod test {
} }
#[test] #[test]
#[allow(deprecated)]
fn test_pos_at_visual_coords() { fn test_pos_at_visual_coords() {
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ"); let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ");
let slice = text.slice(..); let slice = text.slice(..);
@ -405,4 +760,100 @@ mod test {
assert_eq!(pos_at_visual_coords(slice, (0, 10).into(), 4), 0); assert_eq!(pos_at_visual_coords(slice, (0, 10).into(), 4), 0);
assert_eq!(pos_at_visual_coords(slice, (10, 10).into(), 4), 0); assert_eq!(pos_at_visual_coords(slice, (10, 10).into(), 4), 0);
} }
#[test]
fn test_char_idx_at_visual_row_offset() {
let text = Rope::from("ḧëḷḷö\nẅöṛḷḋ\nfoo");
let slice = text.slice(..);
let mut text_fmt = TextFormat::default();
for i in 0isize..3isize {
for j in -2isize..=2isize {
if !(0..3).contains(&(i + j)) {
continue;
}
println!("{i} {j}");
assert_eq!(
char_idx_at_visual_offset(
slice,
slice.line_to_char(i as usize),
j,
3,
&text_fmt,
&TextAnnotations::default(),
)
.0,
slice.line_to_char((i + j) as usize) + 3
);
}
}
text_fmt.soft_wrap = true;
let mut softwrapped_text = "foo ".repeat(10);
softwrapped_text.push('\n');
let last_char = softwrapped_text.len() - 1;
let text = Rope::from(softwrapped_text.repeat(3));
let slice = text.slice(..);
assert_eq!(
char_idx_at_visual_offset(
slice,
last_char,
0,
0,
&text_fmt,
&TextAnnotations::default(),
)
.0,
32
);
assert_eq!(
char_idx_at_visual_offset(
slice,
last_char,
-1,
0,
&text_fmt,
&TextAnnotations::default(),
)
.0,
16
);
assert_eq!(
char_idx_at_visual_offset(
slice,
last_char,
-2,
0,
&text_fmt,
&TextAnnotations::default(),
)
.0,
0
);
assert_eq!(
char_idx_at_visual_offset(
slice,
softwrapped_text.len() + last_char,
-2,
0,
&text_fmt,
&TextAnnotations::default(),
)
.0,
softwrapped_text.len()
);
assert_eq!(
char_idx_at_visual_offset(
slice,
softwrapped_text.len() + last_char,
-5,
0,
&text_fmt,
&TextAnnotations::default(),
)
.0,
0
);
}
} }

@ -1,81 +0,0 @@
use std::collections::HashMap;
#[derive(Debug)]
pub struct Register {
name: char,
values: Vec<String>,
}
impl Register {
pub const fn new(name: char) -> Self {
Self {
name,
values: Vec::new(),
}
}
pub fn new_with_values(name: char, values: Vec<String>) -> Self {
Self { name, values }
}
pub const fn name(&self) -> char {
self.name
}
pub fn read(&self) -> &[String] {
&self.values
}
pub fn write(&mut self, values: Vec<String>) {
self.values = values;
}
pub fn push(&mut self, value: String) {
self.values.push(value);
}
}
/// Currently just wraps a `HashMap` of `Register`s
#[derive(Debug, Default)]
pub struct Registers {
inner: HashMap<char, Register>,
}
impl Registers {
pub fn get(&self, name: char) -> Option<&Register> {
self.inner.get(&name)
}
pub fn read(&self, name: char) -> Option<&[String]> {
self.get(name).map(|reg| reg.read())
}
pub fn write(&mut self, name: char, values: Vec<String>) {
if name != '_' {
self.inner
.insert(name, Register::new_with_values(name, values));
}
}
pub fn push(&mut self, name: char, value: String) {
if name != '_' {
if let Some(r) = self.inner.get_mut(&name) {
r.push(value);
} else {
self.write(name, vec![value]);
}
}
}
pub fn first(&self, name: char) -> Option<&String> {
self.read(name).and_then(|entries| entries.first())
}
pub fn last(&self, name: char) -> Option<&String> {
self.read(name).and_then(|entries| entries.last())
}
pub fn inner(&self) -> &HashMap<char, Register> {
&self.inner
}
}

@ -0,0 +1,37 @@
use std::io;
use ropey::iter::Chunks;
use ropey::RopeSlice;
pub struct RopeReader<'a> {
current_chunk: &'a [u8],
chunks: Chunks<'a>,
}
impl<'a> RopeReader<'a> {
pub fn new(rope: RopeSlice<'a>) -> RopeReader<'a> {
RopeReader {
current_chunk: &[],
chunks: rope.chunks(),
}
}
}
impl io::Read for RopeReader<'_> {
fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
let buf_len = buf.len();
loop {
let read_bytes = self.current_chunk.read(buf)?;
buf = &mut buf[read_bytes..];
if buf.is_empty() {
return Ok(buf_len);
}
if let Some(next_chunk) = self.chunks.next() {
self.current_chunk = next_chunk.as_bytes();
} else {
return Ok(buf_len - buf.len());
}
}
}
}

@ -21,14 +21,14 @@ use std::borrow::Cow;
/// can be in any order, or even share the same position. /// can be in any order, or even share the same position.
/// ///
/// The anchor and head positions use gap indexing, meaning /// The anchor and head positions use gap indexing, meaning
/// that their indices represent the the gaps *between* `char`s /// that their indices represent the gaps *between* `char`s
/// rather than the `char`s themselves. For example, 1 /// rather than the `char`s themselves. For example, 1
/// represents the position between the first and second `char`. /// represents the position between the first and second `char`.
/// ///
/// Below are some example `Range` configurations to better /// Below are some examples of `Range` configurations.
/// illustrate. The anchor and head indices are show as /// The anchor and head indices are shown as "(anchor, head)"
/// "(anchor, head)", followed by example text with "[" and "]" /// tuples, followed by example text with "[" and "]" symbols
/// inserted to represent the anchor and head positions: /// representing the anchor and head positions:
/// ///
/// - (0, 3): `[Som]e text`. /// - (0, 3): `[Som]e text`.
/// - (3, 0): `]Som[e text`. /// - (3, 0): `]Som[e text`.
@ -38,7 +38,7 @@ use std::borrow::Cow;
/// Ranges are considered to be inclusive on the left and /// Ranges are considered to be inclusive on the left and
/// exclusive on the right, regardless of anchor-head ordering. /// exclusive on the right, regardless of anchor-head ordering.
/// This means, for example, that non-zero-width ranges that /// This means, for example, that non-zero-width ranges that
/// are directly adjecent, sharing an edge, do not overlap. /// are directly adjacent, sharing an edge, do not overlap.
/// However, a zero-width range will overlap with the shared /// However, a zero-width range will overlap with the shared
/// left-edge of another range. /// left-edge of another range.
/// ///
@ -53,7 +53,9 @@ pub struct Range {
pub anchor: usize, pub anchor: usize,
/// The head of the range, moved when extending. /// The head of the range, moved when extending.
pub head: usize, pub head: usize,
pub horiz: Option<u32>, /// The previous visual offset (softwrapped lines and columns) from
/// the start of the line
pub old_visual_position: Option<(u32, u32)>,
} }
impl Range { impl Range {
@ -61,7 +63,7 @@ impl Range {
Self { Self {
anchor, anchor,
head, head,
horiz: None, old_visual_position: None,
} }
} }
@ -127,7 +129,7 @@ impl Range {
Self { Self {
anchor: self.head, anchor: self.head,
head: self.anchor, head: self.anchor,
horiz: self.horiz, old_visual_position: self.old_visual_position,
} }
} }
@ -159,34 +161,35 @@ impl Range {
self.from() <= pos && pos < self.to() self.from() <= pos && pos < self.to()
} }
/// Map a range through a set of changes. Returns a new range representing the same position /// Map a range through a set of changes. Returns a new range representing
/// after the changes are applied. /// the same position after the changes are applied. Note that this
pub fn map(self, changes: &ChangeSet) -> Self { /// function runs in O(N) (N is number of changes) and can therefore
/// cause performance problems if run for a large number of ranges as the
/// complexity is then O(MN) (for multicuror M=N usually). Instead use
/// [Selection::map] or [ChangeSet::update_positions] instead
pub fn map(mut self, changes: &ChangeSet) -> Self {
use std::cmp::Ordering; use std::cmp::Ordering;
let (anchor, head) = match self.anchor.cmp(&self.head) { if changes.is_empty() {
Ordering::Equal => ( return self;
changes.map_pos(self.anchor, Assoc::After),
changes.map_pos(self.head, Assoc::After),
),
Ordering::Less => (
changes.map_pos(self.anchor, Assoc::After),
changes.map_pos(self.head, Assoc::Before),
),
Ordering::Greater => (
changes.map_pos(self.anchor, Assoc::Before),
changes.map_pos(self.head, Assoc::After),
),
};
// We want to return a new `Range` with `horiz == None` every time,
// even if the anchor and head haven't changed, because we don't
// know if the *visual* position hasn't changed due to
// character-width or grapheme changes earlier in the text.
Self {
anchor,
head,
horiz: None,
} }
let positions_to_map = match self.anchor.cmp(&self.head) {
Ordering::Equal => [
(&mut self.anchor, Assoc::After),
(&mut self.head, Assoc::After),
],
Ordering::Less => [
(&mut self.anchor, Assoc::After),
(&mut self.head, Assoc::Before),
],
Ordering::Greater => [
(&mut self.head, Assoc::After),
(&mut self.anchor, Assoc::Before),
],
};
changes.update_positions(positions_to_map.into_iter());
self.old_visual_position = None;
self
} }
/// Extend the range to cover at least `from` `to`. /// Extend the range to cover at least `from` `to`.
@ -198,13 +201,13 @@ impl Range {
Self { Self {
anchor: self.anchor.min(from), anchor: self.anchor.min(from),
head: self.head.max(to), head: self.head.max(to),
horiz: None, old_visual_position: None,
} }
} else { } else {
Self { Self {
anchor: self.anchor.max(to), anchor: self.anchor.max(to),
head: self.head.min(from), head: self.head.min(from),
horiz: None, old_visual_position: None,
} }
} }
} }
@ -219,13 +222,13 @@ impl Range {
Range { Range {
anchor: self.anchor.max(other.anchor), anchor: self.anchor.max(other.anchor),
head: self.head.min(other.head), head: self.head.min(other.head),
horiz: None, old_visual_position: None,
} }
} else { } else {
Range { Range {
anchor: self.from().min(other.from()), anchor: self.from().min(other.from()),
head: self.to().max(other.to()), head: self.to().max(other.to()),
horiz: None, old_visual_position: None,
} }
} }
} }
@ -279,8 +282,8 @@ impl Range {
Range { Range {
anchor: new_anchor, anchor: new_anchor,
head: new_head, head: new_head,
horiz: if new_anchor == self.anchor { old_visual_position: if new_anchor == self.anchor {
self.horiz self.old_visual_position
} else { } else {
None None
}, },
@ -306,7 +309,7 @@ impl Range {
Range { Range {
anchor: self.anchor, anchor: self.anchor,
head: next_grapheme_boundary(slice, self.head), head: next_grapheme_boundary(slice, self.head),
horiz: self.horiz, old_visual_position: self.old_visual_position,
} }
} else { } else {
*self *self
@ -378,7 +381,7 @@ impl From<(usize, usize)> for Range {
Self { Self {
anchor, anchor,
head, head,
horiz: None, old_visual_position: None,
} }
} }
} }
@ -449,17 +452,36 @@ impl Selection {
/// Map selections over a set of changes. Useful for adjusting the selection position after /// Map selections over a set of changes. Useful for adjusting the selection position after
/// applying changes to a document. /// applying changes to a document.
pub fn map(self, changes: &ChangeSet) -> Self { pub fn map(self, changes: &ChangeSet) -> Self {
self.map_no_normalize(changes).normalize()
}
/// Map selections over a set of changes. Useful for adjusting the selection position after
/// applying changes to a document. Doesn't normalize the selection
pub fn map_no_normalize(mut self, changes: &ChangeSet) -> Self {
if changes.is_empty() { if changes.is_empty() {
return self; return self;
} }
Self::new( let positions_to_map = self.ranges.iter_mut().flat_map(|range| {
self.ranges use std::cmp::Ordering;
.into_iter() range.old_visual_position = None;
.map(|range| range.map(changes)) match range.anchor.cmp(&range.head) {
.collect(), Ordering::Equal => [
self.primary_index, (&mut range.anchor, Assoc::After),
) (&mut range.head, Assoc::After),
],
Ordering::Less => [
(&mut range.anchor, Assoc::After),
(&mut range.head, Assoc::Before),
],
Ordering::Greater => [
(&mut range.head, Assoc::After),
(&mut range.anchor, Assoc::Before),
],
}
});
changes.update_positions(positions_to_map);
self
} }
pub fn ranges(&self) -> &[Range] { pub fn ranges(&self) -> &[Range] {
@ -482,7 +504,7 @@ impl Selection {
ranges: smallvec![Range { ranges: smallvec![Range {
anchor, anchor,
head, head,
horiz: None old_visual_position: None
}], }],
primary_index: 0, primary_index: 0,
} }
@ -495,28 +517,63 @@ impl Selection {
/// Normalizes a `Selection`. /// Normalizes a `Selection`.
fn normalize(mut self) -> Self { fn normalize(mut self) -> Self {
let primary = self.ranges[self.primary_index]; if self.len() < 2 {
return self;
}
let mut primary = self.ranges[self.primary_index];
self.ranges.sort_unstable_by_key(Range::from); self.ranges.sort_unstable_by_key(Range::from);
self.ranges.dedup_by(|curr_range, prev_range| {
if prev_range.overlaps(curr_range) {
let new_range = curr_range.merge(*prev_range);
if prev_range == &primary || curr_range == &primary {
primary = new_range;
}
*prev_range = new_range;
true
} else {
false
}
});
self.primary_index = self self.primary_index = self
.ranges .ranges
.iter() .iter()
.position(|&range| range == primary) .position(|&range| range == primary)
.unwrap(); .unwrap();
let mut prev_i = 0; self
for i in 1..self.ranges.len() {
if self.ranges[prev_i].overlaps(&self.ranges[i]) {
self.ranges[prev_i] = self.ranges[prev_i].merge(self.ranges[i]);
} else {
prev_i += 1;
self.ranges[prev_i] = self.ranges[i];
} }
if i == self.primary_index {
self.primary_index = prev_i; /// Replaces ranges with one spanning from first to last range.
pub fn merge_ranges(self) -> Self {
let first = self.ranges.first().unwrap();
let last = self.ranges.last().unwrap();
Selection::new(smallvec![first.merge(*last)], 0)
} }
/// Merges all ranges that are consecutive.
pub fn merge_consecutive_ranges(mut self) -> Self {
let mut primary = self.ranges[self.primary_index];
self.ranges.dedup_by(|curr_range, prev_range| {
if prev_range.to() == curr_range.from() {
let new_range = curr_range.merge(*prev_range);
if prev_range == &primary || curr_range == &primary {
primary = new_range;
}
*prev_range = new_range;
true
} else {
false
} }
});
self.ranges.truncate(prev_i + 1); self.primary_index = self
.ranges
.iter()
.position(|&range| range == primary)
.unwrap();
self self
} }
@ -527,23 +584,18 @@ impl Selection {
assert!(!ranges.is_empty()); assert!(!ranges.is_empty());
debug_assert!(primary_index < ranges.len()); debug_assert!(primary_index < ranges.len());
let mut selection = Self { let selection = Self {
ranges, ranges,
primary_index, primary_index,
}; };
if selection.ranges.len() > 1 { selection.normalize()
// TODO: only normalize if needed (any ranges out of order)
selection = selection.normalize();
}
selection
} }
/// Takes a closure and maps each `Range` over the closure. /// Takes a closure and maps each `Range` over the closure.
pub fn transform<F>(mut self, f: F) -> Self pub fn transform<F>(mut self, mut f: F) -> Self
where where
F: Fn(Range) -> Range, F: FnMut(Range) -> Range,
{ {
for range in self.ranges.iter_mut() { for range in self.ranges.iter_mut() {
*range = f(*range) *range = f(*range)
@ -551,6 +603,16 @@ impl Selection {
self.normalize() self.normalize()
} }
/// Takes a closure and maps each `Range` over the closure to multiple `Range`s.
pub fn transform_iter<F, I>(mut self, f: F) -> Self
where
F: FnMut(Range) -> I,
I: Iterator<Item = Range>,
{
self.ranges = self.ranges.into_iter().flat_map(f).collect();
self.normalize()
}
// Ensures the selection adheres to the following invariants: // Ensures the selection adheres to the following invariants:
// 1. All ranges are grapheme aligned. // 1. All ranges are grapheme aligned.
// 2. All ranges are at least 1 character wide, unless at the // 2. All ranges are at least 1 character wide, unless at the
@ -568,11 +630,19 @@ impl Selection {
self.transform(|range| Range::point(range.cursor(text))) self.transform(|range| Range::point(range.cursor(text)))
} }
pub fn fragments<'a>(&'a self, text: RopeSlice<'a>) -> impl Iterator<Item = Cow<str>> + 'a { pub fn fragments<'a>(
&'a self,
text: RopeSlice<'a>,
) -> impl DoubleEndedIterator<Item = Cow<'a, str>> + ExactSizeIterator<Item = Cow<str>> + 'a
{
self.ranges.iter().map(move |range| range.fragment(text)) self.ranges.iter().map(move |range| range.fragment(text))
} }
pub fn slices<'a>(&'a self, text: RopeSlice<'a>) -> impl Iterator<Item = RopeSlice> + 'a { pub fn slices<'a>(
&'a self,
text: RopeSlice<'a>,
) -> impl DoubleEndedIterator<Item = RopeSlice<'a>> + ExactSizeIterator<Item = RopeSlice<'a>> + 'a
{
self.ranges.iter().map(move |range| range.slice(text)) self.ranges.iter().map(move |range| range.slice(text))
} }
@ -588,11 +658,6 @@ impl Selection {
// returns true if self ⊇ other // returns true if self ⊇ other
pub fn contains(&self, other: &Selection) -> bool { pub fn contains(&self, other: &Selection) -> bool {
// can't contain other if it is larger
if other.len() > self.len() {
return false;
}
let (mut iter_self, mut iter_other) = (self.iter(), other.iter()); let (mut iter_self, mut iter_other) = (self.iter(), other.iter());
let (mut ele_self, mut ele_other) = (iter_self.next(), iter_other.next()); let (mut ele_self, mut ele_other) = (iter_self.next(), iter_other.next());
@ -629,6 +694,15 @@ impl<'a> IntoIterator for &'a Selection {
} }
} }
impl IntoIterator for Selection {
type Item = Range;
type IntoIter = smallvec::IntoIter<[Range; 1]>;
fn into_iter(self) -> smallvec::IntoIter<[Range; 1]> {
self.ranges.into_iter()
}
}
// TODO: checkSelection -> check if valid for doc length && sorted // TODO: checkSelection -> check if valid for doc length && sorted
pub fn keep_or_remove_matches( pub fn keep_or_remove_matches(
@ -1132,6 +1206,52 @@ mod test {
&["", "abcd", "efg", "rs", "xyz"] &["", "abcd", "efg", "rs", "xyz"]
); );
} }
#[test]
fn test_merge_consecutive_ranges() {
let selection = Selection::new(
smallvec![
Range::new(0, 1),
Range::new(1, 10),
Range::new(15, 20),
Range::new(25, 26),
Range::new(26, 30)
],
4,
);
let result = selection.merge_consecutive_ranges();
assert_eq!(
result.ranges(),
&[Range::new(0, 10), Range::new(15, 20), Range::new(25, 30)]
);
assert_eq!(result.primary_index, 2);
let selection = Selection::new(smallvec![Range::new(0, 1)], 0);
let result = selection.merge_consecutive_ranges();
assert_eq!(result.ranges(), &[Range::new(0, 1)]);
assert_eq!(result.primary_index, 0);
let selection = Selection::new(
smallvec![
Range::new(0, 1),
Range::new(1, 5),
Range::new(5, 8),
Range::new(8, 10),
Range::new(10, 15),
Range::new(18, 25)
],
3,
);
let result = selection.merge_consecutive_ranges();
assert_eq!(result.ranges(), &[Range::new(0, 15), Range::new(18, 25)]);
assert_eq!(result.primary_index, 0);
}
#[test] #[test]
fn test_selection_contains() { fn test_selection_contains() {
fn contains(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool { fn contains(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
@ -1157,5 +1277,11 @@ mod test {
vec!((3, 4), (7, 9)) vec!((3, 4), (7, 9))
)); ));
assert!(!contains(vec!((1, 1), (5, 6)), vec!((1, 6)))); assert!(!contains(vec!((1, 1), (5, 6)), vec!((1, 6))));
// multiple ranges of other are all contained in some ranges of self,
assert!(contains(
vec!((1, 4), (7, 10)),
vec!((1, 2), (3, 4), (7, 9))
));
} }
} }

@ -129,8 +129,9 @@ impl<'a> From<&'a str> for Shellwords<'a> {
DquoteEscaped => Dquoted, DquoteEscaped => Dquoted,
}; };
if i >= input.len() - 1 && end == 0 { let c_len = c.len_utf8();
end = i + 1; if i == input.len() - c_len && end == 0 {
end = i + c_len;
} }
if end > 0 { if end > 0 {
@ -293,14 +294,14 @@ mod test {
#[test] #[test]
fn test_lists() { fn test_lists() {
let input = let input =
r#":set statusline.center ["file-type","file-encoding"] '["list", "in", "qoutes"]'"#; r#":set statusline.center ["file-type","file-encoding"] '["list", "in", "quotes"]'"#;
let shellwords = Shellwords::from(input); let shellwords = Shellwords::from(input);
let result = shellwords.words().to_vec(); let result = shellwords.words().to_vec();
let expected = vec![ let expected = vec![
Cow::from(":set"), Cow::from(":set"),
Cow::from("statusline.center"), Cow::from("statusline.center"),
Cow::from(r#"["file-type","file-encoding"]"#), Cow::from(r#"["file-type","file-encoding"]"#),
Cow::from(r#"["list", "in", "qoutes"]"#), Cow::from(r#"["list", "in", "quotes"]"#),
]; ];
assert_eq!(expected, result); assert_eq!(expected, result);
} }
@ -333,4 +334,17 @@ mod test {
assert_eq!(Shellwords::from(":o a").parts(), &[":o", "a"]); assert_eq!(Shellwords::from(":o a").parts(), &[":o", "a"]);
assert_eq!(Shellwords::from(":o a\\ ").parts(), &[":o", "a\\"]); assert_eq!(Shellwords::from(":o a\\ ").parts(), &[":o", "a\\"]);
} }
#[test]
fn test_multibyte_at_end() {
assert_eq!(Shellwords::from("𒀀").parts(), &["𒀀"]);
assert_eq!(
Shellwords::from(":sh echo 𒀀").parts(),
&[":sh", "echo", "𒀀"]
);
assert_eq!(
Shellwords::from(":sh echo 𒀀 hello world𒀀").parts(),
&[":sh", "echo", "𒀀", "hello", "world𒀀"]
);
}
} }

@ -1,6 +1,6 @@
use std::fmt::Display; use std::fmt::Display;
use crate::{search, Range, Selection}; use crate::{movement::Direction, search, Range, Selection};
use ropey::RopeSlice; use ropey::RopeSlice;
pub const PAIRS: &[(char, char)] = &[ pub const PAIRS: &[(char, char)] = &[
@ -55,15 +55,18 @@ pub fn get_pair(ch: char) -> (char, char) {
pub fn find_nth_closest_pairs_pos( pub fn find_nth_closest_pairs_pos(
text: RopeSlice, text: RopeSlice,
range: Range, range: Range,
n: usize, mut skip: usize,
) -> Result<(usize, usize)> { ) -> Result<(usize, usize)> {
let is_open_pair = |ch| PAIRS.iter().any(|(open, _)| *open == ch); let is_open_pair = |ch| PAIRS.iter().any(|(open, _)| *open == ch);
let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch); let is_close_pair = |ch| PAIRS.iter().any(|(_, close)| *close == ch);
let mut stack = Vec::with_capacity(2); let mut stack = Vec::with_capacity(2);
let pos = range.cursor(text); let pos = range.from();
let mut close_pos = pos.saturating_sub(1);
for ch in text.chars_at(pos) { for ch in text.chars_at(pos) {
close_pos += 1;
if is_open_pair(ch) { if is_open_pair(ch) {
// Track open pairs encountered so that we can step over // Track open pairs encountered so that we can step over
// the corresponding close pairs that will come up further // the corresponding close pairs that will come up further
@ -71,20 +74,46 @@ pub fn find_nth_closest_pairs_pos(
// open pair is before the cursor position. // open pair is before the cursor position.
stack.push(ch); stack.push(ch);
continue; continue;
} else if is_close_pair(ch) { }
let (open, _) = get_pair(ch);
if !is_close_pair(ch) {
// We don't care if this character isn't a brace pair item,
// so short circuit here.
continue;
}
let (open, close) = get_pair(ch);
if stack.last() == Some(&open) { if stack.last() == Some(&open) {
// If we are encountering the closing pair for an opener
// we just found while traversing, then its inside the
// selection and should be skipped over.
stack.pop(); stack.pop();
continue; continue;
} else {
// In the ideal case the stack would be empty here and the
// current character would be the close pair that we are
// looking for. It could also be the case that the pairs
// are unbalanced and we encounter a close pair that doesn't
// close the last seen open pair. In either case use this
// char as the auto-detected closest pair.
return find_nth_pairs_pos(text, ch, range, n);
} }
match find_nth_open_pair(text, open, close, close_pos, 1) {
// Before we accept this pair, we want to ensure that the
// pair encloses the range rather than just the cursor.
Some(open_pos)
if open_pos <= pos.saturating_add(1)
&& close_pos >= range.to().saturating_sub(1) =>
{
// Since we have special conditions for when to
// accept, we can't just pass the skip parameter on
// through to the find_nth_*_pair methods, so we
// track skips manually here.
if skip > 1 {
skip -= 1;
continue;
}
return match range.direction() {
Direction::Forward => Ok((open_pos, close_pos)),
Direction::Backward => Ok((close_pos, open_pos)),
};
}
_ => continue,
} }
} }
@ -244,141 +273,135 @@ mod test {
use ropey::Rope; use ropey::Rope;
use smallvec::SmallVec; use smallvec::SmallVec;
#[allow(clippy::type_complexity)] #[test]
fn check_find_nth_pair_pos( fn test_get_surround_pos() {
text: &str, #[rustfmt::skip]
cases: Vec<(usize, char, usize, Result<(usize, usize)>)>, let (doc, selection, expectations) =
) { rope_with_selections_and_expectations(
let doc = Rope::from(text); "(some) (chars)\n(newline)",
let slice = doc.slice(..); "_ ^ _ _ ^ _\n_ ^ _"
);
for (cursor_pos, ch, n, expected_range) in cases {
let range = find_nth_pairs_pos(slice, ch, (cursor_pos, cursor_pos + 1).into(), n);
assert_eq!( assert_eq!(
range, expected_range, get_surround_pos(doc.slice(..), &selection, Some('('), 1).unwrap(),
"Expected {:?}, got {:?}", expectations
expected_range, range
); );
} }
}
#[test] #[test]
fn test_find_nth_pairs_pos() { fn test_get_surround_pos_bail_different_surround_chars() {
check_find_nth_pair_pos( #[rustfmt::skip]
"some (text) here", let (doc, selection, _) =
vec![ rope_with_selections_and_expectations(
// cursor on [t]ext "[some]\n(chars)xx\n(newline)",
(6, '(', 1, Ok((5, 10))), " ^ \n ^ \n "
(6, ')', 1, Ok((5, 10))), );
// cursor on so[m]e
(2, '(', 1, Err(Error::PairNotFound)), assert_eq!(
// cursor on bracket itself get_surround_pos(doc.slice(..), &selection, Some('('), 1),
(5, '(', 1, Ok((5, 10))), Err(Error::PairNotFound)
(10, '(', 1, Ok((5, 10))),
],
); );
} }
#[test] #[test]
fn test_find_nth_pairs_pos_skip() { fn test_get_surround_pos_bail_overlapping_surround_chars() {
check_find_nth_pair_pos( #[rustfmt::skip]
"(so (many (good) text) here)", let (doc, selection, _) =
vec![ rope_with_selections_and_expectations(
// cursor on go[o]d "[some]\n(chars)xx\n(newline)",
(13, '(', 1, Ok((10, 15))), " \n ^ \n ^ "
(13, '(', 2, Ok((4, 21))), );
(13, '(', 3, Ok((0, 27))),
], assert_eq!(
get_surround_pos(doc.slice(..), &selection, Some('('), 1),
Err(Error::PairNotFound) // overlapping surround chars
); );
} }
#[test] #[test]
fn test_find_nth_pairs_pos_same() { fn test_get_surround_pos_bail_cursor_overlap() {
check_find_nth_pair_pos( #[rustfmt::skip]
"'so 'many 'good' text' here'", let (doc, selection, _) =
vec![ rope_with_selections_and_expectations(
// cursor on go[o]d "[some]\n(chars)xx\n(newline)",
(13, '\'', 1, Ok((10, 15))), " ^^ \n \n "
(13, '\'', 2, Ok((4, 21))), );
(13, '\'', 3, Ok((0, 27))),
// cursor on the quotes assert_eq!(
(10, '\'', 1, Err(Error::CursorOnAmbiguousPair)), get_surround_pos(doc.slice(..), &selection, Some('['), 1),
], Err(Error::CursorOverlap)
) );
} }
#[test] #[test]
fn test_find_nth_pairs_pos_step() { fn test_find_nth_pairs_pos_quote_success() {
check_find_nth_pair_pos( #[rustfmt::skip]
"((so)((many) good (text))(here))", let (doc, selection, expectations) =
vec![ rope_with_selections_and_expectations(
// cursor on go[o]d "some 'quoted text' on this 'line'\n'and this one'",
(15, '(', 1, Ok((5, 24))), " _ ^ _ \n "
(15, '(', 2, Ok((0, 31))), );
],
assert_eq!(2, expectations.len());
assert_eq!(
find_nth_pairs_pos(doc.slice(..), '\'', selection.primary(), 1)
.expect("find should succeed"),
(expectations[0], expectations[1])
) )
} }
#[test] #[test]
fn test_find_nth_pairs_pos_mixed() { fn test_find_nth_pairs_pos_nested_quote_success() {
check_find_nth_pair_pos( #[rustfmt::skip]
"(so [many {good} text] here)", let (doc, selection, expectations) =
vec![ rope_with_selections_and_expectations(
// cursor on go[o]d "some 'nested 'quoted' text' on this 'line'\n'and this one'",
(13, '{', 1, Ok((10, 15))), " _ ^ _ \n "
(13, '[', 1, Ok((4, 21))), );
(13, '(', 1, Ok((0, 27))),
], assert_eq!(2, expectations.len());
assert_eq!(
find_nth_pairs_pos(doc.slice(..), '\'', selection.primary(), 2)
.expect("find should succeed"),
(expectations[0], expectations[1])
) )
} }
#[test] #[test]
fn test_get_surround_pos() { fn test_find_nth_pairs_pos_inside_quote_ambiguous() {
let doc = Rope::from("(some) (chars)\n(newline)"); #[rustfmt::skip]
let slice = doc.slice(..); let (doc, selection, _) =
let selection = Selection::new( rope_with_selections_and_expectations(
SmallVec::from_slice(&[Range::point(2), Range::point(9), Range::point(20)]), "some 'nested 'quoted' text' on this 'line'\n'and this one'",
0, " ^ \n "
); );
// cursor on s[o]me, c[h]ars, newl[i]ne
assert_eq!( assert_eq!(
get_surround_pos(slice, &selection, Some('('), 1) find_nth_pairs_pos(doc.slice(..), '\'', selection.primary(), 1),
.unwrap() Err(Error::CursorOnAmbiguousPair)
.as_slice(), )
&[0, 5, 7, 13, 15, 23]
);
} }
#[test] // Create a Rope and a matching Selection using a specification language.
fn test_get_surround_pos_bail() { // ^ is a single-point selection.
let doc = Rope::from("[some]\n(chars)xx\n(newline)"); // _ is an expected index. These are returned as a Vec<usize> for use in assertions.
let slice = doc.slice(..); fn rope_with_selections_and_expectations(
text: &str,
spec: &str,
) -> (Rope, Selection, Vec<usize>) {
if text.len() != spec.len() {
panic!("specification must match text length -- are newlines aligned?");
}
let selection = let rope = Rope::from(text);
Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(9)]), 0);
// cursor on s[o]me, c[h]ars
assert_eq!(
get_surround_pos(slice, &selection, Some('('), 1),
Err(Error::PairNotFound) // different surround chars
);
let selection = Selection::new( let selections: SmallVec<[Range; 1]> = spec
SmallVec::from_slice(&[Range::point(14), Range::point(24)]), .match_indices('^')
0, .map(|(i, _)| Range::point(i))
); .collect();
// cursor on [x]x, newli[n]e
assert_eq!(
get_surround_pos(slice, &selection, Some('('), 1),
Err(Error::PairNotFound) // overlapping surround chars
);
let selection = let expectations: Vec<usize> = spec.match_indices('_').map(|(i, _)| i).collect();
Selection::new(SmallVec::from_slice(&[Range::point(2), Range::point(3)]), 0);
// cursor on s[o][m]e (rope, Selection::new(selections, 0), expectations)
assert_eq!(
get_surround_pos(slice, &selection, Some('['), 1),
Err(Error::CursorOverlap)
);
} }
} }

File diff suppressed because it is too large Load Diff

@ -1,7 +1,9 @@
//! Test helpers. //! Test helpers.
use crate::{Range, Selection}; use crate::{Range, Selection};
use ropey::Rope;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::cmp::Reverse; use std::cmp::Reverse;
use unicode_segmentation::UnicodeSegmentation;
/// Convert annotated test string to test string and selection. /// Convert annotated test string to test string and selection.
/// ///
@ -10,6 +12,10 @@ use std::cmp::Reverse;
/// `#[` for primary selection with head after anchor followed by `|]#`. /// `#[` for primary selection with head after anchor followed by `|]#`.
/// `#(` for secondary selection with head after anchor followed by `|)#`. /// `#(` for secondary selection with head after anchor followed by `|)#`.
/// ///
/// If the selection contains any LF or CRLF sequences, which are immediately
/// followed by the same grapheme, then the subsequent one is removed. This is
/// to allow representing having the cursor over the end of the line.
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -30,23 +36,23 @@ use std::cmp::Reverse;
pub fn print(s: &str) -> (String, Selection) { pub fn print(s: &str) -> (String, Selection) {
let mut primary_idx = None; let mut primary_idx = None;
let mut ranges = SmallVec::new(); let mut ranges = SmallVec::new();
let mut iter = s.chars().peekable(); let mut iter = UnicodeSegmentation::graphemes(s, true).peekable();
let mut left = String::with_capacity(s.len()); let mut left = String::with_capacity(s.len());
'outer: while let Some(c) = iter.next() { 'outer: while let Some(c) = iter.next() {
let start = left.chars().count(); let start = left.chars().count();
if c != '#' { if c != "#" {
left.push(c); left.push_str(c);
continue; continue;
} }
let (is_primary, close_pair) = match iter.next() { let (is_primary, close_pair) = match iter.next() {
Some('[') => (true, ']'), Some("[") => (true, "]"),
Some('(') => (false, ')'), Some("(") => (false, ")"),
Some(ch) => { Some(ch) => {
left.push('#'); left.push('#');
left.push(ch); left.push_str(ch);
continue; continue;
} }
None => break, None => break,
@ -56,24 +62,45 @@ pub fn print(s: &str) -> (String, Selection) {
panic!("primary `#[` already appeared {:?} {:?}", left, s); panic!("primary `#[` already appeared {:?} {:?}", left, s);
} }
let head_at_beg = iter.next_if_eq(&'|').is_some(); let head_at_beg = iter.next_if_eq(&"|").is_some();
let last_grapheme = |s: &str| {
UnicodeSegmentation::graphemes(s, true)
.last()
.map(String::from)
};
while let Some(c) = iter.next() { while let Some(c) = iter.next() {
if !(c == close_pair && iter.peek() == Some(&'#')) { let next = iter.peek();
left.push(c); let mut prev = last_grapheme(left.as_str());
if !(c == close_pair && next == Some(&"#")) {
left.push_str(c);
continue; continue;
} }
if !head_at_beg { if !head_at_beg {
let prev = left.pop().unwrap(); match &prev {
if prev != '|' { Some(p) if p != "|" => {
left.push(prev); left.push_str(c);
left.push(c);
continue; continue;
} }
Some(p) if p == "|" => {
left.pop().unwrap(); // pop the |
prev = last_grapheme(left.as_str());
}
_ => (),
}
} }
iter.next(); // skip "#" iter.next(); // skip "#"
let next = iter.peek();
// skip explicit line end inside selection
if (prev == Some(String::from("\r\n")) || prev == Some(String::from("\n")))
&& next.map(|n| String::from(*n)) == prev
{
iter.next();
}
if is_primary { if is_primary {
primary_idx = Some(ranges.len()); primary_idx = Some(ranges.len());
@ -118,14 +145,16 @@ pub fn print(s: &str) -> (String, Selection) {
/// use smallvec::smallvec; /// use smallvec::smallvec;
/// ///
/// assert_eq!( /// assert_eq!(
/// plain("abc", Selection::new(smallvec![Range::new(0, 1), Range::new(3, 2)], 0)), /// plain("abc", &Selection::new(smallvec![Range::new(0, 1), Range::new(3, 2)], 0)),
/// "#[a|]#b#(|c)#".to_owned() /// "#[a|]#b#(|c)#".to_owned()
/// ); /// );
/// ``` /// ```
pub fn plain(s: &str, selection: Selection) -> String { pub fn plain<R: Into<Rope>>(s: R, selection: &Selection) -> String {
let s = s.into();
let primary = selection.primary_index(); let primary = selection.primary_index();
let mut out = String::with_capacity(s.len() + 5 * selection.len()); let mut out = String::with_capacity(s.len_bytes() + 5 * selection.len());
out.push_str(s); out.push_str(&s.to_string());
let mut insertion: Vec<_> = selection let mut insertion: Vec<_> = selection
.iter() .iter()
.enumerate() .enumerate()
@ -138,7 +167,9 @@ pub fn plain(s: &str, selection: Selection) -> String {
(false, false) => [(range.anchor, ")#"), (range.head, "#(|")], (false, false) => [(range.anchor, ")#"), (range.head, "#(|")],
} }
}) })
.map(|(char_idx, marker)| (s.char_to_byte(char_idx), marker))
.collect(); .collect();
// insert in reverse order // insert in reverse order
insertion.sort_unstable_by_key(|k| Reverse(k.0)); insertion.sort_unstable_by_key(|k| Reverse(k.0));
for (i, s) in insertion { for (i, s) in insertion {
@ -262,4 +293,94 @@ mod test {
print("hello #[|👨‍👩‍👧‍👦]# goodbye") print("hello #[|👨‍👩‍👧‍👦]# goodbye")
); );
} }
#[test]
fn plain_single() {
assert_eq!("#[|h]#ello", plain("hello", &Selection::single(1, 0)));
assert_eq!("#[h|]#ello", plain("hello", &Selection::single(0, 1)));
assert_eq!("#[|hell]#o", plain("hello", &Selection::single(4, 0)));
assert_eq!("#[hell|]#o", plain("hello", &Selection::single(0, 4)));
assert_eq!("#[|hello]#", plain("hello", &Selection::single(5, 0)));
assert_eq!("#[hello|]#", plain("hello", &Selection::single(0, 5)));
}
#[test]
fn plain_multi() {
assert_eq!(
plain(
"hello",
&Selection::new(
SmallVec::from_slice(&[Range::new(1, 0), Range::new(5, 4)]),
0
)
),
String::from("#[|h]#ell#(|o)#")
);
assert_eq!(
plain(
"hello",
&Selection::new(
SmallVec::from_slice(&[Range::new(0, 1), Range::new(4, 5)]),
0
)
),
String::from("#[h|]#ell#(o|)#")
);
assert_eq!(
plain(
"hello",
&Selection::new(
SmallVec::from_slice(&[Range::new(2, 0), Range::new(5, 3)]),
0
)
),
String::from("#[|he]#l#(|lo)#")
);
assert_eq!(
plain(
"hello\r\nhello\r\nhello\r\n",
&Selection::new(
SmallVec::from_slice(&[
Range::new(7, 5),
Range::new(21, 19),
Range::new(14, 12)
]),
0
)
),
String::from("hello#[|\r\n]#hello#(|\r\n)#hello#(|\r\n)#")
);
}
#[test]
fn plain_multi_byte_code_point() {
assert_eq!(
plain("„“", &Selection::single(1, 0)),
String::from("#[|„]#“")
);
assert_eq!(
plain("„“", &Selection::single(2, 1)),
String::from("„#[|“]#")
);
assert_eq!(
plain("„“", &Selection::single(0, 1)),
String::from("#[„|]#“")
);
assert_eq!(
plain("„“", &Selection::single(1, 2)),
String::from("„#[“|]#")
);
assert_eq!(
plain("they said „hello“", &Selection::single(11, 10)),
String::from("they said #[|„]#hello“")
);
}
#[test]
fn plain_multi_code_point_grapheme() {
assert_eq!(
plain("hello 👨‍👩‍👧‍👦 goodbye", &Selection::single(13, 6)),
String::from("hello #[|👨‍👩‍👧‍👦]# goodbye")
);
}
} }

@ -0,0 +1,271 @@
use std::cell::Cell;
use std::ops::Range;
use std::rc::Rc;
use crate::syntax::Highlight;
use crate::Tendril;
/// An inline annotation is continuous text shown
/// on the screen before the grapheme that starts at
/// `char_idx`
#[derive(Debug, Clone)]
pub struct InlineAnnotation {
pub text: Tendril,
pub char_idx: usize,
}
impl InlineAnnotation {
pub fn new(char_idx: usize, text: impl Into<Tendril>) -> Self {
Self {
char_idx,
text: text.into(),
}
}
}
/// Represents a **single Grapheme** that is part of the document
/// that start at `char_idx` that will be replaced with
/// a different `grapheme`.
/// If `grapheme` contains multiple graphemes the text
/// will render incorrectly.
/// If you want to overlay multiple graphemes simply
/// use multiple `Overlays`.
///
/// # Examples
///
/// The following examples are valid overlays for the following text:
///
/// `aX͎̊͢͜͝͡bc`
///
/// ```
/// use helix_core::text_annotations::Overlay;
///
/// // replaces a
/// Overlay::new(0, "X");
///
/// // replaces X͎̊͢͜͝͡
/// Overlay::new(1, "\t");
///
/// // replaces b
/// Overlay::new(6, "X̢̢̟͖̲͌̋̇͑͝");
/// ```
///
/// The following examples are invalid uses
///
/// ```
/// use helix_core::text_annotations::Overlay;
///
/// // overlay is not aligned at grapheme boundary
/// Overlay::new(3, "x");
///
/// // overlay contains multiple graphemes
/// Overlay::new(0, "xy");
/// ```
#[derive(Debug, Clone)]
pub struct Overlay {
pub char_idx: usize,
pub grapheme: Tendril,
}
impl Overlay {
pub fn new(char_idx: usize, grapheme: impl Into<Tendril>) -> Self {
Self {
char_idx,
grapheme: grapheme.into(),
}
}
}
/// Line annotations allow for virtual text between normal
/// text lines. They cause `height` empty lines to be inserted
/// below the document line that contains `anchor_char_idx`.
///
/// These lines can be filled with text in the rendering code
/// as their contents have no effect beyond visual appearance.
///
/// To insert a line after a document line simply set
/// `anchor_char_idx` to `doc.line_to_char(line_idx)`
#[derive(Debug, Clone)]
pub struct LineAnnotation {
pub anchor_char_idx: usize,
pub height: usize,
}
#[derive(Debug)]
struct Layer<A, M> {
annotations: Rc<[A]>,
current_index: Cell<usize>,
metadata: M,
}
impl<A, M: Clone> Clone for Layer<A, M> {
fn clone(&self) -> Self {
Layer {
annotations: self.annotations.clone(),
current_index: self.current_index.clone(),
metadata: self.metadata.clone(),
}
}
}
impl<A, M> Layer<A, M> {
pub fn reset_pos(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) {
let new_index = self
.annotations
.partition_point(|annot| get_char_idx(annot) < char_idx);
self.current_index.set(new_index);
}
pub fn consume(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) -> Option<&A> {
let annot = self.annotations.get(self.current_index.get())?;
debug_assert!(get_char_idx(annot) >= char_idx);
if get_char_idx(annot) == char_idx {
self.current_index.set(self.current_index.get() + 1);
Some(annot)
} else {
None
}
}
}
impl<A, M> From<(Rc<[A]>, M)> for Layer<A, M> {
fn from((annotations, metadata): (Rc<[A]>, M)) -> Layer<A, M> {
Layer {
annotations,
current_index: Cell::new(0),
metadata,
}
}
}
fn reset_pos<A, M>(layers: &[Layer<A, M>], pos: usize, get_pos: impl Fn(&A) -> usize) {
for layer in layers {
layer.reset_pos(pos, &get_pos)
}
}
/// Annotations that change that is displayed when the document is render.
/// Also commonly called virtual text.
#[derive(Default, Debug, Clone)]
pub struct TextAnnotations {
inline_annotations: Vec<Layer<InlineAnnotation, Option<Highlight>>>,
overlays: Vec<Layer<Overlay, Option<Highlight>>>,
line_annotations: Vec<Layer<LineAnnotation, ()>>,
}
impl TextAnnotations {
/// Prepare the TextAnnotations for iteration starting at char_idx
pub fn reset_pos(&self, char_idx: usize) {
reset_pos(&self.inline_annotations, char_idx, |annot| annot.char_idx);
reset_pos(&self.overlays, char_idx, |annot| annot.char_idx);
reset_pos(&self.line_annotations, char_idx, |annot| {
annot.anchor_char_idx
});
}
pub fn collect_overlay_highlights(
&self,
char_range: Range<usize>,
) -> Vec<(usize, Range<usize>)> {
let mut highlights = Vec::new();
self.reset_pos(char_range.start);
for char_idx in char_range {
if let Some((_, Some(highlight))) = self.overlay_at(char_idx) {
// we don't know the number of chars the original grapheme takes
// however it doesn't matter as highlight boundaries are automatically
// aligned to grapheme boundaries in the rendering code
highlights.push((highlight.0, char_idx..char_idx + 1))
}
}
highlights
}
/// Add new inline annotations.
///
/// The annotations grapheme will be rendered with `highlight`
/// patched on top of `ui.text`.
///
/// The annotations **must be sorted** by their `char_idx`.
/// Multiple annotations with the same `char_idx` are allowed,
/// they will be display in the order that they are present in the layer.
///
/// If multiple layers contain annotations at the same position
/// the annotations that belong to the layers added first will be shown first.
pub fn add_inline_annotations(
&mut self,
layer: Rc<[InlineAnnotation]>,
highlight: Option<Highlight>,
) -> &mut Self {
self.inline_annotations.push((layer, highlight).into());
self
}
/// Add new grapheme overlays.
///
/// The overlaid grapheme will be rendered with `highlight`
/// patched on top of `ui.text`.
///
/// The overlays **must be sorted** by their `char_idx`.
/// Multiple overlays with the same `char_idx` **are allowed**.
///
/// If multiple layers contain overlay at the same position
/// the overlay from the layer added last will be show.
pub fn add_overlay(&mut self, layer: Rc<[Overlay]>, highlight: Option<Highlight>) -> &mut Self {
self.overlays.push((layer, highlight).into());
self
}
/// Add new annotation lines.
///
/// The line annotations **must be sorted** by their `char_idx`.
/// Multiple line annotations with the same `char_idx` **are not allowed**.
pub fn add_line_annotation(&mut self, layer: Rc<[LineAnnotation]>) -> &mut Self {
self.line_annotations.push((layer, ()).into());
self
}
/// Removes all line annotations, useful for vertical motions
/// so that virtual text lines are automatically skipped.
pub fn clear_line_annotations(&mut self) {
self.line_annotations.clear();
}
pub(crate) fn next_inline_annotation_at(
&self,
char_idx: usize,
) -> Option<(&InlineAnnotation, Option<Highlight>)> {
self.inline_annotations.iter().find_map(|layer| {
let annotation = layer.consume(char_idx, |annot| annot.char_idx)?;
Some((annotation, layer.metadata))
})
}
pub(crate) fn overlay_at(&self, char_idx: usize) -> Option<(&Overlay, Option<Highlight>)> {
let mut overlay = None;
for layer in &self.overlays {
while let Some(new_overlay) = layer.consume(char_idx, |annot| annot.char_idx) {
overlay = Some((new_overlay, layer.metadata));
}
}
overlay
}
pub(crate) fn annotation_lines_at(&self, char_idx: usize) -> usize {
self.line_annotations
.iter()
.map(|layer| {
let mut lines = 0;
while let Some(annot) = layer.annotations.get(layer.current_index.get()) {
if annot.anchor_char_idx == char_idx {
layer.current_index.set(layer.current_index.get() + 1);
lines += annot.height
} else {
break;
}
}
lines
})
.sum()
}
}

@ -231,8 +231,20 @@ fn textobject_pair_surround_impl(
}; };
pair_pos pair_pos
.map(|(anchor, head)| match textobject { .map(|(anchor, head)| match textobject {
TextObject::Inside => Range::new(next_grapheme_boundary(slice, anchor), head), TextObject::Inside => {
TextObject::Around => Range::new(anchor, next_grapheme_boundary(slice, head)), if anchor < head {
Range::new(next_grapheme_boundary(slice, anchor), head)
} else {
Range::new(anchor, next_grapheme_boundary(slice, head))
}
}
TextObject::Around => {
if anchor < head {
Range::new(anchor, next_grapheme_boundary(slice, head))
} else {
Range::new(next_grapheme_boundary(slice, anchor), head)
}
}
TextObject::Movement => unreachable!(), TextObject::Movement => unreachable!(),
}) })
.unwrap_or(range) .unwrap_or(range)
@ -425,7 +437,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = selection let selection = selection
.transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 1)); .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 1));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -448,7 +460,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = selection let selection = selection
.transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 2)); .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 2));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }
@ -479,7 +491,7 @@ mod test {
let text = Rope::from(s.as_str()); let text = Rope::from(s.as_str());
let selection = selection let selection = selection
.transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Around, 1)); .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Around, 1));
let actual = crate::test::plain(&s, selection); let actual = crate::test::plain(s.as_ref(), &selection);
assert_eq!(actual, expected, "\nbefore: `{:?}`", before); assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
} }
} }

@ -1,8 +1,12 @@
use ropey::RopeSlice;
use smallvec::SmallVec;
use crate::{Range, Rope, Selection, Tendril}; use crate::{Range, Rope, Selection, Tendril};
use std::borrow::Cow; use std::{borrow::Cow, iter::once};
/// (from, to, replacement) /// (from, to, replacement)
pub type Change = (usize, usize, Option<Tendril>); pub type Change = (usize, usize, Option<Tendril>);
pub type Deletion = (usize, usize);
// TODO: pub(crate) // TODO: pub(crate)
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -39,7 +43,7 @@ impl ChangeSet {
} }
#[must_use] #[must_use]
pub fn new(doc: &Rope) -> Self { pub fn new(doc: RopeSlice) -> Self {
let len = doc.len_chars(); let len = doc.len_chars();
Self { Self {
changes: Vec::new(), changes: Vec::new(),
@ -323,20 +327,75 @@ impl ChangeSet {
self.changes.is_empty() || self.changes == [Operation::Retain(self.len)] self.changes.is_empty() || self.changes == [Operation::Retain(self.len)]
} }
/// Map a position through the changes. /// Map a (mostly) *sorted* list of positions through the changes.
/// ///
/// `assoc` indicates which size to associate the position with. `Before` will keep the /// This is equivalent to updating each position with `map_pos`:
/// position close to the character before, and will place it before insertions over that ///
/// range, or at that point. `After` will move it forward, placing it at the end of such /// ``` no-compile
/// insertions. /// for (pos, assoc) in positions {
pub fn map_pos(&self, pos: usize, assoc: Assoc) -> usize { /// *pos = changes.map_pos(*pos, assoc);
/// }
/// ```
/// However this function is significantly faster for sorted lists running
/// in `O(N+M)` instead of `O(NM)`. This function also handles unsorted/
/// partially sorted lists. However, in that case worst case complexity is
/// again `O(MN)`. For lists that are often/mostly sorted (like the end of diagnostic ranges)
/// performance is usally close to `O(N + M)`
pub fn update_positions<'a>(&self, positions: impl Iterator<Item = (&'a mut usize, Assoc)>) {
use Operation::*; use Operation::*;
let mut positions = positions.peekable();
let mut old_pos = 0; let mut old_pos = 0;
let mut new_pos = 0; let mut new_pos = 0;
let mut iter = self.changes.iter().enumerate().peekable();
let mut iter = self.changes.iter().peekable(); 'outer: loop {
macro_rules! map {
($map: expr, $i: expr) => {
loop {
let Some((pos, assoc)) = positions.peek_mut() else { return; };
if **pos < old_pos {
// Positions are not sorted, revert to the last Operation that
// contains this position and continue iterating from there.
// We can unwrap here since `pos` can not be negative
// (unsigned integer) and iterating backwards to the start
// should always move us back to the start
for (i, change) in self.changes[..$i].iter().enumerate().rev() {
match change {
Retain(i) => {
old_pos -= i;
new_pos -= i;
}
Delete(i) => {
old_pos -= i;
}
Insert(ins) => {
new_pos -= ins.chars().count();
}
}
if old_pos <= **pos {
iter = self.changes[i..].iter().enumerate().peekable();
}
}
debug_assert!(old_pos <= **pos, "Reverse Iter across changeset works");
continue 'outer;
}
let Some(new_pos) = $map(**pos, *assoc) else { break; };
**pos = new_pos;
positions.next();
}
};
}
let Some((i, change)) = iter.next() else {
map!(
|pos, _| (old_pos == pos).then_some(new_pos),
self.changes.len()
);
break;
};
while let Some(change) = iter.next() {
let len = match change { let len = match change {
Delete(i) | Retain(i) => *i, Delete(i) | Retain(i) => *i,
Insert(_) => 0, Insert(_) => 0,
@ -345,46 +404,51 @@ impl ChangeSet {
match change { match change {
Retain(_) => { Retain(_) => {
if old_end > pos { map!(
return new_pos + (pos - old_pos); |pos, _| (old_end > pos).then_some(new_pos + (pos - old_pos)),
} i
);
new_pos += len; new_pos += len;
} }
Delete(_) => { Delete(_) => {
// in range // in range
if old_end > pos { map!(|pos, _| (old_end > pos).then_some(new_pos), i);
return new_pos;
}
} }
Insert(s) => { Insert(s) => {
let ins = s.chars().count(); let ins = s.chars().count();
// a subsequent delete means a replace, consume it // a subsequent delete means a replace, consume it
if let Some(Delete(len)) = iter.peek() { if let Some((_, Delete(len))) = iter.peek() {
iter.next(); iter.next();
old_end = old_pos + len; old_end = old_pos + len;
// in range of replaced text // in range of replaced text
if old_end > pos { map!(
|pos, assoc| (old_end > pos).then(|| {
// at point or tracking before // at point or tracking before
if pos == old_pos || assoc == Assoc::Before { if pos == old_pos || assoc == Assoc::Before {
return new_pos; new_pos
} else { } else {
// place to end of insert // place to end of insert
return new_pos + ins; new_pos + ins
}
} }
}),
i
);
} else { } else {
// at insert point // at insert point
if old_pos == pos { map!(
|pos, assoc| (old_pos == pos).then(|| {
// return position before inserted text // return position before inserted text
if assoc == Assoc::Before { if assoc == Assoc::Before {
return new_pos; new_pos
} else { } else {
// after text // after text
return new_pos + ins; new_pos + ins
}
} }
}),
i
);
} }
new_pos += ins; new_pos += ins;
@ -392,14 +456,20 @@ impl ChangeSet {
} }
old_pos = old_end; old_pos = old_end;
} }
let out_of_bounds: Vec<_> = positions.collect();
if pos > old_pos { panic!("Positions {out_of_bounds:?} are out of range for changeset len {old_pos}!",)
panic!(
"Position {} is out of range for changeset len {}!",
pos, old_pos
)
} }
new_pos
/// Map a position through the changes.
///
/// `assoc` indicates which side to associate the position with. `Before` will keep the
/// position close to the character before, and will place it before insertions over that
/// range, or at that point. `After` will move it forward, placing it at the end of such
/// insertions.
pub fn map_pos(&self, mut pos: usize, assoc: Assoc) -> usize {
self.update_positions(once((&mut pos, assoc)));
pos
} }
pub fn changes_iter(&self) -> ChangeIterator { pub fn changes_iter(&self) -> ChangeIterator {
@ -419,7 +489,7 @@ impl Transaction {
/// Create a new, empty transaction. /// Create a new, empty transaction.
pub fn new(doc: &Rope) -> Self { pub fn new(doc: &Rope) -> Self {
Self { Self {
changes: ChangeSet::new(doc), changes: ChangeSet::new(doc.slice(..)),
selection: None, selection: None,
} }
} }
@ -466,6 +536,33 @@ impl Transaction {
self self
} }
/// Generate a transaction from a set of potentially overlapping changes. The `change_ranges`
/// iterator yield the range (of removed text) in the old document for each edit. If any change
/// overlaps with a range overlaps with a previous range then that range is ignored.
///
/// The `process_change` callback is called for each edit that is not ignored (in the order
/// yielded by `changes`) and should return the new text that the associated range will be
/// replaced with.
///
/// To make this function more flexible the iterator can yield additional data for each change
/// that is passed to `process_change`
pub fn change_ignore_overlapping<T>(
doc: &Rope,
change_ranges: impl Iterator<Item = (usize, usize, T)>,
mut process_change: impl FnMut(usize, usize, T) -> Option<Tendril>,
) -> Self {
let mut last = 0;
let changes = change_ranges.filter_map(|(from, to, data)| {
if from < last {
return None;
}
let tendril = process_change(from, to, data);
last = to;
Some((from, to, tendril))
});
Self::change(doc, changes)
}
/// Generate a transaction from a set of changes. /// Generate a transaction from a set of changes.
pub fn change<I>(doc: &Rope, changes: I) -> Self pub fn change<I>(doc: &Rope, changes: I) -> Self
where where
@ -481,6 +578,11 @@ impl Transaction {
for (from, to, tendril) in changes { for (from, to, tendril) in changes {
// Verify ranges are ordered and not overlapping // Verify ranges are ordered and not overlapping
debug_assert!(last <= from); debug_assert!(last <= from);
// Verify ranges are correct
debug_assert!(
from <= to,
"Edit end must end before it starts (should {from} <= {to})"
);
// Retain from last "to" to current "from" // Retain from last "to" to current "from"
changeset.retain(from - last); changeset.retain(from - last);
@ -500,6 +602,46 @@ impl Transaction {
Self::from(changeset) Self::from(changeset)
} }
/// Generate a transaction from a set of potentially overlapping deletions
/// by merging overlapping deletions together.
pub fn delete<I>(doc: &Rope, deletions: I) -> Self
where
I: Iterator<Item = Deletion>,
{
let len = doc.len_chars();
let (lower, upper) = deletions.size_hint();
let size = upper.unwrap_or(lower);
let mut changeset = ChangeSet::with_capacity(2 * size + 1); // rough estimate
let mut last = 0;
for (mut from, to) in deletions {
if last > to {
continue;
}
if last > from {
from = last
}
debug_assert!(
from <= to,
"Edit end must end before it starts (should {from} <= {to})"
);
// Retain from last "to" to current "from"
changeset.retain(from - last);
changeset.delete(to - from);
last = to;
}
changeset.retain(len - last);
Self::from(changeset)
}
pub fn insert_at_eof(mut self, text: Tendril) -> Transaction {
self.changes.insert(text);
self
}
/// Generate a transaction with a change per selection range. /// Generate a transaction with a change per selection range.
pub fn change_by_selection<F>(doc: &Rope, selection: &Selection, f: F) -> Self pub fn change_by_selection<F>(doc: &Rope, selection: &Selection, f: F) -> Self
where where
@ -508,6 +650,54 @@ impl Transaction {
Self::change(doc, selection.iter().map(f)) Self::change(doc, selection.iter().map(f))
} }
pub fn change_by_selection_ignore_overlapping(
doc: &Rope,
selection: &Selection,
mut change_range: impl FnMut(&Range) -> (usize, usize),
mut create_tendril: impl FnMut(usize, usize) -> Option<Tendril>,
) -> (Transaction, Selection) {
let mut last_selection_idx = None;
let mut new_primary_idx = None;
let mut ranges: SmallVec<[Range; 1]> = SmallVec::new();
let process_change = |change_start, change_end, (idx, range): (usize, &Range)| {
// update the primary idx
if idx == selection.primary_index() {
new_primary_idx = Some(idx);
} else if new_primary_idx.is_none() {
if idx > selection.primary_index() {
new_primary_idx = last_selection_idx;
} else {
last_selection_idx = Some(idx);
}
}
ranges.push(*range);
create_tendril(change_start, change_end)
};
let transaction = Self::change_ignore_overlapping(
doc,
selection.iter().enumerate().map(|range| {
let (change_start, change_end) = change_range(range.1);
(change_start, change_end, range)
}),
process_change,
);
(
transaction,
Selection::new(ranges, new_primary_idx.unwrap_or(0)),
)
}
/// Generate a transaction with a deletion per selection range.
/// Compared to using `change_by_selection` directly these ranges may overlap.
/// In that case they are merged
pub fn delete_by_selection<F>(doc: &Rope, selection: &Selection, f: F) -> Self
where
F: FnMut(&Range) -> Deletion,
{
Self::delete(doc, selection.iter().map(f))
}
/// Insert text at each selection head. /// Insert text at each selection head.
pub fn insert(doc: &Rope, selection: &Selection, text: Tendril) -> Self { pub fn insert(doc: &Rope, selection: &Selection, text: Tendril) -> Self {
Self::change_by_selection(doc, selection, |range| { Self::change_by_selection(doc, selection, |range| {
@ -680,6 +870,20 @@ mod test {
}; };
assert_eq!(cs.map_pos(2, Assoc::Before), 2); assert_eq!(cs.map_pos(2, Assoc::Before), 2);
assert_eq!(cs.map_pos(2, Assoc::After), 2); assert_eq!(cs.map_pos(2, Assoc::After), 2);
// unsorted selection
let cs = ChangeSet {
changes: vec![
Insert("ab".into()),
Delete(2),
Insert("cd".into()),
Delete(2),
],
len: 4,
len_after: 4,
};
let mut positions = [4, 2];
cs.update_positions(positions.iter_mut().map(|pos| (pos, Assoc::After)));
assert_eq!(positions, [4, 2]);
} }
#[test] #[test]
@ -746,9 +950,9 @@ mod test {
#[test] #[test]
fn combine_with_empty() { fn combine_with_empty() {
let empty = Rope::from(""); let empty = Rope::from("");
let a = ChangeSet::new(&empty); let a = ChangeSet::new(empty.slice(..));
let mut b = ChangeSet::new(&empty); let mut b = ChangeSet::new(empty.slice(..));
b.insert("a".into()); b.insert("a".into());
let changes = a.compose(b); let changes = a.compose(b);
@ -762,9 +966,9 @@ mod test {
const TEST_CASE: &str = "Hello, これはヘリックスエディターです!"; const TEST_CASE: &str = "Hello, これはヘリックスエディターです!";
let empty = Rope::from(""); let empty = Rope::from("");
let a = ChangeSet::new(&empty); let a = ChangeSet::new(empty.slice(..));
let mut b = ChangeSet::new(&empty); let mut b = ChangeSet::new(empty.slice(..));
b.insert(TEST_CASE.into()); b.insert(TEST_CASE.into());
let changes = a.compose(b); let changes = a.compose(b);

@ -1,7 +1,9 @@
use smartstring::{LazyCompact, SmartString}; use smartstring::{LazyCompact, SmartString};
use textwrap::{Options, WordSplitter::NoHyphenation};
/// Given a slice of text, return the text re-wrapped to fit it /// Given a slice of text, return the text re-wrapped to fit it
/// within the given width. /// within the given width.
pub fn reflow_hard_wrap(text: &str, max_line_len: usize) -> SmartString<LazyCompact> { pub fn reflow_hard_wrap(text: &str, text_width: usize) -> SmartString<LazyCompact> {
textwrap::refill(text, max_line_len).into() let options = Options::new(text_width).word_splitter(NoHyphenation);
textwrap::refill(text, options).into()
} }

@ -0,0 +1,48 @@
std::vector<std::string>
fn_with_many_parameters(int parm1, long parm2, float parm3, double parm4,
char* parm5, bool parm6);
std::vector<std::string>
fn_with_many_parameters(int parm1, long parm2, float parm3, double parm4,
char* parm5, bool parm6) {
auto lambda = []() {
return 0;
};
auto lambda_with_a_really_long_name_that_uses_a_whole_line
= [](int some_more_aligned_parameters,
std::string parm2) {
do_smth();
};
if (brace_on_same_line) {
do_smth();
} else if (brace_on_next_line)
{
do_smth();
} else if (another_condition) {
do_smth();
}
else {
do_smth();
}
if (inline_if_statement)
do_smth();
if (another_inline_if_statement)
return [](int parm1, char* parm2) {
this_is_a_really_pointless_lambda();
};
switch (var) {
case true:
return -1;
case false:
return 42;
}
}
class MyClass : public MyBaseClass {
public:
MyClass();
void public_fn();
private:
super_secret_private_fn();
}

@ -1 +0,0 @@
../../../src/indent.rs

@ -11,3 +11,16 @@ indent = { tab-width = 4, unit = " " }
[[grammar]] [[grammar]]
name = "rust" name = "rust"
source = { git = "https://github.com/tree-sitter/tree-sitter-rust", rev = "0431a2c60828731f27491ee9fdefe25e250ce9c9" } source = { git = "https://github.com/tree-sitter/tree-sitter-rust", rev = "0431a2c60828731f27491ee9fdefe25e250ce9c9" }
[[language]]
name = "cpp"
scope = "source.cpp"
injection-regex = "cpp"
file-types = ["cc", "hh", "c++", "cpp", "hpp", "h", "ipp", "tpp", "cxx", "hxx", "ixx", "txx", "ino", "C", "H"]
roots = []
comment-token = "//"
indent = { tab-width = 2, unit = " " }
[[grammar]]
name = "cpp"
source = { git = "https://github.com/tree-sitter/tree-sitter-cpp", rev = "2d2c4aee8672af4c7c8edff68e7dd4c07e88d2b1" }

@ -1,36 +1,192 @@
use helix_core::{ use helix_core::{
indent::{treesitter_indent_for_pos, IndentStyle}, indent::{indent_level_for_line, treesitter_indent_for_pos, IndentStyle},
syntax::Loader, syntax::{Configuration, Loader},
Syntax, Syntax,
}; };
use std::path::PathBuf; use ropey::Rope;
use std::{ops::Range, path::PathBuf, process::Command};
#[test] #[test]
fn test_treesitter_indent_rust() { fn test_treesitter_indent_rust() {
test_treesitter_indent("rust.rs", "source.rust"); standard_treesitter_test("rust.rs", "source.rust");
} }
#[test]
fn test_treesitter_indent_cpp() {
standard_treesitter_test("cpp.cpp", "source.cpp");
}
#[test]
fn test_treesitter_indent_rust_helix() {
// We pin a specific git revision to prevent unrelated changes from causing the indent tests to fail.
// Ideally, someone updates this once in a while and fixes any errors that occur.
let rev = "af382768cdaf89ff547dbd8f644a1bddd90e7c8f";
let files = Command::new("git")
.args([
"ls-tree",
"-r",
"--name-only",
"--full-tree",
rev,
"helix-term/src",
])
.output()
.unwrap();
let files = String::from_utf8(files.stdout).unwrap();
let ignored_files = vec![
// Contains many macros that tree-sitter does not parse in a meaningful way and is otherwise not very interesting
"helix-term/src/health.rs",
];
for file in files.split_whitespace() {
if ignored_files.contains(&file) {
continue;
}
let ignored_lines: Vec<Range<usize>> = match file {
"helix-term/src/application.rs" => vec![
// We can't handle complicated indent rules inside macros (`json!` in this case) since
// the tree-sitter grammar only parses them as `token_tree` and `identifier` nodes.
1045..1051,
],
"helix-term/src/commands.rs" => vec![
// This is broken because of the current handling of `call_expression`
// (i.e. having an indent query for it but outdenting again in specific cases).
// The indent query is needed to correctly handle multi-line arguments in function calls
// inside indented `field_expression` nodes (which occurs fairly often).
//
// Once we have the `@indent.always` capture type, it might be possible to just have an indent
// capture for the `arguments` field of a call expression. That could enable us to correctly
// handle this.
2226..2230,
],
"helix-term/src/commands/dap.rs" => vec![
// Complex `format!` macro
46..52,
],
"helix-term/src/commands/lsp.rs" => vec![
// Macro
624..627,
// Return type declaration of a closure. `cargo fmt` adds an additional space here,
// which we cannot (yet) model with our indent queries.
878..879,
// Same as in `helix-term/src/commands.rs`
1335..1343,
],
"helix-term/src/config.rs" => vec![
// Multiline string
146..152,
],
"helix-term/src/keymap.rs" => vec![
// Complex macro (see above)
456..470,
// Multiline string without indent
563..567,
],
"helix-term/src/main.rs" => vec![
// Multiline string
44..70,
],
"helix-term/src/ui/completion.rs" => vec![
// Macro
218..232,
],
"helix-term/src/ui/editor.rs" => vec![
// The chained function calls here are not indented, probably because of the comment
// in between. Since `cargo fmt` doesn't even attempt to format it, there's probably
// no point in trying to indent this correctly.
342..350,
],
"helix-term/src/ui/lsp.rs" => vec![
// Macro
56..61,
],
"helix-term/src/ui/statusline.rs" => vec![
// Same as in `helix-term/src/commands.rs`
436..442,
450..456,
],
_ => Vec::new(),
};
let git_object = rev.to_string() + ":" + file;
let content = Command::new("git")
.args(["cat-file", "blob", &git_object])
.output()
.unwrap();
let doc = Rope::from_reader(&mut content.stdout.as_slice()).unwrap();
test_treesitter_indent(file, doc, "source.rust", ignored_lines);
}
}
#[test]
fn test_indent_level_for_line_with_spaces() {
let tab_width: usize = 4;
let indent_width: usize = 4;
let line = ropey::Rope::from_str(" Indented with 8 spaces");
let indent_level = indent_level_for_line(line.slice(0..), tab_width, indent_width);
assert_eq!(indent_level, 2)
}
#[test] #[test]
fn test_treesitter_indent_rust_2() { fn test_indent_level_for_line_with_tabs() {
test_treesitter_indent("indent.rs", "source.rust"); let tab_width: usize = 4;
// TODO Use commands.rs as indentation test. let indent_width: usize = 4;
// Currently this fails because we can't align the parameters of a closure yet
// test_treesitter_indent("commands.rs", "source.rust"); let line = ropey::Rope::from_str("\t\tIndented with 2 tabs");
let indent_level = indent_level_for_line(line.slice(0..), tab_width, indent_width);
assert_eq!(indent_level, 2)
}
#[test]
fn test_indent_level_for_line_with_spaces_and_tabs() {
let tab_width: usize = 4;
let indent_width: usize = 4;
let line = ropey::Rope::from_str(" \t \tIndented with mix of spaces and tabs");
let indent_level = indent_level_for_line(line.slice(0..), tab_width, indent_width);
assert_eq!(indent_level, 2)
} }
fn test_treesitter_indent(file_name: &str, lang_scope: &str) { fn indent_tests_dir() -> PathBuf {
let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
test_dir.push("tests/data/indent"); test_dir.push("tests/data/indent");
test_dir
}
fn indent_test_path(name: &str) -> PathBuf {
let mut path = indent_tests_dir();
path.push(name);
path
}
fn indent_tests_config() -> Configuration {
let mut config_path = indent_tests_dir();
config_path.push("languages.toml");
let config = std::fs::read_to_string(config_path).unwrap();
toml::from_str(&config).unwrap()
}
let mut test_file = test_dir.clone(); fn standard_treesitter_test(file_name: &str, lang_scope: &str) {
test_file.push(file_name); let test_path = indent_test_path(file_name);
let test_file = std::fs::File::open(test_file).unwrap(); let test_file = std::fs::File::open(test_path).unwrap();
let doc = ropey::Rope::from_reader(test_file).unwrap(); let doc = ropey::Rope::from_reader(test_file).unwrap();
test_treesitter_indent(file_name, doc, lang_scope, Vec::new())
}
let mut config_file = test_dir; /// Test that all the lines in the given file are indented as expected.
config_file.push("languages.toml"); /// ignored_lines is a list of (1-indexed) line ranges that are excluded from this test.
let config = std::fs::read(config_file).unwrap(); fn test_treesitter_indent(
let config = toml::from_slice(&config).unwrap(); test_name: &str,
let loader = Loader::new(config); doc: Rope,
lang_scope: &str,
ignored_lines: Vec<std::ops::Range<usize>>,
) {
let loader = Loader::new(indent_tests_config());
// set runtime path so we can find the queries // set runtime path so we can find the queries
let mut runtime = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut runtime = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
@ -38,19 +194,25 @@ fn test_treesitter_indent(file_name: &str, lang_scope: &str) {
std::env::set_var("HELIX_RUNTIME", runtime.to_str().unwrap()); std::env::set_var("HELIX_RUNTIME", runtime.to_str().unwrap());
let language_config = loader.language_config_for_scope(lang_scope).unwrap(); let language_config = loader.language_config_for_scope(lang_scope).unwrap();
let indent_style = IndentStyle::from_str(&language_config.indent.as_ref().unwrap().unit);
let highlight_config = language_config.highlight_config(&[]).unwrap(); let highlight_config = language_config.highlight_config(&[]).unwrap();
let syntax = Syntax::new(&doc, highlight_config, std::sync::Arc::new(loader));
let indent_query = language_config.indent_query().unwrap();
let text = doc.slice(..); let text = doc.slice(..);
let syntax = Syntax::new(text, highlight_config, std::sync::Arc::new(loader)).unwrap();
let indent_query = language_config.indent_query().unwrap();
for i in 0..doc.len_lines() { for i in 0..doc.len_lines() {
let line = text.line(i); let line = text.line(i);
if ignored_lines.iter().any(|range| range.contains(&(i + 1))) {
continue;
}
if let Some(pos) = helix_core::find_first_non_whitespace_char(line) { if let Some(pos) = helix_core::find_first_non_whitespace_char(line) {
let tab_width: usize = 4;
let suggested_indent = treesitter_indent_for_pos( let suggested_indent = treesitter_indent_for_pos(
indent_query, indent_query,
&syntax, &syntax,
&IndentStyle::Spaces(4), &indent_style,
4, tab_width,
indent_style.indent_width(tab_width),
text, text,
i, i,
text.line_to_char(i) + pos, text.line_to_char(i) + pos,
@ -59,7 +221,8 @@ fn test_treesitter_indent(file_name: &str, lang_scope: &str) {
.unwrap(); .unwrap();
assert!( assert!(
line.get_slice(..pos).map_or(false, |s| s == suggested_indent), line.get_slice(..pos).map_or(false, |s| s == suggested_indent),
"Wrong indentation on line {}:\n\"{}\" (original line)\n\"{}\" (suggested indentation)\n", "Wrong indentation for file {:?} on line {}:\n\"{}\" (original line)\n\"{}\" (suggested indentation)\n",
test_name,
i+1, i+1,
line.slice(..line.len_chars()-1), line.slice(..line.len_chars()-1),
suggested_indent, suggested_indent,

@ -19,7 +19,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
thiserror = "1.0" thiserror = "1.0"
tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "net", "sync"] } tokio = { version = "1", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "net", "sync"] }
which = "4.2" which = "4.4"
[dev-dependencies] [dev-dependencies]
fern = "0.6" fern = "0.6"

@ -1,4 +1,5 @@
use crate::{ use crate::{
requests::DisconnectArguments,
transport::{Payload, Request, Response, Transport}, transport::{Payload, Request, Response, Transport},
types::*, types::*,
Error, Result, ThreadId, Error, Result, ThreadId,
@ -31,6 +32,8 @@ pub struct Client {
_process: Option<Child>, _process: Option<Child>,
server_tx: UnboundedSender<Payload>, server_tx: UnboundedSender<Payload>,
request_counter: AtomicU64, request_counter: AtomicU64,
connection_type: Option<ConnectionType>,
starting_request_args: Option<Value>,
pub caps: Option<DebuggerCapabilities>, pub caps: Option<DebuggerCapabilities>,
// thread_id -> frames // thread_id -> frames
pub stack_frames: HashMap<ThreadId, Vec<StackFrame>>, pub stack_frames: HashMap<ThreadId, Vec<StackFrame>>,
@ -41,6 +44,12 @@ pub struct Client {
pub quirks: DebuggerQuirks, pub quirks: DebuggerQuirks,
} }
#[derive(Clone, Copy, Debug)]
pub enum ConnectionType {
Launch,
Attach,
}
impl Client { impl Client {
// Spawn a process and communicate with it by either TCP or stdio // Spawn a process and communicate with it by either TCP or stdio
pub async fn process( pub async fn process(
@ -53,12 +62,10 @@ impl Client {
if command.is_empty() { if command.is_empty() {
return Result::Err(Error::Other(anyhow!("Command not provided"))); return Result::Err(Error::Other(anyhow!("Command not provided")));
} }
if transport == "tcp" && port_arg.is_some() { match (transport, port_arg) {
Self::tcp_process(command, args, port_arg.unwrap(), id).await ("tcp", Some(port_arg)) => Self::tcp_process(command, args, port_arg, id).await,
} else if transport == "stdio" { ("stdio", _) => Self::stdio(command, args, id),
Self::stdio(command, args, id) _ => Result::Err(Error::Other(anyhow!("Incorrect transport {}", transport))),
} else {
Result::Err(Error::Other(anyhow!("Incorrect transport {}", transport)))
} }
} }
@ -70,7 +77,7 @@ impl Client {
process: Option<Child>, process: Option<Child>,
) -> Result<(Self, UnboundedReceiver<Payload>)> { ) -> Result<(Self, UnboundedReceiver<Payload>)> {
let (server_rx, server_tx) = Transport::start(rx, tx, err, id); let (server_rx, server_tx) = Transport::start(rx, tx, err, id);
let (client_rx, client_tx) = unbounded_channel(); let (client_tx, client_rx) = unbounded_channel();
let client = Self { let client = Self {
id, id,
@ -78,7 +85,8 @@ impl Client {
server_tx, server_tx,
request_counter: AtomicU64::new(0), request_counter: AtomicU64::new(0),
caps: None, caps: None,
// connection_type: None,
starting_request_args: None,
stack_frames: HashMap::new(), stack_frames: HashMap::new(),
thread_states: HashMap::new(), thread_states: HashMap::new(),
thread_id: None, thread_id: None,
@ -86,9 +94,9 @@ impl Client {
quirks: DebuggerQuirks::default(), quirks: DebuggerQuirks::default(),
}; };
tokio::spawn(Self::recv(server_rx, client_rx)); tokio::spawn(Self::recv(server_rx, client_tx));
Ok((client, client_tx)) Ok((client, client_rx))
} }
pub async fn tcp( pub async fn tcp(
@ -150,6 +158,10 @@ impl Client {
) )
} }
pub fn starting_request_args(&self) -> &Option<Value> {
&self.starting_request_args
}
pub async fn tcp_process( pub async fn tcp_process(
cmd: &str, cmd: &str,
args: Vec<&str>, args: Vec<&str>,
@ -207,6 +219,10 @@ impl Client {
self.id self.id
} }
pub fn connection_type(&self) -> Option<ConnectionType> {
self.connection_type
}
fn next_request_id(&self) -> u64 { fn next_request_id(&self) -> u64 {
self.request_counter.fetch_add(1, Ordering::Relaxed) self.request_counter.fetch_add(1, Ordering::Relaxed)
} }
@ -254,7 +270,7 @@ impl Client {
// TODO: specifiable timeout, delay other calls until initialize success // TODO: specifiable timeout, delay other calls until initialize success
timeout(Duration::from_secs(20), callback_rx.recv()) timeout(Duration::from_secs(20), callback_rx.recv())
.await .await
.map_err(|_| Error::Timeout)? // return Timeout .map_err(|_| Error::Timeout(id))? // return Timeout
.ok_or(Error::StreamClosed)? .ok_or(Error::StreamClosed)?
.map(|response| response.body.unwrap_or_default()) .map(|response| response.body.unwrap_or_default())
// TODO: check response.success // TODO: check response.success
@ -334,18 +350,35 @@ impl Client {
Ok(()) Ok(())
} }
pub fn disconnect(&self) -> impl Future<Output = Result<Value>> { pub fn disconnect(
self.call::<requests::Disconnect>(()) &mut self,
args: Option<DisconnectArguments>,
) -> impl Future<Output = Result<Value>> {
self.connection_type = None;
self.call::<requests::Disconnect>(args)
} }
pub fn launch(&self, args: serde_json::Value) -> impl Future<Output = Result<Value>> { pub fn launch(&mut self, args: serde_json::Value) -> impl Future<Output = Result<Value>> {
self.connection_type = Some(ConnectionType::Launch);
self.starting_request_args = Some(args.clone());
self.call::<requests::Launch>(args) self.call::<requests::Launch>(args)
} }
pub fn attach(&self, args: serde_json::Value) -> impl Future<Output = Result<Value>> { pub fn attach(&mut self, args: serde_json::Value) -> impl Future<Output = Result<Value>> {
self.connection_type = Some(ConnectionType::Attach);
self.starting_request_args = Some(args.clone());
self.call::<requests::Attach>(args) self.call::<requests::Attach>(args)
} }
pub fn restart(&self) -> impl Future<Output = Result<Value>> {
let args = if let Some(args) = &self.starting_request_args {
args.clone()
} else {
Value::Null
};
self.call::<requests::Restart>(args)
}
pub async fn set_breakpoints( pub async fn set_breakpoints(
&self, &self,
file: PathBuf, file: PathBuf,
@ -477,4 +510,10 @@ impl Client {
self.call::<requests::SetExceptionBreakpoints>(args) self.call::<requests::SetExceptionBreakpoints>(args)
} }
pub fn current_stack_frame(&self) -> Option<&StackFrame> {
self.stack_frames
.get(&self.thread_id?)?
.get(self.active_frame?)
}
} }

@ -2,7 +2,7 @@ mod client;
mod transport; mod transport;
mod types; mod types;
pub use client::Client; pub use client::{Client, ConnectionType};
pub use events::Event; pub use events::Event;
pub use transport::{Payload, Response, Transport}; pub use transport::{Payload, Response, Transport};
pub use types::*; pub use types::*;
@ -14,8 +14,8 @@ pub enum Error {
Parse(#[from] serde_json::Error), Parse(#[from] serde_json::Error),
#[error("IO Error: {0}")] #[error("IO Error: {0}")]
IO(#[from] std::io::Error), IO(#[from] std::io::Error),
#[error("request timed out")] #[error("request {0} timed out")]
Timeout, Timeout(u64),
#[error("server closed the stream")] #[error("server closed the stream")]
StreamClosed, StreamClosed,
#[error(transparent)] #[error(transparent)]

@ -230,38 +230,48 @@ impl Transport {
} }
} }
async fn recv( async fn recv_inner(
transport: Arc<Self>, transport: Arc<Self>,
mut server_stdout: Box<dyn AsyncBufRead + Unpin + Send>, mut server_stdout: Box<dyn AsyncBufRead + Unpin + Send>,
client_tx: UnboundedSender<Payload>, client_tx: UnboundedSender<Payload>,
) { ) -> Result<()> {
let mut recv_buffer = String::new(); let mut recv_buffer = String::new();
loop { loop {
match Self::recv_server_message(&mut server_stdout, &mut recv_buffer).await { let msg = Self::recv_server_message(&mut server_stdout, &mut recv_buffer).await?;
Ok(msg) => { transport.process_server_message(&client_tx, msg).await?;
transport
.process_server_message(&client_tx, msg)
.await
.unwrap();
}
Err(err) => {
error!("err: <- {:?}", err);
break;
} }
} }
async fn recv(
transport: Arc<Self>,
server_stdout: Box<dyn AsyncBufRead + Unpin + Send>,
client_tx: UnboundedSender<Payload>,
) {
if let Err(err) = Self::recv_inner(transport, server_stdout, client_tx).await {
error!("err: <- {:?}", err);
} }
} }
async fn send( async fn send_inner(
transport: Arc<Self>, transport: Arc<Self>,
mut server_stdin: Box<dyn AsyncWrite + Unpin + Send>, mut server_stdin: Box<dyn AsyncWrite + Unpin + Send>,
mut client_rx: UnboundedReceiver<Payload>, mut client_rx: UnboundedReceiver<Payload>,
) { ) -> Result<()> {
while let Some(payload) = client_rx.recv().await { while let Some(payload) = client_rx.recv().await {
transport transport
.send_payload_to_server(&mut server_stdin, payload) .send_payload_to_server(&mut server_stdin, payload)
.await .await?;
.unwrap() }
Ok(())
}
async fn send(
transport: Arc<Self>,
server_stdin: Box<dyn AsyncWrite + Unpin + Send>,
client_rx: UnboundedReceiver<Payload>,
) {
if let Err(err) = Self::send_inner(transport, server_stdin, client_rx).await {
error!("err: <- {:?}", err);
} }
} }

@ -378,7 +378,7 @@ pub mod requests {
impl Request for Launch { impl Request for Launch {
type Arguments = Value; type Arguments = Value;
type Result = Value; type Result = ();
const COMMAND: &'static str = "launch"; const COMMAND: &'static str = "launch";
} }
@ -387,15 +387,35 @@ pub mod requests {
impl Request for Attach { impl Request for Attach {
type Arguments = Value; type Arguments = Value;
type Result = Value; type Result = ();
const COMMAND: &'static str = "attach"; const COMMAND: &'static str = "attach";
} }
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DisconnectArguments {
#[serde(skip_serializing_if = "Option::is_none")]
pub restart: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub terminate_debuggee: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suspend_debuggee: Option<bool>,
}
#[derive(Debug)]
pub enum Restart {}
impl Request for Restart {
type Arguments = Value;
type Result = ();
const COMMAND: &'static str = "restart";
}
#[derive(Debug)] #[derive(Debug)]
pub enum Disconnect {} pub enum Disconnect {}
impl Request for Disconnect { impl Request for Disconnect {
type Arguments = (); type Arguments = Option<DisconnectArguments>;
type Result = (); type Result = ();
const COMMAND: &'static str = "disconnect"; const COMMAND: &'static str = "disconnect";
} }

@ -0,0 +1,15 @@
[package]
name = "helix-event"
version = "0.6.0"
authors = ["Blaž Hrastnik <blaz@mxxn.io>"]
edition = "2021"
license = "MPL-2.0"
categories = ["editor"]
repository = "https://github.com/helix-editor/helix"
homepage = "https://helix-editor.com"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "sync", "parking_lot"] }
parking_lot = { version = "0.12", features = ["send_guard"] }

@ -0,0 +1,8 @@
//! `helix-event` contains systems that allow (often async) communication between
//! different editor components without strongly coupling them. Currently this
//! crate only contains some smaller facilities but the intend is to add more
//! functionality in the future ( like a generic hook system)
pub use redraw::{lock_frame, redraw_requested, request_redraw, start_frame, RenderLockGuard};
mod redraw;

@ -0,0 +1,49 @@
//! Signals that control when/if the editor redraws
use std::future::Future;
use parking_lot::{RwLock, RwLockReadGuard};
use tokio::sync::Notify;
/// A `Notify` instance that can be used to (asynchronously) request
/// the editor the render a new frame.
static REDRAW_NOTIFY: Notify = Notify::const_new();
/// A `RwLock` that prevents the next frame from being
/// drawn until an exclusive (write) lock can be acquired.
/// This allows asynchsonous tasks to acquire `non-exclusive`
/// locks (read) to prevent the next frame from being drawn
/// until a certain computation has finished.
static RENDER_LOCK: RwLock<()> = RwLock::new(());
pub type RenderLockGuard = RwLockReadGuard<'static, ()>;
/// Requests that the editor is redrawn. The redraws are debounced (currently to
/// 30FPS) so this can be called many times without causing a ton of frames to
/// be rendered.
pub fn request_redraw() {
REDRAW_NOTIFY.notify_one();
}
/// Returns a future that will yield once a redraw has been asynchronously
/// requested using [`request_redraw`].
pub fn redraw_requested() -> impl Future<Output = ()> {
REDRAW_NOTIFY.notified()
}
/// Wait until all locks acquired with [`lock_frame`] have been released.
/// This function is called before rendering and is intended to allow the frame
/// to wait for async computations that should be included in the current frame.
pub fn start_frame() {
drop(RENDER_LOCK.write());
// exhaust any leftover redraw notifications
let notify = REDRAW_NOTIFY.notified();
tokio::pin!(notify);
notify.enable();
}
/// Acquires the render lock which will prevent the next frame from being drawn
/// until the returned guard is dropped.
pub fn lock_frame() -> RenderLockGuard {
RENDER_LOCK.read()
}

@ -16,17 +16,20 @@ path = "src/main.rs"
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
toml = "0.5" toml = "0.7"
etcetera = "0.4" etcetera = "0.8"
tree-sitter = "0.20" tree-sitter.workspace = true
once_cell = "1.16" once_cell = "1.18"
log = "0.4" log = "0.4"
which = "4.4"
# TODO: these two should be on !wasm32 only # TODO: these two should be on !wasm32 only
# cloning/compiling tree-sitter grammars # cloning/compiling tree-sitter grammars
cc = { version = "1" } cc = { version = "1" }
threadpool = { version = "1.0" } threadpool = { version = "1.0" }
tempfile = "3.8.1"
dunce = "1.0.4"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
libloading = "0.7" libloading = "0.8"

@ -1,4 +1,5 @@
use std::borrow::Cow; use std::borrow::Cow;
use std::path::Path;
use std::process::Command; use std::process::Command;
const VERSION: &str = include_str!("../VERSION"); const VERSION: &str = include_str!("../VERSION");
@ -11,7 +12,7 @@ fn main() {
.filter(|output| output.status.success()) .filter(|output| output.status.success())
.and_then(|x| String::from_utf8(x.stdout).ok()); .and_then(|x| String::from_utf8(x.stdout).ok());
let version: Cow<_> = match git_hash { let version: Cow<_> = match &git_hash {
Some(git_hash) => format!("{} ({})", VERSION, &git_hash[..8]).into(), Some(git_hash) => format!("{} ({})", VERSION, &git_hash[..8]).into(),
None => VERSION.into(), None => VERSION.into(),
}; };
@ -23,4 +24,44 @@ fn main() {
println!("cargo:rerun-if-changed=../VERSION"); println!("cargo:rerun-if-changed=../VERSION");
println!("cargo:rustc-env=VERSION_AND_GIT_HASH={}", version); println!("cargo:rustc-env=VERSION_AND_GIT_HASH={}", version);
if git_hash.is_none() {
return;
}
// we need to revparse because the git dir could be anywhere if you are
// using detached worktrees but there is no good way to obtain an OsString
// from command output so for now we can't accept non-utf8 paths here
// probably rare enouch where it doesn't matter tough we could use gitoxide
// here but that would be make it a hard dependency and slow compile times
let Some(git_dir): Option<String> = Command::new("git")
.args(["rev-parse", "--git-dir"])
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|x| String::from_utf8(x.stdout).ok())
else {
return;
};
// If heads starts pointing at something else (different branch)
// we need to return
let head = Path::new(&git_dir).join("HEAD");
if head.exists() {
println!("cargo:rerun-if-changed={}", head.display());
}
// if the thing head points to (branch) itself changes
// we need to return
let Some(head_ref): Option<String> = Command::new("git")
.args(["symbolic-ref", "HEAD"])
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|x| String::from_utf8(x.stdout).ok())
else {
return;
};
let head_ref = Path::new(&git_dir).join(head_ref);
if head_ref.exists() {
println!("cargo:rerun-if-changed={}", head_ref.display());
}
} }

@ -1,24 +1,28 @@
use std::str::from_utf8;
/// Default built-in languages.toml. /// Default built-in languages.toml.
pub fn default_lang_config() -> toml::Value { pub fn default_lang_config() -> toml::Value {
toml::from_slice(include_bytes!("../../languages.toml")) let default_config = include_bytes!("../../languages.toml");
toml::from_str(from_utf8(default_config).unwrap())
.expect("Could not parse built-in languages.toml to valid toml") .expect("Could not parse built-in languages.toml to valid toml")
} }
/// User configured languages.toml file, merged with the default config. /// User configured languages.toml file, merged with the default config.
pub fn user_lang_config() -> Result<toml::Value, toml::de::Error> { pub fn user_lang_config() -> Result<toml::Value, toml::de::Error> {
let config = crate::local_config_dirs() let config = [
crate::config_dir(),
crate::find_workspace().0.join(".helix"),
]
.into_iter() .into_iter()
.chain([crate::config_dir()].into_iter())
.map(|path| path.join("languages.toml")) .map(|path| path.join("languages.toml"))
.filter_map(|file| { .filter_map(|file| {
std::fs::read(&file) std::fs::read_to_string(file)
.map(|config| toml::from_slice(&config)) .map(|config| toml::from_str(&config))
.ok() .ok()
}) })
.collect::<Result<Vec<_>, _>>()? .collect::<Result<Vec<_>, _>>()?
.into_iter() .into_iter()
.chain([default_lang_config()].into_iter()) .fold(default_lang_config(), |a, b| {
.fold(toml::Value::Table(toml::value::Table::default()), |a, b| {
// combines for example // combines for example
// b: // b:
// [[language]] // [[language]]
@ -35,7 +39,7 @@ pub fn user_lang_config() -> Result<toml::Value, toml::de::Error> {
// language-server = { command = "/usr/bin/taplo" } // language-server = { command = "/usr/bin/taplo" }
// //
// thus it overrides the third depth-level of b with values of a if they exist, but otherwise merges their values // thus it overrides the third depth-level of b with values of a if they exist, but otherwise merges their values
crate::merge_toml_values(b, a, 3) crate::merge_toml_values(a, b, 3)
}); });
Ok(config) Ok(config)

@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs; use std::fs;
use std::time::SystemTime; use std::time::SystemTime;
@ -8,6 +8,7 @@ use std::{
process::Command, process::Command,
sync::mpsc::channel, sync::mpsc::channel,
}; };
use tempfile::TempPath;
use tree_sitter::Language; use tree_sitter::Language;
#[cfg(unix)] #[cfg(unix)]
@ -67,8 +68,9 @@ pub fn get_language(name: &str) -> Result<Language> {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub fn get_language(name: &str) -> Result<Language> { pub fn get_language(name: &str) -> Result<Language> {
use libloading::{Library, Symbol}; use libloading::{Library, Symbol};
let mut library_path = crate::runtime_dir().join("grammars").join(name); let mut rel_library_path = PathBuf::new().join("grammars").join(name);
library_path.set_extension(DYLIB_EXTENSION); rel_library_path.set_extension(DYLIB_EXTENSION);
let library_path = crate::runtime_file(&rel_library_path);
let library = unsafe { Library::new(&library_path) } let library = unsafe { Library::new(&library_path) }
.with_context(|| format!("Error opening dynamic library {:?}", library_path))?; .with_context(|| format!("Error opening dynamic library {:?}", library_path))?;
@ -83,7 +85,16 @@ pub fn get_language(name: &str) -> Result<Language> {
Ok(language) Ok(language)
} }
fn ensure_git_is_available() -> Result<()> {
match which::which("git") {
Ok(_cmd) => Ok(()),
Err(err) => Err(anyhow::anyhow!("'git' could not be found ({err})")),
}
}
pub fn fetch_grammars() -> Result<()> { pub fn fetch_grammars() -> Result<()> {
ensure_git_is_available()?;
// We do not need to fetch local grammars. // We do not need to fetch local grammars.
let mut grammars = get_grammar_configs()?; let mut grammars = get_grammar_configs()?;
grammars.retain(|grammar| !matches!(grammar.source, GrammarSource::Local { .. })); grammars.retain(|grammar| !matches!(grammar.source, GrammarSource::Local { .. }));
@ -96,15 +107,12 @@ pub fn fetch_grammars() -> Result<()> {
let mut git_up_to_date = 0; let mut git_up_to_date = 0;
let mut non_git = Vec::new(); let mut non_git = Vec::new();
for res in results { for (grammar_id, res) in results {
match res { match res {
Ok(FetchStatus::GitUpToDate) => git_up_to_date += 1, Ok(FetchStatus::GitUpToDate) => git_up_to_date += 1,
Ok(FetchStatus::GitUpdated { Ok(FetchStatus::GitUpdated { revision }) => git_updated.push((grammar_id, revision)),
grammar_id, Ok(FetchStatus::NonGit) => non_git.push(grammar_id),
revision, Err(e) => errors.push((grammar_id, e)),
}) => git_updated.push((grammar_id, revision)),
Ok(FetchStatus::NonGit { grammar_id }) => non_git.push(grammar_id),
Err(e) => errors.push(e),
} }
} }
@ -136,16 +144,18 @@ pub fn fetch_grammars() -> Result<()> {
if !errors.is_empty() { if !errors.is_empty() {
let len = errors.len(); let len = errors.len();
println!("{} grammars failed to fetch", len); for (i, (grammar, error)) in errors.into_iter().enumerate() {
for (i, error) in errors.into_iter().enumerate() { println!("Failure {}/{len}: {grammar} {error}", i + 1);
println!("\tFailure {}/{}: {}", i + 1, len, error);
} }
bail!("{len} grammars failed to fetch");
} }
Ok(()) Ok(())
} }
pub fn build_grammars(target: Option<String>) -> Result<()> { pub fn build_grammars(target: Option<String>) -> Result<()> {
ensure_git_is_available()?;
let grammars = get_grammar_configs()?; let grammars = get_grammar_configs()?;
println!("Building {} grammars", grammars.len()); println!("Building {} grammars", grammars.len());
let results = run_parallel(grammars, move |grammar| { let results = run_parallel(grammars, move |grammar| {
@ -156,11 +166,11 @@ pub fn build_grammars(target: Option<String>) -> Result<()> {
let mut already_built = 0; let mut already_built = 0;
let mut built = Vec::new(); let mut built = Vec::new();
for res in results { for (grammar_id, res) in results {
match res { match res {
Ok(BuildStatus::AlreadyBuilt) => already_built += 1, Ok(BuildStatus::AlreadyBuilt) => already_built += 1,
Ok(BuildStatus::Built { grammar_id }) => built.push(grammar_id), Ok(BuildStatus::Built) => built.push(grammar_id),
Err(e) => errors.push(e), Err(e) => errors.push((grammar_id, e)),
} }
} }
@ -177,10 +187,10 @@ pub fn build_grammars(target: Option<String>) -> Result<()> {
if !errors.is_empty() { if !errors.is_empty() {
let len = errors.len(); let len = errors.len();
println!("{} grammars failed to build", len); for (i, (grammar_id, error)) in errors.into_iter().enumerate() {
for (i, error) in errors.into_iter().enumerate() { println!("Failure {}/{len}: {grammar_id} {error}", i + 1);
println!("\tFailure {}/{}: {}", i, len, error);
} }
bail!("{len} grammars failed to build");
} }
Ok(()) Ok(())
@ -212,7 +222,7 @@ fn get_grammar_configs() -> Result<Vec<GrammarConfiguration>> {
Ok(grammars) Ok(grammars)
} }
fn run_parallel<F, Res>(grammars: Vec<GrammarConfiguration>, job: F) -> Vec<Result<Res>> fn run_parallel<F, Res>(grammars: Vec<GrammarConfiguration>, job: F) -> Vec<(String, Result<Res>)>
where where
F: Fn(GrammarConfiguration) -> Result<Res> + Send + 'static + Clone, F: Fn(GrammarConfiguration) -> Result<Res> + Send + 'static + Clone,
Res: Send + 'static, Res: Send + 'static,
@ -227,7 +237,7 @@ where
pool.execute(move || { pool.execute(move || {
// Ignore any SendErrors, if any job in another thread has encountered an // Ignore any SendErrors, if any job in another thread has encountered an
// error the Receiver will be closed causing this send to fail. // error the Receiver will be closed causing this send to fail.
let _ = tx.send(job(grammar)); let _ = tx.send((grammar.grammar_id.clone(), job(grammar)));
}); });
} }
@ -238,13 +248,8 @@ where
enum FetchStatus { enum FetchStatus {
GitUpToDate, GitUpToDate,
GitUpdated { GitUpdated { revision: String },
grammar_id: String, NonGit,
revision: String,
},
NonGit {
grammar_id: String,
},
} }
fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> { fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> {
@ -252,7 +257,9 @@ fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> {
remote, revision, .. remote, revision, ..
} = grammar.source } = grammar.source
{ {
let grammar_dir = crate::runtime_dir() let grammar_dir = crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars") .join("grammars")
.join("sources") .join("sources")
.join(&grammar.grammar_id); .join(&grammar.grammar_id);
@ -263,7 +270,7 @@ fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> {
))?; ))?;
// create the grammar dir contains a git directory // create the grammar dir contains a git directory
if !grammar_dir.join(".git").is_dir() { if !grammar_dir.join(".git").exists() {
git(&grammar_dir, ["init"])?; git(&grammar_dir, ["init"])?;
} }
@ -283,17 +290,12 @@ fn fetch_grammar(grammar: GrammarConfiguration) -> Result<FetchStatus> {
)?; )?;
git(&grammar_dir, ["checkout", &revision])?; git(&grammar_dir, ["checkout", &revision])?;
Ok(FetchStatus::GitUpdated { Ok(FetchStatus::GitUpdated { revision })
grammar_id: grammar.grammar_id,
revision,
})
} else { } else {
Ok(FetchStatus::GitUpToDate) Ok(FetchStatus::GitUpToDate)
} }
} else { } else {
Ok(FetchStatus::NonGit { Ok(FetchStatus::NonGit)
grammar_id: grammar.grammar_id,
})
} }
} }
@ -343,14 +345,16 @@ where
enum BuildStatus { enum BuildStatus {
AlreadyBuilt, AlreadyBuilt,
Built { grammar_id: String }, Built,
} }
fn build_grammar(grammar: GrammarConfiguration, target: Option<&str>) -> Result<BuildStatus> { fn build_grammar(grammar: GrammarConfiguration, target: Option<&str>) -> Result<BuildStatus> {
let grammar_dir = if let GrammarSource::Local { path } = &grammar.source { let grammar_dir = if let GrammarSource::Local { path } = &grammar.source {
PathBuf::from(&path) PathBuf::from(&path)
} else { } else {
crate::runtime_dir() crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars") .join("grammars")
.join("sources") .join("sources")
.join(&grammar.grammar_id) .join(&grammar.grammar_id)
@ -401,10 +405,25 @@ fn build_tree_sitter_library(
None None
} }
}; };
let parser_lib_path = crate::runtime_dir().join("grammars"); let parser_lib_path = crate::runtime_dirs()
.first()
.expect("No runtime directories provided") // guaranteed by post-condition
.join("grammars");
let mut library_path = parser_lib_path.join(&grammar.grammar_id); let mut library_path = parser_lib_path.join(&grammar.grammar_id);
library_path.set_extension(DYLIB_EXTENSION); library_path.set_extension(DYLIB_EXTENSION);
// if we are running inside a buildscript emit cargo metadata
// to detect if we are running from a buildscript check some env variables
// that cargo only sets for build scripts
if std::env::var("OUT_DIR").is_ok() && std::env::var("CARGO").is_ok() {
if let Some(scanner_path) = scanner_path.as_ref().and_then(|path| path.to_str()) {
println!("cargo:rerun-if-changed={scanner_path}");
}
if let Some(parser_path) = parser_path.to_str() {
println!("cargo:rerun-if-changed={parser_path}");
}
}
let recompile = needs_recompile(&library_path, &parser_path, &scanner_path) let recompile = needs_recompile(&library_path, &parser_path, &scanner_path)
.context("Failed to compare source and binary timestamps")?; .context("Failed to compare source and binary timestamps")?;
@ -425,16 +444,53 @@ fn build_tree_sitter_library(
for (key, value) in compiler.env() { for (key, value) in compiler.env() {
command.env(key, value); command.env(key, value);
} }
command.args(compiler.args()); command.args(compiler.args());
// used to delay dropping the temporary object file until after the compilation is complete
let _path_guard;
if cfg!(all(windows, target_env = "msvc")) { if compiler.is_like_msvc() {
command command
.args(["/nologo", "/LD", "/I"]) .args(["/nologo", "/LD", "/I"])
.arg(header_path) .arg(header_path)
.arg("/Od") .arg("/Od")
.arg("/utf-8"); .arg("/utf-8")
.arg("/std:c11");
if let Some(scanner_path) = scanner_path.as_ref() { if let Some(scanner_path) = scanner_path.as_ref() {
if scanner_path.extension() == Some("c".as_ref()) {
command.arg(scanner_path); command.arg(scanner_path);
} else {
let mut cpp_command = Command::new(compiler.path());
cpp_command.current_dir(src_path);
for (key, value) in compiler.env() {
cpp_command.env(key, value);
}
cpp_command.args(compiler.args());
let object_file =
library_path.with_file_name(format!("{}_scanner.obj", &grammar.grammar_id));
cpp_command
.args(["/nologo", "/LD", "/I"])
.arg(header_path)
.arg("/Od")
.arg("/utf-8")
.arg("/std:c++14")
.arg(format!("/Fo{}", object_file.display()))
.arg("/c")
.arg(scanner_path);
let output = cpp_command
.output()
.context("Failed to execute C++ compiler")?;
if !output.status.success() {
return Err(anyhow!(
"Parser compilation failed.\nStdout: {}\nStderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
command.arg(&object_file);
_path_guard = TempPath::from_path(object_file);
}
} }
command command
@ -446,20 +502,49 @@ fn build_tree_sitter_library(
.arg("-shared") .arg("-shared")
.arg("-fPIC") .arg("-fPIC")
.arg("-fno-exceptions") .arg("-fno-exceptions")
.arg("-g")
.arg("-I") .arg("-I")
.arg(header_path) .arg(header_path)
.arg("-o") .arg("-o")
.arg(&library_path) .arg(&library_path);
.arg("-O3");
if let Some(scanner_path) = scanner_path.as_ref() { if let Some(scanner_path) = scanner_path.as_ref() {
if scanner_path.extension() == Some("c".as_ref()) { if scanner_path.extension() == Some("c".as_ref()) {
command.arg("-xc").arg("-std=c99").arg(scanner_path); command.arg("-xc").arg("-std=c11").arg(scanner_path);
} else { } else {
command.arg(scanner_path); let mut cpp_command = Command::new(compiler.path());
cpp_command.current_dir(src_path);
for (key, value) in compiler.env() {
cpp_command.env(key, value);
}
cpp_command.args(compiler.args());
let object_file =
library_path.with_file_name(format!("{}_scanner.o", &grammar.grammar_id));
cpp_command
.arg("-fPIC")
.arg("-fno-exceptions")
.arg("-I")
.arg(header_path)
.arg("-o")
.arg(&object_file)
.arg("-std=c++14")
.arg("-c")
.arg(scanner_path);
let output = cpp_command
.output()
.context("Failed to execute C++ compiler")?;
if !output.status.success() {
return Err(anyhow!(
"Parser compilation failed.\nStdout: {}\nStderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
command.arg(&object_file);
_path_guard = TempPath::from_path(object_file);
} }
} }
command.arg("-xc").arg(parser_path); command.arg("-xc").arg("-std=c11").arg(parser_path);
if cfg!(all( if cfg!(all(
unix, unix,
not(any(target_os = "macos", target_os = "illumos")) not(any(target_os = "macos", target_os = "illumos"))
@ -479,9 +564,7 @@ fn build_tree_sitter_library(
)); ));
} }
Ok(BuildStatus::Built { Ok(BuildStatus::Built)
grammar_id: grammar.grammar_id,
})
} }
fn needs_recompile( fn needs_recompile(
@ -511,9 +594,6 @@ fn mtime(path: &Path) -> Result<SystemTime> {
/// Gives the contents of a file from a language's `runtime/queries/<lang>` /// Gives the contents of a file from a language's `runtime/queries/<lang>`
/// directory /// directory
pub fn load_runtime_file(language: &str, filename: &str) -> Result<String, std::io::Error> { pub fn load_runtime_file(language: &str, filename: &str) -> Result<String, std::io::Error> {
let path = crate::RUNTIME_DIR let path = crate::runtime_file(&PathBuf::new().join("queries").join(language).join(filename));
.join("queries") std::fs::read_to_string(path)
.join(language)
.join(filename);
std::fs::read_to_string(&path)
} }

@ -2,54 +2,143 @@ pub mod config;
pub mod grammar; pub mod grammar;
use etcetera::base_strategy::{choose_base_strategy, BaseStrategy}; use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::RwLock;
pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH"); pub const VERSION_AND_GIT_HASH: &str = env!("VERSION_AND_GIT_HASH");
pub static RUNTIME_DIR: once_cell::sync::Lazy<PathBuf> = once_cell::sync::Lazy::new(runtime_dir); static CWD: RwLock<Option<PathBuf>> = RwLock::new(None);
static RUNTIME_DIRS: once_cell::sync::Lazy<Vec<PathBuf>> =
once_cell::sync::Lazy::new(prioritize_runtime_dirs);
static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new(); static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
pub fn initialize_config_file(specified_file: Option<PathBuf>) { static LOG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
let config_file = specified_file.unwrap_or_else(|| {
let config_dir = config_dir();
if !config_dir.exists() { // Get the current working directory.
std::fs::create_dir_all(&config_dir).ok(); // This information is managed internally as the call to std::env::current_dir
// might fail if the cwd has been deleted.
pub fn current_working_dir() -> PathBuf {
if let Some(path) = &*CWD.read().unwrap() {
return path.clone();
} }
config_dir.join("config.toml") let path = std::env::current_dir()
}); .and_then(dunce::canonicalize)
.expect("Couldn't determine current working directory");
let mut cwd = CWD.write().unwrap();
*cwd = Some(path.clone());
path
}
// We should only initialize this value once. pub fn set_current_working_dir(path: impl AsRef<Path>) -> std::io::Result<()> {
let path = dunce::canonicalize(path)?;
std::env::set_current_dir(&path)?;
let mut cwd = CWD.write().unwrap();
*cwd = Some(path);
Ok(())
}
pub fn initialize_config_file(specified_file: Option<PathBuf>) {
let config_file = specified_file.unwrap_or_else(default_config_file);
ensure_parent_dir(&config_file);
CONFIG_FILE.set(config_file).ok(); CONFIG_FILE.set(config_file).ok();
} }
pub fn runtime_dir() -> PathBuf { pub fn initialize_log_file(specified_file: Option<PathBuf>) {
if let Ok(dir) = std::env::var("HELIX_RUNTIME") { let log_file = specified_file.unwrap_or_else(default_log_file);
return dir.into(); ensure_parent_dir(&log_file);
LOG_FILE.set(log_file).ok();
} }
/// A list of runtime directories from highest to lowest priority
///
/// The priority is:
///
/// 1. sibling directory to `CARGO_MANIFEST_DIR` (if environment variable is set)
/// 2. subdirectory of user config directory (always included)
/// 3. `HELIX_RUNTIME` (if environment variable is set)
/// 4. `HELIX_DEFAULT_RUNTIME` (if environment variable is set *at build time*)
/// 5. subdirectory of path to helix executable (always included)
///
/// Postcondition: returns at least two paths (they might not exist).
fn prioritize_runtime_dirs() -> Vec<PathBuf> {
const RT_DIR: &str = "runtime";
// Adding higher priority first
let mut rt_dirs = Vec::new();
if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") { if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") {
// this is the directory of the crate being run by cargo, we need the workspace path so we take the parent // this is the directory of the crate being run by cargo, we need the workspace path so we take the parent
let path = std::path::PathBuf::from(dir).parent().unwrap().join(RT_DIR); let path = PathBuf::from(dir).parent().unwrap().join(RT_DIR);
log::debug!("runtime dir: {}", path.to_string_lossy()); log::debug!("runtime dir: {}", path.to_string_lossy());
return path; rt_dirs.push(path);
} }
const RT_DIR: &str = "runtime"; let conf_rt_dir = config_dir().join(RT_DIR);
let conf_dir = config_dir().join(RT_DIR); rt_dirs.push(conf_rt_dir);
if conf_dir.exists() {
return conf_dir; if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
rt_dirs.push(dir.into());
}
// If this variable is set during build time, it will always be included
// in the lookup list. This allows downstream packagers to set a fallback
// directory to a location that is conventional on their distro so that they
// need not resort to a wrapper script or a global environment variable.
if let Some(dir) = std::option_env!("HELIX_DEFAULT_RUNTIME") {
rt_dirs.push(dir.into());
} }
// fallback to location of the executable being run // fallback to location of the executable being run
// canonicalize the path in case the executable is symlinked // canonicalize the path in case the executable is symlinked
std::env::current_exe() let exe_rt_dir = std::env::current_exe()
.ok() .ok()
.and_then(|path| std::fs::canonicalize(path).ok()) .and_then(|path| std::fs::canonicalize(path).ok())
.and_then(|path| path.parent().map(|path| path.to_path_buf().join(RT_DIR))) .and_then(|path| path.parent().map(|path| path.to_path_buf().join(RT_DIR)))
.unwrap() .unwrap();
rt_dirs.push(exe_rt_dir);
rt_dirs
}
/// Runtime directories ordered from highest to lowest priority
///
/// All directories should be checked when looking for files.
///
/// Postcondition: returns at least one path (it might not exist).
pub fn runtime_dirs() -> &'static [PathBuf] {
&RUNTIME_DIRS
}
/// Find file with path relative to runtime directory
///
/// `rel_path` should be the relative path from within the `runtime/` directory.
/// The valid runtime directories are searched in priority order and the first
/// file found to exist is returned, otherwise None.
fn find_runtime_file(rel_path: &Path) -> Option<PathBuf> {
RUNTIME_DIRS.iter().find_map(|rt_dir| {
let path = rt_dir.join(rel_path);
if path.exists() {
Some(path)
} else {
None
}
})
}
/// Find file with path relative to runtime directory
///
/// `rel_path` should be the relative path from within the `runtime/` directory.
/// The valid runtime directories are searched in priority order and the first
/// file found to exist is returned, otherwise the path to the final attempt
/// that failed.
pub fn runtime_file(rel_path: &Path) -> PathBuf {
find_runtime_file(rel_path).unwrap_or_else(|| {
RUNTIME_DIRS
.last()
.map(|dir| dir.join(rel_path))
.unwrap_or_default()
})
} }
pub fn config_dir() -> PathBuf { pub fn config_dir() -> PathBuf {
@ -60,15 +149,6 @@ pub fn config_dir() -> PathBuf {
path path
} }
pub fn local_config_dirs() -> Vec<PathBuf> {
let directories = find_local_config_dirs()
.into_iter()
.map(|path| path.join(".helix"))
.collect();
log::debug!("Located configuration folders: {:?}", directories);
directories
}
pub fn cache_dir() -> PathBuf { pub fn cache_dir() -> PathBuf {
// TODO: allow env var override // TODO: allow env var override
let strategy = choose_base_strategy().expect("Unable to find the config directory!"); let strategy = choose_base_strategy().expect("Unable to find the config directory!");
@ -78,34 +158,23 @@ pub fn cache_dir() -> PathBuf {
} }
pub fn config_file() -> PathBuf { pub fn config_file() -> PathBuf {
CONFIG_FILE CONFIG_FILE.get().map(|path| path.to_path_buf()).unwrap()
.get()
.map(|path| path.to_path_buf())
.unwrap_or_else(|| config_dir().join("config.toml"))
}
pub fn lang_config_file() -> PathBuf {
config_dir().join("languages.toml")
} }
pub fn log_file() -> PathBuf { pub fn log_file() -> PathBuf {
cache_dir().join("helix.log") LOG_FILE.get().map(|path| path.to_path_buf()).unwrap()
} }
pub fn find_local_config_dirs() -> Vec<PathBuf> { pub fn workspace_config_file() -> PathBuf {
let current_dir = std::env::current_dir().expect("unable to determine current directory"); find_workspace().0.join(".helix").join("config.toml")
let mut directories = Vec::new();
for ancestor in current_dir.ancestors() {
if ancestor.join(".git").is_dir() {
directories.push(ancestor.to_path_buf());
// Don't go higher than repo if we're in one
break;
} else if ancestor.join(".helix").is_dir() {
directories.push(ancestor.to_path_buf());
} }
pub fn lang_config_file() -> PathBuf {
config_dir().join("languages.toml")
} }
directories
pub fn default_log_file() -> PathBuf {
cache_dir().join("helix.log")
} }
/// Merge two TOML documents, merging values from `right` onto `left` /// Merge two TOML documents, merging values from `right` onto `left`
@ -177,11 +246,55 @@ pub fn merge_toml_values(left: toml::Value, right: toml::Value, merge_depth: usi
} }
} }
/// Finds the current workspace folder.
/// Used as a ceiling dir for LSP root resolution, the filepicker and potentially as a future filewatching root
///
/// This function starts searching the FS upward from the CWD
/// and returns the first directory that contains either `.git` or `.helix`.
/// If no workspace was found returns (CWD, true).
/// Otherwise (workspace, false) is returned
pub fn find_workspace() -> (PathBuf, bool) {
let current_dir = current_working_dir();
for ancestor in current_dir.ancestors() {
if ancestor.join(".git").exists() || ancestor.join(".helix").exists() {
return (ancestor.to_owned(), false);
}
}
(current_dir, true)
}
fn default_config_file() -> PathBuf {
config_dir().join("config.toml")
}
fn ensure_parent_dir(path: &Path) {
if let Some(parent) = path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent).ok();
}
}
}
#[cfg(test)] #[cfg(test)]
mod merge_toml_tests { mod merge_toml_tests {
use super::merge_toml_values; use std::str;
use super::{current_working_dir, merge_toml_values, set_current_working_dir};
use toml::Value; use toml::Value;
#[test]
fn current_dir_is_set() {
let new_path = dunce::canonicalize(std::env::temp_dir()).unwrap();
let cwd = current_working_dir();
assert_ne!(cwd, new_path);
set_current_working_dir(&new_path).expect("Couldn't set new path");
let cwd = current_working_dir();
assert_eq!(cwd, new_path);
}
#[test] #[test]
fn language_toml_map_merges() { fn language_toml_map_merges() {
const USER: &str = r#" const USER: &str = r#"
@ -191,8 +304,9 @@ mod merge_toml_tests {
indent = { tab-width = 4, unit = " ", test = "aaa" } indent = { tab-width = 4, unit = " ", test = "aaa" }
"#; "#;
let base: Value = toml::from_slice(include_bytes!("../../languages.toml")) let base = include_bytes!("../../languages.toml");
.expect("Couldn't parse built-in languages config"); let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
let user: Value = toml::from_str(USER).unwrap(); let user: Value = toml::from_str(USER).unwrap();
let merged = merge_toml_values(base, user, 3); let merged = merge_toml_values(base, user, 3);
@ -224,8 +338,9 @@ mod merge_toml_tests {
language-server = { command = "deno", args = ["lsp"] } language-server = { command = "deno", args = ["lsp"] }
"#; "#;
let base: Value = toml::from_slice(include_bytes!("../../languages.toml")) let base = include_bytes!("../../languages.toml");
.expect("Couldn't parse built-in languages config"); let base = str::from_utf8(base).expect("Couldn't parse built-in languages config");
let base: Value = toml::from_str(base).expect("Couldn't parse built-in languages config");
let user: Value = toml::from_str(USER).unwrap(); let user: Value = toml::from_str(USER).unwrap();
let merged = merge_toml_values(base, user, 3); let merged = merge_toml_values(base, user, 3);

@ -14,15 +14,18 @@ homepage = "https://helix-editor.com"
[dependencies] [dependencies]
helix-core = { version = "0.6", path = "../helix-core" } helix-core = { version = "0.6", path = "../helix-core" }
helix-loader = { version = "0.6", path = "../helix-loader" } helix-loader = { version = "0.6", path = "../helix-loader" }
helix-parsec = { version = "0.6", path = "../helix-parsec" }
anyhow = "1.0" anyhow = "1.0"
futures-executor = "0.3" futures-executor = "0.3"
futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false } futures-util = { version = "0.3", features = ["std", "async-await"], default-features = false }
globset = "0.4.13"
log = "0.4" log = "0.4"
lsp-types = { version = "0.93", features = ["proposed"] } lsp-types = { version = "0.94" }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
thiserror = "1.0" thiserror = "1.0"
tokio = { version = "1.22", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] } tokio = { version = "1.34", features = ["rt", "rt-multi-thread", "io-util", "io-std", "time", "process", "macros", "fs", "parking_lot", "sync"] }
tokio-stream = "0.1.11" tokio-stream = "0.1.14"
which = "4.2" which = "4.4"
parking_lot = "0.12.1"

@ -1,21 +1,27 @@
use crate::{ use crate::{
jsonrpc, find_lsp_workspace, jsonrpc,
transport::{Payload, Transport}, transport::{Payload, Transport},
Call, Error, OffsetEncoding, Result, Call, Error, OffsetEncoding, Result,
}; };
use helix_core::{find_root, ChangeSet, Rope}; use helix_core::{find_workspace, path, syntax::LanguageServerFeature, ChangeSet, Rope};
use helix_loader::{self, VERSION_AND_GIT_HASH}; use helix_loader::{self, VERSION_AND_GIT_HASH};
use lsp::{
notification::DidChangeWorkspaceFolders, CodeActionCapabilityResolveSupport,
DidChangeWorkspaceFoldersParams, OneOf, PositionEncodingKind, WorkspaceFolder,
WorkspaceFoldersChangeEvent,
};
use lsp_types as lsp; use lsp_types as lsp;
use parking_lot::Mutex;
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::process::Stdio; use std::process::Stdio;
use std::sync::{ use std::sync::{
atomic::{AtomicU64, Ordering}, atomic::{AtomicU64, Ordering},
Arc, Arc,
}; };
use std::{collections::HashMap, path::PathBuf};
use tokio::{ use tokio::{
io::{BufReader, BufWriter}, io::{BufReader, BufWriter},
process::{Child, Command}, process::{Child, Command},
@ -25,31 +31,153 @@ use tokio::{
}, },
}; };
fn workspace_for_uri(uri: lsp::Url) -> WorkspaceFolder {
lsp::WorkspaceFolder {
name: uri
.path_segments()
.and_then(|segments| segments.last())
.map(|basename| basename.to_string())
.unwrap_or_default(),
uri,
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct Client { pub struct Client {
id: usize, id: usize,
name: String,
_process: Child, _process: Child,
server_tx: UnboundedSender<Payload>, server_tx: UnboundedSender<Payload>,
request_counter: AtomicU64, request_counter: AtomicU64,
pub(crate) capabilities: OnceCell<lsp::ServerCapabilities>, pub(crate) capabilities: OnceCell<lsp::ServerCapabilities>,
offset_encoding: OffsetEncoding,
config: Option<Value>, config: Option<Value>,
root_path: std::path::PathBuf, root_path: std::path::PathBuf,
root_uri: Option<lsp::Url>, root_uri: Option<lsp::Url>,
workspace_folders: Vec<lsp::WorkspaceFolder>, workspace_folders: Mutex<Vec<lsp::WorkspaceFolder>>,
initialize_notify: Arc<Notify>,
/// workspace folders added while the server is still initializing
req_timeout: u64, req_timeout: u64,
} }
impl Client { impl Client {
#[allow(clippy::type_complexity)] pub fn try_add_doc(
#[allow(clippy::too_many_arguments)] self: &Arc<Self>,
root_markers: &[String],
manual_roots: &[PathBuf],
doc_path: Option<&std::path::PathBuf>,
may_support_workspace: bool,
) -> bool {
let (workspace, workspace_is_cwd) = find_workspace();
let workspace = path::get_normalized_path(&workspace);
let root = find_lsp_workspace(
doc_path
.and_then(|x| x.parent().and_then(|x| x.to_str()))
.unwrap_or("."),
root_markers,
manual_roots,
&workspace,
workspace_is_cwd,
);
let root_uri = root
.as_ref()
.and_then(|root| lsp::Url::from_file_path(root).ok());
if self.root_path == root.unwrap_or(workspace)
|| root_uri.as_ref().map_or(false, |root_uri| {
self.workspace_folders
.lock()
.iter()
.any(|workspace| &workspace.uri == root_uri)
})
{
// workspace URI is already registered so we can use this client
return true;
}
// this server definitely doesn't support multiple workspace, no need to check capabilities
if !may_support_workspace {
return false;
}
let Some(capabilities) = self.capabilities.get() else {
let client = Arc::clone(self);
// initialization hasn't finished yet, deal with this new root later
// TODO: In the edgecase that a **new root** is added
// for an LSP that **doesn't support workspace_folders** before initaliation is finished
// the new roots are ignored.
// That particular edgecase would require retroactively spawning new LSP
// clients and therefore also require us to retroactively update the corresponding
// documents LSP client handle. It's doable but a pretty weird edgecase so let's
// wait and see if anyone ever runs into it.
tokio::spawn(async move {
client.initialize_notify.notified().await;
if let Some(workspace_folders_caps) = client
.capabilities()
.workspace
.as_ref()
.and_then(|cap| cap.workspace_folders.as_ref())
.filter(|cap| cap.supported.unwrap_or(false))
{
client.add_workspace_folder(
root_uri,
&workspace_folders_caps.change_notifications,
);
}
});
return true;
};
if let Some(workspace_folders_caps) = capabilities
.workspace
.as_ref()
.and_then(|cap| cap.workspace_folders.as_ref())
.filter(|cap| cap.supported.unwrap_or(false))
{
self.add_workspace_folder(root_uri, &workspace_folders_caps.change_notifications);
true
} else {
// the server doesn't support multi workspaces, we need a new client
false
}
}
fn add_workspace_folder(
&self,
root_uri: Option<lsp::Url>,
change_notifications: &Option<OneOf<bool, String>>,
) {
// root_uri is None just means that there isn't really any LSP workspace
// associated with this file. For servers that support multiple workspaces
// there is just one server so we can always just use that shared instance.
// No need to add a new workspace root here as there is no logical root for this file
// let the server deal with this
let Some(root_uri) = root_uri else {
return;
};
// server supports workspace folders, let's add the new root to the list
self.workspace_folders
.lock()
.push(workspace_for_uri(root_uri.clone()));
if &Some(OneOf::Left(false)) == change_notifications {
// server specifically opted out of DidWorkspaceChange notifications
// let's assume the server will request the workspace folders itself
// and that we can therefore reuse the client (but are done now)
return;
}
tokio::spawn(self.did_change_workspace(vec![workspace_for_uri(root_uri)], Vec::new()));
}
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub fn start( pub fn start(
cmd: &str, cmd: &str,
args: &[String], args: &[String],
config: Option<Value>, config: Option<Value>,
server_environment: HashMap<String, String>, server_environment: HashMap<String, String>,
root_markers: &[String], root_markers: &[String],
manual_roots: &[PathBuf],
id: usize, id: usize,
name: String,
req_timeout: u64, req_timeout: u64,
doc_path: Option<&std::path::PathBuf>, doc_path: Option<&std::path::PathBuf>,
) -> Result<(Self, UnboundedReceiver<(usize, Call)>, Arc<Notify>)> { ) -> Result<(Self, UnboundedReceiver<(usize, Call)>, Arc<Notify>)> {
@ -74,48 +202,51 @@ impl Client {
let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr")); let stderr = BufReader::new(process.stderr.take().expect("Failed to open stderr"));
let (server_rx, server_tx, initialize_notify) = let (server_rx, server_tx, initialize_notify) =
Transport::start(reader, writer, stderr, id); Transport::start(reader, writer, stderr, id, name.clone());
let (workspace, workspace_is_cwd) = find_workspace();
let root_path = find_root( let workspace = path::get_normalized_path(&workspace);
doc_path.and_then(|x| x.parent().and_then(|x| x.to_str())), let root = find_lsp_workspace(
doc_path
.and_then(|x| x.parent().and_then(|x| x.to_str()))
.unwrap_or("."),
root_markers, root_markers,
manual_roots,
&workspace,
workspace_is_cwd,
); );
let root_uri = lsp::Url::from_file_path(root_path.clone()).ok(); // `root_uri` and `workspace_folder` can be empty in case there is no workspace
// `root_url` can not, use `workspace` as a fallback
let root_path = root.clone().unwrap_or_else(|| workspace.clone());
let root_uri = root.and_then(|root| lsp::Url::from_file_path(root).ok());
// TODO: support multiple workspace folders
let workspace_folders = root_uri let workspace_folders = root_uri
.clone() .clone()
.map(|root| { .map(|root| vec![workspace_for_uri(root)])
vec![lsp::WorkspaceFolder {
name: root
.path_segments()
.and_then(|segments| segments.last())
.map(|basename| basename.to_string())
.unwrap_or_default(),
uri: root,
}]
})
.unwrap_or_default(); .unwrap_or_default();
let client = Self { let client = Self {
id, id,
name,
_process: process, _process: process,
server_tx, server_tx,
request_counter: AtomicU64::new(0), request_counter: AtomicU64::new(0),
capabilities: OnceCell::new(), capabilities: OnceCell::new(),
offset_encoding: OffsetEncoding::Utf8,
config, config,
req_timeout, req_timeout,
root_path, root_path,
root_uri, root_uri,
workspace_folders, workspace_folders: Mutex::new(workspace_folders),
initialize_notify: initialize_notify.clone(),
}; };
Ok((client, server_rx, initialize_notify)) Ok((client, server_rx, initialize_notify))
} }
pub fn name(&self) -> &str {
&self.name
}
pub fn id(&self) -> usize { pub fn id(&self) -> usize {
self.id self.id
} }
@ -146,16 +277,111 @@ impl Client {
.expect("language server not yet initialized!") .expect("language server not yet initialized!")
} }
/// Client has to be initialized otherwise this function panics
#[inline]
pub fn supports_feature(&self, feature: LanguageServerFeature) -> bool {
let capabilities = self.capabilities();
use lsp::*;
match feature {
LanguageServerFeature::Format => matches!(
capabilities.document_formatting_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::GotoDeclaration => matches!(
capabilities.declaration_provider,
Some(
DeclarationCapability::Simple(true)
| DeclarationCapability::RegistrationOptions(_)
| DeclarationCapability::Options(_),
)
),
LanguageServerFeature::GotoDefinition => matches!(
capabilities.definition_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::GotoTypeDefinition => matches!(
capabilities.type_definition_provider,
Some(
TypeDefinitionProviderCapability::Simple(true)
| TypeDefinitionProviderCapability::Options(_),
)
),
LanguageServerFeature::GotoReference => matches!(
capabilities.references_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::GotoImplementation => matches!(
capabilities.implementation_provider,
Some(
ImplementationProviderCapability::Simple(true)
| ImplementationProviderCapability::Options(_),
)
),
LanguageServerFeature::SignatureHelp => capabilities.signature_help_provider.is_some(),
LanguageServerFeature::Hover => matches!(
capabilities.hover_provider,
Some(HoverProviderCapability::Simple(true) | HoverProviderCapability::Options(_),)
),
LanguageServerFeature::DocumentHighlight => matches!(
capabilities.document_highlight_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::Completion => capabilities.completion_provider.is_some(),
LanguageServerFeature::CodeAction => matches!(
capabilities.code_action_provider,
Some(
CodeActionProviderCapability::Simple(true)
| CodeActionProviderCapability::Options(_),
)
),
LanguageServerFeature::WorkspaceCommand => {
capabilities.execute_command_provider.is_some()
}
LanguageServerFeature::DocumentSymbols => matches!(
capabilities.document_symbol_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::WorkspaceSymbols => matches!(
capabilities.workspace_symbol_provider,
Some(OneOf::Left(true) | OneOf::Right(_))
),
LanguageServerFeature::Diagnostics => true, // there's no extra server capability
LanguageServerFeature::RenameSymbol => matches!(
capabilities.rename_provider,
Some(OneOf::Left(true)) | Some(OneOf::Right(_))
),
LanguageServerFeature::InlayHints => matches!(
capabilities.inlay_hint_provider,
Some(OneOf::Left(true) | OneOf::Right(InlayHintServerCapabilities::Options(_)))
),
}
}
pub fn offset_encoding(&self) -> OffsetEncoding { pub fn offset_encoding(&self) -> OffsetEncoding {
self.offset_encoding self.capabilities()
.position_encoding
.as_ref()
.and_then(|encoding| match encoding.as_str() {
"utf-8" => Some(OffsetEncoding::Utf8),
"utf-16" => Some(OffsetEncoding::Utf16),
"utf-32" => Some(OffsetEncoding::Utf32),
encoding => {
log::error!("Server provided invalid position encoding {encoding}, defaulting to utf-16");
None
},
})
.unwrap_or_default()
} }
pub fn config(&self) -> Option<&Value> { pub fn config(&self) -> Option<&Value> {
self.config.as_ref() self.config.as_ref()
} }
pub fn workspace_folders(&self) -> &[lsp::WorkspaceFolder] { pub async fn workspace_folders(
&self.workspace_folders &self,
) -> parking_lot::MutexGuard<'_, Vec<lsp::WorkspaceFolder>> {
self.workspace_folders.lock()
} }
/// Execute a RPC request on the language server. /// Execute a RPC request on the language server.
@ -175,12 +401,22 @@ impl Client {
&self, &self,
params: R::Params, params: R::Params,
) -> impl Future<Output = Result<Value>> ) -> impl Future<Output = Result<Value>>
where
R::Params: serde::Serialize,
{
self.call_with_timeout::<R>(params, self.req_timeout)
}
fn call_with_timeout<R: lsp::request::Request>(
&self,
params: R::Params,
timeout_secs: u64,
) -> impl Future<Output = Result<Value>>
where where
R::Params: serde::Serialize, R::Params: serde::Serialize,
{ {
let server_tx = self.server_tx.clone(); let server_tx = self.server_tx.clone();
let id = self.next_request_id(); let id = self.next_request_id();
let timeout_secs = self.req_timeout;
async move { async move {
use std::time::Duration; use std::time::Duration;
@ -190,7 +426,7 @@ impl Client {
let request = jsonrpc::MethodCall { let request = jsonrpc::MethodCall {
jsonrpc: Some(jsonrpc::Version::V2), jsonrpc: Some(jsonrpc::Version::V2),
id, id: id.clone(),
method: R::METHOD.to_string(), method: R::METHOD.to_string(),
params: Self::value_into_params(params), params: Self::value_into_params(params),
}; };
@ -207,7 +443,7 @@ impl Client {
// TODO: delay other calls until initialize success // TODO: delay other calls until initialize success
timeout(Duration::from_secs(timeout_secs), rx.recv()) timeout(Duration::from_secs(timeout_secs), rx.recv())
.await .await
.map_err(|_| Error::Timeout)? // return Timeout .map_err(|_| Error::Timeout(id))? // return Timeout
.ok_or(Error::StreamClosed)? .ok_or(Error::StreamClosed)?
} }
} }
@ -275,7 +511,7 @@ impl Client {
// General messages // General messages
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
pub(crate) async fn initialize(&self) -> Result<lsp::InitializeResult> { pub(crate) async fn initialize(&self, enable_snippets: bool) -> Result<lsp::InitializeResult> {
if let Some(config) = &self.config { if let Some(config) = &self.config {
log::info!("Using custom LSP config: {}", config); log::info!("Using custom LSP config: {}", config);
} }
@ -283,7 +519,7 @@ impl Client {
#[allow(deprecated)] #[allow(deprecated)]
let params = lsp::InitializeParams { let params = lsp::InitializeParams {
process_id: Some(std::process::id()), process_id: Some(std::process::id()),
workspace_folders: Some(self.workspace_folders.clone()), workspace_folders: Some(self.workspace_folders.lock().clone()),
// root_path is obsolete, but some clients like pyright still use it so we specify both. // root_path is obsolete, but some clients like pyright still use it so we specify both.
// clients will prefer _uri if possible // clients will prefer _uri if possible
root_path: self.root_path.to_str().map(|path| path.to_owned()), root_path: self.root_path.to_str().map(|path| path.to_owned()),
@ -304,12 +540,35 @@ impl Client {
execute_command: Some(lsp::DynamicRegistrationClientCapabilities { execute_command: Some(lsp::DynamicRegistrationClientCapabilities {
dynamic_registration: Some(false), dynamic_registration: Some(false),
}), }),
inlay_hint: Some(lsp::InlayHintWorkspaceClientCapabilities {
refresh_support: Some(false),
}),
workspace_edit: Some(lsp::WorkspaceEditClientCapabilities {
document_changes: Some(true),
resource_operations: Some(vec![
lsp::ResourceOperationKind::Create,
lsp::ResourceOperationKind::Rename,
lsp::ResourceOperationKind::Delete,
]),
failure_handling: Some(lsp::FailureHandlingKind::Abort),
normalizes_line_endings: Some(false),
change_annotation_support: None,
}),
did_change_watched_files: Some(lsp::DidChangeWatchedFilesClientCapabilities {
dynamic_registration: Some(true),
relative_pattern_support: Some(false),
}),
file_operations: Some(lsp::WorkspaceFileOperationsClientCapabilities {
will_rename: Some(true),
did_rename: Some(true),
..Default::default()
}),
..Default::default() ..Default::default()
}), }),
text_document: Some(lsp::TextDocumentClientCapabilities { text_document: Some(lsp::TextDocumentClientCapabilities {
completion: Some(lsp::CompletionClientCapabilities { completion: Some(lsp::CompletionClientCapabilities {
completion_item: Some(lsp::CompletionItemCapability { completion_item: Some(lsp::CompletionItemCapability {
snippet_support: Some(false), snippet_support: Some(enable_snippets),
resolve_support: Some(lsp::CompletionItemCapabilityResolveSupport { resolve_support: Some(lsp::CompletionItemCapabilityResolveSupport {
properties: vec![ properties: vec![
String::from("documentation"), String::from("documentation"),
@ -318,6 +577,10 @@ impl Client {
], ],
}), }),
insert_replace_support: Some(true), insert_replace_support: Some(true),
deprecated_support: Some(true),
tag_support: Some(lsp::TagSupport {
value_set: vec![lsp::CompletionItemTag::DEPRECATED],
}),
..Default::default() ..Default::default()
}), }),
completion_item_kind: Some(lsp::CompletionItemKindCapability { completion_item_kind: Some(lsp::CompletionItemKindCapability {
@ -344,7 +607,7 @@ impl Client {
}), }),
rename: Some(lsp::RenameClientCapabilities { rename: Some(lsp::RenameClientCapabilities {
dynamic_registration: Some(false), dynamic_registration: Some(false),
prepare_support: Some(false), prepare_support: Some(true),
prepare_support_default_behavior: None, prepare_support_default_behavior: None,
honors_change_annotations: Some(false), honors_change_annotations: Some(false),
}), }),
@ -366,17 +629,36 @@ impl Client {
.collect(), .collect(),
}, },
}), }),
is_preferred_support: Some(true),
disabled_support: Some(true),
data_support: Some(true),
resolve_support: Some(CodeActionCapabilityResolveSupport {
properties: vec!["edit".to_owned(), "command".to_owned()],
}),
..Default::default() ..Default::default()
}), }),
publish_diagnostics: Some(lsp::PublishDiagnosticsClientCapabilities { publish_diagnostics: Some(lsp::PublishDiagnosticsClientCapabilities {
version_support: Some(true),
..Default::default() ..Default::default()
}), }),
inlay_hint: Some(lsp::InlayHintClientCapabilities {
dynamic_registration: Some(false),
resolve_support: None,
}),
..Default::default() ..Default::default()
}), }),
window: Some(lsp::WindowClientCapabilities { window: Some(lsp::WindowClientCapabilities {
work_done_progress: Some(true), work_done_progress: Some(true),
..Default::default() ..Default::default()
}), }),
general: Some(lsp::GeneralClientCapabilities {
position_encodings: Some(vec![
PositionEncodingKind::UTF8,
PositionEncodingKind::UTF32,
PositionEncodingKind::UTF16,
]),
..Default::default()
}),
..Default::default() ..Default::default()
}, },
trace: None, trace: None,
@ -423,6 +705,75 @@ impl Client {
) )
} }
pub fn did_change_workspace(
&self,
added: Vec<WorkspaceFolder>,
removed: Vec<WorkspaceFolder>,
) -> impl Future<Output = Result<()>> {
self.notify::<DidChangeWorkspaceFolders>(DidChangeWorkspaceFoldersParams {
event: WorkspaceFoldersChangeEvent { added, removed },
})
}
pub fn prepare_file_rename(
&self,
old_uri: &lsp::Url,
new_uri: &lsp::Url,
) -> Option<impl Future<Output = Result<lsp::WorkspaceEdit>>> {
let capabilities = self.capabilities.get().unwrap();
// Return early if the server does not support willRename feature
match &capabilities.workspace {
Some(workspace) => match &workspace.file_operations {
Some(op) => {
op.will_rename.as_ref()?;
}
_ => return None,
},
_ => return None,
}
let files = vec![lsp::FileRename {
old_uri: old_uri.to_string(),
new_uri: new_uri.to_string(),
}];
let request = self.call_with_timeout::<lsp::request::WillRenameFiles>(
lsp::RenameFilesParams { files },
5,
);
Some(async move {
let json = request.await?;
let response: Option<lsp::WorkspaceEdit> = serde_json::from_value(json)?;
Ok(response.unwrap_or_default())
})
}
pub fn did_file_rename(
&self,
old_uri: &lsp::Url,
new_uri: &lsp::Url,
) -> Option<impl Future<Output = std::result::Result<(), Error>>> {
let capabilities = self.capabilities.get().unwrap();
// Return early if the server does not support DidRename feature
match &capabilities.workspace {
Some(workspace) => match &workspace.file_operations {
Some(op) => {
op.did_rename.as_ref()?;
}
_ => return None,
},
_ => return None,
}
let files = vec![lsp::FileRename {
old_uri: old_uri.to_string(),
new_uri: new_uri.to_string(),
}];
Some(self.notify::<lsp::notification::DidRenameFiles>(lsp::RenameFilesParams { files }))
}
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
// Text document // Text document
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
@ -466,7 +817,11 @@ impl Client {
// Calculation is therefore a bunch trickier. // Calculation is therefore a bunch trickier.
use helix_core::RopeSlice; use helix_core::RopeSlice;
fn traverse(pos: lsp::Position, text: RopeSlice) -> lsp::Position { fn traverse(
pos: lsp::Position,
text: RopeSlice,
offset_encoding: OffsetEncoding,
) -> lsp::Position {
let lsp::Position { let lsp::Position {
mut line, mut line,
mut character, mut character,
@ -483,7 +838,11 @@ impl Client {
line += 1; line += 1;
character = 0; character = 0;
} else { } else {
character += ch.len_utf16() as u32; character += match offset_encoding {
OffsetEncoding::Utf8 => ch.len_utf8() as u32,
OffsetEncoding::Utf16 => ch.len_utf16() as u32,
OffsetEncoding::Utf32 => 1,
};
} }
} }
lsp::Position { line, character } lsp::Position { line, character }
@ -504,7 +863,7 @@ impl Client {
} }
Delete(_) => { Delete(_) => {
let start = pos_to_lsp_pos(new_text, new_pos, offset_encoding); let start = pos_to_lsp_pos(new_text, new_pos, offset_encoding);
let end = traverse(start, old_text.slice(old_pos..old_end)); let end = traverse(start, old_text.slice(old_pos..old_end), offset_encoding);
// deletion // deletion
changes.push(lsp::TextDocumentContentChangeEvent { changes.push(lsp::TextDocumentContentChangeEvent {
@ -521,7 +880,8 @@ impl Client {
// a subsequent delete means a replace, consume it // a subsequent delete means a replace, consume it
let end = if let Some(Delete(len)) = iter.peek() { let end = if let Some(Delete(len)) = iter.peek() {
old_end = old_pos + len; old_end = old_pos + len;
let end = traverse(start, old_text.slice(old_pos..old_end)); let end =
traverse(start, old_text.slice(old_pos..old_end), offset_encoding);
iter.next(); iter.next();
@ -577,7 +937,7 @@ impl Client {
}] }]
} }
lsp::TextDocumentSyncKind::INCREMENTAL => { lsp::TextDocumentSyncKind::INCREMENTAL => {
Self::changeset_to_changes(old_text, new_text, changes, self.offset_encoding) Self::changeset_to_changes(old_text, new_text, changes, self.offset_encoding())
} }
lsp::TextDocumentSyncKind::NONE => return None, lsp::TextDocumentSyncKind::NONE => return None,
kind => unimplemented!("{:?}", kind), kind => unimplemented!("{:?}", kind),
@ -628,7 +988,7 @@ impl Client {
Some(self.notify::<lsp::notification::DidSaveTextDocument>( Some(self.notify::<lsp::notification::DidSaveTextDocument>(
lsp::DidSaveTextDocumentParams { lsp::DidSaveTextDocumentParams {
text_document, text_document,
text: include_text.then(|| text.into()), text: include_text.then_some(text.into()),
}, },
)) ))
} }
@ -679,6 +1039,24 @@ impl Client {
Some(self.call::<lsp::request::ResolveCompletionItem>(completion_item)) Some(self.call::<lsp::request::ResolveCompletionItem>(completion_item))
} }
pub fn resolve_code_action(
&self,
code_action: lsp::CodeAction,
) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap();
// Return early if the server does not support resolving code actions.
match capabilities.code_action_provider {
Some(lsp::CodeActionProviderCapability::Options(lsp::CodeActionOptions {
resolve_provider: Some(true),
..
})) => (),
_ => return None,
}
Some(self.call::<lsp::request::CodeActionResolveRequest>(code_action))
}
pub fn text_document_signature_help( pub fn text_document_signature_help(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
@ -703,6 +1081,31 @@ impl Client {
Some(self.call::<lsp::request::SignatureHelpRequest>(params)) Some(self.call::<lsp::request::SignatureHelpRequest>(params))
} }
pub fn text_document_range_inlay_hints(
&self,
text_document: lsp::TextDocumentIdentifier,
range: lsp::Range,
work_done_token: Option<lsp::ProgressToken>,
) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap();
match capabilities.inlay_hint_provider {
Some(
lsp::OneOf::Left(true)
| lsp::OneOf::Right(lsp::InlayHintServerCapabilities::Options(_)),
) => (),
_ => return None,
}
let params = lsp::InlayHintParams {
text_document,
range,
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
};
Some(self.call::<lsp::request::InlayHintRequest>(params))
}
pub fn text_document_hover( pub fn text_document_hover(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
@ -886,6 +1289,31 @@ impl Client {
)) ))
} }
pub fn goto_declaration(
&self,
text_document: lsp::TextDocumentIdentifier,
position: lsp::Position,
work_done_token: Option<lsp::ProgressToken>,
) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap();
// Return early if the server does not support goto-declaration.
match capabilities.declaration_provider {
Some(
lsp::DeclarationCapability::Simple(true)
| lsp::DeclarationCapability::RegistrationOptions(_)
| lsp::DeclarationCapability::Options(_),
) => (),
_ => return None,
}
Some(self.goto_request::<lsp::request::GotoDeclaration>(
text_document,
position,
work_done_token,
))
}
pub fn goto_type_definition( pub fn goto_type_definition(
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
@ -938,6 +1366,7 @@ impl Client {
&self, &self,
text_document: lsp::TextDocumentIdentifier, text_document: lsp::TextDocumentIdentifier,
position: lsp::Position, position: lsp::Position,
include_declaration: bool,
work_done_token: Option<lsp::ProgressToken>, work_done_token: Option<lsp::ProgressToken>,
) -> Option<impl Future<Output = Result<Value>>> { ) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap(); let capabilities = self.capabilities.get().unwrap();
@ -954,7 +1383,7 @@ impl Client {
position, position,
}, },
context: lsp::ReferenceContext { context: lsp::ReferenceContext {
include_declaration: true, include_declaration,
}, },
work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token }, work_done_progress_params: lsp::WorkDoneProgressParams { work_done_token },
partial_result_params: lsp::PartialResultParams { partial_result_params: lsp::PartialResultParams {
@ -986,6 +1415,29 @@ impl Client {
Some(self.call::<lsp::request::DocumentSymbolRequest>(params)) Some(self.call::<lsp::request::DocumentSymbolRequest>(params))
} }
pub fn prepare_rename(
&self,
text_document: lsp::TextDocumentIdentifier,
position: lsp::Position,
) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap();
match capabilities.rename_provider {
Some(lsp::OneOf::Right(lsp::RenameOptions {
prepare_provider: Some(true),
..
})) => (),
_ => return None,
}
let params = lsp::TextDocumentPositionParams {
text_document,
position,
};
Some(self.call::<lsp::request::PrepareRenameRequest>(params))
}
// empty string to get all symbols // empty string to get all symbols
pub fn workspace_symbols(&self, query: String) -> Option<impl Future<Output = Result<Value>>> { pub fn workspace_symbols(&self, query: String) -> Option<impl Future<Output = Result<Value>>> {
let capabilities = self.capabilities.get().unwrap(); let capabilities = self.capabilities.get().unwrap();
@ -1002,7 +1454,7 @@ impl Client {
partial_result_params: lsp::PartialResultParams::default(), partial_result_params: lsp::PartialResultParams::default(),
}; };
Some(self.call::<lsp::request::WorkspaceSymbol>(params)) Some(self.call::<lsp::request::WorkspaceSymbolRequest>(params))
} }
pub fn code_actions( pub fn code_actions(
@ -1039,14 +1491,9 @@ impl Client {
position: lsp::Position, position: lsp::Position,
new_name: String, new_name: String,
) -> Option<impl Future<Output = Result<lsp::WorkspaceEdit>>> { ) -> Option<impl Future<Output = Result<lsp::WorkspaceEdit>>> {
let capabilities = self.capabilities.get().unwrap(); if !self.supports_feature(LanguageServerFeature::RenameSymbol) {
return None;
// Return early if the language server does not support renaming. }
match capabilities.rename_provider {
Some(lsp::OneOf::Left(true)) | Some(lsp::OneOf::Right(_)) => (),
// None | Some(false)
_ => return None,
};
let params = lsp::RenameParams { let params = lsp::RenameParams {
text_document_position: lsp::TextDocumentPositionParams { text_document_position: lsp::TextDocumentPositionParams {
@ -1084,4 +1531,13 @@ impl Client {
Some(self.call::<lsp::request::ExecuteCommand>(params)) Some(self.call::<lsp::request::ExecuteCommand>(params))
} }
pub fn did_change_watched_files(
&self,
changes: Vec<lsp::FileEvent>,
) -> impl Future<Output = std::result::Result<(), Error>> {
self.notify::<lsp::notification::DidChangeWatchedFiles>(lsp::DidChangeWatchedFilesParams {
changes,
})
}
} }

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

Loading…
Cancel
Save