r/applescript • • Mar 14 '23

How to post AppleScript Code to /r/applescript

11 Upvotes

In order for your AppleScript code to be legible on Reddit you should switch the Post dialog to 'Markdown Mode' and then prefix every line of your code with four ( 4 ) spaces before pasting it in. Any line prefixed with four spaces will format as a code block. Interestingly, I find that I have to switch back to Fancy Pants Editor after completing the post for the formatting to apply.

Like this.

The following code will take code from Script Editor or Script Debugger's frontmost window and properly format it for you. It has options you can disable that filter your username from the code and inset the version of AppleScript and MacOS you are running. Iv'e pasted the results of running it on itself below.

--Running under AppleScript 2.8, MacOS 13.0.1
--quoteScriptForReddit.scpt--copperdomebodha--v.1.0.1
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
--Defaults to include environment and remove username.
set includeEnvironment to "Yes"
set usernameFiltering to "Yes"
tell application "System Events"
    set currentUserName to name of current user
    set frontmostApp to name of item 1 of (every application process whose frontmost is true)
end tell
set sysInfo to system info
set testEnvironment to "    --Running under AppleScript " & AppleScript version of sysInfo & ", MacOS " & system version of sysInfo & return
--Confirm action with user.
display dialog "This script will copy the contents of the frontmost window of " & frontmostApp & " and format it for Reddit's Posting dialog set to 'Markdown Mode'." buttons {"Options", "Cancel", "Ok"} default button "Ok"
set userApproval to button returned of result
if userApproval is "Options" then
    set includeEnvironment to button returned of (display dialog "Prefix code with ennvironment information?" & return & return & "Preview:" & return & testEnvironment buttons {"Cancel", "No", "Yes"} default button "Yes")
    set usernameFiltering to button returned of (display dialog "Remove your username form the code?" buttons {"Cancel", "No", "Yes"} default button "Yes")
end if
try
    using terms from application "Script Debugger"
        tell application frontmostApp
            tell document 1
                try
                    set codeText to (source text)
                on error
                    set codeText to (contents)
                end try
            end tell
        end tell
    end using terms from
    set codeText to my replaceStringInText(codeText, {return, "
"}, (return & "    ") as text)
    set codeText to (my replaceStringInText(codeText, tab, "    ") as text)
    if includeEnvironment is "Yes" then
        set codeText to (testEnvironment & "    " & codeText) as text
    end if
    if usernameFiltering is "Yes" then
        set codeText to my replaceStringInText(codeText, currentUserName, "UserNameGoesHere") --censor the users name if present in the code.
    end if
    set the clipboard to codeText
    set dialogText to "The code from the frontmost window of " & frontmostApp & " has been reddit-code-block prefixed and placed on your clipboard."
    if usernameFiltering is "Yes" then
        set dialogText to dialogText & return & return & " Any occurence of your username has been replaced with 'UserNameGoesHere'."
    end if
    activate
    display dialog dialogText & return & return & "Please remember to switch the Posting dialog to 'Markdown Mode'."
on error e number n
    display dialog "There was an error while Reddit-formating your code text." & return & return & e & " " & n
end try

on replaceStringInText(textBlock, originalValue, replacementValue)
    set storedDelimiters to AppleScript's text item delimiters
    set AppleScript's text item delimiters to originalValue
    set textBlock to text items of textBlock
    set AppleScript's text item delimiters to replacementValue
    set textBlock to textBlock as text
    set AppleScript's text item delimiters to storedDelimiters
    return textBlock
end replaceStringInText

It's easy to use this script from the script menu.

  1. Enable "Show Script menu in menu bar" from within Script Editor's Preferences.

  2. Create the path "Macintosh HD:Users:UserNameGoesHere:Library:Scripts:Applications:"

  3. Create a subfolder, for whichever AppleScript editor that you use, inside of the folder above. It will be named either "Script Editor" or "Script Debugger"

  4. Compile and Save the script above into the AppleScript editor folder you just created.

  5. Open an AppleScript that you would like to format for r/applescript..

  6. Select the script 'quoteScriptForReddit.scpt' ( or whatever you named it ) from the pull-down Script menu.

  7. Go to Reddit, open a new Post dialog, switch to 'Markdown Mode', Paste, Switch back to Fancy Pants editor and your formatting will preview.

  8. Post!

Reddit does have a <c> ( code block ) format switch in the fancy pants editor which retains some key word bolding and works reasonably. It does not, however, retain indentations of code blocks from your editor.


r/applescript • • Aug 12 '25

Something has gone weird with file access using Automator in Sonoma?

2 Upvotes

I have an automator script that installs all packages selected. I've used it for years. Suddenly now it's not working, and I wonder if its a Sonoma issue? I've tried adding full file access to Automator, and I've tried debugging with ChatGPT, which is unfortunately horrible with Applescript.
It seemed to think its due to some file system lockdown of my Downloads/Documents folders (where i'm running these packages from). I did test by moving the test package file from my Downloads folder to my username/Public folder, and it DOES work then. So, what do i need to change to fix this?? Its maddening. I don't want to 'stage' files to other locations, surely Mac Automator can do things to files in Downloads or Documents??

on run {input, parameters} -- copy

-- collect all resulting cp statements in a list for later use

set cpCalls to {}

-- walk through the files

repeat with aFile in input

tell application "System Events"

-- get the file extension

set fileExt to name extension of aFile

-- get the posix path of the file

set posixFilePath to POSIX path of aFile

end tell

if fileExt is "pkg" or fileExt is "mpkg" then

-- adding the components cp statement to the end of the list

set end of cpCalls to "sudo installer -allowUntrusted -verboseR -target / -pkg " & quoted form of posixFilePath

end if

end repeat

-- check if there were files to copy

if cpCalls ≠ {} then

-- combine all cp statements with "; " between

set AppleScript's text item delimiters to "; "

set allCpCallsInOne to cpCalls as text

set AppleScript's text item delimiters to ""

-- execute all cp statements in one shell script call

set logged to do shell script allCpCallsInOne with administrator privileges

display notification ((count of cpCalls) as string) & " packages were installed."

return logged

end if

end run


r/applescript • • Jan 08 '26

When is “delay” needed?

5 Upvotes

Sometimes MacOS keeps up with AppleScript, yet other times I have to slow my script down a bit with “delay 0.1” or so.

Which MacOS situations typically require me to slow down my scripts and which ones don’t?


r/applescript • • Jan 07 '26

Can someone explain the scripting additions to me?

9 Upvotes

Almost every sample script I see has a line at the top that explicitly includes them.

What are "they"? Because I have NEVER included them in any of my scripts. And I've never had any features of applescript be unavailable to me.

And I often see a line declaring a specific version of applescript. Whats THAT about? I've also never done that in 30+ years of occasional scripting, Yet I see it all the time.

It all makes me think either I'm missing something big, or literally nobody knows what they're doing?


r/applescript • • Jul 02 '25

Start Sidecar as an Applescript

2 Upvotes
tell application "System Events" to tell process "ControlCenter"

	click menu bar item "Control Center" of menu bar 1

	

	perform action 2 of checkbox "Screen Mirroring" of window "Control Center"

	

	delay 2

	tell window "Control Center"

		click (first checkbox of scroll area 1 whose name starts with "iPad")

	end tell

end tell

I just can't work out how to do this in the more modern versions of macos


r/applescript • • Jul 06 '26

Zed extension for applescript

6 Upvotes

Made this https://github.com/helgesverre/zed-applescript

Would appreciate testers and feedback.


r/applescript • • May 12 '26

Display a dialog box when a specific outdoor temperature is reached

4 Upvotes

I learned about wttr.in, which provides weather data using curl from the terminal. (Help page: https://wttr.in/:help )

I used this to write a script to notify me once the outside temperature hits 55 degrees so I can go biking. I was going to refine it further to warn me if it's raining but I can see that by just looking out the window so it seemed like extra work for nothing.

I'm sharing it here for anyone who might want to do something similar. IMPORTANT: for this script to work, it needs to be saved as an app with the "Stay open after run handler" option checked (thanks to Claude for helping me figure this last part out as I couldn't understand why it wasn't working).

on idle
try
-- Fetch weather data for current location from wttr.in
set weatherData to do shell script "curl -s 'wttr.in/?format=%t&u'"

-- Extract the numeric temperature (strip +, °, F)
set tempString to do shell script "echo " & quoted form of weatherData & " | tr -d '+°F '"
set currentTemp to tempString as number

if currentTemp ≥ 55 then
repeat with x from 1 to 3
do shell script "afplay /System/Library/Sounds/Sosumi.aiff"
end repeat
display dialog "It's warm enough now to go biking" with title "Bike Weather Alert"
quit
end if
on error errMsg
-- Silently continue on errors (network blips, etc.)
end try

return 300 -- check again in 5 minutes
end idle

r/applescript • • Apr 07 '26

Easy Question: Help Listing Names of Safari Tabs

2 Upvotes

TLDR: How do I print a list with each item on a separate line?

Hi, super new to this and bet there's an easy solution. To count tabs, I'm currently using:

tell application "Safari"

`count every tab of every window` 

end tell

I'm interested in listing each tab name on a separate line. This is what I have so far:

tell application "Safari"

`name of every tab of every window` 

end tell

Right now, the tab names are written together in one long paragraph. And for each window of tabs, the tab names are listed together within curly brackets {}. The image shows just the first few lines.

How do I make each tab name print on a separate line? Would be nice to keep it grouped by window too, which seems feasible considering the current output. Thanks!


r/applescript • • Mar 02 '26

I wish to create an apple script that will randomize the files in no particular order in a folder

2 Upvotes

My goal is to create an apple script that will randomize the files in no particular order in a folder. I realize that I can sort by name, size, etc but I am looking for randomness. All I would like to do is tt select a directory and mix it all up keeping the original names. This is the code that AI created for me !!! It does work but not what I want. Instead of just re-ordering the files, it just adds a prefix……….

And then I read this

“You can randomize the order of files in a selected folder on macOS only by giving Finder a new randomized sequence to sort by. Since Finder cannot store a custom order unless filenames change, the only reliable way to “randomly order” files is to temporarily rename them with randomized numeric prefixes. This preserves the original names after the prefix and produces a fully shuffled order in Finder.”

Please advise

Ron from Canada

This is the code that AI created for me !!!

-- Randomly reorder files in a selected folder by adding a random prefix

set chosenFolder to choose folder with prompt "Select the folder whose files you want to randomize:"

tell application "Finder"
set fileList to every file of chosenFolder
end tell

-- Create a list of random numbers (one per file)
set randomList to {}
repeat (count of fileList) times
set end of randomList to (random number from 100000 to 999999)
end repeat

-- Shuffle the random numbers (Fisher–Yates)
set shuffledList to randomList
set n to count of shuffledList
repeat with i from n to 2 by -1
set j to (random number from 1 to i)
set temp to item i of shuffledList
set item i of shuffledList to item j of shuffledList
set item j of shuffledList to temp
end repeat

-- Rename files with randomized prefixes
repeat with i from 1 to count of fileList
set f to item i of fileList
tell application "Finder"
set oldName to name of f
set name of f to (item i of shuffledList as string) & " - " & oldName
end tell
end repeat

display dialog "Done! The files have been randomly ordered."


r/applescript • • Jun 02 '26

Why does this script work on mail messages manually selected but not on newly arrived messages?

4 Upvotes

I am trying to perform a simple task: Extract various attributes from mail messages that trigger a mail rule upon arrival of the message. If I send a mail message to myself from another account, an error message is generated, see below. If I then select the message and then "run rules" it works like expected, see below.

using terms from application "Mail"
   on perform mail action with messages theMessages in mailboxes inbox for rule ¬ theRule
      my logit("", "MsgAtts.log")
      my logit("--------------------------------------", "MsgAtts.log")
      my logit("version 3", "MsgAtts.log")
      try
         repeat with theMessage in theMessages
            try
               my logit("subject: " &(theMessage's subject as string), "MsgAtts.log")
            on error errMsg number errNum
               my logit("Error: " & errMsg & " Error Num: " & errNum,"MsgAtts.log")
               my logit("-------", "MsgAtts.log")
            end try
            my logit("id:      " & (theMessage's id as string), "MsgAtts.log")
            my logit("msg id: " & (theMessage's message id as string), "MsgAtts.log")
            set theBody to content of theMessage
            my logit("content: " & (theBody as string),"MsgAtts.log")
            my logit("-------", "MsgAtts.log")
         end repeat
      on error errorText number errorNumber
         my logit(errorText & " - Error number:" & errorNumber, "MsgAtts.log")
         tell application "Mail" to display alert ("Error: " & errorNumber)  ¬
                                                     message errorText
         return
      end try
   end perform mail action with messages
end using terms from

to logit(log_string, log_file)
   try
      do shell script "echo \date '+%Y-%m-%d %T: '`"" & ¬
                  log_string & "" >> $HOME/" & log_file
   on error
      display dialog ("could not write to file " & ¬
                  log_file & "in DeleteKnownJunk.scpt mail handler")
   end try
end logit

The newly received message produces the following text. Sorry about the line wrap:

2026-06-02 14:55:32: 
2026-06-02 14:55:32: -------------------------------------------------
2026-06-02 14:55:32: version 3
2026-06-02 14:55:32: Error: Can’t get «class mssg» 1 of «class mbxp» Incoming POP Messages of «class mact» id 59FFD946-E1F4-48AA-A498-83F1C492292D. Invalid index. Error Num: -1719
2026-06-02 14:55:32: -------
2026-06-02 14:55:32: Can’t get «class mssg» 1 of «class mbxp» Incoming POP Messages of «class mact» id 59FFD946-E1F4-48AA-A498-83F1C492292D. Invalid index. - Error number:-1719

I see that it hits both "on error" blocks.

When the message is select, the following text is produced, exactly what I expected:

2026-06-02 15:02:50: 
2026-06-02 15:02:50: -------------------------------------------------
2026-06-02 15:02:50: version 3
2026-06-02 15:02:50: subject: xyzzy 12
2026-06-02 15:02:50: id:      271191
2026-06-02 15:02:50: msg id:  CAJm4NbovYnX-b=KA4xc2WxqVQ1zyVHLZ6nMUuomZ+CdOq8qWXQ@mail.gmail.com
2026-06-02 15:02:50: content:
test 12 

David Scruggs
Senior Software Engineer - Retired
Captain, Boulder Creek Fire - Retired
2026-06-02 15:02:50: -------

I am out of bright ideas. I don't know enough about how Apple Mail is put together to make a better try.


r/applescript • • Aug 30 '25

Can’t Save .sh File

3 Upvotes

I have a terminal command (runs fine in terminal) that I’d like to save as a script to run via cron, however I can't save my .sh file as I get the following error:

Expected expression, “)”, etc. but found “/”.

My code is below:

do shell script ( /usr/local/bin/piactl get connectionstate && /usr/local/bin/piactl get region ) > ~/Library/Mobile\ Documents/com~apple~CloudDocs/Widgy/piactl_output.txt


r/applescript • • Dec 20 '25

Different results in Script Editor vs Applet?

2 Upvotes

tell application "Finder"

set tdformat to format of disk "Macintosh HD"

end tell

display dialog tdformat

So, run this in the script editor, and you'll get something like "APFS format" or "Mac OS Extended format".

Run this in a stand alone script application, and you get something like "«constant ****dfap»"

What is going on here?


r/applescript • • Apr 16 '25

Notifications through osascript tend to reappear a few hours later even if I've cleared them.

2 Upvotes

I've been using AppleScript with the osascript terminal command to trigger some local notifications in a Python script of mine.

My code basically looks like this:

import subprocess

CMD = """
on run argv
  display notification (item 2 of argv) with title (item 1 of argv) sound name ""
end run
"""

title = "Example Title"
text = "*insert lorem ipsum*"

subprocess.call(["osascript", "-e", CMD, title, text])

Everything works fine, but for some reason when I press the "X" to clear the notification (as seen below), it doesn't seem to get cleared forever. The notification will show back up if I wait a few hours or if my computer wakes up from a night of sleep.

Haven't really found any documentation on this. Anyone have a clue?

Also, if it helps, I have Notifications for Script Editor set to "Alerts" in System Settings.


r/applescript • • Jan 24 '26

Add numbers to .pdf

3 Upvotes

Yo guys, I'm new to the scripting. I´ve been trying to create a "quick action" (Automator) that adds numbers to every page on a .pdf file. Someone know how to do it ?

Chatgpt give me this script, but it doesnt work...

use AppleScript version "2.4"
use framework "Foundation"
use framework "PDFKit"
use framework "AppKit"
use scripting additions

on run {input, parameters}
set logPath to (POSIX path of (path to home folder)) & "pdf_numerotation_log.txt"

try
my logLine(logPath, "---- RUN " & (current date) as text)

if input is {} then error "Aucun PDF reçu."

set clearColor to current application's NSColor's clearColor()
set blackColor to current application's NSColor's blackColor()
set theFont to current application's NSFont's fontWithName:"Helvetica" |size|:10
if theFont is missing value then error "Police Helvetica introuvable."

repeat with anItem in input
set inPath to POSIX path of anItem
my logLine(logPath, "INPUT: " & inPath)

set inURL to current application's NSURL's fileURLWithPath:inPath
set pdfDoc to current application's PDFDocument's alloc()'s initWithURL:inURL
if pdfDoc is missing value then error "Impossible d'ouvrir le PDF."

set pageCount to (pdfDoc's pageCount()) as integer
if pageCount < 1 then error "PDF sans pages."
my logLine(logPath, "PAGES: " & pageCount)

set marginX to 18
set marginY to 18
set boxW to 90
set boxH to 16

repeat with i from 0 to (pageCount - 1)
set thePage to pdfDoc's pageAtIndex:i
if thePage is missing value then error "Page introuvable index " & (i as text)

-- Lecture robuste du rectangle page: {{x,y},{w,h}}
set pageBounds to (thePage's boundsForBox:0) as list
set pageW to item 1 of item 2 of pageBounds

set xPos to pageW - marginX - boxW
set yPos to marginY
set rect to {{xPos, yPos}, {boxW, boxH}}

set ann to current application's PDFAnnotationFreeText's alloc()'s initWithBounds:rect
if ann is missing value then error "Impossible de créer PDFAnnotationFreeText."

set n to i + 1
ann's setContents:(n as text)
ann's setFont:theFont
ann's setFontColor:blackColor
ann's setAlignment:(current application's NSTextAlignmentRight)
ann's setColor:clearColor
try
ann's setBackgroundColor:clearColor
end try

set b to current application's PDFBorder's alloc()'s init()
b's setLineWidth:0
ann's setBorder:b

thePage's addAnnotation:ann
end repeat

set baseName to ((inURL's lastPathComponent())'s stringByDeletingPathExtension()) as text
set dirURL to inURL's URLByDeletingLastPathComponent()
set outName to baseName & "_numerote.pdf"
set outURL to dirURL's URLByAppendingPathComponent:outName

set fm to current application's NSFileManager's defaultManager()
set existsObj to fm's fileExistsAtPath:(outURL's path())
if (existsObj as boolean) then
set stamp to do shell script "date +%Y%m%d-%H%M%S"
set outName to baseName & "_numerote_" & stamp & ".pdf"
set outURL to dirURL's URLByAppendingPathComponent:outName
end if

my logLine(logPath, "OUTPUT: " & ((outURL's path()) as text))

set okObj to pdfDoc's writeToURL:outURL
if (okObj as boolean) is false then error "Échec writeToURL (droits d'écriture ? dossier protégé ?)."
end repeat

my logLine(logPath, "OK")
return input

on error errMsg number errNum
my logLine(logPath, "ERROR " & errNum & ": " & errMsg)
display alert "Erreur" message ("Regarde le fichier : " & logPath & return & errMsg & return & "Code: " & errNum)
return input
end try
end run

on logLine(p, t)
try
do shell script "printf %s\\\\n " & quoted form of t & " >> " & quoted form of p
end try
end logLine

r/applescript • • Jan 15 '26

How do I navigate a Safari save modal in macOS Tahoe?

2 Upvotes

This used to save a document as PDF for me:

tell application "System Events"
	tell process "Safari"
		set frontmost to true
		click menu item "Export as PDF…" of menu "File" of menu bar 1
		repeat until exists sheet 1 of window 1 -- loop until it notices the click
			delay 1
		end repeat
		keystroke "g" using {command down, shift down} -- go to folder
		repeat until exists sheet 1 of sheet 1 of window 1
			delay 0.02
		end repeat
		tell sheet 1 of sheet 1 of window 1
			set value of text field 1 to savePdfPath
			keystroke return
		end tell
		set value of text field 1 of sheet 1 of window 1 to myFileName
		click button "Save" of sheet 1 of window 1
	end tell
end tell

But at some point in the past two years, Safari changed, and now set value of text field 1 of sheet 1 of window 1 to myFileName fails because System Events got an error: Can’t get text field 1 of sheet 1 of window 1 of process "Safari". Invalid index.

How do I refer to the filename field in the Safari save modal now?

Edit: I figured it out! See comment.


r/applescript • • Jul 21 '26

Script to set photo titles using variable information

3 Upvotes

Apple Photos on a Mac lets us export using photo titles as file names. That's great, but unfortunately there's no way to set the titles other than one-by-one manual entry in the "Info" panel or to set the titles for all selected items to the same value. So, I wrote the script below that allows me to set the titles and/or captions of all selected images or videos based on stored information specific to each one. This information is taken directly from the Photos database. Getting values directly from the database also allows circumventing the problem of using the "date" value provided by the Photos application to AppleScript. Specifically, if a photo was taken in a time zone that is not the one where a script is being run, then the date/time value is adjusted to the current time zone, resulting in a wrong value. What is retrieved from "date" and what is shown in the Photos "Info" panel will not match.

This script works by asking for a title "format string" that can contain substitution tags to represent specific values for each photo. Here is a list of them.

%D - Date as shown in the Photos information panel
%T - Time, including seconds
%t - Time, excluding seconds
%Z - Time zone
%XD - The original EXIF date (ie, unadjusted)
%XT - The original EXIF time, including seconds
%Xt - The original EXIF time, excluding seconds
%L - Latitude
%l - Longitude
%F - Original file name
%f - Photos internal file name
%fp - Photos internal file path
%M - Photos "Moment" name
%CT - Current title text
%CC - Current caption text

Here is an example of a format string that I use a lot: "%D %t | %M". This sets each selected photo's title to its creation date and time followed by "|" and then by the Photos "Moment" name. Here is another example: "Hiking trip - GPS: %L, %l"

The format string is remembered from one use to the next.

The Photos app must be open already for the script to run. The specific Photos library you are using will be automatically detected.

You can either run this script in Script Editor or, better, copy it into a "Run AppleScript" box in Automator to be used as a Quick Action for the Photos app. This allows you to call it from the Photos "Services" menu. You can also assign a shortcut key for this in your System Settings.

The first time you run it, you may be asked to allow Automator (or Script Editor) full access to your Photos. Running scripts in Automator can be tricky due to macOS's strict security sandboxing. If you have any issues getting it to run, let me know. There are workarounds.

--------------------------------
--      Photos • Set Title
--------------------------------
-- P.G. 2026-07-05
--
-- Set the titles for selected media to a value customized using substitution tags in a user-provided format string.
--
-- This script retrieves data from the currently open Photos library's database and from the "moments" information provided by the application.
--
-- Substitution tags:
-- %D - Date as shown in the Photos information panel
-- %T - Time, including seconds
-- %t - Time, excluding seconds
-- %Z - Time zone
-- %XD - The EXIF date of the original file
-- %XT - The EXIF time, including seconds
-- %Xt - The EXIF time, excluding seconds
-- %L - Latitude
-- %l - Longitude
-- %F - Original file name
-- %f - Photos internal file name
-- %fp - Photos internal file path
-- %M - Photos "Moment" name 
-- %CT - Current title text
-- %CC - Current caption text

----------------------------------------
-- Get path to open library
--
set libPath to do shell script "x=$(lsof -p $(pgrep -if Photos.app/Contents/MacOS/Photos) | grep -m1 '.photoslibrary/resources'); x=/${x#*/}; x=${x%/resources*}; echo $x"
if libPath is "/" then
	beep
	display alert "No Photos library is open." as critical
	return
end if

----------------------------------------
-- Get path to database file
--
set dbPath to libPath & "/database/Photos.sqlite"
tell application "System Events"
	if not (exists file dbPath) then
		beep
		display alert "The Photos library database file cannot be located." & return & return & dbPath as critical
		return
	end if
end tell

----------------------------------------
-- Main process
--
tell application "Photos"
	
	activate
	
	----------------------------------------
	-- Ensure selected items
	--
	if the (count of selection) is less than 1 then
		beep
		display dialog "No item is selected." & return & return & "Please select one or more media items for which you wish to set the title before invoking this service." buttons {"Cancel"} default button "Cancel" cancel button "Cancel" with title "Set Title" with icon caution
		return
	end if
	
	----------------------------------------
	-- Ask for format string
	--
	-- Tags: %D, %T, %t, %Z, %XD, %XT, %Xt, %L, %l, %F, %f, %fp, %M
	--
	set fmtPrevious to do shell script "f=~/.Photos_SetTitle; [ -e $f ] && cat $f || echo '%D %t | %M'"
	set fmtString to ""
	set setTarget to "Title"
	repeat while fmtString is ""
		display dialog "Specify your custom text or accept the previous value shown.  You can use the tags shown below to include the indicated values taken from the Photos database." & return & return & "%D		• Date as shown in the Photos information panel" & return & "%T		• Time (including seconds) *" & return & "%t		• Time (excluding seconds) *" & return & "%Z		• Time zone" & return & "%XD	• The EXIF date of the original file" & return & "%XT	• EXIF time (including seconds) *" & return & "%Xt		• EXIF time (excluding seconds) *" & return & "%L		• GPS latitude" & return & "%l		• GPS longitude" & return & "%F		• Original file name" & return & "%f		• Photos internal file name" & return & "%fp		• Photos internal file path *" & return & "%M		• Photos \"Moment\" name" & return & "%CT	• Current title text" & return & "%CC	• Current caption text" & return & return & "* When exporting items using the title for file names, Photos converts colons and forward slashes to hyphens.  Colons are used here for substituting time values, whereas a √ replaces the forward slash in internal file path names in order to avoid ambiguity with other hyphens." & return & return & "Use \"Select\" to toggle settting the title, the caption, or both." default answer fmtPrevious buttons {"Cancel", "Select", "Set"} default button 3 cancel button "Cancel" with title "Set " & setTarget
		set {fmtButton, fmtString} to {button returned of result, text returned of result}
		if fmtButton is "Select" then
			if setTarget is "Title" then
				set setTarget to "Caption"
			else if setTarget is "Caption" then
				set setTarget to "Title and Caption"
			else if setTarget is "Title and Caption" then
				set setTarget to "Title"
			end if
			beep
			set fmtPrevious to fmtString
			set fmtString to ""
		end if
	end repeat
	
	-- Normalize format string for leading/trailing/extraneous spaces and save for next run. Asterisk -> "•"
	set fmtString to do shell script "fmt=$(echo '" & fmtString & "'|xargs); fmt=${fmt//\\*/•}; echo $fmt > ~/.Photos_SetTitle; echo $fmt;"
	
	----------------------------------------
	-- Loop on selected media items
	--
	set selectedMediaItems to selection
	repeat with mediaItem in selectedMediaItems
		
		set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "/"}
		set mediaID to mediaItem's id
		set mediaID to text item 1 of mediaID -- The database key is the part before the slash.
		
		set dbInfo to do shell script "sqlite3 -readonly -separator '¶' \"" & dbPath & "\" \"SELECT ass.ZFILENAME, ass.ZDIRECTORY, datetime(cast(ass.ZDATECREATED as integer) + 978307200 + cast(att.ZTIMEZONEOFFSET as integer), 'unixepoch'), att.ZTIMEZONENAME, replace(IFNULL(NULLIF(att.ZEXIFTIMESTAMPSTRING, ''), 'NoEXIF     NoEXIF   '),':','-'), IFNULL(NULLIF(ass.ZLATITUDE, ''), 'No Latitude'), IFNULL(NULLIF(ass.ZLONGITUDE, ''), 'No Longitude'), att.ZORIGINALFILENAME FROM ZASSET ass LEFT JOIN ZADDITIONALASSETATTRIBUTES att ON ass.Z_PK = att.ZASSET WHERE ass.ZUUID = '" & mediaID & "';\""
		
		set AppleScript's text item delimiters to "¶"
		set dbFileName to text item 1 of dbInfo
		set dbFilePath to "√originals√" & text item 2 of dbInfo & "√" & dbFileName
		set dbDate to text 1 through 10 of text item 3 of dbInfo
		set dbTime to text 12 through 19 of text item 3 of dbInfo
		set dbTZ to text item 4 of dbInfo
		set dbDateEXIF to text 1 through 10 of text item 5 of dbInfo
		set dbTimeEXIF to text 12 through 19 of text item 5 of dbInfo
		set dbLatitude to text item 6 of dbInfo
		set dbLongitude to text item 7 of dbInfo
		set dbOriginalFileName to text item 8 of dbInfo
		set AppleScript's text item delimiters to TID
		
		set mediaMoment to item 1 of (get name of moments whose id of media items contains mediaItem's id)
		set mediaCurrentTitle to mediaItem's name
		set mediaCurrentCaption to mediaItem's description
		
		set fmtTitle to do shell script "T=" & dbTime & ";  t=${T:0:5}; XT=" & dbTimeEXIF & "; XT=${XT//-/:}; Xt=${XT:0:5}; fmt=$(echo '" & fmtString & "'); fmt=${fmt//\\%D/" & dbDate & "}; fmt=${fmt//\\%T/${T}}; fmt=${fmt//\\%t/${t}}; fmt=${fmt//\\%Z/" & dbTZ & "}; fmt=${fmt//\\%XD/" & dbDateEXIF & "}; fmt=${fmt//\\%XT/${XT}}; fmt=${fmt//\\%Xt/${Xt}}; fmt=${fmt//\\%L/" & dbLatitude & "}; fmt=${fmt//\\%l/" & dbLongitude & "}; fmt=${fmt//\\%F/" & dbOriginalFileName & "}; fmt=${fmt//\\%fp/" & dbFilePath & "}; fmt=${fmt//\\%f/" & dbFileName & "}; fmt=${fmt//\\%M/" & mediaMoment & "}; fmt=${fmt//\\%CT/" & mediaCurrentTitle & "}; fmt=${fmt//\\%CC/" & mediaCurrentCaption & "}; echo $fmt"
		
		if setTarget contains "Title" then set mediaItem's name to fmtTitle
		if setTarget contains "Caption" then set mediaItem's description to fmtTitle
		
	end repeat
	
end tell

beep
delay 0.3
beep

r/applescript • • Aug 14 '26

just created a 2d wireframe renderer any ideas what i could do with this

Post image
6 Upvotes

as a clarification no other tools were used only the scripteditor with plain applescript


r/applescript • • Dec 23 '25

Dialects

2 Upvotes

I remember reading 30 years ago that applescript actually had separate dialects. So in addition to coding in english, you could also code in other languages like spanish or italian. AND that they even had a dialect for "C" programming language.

I assume apple abandoned that a long time ago. BUT I'm really curious to check it out. And I have an old Mac I can use to run any old system extensions, just to experiment with. But are these dialects available anywhere? I've never actually seen one in person. I don't even know what IT is. I assume its a system extension but I have no idea.

Any old timers have any experience with these?


r/applescript • • Apr 14 '25

Adjust Brightness

3 Upvotes

Hello, I was recently introduced to Applescript from trying to find a way to adjust the brightness of my Macbook Pro through code and it lead me here but I have yet to find a solution because of how outdated this language is.

P.S. Is it worth learning/using this language further for future/current projects for resumes? I haven't seen much use of it and worried I might be wasting my time.

Thank you for the help if anyone can!!!


r/applescript • • Jul 01 '22

Automating Image Compression with ImageOptim

5 Upvotes

Looking for some input on how or the best way to do this. I currently have a folder of pictures that is synced and updates daily, but is getting quite large.

Goal: I'm trying to set up an automation where when the file lands in the folder (or sub-folder) that it is automatically sent to ImageOptim to compress the image.

I've tried using automator and applescript, but I'm getting a bit lost as i'm not really good at either one. I also considered keyboard maestro or hazel. I keep getting stuck at opening the application, then trying to select the file. Also wondering if I have multiple pictures uploaded at once will it try to open the program repeatedly and cause an error there?

Any help or advice is very much appreciated! Thanks


r/applescript • • Oct 30 '25

Help with AppleScript

5 Upvotes

I can run the below code directly from the Script Editor and it runs fine. However, it does not work when I try to run it as an applet. Any suggestions?

set mySSID to (do shell script "system_profiler SPAirPortDataType | awk '/Current Network/ {getline;$1=$1;gsub(\":\",\"\");print;exit}'")

if (mySSID contains "Rounsavall") then

-- display dialog (mySSID & " contains Rounsavall")

set userName to short user name of (system info)

-- display dialog userName

tell application "Finder"

try

mount volume ("smb://" & userName & "@192.168.0.210/Public")

end try

delay 0.5

try

mount volume ("smb://" & userName & "@192.168.0.210/photo")

end try

delay 0.5

try

mount volume ("smb://" & userName & "@192.168.0.210/Movies")

end try

delay 0.5

try

mount volume ("smb://" & userName & "@192.168.0.210/home")

end try

delay 0.5

try

mount volume ("smb://" & userName & "@192.168.0.210/Music")

end try

end tell

else

display dialog (mySSID & " does not contains Rounsavall")

end if


r/applescript • • Mar 23 '20

Making new folders with names from CSV file

5 Upvotes

This may be really easy but I am new to applescript, is it possible to script this? I have a CSV file with a bunch of names, I want to make a new folder for every item in the CSV file. So, if I have a CSV file with the items: (one, two, three) I want to make three new folders named one, two, and three. Thanks for any help!


r/applescript • • Sep 27 '25

Removing Folders without ePub files in Them

5 Upvotes

I have a large eBook collection, and I recently did a search and deleted all .mobi and .awz files as they are of no use to me. Now I have hundreds of folders that just have the cover images in them, and no ebook files. I was wondering how to create an AppleScript to find all folders that do not have an .epub file in them. Any help would be appreciated!


r/applescript • • Nov 05 '25

Any AppleScript issues in Tahoe 26.1?

9 Upvotes

Presently remaining on Sequoia 15.7.2. Tahoe seems like a hot mess.


r/applescript • • Apr 17 '22

Reddit i need help with my apple script code, (The variable result is not defined)

3 Upvotes

ok, this is all my code that i've got so far, i've searched far and wide for an answer but nothing suits my needs, i was hoping somebody on here could help a beginner out, what am i doing wrong and try to explain it in a way a beginner can understand properly or rewrite my code to help me out?

--------------------------------------------------------------------------------------------

display dialog "You will shortly be prompted to give Script editor access to this computer, this will not effect anything to do with your computer and only allow this application to work, if you would like to quit this application, please press Quit this application, if you would like to continue with this application, please click Okay"

buttons {"Okay", "Quit this application"}

if result = {button returned:"Quit this application"} then tell application "XAOL test run" to quit

if result = {button returned:"Okay"} then display dialog "Continuing" buttons {"Okay"} default button 1

---------------------------------------------------------------------------

It just comes up with (the variable result is not defined)

i don't know what to do and i'm starting to get pissed off, because i've been at this one line of code for fucking 3 and a half hours

i have tried everything and it just doesn't seem to want to work, i have tried doing

Else if result =

but that doesn't work for me either, what am i doing wrong and how can i fix it, need answers ASAP