1

I would like to open certain files in Vim (iTerm2) when I double-click on them in Finder (similar to this question)

The following snippet I found on this website gets most of the job done

on run {input, parameters}

set filename to POSIX path of input

    set cmd to "clear && 'vim' '" & filename & "' && exit"

    tell application "iTerm"
        set newWindow to (create window with default profile)
            tell current session of newWindow
                write text cmd
            end tell
    end tell

end run

However, after opening a file in Vim, another iTerm window is opened, which is brought to the foreground. As a result, I have to close the extra window before I can see the opened file.

Is it possible to modify the script or change a preference in iTerm2 to prevent the second window from opening? Ideally, I would like iTerm to open a window with the default profile when I manually open iTerm but do not open an additional window when double clicking on files in Finder.

I tried changing the "Open a window at startup?" option under Advanced to No, but it did not make a difference. Although this option could only solve the original problem, I had to manually open a window every time I started iTerm.

1
  • 1
    ITerm2 has a Symantec History function that allows you to define what to do with files you Cmd-Click on. This can be opening in an editor, running a script, etc.
    – Allan
    Apr 20 at 18:28

1 Answer 1

2

Here is how I managed to address this problem:

on run {input, parameters}
    
    set filename to POSIX path of input
    
    set cmd to "clear && 'vim' '" & filename & "' && exit"
    
    if application "iTerm" is running then
        tell application "iTerm"
            set newWindow to (create window with default profile)
            tell current session of newWindow
                write text cmd
            end tell
        end tell
    else
        activate application "iTerm"
        tell application "iTerm"
            repeat until (exists current window)
                delay 0.1
            end repeat
            set newWindow to current window
            tell current session of newWindow
                write text cmd
            end tell
        end tell
    end if
    
end run

The script works fine without the repeat statement on my older machine, but needs to be present for the script to work on my M1 mac.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .