Skip to content
This repository was archived by the owner on Dec 21, 2023. It is now read-only.
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 17 additions & 25 deletions OpenTabletDriver.Web/TagHelpers/CodeBlockTagHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
Expand Down Expand Up @@ -29,42 +27,36 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu
output.Content.SetHtmlContent(code);
}

private string TrimPreceding(string value, char character)
private static string TrimPreceding(string value, char character)
{
var lines = value.Split(Environment.NewLine);
var preceding = CountPreceding(lines, character);
var trimmedLines = from line in lines
select TrimPrecedingLine(line, character, preceding);
for (var i = 0; i < lines.Length; ++i)
{
var line = lines[i];
lines[i] = line.Length >= preceding ? line[preceding..] : string.Empty;
}

return string.Join(Environment.NewLine, trimmedLines);
return string.Join(Environment.NewLine, lines);
}

private int CountPreceding(IEnumerable<string> lines, char leadingCharacter)
private static int CountPreceding(string[] lines, char leadingCharacter)
{
var min = int.MaxValue;
foreach (var line in lines)
{
// Make sure that the line actually starts with the leading character
if (line.StartsWith(leadingCharacter) == false)
continue;

// Determine last index of leading character, return if something else is found
for (var i = 0; i < line.Length; i++)
var lineSpan = line.AsSpan();
for (var i = 0; i < lineSpan.Length; ++i)
{
var character = line[i];
if (character != leadingCharacter)
return i;
if (lineSpan[i] != leadingCharacter)
{
min = i < min ? i : min;
break;
}
}

// Assume that this line is the template for trimming
return line.Length;
}

throw new ArgumentException("No lines match the target leading character.", nameof(lines));
}

private string TrimPrecedingLine(string line, char character, int amount)
{
return line.StartsWith(character) ? new string(line.Skip(amount).ToArray()) : line;
return min;
}
}
}