Mac笔记本初始配置

Productivity 搬砖力
Apr 29, 2023 ~

理论上,这种类似 dot file的东西,应该是搞一个 Github的repo。但是因为本人太懒,而且觉得换电脑这种事情频率足够低,省下的精力成本大概还不够我这个半吊子码农setup这个repo并且 maintain好所需要花费的精力多,所以干脆就记一个笔记,大概也是够用了。

Alacritty + Font

Alacritty

GPU加速的Terminal,在Mac下性能非常好,简单好用。(其实我也没怎么用过别的Terminal,所以其实也只是在用这个而已,不想换了)

brew install --cask alacritty

字体

字体方面目前的选择是 MesloLGS NF

安装需要是参考的Powerlevel 10K 的文档

  1. Download these four ttf files:
  2. Double-click on each file and click “Install”. This will make MesloLGS NF font available to all applications on your system.
  3. Create ~/.config/alacritty/alacritty.yml
    • 需要添加两类东西
      • 一是字体
      • 二是把Option键当作Meta键(也就是Alt键)
        • 主要就是在Tmux以及Vim里面切换panel的时候用的。
font:
  normal:
    family: "MesloLGS NF"
key_bindings:
  - { key: J, mods: Alt, chars: "\x1bj" }
  - { key: K, mods: Alt, chars: "\x1bk" }
  - { key: H, mods: Alt, chars: "\x1bh" }
  - { key: L, mods: Alt, chars: "\x1bl" }

ZSH + FZF + Oh-My-Zsh + Powerlevel 10K + 插件

Install ZSH

brew install zsh

FZF的安装

brew install fzf

$(brew --prefix)/opt/fzf/install

安装好之后,如果要在zsh里面使用,需要配置插件,详见后面的【配置FZF插件章节】

Install Oh My Zsh

sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

# Or through wget
sh -c "$(wget https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh -O -)"

安装zsh的插件

  • zsh-autosuggestions
    • git clone https://github.com/zsh-users/zsh-autosuggestions.git $ZSH_CUSTOM/plugins/zsh-autosuggestions
  • zsh-syntax-highlighting
    • git clone https://github.com/zsh-users/zsh-syntax-highlighting.git $ZSH_CUSTOM/plugins/zsh-syntax-highlighting
  • fast-syntax-highlighting plugin
    • git clone https://github.com/zdharma-continuum/fast-syntax-highlighting.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/fast-syntax-highlighting
  • zsh-history-substring-search
  • bazel
    • mkdir -p ~/.oh-my-zsh/plugins/bazel
    • wget -P ~/.oh-my-zsh/plugins https://raw.githubusercontent.com/bazelbuild/bazel/master/scripts/zsh_completion/_bazel
    • Add bazel to the plugins list in your ~/.zshrc
  • zsh-vi-mode
    • git clone https://github.com/jeffreytse/zsh-vi-mode $ZSH_CUSTOM/plugins/zsh-vi-mode

配置 .zshrc

配置Bazel plugin

# Suggested by bazel completion plugin
# Ref: https://raw.githubusercontent.com/bazelbuild/bazel/master/scripts/zsh_completion/_bazel
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache

配置zsh-completions

这个插件还需要homebrew才可以。

brew install zsh-completion

然后再添加下面这段到.zshrc中。

# Auto-completion
if type brew &>/dev/null; then
    FPATH=$(brew --prefix)/share/zsh-completions:$FPATH

      autoload -Uz compinit
        compinit
fi

上面的可能已经过时了。现在的安装方法是:

# Clone the repository inside your oh-my-zsh repo:
  git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions

# Add it to FPATH in your .zshrc by adding the following line before source "$ZSH/oh-my-zsh.sh":
  fpath+=${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions/src

之后启动的时候还可能报错:

zsh compinit: insecure directories, run compaudit for list.
Ignore insecure directories and continue [y] or abort compinit [n]

解决方法是,直接改 /opt/homebrew/share 的权限(应该是跟group exec的权限有关)

sudo chmod -R 755 /opt/homebrew/share

Reference: https://stackoverflow.com/questions/13762280/zsh-compinit-insecure-directories

配置zsh-vi-mode

Install zsh-vi-mode
git clone https://github.com/jeffreytse/zsh-vi-mode $ZSH_CUSTOM/plugins/zsh-vi-mode
基础配置
# zsh-vi-mode
# Custom cursor style and color for different modes
ZVM_INSERT_MODE_CURSOR=$ZVM_CURSOR_BLINK_BLOCK
处理 FZF 和 zsh-vi-mode 以及 zsh-autosuggestions 的冲突

在 .zshrc 后面添加:

# Conflict with Fzf and zsh-autosuggestions, need to re-execute fzf.
zvm_after_init_commands+=(my_init_fzf)
zvm_after_init_commands+=(my_init_zsh_autosuggestions)

注意这里用了两个后面定义的function: my_init_fzfmy_init_zsh_autosuggestions.

配置FZF插件

# Fzf
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
function my_init_fzf() {
    [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
}
# 上面定义的这个function,在之前处理zsh-vi-mode的时候用到了。

此时FZF在被ZSH使用的时候,还是可能报错:“command not found: bind”(参考答案

这是因为.zshrc引用了.bashrc的内容,而两者syntax上其实并不完全通用。但是这个引用有时又是无法删除的(比如公司电脑的配置说明中要求.bashrc在.zshrc中要被引用)。这时需要在.bashrc中做如下修改:

# Change this line:
[ -f ~/.fzf.bash ] && source ~/.fzf.bash

# To this line:
[ -z "$ZSH_NAME" ] && [ -f ~/.fzf.bash ] && source ~/.fzf.bash

配置auto-suggestions

# zsh-auto-suggestions
function my_init_zsh_autosuggestions() {
    bindkey '^ ' autosuggest-accept
}
# 上面定义的这个function,在之前处理zsh-vi-mode的时候用到了。
bindkey '^ ' autosuggest-accept

添加 Plugins

# Update ~/.zshrc, at the line of "plugins=(", add following plugins
# zsh-vi-mode
# zsh-completions
# zsh-autosuggestions
# zsh-syntax-highlighting
# fast-syntax-highlighting
# git
# bazel
# 这里没有选择添加 zsh-autocomplete 因为这个跟 zsh-vi-mode 和 bazel plugin似乎有冲突。

zsh-completions 在这里被删除了,因为这个安装方法对它不适用(详见)。

Install Powerlevel 10K

git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k

# Then set ZSH_THEME="powerlevel10k/powerlevel10k" in ~/.zshrc

# Then logout and login, open Alacritty, p10k wizard should run automatically to guide the configuration.

Tmux Setup

brew install tmux

The content of ~/.tmux.conf:

  • 别忘了打开Tmux然后 prefix+I, prefix+U
# indices start from 1
set -g base-index 1

# Auto set window title
set-window-option -g automatic-rename on
set-option -g set-titles on

# Always set the default TERM
set -g default-terminal screen-256color
set -g status-keys vi
set -g history-limit 20000

# Mouse on
set -g mouse on

# Change to copy mode when wheel is used
bind-key -T copy-mode-vi WheelUpPane send-keys -X scroll-up
bind-key -T copy-mode-vi WheelDownPane send-keys -X scroll-down
bind-key -T copy-mode-vi C-WheelUpPane send-keys -X -N 30 scroll-up
bind-key -T copy-mode-vi C-WheelDownPane send-keys -X -N 30 scroll-down

# Use vim binding
setw -g mode-keys vi
bind-key -T copy-mode-vi 'v' send -X begin-selection

# Turn on activity monitor
setw -g monitor-activity on
set -g visual-activity on

# Split window (create panes)
bind-key v split-window -h -c "#{pane_current_path}"
bind-key s split-window -v -c "#{pane_current_path}"

# Create new window in the same directory
bind-key c new-window -c "#{pane_current_path}"

# Resize panes with <prefix>+J/K/H/L
bind-key J resize-pane -D 5
bind-key K resize-pane -U 5
bind-key H resize-pane -L 5
bind-key L resize-pane -R 5

# Resize panes with <prefix>+ALT+j/k/h/l
bind-key M-j resize-pane -D
bind-key M-k resize-pane -U
bind-key M-h resize-pane -L
bind-key M-l resize-pane -R

# Use Alt-jkhl keys without prefix to switch pane
bind-key -n M-h select-pane -L
bind-key -n M-j select-pane -D
bind-key -n M-k select-pane -U
bind-key -n M-l select-pane -R

# Use Alt-left/right to switch windows
bind-key -n S-Left previous-window
bind-key -n S-Right next-window

# Shift-Ctrl-left/right to move window order
bind-key -n C-S-Left swap-window -t -1
bind-key -n C-S-Right swap-window -t +1

# No delay for Esc
set -sg escape-time 10

# Make ctrl-let/right work right in tmux
set-window-option -g xterm-keys on

##################
## Tmux Plugins ##
##################

# prefix+I: install all new plugins and refresh tmux env
# prefix+U: update plugins
# prefix+ALT+u: remove/uninstall plugins

# plugins
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-yank'
set -g @plugin 'jimeh/tmux-themepack'
set -g @themepack 'powerline/block/orange'

# initialize tmux plugin manager (must be the last line of tmux.conf)
run '~/.tmux/plugins/tpm/tpm'

Vim

(Skip vim installation)

Install Plug

curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

然后就添加下面这个 .vimrc 文件

"" Enable modern Vim features not compatible with Vi spec.
set nocompatible " be iMproved, required
filetype off " required
set noswapfile " disable swap file

call plug#begin('~/.vim/plugged')

"" theme, colorscheme
Plug 'flazz/vim-colorschemes'
Plug 'kien/rainbow_parentheses.vim'
Plug 'sheerun/vim-polyglot'
"Plug 'mhinz/vim-hugefile'

"" motion, repeating
Plug 'easymotion/vim-easymotion'
Plug 'justinmk/vim-sneak'
Plug 'terryma/vim-multiple-cursors'
Plug 'ntpeters/vim-better-whitespace'

"" IDE
Plug 'ctrlpvim/ctrlp.vim'
  " by default use <leader>ig to toggle vim indent guides plugin.
  " or just use :IndentGuidesToggle
Plug 'nathanaelkane/vim-indent-guides'
  " Toggle comments faster
  " <leader>cc : set to comment
  " <leader>cu : cancel comment
Plug 'scrooloose/nerdcommenter'
  " project specific vim settings, this is much better than :set exrc
Plug 'thinca/vim-localrc'
Plug 'scrooloose/syntastic'
Plug 'scrooloose/nerdtree'
Plug 'bling/vim-airline'
Plug 'mhinz/vim-signify'
Plug 'kien/tabman.vim'
Plug 'mileszs/ack.vim'
Plug 'jeetsukumaran/vim-buffergator'

""" language
"Plug 'Valloric/YouCompleteMe', {'for': ['cpp', 'c', 'objcpp', 'objc', 'go', 'java']}
"  " vim rtags binding
"  " common usage:
"  " <leader>rf : find references
"  " <leader>rj : go to definition
"  " <leader>rS : go to definition, open in horizontal split
"  " <leader>rV : go to definition, open in vertical split
"  " <leader>rr : reindex current file
"  " <leader>rw : rename symbol under cursor (not tested)
"  " Note, only work in C family language.
"Plug 'lyuts/vim-rtags', {'for': ['cpp', 'c']}
"  " It seems 'google' package already contains 'clang linter'.
"  " And adding it again will cause some conflit, check the existence before
"  " installing this plugin.
"Plug 'rhysd/vim-clang-format', {'for': ['cpp', 'c']}
"  " A vim plugin that applies yapf to the current file.
"Plug 'pignacio/vim-yapf-format', {'for': 'python'}
"Plug 'klen/python-mode', {'for': 'python'}
"Plug 'plasticboy/vim-markdown', {'for': 'markdown'}

call plug#end()

"""" colorscheme
"" not fully understood
set background=dark
colorscheme desertEx
highlight Normal ctermbg=none
set t_Co=256

"""" airline settings
set laststatus=2
let g:airline#extensions#tabline#enabled=1

"""" vim-easymotion settings
"" disable default mapping first
let g:EasyMotion_do_mapping=0
"" map easymotion prefix to <leader>
map <leader> <plug>(easymotion-prefix)
"" turn on smart case for vim-easymotion
"" just like set ignorecase and set smartcase
let g:EasyMotion_smartcase=1
"" set f to bi-directional and over-windows search
"" need 2 char to trigger, i.e. <leader>s{char}{char}{label}
"" This is exactly what I want!
"" Give me a tag for every word, it is like vimium in Chrome now.
nmap f <plug>(easymotion-bd-w)
"" jk motions, use when in easymotion mode
map <leader>j <plug>(easymotion-j)
map <leader>k <plug>(easymotion-k)
"" use easymotion for incremental search
map / <Plug>(easymotion-sn)
"" should be used together with the map above, but not sure what it is.
" omap / <Plug>(easymotion-tn)
"" Set easymotion to shade text for search.
let g:EasyMotion_do_shade=1

"""" vim-sneak settings
" follow generic settings for the case-sensitivity
let g:sneak#use_ic_scs=1

"""" syntastic settings
"" populate location list
let g:syntastic_always_populate_loc_list=1
"" set passive mode for some file types
""  may conflict with vim-go
let g:syntastic_mode_map = {
      \ "mode": "active",
      \ "passive_filetypes": ["go"],
      \ }

"""" vim-indent-guide settings
let g:indent_guides_start_level=2
let g:indent_guides_guide_size=1
"" color of indent strips
let g:indent_guides_auto_colors=0
autocmd VimEnter,Colorscheme * :hi IndentGuidesOdd guibg=red ctermbg=black
autocmd VimEnter,Colorscheme * :hi IndentGuidesEven guibg=green ctermbg=darkgrey

"""" NerdTree settings
"" Toggle folder tree split
map <leader>ne :NERDTreeFind<CR>

"""" NerdCommenter settings
"" Add a blank space before commented content
let g:NERDSpaceDelims=1

"""" tagbar settings
"" use <F8> to toggle
nnoremap <F8> :TagbarToggle<CR>

"""" ctrlp settings
"" Use <leader>f to trigger fuzzy buffer search of CtrlP
nnoremap F :CtrlPLine<CR>
"" Usually METADATA file is the root of a project
let g:ctrlp_root_markers = ['METADATA']
"" Use AG for ctrlp
if executable('ag')
  " use ag over grep
  set grepprg=ag\ --nogroup\ --nocolor
  " use ag for listing files
  let g:ctrlp_user_command = 'ag %s -i --nocolor --nogroup --hidden
        \ --ignore .git
        \ --ignore .svn
        \ --ignore .DS_Store
        \ --ignore "**/*.pyc"
        \ --ignore .hg
        \ --ignore review
        \ -g ""'
  let g:ctrlp_use_caching=0
endif

"""" Ack settings
"" use ag if possible
if executable('ag')
  let g:ackprg = 'ag --vimgrep'
endif
"" highlight search term
let g:ackhighlight = 1

"################################
"####### generic settings #######
"################################

"" Rational way to move between splits
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-h> <C-w>h
nnoremap <C-l> <C-w>l

"" Use * in visual mode to search selected word
vnoremap * y/<C-R>"<CR>

"" enable mouse
if has('mouse')
  set mouse=a
endif

"" how many lines of history VIM should remember
set history=1000

"" Rational backspace
set backspace=indent,eol,start

"" show line number
set nu

"" show me a bar at col 80
set colorcolumn=80

"" incremental search and highlight search result
set incsearch
set hlsearch

"" if /<lower case>, return both upper case and lower case results.
"" if /<upper case>, only return upper case results.
set ignorecase
set smartcase
augroup dynamic_smartcase
  autocmd!
  autocmd CmdLineEnter : set nosmartcase
  autocmd CmdLineLeave : set smartcase
augroup END

"" Enable the autocompletion little menu
set wildmenu
set wildmode=longest:full,full

"" show match parenthesis
set showmatch

"" show title in terminal
set title

"" set highlight on the current line
set cursorline
hi CursorLine term=bold cterm=bold gui=bold ctermbg=237

"" Move vertically by visual line
noremap j gj
noremap k gk

"" At least 15 lines before and after cursor
set scrolloff=15

"" Use system clipboard with 'intuitive' keys
"" These maps work in visual and insert mode, so I
"" don't need to worry about conflicts.
vmap <C-c> "+yi
vmap <C-x> "+c
vmap <C-v> c<ESC>"+p
imap <C-v> <C-r><C-o>+

"" keep search result at the center
nnoremap n nzz
nnoremap N Nzz

"" Wrap paragraphs with Q
map Q gq

"" To make undo work correctly
inoremap <C-U> <C-G>u<C-U>
inoremap <C-W> <C-G>u<C-W>

"" Sets the copy paste buffer large enough
set viminfo-='20,<9000,s9000

"" Sets the split to be open at below or right
set splitbelow
set splitright

"" [b to switch to previous buffer, and ]b to the next buffer and list
"" buffers after switching.
nnoremap [b :pclose<CR>:bprevious<CR>:redraw<CR>
nnoremap ]b :pclose<CR>:bnext<CR>:redraw<CR>

"" set hidden option so any buffer can be hidden (keeping its changes) without
"" first writing the buffer to a file, this affect all commands and all
"" buffers
set hidden

"" indent settings
set tabstop=2
set shiftwidth=2
set softtabstop=2
set smarttab
set expandtab

"" disable folding
set nofoldenable
set foldmethod=indent

"" auto resize splits
autocmd VimResized * wincmd =

最后是打开 vim,然后: PlugInstall 即可

长按按键==快速重复

defaults write -g ApplePressAndHoldEnabled -bool false

然后还要改系统设置

加速各种动画

(似乎用处不大,尤其是对于用键盘切换workspace,似乎完全没用)

Dock and Finder

defaults write com.apple.finder DisableAllAnimations -bool true
defaults write com.apple.dock springboard-show-duration -float .1
defaults write com.apple.dock springboard-hide-duration -float .1
defaults write com.apple.dock springboard-page-duration -float .2

Mission Control

# Speed up mission control
defaults write com.apple.dock expose-animation-duration -float 0.15

# To take effect:
killall Dock

# Disable mission control animations
defaults write com.apple.dock expose-animation-duration -float 0

# Bring back the default setting:
defaults delete com.apple.dock expose-animation-duration; killall Dock

语言以及输入法相关

  • 添加中文
  • 关闭自动大写
  • 使用 Caps Lock 做切换
  • 关闭使用两个空格来输入句号
  • 关闭 Smart Quote

调整Home键在Mac上面的功能

效果:

  • Home and End will go to start and end of line
  • Shift+Home and Shift+End will select to start and end of line
  • Ctrl+Home and Ctrl+End will go to start and end of document
  • Shift+Ctrl+Home and Shift+Ctrl+End will select to start and end of document
# 添加在 ~/Library/KeyBindings/DefaulKeyBinding.dict
{
  "\UF729"  = moveToBeginningOfParagraph:; // home
  "\UF72B"  = moveToEndOfParagraph:; // end
  "$\UF729" = moveToBeginningOfParagraphAndModifySelection:; // shift-home
  "$\UF72B" = moveToEndOfParagraphAndModifySelection:; // shift-end
  "^\UF729" = moveToBeginningOfDocument:; // ctrl-home
  "^\UF72B" = moveToEndOfDocument:; // ctrl-end
  "^$\UF729" = moveToBeginningOfDocumentAndModifySelection:; // ctrl-shift-home
  "^$\UF72B" = moveToEndOfDocumentAndModifySelection:; // ctrl-shift-end
}

MX Master 鼠标的设置

  • 安装Options,把鼠标的垂直滚轮调成正常的方向(系统默认的方向是reverse的,虽然touchpad用很合适,但是鼠标用实在是太反人类了)。
  • 在Options里面别忘了把Horizontal Wheel的功能设置一下。默认是switch page,完全就是添乱用的。改为水平滑动条就可以了。

标签