Sublime Forum

Q: How does Sublime create a custom keyEquivalent string in its menu?

#1

This is a question about how Sublime implements its application menu on macOS (the NSMenu).

This isn’t directly related to Sublime Text, but I would really appreciate it if you could give me any direction as to how you’ve solved this small problem when programming Sublime Text.

Basically, I have an app that registers shortcuts (the source is here), and I have multi-key shortcuts (like "cmd+k, cmd+a", etc). But no matter what I do I can’t customise the keyEquivalent (the shortcut text) in the NSMenuItem.

Here’s an image of Sublime Text doing what I mean, the keyEquivalent text is boxed:

By default, an NSMenuItem generates that string from whatever you pass in as a keyEquivalent, and so having these custom strings isn’t supported by default.

Now, I’ve tried making a completely custom view in order to get this behaviour, but once I do that thanks to some strange translucency/apperance issues the background color of the NSMenuItem is botched. Here’s an attempt:

This is setting the background color to EXACTLY the same blue as the highlighted color.
As you can see it doesn’t work (this is achieved using a completely custom NSView), and it creates different colors behind an NSImage. Weird.

This is the blue I want it to be like.

Here’s Sublime doing the same thing, with the correct color:


I would really appreciate it if you could let me know how you manage to have a custom keyEquivalent shortcut string with a normal NSMenuItem. :heart:

0 Likes

#2

As you might imagine, it’s a giant hack. If a menu has any multi step key bindings, we don’t set any key equivalents, and instead just use attributed strings with embedded tab stops to display the text + key binding. It doesn’t work correctly in all cases (especially if you want sub menus - you’ll notice there are no menu items with multi step key bindings at the top level), but it’s better than displaying nothing.

4 Likes

#3

Ah, I see now. I had never noticed the difference if there was a menu with no multi-step key bindings - so I suppose while it’s a hack it worked well. :smile:

I guess I’ll give that a shot, it has to be better than what I’m doing now. I really don’t like how there’s no easy way to customise a normal NSMenuItem, or to even just get something that looks like it. Classic Apple, making the simple things hard.

Thank you so much for responding, really appreciate that. :thumbsup:

0 Likes

#4

For any future readers based on the answer @jps gave me here’s a quick and simple implementation of it in Swift: https://github.com/acheronfail/apptivator/blob/0e29f650277884399efcf5f5461ed42e23d90b9f/Apptivator/AppDelegate.swift#L146-L171

Thanks again! :tada: :slight_smile:

0 Likes