diff --git a/readme.md b/readme.md index 6ffb6de3..7eaf985d 100644 --- a/readme.md +++ b/readme.md @@ -47,7 +47,7 @@ You can **try Markdig online** and compare it to other implementations on [babel - [**Emoji**](src/Markdig.Tests/Specs/EmojiSpecs.md) support (inspired from [Markdown-it](https://markdown-it.github.io/)) - [**SmartyPants**](src/Markdig.Tests/Specs/SmartyPantsSpecs.md) (inspired from [Daring Fireball - SmartyPants](https://daringfireball.net/projects/smartypants/)) - [**Bootstrap**](src/Markdig.Tests/Specs/BootstrapSpecs.md) class (to output bootstrap class) - - [**Diagrams**](src/Markdig.Tests/Specs/DiagramsSpecs.md) extension whenever a fenced code block contains a special keyword, it will be converted to a div block with the content as-is (currently, supports only for [`mermaid` diagrams](https://knsv.github.io/mermaid/)) + - [**Diagrams**](src/Markdig.Tests/Specs/DiagramsSpecs.md) extension whenever a fenced code block contains a special keyword, it will be converted to a div block with the content as-is (currently, supports [`mermaid`](https://knsv.github.io/mermaid/) and [`nomnoml`](https://github.com/skanaar/nomnoml) diagrams) - [**YAML frontmatter**](src/Markdig.Tests/Specs/YamlSpecs.md) to parse without evaluating the frontmatter and to discard it from the HTML output (typically used for previewing without the frontmatter in MarkdownEditor) - [**JIRA links**](src/Markdig.Tests/Specs/JiraLinks.md) to automatically generate links for JIRA project references (Thanks to @clarkd: https://github.com/clarkd/MarkdigJiraLinker) - Compatible with .NET 3.5, 4.0+ and .NET Core (`netstandard1.1+`) diff --git a/src/Markdig.Tests/Markdig.Tests.csproj b/src/Markdig.Tests/Markdig.Tests.csproj index d5cd3b3f..d792a17c 100644 --- a/src/Markdig.Tests/Markdig.Tests.csproj +++ b/src/Markdig.Tests/Markdig.Tests.csproj @@ -61,8 +61,8 @@ - + diff --git a/src/Markdig.Tests/Specs/DiagramsSpecs.md b/src/Markdig.Tests/Specs/DiagramsSpecs.md index 31fa8616..495c8fbc 100644 --- a/src/Markdig.Tests/Specs/DiagramsSpecs.md +++ b/src/Markdig.Tests/Specs/DiagramsSpecs.md @@ -23,4 +23,35 @@ graph TD; ```````````````````````````````` +## nomnoml diagrams + +Using a fenced code block with the `nomnoml` language info will output a `
` instead of a `pre/code` block: + +```````````````````````````````` example +```nomnoml +[example| + propertyA: Int + propertyB: string +| + methodA() + methodB() +| + [subA]--[subB] + [subA]-:>[sub C] +] +``` +. +
[example| + propertyA: Int + propertyB: string +| + methodA() + methodB() +| + [subA]--[subB] + [subA]-:>[sub C] +] +
+```````````````````````````````` + TODO: Add other text diagram languages \ No newline at end of file diff --git a/src/Markdig.Tests/Specs/PipeTableSpecs.md b/src/Markdig.Tests/Specs/PipeTableSpecs.md index acddfbb4..3dab4c32 100644 --- a/src/Markdig.Tests/Specs/PipeTableSpecs.md +++ b/src/Markdig.Tests/Specs/PipeTableSpecs.md @@ -513,6 +513,39 @@ a | b ```````````````````````````````` +** Rule #9** + +It is possible to have a single row header only: + +```````````````````````````````` example +a | b +-- | -- +. + + + + + + + +
ab
+```````````````````````````````` + +```````````````````````````````` example +|a|b|c +|---|---|---| +. + + + + + + + + +
abc
+```````````````````````````````` + ** Tests ** Tests trailing spaces after pipes diff --git a/src/Markdig.Tests/Specs/Specs.cs b/src/Markdig.Tests/Specs/Specs.cs index 45bd5979..96725a74 100644 --- a/src/Markdig.Tests/Specs/Specs.cs +++ b/src/Markdig.Tests/Specs/Specs.cs @@ -1,4 +1,4 @@ -using System; +using System; using NUnit.Framework; namespace Markdig.Tests @@ -17259,9 +17259,9 @@ namespace Markdig.Tests TestParser.TestSpec("a | b\n-- | --\n[This is a link with a | inside the label](http://google.com) | 1", "\n\n\n\n\n\n\n\n\n\n\n\n\n
ab
This is a link with a | inside the label1
", "pipetables|advanced"); } } - // ** Tests ** + // ** Rule #9** // - // Tests trailing spaces after pipes + // It is possible to have a single row header only: [TestFixture] public partial class TestExtensionsPipeTable { @@ -17272,6 +17272,64 @@ namespace Markdig.Tests // Section: Extensions Pipe Table // // The following CommonMark: + // a | b + // -- | -- + // + // Should be rendered as: + // + // + // + // + // + // + // + //
ab
+ + Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 22, "Extensions Pipe Table"); + TestParser.TestSpec("a | b\n-- | --", "\n\n\n\n\n\n\n
ab
", "pipetables|advanced"); + } + } + [TestFixture] + public partial class TestExtensionsPipeTable + { + [Test] + public void Example023() + { + // Example 23 + // Section: Extensions Pipe Table + // + // The following CommonMark: + // |a|b|c + // |---|---|---| + // + // Should be rendered as: + // + // + // + // + // + // + // + // + //
abc
+ + Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 23, "Extensions Pipe Table"); + TestParser.TestSpec("|a|b|c\n|---|---|---|", "\n\n\n\n\n\n\n\n
abc
", "pipetables|advanced"); + } + } + // ** Tests ** + // + // Tests trailing spaces after pipes + [TestFixture] + public partial class TestExtensionsPipeTable + { + [Test] + public void Example024() + { + // Example 24 + // Section: Extensions Pipe Table + // + // The following CommonMark: // | abc | def | // |---|---| // | cde| ddd| @@ -17307,7 +17365,7 @@ namespace Markdig.Tests // // - Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 22, "Extensions Pipe Table"); + Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 24, "Extensions Pipe Table"); TestParser.TestSpec("| abc | def | \n|---|---|\n| cde| ddd| \n| eee| fff|\n| fff | fffff | \n|gggg | ffff | ", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
abcdef
cdeddd
eeefff
ffffffff
ggggffff
", "pipetables|advanced"); } } @@ -17318,9 +17376,9 @@ namespace Markdig.Tests public partial class TestExtensionsPipeTable { [Test] - public void Example023() + public void Example025() { - // Example 23 + // Example 25 // Section: Extensions Pipe Table // // The following CommonMark: @@ -17346,7 +17404,7 @@ namespace Markdig.Tests // // - Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 23, "Extensions Pipe Table"); + Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 25, "Extensions Pipe Table"); TestParser.TestSpec("a | b\n-- | - \n0 | 1 | 2", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ab
012
", "pipetables|advanced"); } } @@ -18664,15 +18722,15 @@ namespace Markdig.Tests // Section: Extensions Emoji // // The following CommonMark: - // This is a sentance :ok_hand: + // This is a sentence :ok_hand: // and keeps going to the next line :) // // Should be rendered as: - //

This is a sentance 👌 + //

This is a sentence 👌 // and keeps going to the next line 😃

Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 4, "Extensions Emoji"); - TestParser.TestSpec("This is a sentance :ok_hand:\nand keeps going to the next line :)", "

This is a sentance 👌\nand keeps going to the next line 😃

", "emojis|advanced+emojis"); + TestParser.TestSpec("This is a sentence :ok_hand:\nand keeps going to the next line :)", "

This is a sentence 👌\nand keeps going to the next line 😃

", "emojis|advanced+emojis"); } } // # Extensions @@ -20361,6 +20419,49 @@ namespace Markdig.Tests Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 1, "Extensions Mermaid diagrams"); TestParser.TestSpec("```mermaid\ngraph TD;\n A-->B;\n A-->C;\n B-->D;\n C-->D;\n```", "
graph TD;\n A-->B;\n A-->C;\n B-->D;\n C-->D;\n
", "diagrams|advanced"); } + } + // ## nomnoml diagrams + // + // Using a fenced code block with the `nomnoml` language info will output a `
` instead of a `pre/code` block: + [TestFixture] + public partial class TestExtensionsnomnomldiagrams + { + [Test] + public void Example002() + { + // Example 2 + // Section: Extensions nomnoml diagrams + // + // The following CommonMark: + // ```nomnoml + // [example| + // propertyA: Int + // propertyB: string + // | + // methodA() + // methodB() + // | + // [subA]--[subB] + // [subA]-:>[sub C] + // ] + // ``` + // + // Should be rendered as: + //
[example| + // propertyA: Int + // propertyB: string + // | + // methodA() + // methodB() + // | + // [subA]--[subB] + // [subA]-:>[sub C] + // ] + //
+ + Console.WriteLine("Example {0}" + Environment.NewLine + "Section: {0}" + Environment.NewLine, 2, "Extensions nomnoml diagrams"); + TestParser.TestSpec("```nomnoml\n[example|\n propertyA: Int\n propertyB: string\n|\n methodA()\n methodB()\n|\n [subA]--[subB]\n [subA]-:>[sub C]\n]\n```", "
[example|\n propertyA: Int\n propertyB: string\n|\n methodA()\n methodB()\n|\n [subA]--[subB]\n [subA]-:>[sub C]\n]\n
", "diagrams|advanced"); + } } // TODO: Add other text diagram languages // # Extensions diff --git a/src/Markdig.Tests/Specs/Specs.tt b/src/Markdig.Tests/Specs/Specs.tt index 86671206..1ffe3e98 100644 --- a/src/Markdig.Tests/Specs/Specs.tt +++ b/src/Markdig.Tests/Specs/Specs.tt @@ -1,4 +1,4 @@ -<#/* +<#/* Copyright (c) Alexandre Mutel. All rights reserved. This file is licensed under the BSD-Clause 2 license. See the license.txt file in the project root for more information.The MIT License (MIT) @@ -36,7 +36,8 @@ SOFTWARE. <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.CodeDom" #> <#@ import namespace="System.CodeDom.Compiler" #> -<#@ output extension=".cs" #><# +<#@ output extension=".cs" encoding="utf-8"#> +<# var specFiles = new KeyValuePair[] { new KeyValuePair("https://raw.githubusercontent.com/jgm/CommonMark/4ec06917c3a3632be4a935ffa0973092bd2621be/spec.txt", string.Empty), // 0.28 new KeyValuePair(Host.ResolvePath("PipeTableSpecs.md"), "pipetables|advanced"), diff --git a/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierExtension.cs b/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierExtension.cs index 22fa75f1..e2134795 100644 --- a/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierExtension.cs +++ b/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierExtension.cs @@ -1,4 +1,4 @@ -// Copyright (c) Alexandre Mutel. All rights reserved. +// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. @@ -143,7 +143,12 @@ namespace Markdig.Extensions.AutoIdentifiers stripRenderer.Render(headingBlock.Inline); var headingText = headingWriter.ToString(); headingWriter.GetStringBuilder().Length = 0; - headingText = LinkHelper.Urilize(headingText, (options & AutoIdentifierOptions.AllowOnlyAscii) != 0); + + // TODO: Should we have a struct with more configure optionss for LinkHelper.Urilize? + headingText = LinkHelper.Urilize(headingText, + (options & AutoIdentifierOptions.AllowOnlyAscii) != 0, + (options & AutoIdentifierOptions.KeepOpeningDigits) != 0, + (options & AutoIdentifierOptions.DiscardDots) != 0); var baseHeadingId = string.IsNullOrEmpty(headingText) ? "section" : headingText; int index = 0; diff --git a/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierOptions.cs b/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierOptions.cs index 86d1b105..dde55ecc 100644 --- a/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierOptions.cs +++ b/src/Markdig/Extensions/AutoIdentifiers/AutoIdentifierOptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Alexandre Mutel. All rights reserved. +// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; @@ -21,6 +21,11 @@ namespace Markdig.Extensions.AutoIdentifiers /// Default = AutoLink | AllowOnlyAscii, + /// + /// Renders auto identifiers like GitHub. + /// + GitHub = Default | KeepOpeningDigits | DiscardDots, + /// /// Allows to link to a header by using the same text as the header for the link label. Default is true /// @@ -30,5 +35,15 @@ namespace Markdig.Extensions.AutoIdentifiers /// Allows only ASCII characters in the url (HTML 5 allows to have UTF8 characters). Default is true /// AllowOnlyAscii = 2, + + /// + /// Allows to keep digits starting a heading (by default, it keeps only characters starting from the first letter) + /// + KeepOpeningDigits = 4, + + /// + /// Discard dots when computing an identifier. + /// + DiscardDots = 8 } } \ No newline at end of file diff --git a/src/Markdig/Extensions/Diagrams/DiagramExtension.cs b/src/Markdig/Extensions/Diagrams/DiagramExtension.cs index 417a4b23..484f034c 100644 --- a/src/Markdig/Extensions/Diagrams/DiagramExtension.cs +++ b/src/Markdig/Extensions/Diagrams/DiagramExtension.cs @@ -25,6 +25,7 @@ namespace Markdig.Extensions.Diagrams var codeRenderer = htmlRenderer.ObjectRenderers.FindExact(); // TODO: Add other well known diagram languages codeRenderer.BlocksAsDiv.Add("mermaid"); + codeRenderer.BlocksAsDiv.Add("nomnoml"); } } } diff --git a/src/Markdig/Extensions/Tables/HtmlTableRenderer.cs b/src/Markdig/Extensions/Tables/HtmlTableRenderer.cs index 2804d02f..5c32b0cf 100644 --- a/src/Markdig/Extensions/Tables/HtmlTableRenderer.cs +++ b/src/Markdig/Extensions/Tables/HtmlTableRenderer.cs @@ -85,7 +85,7 @@ namespace Markdig.Extensions.Tables { renderer.Write($" rowspan=\"{cell.RowSpan}\""); } - if (table.ColumnDefinitions != null) + if (table.ColumnDefinitions.Count > 0) { var columnIndex = cell.ColumnIndex < 0 || cell.ColumnIndex >= table.ColumnDefinitions.Count ? i diff --git a/src/Markdig/Extensions/Tables/PipeTableOptions.cs b/src/Markdig/Extensions/Tables/PipeTableOptions.cs index dc8058f0..01a6c733 100644 --- a/src/Markdig/Extensions/Tables/PipeTableOptions.cs +++ b/src/Markdig/Extensions/Tables/PipeTableOptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Alexandre Mutel. All rights reserved. +// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. namespace Markdig.Extensions.Tables diff --git a/src/Markdig/Extensions/Tables/PipeTableParser.cs b/src/Markdig/Extensions/Tables/PipeTableParser.cs index 9397e845..06356e00 100644 --- a/src/Markdig/Extensions/Tables/PipeTableParser.cs +++ b/src/Markdig/Extensions/Tables/PipeTableParser.cs @@ -440,12 +440,13 @@ namespace Markdig.Extensions.Tables // If we have a header row, we can remove it // TODO: we could optimize this by merging FindHeaderRow and the previous loop + var tableRow = (TableRow)table[0]; + tableRow.IsHeader = Options.RequireHeaderSeparator; if (aligns != null) { - table.RemoveAt(1); - var tableRow = (TableRow) table[0]; - table.ColumnDefinitions.AddRange(aligns); tableRow.IsHeader = true; + table.RemoveAt(1); + table.ColumnDefinitions.AddRange(aligns); } // Perform delimiter processor that are coming after this processor @@ -532,6 +533,13 @@ namespace Markdig.Extensions.Tables ? columnDelimiter.FirstChild : delimiter.NextSibling; + // If there is no content after + if (IsNullOrSpace(nextSibling)) + { + isValidRow = true; + break; + } + if (!ParseHeaderString(nextSibling, out align)) { break; @@ -606,6 +614,20 @@ namespace Markdig.Extensions.Tables } } + private static bool IsNullOrSpace(Inline inline) + { + if (inline == null) + { + return true; + } + var literal = inline as LiteralInline; + if (literal != null) + { + return literal.Content.IsEmptyOrWhitespace(); + } + return false; + } + private class TableState { public TableState() diff --git a/src/Markdig/Extensions/Tables/Table.cs b/src/Markdig/Extensions/Tables/Table.cs index 121ba8ab..9ec8cd84 100644 --- a/src/Markdig/Extensions/Tables/Table.cs +++ b/src/Markdig/Extensions/Tables/Table.cs @@ -33,7 +33,7 @@ namespace Markdig.Extensions.Tables /// /// Gets or sets the column alignments. May be null. /// - public List ColumnDefinitions { get; private set; } + public List ColumnDefinitions { get; } /// /// Checks if the table structure is valid. diff --git a/src/Markdig/Helpers/LinkHelper.cs b/src/Markdig/Helpers/LinkHelper.cs index 04014e72..875cf8c7 100644 --- a/src/Markdig/Helpers/LinkHelper.cs +++ b/src/Markdig/Helpers/LinkHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Alexandre Mutel. All rights reserved. +// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using System; @@ -18,10 +18,10 @@ namespace Markdig.Helpers return TryParseAutolink(ref text, out link, out isEmail); } - public static string Urilize(string headingText, bool allowOnlyAscii) + public static string Urilize(string headingText, bool allowOnlyAscii, bool keepOpeningDigits = false, bool discardDots = false) { var headingBuffer = StringBuilderCache.Local(); - bool hasLetter = false; + bool hasLetter = keepOpeningDigits && headingText.Length > 0 && char.IsLetterOrDigit(headingText[0]); bool previousIsSpace = false; for (int i = 0; i < headingText.Length; i++) { @@ -47,7 +47,7 @@ namespace Markdig.Helpers } else if (hasLetter) { - if (IsReservedPunctuation(c)) + if (IsReservedPunctuation(c, discardDots)) { if (previousIsSpace) { @@ -67,7 +67,7 @@ namespace Markdig.Helpers else if (!previousIsSpace && c.IsWhitespace()) { var pc = headingBuffer[headingBuffer.Length - 1]; - if (!IsReservedPunctuation(pc)) + if (!IsReservedPunctuation(pc, discardDots)) { headingBuffer.Append('-'); } @@ -81,7 +81,7 @@ namespace Markdig.Helpers while (headingBuffer.Length > 0) { var c = headingBuffer[headingBuffer.Length - 1]; - if (IsReservedPunctuation(c)) + if (IsReservedPunctuation(c, false)) { headingBuffer.Length--; } @@ -97,9 +97,9 @@ namespace Markdig.Helpers } [MethodImpl(MethodImplOptionPortable.AggressiveInlining)] - private static bool IsReservedPunctuation(char c) + private static bool IsReservedPunctuation(char c, bool discardDots) { - return c == '_' || c == '-' || c == '.'; + return c == '_' || c == '-' || (!discardDots && c == '.'); } public static bool TryParseAutolink(ref StringSlice text, out string link, out bool isEmail) diff --git a/src/Markdig/Markdig.csproj b/src/Markdig/Markdig.csproj index a821d307..5cdbd671 100644 --- a/src/Markdig/Markdig.csproj +++ b/src/Markdig/Markdig.csproj @@ -5,7 +5,7 @@ Alexandre Mutel Markdig en-US - 0.13.3 + 0.13.4 Alexandre Mutel net35;net40;portable40-net40+sl5+win8+wp8+wpa81;netstandard1.1;uap10.0 Markdig @@ -13,14 +13,17 @@ Markdig.Signed Markdown CommonMark md html md2html - > 0.13.3 - - Add support for Pandoc YAML frontmatter (#138) - > 0.13.2 - - Add support for UAP10.0 (#137) - > 0.13.1 - - Fix indenting issue after a double digit list block using a tab (#134) - > 0.13.0 - - Update to latest CommonMark specs 0.28 +> 0.13.4 +- Add support for single table header row without a table body rows (#141) +- ADd support for `nomnoml` diagrams +> 0.13.3 +- Add support for Pandoc YAML frontmatter (#138) +> 0.13.2 +- Add support for UAP10.0 (#137) +> 0.13.1 +- Fix indenting issue after a double digit list block using a tab (#134) +> 0.13.0 +- Update to latest CommonMark specs 0.28 https://raw.githubusercontent.com/lunet-io/markdig/master/img/markdig.png https://github.com/lunet-io/markdig diff --git a/src/markdig.sln b/src/markdig.sln index 69cd9e0e..8e4bf05f 100644 --- a/src/markdig.sln +++ b/src/markdig.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26430.16 +VisualStudioVersion = 15.0.26730.16 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{061866E2-005C-4D13-A338-EA464BBEC60F}" ProjectSection(SolutionItems) = preProject @@ -26,6 +26,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Markdig.WebApp", "Markdig.W EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnicodeNormDApp", "UnicodeNormDApp\UnicodeNormDApp.csproj", "{33FFC0B9-0187-44F9-9424-BB5AF5B4FB84}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "mdtoc", "mdtoc\mdtoc.csproj", "{E3CDFF0F-5BFC-42E9-BDBA-2797651900A2}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -52,8 +54,15 @@ Global {33FFC0B9-0187-44F9-9424-BB5AF5B4FB84}.Debug|Any CPU.Build.0 = Debug|Any CPU {33FFC0B9-0187-44F9-9424-BB5AF5B4FB84}.Release|Any CPU.ActiveCfg = Release|Any CPU {33FFC0B9-0187-44F9-9424-BB5AF5B4FB84}.Release|Any CPU.Build.0 = Release|Any CPU + {E3CDFF0F-5BFC-42E9-BDBA-2797651900A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E3CDFF0F-5BFC-42E9-BDBA-2797651900A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E3CDFF0F-5BFC-42E9-BDBA-2797651900A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E3CDFF0F-5BFC-42E9-BDBA-2797651900A2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {D068F7B6-6ACC-456C-A2E1-10EA746D956D} + EndGlobalSection EndGlobal diff --git a/src/mdtoc/App.config b/src/mdtoc/App.config new file mode 100644 index 00000000..731f6de6 --- /dev/null +++ b/src/mdtoc/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/mdtoc/Program.cs b/src/mdtoc/Program.cs new file mode 100644 index 00000000..13c657b5 --- /dev/null +++ b/src/mdtoc/Program.cs @@ -0,0 +1,101 @@ +// Copyright (c) Alexandre Mutel. All rights reserved. +// This file is licensed under the BSD-Clause 2 license. +// See the license.txt file in the project root for more information. +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using Markdig; +using Markdig.Extensions.AutoIdentifiers; +using Markdig.Renderers; +using Markdig.Renderers.Html; +using Markdig.Syntax; + +namespace mdtoc +{ + /// + /// A tool to generate a markdown TOC from a markdown local file or a github link to a markdown file. + /// + class Program + { + static void Error(string message) + { + Console.WriteLine(message); + Environment.Exit(1); + } + + static void Main(string[] args) + { + if (args.Length != 1 || args[0] == "--help" || args[0] == "-help" || args[0] == "/?" || args[0] == "/help") + { + Error("Usage: mdtoc [markdown file path | http github URL]"); + return; + } + + var path = args[0]; + string markdown = null; + if (path.StartsWith("https:")) + { + Uri uri; + if (!Uri.TryCreate(path, UriKind.Absolute, out uri)) + { + Error($"Unable to parse Uri `{path}`"); + return; + } + // Special handling of github URL to access the raw content instead + if (uri.Host == "github.com") + { + // https://github.com/lunet-io/scriban/blob/master/doc/language.md + // https://raw.githubusercontent.com/lunet-io/scriban/master/doc/language.md + var newPath = uri.AbsolutePath; + var paths = new List(newPath.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries)); + if (paths.Count < 5 || paths[2] != "blob") + { + Error($"Invalid github.com URL `{path}`"); + return; + } + paths.RemoveAt(2); // remove blob + uri = new Uri($"https://raw.githubusercontent.com/{(string.Join("/", paths))}"); + } + + var httpClient = new HttpClient(); + markdown = httpClient.GetStringAsync(uri).ConfigureAwait(false).GetAwaiter().GetResult(); + } + else + { + markdown = File.ReadAllText(path); + } + + var pipeline = new MarkdownPipelineBuilder().UseAutoIdentifiers(AutoIdentifierOptions.GitHub).Build(); + var doc = Markdown.Parse(markdown, pipeline); + + // Precomputes the minHeading + var headings = doc.Descendants().ToList(); + int minHeading = int.MaxValue; + int maxHeading = int.MinValue; + foreach (var heading in headings) + { + minHeading = Math.Min(minHeading, heading.Level); + maxHeading = Math.Max(maxHeading, heading.Level); + } + + var writer = Console.Out; + // Use this htmlWriter to write content of headings into link label + var htmlWriter = new HtmlRenderer(writer) {EnableHtmlForInline = true}; + foreach (var heading in headings) + { + var indent = heading.Level - minHeading; + for (int i = 0; i < indent; i++) + { + // - Start Of Heading + writer.Write(" "); + } + writer.Write("- ["); + htmlWriter.WriteLeafInline(heading); + writer.Write($"](#{heading.GetAttributes().Id})"); + writer.WriteLine(); + } + } + } +} diff --git a/src/mdtoc/Properties/AssemblyInfo.cs b/src/mdtoc/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..5d211f85 --- /dev/null +++ b/src/mdtoc/Properties/AssemblyInfo.cs @@ -0,0 +1,39 @@ +// Copyright (c) Alexandre Mutel. All rights reserved. +// This file is licensed under the BSD-Clause 2 license. +// See the license.txt file in the project root for more information. +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("mdtoc")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Alexandre Mutel")] +[assembly: AssemblyProduct("mdtoc")] +[assembly: AssemblyCopyright("Copyright © 2017 - Alexandre Mutel")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e3cdff0f-5bfc-42e9-bdba-2797651900a2")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/mdtoc/mdtoc.csproj b/src/mdtoc/mdtoc.csproj new file mode 100644 index 00000000..fb24835d --- /dev/null +++ b/src/mdtoc/mdtoc.csproj @@ -0,0 +1,58 @@ + + + + + Debug + AnyCPU + {E3CDFF0F-5BFC-42E9-BDBA-2797651900A2} + Exe + mdtoc + mdtoc + v4.6.1 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {8a58a7e2-627c-4f41-933f-5ac92adfab48} + Markdig + + + + \ No newline at end of file