I cannot find any function which delivers the output width of formatted text. I need that either in absolute printer points or scaled to the enclosing context or as the number of characters in standard output font size (13 in my environment).
As an example I want to use Multicolumn for a list of base-b tuples:
Block[{ruler = StringRepeat["1234567890", 7], k, tuples, base, cols},
base = 16; k = 3;
tuples = RandomChoice[Tuples[Range[0, base - 1], k], 20];
tuples = BaseForm[#, base] & /@ tuples;
cols = 5;
Print[ruler, "\ncols = ", cols, "\n", Multicolumn[tuples, cols]];
];
In this example, I use a fixed number of column cols = 5 which gives a total horizontal width of about 69 standard characters. But of course, this number cols should be dependent on the total horizontal width available and the base-dependent width of each tuple, which in turn is depended on Style-formating.
As a bypass, I calculate cols in some rude way by the following code for twidth and cols. It is done twice, without and with formatting:
Block[{ruler = StringRepeat["1234567890", 7], k, tuples, base, cols,
hwidth = 70, ds = 1, twidth, fs},
(* Build tuples *)
base = 16; k = 3;
tuples = RandomChoice[Tuples[Range[0, base - 1], k], 20];
tuples = BaseForm[#, base] & /@ tuples;
(* Calculate the width of one tupel *)
twidth =
2 + k - 1 +
k*(1 + Switch[Sign[base - 10], 0, 0, +1, 2.00, -1, 1.0]);
(* Calculate the number of columns and print *)
cols = Max[Floor[(hwidth + ds)/(twidth + ds)], 1];
Print[ruler, "\n{twidth, cols} = ", {twidth, cols}, "\n",
Multicolumn[tuples, cols]];
(* The same for a larger font size fs *)
fs = 18;
tuples = Style[#, Blue, fs] & /@ tuples;
twidth =
fs/13*(2 + k - 1 +
k*(1 + Switch[Sign[base - 10], 0, 0, +1, 2.00, -1, 1.0]));
cols = Max[Floor[(hwidth + ds)/(twidth + ds)], 1];
Print[ruler, "\n{twidth, cols} = ", {twidth, cols}, "\n",
Multicolumn[tuples, cols]];
];
The calculation of twidth above is the crucial point. If I had a WL-function like WidthChr[expr], I could just write:
twidth = WidthChr[First[tuples]];
or any other formatted or non-formatted expression instead of tuples. Of course, this could be given as a read-only property as well.