Giter Site home page Giter Site logo

wbaldoumas / markdown-colorcode Goto Github PK

View Code? Open in Web Editor NEW
22.0 2.0 4.0 966 KB

An extension for Markdig that adds syntax highlighting to code through the power of ColorCode-Universal.

Home Page: https://wbaldoumas.github.io/markdown-colorcode/

License: MIT License

C# 93.29% CSS 6.71%
markdown markdig syntax-highlighting color colorcode-universal colorcode colorization hacktoberfest

markdown-colorcode's Introduction

Markdown.ColorCode

Build Coverage

Version Downloads

Contributor Covenant Contributors Commits

Forks Stargazers Issues MIT License

LinkedIn

About The Project

An extension for Markdig that adds syntax highlighting to code through the power of ColorCode.

Demonstration

Before

using Foo.Bar.Baz;

namespace Foo.Api;

public interface FooService {
    /// <summary>
    ///     Gets a new Foo!
    /// </summary>
    /// <returns>A new Foo</returns>
    public void GetFoo() {
        return new Foo();
    }
}

After

using Foo.Bar.Baz;

namespace Foo.Api;

public interface FooService {
    /// <summary>
    ///     Gets a new Foo!
    /// </summary>
    /// <returns>A new Foo</returns>
    public void GetFoo() {
        return new Foo();
    }
}

Installation

Package Manager

Install-Package Markdown.ColorCode -Version 2.2.2

.NET CLI

dotnet add package Markdown.ColorCode --version 2.2.2

Usage

To use this extension with Markdig, simply install the Markdown.ColorCode package use the ColorCode extension:

var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseColorCode()
    .Build();

var colorizedHtml = Markdig.Markdown.ToHtml(someMarkdown, pipeline);

Several optional configuration options are also at your disposal:

var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseColorCode(
        HtmlFormatterType.Style, // use style-based colorization (default)
        myCustomStyleDictionary, // use a custom colorization style dictionary
        myAdditionalLanguages, // augment the built-in language support
        myCustomLanguageId // set a default language ID to fall back to
    )
    .Build();

var colorizedHtml = Markdig.Markdown.ToHtml(someMarkdown, pipeline);

Improved C# Syntax Highlighting

For an improved experience with C# code blocks, consider using the Markdown.ColorCode.CSharpToColoredHtml package. This package provides a more robust syntax highlighting experience for C# code blocks by leveraging CSharpToColouredHtml.Core.

var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .UseColorCodeWithCSharpToColoredHtml(
        HtmlFormatterType.Style, // use style-based colorization (default)
        myCustomStyleDictionary, // use a custom colorization style dictionary
        myHtmlEmitterSettings, // configures CSharpToColouredHtml's HTML emitter
        myAdditionalLanguages, // augment the built-in language support
        myCustomLanguageId // set a default language ID to fall back to
    )
    .Build();

var colorizedHtml = Markdig.Markdown.ToHtml(someMarkdown, pipeline);

Note

The CsharpToColouredHTML package introduces dependencies which will not work well with Blazor WebAssembly projects. Either generate the HTML on the server side and send it to the client or use the base Markdown.ColorCode package if you are working with Blazor WebAssembly. See dotnet/aspnetcore#27373 and dotnet/aspnetcore#26724 for more details on the problem.

Roadmap

See the open issues for a list of proposed features (and known issues).

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated. For detailed contributing guidelines, please see CONTRIBUTING.md.

License

Distributed under the MIT License License. See LICENSE for more information.

Contact

@wbaldoumas

Project Link: https://github.com/wbaldoumas/markdown-colorcode

Acknowledgements

This README was adapted from https://github.com/othneildrew/Best-README-Template.

markdown-colorcode's People

Contributors

dependabot[bot] avatar renovate[bot] avatar wbaldoumas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

markdown-colorcode's Issues

Nullreference exception on .net6

Description

Markdown.ToHtml method throws nullreferenceexception when this package is loaded.

I'm seeing a package warning on restore of :-
warning NU1701: Package 'ColorCode.Portable 1.0.3' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NET
Framework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net6.0'. This package may not be full
y compatible with your project but a prior issue opened states that only net6.0 is supported, so this is surprising :)

Expected Behaviour

Render the markdown as happens when this extension is not loaded.

Actual Behaviour

throws nullreferenceexception

Affected Version

1.0.3

Steps to Reproduce

  1. Create empty .net 6.0 project
  2. Paste the below code
    using Markdig;
    using Markdown.ColorCode;

internal class Program
{
private static void Main(string[] args)
{
var inlocation = "C:\Source\Personal\SiteV3\SiteData";
var outlocation = "C:\Source\Personal\SiteV3\Generated";

      var pipeline = new MarkdownPipelineBuilder()
          .UseColorCode()
          .UseAdvancedExtensions()
          .Build();

      foreach (string fi in Directory.EnumerateFiles(inlocation))
      {
          if (fi.EndsWith(".md"))
          {
              var text = File.ReadAllText(fi);
              var html = Markdig.Markdown.ToHtml(text, pipeline);
              File.WriteAllText(fi.Replace(".md", ".html").Replace(inlocation, outlocation), html);
          }
      }
  }

}

  1. Create the appropriate folder structure and save the markdown file below.

Title Goes Here

Subtitle Goes Here

This is a comment in bold
Link to page 2: Page 2

Image of a cat goes here

using epicness; 
namespace funky
{
    public class chicken : animal
    {
        public chicken()
        {
            this.name = "chicken";
        }
    }
}

That was some embedded csharp code.

Checklist

Python is broken in the current Nuget version

Description

Python is broken in the current Nuget version : v1.0.1

It seems the last version (v2.0.13) of ColorCode had some build issue that somehow broke support for Python, it was fixed in the latest version (v2.0.14). This has been updated and merged already but the Nuget package has not been updated.

Expected Behaviour

Python language blocks should be properly color coded

<div style="color:#DADADA;background-color:#1E1E1E;"><pre>
    this = that
    DoSomething()
    <span style="color:#57A64A;"># this is a comment</span>
</pre></div>

Actual Behaviour

Python language blocks are not properly color coded

<pre><code class="language-python">    this = that
    DoSomething()
    # this is a comment
</code></pre>

Affected Version

v1.0.1

Steps to Reproduce

dotnet add package Markdown.ColorCode --version 1.0.1

string code = @"```python
    this = that
    DoSomething()
    # this is a comment
```";
                var pipeline = new MarkdownPipelineBuilder()
                    .UseAdvancedExtensions()
                    .UseColorCode()
                    .Build();
                Console.WriteLine(Markdig.Markdown.ToHtml(code, pipeline));

Checklist

Code block without explicit language rendered as normal text

Description

Code blocks, which do not have a language declared at all will render as normal text.

e.g. take following markdown input:
image

Expected Behaviour

The code is rendered as such without any syntax highlighting done.

The expected generated code:

<p>Just some text</p>
<div style="color:#DADADA;background-color:#1E1E1E;"><pre>We put random stuff in a code-block without a language.
This should be rendered as a code-block.
</pre>
</div>
<p>Some more text</p>

Screenshot

Actual Behaviour

The code is rendered as normal text within the html.

The actually generated code:

<p>Just some text</p>
<pre><code>We put random stuff in a code-block without a language.
This should be rendered as a code-block.
</code></pre>
<p>Some more text</p>

Screenshot

Affected Version

1.1.1 - Possibly prior versions; I did not test this.

Steps to Reproduce

  1. Save example markdown I provided above
  2. Transform to html using the library
  3. look at the result

Checklist

Support CSS Class Styling

Problem Statement

I need to be able to format HTML via CSS class names instead of inline style attributes.

Proposed Solution

ColorCode supports doing this using the HtmlClassFormatter instead of the HtmlFormatter. Having the ability to select this option would be big improvement. This could be via a parameter on the UseColorCode method or just a separate Use method altogether.

Default CSS template for HtmlFormatterType.Css

Problem Statement

In my case, the inlined CSS option is not a suitable option, because it conflicts with my own styling that I want to have on the code wrapper. It is impossible to overwrite it from my CSS because the parent div element doesn't have a class or something to target it.
So I decided to go with HtmlFormatterType.Css which is a great option.

However, I cannot find the default CSS file for the provided classes. I mean, it must be somewhere, right? I want to apply the same styling as per inlined CSS but have the option to add my own code to the CSS file.

Proposed Solution

Place the default CSS template in the repository for easy download (assets folder, maybe?)

compatibility issue

Description

Install-Package : Could not install package 'Markdown.ColorCode 1.0.1'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.7.2', but
the package does not contain any assembly references or content files that are compatible with that framework.

Nullreference exception with some markdown

Description

"System.NullReferenceException: Object reference not set to an instance of an object" thrown with some markdown, only when colorcode extension is used

Expected Behaviour

No error is thrown and markdown is produced

Actual Behaviour

Error was thrown

Affected Version

1.0.3

Steps to Reproduce

Sample code

using Markdig;
using Markdown.ColorCode;
using ColorCode.Styling;
using System;

public class Program
{
	public static void Main()
	{
		
		var markdownPipeline = new Markdig.MarkdownPipelineBuilder()
            .UsePipeTables()
            .UseAdvancedExtensions()
            .UseColorCode(StyleDictionary.DefaultDark)
            .UseAutoLinks()
            .UseEmojiAndSmiley()
            .UseMediaLinks()
            .UseCitations()
            .Build();
		
		var result = Markdig.Markdown.ToHtml("To print \"Hello World\" in C#, you can use the following code:\n```c",markdownPipeline);
		Console.WriteLine(result); 
	}
}

Error is not thrown if UseColorCode line is commented out

Checklist

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/build-test.yml
  • actions/checkout v4
  • actions/setup-dotnet v4
  • codecov/codecov-action v4
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • actions/setup-dotnet v4
  • github/codeql-action v3
.github/workflows/docs.yml
  • actions/checkout v4
  • nikeee/docfx-action v1.0.0
  • actions/setup-node v4
  • nikeee/docfx-action v1.0.0
  • JamesIves/github-pages-deploy-action v4.6.1
.github/workflows/lint.yml
  • actions/checkout v4
  • avto-dev/markdown-lint v1
  • actions/checkout v4
  • ocular-d/json-linter 0.0.2
  • actions/checkout v4
  • suzuki-shunsuke/github-action-renovate-config-validator v1.0.1
.github/workflows/publish-preview.yml
  • actions/checkout v4
  • actions/setup-dotnet v4
.github/workflows/publish.yml
  • actions/checkout v4
  • actions/setup-dotnet v4
  • alirezanet/publish-nuget v3.1.0
  • alirezanet/publish-nuget v3.1.0
.github/workflows/stale.yml
  • actions/stale v9
npm
docs/package.json
  • js-yaml 4.1.0
nuget
src/Markdown.ColorCode.CSharpToColoredHtml/Markdown.ColorCode.CSharpToColoredHtml.csproj
  • CsharpToColouredHTML.Core 1.0.44
  • ColorCode.Core 2.0.15
src/Markdown.ColorCode/Markdown.ColorCode.csproj
  • StyleCop.Analyzers 1.1.118
  • Markdig 0.37.0
  • ColorCode.HTML 2.0.15
  • ColorCode.Core 2.0.15
tests/Markdown.ColorCode.UnitTests/Markdown.ColorCode.UnitTests.csproj
  • StyleCop.Analyzers 1.1.118
  • NUnit3TestAdapter 4.5.0
  • NUnit 4.1.0
  • NSubstitute.Analyzers.CSharp 1.0.17
  • NSubstitute 5.1.0
  • Microsoft.NET.Test.Sdk 17.10.0
  • HtmlAgilityPack 1.11.61
  • FluentAssertions.Analyzers 0.32.0
  • FluentAssertions 6.12.0
  • coverlet.collector 6.0.2

  • Check this box to trigger a request for Renovate to run again on this repository

Restore code HTML element and language-[lang] class

Problem Statement

Current implementation removes the code tags from code blocks. Adding them back in could arguably improve the accessibility of webpages that use this package by following semantic HTML for screen readers. But in my case, it simply would make my Tailwind CSS classes cleaner ๐Ÿ˜†.

Similarly, retaining language-[lang] classes on the code element would allow for easier custom styling to be applied down the line and would be more "in line" with other syntax highlighting packages, such as hljs.

Proposed Solution

For adding back code tags, a StringBuilder or simple string interpolation could be used to add them back. For example, in ColorCodeBlockRenderer.cs:

protected override void Write(HtmlRenderer renderer, CodeBlock codeBlock)
{
// ...
        var code = ExtractCode(codeBlock);
        var formatter = new HtmlFormatter(_styleDictionary);
        var html = formatter.GetHtmlString(code, language);

        renderer.Write($"<code>{html}<code/>");
}

For adding back the language class, it could added back in the same step as adding the code tags. For example,

        renderer.Write($"<code class=\"language-{language.CssClassName}\">{html}<code/>");

Alternatives Considered

I am opening this issue before beginning work on a fork in case this would not be a desired feature. As hinted to above, there may be a more performant implementation than my example code. If desired, I'd be more than happy to write and PR this myself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.