Get Value for a Key in a Plist

In macOS Tahoe, you can assign Spotlight quick keys to a shortcut or action, and I wondered if there might be a way to get a list of quick key assignments and the shortcut or action they invoke.

The following plist file appears to contain the quick keys. Just to make sure, I created a new quick key for a test shortcut, and it was almost immediately reflected in this plist.

/Users/robert/Library/Preferences/com.apple.Spotlight.plist

The following is a snippet from this plist, and the tt quick key at the end calls a shortcut I’ve created named Empty Trash.

<key>SSActionKeyboardAliasStoreKey</key>
<dict>
	<key>com.apple.shortcuts</key>
	<dict>
		<key>0293D944-E22E-4A2D-958F-609AC139B177</key>
		<string>miifw</string>
		<key>036F36CF-073C-4E66-951F-A1751C4847AA</key>
		<string>xx</string>
		<key>042955D8-7E2E-4679-BEE1-020CD09765E0</key>
		<string>st</string>
		<key>04D56F93-4A37-4C35-A01E-9CB9CD85613A</key>
		<string>w21</string>
		<key>052F47C6-6D84-4AE7-B3D8-A413B25A6F46</key>
		<string>cf</string>
		<key>0B935398-D20F-42EB-99A8-7D43F6B4B352</key>
		<string>ir</string>
		<key>1048</key>
		<string>cls</string>
		<key>1070F44E-F262-43AD-B688-207425584E2D</key>
		<string>tt</string>
		<key>110C7FE8-4784-489C-8FEE-8F8BB54A15F8</key>

I assume that the key value is what I want, and I wondered if anyone knows how to get a name value for this key (or even if this is possible). I can read the plist file with the defaults command but I haven’t gotten beyond that point. Thanks for the help.

1 Like

System Events can read property list files since ages.

I’ve not (yet) upgraded to Tahoe so I don’t have this particular key but this might be a starting point assuming the key is on the top level

tell application "System Events"
	set spotlightPlistPath to path of preferences folder & "com.apple.spotlight.plist"
	set spotlightPlist to property list file spotlightPlistPath
	set actionKeys to value of property list item "SSActionKeyboardAliasStoreKey" of contents of spotlightPlist
end tell
2 Likes

Thanks Stefan. Your script does return the applicable section of the plist file, and that’s helpful. After running your script, I happened to notice that some quick key assignments have keys that contain predefined shortcut actions (an example is is.workflow.actions.number.random). Perhaps the keys that contain a series of random numbers and letters refer to shortcuts that I have created and that are only understood by the Shortcuts app.

peavine,
I always enjoy reading your posts about Shortcuts — they’re really helpful and inspiring.

My English isn’t great, so I might be misunderstanding your point,
but the KEY in com.apple.shortcuts’s DICT is the UUID, right?
It seems to be linked to each Shortcut’s ID.

tell application "Shortcuts Events"
	set listShortCuts to name of every shortcut as list
end tell
repeat with itemShortCuts in listShortCuts
	tell application "Shortcuts Events"
		tell shortcut itemShortCuts
			log id as text
			--> com.apple.shortcuts DICT KEY
			log name as text
		end tell
	end tell
end repeat

It looks like it might be possible to get the ID from Shortcuts Events
and then edit the PLIST to register a quick key.

I’m not sure if it works in an English environment,
but here’s the script to get the UUID.


#全てのショートカット(Shortcuts)をリストにする
# List all Shortcuts

tell application "Shortcuts Events"
	#ショートカット(Shortcuts)のリスト
	# List of Shortcuts
	set listShortCuts to every shortcut as list
	#ショートカット(Shortcuts)名のリスト
	# List of Shortcut names
	set listShortCutName to name of every shortcut as list
	#ショートカット(Shortcuts)のIDリスト
	# List of Shortcut IDs
	set listShortCutID to id of every shortcut as list
	#フォルダのリスト
	# List of folders
	set listFolder to every folder as list
	#フォルダ名のリスト
	# List of folder names
	set listFolderName to name of every folder as list
	#フォルダIDのリスト
	# List of folder IDs
	set listFolderID to id of every folder as list
end tell


#ダイアログ
# Dialog
try
	tell current application
		activate
		set refResponse to (choose from list listShortCutName with title "選んでください(Please choose)" with prompt "選んでください(Please choose)" default items (first item of listShortCutName) OK button name "OK" cancel button name "Cancel" with multiple selections allowed without empty selection allowed)
	end tell
	
on error strErrMes number numErrNo
	log "エラーしました(An error has occurred)"
	return false
end try
if (class of refResponse) is boolean then
	log "Error キャンセルしました(Error: Operation canceled)"
	return false
else if (class of refResponse) is list then
	if refResponse is {} then
		log "Error 何も選んでいません(Error: Nothing selected)"
		return false
	else
		#戻り値リスト
		#Return list
		set listShortCutsName to refResponse as list
	end if
end if

set strLog to ("") as text

#順番に実行する
#Execute in order
repeat with itemShortCuts in listShortCutsName
	tell application "Shortcuts Events"
		tell shortcut itemShortCuts
			set strID to id as text
			set strName to name as text
			#	run
		end tell
	end tell
	
	log "" & strID & ": " & strName & ""
	set strLog to (strLog & strID & "\r") as text
	set strLog to (strLog & strName & "\r") as text
	set strLog to (strLog & "\r") as text
end repeat


return strLog



Hope this information is useful.

1 Like

Thanks IceFole–that’s perfect. Both of your scripts worked great.

The following is a proof-of-concept script that returns a list of lists with each sublist containing the Quick Keys and the name of the Shortcut. This was my original goal, and I’ll probably modify the script to write the list to a text file.

--This shortcut returns a list of lists containing Quick Keys and their corresponding shortcut name.

use framework "Foundation"
use scripting additions

set homeFolder to current application's NSHomeDirectory() as text
set plistFile to homeFolder & "/Library/Preferences/com.apple.Spotlight.plist" --change robert to correct value

try
	set quickKeyAssignments to ((current application's NSUserDefaults's alloc()'s initWithSuiteName:plistFile)'s objectForKey:"SSActionKeyboardAliasStoreKey")'s valueForKey:"com.apple.shortcuts"
on error
	display dialog "The applicable section of the plist file was not found" buttons {"OK"} cancel button 1 default button 1
end try

set theUUIDs to quickKeyAssignments's allKeys() as list
set theQuickKeys to quickKeyAssignments's allValues() as list

set namesAndQuickKeys to {}
set errorList to {}
tell application "Shortcuts Events"
	repeat with i from 1 to (count theUUIDs)
		try
			set shortcutName to name of shortcut id (item i of theUUIDs)
			set end of namesAndQuickKeys to {item i of theQuickKeys, shortcutName}
		on error
			set end of errorList to item i of theQuickKeys
		end try
	end repeat
end tell

return namesAndQuickKeys
# return errorList

I think this can easily be modified to set Quick Keys assignments in the plist file. I’ll work on that.

Just as a point of general information, the plist file appears to contain Quick Key assignments for shortcuts that were deleted days ago. These are skipped by use of the try statement (hopefully). System Settings has a “Reset Quick Keys” option, which may need to be used periodically. Or, perhaps this is a bug that will be fixed.

The following is the errorList on my computer:

{“qq”, “reqcf”, “rqcf”, “o”, “os”, “qcrw”, “a2”, “a”, “gd”, “ct”, “x”, “rqcs”, “qq”, “qrcoref”, “x”, “qrcorf”, “a”, “gp”, “clf”, “ii”, “test”, “qq”, “cls”, “test”, “miifw”, “xxx”, “cc”, “gert”, “x1”, “tt”, “xx1”, “w21”, “ee”, “a3”, “cot”, “xx1”, “test”, “rdm”, “kk”, “ts”, “t”, “smt”, “slt”, “xx”, “xx”, “qrcrf”, “xxx”, “ee”, “qrcrw”, “qrcrs”, “qrcors”, “qq”, “xxx”, “xxx”, “grt”, “test”, “xxx”, “chc”, “xx”, “x2”, “xxx”, “xxx”, “qcr”, “chco”, “cfs”, “tqa”, “te”, “qrcores”, “tes”, “qcrf”, “cs”, “oso”, “qcrs”}

After resetting the Quick Keys in System Settings, the errorList was empty.

1 Like

I’ve been looking at the scripts from StefanK and peavine (very helpful, by the way!),
and it got me thinking — maybe it’s possible to:

  • save the contents of Quick Keys, and
  • restore them later.

So, I tried a few things.

For restoring Quick Keys, I figured I could use ASOC,
I know I could just copy and save the plist file
but for saving the values, I wondered if I could store them as a record
(since that would make adding or editing much easier).

After some experimenting… I ended up with a rather clunky script :sweat_smile:
I’m pretty sure there’s something fundamentally wrong with it,
and halfway through I was like, “Wait, what am I even doing?”

I think there’s definitely a more efficient way —
so I’ll keep trying a bit longer!


###############
#com.apple.spotlight.plist record
set recordActionKeyName to ("set recordActionKeyName to {")
set recordShortcutsKeyID to ("set recordStoreKey to {")

set aliasPrefDirPath to (path to preferences folder from user domain) as alias
tell application "Finder"
	set aliasPlistFilePath to (file "com.apple.spotlight.plist" of folder aliasPrefDirPath) as alias
end tell
set strPlistFilePath to (POSIX path of aliasPlistFilePath) as text
tell application "System Events"
	set plistSpotlight to (property list file strPlistFilePath)
	set plistActionKeys to (property list item "SSActionKeyboardAliasStoreKey" of contents of plistSpotlight)
	set plistShortcuts to property list item "com.apple.shortcuts" of plistActionKeys
	set listShortcuts to (every property list item of plistShortcuts) as list
	set numCntKey to (count of listShortcuts) as integer
	repeat with itemIntNo from 1 to numCntKey by 1
		set itemRcord to item itemIntNo of listShortcuts
		set strItemName to name of itemRcord as text
		set strItemvalue to value of itemRcord as text
		set recordActionKeyName to (recordActionKeyName & "|" & strItemName & "|: ")
		set recordShortcutsKeyID to (recordShortcutsKeyID & "|" & strItemvalue & "|: ")
		set recordActionKeyName to (recordActionKeyName & "\"" & strItemvalue & "")
		set recordShortcutsKeyID to (recordShortcutsKeyID & "\"" & strItemName & "")
		if itemIntNo = numCntKey then
			set recordActionKeyName to (recordActionKeyName & "\"} as record")
			set recordShortcutsKeyID to (recordShortcutsKeyID & "\"} as record")
		else
			set recordActionKeyName to (recordActionKeyName & "\",")
			set recordShortcutsKeyID to (recordShortcutsKeyID & "\",")
		end if
	end repeat
end tell

###############
#Shortcuts Events record
set recordShortcutsName to ("set recordShortcutsName to {")
set recordShortcutsID to ("set recordShortcutsID to {")

tell application "Shortcuts Events"
	set listShortcuts to the name of every shortcut as list
	set numCntList to (count of listShortcuts) as integer
end tell


set numCntRepeat to 1 as integer
repeat with itemShortCuts in listShortcuts
	tell application "Shortcuts Events"
		tell shortcut itemShortCuts
			set strItemID to id as text
			set strItemName to name as text
			#
			set recordShortcutsName to (recordShortcutsName & "|" & strItemID & "|: ")
			set recordShortcutsID to (recordShortcutsID & "|" & strItemName & "|: ")
			set recordShortcutsName to (recordShortcutsName & "\"" & strItemName & "")
			set recordShortcutsID to (recordShortcutsID & "\"" & strItemID & "")
			if numCntRepeat = numCntList then
				set recordShortcutsName to (recordShortcutsName & "\"} as record")
				set recordShortcutsID to (recordShortcutsID & "\"} as record")
			else
				set recordShortcutsName to (recordShortcutsName & "\",")
				set recordShortcutsID to (recordShortcutsID & "\",")
			end if
		end tell
	end tell
	set numCntRepeat to numCntRepeat + 1 as integer
end repeat

set strScriptText to ("\r" & recordActionKeyName & "\r\r" & recordShortcutsKeyID & "\r\r" & recordShortcutsName & "\r\r" & recordShortcutsID & "\r\r") as «class utf8»

###############
#MakeAppleScript

set aliasDesktopDirPath to (path to desktop folder from user domain) as alias
set strDesktopDirPath to (POSIX path of aliasDesktopDirPath) as text
set strSaveFilePath to ("" & strDesktopDirPath & "ShortcutsRecord.applescript") as text

tell application "Finder"
	try
		make new document file at aliasDesktopDirPath with properties {name:"ShortcutsRecord.applescript"}
	end try
end tell
set aliasSaveFilePath to (POSIX file strSaveFilePath) as alias
try
	set refReadFile to open for access aliasSaveFilePath with write permission
	write strScriptText to refReadFile as «class utf8» starting at eof
	close access refReadFile
on error
	close access refReadFile
end try

tell application "Script Editor"
	set refActivDoc to open file aliasSaveFilePath
	tell refActivDoc
		compile
	end tell
	tell refActivDoc
		save as "text" in aliasSaveFilePath with stay open without run only and startup screen
	end tell
end tell

By the way, I assigned tt to the same function too.:smile:

System Events is pretty handy to read property list files but can be cumbersome to modify and write them.

The Foundation framework provides API’s to deal with Property List and JSON.

This example reads the property list with NSPropertyListSerialization and writes the dictionary com.apple.sortcuts as JSON to disk using NSJSONSerialization

set strPlistFilePath to POSIX path of (path to preferences folder) & "com.apple.spotlight.plist"
set shortcutsBackupPath to POSIX path of (path to desktop) & "shortcutsBackup.json"

set plistData to current application's NSData's dataWithContentsOfFile:strPlistFilePath
set {plist, plistError} to current application's NSPropertyListSerialization's propertyListWithData:plistData options:0 format:(missing value) |error|:(reference)
if plistError is not missing value then
	error (plistError's localizedDescription() as text)
else
	set actionShortcuts to (plist's objectForKey:"SSActionKeyboardAliasStoreKey")
	set {shortcutsJSONData, jsonError} to current application's NSJSONSerialization's dataWithJSONObject:actionShortcuts options:0 |error|:(reference)
	if jsonError is not missing value then
		error (jsonError's localizedDescription() as text)
	else
		set {success, writeError} to shortcutsJSONData's writeToFile:shortcutsBackupPath options:0 |error|:(reference)
		if not success then
			error (writeError's localizedDescription() as text)
		end if
	end if
end if

As you can see you don’t need the Finder to create the POSIX file path. An HFS path can be coerced to POSIX path directly. And all path to expressions return alias specifiers, the coercion to alias is redundant.

The reverse is straightforward. Read the property list and the JSON to dictionary, update the dictionary in the preference plist and write it back with NSPropertyListSerialization.

1 Like

StefanK,

Backup data in JSON format is great!
It’s very convenient, and editing is easy, so it’s really nice.

I decided to give it a try right away.
It’s a bit long, but (I know it’s unnecessarily long even for myself, so please just ignore that part).

I ran into two issues during the restore process:

When I killed Spotlight with HUP, it sometimes took a long time—up to 3 minutes—for Spotlight to restart.

At some point (I’m not sure exactly when), Spotlight would crash when performing a restore.
I was able to recover by resetting Quickkey from the Spotlight panel in System Settings.

So, this might be a “suspicious process.”
If you don’t like dealing with trouble (who does?), it might be better not to try it.
Just something to keep in mind as a reference.

Spotlight Quick key BackUp JSON.scpt

#!/usr/bin/env osascript
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

#READ PLIST
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidPlistFilePathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Preferences/com.apple.Spotlight.plist") isDirectory:(false)

#SAVE DIR 
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDocumentDirPathURL to ocidURLsArray's firstObject()
set strDateText to doGetDateNo("yyyyMMdd-hhmmss") as text
set strSaveDirName to ("Apple/Spotlight/" & strDateText) as text
set ocidSaveDirPathURL to ocidDocumentDirPathURL's URLByAppendingPathComponent:(strSaveDirName) isDirectory:(true)
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s init()
ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions)
set listDone to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)

#SAVE FILE
set ocidJsonPathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("com.apple.shortcuts.json") isDirectory:(false)
set ocidApplescriptPathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("com.apple.Spotlight.applescript") isDirectory:(false)

#DICT
set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error|:(reference)
set ocidPlistDict to (first item of listResponse)
set ocidSSStoreKeyDict to ocidPlistDict's objectForKey:("SSActionKeyboardAliasStoreKey")
if ocidSSStoreKeyDict = (missing value) then
	return "SSActionKeyboardAliasStoreKey 404"
end if
set ocidShortcutsDict to ocidSSStoreKeyDict's objectForKey:("com.apple.shortcuts")
if ocidShortcutsDict = (missing value) then
	return "com.apple.shortcuts 404"
end if

#NSJSONSerialization
set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
set listResponse to (refMe's NSJSONSerialization's dataWithJSONObject:(ocidShortcutsDict) options:(ocidOption) |error|:(reference))
set ocidJsonData to (first item of listResponse)

#Applescript
set ocidJsonString to refMe's NSString's alloc()'s initWithData:(ocidJsonData) encoding:(refMe's NSUTF8StringEncoding)
set ocidJsonString to (ocidJsonString's stringByReplacingOccurrencesOfString:("{\"") withString:("set recordStoreKey to {|"))
set ocidJsonString to (ocidJsonString's stringByReplacingOccurrencesOfString:("\":\"") withString:("|:\""))
set ocidJsonString to (ocidJsonString's stringByReplacingOccurrencesOfString:("\",\"") withString:("\",|"))
set ocidJsonString to (ocidJsonString's stringByReplacingOccurrencesOfString:("}") withString:("} as record"))
set listDone to ocidJsonString's writeToURL:(ocidApplescriptPathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)

#SAVE JSON
set ocidOption to (refMe's NSDataWritingAtomic)
set listDone to ocidJsonData's writeToURL:(ocidJsonPathURL) options:(ocidOption) |error|:(reference)

#Save Dir OPEN
set appSharedWorkspace to refMe's NSWorkspace's sharedWorkspace()
set boolDone to appSharedWorkspace's openURL:(ocidSaveDirPathURL)

return boolDone
##DATE NO
to doGetDateNo(strDateFormat)
	set ocidDate to current application's NSDate's |date|()
	set ocidNSDateFormatter to current application's NSDateFormatter's alloc()'s init()
	ocidNSDateFormatter's setLocale:(current application's NSLocale's localeWithLocaleIdentifier:"ja_JP_POSIX")
	ocidNSDateFormatter's setDateFormat:(strDateFormat)
	set ocidDateAndTime to ocidNSDateFormatter's stringFromDate:(ocidDate)
	set strDateAndTime to ocidDateAndTime as text
	return strDateAndTime
end doGetDateNo


Spotlight Quick Key Restore JSON.scpt

#!/usr/bin/env osascript
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions
property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

#Dialog
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDocumentDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidDocumentDirPathURL to ocidURLsArray's firstObject()
set ocidSaveDirPathURL to ocidDocumentDirPathURL's URLByAppendingPathComponent:("Apple/Spotlight") isDirectory:(true)
set aliasSaveDirPath to (ocidSaveDirPathURL's absoluteURL()) as alias
set listUTI to {"public.json"} as list
set strMes to ("Choose BackUP JSON FILE") as text
set strPrompt to ("Choose BackUP JSON FILE") as text

set aliasJsonFilePath to (choose file strMes with prompt strPrompt default location (aliasSaveDirPath) of type listUTI without invisibles, showing package contents and multiple selections allowed) as alias

#JSON FILE
set strJsonFilePath to (POSIX path of aliasJsonFilePath) as text
set ocidJsonFilePathStr to refMe's NSString's stringWithString:(strJsonFilePath)
set ocidJsonFilePath to ocidJsonFilePathStr's stringByStandardizingPath()
set ocidJsonFilePathURL to refMe's NSURL's fileURLWithPath:(ocidJsonFilePath) isDirectory:(false)
#NSDATA
set ocidOption to (refMe's NSDataReadingMappedIfSafe)
set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidJsonFilePathURL) options:(ocidOption) |error|:(reference)
set ocidJsonData to (first item of listResponse)
#JSON DICT
set ocidOption to (refMe's NSJSONReadingJSON5Allowed)
set listResponse to (refMe's NSJSONSerialization's JSONObjectWithData:(ocidJsonData) options:(ocidOption) |error|:(reference))
set ocidRestoreJsonDict to (first item of listResponse)

#READ FILE
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidPlistFilePathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Preferences/com.apple.Spotlight.plist") isDirectory:(false)
#DICT
set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error|:(reference)
set ocidPlistDict to (first item of listResponse)
set ocidPlistDictM to ocidPlistDict's mutableCopy()
#
set ocidAliasStoreKeyDict to ocidPlistDictM's objectForKey:("SSActionKeyboardAliasStoreKey")
if ocidAliasStoreKeyDict = (missing value) then
	set ocidAliasStoreKeyDictM to refMe's NSMutableDictionary's alloc()'s init()
	ocidAliasStoreKeyDictM's setObject:(ocidRestoreJsonDict) forKey:("com.apple.shortcuts")
	ocidPlistDictM's setObject:(ocidAliasStoreKeyDictM) forKey:("SSActionKeyboardAliasStoreKey")
else
	ocidAliasStoreKeyDict's setObject:(ocidRestoreJsonDict) forKey:("com.apple.shortcuts")
end if

#NSPropertyListSerialization DICT 2 PLIST
set ocidFromat to (refMe's NSPropertyListBinaryFormat_v1_0)
set listResponse to refMe's NSPropertyListSerialization's dataWithPropertyList:(ocidPlistDictM) format:(ocidFromat) options:0 |error|:(reference)
set ocidPlistDataM to (first item of listResponse)

#NSDATA SAVE 
set ocidOption to (refMe's NSDataWritingAtomic)
set listDone to ocidPlistDataM's writeToURL:(ocidPlistFilePathURL) options:(ocidOption) |error|:(reference)


#Reboot Spotlight
set ocidPlistFilePath to ocidPlistFilePathURL's |path|()
set strPlistFilePath to ocidPlistFilePath as text
#	set appWorkspace to refMe's NSWorkspace's sharedWorkspace()
#	(appWorkspace's noteFileSystemChanged:(ocidPlistFilePath))
set appUserDefaults to refMe's NSUserDefaults's standardUserDefaults()
set boolDone to appUserDefaults's synchronize()
log boolDone
do shell script ("/bin/zsh -c '/usr/libexec/PlistBuddy -c \"Save\"  \"" & strPlistFilePath & "\"'")
do shell script ("/bin/zsh -c '/usr/bin/killall -HUP cfprefsd 2>/dev/null || true'")
do shell script ("/bin/zsh -c '/usr/bin/notifyutil -p com.apple.CFPreferences.changed'")

delay 2

set ocidAppArray to refMe's NSRunningApplication's runningApplicationsWithBundleIdentifier:("com.apple.Spotlight")
repeat with itemApp in ocidAppArray
	set numPID to itemApp's processIdentifier() as text
	log numPID
	do shell script ("/bin/zsh -c '/usr/bin/kill -HUP " & numPID & "' 2>/dev/null || true")
end repeat
#
do shell script ("/bin/zsh -c '/usr/bin/killall -HUP Spotlight 2>/dev/null || true'")
#	
do shell script ("/bin/zsh -c '/usr/bin/killall -HUP corespotlightd 2>/dev/null || true'")
do shell script ("/bin/zsh -c '/usr/bin/killall -HUP spotlightknowledged 2>/dev/null || true'")
do shell script ("/bin/zsh -c '/usr/bin/killall -HUP managedcorespotlightd 2>/dev/null || true'")

return

I wrote this mainly for my own use, so it creates some folders automatically.
Please keep that in mind if you decide to try it out.

As I said I’m still on Sequoia so I can’t test the script.

FWIW, I rewrote my script to save the Spotlight Quick Keys data to a text file. I included UUIDs in the data because I thought I might use the text file to restore the Quick Keys, but I decided I didn’t want to mess with the Spotlight plist file. I don’t know why the orphan Quick Keys exist, because their UUIDs do not appear to reference a shortcut.

use framework "Foundation"
use scripting additions

--set paths for Quick Keys data and plist files
set quickKeysDataFile to "/Users/robert/Desktop/Quick Keys Data.txt"
set homeFolder to current application's NSHomeDirectory() as text
set plistFile to homeFolder & "/Library/Preferences/com.apple.Spotlight.plist"

--get lists of Quick Keys and shortcut UUIDs
try
	set quickKeysDictionary to ((current application's NSUserDefaults's alloc()'s initWithSuiteName:plistFile)'s objectForKey:"SSActionKeyboardAliasStoreKey")'s valueForKey:"com.apple.shortcuts"
on error
	display dialog "The applicable section of the plist file was not found" buttons {"OK"} cancel button 1 default button 1
end try
set UUIDs to quickKeysDictionary's allKeys() as list
set quickKeys to quickKeysDictionary's allValues() as list

--create string with each line containing the Quick Keys, shortcut name, and shortcut UUID
set quickKeysData to ""
set errorText to ""
tell application "Shortcuts Events"
	repeat with i from 1 to (count UUIDs)
		try
			set shortcutName to name of shortcut id (item i of UUIDs)
			set quickKeysData to quickKeysData & (item i of quickKeys) & space & shortcutName & space & (item i of UUIDs) & linefeed
		on error
			set errorText to errorText & (item i of quickKeys) & space & (item i of UUIDs) & linefeed
		end try
	end repeat
end tell

--sort string and write to file
set theString to current application's NSString's stringWithString:quickKeysData
set sortedArray to (theString's componentsSeparatedByString:linefeed)'s sortedArrayUsingSelector:"localizedStandardCompare:"
set sortedArray to sortedArray's subarrayWithRange:{1, (sortedArray's |count|()) - 1} -- delete first item (a linefeed)
set sortedString to sortedArray's componentsJoinedByString:linefeed
set formattedString to current application's NSString's stringWithFormat_("SPOTLIGHT QUICK KEYS:%@%@%@ORPHANED QUICK KEYS:%@%@", linefeed & linefeed, sortedString, linefeed & linefeed, linefeed & linefeed, errorText)
formattedString's writeToFile:quickKeysDataFile atomically:true encoding:(current application's NSUTF8StringEncoding) |error|:(missing value)
1 Like

@peavine
I wonder why that happens.
Since Shortcuts syncs through iCloud, could it be related to people using multiple devices?
I checked , and so far, I haven’t found any Quick Keys with orphaned UUIDs
It might also be because I’ve reset my Quick Key settings a few times, so any leftovers may have been cleared.

#!/usr/bin/env osascript
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
property refMe : a reference to current application
set appFileManager to refMe's NSFileManager's defaultManager()

##############################
#READ FILE com.apple.Spotlight.plist
set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSLibraryDirectory) inDomains:(refMe's NSUserDomainMask))
set ocidLibraryDirPathURL to ocidURLsArray's firstObject()
set ocidPlistFilePathURL to ocidLibraryDirPathURL's URLByAppendingPathComponent:("Preferences/com.apple.Spotlight.plist") isDirectory:(false)
#DICT
set listResponse to refMe's NSDictionary's alloc()'s initWithContentsOfURL:(ocidPlistFilePathURL) |error|:(reference)
set ocidPlistDict to (first item of listResponse)
set ocidSSStoreKeyDict to ocidPlistDict's objectForKey:("SSActionKeyboardAliasStoreKey")
set ocidShortcutsDict to ocidSSStoreKeyDict's objectForKey:("com.apple.shortcuts")

#ALLKEYS com.apple.Spotlight.plist = Spotlight
set ocidSpotlightAllKeysArray to ocidShortcutsDict's allKeys()


##############################
#Shortcuts Events
tell application "Shortcuts Events"
	set listShortCutID to (id of every shortcut) as list
end tell
set ocidShortcutsIDArray to refMe's NSArray's arrayWithArray:(listShortCutID)


##############################
#compare
repeat with itemSpotlightID in ocidSpotlightAllKeysArray
	
	set boolContain to (ocidShortcutsIDArray's containsObject:(itemSpotlightID))
	if (boolContain as boolean) is true then
		set strValue to (ocidShortcutsDict's valueForKey:(itemSpotlightID)) as text
		log "\rSpotlightID:" & itemSpotlightID & ": " & strValue & "\r"
		tell application "Shortcuts Events"
			tell shortcut id (itemSpotlightID as text)
				log "\rShortcutsID:" & (id as text) & ":" & (name as text) & "\r"
			end tell
		end tell
	end if
end repeat


return

@IceFole. The first time I reset the Spotlight Quick Keys was yesterday, and many of the orphaned Quick Keys assignments could have occurred while I was running macOS Tahoe betas. However, since yesterday, I’ve encountered two new orphaned Quick Key assignments. I only have one computer connected to my iCloud account, and I don’t think that would be the cause. Fortunately, the orphaned Quick Keys are not recognized in Spotlight, so no harm is done.

1 Like