/// <summary> /// Sorts the text within the specified text selection. /// </summary> /// <param name="textSelection">The text selection.</param> private void SortText(TextSelection textSelection) { // If the selection has no length, try to pick up the next line. if (textSelection.IsEmpty) { textSelection.LineDown(true); textSelection.EndOfLine(true); } // Start of selection should always be at the beginning of the line. var start = textSelection.TopPoint.CreateEditPoint(); start.StartOfLine(); // End of selection should always be at the start of the following line (i.e. extend past the last line's newline character). var end = textSelection.BottomPoint.CreateEditPoint(); if (!end.AtStartOfLine) { end.EndOfLine(); end.CharRight(); } // Capture the selected text. var selectedText = start.GetText(end); // Create the sorted text lines. var splitText = selectedText.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var orderedText = splitText.OrderBy(x => x); var sb = new StringBuilder(); foreach (var line in orderedText) { sb.AppendLine(line); } var sortedText = sb.ToString(); // If the selected and sorted text do not match, delete and insert the replacement. if (!selectedText.Equals(sortedText, StringComparison.CurrentCulture)) { start.Delete(end); var insertCursor = start.CreateEditPoint(); insertCursor.Insert(sortedText); textSelection.MoveToPoint(start, false); textSelection.MoveToPoint(insertCursor, true); } }