Subject: bug#44973: Add a macOS global hotkey function

From: [email-masked]
Date: Sun, 20 Dec 2020 16:40:37 -0800

Hi Lars,

I'm pretty close to having a patch ready, but I'm stuck in one key spot. I
don't know if anyone on the list could help?

After the user registers a hotkey, and when they press the hotkey, MacOS
will run the code below. On the line "RUN_SOME_ELISP_FUNCTION", I would
expect some elisp function to be run (e.g. 'emacs-version').

But no matter what I do, it always crashes the program. I think my first
problem is not knowing how to call elisp (run_hooks, safe_call, etc?)
correctly, but second, I suspect if this is crashing due to a threading
issue.

    handler = [NSEvent
addGlobalMonitorForEventsMatchingMask:(NSEventMaskKeyDown)
handler:^(NSEvent *event){
        if (event.modifierFlags & modifier)
          if([event.charactersIgnoringModifiers characterAtIndex:0] ==
vkey) {
           RUN_SOME_ELISP_FUNCTION
            [[NSApp mainWindow] makeKeyAndOrderFront:NSApp];
          }
        }
      }];

Is there anyone who might know how to fill in this piece?

Thanks

On Tue, Dec 8, 2020 at 12:39 PM Lars Ingebrigtsen <[email-masked]> wrote:

> [email-masked] writes:
>
> > MacOS makes it very difficult to assign global hotkeys to focus
> > Emacs. For example, if I'm in another program, and I want to
> > launch/focus Emacs with "Alt-SPC", it can't just be set in the system
> > preferences; I'd need to use a 3rd-party program like skhd.
> >
> > Would it be possible to add a function or hook to Emacs which registers
> one or
> > more global hotkeys (using addGlobalMonitorForEventsMatchingMask), and
> then
> > when the hotkey is pressed, run an elisp function?
>
> [...]
>
> > Even if it's rare for Emacs to implement an OS-specific feature, there
> > is some precedent on Windows. If you look at w32-register-hot-keys,
> > it's similar to, but different from my request.
>
> Sure, I think that makes sense.  Would it be possible for you to work up
> a patch that adds this functionality?
>
> --
> (domestic pets only, the antidote for overdose, milk.)
>    bloggy blog: http://lars.ingebrigtsen.no
>