public static Paragraph Parse(string text, Style?style = null) { if (text is null) { throw new ArgumentNullException(nameof(text)); } style ??= Style.Plain; var result = new Paragraph(); using var tokenizer = new MarkupTokenizer(text); var stack = new Stack <Style>(); while (tokenizer.MoveNext()) { var token = tokenizer.Current; if (token == null) { break; } if (token.Kind == MarkupTokenKind.Open) { var parsedStyle = StyleParser.Parse(token.Value); stack.Push(parsedStyle); } else if (token.Kind == MarkupTokenKind.Close) { if (stack.Count == 0) { throw new InvalidOperationException($"Encountered closing tag when none was expected near position {token.Position}."); } stack.Pop(); } else if (token.Kind == MarkupTokenKind.Text) { // Get the effective style. var effectiveStyle = style.Combine(stack.Reverse()); result.Append(Emoji.Replace(token.Value), effectiveStyle); } else { throw new InvalidOperationException("Encountered unknown markup token."); } } if (stack.Count > 0) { throw new InvalidOperationException("Unbalanced markup stack. Did you forget to close a tag?"); } return(result); }
/// <summary> /// Converts the string representation of a style to its <see cref="Style"/> equivalent. /// A return value indicates whether the operation succeeded. /// </summary> /// <param name="text">A string containing a style to parse.</param> /// <param name="result"> /// When this method returns, contains the <see cref="Style"/> equivalent of the text contained in <paramref name="text"/>, /// if the conversion succeeded, or <c>null</c> if the conversion failed. /// </param> /// <returns><c>true</c> if s was converted successfully; otherwise, <c>false</c>.</returns> public static bool TryParse(string text, out Style?result) { return(StyleParser.TryParse(text, out result)); }
/// <summary> /// Converts the string representation of a style to its <see cref="Style"/> equivalent. /// </summary> /// <param name="text">A string containing a style to parse.</param> /// <returns>A <see cref="Style"/> equivalent of the text contained in <paramref name="text"/>.</returns> public static Style Parse(string text) { return(StyleParser.Parse(text)); }