Define context-aware keys in Emacs05 Jan 2016, by Artur Malabarba.
What do you do if you want to override a key only in a certain context? Take this Quotation Marks post as an example. We want to change the " key in general, but retain the regular behaviour if we’re inside a code-block. In this case the solution was to just call the old behaviour manually, but what if you’re writing a more general command and you don’t know what this “old behaviour” is?
As it turns out, it’s a little-known feature of Emacs that you can specify filter functions to determine whether a keybind should be active. We use this quite a bit in SX.el. While the syntax is far from simple, it’s very easy to copy-paste and just fill in your predicate.
First, we redefine
endless/round-quotes without that ugly part that
self-insert-command (previous version here).
Then, we define the same key as before, but instead of just passing the command
we use a menu-item bound to
nil. The fact that it’s a menu-item is irrelevant
here, it behaves exactly like a key bound to
nil (i.e., an empty keybind).
However, this allows us to setup a filter that changes the keybind to
endless/round-quotes if we’re not inside an org-src-block.
maybe-round-quotes is just a useless name for the menu-item, and you can
learn more about all of this on this manual page. For now, it suffices to say we
deserve a more convenient way to use this feature.
Of course, that’s nothing a good macro can’t fix.
Which leads to the much nicer syntax:
And a similar keybind for Markdown, which is a bit more of a mouth-full.