0

Seems that the ButtonBox is visually (not functionally) treating the String as an Expression.

(* 1 *) DisplayForm[ButtonBox["2%"]]

(* 2 *) Button["2%"]

(* 3 *) DisplayForm["2%"]

(* 4 *) "2%"

(* 5 *) 2%

The text in 1 and 5 appear the same (2x%). The rest appear as the string (2%).

Is there some option or function that allows the ButtonBox to visually treat the string as a string?

edit:

I was going down this road, rather than simply using Buttons, just to see if there were ways to speed up a dynamic display. The suggestion by @CarlWoll was almost three times as fast as using the HoldForm way.

If you have a list of strings that have "%" in them, such as

strings = {"this", "that", "2%", "(330%)"}

then something like this

StringReplace[strings, {StringExpression[d : (DigitCharacter ...), 
    "%"] :> StringExpression["\"", d, "%", "\""]}]

would fix them so that they can be displayed properly.

jWey
  • 73
  • 6
  • I would use RawBoxes instead of DisplayForm, and use "\"2%\"" instead of "2%" DisplayForm uses heuristics to decide whether a string should be considered as "boxes" or it should be considered as "expression". RawBoxes does not use any heuristics, all strings are interpreted as "boxes". – Carl Woll Feb 22 '22 at 17:56
  • Since % is a reserved character (shorthand for Out), and since Mathematica tries to be helpful with arithmetic expressions, the expression 2% will be interpreted as Times[2, %], where the % will actually be resolved to some Out[...] expression. I'm not an expert with box expressions, so I don't know what the consequences will be, but you could try something like DisplayForm[ButtonBox[HoldForm["2%"]]] – lericr Feb 22 '22 at 17:58
  • @lericr HoldForm will work just fine. Thanks for the suggestion. – jWey Feb 22 '22 at 18:18
  • @CarlWoll I probably won't go down the RawBoxes route, and will just wrap the strings in HoldForm. Is there some other advantage to RawBoxes? (edit: I was using ButtonBoxes because it seemed to render/load-in-the-front-end about twice as fast as buttons, and I was creating a display with several hundred buttons within a scrollable pane.) – jWey Feb 22 '22 at 18:30
  • I despise DisplayForm. DisplayForm allows one to mix boxes and expressions, and then tries to guess what the user wanted. Using RawBoxes only allows boxes, and will complain when given something that is a mix of boxes and expressions. When DisplayForm doesn't work as you want, you have to look at what you have, and try to figure out which heuristic used by DisplayForm doesn't work the way you want. – Carl Woll Feb 22 '22 at 19:07

0 Answers0