|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Sorts the focused container |
| 4 | +# You'll usually want to focus the parent container first |
| 5 | + |
| 6 | +# Example sway config: |
| 7 | +# |
| 8 | +# bindsym $mod+a focus parent # from default sway config |
| 9 | +# bindsym $mod+Shift+s exec sort-container.py |
| 10 | + |
| 11 | +import re |
| 12 | + |
| 13 | +import i3ipc |
| 14 | + |
| 15 | + |
| 16 | +def str_compare(str1, str2): |
| 17 | + split1 = re.split("([0-9]+)", str1) |
| 18 | + split2 = re.split("([0-9]+)", str2) |
| 19 | + |
| 20 | + for i, item in enumerate(split1): |
| 21 | + try: |
| 22 | + split1[i] = int(item) |
| 23 | + except ValueError: |
| 24 | + pass |
| 25 | + |
| 26 | + for i, item in enumerate(split2): |
| 27 | + try: |
| 28 | + split2[i] = int(item) |
| 29 | + except ValueError: |
| 30 | + pass |
| 31 | + |
| 32 | + return split1 < split2 |
| 33 | + |
| 34 | + |
| 35 | +if __name__ == "__main__": |
| 36 | + ipc = i3ipc.Connection() |
| 37 | + |
| 38 | + focused = ipc.get_tree().find_focused() |
| 39 | + |
| 40 | + layout = focused.layout |
| 41 | + |
| 42 | + if layout == "splitv" or layout == "stacked": |
| 43 | + move_prev = "move up" |
| 44 | + elif layout == "splith" or layout == "tabbed": |
| 45 | + move_prev = "move left" |
| 46 | + else: |
| 47 | + exit() |
| 48 | + |
| 49 | + leaves = focused.leaves() |
| 50 | + commands = [] |
| 51 | + |
| 52 | + # insertion sort |
| 53 | + for i in range(1, len(leaves)): |
| 54 | + # focus leaf i |
| 55 | + commands.append(f'[con_id="{leaves[i].id}"] focus') |
| 56 | + |
| 57 | + # insert leaf i into sorted section |
| 58 | + for j in reversed(range(0, i)): |
| 59 | + if str_compare(leaves[j].name, leaves[j+1].name): |
| 60 | + break |
| 61 | + leaves[j+1], leaves[j] = leaves[j], leaves[j+1] |
| 62 | + commands.append(move_prev) |
| 63 | + |
| 64 | + commands.append(f'[con_id="{leaves[0].id}"] focus') |
| 65 | + |
| 66 | + for cmd in commands: |
| 67 | + ipc.command(cmd) |
0 commit comments