macosapplescriptitunesapple-music

Apple Music/iTunes English Capitalisation script - AppleScript


I'm trying to run the following script in the Apple Music app to use proper English capitalisation on the selected tracks (ignoring anything that is in all capital letters to start)

So for example the track name...

opportunities (Let's MAKE lots of money) (Reprise)

should become

Opportunities (Let's MAKE Lots of Money) (Reprise)

It looks like it should work, i'm getting no syntax errors or errors at all - it's simply not doing anything at all to the tracks selected in Apple Music.

on properEnglishCapitalization(textString)
    set newText to do shell script "echo " & quoted form of textString & " | perl -pe 's/(?<=\\b|^)(\\w)/\\U$1/g'"
    return newText
end properEnglishCapitalization

tell application "Music"
    set selectedTracks to selection
    if selectedTracks is not {} then
        repeat with aTrack in selectedTracks
            set trackName to name of aTrack
            set newName to my properEnglishCapitalization(trackName)
            if newName is not trackName then
                set name of aTrack to newName
                set loved of aTrack to loved of aTrack
            end if
        end repeat
    end if
end tell

Solution

  • By default, the latter's case is not considered. So, add considering case.

    Also, checking if the selection is empty no need when referring to list items instead of indexes of list items. So, you can remove the first if statement. When the selection is empty, the repeat loop is simply ignored.

    on properEnglishCapitalization(textString)
        set newText to do shell script "echo " & quoted form of textString & " | perl -pe 's/(?<=\\b|^)(\\w)/\\U$1/g'"
        return newText
    end properEnglishCapitalization
    
    tell application "Music"
        repeat with aTrack in (get selection) -- SIMPLIFIED
            set trackName to name of aTrack
            set newName to my properEnglishCapitalization(trackName)
            considering case -- ADDED
                if newName is not trackName then
                    set name of aTrack to newName
                    set loved of aTrack to true -- EDITED
                end if
            end considering -- ADDED
        end repeat
    end tell
    

    Additional tests.

    By default:

    "animal" is not "AniMal" --> false, the case ignored
    

    With case considering:

    considering case
        "animal" is not "AniMal"
    end considering --> true (that is, you need this form)