|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using CommandLine.Infrastructure; |
| 6 | + |
| 7 | +namespace CommandLine.Text |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// A utility class to word-wrap and indent blocks of text |
| 11 | + /// </summary> |
| 12 | + public class TextWrapper |
| 13 | + { |
| 14 | + private string[] lines; |
| 15 | + public TextWrapper(string input) |
| 16 | + { |
| 17 | + //start by splitting at newlines and then reinserting the newline as a separate word |
| 18 | + //Note that on the input side, we can't assume the line-break style at run time so we have to |
| 19 | + //be able to handle both. We can't use Environment.NewLine because that changes at |
| 20 | + //_runtime_ and may not match the line-break style that was compiled in |
| 21 | + lines = input |
| 22 | + .Replace("\r","") |
| 23 | + .Split(new[] {'\n'}, StringSplitOptions.None); |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Splits a string into a words and performs wrapping while also preserving line-breaks and sub-indentation |
| 28 | + /// </summary> |
| 29 | + /// <param name="columnWidth">The number of characters we can use for text</param> |
| 30 | + /// <remarks> |
| 31 | + /// This method attempts to wrap text without breaking words |
| 32 | + /// For example, if columnWidth is 10 , the input |
| 33 | + /// "a string for wrapping 01234567890123" |
| 34 | + /// would return |
| 35 | + /// "a string |
| 36 | + /// "for |
| 37 | + /// "wrapping |
| 38 | + /// "0123456789 |
| 39 | + /// "0123" |
| 40 | + /// </remarks> |
| 41 | + /// <returns>this</returns> |
| 42 | + public TextWrapper WordWrap(int columnWidth) |
| 43 | + { |
| 44 | + //ensure we always use at least 1 column even if the client has told us there's no space available |
| 45 | + columnWidth = Math.Max(1, columnWidth); |
| 46 | + lines= lines |
| 47 | + .SelectMany(line => WordWrapLine(line, columnWidth)) |
| 48 | + .ToArray(); |
| 49 | + return this; |
| 50 | + } |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// Indent all lines in the TextWrapper by the desired number of spaces |
| 54 | + /// </summary> |
| 55 | + /// <param name="numberOfSpaces">The number of spaces to indent by</param> |
| 56 | + /// <returns>this</returns> |
| 57 | + public TextWrapper Indent(int numberOfSpaces) |
| 58 | + { |
| 59 | + lines = lines |
| 60 | + .Select(line => numberOfSpaces.Spaces() + line) |
| 61 | + .ToArray(); |
| 62 | + return this; |
| 63 | + } |
| 64 | + |
| 65 | + /// <summary> |
| 66 | + /// Returns the current state of the TextWrapper as a string |
| 67 | + /// </summary> |
| 68 | + /// <returns></returns> |
| 69 | + public string ToText() |
| 70 | + { |
| 71 | + //return the whole thing as a single string |
| 72 | + return string.Join(Environment.NewLine,lines); |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Convenience method to wraps and indent a string in a single operation |
| 77 | + /// </summary> |
| 78 | + /// <param name="input">The string to operate on</param> |
| 79 | + /// <param name="indentLevel">The number of spaces to indent by</param> |
| 80 | + /// <param name="columnWidth">The width of the column used for wrapping</param> |
| 81 | + /// <remarks> |
| 82 | + /// The string is wrapped _then_ indented so the columnWidth is the width of the |
| 83 | + /// usable text block, and does NOT include the indentLevel. |
| 84 | + /// </remarks> |
| 85 | + /// <returns>the processed string</returns> |
| 86 | + public static string WrapAndIndentText(string input, int indentLevel,int columnWidth) |
| 87 | + { |
| 88 | + return new TextWrapper(input) |
| 89 | + .WordWrap(columnWidth) |
| 90 | + .Indent(indentLevel) |
| 91 | + .ToText(); |
| 92 | + } |
| 93 | + |
| 94 | + |
| 95 | + private string [] WordWrapLine(string line,int columnWidth) |
| 96 | + { |
| 97 | + //create a list of individual lines generated from the supplied line |
| 98 | + |
| 99 | + //When handling sub-indentation we must always reserve at least one column for text! |
| 100 | + var unindentedLine = line.TrimStart(); |
| 101 | + var currentIndentLevel = Math.Min(line.Length - unindentedLine.Length,columnWidth-1) ; |
| 102 | + columnWidth -= currentIndentLevel; |
| 103 | + |
| 104 | + return unindentedLine.Split(' ') |
| 105 | + .Aggregate( |
| 106 | + new List<StringBuilder>(), |
| 107 | + (lineList, word) => AddWordToLastLineOrCreateNewLineIfNecessary(lineList, word, columnWidth) |
| 108 | + ) |
| 109 | + .Select(builder => currentIndentLevel.Spaces()+builder.ToString().TrimEnd()) |
| 110 | + .ToArray(); |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// When presented with a word, either append to the last line in the list or start a new line |
| 115 | + /// </summary> |
| 116 | + /// <param name="lines">A list of StringBuilders containing results so far</param> |
| 117 | + /// <param name="word">The individual word to append</param> |
| 118 | + /// <param name="columnWidth">The usable text space</param> |
| 119 | + /// <remarks> |
| 120 | + /// The 'word' can actually be an empty string. It's important to keep these - |
| 121 | + /// empty strings allow us to preserve indentation and extra spaces within a line. |
| 122 | + /// </remarks> |
| 123 | + /// <returns>The same list as is passed in</returns> |
| 124 | + private static List<StringBuilder> AddWordToLastLineOrCreateNewLineIfNecessary(List<StringBuilder> lines, string word,int columnWidth) |
| 125 | + { |
| 126 | + //The current indentation level is based on the previous line but we need to be careful |
| 127 | + var previousLine = lines.LastOrDefault()?.ToString() ??string.Empty; |
| 128 | + |
| 129 | + var wouldWrap = !lines.Any() || (word.Length>0 && previousLine.Length + word.Length > columnWidth); |
| 130 | + |
| 131 | + if (!wouldWrap) |
| 132 | + { |
| 133 | + //The usual case is we just append the 'word' and a space to the current line |
| 134 | + //Note that trailing spaces will get removed later when we turn the line list |
| 135 | + //into a single string |
| 136 | + lines.Last().Append(word + ' '); |
| 137 | + } |
| 138 | + else |
| 139 | + { |
| 140 | + //The 'while' here is to take account of the possibility of someone providing a word |
| 141 | + //which just can't fit in the current column. In that case we just split it at the |
| 142 | + //column end. |
| 143 | + //That's a rare case though - most of the time we'll succeed in a single pass without |
| 144 | + //having to split |
| 145 | + //Note that we always do at least one pass even if the 'word' is empty in order to |
| 146 | + //honour sub-indentation and extra spaces within strings |
| 147 | + do |
| 148 | + { |
| 149 | + var availableCharacters = Math.Min(columnWidth, word.Length); |
| 150 | + var segmentToAdd = LeftString(word,availableCharacters) + ' '; |
| 151 | + lines.Add(new StringBuilder(segmentToAdd)); |
| 152 | + word = RightString(word,availableCharacters); |
| 153 | + } while (word.Length > 0); |
| 154 | + } |
| 155 | + return lines; |
| 156 | + } |
| 157 | + |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Return the right part of a string in a way that compensates for Substring's deficiencies |
| 161 | + /// </summary> |
| 162 | + private static string RightString(string str,int n) |
| 163 | + { |
| 164 | + return (n >= str.Length || str.Length==0) |
| 165 | + ? string.Empty |
| 166 | + : str.Substring(n); |
| 167 | + } |
| 168 | + /// <summary> |
| 169 | + /// Return the left part of a string in a way that compensates for Substring's deficiencies |
| 170 | + /// </summary> |
| 171 | + private static string LeftString(string str,int n) |
| 172 | + { |
| 173 | + |
| 174 | + return (n >= str.Length || str.Length==0) |
| 175 | + ? str |
| 176 | + : str.Substring(0,n); |
| 177 | + } |
| 178 | + } |
| 179 | +} |
0 commit comments