Mac標準ターミナルをいつでもどこでも呼び出したい(表示・非表示を切り替えてすぐにターミナルを使いたい)と思い方法を色々探ってみたのですが、なかなかいい方法が見つからなかったのでAppleScriptでスクリプトを書きKarabiner Elementsに設定することで実現したのでメモ。
Macの標準機能ではCmd+Hでウインドウを隠す動作が可能ですが、隠したあとウインドウを呼び戻すのは少し困難です。また、隠したウインドウを再表示することも難しいので、これまではiTerm2のような別ターミナルの機能で実現していました。
今回は、Terminalが最前面にあるときに、Cmd+`
を押すと非表示になり、もう一度押すと最前面に戻ってくるような動作にしています。
これを応用してTerminal以外にも任意のアプリケーションに適用することができます。
前提
- macOS
- 今回は Mojave 10.14.6
- Karabiner-Elements(Karabiner)
- 今回は12.7.0
が使えること
方法
Scriptの作成
以下のApple ScriptをKarabinerの.config配下に保存します。
$ mkdir -p ~/.config/karabiner/scripts $ vim toggle_terminal.script ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ set name_of_app to "Terminal" tell application "System Events" get name of application processes whose frontmost is true and visible is true end tell if Result contains name_of_app then tell application "System Events" set visible of process name_of_app to false end tell else tell application "System Events" set frontmost of process name_of_app to true set visible of process name_of_app to true end tell end if ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ためしに実行してみる
$ osascript ~/.config/karabiner/scripts/toggle_terminal.script # Terminalが消える #
set name_of_app to "Terminal"
のTerminalのところを別の名前にしてもOK
これを任意のショートカットキーに紐付けるだけです。
Karabinerに登録
以下のファイルを作成します
$ vim ~/.config/karabiner/assets/complex_modifications/terminal.json ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ { "title": "スーパーすごいショートカット", "rules": [ { "description": "TerminalのShow/Hide", "manipulators": [ { "from": { "key_code": "grave_accent_and_tilde", "modifiers": { "mandatory": [ "left_command" ] } }, "to": [ { "shell_command": "osascript ~/.config/karabiner/scripts/toggle_terminal.script" } ], "type": "basic" } ] } ] } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
KarabinerのJSON記述方法はおググりを🙏
あとはKarabinerのPreference>Complex Modifications>Add Rule>にターミナルの〜があるのでEnableにするだけ
補足
Apple Scriptむずい