Automating Spaces in Mission Control

Not sure if that fits your bill, but I made two Keyboard Maestro Macros for creating and deleting Spaces. Both are mere keyboard shortcuts for triggering an AppleScript that will use UI scripting to click on the add and close buttons. So they can be recreated in whatever tool you prefer, but… they’re not tidy to put it kindly.

When I previously researched this, creating spaces could be done easily via keyboard shortcut via Yabai. But it required disabling SIP, which was a no go for me. Hence this ugly UI AppleScript workaround.

Here’s the one for creating a new space

do shell script "open -b 'com.apple.exposelauncher'"
delay 0.2
tell application id "com.apple.systemevents"
	tell (every application process ¬
		whose bundle identifier = "com.apple.dock") to ¬
		click (button 1 of group 2 of group 1 of group 1)
	delay 0.2
	key code 53 -- esc key
end tell

There’s the one for closing the current space

tell application "Mission Control" to launch
delay 0.25
tell application "System Events"
	tell list 1 of group 2 of group 1 of group 1 of process "Dock"
		set countSpaces to count of buttons
		if countSpaces is greater than 1 then
			perform action "AXRemoveDesktop" of button countSpaces
		end if
	end tell
	delay 0.6
	key code 53 --  # Esc key on US English Keyboard
end tell
3 Likes