nokoのブログ

こちらは暫定のメモ置き場ですので悪しからず

Macの初期セットアップ手順メモ(vivaldi, vscode, xonsh, etc)(2021)

はじめに

  • Macを初期セットアップしたときのメモ。

キーバインド設定

  • システム環境設定 > キーボード > caps lock -> command(キーボードごとに)
  • ctrlとcmdの入れ替え
  • 入力ソースにローマ字とABC
  • システム環境設定 > キーボード > ショートカット > 入力ソースの変換(英数かな文字変換) command + space (Spotlightは ctrl + space に)
  • 辞書登録

デスクトップ設定

Docks設定

Vivaldi

  • スタートページ登録(新規タブはスタートページ)
  • 設定
    • command + q でタブを閉じる
  • 拡張機能インストール
    • Gmail送信チェッカー
    • Google翻訳
    • Full Page Screen Capture
    • DeepL
    • (switch omega)
  • ダウンロードディレクトリはデスクトップに変更
  • タブは下
  • サイドバーは右。ダウンロード、お気に入り、ウィンドウ

Chrome

Clipy

  • command × 2
  • command + ctrl + R
  • command + ctrl + S

Alfred

Line

Zoom

Slack

Boost Note(EverNote

ToDoist

iTerm2

  • カラー
    • Tango Dark
  • 文字サイズ
    • 16
  • ホットキー設定+デスクトップ上に被せてフルスクリーンで表示
    • iTerm2 > Preferences > General > Window > Native full screen windowsのチェックを外す
    • iTerm2 > Preferences > Profiles > Window > Settings for New Windows > Style, Screen, Space
    • iTerm2 > Preferences > Keys > HotKey > Show/hide iTerm2 with a system-wide hotkeyにチェック
    • command 2回をホットキー設定(Profilesの方から)
    • pin hotkey

ssh設定

  • .ssh/config設定
Host own-dev-app01
    HostName 3.14.15.92
    Port 22
    User ec2-user
    IdentityFile ~/.ssh/own-dev-key.pem
    IdentitiesOnly yes
    TCPKeepAlive yes

vim

# 事前にbrewのインストール
# echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc
brew install vim
~/.vimrc
"----------------------------------------
" setting
"----------------------------------------
"文字コードをUFT-8に設定
set fenc=utf-8
" バックアップファイルを作らない
set nobackup
" スワップファイルを作らない
set noswapfile
" 編集中のファイルが変更されたら自動で読み直す
set autoread
" バッファが編集中でもその他のファイルを開けるように
set hidden
" 入力中のコマンドをステータスに表示する
set showcmd

"----------------------------------------
" 見た目系
"----------------------------------------
" 行番号を表示
set number
" タイトルを表示
set title
" 現在の行を強調表示
set cursorline
" 行末の1文字先までカーソルを移動できるように
set virtualedit=onemore
" 括弧入力時の対応する括弧を表示
set showmatch
" ステータスラインを常に表示
set laststatus=2
" コマンドラインの補完
set wildmode=list:longest
" 折り返し時に表示行単位での移動できるようにする
nnoremap j gj
nnoremap k gk
" シンタックスハイライトの有効化
syntax enable
" コメントの色を水色
hi Comment ctermfg=3

"----------------------------------------
" Tab系
"----------------------------------------
" 不可視文字を可視化(タブが「▸-」と表示される)
set list listchars=tab:\▸\-
" Tab文字を半角スペースにする
set expandtab
" 行頭以外のTab文字の表示幅(スペースいくつ分)
set tabstop=4
" 行頭でのTab文字の表示幅
set shiftwidth=4

"----------------------------------------
" 検索系
"----------------------------------------
" 検索文字列が小文字の場合は大文字小文字を区別なく検索する
set ignorecase
" 検索文字列に大文字が含まれている場合は区別して検索する
set smartcase
" 検索文字列入力時に順次対象文字列にヒットさせる
set incsearch
" 検索時に最後まで行ったら最初に戻る
set wrapscan
" 検索語をハイライト表示
set hlsearch

Python3

$ brew install pyenv 
$ pyenv install 3.9.2 
$ pyenv global 3.9.2 
$ mkdir -p ~/opt/python_env 
$ cd python_env; pwd 
# 上記でセットアップしたpythonを利用
# /Users/<USER>/.pyenv/versions/3.9.2/bin/python -V
$ python -m venv py392env 
$ source /Users/username/opt/python_env/py392env/bin/activate 
$ pip install numpy 
$ pip install Pillow 
$ pip install jupyter 
$ jupyter notebook --notebook-dir=~/pj/ & 
# Tabnineのインストール

xonsh

  • xonshインストール
# python仮想環境activate後に実施
$ pip install xonsh
$ pip install gnureadline

$ brew install bash-completion2
$ brew install peco

$ which xonsh
->iTerm各プロファイルのCommandを上記パスに修正
  • xonshrcの設定
# python
# source-bash source /Users/username/opt/python_env/py364env/bin/activate

# path
$PATH.append("/usr/local/bin/")

# prompt
$PROMPT = "{INTENSE_RED}{user}{INTENSE_GREEN}@{INTENSE_BLUE}{hostname}{INTENSE_YELLOW} [ {cwd} ] {GREEN}$ "

# tab
$INDENT = "    "

# completion
$COMPLETIONS_CONFIRM = True

# ls
$LS_COLORS="di=34:ln=35:so=32:pi=33:ex=31:bd=46;34:cd=43;34:su=41;30:sg=46;30:tw=42;30:ow=43;30"

# alias
aliases["lt"] = "ls -ltr"
aliases["la"] = "ls -la"
aliases["ll"] = "ls -l"

# complement command and ssh
import os
import json
from collections import OrderedDict
from operator import itemgetter
from prompt_toolkit.keys import Keys
from prompt_toolkit.filters import (Condition, IsMultiline, HasSelection, ViInsertMode)
from prompt_toolkit import print_formatted_text
from prompt_toolkit.styles import Style

@events.on_ptk_create
def custom_keybindings(bindings, **kw):
    # ctrl+rで過去の実行コマンドをpeco
    @bindings.add('c-r')
    def select_history(event):
        sess_history = $(history).split('\n')
        hist = _get_history(sess_history)
        selected = $(echo @(hist) | peco)
        event.current_buffer.insert_text(selected.strip())

    # ctrl+sでssh_config内のhost先をpeco
    @bindings.add('c-s')
    def select_ssh(event):
        hosts = _get_host(True)
        selected = $(echo @(hosts) | peco)
        if selected:
            event.current_buffer.insert_text('ssh ' + selected.strip().split(', ')[0])

    # ctrl+fで今いるディレクトリのfileをpeco
    @bindings.add('c-f')
    def select_file(event):
        r = lambda x: './'+x if os.path.isdir(x) else x
        files = '\n'.join([r(x.split(' ')[-1]) for x in $(ls -l).split('\n')])
        selected = $(echo @(files) | peco)
        event.current_buffer.insert_text(selected.strip())

inquirer_style = Style.from_dict({
    'qa': '#5F819D',
    'qu': '#FF9D00',
    'dp': '#000'
})

def _get_history(session_history=None, return_list=False):
    hist_dir = __xonsh__.env['XONSH_DATA_DIR']
    files = [ os.path.join(hist_dir,f) for f in os.listdir(hist_dir)
              if f.startswith('xonsh-') and f.endswith('.json') ]
    file_hist = []
    for f in files:
        try:
            file_hist.append(json.load(open(f))['data']['cmds'])
        except:
            pass
    cmds = [ ( c['inp'].replace('\n', ''), c['ts'][0] )
                 for cmds in file_hist for c in cmds if c]
    cmds.sort(key=itemgetter(1))
    cmds = [ c[0] for c in cmds[::-1] ]
    if session_history:
        cmds.extend(session_history)
    # dedupe
    zip_with_dummy = list(zip(cmds, [0] * len(cmds)))[::-1]
    cmds = list(OrderedDict(zip_with_dummy).keys())[::-1]
    cmds = reversed(cmds)
    if return_list:
        return cmds
    else:
        return '\n'.join(cmds)

def _get_host(color=False):
    all_text = ''
    text = ''
    for x in $(cat ~/.ssh/config).split('\n'):
        if 'LocalForward' in x:
            text += ', ' + x.strip().split(' ')[1]
        if 'HostName' in x:
            text += ', ' + x.strip().split(' ')[1]
        elif 'Host ' in x:
            if text!='':
                all_text += text + '\n'
            text = x.split(' ')[1]
    all_text += text + '\n'
    if not color:
        all_d = []
        for x in all_text.split('\n'):
            for i,y in enumerate(x.split(', ')):
                if i==0:
                    all_d.append(('class:qu', y))
                if i==1:
                    all_d.append(('', ', '))
                    all_d.append(('class:qa', y))
                    if len(x.split(', '))==2:
                        all_d.append(('','\n'))
                if i==2:
                    all_d.append(('', ', '))
                    all_d.append(('class:qp', y))
                    all_d.append(('','\n'))
        print_formatted_text(FormattedText(all_d),
                style=inquirer_style)
        return
    return all_text

aliases['host']=_get_host

Docker

VS Code

  • font 16
  • Color theme Solalized Dark-
  • [表示]  > [コマンドパレット] > install coと入力 > シェルコマンドを・・・を選択 : code <ファイル名>で開けるように設定
  • venvpathに上記でインストールしたvenvのパスを記載
  • [表示]  > [コマンドパレット] > select intと入力 > インタプリターを・・・を選択 : インタプリタを設定
  • 拡張機能

    • Vim
    • vscode-icons-mac
    • trailing spaces
    • Bracket Pair Colorizer
    • Rainbow CSV
    • Output Colorizer
    • Indenticator
    • indent-rainbow
    • Python
    • Tabnine
    • YAML
    • Remote Development
    • Terraform
    • Docker
    • Markdown All in One
  • キーボードショートカット

// Place your key bindings in this file to overwrite the defaults
[
{
    "key": "cmd+t",
    "command": "workbench.action.files.newUntitledFile" },
{
    "key": "cmd+q",
    "command": "workbench.action.closeActiveEditor"
},
{
    "key": "cmd+h",
    "command": "editor.action.startFindReplaceAction"
},
]

おわりに

  • とりあえず上記で始めて、使いながら追加していこうと思います。