Skip to main content

notebooks - Is there a keybinding for absolute value?


Is there a keyboard shortcut or esc-sequence for typing in the absolute value bars into input cells? I know that if you do,


Abs[-4] // TraditionalForm

and copy the output into an input cell using the "Paste literal" option, you get functioning absolute value bars with a placeholder. I'm curious if there's a less roundabout way to obtain them.



Answer




There isn't a built-in keybinding, but you can define one yourself:


ClearAll[myAbs]

appearanceAbs[x_] :=
TemplateBox[{x}, "myAbs",
DisplayFunction :> (RowBox[{"\[LeftBracketingBar]",
"\[NoBreak]", #1, "\[NoBreak]", "\[RightBracketingBar]"}] &),
InterpretationFunction :> (RowBox[{"myAbs", "[", #1, "]"}] &)]

myAbs[x_?NumericQ] := Abs[x]


myAbs /: MakeBoxes[myAbs[x_], _] := appearanceAbs[ToBoxes[x]]

SetOptions[EvaluationNotebook[],
InputAliases ->
DeleteDuplicates@
Join[{"abs" -> appearanceAbs["\[SelectionPlaceholder]"]},
InputAliases /.
Quiet[Options[EvaluationNotebook[], InputAliases]] /.
InputAliases -> {}]]


This adds a shortcut EscabsEsc to the notebook's InputAliases. When you type it, a template will appear that looks the way one expects, $|\square|$. You may have to tab into it (that's a bug that didn't exist in older versions), and it will evaluate as Abs if the argument you entered is numeric. Otherwise, the display will remain of the form you see in TraditionalForm output. The evaluation of Abs happens because I define the template with an InterpretationFunction. I restrict this to numeric arguments, and for the other cases there is the definition myAbs /: MakeBoxes which kicks in when an unevaluated template is to be displayed again. To make this case distinction possible, I define an intermediate function myAbs.


Comments