LoginSignup
128
114

More than 3 years have passed since last update.

tmuxとMacのクリップボードを共有する(copy-mode, vim)

Last updated at Posted at 2014-02-25

環境

OS X: 10.9.1
tmux: 1.9
vim: 7.4.161

:warning: tmux 2.4 からは、以下で説明している vi-copycopy-mode-vi に変更になりました。また、 copy-pipe 相当の動作は copy-pipe-and-cancel となりました
:warning: tmux 2.6 からは、以下で説明している reattach-to-user-namespace の設定は不要です。copy-pipe-and-cancel には単に "pbcopy" を指定すればOKです

tmuxのコピーコマンドでのクリップボード共有

下記の方法でvimライクの設定にすることができる。

tmux Copy & Paste on OS X: A Better Future

使うのはreattach-to-user-namespace。Homebrewでインストールできる。

ChrisJohnsen/tmux-MacOSX-pasteboard

$ brew install reattach-to-user-namespace
.tmux.conf
# Use vim keybindings in copy mode
setw -g mode-keys vi

# Setup 'v' to begin selection as in Vim
bind-key -t vi-copy v begin-selection
bind-key -t vi-copy y copy-pipe "reattach-to-user-namespace pbcopy"

# Update default binding of `Enter` to also use copy-pipe
unbind -t vi-copy Enter
bind-key -t vi-copy Enter copy-pipe "reattach-to-user-namespace pbcopy"

これで<prefix> [でコピーモードに入った時に、vで選択を開始しyもしくはEnterで選択範囲をコピーできるようになる。

tmux上で起動したvimのクリップボード共有

上記方法ではtmux上で起動したvimで依然クリップボードが使えず、Nothing in register *というエラーが表示される。
これを回避するには、reattach-to-user-namespaceをtmuxのdefault-commandに設定する。

.tmux.conf
set-option -g default-command "reattach-to-user-namespace -l bash"

それでもダメな場合

しかし、僕の環境ではこの設定をするとtmuxが[exited]というログとともにすぐに終了してしまうようになってしまった。

default-commandの設定を消し、tmux内ですぐに

$ exec reattach-to-user-namespace -l "$SHELL"

を実行すると有効になるが、面倒くさい。

そこで、aliasを作る。

alias vim="reattach-to-user-namespace vim"

結局vimだけ共有されていれば良いので、これで十分な感じだ。tmux起動していない時もalias貼られるのがちょっともやっとするけど。

参考: Sharipov Ruslan : tmux 1.8 + vim/MacVim: easy OSX clipboard integration

シェルスクリプトを使う方法

いろいろ試した結果、どうも次のようなシェルスクリプトでラッピングすると使えるようになるみたいだ。

login-shell
#! /usr/bin/env bash

# Ensure that tmux windows are by default named after the shell, rather than
# full path to the shell binary.
shell=$(basename "$SHELL")

# If reattach-to-user-namespace is not available, just run the command.
if [ -n "$(command -v reattach-to-user-namespace)" ]; then
  reattach-to-user-namespace -l "$shell"
else
  exec "$shell"
fi
.tmux.conf
set-option -g default-command "login-shell"

権限設定を忘れずに。

$ chmod +x ~/bin/login-shell
128
114
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
128
114