Compare commits

...

104 Commits
v0.9.4 ... main

Author SHA1 Message Date
Ajeet D'Souza 194f8e31e4
Update README.md 2025-10-03 02:59:45 +05:30
Ajeet D'Souza eb7b08fed3
Update README.md 2025-09-30 18:34:43 +05:30
dependabot[bot] 6ac39b7f41
Bump Swatinem/rust-cache from 2.8.0 to 2.8.1 (#1119)
Bumps [Swatinem/rust-cache](https://github.com/swatinem/rust-cache) from 2.8.0 to 2.8.1.
- [Release notes](https://github.com/swatinem/rust-cache/releases)
- [Changelog](https://github.com/Swatinem/rust-cache/blob/master/CHANGELOG.md)
- [Commits](https://github.com/swatinem/rust-cache/compare/v2.8.0...v2.8.1)

---
updated-dependencies:
- dependency-name: Swatinem/rust-cache
  dependency-version: 2.8.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-23 01:57:49 +05:30
Ajeet D'Souza 76125d9bd3 Update sponsorship 2025-09-18 21:11:43 +05:30
Ben Beasley 2299f2834b
Unpin and update tempfile (#1105) 2025-08-23 02:27:21 +05:30
Bryan Corey c070535968
Add link to raycast-zoxide integration (#1050) 2025-08-16 09:57:04 +05:30
dependabot[bot] 4549438ffa
Bump actions/checkout from 4 to 5 (#1101)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-12 08:12:29 +05:30
Azalea Colburn 261cf8846a
--basedir query option (#1027) 2025-08-10 13:26:52 +05:30
Ben Beasley 30129f4344
Update rstest from 0.25 to 0.26 (#1099) 2025-08-07 21:55:06 +05:30
dependabot[bot] 9b899e90e3
Bump Swatinem/rust-cache from 2.7.8 to 2.8.0 (#1083)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-07 19:51:56 +05:30
Tony 6324b4e347
Add support for multi digits dirstack entry (e.g. +12). (#1080) 2025-06-17 15:27:46 +05:30
Steven Xu db14bdc2ff
nushell: use sigil operator (#1070) 2025-05-31 04:53:54 +05:30
Ajeet D'Souza d6c0203c09 Add Ubuntu install instructions 2025-05-27 05:28:12 +05:30
Ajeet D'Souza 859268aec8 chore(release): v0.9.8 2025-05-27 03:13:06 +05:30
Ajeet D'Souza b318a2a190 Nushell: add CLI completions 2025-05-27 02:34:48 +05:30
smolsbs ee8bbe57d3
Fixed the arg[0] argument position (#1056) 2025-05-16 03:19:09 -07:00
Koichi Murase 9c0dcf12f3
Run the cd command after "cd ... <space><tab>" in Bash integration (#1055) 2025-05-14 08:38:54 +05:30
benz 628f8542a0
Fixes #995: Wildcard expansion for PowerShell (#1001)
Co-authored-by: Ajeet D'Souza <98ajeet@gmail.com>
2025-05-13 17:48:55 +05:30
Ajeet D'Souza 3d9f928e01 Upgrade to Rust 2024 2025-05-12 09:42:37 -07:00
Ajeet D'Souza 4807518c4b Call fsync before close 2025-05-12 09:37:04 -07:00
Ajeet D'Souza 8e14038811 Fix lints 2025-05-12 06:22:54 -07:00
Ajeet D'Souza 1d08fe2b84 Add doctor for POSIX shells 2025-05-11 23:24:35 -07:00
Ajeet D'Souza 36537410cd Doctor should handle PROMPT_COMMAND being an array 2025-05-10 23:41:55 -07:00
Ajeet D'Souza 306d7ae143 Fix shellcheck lint 2025-05-10 21:52:39 -07:00
Ajeet D'Souza 9768e645c7 Remove unneeded quotes 2025-05-10 11:27:02 -07:00
Ajeet D'Souza 8f0288b0c9 Check if zoxide is running under VS Code 2025-05-10 10:22:20 -07:00
Koichi Murase 6ec0436859
Add fixes to Bash integration (#1048) 2025-05-10 13:21:47 +05:30
XTY f1d848820a
docs(install): fix broken Nixpkgs link (#1051) 2025-05-10 00:19:12 +05:30
Ajeet D'Souza 095b270fea csh -> tcsh 2025-05-06 00:26:07 -07:00
Ajeet D'Souza 09aa626a86
Add support for csh (#1047) 2025-05-06 11:28:54 +05:30
Lisa FS 7691d7e9a5
nushell: fix jumping to symlinks that are not in the database (#1032)
Expand path before checking for its type. This solves the issue of ignoring symlinks.
2025-04-13 08:46:27 -05:00
Brian 6902d375c5
powershell: Ignore errors from `__zoxide_hooked` (#1038) 2025-04-10 15:46:57 +05:30
Y.D.X. b193a84eb0
docs: Update minimum supported fzf version (#1034)
Before v0.51.0, fzf generates redundant escaping of backslashes for Windows, which breaks `zoxide edit`.
https://github.com/junegunn/fzf/releases/tag/0.51.0

Closes #539

Co-authored-by: Loïc Riegel <loic.riegel@outlook.fr>
2025-04-04 20:49:14 +05:30
Azalea Colburn e1e2f41ecb
feat: add --score option (#1030) 2025-03-31 11:43:40 +05:30
dependabot[bot] 7617799eb5
Bump Swatinem/rust-cache from 2.7.7 to 2.7.8 (#1025)
Bumps [Swatinem/rust-cache](https://github.com/swatinem/rust-cache) from 2.7.7 to 2.7.8.
- [Release notes](https://github.com/swatinem/rust-cache/releases)
- [Changelog](https://github.com/Swatinem/rust-cache/blob/master/CHANGELOG.md)
- [Commits](https://github.com/swatinem/rust-cache/compare/v2.7.7...v2.7.8)

---
updated-dependencies:
- dependency-name: Swatinem/rust-cache
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-25 01:33:55 +05:30
dependabot[bot] 2480ed0853
Bump cachix/cachix-action from 15 to 16 (#1018)
Bumps [cachix/cachix-action](https://github.com/cachix/cachix-action) from 15 to 16.
- [Release notes](https://github.com/cachix/cachix-action/releases)
- [Commits](https://github.com/cachix/cachix-action/compare/v15...v16)

---
updated-dependencies:
- dependency-name: cachix/cachix-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-20 11:47:18 +05:30
Ajeet D'Souza 8118af567c
Update integrations 2025-03-20 11:46:13 +05:30
Ajeet D'Souza 6679619c00 bash: rewrite prompt after space-tab 2025-03-19 06:01:14 +05:30
dependabot[bot] 2ecb310108
Bump cachix/install-nix-action from 30 to 31 (#1012)
Bumps [cachix/install-nix-action](https://github.com/cachix/install-nix-action) from 30 to 31.
- [Release notes](https://github.com/cachix/install-nix-action/releases)
- [Commits](https://github.com/cachix/install-nix-action/compare/v30...v31)

---
updated-dependencies:
- dependency-name: cachix/install-nix-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-11 12:55:35 +05:30
Ajeet D'Souza 0f07314d33
Update README.md 2025-02-27 00:06:36 +05:30
Ajeet D'Souza 845fe79b5e Lazy initialize help template 2025-02-13 13:00:58 +05:30
oliviajohnsto 868a242e05
Add Warp Pack sponsorship (#978) 2025-02-10 03:44:02 +05:30
Ajeet D'Souza d74bce3b74 Fix link in CHANGELOG 2025-02-10 03:19:05 +05:30
Ajeet D'Souza 5659f3c7dc chore(release): v0.9.7 2025-02-10 03:16:52 +05:30
Ajeet D'Souza 06f9f3f27c Release v0.9.7 2025-02-10 03:10:20 +05:30
Bahex da0fdb2bae
Update nushell init script (#966) 2025-02-10 02:47:41 +05:30
Ajeet D'Souza 3fe42e901e bash doctor 2025-01-09 04:36:18 +05:30
Ajeet D'Souza 791deec8ac zsh doctor 2025-01-09 03:53:39 +05:30
Ajeet D'Souza 678bbdefbc Use POSIX implementation for ksh shells
Only ksh93 supports DEBUG traps, and the rest don't have any features
that can be used for setting up hooks. May as well use the POSIX
implementation for all ksh shells.
2025-01-09 02:19:20 +05:30
dependabot[bot] d99d82f141
Bump Swatinem/rust-cache from 2.7.5 to 2.7.7 (#963)
Bumps [Swatinem/rust-cache](https://github.com/swatinem/rust-cache) from 2.7.5 to 2.7.7.
- [Release notes](https://github.com/swatinem/rust-cache/releases)
- [Changelog](https://github.com/Swatinem/rust-cache/blob/master/CHANGELOG.md)
- [Commits](https://github.com/swatinem/rust-cache/compare/v2.7.5...v2.7.7)

---
updated-dependencies:
- dependency-name: Swatinem/rust-cache
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-31 08:12:42 +05:30
Ajeet D'Souza 1bdf393f9d Update Warp logo 2024-12-25 22:13:55 +05:30
Ben Beasley d52f6bffda
Update rstest to 0.23.0, the latest version (#937)
* Update rstest to 0.23.0 (the latest version)

* Update Cargo.lock for rstest 0.23.0
2024-11-16 03:22:46 +05:30
Ajeet D'Souza 60e870d704
Allow only one CI job at a time 2024-11-06 08:02:07 +05:30
nisbet-hubbard ede1224259 Update package info on Red Hat-based distros (#905)
---------

Co-authored-by: Ajeet D'Souza <98ajeet@gmail.com>
2024-10-16 04:37:42 +05:30
dependabot[bot] c61bdc1d54
Bump Swatinem/rust-cache from 2.7.3 to 2.7.5 (#921)
Bumps [Swatinem/rust-cache](https://github.com/swatinem/rust-cache) from 2.7.3 to 2.7.5.
- [Release notes](https://github.com/swatinem/rust-cache/releases)
- [Changelog](https://github.com/Swatinem/rust-cache/blob/master/CHANGELOG.md)
- [Commits](https://github.com/swatinem/rust-cache/compare/v2.7.3...v2.7.5)

---
updated-dependencies:
- dependency-name: Swatinem/rust-cache
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-16 04:02:18 +05:30
dependabot[bot] 7696872637
Bump cachix/install-nix-action from V28 to 30 (#912)
Bumps [cachix/install-nix-action](https://github.com/cachix/install-nix-action) from V28 to 30. This release includes the previously tagged commit.
- [Release notes](https://github.com/cachix/install-nix-action/releases)
- [Commits](https://github.com/cachix/install-nix-action/compare/V28...v30)

---
updated-dependencies:
- dependency-name: cachix/install-nix-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-16 04:02:09 +05:30
Ajeet D'Souza a0c4049bf9
Remove Windows from CI 2024-10-09 19:12:57 +05:30
Ajeet D'Souza 7113ccddea Add envrc 2024-10-06 14:27:41 +05:30
Ajeet D'Souza d5f12fccea
Update Rust in CI 2024-09-20 21:31:59 +05:30
Peter Jeschke 075fd2c695
Add note about the default hook behaviour (#890) 2024-09-20 20:41:34 +05:30
Ajeet D'Souza 6d3a711115 Remove extra import 2024-09-20 23:05:53 +08:00
Ajeet D'Souza eb9bd54e59 cargo update 2024-09-19 16:27:01 +08:00
Ajeet D'Souza 3d3267b4fd chore(release): v0.9.6 2024-09-19 16:11:26 +08:00
Ajeet D'Souza e9d5af3f95 Remove builtin from abbr 2024-09-19 15:21:34 +08:00
dependabot[bot] 991cb0a144
Bump cachix/install-nix-action from V27 to 28 (#889)
Bumps [cachix/install-nix-action](https://github.com/cachix/install-nix-action) from V27 to 28. This release includes the previously tagged commit.
- [Release notes](https://github.com/cachix/install-nix-action/releases)
- [Commits](https://github.com/cachix/install-nix-action/compare/V27...V28)

---
updated-dependencies:
- dependency-name: cachix/install-nix-action
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-17 03:38:13 +05:30
Ajeet D'Souza 4403326d58
Update ksh instructions 2024-09-13 07:29:36 +05:30
Ajeet D'Souza 55ffe7446d chore(release): v0.9.5 2024-09-13 06:17:34 +05:30
Ajeet D'Souza efd49e7f3d Handle symlinked database files correctly 2024-09-13 06:05:41 +05:30
Ajeet D'Souza 450433644f Add symlinks to the database 2024-09-13 05:44:35 +05:30
Ajeet D'Souza c1d7c4f4c7
Add support for ksh (#885) 2024-09-13 05:00:42 +05:30
Ajeet D'Souza a1be4012e0 fish: fix typo 2024-09-12 22:37:47 +05:30
Ajeet D'Souza dc0d039be2 fish: use cd from data_dir 2024-09-12 04:43:06 +05:30
Ajeet D'Souza 1ef6d5b8fc fish: Jump to directory from interactive selector (experimental) 2024-09-12 04:42:17 +05:30
Ajeet D'Souza 878b41c937
Use macos-latest 2024-09-07 23:16:07 +05:30
Guillaume Gomez 550bca6458
Switch from askama to rinja (#879) 2024-09-02 13:28:30 +05:30
phanium 297499a4fe
fix(fish): prefix builtin for all non-reserved words (#865) 2024-08-03 23:12:09 +05:30
Han Li d655e026f5
Support `z -- dir` for zsh and fish (#858) 2024-07-20 10:49:43 +05:30
solodov 8da8f50eaa
support autocd option (#695)
* support autocd option

In bash, when autocd option is set and user enters a directory name as a
command, it results in a very specific call to cd:

cd -- [directory name]

zoxide's directory changing function passes all arguments to __zoxide_z as is,
including the "--" first argument. By detecting this and skipping the first
argument changing directory works with autocd set.

* remove directory check

just skip the first argument and pass the rest as is. checking for directory
breaks cd'ing to symlinked directories

* undo some of the hackery

tests are failing
2024-06-25 22:47:33 +05:30
Ajeet D'Souza b881866216
Verify that _ZO_DATA_DIR is an absolute path 2024-06-20 20:41:20 +05:30
Ajeet D'Souza dbe6f185cf
Remove --select-1 2024-06-03 13:04:07 +05:30
Ajeet D'Souza 063f9c1632
Add i686-unknown-linux under releases (#833) 2024-05-30 02:48:56 +05:30
alaviss 0dfe1c4073
fix(elvish): before-chdir should assign to oldpwd upvalue (#818)
elvish uses lexical scoping for closure capture, as such all `oldpwd`
references within the script refers to the `oldpwd` defined at the top.
However, before-chdir hook is trying to assign to `oldpwd` within the
editor scope, which is not used by this script.

This manifested as a bug in which:

```
~
> mkdir -p /tmp/another

~
> z /tmp

/tmp
> z another

/tmp/another
> z -

~
> # The previous dir should be /tmp not ~!
```

Because the hook was updating a variable that was not used.

Fix the hook so that before-chdir assign to the proper upvalue.
2024-05-29 15:06:28 +05:30
dedebenui 1a4c4933ca
fixed nushell init for new `path type` behavior (#830) 2024-05-29 13:15:56 +05:30
dependabot[bot] df0f6e525c
--- (#824)
updated-dependencies:
- dependency-name: cachix/cachix-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-21 09:17:24 +05:30
dependabot[bot] 8d28840a89
--- (#823)
updated-dependencies:
- dependency-name: cachix/install-nix-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-21 09:16:51 +05:30
huajingyun 226aa66c3b
Update Cargo.lock (#817) 2024-05-16 23:09:05 +05:30
Ajeet D'Souza e2891634e2
Feature alfred-zoxide on README 2024-05-12 03:17:13 +05:30
Ajeet D'Souza 796fee720e
Add build for Android (#814) 2024-05-11 18:01:57 +05:30
Ajeet D'Souza ae33940331
chmod -- doesn't work on macOS 2024-05-10 18:07:19 +05:30
Ajeet D'Souza 1cb6312fb2 Return 0 only for Space+Tab 2024-05-06 10:47:50 +05:30
Aaron Dill 801d5e2f22
New installer options (v2) (#672)
Adds support for serveral new command line options (taken from the usage):
    - `--bin-dir   Override the bin installation directory`
    - `--man-dir   Override the man installation directory`
    - `--arch      Override the architecture identified by the installer`
    - `--sudo      Override the default sudo command`
    - `-h, --help      Display this help message`

---------

Co-authored-by: Ajeet D'Souza <98ajeet@gmail.com>
2024-05-06 02:51:23 +05:30
Ajeet D'Souza 4cba9808ff
Lazily delete excluded directories (#809) 2024-05-05 19:48:33 +05:30
gi1242 208bb6375e
zsh: better local directory completion (#787) 2024-05-05 19:40:29 +05:30
Ashley Bartlett 5d8a7ea7b2
fix: Space-Tab interactive completions repeating (#785) 2024-04-13 02:30:59 +05:30
David Legrand 36f440f3e3
docs: add install instructions for Exherbo Linux in README.md (#783) 2024-04-13 02:12:00 +05:30
Ajeet D'Souza 9f67fb5bb9
Add yazi integration 2024-03-30 02:07:55 +05:30
Ajeet D'Souza 94d3cba60e nushell: handle queries that look like args (#761) 2024-03-16 23:10:35 +05:30
Ajeet D'Souza 5b2c9222f9
pwsh: handle queries that look like args (#760) 2024-03-16 12:30:19 +05:30
Anselm Schüler 88d494fc2d
Fix handling of directories that look like flags in fish (#605) 2024-03-16 11:31:42 +05:30
dependabot[bot] 73a2eca43c
Bump softprops/action-gh-release from 1 to 2 (#751)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-13 23:00:15 +05:30
dependabot[bot] 06f6ed56b5
Bump cachix/install-nix-action from 25 to 26 (#752)
Bumps [cachix/install-nix-action](https://github.com/cachix/install-nix-action) from 25 to 26.
- [Release notes](https://github.com/cachix/install-nix-action/releases)
- [Commits](https://github.com/cachix/install-nix-action/compare/v25...v26)

---
updated-dependencies:
- dependency-name: cachix/install-nix-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-13 23:00:04 +05:30
xfzv 18001773f3
Add Gentoo repository (#743) 2024-03-05 10:36:09 +05:30
Ajeet D'Souza 012c67de63
Detect infinite loop on Fish (#732) 2024-02-24 04:00:38 +05:30
Ajeet D'Souza 65941f60a4
Highlight instructions 2024-02-22 23:47:39 +05:30
42 changed files with 1609 additions and 862 deletions

1
.envrc Normal file
View File

@ -0,0 +1 @@
use nix

View File

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

View File

@ -1,6 +1,8 @@
name: release
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
env:
CARGO_INCREMENTAL: 0
@ -21,12 +23,18 @@ jobs:
target: arm-unknown-linux-musleabihf
- os: ubuntu-latest
target: armv7-unknown-linux-musleabihf
deb: true
- os: ubuntu-latest
target: aarch64-unknown-linux-musl
deb: true
- os: macos-11
- os: ubuntu-latest
target: i686-unknown-linux-musl
deb: true
- os: ubuntu-latest
target: aarch64-linux-android
- os: macos-latest
target: x86_64-apple-darwin
- os: macos-11
- os: macos-latest
target: aarch64-apple-darwin
- os: windows-latest
target: x86_64-pc-windows-msvc
@ -34,7 +42,7 @@ jobs:
target: aarch64-pc-windows-msvc
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Get version
@ -51,9 +59,15 @@ jobs:
override: true
target: ${{ matrix.target }}
- name: Setup cache
uses: Swatinem/rust-cache@v2.7.3
uses: Swatinem/rust-cache@v2.8.1
with:
key: ${{ matrix.target }}
- name: Install cross
if: ${{ runner.os == 'Linux' }}
uses: actions-rs/cargo@v1
with:
command: install
args: --color=always --git=https://github.com/cross-rs/cross.git --locked --rev=e281947ca900da425e4ecea7483cfde646c8a1ea --verbose cross
- name: Build binary
uses: actions-rs/cargo@v1
with:
@ -96,7 +110,7 @@ jobs:
- name: Create release
if: |
github.ref == 'refs/heads/main' && startsWith(github.event.head_commit.message, 'chore(release)')
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
draft: true
files: |

View File

@ -7,11 +7,85 @@ 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/),
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
### Added
- Zsh: improved `cd` completions.
- Lazily delete excluded directories from the database.
- Fish: detect infinite loop when using `alias cd=z`.
- Installer: added flags for `--bin-dir`, `--man-dir`, `--arch`, and `--sudo`.
- Nushell: support for v0.94.0+.
- Bash/Fish/Zsh: support for `z -- dir` style queries.
- Fish: improved Space-Tab completions.
- Ksh: added support for the Korn shell.
### Changed
- fzf: removed `--select-1` from default options. The interactive selector will
now open up even if there is only one match.
- Enforce that `$_ZO_DATA_DIR` is an absolute path.
### Fixed
- Zsh: Space-Tab completion repeating output multiple times when matching single
directory
- Fish / Nushell / PowerShell: handle queries that look like args (e.g. `z -x`).
- Elvish: `z -` now works as expected.
- Fish: generated shell code avoids using aliased builtins.
- Fish: `cd` command is now copied directly from
`$__fish_data_dir/functions/cd.fish`. This should minimize the chances of an
infinite loop when aliasing `cd=z`.
- Symlinks not getting added to the database when `$_ZO_RESOLVE_SYMLINKS=0`.
- Symlinked database files getting replaced instead of the actual files.
## [0.9.4] - 2024-02-21
### Changed
- zsh: improved Space-Tab completions.
- Zsh: improved Space-Tab completions.
## [0.9.3] - 2024-02-13
@ -253,9 +327,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- `cd -` on fish shells.
- `cd -` on Fish shells.
- `__zoxide_hook` no longer changes value of `$?` within `$PROMPT_COMMAND` on
bash.
Bash.
### Removed
@ -294,7 +368,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `$_ZO_EXCLUDE_DIRS` now supports globs.
- `zoxide init` now defines `__zoxide_z*` functions that can be aliased as
needed.
- Support for the [xonsh](https://xon.sh/) shell.
- Support for the [Xonsh](https://xon.sh/) shell.
- `zoxide import` can now import from Autojump.
### Changed
@ -303,7 +377,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Clobber conflicting alias definitions in bash/fish/zsh/POSIX shells.
- Clobber conflicting alias definitions in Bash/Fish/Zsh/POSIX shells.
### Removed
@ -314,7 +388,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Bug in Fish init script
- Bug in Fish init script.
## [0.4.2] - 2020-07-03
@ -339,7 +413,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Support for powershell.
- Support for PowerShell.
### Removed
@ -367,7 +441,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### 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
@ -407,7 +481,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Incorrect exit codes in `z` command on fish.
- Incorrect exit codes in `z` command on Fish.
### Removed
@ -420,7 +494,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `$_ZO_ECHO` to echo match before `cd`ing.
- Minimal `ranger` plugin.
- 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`.
### Fixed
@ -434,11 +508,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `init` subcommand to remove dependency on shell plugin managers.
- Support for `z -` command to go to previous directory.
- `Cargo.lock` for more reproducible builds.
- Support for the fish shell.
- Support for the Fish shell.
### Fixed
- `_zoxide_precmd` overriding other precmd hooks on zsh.
- `_zoxide_precmd` overriding other precmd hooks on Zsh.
## [0.1.1] - 2020-03-08
@ -460,8 +534,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- GitHub Actions pipeline to build and upload releases.
- Support for zsh.
- Add 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.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.2]: https://github.com/ajeetdsouza/zoxide/compare/v0.9.1...v0.9.2

691
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

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

169
README.md
View File

@ -11,18 +11,15 @@
<sup>Special thanks to:</sup>
<a href="https://www.warp.dev/?utm_source=github&utm_medium=referral&utm_campaign=zoxide_20231001">
<div>
<img src="contrib/warp.png" width="230" alt="Warp" />
</div>
<b>
Warp is a modern, Rust-based terminal with AI built in so you and your team
can build great software, faster.
</b>
<div>
<sup>Visit <u>warp.dev</u> to learn more.</sup>
</div>
</a>
<!-- markdownlint-disable-next-line MD013 -->
<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><sup><b>Warp, built for coding with multiple AI agents.</b></sup></div>
<div><sup>Available for macOS, Linux, and Windows.</sup></div>
<div><sup>
Visit
<a href="https://go.warp.dev/zoxide"><u>warp.dev</u></a>
to learn more.
</sup></div>
<hr />
@ -81,35 +78,40 @@ zoxide can be installed in 4 easy steps:
> The recommended way to install zoxide is via the install script:
>
> ```sh
> curl -sS https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | bash
> curl -sSfL https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh
> ```
>
> Or, you can use a package manager:
>
> | Distribution | Repository | Instructions |
> | ------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
> | **_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_ | [conda-forge] | `conda install -c conda-forge zoxide` |
> | _Any_ | [guix] | `guix install zoxide` |
> | _Any_ | [Linuxbrew] | `brew install zoxide` |
> | _Any_ | [nixpkgs] | `nix-env -iA nixpkgs.zoxide` |
> | Alpine Linux 3.13+ | [Alpine Linux Packages] | `apk add zoxide` |
> | Arch Linux | [Arch Linux Extra] | `pacman -S zoxide` |
> | CentOS 7+ | [Copr] | `dnf copr enable atim/zoxide` <br /> `dnf install zoxide` |
> | ~Debian 11+~[^1] | ~[Debian Packages]~ | ~`apt install zoxide`~ |
> | Devuan 4.0+ | [Devuan Packages] | `apt install zoxide` |
> | Fedora 32+ | [Fedora Packages] | `dnf install zoxide` |
> | Gentoo | [GURU Overlay] | `eselect repository enable guru` <br /> `emerge --sync guru` <br /> `emerge app-shells/zoxide` |
> | Manjaro | | `pacman -S zoxide` |
> | openSUSE Tumbleweed | [openSUSE Factory] | `zypper install zoxide` |
> | ~Parrot OS~[^1] | | ~`apt install zoxide`~ |
> | ~Raspbian 11+~[^1] | ~[Raspbian Packages]~ | ~`apt install zoxide`~ |
> | Rhino Linux | [Pacstall Packages] | `pacstall -I zoxide-deb` |
> | Slackware 15.0+ | [SlackBuilds] | [Instructions][slackbuilds-howto] |
> | Solus | [Solus Packages] | `eopkg install zoxide` |
> | ~Ubuntu 21.04+~[^1] | ~[Ubuntu Packages]~ | ~`apt install zoxide`~ |
> | Void Linux | [Void Linux Packages] | `xbps-install -S zoxide` |
> | Distribution | Repository | Instructions |
> | ------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------- |
> | **_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_ | [conda-forge] | `conda install -c conda-forge zoxide` |
> | _Any_ | [guix] | `guix install zoxide` |
> | _Any_ | [Linuxbrew] | `brew install zoxide` |
> | _Any_ | [nixpkgs] | `nix-env -iA nixpkgs.zoxide` |
> | AlmaLinux | | `dnf install zoxide` |
> | Alpine Linux 3.13+ | [Alpine Linux Packages] | `apk add zoxide` |
> | Arch Linux | [Arch Linux Extra] | `pacman -S zoxide` |
> | CentOS Stream | | `dnf install zoxide` |
> | ~Debian 11+~[^1] | ~[Debian 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` |
> | Fedora 32+ | [Fedora Packages] | `dnf install zoxide` |
> | Gentoo | [Gentoo Packages] | `emerge app-shells/zoxide` |
> | Linux Mint | [apt.cli.rs] (unofficial) | [Setup the repository][apt.cli.rs-setup], then `apt install zoxide` |
> | Manjaro | | `pacman -S zoxide` |
> | openSUSE Tumbleweed | [openSUSE Factory] | `zypper install zoxide` |
> | ~Parrot OS~[^1] | | ~`apt install zoxide`~ |
> | ~Raspbian 11+~[^1] | ~[Raspbian Packages]~ | ~`apt install zoxide`~ |
> | RHEL 8+ | | `dnf install zoxide` |
> | Rhino Linux | [Pacstall Packages] | `pacstall -I zoxide-deb` |
> | Rocky Linux | | `dnf install 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>
@ -130,7 +132,7 @@ zoxide can be installed in 4 easy steps:
> Or, run this command in your terminal:
>
> ```sh
> curl -sS https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | bash
> curl -sSfL https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh
> ```
</details>
@ -155,6 +157,12 @@ zoxide can be installed in 4 easy steps:
> | [Chocolatey] | `choco install zoxide` |
> | [conda-forge] | `conda install -c conda-forge zoxide` |
> | [Scoop] | `scoop install zoxide` |
>
> If you're using Cygwin, Git Bash, or MSYS2, you can also use the install script:
>
> ```sh
> curl -sSfL https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | sh
> ```
</details>
@ -186,6 +194,12 @@ zoxide can be installed in 4 easy steps:
> | Repository | Instructions |
> | ---------- | -------------------- |
> | [Termux] | `pkg install zoxide` |
>
> Or, run this command in your terminal:
>
> ```sh
> curl -sS https://raw.githubusercontent.com/ajeetdsouza/zoxide/main/install.sh | bash
> ```
</details>
@ -196,7 +210,7 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Bash</summary>
> Add this to the **end** of your config file (usually `~/.bashrc`):
> Add this to the <ins>**end**</ins> of your config file (usually `~/.bashrc`):
>
> ```sh
> eval "$(zoxide init bash)"
@ -207,7 +221,7 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Elvish</summary>
> Add this to the **end** of your config file (usually `~/.elvish/rc.elv`):
> Add this to the <ins>**end**</ins> of your config file (usually `~/.elvish/rc.elv`):
>
> ```sh
> eval (zoxide init elvish | slurp)
@ -221,10 +235,10 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Fish</summary>
> Add this to the **end** of your config file (usually
> Add this to the <ins>**end**</ins> of your config file (usually
> `~/.config/fish/config.fish`):
>
> ```fish
> ```sh
> zoxide init fish | source
> ```
@ -233,14 +247,14 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Nushell</summary>
> Add this to the **end** of your env file (find it by running `$nu.env-path`
> Add this to the <ins>**end**</ins> of your env file (find it by running `$nu.env-path`
> in Nushell):
>
> ```sh
> zoxide init nushell | save -f ~/.zoxide.nu
> ```
>
> Now, add this to the **end** of your config file (find it by running
> Now, add this to the <ins>**end**</ins> of your config file (find it by running
> `$nu.config-path` in Nushell):
>
> ```sh
@ -255,7 +269,7 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>PowerShell</summary>
> Add this to the **end** of your config file (find it by running
> Add this to the <ins>**end**</ins> of your config file (find it by running
> `echo $profile` in PowerShell):
>
> ```powershell
@ -264,10 +278,22 @@ zoxide can be installed in 4 easy steps:
</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>
<summary>Xonsh</summary>
> Add this to the **end** of your config file (usually `~/.xonshrc`):
> Add this to the <ins>**end**</ins> of your config file (usually `~/.xonshrc`):
>
> ```python
> execx($(zoxide init xonsh), 'exec', __xonsh__.ctx, filename='zoxide')
@ -278,7 +304,7 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Zsh</summary>
> Add this to the **end** of your config file (usually `~/.zshrc`):
> Add this to the <ins>**end**</ins> of your config file (usually `~/.zshrc`):
>
> ```sh
> eval "$(zoxide init zsh)"
@ -293,7 +319,7 @@ zoxide can be installed in 4 easy steps:
<details>
<summary>Any POSIX shell</summary>
> Add this to the **end** of your config file:
> Add this to the <ins>**end**</ins> of your config file:
>
> ```sh
> eval "$(zoxide init posix --hook prompt)"
@ -307,7 +333,7 @@ zoxide can be installed in 4 easy steps:
interactive selection. It can be installed from [here][fzf-installation].
> **Note**
> zoxide only supports fzf v0.33.0 and above.
> The minimum supported fzf version is v0.51.0.
4. **Import your data** <sup>(optional)</sup>
@ -380,11 +406,13 @@ When calling `zoxide init`, the following flags are available:
- `--cmd cd` would replace the `cd` command.
- `--hook <HOOK>`
- Changes how often zoxide increments a directory's score:
| Hook | Description |
| -------- | --------------------------------- |
| `none` | Never |
| `prompt` | At every shell prompt |
| `pwd` | Whenever the directory is changed |
| Hook | Description |
| --------------- | --------------------------------- |
| `none` | Never |
| `prompt` | At every shell prompt |
| `pwd` (default) | Whenever the directory is changed |
- `--no-cmd`
- Prevents zoxide from defining the `z` and `zi` commands.
- These functions will still be available in your shell as `__zoxide_z` and
@ -398,11 +426,13 @@ Environment variables[^2] can be used for configuration. They must be set before
- `_ZO_DATA_DIR`
- Specifies the directory in which the database is stored.
- The default value varies across OSes:
| OS | Path | Example |
| ----------- | ---------------------------------------- | ------------------------------------------ |
| Linux / BSD | `$XDG_DATA_HOME` or `$HOME/.local/share` | `/home/alice/.local/share` |
| macOS | `$HOME/Library/Application Support` | `/Users/Alice/Library/Application Support` |
| Windows | `%LOCALAPPDATA%` | `C:\Users\Alice\AppData\Local` |
- `_ZO_ECHO`
- When set to 1, `z` will print the matched directory before navigating to
it.
@ -410,10 +440,12 @@ Environment variables[^2] can be used for configuration. They must be set before
- Excludes the specified directories from the database.
- This is provided as a list of [globs][glob], separated by OS-specific
characters:
| OS | Separator | Example |
| ------------------- | --------- | ----------------------- |
| Linux / macOS / BSD | `:` | `$HOME:$HOME/private/*` |
| Windows | `;` | `$HOME;$HOME/private/*` |
- By default, this is set to `"$HOME"`.
- `_ZO_FZF_OPTS`
- Custom options to pass to [fzf] during interactive selection. See
@ -431,6 +463,7 @@ Environment variables[^2] can be used for configuration. They must be set before
| Application | Description | Plugin |
| --------------------- | -------------------------------------------- | -------------------------- |
| [aerc] | Email client | Natively supported |
| [alfred] | macOS launcher | [alfred-zoxide] |
| [clink] | Improved cmd.exe for Windows | [clink-zoxide] |
| [emacs] | Text editor | [zoxide.el] |
| [felix] | File manager | Natively supported |
@ -438,17 +471,22 @@ Environment variables[^2] can be used for configuration. They must be set before
| [lf] | File manager | See the [wiki][lf-wiki] |
| [nnn] | File manager | [nnn-autojump] |
| [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] |
| [t] | `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] |
| [xplr] | File manager | [zoxide.xplr] |
| [xxh] | Transports shell configuration over SSH | [xxh-plugin-prerun-zoxide] |
| [yazi] | File manager | 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 |
[^1]:
Debian / Ubuntu derivatives update their packages very slowly. If you're
Debian and its derivatives update their packages very slowly. If you're
using one of these distributions, consider using the install script instead.
[^2]:
@ -456,9 +494,13 @@ Environment variables[^2] can be used for configuration. They must be set before
out the [wiki][wiki-env].
[aerc]: https://github.com/rjarry/aerc
[alfred]: https://www.alfredapp.com/
[alfred-zoxide]: https://github.com/yihou/alfred-zoxide
[algorithm-aging]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#aging
[algorithm-matching]: https://github.com/ajeetdsouza/zoxide/wiki/Algorithm#matching
[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/
[asdf]: https://github.com/asdf-vm/asdf
[builtwithnix-badge]: https://img.shields.io/badge/builtwith-nix-7d81f7?logo=nixos&logoColor=white&style=flat-square
@ -467,10 +509,10 @@ Environment variables[^2] can be used for configuration. They must be set before
[clink-zoxide]: https://github.com/shunsambongi/clink-zoxide
[clink]: https://github.com/mridgers/clink
[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]: https://crates.io/crates/zoxide
[debian packages]: https://packages.debian.org/stable/admin/zoxide
[exherbo packages]: https://gitlab.exherbo.org/exherbo/rust/-/tree/master/packages/sys-apps/zoxide
[devuan packages]: https://pkginfo.devuan.org/cgi-bin/package-query.html?c=package&q=zoxide
[downloads-badge]: https://img.shields.io/github/downloads/ajeetdsouza/zoxide/total?logo=github&logoColor=white&style=flat-square
[dports]: https://github.com/DragonFlyBSD/DPorts/tree/master/sysutils/zoxide
@ -481,9 +523,9 @@ Environment variables[^2] can be used for configuration. They must be set before
[fzf-installation]: https://github.com/junegunn/fzf#installation
[fzf-man]: https://manpages.ubuntu.com/manpages/en/man1/fzf.1.html
[fzf]: https://github.com/junegunn/fzf
[gentoo packages]: https://packages.gentoo.org/packages/app-shells/zoxide
[glob]: https://man7.org/linux/man-pages/man7/glob.7.html
[guix]: https://packages.guix.gnu.org/packages/zoxide/
[guru overlay]: https://github.com/gentoo-mirror/guru
[homebrew]: https://formulae.brew.sh/formula/zoxide
[issues]: https://github.com/ajeetdsouza/zoxide/issues/new
[joshuto]: https://github.com/kamiyaa/joshuto
@ -492,7 +534,7 @@ Environment variables[^2] can be used for configuration. They must be set before
[linuxbrew]: https://formulae.brew.sh/formula-linux/zoxide
[macports]: https://ports.macports.org/port/zoxide/summary
[neovim]: https://github.com/neovim/neovim
[nixpkgs]: https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/zoxide/default.nix
[nixpkgs]: https://github.com/NixOS/nixpkgs/blob/master/pkgs/by-name/zo/zoxide/package.nix
[nnn-autojump]: https://github.com/jarun/nnn/blob/master/plugins/autojump
[nnn]: https://github.com/jarun/nnn
[opensuse factory]: https://build.opensuse.org/package/show/openSUSE:Factory/zoxide
@ -501,25 +543,30 @@ Environment variables[^2] can be used for configuration. They must be set before
[ranger-zoxide]: https://github.com/jchook/ranger-zoxide
[ranger]: https://github.com/ranger/ranger
[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
[rfm]: https://github.com/dsxmachina/rfm
[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-howto]: https://slackbuilds.org/howto/
[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.nvim]: https://github.com/nvim-telescope/telescope.nvim
[termux]: https://github.com/termux/termux-packages/tree/master/packages/zoxide
[tmux-session-wizard]: https://github.com/27medkamal/tmux-session-wizard
[tmux-sessionx]: https://github.com/omerxx/tmux-sessionx
[tutorial]: contrib/tutorial.webp
[ubuntu packages]: https://packages.ubuntu.com/jammy/zoxide
[vim]: https://github.com/vim/vim
[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"
[xplr]: https://github.com/sayanarijit/xplr
[xxh-plugin-prerun-zoxide]: https://github.com/xxh/xxh-plugin-prerun-zoxide
[xxh]: https://github.com/xxh/xxh
[yazi]: https://github.com/sxyazi/yazi
[zabb]: https://github.com/Mellbourn/zabb
[zesh]: https://github.com/roberte777/zesh
[zoxide.el]: https://gitlab.com/Vonfry/zoxide.el
[zoxide.vim]: https://github.com/nanotee/zoxide.vim
[zoxide.xplr]: https://github.com/sayanarijit/zoxide.xplr

View File

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

View File

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

View File

@ -21,10 +21,10 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
$completions = @(switch ($command) {
'zoxide' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [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('edit', 'edit', [CompletionResultType]::ParameterValue, 'Edit the database')
[CompletionResult]::new('import', 'import', [CompletionResultType]::ParameterValue, 'Import entries from another application')
@ -34,17 +34,19 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
break
}
'zoxide;add' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[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('--score', '--score', [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('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;edit' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('decrement', 'decrement', [CompletionResultType]::ParameterValue, 'decrement')
[CompletionResult]::new('delete', 'delete', [CompletionResultType]::ParameterValue, 'delete')
[CompletionResult]::new('increment', 'increment', [CompletionResultType]::ParameterValue, 'increment')
@ -52,73 +54,74 @@ Register-ArgumentCompleter -Native -CommandName 'zoxide' -ScriptBlock {
break
}
'zoxide;edit;decrement' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;edit;delete' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;edit;increment' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;edit;reload' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;import' {
[CompletionResult]::new('--from', 'from', [CompletionResultType]::ParameterName, 'Application to import from')
[CompletionResult]::new('--merge', 'merge', [CompletionResultType]::ParameterName, 'Merge into existing database')
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--from', '--from', [CompletionResultType]::ParameterName, 'Application to import from')
[CompletionResult]::new('--merge', '--merge', [CompletionResultType]::ParameterName, 'Merge into existing database')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;init' {
[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('--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('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[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('--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('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;query' {
[CompletionResult]::new('--exclude', 'exclude', [CompletionResultType]::ParameterName, 'Exclude the current directory')
[CompletionResult]::new('-a', 'a', [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('--interactive', 'interactive', [CompletionResultType]::ParameterName, 'Use interactive selection')
[CompletionResult]::new('-l', 'l', [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('--score', 'score', [CompletionResultType]::ParameterName, 'Print score with results')
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[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('--all', '--all', [CompletionResultType]::ParameterName, 'Show unavailable directories')
[CompletionResult]::new('-i', '-i', [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('--list', '--list', [CompletionResultType]::ParameterName, 'List all matching directories')
[CompletionResult]::new('-s', '-s', [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('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
'zoxide;remove' {
[CompletionResult]::new('-h', 'h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', 'help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', 'V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', 'version', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('-h', '-h', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('--help', '--help', [CompletionResultType]::ParameterName, 'Print help')
[CompletionResult]::new('-V', '-V ', [CompletionResultType]::ParameterName, 'Print version')
[CompletionResult]::new('--version', '--version', [CompletionResultType]::ParameterName, 'Print version')
break
}
})

View File

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

View File

@ -30,6 +30,8 @@ set edit:completion:arg-completer[zoxide] = {|@words|
cand remove 'Remove a directory from the database'
}
&'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 --help 'Print help'
cand -V 'Print version'
@ -88,6 +90,7 @@ set edit:completion:arg-completer[zoxide] = {|@words|
}
&'zoxide;query'= {
cand --exclude 'Exclude the current directory'
cand --base-dir 'Only search within this directory'
cand -a 'Show unavailable directories'
cand --all 'Show unavailable directories'
cand -i 'Use interactive selection'

View File

@ -1,42 +1,73 @@
complete -c zoxide -n "__fish_use_subcommand" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_use_subcommand" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_use_subcommand" -f -a "add" -d 'Add a new directory or increment its rank'
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'
complete -c zoxide -n "__fish_use_subcommand" -f -a "init" -d 'Generate shell configuration'
complete -c zoxide -n "__fish_use_subcommand" -f -a "query" -d 'Search for a directory in the database'
complete -c zoxide -n "__fish_use_subcommand" -f -a "remove" -d 'Remove a directory from the database'
complete -c zoxide -n "__fish_seen_subcommand_from add" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from add" -s V -l version -d 'Print version'
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'
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'
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"
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"
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"
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"
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from decrement" -s h -l help -d 'Print help'
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'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from delete" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from increment" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from increment" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from reload" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from edit; and __fish_seen_subcommand_from reload" -s V -l version -d 'Print version'
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_seen_subcommand_from import" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from import" -s V -l version -d 'Print version'
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_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_seen_subcommand_from init" -l no-cmd -d 'Prevents zoxide from defining the `z` and `zi` commands'
complete -c zoxide -n "__fish_seen_subcommand_from init" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from init" -s V -l version -d 'Print version'
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_seen_subcommand_from query" -s a -l all -d 'Show unavailable directories'
complete -c zoxide -n "__fish_seen_subcommand_from query" -s i -l interactive -d 'Use interactive selection'
complete -c zoxide -n "__fish_seen_subcommand_from query" -s l -l list -d 'List all matching directories'
complete -c zoxide -n "__fish_seen_subcommand_from query" -s s -l score -d 'Print score with results'
complete -c zoxide -n "__fish_seen_subcommand_from query" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from query" -s V -l version -d 'Print version'
complete -c zoxide -n "__fish_seen_subcommand_from remove" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_seen_subcommand_from remove" -s V -l version -d 'Print version'
# Print an optspec for argparse to handle cmd's options that are independent of any subcommand.
function __fish_zoxide_global_optspecs
string join \n h/help V/version
end
function __fish_zoxide_needs_command
# Figure out if the current invocation already has a command.
set -l cmd (commandline -opc)
set -e cmd[1]
argparse -s (__fish_zoxide_global_optspecs) -- $cmd 2>/dev/null
or return
if set -q argv[1]
# Also print the command, so this can be used to figure out what it is.
echo $argv[1]
return 1
end
return 0
end
function __fish_zoxide_using_subcommand
set -l cmd (__fish_zoxide_needs_command)
test -z "$cmd"
and return 1
contains -- $cmd[1] $argv
end
complete -c zoxide -n "__fish_zoxide_needs_command" -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_zoxide_needs_command" -f -a "add" -d 'Add a new directory or increment its rank'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "edit" -d 'Edit the database'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "import" -d 'Import entries from another application'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "init" -d 'Generate shell configuration'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "query" -d 'Search for a directory in the database'
complete -c zoxide -n "__fish_zoxide_needs_command" -f -a "remove" -d 'Remove a directory from the database'
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_zoxide_using_subcommand add" -s h -l help -d 'Print help'
complete -c zoxide -n "__fish_zoxide_using_subcommand add" -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" -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" -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 "decrement"
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_zoxide_using_subcommand edit; and not __fish_seen_subcommand_from decrement delete increment reload" -f -a "increment"
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'

99
contrib/completions/zoxide.nu generated Normal file
View File

@ -0,0 +1,99 @@
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,6 +6,15 @@ const completion: Fig.Spec = {
name: "add",
description: "Add a new directory or increment its rank",
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"],
description: "Print help",
@ -185,6 +194,7 @@ const completion: Fig.Spec = {
"nushell",
"posix",
"powershell",
"tcsh",
"xonsh",
"zsh",
],
@ -204,6 +214,16 @@ const completion: Fig.Spec = {
template: "folders",
},
},
{
name: "--base-dir",
description: "Only search within this directory",
isRepeatable: true,
args: {
name: "base_dir",
isOptional: true,
template: "folders",
},
},
{
name: ["-a", "--all"],
description: "Show unavailable directories",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 817 KiB

View File

@ -1,5 +1,6 @@
#!/bin/sh
# shellcheck shell=dash
# shellcheck disable=SC3043 # Assume `local` extension
# The official zoxide installer.
#
@ -7,29 +8,35 @@
# extension. Note: Most shells limit `local` to 1 var per line, contra bash.
main() {
# The version of ksh93 that ships with many illumos systems does not support the "local"
# extension. Print a message rather than fail in subtle ways later on:
if [ "${KSH_VERSION-}" = 'Version JM 93t+ 2010-03-05' ]; then
# The version of ksh93 that ships with many illumos systems does not
# support the "local" extension. Print a message rather than fail in
# subtle ways later on:
err 'the installer does not work with this ksh93 version; please try bash'
fi
set -u
# Detect and print host target triple.
ensure get_architecture
local _arch="${RETVAL}"
parse_args "$@"
local _arch
_arch="${ARCH:-$(ensure get_architecture)}"
assert_nz "${_arch}" "arch"
echo "Detected architecture: ${_arch}"
local _bin_name
case "${_arch}" in
*windows*) _bin_name="zoxide.exe" ;;
*) _bin_name="zoxide" ;;
esac
# Create and enter a temporary directory.
local _tmp_dir
_tmp_dir="$(mktemp -d)" || err "mktemp: could not create temporary directory"
cd "${_tmp_dir}" || err "cd: failed to enter directory: ${_tmp_dir}"
# Download and extract zoxide.
ensure download_zoxide "${_arch}"
local _package="${RETVAL}"
local _package
_package="$(ensure download_zoxide "${_arch}")"
assert_nz "${_package}" "package"
echo "Downloaded package: ${_package}"
case "${_package}" in
@ -47,31 +54,77 @@ main() {
esac
# Install binary.
local _bin_dir="${HOME}/.local/bin"
local _bin_name
case "${_arch}" in
*windows*) _bin_name="zoxide.exe" ;;
*) _bin_name="zoxide" ;;
esac
ensure mkdir -p "${_bin_dir}"
ensure cp "${_bin_name}" "${_bin_dir}"
ensure chmod +x "${_bin_dir}/${_bin_name}"
echo "Installed zoxide to ${_bin_dir}"
ensure try_sudo mkdir -p -- "${BIN_DIR}"
ensure try_sudo cp -- "${_bin_name}" "${BIN_DIR}/${_bin_name}"
ensure try_sudo chmod +x "${BIN_DIR}/${_bin_name}"
echo "Installed zoxide to ${BIN_DIR}"
# Install manpages.
local _man_dir="${HOME}/.local/share/man"
ensure mkdir -p "${_man_dir}/man1"
ensure cp "man/man1/"* "${_man_dir}/man1/"
echo "Installed manpages to ${_man_dir}"
ensure try_sudo mkdir -p -- "${MAN_DIR}/man1"
ensure try_sudo cp -- "man/man1/"* "${MAN_DIR}/man1/"
echo "Installed manpages to ${MAN_DIR}"
# Print success message and check $PATH.
echo ""
echo "zoxide is installed!"
if ! echo ":${PATH}:" | grep -Fq ":${_bin_dir}:"; then
echo "NOTE: ${_bin_dir} is not on your \$PATH. zoxide will not work unless it is added to \$PATH."
if ! echo ":${PATH}:" | grep -Fq ":${BIN_DIR}:"; then
echo "Note: ${BIN_DIR} is not on your \$PATH. zoxide will not work unless it is added to \$PATH."
fi
}
# Parse the arguments passed and set variables accordingly.
parse_args() {
BIN_DIR_DEFAULT="${HOME}/.local/bin"
MAN_DIR_DEFAULT="${HOME}/.local/share/man"
SUDO_DEFAULT="sudo"
BIN_DIR="${BIN_DIR_DEFAULT}"
MAN_DIR="${MAN_DIR_DEFAULT}"
SUDO="${SUDO_DEFAULT}"
while [ "$#" -gt 0 ]; do
case "$1" in
--arch) ARCH="$2" && shift 2 ;;
--arch=*) ARCH="${1#*=}" && shift 1 ;;
--bin-dir) BIN_DIR="$2" && shift 2 ;;
--bin-dir=*) BIN_DIR="${1#*=}" && shift 1 ;;
--man-dir) MAN_DIR="$2" && shift 2 ;;
--man-dir=*) MAN_DIR="${1#*=}" && shift 1 ;;
--sudo) SUDO="$2" && shift 2 ;;
--sudo=*) SUDO="${1#*=}" && shift 1 ;;
-h | --help) usage && exit 0 ;;
*) err "Unknown option: $1" ;;
esac
done
}
usage() {
# heredocs are not defined in POSIX.
local _text_heading _text_reset
_text_heading="$(tput bold || true 2>/dev/null)$(tput smul || true 2>/dev/null)"
_text_reset="$(tput sgr0 || true 2>/dev/null)"
local _arch
_arch="$(get_architecture || true)"
echo "\
${_text_heading}zoxide installer${_text_reset}
Ajeet D'Souza <98ajeet@gmail.com>
https://github.com/ajeetdsouza/zoxide
Fetches and installs zoxide. If zoxide is already installed, it will be updated to the latest version.
${_text_heading}Usage:${_text_reset}
install.sh [OPTIONS]
${_text_heading}Options:${_text_reset}
--arch Override the architecture identified by the installer [current: ${_arch}]
--bin-dir Override the installation directory [default: ${BIN_DIR_DEFAULT}]
--man-dir Override the manpage installation directory [default: ${MAN_DIR_DEFAULT}]
--sudo Override the command used to elevate to root privileges [default: ${SUDO_DEFAULT}]
-h, --help Print help"
}
download_zoxide() {
local _arch="$1"
@ -97,7 +150,7 @@ download_zoxide() {
err "you have exceeded GitHub's API rate limit. Please try again later, or use a different installation method: https://github.com/ajeetdsouza/zoxide/#installation"
local _package_url
_package_url="$(echo "${_releases}" | grep "browser_download_url" | cut -d '"' -f 4 | grep "${_arch}")" ||
_package_url="$(echo "${_releases}" | grep "browser_download_url" | cut -d '"' -f 4 | grep -- "${_arch}")" ||
err "zoxide has not yet been packaged for your architecture (${_arch}), please file an issue: https://github.com/ajeetdsouza/zoxide/issues"
local _ext
@ -114,7 +167,30 @@ download_zoxide() {
*) err "unsupported downloader: ${_dld}" ;;
esac
RETVAL="${_package}"
echo "${_package}"
}
try_sudo() {
if "$@" >/dev/null 2>&1; then
return 0
fi
need_sudo
"${SUDO}" "$@"
}
need_sudo() {
if ! check_cmd "${SUDO}"; then
err "\
could not find the command \`${SUDO}\` needed to get permissions for install.
If you are on Windows, please run your shell as an administrator, then rerun this script.
Otherwise, please run this script as root, or install \`sudo\`."
fi
if ! "${SUDO}" -v; then
err "sudo permissions not granted, aborting installation"
fi
}
# The below functions have been extracted with minor modifications from the
@ -259,8 +335,7 @@ get_architecture() {
x86_64)
# 32-bit executable for amd64 = x32
if is_host_amd64_elf; then {
echo "x32 userland is unsupported" 1>&2
exit 1
err "x32 userland is unsupported"
}; else
_cputype=i686
fi
@ -297,7 +372,7 @@ get_architecture() {
fi
_arch="${_cputype}-${_ostype}"
RETVAL="${_arch}"
echo "${_arch}"
}
get_bitness() {
@ -320,9 +395,9 @@ get_bitness() {
}
get_endianness() {
local cputype=$1
local suffix_eb=$2
local suffix_el=$3
local cputype="$1"
local suffix_eb="$2"
local suffix_el="$3"
# detect endianness without od/hexdump, like get_bitness() does.
need_cmd head
@ -365,7 +440,7 @@ need_cmd() {
}
check_cmd() {
command -v "$1" >/dev/null 2>&1
command -v -- "$1" >/dev/null 2>&1
}
# Run a command that should never fail. If the command fails execution

View File

@ -55,6 +55,14 @@ $profile\fR in PowerShell):
\fBInvoke-Expression (& { (zoxide init powershell | Out-String) })\fR
.fi
.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
Add this to the \fBend\fR of your config file (usually \fB~/.xonshrc\fR):
.sp

View File

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

View File

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

View File

@ -1,6 +1,6 @@
use std::path::Path;
use anyhow::{bail, Result};
use anyhow::{Result, bail};
use crate::cmd::{Add, Run};
use crate::db::Database;
@ -33,7 +33,9 @@ impl Run for Add {
if !Path::new(path).is_dir() {
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() {

View File

@ -2,9 +2,14 @@
use std::path::PathBuf;
use clap::builder::{IntoResettable, Resettable, StyledStr};
use clap::{Parser, Subcommand, ValueEnum, ValueHint};
const HELP_TEMPLATE: &str = color_print::cstr!("\
struct HelpTemplate;
impl IntoResettable<StyledStr> for HelpTemplate {
fn into_resettable(self) -> Resettable<StyledStr> {
color_print::cstr!("\
{before-help}<bold><underline>{name} {version}</underline></bold>
{author}
https://github.com/ajeetdsouza/zoxide
@ -22,13 +27,15 @@ https://github.com/ajeetdsouza/zoxide
{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_MAXAGE</bold> {tab}Maximum total age after which entries start getting deleted
{tab}<bold>_ZO_RESOLVE_SYMLINKS</bold>{tab}Resolve symlinks when storing paths");
{tab}<bold>_ZO_RESOLVE_SYMLINKS</bold>{tab}Resolve symlinks when storing paths").into_resettable()
}
}
#[derive(Debug, Parser)]
#[clap(
about,
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
disable_help_subcommand = true,
propagate_version = true,
version,
@ -46,18 +53,23 @@ pub enum Cmd {
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Add {
#[clap(num_args = 1.., required = true, value_hint = ValueHint::DirPath)]
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
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Edit {
#[clap(subcommand)]
@ -80,7 +92,7 @@ pub enum EditCommand {
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Import {
#[clap(value_hint = ValueHint::FilePath)]
@ -106,7 +118,7 @@ pub enum ImportFrom {
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Init {
#[clap(value_enum)]
@ -138,8 +150,10 @@ pub enum InitShell {
Elvish,
Fish,
Nushell,
#[clap(alias = "ksh")]
Posix,
Powershell,
Tcsh,
Xonsh,
Zsh,
}
@ -148,7 +162,7 @@ pub enum InitShell {
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Query {
pub keywords: Vec<String>,
@ -172,13 +186,17 @@ pub struct Query {
/// Exclude the current directory
#[clap(long, value_hint = ValueHint::DirPath, value_name = "path")]
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
#[derive(Debug, Parser)]
#[clap(
author,
help_template = HELP_TEMPLATE,
help_template = HelpTemplate,
)]
pub struct Remove {
#[clap(value_hint = ValueHint::DirPath)]

View File

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

View File

@ -6,7 +6,7 @@ use askama::Template;
use crate::cmd::{Init, InitShell, Run};
use crate::config;
use crate::error::BrokenPipeHandler;
use crate::shell::{Bash, Elvish, Fish, Nushell, Opts, Posix, Powershell, Xonsh, Zsh};
use crate::shell::{Bash, Elvish, Fish, Nushell, Opts, Posix, Powershell, Tcsh, Xonsh, Zsh};
impl Run for Init {
fn run(&self) -> Result<()> {
@ -22,6 +22,7 @@ impl Run for Init {
InitShell::Nushell => Nushell(opts).render(),
InitShell::Posix => Posix(opts).render(),
InitShell::Powershell => Powershell(opts).render(),
InitShell::Tcsh => Tcsh(opts).render(),
InitShell::Xonsh => Xonsh(opts).render(),
InitShell::Zsh => Zsh(opts).render(),
}

View File

@ -1,10 +1,10 @@
use std::io::{self, Write};
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result};
use crate::cmd::{Query, Run};
use crate::config;
use crate::db::{Database, Epoch, Stream};
use crate::db::{Database, Epoch, Stream, StreamOptions};
use crate::error::BrokenPipeHandler;
use crate::util::{self, Fzf, FzfChild};
@ -18,59 +18,76 @@ impl Run for Query {
impl Query {
fn query(&self, db: &mut Database) -> Result<()> {
let now = util::current_time()?;
let mut stream = self.get_stream(db, now);
let mut stream = self.get_stream(db, now)?;
if self.interactive {
let mut fzf = Self::get_fzf()?;
let selection = loop {
match stream.next() {
Some(dir) => {
if let Some(selection) = fzf.write(dir, now)? {
break selection;
}
}
None => break fzf.wait()?,
}
};
if self.score {
print!("{selection}");
} else {
let path = selection.get(7..).context("could not read selection from fzf")?;
print!("{path}");
}
self.query_interactive(&mut stream, now)
} else if self.list {
let handle = &mut io::stdout().lock();
while let Some(dir) = stream.next() {
let dir = if self.score { dir.display().with_score(now) } else { dir.display() };
writeln!(handle, "{dir}").pipe_exit("stdout")?;
}
self.query_list(&mut stream, now)
} else {
let handle = &mut io::stdout();
let Some(dir) = stream.next() else {
bail!(if stream.did_exclude() {
"you are already in the only match"
} else {
"no match found"
});
};
let dir = if self.score { dir.display().with_score(now) } else { dir.display() };
writeln!(handle, "{dir}").pipe_exit("stdout")?;
self.query_first(&mut stream, now)
}
}
fn query_interactive(&self, stream: &mut Stream, now: Epoch) -> Result<()> {
let mut fzf = Self::get_fzf()?;
let selection = loop {
match stream.next() {
Some(dir) if Some(dir.path.as_ref()) == self.exclude.as_deref() => continue,
Some(dir) => {
if let Some(selection) = fzf.write(dir, now)? {
break selection;
}
}
None => break fzf.wait()?,
}
};
if self.score {
print!("{selection}");
} else {
let path = selection.get(7..).context("could not read selection from fzf")?;
print!("{path}");
}
Ok(())
}
fn get_stream<'a>(&self, db: &'a mut Database, now: Epoch) -> Stream<'a> {
let mut stream = db.stream(now).with_keywords(&self.keywords);
fn query_list(&self, stream: &mut Stream, now: Epoch) -> Result<()> {
let handle = &mut io::stdout().lock();
while let Some(dir) = stream.next() {
if Some(dir.path.as_ref()) == self.exclude.as_deref() {
continue;
}
let dir = if self.score { dir.display().with_score(now) } else { dir.display() };
writeln!(handle, "{dir}").pipe_exit("stdout")?;
}
Ok(())
}
fn query_first(&self, stream: &mut Stream, now: Epoch) -> Result<()> {
let handle = &mut io::stdout();
let mut dir = stream.next().context("no match found")?;
while Some(dir.path.as_ref()) == self.exclude.as_deref() {
dir = stream.next().context("you are already in the only match")?;
}
let dir = if self.score { dir.display().with_score(now) } else { dir.display() };
writeln!(handle, "{dir}").pipe_exit("stdout")
}
fn get_stream<'a>(&self, db: &'a mut Database, now: Epoch) -> Result<Stream<'a>> {
let mut options = StreamOptions::new(now)
.with_keywords(self.keywords.iter().map(|s| s.as_str()))
.with_exclude(config::exclude_dirs()?)
.with_base_dir(self.base_dir.clone());
if !self.all {
let resolve_symlinks = config::resolve_symlinks();
stream = stream.with_exists(resolve_symlinks);
options = options.with_exists(true).with_resolve_symlinks(resolve_symlinks);
}
if let Some(path) = &self.exclude {
stream = stream.with_exclude(path);
}
stream
let stream = Stream::new(db, options);
Ok(stream)
}
fn get_fzf() -> Result<FzfChild> {
@ -96,7 +113,6 @@ impl Query {
"--tabstop=1",
// Scripting
"--exit-0",
"--select-1",
])
.enable_preview()
}

View File

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

View File

@ -2,23 +2,25 @@ use std::env;
use std::ffi::OsString;
use std::path::PathBuf;
use anyhow::{Context, Result};
use anyhow::{Context, Result, ensure};
use glob::Pattern;
use crate::db::Rank;
pub fn data_dir() -> Result<PathBuf> {
let path = match env::var_os("_ZO_DATA_DIR") {
let dir = match env::var_os("_ZO_DATA_DIR") {
Some(path) => PathBuf::from(path),
None => dirs::data_local_dir()
.context("could not find data directory, please set _ZO_DATA_DIR manually")?
.join("zoxide"),
};
Ok(path)
ensure!(dir.is_absolute(), "_ZO_DATA_DIR must be an absolute path");
Ok(dir)
}
pub fn echo() -> bool {
env::var_os("_ZO_ECHO").map_or(false, |var| var == "1")
env::var_os("_ZO_ECHO").is_some_and(|var| var == "1")
}
pub fn exclude_dirs() -> Result<Vec<Pattern>> {
@ -56,5 +58,5 @@ pub fn maxage() -> Result<Rank> {
}
pub fn resolve_symlinks() -> bool {
env::var_os("_ZO_RESOLVE_SYMLINKS").map_or(false, |var| var == "1")
env::var_os("_ZO_RESOLVE_SYMLINKS").is_some_and(|var| var == "1")
}

View File

@ -4,12 +4,12 @@ mod stream;
use std::path::{Path, PathBuf};
use std::{fs, io};
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result, bail};
use bincode::Options;
use ouroboros::self_referencing;
pub use crate::db::dir::{Dir, Epoch, Rank};
pub use crate::db::stream::Stream;
pub use crate::db::stream::{Stream, StreamOptions};
use crate::{config, util};
#[self_referencing]
@ -33,6 +33,7 @@ impl Database {
pub fn open_dir(data_dir: impl AsRef<Path>) -> Result<Self> {
let data_dir = data_dir.as_ref();
let path = data_dir.join("db.zo");
let path = fs::canonicalize(&path).unwrap_or(path);
match fs::read(&path) {
Ok(bytes) => Self::try_new(path, bytes, |bytes| Self::deserialize(bytes), false),
@ -135,10 +136,6 @@ impl Database {
self.with_dirty_mut(|dirty_prev| *dirty_prev |= dirty);
}
pub fn stream(&mut self, now: Epoch) -> Stream {
Stream::new(self, now)
}
pub fn dedup(&mut self) {
// Sort by path, so that equal paths are next to each other.
self.sort_by_path();
@ -186,7 +183,7 @@ impl Database {
*self.borrow_dirty()
}
pub fn dirs(&self) -> &[Dir] {
pub fn dirs(&self) -> &[Dir<'_>] {
self.borrow_dirs()
}
@ -206,7 +203,7 @@ impl 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
// strange errors when it encounters invalid data.
const MAX_SIZE: u64 = 32 << 20; // 32 MiB

View File

@ -1,81 +1,51 @@
use std::iter::Rev;
use std::ops::Range;
use std::path::Path;
use std::{fs, path};
use glob::Pattern;
use crate::db::{Database, Dir, Epoch};
use crate::util::{self, MONTH};
pub struct Stream<'a> {
// State
db: &'a mut Database,
idxs: Rev<Range<usize>>,
did_exclude: bool,
// Configuration
keywords: Vec<String>,
check_exists: bool,
expire_below: Epoch,
resolve_symlinks: bool,
exclude_path: Option<String>,
options: StreamOptions,
}
impl<'a> Stream<'a> {
pub fn new(db: &'a mut Database, now: Epoch) -> Self {
db.sort_by_score(now);
pub fn new(db: &'a mut Database, options: StreamOptions) -> Self {
db.sort_by_score(options.now);
let idxs = (0..db.dirs().len()).rev();
// If a directory is deleted and hasn't been used for 3 months, delete
// it from the database.
let expire_below = now.saturating_sub(3 * MONTH);
Stream {
db,
idxs,
did_exclude: false,
keywords: Vec::new(),
check_exists: false,
expire_below,
resolve_symlinks: false,
exclude_path: None,
}
Stream { db, idxs, options }
}
pub fn with_exclude(mut self, path: impl Into<String>) -> Self {
self.exclude_path = Some(path.into());
self
}
pub fn with_exists(mut self, resolve_symlinks: bool) -> Self {
self.check_exists = true;
self.resolve_symlinks = resolve_symlinks;
self
}
pub fn with_keywords(mut self, keywords: &[impl AsRef<str>]) -> Self {
self.keywords = keywords.iter().map(util::to_lowercase).collect();
self
}
pub fn next(&mut self) -> Option<&Dir> {
pub fn next(&mut self) -> Option<&Dir<'_>> {
while let Some(idx) = self.idxs.next() {
let dir = &self.db.dirs()[idx];
if !self.matches_keywords(&dir.path) {
if !self.filter_by_keywords(&dir.path) {
continue;
}
if !self.matches_exists(&dir.path) {
if dir.last_accessed < self.expire_below {
if !self.filter_by_base_dir(&dir.path) {
continue;
}
if !self.filter_by_exclude(&dir.path) {
self.db.swap_remove(idx);
continue;
}
// Exists queries are slow, this should always be checked last.
if !self.filter_by_exists(&dir.path) {
if dir.last_accessed < self.options.ttl {
self.db.swap_remove(idx);
}
continue;
}
if Some(dir.path.as_ref()) == self.exclude_path.as_deref() {
self.did_exclude = true;
continue;
}
let dir = &self.db.dirs()[idx];
return Some(dir);
}
@ -83,20 +53,32 @@ impl<'a> Stream<'a> {
None
}
pub fn did_exclude(&self) -> bool {
self.did_exclude
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 matches_exists(&self, path: &str) -> bool {
if !self.check_exists {
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;
}
let resolver = if self.resolve_symlinks { fs::symlink_metadata } else { fs::metadata };
resolver(path).map(|m| m.is_dir()).unwrap_or_default()
// 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 matches_keywords(&self, path: &str) -> bool {
let (keywords_last, keywords) = match self.keywords.split_last() {
fn filter_by_keywords(&self, path: &str) -> bool {
let (keywords_last, keywords) = match self.options.keywords.split_last() {
Some(split) => split,
None => return true,
};
@ -124,6 +106,74 @@ impl<'a> Stream<'a> {
}
}
pub struct StreamOptions {
/// The current time.
now: Epoch,
/// Only directories matching these keywords will be returned.
keywords: Vec<String>,
/// Directories that match any of these globs will be lazily removed.
exclude: Vec<Pattern>,
/// Directories will only be returned if they exist on the filesystem.
exists: bool,
/// Whether to resolve symlinks when checking if a directory exists.
resolve_symlinks: bool,
/// Directories that do not exist and haven't been accessed since TTL will
/// be lazily removed.
ttl: Epoch,
/// Only return directories within this parent directory
/// Does not check if the path exists
base_dir: Option<String>,
}
impl StreamOptions {
pub fn new(now: Epoch) -> Self {
StreamOptions {
now,
keywords: Vec::new(),
exclude: Vec::new(),
exists: false,
resolve_symlinks: false,
ttl: now.saturating_sub(3 * MONTH),
base_dir: None,
}
}
pub fn with_keywords<I>(mut self, keywords: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
self.keywords = keywords.into_iter().map(util::to_lowercase).collect();
self
}
pub fn with_exclude(mut self, exclude: Vec<Pattern>) -> Self {
self.exclude = exclude;
self
}
pub fn with_exists(mut self, exists: bool) -> Self {
self.exists = exists;
self
}
pub fn with_resolve_symlinks(mut self, resolve_symlinks: bool) -> Self {
self.resolve_symlinks = resolve_symlinks;
self
}
pub fn with_base_dir(mut self, base_dir: Option<String>) -> Self {
self.base_dir = base_dir;
self
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
@ -154,7 +204,8 @@ mod tests {
#[case(&["/foo/", "/bar"], "/foo/baz/bar", true)]
fn query(#[case] keywords: &[&str], #[case] path: &str, #[case] is_match: bool) {
let db = &mut Database::new(PathBuf::new(), Vec::new(), |_| Vec::new(), false);
let stream = Stream::new(db, 0).with_keywords(keywords);
assert_eq!(is_match, stream.matches_keywords(path));
let options = StreamOptions::new(0).with_keywords(keywords.iter());
let stream = Stream::new(db, options);
assert_eq!(is_match, stream.filter_by_keywords(path));
}
}

View File

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

View File

@ -1,9 +1,5 @@
#![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 config;
mod db;
@ -22,8 +18,8 @@ use crate::error::SilentExit;
pub fn main() -> ExitCode {
// Forcibly disable backtraces.
env::remove_var("RUST_LIB_BACKTRACE");
env::remove_var("RUST_BACKTRACE");
unsafe { env::remove_var("RUST_LIB_BACKTRACE") };
unsafe { env::remove_var("RUST_BACKTRACE") };
match Cmd::parse().run() {
Ok(()) => ExitCode::SUCCESS,

View File

@ -29,6 +29,7 @@ make_template!(Fish, "fish.txt");
make_template!(Nushell, "nushell.txt");
make_template!(Posix, "posix.txt");
make_template!(Powershell, "powershell.txt");
make_template!(Tcsh, "tcsh.txt");
make_template!(Xonsh, "xonsh.txt");
make_template!(Zsh, "zsh.txt");
@ -70,7 +71,7 @@ mod tests {
let source = Bash(&opts).render().unwrap();
Command::new("shellcheck")
.args(["--enable", "all", "--shell", "bash", "-"])
.args(["--enable=all", "-"])
.write_stdin(source)
.assert()
.success()
@ -96,7 +97,7 @@ mod tests {
#[apply(opts)]
fn elvish_elvish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let mut source = String::default();
let mut source = String::new();
// Filter out lines using edit:*, since those functions are only available in
// the interactive editor.
@ -113,6 +114,16 @@ mod tests {
.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)]
fn fish_fish(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
@ -196,12 +207,12 @@ mod tests {
}
#[apply(opts)]
fn posix_shellcheck_(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
fn posix_shellcheck(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
let source = Posix(&opts).render().unwrap();
Command::new("shellcheck")
.args(["--enable", "all", "--shell", "sh", "-"])
.args(["--enable=all", "-"])
.write_stdin(source)
.assert()
.success()
@ -238,6 +249,20 @@ mod tests {
.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)]
fn xonsh_black(cmd: Option<&str>, hook: InitHook, echo: bool, resolve_symlinks: bool) {
let opts = Opts { cmd, hook, echo, resolve_symlinks };
@ -298,7 +323,7 @@ mod tests {
// ShellCheck doesn't support zsh yet: https://github.com/koalaman/shellcheck/issues/809
Command::new("shellcheck")
.args(["--enable", "all", "--shell", "bash", "-"])
.args(["--enable=all", "-"])
.write_stdin(source)
.assert()
.success()

View File

@ -8,7 +8,7 @@ use std::{env, mem};
#[cfg(windows)]
use anyhow::anyhow;
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result, bail};
use crate::db::{Dir, Epoch};
use crate::error::SilentExit;
@ -135,7 +135,7 @@ impl FzfChild {
mem::drop(self.0.stdin.take());
let mut stdout = self.0.stdout.take().unwrap();
let mut output = String::default();
let mut output = String::new();
stdout.read_to_string(&mut output).context("failed to read from fzf")?;
let status = self.0.wait().context("wait failed on fzf")?;
@ -169,16 +169,21 @@ pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
#[cfg(unix)]
if let Ok(metadata) = path.metadata() {
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use nix::unistd::{self, Gid, Uid};
let uid = Uid::from_raw(metadata.uid());
let gid = Gid::from_raw(metadata.gid());
_ = unistd::fchown(tmp_file.as_raw_fd(), Some(uid), Some(gid));
_ = unistd::fchown(&tmp_file, Some(uid), Some(gid));
}
// 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);
rename(&tmp_path, path)
})();

View File

@ -1,6 +1,8 @@
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
# shellcheck shell=bash
{{ section }}
# Utility functions for zoxide.
#
@ -25,11 +27,8 @@ function __zoxide_cd() {
{{ section }}
# Hook configuration for zoxide.
#
{%- if hook != InitHook::None %}
{% if hook == InitHook::None -%}
{{ not_configured }}
{%- else -%}
# Hook to add new entries to the database.
{%- if hook == InitHook::Prompt %}
function __zoxide_hook() {
@ -38,6 +37,7 @@ function __zoxide_hook() {
\command zoxide add -- "$(__zoxide_pwd)"
return "${retval}"
}
{%- else if hook == InitHook::Pwd %}
__zoxide_oldpwd="$(__zoxide_pwd)"
@ -58,7 +58,32 @@ if [[ ${PROMPT_COMMAND:=} != *'__zoxide_hook'* ]]; then
PROMPT_COMMAND="__zoxide_hook;${PROMPT_COMMAND#;}"
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 }}
# When using zoxide with --no-cmd, alias these internal functions as desired.
@ -68,6 +93,8 @@ __zoxide_z_prefix='z#'
# Jump to a directory using only keywords.
function __zoxide_z() {
__zoxide_doctor
# shellcheck disable=SC2199
if [[ $# -eq 0 ]]; then
__zoxide_cd ~
@ -75,6 +102,8 @@ function __zoxide_z() {
__zoxide_cd "${OLDPWD}"
elif [[ $# -eq 1 && -d $1 ]]; then
__zoxide_cd "$1"
elif [[ $# -eq 2 && $1 == '--' ]]; then
__zoxide_cd "$2"
elif [[ ${@: -1} == "${__zoxide_z_prefix}"?* ]]; then
# shellcheck disable=SC2124
\builtin local result="${@: -1}"
@ -89,6 +118,7 @@ function __zoxide_z() {
# Jump to a directory using interactive search.
function __zoxide_zi() {
__zoxide_doctor
\builtin local result
result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}"
}
@ -117,8 +147,13 @@ function {{cmd}}i() {
# - 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 ]] &&
[[ :"${SHELLOPTS}": =~ :(vi|emacs): && ${TERM} != 'dumb' ]]; then
# Use `printf '\e[5n'` to redraw line after fzf closes.
\builtin bind '"\e[0n": redraw-current-line' &>/dev/null
function __zoxide_z_complete_helper() {
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() {
# Only show completions when the cursor is at the end of the line.
@ -130,12 +165,20 @@ if [[ ${BASH_VERSINFO[0]:-0} -eq 4 && ${BASH_VERSINFO[1]:-0} -ge 4 || ${BASH_VER
\builtin compgen -A directory -- "${COMP_WORDS[-1]}" || \builtin true
)
# If there is a space after the last word, use interactive selection.
elif [[ -z ${COMP_WORDS[-1]} ]] && [[ ${COMP_WORDS[-2]} != "${__zoxide_z_prefix}"?* ]]; then
\builtin local result
elif [[ -z ${COMP_WORDS[-1]} ]]; then
# shellcheck disable=SC2312
result="$(\command zoxide query --exclude "$(__zoxide_pwd)" --interactive -- "{{ "${COMP_WORDS[@]:1:${#COMP_WORDS[@]}-2}" }}")" &&
COMPREPLY=("${__zoxide_z_prefix}${result}/")
\builtin printf '\e[5n'
__zoxide_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
# mechanism steals the response, it is still worth completing
# 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
}
@ -150,6 +193,6 @@ fi
{%- endmatch %}
{{ section }}
# To initialize zoxide, add this to your configuration (usually ~/.bashrc):
# To initialize zoxide, add this to your shell configuration file (usually ~/.bashrc):
#
# eval "$(zoxide init bash)"

View File

@ -22,7 +22,7 @@ fn __zoxide_cd {|path|
# Initialize hook to track previous directory.
var oldpwd = $builtin:pwd
set builtin:before-chdir = [$@builtin:before-chdir {|_| edit:add-var oldpwd $builtin:pwd }]
set builtin:before-chdir = [$@builtin:before-chdir {|_| set oldpwd = $builtin:pwd }]
# Initialize hook to add directories to zoxide.
{%- if hook == InitHook::None %}

View File

@ -19,19 +19,21 @@ end
# A copy of fish's internal cd function. This makes it possible to use
# `alias cd=z` without causing an infinite loop.
if ! builtin functions --query __zoxide_cd_internal
if builtin functions --query cd
builtin functions --copy cd __zoxide_cd_internal
else
alias __zoxide_cd_internal='builtin cd'
end
string replace --regex -- '^function cd\s' 'function __zoxide_cd_internal ' <$__fish_data_dir/functions/cd.fish | source
end
# cd + custom logic based on the value of _ZO_ECHO.
function __zoxide_cd
if set -q __zoxide_loop
builtin echo "zoxide: infinite loop detected"
builtin echo "Avoid aliasing `cd` to `z` directly, use `zoxide init --cmd=cd fish` instead"
return 1
end
{%- if cfg!(windows) %}
__zoxide_cd_internal (cygpath -u $argv)
__zoxide_loop=1 __zoxide_cd_internal (cygpath -u $argv)
{%- else %}
__zoxide_cd_internal $argv
__zoxide_loop=1 __zoxide_cd_internal $argv
{%- endif %}
{%- if echo %}
and __zoxide_pwd
@ -62,22 +64,17 @@ end
# When using zoxide with --no-cmd, alias these internal functions as desired.
#
if test -z $__zoxide_z_prefix
set __zoxide_z_prefix 'z!'
end
set __zoxide_z_prefix_regex ^(string escape --style=regex $__zoxide_z_prefix)
# Jump to a directory using only keywords.
function __zoxide_z
set -l argc (count $argv)
set -l argc (builtin count $argv)
if test $argc -eq 0
__zoxide_cd $HOME
else if test "$argv" = -
__zoxide_cd -
else if test $argc -eq 1 -a -d $argv[1]
__zoxide_cd $argv[1]
else if set -l result (string replace --regex $__zoxide_z_prefix_regex '' $argv[-1]); and test -n $result
__zoxide_cd $result
else if test $argc -eq 2 -a $argv[1] = --
__zoxide_cd -- $argv[2]
else
set -l result (command zoxide query --exclude (__zoxide_pwd) -- $argv)
and __zoxide_cd $result
@ -86,19 +83,18 @@ end
# Completions.
function __zoxide_z_complete
set -l tokens (commandline --current-process --tokenize)
set -l curr_tokens (commandline --cut-at-cursor --current-process --tokenize)
set -l tokens (builtin commandline --current-process --tokenize)
set -l curr_tokens (builtin commandline --cut-at-cursor --current-process --tokenize)
if test (count $tokens) -le 2 -a (count $curr_tokens) -eq 1
if test (builtin count $tokens) -le 2 -a (builtin count $curr_tokens) -eq 1
# If there are < 2 arguments, use `cd` completions.
complete --do-complete "'' "(commandline --cut-at-cursor --current-token) | string match --regex '.*/$'
else if test (count $tokens) -eq (count $curr_tokens); and ! string match --quiet --regex $__zoxide_z_prefix_regex. $tokens[-1]
# If the last argument is empty and the one before doesn't start with
# $__zoxide_z_prefix, use interactive selection.
complete --do-complete "'' "(builtin commandline --cut-at-cursor --current-token) | string match --regex -- '.*/$'
else if test (builtin count $tokens) -eq (builtin count $curr_tokens)
# If the last argument is empty, use interactive selection.
set -l query $tokens[2..-1]
set -l result (zoxide query --exclude (__zoxide_pwd) --interactive -- $query)
and echo $__zoxide_z_prefix$result
commandline --function repaint
set -l result (command zoxide query --exclude (__zoxide_pwd) --interactive -- $query)
and __zoxide_cd $result
and builtin commandline --function cancel-commandline repaint
end
end
complete --command __zoxide_z --no-files --arguments '(__zoxide_z_complete)'

View File

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

View File

@ -1,6 +1,8 @@
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
# shellcheck shell=sh
{{ section }}
# Utility functions for zoxide.
#
@ -41,6 +43,30 @@ if [ "${PS1:=}" = "${PS1#*\$(__zoxide_hook)}" ]; then
PS1="${PS1}\$(__zoxide_hook)"
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 -%}
\command printf "%s\n%s\n" \
"zoxide: PWD hooks are not supported on POSIX shells." \
@ -54,6 +80,8 @@ fi
# Jump to a directory using only keywords.
__zoxide_z() {
__zoxide_doctor
if [ "$#" -eq 0 ]; then
__zoxide_cd ~
elif [ "$#" -eq 1 ] && [ "$1" = '-' ]; then
@ -74,6 +102,7 @@ __zoxide_z() {
# Jump to a directory using interactive search.
__zoxide_zi() {
__zoxide_doctor
__zoxide_result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${__zoxide_result}"
}

View File

@ -62,7 +62,7 @@ function global:__zoxide_cd($dir, $literal) {
function global:__zoxide_hook {
$result = __zoxide_pwd
if ($null -ne $result) {
zoxide add -- $result
zoxide add "--" $result
}
}
{%- else if hook == InitHook::Pwd -%}
@ -72,7 +72,7 @@ function global:__zoxide_hook {
$result = __zoxide_pwd
if ($result -ne $global:__zoxide_oldpwd) {
if ($null -ne $result) {
zoxide add -- $result
zoxide add "--" $result
}
$global:__zoxide_oldpwd = $result
}
@ -80,7 +80,7 @@ function global:__zoxide_hook {
{%- endif %}
# Initialize hook.
$global:__zoxide_hooked = (Get-Variable __zoxide_hooked -ErrorAction SilentlyContinue -ValueOnly)
$global:__zoxide_hooked = (Get-Variable __zoxide_hooked -ErrorAction Ignore -ValueOnly)
if ($global:__zoxide_hooked -ne 1) {
$global:__zoxide_hooked = 1
$global:__zoxide_prompt_old = $function:prompt
@ -106,16 +106,19 @@ function global:__zoxide_z {
elseif ($args.Length -eq 1 -and ($args[0] -eq '-' -or $args[0] -eq '+')) {
__zoxide_cd $args[0] $false
}
elseif ($args.Length -eq 1 -and (Test-Path $args[0] -PathType Container)) {
elseif ($args.Length -eq 1 -and (Test-Path -PathType Container -LiteralPath $args[0])) {
__zoxide_cd $args[0] $true
}
elseif ($args.Length -eq 1 -and (Test-Path -PathType Container -Path $args[0] )) {
__zoxide_cd $args[0] $false
}
else {
$result = __zoxide_pwd
if ($null -ne $result) {
$result = __zoxide_bin query --exclude $result -- @args
$result = __zoxide_bin query --exclude $result "--" @args
}
else {
$result = __zoxide_bin query -- @args
$result = __zoxide_bin query "--" @args
}
if ($LASTEXITCODE -eq 0) {
__zoxide_cd $result $true
@ -125,7 +128,7 @@ function global:__zoxide_z {
# Jump to a directory using interactive search.
function global:__zoxide_zi {
$result = __zoxide_bin query -i -- @args
$result = __zoxide_bin query -i "--" @args
if ($LASTEXITCODE -eq 0) {
__zoxide_cd $result $true
}

74
templates/tcsh.txt Normal file
View File

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

View File

@ -1,6 +1,8 @@
{%- let section = "# =============================================================================\n#" -%}
{%- let not_configured = "# -- not configured --" -%}
# shellcheck shell=bash
{{ section }}
# Utility functions for zoxide.
#
@ -26,10 +28,6 @@ function __zoxide_cd() {
# Hook configuration for zoxide.
#
{% if hook == InitHook::None -%}
{{ not_configured -}}
{% else -%}
# Hook to add new entries to the database.
function __zoxide_hook() {
# shellcheck disable=SC2312
@ -37,28 +35,59 @@ function __zoxide_hook() {
}
# Initialize hook.
# shellcheck disable=SC2154
if [[ ${precmd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]] && [[ ${chpwd_functions[(Ie)__zoxide_hook]:-} -eq 0 ]]; then
{%- if hook == InitHook::Prompt %}
precmd_functions+=(__zoxide_hook)
{%- else if hook == InitHook::Pwd %}
chpwd_functions+=(__zoxide_hook)
{%- endif %}
fi
\builtin typeset -ga precmd_functions
\builtin typeset -ga chpwd_functions
# shellcheck disable=SC2034,SC2296
precmd_functions=("${(@)precmd_functions:#__zoxide_hook}")
# shellcheck disable=SC2034,SC2296
chpwd_functions=("${(@)chpwd_functions:#__zoxide_hook}")
{%- if hook == InitHook::Prompt %}
precmd_functions+=(__zoxide_hook)
{%- else if hook == InitHook::Pwd %}
chpwd_functions+=(__zoxide_hook)
{%- endif %}
# 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 %}
_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 }}
# When using zoxide with --no-cmd, alias these internal functions as desired.
#
# Jump to a directory using only keywords.
function __zoxide_z() {
# shellcheck disable=SC2199
__zoxide_doctor
if [[ "$#" -eq 0 ]]; then
__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"
elif [[ "$#" -eq 2 ]] && [[ "$1" = "--" ]]; then
__zoxide_cd "$2"
else
\builtin local result
# shellcheck disable=SC2312
@ -68,6 +97,7 @@ function __zoxide_z() {
# Jump to a directory using interactive search.
function __zoxide_zi() {
__zoxide_doctor
\builtin local result
result="$(\command zoxide query --interactive -- "$@")" && __zoxide_cd "${result}"
}
@ -87,6 +117,12 @@ function {{ cmd }}i() {
__zoxide_zi "$@"
}
{%- when None %}
{{ not_configured }}
{%- endmatch %}
# Completions.
if [[ -o zle ]]; then
__zoxide_result=''
@ -98,27 +134,32 @@ if [[ -o zle ]]; then
if [[ "{{ "${#words[@]}" }}" -eq 2 ]]; then
# Show completions for local directories.
_files -/
_cd -/
elif [[ "${words[-1]}" == '' ]]; then
# Show completions for Space-Tab.
# shellcheck disable=SC2086
__zoxide_result="$(\command zoxide query --exclude "$(__zoxide_pwd || \builtin true)" --interactive -- ${words[2,-1]})" || __zoxide_result=''
# Set a result to ensure completion doesn't re-run
compadd -Q ""
# Bind '\e[0n' to helper function.
\builtin bindkey '\e[0n' '__zoxide_z_complete_helper'
# Send '\e[0n' to console input.
# Sends query device status code, which results in a '\e[0n' being sent to console input.
\builtin printf '\e[5n'
fi
# Report that the completion was successful, so that we don't fall back
# to another completion function.
return 0
# Report that the completion was successful, so that we don't fall back
# to another completion function.
return 0
fi
}
function __zoxide_z_complete_helper() {
if [[ -n "${__zoxide_result}" ]]; then
# shellcheck disable=SC2034,SC2296
BUFFER="{{ cmd }} ${(q-)__zoxide_result}"
BUFFER="{{ cmd.unwrap_or("cd") }} ${(q-)__zoxide_result}"
__zoxide_result=''
\builtin zle reset-prompt
\builtin zle accept-line
else
@ -126,17 +167,13 @@ if [[ -o zle ]]; then
fi
}
\builtin zle -N __zoxide_z_complete_helper
{%- if let Some(cmd) = cmd %}
[[ "${+functions[compdef]}" -ne 0 ]] && \compdef __zoxide_z_complete {{ cmd }}
{%- endif %}
fi
{%- when None %}
{{ not_configured }}
{%- endmatch %}
{{ section }}
# To initialize zoxide, add this to your configuration (usually ~/.zshrc):
# To initialize zoxide, add this to your shell configuration file (usually ~/.zshrc):
#
# eval "$(zoxide init zsh)"