Adding a keyboard shortcut to Mathematica V7

(updated 2009-03-23 to add the backslashes that disappeared between my blog editor and WordPress)

In Mathematica, typing index brackets is clumsy, as one has to type esc-[[-esc then esc-]]-esc. I found a way to modify the Edit menu to add a shortcut for this.
I don’t know how this would be done from non-Macintosh systems, but on Macintosh, you copy the file “/Applications/Mathematica.app/SystemFiles/FrontEnd/TextResources/Macintosh/MenuSetup.tr” (in the Application bundle) into “~/Library/Mathematica/SystemFiles/FrontEnd/TextResources/Macintosh/MenuSetup.tr”. Then, edit it using a plain text editor like BBEdit, or even with Mathematica itself.

In this file, find the line

MenuItem["Matching []", "InsertMatchingBrackets", MenuKey["]", Modifiers->{"Command", "Option"}]],

In the same block of menu items, add this

MenuItem["Matching [LeftDoubleBracket][RightDoubleBracket]",
    FrontEndExecute[{
        FrontEnd`NotebookApply[FrontEnd`InputNotebook[],
            "[LeftDoubleBracket][SelectionPlaceholder][RightDoubleBracket]"]}],
    MenuKey["]", Modifiers->{"Command", "Option", "Control"}]],

You have to restart Mathematica for it to see this change, but now you can wrap index brackets around the selection by typing cmd-opt-ctl-].

This is different from the other “Matching…” insertions, as it wraps the brackets around the selection, or leaves a “placeholder” selected if there was no selection rather than replacing the selection with the insertion. Since I’m used to editors that wrap the selection in this case, I’ve also changed the existing “Matching…” menu items to use this same technique.

This is what I have now:

MenuItem["Matching []",
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],"[[SelectionPlaceholder]]"]}],
    MenuKey["]", Modifiers->{"Command", "Option"}]],
MenuItem["Matching {}",
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],"{[SelectionPlaceholder]}"]}],
    MenuKey["}", Modifiers->{"Command", "Option"}]],
MenuItem["Matching ()",
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],"([SelectionPlaceholder])"]}],
    MenuKey[")", Modifiers->{"Command", "Option"}]],
MenuItem["Matching [LeftDoubleBracket][RightDoubleBracket]",
    FrontEndExecute[{
        FrontEnd`NotebookApply[
            FrontEnd`InputNotebook[],"[LeftDoubleBracket][SelectionPlaceholder][RightDoubleBracket]"]}],
    MenuKey["]", Modifiers->{"Command", "Option", "Control"}]],

These changes should survive minor updates to Mathematica, but it’s best to keep a copy of your file in case some later update replaces it.


Posted

in

, ,

by

Tags: