Applescript if no file is added

Viewed 74

I have the following automator apple script that I'm using so that when I drag a file into a dock icon, it opens that file in vim:

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, I would also like to allow clicking the icon itself to open vim without any file, i.e., running $ vim. How would I change the above script so that:

  • If a filename is passed, I open vim with that file, vim filename
  • If no filename is passed (the icon is just double-clicked), it just opens vim, with vim ?
1 Answers

The following example AppleScript code will do as you've asked; however, keep in mind that input is a list and as presently coded it is expecting a single item list, meaning you've only dragged and dropped one file onto the app's Dock Tile:

on run {input, parameters}

    if not input is equal to {} then
        set filename to POSIX path of first item of input
        set cmd to "clear && 'vim' '" & filename & "' && exit"
    else
        set cmd to "clear && 'vim' '" & "' && exit"
    end if

    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

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Related