openwebwork / pg

Problem rendering engine for WeBWorK
http://webwork.maa.org/wiki/Category:Authors
Other
45 stars 76 forks source link

braces around math #1086

Open Alex-Jordan opened 2 months ago

Alex-Jordan commented 2 months ago

This is not really a PG "issue". But I am having an issue with PTX that and LaTeX that stems from something MathObjects does, so I will post here.

If you have like $f = Formula('x');, then $f->TeX is {x} with those surrounding braces. Why are those there? And where are they added? (I looked around in Value but could not pinpoint them.)

I am wondering if it would be safe to make those go away. This has to do with https://tex.stackexchange.com/questions/722329/unwanted-space-in-tcbraster. If a math expression ends up being wider than a tcolorbox that contains it, and the math expression has these braces, my best understanding is that the math expression is not line-breakable and that leads to the issue described there.

Perhaps this is a webwork2 issue though too (in rare situations) since several hardcopy themes use tcolorbox.

dpvc commented 2 months ago

If you have like $f = Formula('x');, then $f->TeX is {x} with those surrounding braces. Why are those there?

I am not able to reproduce this. For me on the current develop branch, Formula('x')->TeX generates a plain x for me. To my knowledge, the TeX() method has never added braces like this.

Alex-Jordan commented 2 months ago

OK, it's more complicated than I thought. I get braces with the combination of MathObjects and PGML.

$x = Formula("x");

Context()->texStrings;
# makes x (no braces)
BEGIN_TEXT
\($x\)
END_TEXT
Context()->normalStrings;

# makes x (no braces)
BEGIN_PGML
[`x`]
END_PGML

# makes {x} (braces)
BEGIN_PGML
[`[$x]`]
END_PGML
dpvc commented 2 months ago

OK, thanks for the wider context. The braces are coming from this line:

https://github.com/openwebwork/pg/blob/2bd3ca35d2d878a4e48e9a35266d522b7103a0bf/macros/core/PGML.pl#L892

It has been some decades since I wrote it, but I suspect the idea was to allow things like

$a = Real(123);
BEGIN_PGML
[`x^[$a]`]
END_PGML

to work without knowing whether $a has one digit or more than one digit. Otherwise, you would need to use

$a = Real(123);
BEGIN_PGML
[`x^{[$a]}`]
END_PGML

to make sure you handle both cases, in the situation where $a could be more than one digit. Not everyone will think to do this, just as they don't think to do it in

$a = Formula("pi+1");
$f = Formula("x^$a");

which is why MathObjects stringify using parentheses in these situations.

You could probably remove the braces in the TeX output, but it might break existing problems that use these constructions.

On the other hand, if you want to avoid the braces, you could do

$x = Formula('x';
BEGIN_PGML
[`[$x->TeX]`]
END_PGML

or

$x = Formula('x';
BEGIN_PGML
[`[@ $x->TeX @]`]
END_PGML

to get the un-braced version in the cases where you want to allow line breaking for in-line math expressions.