Created
January 28, 2022 14:45
-
-
Save travisbhartwell/4ff06d2aa99d7437102cbed32d5b4ab5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import iterm2 | |
import iterm2.tmux | |
async def main(connection): | |
# This is an example of using an asyncio context manager to register a custom control | |
# sequence. You can send a custom control sequence by issuing this command in a | |
# terminal session in iTerm2 while this script is running: | |
# | |
# printf "\033]1337;Custom=id=%s:%s\a" "shared-secret" "create-window" | |
# printf "\033]1337;Custom=id=%s:%s(\"%s\")\a" "shared-secret" "switch-session" "Default Session" | |
async with iterm2.CustomControlSequenceMonitor( | |
connection, "shared-secret", r"^switch-session\((?P<session_name>[^)]+)\)$" | |
) as mon: | |
while True: | |
match = await mon.async_get() | |
desired_session_name = match.group("session_name").strip('"') | |
print(f"Received command with argument: '{desired_session_name}'") | |
tmux_connections = await iterm2.tmux.async_get_tmux_connections(connection) | |
for t in tmux_connections: | |
session_name = await t.async_send_command("display-message -p '#S'") | |
print( | |
f"Comparing '{desired_session_name}' with session name '{session_name}'." | |
) | |
if session_name == desired_session_name: | |
print( | |
"Found a match, closing exiting tab and switching to tmux session" | |
) | |
print( | |
f"Now seearching for tab with connection id '{t.connection_id}'" | |
) | |
app = await iterm2.async_get_app(connection) | |
active_tab = None | |
for window in app.windows: | |
for tab in window.tabs: | |
print( | |
f"Comparing tab '{tab.tab_id}' with tmux connection id '{tab.tmux_connection_id}'" | |
) | |
if tab.tmux_connection_id == t.connection_id: | |
print("Found tab.") | |
active_tab = window.current_tab | |
break | |
if active_tab is not None: | |
await active_tab.async_activate() | |
await app.current_terminal_window.current_tab.async_close() | |
else: | |
print("Didn't find match") | |
# This instructs the script to run the "main" coroutine and to keep running even after it returns. | |
iterm2.run_forever(main) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
printf "\033]1337;Custom=id=%s:%s(\"%s\")\a" "shared-secret" "switch-session" "My Test Session" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment