2
1

More than 3 years have passed since last update.

JXAでFinderのカレントパスをiTerm2で開く

Last updated at Posted at 2019-12-29

前々からJXAに興味があったので、練習がてら書いてみました。
AppleScriptを一から覚えるのは面倒ですが、JXAなら一度勝手が分かれば、スラスラ書けそうな気がします。同様のことをAppleScriptでやる記事は良く見かけますが、JXAでは見かけなかったので、誰かの参考になれば幸いです。

Script Editorで記述したスクリプトは、メニューバーから
File > Export...を選択し、File FormatにApplicationを選択して保存。cdtoやgo2shellなどと同様に、Finderのツールバーに配置して利用できます。

サンプルコード

open-cwd-with-iterm2.js

(function () {
    // iTerm2以外の任意のアプリケーションの実行可能パスも指定可能
    let exePath = "/Applications/iTerm.app/Contents/MacOS/iTerm2";

    let finder  = Application("Finder");
    let frontWindow = finder.windows().filter(function (w) {return w.index() == 1;})[0];
    let cwd = $.NSURL.alloc.initWithString(frontWindow.target().url()).fileSystemRepresentation;
    let app = Application.currentApplication();
    app.includeStandardAdditions = true;
    cmd = `open -a "${exePath}" "${cwd}"`;
    result = app.doShellScript(cmd, {
        administratorPrivileges: false,
        withPrompt: '',
        alteringLineEndings: false
    });
    console.log(result);
})();

任意のアプリケーションの実行可能パス取得方法

  1. Finderで/Applicationsを開く
  2. 任意アプリケーション(*.app)を右クリしてShow Package Contentを選択
  3. Contents/MacOS/ の中から実行可能ファイルを見つけ右クリ
  4. Optionキーを押下しながら、コンテキストメニューの中からCopy "XXXX" as Pathnameを選択する

アプリケーションの実行可能パス例

Name Path
Visual Studio Code /System/Volumes/Data/Applications/Visual Studio Code.app/Contents/MacOS/Electron
Visual Studio Code - Insiders /System/Volumes/Data/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron
Sourcetree /System/Volumes/Data/Applications/Sourcetree.app/Contents/MacOS/Sourcetree
Fork /System/Volumes/Data/Applications/Fork.app/Contents/MacOS/Fork
Sublime Merge /System/Volumes/Data/Applications/Sublime Merge.app/Contents/MacOS/sublime_merge
/System/Volumes/Data/Applications/Sublime Merge.app/Contents/SharedSupport/bin/smerge
Sublime Text /System/Volumes/Data/Applications/Sublime Text.app/Contents/MacOS/Sublime Text
/System/Volumes/Data/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl

アイコン変更方法

  1. Finderで/Applicationsを開く
  2. 任意アプリケーション(*.app)をコピー(Cmd+c)
  3. open-cwd-with-app.appを右クリしてGet Infoを選択(Cmd+i)
  4. 左上のアイコンを選択してペースト(Cmd+v)
2
1
0

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
2
1