I like to annotate output, using something like the following:

annotStyle[t_] := Text@Style[t, Darker@Blue, Larger]
Format[annot[t_][x_]] := Row[{annotStyle[t], annotStyle[":  "], x}]

(data = Array[RandomReal, 10]) // annot@"Ten random numbers"
{Min@data, Max@data} // annot@Range
Mean@data // annot@μ
Median@data // annot@Median
Variance@data // annot@Variance
Sqrt@%[[1]] // annot@"Standard deviation"

The downside is that annotating changes the value of the output. Is there some way of avoiding this, so that, for example, in the first line of the example I don't need parentheses and in the last line of the example, I don't need to use [[1]]?

Specifically, if possible, I'd like

x // annot@t

to display as t: x, but have the value of x, for any expression x.

As I've put this question together, I've realised that

annot[t_][x_] := (Print[annotStyle[t], annotStyle[":  "], x]; x;)

almost does what I want and is better than my previous attempt. Is there a way of getting exactly what I want?


Based on an answer to the duplicate question, the following, using $PreRead and $PrePrint, meets my needs, interpreting both x // "t" or x; "t" for annotations.

 annotStyle[t_] := Text@Style[Style[t, Darker@Blue, Larger], Larger]
 annotLine[t_, x_] := If[Characters[t][[-1]] == " ", {annotStyle[t], x}, 
   {annotStyle[t], annotStyle[Style[":  ", Bold]], x}]
 $PreRead = 
Replace[#, RowBox[{body__, ";" | "//", note_String?(StringMatchQ[#, "\"*\""] &)}] :> 
  ($note = note; RowBox[{body}])] &;
 $PrePrint = 
If[$note =!= Null, # &[Row[annotLine[ToExpression[$note], Pane@#]], 
  $note = Null], #] &;

 data = Array[RandomReal, 10]; "The random data is  "
 {Min@data, Max@data} // "Range"
 Mean@data // "μ"
 Median@data // "Median"
 Variance@data // "Variance"
 Sqrt@%[[1]] // "Standard deviation"

Not the answer you're looking for? Browse other questions tagged or ask your own question.