Skip to content

Instantly share code, notes, and snippets.

@GSonofNun
Created May 9, 2023 19:37
Show Gist options
  • Save GSonofNun/f5a97b24bb9d57c06c723a7bc02940a0 to your computer and use it in GitHub Desktop.
Save GSonofNun/f5a97b24bb9d57c06c723a7bc02940a0 to your computer and use it in GitHub Desktop.
public class CsvHighlightingRule : IHighlightingRule
{
private readonly int _headerRowsCount;
private int _counter;
private SimpleHighlightingBrush[] _colors;
private int _currentLineNumber;
private List<RuleMatch> _matchesForCurrentLine = new List<RuleMatch>();
public CsvHighlightingRule(
string delimiter,
int headerRowsCount
)
{
Delimiter = delimiter;
_headerRowsCount = headerRowsCount;
var themeBrushes = ThemeService.Current.ActualCurrentTheme == ThemeService.Theme.Dark
? ThemeColors.DarkThemeFontBrushes
: ThemeColors.LightThemeFontBrushes;
_colors = new SimpleHighlightingBrush[themeBrushes.Length];
for (int i = 0; i < themeBrushes.Length; i++)
{
_colors[i] = new SimpleHighlightingBrush(themeBrushes[i].Color);
}
}
public HighlightingColor Color
{
get
{
var highlightInfo = new HighlightingColor();
highlightInfo.Foreground = _colors[_counter++ % _colors.Length];
if (_currentLineNumber <= _headerRowsCount)
{
highlightInfo.FontWeight = FontWeights.Bold;
highlightInfo.Underline = _currentLineNumber == _headerRowsCount;
}
return highlightInfo;
}
}
public string RuleInfo => $"Delimiter: \"{Delimiter}\"";
public bool CombineConsecutiveDelimiters { get; set; }
public string Delimiter { get; }
public RuleMatch? GetMatch(string input, int beginning, int length, int lineNumber)
{
if (lineNumber != _currentLineNumber)
{
_counter = 0;
_currentLineNumber = lineNumber;
_matchesForCurrentLine.Clear();
if (DsvConverter.TryGetDelimiterMatches(input, out var result, Delimiter)) // Custom code that returns list of locations of the delimiter instances in the line
{
var matches = result.Value.matches;
for (int i = 0; i < matches.Count; i++)
{
var valueStartIndex = i == 0 ? 0 : matches[i - 1].Index + matches[i - 1].Length;
var value = new RuleMatch()
{
Success = true,
Index = valueStartIndex,
Length = matches[i].Index - valueStartIndex + matches[i].Length,
};
_matchesForCurrentLine.Add(value);
}
// Add the final value, which occurs after the final delimiter (or, if there is only one value, that value)
var finalValue = new RuleMatch()
{
Success = true,
Index = matches[^1].Index + matches[^1].Length,
Length = input.Length - matches[^1].Index - matches[^1].Length,
};
_matchesForCurrentLine.Add(finalValue);
}
}
return _matchesForCurrentLine.FirstOrDefault(x => x.Index == beginning) ?? new RuleMatch();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment