2

My notebooks contain only text-based cells and no code. I use InputAliases quite a bit to save time. Typing the escape key before and after to trigger the InputAliases is not very efficient for me.

I would like to build a NotebookEventAction that triggers when I type "s" and "/" successively. This will work for me as it is rare that I would ever type these keys successively in my text-based notebooks.

I have successfully built the action to trigger when I type the "s" as shown below. Works great.

SetOptions[SelectedNotebook[], 
  NotebookEventActions -> {{"KeyDown", "s"} :> 
     KeyBindings`MySpecial[]}];

KeyBindings`MySpecial[] := Module[{}, SelectionMove[InputNotebook[], All, Word]; NotebookApply[InputNotebook[], "\[AliasDelimiter]\[SelectionPlaceholder]\[AliasDelimiter]"]];

However, I would like it to only trigger when I type "s" and then "/" in succession. Any ideas?

B flat
  • 5,523
  • 2
  • 14
  • 36

2 Answers2

1

You'd probably have more luck using a modifier such as Control rather than tracking a two-key sequence. However NotebookEventActions does not seem to support that. A solution would be to add the modified key binding as a menu item, added to MenuSetup.tr

Something like this

Item["Special KeyBinding", KernelExecute[KeyBindings`MySpecial[]],
 MenuKey["s", Modifiers -> {"Control"}], MenuEvaluator -> Automatic]

based on the last item here: How can I set a keyboard shortcut to run a command?

Of course, Control+s is generally used for Save so you'd probably want to use something different. You might also need FrontEndExecute instead of KernelExecute.

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
1

I found a solution for successive keystrokes. This one triggers when I press "/" and then "s" in succession (the s is my moniker for shortcut). I'm not great at writing code. Maybe someone else can clean up my code below, but it does seem to work. Notice, I temporarily created a NotebookEventAction inside of the other one and then reset it after so that the succession works.

To try it out, run the code below and then open a text cell and type "alpha.s"

Res := SetOptions[SelectedNotebook[], 
   NotebookEventActions -> {{"KeyDown", "/"} :>
  MyBindings`MySpecial[]
 }];

Res[]; MyBindings`MySpecial[] := Module[{}, SetOptions[SelectedNotebook[], NotebookEventActions -> {{"KeyDown", "s"} :> { SelectionMove[InputNotebook[], All, Word];

     NotebookApply[InputNotebook[], 
      "\\[AliasDelimiter]\\[SelectionPlaceholder]\\[\

AliasDelimiter]"]; Res[]; }}]; ];

B flat
  • 5,523
  • 2
  • 14
  • 36
  • 1
    +1 very clever. Something is weirdly breaking in the copy & paste to Mathematica though. I got it working fine by copying in the complete NotebookApply expression from your original question section. – Chris Degnen Mar 06 '22 at 22:15
  • related... https://mathematica.stackexchange.com/questions/265379/my-custom-shortcut-for-escape-key-is-not-parsing – B flat Mar 19 '22 at 04:48