|
| 1 | +namespace MarkdownOut { |
| 2 | + |
| 3 | + /// <summary> |
| 4 | + /// A container for extension methods related to Markdown styling and formatting. |
| 5 | + /// </summary> |
| 6 | + public static class MdExtensions { |
| 7 | + |
| 8 | + /// <summary> |
| 9 | + /// Styles one or more substrings of the provided string using the specified |
| 10 | + /// <see cref="MdStyle"/>. |
| 11 | + /// </summary> |
| 12 | + /// <param name="str">The string containing the substring to style.</param> |
| 13 | + /// <param name="substring">The substring to style.</param> |
| 14 | + /// <param name="style">The Markdown style to apply.</param> |
| 15 | + /// <param name="firstOnly"> |
| 16 | + /// If true, only the first occurrence of the substring is styled; otherwise, all |
| 17 | + /// occurrences of the substring are styled. |
| 18 | + /// </param> |
| 19 | + /// <returns> |
| 20 | + /// The selectively styled string. If <paramref name="str"/> does not contain any |
| 21 | + /// occurrences of <paramref name="substring"/>, it is returned unchanged. |
| 22 | + /// </returns> |
| 23 | + [System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "<Pending>")] |
| 24 | + public static string StyleSubstring(this string str, string substring, MdStyle style, |
| 25 | + bool firstOnly = false) { |
| 26 | + if (string.IsNullOrEmpty(str)) |
| 27 | + { |
| 28 | + throw new System.ArgumentException("cannot stylize empty string", nameof(str)); |
| 29 | + } |
| 30 | + |
| 31 | + if (string.IsNullOrEmpty(substring)) |
| 32 | + { |
| 33 | + throw new System.ArgumentException("cannot stylize empty string", nameof(str)); |
| 34 | + } |
| 35 | + |
| 36 | + if (!firstOnly) { |
| 37 | + return str?.Replace(substring, MdText.Style(substring, style), System.StringComparison.Ordinal); |
| 38 | + } |
| 39 | + int pos = str.IndexOf(substring, System.StringComparison.Ordinal); |
| 40 | + if (pos < 0) { |
| 41 | + return str; |
| 42 | + } |
| 43 | + return str.Substring(0, pos) + MdText.Style(substring, style) |
| 44 | + + str.Substring(pos + substring.Length); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments