macosluahammerspoon

MRU browser tab switching with Hammerspoon (Lua+Mac issue)


I'm feeling determined to get most-recently-used tab switching working for Chrome. To do this I have installed CLUT Chrome browser extension, which currently maps alt-w to switch to the last tab, and installed Hammerspoon, which allows intercepting system keystrokes.

In init.lua I have this code:

local ctrlTab = hotkey.new({"ctrl"}, "tab", function()
  hs.eventtap.keyStroke({"alt"}, "w")
end)
chromeWatcher = hs.application.watcher.new(function(name, eventType, app)
  if eventType ~= hs.application.watcher.activated then return end
  if name == "Google Chrome" then
    ctrlTab:enable()
  else
    ctrlTab:disable()
  end
end)

chromeWatcher:start()

However, I get this error in Hammerspoon:

attempt to index a nil value (global 'hotkey')

stack traceback:
    /Users/vonwao/.hammerspoon/init.lua:1: in main chunk
    [C]: in function 'xpcall'
    ...app/Contents/Resources/extensions/hs/_coresetup/init.lua:410: in function 'hs._coresetup.setup'
    (...tail calls...)

I searched, but couldn't figure out what this error means.

EDIT - Here is the final solution, if anybody else wants MRU tab switching on Mac:

local ctrlTab = hs.hotkey.new({"ctrl"}, "tab", nil, function()
  hs.eventtap.keyStroke({"alt"}, "w")
end)
chromeWatcher = hs.application.watcher.new(function(name, eventType, app)
  if eventType ~= hs.application.watcher.activated then return end
  if name == "Google Chrome" then
    ctrlTab:enable()
  else
    ctrlTab:disable()
  end
end)

chromeWatcher:start()

Solution

  • You should use "hs.hotkey.new" on the first line.

    Also, I would recommend you add a nil argument before the hokey function - you are currently binding to the moment when ctrl-tab is pressed, and then emitting a keystroke. The OS will see all of these keys happening at once. If you pass a nil before the function, your hotkey will trigger when you release ctrl-tab and only alt-w will be interpreted.