using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Windows; namespace Utils { public class CopyFormatter { Literal [][] matrix; public void FormatFromClipBoard() { try { string clipboardText = Clipboard.GetText(TextDataFormat.Text); BuildMatrx(clipboardText); CalculateTabs(); string sReformatedText = ReformatText(); Clipboard.SetText(sReformatedText); } catch( Exception e) { } } private string ReformatText() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < matrix.Length; i++) { for (int j = 0; j < matrix[0].Length; j++) { sb.Append(matrix[i][j].StringWithTabs()); } sb.AppendLine(); } return sb.ToString(); } private void CalculateTabs() { for (int j = 0; j < matrix[0].Length; j++) { //scan vertically all first elements, all second elements to get longest token for each column ReferenceInt maxChars = new ReferenceInt(); for (int i = 0; i < matrix.Length; i++) { maxChars.LocalInt = maxChars.LocalInt > matrix[i][j].Length ? maxChars.LocalInt : matrix[i][j].Length; maxChars.ContainsPeriod = matrix[i][j].text.Contains('.') ? true : maxChars.ContainsPeriod; matrix[i][j].MaxCharCount = maxChars; } } } private void BuildMatrx(string clipboardText) { string[] arr = clipboardText.Split(new string[] { "\r\n" }, StringSplitOptions.None); if (arr != null && arr.Length > 0) { //number of lines matrix = new Literal[arr.Length][]; List<string[]> lst = new List<string[]>(); int maxlen = 0; Array.ForEach(arr, line => { string[] l = line.Split(new char[] { '\t' }, StringSplitOptions.None); lst.Add(l); maxlen = l.Length > maxlen ? l.Length : maxlen; }); if (maxlen > 0) { int i = 0; lst.ForEach(line => { matrix[i] = new Literal[maxlen]; int j = 0; Array.ForEach(line, token => { matrix[i][j++] = new Literal(token); }); for(; j < maxlen; j++) { matrix[i][j] = new Literal(string.Empty); } i++; }); } } } } private class Literal { public Literal(string token) { text = token; } public string text { get; set; } = string.Empty; public int Length { get { return text.Length; } } public ReferenceInt MaxCharCount { get; set; } public string StringWithTabs() { int tabSize = 5; int numberOfFlights = MaxCharCount.LocalInt / tabSize; int currWordFlights = Length / tabSize; int totalTabs = numberOfFlights - currWordFlights + 1; string s = new String('\t', totalTabs); return text + s; } } private class ReferenceInt { public int LocalInt { get; set; } = 0; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)