Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 66 additions & 1 deletion CSharpMath.Core.Tests/Atom/LaTeXParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,71 @@ public void TestText() {
Assert.Equal(@"\mathrm{\pounds x\ y}", LaTeXParser.MathListToLaTeX(list).ToString());
}

[Fact]
public void TestInlineMathInsideText() {
var list = ParseLaTeX(@"\text{before $x+1$ after}");
Assert.Equal(FontStyle.Roman, list[0].FontStyle);
Assert.Equal(FontStyle.Default, list[7].FontStyle);
Assert.Equal(FontStyle.Default, list[8].FontStyle);
Assert.Equal(FontStyle.Default, list[9].FontStyle);
Assert.Equal(FontStyle.Roman, list[10].FontStyle);
Assert.Equal(@"\mathrm{before\ }x+1\mathrm{\ after}", LaTeXParser.MathListToLaTeX(list).ToString());
}

[Fact]
public void TestEscapedDollarInsideTextIsLiteralAndRoundTrips() {
var list = ParseLaTeX(@"\text{price \$5}");
Assert.Contains(list, atom => atom is Ordinary { Nucleus: "$" });
var serialized = LaTeXParser.MathListToLaTeX(list).ToString();
Assert.Contains(@"\$", serialized);
Assert.Equal(list, ParseLaTeX(serialized));
}

[Fact]
public void TestTextInlineMathCommandsBracesScriptsAndEscapedDollarRoundTrip() {
var input = @"\text{cases: $\frac{n^{2}}{2}$, \mathbf{Roman} and \$ literal}";
var list = ParseLaTeX(input);
var serialized = LaTeXParser.MathListToLaTeX(list).ToString();
Assert.Equal(list, ParseLaTeX(serialized));
}

[Fact]
public void TestIssue205CasesRoundTrip() {
var input = @"f(n) = \begin{cases} n/2, & \text{if $n$ is even} \\ 3n+1, & \text{if $n$ is odd} \end{cases}";
var list = ParseLaTeX(input);
Assert.Equal(list, ParseLaTeX(LaTeXParser.MathListToLaTeX(list).ToString()));
}

[Fact]
public void TestUnbalancedInlineMathInsideTextReportsSourcePosition() {
var input = @"\text{before $x after}";
var builder = new LaTeXParser(input);
var (list, error) = builder.Build();
Assert.Null(list);
Assert.Contains("Expected character not found: $", error);
Assert.Equal(input.Length - 1, builder.NextChar);
Assert.EndsWith($"↑ (pos {input.Length - 1})", LaTeXParser.HelpfulErrorMessage(error!, input, builder.NextChar));
}

[Fact]
public void TestTextStateIsRestoredWhenTextArgumentFails() {
var builder = new LaTeXParser(@"\text{bad \notacommand}");
var (_, error) = builder.Build();
Assert.NotNull(error);
Assert.False(builder.TextMode);
Assert.Equal(FontStyle.Default, builder.CurrentFontStyle);
}

[Theory]
[InlineData(@"\text{a $$ b}")]
[InlineData(@"\text{a $$$ b}")]
public void TestDisplayDollarDelimitersInsideTextAreRejected(string input) {
var builder = new LaTeXParser(input);
var (_, error) = builder.Build();
Assert.Contains("Display math delimiters $$ are not allowed inside text", error);
Assert.Equal(input.IndexOf("$$", StringComparison.Ordinal) + 1, builder.NextChar);
}

[Fact]
public void TestScriptOrdering() {
var list = ParseLaTeX(@"\int_a^b");
Expand Down Expand Up @@ -1634,4 +1699,4 @@ public void TestErrorSurrogates() {
}
}
}
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 2 additions & 1 deletion CSharpMath.Rendering.Tests/TestRenderingMathData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public sealed class TestRenderingMathData : TestRenderingSharedData<TestRenderin
public const string BraSum = @"\frac{1}{\sqrt{2^n}} \sum_{i=0}^{2^n-1} \Bra{i}";

public const string Cases = @" w \equiv \begin{cases} 0 & \text{for}\ c = d = 0\\ \sqrt{|c|}\,\sqrt{\frac{1+\sqrt{1+(d/c)^2}}{2}} &\text{for}\ |c| \geq |d|\\ \sqrt{|d|}\,\sqrt{\frac{|c/d| + \sqrt{1+(c/d)^2}}{2}} &\text{for}\ |c|<|d| \end{cases}";
public const string Issue205NestedTextMath = @"f(n) = \begin{cases} n/2, & \text{if $n$ is even} \\ 3n+1, & \text{if $n$ is odd} \end{cases}";
public const string Choose = @"{6 \choose x}";
public const string Commands = @"5\times(-2 \div 1) = -10";

Expand Down Expand Up @@ -135,4 +136,4 @@ public sealed class TestRenderingMathData : TestRenderingSharedData<TestRenderin

public const string VectorProjection = @"Proj_\vec{v}\vec{u}=|\vec u|\cos\theta\times\frac\vec v{|\vec v|}=|\vec u|\frac{\vec u \cdot \vec v}{|\vec u||\vec v|}\times\frac\vec v{|\vec v|}\\\text{Suppose \mathit{u} and \mathit v are unit vectors, }Proj_\vec v\vec u = (\vec u\cdot\vec v)\vec v";
}
}
}
27 changes: 26 additions & 1 deletion CSharpMath/Atom/LaTeXParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ private Result<MathList> BuildInternal(bool oneCharOnly, char stopChar = '\0', M
r ??= new MathList();
MathAtom? prevAtom = null;
while (HasCharacters) {
if (TextMode && Chars[NextChar] == '$') {
NextChar++;
if (HasCharacters && Chars[NextChar] == '$')
return "Display math delimiters $$ are not allowed inside text";
var oldTextMode = TextMode;
var oldFontStyle = CurrentFontStyle;
TextMode = false;
CurrentFontStyle = FontStyle.Default;
Result<MathList> inlineMath;
try {
inlineMath = BuildInternal(false, '$');
} finally {
TextMode = oldTextMode;
CurrentFontStyle = oldFontStyle;
}
if (inlineMath.Error is string inlineError) return inlineError;
r.Append(inlineMath.Match(value => value, _ => throw new InvalidCodePathException("Inline math unexpectedly failed")));
prevAtom = r.Atoms.LastOrDefault();
continue;
}
if (stopChar == '$' && Chars[NextChar] == '}')
return "Expected character not found: $";
MathAtom? atom = null;
if (Chars[NextChar] == stopChar && stopChar > '\0') {
NextChar++;
Expand Down Expand Up @@ -702,6 +724,9 @@ static bool MathAtomToLaTeX(MathAtom atom, StringBuilder builder,
case { Nucleus: "\u2212" }:
builder.Append('-');
break;
case { Nucleus: "$" }:
builder.Append(@"\$");
break;
case { Nucleus: var aNucleus }:
builder.Append(aNucleus);
break;
Expand Down Expand Up @@ -731,4 +756,4 @@ public static StringBuilder MathListToLaTeX(MathList mathList, StringBuilder? sb
return sb;
}
}
}
}
9 changes: 7 additions & 2 deletions CSharpMath/Atom/LaTeXSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,14 @@ public static class LaTeXSettings {
var readsToEnd =
!command.AsSpan().StartsWithInvariant("math")
&& !command.AsSpan().StartsWithInvariant("text");
return (readsToEnd ? parser.ReadUntil(stopChar, accumulate) : parser.ReadArgument()).Bind(r => {
Result<MathList> result;
try {
result = readsToEnd ? parser.ReadUntil(stopChar, accumulate) : parser.ReadArgument();
} finally {
parser.CurrentFontStyle = oldFontStyle;
parser.TextMode = oldSpacesAllowed;
}
return result.Bind(r => {
if (readsToEnd)
return OkStop(accumulate);
else return OkStyled(r);
Expand Down Expand Up @@ -1189,4 +1194,4 @@ atom is Accent accent
// \varsupsetneqq -> ⫌ + U+FE00 (Variation Selector 1) Not dealing with variation selectors, thank you very much
};
}
}
}
Loading