Skip to content

Instantly share code, notes, and snippets.

@maboloshi
Last active December 19, 2021 04:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maboloshi/cc07327ce9ec8764ae2713f4f3811598 to your computer and use it in GitHub Desktop.
Save maboloshi/cc07327ce9ec8764ae2713f4f3811598 to your computer and use it in GitHub Desktop.
[Mac 相关设置]
export PATH="/usr/local/sbin:$PATH:$HOME/bin"
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="agnosterzak_black"
# 大小写敏感
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# 启用命令自动更正
ENABLE_CORRECTION="true"
# 在等待完成时显示红点.
COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# 更改`history`命令输出中显示的时间格式
# 三种基本格式 "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# 或者使用strftime函数格式规范设置自定义格式,
# 详见 'man strftime'细节.
# HIST_STAMPS="mm/dd/yyyy"
# 自定义`ZSH_custom`文件夹路径
#ZSH_CUSTOM=$HOME/Library/Mobile\ Documents/com~apple~CloudDocs/设置/oh-my-zsh/custom
ZSH_CUSTOM=$ZSH/custom
# 加载插件设置:
# 官方自带插件 ~/.oh-my-zsh/plugins/*
# 个人自定义插件可放到 ~/.oh-my-zsh/custom/plugins/下, 或者自定义`ZSH_custom`
# 理智添加,太多的插件会减慢shell的启动速度
# 注意: 这里将全部外部插件放在opt_plugins中, 并在plugins中引用它
# 为了在缺失外部插件时能自动安装, 必须使用如下的书写形式
# 其中每个外部插件名后面添加以 # + git clone 地址
opt_plugins=(
zsh-autosuggestions # https://github.com/zsh-users/zsh-autosuggestions
# zsh-syntax-highlighting # https://github.com/zsh-users/zsh-syntax-highlighting
fast-syntax-highlighting # https://github.com/zdharma/fast-syntax-highlighting
zsh-completions # https://github.com/zsh-users/zsh-completions
# incr
zsh-history-substring-search # https://github.com/zsh-users/zsh-history-substring-search
z.lua # https://github.com/skywind3000/z.lua
)
# plugins中添加${opt_plugins},以启用外部插件
plugins=(
#colored-man-pages
common-aliases
extract
git
history
sublime
#z
$opt_plugins
)
# 每次启动 ZSH shell 时, 自动检测是否缺失外部插件
# 当缺失外部插件时, 会自动安装
function install_opt_plugins {
local opt_plugins_path="$ZSH_CUSTOM/plugins"
for plugin ($opt_plugins) ; do
if [ ! -d "$opt_plugins_path/$plugin" ]; then
# 读取~.zshrc中外部插件的安装链接(注意: 此处 awk 命令必须使用单引号)
local url=$(grep "^[[:blank:]]*$plugin" "$HOME/.zshrc" | awk -F '#[[:blank:]]*' '{print $2}')
if [ ! "$url" ]; then
echo -e "\033[31mError ==> 无法获取 $plugin 安装链接, 请确认设置是否正确!!!!!!!!!!\033[0m"
else
echo -e "\033[34m==> 安装缺失的外部插件: \033[31m$plugin\033[0m"
git clone "$url" "$opt_plugins_path/$plugin" || echo -e "\033[31mError ==> 安装 $plugin 失败, 请确认设置是否正确!!!!!!!!!!\033[0m"
fi
fi
done
}
install_opt_plugins
# zsh completions for brew
fpath=(/usr/local/share/zsh/site-functions $fpath)
#compinit
source "$ZSH/oh-my-zsh.sh"
# ==============用户配置===================
# 代理设置:
export HTTPS_PROXY=http://127.0.0.1:7890 HTTP_PROXY=http://127.0.0.1:7890 ALL_PROXY=socks5://127.0.0.1:7890
# alias setproxy="export HTTPS_PROXY=http://127.0.0.1:7890 HTTP_PROXY=http://127.0.0.1:7890 ALL_PROXY=socks5://127.0.0.1:7890 && echo -e "\033[31m已设置代理""
# alias unsetproxy="unset HTTPS_PROXY HTTP_PROXY ALL_PROXY && echo -e "\033[31m已取消代理设置"
# 验证
# curl http://ipinfo.io
# 时间显示语言格式:
# export LC_TIME=en_US.UTF-8
# 本地和远程会话的首选编辑器
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# 使用"less"定义的自定义手册页颜色
export LESS_TERMCAP_mb=$'\e[1;31m' # begin blinking
export LESS_TERMCAP_md=$'\e[1;31m' # begin bold
export LESS_TERMCAP_me=$'\e[0m' # end mode
export LESS_TERMCAP_se=$'\e[0m' # end standout-mode
export LESS_TERMCAP_so=$'\e[1;44;33m' # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\e[0m' # end underline
export LESS_TERMCAP_us=$'\e[1;32m' # begin underline
# ============快捷键设置===================
# 详见 http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html
# 前后移动一个单词
bindkey '^[[1;3C' forward-word # Alt + →
bindkey '^[[1;3D' backward-word # Alt + ←
# 向前删除一个单词
bindkey '^[0x17' backward-kill-word # Alt + Backspace
# 删除整行
bindkey '^[[3;3~' kill-whole-line # Alt + Del
# Fix Del
bindkey '^[[3~' delete-char # Del
# zsh-history-substring-search 快捷键
# 匹配输入前缀的历史输入
bindkey '^[[1;3A' history-substring-search-up # Alt +↑
bindkey '^[[1;3B' history-substring-search-down # Alt +↓
# EMACS模式下
bindkey -M emacs '^P' history-substring-search-up # Ctrl + N
bindkey -M emacs '^N' history-substring-search-down # Ctrl + P
# zsh-autosuggestions 快捷键
# 接受当前建议
# bindkey '^,' autosuggest-accept
# 清除当前建议
bindkey '^[/' autosuggest-clear # Alt + /
# =============插件设置====================
# `zsh-autosuggestions`命令建议样式
# (fg:前景色 bg:背景颜色 粗体等), 颜色代码详见:
# https://jonasjacek.github.io/colors/
# https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=247,underline'
# 更多`zsh-autosuggestions`插件设置详见:
# `https://github.com/zsh-users/zsh-autosuggestions#configuration`
# ===========自定义函数===================
# 更新外部插件
function update_ohmyzsh_opt_plugins {
local opt_plugins_path="$ZSH_CUSTOM/plugins"
for plugin ($opt_plugins) ; do
if [ -d "$opt_plugins_path/$plugin" ]; then
echo -e "\033[34m==> 更新外部插件: \033[31m$plugin\033[0m"
git -C "$opt_plugins_path/$plugin" pull --rebase --stat origin master || echo -e "\033[31mError ==> 更新 $plugin 失败, 请确认设置是否正确!!!!!!!!!!\033[0m"
fi
done
}
# 代理设置和取消
function setproxy() {
if [[ -z $1 ]] || [[ $1 = "on" ]]; then
export HTTPS_PROXY=http://127.0.0.1:7890 HTTP_PROXY=http://127.0.0.1:7890 ALL_PROXY=socks5://127.0.0.1:7890
echo -e "\033[31m已设置代理"
elif [[ $1 = "off" ]]; then
unset HTTPS_PROXY HTTP_PROXY ALL_PROXY
echo -e "\033[31m已取消代理设置"
fi
}
# ============别名设置===================
alias sha512sum="shasum -a 512"
alias sha256sum="shasum -a 256"
alias ls="exa"
alias tree="exa --tree"
# alias for cnpm
# alias npm="npm --registry=https://registry.npm.taobao.org \
# --cache=$HOME/.npm/.cache/cnpm \
# --disturl=https://npm.taobao.org/dist \
# --userconfig=$HOME/.cnpmrc"
# 全局使用阿里源
# npm config set registry https://registry.npm.taobao.org
# 恢复默认
# npm config set registry https://registry.npmjs.org
# 验证
# npm config get registry
# ----------- HomeBrew 设置 ------------------
# HOMEBREW 镜像设置(中科大源)
# export HOMEBREW_BREW_GIT_REMOTE=https://mirrors.ustc.edu.cn/brew.git
# export HOMEBREW_CORE_GIT_REMOTE=https://mirrors.ustc.edu.cn/homebrew-core.git
# export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles
### homebrew-cask 镜像设置(中科大源)
# 手动替换 USTC 镜像:
# git -C "$(brew --repo)"/Library/Taps/homebrew/homebrew-cask remote set-url origin https://mirrors.ustc.edu.cn/homebrew-cask.git
# 手动重置为官方地址:
# git -C "$(brew --repo)"/Library/Taps/homebrew/homebrew-cask remote set-url origin https://github.com/Homebrew/homebrew-cask.git
###
export HOMEBREW_GITHUB_API_TOKEN=
export HOMEBREW_NO_AUTO_UPDATE=true
# 间隔 24 小时更新一次 (单位:秒)
#export HOMEBREW_AUTO_UPDATE_SECS=86400
# 私人库私人下载策略文件定位
export HOMEBREW_CUSTOM_DOWNLOAD_STRATEGY=/usr/local/Homebrew/Library/Taps/maboloshi/homebrew-private/lib/custom_download_strategy.rb
# 自定义`brew`命令
# 参考: https://github.com/wolffaxn/brew-zsh-plugin/blob/master/brew.plugin.zsh
# https://github.com/digitalraven/omz-homebrew/blob/master/omz-homebrew.plugin.zsh
function brew () {
case "$1" in
# cleanup)
# (cd "$(brew --repo)" && git prune && git gc)
# command brew cleanup
# rm -rf "$(brew --cache)"
# ;;
repair)
echo -e "\033[34m==> \033[1;37m修复 brew 数据库......\033[0m"
# (cd "$(brew --repo homebrew/core)" && git fetch origin master && git reset --hard origin/master && rm -rf .git/rebase-apply/)
# (cd "$(brew --repo homebrew/cask)" && git fetch origin master && git reset --hard origin/master && rm -rf .git/rebase-apply/)
command brew update --force
# brew doctor
;;
update)
echo -e "\033[34m==> \033[1;37m同步 brew 数据库......\033[0m"
command brew update
echo -e "\033[34m==> \033[1;37m更新过时的 Formulae 和 Casks......\033[0m"
command brew upgrade
echo -e "\033[34m==> \033[1;37m清理过时的缓存......\033[0m"
brew cleanup
;;
backup)
echo -e "\033[34m==> \033[1;37m备份个人 brew 清单......\033[0m"
brew bundle dump --describe --force --file="~/.Brewfile"
;;
*)
command brew "$@"
;;
esac
}
# ----------- HomeBrew 设置 ------------------
# auto-fu.zsh 插件
# git clone --branch=pu https://github.com/hchbaw/auto-fu.zsh ~/.oh-my-zsh/custom/plugins/auto-fu.zsh
# A=~/.oh-my-zsh/custom/plugins/auto-fu.zsh/auto-fu.zsh ; (zsh -c "source $A ; auto-fu-zcompile $A ~/.zsh")
{ . ~/.zsh/auto-fu; auto-fu-install; }
zstyle ':auto-fu:highlight' input bold
zstyle ':auto-fu:highlight' completion fg=black,bold
zstyle ':auto-fu:highlight' completion/one fg=white,bold,underline
zstyle ':auto-fu:var' postdisplay $'\n-azfu-'
zstyle ':auto-fu:var' track-keymap-skip opp
zstyle ':completion:*' completer _oldlist _complete
zle-line-init () {auto-fu-init;}; zle -N zle-line-init
zle -N zle-keymap-select auto-fu-zle-keymap-select
# vim:ft=zsh ts=2 sw=2 sts=2
#
# agnoster's Theme - https://gist.github.com/3712874
# A Powerline-inspired theme for ZSH
#
# # README
#
# In order for this theme to render correctly, you will need a
# [Powerline-patched font](https://gist.github.com/1595572).
#
# In addition, I recommend the
# [Solarized theme](https://github.com/altercation/solarized/) and, if you're
# using it on Mac OS X, [iTerm 2](http://www.iterm2.com/) over Terminal.app -
# it has significantly better color fidelity.
#
# # Goals
#
# The aim of this theme is to only show you *relevant* information. Like most
# prompts, it will only show git information when in a git working directory.
# However, it goes a step further: everything from the current user and
# hostname to whether the last call exited with an error to whether background
# jobs are running in this shell will all be displayed automatically when
# appropriate.
### Segment drawing
# A few utility functions to make it easy and re-usable to draw segmented prompts
CURRENT_BG='NONE'
# Characters
SEGMENT_SEPARATOR="\ue0b0"
PLUSMINUS="\u00b1"
BRANCH="\ue0a0"
DETACHED="\u27a6"
CROSS="\u2718"
LIGHTNING="\u26a1"
GEAR="\u2699"
# Begin a segment
# Takes two arguments, background and foreground. Both can be omitted,
# rendering default background/foreground.
prompt_segment() {
local bg fg
[[ -n $1 ]] && bg="%K{$1}" || bg="%k"
[[ -n $2 ]] && fg="%F{$2}" || fg="%f"
if [[ $CURRENT_BG != 'NONE' && $1 != $CURRENT_BG ]]; then
print -n " %{$bg%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR%{$fg%} "
else
print -n "%{$bg%}%{$fg%} "
fi
CURRENT_BG=$1
[[ -n $3 ]] && print -n $3
}
# End the prompt, closing any open segments
prompt_end() {
if [[ -n $CURRENT_BG ]]; then
print -n " %{%k%F{$CURRENT_BG}%}$SEGMENT_SEPARATOR"
else
print -n "%{%k%}"
fi
print -n "%{%f%}"
CURRENT_BG=''
}
### Prompt components
# Each component will draw itself, and hide itself if no information needs to be shown
# Context: user@hostname (who am I and where am I)
prompt_context() {
if [[ -n "$SSH_CLIENT" ]]; then
#prompt_segment magenta white "%{$fg_no_bold[white]%(!.%{%F{white}%}.)%}$USER@%m%{$fg_no_bold[white]%}"
prompt_segment magenta white "%{$fg_no_bold[white]%(!.%{%F{white}%}.)%}$USER@%m%{$fg_no_bold[white]%}"
else
#prompt_segment yellow magenta "%{$fg_no_bold[magenta]%(!.%{%F{magenta}%}.)%}@$USER%{$fg_no_bold[magenta]%}"
#prompt_segment yellow black "%{$fg_no_bold[black]%(!.%{%F{black}%}.)%}@$USER%{$fg_no_bold[magenta]%}"
fi
}
# Battery Level
prompt_battery() {
HEART='♥ '
if [[ $(uname) == "Darwin" ]] ; then
function battery_is_charging() {
[ $(ioreg -rc AppleSmartBattery | grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]
}
function battery_pct() {
local smart_battery_status="$(ioreg -rc "AppleSmartBattery")"
typeset -F maxcapacity=$(echo $smart_battery_status | grep '^.*"MaxCapacity"\ =\ ' | sed -e 's/^.*"MaxCapacity"\ =\ //')
typeset -F currentcapacity=$(echo $smart_battery_status | grep '^.*"CurrentCapacity"\ =\ ' | sed -e 's/^.*CurrentCapacity"\ =\ //')
integer i=$(((currentcapacity/maxcapacity) * 100))
echo $i
}
function battery_pct_remaining() {
if battery_is_charging ; then
battery_pct
else
echo "External Power"
fi
}
function battery_time_remaining() {
local smart_battery_status="$(ioreg -rc "AppleSmartBattery")"
if [[ $(echo $smart_battery_status | grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]] ; then
timeremaining=$(echo $smart_battery_status | grep '^.*"AvgTimeToEmpty"\ =\ ' | sed -e 's/^.*"AvgTimeToEmpty"\ =\ //')
if [ $timeremaining -gt 720 ] ; then
echo "::"
else
echo "~$((timeremaining / 60)):$((timeremaining % 60))"
fi
fi
}
b=$(battery_pct_remaining)
if [[ $(ioreg -rc AppleSmartBattery | grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]] ; then
if [ $b -gt 50 ] ; then
prompt_segment green white
elif [ $b -gt 20 ] ; then
prompt_segment yellow white
else
prompt_segment red white
fi
echo -n "%{$fg_no_bold[white]%}$HEART$(battery_pct_remaining)%%%{$fg_no_bold[white]%}"
fi
fi
if [[ $(uname) == "Linux" && -d /sys/module/battery ]] ; then
function battery_is_charging() {
! [[ $(acpi 2&>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]]
}
function battery_pct() {
if (( $+commands[acpi] )) ; then
echo "$(acpi | cut -f2 -d ',' | tr -cd '[:digit:]')"
fi
}
function battery_pct_remaining() {
if [ ! $(battery_is_charging) ] ; then
battery_pct
else
echo "External Power"
fi
}
function battery_time_remaining() {
if [[ $(acpi 2&>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]] ; then
echo $(acpi | cut -f3 -d ',')
fi
}
b=$(battery_pct_remaining)
if [[ $(acpi 2&>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]] ; then
if [ $b -gt 40 ] ; then
prompt_segment green white
elif [ $b -gt 20 ] ; then
prompt_segment yellow white
else
prompt_segment red white
fi
echo -n "%{$fg_no_bold[white]%}$HEART$(battery_pct_remaining)%%%{$fg_no_bold[white]%}"
fi
fi
}
# Git: branch/detached head, dirty status
prompt_git() {
#«»±˖˗‑‐‒ ━ ✚‐↔←↑↓→↭⇎⇔⋆━◂▸◄►◆☀★☗☊✔✖❮❯⚑⚙
local PL_BRANCH_CHAR
() {
local LC_ALL="" LC_CTYPE="en_US.UTF-8"
PL_BRANCH_CHAR="$BRANCH"
}
local ref dirty mode repo_path clean has_upstream
local modified untracked added deleted tagged stashed
local ready_commit git_status bgclr fgclr
local commits_diff commits_ahead commits_behind has_diverged to_push to_pull
repo_path=$(git rev-parse --git-dir 2>/dev/null)
if $(git rev-parse --is-inside-work-tree >/dev/null 2>&1); then
dirty=$(parse_git_dirty)
git_status=$(git status --porcelain 2> /dev/null)
ref=$(git symbolic-ref HEAD 2> /dev/null) || ref="➦ $(git rev-parse --short HEAD 2> /dev/null)"
if [[ -n $dirty ]]; then # 有修改状态
clean=''
bgclr='yellow'
fgclr='magenta'
#fgclr='purple'
else # 干净状态
clean=' ✔'
bgclr='green'
#fgclr='white'
fgclr='black'
fi
local upstream=$(git rev-parse --symbolic-full-name --abbrev-ref @{upstream} 2> /dev/null)
if [[ -n "${upstream}" && "${upstream}" != "@{upstream}" ]]; then has_upstream=true; fi
local current_commit_hash=$(git rev-parse HEAD 2> /dev/null)
local number_of_untracked_files=$(\grep -c "^??" <<< "${git_status}")
# if [[ $number_of_untracked_files -gt 0 ]]; then untracked=" $number_of_untracked_files◆"; fi
if [[ $number_of_untracked_files -gt 0 ]]; then untracked=" $number_of_untracked_files☀"; fi
local number_added=$(\grep -c "^A" <<< "${git_status}")
if [[ $number_added -gt 0 ]]; then added=" $number_added✚"; fi
local number_modified=$(\grep -c "^.M" <<< "${git_status}")
if [[ $number_modified -gt 0 ]]; then
modified=" $number_modified●"
bgclr='red'
#fgclr='white'
#bgclr='yellow'
fgclr='black'
fi
local number_added_modified=$(\grep -c "^M" <<< "${git_status}")
local number_added_renamed=$(\grep -c "^R" <<< "${git_status}")
if [[ $number_modified -gt 0 && $number_added_modified -gt 0 ]]; then
modified="$modified$((number_added_modified+number_added_renamed))±"
elif [[ $number_added_modified -gt 0 ]]; then
modified=" ●$((number_added_modified+number_added_renamed))±"
fi
local number_deleted=$(\grep -c "^.D" <<< "${git_status}")
if [[ $number_deleted -gt 0 ]]; then
deleted=" $number_deleted‒"
bgclr='red'
#fgclr='white'
fgclr='black'
fi
local number_added_deleted=$(\grep -c "^D" <<< "${git_status}")
if [[ $number_deleted -gt 0 && $number_added_deleted -gt 0 ]]; then
deleted="$deleted$number_added_deleted±"
elif [[ $number_added_deleted -gt 0 ]]; then
deleted=" ‒$number_added_deleted±"
fi
local tag_at_current_commit=$(git describe --exact-match --tags $current_commit_hash 2> /dev/null)
if [[ -n $tag_at_current_commit ]]; then tagged=" ☗$tag_at_current_commit "; fi
local number_of_stashes="$(git stash list -n1 2> /dev/null | wc -l)"
if [[ $number_of_stashes -gt 0 ]]; then
stashed=" ${number_of_stashes##*( )}⚙"
bgclr='magenta'
#fgclr='white'
fgclr='black'
fi
if [[ $number_added -gt 0 || $number_added_modified -gt 0 || $number_added_deleted -gt 0 ]]; then ready_commit=' ⚑'; fi
local upstream_prompt=''
if [[ $has_upstream == true ]]; then
commits_diff="$(git log --pretty=oneline --topo-order --left-right ${current_commit_hash}...${upstream} 2> /dev/null)"
commits_ahead=$(\grep -c "^<" <<< "$commits_diff")
commits_behind=$(\grep -c "^>" <<< "$commits_diff")
upstream_prompt="$(git rev-parse --symbolic-full-name --abbrev-ref @{upstream} 2> /dev/null)"
#upstream_prompt=$(sed -e 's/\/.*$/ ☊ /g' <<< "$upstream_prompt")
upstream_prompt=$(sed -e 's/\/.*$/ ↑ /g' <<< "$upstream_prompt")
fi
has_diverged=false
if [[ $commits_ahead -gt 0 && $commits_behind -gt 0 ]]; then has_diverged=true; fi
if [[ $has_diverged == false && $commits_ahead -gt 0 ]]; then
if [[ $bgclr == 'red' || $bgclr == 'magenta' ]] then
to_push=" $fg_no_bold[white]↑$commits_ahead$fg_no_bold[$fgclr]"
else
to_push=" $fg_no_bold[black]↑$commits_ahead$fg_no_bold[$fgclr]"
fi
fi
if [[ $has_diverged == false && $commits_behind -gt 0 ]]; then to_pull=" $fg_no_bold[magenta]↓$commits_behind$fg_no_bold[$fgclr]"; fi
if [[ -e "${repo_path}/BISECT_LOG" ]]; then
mode=" <B>"
elif [[ -e "${repo_path}/MERGE_HEAD" ]]; then
mode=" >M<"
elif [[ -e "${repo_path}/rebase" || -e "${repo_path}/rebase-apply" || -e "${repo_path}/rebase-merge" || -e "${repo_path}/../.dotest" ]]; then
mode=" >R>"
fi
prompt_segment $bgclr $fgclr
print -n "%{$fg_no_bold[$fgclr]%}${ref/refs\/heads\//$PL_BRANCH_CHAR $upstream_prompt}${mode}$to_push$to_pull$clean$tagged$stashed$untracked$modified$deleted$added$ready_commit%{$fg_no_bold[$fgclr]%}"
fi
}
prompt_hg() {
local rev status
if $(hg id >/dev/null 2>&1); then
if $(hg prompt >/dev/null 2>&1); then
if [[ $(hg prompt "{status|unknown}") = "?" ]]; then
# if files are not added
prompt_segment red white
st='±'
elif [[ -n $(hg prompt "{status|modified}") ]]; then
# if any modification
prompt_segment yellow black
st='±'
else
# if working copy is clean
prompt_segment green black
fi
print -n $(hg prompt "☿ {rev}@{branch}") $st
else
st=""
rev=$(hg id -n 2>/dev/null | sed 's/[^-0-9]//g')
branch=$(hg id -b 2>/dev/null)
if `hg st | grep -q "^\?"`; then
prompt_segment red black
st='±'
elif `hg st | grep -q "^[MA]"`; then
prompt_segment yellow black
st='±'
else
prompt_segment green black
fi
print -n "☿ $rev@$branch" $st
fi
fi
}
# Dir: current working directory
prompt_dir() {
prompt_segment cyan white "%{$fg_no_bold[white]%}%~%{$fg_no_bold[white]%}"
#prompt_segment blue black "%{$fg_no_bold[black]%}%~%{$fg_no_bold[black]%}"
}
# Virtualenv: current working virtualenv
prompt_virtualenv() {
local virtualenv_path="$VIRTUAL_ENV"
if [[ -n $virtualenv_path && -n $VIRTUAL_ENV_DISABLE_PROMPT ]]; then
prompt_segment blue black "(`basename $virtualenv_path`)"
fi
}
prompt_time() {
#prompt_segment blue white "%{$fg_no_bold[white]%}%D{%a %e %b - %H:%M}%{$fg_no_bold[white]%}"
prompt_segment blue white "%{$fg_no_bold[white]%}%D{%m/%d周%a%H:%M}%{$fg_no_bold[black]%}"
}
# Status:
# - was there an error
# - am I root
# - are there background jobs?
prompt_status() {
local symbols
symbols=()
[[ $RETVAL -ne 0 ]] && symbols+="%{%F{red}%}$CROSS"
[[ $UID -eq 0 ]] && symbols+="%{%F{yellow}%}$LIGHTNING"
[[ $(jobs -l | wc -l) -gt 0 ]] && symbols+="%{%F{cyan}%}$GEAR"
[[ -n "$symbols" ]] && prompt_segment black default "$symbols"
}
## Main prompt
build_prompt() {
RETVAL=$?
print -n "\n"
prompt_status
prompt_battery
prompt_time
prompt_context
prompt_virtualenv
prompt_dir
prompt_git
prompt_hg
prompt_end
CURRENT_BG='NONE'
print -n "\n"
prompt_end
}
PROMPT='%{%f%b%k%}$(build_prompt) '
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>DisplayProductID</key>
<integer>16498</integer>
<key>DisplayVendorID</key>
<integer>4268</integer>
<key>scale-resolutions</key>
<array>
<data>AAALQA==</data>
</array>
</dict>
</plist>

系统设置

开启HiDPI

  1. 生成并安装HiDPI设置文件
bash -c "$(curl -fsSL https://raw.githubusercontent.com/xzhih/one-key-hidpi/master/hidpi.sh)"

本人DELL U2312HM显示器 HIDPI: 1440x810

  1. 重启后, 系统偏好设置 > 显示器将分辨率设置为1440x810 (HiDPI).

截屏2020-10-07 下午7 52 43

其他见说明

Mac如何打开身份不明开发者的程序

sudo spctl --master-disable

Homebrew 安装并设置

Homebrew 是 MacOS 上的套件管理器,主要面对开发者,你几乎可以用它下载和部署所有的软件/环境,类似于 iOS 上越狱后的 Cyida。
Homebrew-cask 主要针对普通用户,用来下载各种 GUI 程序,是 Homebrew 的补充。
现 Homebrew 发行版已集成 Homebrew-cask 无需单独安装。

安装

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

设置HOMEBREW_GITHUB_API_TOKEN

  1. 创建 GitHub 私人TOKEN
    点击创建TOKEN,复制生成的 GITHUB API TOKEN。

  2. 添加HOMEBREW_GITHUB_API_TOKEN

  echo 'export HOMEBREW_GITHUB_API_TOKEN=<YOUR_GITHUB_API_TOKEN>' >>~/.zshrc

<YOUR_GITHUB_API_TOKEN>替换为上面生成的 GITHUB API TOKEN。
.zshrc 为 ZSH 的设置文件.

常用软件安装

常用软件

### 测试版软件库
brew tap homebrew/cask-versions
### chrome 浏览器 beta 版
brew cask install google-chrome-beta
### 全能播放器
brew cask install iina-beta
### Markdown 编辑器
brew cask install Typora
### 解压软甲
brew cask install ezip
### TeamViewer 远程控制
brew cask install teamviewer
### 网易云音乐
brew cask install neteasemusic
### 印象笔记
brew cask install yinxiangbiji
### 显示器色温控制
brew cask install flux
### Clover 设置编辑器
brew cask install clover-configurator
### 搜狗拼音输入法
brew cask install sogouinput
### 音频文件标签修改(不支持 ape 格式)
brew cask install meta
### ShadowsocksX
brew cask install shadowsocksx-ng
### V2rayX
brew cask install v2rayx
### 下载工具
brew cask install free-download-manager
### HWSensors
brew cask install HWSensors

开发者相关工具

### 安装 node 并设置镜像源
brew install node
echo registry = https://registry.npm.taobao.org > ~/.npmrc
### Sublime Text 3
brew cask install sublime-text
### sublime-merge
brew cask install sublime-merge
### Gist 管理
brew cask install lepton
### 7zip 压缩工具
brew install p7zip
### travis 命令行工具
brew install travis

Finder 预览插件

# Markdown 预览插件
brew cask install qlmarkdown
# 无文件扩展名的纯文本文件
brew cask install qlstephen
# 源文件语法高亮插件
brew cask install qlcolorcode
# 格式化预览JSON文件
brew cask install quicklook-json
# 预览.patch文件
brew cask install qlprettypatch

参考

iTerm2 [待整理]

安装

brew cask install iterm2

配色主题设置

iTerm2 提供非常多的配色主题可以下载,可以到 iterm2 color schemes 选择喜欢的配色主题,右上角的下载标识是整包下载,有 .tar 和 .zip 档可以选择,也可以点击主题名称下载单独配色主题文件. 以 Flatland 主题为例:

flatland.png

  1. 下载整包解压或下载单独配色主题文件, 如Flatland.itermcolors.

  2. 导入并设置iterm2主题: iterm2 → Preferences → Profiles → Colors, 在右下方的 Color Presets 中 → 点选 import 导入主题路径后 →再点选一次 Color Presets 选取导入后的Flatland主题.

如果愿意,可以创建除“Default”以外的其他配置文件。

字体设置

  1. 字体安装
  2. 设置iterm2字体: iterm2 → Preferences → Profiles → Text → Change Font

Oh My Zsh 安装与设置

更多详见: https://github.com/robbyrussell/oh-my-zsh

安装并修改默认shell

sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
# 修改默认shell为zsh
chsh -s $(which zsh)

配置主题及字体

安装agnosterzak主题

# 下载并安装
curl -Oo ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/themes/ -s https://gist.githubusercontent.com/maboloshi/cc07327ce9ec8764ae2713f4f3811598/raw/agnosterzak_black.zsh-theme
# 设置为当前主题
sed -i '' 's/.*\(ZSH_THEME=\).*/\1"agnosterzak_black"/' ~/.zshrc || echo 'ZSH_THEME="agnosterzak_black"' >> ~/.zshrc

其他更多主题:

安装 Roboto Mono for Powerline 字体

brew tap homebrew/cask-fonts
brew cask install font-roboto-mono-for-powerline

之后在惯用的终端工具的偏好设置里将"所有字体"改为 Roboto Mono for Powerline 字体

其他更多字体:

配置插件

常用插件简介

插件 来源 状态 简介
common-aliases * 常用命令别名
extract * 一键解压, 支持多种解压格式
history * 显示历史命令
z.lua 高级文件夹跳转
fast-syntax-highlighting 语法高亮显示
zsh-autosuggestions 自动建议(基于历史)
zsh-completions 自动补全
zsh-history-substring-search 历史搜索

* 表示 oh-my-zsh 官方自带插件

其他更多插件:

安装外部插件

plugins_path="~/.oh-my-zsh/custom/plugins/"
# zsh-syntax-highlighting
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${plugins_path}/zsh-syntax-highlighting
# zsh-autosuggestions
git clone https://github.com/zsh-users/zsh-autosuggestions.git ${plugins_path}/zsh-autosuggestions
# 修改插件`zsh-autosuggestions`自动补全热键
echo "# 修改插件\`zsh-autosuggestions\`自动补全热键为逗号
bindkey ',' autosuggest-accept" >> ~/.zshrc

或者按下面启用/禁用插件的方法先设置, 并当重启终端 (zsh) 时自动安装缺失的插件.

启用/禁用插件

编辑 ~/.zshrc:

# 自定义`ZSH_custom`文件夹路径
ZSH_CUSTOM=$HOME/Library/Mobile\ Documents/com~apple~CloudDocs/设置/oh-my-zsh/custom

# 加载插件设置:
# 官方自带插件 ~/.oh-my-zsh/plugins/*
# 个人自定义插件可放到 ~/.oh-my-zsh/custom/plugins/下, 或者自定义`ZSH_custom`
# 理智添加,太多的插件会减慢shell的启动速度

# 注意: 这里将全部外部插件放在opt_plugins中, 并在plugins中引用它
# 为了在缺失外部插件时能自动安装, 必须使用如下的书写形式
# 其中每个外部插件名后面添加以 # + git clone 地址
opt_plugins=(
    zsh-autosuggestions          # https://github.com/zsh-users/zsh-autosuggestions
    # zsh-syntax-highlighting      # https://github.com/zsh-users/zsh-syntax-highlighting
    fast-syntax-highlighting     # https://github.com/zdharma/fast-syntax-highlighting
    zsh-completions              # https://github.com/zsh-users/zsh-completions
#    incr
    zsh-history-substring-search # https://github.com/zsh-users/zsh-history-substring-search
    z.lua                        # https://github.com/skywind3000/z.lua
    )
# plugins中添加${opt_plugins},以启用外部插件
plugins=(
    #colored-man-pages
    common-aliases
    extract
    git
    history
    sublime
    #z
    $opt_plugins
    )
# 每次启动 ZSH shell 时, 自动检测是否缺失外部插件
# 当缺失外部插件时, 会自动安装
function install_opt_plugins {
    local opt_plugins_path="$ZSH_CUSTOM/plugins"
    for plugin ($opt_plugins) ; do
      if [ ! -d "$opt_plugins_path/$plugin" ]; then
        # 读取~.zshrc中外部插件的安装链接(注意: 此处 awk 命令必须使用单引号)
        local url=$(grep "^[[:blank:]]*$plugin" "$HOME/.zshrc" | awk -F '#[[:blank:]]*' '{print $2}')
        if [ ! "$url" ]; then
            echo -e "\033[31mError ==> 无法获取 $plugin 安装链接, 请确认设置是否正确!!!!!!!!!!\033[0m"
        else
            echo -e "\033[34m==> 安装缺失的外部插件: \033[31m$plugin\033[0m"
            git clone "$url" "$opt_plugins_path/$plugin" || echo -e "\033[31mError ==> 安装 $plugin 失败, 请确认设置是否正确!!!!!!!!!!\033[0m"
        fi
      fi
    done
}
install_opt_plugins

重启终端或 source 生效,每次启动终端 (zsh) 时都会自动检测并安装缺失的外部插件。

其他设置

详见我的.zshrc设置备份:

注意事项

zsh Shell 虽然对bash Shell 兼容性很好, 但仍然存在一定兼容性问题. 详见. 故在oh-my-zsh(即zsh)环境下调试基于bash的脚本代码需要注意这个问题.


Sublime Text 3

Package Control是 Sublime Text 3 的插件管理器,默认未安装。

Package Control 安装

打开 ST3 > Tools > Install Package Control

Package Control 代理设置

打开ST3 > Preferences > Package Settings > Package Control > Settings – User, 添加:

"http_proxy": "http://127.0.0.1:7890",
"https_proxy": "http://127.0.0.1:7890",

注意:Sublime Text 3现仅支持http协议,所以要注意socks5和http端口号的区别。

插件

  • 本人常用的插件概述见这里

  • 插件安装: 使用快捷键 ⌘ + ⇧ + p 或者 ST3 > Preferences > Package Control 换出 “命令面板”,选择 Package Control: Install Package 命令,再输入要安装的插件名即可。

  • 当导入备份设置,需先安装好Package Control,默认状态下Package Control会自动检测并安装缺失的插件。

其他设置

详见我的设置备份:Sublime-Text-User-Settings

常用快捷键

参考

使用 Mackup 备份和同步设置

存放在iCloud

安装 Mackup

brew install mackup

设置 Mackup

~/.mackup.cfg

[storage]
engine = icloud
directory = 设置/Mackup

[applications_to_sync]

[applications_to_ignore]

~/.mackup/my-files.cfg

[application]
name = My personal synced files and dirs

[configuration_files]
Library/Services
.Brewfile

~/.mackup/sublime-text-3.cfg

[application]
name = Sublime Text 3

[configuration_files]
# Based on https://packagecontrol.io/docs/syncing
Library/Application Support/Sublime Text 3/Packages/User
# 自定义
Library/Application Support/Sublime Text 3/Local

[xdg_configuration_files]
sublime-text-3/Packages/User

备份App设置

mackup backup

恢复App设置

mackup restore

参考

zsh 快捷键

快捷键 等效快捷键 说明
⌃ + u 清空当前行
⌃ + a [Home] 移动到行首
⌃ + e [End] 移动到行尾
⌃ + f 向前移动
⌃ + b 向后移动
⌃ + p [PageUP] 末尾才有效 上一条命令
⌃ + n [PageDown] 末尾才有效 下一条命令
⌃ + r 搜索历史命令
⌃ + y 召回最近用命令删除的文字
⌃ + h [Backspace] 删除光标之前的字符
⌃ + d [Delete] 删除光标所指的字符
⌃ + w 删除光标之前的单词
⌃ + k 删除从光标到行尾的内容
⌃ + t 交换光标和之前的字符
^ + Click 鼠标右键 右键菜单
⌘ + Click 可以打开文件,文件夹和链接
⌘ + n 新建窗口
⌘ + t 新建标签页
⌘ + w 关闭当前页
⌘ + 数字 ⌘ + 方向键 切换标签页
⌥⌘ + 数字 切换窗口
⌘ + enter 切换全屏
⌘ + d 左右分屏
⇧⌘ + d 上下分屏
⌘ + ; 自动补全历史记录
⇧⌘ + h 自动补全剪贴板历史
⌥⌘ + e 查找所有来定位某个标签页
⌘ + r ⌃ + l 清屏
⌘ + / 显示光标位置
⌥⌘ + b 历史回放
⌘ + f 查找,然后用 tab 和 ⇧ + tab 可以向右和向左补全,补全之后的内容会被自动复制, 还可以用 ⌥ + enter 将查找结果输入终端
选中即复制,鼠标中键粘贴
@maboloshi
Copy link
Author

maboloshi commented Feb 24, 2019

install MiKTeX

brew cask install miktex-console

@maboloshi
Copy link
Author

maboloshi commented Mar 18, 2019

    url=$(sed -n "s/^[[:blank:]]*$i[[:blank:]]*#[[:blank:]]*\(.*\)/\1/p" $HOME/.zshrc)
或
    url=$(grep "^[[:blank:]]*$i" $HOME/.zshrc | sed 's/.*#[[:blank:]]*\(.*\)/\1/')
    url=$(grep "^[[:blank:]]*$i" $HOME/.zshrc | awk -F '#[[:blank:]]' '{print $2}')
    url=$(sed -n "s/^[[:blank:]]*$i[[:blank:]]*#[[:blank:]]*\(.*git\).*/\1/p" $HOME/.zshrc)
或
    url=$(grep "^[[:blank:]]*$i" $HOME/.zshrc | sed 's/.*#[[:blank:]]*\(.*git\).*/\1/)

@maboloshi
Copy link
Author

实体按键名称 按键代码 快捷功能

| [Home] | ${terminfo[khome]} |Go to beginning of line
| [End] | ${terminfo[kend]} |Go to end of line
| [Space] | |do history expansion
| [Ctrl-RightArrow] | ^[[1;5C |move forward one word
| [Ctrl-LeftArrow] | ^[[1;5D |move backward one word
| [Shift-Tab] | ${terminfo[kcbt]} |move through the completion menu backwards
| [Backspace] | ^? |delete backward
| [Delete] | ${terminfo[kdch1]} |delete forward

| Use emacs key bindings
| [Esc-w] | \ew |Kill from the cursor to the mark
| [Esc-l] | \el |run command: ls
| [Ctrl-r] | ^r |Search backward incrementally for a specified string. The string may begin with ^ to anchor the search to the beginning of the line.
| [PageUp] | ${terminfo[kpp]} |Up a line of history
| [PageDown] | ${terminfo[knp]} |Down a line of history

| start typing + [Up-Arrow] | ${terminfo[kcuu1]} |fuzzy find history forward
| start typing + [Down-Arrow] | ${terminfo[kcud1]} |fuzzy find history backward

@maboloshi
Copy link
Author

maboloshi commented Apr 13, 2019

一键设置 macOS

  1. 提前设置好网络环境

  2. 一键设置 macOS

zsh -c "$(curl -fsSL https://gist.github.com/maboloshi/cc07327ce9ec8764ae2713f4f3811598/one-key-mac.sh)"

one-key-mac.sh:

#!/bin/zsh

# 一键设置 macOS

## 系统设置
echo 开启 HiDPI
echo 请设置本机 HIDPI为 1440x810。
# sh -c "$(curl -fsSL https://raw.githubusercontent.com/syscl/Enable-HiDPI-OSX/master/enable-HiDPI.sh)"
bash -c "$(curl -fsSL https://raw.githubusercontent.com/xzhih/one-key-hidpi/master/hidpi.sh)"
echo '重启后,系统偏好设置 > 显示器将分辨率设置为1440x810 (HiDPI).'

echo Mac如何打开身份不明开发者的程序
sudo spctl --master-disable

echo 修改默认shell为zsh
chsh -s "$(which zsh)"

echo 安装 Homebrew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

echo 安装 oh-my-zsh
sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"

# 恢复并载入 .zshrc 设置
ln -s ~/Library/Mobile\ Documents/com~apple~CloudDocs/设置/Mackup/.zshrc "$HOME"
source "$HOME/.zshrc"

echo 恢复各种设置
# 安装 mackup
brew install mackup
# 恢复 mackup 设置文件
ln -s ~/Library/Mobile\ Documents/com~apple~CloudDocs/设置/Mackup/.mackup.cfg "$HOME"
ln -s ~/Library/Mobile\ Documents/com~apple~CloudDocs/设置/Mackup/.mackup "$HOME"
# 恢复其他各种设置
mackup restore

echo 重新安装各种 App
# 安装 mas
brew install mas

# 批量安装软件
brew bundle --file="$HOME/.Brewfile"

echo 一键设置完成, 请重启系统

@maboloshi
Copy link
Author

maboloshi commented Jul 22, 2020

根据OS系统绑定该使用那些设置

OS=`uname -s`
if [ ${OS} == "Darwin"  ];then

if
if [ ${OS} == "Linux"  ];then

if

@maboloshi
Copy link
Author

终端主题预览工具: https://windowsterminalthemes.dev/
虽然是为Windows Terminal 开发的,当其中的主题是iterm2 color schemes的转换格式而来, 可以用作预览 Iterm2 色彩主题工具

@maboloshi
Copy link
Author

maboloshi commented Oct 15, 2020

# 使用“less”定义的自定义手册页颜色
export LESS_TERMCAP_mb=$'\e[1;31m'      # begin blinking
export LESS_TERMCAP_md=$'\e[1;31m'      # begin bold
export LESS_TERMCAP_me=$'\e[0m'         # end mode
export LESS_TERMCAP_se=$'\e[0m'         # end standout-mode
export LESS_TERMCAP_so=$'\e[1;44;33m'   # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\e[0m'         # end underline
export LESS_TERMCAP_us=$'\e[1;32m'      # begin underline

全局彩色 Man 页代替colored-man-pages插件

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment