Reputation: 2983
Is there a way to select some text in a Mathematica notebook and then wrap the selection in brackets?
For example, if I typed the following in a notebook:
1, 2, 3, 4
I want to be able to select all the text and then type the command to insert matching curly brackets (alt-}
on linux) and it would wrap the selection in curly brackets.
{1, 2, 3, 4}
Upvotes: 5
Views: 1208
Reputation: 8680
The following function adds a command that basically does what you asked.
As written, it coopts the Control+U key combination, (which is usually 'underline'). You can change that quite simply. It also adds an item called 'Make List' to the Insert menu, but I imagine you'd just use the key combination.
This modification only persists for the current session, but you could add the function to an init file to load at start-up. There are other ways of permanently adding the functionality, such as by editing the KeyEventsTranslations file, like here.)
Once you have run the implementation function it can be executed with Control+U.
FrontEndExecute[
FrontEnd`AddMenuCommands["DuplicatePreviousOutput",
{Delimiter, MenuItem["Make List",
FrontEnd`KernelExecute[
nb = SelectedNotebook[];
sel = NotebookRead[nb];
NotebookWrite[nb, Cell[BoxData[RowBox[{"{", sel, "}"}]]]]],
MenuKey["u", Modifiers -> {"Control"}],
System`MenuEvaluator -> Automatic]}]]
Having typed and selected: 1, 2, 3, 4
Control+U
{1, 2, 3, 4}
Addendum
Here is a version you could use instead of your MenuSetup modification. It's set to activate on "{" key press, and will wrap a selection or just match braces. Putting this into MenuSetup isn't so straightforward; I would do it by calling an external program from MenuSetup with KernelExecute
. It would be just as effective to put the code below in an init file.
FrontEndExecute[
FrontEnd`AddMenuCommands[
"DuplicatePreviousOutput", {Delimiter, MenuItem["Make List",
FrontEnd`KernelExecute[
nb = SelectedNotebook[];
sel = NotebookRead[nb];
If[sel === {},
FrontEndExecute[FrontEndToken["InsertMatchingBraces"]],
NotebookWrite[nb, Cell[BoxData[RowBox[{"{", sel, "}"}]]]]]],
MenuKey["{", Modifiers -> {}],
System`MenuEvaluator -> Automatic]}]]
Upvotes: 6