Exemplo n.º 1
0
        public void LineNumberTest_CodeSnippet()
        {
            //arange
            var content = @"// <tag>
line1
// </tag>";

            if (!Directory.Exists("LineNumber"))
            {
                Directory.CreateDirectory("LineNumber");
            }

            File.WriteAllText("LineNumber/Program.cs", content.Replace("\r\n", "\n"));

            // act
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = ".",
                Extensions = new Dictionary <string, object>
                {
                    { LineNumberExtension.EnableSourceInfo, true }
                }
            };
            var service = new MarkdigMarkdownService(parameter);
            var marked  = service.Markup(@"[!code[tag-test](LineNumber/Program.cs#Tag)]", "Topic.md");

            // assert
            var expected = @"<pre><code sourceFile=""Topic.md"" sourceStartLineNumber=""1"" sourceEndLineNumber=""1"" name=""tag-test"">line1
</code></pre>";

            Assert.Equal(expected.Replace("\r\n", "\n"), marked.Html);
        }
Exemplo n.º 2
0
        public ProcessContext(IHostService hs, FileModel fm, IDocumentBuildContext bc = null)
        {
            _model = fm;
            OriginalFileAndType = fm.OriginalFileAndType;
            FileAndType         = fm.FileAndType;
            Uids              = new List <UidDefinition>();
            UidLinkSources    = new Dictionary <string, List <LinkSourceInfo> >();
            FileLinkSources   = new Dictionary <string, List <LinkSourceInfo> >();
            Dependency        = new HashSet <string>();
            XRefSpecs         = new List <XRefSpec>();
            ExternalXRefSpecs = new List <XRefSpec>();
            if (((IDictionary <string, object>)(fm.Properties)).TryGetValue("PathProperties", out var properties))
            {
                var pathProperties = properties as Dictionary <string, Dictionary <string, object> >;
                PathProperties = pathProperties ?? throw new ArgumentException($"PathProperties is expecting a dictionary however is a {pathProperties.GetType()}");
            }
            else
            {
                fm.Properties.PathProperties = PathProperties = new Dictionary <string, Dictionary <string, object> >();
            }

            Host         = hs;
            BuildContext = bc;
            if (((IDictionary <string, object>)(fm.Properties)).TryGetValue("MarkdigMarkdownService", out var service))
            {
                MarkdigMarkdownService = (MarkdigMarkdownService)service;
            }
        }
        public SchemaDrivenDocumentProcessor(
            DocumentSchema schema,
            ICompositionContainer container,
            MarkdigMarkdownService markdigMarkdownService,
            FolderRedirectionManager folderRedirectionManager)
        {
            if (string.IsNullOrWhiteSpace(schema.Title))
            {
                throw new ArgumentException("Title for schema must not be empty");
            }

            _schemaName               = schema.Title;
            _schema                   = schema;
            SchemaValidator           = schema.Validator;
            _allowOverwrite           = schema.AllowOverwrite;
            _serializerPool           = new ResourcePoolManager <JsonSerializer>(GetSerializer, 0x10);
            _markdigMarkdownService   = markdigMarkdownService ?? throw new ArgumentNullException(nameof(MarkdigMarkdownService));
            _folderRedirectionManager = folderRedirectionManager;
            if (container != null)
            {
                var commonSteps         = container.GetExports <IDocumentBuildStep>(nameof(SchemaDrivenDocumentProcessor));
                var schemaSpecificSteps = container.GetExports <IDocumentBuildStep>($"{nameof(SchemaDrivenDocumentProcessor)}.{_schemaName}");
                BuildSteps = commonSteps.Union(schemaSpecificSteps).ToList();
            }
        }
Exemplo n.º 4
0
        public void CodeSnippetNotFound()
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath = ".",
                Tokens   = new Dictionary <string, string>
                {
                    { "codeIncludeNotFound", "你要查找的示例似乎已移动! 不要担心,我们正在努力解决此问题。" },
                    { "warning", "<h5>警告</h5>" }
                }.ToImmutableDictionary(),
                Extensions = new Dictionary <string, object>
                {
                    { "EnableSourceInfo", false }
                }
            };
            var service = new MarkdigMarkdownService(parameter);
            var marked  = service.Markup(@"[!code-csharp[name](Program1.cs)]", "Topic.md");
            // assert
            var expected = @"<div class=""WARNING"">
<h5>警告</h5>
<p>你要查找的示例似乎已移动! 不要担心,我们正在努力解决此问题。</p>
</div>";

            Assert.Equal(expected.Replace("\r\n", "\n"), marked.Html.Replace("\r\n", "\n"));
        }
Exemplo n.º 5
0
        public static MarkupResult Markup(string content, string filePath = null)
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath = "."
            };
            var service = new MarkdigMarkdownService(parameter);

            return(service.Markup(content, filePath ?? string.Empty));
        }
Exemplo n.º 6
0
        private static MarkupResult SimpleMarkup(string source)
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath = "."
            };
            var service = new MarkdigMarkdownService(parameter);

            return(service.Markup(source, "Topic.md"));
        }
Exemplo n.º 7
0
        static MarkdigForDocfx()
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = ".",
                Extensions = new Dictionary <string, object>
                {
                    { "EnableSourceInfo", false }
                }
            };

            _service = new MarkdigMarkdownService(parameter);
        }
Exemplo n.º 8
0
        public static MarkupResult MarkupWithoutSourceInfo(string content, string filePath = null)
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = ".",
                Extensions = new Dictionary <string, object>
                {
                    { LineNumberExtension.EnableSourceInfo, false }
                }
            };
            var service = new MarkdigMarkdownService(parameter);

            return(service.Markup(content, filePath ?? string.Empty));
        }
Exemplo n.º 9
0
        private static MarkupResult SimpleMarkup(string source)
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = ".",
                Extensions = new Dictionary <string, object>
                {
                    { LineNumberExtension.EnableSourceInfo, true }
                }
            };
            var service = new MarkdigMarkdownService(parameter);

            return(service.Markup(source, "Topic.md"));
        }
Exemplo n.º 10
0
        private static string Markup(string markdown, string filePath, string basePath = ".")
        {
            EnvironmentContext.FileAbstractLayerImpl = FileAbstractLayerBuilder.Default.ReadFromRealFileSystem(basePath).WriteToRealFileSystem(basePath).Create();
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = basePath,
                Extensions = new Dictionary <string, object>
                {
                    { "EnableSourceInfo", true }
                }
            };
            var markupService = new MarkdigMarkdownService(parameter);

            return(markupService.Markup(markdown, filePath ?? "topic.md").Html);
        }
Exemplo n.º 11
0
        public void TestDfmNote_NoteWithLocalization()
        {
            var source    = @"# Note not in one line
> [!NOTE]
> hello
> world
> [!WARNING]
> Hello world
this is also warning";
            var expected  = @"<h1 id=""note-not-in-one-line"">Note not in one line</h1>
<div class=""NOTE"">
<h5>注意</h5>
<p>hello
world</p>
</div>
<div class=""WARNING"">
<h5>警告</h5>
<p>Hello world
this is also warning</p>
</div>
";
            var parameter = new MarkdownServiceParameters
            {
                BasePath = ".",
                Tokens   = new Dictionary <string, string>
                {
                    { "note", "<h5>注意</h5>" },
                    { "warning", "<h5>警告</h5>" }
                }.ToImmutableDictionary(),
                Extensions = new Dictionary <string, object>
                {
                    { LineNumberExtension.EnableSourceInfo, false }
                }
            };
            var service = new MarkdigMarkdownService(parameter);
            var marked  = service.Markup(source, "Topic.md");

            Assert.Equal(expected.Replace("\r\n", "\n"), marked.Html);
        }
Exemplo n.º 12
0
        public void TestSectionBlockLevel(string source)
        {
            var parameter = new MarkdownServiceParameters
            {
                BasePath = "."
            };
            var service = new MarkdigMarkdownService(parameter);
            var content = service.Markup(source, "Topic.md");

            // assert
            XmlDocument xdoc = new XmlDocument();

            xdoc.LoadXml(content.Html);
            var tabbedCodeNode = xdoc.SelectSingleNode("//div[@class='tabbedCodeSnippets' and @data-resources='OutlookServices.Calendar']");

            Assert.True(tabbedCodeNode != null);
            var csNode = tabbedCodeNode.SelectSingleNode("./pre/code[@class='lang-cs-i']");

            Assert.True(csNode != null);
            var jsNode = tabbedCodeNode.SelectSingleNode("./pre/code[@class='lang-javascript-i']");

            Assert.True(jsNode != null);
        }
        public MarkdigMarkdownRenderer(Stack <IMarkdownToken> processedBlockTokens, string basePath, bool useLegacyMode = true, MigrationRule rule = MigrationRule.All)
        {
            var option = DocfxFlavoredMarked.CreateDefaultOptions();

            option.LegacyMode = useLegacyMode;
            var builder = new DfmEngineBuilder(option);
            var render  = new DfmRenderer();

            _dfmEngine     = builder.CreateDfmEngine(render);
            _dfmHtmlRender = new DfmHtmlRender(useLegacyMode);
            _rule          = rule;

            var parameter = new MarkdownServiceParameters
            {
                BasePath   = basePath,
                Extensions = new Dictionary <string, object>
                {
                    { "EnableSourceInfo", false }
                }
            };

            _service = new MarkdigMarkdownService(parameter);
            _processedBlockTokens = processedBlockTokens;
        }
Exemplo n.º 14
0
        public void TestFallback_InclusionWithCodeFences()
        {
            // -root_folder (this is also docset folder)
            //  |- root.md
            //  |- a_folder
            //     |- a.md
            //  |- code_folder
            //     |- sample1.cs
            // -fallback_folder
            //  |- a_folder
            //     |- code_in_a.cs
            //  |- code_folder
            //     |- sample2.cs

            // 1. Prepare data
            var root = @"markdown root.md main content start.

mardown a content in root.md content start

[!include[a](a_folder/a.md ""This is a.md"")]

mardown a content in root.md content end

sample 1 code in root.md content start

[!CODE-cs[this is sample 1 code](code_folder/sample1.cs)]

sample 1 code in root.md content end

sample 2 code in root.md content start

[!CODE-cs[this is sample 2 code](code_folder/sample2.cs)]

sample 2 code in root.md content end

markdown root.md main content end.";

            var a = @"markdown a.md main content start.

code_in_a code in a.md content start

[!CODE-cs[this is code_in_a code](code_in_a.cs)]

code_in_a in a.md content end

markdown a.md a.md content end.";

            var code_in_a = @"namespace code_in_a{}";

            var sample1 = @"namespace sample1{}";

            var sample2 = @"namespace sample2{}";

            var uniqueFolderName = Path.GetRandomFileName();

            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder/root.md", root);
            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder/a_folder/a.md", a);
            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder/code_folder/sample1.cs", sample1);
            TestUtility.WriteToFile($"{uniqueFolderName}/fallback_folder/a_folder/code_in_a.cs", code_in_a);
            TestUtility.WriteToFile($"{uniqueFolderName}/fallback_folder/code_folder/sample2.cs", sample2);

            var fallbackFolders = new List <string> {
                { Path.Combine(Directory.GetCurrentDirectory(), $"{uniqueFolderName}/fallback_folder") }
            };

            // Verify root.md markup result
            var parameter = new MarkdownServiceParameters
            {
                BasePath = "."
            };
            var service = new MarkdigMarkdownService(parameter);
            //var rootMarked = service.Markup(Path.Combine(Directory.GetCurrentDirectory(), $"{uniqueFolderName}/root_folder"), root, fallbackFolders, "root.md");
            var rootMarked     = service.Markup("place", "holder");
            var rootDependency = rootMarked.Dependency;

            Assert.Equal(@"<p>markdown root.md main content start.</p>
<p>mardown a content in root.md content start</p>
<p>markdown a.md main content start.</p>
<p>code_in_a code in a.md content start</p>
<pre><code class=""lang-cs"" name=""this is code_in_a code"">namespace code_in_a{}
</code></pre><p>code_in_a in a.md content end</p>
<p>markdown a.md a.md content end.</p>
<p>mardown a content in root.md content end</p>
<p>sample 1 code in root.md content start</p>
<pre><code class=""lang-cs"" name=""this is sample 1 code"">namespace sample1{}
</code></pre><p>sample 1 code in root.md content end</p>
<p>sample 2 code in root.md content start</p>
<pre><code class=""lang-cs"" name=""this is sample 2 code"">namespace sample2{}
</code></pre><p>sample 2 code in root.md content end</p>
<p>markdown root.md main content end.</p>
".Replace("\r\n", "\n"), rootMarked.Html);
            Assert.Equal(
                new[] { "../fallback_folder/a_folder/code_in_a.cs", "../fallback_folder/code_folder/sample2.cs", "a_folder/a.md", "a_folder/code_in_a.cs", "code_folder/sample1.cs", "code_folder/sample2.cs" },
                rootDependency.OrderBy(x => x).ToArray());

            // Verify a.md markup result
            //var aMarked = service.Markup(Path.Combine(Directory.GetCurrentDirectory(), $"{uniqueFolderName}/root_folder"), a, fallbackFolders, "a_folder/a.md");
            var aMarked     = service.Markup("place", "holder");
            var aDependency = aMarked.Dependency;

            Assert.Equal(@"<p>markdown a.md main content start.</p>
<p>code_in_a code in a.md content start</p>
<pre><code class=""lang-cs"" name=""this is code_in_a code"">namespace code_in_a{}
</code></pre><p>code_in_a in a.md content end</p>
<p>markdown a.md a.md content end.</p>
".Replace("\r\n", "\n"), aMarked.Html);
            Assert.Equal(
                new[] { "../../fallback_folder/a_folder/code_in_a.cs", "code_in_a.cs" },
                aDependency.OrderBy(x => x).ToArray());
        }
Exemplo n.º 15
0
        public void TestFallback_Inclusion_random_name()
        {
            // -root_folder (this is also docset folder)
            //  |- root.md
            //  |- a_folder
            //  |  |- a.md
            //  |- token_folder
            //  |  |- token1.md
            // -fallback_folder
            //  |- token_folder
            //     |- token2.md

            // 1. Prepare data
            var uniqueFolderName = Path.GetRandomFileName();
            var root             = $@"1markdown root.md main content start.

[!include[a](a_folder_{uniqueFolderName}/a_{uniqueFolderName}.md ""This is a.md"")]

markdown root.md main content end.";

            var a = $@"1markdown a.md main content start.

[!include[token1](../token_folder_{uniqueFolderName}/token1_{uniqueFolderName}.md ""This is token1.md"")]
[!include[token1](../token_folder_{uniqueFolderName}/token2_{uniqueFolderName}.md ""This is token2.md"")]

markdown a.md main content end.";

            var token1 = $@"1markdown token1.md content start.

[!include[token2](token2_{uniqueFolderName}.md ""This is token2.md"")]

markdown token1.md content end.";

            var token2 = @"**1markdown token2.md main content**";

            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder_{uniqueFolderName}/root_{uniqueFolderName}.md", root);
            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder_{uniqueFolderName}/a_folder_{uniqueFolderName}/a_{uniqueFolderName}.md", a);
            TestUtility.WriteToFile($"{uniqueFolderName}/root_folder_{uniqueFolderName}/token_folder_{uniqueFolderName}/token1_{uniqueFolderName}.md", token1);
            TestUtility.WriteToFile($"{uniqueFolderName}/fallback_folder_{uniqueFolderName}/token_folder_{uniqueFolderName}/token2_{uniqueFolderName}.md", token2);

            var fallbackFolders = new List <string> {
                { Path.Combine(Directory.GetCurrentDirectory(), $"{uniqueFolderName}/fallback_folder_{uniqueFolderName}") }
            };
            var parameter = new MarkdownServiceParameters
            {
                BasePath = "."
            };
            var service = new MarkdigMarkdownService(parameter);
            //var marked = service.Markup(Path.Combine(Directory.GetCurrentDirectory(), $"{uniqueFolderName}/root_folder_{uniqueFolderName}"), root, fallbackFolders, $"root_{uniqueFolderName}.md");
            var marked     = service.Markup("place", "holder");
            var dependency = marked.Dependency;

            Assert.Equal(@"<p>1markdown root.md main content start.</p>
<p>1markdown a.md main content start.</p>
<p>1markdown token1.md content start.</p>
<p><strong>1markdown token2.md main content</strong></p>
<p>markdown token1.md content end.</p>
<p><strong>1markdown token2.md main content</strong></p>
<p>markdown a.md main content end.</p>
<p>markdown root.md main content end.</p>
".Replace("\r\n", "\n"), marked.Html);
            Assert.Equal(
                new[] { $"../fallback_folder_{uniqueFolderName}/token_folder_{uniqueFolderName}/token2_{uniqueFolderName}.md", $"a_folder_{uniqueFolderName}/a_{uniqueFolderName}.md", $"token_folder_{uniqueFolderName}/token1_{uniqueFolderName}.md", $"token_folder_{uniqueFolderName}/token2_{uniqueFolderName}.md" },
                dependency.OrderBy(x => x).ToArray());
        }
Exemplo n.º 16
0
        private string RenderHTMLBlock(string markdown, string filepath)
        {
            //DFM engine
            var htmlRender = new DfmRenderer();
            var dfmengine  = _builder.CreateDfmEngine(htmlRender);

            //Markdig engine
            var parameter = new MarkdownServiceParameters
            {
                BasePath   = _workingFolder,
                Extensions = new Dictionary <string, object>
                {
                    { "EnableSourceInfo", false }
                }
            };

            var markdigService = new MarkdigMarkdownService(parameter);
            var markdigToken   = markdigService.Parse(markdown, Path.GetFileName(filepath));

            if (markdigToken == null)
            {
                return(markdown);
            }

            var htmlBlockTokens = markdigToken.Where(token => token is HtmlBlock).ToList();

            if (htmlBlockTokens.Count == 0)
            {
                return(markdown);
            }

            var lines = markdown.Split('\n');

            var lineIndex = 0;
            var result    = new StringBuilder();

            foreach (HtmlBlock block in htmlBlockTokens)
            {
                if (!_useLegacyMode && !string.IsNullOrEmpty(lines[block.Line]) &&
                    lines[block.Line].StartsWith("<!--"))
                {
                    continue;
                }

                var blockStart = block.Line;
                var blockEnd   = block.Line + block.Lines.Count - 1;

                while (lineIndex < blockStart)
                {
                    if (lineIndex != 0)
                    {
                        result.Append('\n');
                    }
                    result.Append(lines[lineIndex]);
                    lineIndex++;
                }

                var tempMarkdown = new StringBuilder();
                while (lineIndex <= blockEnd)
                {
                    if (lineIndex != 0)
                    {
                        if (lineIndex == blockStart)
                        {
                            result.Append('\n');
                        }
                        else
                        {
                            tempMarkdown.Append('\n');
                        }
                    }
                    tempMarkdown.Append(lines[lineIndex]);
                    lineIndex++;
                }

                // Wrap in <migratetemproot> to make sure DFM recognize it as a single Html Block
                var tempResult = dfmengine.Markup($"<migratetemproot>{tempMarkdown.ToString()}</migratetemproot>", Path.GetFileName(filepath)).TrimEnd('\n');

                if (tempResult.StartsWith("<migratetemproot>") && tempResult.EndsWith("</migratetemproot>"))
                {
                    tempResult = tempResult.Substring("<migratetemproot>".Length, tempResult.Length - "<migratetemproot></migratetemproot>".Length);
                }
                else
                {
                    tempResult = tempMarkdown.ToString();
                }

                result.Append(tempResult);
            }

            while (lineIndex < lines.Count())
            {
                if (lineIndex != 0)
                {
                    result.Append('\n');
                }
                result.Append(lines[lineIndex]);
                lineIndex++;
            }

            return(result.ToString());
        }