private string TermToLatex(Term tree, bool mathMode = false) { switch (tree) { case CompositeTerm composite: var latexTerms = composite.Terms.Select(t => TermToLatex(t, mathMode)); return(string.Join("", latexTerms)); case DividerTerm divider: if (divider.RequiresMathMode() && !mathMode) { return("$" + divider.Divider + "$"); } return(divider.Divider.ToString()); case EncapsulatedTerm encapsulated: var term = TermToLatex(encapsulated.Term, mathMode); if (encapsulated.ShowEncapsulatorTerm) { var left = encapsulated.Encapsulator; var right = EncapsulatedTerm.GetEncapsulatorEnd(left); return(EscapeString(left.ToString(), mathMode) + term + EscapeString(right.ToString(), mathMode)); } else { return(term); } case LeftRightTerm leftRightTerm: var leftLatex = TermToLatex(leftRightTerm.Left, true); leftLatex = leftLatex.Length > 1 ? "{" + leftLatex + "}" : leftLatex; var rightLatex = TermToLatex(leftRightTerm.Right, true); rightLatex = rightLatex.Length > 1 ? "{" + rightLatex + "}" : rightLatex; var content = leftLatex + leftRightTerm.Connector + rightLatex; return(mathMode ? content : "$" + content + "$"); case RawTerm raw: return(EscapeString(raw.Content, mathMode)); } throw new Exception("Unknown node " + nameof(tree)); }
private Term TextToTerm(string text) { var terms = new List <Term>(); var currentText = ""; var encapsulationText = ""; char?encapsulator = null; int encapsulationDepth = 0; for (var i = 0; i < text.Length; i++) { char currentChar = text[i]; if (encapsulator != null) { if (EncapsulatedTerm.IsEncapsulatorEnd(currentChar, encapsulator.Value) && encapsulationDepth-- == 0) { var innerTerm = TextToTerm(encapsulationText); terms.Add(new EncapsulatedTerm(encapsulator.Value, innerTerm)); encapsulator = null; encapsulationText = ""; encapsulationDepth = 0; } else { if (currentChar == encapsulator.Value) { encapsulationDepth++; } encapsulationText += currentChar; } continue; } if (EncapsulatedTerm.IsEncapsulatorStart(currentChar)) { terms.Add(new RawTerm(currentText)); currentText = ""; encapsulator = currentChar; continue; } if (DividerTerm.IsDivider(currentChar)) { terms.Add(new RawTerm(currentText)); currentText = ""; terms.Add(new DividerTerm(currentChar)); continue; } currentText += currentChar; } if (encapsulator != null) { terms.Add(new RawTerm(encapsulator.ToString())); var innerTerm = TextToTerm(encapsulationText); if (innerTerm is CompositeTerm composite) { terms.AddRange(composite.Terms); } else { terms.Add(innerTerm); } } if (currentText.Length > 0) { terms.Add(new RawTerm(currentText)); } return(terms.Count == 1 ? terms.Single() : new CompositeTerm(terms)); }