Ejemplo n.º 1
0
 internal void Update(MarkdownObject objectToParse)
 {
     Object = objectToParse;
     Source = Object is null
         ? StringSlice.Empty
         : new StringSlice(ParsingResult.Source, Object.Span.Start, Object.Span.End);
 }
Ejemplo n.º 2
0
 public string RenderHtml(MarkdownObject obj)
 {
     (_htmlRenderer.Writer as StringWriter).GetStringBuilder().Clear();
     _htmlRenderer.Render(obj);
     _htmlRenderer.Writer.Flush();
     return(_htmlRenderer.Writer.ToString());
 }
 public override object Render(MarkdownObject markdownObject)
 {
     Root   = new FlowDocument();
     Blocks = Root.Blocks;
     Write(markdownObject);
     return(null);
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Looks into the markdown element for a marker, and adds it as bookmark to the OpenXML document.
 /// The presumtion here is that the topmost element on the <see cref="OpenXmlCompositeElement"/> stack is a <see cref="Paragraph"/>.
 /// </summary>
 /// <param name="obj">The object.</param>
 public void AddBookmarkIfNeccessary(MarkdownObject obj)
 {
     if (Peek() is Paragraph paragraph)
     {
         AddBookmarkIfNeccessary(obj, paragraph);
     }
 }
        public string ToHtml(string markdown)
        {
            if (string.IsNullOrEmpty(markdown))
            {
                return("");
            }

            var pipeline = new MarkdownPipelineBuilder();
            MarkdownPipeline markdownPipeline = pipeline.UseAdvancedExtensions().Build();

            MarkdownObject doc    = Markdown.Parse(markdown, markdownPipeline);
            var            walker = new MarkdigImageAndLinkWalker(
                (e) =>
            {
                ImageParsed?.Invoke(e);
            },
                (e) =>
            {
                LinkParsed?.Invoke(e);
            });

            walker.WalkAndBindParseEvents(doc);

            var builder    = new StringBuilder();
            var textwriter = new StringWriter(builder);

            var renderer = new HtmlRenderer(textwriter);

            renderer.Render(doc);

            return(builder.ToString());
        }
Ejemplo n.º 6
0
 private static void TransformUrl(MarkdownObject markdownObject, string currentDir)
 {
     foreach (MarkdownObject child in markdownObject.Descendants())
     {
         // LinkInline can be both an image or a <a href="...">
         LinkInline link = child as LinkInline;
         if (link != null)
         {
             string url = link.Url;
             if (!urlRegex.IsMatch(url))
             {
                 try
                 {
                     if (!Path.IsPathRooted(url) && currentDir != null)
                     {
                         url = Path.GetFullPath(Path.Combine(currentDir, url)).Replace('\\', '/');
                     }
                     url      = "file:///" + url;
                     link.Url = url;
                 }
                 catch (Exception)
                 {
                     return;
                 }
             }
         }
         TransformUrl(child, currentDir);
     }
 }
Ejemplo n.º 7
0
        internal static string ToMarkdownString(this MarkdownObject md, NormalizeOptions?options = null)
        {
            var writer = new StringWriter();

            WriteTo(md, writer, options);
            return(writer.ToString());
        }
        private void RenderWithIndent(VT100Renderer renderer, MarkdownObject block, char listBullet, int indentLevel)
        {
            // Indent left by 2 for each level on list.
            string indent = Padding(indentLevel * 2);

            if (block is ParagraphBlock paragraphBlock)
            {
                renderer.Write(indent).Write(listBullet).Write(" ").Write(paragraphBlock.Inline);
            }
            else
            {
                // If there is a sublist, the block is a ListBlock instead of ParagraphBlock.
                if (block is ListBlock subList)
                {
                    foreach (var subListItem in subList)
                    {
                        if (subListItem is ListItemBlock subListItemBlock)
                        {
                            foreach (var line in subListItemBlock)
                            {
                                // Increment indent level for sub list.
                                RenderWithIndent(renderer, line, listBullet, indentLevel + 1);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
 private void TryAddTarget(string url, MarkdownObject obj)
 {
     if (url != null && Uri.TryCreate(url, UriKind.Absolute, out _))
     {
         obj.GetAttributes().AddPropertyIfNotExist("target", "_blank");
     }
 }
Ejemplo n.º 10
0
        public BlazorRenderer WriteAttributes(MarkdownObject markdownObject, Func <string, string> classFilter = null)
        {
            var attributes = markdownObject.TryGetAttributes();

            if (attributes != null)
            {
                if (attributes.Id != null)
                {
                    AddAttribute("id", attributes.Id);
                }

                if (attributes.Classes != null && attributes.Classes.Count > 0)
                {
                    var @class = string.Join(' ', attributes.Classes.Select(s => classFilter != null ? classFilter(s) : s));
                    AddAttribute("class", @class);
                }

                if (attributes.Properties != null && attributes.Properties.Count > 0)
                {
                    foreach (var property in attributes.Properties)
                    {
                        AddAttribute(property.Key, property.Value);
                    }
                }
            }

            return(this);
        }
Ejemplo n.º 11
0
        private static string GetType(MarkdownObject mdo)
        {
            var type = mdo.GetType().Name;

            return(mdo is HeadingBlock heading
                    ? type + " " + heading.Level
                    : type);
        }
Ejemplo n.º 12
0
        private static LocationSpan GetLocationSpan(MarkdownObject mdo, CharacterPositionFinder finder)
        {
            var span  = mdo.Span;
            var start = finder.GetLineInfo(span.Start);
            var end   = finder.GetLineInfo(span.End);

            return(new LocationSpan(start, end));
        }
Ejemplo n.º 13
0
        public void Write(RendererBase renderer, MarkdownObject astNode)
        {
            var extensionHtmlRenderer = renderer as ExtensionHtmlRenderer;
            var extensionBlock        = astNode as IExtensionBlock;
            var model = (TModel)extensionHtmlRenderer.GetBlockModel(extensionBlock);

            Render(extensionHtmlRenderer, model, extensionHtmlRenderer.FormatState);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Writes the attached <see cref="HtmlAttributes"/> on the specified <see cref="MarkdownObject"/>.
 /// </summary>
 /// <param name="markdownObject">The object.</param>
 /// <returns></returns>
 public HtmlRenderer WriteAttributes(MarkdownObject markdownObject)
 {
     if (markdownObject == null)
     {
         ThrowHelper.ArgumentNullException_markdownObject();
     }
     return(WriteAttributes(markdownObject.TryGetAttributes()));
 }
Ejemplo n.º 15
0
 private static string GetLink(string path, MarkdownObject origin)
 {
     if (InclusionContext.IsInclude && RelativePath.IsRelativePath(path) && PathUtility.IsRelativePath(path) && !RelativePath.IsPathFromWorkingFolder(path) && !path.StartsWith("#", StringComparison.Ordinal))
     {
         return(((RelativePath)InclusionContext.File + (RelativePath)path).GetPathFromWorkingFolder());
     }
     return(path);
 }
Ejemplo n.º 16
0
        public bool Render(HtmlRenderer renderer, MarkdownObject markdownObject, Action <string> logWarning)
        {
            renderer.WriteLine("<div class=\"embeddedvideo\">");
            renderer.Write($"<iframe").WriteAttributes(markdownObject).WriteLine(">");
            renderer.WriteLine("</div>");

            return(true);
        }
Ejemplo n.º 17
0
 private static void AddStyleClass(MarkdownObject node, string style)
 {
     if (string.IsNullOrEmpty(style))
     {
         return;
     }
     node.GetAttributes().AddClass(style);
 }
Ejemplo n.º 18
0
 public override RenderFragment Render(MarkdownObject markdownObject)
 {
     return(builder =>
     {
         Builder = builder;
         Write(markdownObject);
     });
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Writes the attached <see cref="HtmlAttributes"/> on the specified <see cref="MarkdownObject"/>.
 /// </summary>
 /// <param name="obj">The object.</param>
 /// <returns></returns>
 public HtmlRenderer WriteAttributes(MarkdownObject obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException(nameof(obj));
     }
     return(WriteAttributes(obj.TryGetAttributes()));
 }
        private bool PageMatchesFilter(MarkdownObject document)
        {
            if (!string.IsNullOrEmpty(_options.Filter))
            {
                Log($"Filter provided: {_options.Filter}", LogLevel.Information, 2);

                var filters     = _options.Filter.Split(",");
                var frontmatter = document.Descendants <YamlFrontMatterBlock>().FirstOrDefault();

                if (frontmatter == null)
                {
                    Log($"Page has no frontmatter tags", LogLevel.Information, 2);
                    return(false);
                }

                var frontmatterTags = new List <string>();
                var lastTag         = "";
                foreach (StringLine frontmatterline in frontmatter.Lines)
                {
                    var splice = frontmatterline.Slice.ToString();
                    var split  = splice.Split(":");

                    //title:test or <empty>:test2 or tags:<empty>
                    if (split.Length == 2)
                    {
                        //title:
                        if (string.IsNullOrEmpty(split[1]))
                        {
                            lastTag = split[0].Trim();
                        }
                        //title:test
                        else if (!string.IsNullOrEmpty(split[0]))
                        {
                            frontmatterTags.Add($"{split[0].Trim()}:{split[1].Trim()}");
                        }
                        //:test2
                        else
                        {
                            frontmatterTags.Add($"{lastTag}:{split[1].Trim()}");
                        }
                    }
                    else if (split.Length == 1 && !string.IsNullOrEmpty(split[0]))
                    {
                        frontmatterTags.Add($"{lastTag}:{split[0].Trim().Substring(2)}");
                    }
                }

                foreach (var filter in filters)
                {
                    if (frontmatterTags.Contains(filter, StringComparer.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            return(true);
        }
Ejemplo n.º 21
0
        public override object Render(MarkdownObject markdownObject)
        {
            OpenElement("div");
            AddAttribute("class", "markdown-body");
            Write(markdownObject);
            CloseElement();

            return(this._builder);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Returns object location in source
 /// </summary>
 public static TextSpan ToSourceTextSpan(this MarkdownObject obj)
 {
     return(new TextSpan
     {
         iStartLine = obj.Line,
         iEndLine = obj.Line,
         iStartIndex = obj.Column,
         iEndIndex = obj.Column + obj.Span.Length
     });
 }
Ejemplo n.º 23
0
 public override object Render(MarkdownObject markdownObject)
 {
     if (markdownObject is MarkdownDocument document)
     {
         document.SetLinkReferenceDefinition("!Note", new LinkReferenceDefinition("!Note", "", ""));
         Write(markdownObject);
         XmlWriter.Close();
     }
     return(null);
 }
        private void MoveCaretToBlock(MarkdownObject mdobj)
        {
            var point = new SnapshotPoint(_view.TextBuffer.CurrentSnapshot, mdobj.Span.Start);

            _view.Caret.MoveTo(point);

            var span = new SnapshotSpan(point, 0);

            _view.ViewScroller.EnsureSpanVisible(span);
        }
Ejemplo n.º 25
0
        private static string ConvertToHtml(MarkdownObject markdownObject)
        {
            var builder    = new StringBuilder();
            var textwriter = new StringWriter(builder);

            var renderer = new HtmlRenderer(textwriter);

            renderer.Render(markdownObject);

            return(builder.ToString());
        }
Ejemplo n.º 26
0
        public virtual void Write(RendererBase renderer, MarkdownObject obj)
        {
            var htmlRenderer = (TRenderer)renderer;
            var typedObj     = (TObject)obj;

            if (_tryWriters is not null && TryWrite(htmlRenderer, typedObj))
            {
                return;
            }

            Write(htmlRenderer, typedObj);
        }
        public void CorrectLinksAndImages(MarkdownObject document, FileInfo file, MarkdownFile mf)
        {
            Log("Correcting Links and Images");
            // walk the document node tree and replace relative image links
            // and relative links to markdown pages
            foreach (var link in document.Descendants().OfType <LinkInline>())
            {
                if (!link.Url.StartsWith("http"))
                {
                    string absPath = null;

                    if (link.Url.StartsWith("/"))
                    {
                        absPath = Path.GetFullPath(_path + link.Url);
                    }
                    else
                    {
                        absPath = Path.GetFullPath(file.Directory.FullName + "/" + link.Url);
                    }
                    //the file is a markdown file, create a link to it
                    var isMarkdown = false;
                    var fileInfo   = new FileInfo(absPath);
                    if (fileInfo.Exists && fileInfo.Extension.Equals(".md", StringComparison.InvariantCultureIgnoreCase))
                    {
                        isMarkdown = true;
                    }
                    else if (fileInfo.Exists)
                    {
                        link.Url = $"file:///{absPath}";
                    }

                    fileInfo = new FileInfo($"{absPath}.md");
                    if (fileInfo.Exists && fileInfo.Extension.Equals(".md", StringComparison.InvariantCultureIgnoreCase))
                    {
                        isMarkdown = true;
                    }

                    //only markdown files get a pdf internal link
                    if (isMarkdown)
                    {
                        var relPath = mf.RelativePath + "\\" + link.Url;
                        relPath = relPath.Replace("/", "\\");
                        relPath = relPath.Replace("\\", "");
                        relPath = relPath.Replace(".md", "");
                        relPath = relPath.ToLower();
                        Log($"\tMarkdown link: {relPath}");
                        link.Url = $"#{relPath}";
                    }
                }

                CorrectLinksAndImages(link, file, mf);
            }
        }
Ejemplo n.º 28
0
        private static void UpdateLinks(MarkdownObject markdownObject)
        {
            if (markdownObject == null)
            {
                return;
            }

            if (markdownObject is ContainerBlock containerBlock)
            {
                if (markdownObject is TripleColonBlock tripleColonBlock && tripleColonBlock.Extension.Name == "image")
                {
                    var htmlAttributes = tripleColonBlock.GetAttributes();

                    if (htmlAttributes.Properties.Any(p => p.Key == "src"))
                    {
                        var srcHtmlAttribute = htmlAttributes.Properties.First(p => p.Key == "src");
                        var src = srcHtmlAttribute.Value;

                        htmlAttributes.Properties.Remove(new KeyValuePair <string, string>("src", src));
                        htmlAttributes.AddProperty("src", GetLink(src, InclusionContext.File, InclusionContext.RootFile, tripleColonBlock));
                        //block.SetData(typeof(HtmlAttributes), htmlAttributes);
                    }
                }

                foreach (var subBlock in containerBlock)
                {
                    UpdateLinks(subBlock);
                }
            }
            else if (markdownObject is LeafBlock leafBlock)
            {
                if (leafBlock.Inline != null)
                {
                    foreach (var subInline in leafBlock.Inline)
                    {
                        UpdateLinks(subInline);
                    }
                }
            }
            else if (markdownObject is ContainerInline containerInline)
            {
                foreach (var subInline in containerInline)
                {
                    UpdateLinks(subInline);
                }

                if (markdownObject is LinkInline linkInline && !linkInline.IsAutoLink)
                {
                    linkInline.GetDynamicUrl = () => GetLink(linkInline.Url, InclusionContext.File, InclusionContext.RootFile, linkInline);
                }
            }
        }
Ejemplo n.º 29
0
        public bool Render(HtmlRenderer renderer, MarkdownObject markdownObject, Action <string> logWarning)
        {
            var block = (TripleColonBlock)markdownObject;

            block.RenderProperties.TryGetValue("submitText", out var buttonText);

            renderer.Write("<form").WriteAttributes(block).WriteLine(">");
            renderer.WriteLine("<div></div>");
            renderer.WriteLine($"<button class=\"button is-primary\" disabled=\"disabled\" type=\"submit\">{buttonText}</button>");
            renderer.WriteLine("</form>");

            return(true);
        }
Ejemplo n.º 30
0
        private static string GetName(MarkdownObject mdo, TextProvider textProvider)
        {
            switch (mdo)
            {
            case HeadingBlock heading:
                var text = textProvider.GetText(heading);
                var name = text.Trim(heading.HeaderChar).Trim();
                return(name);

            default:
                return(string.Empty);    // TODO: RKN mdo.GetType().Name;
            }
        }