Skip to content

Instantly share code, notes, and snippets.

@sergiocarneiro
Last active May 7, 2026 23:01
Show Gist options
  • Select an option

  • Save sergiocarneiro/0d87d3fb3fb6e73993a3e432bf818b1d to your computer and use it in GitHub Desktop.

Select an option

Save sergiocarneiro/0d87d3fb3fb6e73993a3e432bf818b1d to your computer and use it in GitHub Desktop.
zsh essentials

zsh essentials

File Structure

~
├── .zshrc
└── .ssh
    └── config
└── zsh
    ├── completion.zsh
    └── terminal-features.zsh

Setup

Mostly copy-paste, except:

  • In ~/.zshrc, rename <username> to your machine's username.
export HOME="/Users/<username>"
export EDITOR="code --wait"
[ -f ~/.env ] && source ~/.env
# History/completion settings
source ~/zsh/terminal-features.zsh
# pnpm
export PNPM_HOME="$HOME/Library/pnpm"
case ":$PATH:" in
*":$PNPM_HOME:"*) ;;
*) export PATH="$PNPM_HOME:$PATH" ;;
esac
export PATH="$(pnpm bin -g):$PATH" # required when pnpm manages node
# » ┌──────────────────────────────────────────────────────────────────────────┐
# » │ Environment Check │
# » └──────────────────────────────────────────────────────────────────────────┘
# Node version mismatch warning for pnpm projects
check_node_version() {
[[ -f .npmrc ]] || return
local required=$(grep -oE 'use-node-version[[:space:]]*=[[:space:]]*"[^"]+"' .npmrc 2>/dev/null | grep -oE '"[^"]+"' | tr -d '"')
[[ -z "$required" ]] && return
local current=$(node -v 2>/dev/null | sed 's/v//')
[[ "$current" != "$required" ]] && \
printf '\033[33m⚠ Node mismatch: terminal=%s, project=%s\033[0m\n Run: pnpm env use --global %s\n' "$current" "$required" "$required"
}
autoload -U add-zsh-hook
add-zsh-hook chpwd check_node_version
check_node_version # Check on shell init too
# » ┌──────────────────────────────────────────────────────────────────────────┐
# » │ Signing commits │
# » └──────────────────────────────────────────────────────────────────────────┘
if ! ssh-add -l | grep -q "id_ed25519"; then
ssh-add --apple-use-keychain ~/.ssh/id_ed25519 > /dev/null 2>&1
fi
# Note: Also make sure ~/.ssh/config has the following lines:
# ```
# Host github.com
# AddKeysToAgent yes
# UseKeychain yes
# IdentityFile ~/.ssh/id_ed25519
# ```
# » ————————————————— End of Reviewed Configuration —————————————————
# ____ ___ __ __ ____ _ _____ _____ ___ ___ _ _
# / ___/ _ \| \/ | _ \| | | ____|_ _|_ _/ _ \| \ | |
# | | | | | | |\/| | |_) | | | _| | | | | | | | \| |
# | |__| |_| | | | | __/| |___| |___ | | | | |_| | |\ |
# \____\___/|_| |_|_| |_____|_____| |_| |___\___/|_| \_|
#
# Based on:
# - https://github.com/Phantas0s/.dotfiles/blob/master/zsh/completion.zsh
# - https://thevaluable.dev/zsh-install-configure-mouseless/
SCRIPT_PATH=$(dirname "$0")
# +---------+
# | General |
# +---------+
# Load more completions
fpath=($DOTFILES/zsh/plugins/zsh-completions/src $fpath)
# Should be called before compinit
zmodload zsh/complist
# Use hjlk in menu selection (during completion)
# Doesn't work well with interactive mode
bindkey -M menuselect 'h' vi-backward-char
bindkey -M menuselect 'k' vi-up-line-or-history
bindkey -M menuselect 'j' vi-down-line-or-history
bindkey -M menuselect 'l' vi-forward-char
bindkey -M menuselect '^xg' clear-screen
bindkey -M menuselect '^xi' vi-insert # Insert
bindkey -M menuselect '^xh' accept-and-hold # Hold
bindkey -M menuselect '^xn' accept-and-infer-next-history # Next
bindkey -M menuselect '^xu' undo # Undo
autoload -U compinit; compinit
_comp_options+=(globdots) # With hidden files
# Only work with the Zsh function vman
# See $DOTFILES/zsh/scripts.zsh
compdef vman="man"
# +---------+
# | Options |
# +---------+
# setopt GLOB_COMPLETE # Show autocompletion menu with globs
setopt MENU_COMPLETE # Automatically highlight first element of completion menu
setopt AUTO_LIST # Automatically list choices on ambiguous completion.
setopt COMPLETE_IN_WORD # Complete from both ends of a word.
# +---------+
# | zstyles |
# +---------+
# Ztyle pattern
# :completion:<function>:<completer>:<command>:<argument>:<tag>
# Define completers
zstyle ':completion:*' completer _extensions _complete _approximate
# Use cache for commands using cache
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path "$XDG_CACHE_HOME/zsh/.zcompcache"
# Complete the alias when _expand_alias is used as a function
zstyle ':completion:*' complete true
zle -C alias-expension complete-word _generic
bindkey '^Xa' alias-expension
zstyle ':completion:alias-expension:*' completer _expand_alias
# Use cache for commands which use it
# Allow you to select in a menu
zstyle ':completion:*' menu select
# Autocomplete options for cd instead of directory stack
zstyle ':completion:*' complete-options true
zstyle ':completion:*' file-sort modification
zstyle ':completion:*:*:*:*:corrections' format '%F{yellow}!- %d (errors: %e) -!%f'
zstyle ':completion:*:*:*:*:descriptions' format '%F{blue}-- %D %d --%f'
zstyle ':completion:*:*:*:*:messages' format ' %F{purple} -- %d --%f'
zstyle ':completion:*:*:*:*:warnings' format ' %F{red}-- no matches found --%f'
# zstyle ':completion:*:default' list-prompt '%S%M matches%s'
# Colors for files and directory
zstyle ':completion:*:*:*:*:default' list-colors ${(s.:.)LS_COLORS}
# Only display some tags for the command cd
zstyle ':completion:*:*:cd:*' tag-order local-directories directory-stack path-directories
# zstyle ':completion:*:complete:git:argument-1:' tag-order !aliases
# Required for completion to be in good groups (named after the tags)
zstyle ':completion:*' group-name ''
zstyle ':completion:*:*:-command-:*:*' group-order aliases builtins functions commands
# See ZSHCOMPWID "completion matching control"
zstyle ':completion:*' matcher-list '' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' keep-prefix true
zstyle -e ':completion:*:(ssh|scp|sftp|rsh|rsync):hosts' hosts 'reply=(${=${${(f)"$(cat {/etc/ssh_,~/.ssh/known_}hosts(|2)(N) /dev/null)"}%%[# ]*}//,/ })'
# +---------+
# | Plugins |
# +---------+
# (locally cloned from sources for enhanced security)
## source $SCRIPT_PATH/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
Host github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519
# » ┌──────────────────────────────────────────────────────────────────────────┐
# » │ Terminal Features (sort of plugins) │
# » └──────────────────────────────────────────────────────────────────────────┘
# Commands that should only run in interactive shells
if [[ $- == *i* ]]; then
# » Completions
source ~/zsh/completion.zsh
# tabtab source for packages
[[ -f ~/.config/tabtab/zsh/__tabtab.zsh ]] && . ~/.config/tabtab/zsh/__tabtab.zsh || true
# Terraform
## autoload -U +X bashcompinit && bashcompinit
## complete -o nospace -C /opt/homebrew/bin/terraform terraform
# bun completions
[ -s "~/.bun/_bun" ] && source "~/.bun/_bun"
# » History
# https://github.com/mattjj/my-oh-my-zsh/blob/master/history.zsh
HISTSIZE=100000
SAVEHIST=100000
setopt BANG_HIST # Treat the '!' character specially during expansion.
setopt EXTENDED_HISTORY # Write the history file in the ":start:elapsed;command" format.
setopt INC_APPEND_HISTORY # Write to the history file immediately, not when the shell exits.
setopt SHARE_HISTORY # Share history between all sessions.
setopt HIST_EXPIRE_DUPS_FIRST # Expire duplicate entries first when trimming history.
setopt HIST_IGNORE_DUPS # Don't record an entry that was just recorded again.
setopt HIST_IGNORE_ALL_DUPS # Delete old recorded entry if new entry is a duplicate.
setopt HIST_FIND_NO_DUPS # Do not display a line previously found.
setopt HIST_IGNORE_SPACE # Don't record an entry starting with a space.
setopt HIST_SAVE_NO_DUPS # Don't write duplicate entries in the history file.
setopt HIST_REDUCE_BLANKS # Remove superfluous blanks before recording entry.
setopt HIST_VERIFY # Don't execute immediately upon history expansion.
setopt HIST_BEEP # Beep when accessing nonexistent history.
## HISTFILE="$HOME/.zhistory"
# Directory-based history
# (doesn't work well)
#### function chpwd {
#### HISTFILE=$HOME/.zsh_history/$(basename $PWD)
#### fc -p $HISTFILE
#### }
# » History Completion
# Enable history completion
autoload -Uz compinit
compinit
# Use history for substring matching
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
# Configure history completion
zstyle ':completion:*' menu select
zstyle ':completion:*' auto-description 'specify: %d'
zstyle ':completion:*' completer _expand _complete _correct _approximate
zstyle ':completion:*' format 'Completing %d'
zstyle ':completion:*' group-name ''
zstyle ':completion:*' matcher-list '' 'm:{[:lower:][:upper:]}={[:upper:][:lower:]}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' menu select=long
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
# History search (Up and Down arrow keys)
bindkey "^[[A" history-beginning-search-backward
bindkey "^[[B" history-beginning-search-forward
PATH=~/.console-ninja/.bin:$PATH
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment