Skip to content

Commit

Permalink
Add markdown generator
Browse files Browse the repository at this point in the history
  • Loading branch information
firedef committed Jun 1, 2022
1 parent 5c1dda8 commit 1e71b16
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions ObsidianSharp.Core/src/markdown/MdGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Text;

namespace ObsidianSharp.Core.markdown;

public class MdGenerator {
private readonly StringBuilder md = new();
private readonly Dictionary<string, int> footnoteRefs = new();
private readonly List<string> footnotes = new();

public void Add(string txt) => md.Append(txt);
public void AddLine(string txt) => md.Append(txt + "<br/>\n");

public void NextLine() => AddLine("");

public void AddHeading(string txt, int level = 1) => AddLine(new string('#', level) + " " + txt);
public void AddHeading(string txt, string id, int level = 1) => AddLine($"{new('#', level)} {txt} {{#{id}}}");

public void AddBold(string txt) => Add($"**{txt}**");
public void AddItalic(string txt) => Add($"*{txt}*");
public void AddStrikethrough(string txt) => Add($"~~{txt}~~");
public void AddSubscript(string txt) => Add($"~{txt}~");
public void AddSuperscript(string txt) => Add($"^{txt}^");

public void AddQuote(string txt) => AddLine($"> {txt}");

public void AddCode(string txt) => AddLine($"`{txt}`");
public void AddCode(string txt, string lang) => AddLine($"`{lang} {txt}`");

public void AddRule() => AddLine("---");

public void AddLink(string title, string link) => Add($"[{title}]({link})");

public void AddImage(string title, string link) => Add($"![{title}]({link})");

public void AddFootnote(string title, string description) {
footnoteRefs.Add(title, footnotes.Count);
footnotes.Add($"[^{footnoteRefs[title] + 1}]: " + description);
}

public void AddFootnoteRef(string title) => Add($" [^{footnoteRefs[title] + 1}]");


public string Generate() {
StringBuilder sb = new(md.ToString());
sb.AppendLine();

foreach (string footnote in footnotes) {
sb.AppendLine(footnote);
}

return sb.ToString();
}
}

0 comments on commit 1e71b16

Please sign in to comment.