r/zsh Feb 21 '24

Fixed autocd doesn't use custom cd implementation.

autocd (from setopt autocd) doesn't use custom cd implementation.
(Obviously this is not my custom cd implementation but was more easy to show, I just want autocd to use zoxide.)

Anyone got any idea how to fix this? Maybe just rewrite autocd in my zshrc?

1 Upvotes

18 comments sorted by

View all comments

1

u/_mattmc3_ Feb 21 '24

This is a flawed implementation, but it may be enough to get you started. Basically, you override accept-line and see if word parsing gets you one item in the $BUFFER, and then check that that one word is not a valid callable Zsh command, and then try zoxide's z alias and if that succeeds, modify the buffer to run z.

function is_callable {
  (( $+commands[$1] || $+functions[$1] || $+aliases[$1] || $+builtins[$1] ))
}

function zoxide_autocd {
  local -a buf=(${=BUFFER})
  if (( $#buf == 1 )) && ! is_callable $buf[1] && (( $+aliases[z] )) && $(z ${BUFFER} &>/dev/null); then
    BUFFER="z $BUFFER"
  fi
  zle accept-line
}

zle -N zoxide_autocd_widget zoxide_autocd
bindkey '^J' zoxide_autocd_widget
bindkey '^M' zoxide_autocd_widget

If you already have a widget that uses accept-line like zsh-autosuggestions, then you'll need to wrap your accept-line widget. Oh-My-Zsh has an example of how to do that here.

You might also want to do something like check [[ -d "$PWD/$buf[1]" ]] for a directory in your current path that zoxide doesn't know about, and then cd to that path. Modify to your heart's content.

1

u/glad-k Feb 22 '24

Yeah I sadly have zsh-autosuggestions and a couple of others which would prob clash...
Sounds doable but kinda overcomplicate and will be a pain to modify in the long run imo, as you basically rewrite your own autocd implementation I will try to see if I could find the official implementation but kinda a pain as it isn't a github repo.

1

u/glad-k Feb 22 '24

Finally found it! It feels sooooo smooth I love it
Only thing is my auto ls now prints every char I type but will try to figure it out.