Repository navigation
Expand file tree
/
Copy pathObsidianText.cs
More file actions
178 lines (148 loc) · 5.89 KB
/
Copy pathObsidianText.cs
File metadata and controls
178 lines (148 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
using Nodsoft.MoltenObsidian.Converter;
using Nodsoft.MoltenObsidian.Vault;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
namespace Nodsoft.MoltenObsidian;
/// <summary>
/// Represents a string of Obsidian-flavoured Markdown text.
/// </summary>
[PublicAPI]
public readonly record struct ObsidianText
{
/// <summary>
/// The Obsidian vault file that this text was loaded from.
/// </summary>
private readonly IVaultNote? _vaultFile;
/// <summary>
/// Creates a new <see cref="ObsidianText"/> from the specified string.
/// </summary>
/// <param name="obsidianText">The Obsidian-flavoured Markdown string.</param>
/// <param name="vaultFile">The Obsidian vault file that this text was loaded from.</param>
public ObsidianText(string obsidianText, IVaultNote? vaultFile = null)
{
_vaultFile = vaultFile;
if (obsidianText is null or "")
{
return;
}
// First, check if the text starts with a YAML header, and split it off if so.
TrimBom(ref obsidianText);
(string? frontmatter, Text) = SplitYamlFrontMatter(obsidianText);
// If there is a YAML header, parse it into a dictionary.
// Otherwise, set the frontmatter to an empty dictionary.
Frontmatter = frontmatter is null ? [] : ParseYamlFrontMatter(frontmatter);
}
/// <summary>
/// YAML deserializer used to parse the YAML frontmatter, if present.
/// </summary>
private static readonly IDeserializer YamlDeserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
/// <summary>
/// The Obsidian-flavoured Markdown text.
/// </summary>
public string Text { get; } = "";
/// <summary>
/// The YAML header (frontmatter) found at the beginning of the text, parsed into a key-value dictionary.
/// </summary>
public Dictionary<string, object> Frontmatter { get; } = [];
/// <summary>
/// The length of <see cref="Text"/>.
/// </summary>
public int Length => Text.Length;
/// <summary>
/// Creates a new ObsidianText from the specified string.
/// </summary>
/// <param name="text">The text to create the ObsidianText from.</param>
public static implicit operator ObsidianText(string text) => new(text);
/// <summary>
/// Creates a new ObsidianText from the specified string.
/// </summary>
/// <param name="text">The text to create the ObsidianText from.</param>
public static implicit operator string(ObsidianText text) => text.Text;
/// <summary>
/// Returns the text of the ObsidianText.
/// </summary>
/// <returns>The text of the ObsidianText.</returns>
public override string ToString() => Text;
/// <summary>
/// Returns the text of the ObsidianText.
/// </summary>
/// <returns>The text of the ObsidianText.</returns>
public string ToHtml() => _vaultFile is null
? ObsidianHtmlConverter.Default.Convert(Text)
: ObsidianHtmlConverter.Default.Convert(Text, _vaultFile);
/// <inheritdoc cref="ToHtml()"/>
/// <param name="converter">The converter to use.</param>
public string ToHtml(ObsidianHtmlConverter converter) => _vaultFile is null
? converter.Convert(Text)
: converter.Convert(Text, _vaultFile);
/// <summary>
/// Splits the YAML front matter from the Markdown content.
/// </summary>
/// <param name="obsidianMarkdown">The original Obsidian Markdown, with maybe a YAML front matter at the beginning.</param>
/// <returns>A tuple containing the YAML front matter and the remaining Obsidian Markdown content.</returns>
private static (string? frontMatter, string content) SplitYamlFrontMatter(string obsidianMarkdown)
{
// We need to find the first line with three dashes, and then the next line with three dashes.
// The content between the two lines is the front matter.
// If there is no front matter, the content is the whole file.
string[] lines = SplitByNewline(obsidianMarkdown);
// string[] lines = obsidianMarkdown.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
int firstLine = Array.FindIndex(lines, _LineDelimiterPredicate);
int secondLine = Array.FindIndex(lines, firstLine + 1, _LineDelimiterPredicate);
if (firstLine is not 0 || secondLine is -1)
{
return (null, obsidianMarkdown);
}
string frontMatter = string.Join(Environment.NewLine, lines[1..secondLine]);
string content = string.Join(Environment.NewLine, lines[(secondLine + 1)..]);
return (frontMatter, content);
// The front matter is a YAML document at the beginning of the file, delimited by three dashes.
static bool _LineDelimiterPredicate(string line) => line is "---";
}
/// <summary>
/// Parses a YAML front matter into a dictionary of key-value pairs.
/// </summary>
/// <param name="frontMatter">The YAML front matter to parse.</param>
/// <returns>A dictionary of key-value pairs.</returns>
/// <exception cref="YamlException">Thrown when the YAML front matter is invalid.</exception>
public static Dictionary<string, object> ParseYamlFrontMatter(string frontMatter) => YamlDeserializer.Deserialize<Dictionary<string, object>>(frontMatter);
private static void TrimBom(scoped ref string text)
{
if (text[0] is '\uFEFF')
{
text = text[1..];
}
}
/// <summary>
/// Splits the specified string by newlines, handling first \r\n, then \r, then \n.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string[] SplitByNewline(ReadOnlySpan<char> input)
{
List<string> result = [];
int previousIndex = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] is '\n' || (input[i] is '\r' && (i == input.Length - 1 || input[i + 1] is not '\n')))
{
result.Add(input[previousIndex..i].ToString());
previousIndex = i + 1;
}
else if (input[i] is '\r' && i < input.Length - 1 && input[i + 1] is '\n')
{
result.Add(input[previousIndex..i].ToString());
previousIndex = i + 2;
i++;
}
}
if (previousIndex < input.Length)
{
result.Add(input[previousIndex..].ToString());
}
return [..result];
}
}