Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [ActionHandler("PasteCSV")]
- public class PasteCSV : IActionHandler
- {
- private readonly ActionManager actionManager;
- public PasteCSV(ActionManager actionManager)
- {
- this.actionManager = actionManager;
- }
- public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
- {
- return Clipboard.ContainsText(TextDataFormat.CommaSeparatedValue) &&
- context.GetData(JetBrains.TextControl.DataContext.DataConstants.TEXT_CONTROL) != null;
- }
- public void Execute(IDataContext context, DelegateExecute nextExecute)
- {
- var csv = Clipboard.GetText(TextDataFormat.CommaSeparatedValue);
- var textControl = context.GetData(JetBrains.TextControl.DataContext.DataConstants.TEXT_CONTROL);
- if (!string.IsNullOrWhiteSpace(csv))
- {
- var sb = new StringBuilder();
- var lines = csv.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
- int rows = lines.Length;
- int cols = lines[0].Split(',').Length;
- if (IsAllDataNumeric(lines))
- {
- if (rows == 1 || cols == 1)
- {
- sb.AppendFormat("double[] foo = {{ {0} }};",
- rows == 1 ? lines[0] : lines.Join(","));
- }
- else
- {
- sb.Append("double[,] foo = {").AppendLine();
- foreach (var line in lines)
- sb.AppendFormat("{{ {0} }},", line).AppendLine();
- sb.Append("};");
- }
- }
- else
- {
- if (rows == 1 || cols == 1)
- {
- var data = rows == 1 ? lines[0].Split(',') : lines.ToArray();
- sb.AppendFormat("var foo = Tuple.Create({0});", data.Select(FormatForType).Join(","));
- } else
- {
- sb.Append("var foo = new[] {").AppendLine();
- foreach (var line in lines)
- sb.Append("Tuple.Create(").Append(line.Split(',').Select(FormatForType).Join(",")).Append("),");
- sb.Append("};");
- }
- }
- var doc = textControl.Document;
- var pos = textControl.Caret.Position;
- doc.InsertText(pos.Value.ToDocOffset(), sb.ToString());
- }
- }
- public string FormatForType(string input)
- {
- DateTime dt;
- double d;
- if (DateTime.TryParse(input, out dt))
- return dt.ToAssemblyCode();
- else if (double.TryParse(input, out d))
- return input;
- else return input.Quoted();
- }
- public bool IsAllDataNumeric(string[] lines)
- {
- double dummy;
- return lines.SelectMany(line => line.Split(','))
- .All(element => double.TryParse(element, out dummy));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement