vitorgalvao/custom-alfred-iterm-scripts

Command not always sent to iTerm in Catalina (with fix)

webdevnerdstuff opened this issue · 2 comments

Alfred 5.0.1 [2067]
iTerm2 3.4.16
macOS Monterey 12.4

Note

First I'll start with this. On my M1 Mac with the specs above, it seems to be working as intended. But for the specs from my older Intel Mac (below) I had to make some adjustments to the script to get it to work properly. So this Issue is more for "if someone else is having this issue" and on Catalina, perhaps this code snippet will help them.

Alfred 5.0.1 [2067]
iTerm2 3.4.16
macOS Catalina 10.15.7 (19H1922)

Issue

Depending on the property settings open_in_new_window and/or open_in_new_tab set to true, the command was not being added to the console.

Fix

-- For the latest version:
-- https://github.com/vitorgalvao/custom-alfred-iterm-scripts

-- Set this property to true to always open in a new window
property open_in_new_window : true

-- Set this property to false to reuse current tab
property open_in_new_tab : true

-- Handlers
on new_window()
  tell application "iTerm" to create window with default profile
  activate
end new_window

on new_tab()
  tell application "iTerm" to tell the first window to create tab with default profile
  activate
end new_tab

on is_running()
  application "iTerm" is running
end is_running

on call_forward()
  tell application "iTerm" to activate
end call_forward

on send_text(custom_text)
  tell application "iTerm" to tell the first window to tell current session to write text custom_text
end send_text

-- Main
on alfred_script(query)
  -- Check to see if iTerm is running
  if is_running() then
    -- Open in new window
    if open_in_new_window then
      new_window()
    -- Open in new tab
    else if open_in_new_tab then
      new_tab()
    else
      -- Reuse current tab
    end if
  -- iTerm is not running, activate new instance
  else
    call_forward()
  end if

  -- Make sure a window exists before we continue, or the write may fail
  repeat until is_running()
    delay 0.01
  end repeat

  send_text(query)
end alfred_scripts

Since this is not a bug, but more for information, I will close this (non) Issue.

Thank you @webdevnerdstuff. I appreciate you having gone through the trouble of explaining it so clearly to people who may need it.