Learning AppleScript

Published January 5, 2022


Hello. I've always wanted to learn AppleScript in order to replace my Mac tracking apps and save a bit of money. Over this break, I had time to do that. And it seems to be about as hard as I expected it to be, which is to say it's simple to the point of being hard to learn. Here's an example

Applescripts is written in this natural language sort of format. You expect that makes it easier to learn and read and write, but it doesn't unless you know the syntax. Much like how a Python aficionado would find it difficult to explain to a newbie how they know of all the different built-in functions, I find it similarly hard to learn the types and values that variables can take on in an AppleScript.

I've written a few atomic scripts and tips I wanted to share, and I'll show them in this post. Like usual, examples of other scripts helped me learn how to write my own. For Applescripts, I had an interesting problem that my example code wouldn't work when I began to switch in my own variables. This leads me to tip #1

Tip #1: Do not name your variables "yes"

Everyone has a default name for trash variables that will be replaced by something more descriptive later, and mine happens to be "yes". However, if you name your variables yes in your Applescript, you are going to have a bad time. The script throws a funky error that doesn't mention that yes is a built-in word that cannot be assigned.

Tip #2: Applescript has no OOP, at least officially

This means when you try to write a more complicated Applescript and want to be a good little SWE who uses objects and functions, you will encounter various forum posts which tell you that AS is not meant for this stuff and you should give up. Maybe I just phrased my problem poorly, but my desire to make functions is solved perfectly by subroutines, which nobody mentioned until I saw it on an Applescripts blog.

There are also not AppleScript blogs in the same way that there are Javascript/CSS blogs. Being Apple fans, each of the AS tutorial websites is written in a legible fashion. However they are nowhere as smooth as those CSS blogs showing live examples of X property. I understand that this is because scripts cannot be played online, but it still makes it hard when they show no pictures of what the output is supposed to look like.

OK, onto the examples.

Examples

Spotify Context

############ Get current spotify usage
on getSpotify()
    set retList to {""}
    if application "Spotify" is running then
        tell application "Spotify"
            if player state is playing then
                set tr to current track
                set retList to {name of tr, artist of tr, player position, (duration of tr) / 1000, id of tr}
            end if
        end tell
    end if
    return retList
end getSpotify

My problem with learning from example Applescript I read online is that the examples are not clearly cross-applicable and the errors you get are not helpful. I can read this code perfectly fine, and you probably can too — but it's a trap to trick you into thinking you know how to write it! This took me like an hour because I kept naming my variable yes, but even when I stopped that it still took me a while to realize "application "x"" is not replaceable with a macro like it would be in C.

Current date and time, formatted as a timestamp or filename

########## get current date/time formatted as a sortable string
on date_format(adate) -- Old_date is text, not a date.
    set {year:y, month:m, day:d, time:t} to adate
    set delim to "."
    set yada to (y as string) & delim & (m as integer) & delim & d & delim & t
    return yada
end date_format

Here you'll note that I did not include the word "yes" as my variable, but notice how similar it is to the current variable "yada". Wonder how that happened...

Get currently focused app and path to that app

Remixed from Stack Overflow

############ Get URL and name of focused app
set windowTitle to ""
tell application "System Events"
    set frontApp to first application process whose frontmost is true
    set frontAppName to name of frontApp
    tell process frontAppName
        tell (1st window whose value of attribute "AXMain" is true)
            set windowTitle to value of attribute "AXTitle"
        end tell
    end tell
    set appfilepath to POSIX path of application file of frontApp
end tell

Get the URL of any application that has a URL or path (Finder, Preview, Chrome, Safari)

Remixed from Stack Overflow, [1] [2]

############ Get URL of current chrome/safari/preview/finder tab
set currentTabUrl to ""
if (frontAppName = "Safari") or (frontAppName = "Webkit") then
    tell application "Safari" to set currentTabUrl to URL of front document
else if (frontAppName = "Google Chrome") or (frontAppName = "Google Chrome Canary") or (frontAppName = "Chromium") then
    tell application "Google Chrome" to set currentTabUrl to URL of active tab of front window
else if (frontAppName = "Preview") then
    tell application "Preview" to set currentTabUrl to path of front document
else if (frontAppName = "Finder") then
    tell application "Finder"
        if exists Finder window 1 then
            set currentDir to target of Finder window 1 as alias
        else
            set currentDir to desktop as alias
        end if
        set currentTabUrl to POSIX path of currentDir
    end tell
end if

Conclusion

That's all I got for now. I'm going to try to run a continuous log of my current laptop's "context", so I need file appending eventually. Until then, cya later!

applescript scripting quantifiedself