WSLとHyperを利用した環境を整える

はじめに

Windowsのコマンドラインでの作業はWindows独特のコマンドもあってやりにくく感じていました。できることならばLinuxのコマンド群を利用して作業をしたいところです。以前にはCygwinやMSYS2などを使っていましたが、どちらも微妙につらみがあり、最終的にはLinuxコマンド化を諦めてPowerShellを利用していました。

しかし、最近になってWindows Subsystem for Linux(WSL)が安定してきたようなので、WSLを利用して環境を整えてみました。1ヶ月ほど使ってみて割とよい感じだったので記録として残しておくことにします。

この記事では、WSLについて軽く説明したあと、今回利用するHyperというターミナルエミュレータの紹介と設定を行っていきます。

Windows Subsystem for Linuxとは

WSLの導入手順や、そもそもWSLが何者なのかということについては、次のページがとてもわかりやすかったです。

シス管系女子BEGINS 特別編 まんがでわかるWSL - 【シス管系女子】特設サイト

CygwinやMSYS2がコマンドレベルでの翻訳だったのに対し、WSLはカーネルレベルでの翻訳を行っているようです。そのため、LinuxのディストリビューションからLinuxカーネルを除いて代わりにWSLを利用することで、Linuxのディストリビューションがほとんど違和感なく動くそうです。すごい。現在はストアアプリとしてUbuntuやopenSUSE Leapなどが入手できるようになっています。

WSLは改良が続いており、ネット上の情報が古いこともあるので注意が必要です。 特にストア版になる前と後ではまったく違うので注意が必要になります。

Hyperとは

Electron製React、Reduxを利用したターミナルエミュレータです。Windowsのデフォルトのコマンドプロンプトはとても使いにくいので代わりに利用します。他にもWindowsのターミナルエミュレータというとConEmuなどがありますが、見た目などが好みなので今回はこちらを利用します。

Hyper™

以前は日本語の文字列の扱いに難があったのですが、バージョンが2になってからはcjk文字列も問題なく扱えるようになりました。

WindowsアプリとしてのUbuntuのインストール

まずはWSLが有効になっていない方はWSLを有効にする必要があります。「Windowsの機能の有効化または無効化」から「Windows Subsystem for Linux」を有効にしてWindowsを再起動しましょう。

WSLの有効化

Microsoft Storeから「Ubuntu 18.04」を検索し、インストールをします。

Ubuntu 18.04のインストール

Ubuntu 18.04をインストールし最初に起動すると少し待ったあとにユーザ名とパスワードを決めるよう求められます。指示にしたがい入力しましょう。

ユーザ名とパスワードの決定

これで問題なくUbuntuが起動しました。

その後パッケージのアップデートを行います。ダウンロードのサーバを日本に書き換えてからアップデートを行っています。

$ sudo sed -i 's/\/archive\.ubuntu/\/jp\.archive\.ubuntu/' /etc/apt/sources.list
$ sudo apt update
$ sudo apt upgrade

パッケージのアップデートの際にebtables関連でエラーが出る場合は、次のコマンドで解消できるようです。

$ sudo cp -p /bin/true /sbin/ebtables
$ sudo apt update -y
$ sudo apt upgrade -y

Errors in Ubuntu 18.04 on Windows 10 - Microsoft Community


タイムゾーンを東京に設定します。次のコマンドを実行後にAsiaからTokyoを選びます。

$ sudo dpkg-reconfigure tzdata

次に、私が普段よく利用するパッケージをインストールしていきます。

Git

$ sudo add-apt-repository ppa:git-core/ppa
$ sudo apt update
$ sudo apt install git

Gitで日本語のエンコーディングで文字化けする場合は次のコマンドを実行します。

$ git config --global i18n.commitencoding UTF-8

pandoc

$ wget https://github.com/jgm/pandoc/releases/download/2.2.1/pandoc-2.2.1-1-amd64.deb
$ sudo dpkg -i pandoc-2.2.1-1-amd64.deb
$ rm pandoc-2.2.1-1-amd64.deb

fish

$ sudo apt-add-repository ppa:fish-shell/release-2
$ sudo apt update
$ sudo apt install fish
$ sudo chsh -s `which fish`

fishのプラグインマネージャであるfishermanもインストールします。

$ curl -Lo ~/.config/fish/functions/fisher.fish --create-dirs git.io/fisherman

fishのテーマをfisherma経由でインストールします。

$ fisher omf/theme-bobthefish

fishのコンフィグファイルを作成します。

$ touch ~/.config/fish/config.fish
$ vi ~/.config/fish/config.fish

コンフィグファイルに次のテーマのコンフィグを追記します。

set -g theme_color_scheme base16-light
set -g theme_newline_cursor yes

このテーマはPowerlineフォントとともに使うことが想定されています。私はCicaというフォントを利用しています。

その他、fisherman経由で便利なプラグインを入れておきます。

$ fisher 0rax/fish-bd
$ fisher z

fzf

$ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf
$ ~/.fzf/install

fishのプラグインも入れます。

$ fisher fzf

fzfのデフォルトの設定も変更しました。

set FZF_DEFAULT_OPTS '--height 40% --reverse --border'

go

$ sudo apt install golang-go

$GOPATHを追加し$GOPATH/binにパスを通します。 以下をconfig.fishに追記します。

set -x GOPATH $HOME/go
set -x PATH $GOPATH/bin $PATH

ghq

$ go get github.com/motemen/ghq

Windows側のghqとパスを合わせるために~/.gitconfigへ以下を追記します。

[ghq]
    root = /mnt/c/Users/<username>/<ghq>

<username>にはWindowsのユーザ名を、<ghq>には Windows側のghqのルートを入れます。これでWSL上でのghqでもWindows側と同じghqのrootを見てくれるようになります。

fishのghq用拡張もインストールします。

$ fisher decors/fish-ghq

これでCtrl-gからghqのパッケージのリストが見れるようになります。

fnm

fish用のNode.jsのバージョン管理用のコマンドです。

$ fisher fnm
$ fnm latest

これで最新版のnodeとnpm、npxがインストールされました。

hexo

$ npm i hexo-cli -g

WSL側で立てたローカルサーバーはWindows側からでも見ることができるので、hexo serverの結果をWindows側のブラウザで確認することもできます。うまくいかない場合はhexo cleanでキャッシュを削除して再度試しましょう。

インストールのあとに

最後にfishのコマンド補完をリロードしておきます。

$ fish_update_completions

これで新しくインストールしたパッケージにもfishのコマンド補完が自動生成されます。

Hyperのインストール

公式サイトからダウンロードしてインストールをしましょう。立ち上げると次のようになります。

Hyperの様子

最初はcmd.exeが動いています。HyperでWSLを利用するために.hyper.jsの次の項目を次のように書き換えます。

shell: 'C:\\Windows\\System32\\wsl.exe',
shellArgs: [],

これでHyperのデフォルトでWSLが立ち上がるようになりました。


Hyperでは.hyper.jsのプラグインの項目にプラグイン名を記入すると、裏でnpmによるプラグインのインストールが行われます。プラグインのリストはこちらになります。バージョン2に対応しておらず、動かないプラグインも多いので注意が必要です。

今回は次のHyperのプラグインやテーマを入れていきます。

hyperterm-overlay - npm

ターミナルを最前面で表示するようにし、グローバルショートカットキーでターミナルを呼び出せるようにするプラグインです。

グローバルショートカットキーはCtrl-F12と使っていなかったHOMEキーに割り当てました。これでどこからでもターミナルをショートカット一発で表示できるため便利です。縦に長い画面のほうが長いログなどが見やすいため、ターミナルの表示位置はデフォルトの上側から画面の右側にしました。

URLをハイパーリンクにしてくれるプラグインです。 Hyperの画面やデフォルトブラウザでURLを開いてくれるようになります。これがあるだけでターミナルが格段に使いやすくなります。

hyper-tab-icons - npm

Tabのアイコンを実行しているプロセスに合わせて変更してくれるプラグインです。 Nodeを動かしているときはタブにNodeのアイコンが表示されるらしいです。 華やかになりそうなのでとりあえず入れておきます。

hyper-ayu - npm

テーマはとりあえずこれにしてみました。

hyper-opacity - npm

Windows環境でもターミナルを半透明にするプラグインです。Electronの問題かデフォルトではMac OSしか半透明に対応していないので、こちらのプラグインを入れます。フォーカス時とフォーカス外れたときの透明度を変えられるという利点もあります。


以上の設定も含めて設定ファイルの.hyper.jsは次のようになりました。

// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // choose either `'stable'` for receiving highly polished,
    // or `'canary'` for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 13,

    // font family with optional fallbacks
    fontFamily: 'Cica, Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // default font weight: 'normal' or 'bold'
    fontWeight: 'normal',

    // font weight for bold characters: 'normal' or 'bold'
    fontWeightBold: 'bold',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // terminal text color under BLOCK cursor
    cursorAccentColor: '#000',

    // `'BEAM'` for |, `'UNDERLINE'` for _, `'BLOCK'` for █
    cursorShape: 'BLOCK',

    // set to `true` (without backticks and without quotes) for blinking cursor
    cursorBlink: true,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    // opacity is only supported on macOS
    backgroundColor: '#000',

    // terminal selection color
    selectionColor: 'rgba(248,28,229,0.3)',

    // border color (window, tabs)
    borderColor: '#333',

    // custom CSS to embed in the main window
    css: '',

    // custom CSS to embed in the terminal window
    termCSS: '',

    // if you're using a Linux setup which show native menus, set to false
    // default: `true` on Linux, `true` on Windows, ignored on macOS
    showHamburgerMenu: '',

    // set to `false` (without backticks and without quotes) if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` (without backticks and without quotes) on Windows and Linux, ignored on macOS
    showWindowControls: '',

    // custom padding (CSS format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#C51E14',
      green: '#1DC121',
      yellow: '#C7C329',
      blue: '#0A2FC4',
      magenta: '#C839C5',
      cyan: '#20C5C6',
      white: '#C7C7C7',
      lightBlack: '#686868',
      lightRed: '#FD6F6B',
      lightGreen: '#67F86F',
      lightYellow: '#FFFA72',
      lightBlue: '#6A76FB',
      lightMagenta: '#FD7CFC',
      lightCyan: '#68FDFE',
      lightWhite: '#FFFFFF',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // PowerShell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: 'C:\\Windows\\System32\\wsl.exe',

    // for setting shell arguments (i.e. for using interactive shellArgs: `['-i']`)
    // by default `['--login']` will be used
    shellArgs: [],

    // for environment variables
    env: {},

    // set to `false` for no bell
    bell: 'SOUND',

    // if `true` (without backticks and without quotes), selected text will automatically be copied to the clipboard
    copyOnSelect: true,

    // if `true` (without backticks and without quotes), hyper will be set as the default protocol client for SSH
    defaultSSHApp: true,

    // if `true` (without backticks and without quotes), on right click selected text will be copied or pasted if no
    // selection is present (`true` by default on Windows and disables the context menu feature)
    // quickEdit: true,

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
    overlay: {
      alwaysOnTop: true,
      animate: false,
      hasShadow: false,
      hideDock: true,
      hideOnBlur: false,
      hotkeys: ['Ctrl+F12', 'HOME'],
      position: 'right',
      primaryDisplay: false,
      resizable: true,
      startAlone: true,
      startup: true,
      size: 0.5,
      tray: true,
      unique: false,
    },

    opacity: {
      focus: 0.85,
      blur: 0.65,
    }
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'hyperterm-overlay',
    'hyperlinks',
    'hyper-tab-icons',
    'hyper-ayu',
    'hyper-opacity',
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  },
};

テーマで上書きされる色の設定など意味のないものもデフォルト値のまま放置してあります。


最終的にこのような見た目になりました。

スクリーンショット

(普段は違う壁紙を利用していますが、スクリーンショット撮影のためにデフォルトの壁紙にしました)

おわりに

Windows上のファイル操作が手慣れたLinuxのコマンドで行えるようになったの扱いやすいです。ターミナルがショートカットキー一発で出てくるようになったのも嬉しいところです。これで、Windowsを普段遣いするのにはなかなかよい環境を構築できたと思います。

一方で、WSLは一部独特な部分があるようなので、まじめにLinuxとして運用したいのならば仮想環境などを用意したほうがよさそうです。