Toggle Autocorrect

I’ve ran into a need to Toggle Correct Spelling Automatically. Here is a script that asks nicely and changes the value of autocorrect if asked to. It closes System Preferences if the app was not open previously.


tell application "System Events"
	set SystemPreferencesOpen to count (every process whose name is "System Preferences")
end tell

tell application "System Preferences"
	activate
	set the current pane to pane id "com.apple.Localization"
	reveal anchor "Text" of pane id "com.apple.Localization"
	try
		tell application "System Events"
			tell application process "System Preferences" to set checked to get value of checkbox "Correct spelling automatically" of tab group 1 of window "Language & Text"
			if checked is 1 then
				set promptString to "On"
			else
				set promptString to "Off"
			end if
			set promptString to "Autocorrect is " & promptString & ". Change?"
			display dialog promptString buttons {"No", "Yes"} default button 2 cancel button 1 with title "Change Autocorrect"
			tell application process "System Preferences" to set checked to click checkbox "Correct spelling automatically" of tab group 1 of window "Language & Text"
		end tell
	on error
		-- user canceled. do nothing
	end try
	if SystemPreferencesOpen is 0 then tell application "System Preferences" to quit
end tell