macoshammerspoon

Using hammerspoon and the spaces module to move window to new space


I have installed the "undocumented spaces" module from https://github.com/asmagill/hs._asm.undocumented.spaces. In particular, it provides a method moveWindowToSpace that I am trying to use to bind cmd+1 to move the the current window to space 1 using the following:

local spaces = require("hs._asm.undocumented.spaces")
function MoveWindowToSpace(sp)
    local spaceID = spaces.query()[sp]
    spaces.moveWindowToSpace(hs.window.focusedWindow():id(), spaceID)
    spaces.changeToSpace(spaceID)
end
hs.hotkey.bind({"cmd"}, "1",function() MoveWindowToSpace(1) end)

This works in the sense that it moves the window to a new space, however, the spaces appear to be in a pseudo random order.

Does any one know how to correctly map spaceIDs, as returned by spaces.query(), to the actual spaces?


Solution

  • As undocumented spaces has moved to spaces, the new code would be as follows (some lines could be merged, but I like the clarity of splitting operations):

    spaces = require("hs.spaces")
    -- move current window to the space sp
    function MoveWindowToSpace(sp)
      local win = hs.window.focusedWindow()      -- current window
      local cur_screen = hs.screen.mainScreen()
      local cur_screen_id = cur_screen:getUUID()
      local all_spaces=spaces.allSpaces()
      local spaceID = all_spaces[cur_screen_id][sp]
      spaces.moveWindowToSpace(win:id(), spaceID)
      spaces.gotoSpace(spaceID)              -- follow window to new space
    end
    hs.hotkey.bind(hyper, '1', function() MoveWindowToSpace(1) end)
    hs.hotkey.bind(hyper, '2', function() MoveWindowToSpace(2) end)
    hs.hotkey.bind(hyper, '3', function() MoveWindowToSpace(3) end)