Skip to content

Instantly share code, notes, and snippets.

@krooked
Created May 17, 2023 11:07
Show Gist options
  • Save krooked/964f4b6b7ff804106ec5692afc57e68d to your computer and use it in GitHub Desktop.
Save krooked/964f4b6b7ff804106ec5692afc57e68d to your computer and use it in GitHub Desktop.
Hammerspoon (https://www.hammerspoon.org) script to add a custom key binding for vim mode in Xcode. Pressing two times the f-key within the time frame exits insert mode in normal vim mode.
local timer = require("hs.timer")
local eventtap = require("hs.eventtap")
local keycodes = require("hs.keycodes")
local events = eventtap.event.types
local timeFrame = 0.2
local f_key = 3
local pressTime, firstDown = 0, false
function twoHandler()
local frontmostAppName = hs.application.frontmostApplication():name()
if frontmostAppName == "Xcode" then
hs.eventtap.keyStroke({"ctrl"}, "h", 100, frontmostAppName)
hs.eventtap.keyStroke({"ctrl"}, "h", 100, frontmostAppName)
hs.eventtap.keyStroke({""}, "ESCAPE", 100, frontmostAppName)
end
end
function isKeyCorrect(event)
local keyCode = event:getKeyCode()
return keyCode == f_key
end
function inTime(time)
return timer.secondsSinceEpoch() - time < timeFrame
end
keydown = eventtap.new({ events.keyDown }, function(event) --keep keydown globally to ensure it stays alive
if isKeyCorrect(event) then
if firstDown and inTime(pressTime) then --if first press already happened and the second was in time
twoHandler()
elseif not firstDown or not inTime(pressTime) then --if the first press has not happened or the second wasn't in time
pressTime, firstDown = timer.secondsSinceEpoch(), true --set first press time to now and first press to true
return false --stop prematurely
end
end
pressTime, firstDown = 0, false --if it reaches here that means the key was incorrect, then reset timer and flag
return false --keeps the event propagating
end
) --start our watcher
keydown:start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment