Skip to content

Instantly share code, notes, and snippets.

@vsuharnikov
Last active January 6, 2023 07:08
Show Gist options
  • Save vsuharnikov/d36037745b7afcdc13c51d079273ac26 to your computer and use it in GitHub Desktop.
Save vsuharnikov/d36037745b7afcdc13c51d079273ac26 to your computer and use it in GitHub Desktop.
Focus next window in Sway
# ====================================================================================== #
# Focus the next window on the current workspace in sway, e.g. for binding to Alt+Tab #
# Depends: jq, sway #
# License: AS IS #
# Heavily inspired by i3 version https://gist.github.com/Nervengift/0ab9e6127ac17b8317ac #
# ====================================================================================== #
ws=$(swaymsg -t get_workspaces|jq "map(select(.focused))[]|.name")
windows=$(swaymsg -t get_tree|jq ".nodes|map(.nodes[])|map(select(.type==\"workspace\" and .name==$ws))[0]|[recurse(.nodes[])|select(.layout==\"none\")]|map({id: .id, focused: .focused})")
# https://stackoverflow.com/questions/53135035/jq-returning-null-as-string-if-the-json-is-empty
current=$(echo $windows | jq ".[]|select(.focused).id // empty")
if [[ -n $current ]]; then
first=$(echo $windows | jq ".[0]|select(.focused==false).id")
after=$(echo $windows | jq 'map(.id, if .focused then "F" else "" end) | join(" ") | split(" F") | last | split(" ") | map(select(. != "")) | first // empty')
if [[ -n $after ]]; then
next=$after
else
next=$first
fi
# Note, con_id, not "id". See: https://github.com/swaywm/sway/issues/4972#issuecomment-582213301
swaymsg "[con_id=$next]" focus > /dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment