How can I use attach in such a way that the layout is not affected?

I am trying to lay out some school-level mathematics and I’d like to show the borrowing/relabelling involved in a subtraction. The closest I can get is shown below, but you can see that when I add the workings (in red), this moves the digits ‘5’ and ‘2’ so they are no longer aligned.

The second part of the diagram was generated using the code below.

$#grid(columns:5,
align: center,
stroke: (x, y) => if y == 2  and x >= 0 { (top: 0.4pt + black) },
inset: (x, y) => if x == 2 { (x: 0pt, y: 3pt) } else { (x: 2pt, y: 3pt) },
[], [$attach(tl: #text(red)[4], cancel(stroke: #(paint: red), 5))$], [.], [$attach(2, tl: #text(red)[1])$], [7],
[$minus$], [3], [.], [4], [2], 
[], [1], [.], [8], [5])$

I couldn’t work out how to use place (or something else) to make it so the attachments did not affect the layout of the original text shown in black.

Would aligning your columns right help you?

image

1 Like

Thanks for this suggestion, which I had not considered. One issue is that the decimal points are not centred nicely (but I can change it to center that column), but a bigger issue is the fact that columns with attachments are much wider.

I would like it to have the exact same width as the original grid, but just with the items attached, but as you can see, it is now much wider.
image

I think, you should use place in that case for absolute positioning. dx and dy should get your supscript in the right place!

I couldn’t work out how to get place to work with the attach function though. I also couldn’t really work out how to manufacture the right appearance of small text using place directly.

The following seems to work:

#let annotate(it, with: none) = math.attach(it, tl: box(
  place(
    bottom+right,
    text(red, with),
)))

#let strike = math.cancel.with(stroke: red)

#grid(
  columns:5,
  align: center,
  stroke: (x, y) => if y == 2  and x >= 0 { (top: 0.4pt + black) },
  inset: (x, y) => if x == 2 { (x: 0pt, y: 3pt) } else { (x: 2pt, y: 3pt) },
  [], $annotate(strike(5), with: 4)$, $.$, $annotate(2, with: 1)$, $7$,
  $-$, $3$, $.$, $4$, $2$, 
  $$, $1$, $.$, $8$, $5$,
)

image

I put the place call in a box: the placed content doesn’t take any space so the box will be zero-size, at the correct position. Aligning the bottom-right of the placed content with the (bottom-right of) the zero-sized box works well. (I’m not sure what happens here with spacing when you don’t include the box.)

1 Like

The use of the box was the missing piece of the puzzle for me! Thank you.