Applescriptでファイル名を取得 | ネットでゴロニャン

ネットでゴロニャン

気が向いたら更新

ファイル.tex を NeoVim-iTerm で開くためのスクリプト。

ファイルをvimコマンドで閉じたときにカレントディレクトリで

iTermを作業できる状態にしておきたいので

ファイルのフルパスをフォルダ名とファイル名に分けて

両者を別々に取得しておく必要があるのだが、

これを applescript で完結しようとすると

一筋縄ではいかないようだ。丸1日かかったけど、

とりあえずコンパイルできたので記念カキコ。

参考サイトはこことかこことかこことかこことか。

自分でも何やったのか全く覚えてないw

何はともあれ、有志の皆様に感謝。

↑後日作り直したので一応リンク貼っておきます。
下記は試作段階のものです。Finderでツリーを展開した状態でクリックするとパスを途中までしか認識できません。

 
on run {input, parameters}


    set fullpath to POSIX path of input
    --    tell application "System Events"
    --        set pName to name of disk item fullpath
    --    end tell
    --   pname と後述の fname は同じだそうだ。
    set aFile to POSIX file fullpath
    tell application "Finder"
        set fname to name of (aFile as alias)
        set hfsCurrentFolder to insertion location as Unicode text
        set currentFolder to get POSIX path of hfsCurrentFolder
    end tell
    
    set myCmd to "cd " & currentFolder
    
    if application "iTerm" is running then
        tell application "iTerm"
            try
                tell current window
                    create tab with default profile
                    delay 0.5
                    tell current session of current tab
                        write text myCmd
                        write text "nvim " & fName
                    end tell
                end tell
                activate
            on error errMsg
                create window with default profile
                delay 0.5
                tell current session of current window
                    write text myCmd
                    write text "nvim " & fName
                end tell
                activate
            end try
            
        end tell
    else
        tell application "iTerm"
            -- ターミナルが起動していない場合は launch で起動する
            -- launch しないと暗黙的に run され,ウィンドウが1つ開いてしまう
            launch
            create tab with default profile
            delay 0.5
            tell current session of current window
                delay 0.5
                write text myCmd
                write text "nvim " & fName
            end tell
            activate -- 最前面に表示
        end tell
    end if
    
end run