Compare commits

..

No commits in common. "main" and "v0.9.5" have entirely different histories.
main ... v0.9.5

41 changed files with 980 additions and 1228 deletions

1
.envrc
View File

@ -1 +0,0 @@
use nix

View File

@ -8,9 +8,6 @@ env:
CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }} CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }}
CARGO_INCREMENTAL: 0 CARGO_INCREMENTAL: 0
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions: permissions:
contents: read contents: read
jobs: jobs:
@ -19,9 +16,9 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest] os: [ubuntu-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions-rs/toolchain@v1 - uses: actions-rs/toolchain@v1
@ -36,17 +33,17 @@ jobs:
components: rustfmt components: rustfmt
profile: minimal profile: minimal
toolchain: nightly toolchain: nightly
- uses: cachix/install-nix-action@v31 - uses: cachix/install-nix-action@V27
if: ${{ matrix.os != 'windows-latest' }} if: ${{ matrix.os != 'windows-latest' }}
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
- uses: cachix/cachix-action@v16 - uses: cachix/cachix-action@v15
if: ${{ matrix.os != 'windows-latest' && env.CACHIX_AUTH_TOKEN != '' }} if: ${{ matrix.os != 'windows-latest' && env.CACHIX_AUTH_TOKEN != '' }}
with: with:
authToken: ${{ env.CACHIX_AUTH_TOKEN }} authToken: ${{ env.CACHIX_AUTH_TOKEN }}
name: zoxide name: zoxide
- name: Setup cache - name: Setup cache
uses: Swatinem/rust-cache@v2.8.1 uses: Swatinem/rust-cache@v2.7.3
with: with:
key: ${{ matrix.os }} key: ${{ matrix.os }}
- name: Install just - name: Install just

View File

@ -42,7 +42,7 @@ jobs:
target: aarch64-pc-windows-msvc target: aarch64-pc-windows-msvc
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v5 uses: actions/checkout@v4
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Get version - name: Get version
@ -59,7 +59,7 @@ jobs:
override: true override: true
target: ${{ matrix.target }} target: ${{ matrix.target }}
- name: Setup cache - name: Setup cache
uses: Swatinem/rust-cache@v2.8.1 uses: Swatinem/rust-cache@v2.7.3
with: with:
key: ${{ matrix.target }} key: ${{ matrix.target }}
- name: Install cross - name: Install cross
@ -67,7 +67,7 @@ jobs:
uses: actions-rs/cargo@v1 uses: actions-rs/cargo@v1
with: with:
command: install command: install
args: --color=always --git=https://github.com/cross-rs/cross.git --locked --rev=e281947ca900da425e4ecea7483cfde646c8a1ea --verbose cross args: --color=always --git=https://github.com/cross-rs/cross.git --locked --rev=02bf930e0cb0c6f1beffece0788f3932ecb2c7eb --verbose cross
- name: Build binary - name: Build binary
uses: actions-rs/cargo@v1 uses: actions-rs/cargo@v1
with: with:

View File

@ -7,60 +7,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.9.8] - 2025-05-27
### Added
- Support for Tcsh.
- Added `--score` flag to `zoxide add`.
- POSIX: add doctor to diagnose common issues.
- Nushell: add CLI completions.
### Changed
- Bash: zoxide will now automatically `cd` when selecting Space-Tab completions.
### Fixed
- Bash: doctor now handles `PROMPT_COMMAND` being an array.
- Bash: doctor now handles Visual Studio Code's shell integration.
- Bash: completions now work with `ble.sh`.
- Nushell: stop ignoring symlinks when `cd`-ing into a directory.
- Fzf: updated minimum supported version to v0.51.0.
- PowerShell: avoid setting `$error` when defining `__zoxide_hooked`.
- PowerShell: handle special characters in file paths when `cd`-ing into them.
- Database corruption issue when the filesystem is 100% full.
## [0.9.7] - 2025-02-10
### Added
- Nushell: support for 0.102.0.
- Bash / Zsh: add doctor to diagnose common issues.
### Fixed
- ksh: alias to regular POSIX implementation for better compatibility.
## [0.9.6] - 2024-09-19
### Fixed
- Fish: `builtin abbr` doesn't work on older versions.
- Zsh: make `__zoxide_z_complete` available with `--no-cmd`.
## [0.9.5] - 2024-09-13 ## [0.9.5] - 2024-09-13
### Added ### Added
- Zsh: improved `cd` completions. - zsh: improved `cd` completions.
- Lazily delete excluded directories from the database. - Lazily delete excluded directories from the database.
- Fish: detect infinite loop when using `alias cd=z`. - fish: detect infinite loop when using `alias cd=z`.
- Installer: added flags for `--bin-dir`, `--man-dir`, `--arch`, and `--sudo`. - Installer: added flags for `--bin-dir`, `--man-dir`, `--arch`, and `--sudo`.
- Nushell: support for v0.94.0+. - Nushell: support for v0.94.0+.
- Bash/Fish/Zsh: support for `z -- dir` style queries. - bash/fish/zsh: support for `z -- dir` style queries.
- Fish: improved Space-Tab completions. - fish: improved Space-Tab completions.
- Ksh: added support for the Korn shell. - ksh: added support for the Korn shell.
### Changed ### Changed
@ -70,12 +28,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Zsh: Space-Tab completion repeating output multiple times when matching single - zsh: Space-Tab completion repeating output multiple times when matching single
directory directory
- Fish / Nushell / PowerShell: handle queries that look like args (e.g. `z -x`). - fish / Nushell / PowerShell: handle queries that look like args (e.g. `z -x`).
- Elvish: `z -` now works as expected. - elvish: `z -` now works as expected.
- Fish: generated shell code avoids using aliased builtins. - fish: generated shell code avoids using aliased builtins.
- Fish: `cd` command is now copied directly from - fish: `cd` command is now copied directly from
`$__fish_data_dir/functions/cd.fish`. This should minimize the chances of an `$__fish_data_dir/functions/cd.fish`. This should minimize the chances of an
infinite loop when aliasing `cd=z`. infinite loop when aliasing `cd=z`.
- Symlinks not getting added to the database when `$_ZO_RESOLVE_SYMLINKS=0`. - Symlinks not getting added to the database when `$_ZO_RESOLVE_SYMLINKS=0`.
@ -85,7 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed ### Changed
- Zsh: improved Space-Tab completions. - zsh: improved Space-Tab completions.
## [0.9.3] - 2024-02-13 ## [0.9.3] - 2024-02-13
@ -327,9 +285,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- `cd -` on Fish shells. - `cd -` on fish shells.
- `__zoxide_hook` no longer changes value of `$?` within `$PROMPT_COMMAND` on - `__zoxide_hook` no longer changes value of `$?` within `$PROMPT_COMMAND` on
Bash. bash.
### Removed ### Removed
@ -368,7 +326,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `$_ZO_EXCLUDE_DIRS` now supports globs. - `$_ZO_EXCLUDE_DIRS` now supports globs.
- `zoxide init` now defines `__zoxide_z*` functions that can be aliased as - `zoxide init` now defines `__zoxide_z*` functions that can be aliased as
needed. needed.
- Support for the [Xonsh](https://xon.sh/) shell. - Support for the [xonsh](https://xon.sh/) shell.
- `zoxide import` can now import from Autojump. - `zoxide import` can now import from Autojump.
### Changed ### Changed
@ -377,7 +335,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Clobber conflicting alias definitions in Bash/Fish/Zsh/POSIX shells. - Clobber conflicting alias definitions in bash/fish/zsh/POSIX shells.
### Removed ### Removed
@ -388,7 +346,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Bug in Fish init script. - Bug in Fish init script
## [0.4.2] - 2020-07-03 ## [0.4.2] - 2020-07-03
@ -413,7 +371,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- Support for PowerShell. - Support for powershell.
### Removed ### Removed
@ -441,7 +399,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Fish no longer `cd`s to the user's home when no match is found. - fish no longer `cd`s to the user's home when no match is found.
## [0.3.1] - 2020-04-03 ## [0.3.1] - 2020-04-03
@ -481,7 +439,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
- Incorrect exit codes in `z` command on Fish. - Incorrect exit codes in `z` command on fish.
### Removed ### Removed
@ -494,7 +452,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `$_ZO_ECHO` to echo match before `cd`ing. - `$_ZO_ECHO` to echo match before `cd`ing.
- Minimal `ranger` plugin. - Minimal `ranger` plugin.
- PWD hook to only update the database when the current directory is changed. - PWD hook to only update the database when the current directory is changed.
- Support for Bash. - Support for bash.
- `migrate` subcommand to allow users to migrate from `z`. - `migrate` subcommand to allow users to migrate from `z`.
### Fixed ### Fixed
@ -508,11 +466,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `init` subcommand to remove dependency on shell plugin managers. - `init` subcommand to remove dependency on shell plugin managers.
- Support for `z -` command to go to previous directory. - Support for `z -` command to go to previous directory.
- `Cargo.lock` for more reproducible builds. - `Cargo.lock` for more reproducible builds.
- Support for the Fish shell. - Support for the fish shell.
### Fixed ### Fixed
- `_zoxide_precmd` overriding other precmd hooks on Zsh. - `_zoxide_precmd` overriding other precmd hooks on zsh.
## [0.1.1] - 2020-03-08 ## [0.1.1] - 2020-03-08
@ -534,11 +492,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- GitHub Actions pipeline to build and upload releases. - GitHub Actions pipeline to build and upload releases.
- Add support for Zsh. - Support for zsh.
[0.9.8]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.7...v0.9.8
[0.9.7]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.6...v0.9.7
[0.9.6]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.5...v0.9.6
[0.9.5]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.4...v0.9.5 [0.9.5]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.4...v0.9.5
[0.9.4]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.3...v0.9.4 [0.9.4]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.3...v0.9.4
[0.9.3]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.2...v0.9.3 [0.9.3]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.2...v0.9.3

784
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -2,56 +2,52 @@
authors = ["Ajeet D'Souza <98ajeet@gmail.com>"] authors = ["Ajeet D'Souza <98ajeet@gmail.com>"]
categories = ["command-line-utilities", "filesystem"] categories = ["command-line-utilities", "filesystem"]
description = "A smarter cd command for your terminal" description = "A smarter cd command for your terminal"
edition = "2024" edition = "2021"
homepage = "https://github.com/ajeetdsouza/zoxide" homepage = "https://github.com/ajeetdsouza/zoxide"
keywords = ["cli", "filesystem", "shell", "tool", "utility"] keywords = ["cli", "filesystem", "shell", "tool", "utility"]
license = "MIT" license = "MIT"
name = "zoxide" name = "zoxide"
readme = "README.md" readme = "README.md"
repository = "https://github.com/ajeetdsouza/zoxide" repository = "https://github.com/ajeetdsouza/zoxide"
rust-version = "1.85.0" rust-version = "1.74.1"
version = "0.9.8" version = "0.9.5"
[badges] [badges]
maintenance = { status = "actively-developed" } maintenance = { status = "actively-developed" }
[dependencies] [dependencies]
anyhow = "1.0.32" anyhow = "1.0.32"
askama = { version = "0.14.0", default-features = false, features = [
"derive",
"std",
] }
bincode = "1.3.1" bincode = "1.3.1"
clap = { version = "4.3.0", features = ["derive"] } clap = { version = "4.3.0", features = ["derive"] }
color-print = "0.3.4" color-print = "0.3.4"
dirs = "6.0.0" dirs = "5.0.0"
dunce = "1.0.1" dunce = "1.0.1"
fastrand = "2.0.0" fastrand = "2.0.0"
glob = "0.3.0" glob = "0.3.0"
ouroboros = "0.18.3" ouroboros = "0.18.3"
rinja = { version = "0.3.2", default-features = false }
serde = { version = "1.0.116", features = ["derive"] } serde = { version = "1.0.116", features = ["derive"] }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
nix = { version = "0.30.1", default-features = false, features = [ nix = { version = "0.27.1", default-features = false, features = [
"fs", "fs",
"user", "user",
] } ] }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
which = "7.0.3" which = "6.0.0"
[build-dependencies] [build-dependencies]
clap = { version = "4.3.0", features = ["derive"] } clap = { version = "4.3.0", features = ["derive"] }
clap_complete = "4.5.50" clap_complete = "4.3.0"
clap_complete_fig = "4.5.2" clap_complete_fig = "4.3.0"
clap_complete_nushell = "4.5.5"
color-print = "0.3.4" color-print = "0.3.4"
[dev-dependencies] [dev-dependencies]
assert_cmd = "2.0.0" assert_cmd = "2.0.0"
rstest = { version = "0.26.0", default-features = false } rstest = { version = "0.18.0", default-features = false }
rstest_reuse = "0.7.0" rstest_reuse = "0.6.0"
tempfile = "3.15.0" tempfile = "3.1.0"
[features] [features]
default = [] default = []

137
README.md
View File

@ -11,15 +11,18 @@
<sup>Special thanks to:</sup> <sup>Special thanks to:</sup>
<!-- markdownlint-disable-next-line MD013 --> <a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=zoxide_20231001">
<div><a href="https://go.warp.dev/zoxide"><img alt="Sponsored by Warp" width="230" src="https://raw.githubusercontent.com/warpdotdev/brand-assets/refs/heads/main/Github/Sponsor/Warp-Github-LG-03.png" /></a></div> <div>
<div><sup><b>Warp, built for coding with multiple AI agents.</b></sup></div> <img src="contrib/warp.png" width="230" alt="Warp" />
<div><sup>Available for macOS, Linux, and Windows.</sup></div> </div>
<div><sup> <b>
Visit Warp is a modern, Rust-based terminal with AI built in so you and your team
<a href="https://go.warp.dev/zoxide"><u>warp.dev</u></a> can build great software, faster.
to learn more. </b>
</sup></div> <div>
<sup>Visit <u>warp.dev</u> to learn more.</sup>
</div>
</a>
<hr /> <hr />
@ -83,35 +86,31 @@ zoxide can be installed in 4 easy steps:
> >
> Or, you can use a package manager: > Or, you can use a package manager:
> >
> | Distribution | Repository | Instructions | > | Distribution | Repository | Instructions |
> | ------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------- | > | ------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
> | **_Any_** | **[crates.io]** | `cargo install zoxide --locked` | > | **_Any_** | **[crates.io]** | `cargo install zoxide --locked` |
> | _Any_ | [asdf] | `asdf plugin add zoxide https://github.com/nyrst/asdf-zoxide.git` <br /> `asdf install zoxide latest` | > | _Any_ | [asdf] | `asdf plugin add zoxide https://github.com/nyrst/asdf-zoxide.git` <br /> `asdf install zoxide latest` |
> | _Any_ | [conda-forge] | `conda install -c conda-forge zoxide` | > | _Any_ | [conda-forge] | `conda install -c conda-forge zoxide` |
> | _Any_ | [guix] | `guix install zoxide` | > | _Any_ | [guix] | `guix install zoxide` |
> | _Any_ | [Linuxbrew] | `brew install zoxide` | > | _Any_ | [Linuxbrew] | `brew install zoxide` |
> | _Any_ | [nixpkgs] | `nix-env -iA nixpkgs.zoxide` | > | _Any_ | [nixpkgs] | `nix-env -iA nixpkgs.zoxide` |
> | AlmaLinux | | `dnf install zoxide` | > | Alpine Linux 3.13+ | [Alpine Linux Packages] | `apk add zoxide` |
> | Alpine Linux 3.13+ | [Alpine Linux Packages] | `apk add zoxide` | > | Arch Linux | [Arch Linux Extra] | `pacman -S zoxide` |
> | Arch Linux | [Arch Linux Extra] | `pacman -S zoxide` | > | CentOS 7+ | [Copr] | `dnf copr enable atim/zoxide` <br /> `dnf install zoxide` |
> | CentOS Stream | | `dnf install zoxide` | > | ~Debian 11+~[^1] | ~[Debian Packages]~ | ~`apt install zoxide`~ |
> | ~Debian 11+~[^1] | ~[Debian Packages]~ | ~`apt install zoxide`~ | > | Devuan 4.0+ | [Devuan Packages] | `apt install zoxide` |
> | Devuan 4.0+ | [Devuan Packages] | `apt install zoxide` | > | Exherbo Linux | [Exherbo packages] | `cave resolve -x repository/rust` <br /> `cave resolve -x zoxide` |
> | Exherbo Linux | [Exherbo packages] | `cave resolve -x repository/rust` <br /> `cave resolve -x zoxide` | > | Fedora 32+ | [Fedora Packages] | `dnf install zoxide` |
> | Fedora 32+ | [Fedora Packages] | `dnf install zoxide` | > | Gentoo | [Gentoo Packages] | `emerge app-shells/zoxide` |
> | Gentoo | [Gentoo Packages] | `emerge app-shells/zoxide` | > | Manjaro | | `pacman -S zoxide` |
> | Linux Mint | [apt.cli.rs] (unofficial) | [Setup the repository][apt.cli.rs-setup], then `apt install zoxide` | > | openSUSE Tumbleweed | [openSUSE Factory] | `zypper install zoxide` |
> | Manjaro | | `pacman -S zoxide` | > | ~Parrot OS~[^1] | | ~`apt install zoxide`~ |
> | openSUSE Tumbleweed | [openSUSE Factory] | `zypper install zoxide` | > | ~Raspbian 11+~[^1] | ~[Raspbian Packages]~ | ~`apt install zoxide`~ |
> | ~Parrot OS~[^1] | | ~`apt install zoxide`~ | > | Rhino Linux | [Pacstall Packages] | `pacstall -I zoxide-deb` |
> | ~Raspbian 11+~[^1] | ~[Raspbian Packages]~ | ~`apt install zoxide`~ | > | Slackware 15.0+ | [SlackBuilds] | [Instructions][slackbuilds-howto] |
> | RHEL 8+ | | `dnf install zoxide` | > | Solus | [Solus Packages] | `eopkg install zoxide` |
> | Rhino Linux | [Pacstall Packages] | `pacstall -I zoxide-deb` | > | ~Ubuntu 21.04+~[^1] | ~[Ubuntu Packages]~ | ~`apt install zoxide`~ |
> | Rocky Linux | | `dnf install zoxide` | > | Void Linux | [Void Linux Packages] | `xbps-install -S zoxide` |
> | Slackware 15.0+ | [SlackBuilds] | [Instructions][slackbuilds-howto] |
> | Solus | [Solus Packages] | `eopkg install zoxide` |
> | Ubuntu | [apt.cli.rs] (unofficial) | [Setup the repository][apt.cli.rs-setup], then `apt install zoxide` |
> | Void Linux | [Void Linux Packages] | `xbps-install -S zoxide` |
</details> </details>
@ -244,6 +243,17 @@ zoxide can be installed in 4 easy steps:
</details> </details>
<details>
<summary>Ksh</summary>
> Add this to the <ins>**end**</ins> of your config file (usually `~/.kshrc`):
>
> ```sh
> eval "$(zoxide init ksh)"
> ```
</details>
<details> <details>
<summary>Nushell</summary> <summary>Nushell</summary>
@ -278,18 +288,6 @@ zoxide can be installed in 4 easy steps:
</details> </details>
<details>
<summary>Tcsh</summary>
> Add this to the <ins>**end**</ins> of your config file (usually `~/.tcshrc`):
>
> ```sh
> zoxide init tcsh > ~/.zoxide.tcsh
> source ~/.zoxide.tcsh
> ```
</details>
<details> <details>
<summary>Xonsh</summary> <summary>Xonsh</summary>
@ -333,7 +331,7 @@ zoxide can be installed in 4 easy steps:
interactive selection. It can be installed from [here][fzf-installation]. interactive selection. It can be installed from [here][fzf-installation].
> **Note** > **Note**
> The minimum supported fzf version is v0.51.0. > zoxide only supports fzf v0.33.0 and above.
4. **Import your data** <sup>(optional)</sup> 4. **Import your data** <sup>(optional)</sup>
@ -406,13 +404,11 @@ When calling `zoxide init`, the following flags are available:
- `--cmd cd` would replace the `cd` command. - `--cmd cd` would replace the `cd` command.
- `--hook <HOOK>` - `--hook <HOOK>`
- Changes how often zoxide increments a directory's score: - Changes how often zoxide increments a directory's score:
| Hook | Description |
| Hook | Description | | -------- | --------------------------------- |
| --------------- | --------------------------------- | | `none` | Never |
| `none` | Never | | `prompt` | At every shell prompt |
| `prompt` | At every shell prompt | | `pwd` | Whenever the directory is changed |
| `pwd` (default) | Whenever the directory is changed |
- `--no-cmd` - `--no-cmd`
- Prevents zoxide from defining the `z` and `zi` commands. - Prevents zoxide from defining the `z` and `zi` commands.
- These functions will still be available in your shell as `__zoxide_z` and - These functions will still be available in your shell as `__zoxide_z` and
@ -426,13 +422,11 @@ Environment variables[^2] can be used for configuration. They must be set before
- `_ZO_DATA_DIR` - `_ZO_DATA_DIR`
- Specifies the directory in which the database is stored. - Specifies the directory in which the database is stored.
- The default value varies across OSes: - The default value varies across OSes:
| OS | Path | Example | | OS | Path | Example |
| ----------- | ---------------------------------------- | ------------------------------------------ | | ----------- | ---------------------------------------- | ------------------------------------------ |
| Linux / BSD | `$XDG_DATA_HOME` or `$HOME/.local/share` | `/home/alice/.local/share` | | Linux / BSD | `$XDG_DATA_HOME` or `$HOME/.local/share` | `/home/alice/.local/share` |
| macOS | `$HOME/Library/Application Support` | `/Users/Alice/Library/Application Support` | | macOS | `$HOME/Library/Application Support` | `/Users/Alice/Library/Application Support` |
| Windows | `%LOCALAPPDATA%` | `C:\Users\Alice\AppData\Local` | | Windows | `%LOCALAPPDATA%` | `C:\Users\Alice\AppData\Local` |
- `_ZO_ECHO` - `_ZO_ECHO`
- When set to 1, `z` will print the matched directory before navigating to - When set to 1, `z` will print the matched directory before navigating to
it. it.
@ -440,12 +434,10 @@ Environment variables[^2] can be used for configuration. They must be set before
- Excludes the specified directories from the database. - Excludes the specified directories from the database.
- This is provided as a list of [globs][glob], separated by OS-specific - This is provided as a list of [globs][glob], separated by OS-specific
characters: characters:
| OS | Separator | Example | | OS | Separator | Example |
| ------------------- | --------- | ----------------------- | | ------------------- | --------- | ----------------------- |
| Linux / macOS / BSD | `:` | `$HOME:$HOME/private/*` | | Linux / macOS / BSD | `:` | `$HOME:$HOME/private/*` |
| Windows | `;` | `$HOME;$HOME/private/*` | | Windows | `;` | `$HOME;$HOME/private/*` |
- By default, this is set to `"$HOME"`. - By default, this is set to `"$HOME"`.
- `_ZO_FZF_OPTS` - `_ZO_FZF_OPTS`
- Custom options to pass to [fzf] during interactive selection. See - Custom options to pass to [fzf] during interactive selection. See
@ -471,22 +463,18 @@ Environment variables[^2] can be used for configuration. They must be set before
| [lf] | File manager | See the [wiki][lf-wiki] | | [lf] | File manager | See the [wiki][lf-wiki] |
| [nnn] | File manager | [nnn-autojump] | | [nnn] | File manager | [nnn-autojump] |
| [ranger] | File manager | [ranger-zoxide] | | [ranger] | File manager | [ranger-zoxide] |
| [raycast] | macOS launcher | [raycast-zoxide] |
| [rfm] | File manager | Natively supported |
| [sesh] | `tmux` session manager | Natively supported |
| [telescope.nvim] | Fuzzy finder for Neovim | [telescope-zoxide] | | [telescope.nvim] | Fuzzy finder for Neovim | [telescope-zoxide] |
| [t] | `tmux` session manager | Natively supported |
| [tmux-session-wizard] | `tmux` session manager | Natively supported | | [tmux-session-wizard] | `tmux` session manager | Natively supported |
| [tmux-sessionx] | `tmux` session manager | Natively supported |
| [vim] / [neovim] | Text editor | [zoxide.vim] | | [vim] / [neovim] | Text editor | [zoxide.vim] |
| [xplr] | File manager | [zoxide.xplr] | | [xplr] | File manager | [zoxide.xplr] |
| [xxh] | Transports shell configuration over SSH | [xxh-plugin-prerun-zoxide] | | [xxh] | Transports shell configuration over SSH | [xxh-plugin-prerun-zoxide] |
| [yazi] | File manager | Natively supported | | [yazi] | File manager | Natively supported |
| [zabb] | Finds the shortest possible query for a path | Natively supported | | [zabb] | Finds the shortest possible query for a path | Natively supported |
| [zesh] | `zellij` session manager | Natively supported |
| [zsh-autocomplete] | Realtime completions for zsh | Natively supported | | [zsh-autocomplete] | Realtime completions for zsh | Natively supported |
[^1]: [^1]:
Debian and its derivatives update their packages very slowly. If you're Debian / Ubuntu derivatives update their packages very slowly. If you're
using one of these distributions, consider using the install script instead. using one of these distributions, consider using the install script instead.
[^2]: [^2]:
@ -499,8 +487,6 @@ Environment variables[^2] can be used for configuration. They must be set before
[algorithm-aging]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#aging [algorithm-aging]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#aging
[algorithm-matching]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#matching [algorithm-matching]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#matching
[alpine linux packages]: https://pkgs.alpinelinux.org/packages?name=zoxide [alpine linux packages]: https://pkgs.alpinelinux.org/packages?name=zoxide
[apt.cli.rs]: https://apt.cli.rs/
[apt.cli.rs-setup]: https://github.com/emmatyping/apt.cli.rs#how-to-add-the-repo
[arch linux extra]: https://archlinux.org/packages/extra/x86_64/zoxide/ [arch linux extra]: https://archlinux.org/packages/extra/x86_64/zoxide/
[asdf]: https://github.com/asdf-vm/asdf [asdf]: https://github.com/asdf-vm/asdf
[builtwithnix-badge]: https://img.shields.io/badge/builtwith-nix-7d81f7?logo=nixos&logoColor=white&style=flat-square [builtwithnix-badge]: https://img.shields.io/badge/builtwith-nix-7d81f7?logo=nixos&logoColor=white&style=flat-square
@ -509,6 +495,7 @@ Environment variables[^2] can be used for configuration. They must be set before
[clink-zoxide]: https://github.com/shunsambongi/clink-zoxide [clink-zoxide]: https://github.com/shunsambongi/clink-zoxide
[clink]: https://github.com/mridgers/clink [clink]: https://github.com/mridgers/clink
[conda-forge]: https://anaconda.org/conda-forge/zoxide [conda-forge]: https://anaconda.org/conda-forge/zoxide
[copr]: https://copr.fedorainfracloud.org/coprs/atim/zoxide/
[crates.io-badge]: https://img.shields.io/crates/v/zoxide?logo=rust&logoColor=white&style=flat-square [crates.io-badge]: https://img.shields.io/crates/v/zoxide?logo=rust&logoColor=white&style=flat-square
[crates.io]: https://crates.io/crates/zoxide [crates.io]: https://crates.io/crates/zoxide
[debian packages]: https://packages.debian.org/stable/admin/zoxide [debian packages]: https://packages.debian.org/stable/admin/zoxide
@ -534,7 +521,7 @@ Environment variables[^2] can be used for configuration. They must be set before
[linuxbrew]: https://formulae.brew.sh/formula-linux/zoxide [linuxbrew]: https://formulae.brew.sh/formula-linux/zoxide
[macports]: https://ports.macports.org/port/zoxide/summary [macports]: https://ports.macports.org/port/zoxide/summary
[neovim]: https://github.com/neovim/neovim [neovim]: https://github.com/neovim/neovim
[nixpkgs]: https://github.com/NixOS/nixpkgs/blob/master/pkgs/by-name/zo/zoxide/package.nix [nixpkgs]: https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/zoxide/default.nix
[nnn-autojump]: https://github.com/jarun/nnn/blob/master/plugins/autojump [nnn-autojump]: https://github.com/jarun/nnn/blob/master/plugins/autojump
[nnn]: https://github.com/jarun/nnn [nnn]: https://github.com/jarun/nnn
[opensuse factory]: https://build.opensuse.org/package/show/openSUSE:Factory/zoxide [opensuse factory]: https://build.opensuse.org/package/show/openSUSE:Factory/zoxide
@ -543,21 +530,18 @@ Environment variables[^2] can be used for configuration. They must be set before
[ranger-zoxide]: https://github.com/jchook/ranger-zoxide [ranger-zoxide]: https://github.com/jchook/ranger-zoxide
[ranger]: https://github.com/ranger/ranger [ranger]: https://github.com/ranger/ranger
[raspbian packages]: https://archive.raspbian.org/raspbian/pool/main/r/rust-zoxide/ [raspbian packages]: https://archive.raspbian.org/raspbian/pool/main/r/rust-zoxide/
[raycast]: https://www.raycast.com/
[raycast-zoxide]: https://www.raycast.com/mrpunkin/raycast-zoxide
[releases]: https://github.com/ajeetdsouza/zoxide/releases [releases]: https://github.com/ajeetdsouza/zoxide/releases
[rfm]: https://github.com/dsxmachina/rfm
[scoop]: https://github.com/ScoopInstaller/Main/tree/master/bucket/zoxide.json [scoop]: https://github.com/ScoopInstaller/Main/tree/master/bucket/zoxide.json
[sesh]: https://github.com/joshmedeski/sesh
[slackbuilds]: https://slackbuilds.org/repository/15.0/system/zoxide/ [slackbuilds]: https://slackbuilds.org/repository/15.0/system/zoxide/
[slackbuilds-howto]: https://slackbuilds.org/howto/ [slackbuilds-howto]: https://slackbuilds.org/howto/
[solus packages]: https://github.com/getsolus/packages/tree/main/packages/z/zoxide/ [solus packages]: https://github.com/getsolus/packages/tree/main/packages/z/zoxide/
[t]: https://github.com/joshmedeski/t-smart-tmux-session-manager
[telescope-zoxide]: https://github.com/jvgrootveld/telescope-zoxide [telescope-zoxide]: https://github.com/jvgrootveld/telescope-zoxide
[telescope.nvim]: https://github.com/nvim-telescope/telescope.nvim [telescope.nvim]: https://github.com/nvim-telescope/telescope.nvim
[termux]: https://github.com/termux/termux-packages/tree/master/packages/zoxide [termux]: https://github.com/termux/termux-packages/tree/master/packages/zoxide
[tmux-session-wizard]: https://github.com/27medkamal/tmux-session-wizard [tmux-session-wizard]: https://github.com/27medkamal/tmux-session-wizard
[tmux-sessionx]: https://github.com/omerxx/tmux-sessionx
[tutorial]: contrib/tutorial.webp [tutorial]: contrib/tutorial.webp
[ubuntu packages]: https://packages.ubuntu.com/jammy/zoxide
[vim]: https://github.com/vim/vim [vim]: https://github.com/vim/vim
[void linux packages]: https://github.com/void-linux/void-packages/tree/master/srcpkgs/zoxide [void linux packages]: https://github.com/void-linux/void-packages/tree/master/srcpkgs/zoxide
[wiki-env]: https://github.com/ajeetdsouza/zoxide/wiki/HOWTO:-set-environment-variables "HOWTO: set environment variables" [wiki-env]: https://github.com/ajeetdsouza/zoxide/wiki/HOWTO:-set-environment-variables "HOWTO: set environment variables"
@ -566,7 +550,6 @@ Environment variables[^2] can be used for configuration. They must be set before
[xxh]: https://github.com/xxh/xxh [xxh]: https://github.com/xxh/xxh
[yazi]: https://github.com/sxyazi/yazi [yazi]: https://github.com/sxyazi/yazi
[zabb]: https://github.com/Mellbourn/zabb [zabb]: https://github.com/Mellbourn/zabb
[zesh]: https://github.com/roberte777/zesh
[zoxide.el]: https://gitlab.com/Vonfry/zoxide.el [zoxide.el]: https://gitlab.com/Vonfry/zoxide.el
[zoxide.vim]: https://github.com/nanotee/zoxide.vim [zoxide.vim]: https://github.com/nanotee/zoxide.vim
[zoxide.xplr]: https://github.com/sayanarijit/zoxide.xplr [zoxide.xplr]: https://github.com/sayanarijit/zoxide.xplr

View File

@ -3,10 +3,9 @@ mod cmd;
use std::{env, io}; use std::{env, io};
use clap::CommandFactory as _; use clap::CommandFactory;
use clap_complete::shells::{Bash, Elvish, Fish, PowerShell, Zsh}; use clap_complete::shells::{Bash, Elvish, Fish, PowerShell, Zsh};
use clap_complete_fig::Fig; use clap_complete_fig::Fig;
use clap_complete_nushell::Nushell;
use cmd::Cmd; use cmd::Cmd;
fn main() -> io::Result<()> { fn main() -> io::Result<()> {
@ -28,7 +27,6 @@ fn generate_completions() -> io::Result<()> {
clap_complete::generate_to(Elvish, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Elvish, cmd, BIN_NAME, OUT_DIR)?;
clap_complete::generate_to(Fig, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Fig, cmd, BIN_NAME, OUT_DIR)?;
clap_complete::generate_to(Fish, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Fish, cmd, BIN_NAME, OUT_DIR)?;
clap_complete::generate_to(Nushell, cmd, BIN_NAME, OUT_DIR)?;
clap_complete::generate_to(PowerShell, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(PowerShell, cmd, BIN_NAME, OUT_DIR)?;
clap_complete::generate_to(Zsh, cmd, BIN_NAME, OUT_DIR)?; clap_complete::generate_to(Zsh, cmd, BIN_NAME, OUT_DIR)?;

View File

@ -14,7 +14,7 @@ _zoxide() {
fi fi
local context curcontext="$curcontext" state line local context curcontext="$curcontext" state line
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
@ -29,9 +29,7 @@ _zoxide() {
curcontext="${curcontext%:*:*}:zoxide-command-$line[1]:" curcontext="${curcontext%:*:*}:zoxide-command-$line[1]:"
case $line[1] in case $line[1] in
(add) (add)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-s+[The rank to increment the entry if it exists or initialize it with if it doesn'\''t]:SCORE:_default' \
'--score=[The rank to increment the entry if it exists or initialize it with if it doesn'\''t]:SCORE:_default' \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
@ -40,7 +38,7 @@ _arguments "${_arguments_options[@]}" : \
&& ret=0 && ret=0
;; ;;
(edit) (edit)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
@ -56,34 +54,34 @@ _arguments "${_arguments_options[@]}" : \
curcontext="${curcontext%:*:*}:zoxide-edit-command-$line[1]:" curcontext="${curcontext%:*:*}:zoxide-edit-command-$line[1]:"
case $line[1] in case $line[1] in
(decrement) (decrement)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
'--version[Print version]' \ '--version[Print version]' \
':path:_default' \ ':path:' \
&& ret=0 && ret=0
;; ;;
(delete) (delete)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
'--version[Print version]' \ '--version[Print version]' \
':path:_default' \ ':path:' \
&& ret=0 && ret=0
;; ;;
(increment) (increment)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
'--version[Print version]' \ '--version[Print version]' \
':path:_default' \ ':path:' \
&& ret=0 && ret=0
;; ;;
(reload) (reload)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
@ -95,7 +93,7 @@ _arguments "${_arguments_options[@]}" : \
esac esac
;; ;;
(import) (import)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'--from=[Application to import from]:FROM:(autojump z)' \ '--from=[Application to import from]:FROM:(autojump z)' \
'--merge[Merge into existing database]' \ '--merge[Merge into existing database]' \
'-h[Print help]' \ '-h[Print help]' \
@ -106,21 +104,20 @@ _arguments "${_arguments_options[@]}" : \
&& ret=0 && ret=0
;; ;;
(init) (init)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'--cmd=[Changes the prefix of the \`z\` and \`zi\` commands]:CMD:_default' \ '--cmd=[Changes the prefix of the \`z\` and \`zi\` commands]:CMD: ' \
'--hook=[Changes how often zoxide increments a directory'\''s score]:HOOK:(none prompt pwd)' \ '--hook=[Changes how often zoxide increments a directory'\''s score]:HOOK:(none prompt pwd)' \
'--no-cmd[Prevents zoxide from defining the \`z\` and \`zi\` commands]' \ '--no-cmd[Prevents zoxide from defining the \`z\` and \`zi\` commands]' \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
'--version[Print version]' \ '--version[Print version]' \
':shell:(bash elvish fish nushell posix powershell tcsh xonsh zsh)' \ ':shell:(bash elvish fish ksh nushell posix powershell xonsh zsh)' \
&& ret=0 && ret=0
;; ;;
(query) (query)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'--exclude=[Exclude the current directory]:path:_files -/' \ '--exclude=[Exclude the current directory]:path:_files -/' \
'--base-dir=[Only search within this directory]:path:_files -/' \
'-a[Show unavailable directories]' \ '-a[Show unavailable directories]' \
'--all[Show unavailable directories]' \ '--all[Show unavailable directories]' \
'(-l --list)-i[Use interactive selection]' \ '(-l --list)-i[Use interactive selection]' \
@ -133,11 +130,11 @@ _arguments "${_arguments_options[@]}" : \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
'--version[Print version]' \ '--version[Print version]' \
'*::keywords:_default' \ '*::keywords:' \
&& ret=0 && ret=0
;; ;;
(remove) (remove)
_arguments "${_arguments_options[@]}" : \ _arguments "${_arguments_options[@]}" \
'-h[Print help]' \ '-h[Print help]' \
'--help[Print help]' \ '--help[Print help]' \
'-V[Print version]' \ '-V[Print version]' \
@ -167,16 +164,6 @@ _zoxide__add_commands() {
local commands; commands=() local commands; commands=()
_describe -t commands 'zoxide add commands' commands "$@" _describe -t commands 'zoxide add commands' commands "$@"
} }
(( $+functions[_zoxide__edit_commands] )) ||
_zoxide__edit_commands() {
local commands; commands=(
'decrement:' \
'delete:' \
'increment:' \
'reload:' \
)
_describe -t commands 'zoxide edit commands' commands "$@"
}
(( $+functions[_zoxide__edit__decrement_commands] )) || (( $+functions[_zoxide__edit__decrement_commands] )) ||
_zoxide__edit__decrement_commands() { _zoxide__edit__decrement_commands() {
local commands; commands=() local commands; commands=()
@ -187,21 +174,26 @@ _zoxide__edit__delete_commands() {
local commands; commands=() local commands; commands=()
_describe -t commands 'zoxide edit delete commands' commands "$@" _describe -t commands 'zoxide edit delete commands' commands "$@"
} }
(( $+functions[_zoxide__edit__increment_commands] )) || (( $+functions[_zoxide__edit_commands] )) ||
_zoxide__edit__increment_commands() { _zoxide__edit_commands() {
local commands; commands=() local commands; commands=(
_describe -t commands 'zoxide edit increment commands' commands "$@" 'decrement:' \
} 'delete:' \
(( $+functions[_zoxide__edit__reload_commands] )) || 'increment:' \
_zoxide__edit__reload_commands() { 'reload:' \
local commands; commands=() )
_describe -t commands 'zoxide edit reload commands' commands "$@" _describe -t commands 'zoxide edit commands' commands "$@"
} }
(( $+functions[_zoxide__import_commands] )) || (( $+functions[_zoxide__import_commands] )) ||
_zoxide__import_commands() { _zoxide__import_commands() {
local commands; commands=() local commands; commands=()
_describe -t commands 'zoxide import commands' commands "$@" _describe -t commands 'zoxide import commands' commands "$@"
} }
(( $+functions[_zoxide__edit__increment_commands] )) ||
_zoxide__edit__increment_commands() {
local commands; commands=()
_describe -t commands 'zoxide edit increment commands' commands "$@"
}
(( $+functions[_zoxide__init_commands] )) || (( $+functions[_zoxide__init_commands] )) ||
_zoxide__init_commands() { _zoxide__init_commands() {
local commands; commands=() local commands; commands=()
@ -212,6 +204,11 @@ _zoxide__query_commands() {
local commands; commands=() local commands; commands=()
_describe -t commands 'zoxide query commands' commands "$@" _describe -t commands 'zoxide query commands' commands "$@"
} }
(( $+functions[_zoxide__edit__reload_commands] )) ||
_zoxide__edit__reload_commands() {
local commands; commands=()
_describe -t commands 'zoxide edit reload commands' commands "$@"
}
(( $+functions[_zoxide__remove_commands] )) || (( $+functions[_zoxide__remove_commands] )) ||
_zoxide__remove_commands() { _zoxide__remove_commands() {
local commands; commands=() local commands; commands=()

View File

@ -21,10 +21,10 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
$completions = @(switch ($command) { $completions = @(switch ($command) {
'zoxide' { 'zoxide' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('add', 'add', [CompletionResultType]::ParameterValue, 'Add a new directory or increment its rank') [CompletionResult]::new('add', 'add', [CompletionResultType]::ParameterValue, 'Add a new directory or increment its rank')
[CompletionResult]::new('edit', 'edit', [CompletionResultType]::ParameterValue, 'Edit the database') [CompletionResult]::new('edit', 'edit', [CompletionResultType]::ParameterValue, 'Edit the database')
[CompletionResult]::new('import', 'import', [CompletionResultType]::ParameterValue, 'Import entries from another application') [CompletionResult]::new('import', 'import', [CompletionResultType]::ParameterValue, 'Import entries from another application')
@ -34,19 +34,17 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
break break
} }
'zoxide;add' { 'zoxide;add' {
[CompletionResult]::new('-s', '-s', [CompletionResultType]::ParameterName, 'The rank to increment the entry if it exists or initialize it with if it doesn''t') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--score', '--score', [CompletionResultType]::ParameterName, 'The rank to increment the entry if it exists or initialize it with if it doesn''t') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;edit' { 'zoxide;edit' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('decrement', 'decrement', [CompletionResultType]::ParameterValue, 'decrement') [CompletionResult]::new('decrement', 'decrement', [CompletionResultType]::ParameterValue, 'decrement')
[CompletionResult]::new('delete', 'delete', [CompletionResultType]::ParameterValue, 'delete') [CompletionResult]::new('delete', 'delete', [CompletionResultType]::ParameterValue, 'delete')
[CompletionResult]::new('increment', 'increment', [CompletionResultType]::ParameterValue, 'increment') [CompletionResult]::new('increment', 'increment', [CompletionResultType]::ParameterValue, 'increment')
@ -54,74 +52,73 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
break break
} }
'zoxide;edit;decrement' { 'zoxide;edit;decrement' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;edit;delete' { 'zoxide;edit;delete' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;edit;increment' { 'zoxide;edit;increment' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;edit;reload' { 'zoxide;edit;reload' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;import' { 'zoxide;import' {
[CompletionResult]::new('--from', '--from', [CompletionResultType]::ParameterName, 'Application to import from') [CompletionResult]::new('--from', 'from', [CompletionResultType]::ParameterName, 'Application to import from')
[CompletionResult]::new('--merge', '--merge', [CompletionResultType]::ParameterName, 'Merge into existing database') [CompletionResult]::new('--merge', 'merge', [CompletionResultType]::ParameterName, 'Merge into existing database')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;init' { 'zoxide;init' {
[CompletionResult]::new('--cmd', '--cmd', [CompletionResultType]::ParameterName, 'Changes the prefix of the `z` and `zi` commands') [CompletionResult]::new('--cmd', 'cmd', [CompletionResultType]::ParameterName, 'Changes the prefix of the `z` and `zi` commands')
[CompletionResult]::new('--hook', '--hook', [CompletionResultType]::ParameterName, 'Changes how often zoxide increments a directory''s score') [CompletionResult]::new('--hook', 'hook', [CompletionResultType]::ParameterName, 'Changes how often zoxide increments a directory''s score')
[CompletionResult]::new('--no-cmd', '--no-cmd', [CompletionResultType]::ParameterName, 'Prevents zoxide from defining the `z` and `zi` commands') [CompletionResult]::new('--no-cmd', 'no-cmd', [CompletionResultType]::ParameterName, 'Prevents zoxide from defining the `z` and `zi` commands')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;query' { 'zoxide;query' {
[CompletionResult]::new('--exclude', '--exclude', [CompletionResultType]::ParameterName, 'Exclude the current directory') [CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'Exclude the current directory')
[CompletionResult]::new('--base-dir', '--base-dir', [CompletionResultType]::ParameterName, 'Only search within this directory') [CompletionResult]::new('-a', 'a', [CompletionResultType]::ParameterName, 'Show unavailable directories')
[CompletionResult]::new('-a', '-a', [CompletionResultType]::ParameterName, 'Show unavailable directories') [CompletionResult]::new('--all', 'all', [CompletionResultType]::ParameterName, 'Show unavailable directories')
[CompletionResult]::new('--all', '--all', [CompletionResultType]::ParameterName, 'Show unavailable directories') [CompletionResult]::new('-i', 'i', [CompletionResultType]::ParameterName, 'Use interactive selection')
[CompletionResult]::new('-i', '-i', [CompletionResultType]::ParameterName, 'Use interactive selection') [CompletionResult]::new('--interactive', 'interactive', [CompletionResultType]::ParameterName, 'Use interactive selection')
[CompletionResult]::new('--interactive', '--interactive', [CompletionResultType]::ParameterName, 'Use interactive selection') [CompletionResult]::new('-l', 'l', [CompletionResultType]::ParameterName, 'List all matching directories')
[CompletionResult]::new('-l', '-l', [CompletionResultType]::ParameterName, 'List all matching directories') [CompletionResult]::new('--list', 'list', [CompletionResultType]::ParameterName, 'List all matching directories')
[CompletionResult]::new('--list', '--list', [CompletionResultType]::ParameterName, 'List all matching directories') [CompletionResult]::new('-s', 's', [CompletionResultType]::ParameterName, 'Print score with results')
[CompletionResult]::new('-s', '-s', [CompletionResultType]::ParameterName, 'Print score with results') [CompletionResult]::new('--score', 'score', [CompletionResultType]::ParameterName, 'Print score with results')
[CompletionResult]::new('--score', '--score', [CompletionResultType]::ParameterName, 'Print score with results') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
'zoxide;remove' { 'zoxide;remove' {
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help') [CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version') [CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
break break
} }
}) })

View File

@ -1,16 +1,12 @@
_zoxide() { _zoxide() {
local i cur prev opts cmd local i cur prev opts cmd
COMPREPLY=() COMPREPLY=()
if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then cur="${COMP_WORDS[COMP_CWORD]}"
cur="$2" prev="${COMP_WORDS[COMP_CWORD-1]}"
else
cur="${COMP_WORDS[COMP_CWORD]}"
fi
prev="$3"
cmd="" cmd=""
opts="" opts=""
for i in "${COMP_WORDS[@]:0:COMP_CWORD}" for i in ${COMP_WORDS[@]}
do do
case "${cmd},${i}" in case "${cmd},${i}" in
",$1") ",$1")
@ -67,20 +63,12 @@ _zoxide() {
return 0 return 0
;; ;;
zoxide__add) zoxide__add)
opts="-s -h -V --score --help --version <PATHS>..." opts="-h -V --help --version <PATHS>..."
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0 return 0
fi fi
case "${prev}" in case "${prev}" in
--score)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
-s)
COMPREPLY=($(compgen -f "${cur}"))
return 0
;;
*) *)
COMPREPLY=() COMPREPLY=()
;; ;;
@ -177,7 +165,7 @@ _zoxide() {
return 0 return 0
;; ;;
zoxide__init) zoxide__init)
opts="-h -V --no-cmd --cmd --hook --help --version bash elvish fish nushell posix powershell tcsh xonsh zsh" opts="-h -V --no-cmd --cmd --hook --help --version bash elvish fish ksh nushell posix powershell xonsh zsh"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0 return 0
@ -199,7 +187,7 @@ _zoxide() {
return 0 return 0
;; ;;
zoxide__query) zoxide__query)
opts="-a -i -l -s -h -V --all --interactive --list --score --exclude --base-dir --help --version [KEYWORDS]..." opts="-a -i -l -s -h -V --all --interactive --list --score --exclude --help --version [KEYWORDS]..."
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") ) COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0 return 0
@ -212,13 +200,6 @@ _zoxide() {
fi fi
return 0 return 0
;; ;;
--base-dir)
COMPREPLY=()
if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then
compopt -o plusdirs
fi
return 0
;;
*) *)
COMPREPLY=() COMPREPLY=()
;; ;;

View File

@ -30,8 +30,6 @@ set edit:completion:arg-completer[zoxide] = {|@words|
cand remove 'Remove a directory from the database' cand remove 'Remove a directory from the database'
} }
&'zoxide;add'= { &'zoxide;add'= {
cand -s 'The rank to increment the entry if it exists or initialize it with if it doesn''t'
cand --score 'The rank to increment the entry if it exists or initialize it with if it doesn''t'
cand -h 'Print help' cand -h 'Print help'
cand --help 'Print help' cand --help 'Print help'
cand -V 'Print version' cand -V 'Print version'
@ -90,7 +88,6 @@ set edit:completion:arg-completer[zoxide] = {|@words|
} }
&'zoxide;query'= { &'zoxide;query'= {
cand --exclude 'Exclude the current directory' cand --exclude 'Exclude the current directory'
cand --base-dir 'Only search within this directory'
cand -a 'Show unavailable directories' cand -a 'Show unavailable directories'
cand --all 'Show unavailable directories' cand --all 'Show unavailable directories'
cand -i 'Use interactive selection' cand -i 'Use interactive selection'

View File

@ -1,73 +1,42 @@
# Print an optspec for argparse to handle cmd's options that are independent of any subcommand. complete -c zoxide -n "__fish_use_subcommand" -s h -l help -d 'Print help'
function __fish_zoxide_global_optspecs complete -c zoxide -n "__fish_use_subcommand" -s V -l version -d 'Print version'
string join \n h/help V/version complete -c zoxide -n "__fish_use_subcommand" -f -a "add" -d 'Add a new directory or increment its rank'
end complete -c zoxide -n "__fish_use_subcommand" -f -a "edit" -d 'Edit the database'
complete -c zoxide -n "__fish_use_subcommand" -f -a "import" -d 'Import entries from another application'
function __fish_zoxide_needs_command complete -c zoxide -n "__fish_use_subcommand" -f -a "init" -d 'Generate shell configuration'
# Figure out if the current invocation already has a command. complete -c zoxide -n "__fish_use_subcommand" -f -a "query" -d 'Search for a directory in the database'
set -l cmd (commandline -opc) complete -c zoxide -n "__fish_use_subcommand" -f -a "remove" -d 'Remove a directory from the database'
set -e cmd[1] complete -c zoxide -n "__fish_seen_subcommand_from add" -s h -l help -d 'Print help'
argparse -s (__fish_zoxide_global_optspecs) -- $cmd 2>/dev/null complete -c zoxide -n "__fish_seen_subcommand_from add" -s V -l version -d 'Print version'
or return complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -s h -l help -d 'Print help'
if set -q argv[1] complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -s V -l version -d 'Print version'
# Also print the command, so this can be used to figure out what it is. complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -f -a "decrement"
echo $argv[1] complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -f -a "delete"
return 1 complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -f -a "increment"
end complete -c zoxide -n "__fish_seen_subcommand_from edit; and not __fish_seen_subcommand_from decrement; and not __fish_seen_subcommand_from delete; and not __fish_seen_subcommand_from increment; and not __fish_seen_subcommand_from reload" -f -a "reload"
return 0 complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from decrement" -s h -l help -d 'Print help'
end complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from decrement" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from delete" -s h -l help -d 'Print help'
function __fish_zoxide_using_subcommand complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from delete" -s V -l version -d 'Print version'
set -l cmd (__fish_zoxide_needs_command) complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from increment" -s h -l help -d 'Print help'
test -z "$cmd" complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from increment" -s V -l version -d 'Print version'
and return 1 complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from reload" -s h -l help -d 'Print help'
contains -- $cmd[1] $argv complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from reload" -s V -l version -d 'Print version'
end complete -c zoxide -n "__fish_seen_subcommand_from import" -l from -d 'Application to import from' -r -f -a "{autojump '',z ''}"
complete -c zoxide -n "__fish_seen_subcommand_from import" -l merge -d 'Merge into existing database'
complete -c zoxide -n "__fish_zoxide_needs_command" -s h -l help -d 'Print help' complete -c zoxide -n "__fish_seen_subcommand_from import" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_needs_command" -s V -l version -d 'Print version' complete -c zoxide -n "__fish_seen_subcommand_from import" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "add" -d 'Add a new directory or increment its rank' complete -c zoxide -n "__fish_seen_subcommand_from init" -l cmd -d 'Changes the prefix of the `z` and `zi` commands' -r
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "edit" -d 'Edit the database' complete -c zoxide -n "__fish_seen_subcommand_from init" -l hook -d 'Changes how often zoxide increments a directory\'s score' -r -f -a "{none '',prompt '',pwd ''}"
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "import" -d 'Import entries from another application' complete -c zoxide -n "__fish_seen_subcommand_from init" -l no-cmd -d 'Prevents zoxide from defining the `z` and `zi` commands'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "init" -d 'Generate shell configuration' complete -c zoxide -n "__fish_seen_subcommand_from init" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "query" -d 'Search for a directory in the database' complete -c zoxide -n "__fish_seen_subcommand_from init" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "remove" -d 'Remove a directory from the database' complete -c zoxide -n "__fish_seen_subcommand_from query" -l exclude -d 'Exclude the current directory' -r -f -a "(__fish_complete_directories)"
complete -c zoxide -n "__fish_zoxide_using_subcommand add" -s s -l score -d 'The rank to increment the entry if it exists or initialize it with if it doesn\'t' -r complete -c zoxide -n "__fish_seen_subcommand_from query" -s a -l all -d 'Show unavailable directories'
complete -c zoxide -n "__fish_zoxide_using_subcommand add" -s h -l help -d 'Print help' complete -c zoxide -n "__fish_seen_subcommand_from query" -s i -l interactive -d 'Use interactive selection'
complete -c zoxide -n "__fish_zoxide_using_subcommand add" -s V -l version -d 'Print version' complete -c zoxide -n "__fish_seen_subcommand_from query" -s l -l list -d 'List all matching directories'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -s h -l help -d 'Print help' complete -c zoxide -n "__fish_seen_subcommand_from query" -s s -l score -d 'Print score with results'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -s V -l version -d 'Print version' complete -c zoxide -n "__fish_seen_subcommand_from query" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -f -a "decrement" complete -c zoxide -n "__fish_seen_subcommand_from query" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -f -a "delete" complete -c zoxide -n "__fish_seen_subcommand_from remove" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -f -a "increment" complete -c zoxide -n "__fish_seen_subcommand_from remove" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -f -a "reload"
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from decrement" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from decrement" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from delete" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from delete" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from increment" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from increment" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from reload" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand edit; and __fish_seen_subcommand_from reload" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand import" -l from -d 'Application to import from' -r -f -a "autojump\t''
z\t''"
complete -c zoxide -n "__fish_zoxide_using_subcommand import" -l merge -d 'Merge into existing database'
complete -c zoxide -n "__fish_zoxide_using_subcommand import" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand import" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand init" -l cmd -d 'Changes the prefix of the `z` and `zi` commands' -r
complete -c zoxide -n "__fish_zoxide_using_subcommand init" -l hook -d 'Changes how often zoxide increments a directory\'s score' -r -f -a "none\t''
prompt\t''
pwd\t''"
complete -c zoxide -n "__fish_zoxide_using_subcommand init" -l no-cmd -d 'Prevents zoxide from defining the `z` and `zi` commands'
complete -c zoxide -n "__fish_zoxide_using_subcommand init" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand init" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -l exclude -d 'Exclude the current directory' -r -f -a "(__fish_complete_directories)"
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -l base-dir -d 'Only search within this directory' -r -f -a "(__fish_complete_directories)"
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s a -l all -d 'Show unavailable directories'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s i -l interactive -d 'Use interactive selection'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s l -l list -d 'List all matching directories'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s s -l score -d 'Print score with results'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand query" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_zoxide_using_subcommand remove" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand remove" -s V -l version -d 'Print version'

View File

@ -1,99 +0,0 @@
module completions {
# A smarter cd command for your terminal
export extern zoxide [
--help(-h) # Print help
--version(-V) # Print version
]
# Add a new directory or increment its rank
export extern "zoxide add" [
...paths: path
--score(-s): string # The rank to increment the entry if it exists or initialize it with if it doesn't
--help(-h) # Print help
--version(-V) # Print version
]
# Edit the database
export extern "zoxide edit" [
--help(-h) # Print help
--version(-V) # Print version
]
export extern "zoxide edit decrement" [
path: string
--help(-h) # Print help
--version(-V) # Print version
]
export extern "zoxide edit delete" [
path: string
--help(-h) # Print help
--version(-V) # Print version
]
export extern "zoxide edit increment" [
path: string
--help(-h) # Print help
--version(-V) # Print version
]
export extern "zoxide edit reload" [
--help(-h) # Print help
--version(-V) # Print version
]
def "nu-complete zoxide import from" [] {
[ "autojump" "z" ]
}
# Import entries from another application
export extern "zoxide import" [
path: path
--from: string@"nu-complete zoxide import from" # Application to import from
--merge # Merge into existing database
--help(-h) # Print help
--version(-V) # Print version
]
def "nu-complete zoxide init shell" [] {
[ "bash" "elvish" "fish" "nushell" "posix" "powershell" "tcsh" "xonsh" "zsh" ]
}
def "nu-complete zoxide init hook" [] {
[ "none" "prompt" "pwd" ]
}
# Generate shell configuration
export extern "zoxide init" [
shell: string@"nu-complete zoxide init shell"
--no-cmd # Prevents zoxide from defining the `z` and `zi` commands
--cmd: string # Changes the prefix of the `z` and `zi` commands
--hook: string@"nu-complete zoxide init hook" # Changes how often zoxide increments a directory's score
--help(-h) # Print help
--version(-V) # Print version
]
# Search for a directory in the database
export extern "zoxide query" [
...keywords: string
--all(-a) # Show unavailable directories
--interactive(-i) # Use interactive selection
--list(-l) # List all matching directories
--score(-s) # Print score with results
--exclude: path # Exclude the current directory
--base-dir: path # Only search within this directory
--help(-h) # Print help
--version(-V) # Print version
]
# Remove a directory from the database
export extern "zoxide remove" [
...paths: path
--help(-h) # Print help
--version(-V) # Print version
]
}
export use completions *

View File

@ -6,15 +6,6 @@ const completion: Fig.Spec = {
name: "add", name: "add",
description: "Add a new directory or increment its rank", description: "Add a new directory or increment its rank",
options: [ options: [
{
name: ["-s", "--score"],
description: "The rank to increment the entry if it exists or initialize it with if it doesn't",
isRepeatable: true,
args: {
name: "score",
isOptional: true,
},
},
{ {
name: ["-h", "--help"], name: ["-h", "--help"],
description: "Print help", description: "Print help",
@ -191,10 +182,10 @@ const completion: Fig.Spec = {
"bash", "bash",
"elvish", "elvish",
"fish", "fish",
"ksh",
"nushell", "nushell",
"posix", "posix",
"powershell", "powershell",
"tcsh",
"xonsh", "xonsh",
"zsh", "zsh",
], ],
@ -214,16 +205,6 @@ const completion: Fig.Spec = {
template: "folders", template: "folders",
}, },
}, },
{
name: "--base-dir",
description: "Only search within this directory",
isRepeatable: true,
args: {
name: "base_dir",
isOptional: true,
template: "folders",
},
},
{ {
name: ["-a", "--all"], name: ["-a", "--all"],
description: "Show unavailable directories", description: "Show unavailable directories",

BIN
contrib/warp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 817 KiB

View File

@ -30,6 +30,13 @@ Add this to the \fBend\fR of your config file (usually
\fBzoxide init fish | source\fR \fBzoxide init fish | source\fR
.fi .fi
.TP .TP
.B ksh
Add this to the \fBend\fR of your config file (usually \fB~/.kshrc\fR):
.sp
.nf
\fBeval $(zoxide init ksh)\fR
.fi
.TP
.B nushell .B nushell
Add this to the \fBend\fR of your env file (find it by running Add this to the \fBend\fR of your env file (find it by running
\fB$nu.env-path\fR in Nushell): \fB$nu.env-path\fR in Nushell):
@ -55,14 +62,6 @@ $profile\fR in PowerShell):
\fBInvoke-Expression (& { (zoxide init powershell | Out-String) })\fR \fBInvoke-Expression (& { (zoxide init powershell | Out-String) })\fR
.fi .fi
.TP .TP
.B tcsh
Add this to the \fBend\fR of your config file (usually \fB~/.tcshrc\fR):
.sp
.nf
\fBzoxide init tcsh > ~/.zoxide.tcsh\fR
\fBsource ~/.zoxide.tcsh\fR
.fi
.TP
.B xonsh .B xonsh
Add this to the \fBend\fR of your config file (usually \fB~/.xonshrc\fR): Add this to the \fBend\fR of your config file (usually \fB~/.xonshrc\fR):
.sp .sp

View File

@ -5,4 +5,4 @@ use_field_init_shorthand = true
use_small_heuristics = "Max" use_small_heuristics = "Max"
use_try_shorthand = true use_try_shorthand = true
wrap_comments = true wrap_comments = true
style_edition = "2024" version = "Two"

View File

@ -1,10 +1,10 @@
let let
pkgs = import (builtins.fetchTarball pkgs = import (builtins.fetchTarball
"https://github.com/NixOS/nixpkgs/archive/ec9ef366451af88284d7dfd18ee017b7e86a0710.tar.gz") { "https://github.com/NixOS/nixpkgs/archive/4d513ab5f170d66afa3387bdd718d41aa936ee9f.tar.gz") {
overlays = [ rust ]; overlays = [ rust ];
}; };
rust = import (builtins.fetchTarball rust = import (builtins.fetchTarball
"https://github.com/oxalica/rust-overlay/archive/026e8fedefd6b167d92ed04b195c658d95ffc7a5.tar.gz"); "https://github.com/oxalica/rust-overlay/archive/e6679d2ff9136d00b3a7168d2bf1dff9e84c5758.tar.gz");
rust-nightly = rust-nightly =
pkgs.rust-bin.selectLatestNightlyWith (toolchain: toolchain.minimal); pkgs.rust-bin.selectLatestNightlyWith (toolchain: toolchain.minimal);
@ -27,7 +27,6 @@ in pkgs.mkShell {
pkgs.ksh pkgs.ksh
pkgs.nushell pkgs.nushell
pkgs.powershell pkgs.powershell
pkgs.tcsh
pkgs.xonsh pkgs.xonsh
pkgs.zsh pkgs.zsh

View File

@ -1,6 +1,6 @@
use std::path::Path; use std::path::Path;
use anyhow::{Result, bail}; use anyhow::{bail, Result};
use crate::cmd::{Add, Run}; use crate::cmd::{Add, Run};
use crate::db::Database; use crate::db::Database;
@ -33,9 +33,7 @@ impl Run for Add {
if !Path::new(path).is_dir() { if !Path::new(path).is_dir() {
bail!("not a directory: {path}"); bail!("not a directory: {path}");
} }
db.add_update(path, 1.0, now);
let by = self.score.unwrap_or(1.0);
db.add_update(path, by, now);
} }
if db.dirty() { if db.dirty() {

View File

@ -2,14 +2,9 @@
use std::path::PathBuf; use std::path::PathBuf;
use clap::builder::{IntoResettable, Resettable, StyledStr};
use clap::{Parser, Subcommand, ValueEnum, ValueHint}; use clap::{Parser, Subcommand, ValueEnum, ValueHint};
struct HelpTemplate; const HELP_TEMPLATE: &str = color_print::cstr!("\
impl IntoResettable<StyledStr> for HelpTemplate {
fn into_resettable(self) -> Resettable<StyledStr> {
color_print::cstr!("\
{before-help}<bold><underline>{name} {version}</underline></bold> {before-help}<bold><underline>{name} {version}</underline></bold>
{author} {author}
https://github.com/ajeetdsouza/zoxide https://github.com/ajeetdsouza/zoxide
@ -27,15 +22,13 @@ https://github.com/ajeetdsouza/zoxide
{tab}<bold>_ZO_EXCLUDE_DIRS</bold> {tab}List of directory globs to be excluded {tab}<bold>_ZO_EXCLUDE_DIRS</bold> {tab}List of directory globs to be excluded
{tab}<bold>_ZO_FZF_OPTS</bold> {tab}Custom flags to pass to fzf {tab}<bold>_ZO_FZF_OPTS</bold> {tab}Custom flags to pass to fzf
{tab}<bold>_ZO_MAXAGE</bold> {tab}Maximum total age after which entries start getting deleted {tab}<bold>_ZO_MAXAGE</bold> {tab}Maximum total age after which entries start getting deleted
{tab}<bold>_ZO_RESOLVE_SYMLINKS</bold>{tab}Resolve symlinks when storing paths").into_resettable() {tab}<bold>_ZO_RESOLVE_SYMLINKS</bold>{tab}Resolve symlinks when storing paths");
}
}
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
about, about,
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
disable_help_subcommand = true, disable_help_subcommand = true,
propagate_version = true, propagate_version = true,
version, version,
@ -53,23 +46,18 @@ pub enum Cmd {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Add { pub struct Add {
#[clap(num_args = 1.., required = true, value_hint = ValueHint::DirPath)] #[clap(num_args = 1.., required = true, value_hint = ValueHint::DirPath)]
pub paths: Vec<PathBuf>, pub paths: Vec<PathBuf>,
/// The rank to increment the entry if it exists or initialize it with if it
/// doesn't
#[clap(short, long)]
pub score: Option<f64>,
} }
/// Edit the database /// Edit the database
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Edit { pub struct Edit {
#[clap(subcommand)] #[clap(subcommand)]
@ -92,7 +80,7 @@ pub enum EditCommand {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Import { pub struct Import {
#[clap(value_hint = ValueHint::FilePath)] #[clap(value_hint = ValueHint::FilePath)]
@ -118,7 +106,7 @@ pub enum ImportFrom {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Init { pub struct Init {
#[clap(value_enum)] #[clap(value_enum)]
@ -149,11 +137,10 @@ pub enum InitShell {
Bash, Bash,
Elvish, Elvish,
Fish, Fish,
Ksh,
Nushell, Nushell,
#[clap(alias = "ksh")]
Posix, Posix,
Powershell, Powershell,
Tcsh,
Xonsh, Xonsh,
Zsh, Zsh,
} }
@ -162,7 +149,7 @@ pub enum InitShell {
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Query { pub struct Query {
pub keywords: Vec<String>, pub keywords: Vec<String>,
@ -186,17 +173,13 @@ pub struct Query {
/// Exclude the current directory /// Exclude the current directory
#[clap(long, value_hint = ValueHint::DirPath, value_name = "path")] #[clap(long, value_hint = ValueHint::DirPath, value_name = "path")]
pub exclude: Option<String>, pub exclude: Option<String>,
/// Only search within this directory
#[clap(long, value_hint = ValueHint::DirPath, value_name = "path")]
pub base_dir: Option<String>,
} }
/// Remove a directory from the database /// Remove a directory from the database
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[clap(
author, author,
help_template = HelpTemplate, help_template = HELP_TEMPLATE,
)] )]
pub struct Remove { pub struct Remove {
#[clap(value_hint = ValueHint::DirPath)] #[clap(value_hint = ValueHint::DirPath)]

View File

@ -1,6 +1,6 @@
use std::fs; use std::fs;
use anyhow::{Context, Result, bail}; use anyhow::{bail, Context, Result};
use crate::cmd::{Import, ImportFrom, Run}; use crate::cmd::{Import, ImportFrom, Run};
use crate::db::Database; use crate::db::Database;

View File

@ -1,12 +1,12 @@
use std::io::{self, Write}; use std::io::{self, Write};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use askama::Template; use rinja::Template;
use crate::cmd::{Init, InitShell, Run}; use crate::cmd::{Init, InitShell, Run};
use crate::config; use crate::config;
use crate::error::BrokenPipeHandler; use crate::error::BrokenPipeHandler;
use crate::shell::{Bash, Elvish, Fish, Nushell, Opts, Posix, Powershell, Tcsh, Xonsh, Zsh}; use crate::shell::{Bash, Elvish, Fish, Ksh, Nushell, Opts, Posix, Powershell, Xonsh, Zsh};
impl Run for Init { impl Run for Init {
fn run(&self) -> Result<()> { fn run(&self) -> Result<()> {
@ -19,10 +19,10 @@ impl Run for Init {
InitShell::Bash => Bash(opts).render(), InitShell::Bash => Bash(opts).render(),
InitShell::Elvish => Elvish(opts).render(), InitShell::Elvish => Elvish(opts).render(),
InitShell::Fish => Fish(opts).render(), InitShell::Fish => Fish(opts).render(),
InitShell::Ksh => Ksh(opts).render(),
InitShell::Nushell => Nushell(opts).render(), InitShell::Nushell => Nushell(opts).render(),
InitShell::Posix => Posix(opts).render(), InitShell::Posix => Posix(opts).render(),
InitShell::Powershell => Powershell(opts).render(), InitShell::Powershell => Powershell(opts).render(),
InitShell::Tcsh => Tcsh(opts).render(),
InitShell::Xonsh => Xonsh(opts).render(), InitShell::Xonsh => Xonsh(opts).render(),
InitShell::Zsh => Zsh(opts).render(), InitShell::Zsh => Zsh(opts).render(),
} }

View File

@ -79,8 +79,7 @@ impl Query {
fn get_stream<'a>(&self, db: &'a mut Database, now: Epoch) -> Result<Stream<'a>> { fn get_stream<'a>(&self, db: &'a mut Database, now: Epoch) -> Result<Stream<'a>> {
let mut options = StreamOptions::new(now) let mut options = StreamOptions::new(now)
.with_keywords(self.keywords.iter().map(|s| s.as_str())) .with_keywords(self.keywords.iter().map(|s| s.as_str()))
.with_exclude(config::exclude_dirs()?) .with_exclude(config::exclude_dirs()?);
.with_base_dir(self.base_dir.clone());
if !self.all { if !self.all {
let resolve_symlinks = config::resolve_symlinks(); let resolve_symlinks = config::resolve_symlinks();
options = options.with_exists(true).with_resolve_symlinks(resolve_symlinks); options = options.with_exists(true).with_resolve_symlinks(resolve_symlinks);

View File

@ -1,4 +1,4 @@
use anyhow::{Result, bail}; use anyhow::{bail, Result};
use crate::cmd::{Remove, Run}; use crate::cmd::{Remove, Run};
use crate::db::Database; use crate::db::Database;

View File

@ -2,7 +2,7 @@ use std::env;
use std::ffi::OsString; use std::ffi::OsString;
use std::path::PathBuf; use std::path::PathBuf;
use anyhow::{Context, Result, ensure}; use anyhow::{ensure, Context, Result};
use glob::Pattern; use glob::Pattern;
use crate::db::Rank; use crate::db::Rank;
@ -20,7 +20,7 @@ pub fn data_dir() -> Result<PathBuf> {
} }
pub fn echo() -> bool { pub fn echo() -> bool {
env::var_os("_ZO_ECHO").is_some_and(|var| var == "1") env::var_os("_ZO_ECHO").map_or(false, |var| var == "1")
} }
pub fn exclude_dirs() -> Result<Vec<Pattern>> { pub fn exclude_dirs() -> Result<Vec<Pattern>> {
@ -58,5 +58,5 @@ pub fn maxage() -> Result<Rank> {
} }
pub fn resolve_symlinks() -> bool { pub fn resolve_symlinks() -> bool {
env::var_os("_ZO_RESOLVE_SYMLINKS").is_some_and(|var| var == "1") env::var_os("_ZO_RESOLVE_SYMLINKS").map_or(false, |var| var == "1")
} }

View File

@ -4,7 +4,7 @@ mod stream;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::{fs, io}; use std::{fs, io};
use anyhow::{Context, Result, bail}; use anyhow::{bail, Context, Result};
use bincode::Options; use bincode::Options;
use ouroboros::self_referencing; use ouroboros::self_referencing;
@ -183,7 +183,7 @@ impl Database {
*self.borrow_dirty() *self.borrow_dirty()
} }
pub fn dirs(&self) -> &[Dir<'_>] { pub fn dirs(&self) -> &[Dir] {
self.borrow_dirs() self.borrow_dirs()
} }
@ -203,7 +203,7 @@ impl Database {
.context("could not serialize database") .context("could not serialize database")
} }
fn deserialize(bytes: &[u8]) -> Result<Vec<Dir<'_>>> { fn deserialize(bytes: &[u8]) -> Result<Vec<Dir>> {
// Assume a maximum size for the database. This prevents bincode from throwing // Assume a maximum size for the database. This prevents bincode from throwing
// strange errors when it encounters invalid data. // strange errors when it encounters invalid data.
const MAX_SIZE: u64 = 32 << 20; // 32 MiB const MAX_SIZE: u64 = 32 << 20; // 32 MiB

View File

@ -1,6 +1,5 @@
use std::iter::Rev; use std::iter::Rev;
use std::ops::Range; use std::ops::Range;
use std::path::Path;
use std::{fs, path}; use std::{fs, path};
use glob::Pattern; use glob::Pattern;
@ -21,7 +20,7 @@ impl<'a> Stream<'a> {
Stream { db, idxs, options } Stream { db, idxs, options }
} }
pub fn next(&mut self) -> Option<&Dir<'_>> { pub fn next(&mut self) -> Option<&Dir> {
while let Some(idx) = self.idxs.next() { while let Some(idx) = self.idxs.next() {
let dir = &self.db.dirs()[idx]; let dir = &self.db.dirs()[idx];
@ -29,16 +28,11 @@ impl<'a> Stream<'a> {
continue; continue;
} }
if !self.filter_by_base_dir(&dir.path) {
continue;
}
if !self.filter_by_exclude(&dir.path) { if !self.filter_by_exclude(&dir.path) {
self.db.swap_remove(idx); self.db.swap_remove(idx);
continue; continue;
} }
// Exists queries are slow, this should always be checked last.
if !self.filter_by_exists(&dir.path) { if !self.filter_by_exists(&dir.path) {
if dir.last_accessed < self.options.ttl { if dir.last_accessed < self.options.ttl {
self.db.swap_remove(idx); self.db.swap_remove(idx);
@ -53,30 +47,6 @@ impl<'a> Stream<'a> {
None None
} }
fn filter_by_base_dir(&self, path: &str) -> bool {
match &self.options.base_dir {
Some(base_dir) => Path::new(path).starts_with(base_dir),
None => true,
}
}
fn filter_by_exclude(&self, path: &str) -> bool {
!self.options.exclude.iter().any(|pattern| pattern.matches(path))
}
fn filter_by_exists(&self, path: &str) -> bool {
if !self.options.exists {
return true;
}
// The logic here is reversed - if we resolve symlinks when adding entries to
// the database, we should not return symlinks when querying back from
// the database.
let resolver =
if self.options.resolve_symlinks { fs::symlink_metadata } else { fs::metadata };
resolver(path).map(|metadata| metadata.is_dir()).unwrap_or_default()
}
fn filter_by_keywords(&self, path: &str) -> bool { fn filter_by_keywords(&self, path: &str) -> bool {
let (keywords_last, keywords) = match self.options.keywords.split_last() { let (keywords_last, keywords) = match self.options.keywords.split_last() {
Some(split) => split, Some(split) => split,
@ -104,6 +74,23 @@ impl<'a> Stream<'a> {
true true
} }
fn filter_by_exclude(&self, path: &str) -> bool {
!self.options.exclude.iter().any(|pattern| pattern.matches(path))
}
fn filter_by_exists(&self, path: &str) -> bool {
if !self.options.exists {
return true;
}
// The logic here is reversed - if we resolve symlinks when adding entries to
// the database, we should not return symlinks when querying back from
// the database.
let resolver =
if self.options.resolve_symlinks { fs::symlink_metadata } else { fs::metadata };
resolver(path).map(|metadata| metadata.is_dir()).unwrap_or_default()
}
} }
pub struct StreamOptions { pub struct StreamOptions {
@ -125,10 +112,6 @@ pub struct StreamOptions {
/// Directories that do not exist and haven't been accessed since TTL will /// Directories that do not exist and haven't been accessed since TTL will
/// be lazily removed. /// be lazily removed.
ttl: Epoch, ttl: Epoch,
/// Only return directories within this parent directory
/// Does not check if the path exists
base_dir: Option<String>,
} }
impl StreamOptions { impl StreamOptions {
@ -140,7 +123,6 @@ impl StreamOptions {
exists: false, exists: false,
resolve_symlinks: false, resolve_symlinks: false,
ttl: now.saturating_sub(3 * MONTH), ttl: now.saturating_sub(3 * MONTH),
base_dir: None,
} }
} }
@ -167,11 +149,6 @@ impl StreamOptions {
self.resolve_symlinks = resolve_symlinks; self.resolve_symlinks = resolve_symlinks;
self self
} }
pub fn with_base_dir(mut self, base_dir: Option<String>) -> Self {
self.base_dir = base_dir;
self
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,7 +1,7 @@
use std::fmt::{self, Display, Formatter}; use std::fmt::{self, Display, Formatter};
use std::io; use std::io;
use anyhow::{Context, Result, bail}; use anyhow::{bail, Context, Result};
/// Custom error type for early exit. /// Custom error type for early exit.
#[derive(Debug)] #[derive(Debug)]

View File

@ -1,5 +1,9 @@
#![allow(clippy::single_component_path_imports)] #![allow(clippy::single_component_path_imports)]
// rstest_reuse must be imported at the top of the crate.
#[cfg(all(test, feature = "nix-dev"))]
use rstest_reuse;
mod cmd; mod cmd;
mod config; mod config;
mod db; mod db;
@ -18,8 +22,8 @@ use crate::error::SilentExit;
pub fn main() -> ExitCode { pub fn main() -> ExitCode {
// Forcibly disable backtraces. // Forcibly disable backtraces.
unsafe { env::remove_var("RUST_LIB_BACKTRACE") }; env::remove_var("RUST_LIB_BACKTRACE");
unsafe { env::remove_var("RUST_BACKTRACE") }; env::remove_var("RUST_BACKTRACE");
match Cmd::parse().run() { match Cmd::parse().run() {
Ok(()) => ExitCode::SUCCESS, Ok(()) => ExitCode::SUCCESS,

View File

@ -10,7 +10,7 @@ pub struct Opts<'a> {
macro_rules! make_template { macro_rules! make_template {
($name:ident, $path:expr) => { ($name:ident, $path:expr) => {
#[derive(::std::fmt::Debug, ::askama::Template)] #[derive(::std::fmt::Debug, ::rinja::Template)]
#[template(path = $path)] #[template(path = $path)]
pub struct $name<'a>(pub &'a self::Opts<'a>); pub struct $name<'a>(pub &'a self::Opts<'a>);
@ -26,18 +26,18 @@ macro_rules! make_template {
make_template!(Bash, "bash.txt"); make_template!(Bash, "bash.txt");
make_template!(Elvish, "elvish.txt"); make_template!(Elvish, "elvish.txt");
make_template!(Fish, "fish.txt"); make_template!(Fish, "fish.txt");
make_template!(Ksh, "ksh.txt");
make_template!(Nushell, "nushell.txt"); make_template!(Nushell, "nushell.txt");
make_template!(Posix, "posix.txt"); make_template!(Posix, "posix.txt");
make_template!(Powershell, "powershell.txt"); make_template!(Powershell, "powershell.txt");
make_template!(Tcsh, "tcsh.txt");
make_template!(Xonsh, "xonsh.txt"); make_template!(Xonsh, "xonsh.txt");
make_template!(Zsh, "zsh.txt"); make_template!(Zsh, "zsh.txt");
#[cfg(feature = "nix-dev")] #[cfg(feature = "nix-dev")]
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use askama::Template;
use assert_cmd::Command; use assert_cmd::Command;
use rinja::Template;
use rstest::rstest; use rstest::rstest;
use rstest_reuse::{apply, template}; use rstest_reuse::{apply, template};
@ -97,7 +97,7 @@ mod tests {
#[apply(opts)] #[apply(opts)]
fn elvish_elvish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { fn elvish_elvish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks }; let opts = Opts { cmd, hook, echo, resolve_symlinks };
let mut source = String::new(); let mut source = String::default();
// Filter out lines using edit:*, since those functions are only available in // Filter out lines using edit:*, since those functions are only available in
// the interactive editor. // the interactive editor.
@ -114,16 +114,6 @@ mod tests {
.stderr(""); .stderr("");
} }
#[apply(opts)]
fn fish_no_builtin_abbr(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let source = Fish(&opts).render().unwrap();
assert!(
!source.contains("builtin abbr"),
"`builtin abbr` does not work on older versions of Fish"
);
}
#[apply(opts)] #[apply(opts)]
fn fish_fish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { fn fish_fish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks }; let opts = Opts { cmd, hook, echo, resolve_symlinks };
@ -159,6 +149,42 @@ mod tests {
.stderr(""); .stderr("");
} }
#[apply(opts)]
fn ksh_ksh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let source = Ksh(&opts).render().unwrap();
Command::new("ksh").args(["-n", "-c", &source]).assert().success().stdout("").stderr("");
}
#[apply(opts)]
fn ksh_shellcheck(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let source = Ksh(&opts).render().unwrap();
Command::new("shellcheck")
.args(["--enable=all", "-"])
.write_stdin(source)
.assert()
.success()
.stdout("")
.stderr("");
}
#[apply(opts)]
fn ksh_shfmt(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let mut source = Ksh(&opts).render().unwrap();
source.push('\n');
Command::new("shfmt")
.args(["--diff", "--indent=4", "--language-dialect=mksh", "--simplify", "-"])
.write_stdin(source)
.assert()
.success()
.stdout("")
.stderr("");
}
#[apply(opts)] #[apply(opts)]
fn nushell_nushell(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { fn nushell_nushell(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks }; let opts = Opts { cmd, hook, echo, resolve_symlinks };
@ -249,20 +275,6 @@ mod tests {
.stderr(""); .stderr("");
} }
#[apply(opts)]
fn tcsh_tcsh(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let source = Tcsh(&opts).render().unwrap();
Command::new("tcsh")
.args(["-e", "-f", "-s"])
.write_stdin(source)
.assert()
.success()
.stdout("")
.stderr("");
}
#[apply(opts)] #[apply(opts)]
fn xonsh_black(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) { fn xonsh_black(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks }; let opts = Opts { cmd, hook, echo, resolve_symlinks };

View File

@ -8,7 +8,7 @@ use std::{env, mem};
#[cfg(windows)] #[cfg(windows)]
use anyhow::anyhow; use anyhow::anyhow;
use anyhow::{Context, Result, bail}; use anyhow::{bail, Context, Result};
use crate::db::{Dir, Epoch}; use crate::db::{Dir, Epoch};
use crate::error::SilentExit; use crate::error::SilentExit;
@ -135,7 +135,7 @@ impl FzfChild {
mem::drop(self.0.stdin.take()); mem::drop(self.0.stdin.take());
let mut stdout = self.0.stdout.take().unwrap(); let mut stdout = self.0.stdout.take().unwrap();
let mut output = String::new(); let mut output = String::default();
stdout.read_to_string(&mut output).context("failed to read from fzf")?; stdout.read_to_string(&mut output).context("failed to read from fzf")?;
let status = self.0.wait().context("wait failed on fzf")?; let status = self.0.wait().context("wait failed on fzf")?;
@ -169,21 +169,16 @@ pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
#[cfg(unix)] #[cfg(unix)]
if let Ok(metadata) = path.metadata() { if let Ok(metadata) = path.metadata() {
use std::os::unix::fs::MetadataExt; use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::unistd::{self, Gid, Uid}; use nix::unistd::{self, Gid, Uid};
let uid = Uid::from_raw(metadata.uid()); let uid = Uid::from_raw(metadata.uid());
let gid = Gid::from_raw(metadata.gid()); let gid = Gid::from_raw(metadata.gid());
_ = unistd::fchown(&tmp_file, Some(uid), Some(gid)); _ = unistd::fchown(tmp_file.as_raw_fd(), Some(uid), Some(gid));
} }
// Close and rename the tmpfile. // Close and rename the tmpfile.
// In some cases, errors from the last write() are reported only on close().
// Rust ignores errors from close(), since it occurs inside `Drop`. To
// catch these errors, we manually call `File::sync_all()` first.
tmp_file
.sync_all()
.with_context(|| format!("could not sync writes to file: {}", tmp_path.display()))?;
mem::drop(tmp_file); mem::drop(tmp_file);
rename(&tmp_path, path) rename(&tmp_path, path)
})(); })();

View File

@ -27,8 +27,11 @@ function __zoxide_cd() {
{{ section }} {{ section }}
# Hook configuration for zoxide. # Hook configuration for zoxide.
# #
{%- if hook != InitHook::None %}
{% if hook == InitHook::None -%}
{{ not_configured }}
{%- else -%}
# Hook to add new entries to the database. # Hook to add new entries to the database.
{%- if hook == InitHook::Prompt %} {%- if hook == InitHook::Prompt %}
function __zoxide_hook() { function __zoxide_hook() {
@ -37,7 +40,6 @@ function __zoxide_hook() {
\command zoxide add -- "$(__zoxide_pwd)" \command zoxide add -- "$(__zoxide_pwd)"
return "${retval}" return "${retval}"
} }
{%- else if hook == InitHook::Pwd %} {%- else if hook == InitHook::Pwd %}
__zoxide_oldpwd="$(__zoxide_pwd)" __zoxide_oldpwd="$(__zoxide_pwd)"
@ -58,32 +60,7 @@ if [[ ${PROMPT_COMMAND:=} != *'__zoxide_hook'* ]]; then
PROMPT_COMMAND="__zoxide_hook;${PROMPT_COMMAND#;}" PROMPT_COMMAND="__zoxide_hook;${PROMPT_COMMAND#;}"
fi fi
{%- endif %} {% endif -%}
# Report common issues.
function __zoxide_doctor() {
{%- if hook == InitHook::None %}
return 0
{%- else %}
[[ ${_ZO_DOCTOR:-1} -eq 0 ]] && return 0
# shellcheck disable=SC2199
[[ ${PROMPT_COMMAND[@]:-} == *'__zoxide_hook'* ]] && return 0
# shellcheck disable=SC2199
[[ ${__vsc_original_prompt_command[@]:-} == *'__zoxide_hook'* ]] && return 0
_ZO_DOCTOR=0
\builtin printf '%s\n' \
'zoxide: detected a possible configuration issue.' \
'Please ensure that zoxide is initialized right at the end of your shell configuration file (usually ~/.bashrc).' \
'' \
'If the issue persists, consider filing an issue at:' \
'https://github.com/ajeetdsouza/zoxide/issues' \
'' \
'Disable this message by setting _ZO_DOCTOR=0.' \
'' >&2
{%- endif %}
}
{{ section }} {{ section }}
# When using zoxide with --no-cmd, alias these internal functions as desired. # When using zoxide with --no-cmd, alias these internal functions as desired.
@ -93,8 +70,6 @@ __zoxide_z_prefix='z#'
# Jump to a directory using only keywords. # Jump to a directory using only keywords.
function __zoxide_z() { function __zoxide_z() {
__zoxide_doctor
# shellcheck disable=SC2199 # shellcheck disable=SC2199
if [[ $# -eq 0 ]]; then if [[ $# -eq 0 ]]; then
__zoxide_cd ~ __zoxide_cd ~
@ -118,7 +93,6 @@ function __zoxide_z() {
# Jump to a directory using interactive search. # Jump to a directory using interactive search.
function __zoxide_zi() { function __zoxide_zi() {
__zoxide_doctor
\builtin local result \builtin local result
result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}" result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}"
} }
@ -147,13 +121,8 @@ function {{cmd}}i() {
# - Completions don't work on `dumb` terminals. # - Completions don't work on `dumb` terminals.
if [[ ${BASH_VERSINFO[0]:-0} -eq 4 && ${BASH_VERSINFO[1]:-0} -ge 4 || ${BASH_VERSINFO[0]:-0} -ge 5 ]] && if [[ ${BASH_VERSINFO[0]:-0} -eq 4 && ${BASH_VERSINFO[1]:-0} -ge 4 || ${BASH_VERSINFO[0]:-0} -ge 5 ]] &&
[[ :"${SHELLOPTS}": =~ :(vi|emacs): && ${TERM} != 'dumb' ]]; then [[ :"${SHELLOPTS}": =~ :(vi|emacs): && ${TERM} != 'dumb' ]]; then
# Use `printf '\e[5n'` to redraw line after fzf closes.
function __zoxide_z_complete_helper() { \builtin bind '"\e[0n": redraw-current-line' &>/dev/null
READLINE_LINE="{{ cmd }} ${__zoxide_result@Q}"
READLINE_POINT={{ "${#READLINE_LINE}" }}
bind '"\e[0n": accept-line'
\builtin printf '\e[5n' >/dev/tty
}
function __zoxide_z_complete() { function __zoxide_z_complete() {
# Only show completions when the cursor is at the end of the line. # Only show completions when the cursor is at the end of the line.
@ -165,20 +134,12 @@ if [[ ${BASH_VERSINFO[0]:-0} -eq 4 && ${BASH_VERSINFO[1]:-0} -ge 4 || ${BASH_VER
\builtin compgen -A directory -- "${COMP_WORDS[-1]}" || \builtin true \builtin compgen -A directory -- "${COMP_WORDS[-1]}" || \builtin true
) )
# If there is a space after the last word, use interactive selection. # If there is a space after the last word, use interactive selection.
elif [[ -z ${COMP_WORDS[-1]} ]]; then elif [[ -z ${COMP_WORDS[-1]} ]] && [[ ${COMP_WORDS[-2]} != "${__zoxide_z_prefix}"?* ]]; then
\builtin local result
# shellcheck disable=SC2312 # shellcheck disable=SC2312
__zoxide_result="$(\command zoxide query --exclude "$(__zoxide_pwd)" --interactive -- "{{ "${COMP_WORDS[@]:1:${#COMP_WORDS[@]}-2}" }}")" && { result="$(\command zoxide query --exclude "$(__zoxide_pwd)" --interactive -- "{{ "${COMP_WORDS[@]:1:${#COMP_WORDS[@]}-2}" }}")" &&
# In case the terminal does not respond to \e[5n or another COMPREPLY=("${__zoxide_z_prefix}${result}/")
# mechanism steals the response, it is still worth completing \builtin printf '\e[5n'
# the directory in the command line.
COMPREPLY=("${__zoxide_z_prefix}${__zoxide_result}/")
# Note: We here call "bind" without prefixing "\builtin" to be
# compatible with frameworks like ble.sh, which emulates Bash's
# builtin "bind".
bind -x '"\e[0n": __zoxide_z_complete_helper'
\builtin printf '\e[5n' >/dev/tty
}
fi fi
} }
@ -193,6 +154,6 @@ fi
{%- endmatch %} {%- endmatch %}
{{ section }} {{ section }}
# To initialize zoxide, add this to your shell configuration file (usually ~/.bashrc): # To initialize zoxide, add this to your configuration (usually ~/.bashrc):
# #
# eval "$(zoxide init bash)" # eval "$(zoxide init bash)"

View File

@ -112,10 +112,10 @@ end
{%- match cmd %} {%- match cmd %}
{%- when Some with (cmd) %} {%- when Some with (cmd) %}
abbr --erase {{cmd}} &>/dev/null builtin abbr --erase {{cmd}} &>/dev/null
alias {{cmd}}=__zoxide_z alias {{cmd}}=__zoxide_z
abbr --erase {{cmd}}i &>/dev/null builtin abbr --erase {{cmd}}i &>/dev/null
alias {{cmd}}i=__zoxide_zi alias {{cmd}}i=__zoxide_zi
{%- when None %} {%- when None %}

118
templates/ksh.txt Normal file
View File

@ -0,0 +1,118 @@
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
# shellcheck shell=ksh
{{ section }}
# Utility functions for zoxide.
#
# pwd based on the value of _ZO_RESOLVE_SYMLINKS.
__zoxide_pwd() {
{%- if cfg!(windows) %}
\command cygpath -w "$(\builtin pwd -P)"
{%- else if resolve_symlinks %}
\command pwd -P
{%- else %}
\command pwd -L
{%- endif %}
}
# cd + custom logic based on the value of _ZO_ECHO.
__zoxide_cd() {
# shellcheck disable=SC2164
\command cd "$@" {%- if echo %} && __zoxide_pwd {%- endif %}
}
{{ section }}
# Hook configuration for zoxide.
#
{% match hook %}
{%- when InitHook::None -%}
{{ not_configured }}
{%- when InitHook::Prompt -%}
# Hook to add new entries to the database.
__zoxide_hook() {
\command zoxide add -- "$(__zoxide_pwd || \builtin true)"
}
# Initialize hook.
if [[ ${PS1:=} == "${PS1#*\$(__zoxide_hook)}" ]]; then
PS1="${PS1}\$(__zoxide_hook)"
fi
{%- when InitHook::Pwd -%}
# Hook to add new entries to the database.
__zoxide_hook() {
__zoxide_retval="$?"
__zoxide_newpwd="$(__zoxide_pwd)"
if [[ ${__zoxide_oldpwd:-__zoxide_newpwd} != "${__zoxide_newpwd}" ]]; then
\command zoxide add -- "${__zoxide_newpwd}"
__zoxide_oldpwd="${__zoxide_newpwd}"
fi
return "${__zoxide_retval}"
}
# Initialize hook.
__zoxide_trap="$(\command trap -p DEBUG)"
if [[ ${__zoxide_trap} != *'__zoxide_hook'* ]]; then
\command trap "__zoxide_hook;${__zoxide_trap#';'}" DEBUG
fi
{%- endmatch %}
{{ section }}
# When using zoxide with --no-cmd, alias these internal functions as desired.
#
# Jump to a directory using only keywords.
__zoxide_z() {
# shellcheck disable=SC2199
if (($# == 0)); then
__zoxide_cd ~
elif [[ ($# == 1) && $1 == '-' ]]; then
__zoxide_cd "${OLDPWD}"
elif [[ ($# == 1) && -d $1 ]]; then
__zoxide_cd "$1"
elif [[ ($# == 2) && $1 == '--' ]]; then
__zoxide_cd "$2"
else
# shellcheck disable=SC2312
__zoxide_result="$(\command zoxide query --exclude "$(__zoxide_pwd)" -- "$@")" &&
__zoxide_cd "${__zoxide_result}"
fi
}
# Jump to a directory using interactive search.
__zoxide_zi() {
__zoxide_result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${__zoxide_result}"
}
{{ section }}
# Commands for zoxide. Disable these using --no-cmd.
#
{%- match cmd %}
{%- when Some with (cmd) %}
\command unalias {{cmd}} >/dev/null 2>&1 || \true
{{cmd}}() {
__zoxide_z "$@"
}
\command unalias {{cmd}}i >/dev/null 2>&1 || \true
{{cmd}}i() {
__zoxide_zi "$@"
}
{%- when None %}
{{ not_configured }}
{%- endmatch %}
{{ section }}
# To initialize zoxide, add this to your configuration (usually ~/.kshrc):
#
# eval "$(zoxide init ksh)"

View File

@ -12,40 +12,23 @@
{%- else -%} {%- else -%}
# Initialize hook to add new entries to the database. # Initialize hook to add new entries to the database.
export-env { if (not ($env | default false __zoxide_hooked | get __zoxide_hooked)) {
$env.__zoxide_hooked = true
{%- if hook == InitHook::Prompt %} {%- if hook == InitHook::Prompt %}
$env.config = ( $env.config = ($env | default {} config).config
$env.config? $env.config = ($env.config | default {} hooks)
| default {} $env.config = ($env.config | update hooks ($env.config.hooks | default [] pre_prompt))
| upsert hooks { default {} } $env.config = ($env.config | update hooks.pre_prompt ($env.config.hooks.pre_prompt | append { ||
| upsert hooks.pre_prompt { default [] } zoxide add -- $env.PWD
) }))
let __zoxide_hooked = (
$env.config.hooks.pre_prompt | any { try { get __zoxide_hook } catch { false } }
)
if not $__zoxide_hooked {
$env.config.hooks.pre_prompt = ($env.config.hooks.pre_prompt | append {
__zoxide_hook: true,
code: {|| ^zoxide add -- $env.PWD}
})
}
{%- else if hook == InitHook::Pwd %} {%- else if hook == InitHook::Pwd %}
$env.config = ( $env.config = ($env | default {} config).config
$env.config? $env.config = ($env.config | default {} hooks)
| default {} $env.config = ($env.config | update hooks ($env.config.hooks | default {} env_change))
| upsert hooks { default {} } $env.config = ($env.config | update hooks.env_change ($env.config.hooks.env_change | default [] PWD))
| upsert hooks.env_change { default {} } $env.config = ($env.config | update hooks.env_change.PWD ($env.config.hooks.env_change.PWD | append {|_, dir|
| upsert hooks.env_change.PWD { default [] } zoxide add -- $dir
) }))
let __zoxide_hooked = (
$env.config.hooks.env_change.PWD | any { try { get __zoxide_hook } catch { false } }
)
if not $__zoxide_hooked {
$env.config.hooks.env_change.PWD = ($env.config.hooks.env_change.PWD | append {
__zoxide_hook: true,
code: {|_, dir| ^zoxide add -- $dir}
})
}
{%- endif %} {%- endif %}
} }
@ -56,14 +39,13 @@ export-env {
# #
# Jump to a directory using only keywords. # Jump to a directory using only keywords.
def --env --wrapped __zoxide_z [...rest: string] { def --env --wrapped __zoxide_z [...rest:string] {
let path = match $rest { let arg0 = ($rest | append '~').0
[] => {'~'}, let arg0_is_dir = (try {$arg0 | path expand | path type}) == 'dir'
[ '-' ] => {'-'}, let path = if (($rest | length) <= 1) and ($arg0 == '-' or $arg0_is_dir) {
[ $arg ] if ($arg | path expand | path type) == 'dir' => {$arg} $arg0
_ => { } else {
^zoxide query --exclude $env.PWD -- ...$rest | str trim -r -c "\n" (zoxide query --exclude $env.PWD -- ...$rest | str trim -r -c "\n")
}
} }
cd $path cd $path
{%- if echo %} {%- if echo %}
@ -73,7 +55,7 @@ def --env --wrapped __zoxide_z [...rest: string] {
# Jump to a directory using interactive search. # Jump to a directory using interactive search.
def --env --wrapped __zoxide_zi [...rest:string] { def --env --wrapped __zoxide_zi [...rest:string] {
cd $'(^zoxide query --interactive -- ...$rest | str trim -r -c "\n")' cd $'(zoxide query --interactive -- ...$rest | str trim -r -c "\n")'
{%- if echo %} {%- if echo %}
echo $env.PWD echo $env.PWD
{%- endif %} {%- endif %}

View File

@ -43,30 +43,6 @@ if [ "${PS1:=}" = "${PS1#*\$(__zoxide_hook)}" ]; then
PS1="${PS1}\$(__zoxide_hook)" PS1="${PS1}\$(__zoxide_hook)"
fi fi
# Report common issues.
__zoxide_doctor() {
{%- if hook != InitHook::Prompt %}
return 0
{%- else %}
[ "${_ZO_DOCTOR:-1}" -eq 0 ] && return 0
case "${PS1:-}" in
*__zoxide_hook*) return 0 ;;
*) ;;
esac
_ZO_DOCTOR=0
\command printf '%s\n' \
'zoxide: detected a possible configuration issue.' \
'Please ensure that zoxide is initialized right at the end of your shell configuration file.' \
'' \
'If the issue persists, consider filing an issue at:' \
'https://github.com/ajeetdsouza/zoxide/issues' \
'' \
'Disable this message by setting _ZO_DOCTOR=0.' \
'' >&2
{%- endif %}
}
{%- when InitHook::Pwd -%} {%- when InitHook::Pwd -%}
\command printf "%s\n%s\n" \ \command printf "%s\n%s\n" \
"zoxide: PWD hooks are not supported on POSIX shells." \ "zoxide: PWD hooks are not supported on POSIX shells." \
@ -80,8 +56,6 @@ __zoxide_doctor() {
# Jump to a directory using only keywords. # Jump to a directory using only keywords.
__zoxide_z() { __zoxide_z() {
__zoxide_doctor
if [ "$#" -eq 0 ]; then if [ "$#" -eq 0 ]; then
__zoxide_cd ~ __zoxide_cd ~
elif [ "$#" -eq 1 ] && [ "$1" = '-' ]; then elif [ "$#" -eq 1 ] && [ "$1" = '-' ]; then
@ -102,7 +76,6 @@ __zoxide_z() {
# Jump to a directory using interactive search. # Jump to a directory using interactive search.
__zoxide_zi() { __zoxide_zi() {
__zoxide_doctor
__zoxide_result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${__zoxide_result}" __zoxide_result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${__zoxide_result}"
} }

View File

@ -80,7 +80,7 @@ function global:__zoxide_hook {
{%- endif %} {%- endif %}
# Initialize hook. # Initialize hook.
$global:__zoxide_hooked = (Get-Variable __zoxide_hooked -ErrorAction Ignore -ValueOnly) $global:__zoxide_hooked = (Get-Variable __zoxide_hooked -ErrorAction SilentlyContinue -ValueOnly)
if ($global:__zoxide_hooked -ne 1) { if ($global:__zoxide_hooked -ne 1) {
$global:__zoxide_hooked = 1 $global:__zoxide_hooked = 1
$global:__zoxide_prompt_old = $function:prompt $global:__zoxide_prompt_old = $function:prompt
@ -106,12 +106,9 @@ function global:__zoxide_z {
elseif ($args.Length -eq 1 -and ($args[0] -eq '-' -or $args[0] -eq '+')) { elseif ($args.Length -eq 1 -and ($args[0] -eq '-' -or $args[0] -eq '+')) {
__zoxide_cd $args[0] $false __zoxide_cd $args[0] $false
} }
elseif ($args.Length -eq 1 -and (Test-Path -PathType Container -LiteralPath $args[0])) { elseif ($args.Length -eq 1 -and (Test-Path $args[0] -PathType Container)) {
__zoxide_cd $args[0] $true __zoxide_cd $args[0] $true
} }
elseif ($args.Length -eq 1 -and (Test-Path -PathType Container -Path $args[0] )) {
__zoxide_cd $args[0] $false
}
else { else {
$result = __zoxide_pwd $result = __zoxide_pwd
if ($null -ne $result) { if ($null -ne $result) {

View File

@ -1,74 +0,0 @@
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
{%- let pwd_cmd -%}
{%- if resolve_symlinks -%}
{%- let pwd_cmd = "pwd -P" -%}
{%- else -%}
{%- let pwd_cmd = "pwd -L" -%}
{%- endif -%}
{{ section }}
# Hook configuration for zoxide.
#
{%- if hook != InitHook::None %}
# Hook to add new entries to the database.
{%- if hook == InitHook::Prompt %}
alias __zoxide_hook 'zoxide add -- "`{{ pwd_cmd }}`"'
{%- else if hook == InitHook::Pwd %}
set __zoxide_pwd_old = `{{ pwd_cmd }}`
alias __zoxide_hook 'set __zoxide_pwd_tmp = "`{{ pwd_cmd }}`"; test "$__zoxide_pwd_tmp" != "$__zoxide_pwd_old" && zoxide add -- "$__zoxide_pwd_tmp"; set __zoxide_pwd_old = "$__zoxide_pwd_tmp"'
{%- endif %}
# Initialize hook.
alias precmd ';__zoxide_hook'
{%- endif %}
{{ section }}
# When using zoxide with --no-cmd, alias these internal functions as desired.
#
# Jump to a directory using only keywords.
alias __zoxide_z 'set __zoxide_args = (\!*)\
if ("$#__zoxide_args" == 0) then\
cd ~\
else\
if ("$#__zoxide_args" == 1 && "$__zoxide_args[1]" == "-") then\
cd -\
else if ("$#__zoxide_args" == 1 && -d "$__zoxide_args[1]") then\
cd "$__zoxide_args[1]"\
else\
set __zoxide_pwd = `{{ pwd_cmd }}`\
set __zoxide_result = "`zoxide query --exclude '"'"'$__zoxide_pwd'"'"' -- $__zoxide_args`" && cd "$__zoxide_result"\
endif\
endif'
# Jump to a directory using interactive search.
alias __zoxide_zi 'set __zoxide_args = (\!*)\
set __zoxide_pwd = `{{ pwd_cmd }}`\
set __zoxide_result = "`zoxide query --exclude '"'"'$__zoxide_pwd'"'"' --interactive -- $__zoxide_args`" && cd "$__zoxide_result"'
{{ section }}
# Commands for zoxide. Disable these using --no-cmd.
#
{%- match cmd %}
{%- when Some with (cmd) %}
alias {{cmd}} __zoxide_z
alias {{cmd}}i __zoxide_zi
{%- when None %}
{{ not_configured }}
{%- endmatch %}
{{ section }}
# To initialize zoxide, add this to your shell configuration file (usually ~/.tcshrc):
#
# zoxide init tcsh > ~/.zoxide.tcsh
# source ~/.zoxide.tcsh

View File

@ -26,7 +26,7 @@ def __zoxide_bin() -> str:
return zoxide return zoxide
def __zoxide_env() -> dict[str, str]: def __zoxide_env() -> typing.Dict[str, str]:
"""Returns the current environment.""" """Returns the current environment."""
return builtins.__xonsh__.env.detype() # type: ignore # pylint:disable=no-member return builtins.__xonsh__.env.detype() # type: ignore # pylint:disable=no-member
@ -43,13 +43,13 @@ def __zoxide_pwd() -> str:
return pwd return pwd
def __zoxide_cd(path: str | bytes | None = None) -> None: def __zoxide_cd(path: typing.Optional[typing.AnyStr] = None) -> None:
"""cd + custom logic based on the value of _ZO_ECHO.""" """cd + custom logic based on the value of _ZO_ECHO."""
if path is None: if path is None:
args = [] args = []
elif isinstance(path, bytes): elif isinstance(path, bytes):
args = [path.decode("utf-8")] args = [path.decode("utf-8")]
else: elif isinstance(path, str):
args = [path] args = [path]
_, exc, _ = xonsh.dirstack.cd(args) _, exc, _ = xonsh.dirstack.cd(args)
if exc is not None: if exc is not None:
@ -64,11 +64,11 @@ class ZoxideSilentException(Exception):
def __zoxide_errhandler( def __zoxide_errhandler(
func: typing.Callable[[list[str]], None], func: typing.Callable[[typing.List[str]], None]
) -> typing.Callable[[list[str]], int]: ) -> typing.Callable[[typing.List[str]], int]:
"""Print exception and exit with error code 1.""" """Print exception and exit with error code 1."""
def wrapper(args: list[str]) -> int: def wrapper(args: typing.List[str]) -> int:
try: try:
func(args) func(args)
return 0 return 0
@ -113,7 +113,7 @@ if "__zoxide_hook" not in globals():
@__zoxide_errhandler @__zoxide_errhandler
def __zoxide_z(args: list[str]) -> None: def __zoxide_z(args: typing.List[str]) -> None:
"""Jump to a directory using only keywords.""" """Jump to a directory using only keywords."""
if args == []: if args == []:
__zoxide_cd() __zoxide_cd()
@ -138,7 +138,7 @@ def __zoxide_z(args: list[str]) -> None:
@__zoxide_errhandler @__zoxide_errhandler
def __zoxide_zi(args: list[str]) -> None: def __zoxide_zi(args: typing.List[str]) -> None:
"""Jump to a directory using interactive search.""" """Jump to a directory using interactive search."""
try: try:
zoxide = __zoxide_bin() zoxide = __zoxide_bin()

View File

@ -28,6 +28,10 @@ function __zoxide_cd() {
# Hook configuration for zoxide. # Hook configuration for zoxide.
# #
{% if hook == InitHook::None -%}
{{ not_configured -}}
{% else -%}
# Hook to add new entries to the database. # Hook to add new entries to the database.
function __zoxide_hook() { function __zoxide_hook() {
# shellcheck disable=SC2312 # shellcheck disable=SC2312
@ -35,56 +39,27 @@ function __zoxide_hook() {
} }
# Initialize hook. # Initialize hook.
\builtin typeset -ga precmd_functions # shellcheck disable=SC2154
\builtin typeset -ga chpwd_functions if [[ ${precmd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]] && [[ ${chpwd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]]; then
# shellcheck disable=SC2034,SC2296
precmd_functions=("${(@)precmd_functions:#__zoxide_hook}")
# shellcheck disable=SC2034,SC2296
chpwd_functions=("${(@)chpwd_functions:#__zoxide_hook}")
{%- if hook == InitHook::Prompt %} {%- if hook == InitHook::Prompt %}
precmd_functions+=(__zoxide_hook) precmd_functions+=(__zoxide_hook)
{%- else if hook == InitHook::Pwd %} {%- else if hook == InitHook::Pwd %}
chpwd_functions+=(__zoxide_hook) chpwd_functions+=(__zoxide_hook)
{%- endif %} {%- endif %}
fi
# Report common issues.
function __zoxide_doctor() {
{%- if hook == InitHook::None %}
return 0
{%- else %}
[[ ${_ZO_DOCTOR:-1} -ne 0 ]] || return 0
{%- if hook == InitHook::Prompt %}
[[ ${precmd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]] || return 0
{%- else if hook == InitHook::Pwd %}
[[ ${chpwd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]] || return 0
{%- endif %} {%- endif %}
_ZO_DOCTOR=0
\builtin printf '%s\n' \
'zoxide: detected a possible configuration issue.' \
'Please ensure that zoxide is initialized right at the end of your shell configuration file (usually ~/.zshrc).' \
'' \
'If the issue persists, consider filing an issue at:' \
'https://github.com/ajeetdsouza/zoxide/issues' \
'' \
'Disable this message by setting _ZO_DOCTOR=0.' \
'' >&2
{%- endif %}
}
{{ section }} {{ section }}
# When using zoxide with --no-cmd, alias these internal functions as desired. # When using zoxide with --no-cmd, alias these internal functions as desired.
# #
# Jump to a directory using only keywords. # Jump to a directory using only keywords.
function __zoxide_z() { function __zoxide_z() {
__zoxide_doctor # shellcheck disable=SC2199
if [[ "$#" -eq 0 ]]; then if [[ "$#" -eq 0 ]]; then
__zoxide_cd ~ __zoxide_cd ~
elif [[ "$#" -eq 1 ]] && { [[ -d "$1" ]] || [[ "$1" = '-' ]] || [[ "$1" =~ ^[-+][0-9]+$ ]]; }; then elif [[ "$#" -eq 1 ]] && { [[ -d "$1" ]] || [[ "$1" = '-' ]] || [[ "$1" =~ ^[-+][0-9]$ ]]; }; then
__zoxide_cd "$1" __zoxide_cd "$1"
elif [[ "$#" -eq 2 ]] && [[ "$1" = "--" ]]; then elif [[ "$#" -eq 2 ]] && [[ "$1" = "--" ]]; then
__zoxide_cd "$2" __zoxide_cd "$2"
@ -97,7 +72,6 @@ function __zoxide_z() {
# Jump to a directory using interactive search. # Jump to a directory using interactive search.
function __zoxide_zi() { function __zoxide_zi() {
__zoxide_doctor
\builtin local result \builtin local result
result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}" result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}"
} }
@ -117,12 +91,6 @@ function {{ cmd }}i() {
__zoxide_zi "$@" __zoxide_zi "$@"
} }
{%- when None %}
{{ not_configured }}
{%- endmatch %}
# Completions. # Completions.
if [[ -o zle ]]; then if [[ -o zle ]]; then
__zoxide_result='' __zoxide_result=''
@ -158,7 +126,7 @@ if [[ -o zle ]]; then
function __zoxide_z_complete_helper() { function __zoxide_z_complete_helper() {
if [[ -n "${__zoxide_result}" ]]; then if [[ -n "${__zoxide_result}" ]]; then
# shellcheck disable=SC2034,SC2296 # shellcheck disable=SC2034,SC2296
BUFFER="{{ cmd.unwrap_or("cd") }} ${(q-)__zoxide_result}" BUFFER="{{ cmd }} ${(q-)__zoxide_result}"
__zoxide_result='' __zoxide_result=''
\builtin zle reset-prompt \builtin zle reset-prompt
\builtin zle accept-line \builtin zle accept-line
@ -167,13 +135,17 @@ if [[ -o zle ]]; then
fi fi
} }
\builtin zle -N __zoxide_z_complete_helper \builtin zle -N __zoxide_z_complete_helper
{%- if let Some(cmd) = cmd %}
[[ "${+functions[compdef]}" -ne 0 ]] && \compdef __zoxide_z_complete {{ cmd }} [[ "${+functions[compdef]}" -ne 0 ]] && \compdef __zoxide_z_complete {{ cmd }}
{%- endif %}
fi fi
{%- when None %}
{{ not_configured }}
{%- endmatch %}
{{ section }} {{ section }}
# To initialize zoxide, add this to your shell configuration file (usually ~/.zshrc): # To initialize zoxide, add this to your configuration (usually ~/.zshrc):
# #
# eval "$(zoxide init zsh)" # eval "$(zoxide init zsh)"