Search code examples
hammerspoon

remap apostrophe to other keys using hammerspoon


the problem is caused by library's bug and this had been fixed.


I'm using hammerspoon and I'm trying to remap Ctrl + ' to backtick(`) but I cannot.

the setting file init.lua is like below:

local function keyCode(key, modifiers)
   modifiers = modifiers or {}
   return function()
      hs.eventtap.event.newKeyEvent(modifiers, string.lower(key), true):post()
      hs.timer.usleep(100)
      hs.eventtap.event.newKeyEvent(modifiers, string.lower(key), false):post()
   end
end

local function remapKey(modifiers, key, keyCode)
   hs.hotkey.bind(modifiers, key, keyCode, nil, keyCode)
end

remapKey({'ctrl'}, 'h', keyCode('delete')) // works
remapKey({'ctrl'}, "'", keyCode("`")) // does not work

error message is:

Invalid key: ' - this may mean that the key requested does not exist in your keymap (particularly if you switch keyboard layouts frequently)

it seems the problem is hs.keycodes.map does not include apostrophe (but it includes double-quote and backtick).

is it possible to remap apostrophe?


Solution

  • The point here is the keyboard layout (that Hammerspoon thinks your keyboard is in).

    Do you actually have an apostrophe (`) key on your keyboard? I mean, if you need to type something like shift+@ to input the apostrophe, then you must tell so to newKeyEvent.

    remapKey({'ctrl'}, "'", keyCode("@", {"shift"})) 
    

    Or, you could simply use hs.eventtap.keyStroke() in the keyCode() function if you don't want to bother with how to type a string using the keyboard:

    local function keyCode(key, modifiers)
       modifiers = modifiers or {}
       return function()
          hs.eventtap.keyStroke(modifiers, key)
       end
    end
    

    As for hs.keycodes.map having the double quote instead of the single quote, it turned out to be a bug of Hammerspoon, so I've just filed a PR.