Lea Hayes
Lea Hayes

Reputation: 64196

Flexible syntax highlighter written in C#

Is there an open source project written using C# which can apply syntax highlighting to a wide range of languages in a similar way to shjs?

Here is some pseudo code:

public string HighlightSourceInHTML(string html) {
    return Highlighter.HighlightHTML(html);
}

Where input HTML would be something along the lines of:

<!DOCTYPE html>
<html>
<head>...</head>
<body>
    <p>Here is a function written using C#:</p>
    <pre class="source lang-csharp">public void foo(int a, int b) {
    return a + b;
}</pre>

    <p>Here is the same function written using JavaScript:</p>
    <pre class="source lang-javascript">function foo(a, b) {
    return a + b;
}</pre>
</body>
</html>

Where the above would essentially return the entire HTML file where all pre elements with class source are syntax highlighted where source language is defined

Note: This is not for a server-side script but rather is part of an offline application where performance is less important.

Upvotes: 2

Views: 2103

Answers (2)

Lea Hayes
Lea Hayes

Reputation: 64196

Found one! There was one on my HDD the whole time in the Sandcastle Help File Builder (SHFB) folder in a managed DLL called "ColorizerLibrary.dll".

Simply add a reference to this DLL and syntax colouring becomes very easy.

Here is a usage example:

ColorizerLibrary.CodeColorizer colorizer = new ColorizerLibrary.CodeColorizer(
    @"C:\Program Files (x86)\EWSoftware\Sandcastle Help File Builder\Colorizer\highlight.xml",
    @"C:\Program Files (x86)\EWSoftware\Sandcastle Help File Builder\Colorizer\highlight.xsl"
);
colorizer.Init();

string htmlText = "<!DOCTYPE html><html><head><title>Test Page</title></head><body><pre codelanguage=\"CSharp\">public string Foo(string a, int b = 4) {\n\treturn a + b * 3;\n}</pre></body></html>";
return colorizer.ProcessAndHighlightText(htmlText);

Note: Remember to link to the CSS file in head to visualize syntax colours.

Added: Please find source code for ColorizerLibrary from here: http://shfb.codeplex.com/SourceControl/changeset/view/98645#1672960

Upvotes: 2

Ma9ic
Ma9ic

Reputation: 1125

Not exactly what your after, but it might help.

useful link:

http://hilite.me/

Upvotes: 1

Related Questions