Is it possible to switch to a specific keyboard layout via `defaults`, *.plist or similar? I have figured out a workable shell script using osascript (AppleScript) to automatically switch to US keyboard layout when MacVim activates (triggered by Keyboard Maestro), and Swedish layout when it deactivates:

osascript &gt; /dev/null 2&gt;&amp;1 &lt;&lt;-RAW
on changeKeyboardLayout(layoutName)
    tell application "System Events" to tell process "SystemUIServer"
        tell (1st menu bar item of menu bar 1 whose description is "text input") to {click, click (menu 1's menu item layoutName)}
    end tell
end changeKeyboardLayout

changeKeyboardLayout("Svensk - Pro")
RAW
exit $?


However, AppleScript is truly slow and I also don't prefer to see the text input menu in the statusbar to flash open when switching back and forth.

Question:

Is there an alternative to my AppleScript approach to instantly switch layout?

…I envision something like a defaults command or altering any .plist file as potential candidates for the job, only I don't know any specifics.

Two things related to the answer(s) I'm seeking:


I'm keen to have the change propagate instantly – faster than the sluggish AppleScript execution.
I prefer not installing new software daemons to achieve this. (Suggestions are always welcome, though, but 3rd party apps will likely not qualify as the accepted answer.)
~/Library/Preferences/ByHost/com.apple.HIToolbox.*.plist has an AppleSelectedInputSources key, but modifying it directly doesn't seem to actually change the layout.

Most of the solutions posted at MacScripter just use UI scripting as well.

There's a small Objective-C utility called changeInput though that should change the layout almost instantly.