/// <summary> /// This function can be called by any element parsing. Given a start and stopping point this will /// parse all found elements out of the range. /// </summary> /// <returns> A list of parsed inlines. </returns> public static List <MarkdownInline> ParseInlineChildren(string markdown, int startingPos, int maxEndingPos, bool ignoreLinks = false) { int currentParsePosition = startingPos; var inlines = new List <MarkdownInline>(); while (currentParsePosition < maxEndingPos) { // Find the next inline element. var parseResult = FindNextInlineElement(markdown, currentParsePosition, maxEndingPos, ignoreLinks); // If the element we found doesn't start at the position we are looking for there // is text between the element and the start of the parsed element. We need to wrap // it into a text run. if (parseResult.Start != currentParsePosition) { var textRun = TextRunInline.Parse(markdown, currentParsePosition, parseResult.Start); inlines.Add(textRun); } // Add the parsed element. inlines.Add(parseResult.ParsedElement); // Update the current position. currentParsePosition = parseResult.End; } return(inlines); }
private Run InternalRenderTextRun(TextRunInline element, IRenderContext context) { if (!(context is InlineRenderContext localContext)) { throw new RenderContextIncorrectException(); } var inlineCollection = localContext.InlineCollection; // Create the text run Run textRun = new Run { Text = CollapseWhitespace(context, element.Text) }; // Add it inlineCollection.Add(textRun); return(textRun); }
/// <summary> /// Attempts to parse a markdown link e.g. "[](http://www.reddit.com)". /// </summary> /// <param name="markdown"> The markdown text. </param> /// <param name="start"> The location to start parsing. </param> /// <param name="maxEnd"> The location to stop parsing. </param> /// <returns> A parsed markdown link, or <c>null</c> if this is not a markdown link. </returns> internal static InlineParseResult Parse(string markdown, int start, int maxEnd) { // Expect a '[' character. if (start == maxEnd || markdown[start] != '[') { return(null); } // Find the ']' character, keeping in mind that [test [0-9]](http://www.test.com) is allowed. int linkTextOpen = start + 1; int pos = linkTextOpen; int linkTextClose; int openSquareBracketCount = 0; while (true) { linkTextClose = markdown.IndexOfAny(new char[] { '[', ']' }, pos, maxEnd - pos); if (linkTextClose == -1) { return(null); } if (markdown[linkTextClose] == '[') { openSquareBracketCount++; } else if (openSquareBracketCount > 0) { openSquareBracketCount--; } else { break; } pos = linkTextClose + 1; } // Skip whitespace. pos = linkTextClose + 1; while (pos < maxEnd && ParseHelpers.IsMarkdownWhiteSpace(markdown[pos])) { pos++; } if (pos == maxEnd) { return(null); } // Expect the '(' character or the '[' character. int linkOpen = pos; if (markdown[pos] == '(') { // Skip whitespace. linkOpen++; while (linkOpen < maxEnd && ParseHelpers.IsMarkdownWhiteSpace(markdown[linkOpen])) { linkOpen++; } // Find the ')' character. pos = linkOpen; int linkClose = -1; var openParenthesis = 0; while (pos < maxEnd) { if (markdown[pos] == ')') { if (openParenthesis == 0) { linkClose = pos; break; } else { openParenthesis--; } } if (markdown[pos] == '(') { openParenthesis++; } pos++; } if (pos >= maxEnd) { return(null); } int end = linkClose + 1; // Skip whitespace backwards. while (linkClose > linkOpen && ParseHelpers.IsMarkdownWhiteSpace(markdown[linkClose - 1])) { linkClose--; } // If there is no text whatsoever, then this is not a valid link. if (linkOpen == linkClose) { return(null); } // Check if there is tooltip text. string url; string tooltip = null; bool lastUrlCharIsDoubleQuote = markdown[linkClose - 1] == '"'; int tooltipStart = Common.IndexOf(markdown, " \"", linkOpen, linkClose - 1); if (tooltipStart == linkOpen) { return(null); } if (lastUrlCharIsDoubleQuote && tooltipStart != -1) { // Extract the URL (resolving any escape sequences). url = TextRunInline.ResolveEscapeSequences(markdown, linkOpen, tooltipStart).TrimEnd(' ', '\t', '\r', '\n'); tooltip = markdown.Substring(tooltipStart + 2, (linkClose - 1) - (tooltipStart + 2)); } else { // Extract the URL (resolving any escape sequences). url = TextRunInline.ResolveEscapeSequences(markdown, linkOpen, linkClose); } // Check the URL is okay. if (!url.IsEmail()) { if (!Common.IsUrlValid(url)) { return(null); } } else { tooltip = url = $"mailto:{url}"; } // We found a regular stand-alone link. var result = new MarkdownLinkInline { Inlines = Common.ParseInlineChildren(markdown, linkTextOpen, linkTextClose, ignoreLinks: true), Url = url.Replace(" ", "%20", StringComparison.Ordinal), Tooltip = tooltip }; return(new InlineParseResult(result, start, end)); } else if (markdown[pos] == '[') { // Find the ']' character. int linkClose = Common.IndexOf(markdown, ']', pos + 1, maxEnd); if (linkClose == -1) { return(null); } // We found a reference-style link. var result = new MarkdownLinkInline { Inlines = Common.ParseInlineChildren(markdown, linkTextOpen, linkTextClose, ignoreLinks: true), ReferenceId = markdown.Substring(linkOpen + 1, linkClose - (linkOpen + 1)) }; if (string.IsNullOrEmpty(result.ReferenceId)) { result.ReferenceId = markdown.Substring(linkTextOpen, linkTextClose - linkTextOpen); } return(new InlineParseResult(result, start, linkClose + 1)); } return(null); }
/// <summary> /// Renders a text run element. /// </summary> /// <param name="element"> The parsed inline element to render. </param> /// <param name="context"> Persistent state. </param> protected override void RenderTextRun(TextRunInline element, IRenderContext context) { InternalRenderTextRun(element, context); }
/// <summary> /// Attempts to parse an image e.g. "![Toolkit logo](https://raw.githubusercontent.com/windows-toolkit/WindowsCommunityToolkit/master/Microsoft.Toolkit.Uwp.SampleApp/Assets/ToolkitLogo.png)". /// </summary> /// <param name="markdown"> The markdown text. </param> /// <param name="start"> The location to start parsing. </param> /// <param name="end"> The location to stop parsing. </param> /// <returns> A parsed markdown image, or <c>null</c> if this is not a markdown image. </returns> internal static InlineParseResult Parse(string markdown, int start, int end) { // Expect a '!' character. if (start >= end || markdown[start] != '!') { return(null); } int pos = start + 1; // Then a '[' character if (pos >= end || markdown[pos] != '[') { return(null); } pos++; // Find the ']' character while (pos < end) { if (markdown[pos] == ']') { break; } pos++; } if (pos == end) { return(null); } // Extract the alt. string tooltip = markdown.Substring(start + 2, pos - (start + 2)); // Expect the '(' character. pos++; string reference = string.Empty; string url = string.Empty; int imageWidth = 0; int imageHeight = 0; if (pos < end && markdown[pos] == '[') { int refstart = pos; // Find the reference ']' character while (pos < end) { if (markdown[pos] == ']') { break; } pos++; } reference = markdown.Substring(refstart + 1, pos - refstart - 1); } else if (pos < end && markdown[pos] == '(') { while (pos < end && ParseHelpers.IsMarkdownWhiteSpace(markdown[pos])) { pos++; } // Extract the URL. int urlStart = pos; while (pos < end && markdown[pos] != ')') { pos++; } var imageDimensionsPos = markdown.IndexOf(" =", urlStart, pos - urlStart, StringComparison.Ordinal); url = imageDimensionsPos > 0 ? TextRunInline.ResolveEscapeSequences(markdown, urlStart + 1, imageDimensionsPos) : TextRunInline.ResolveEscapeSequences(markdown, urlStart + 1, pos); if (imageDimensionsPos > 0) { // trying to find 'x' which separates image width and height var dimensionsSepatorPos = markdown.IndexOf("x", imageDimensionsPos + 2, pos - imageDimensionsPos - 1, StringComparison.Ordinal); // didn't find separator, trying to parse value as imageWidth if (dimensionsSepatorPos == -1) { var imageWidthStr = markdown.Substring(imageDimensionsPos + 2, pos - imageDimensionsPos - 2); int.TryParse(imageWidthStr, out imageWidth); } else { var dimensions = markdown.Substring(imageDimensionsPos + 2, pos - imageDimensionsPos - 2).Split('x'); // got width and height if (dimensions.Length == 2) { int.TryParse(dimensions[0], out imageWidth); int.TryParse(dimensions[1], out imageHeight); } } } } if (pos == end) { return(null); } // We found something! var result = new ImageInline { Tooltip = tooltip, RenderUrl = url, ReferenceId = reference, Url = url, Text = markdown.Substring(start, pos + 1 - start), ImageWidth = imageWidth, ImageHeight = imageHeight }; return(new InlineParseResult(result, start, pos + 1)); }
/// <summary> /// Finds the next inline element by matching trip chars and verifying the match. /// </summary> /// <param name="markdown"> The markdown text to parse. </param> /// <param name="start"> The position to start parsing. </param> /// <param name="end"> The position to stop parsing. </param> /// <param name="ignoreLinks"> Indicates whether to parse links. </param> /// <returns>Returns the next element</returns> private static InlineParseResult FindNextInlineElement(string markdown, int start, int end, bool ignoreLinks) { // Search for the next inline sequence. for (int pos = start; pos < end; pos++) { // IndexOfAny should be the fastest way to skip characters we don't care about. pos = markdown.IndexOfAny(_tripCharacters, pos, end - pos); if (pos < 0) { break; } // Find the trigger(s) that matched. char currentChar = markdown[pos]; foreach (InlineTripCharHelper currentTripChar in _triggerList) { // Check if our current char matches the suffix char. if (currentChar == currentTripChar.FirstChar) { // Don't match if the previous character was a backslash. if (pos > start && markdown[pos - 1] == '\\') { continue; } // If we are here we have a possible match. Call into the inline class to verify. InlineParseResult parseResult = null; switch (currentTripChar.Method) { case InlineParseMethod.BoldItalic: parseResult = BoldItalicTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.Comment: parseResult = CommentInline.Parse(markdown, pos, end); break; case InlineParseMethod.LinkReference: parseResult = LinkAnchorInline.Parse(markdown, pos, end); break; case InlineParseMethod.Bold: parseResult = BoldTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.Italic: parseResult = ItalicTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.MarkdownLink: if (!ignoreLinks) { parseResult = MarkdownLinkInline.Parse(markdown, pos, end); } break; case InlineParseMethod.AngleBracketLink: if (!ignoreLinks) { parseResult = HyperlinkInline.ParseAngleBracketLink(markdown, pos, end); } break; case InlineParseMethod.Url: if (!ignoreLinks) { parseResult = HyperlinkInline.ParseUrl(markdown, pos, end); } break; case InlineParseMethod.RedditLink: if (!ignoreLinks) { parseResult = HyperlinkInline.ParseRedditLink(markdown, pos, end); } break; case InlineParseMethod.PartialLink: if (!ignoreLinks) { parseResult = HyperlinkInline.ParsePartialLink(markdown, pos, end); } break; case InlineParseMethod.Email: if (!ignoreLinks) { parseResult = HyperlinkInline.ParseEmailAddress(markdown, start, pos, end); } break; case InlineParseMethod.Strikethrough: parseResult = StrikethroughTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.Superscript: parseResult = SuperscriptTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.Subscript: parseResult = SubscriptTextInline.Parse(markdown, pos, end); break; case InlineParseMethod.Code: parseResult = CodeInline.Parse(markdown, pos, end); break; case InlineParseMethod.Image: parseResult = ImageInline.Parse(markdown, pos, end); break; case InlineParseMethod.Emoji: parseResult = EmojiInline.Parse(markdown, pos, end); break; } if (parseResult != null) { return(parseResult); } } } } // If we didn't find any elements we have a normal text block. // Let us consume the entire range. return(new InlineParseResult(TextRunInline.Parse(markdown, start, end), start, end)); }