Skip to content

Dropdown terminal

28th January 2023

I wanted a dropdown terminal anywhere (Guake style), and so found a few resources online. After some searching, this Github issue and gist solved my problem. Generally, you shouldn't be executing random bits of code on the internet on your personal machine, so I read through to make sure it wasn't doing anything malicious, and along the way made some simplifications.

How to:

  1. Install Hammerspoon.
  2. Add an ~./hammerspoon/init.lua file with the code here.
  3. (Optional) If you're not using Alacritty (terminal emulator) then change accordingly. You can also change the hotkey.
  4. Launch Hammerspoon and press + \ to show and hide the terminal! Even works across macOS desktop spaces.
lua
-- file: ~/hammerspoon/init.lua

local spaces = require 'hs.spaces'
local screen = require 'hs.screen'
local hotkey = require 'hs.hotkey'
local application = require 'hs.application'

-- spaces uses private APIs and workarounds only when
-- creating, moving, and jumping to spaces, which this
-- script does not rely on.
local APP_NAME = 'Alacritty'

-- Toggle app
hotkey.bind({'cmd'}, '\\', function () -- cmd + backslash
  -- move to main space
  local function moveWindow(app, space)
    local win = nil
    while win == nil do
      win = app:mainWindow()
    end
    -- set position and window size
    local winFrame = win:frame()
    local scrFrame = screen.mainScreen():frame()
    winFrame.w = scrFrame.w
    winFrame.y = scrFrame.y
    winFrame.x = scrFrame.x
    win:setFrame(winFrame, 0)
    spaces.moveWindowToSpace(win, space)
    win:focus()
  end

  local app = application.get(APP_NAME)
  if app ~= nil and app:isFrontmost() then
    app:hide()
  -- ensure Alacritty is launched
  elseif app ~= nil then
    local space = spaces.activeSpaceOnScreen()
    moveWindow(app, space)
  end
end
)