Created
February 23, 2025 23:13
-
-
Save mikeslattery/60d814e8e5446ae31979432ea03ed71a to your computer and use it in GitHub Desktop.
Set focus of app running in a terminal.
This file contains hidden or 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
#!/bin/bash | |
# Focus the window for the current terminal. | |
# Usage: focusterm | |
# Supports: | |
# X11 | |
# tmux | |
# kitty, westerm, alacrity, and most other terminals | |
# Requirements: | |
# xdotool | |
# ps | |
set -euo pipefail | |
# Focus the multiplexer pane the shell script is running in. | |
focus_pane() { | |
if [[ -n "$TMUX_PANE" ]]; then | |
tmux select-pane -t "$TMUX_PANE" | |
fi | |
# Focus the Kitty pane the shell script is running in. | |
if [[ -n "$KITTY_PANE_ID" ]]; then | |
kitty @ focus-window --match id:"$KITTY_WINDOW_ID" | |
kitty @ goto-layout --match id:"$KITTY_PANE_ID" | |
fi | |
# Focus the wezterm pane the shell script is running in. | |
if [[ -n "$WEZTERM_PANE" ]]; then | |
wezterm cli activate-pane --pane-id "$WEZTERM_PANE" | |
fi | |
} | |
get_ppid() { | |
ps -o ppid= -p "$1" | xargs | |
} | |
# Traverse up process tree to find X11 Window | |
get_window_id() { | |
local pid="$1" | |
local window_id="" | |
while [[ "$pid" != "1" ]] && [[ -z "$window_id" ]]; do | |
# get parent pid | |
pid="$(get_ppid "$pid")" | |
window_id="$(xdotool search --onlyvisible --pid "$pid" 2>/dev/null || true)" | |
done | |
echo -n "$window_id" | |
} | |
# Get the pid of the shell process | |
get_shell_pid() { | |
if [[ -n "$TMUX" ]]; then | |
tmux_pid="$(tmux display -p '#{client_pid}')" | |
get_ppid "$tmux_pid" | |
else | |
get_ppid "$$" | |
fi | |
} | |
main() { | |
focus_pane | |
# Get the x11 window-id | |
if [[ -n "$ALACRITTY_WINDOW_ID" ]]; then | |
window_id="$ALACRITTY_WINDOW_ID" | |
elif [[ -n "$WINDOW_ID" ]]; then | |
window_id="$WINDOW_ID" | |
else | |
shell_pid="$(get_shell_pid)" | |
window_id="$(get_window_id "$shell_pid")" | |
fi | |
if [[ -n "$window_id" ]]; then | |
xdotool windowactivate "$window_id" | |
fi | |
} | |
main | |
#TODO: | |
# WM: | |
# WSLg | |
# Wayland gdbus | |
# Sway | |
# Windows | |
# Mac | |
# Multiplexers: | |
# Ghostty | |
# Terminator | |
# Screen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment