RickStrahl / Snippets-MarkdownMonster-Addin

A Snippet Expansion Manager for embedding templated text into Markdown Monster Markdown documents
https://markdownmonster.west-wind.com
6 stars 3 forks source link

Support for TOC snippet #5

Open NicoJuicy opened 2 years ago

NicoJuicy commented 2 years ago

I created a ToC snippet and tried to run the application but ran into issues ( references and etc).

Is it possible to add support for the System.Text.RegularExpressions namespace?

The snippet i would like to add as a c# razor template is the following one:

@{

string text = Model.ActiveDocument.CurrentText;
string[] headerPrefix = new string[]{"- ","  * ","    + ","      - ","        * ","          + "};

string toc = "";

foreach(var line in text.Split("\n"))
{
    if(isHeader(line)){
        toc +=  GenerateTocLine(line) + "\n";
    }   
}

bool isHeader(string header) 
{
    int headerLevel = header.TakeWhile(c => c == '#').Count();
    return !(headerLevel == 0 || headerLevel > headerPrefix.Length); 
}

string GenerateTocLine(string header)
{
    int headerLevel = header.TakeWhile(c => c == '#').Count();

    return $"{headerPrefix[headerLevel -1]}[{getTitle(header, headerLevel)}]({GetLink(header, headerLevel)})";
}

string GetLink(string header,int headerLevel)
{
    string header1 = header.ToLowerInvariant().Replace("# ","#");
    header2 = Regex1.Replace(header, @"[^\w\s ]", "");
    header3 = header2.Replace(" ","-");
    return "#" + header3;
}

string getTitle(string header, int headerLevel)
{

    header = Regex.Replace(header, "#", "");
    return header.Trim();
}
}

@toc

When i added the regex dll to the folder, it found the namespace. But it displayed it with double ;; on the end. So the execution failed.

image

RickStrahl commented 2 years ago

You shouldn't need the dll since that's part of the .NET runtime.

I think all you should need is:

@using System.Text.RegularExpressions

Note the line has to be just like that, without a semi-colon at the top of the template.

I tried this with your code and I get a bunch of other errors, but not the double ;; and have the included System.Text.RegularExpressions.

NicoJuicy commented 2 years ago

I will check it out this evening, although this was the first thing i tried.