-
Notifications
You must be signed in to change notification settings - Fork 393
/
Extensions.cs
1011 lines (848 loc) · 32.7 KB
/
Extensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Media;
using EditorUtils;
using EnvDTE;
using Microsoft.FSharp.Core;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Vim;
using Vim.Extensions;
using Command = EnvDTE.Command;
namespace VsVim
{
public static class Extensions
{
#region Command
/// <summary>
/// Get the binding strings for this Command. Digs through the various ways a
/// binding string can be stored and returns a uniform result
/// </summary>
public static IEnumerable<string> GetBindings(this Command command)
{
if (null == command)
{
throw new ArgumentException("command");
}
object bindings;
try
{
bindings = command.Bindings;
}
catch (Exception)
{
// Several user reports indicate the above call can throw. Most commonly
// this throws an OutOfMemoryException. Either way we don't care what the
// error is. We just can't get bindings for this element
return Enumerable.Empty<string>();
}
var bindingsArray = bindings as object[];
if (bindingsArray != null)
{
return bindingsArray
.Where(x => x is string)
.Cast<string>()
.Where(x => !String.IsNullOrEmpty(x));
}
var singleBinding = bindings as string;
if (singleBinding != null)
{
return Enumerable.Repeat(singleBinding, 1);
}
return Enumerable.Empty<string>();
}
/// <summary>
/// Get the binding strings in the form of CommandKeyBinding instances
/// </summary>
public static IEnumerable<CommandKeyBinding> GetCommandKeyBindings(this Command command)
{
if (null == command)
{
throw new ArgumentNullException("command");
}
// Need a helper method here so that the argument checking is prompt
return GetCommandKeyBindingsHelper(command);
}
private static IEnumerable<CommandKeyBinding> GetCommandKeyBindingsHelper(Command command)
{
foreach (var cur in command.GetBindings())
{
KeyBinding binding;
if (KeyBinding.TryParse(cur, out binding))
{
yield return new CommandKeyBinding(command.Name, binding);
}
}
}
public static IEnumerable<KeyBinding> GetKeyBindings(this Command command)
{
return GetCommandKeyBindings(command).Select(x => x.KeyBinding);
}
/// <summary>
/// Does the Command have the provided KeyBinding as a valid binding
/// </summary>
public static bool HasKeyBinding(this Command command, KeyBinding binding)
{
return GetCommandKeyBindings(command).Any(x => x.KeyBinding == binding);
}
/// <summary>
/// Remove all bindings on the provided Command value
/// </summary>
/// <param name="command"></param>
public static void SafeResetBindings(this Command command)
{
try
{
command.Bindings = new object[] { };
}
catch (COMException)
{
// Several implementations, Transact SQL in particular, return E_FAIL for this
// operation. Simply ignore the failure and continue
}
}
/// <summary>
/// Safely reset the bindings on this Command to the provided KeyBinding value
/// </summary>
public static void SafeSetBindings(this Command command, KeyBinding binding)
{
SafeSetBindings(command, new[] { binding.CommandString });
}
/// <summary>
/// Safely reset the bindings on this Command to the provided KeyBinding value
/// </summary>
public static void SafeSetBindings(this Command command, IEnumerable<string> commandBindings)
{
try
{
var bindings = commandBindings.Cast<object>().ToArray();
command.Bindings = bindings;
}
catch (COMException)
{
// Several implementations, Transact SQL in particular, return E_FAIL for this
// operation. Simply ignore the failure and continue
}
}
#endregion
#region Commands
public static IEnumerable<Command> GetCommands(this Commands commands)
{
return commands.Cast<Command>();
}
#endregion
#region IVsTextLines
/// <summary>
/// Get the file name of the presented view. If the name cannot be discovered an empty string will be returned
/// </summary>
public static string GetFileName(this IVsTextLines lines)
{
try
{
// GUID_VsBufferMoniker
var monikerId = Constants.VsUserDataFileNameMoniker;
var userData = (IVsUserData)lines;
object data;
if (VSConstants.S_OK != userData.GetData(ref monikerId, out data)
|| String.IsNullOrEmpty(data as string))
{
return String.Empty;
}
return (string)data;
}
catch (InvalidCastException)
{
return String.Empty;
}
}
public static Result<IVsEnumLineMarkers> GetLineMarkersEnum(this IVsTextLines lines, TextSpan span)
{
IVsEnumLineMarkers markers;
var hresult = lines.EnumMarkers(span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, 0, (uint)ENUMMARKERFLAGS.EM_ALLTYPES, out markers);
return Result.CreateSuccessOrError(markers, hresult);
}
public static List<IVsTextLineMarker> GetLineMarkers(this IVsTextLines lines, TextSpan span)
{
var markers = GetLineMarkersEnum(lines, span);
return markers.IsSuccess
? markers.Value.GetAll()
: new List<IVsTextLineMarker>();
}
#endregion
#region IVsTextView
public static Result<IVsTextLines> GetTextLines(this IVsTextView textView)
{
IVsTextLines textLines;
var hresult = textView.GetBuffer(out textLines);
return Result.CreateSuccessOrError(textLines, hresult);
}
public static Result<IVsWindowFrame> GetWindowFrame(this IVsTextView textView)
{
var textViewEx = textView as IVsTextViewEx;
if (textViewEx == null)
{
return Result.Error;
}
return textViewEx.GetWindowFrame();
}
#endregion
#region IVsTextViewEx
public static Result<IVsWindowFrame> GetWindowFrame(this IVsTextViewEx textViewEx)
{
object frame;
if (!ErrorHandler.Succeeded(textViewEx.GetWindowFrame(out frame)))
{
return Result.Error;
}
var vsWindowFrame = frame as IVsWindowFrame;
if (vsWindowFrame == null)
{
return Result.Error;
}
return Result.CreateSuccess(vsWindowFrame);
}
#endregion
#region IVsShell
internal static bool IsPackageInstalled(this IVsShell vsShell, Guid packageId)
{
int isInstalled;
return ErrorHandler.Succeeded(vsShell.IsPackageInstalled(ref packageId, out isInstalled)) && 1 == isInstalled;
}
#endregion
#region IVsUIShell
private sealed class ModelessUtil : IDisposable
{
private readonly IVsUIShell _vsShell;
internal ModelessUtil(IVsUIShell vsShell)
{
_vsShell = vsShell;
vsShell.EnableModeless(0);
}
public void Dispose()
{
_vsShell.EnableModeless(-1);
}
}
public static IDisposable EnableModelessDialog(this IVsUIShell vsShell)
{
return new ModelessUtil(vsShell);
}
public static Result<List<IVsWindowFrame>> GetDocumentWindowFrames(this IVsUIShell vsShell)
{
IEnumWindowFrames enumFrames;
var hr = vsShell.GetDocumentWindowEnum(out enumFrames);
return ErrorHandler.Failed(hr) ? Result.CreateError(hr) : enumFrames.GetContents();
}
public static Result<List<IVsWindowFrame>> GetDocumentWindowFrames(this IVsUIShell4 vsShell, __WindowFrameTypeFlags flags)
{
IEnumWindowFrames enumFrames;
var hr = vsShell.GetWindowEnum((uint)flags, out enumFrames);
return ErrorHandler.Failed(hr) ? Result.CreateError(hr) : enumFrames.GetContents();
}
#endregion
#region IEnumWindowFrames
public static Result<List<IVsWindowFrame>> GetContents(this IEnumWindowFrames enumFrames)
{
var list = new List<IVsWindowFrame>();
var array = new IVsWindowFrame[16];
while (true)
{
uint num;
var hr = enumFrames.Next((uint)array.Length, array, out num);
if (ErrorHandler.Failed(hr))
{
return Result.CreateError(hr);
}
if (0 == num)
{
return list;
}
for (var i = 0; i < num; i++)
{
list.Add(array[i]);
}
}
}
#endregion
#region IVsCodeWindow
/// <summary>
/// Get the primary view of the code window. Is actually the one on bottom
/// </summary>
public static Result<IVsTextView> GetPrimaryView(this IVsCodeWindow vsCodeWindow)
{
IVsTextView vsTextView;
var hr = vsCodeWindow.GetPrimaryView(out vsTextView);
if (ErrorHandler.Failed(hr))
{
return Result.CreateError(hr);
}
return Result.CreateSuccessNonNull(vsTextView);
}
/// <summary>
/// Get the primary view of the code window. Is actually the one on bottom
/// </summary>
public static Result<IWpfTextView> GetPrimaryTextView(this IVsCodeWindow codeWindow, IVsEditorAdaptersFactoryService factoryService)
{
var result = GetPrimaryView(codeWindow);
if (result.IsError)
{
return Result.CreateError(result.HResult);
}
var textView = factoryService.GetWpfTextView(result.Value);
return Result.CreateSuccessNonNull(textView);
}
/// <summary>
/// Is this window currently in a split mode?
/// </summary>
public static bool IsSplit(this IVsCodeWindow vsCodeWindow)
{
return
vsCodeWindow.GetPrimaryView().IsSuccess &&
vsCodeWindow.GetSecondaryView().IsSuccess;
}
/// <summary>
/// Get the secondary view of the code window. Is actually the one on top
/// </summary>
public static Result<IWpfTextView> GetSecondaryTextView(this IVsCodeWindow codeWindow, IVsEditorAdaptersFactoryService factoryService)
{
var result = GetSecondaryView(codeWindow);
if (result.IsError)
{
return Result.CreateError(result.HResult);
}
var textView = factoryService.GetWpfTextView(result.Value);
return Result.CreateSuccessNonNull(textView);
}
/// <summary>
/// Get the secondary view of the code window. Is actually the one on top
/// </summary>
public static Result<IVsTextView> GetSecondaryView(this IVsCodeWindow vsCodeWindow)
{
IVsTextView vsTextView;
var hr = vsCodeWindow.GetSecondaryView(out vsTextView);
if (ErrorHandler.Failed(hr))
{
return Result.CreateError(hr);
}
return Result.CreateSuccessNonNull(vsTextView);
}
#endregion
#region IVsWindowFrame
public static Result<IVsCodeWindow> GetCodeWindow(this IVsWindowFrame vsWindowFrame)
{
var iid = typeof(IVsCodeWindow).GUID;
var ptr = IntPtr.Zero;
try
{
ErrorHandler.ThrowOnFailure(vsWindowFrame.QueryViewInterface(ref iid, out ptr));
return Result.CreateSuccess((IVsCodeWindow)Marshal.GetObjectForIUnknown(ptr));
}
catch (Exception e)
{
// Venus will throw when querying for the code window
return Result.CreateError(e);
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.Release(ptr);
}
}
}
public static Result<IVsTextLines> GetTextLines(this IVsWindowFrame vsWindowFrame)
{
try
{
var vsCodeWindow = vsWindowFrame.GetCodeWindow().Value;
IVsTextLines vsTextLines;
ErrorHandler.ThrowOnFailure(vsCodeWindow.GetBuffer(out vsTextLines));
if (vsTextLines == null)
{
return Result.Error;
}
return Result.CreateSuccess(vsTextLines);
}
catch (Exception ex)
{
return Result.CreateError(ex);
}
}
public static Result<ITextBuffer> GetTextBuffer(this IVsWindowFrame vsWindowFrame, IVsEditorAdaptersFactoryService factoryService)
{
var result = GetTextLines(vsWindowFrame);
if (result.IsError)
{
return Result.CreateError(result.HResult);
}
var vsTextLines = result.Value;
var textBuffer = factoryService.GetDocumentBuffer(vsTextLines);
if (textBuffer == null)
{
return Result.Error;
}
return Result.CreateSuccess(textBuffer);
}
/// <summary>
/// IVsWindowFrame which contains this IVsWindowFrame. They are allowed to nested arbitrarily
/// </summary>
public static bool TryGetParent(this IVsWindowFrame vsWindowFrame, out IVsWindowFrame parentWindowFrame)
{
try
{
object parentObj;
int hresult = vsWindowFrame.GetProperty((int)__VSFPROPID2.VSFPROPID_ParentFrame, out parentObj);
if (!ErrorHandler.Succeeded(hresult))
{
parentWindowFrame = null;
return false;
}
parentWindowFrame = parentObj as IVsWindowFrame;
return parentWindowFrame != null;
}
catch (Exception)
{
parentWindowFrame = null;
return false;
}
}
/// <summary>
/// IVsWindowFrame instances can nest within each other. This method will get the top most IVsWindowFrame
/// in the nesting
/// </summary>
public static IVsWindowFrame GetTopMost(this IVsWindowFrame vsWindowFrame)
{
IVsWindowFrame parent;
if (vsWindowFrame.TryGetParent(out parent))
{
return GetTopMost(parent);
}
return vsWindowFrame;
}
#endregion
#region IVsTextManager
public static Tuple<bool, IWpfTextView> TryGetActiveTextView(this IVsTextManager vsTextManager, IVsEditorAdaptersFactoryService factoryService)
{
IVsTextView vsTextView;
IWpfTextView textView = null;
if (ErrorHandler.Succeeded(vsTextManager.GetActiveView(0, null, out vsTextView)) && vsTextView != null)
{
textView = factoryService.GetWpfTextView(vsTextView);
}
return Tuple.Create(textView != null, textView);
}
#endregion
#region IVsEnumLineMarkers
/// <summary>
/// Don't be tempted to make this an IEnumerable because multiple calls would not
/// produce multiple enumerations since the parameter would need to be reset
/// </summary>
public static List<IVsTextLineMarker> GetAll(this IVsEnumLineMarkers markers)
{
var list = new List<IVsTextLineMarker>();
do
{
IVsTextLineMarker marker;
var hresult = markers.Next(out marker);
if (ErrorHandler.Succeeded(hresult) && marker != null)
{
list.Add(marker);
}
else
{
break;
}
} while (true);
return list;
}
#endregion
#region IVsTextLineMarker
public static Result<TextSpan> GetCurrentSpan(this IVsTextLineMarker marker)
{
var array = new TextSpan[1];
var hresult = marker.GetCurrentSpan(array);
return Result.CreateSuccessOrError(array[0], hresult);
}
public static Result<SnapshotSpan> GetCurrentSpan(this IVsTextLineMarker marker, ITextSnapshot snapshot)
{
var span = GetCurrentSpan(marker);
return span.IsError ? Result.CreateError(span.HResult) : span.Value.ToSnapshotSpan(snapshot);
}
public static Result<MARKERTYPE> GetMarkerType(this IVsTextLineMarker marker)
{
int type;
var hresult = marker.GetType(out type);
return Result.CreateSuccessOrError((MARKERTYPE)type, hresult);
}
#endregion
#region IVsSnippetManager
#endregion
#region IVsMonitorSelection
public static Result<bool> IsCmdUIContextActive(this IVsMonitorSelection selection, Guid cmdId)
{
uint cookie;
var hresult = selection.GetCmdUIContextCookie(ref cmdId, out cookie);
if (ErrorHandler.Failed(hresult))
{
return Result.CreateError(hresult);
}
int active;
hresult = selection.IsCmdUIContextActive(cookie, out active);
return Result.CreateSuccessOrError(active != 0, hresult);
}
#endregion
#region IServiceProvider
public static TInterface GetService<TService, TInterface>(this System.IServiceProvider sp)
{
return (TInterface)sp.GetService(typeof(TService));
}
#endregion
#region IContentType
/// <summary>
/// Does this IContentType represent C++
/// </summary>
public static bool IsCPlusPlus(this IContentType ct)
{
return ct.IsOfType(Constants.CPlusPlusContentType);
}
/// <summary>
/// Does this IContentType represent C#
/// </summary>
public static bool IsCSharp(this IContentType ct)
{
return ct.IsOfType(Constants.CSharpContentType);
}
/// <summary>
/// Is this IContentType of any of the specified types
/// </summary>
public static bool IsOfAnyType(this IContentType contentType, IEnumerable<string> types)
{
foreach (var type in types)
{
if (contentType.IsOfType(type))
{
return true;
}
}
return false;
}
#endregion
#region IDisplayWindowBroker
/// <summary>
/// Are any of the standard displays currently active?
/// </summary>
public static bool IsAnyDisplayActive(this IDisplayWindowBroker displayWindowBroker)
{
return
displayWindowBroker.IsCompletionActive ||
displayWindowBroker.IsQuickInfoActive ||
displayWindowBroker.IsSignatureHelpActive ||
displayWindowBroker.IsSmartTagSessionActive;
}
#endregion
#region ITaggerProvider
/// <summary>
/// Creating an ITagger for an ITaggerProvider can fail in a number of ways. Wrap them
/// all up here
/// </summary>
public static Result<ITagger<T>> SafeCreateTagger<T>(this ITaggerProvider taggerProvider, ITextBuffer textbuffer)
where T : ITag
{
try
{
var tagger = taggerProvider.CreateTagger<T>(textbuffer);
if (tagger == null)
{
return Result.Error;
}
return Result.CreateSuccess(tagger);
}
catch (Exception e)
{
return Result.CreateError(e);
}
}
#endregion
#region ITextView
/// <summary>
/// This will return the SnapshotSpan values from the EditBuffer which are actually visible
/// on the screen.
/// </summary>
public static NormalizedSnapshotSpanCollection GetVisibleSnapshotSpans(this ITextView textView)
{
var bufferGraph = textView.BufferGraph;
var visualSnapshot = textView.VisualSnapshot;
var formattedSpan = textView.TextViewLines.GetFormattedSpan();
if (formattedSpan.IsError)
{
return new NormalizedSnapshotSpanCollection();
}
var visualSpans = bufferGraph.MapUpToSnapshot(formattedSpan.Value, SpanTrackingMode.EdgeExclusive, visualSnapshot);
if (visualSpans.Count != 1)
{
return visualSpans;
}
return bufferGraph.MapDownToSnapshot(visualSpans.Single(), SpanTrackingMode.EdgeExclusive, textView.TextSnapshot);
}
/// <summary>
/// Get the set of all visible SnapshotSpan values and potentially some collapsed / invisible
/// ones. It's common for users to have collapsed / invisible regions on the ITextView and
/// hence simply getting a single SnapshotSpan for the set of visible text could return a huge
/// span (potentially many, many thousands) of lines.
///
/// This method attempts to return the set of SnapshotSpan values which actually have visible
/// text associated with them.
/// </summary>
public static NormalizedSnapshotSpanCollection GetLikelyVisibleSnapshotSpans(this ITextView textView)
{
// Mapping up and down is potentially expensive so we don't want to do it unless we have to. Implement
// a heuristic to check for large sections of invisible text and if it's not present then just return
// the value which doesn't require allocations or deep calculations
var result = textView.TextViewLines.GetFormattedSpan();
if (result.IsError)
{
return new NormalizedSnapshotSpanCollection();
}
var formattedSpan = result.Value;
var formattedLength = formattedSpan.Length;
if (formattedLength / 2 <= textView.VisualSnapshot.Length)
{
return new NormalizedSnapshotSpanCollection(formattedSpan);
}
return GetVisibleSnapshotSpans(textView);
}
#endregion
#region ITextViewLineCollection
/// <summary>
/// Get the SnapshotSpan for the ITextViewLineCollection. This can throw when the ITextView is being
/// laid out so we wrap the try / catch here
/// </summary>
public static Result<SnapshotSpan> GetFormattedSpan(this ITextViewLineCollection collection)
{
try
{
return collection.FormattedSpan;
}
catch (Exception ex)
{
return Result.CreateError(ex);
}
}
#endregion
#region ITextSnapshot
public static Result<SnapshotSpan> ToSnapshotSpan(this TextSpan span, ITextSnapshot snapshot)
{
try
{
var start = snapshot.GetLineFromLineNumber(span.iStartLine).Start.Add(span.iStartIndex);
var end = snapshot.GetLineFromLineNumber(span.iEndLine).Start.Add(span.iEndIndex + 1);
return new SnapshotSpan(start, end);
}
catch (Exception ex)
{
return Result.CreateError(ex);
}
}
#endregion
#region SnapshotSpan
public static TextSpan ToTextSpan(this SnapshotSpan span)
{
var start = SnapshotPointUtil.GetLineColumn(span.Start);
var option = SnapshotSpanUtil.GetLastIncludedPoint(span);
var end = option.IsSome()
? SnapshotPointUtil.GetLineColumn(option.Value)
: start;
return new TextSpan
{
iStartLine = start.Item1,
iStartIndex = start.Item2,
iEndLine = end.Item1,
iEndIndex = end.Item2
};
}
public static Result<SnapshotSpan> SafeTranslateTo(this SnapshotSpan span, ITextSnapshot snapshot, SpanTrackingMode mode)
{
try
{
return span.TranslateTo(snapshot, mode);
}
catch (Exception ex)
{
return Result.CreateError(ex);
}
}
#endregion
#region SnapshotLineRange
public static TextSpan ToTextSpan(this SnapshotLineRange range)
{
return range.Extent.ToTextSpan();
}
public static TextSpan ToTextSpanIncludingLineBreak(this SnapshotLineRange range)
{
return range.ExtentIncludingLineBreak.ToTextSpan();
}
#endregion
#region _DTE
public static IEnumerable<Project> GetProjects(this _DTE dte)
{
var list = dte.Solution.Projects;
for (int i = 1; i <= list.Count; i++)
{
yield return list.Item(i);
}
}
public static IEnumerable<ProjectItem> GetProjectItems(this _DTE dte, string fileName)
{
foreach (var cur in dte.GetProjects())
{
ProjectItem item;
if (cur.TryGetProjectItem(fileName, out item))
{
yield return item;
}
}
}
public static VisualStudioVersion GetVisualStudioVersion(this _DTE dte)
{
var version = dte.Version;
if (string.IsNullOrEmpty(dte.Version))
{
return VisualStudioVersion.Unknown;
}
var parts = version.Split('.');
if (parts.Length == 0)
{
return VisualStudioVersion.Unknown;
}
switch (parts[0])
{
case "10":
return VisualStudioVersion.Dev10;
case "11":
return VisualStudioVersion.Dev11;
default:
return VisualStudioVersion.Unknown;
}
}
#endregion
#region Project
public static IEnumerable<ProjectItem> GetProjecItems(this Project project)
{
var items = project.ProjectItems;
for (int i = 1; i <= items.Count; i++)
{
yield return items.Item(i);
}
}
public static bool TryGetProjectItem(this Project project, string fileName, out ProjectItem item)
{
try
{
item = project.ProjectItems.Item(fileName);
return true;
}
catch (ArgumentException)
{
item = null;
return false;
}
}
#endregion
#region ObservableCollection<T>
public static void AddRange<T>(this ObservableCollection<T> col, IEnumerable<T> enumerable)
{
foreach (var cur in enumerable)
{
col.Add(cur);
}
}
#endregion
#region IEnumerable<T>
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> del)
{
foreach (var cur in enumerable)
{
del(cur);
}
}
public static IEnumerable<T> GetValues<T>(this IEnumerable<Result<T>> enumerable)
{
foreach (var cur in enumerable)
{
if (cur.IsSuccess)
{
yield return cur.Value;
}
}
}
#endregion
#region FSharpOption<T>
/// <summary>
/// Is the F# option both Some and equal to the provided value?
/// </summary>
public static bool IsSome<T>(this FSharpOption<T> option, T value)
{
return option.IsSome() && EqualityComparer<T>.Default.Equals(option.Value, value);
}
#endregion
#region IOleCommandTarget
internal static int Exec(this IOleCommandTarget oleCommandTarget, OleCommandData oleCommandData)
{
Guid commandGroup = oleCommandData.CommandGroup;
return oleCommandTarget.Exec(
ref commandGroup,
oleCommandData.CommandId,
oleCommandData.CommandExecOpt,
oleCommandData.VariantIn,
oleCommandData.VariantOut);
}
internal static int QueryStatus(this IOleCommandTarget oleCommandTarget, OleCommandData oleCommandData)
{
OLECMD command;
return QueryStatus(oleCommandTarget, oleCommandData, out command);
}
internal static int QueryStatus(this IOleCommandTarget oleCommandTarget, OleCommandData oleCommandData, out OLECMD command)
{
var commandGroup = oleCommandData.CommandGroup;
var cmds = new OLECMD[1];
cmds[0] = new OLECMD { cmdID = oleCommandData.CommandId };
var result = oleCommandTarget.QueryStatus(
ref commandGroup,
1,
cmds,
oleCommandData.VariantIn);
command = cmds[0];
return result;
}
#endregion
#region IEditorFormatMap
public static Color GetBackgroundColor(this IEditorFormatMap map, string name, Color defaultColor)
{
var properties = map.GetProperties(name);
var key = EditorFormatDefinition.BackgroundColorId;
var color = defaultColor;
if (properties != null && properties.Contains(key))
{
color = (Color)properties[key];
}
return color;