From 955fd5a6d1562b3a75fe31994191710d57bf173c Mon Sep 17 00:00:00 2001 From: Gal Date: Thu, 4 Jan 2024 02:13:17 +0700 Subject: [PATCH] :sparkles: Add zsh configs --- dot_zsh/aliases.zsh | 74 ++++++++++++++++ dot_zsh/dot_p10k.zsh | 199 ++++++++++++++++++++++++++++++++++++++++++ dot_zsh/functions.zsh | 109 +++++++++++++++++++++++ dot_zshrc | 25 ++++++ 4 files changed, 407 insertions(+) create mode 100644 dot_zsh/aliases.zsh create mode 100644 dot_zsh/dot_p10k.zsh create mode 100644 dot_zsh/functions.zsh create mode 100644 dot_zshrc diff --git a/dot_zsh/aliases.zsh b/dot_zsh/aliases.zsh new file mode 100644 index 0000000..311b79e --- /dev/null +++ b/dot_zsh/aliases.zsh @@ -0,0 +1,74 @@ +# Directory navigation +alias ..="cd .." +alias ...="cd ../.." +alias ....="cd ../../.." +alias .....="cd ../../../.." + +# Docker +alias dps="docker ps" +alias dimages="docker images" +alias dlogs="docker logs" + +# Shortcuts +alias d="cd ~/Documents" +alias dl="cd ~/Downloads" +alias dt="cd ~/Desktop" +alias g="git" +alias latest="find . -d 1 | sort | tail -n 1" # find latest file in current dir + +# Add notification from terminal for long-running commands +# Must install terminal-notifier: brew install terminal-notifier +# Usage example: sleep 10; alert +alias alert="terminal-notifier -title 'Command finished' -message 'Celebrate! 🎉🎉🎉' -sound default" + +# List all files colorized in long format +alias l="ls -lF ${colorflag}" + +# List all files colorized in long format, including dot files +alias la="ls -laF ${colorflag}" + +# List only directories +alias lsd="ls -lF ${colorflag} | grep --color=never '^d'" + +# Always use color output for `ls` +alias ls="command ls ${colorflag}" + +# Colored `grep` output +alias grep='grep --color=auto' +alias fgrep='fgrep --color=auto' +alias egrep='egrep --color=auto' + +# Enable aliases to be sudo’ed +alias sudo='sudo ' + +# IP +alias localip="ipconfig getifaddr en0" +alias ips="ifconfig -a | grep -o 'inet6\? \(addr:\)\?\s\?\(\(\([0-9]\+\.\)\{3\}[0-9]\+\)\|[a-fA-F0-9:]\+\)' | awk '{ sub(/inet6? (addr:)? ?/, \"\"); print }'" + +# Delete `.DS_Store` recursively +alias cleandsstore="find . -type f -name '*.DS_Store' -ls -delete" + +# Empty trash, system logs, downloads logs +alias emptytrash="sudo rm -rfv /Volumes/*/.Trashes; sudo rm -rfv ~/.Trash; sudo rm -rfv /private/var/log/asl/*.asl; sqlite3 +~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV* 'delete from LSQuarantineEvent'" + +# Lock screen +alias afk="/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend" + +# Reload the shell (i.e. invoke as a login shell) +alias reload="exec ${SHELL} -l" + +# Copy pubkey +alias copypubkeyrsa="pbcopy < ~/.ssh/id_rsa.pub" +alias copypubkeyed="pbcopy < ~/.ssh/id_ed25519_sk.pub" + +# Copy private key +alias copyprivkeyrsa="pbcopy < ~/.ssh/id_rsa" +alias copyprivkeyed="pbcopy < ~/.ssh/id_ed25519_sk" + +# List my gpg keys +alias mygpgkeys="gpg --list-secret-keys --keyid-format LONG" + +# Get current external IP +alias myexternalip="curl https://canihazip.com/s" + diff --git a/dot_zsh/dot_p10k.zsh b/dot_zsh/dot_p10k.zsh new file mode 100644 index 0000000..f70b58b --- /dev/null +++ b/dot_zsh/dot_p10k.zsh @@ -0,0 +1,199 @@ +# Generated by Powerlevel10k configuration wizard on 2024-01-04 at 02:04 WIB. +# Based on romkatv/powerlevel10k/config/p10k-pure.zsh, checksum 13301. +# Wizard options: nerdfont-complete + powerline, small icons, pure, snazzy, rprompt, +# 12h time, 2 lines, sparse, transient_prompt, instant_prompt=verbose. +# Type `p10k configure` to generate another config. +# +# Config file for Powerlevel10k with the style of Pure (https://github.com/sindresorhus/pure). +# +# Differences from Pure: +# +# - Git: +# - `@c4d3ec2c` instead of something like `v1.4.0~11` when in detached HEAD state. +# - No automatic `git fetch` (the same as in Pure with `PURE_GIT_PULL=0`). +# +# Apart from the differences listed above, the replication of Pure prompt is exact. This includes +# even the questionable parts. For example, just like in Pure, there is no indication of Git status +# being stale; prompt symbol is the same in command, visual and overwrite vi modes; when prompt +# doesn't fit on one line, it wraps around with no attempt to shorten it. +# +# If you like the general style of Pure but not particularly attached to all its quirks, type +# `p10k configure` and pick "Lean" style. This will give you slick minimalist prompt while taking +# advantage of Powerlevel10k features that aren't present in Pure. + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + autoload -Uz is-at-least && is-at-least 5.1 || return + + # Prompt colors. + local grey='242' + local red='#FF5C57' + local yellow='#F3F99D' + local blue='#57C7FF' + local magenta='#FF6AC1' + local cyan='#9AEDFE' + local white='#F1F1F0' + + # Left prompt segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # context # user@host + dir # current directory + vcs # git status + # command_execution_time # previous command duration + # =========================[ Line #2 ]========================= + newline # \n + # virtualenv # python virtual environment + prompt_char # prompt symbol + ) + + # Right prompt segments. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + command_execution_time # previous command duration + virtualenv # python virtual environment + context # user@host + time # current time + # =========================[ Line #2 ]========================= + newline # \n + ) + + # Basic style options that define the overall prompt look. + typeset -g POWERLEVEL9K_BACKGROUND= # transparent background + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol + typeset -g POWERLEVEL9K_VISUAL_IDENTIFIER_EXPANSION= # no segment icons + + # Add an empty line before each prompt except the first. This doesn't emulate the bug + # in Pure that makes prompt drift down whenever you use the Alt-C binding from fzf or similar. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Magenta prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS}_FOREGROUND=$magenta + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS}_FOREGROUND=$red + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode is the same as in command mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='❮' + # Prompt symbol in overwrite vi mode is the same as in command mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=false + + # Grey Python Virtual Environment. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=$grey + # Don't show Python version. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + + # Blue current directory. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=$blue + + # Context format when root: user@host. The first part white, the rest grey. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE="%F{$white}%n%f%F{$grey}@%m%f" + # Context format when not root: user@host. The whole thing grey. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE="%F{$grey}%n@%m%f" + # Don't show context unless root or in SSH. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_CONTENT_EXPANSION= + + # Show previous command duration only if it's >= 5s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=5 + # Don't show fractional seconds. Thus, 7s rather than 7.3s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Yellow previous command duration. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=$yellow + + # Grey Git prompt. This makes stale prompts indistinguishable from up-to-date ones. + typeset -g POWERLEVEL9K_VCS_FOREGROUND=$grey + + # Disable async loading indicator to make directories that aren't Git repositories + # indistinguishable from large Git repositories without known state. + typeset -g POWERLEVEL9K_VCS_LOADING_TEXT= + + # Don't wait for Git status even for a millisecond, so that prompt always updates + # asynchronously when Git state changes. + typeset -g POWERLEVEL9K_VCS_MAX_SYNC_LATENCY_SECONDS=0 + + # Cyan ahead/behind arrows. + typeset -g POWERLEVEL9K_VCS_{INCOMING,OUTGOING}_CHANGESFORMAT_FOREGROUND=$cyan + # Don't show remote branch, current tag or stashes. + typeset -g POWERLEVEL9K_VCS_GIT_HOOKS=(vcs-detect-changes git-untracked git-aheadbehind) + # Don't show the branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + # When in detached HEAD state, show @commit where branch normally goes. + typeset -g POWERLEVEL9K_VCS_COMMIT_ICON='@' + # Don't show staged, unstaged, untracked indicators. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED}_ICON= + # Show '*' when there are staged, unstaged or untracked files. + typeset -g POWERLEVEL9K_VCS_DIRTY_ICON='*' + # Show '⇣' if local branch is behind remote. + typeset -g POWERLEVEL9K_VCS_INCOMING_CHANGES_ICON=':⇣' + # Show '⇡' if local branch is ahead of remote. + typeset -g POWERLEVEL9K_VCS_OUTGOING_CHANGES_ICON=':⇡' + # Don't show the number of commits next to the ahead/behind arrows. + typeset -g POWERLEVEL9K_VCS_{COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=1 + # Remove space between '⇣' and '⇡' and all trailing spaces. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${${${P9K_CONTENT/⇣* :⇡/⇣⇡}// }//:/ }' + + # Grey current time. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=$grey + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%I:%M:%S %p}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands rather than the end times of + # their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=always + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/dot_zsh/functions.zsh b/dot_zsh/functions.zsh new file mode 100644 index 0000000..622957b --- /dev/null +++ b/dot_zsh/functions.zsh @@ -0,0 +1,109 @@ +# Simple calculator +calc() { + local result="" + result="$(printf "scale=10;%s\\n" "$*" | bc --mathlib | tr -d '\\\n')" + # └─ default (when `--mathlib` is used) is 20 + + if [[ "$result" == *.* ]]; then + # improve the output for decimal numbers + # add "0" for cases like ".5" + # add "0" for cases like "-.5" + # remove trailing zeros + printf "%s" "$result" | + sed -e 's/^\./0./' \ + -e 's/^-\./-0./' \ + -e 's/0*$//;s/\.$//' + else + printf "%s" "$result" + fi + printf "\\n" +} + +# Create a new directory and enter it +mkd() { + mkdir -p "$@" + cd "$@" || exit +} + +# Make a temporary directory and enter it +tmpd() { + local dir + if [ $# -eq 0 ]; then + dir=$(mktemp -d) + else + dir=$(mktemp -d -t "${1}.XXXXXXXXXX") + fi + cd "$dir" || exit +} + +# Determine size of a file or total size of a directory +fs() { + if du -b /dev/null > /dev/null 2>&1; then + local arg=-sbh + else + local arg=-sh + fi + # shellcheck disable=SC2199 + if [[ -n "$@" ]]; then + du $arg -- "$@" + else + du $arg -- .[^.]* * + fi +} + +# Use Git’s colored diff when available +if hash git &>/dev/null ; then + diff() { + git diff --no-index --color-words "$@" + } +fi + +# Convert HEX to the nearest color index (0-255) +fromhex(){ + hex=${1#"#"} + r=$(printf '0x%0.2s' "$hex") + g=$(printf '0x%0.2s' ${hex#??}) + b=$(printf '0x%0.2s' ${hex#????}) + echo '%03d' "$(( (r<75?0:(r-35)/40)*6*6 + + (g<75?0:(g-35)/40)*6 + + (b<75?0:(b-35)/40) + 16 ))" +} + +# Create a new directory and enter it +mkd() { + mkdir -p "$@" && cd "$_"; +} + +# Syntax-highlight JSON strings or files +# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json` +json() { + if [ -t 0 ]; then # argument + python -mjson.tool <<< "$*" | pygmentize -l javascript; + else # pipe + python -mjson.tool | pygmentize -l javascript; + fi; +} + +# Get colors in manual pages +man() { + env \ + LESS_TERMCAP_mb="$(printf '\e[1;31m')" \ + LESS_TERMCAP_md="$(printf '\e[1;31m')" \ + LESS_TERMCAP_me="$(printf '\e[0m')" \ + LESS_TERMCAP_se="$(printf '\e[0m')" \ + LESS_TERMCAP_so="$(printf '\e[1;44;33m')" \ + LESS_TERMCAP_ue="$(printf '\e[0m')" \ + LESS_TERMCAP_us="$(printf '\e[1;32m')" \ + man "$@" +} + +# Check if uri is up +isup() { + local uri=$1 + + if curl -s --head --request GET "$uri" | grep "200 OK" > /dev/null ; then + terminal-notifier -title '$uri' -message 'is down' + else + terminal-notifier -title '$uri' -message 'is up' + fi +} diff --git a/dot_zshrc b/dot_zshrc new file mode 100644 index 0000000..0d58483 --- /dev/null +++ b/dot_zshrc @@ -0,0 +1,25 @@ +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi + +export SSH_ASKPASS=/usr/local/bin/ssh-askpass +export DISPLAY=":0" + +export ZSH=$HOME/.oh-my-zsh + +ZSH_THEME="powerlevel10k/powerlevel10k" + +plugins=(git ssh-agent) + +# Load zsh config files +typeset -U config_files +config_files=(~/.zsh/*.zsh) + +for file in ${config_files}; do + source "$file" +done + +source $ZSH/oh-my-zsh.sh + +# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh. +[[ ! -f ~/.zsh/.p10k.zsh ]] || source ~/.zsh/.p10k.zsh