Change keyboard whenever iTerm is selected

Using either Applescript or Automator is it possible to switch the software keyboard(Input Source) to a certain keyboard(input source) whenever iTerm becomes foreground?

Scenario is as follows

  • I click on iTerm window
  • iTerm window goes foreground
  • A script changes the keyboard(input source) to one that I specify

Solution 1:

You could for example save this plist as ~/Library/LaunchAgents/itermchangeinput.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>itermchangeinput</string>
  <key>ProgramArguments</key>
  <array>
    <string>osascript</string>
    <string>-e</string>
    <string>set prev to missing value
repeat
    set cur to name of application (path to frontmost application as text)
    if cur is "iTerm" and prev is not "iTerm" then do shell script "changeInput U.S."
    delay 1
    set prev to cur
end repeat</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
</dict>
</plist>

Then run launchctl load ~/Library/LaunchAgents/itermchangeinput.plist.

You could also use a shell script like this:

while sleep 1;do cur=$(lsappinfo find ASN=$(lsappinfo front)|cut -d\" -f2);[[ $cur = iTerm && $prev != iTerm ]]&&changeInput U.S.;prev=$cur;done

It might be less efficient though because it executes two new processes every second.

The original blog post about changeInput was deleted by the author, but I uploaded the binary to http://19a5b0.s3-website-us-west-2.amazonaws.com/changeInput.tgz.

If you always switch to iTerm with a keyboard shortcut (like F7), you could use a private.xml like this with KeyRemap4MacBook:

<?xml version="1.0"?>
<root>
  <vkopenurldef>
    <name>KeyCode::VK_OPEN_URL_ITERM</name>
    <url>file:///Applications/iTerm.app</url>
  </vkopenurldef>
  <inputsourcedef>
    <name>US</name>
    <inputsourceid_prefix>com.apple.keylayout.US</inputsourceid_prefix>
  </inputsourcedef>
  <item>
    <name>test</name>
    <identifier>test</identifier>
    <autogen>__KeyToKey__ KeyCode::F7, ModifierFlag::NONE, VK_OPEN_URL_ITERM, VK_CHANGE_INPUTMODE_US</autogen>
  </item>
</root>

You can see the IDs of input sources with EventViewer (/Applications/KeyRemap4MacBook.app/Contents/Applications/EventViewer.app/).