Skip to content

Instantly share code, notes, and snippets.

@Isanderthul
Last active October 24, 2025 08:26
Show Gist options
  • Select an option

  • Save Isanderthul/3db65fffb642955ea186f70b1a6f6adb to your computer and use it in GitHub Desktop.

Select an option

Save Isanderthul/3db65fffb642955ea186f70b1a6f6adb to your computer and use it in GitHub Desktop.
AUTO_CD enhanced
#Insert directly below 'source $ZSH/oh-my-zsh.sh'
unsetopt autocd
setopt no_auto_cd
function auto_dircmd {
# Run a command when PS1 contains a valid directory, similar to auto_cd
# Trim leading and trailing whitespace
BUFFER="${BUFFER#"${BUFFER%%[![:space:]]*}"}" # Remove leading whitespace
BUFFER="${BUFFER%"${BUFFER##*[![:space:]]}"}" # Remove trailing whitespace
# echo "DEBUG: BUFFER='$BUFFER' (after trimming)"
# echo "DEBUG: PWD='$PWD'"
if [[ -d "$BUFFER" ]] && # Check if it's a directory (absolute path)
(( ! $+functions[$BUFFER] )) &&
(( ! $+commands[$BUFFER] ))
then
# echo "DEBUG: Found absolute directory path, converting to cd command"
BUFFER="cd \"$BUFFER\""
elif [[ -d "$PWD/$BUFFER" ]] && # Check if it's a directory (relative path)
(( ! $+functions[$BUFFER] )) &&
(( ! $+commands[$BUFFER] ))
then
# echo "DEBUG: Found relative directory path, converting to cd command"
BUFFER="cd \"./$BUFFER\""
elif [[ -f "$BUFFER" ]] && # Check if it's a file (absolute path)
(( ! $+functions[$BUFFER] )) &&
(( ! $+commands[$BUFFER] ))
then
local dir_path=$(dirname "$BUFFER")
# echo "DEBUG: Found absolute file path, using dirname: '$dir_path'"
BUFFER="cd \"$dir_path\""
elif [[ -f "$PWD/$BUFFER" ]] && # Check if it's a file (relative path)
(( ! $+functions[$BUFFER] )) &&
(( ! $+commands[$BUFFER] ))
then
local dir_path=$(dirname "$PWD/$BUFFER")
# echo "DEBUG: Found relative file path, using dirname: '$dir_path'"
BUFFER="cd \"$dir_path\""
else
# echo "DEBUG: No directory or file match found, leaving BUFFER unchanged"
fi
# echo "DEBUG: Final BUFFER='$BUFFER'"
}
# If the accept-line wrapper already exists don't redefine it
(( ! ${+functions[_auto_dircmd_accept-line]} )) || return 0
case "$widgets[accept-line]" in
# Override the current accept-line widget, calling the old one
user:*) zle -N _auto_dircmd_orig_accept-line "${widgets[accept-line]#user:}"
function _auto_dircmd_accept-line {
auto_dircmd
zle _auto_dircmd_orig_accept-line -- "$@"
} ;;
# If no user widget defined, call the original accept-line widget
builtin) function _auto_dircmd_accept-line {
auto_dircmd
zle .accept-line
} ;;
esac
zle -N accept-line _auto_dircmd_accept-line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment