【技巧】在 Alfred5 中修改默认终端为 iTerm2

Alfred5 是 macOS 上的一款功能强大的应用程序启动器和工作流工具。

Alfred5 提供了快速打开终端和运行 Shell 命令的拓展,默认终端是 macOS 自带的 Terminal。通常情况下我们都会将默认的终端替换为 iTerm2 或者其他现代化终端工具,Alfred5 提供了编写脚本使用任意终端工具运行命令的能力,下面介绍如何将 iTerm2 修改为 Alfred5 的默认终端。

步骤

下列步骤由 vitorgalvao 提供,来源于 Github 仓库: vitorgalvao/custom-alfred-iterm-scripts

  1. 你需要将脚本复制到剪贴板,脚本见 下文
  2. 打开 Alfred 偏好设置(调出 Alfred 并按下 ⌘, 键)。
  3. 导航到 FeatureTerminal
  4. Application 设置为 Custom
  5. 选择框中的文本。
  6. 粘贴。
  7. 你可以通过修改顶部的属性行来随意修改脚本的行为。

Script

 1-- For the latest version:
 2-- https://github.com/vitorgalvao/custom-alfred-iterm-scripts
 3
 4-- Set this property to true to always open in a new window
 5property open_in_new_window : false
 6
 7-- Set this property to false to reuse current tab
 8property open_in_new_tab : true
 9
10-- Set this property to true if iTerm is configured to launch without opening a new window
11property iterm_opens_quietly : false
12
13-- Handlers
14on new_window()
15  tell application "iTerm" to create window with default profile
16end new_window
17
18on new_tab()
19  tell application "iTerm" to tell the first window to create tab with default profile
20end new_tab
21
22on call_forward()
23  tell application "iTerm" to activate
24end call_forward
25
26on is_running()
27  application "iTerm" is running
28end is_running
29
30on has_windows()
31  if not is_running() then return false
32
33  tell application "iTerm"
34    if windows is {} then return false
35    if tabs of current window is {} then return false
36    if sessions of current tab of current window is {} then return false
37
38    set session_text to contents of current session of current tab of current window
39    if words of session_text is {} then return false
40  end tell
41
42  true
43end has_windows
44
45on send_text(custom_text)
46  tell application "iTerm" to tell the first window to tell current session to write text custom_text
47end send_text
48
49-- Main
50on alfred_script(query)
51  if has_windows() then
52    if open_in_new_window then
53      new_window()
54    else if open_in_new_tab then
55      new_tab()
56    else
57      -- Reuse current tab
58    end if
59  else
60    -- If iTerm is not running and we tell it to create a new window, we get two:
61    -- one from opening the application, and the other from the command
62    if is_running() or iterm_opens_quietly then
63      new_window()
64    else
65      call_forward()
66    end if
67  end if
68
69  -- Make sure a window exists before we continue, or the write may fail
70  -- "with timeout" does not work with a "repeat"
71  -- Delay of 0.01 seconds repeated 500 times means a timeout of 5 seconds
72  repeat 500 times
73    if has_windows() then
74      send_text(query)
75      call_forward()
76      exit repeat
77    end if
78
79    delay 0.01
80  end repeat
81end alfred_script