Tags and screen change in the awesome window manager

On my main computer, I've been using the awesome window manager for quite a long time now (I sometimes use xfce4 on other computers, especially on my linux tablet).

I'm mostly happy with it but there's a few (mildly) annoying things that would need to be fixed. One of them is that when I (dis)connect an external screen (or change the screen mode through xrandr), all windows move to tag 1. This is only mildly annoying because I don't do that many times a day, and when that happens I only need a few key strokes to manually move all windows back to their proper tag. Still, I've always felt that this is the kind of things that should just work!

I finally found a post describing how to ensure this: huge thanks to Radiu Corba for this!

Here's the code to be added to ~/.config/awesome/rc.lua. See Radius' post for more explanations on how this works.

tag.connect_signal("request::screen", function(t)
    local fallback_tag = nil

    -- find tag with same name on any other screen
    for other_screen in screen do
        if other_screen ~= t.screen then
            fallback_tag = awful.tag.find_by_name(other_screen, t.name)
            if fallback_tag ~= nil then
                break
            end
        end
    end

    -- no tag with same name exists, use fallback
    if fallback_tag == nil then
        fallback_tag = awful.tag.find_fallback()
    end

    if not (fallback_tag == nil) then
        clients = t:clients()
        for _, c in ipairs(clients) do
           c:move_to_tag(fallback_tag)
           -- preserve info about which screen the window was originally on, so
           -- we can restore it if the screen is reconnected.
           c.desired_screen = t.screen.index
        end
    end
end)

function restore_windows_to_desired_screen(new_screen)
    for _, c in ipairs(client.get()) do
       if not (c.desired_screen == nil) then
          tag_name = c.first_tag.name
          c:move_to_screen(c.desired_screen)
          tag = awful.tag.find_by_name(c.screen, tag_name)
          if not (tag == nil) then
             c:move_to_tag(tag)
          end
          -- now clear the "desired_screen"
          c.desired_screen = nil
       end
    end
end

screen.connect_signal("request::desktop_decoration", function(s)
    -- Each screen has its own tag table.
    awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.suit.tile)
    -- Call our restore function, now that tags are setup
    restore_windows_to_desired_screen(s)
    end)