Igor's Blog

I love cool stuffs

Restore Window Size in Hammerspoon

Aero Snap is a handy feature introduced in Windows 7 back to 2009. Third-party apps also enable similar functionalities on Mac since. I recently found Hammerspoon is particular customizable and neat for windows layout management.


The idea is simple: before resizing happens, store the current window id and frame object (hs.geometry) pair in a lua table:

prevFrameSizes = {}

local curWin = hs.window.focusedWindow()
local curWinFrame = curWin:frame()
-- store current frame position
prevFrameSizes[curWin:id()] = hs.geometry.copy(curWinFrame)

Check curWin:id() in prevFrameSizes before resizing, if non nil presents, we restore the window frame:

if prevFrameSizes[curWin:id()] then
    -- restore frame position and reset storage
    curWin:setFrame(prevFrameSizes[curWin:id()])
    prevFrameSizes[curWin:id()] = nil
end

To make the behavior nicer, we also want to detect current window frame status: For example, if current window already filled the screen left, a "filling screen right" command should not restore curWin size even prevFrameSizes[curWin:id()] exists. You want to fill current window to screen right directly in this case, So the logic becomes:

if filledSomewhere() and notCurrentTargetFrame() then
        -- set frame position directly
        curWin:setFrame(targetFrame)
    elseif prevFrameSizes[curWin:id()] then
        -- restore frame position and reset storage
        curWin:setFrame(prevFrameSizes[curWin:id()])
        prevFrameSizes[curWin:id()] = nil
    else
        -- store current frame position
        prevFrameSizes[curWin:id()] = curWinFrame
        curWin:setFrame(targetFrame)
    end

The compelete init.lua could be found here:

waigx/hammerspoon-config/init.lua

Window management related shortcuts: