Skip to content

Instantly share code, notes, and snippets.

@a1ip
Forked from HappyTetrahedron/switchworkspace.sh
Created September 14, 2021 06:44
Show Gist options
  • Select an option

  • Save a1ip/f04939d1dd85fd08fb142c044149cf15 to your computer and use it in GitHub Desktop.

Select an option

Save a1ip/f04939d1dd85fd08fb142c044149cf15 to your computer and use it in GitHub Desktop.
Script to replicate xmonad multi-monitor behaviour in i3 (configure i3 hotkeys to call this script instead of directly switching workspace)
#!/bin/bash
# get relevant info from i3-msg
WORKSPACEJSON="$(i3-msg -t get_workspaces)"
WORKSPACES="$(echo "$WORKSPACEJSON" | jshon -a -e name -u)"
MONITORS="$(echo "$WORKSPACEJSON" | jshon -a -e output -u)"
FOCUSED="$(echo "$WORKSPACEJSON" | jshon -a -e focused)"
VISIBLE="$(echo "$WORKSPACEJSON" | jshon -a -e visible)"
# FROMNR is the number of the currently focused workspace. TONR is the number of the workspace I want to switch to.
FROMNR="$(echo "$FOCUSED" | nl | grep true | awk '{print $1}')"
TONR="$(echo "$WORKSPACES" | awk '{print "__"$1}' | nl | grep "__$1" | awk '{print $1}')" # Since workspace names can be numbers, grep could accidentally find a line number, so workspace names are prefixed with __ to avoid that
# i3 names of the workspaces to switch.
FROMNAME="$(echo "$WORKSPACES" | sed "$(echo $FROMNR)q;d")"
TONAME="$1"
# Monitors on which both workspaces reside
FROMMONI=$(echo "$MONITORS" | sed "$(echo $FROMNR)q;d")
TOMONI=$(echo "$MONITORS" | sed "$(echo $TONR)q;d")
# "true" if target workspace is currently visible, "false" otherwise
TOVISI=$(echo "$VISIBLE" | sed "$(echo $TONR)q;d")
# Target workspace doesn't exist yet, or is on same monitor as current
if [[ "$TONR" = "" ]] || [[ "$FROMMONI" = "$TOMONI" ]]
then
i3-msg "workspace $TONAME" # simple WS switch as with default i3
else
if [[ "$TOVISI" = "true" ]] # If target workspace is visible
then
i3-msg "move workspace to output $TOMONI" # the current WS is moved to replace it
fi
# Target workspace is first selected and then moved to current monitor.
i3-msg "workspace $TONAME"
i3-msg "move workspace to output $FROMMONI"
i3-msg "focus output $FROMMONI"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment