Skip to content

Commit

Permalink
feat(ObsidianText): Add SplitByNewline method
Browse files Browse the repository at this point in the history
This commit adds a new method `SplitByNewline` to the `ObsidianText` class. This method splits a specified string by newlines, handling different newline characters (`\r\n`, `\r`, `\n`). It returns an array of strings representing the split lines.

The purpose of this change is to improve the handling of line splitting in the `ObsidianText` class, providing more flexibility and compatibility with different newline formats.
  • Loading branch information
SakuraIsayeki committed Aug 5, 2023
1 parent e412b4c commit 6602e7e
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions Nodsoft.MoltenObsidian/ObsidianText.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Nodsoft.MoltenObsidian.Converter;
using System.Text;
using Nodsoft.MoltenObsidian.Converter;
using Nodsoft.MoltenObsidian.Vault;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
Expand Down Expand Up @@ -100,7 +101,9 @@ private static (string? frontMatter, string content) SplitYamlFrontMatter(string
// 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 = obsidianMarkdown.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

string[] lines = SplitByNewline(obsidianMarkdown);
// string[] lines = obsidianMarkdown.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
TrimBom(ref lines[0]);

int firstLine = Array.FindIndex(lines, _LineDelimiterPredicate);
Expand Down Expand Up @@ -135,4 +138,39 @@ private static void TrimBom(scoped ref string text)
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)
{
var result = new List<string>();

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.ToArray();
}
}

0 comments on commit 6602e7e

Please sign in to comment.