public IEditorNavigationDropdownBarClient CreateEditorNavigationDropdownBar(IVsCodeWindow codeWindow, IVsEditorAdaptersFactoryService editorAdaptersFactory) { // a code window can only be associated with a single buffer, so the primary view will get us the correct information IVsTextView primaryViewAdapter = codeWindow.GetPrimaryView(); IWpfTextView textView = editorAdaptersFactory.GetWpfTextView(primaryViewAdapter); IBufferGraph bufferGraph = BufferGraphFactoryService.CreateBufferGraph(textView.TextBuffer); Collection <ITextBuffer> buffers = bufferGraph.GetTextBuffers(i => true); List <IEditorNavigationSource> sources = new List <IEditorNavigationSource>(); foreach (ITextBuffer buffer in buffers) { var bufferProviders = NavigationSourceProviders.Where(provider => provider.Metadata.ContentTypes.Any(contentType => buffer.ContentType.IsOfType(contentType))); var bufferSources = bufferProviders .Select(provider => provider.Value.TryCreateEditorNavigationSource(buffer)) .Where(source => source != null); sources.AddRange(bufferSources); } return(new EditorNavigationDropdownBar(codeWindow, editorAdaptersFactory, sources, BufferGraphFactoryService, EditorNavigationTypeRegistryService)); }
async void IService.HelloWorld() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); //воротаемся в UI поток. vproject = ProjectHelpers.GetActiveProject(); string rootfolder = vproject.GetRootFolder(); //корневая папка проекта с csproj открытым в студии string vsixdllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""); string vsixfolder = Path.GetDirectoryName(vsixdllpath); string filename = "tmp1.cs"; string path2addfile = Path.Combine(vsixfolder, "Templates", filename); var filetoadd = new FileInfo(path2addfile); ProjectItem projectItem = null; string fileprojpath = Path.Combine(rootfolder, filename); var filedest = new FileInfo(Path.Combine(fileprojpath)); if (1 == 1) { if (1 == 1) //добавить файл в проект из VSIX папки { ProjectHelpers.CopyTmpToProjectFile(vproject, filetoadd.FullName, filedest.FullName); } projectItem = vproject.AddFileToProject(filedest); vproject.DTE.ItemOperations.OpenFile(fileprojpath); //открыть редактор с новым файлом if (true) //добавить текст { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); if (view != null) { try { ITextEdit edit = view.TextBuffer.CreateEdit(); edit.Insert(0, Environment.NewLine); edit.Apply(); } catch (Exception e) { } } } if (true) //добавление абсолютной ссылки в проект { VSProject refproject; refproject = (VSProject)vproject.Object; try { refproject.References.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\Microsoft.Build.dll"); } catch (Exception ddd) { } } } }
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) { serviceProvider = package as System.IServiceProvider; Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView(); Microsoft.VisualStudio.Text.SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition; textView.TextBuffer.Insert(caretPosition.Position, "sample code"); }
private async System.Threading.Tasks.Task CreateDtoFile(string inputCamel, string folder, object selectedItem, ProjectItem dtoProject, Project project, TemplateType templateType) { var file = CreateFileInfo(inputCamel, folder, templateType); PackageUtilities.EnsureOutputPath(folder); if (!file.Exists) { int position = await WriteFileAsync(project, file.FullName, inputCamel, templateType); try { ProjectItem projectItem = null; if (selectedItem is ProjectItem projItem) { if ("{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}" == projItem.Kind) // Constants.vsProjectItemKindVirtualFolder { projectItem = projItem.ProjectItems.AddFromFile(file.FullName); } } if (projectItem == null) { projectItem = dtoProject.ProjectItems.AddFromFile(file.FullName); } if (file.FullName.EndsWith("__dummy__")) { projectItem?.Delete(); return; } VsShellUtilities.OpenDocument(this, file.FullName); // Move cursor into position if (position > 0) { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); view?.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, position)); } _dte.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); } catch (Exception ex) { Logger.Log(ex); } } else { System.Windows.Forms.MessageBox.Show("The file '" + file + "' already exist."); } }
public TextAdornment1(Microsoft.VisualStudio.Text.Editor.IWpfTextView view) { var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel)); Workspace = componentModel.GetService <Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>(); View = view; View.LayoutChanged += OnLayoutChanged; }
public ReplayAdornment(Microsoft.VisualStudio.Text.Editor.IWpfTextView view) { var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel)); Workspace = componentModel.GetService <Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>(); View = view; View.LayoutChanged += OnLayoutChanged; View.TextBuffer.Changed += OnTextBufferChanged; View.ViewportWidthChanged += OnViewportWidthChanged; View.Closed += OnClosed; }
static void CreateWindow(Microsoft.VisualStudio.Text.Editor.IWpfTextView v) { _Window = new Options.SyntaxHighlightCustomizationWindow(v) { Width = 560, Height = 600, Owner = System.Windows.Application.Current.MainWindow }; // stop VS from stealing key strokes (enter, backspace, arrow keys, tab stops, etc.) from the window Controls.KeystrokeThief.Bind(_Window); _Window.Closed += UnbindConfig; Config.Loaded += RefreshWindow; }
public static bool WaitForLightBulbSession(ILightBulbBroker broker, Microsoft.VisualStudio.Text.Editor.IWpfTextView view) => Helper.Retry(() => { if (broker.IsLightBulbSessionActive(view)) { return(true); } // checking whether there is any suggested action is async up to editor layer and our waiter doesnt track up to that point. // so here, we have no other way than sleep (with timeout) to see LB is available. HostWaitHelper.PumpingWait(Task.Delay(TimeSpan.FromSeconds(1))); return(broker.IsLightBulbSessionActive(view)); }, TimeSpan.FromSeconds(0));
public void UpdateSource(string innerHtml, string file, int position) { ThreadHelper.ThrowIfNotOnUIThread(); VsHelpers.DTE.ItemOperations.OpenFile(file); ThreadHelper.JoinableTaskFactory.Run(async() => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Microsoft.VisualStudio.Text.Editor.IWpfTextView view = VsHelpers.GetCurentTextView(); HtmlEditorDocument html = HtmlEditorDocument.TryFromTextView(view); if (html == null) { return; } view.Selection.Clear(); html.HtmlEditorTree.GetPositionElement(position + 1, out ElementNode element, out AttributeNode attribute); // HTML element if (element != null && element.Start == position) { Span span = new Span(element.InnerRange.Start, element.InnerRange.Length); string text = html.TextBuffer.CurrentSnapshot.GetText(span); if (text != innerHtml) { UpdateBuffer(innerHtml, html, span); } } // ActionLink else if (element.Start != position) { //@Html.ActionLink("Application name", "Index", "Home", null, new { @class = "brand" }) Span span = new Span(position, 100); if (position + 100 < html.TextBuffer.CurrentSnapshot.Length) { string text = html.TextBuffer.CurrentSnapshot.GetText(span); string result = Regex.Replace(text, @"^html.actionlink\(""([^""]+)""", "Html.ActionLink(\"" + innerHtml + "\"", RegexOptions.IgnoreCase); UpdateBuffer(result, html, span); } } }); }
// Get IVsTextView from filepath internal static Microsoft.VisualStudio.TextManager.Interop.IVsTextView IVsTextView_FromFilePath_Get(string filePath) { var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE)); Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2; Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp); Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchy uiHierarchy; uint itemID; Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame windowFrame; Microsoft.VisualStudio.Text.Editor.IWpfTextView wpfTextView = null; if (Microsoft.VisualStudio.Shell.VsShellUtilities.IsDocumentOpen(serviceProvider, filePath, Guid.Empty, out uiHierarchy, out itemID, out windowFrame)) { return(Microsoft.VisualStudio.Shell.VsShellUtilities.GetTextView(windowFrame)); } return(null); }
public ExternalAdornment(Microsoft.VisualStudio.Text.Editor.IWpfTextView view) { UseLayoutRounding = true; SnapsToDevicePixels = true; Grid.SetColumn(this, 1); Grid.SetRow(this, 1); Grid.SetIsSharedSizeScope(this, true); var grid = view.VisualElement.GetParent <Grid>(); if (grid != null) { grid.Children.Add(this); } else { view.VisualElement.Loaded += VisualElement_Loaded; } _View = view; }
public GazeAdornment(Microsoft.VisualStudio.Text.Editor.IWpfTextView view) { var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel)); Workspace = componentModel.GetService <Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>(); View = view; LayerManager = GazeLayerManager.Get(view); LayerManager.SingletonLayers = new System.Collections.Generic.List <GazeResponseLayer>() { new EllipseInformationalGazeLayerElement(View, Brushes.Red, 5, 5), // show a 5x5 core target that is the discrete X,Y coordinates new EllipseInformationalGazeLayerElement(View, Brushes.Cyan, 100, 100), // show a 100x100 extended target that is the scan area for the gaze targeting system }; EyeTracking.PointAvailable += (sender, e) => Stabilization.AddPoint(e); Stabilization.StabilizedPointAvailable += (sender, e) => { if (_inFlight) { return; } _inFlight = true; // workflow goes here, point should be stabilized coming from point provider try { if (View.VisualElement.Dispatcher.Invoke(() => (View.VisualElement.ActualHeight == 0 || !View.VisualElement.IsInitialized || !View.VisualElement.IsLoaded))) { _inFlight = false; return; // gaze point available before WPF draw is finished } // localize point to our editor view var localPt = View.VisualElement.Dispatcher.Invoke(() => View.VisualElement.PointFromScreen(e)); localPt.X += View.ViewportLeft; localPt.Y += View.ViewportTop; // infer/guess gaze targets var gazedElements = GazeTargeting.GetTargetCandidateTokens(View, Workspace, localPt.X, localPt.Y); // draw singleton layers (coordinate-based) LayerManager.DrawSingletonLayers(localPt.X, localPt.Y); // draw highlights around gazed elements LayerManager.ScrubLayers(); foreach (GazeTarget element in gazedElements.OrderByDescending(el => el.Weight)) { var span = new SnapshotSpan(View.TextSnapshot, element.DefinitionLocation.Start, element.DefinitionLocation.Length); if (!LayerManager.IsTracking(span)) { // gradate opacity of the debug layer based on target weights (on green) LayerManager.Layers.Add(new TextHighlightInformationalGazeLayerElement(View, span, element.Weight)); } var model = EditTimeVisualizerModel.Create(element); if (model != null && model.IsValid) { LayerManager.Layers.Add(new EditTimeVisualizationLayer(View, span, model)); } } LayerManager.Draw(); } catch (Exception ex) { } _inFlight = false; }; }
public void OnDocumentActivated(Microsoft.VisualStudio.Text.Editor.IWpfTextView view) { ThreadHelper.ThrowIfNotOnUIThread(); _exp.OnDocumentActivated(view); }
private async System.Threading.Tasks.Task AddFileAsync(string name, NewItemTarget target) { FileInfo file; // If the file is being added to a solution folder, but that // solution folder doesn't have a corresponding directory on // disk, then write the file to the root of the solution instead. if (target.IsSolutionFolder && !Directory.Exists(target.Directory)) { file = new FileInfo(Path.Combine(Path.GetDirectoryName(_dte.Solution.FullName), Path.GetFileName(name))); } else { file = new FileInfo(Path.Combine(target.Directory, name)); } // Make sure the directory exists before we create the file. Don't use // `PackageUtilities.EnsureOutputPath()` because it can silently fail. Directory.CreateDirectory(file.DirectoryName); if (!file.Exists) { Project project; if (target.IsSolutionOrSolutionFolder) { project = GetOrAddSolutionFolder(Path.GetDirectoryName(name), target); } else { project = target.Project; } int position = await WriteFileAsync(project, file.FullName); if (target.ProjectItem != null && target.ProjectItem.IsKind(Constants.vsProjectItemKindVirtualFolder)) { target.ProjectItem.ProjectItems.AddFromFile(file.FullName); } else { project.AddFileToProject(file); } VsShellUtilities.OpenDocument(this, file.FullName); // Move cursor into position. if (position > 0) { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); if (view != null) { view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, position)); } } ExecuteCommandIfAvailable("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); } else { MessageBox.Show($"The file '{file}' already exists.", Vsix.Name, MessageBoxButton.OK, MessageBoxImage.Information); } }
public IMouseProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) { return(wpfTextView.Properties.GetOrCreateSingletonProperty(() => new IntellisenseMouseProcessor(wpfTextView))); }
public IMouseProcessor GetAssociatedProcessor(IWpfTextView wpfTextView) { return wpfTextView.Properties.GetOrCreateSingletonProperty(() => new IntellisenseMouseProcessor(wpfTextView)); }
private async void ExecuteAsync(object sender, EventArgs e) { object item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } ProjectItem selectedItem = item as ProjectItem; Project selectedProject = item as Project; Project project = selectedItem?.ContainingProject ?? selectedProject ?? ProjectHelpers.GetActiveProject(); if (project == null) { return; } string input = PromptForFileName(folder).TrimStart('/', '\\').Replace("/", "\\"); if (string.IsNullOrEmpty(input)) { return; } string[] parsedInputs = GetParsedInput(input); foreach (string inputItem in parsedInputs) { input = inputItem; if (input.EndsWith("\\", StringComparison.Ordinal)) { input = input + "__dummy__"; } FileInfo file = null; try { file = new FileInfo(Path.Combine(folder, input)); } catch (PathTooLongException ex) { MessageBox.Show("The file name is too long 😢", Vsix.Name, MessageBoxButton.OK, MessageBoxImage.Error); Logger.Log(ex); continue; } catch (Exception ex) { Logger.Log(ex); continue; } if (!IsFileNameValid(file.Name)) { MessageBox.Show($"The file name '{file.Name}' is a system reserved name.", Vsix.Name, MessageBoxButton.OK, MessageBoxImage.Error); continue; } string dir = file.DirectoryName; PackageUtilities.EnsureOutputPath(dir); if (!file.Exists) { try { int position = await WriteFileAsync(project, file.FullName); ProjectItem projectItem = null; if (item is ProjectItem projItem) { if ("{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}" == projItem.Kind) // Constants.vsProjectItemKindVirtualFolder { projectItem = projItem.ProjectItems.AddFromFile(file.FullName); } } if (projectItem == null) { projectItem = project.AddFileToProject(file); } if (file.FullName.EndsWith("__dummy__")) { projectItem?.Delete(); continue; } VsShellUtilities.OpenDocument(this, file.FullName); // Move cursor into position if (position > 0) { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); if (view != null) { view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, position)); } } _dte.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); } catch (Exception ex) { Logger.Log(ex); } } else { System.Windows.Forms.MessageBox.Show("The file '" + file + "' already exist."); } } }
//private void MenuItem_BeforeQueryStatus(object sender, EventArgs e) //{ // var button = (OleMenuCommand)sender; // button.Visible = button.Enabled = false; // UIHierarchyItem item = GetSelectedItem(); // var project = item.Object as Project; // if (project == null || !project.Kind.Equals(EnvDTE.Constants.vsProjectKindSolutionItems, StringComparison.OrdinalIgnoreCase)) // button.Visible = button.Enabled = true; //} private async void ExecuteAsync(object sender, EventArgs e) { object item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var selectedItem = item as ProjectItem; var selectedProject = item as Project; Project project = selectedItem?.ContainingProject ?? selectedProject ?? ProjectHelpers.GetActiveProject(); if (project == null) { return; } dynamic inputValues = PromptForFileName(folder); string input = inputValues.Input.TrimStart('/', '\\').Replace("/", "\\"); if (string.IsNullOrEmpty(input)) { return; } string[] parsedInputs = GetParsedInput(input); foreach (string inputItem in parsedInputs) { input = inputItem; if (input.EndsWith("\\", StringComparison.Ordinal)) { input = input + "__dummy__"; } else { // only prepend the date/time onto filenames (not folders) input = input.Insert(input.LastIndexOf("\\") + 1, DateTime.Now.ToString("yyyyMMdd_HHmmss_")); } var file = new FileInfo(Path.Combine(folder, input)); string dir = file.DirectoryName; PackageUtilities.EnsureOutputPath(dir); if (!file.Exists) { int position = await WriteFileAsync(project, file.FullName); try { ProjectItem projectItem = null; if (item is ProjectItem projItem) { if ("{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}" == projItem.Kind) // Constants.vsProjectItemKindVirtualFolder { projectItem = projItem.ProjectItems.AddFromFile(file.FullName); } } if (projectItem == null) { project.AddFileToProject(file.FullName, isEmbeddedResource: (bool)inputValues.IsEmbeddedResource); } if (file.FullName.EndsWith("__dummy__")) { projectItem?.Delete(); continue; } VsShellUtilities.OpenDocument(this, file.FullName); // Move cursor into position if (position > 0) { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); if (view != null) { view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, position)); } } // I have no idea why but only doing Activate once after SyncwithActiveDocument does not work 100% of the time. _dte.ActiveDocument.Activate(); _dte.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); } catch (Exception ex) { Logger.Log(ex); } } else { System.Windows.Forms.MessageBox.Show("The file '" + file + "' already exist."); } } }
private void UpdateQuickInfoContent(IQuickInfoSession session, SnapshotPoint triggerPoint) { /* use the experimental model to locate and process the expression */ Stopwatch stopwatch = Stopwatch.StartNew(); // lex the entire document var currentSnapshot = triggerPoint.Snapshot; var input = new SnapshotCharStream(currentSnapshot, new Span(0, currentSnapshot.Length)); var unicodeInput = new JavaUnicodeStream(input); var lexer = new Java2Lexer(unicodeInput); var tokens = new CommonTokenStream(lexer); tokens.Fill(); // locate the last token before the trigger point while (true) { IToken nextToken = tokens.LT(1); if (nextToken.Type == CharStreamConstants.EndOfFile) { break; } if (nextToken.StartIndex > triggerPoint.Position) { break; } tokens.Consume(); } IToken triggerToken = tokens.LT(-1); if (triggerToken == null) { return; } switch (triggerToken.Type) { // symbol references case Java2Lexer.IDENTIFIER: case Java2Lexer.THIS: case Java2Lexer.SUPER: // primitive types case Java2Lexer.BOOLEAN: case Java2Lexer.CHAR: case Java2Lexer.BYTE: case Java2Lexer.SHORT: case Java2Lexer.INT: case Java2Lexer.LONG: case Java2Lexer.FLOAT: case Java2Lexer.DOUBLE: // literals case Java2Lexer.INTLITERAL: case Java2Lexer.LONGLITERAL: case Java2Lexer.FLOATLITERAL: case Java2Lexer.DOUBLELITERAL: case Java2Lexer.CHARLITERAL: case Java2Lexer.STRINGLITERAL: case Java2Lexer.TRUE: case Java2Lexer.FALSE: case Java2Lexer.NULL: break; default: return; } NetworkInterpreter interpreter = CreateNetworkInterpreter(tokens); while (interpreter.TryStepBackward()) { if (interpreter.Contexts.Count == 0 || interpreter.Contexts.Count > 400) { break; } if (interpreter.Contexts.All(context => context.BoundedStart)) { break; } } interpreter.Contexts.RemoveAll(i => !i.BoundedStart); interpreter.CombineBoundedStartContexts(); IOutputWindowPane pane = Provider.OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense); if (pane != null) { pane.WriteLine(string.Format("Located {0} QuickInfo expression(s) in {1}ms.", interpreter.Contexts.Count, stopwatch.ElapsedMilliseconds)); } HashSet <string> intermediateResult = new HashSet <string>(); HashSet <string> finalResult = new HashSet <string>(); List <object> quickInfoContent = new List <object>(); foreach (var context in interpreter.Contexts) { Span?span = null; foreach (var transition in context.Transitions) { if (!transition.Transition.IsMatch) { continue; } IToken token = transition.Token; Span tokenSpan = new Span(token.StartIndex, token.StopIndex - token.StartIndex + 1); if (span == null) { span = tokenSpan; } else { span = Span.FromBounds(Math.Min(span.Value.Start, tokenSpan.Start), Math.Max(span.Value.End, tokenSpan.End)); } } if (span.HasValue && !span.Value.IsEmpty) { string text = currentSnapshot.GetText(span.Value); if (!intermediateResult.Add(text)) { continue; } AstParserRuleReturnScope <CommonTree, CommonToken> result = null; try { var expressionInput = new ANTLRStringStream(text); var expressionUnicodeInput = new JavaUnicodeStream(expressionInput); var expressionLexer = new Java2Lexer(expressionUnicodeInput); var expressionTokens = new CommonTokenStream(expressionLexer); var expressionParser = new Java2Parser(expressionTokens); result = expressionParser.primary(); // anchors experiment Contract.Assert(TextBuffer.CurrentSnapshot == triggerPoint.Snapshot); ClassAnchorTracker tracker = new ClassAnchorTracker(TextBuffer, null); SnapshotSpan trackedSpan = new SnapshotSpan(triggerPoint.Snapshot, 0, triggerPoint.Position); ITagSpan <ScopeAnchorTag>[] tags = tracker.GetTags(new NormalizedSnapshotSpanCollection(trackedSpan)).ToArray(); text = result.Tree.ToStringTree(); } catch (RecognitionException) { text = "Could not parse: " + text; } text = text.Replace("\n", "\\n").Replace("\r", "\\r"); finalResult.Add(text); //if (Regex.IsMatch(text, @"^[A-Za-z_]+(?:\.\w+)*$")) //{ // NameResolutionContext resolutionContext = NameResolutionContext.Global(Provider.IntelliSenseCache); // resolutionContext = resolutionContext.Filter(text, null, true); // CodeElement[] matching = resolutionContext.GetMatchingElements(); // if (matching.Length > 0) // { // foreach (var element in matching) // { // element.AugmentQuickInfoSession(quickInfoContent); // } // } // else // { // // check if this is a package // CodePhysicalFile[] files = Provider.IntelliSenseCache.GetPackageFiles(text, true); // if (files.Length > 0) // { // finalResult.Add(string.Format("package {0}", text)); // } // else // { // // check if this is a type // string typeName = text.Substring(text.LastIndexOf('.') + 1); // CodeType[] types = Provider.IntelliSenseCache.GetTypes(typeName, true); // foreach (var type in types) // { // if (type.FullName == text) // finalResult.Add(string.Format("{0}: {1}", type.GetType().Name, type.FullName)); // } // } // } //} //else //{ // finalResult.Add(text); //} } } ITrackingSpan applicableToSpan = null; foreach (var result in finalResult) { quickInfoContent.Add(result); } applicableToSpan = currentSnapshot.CreateTrackingSpan(new Span(triggerToken.StartIndex, triggerToken.StopIndex - triggerToken.StartIndex + 1), SpanTrackingMode.EdgeExclusive); //try //{ // Expression currentExpression = Provider.IntellisenseCache.ParseExpression(selection); // if (currentExpression != null) // { // SnapshotSpan? span = currentExpression.Span; // if (span.HasValue) // applicableToSpan = span.Value.Snapshot.CreateTrackingSpan(span.Value, SpanTrackingMode.EdgeExclusive); // quickInfoContent.Add(currentExpression.ToString()); // } // else // { // quickInfoContent.Add("Could not parse expression."); // } //} //catch (Exception ex) //{ // if (ErrorHandler.IsCriticalException(ex)) // throw; // quickInfoContent.Add(ex.Message); //} lock (_contentUpdateLock) { _triggerPoint = triggerPoint; _applicableToSpan = applicableToSpan; _quickInfoContent = quickInfoContent; } IWpfTextView wpfTextView = session.TextView as IWpfTextView; if (wpfTextView != null && wpfTextView.VisualElement != null) { ITrackingPoint trackingTriggerPoint = triggerPoint.Snapshot.CreateTrackingPoint(triggerPoint.Position, PointTrackingMode.Negative); wpfTextView.VisualElement.Dispatcher.BeginInvoke((Action <IQuickInfoSession, ITrackingPoint, bool>)RetriggerQuickInfo, session, trackingTriggerPoint, true); } }
private async void ExecuteAsync(object sender, EventArgs e) { //var assmbly = System.Reflection.Assembly.LoadFile(@"D:\sample\abp-master\abp-master\samples\BookStore\src\Acme.BookStore.Domain\bin\Debug\netcoreapp2.2\Acme.BookStore.Domain.dll"); //if (assmbly != null) { // var fullname = assmbly.FullName; // var types = assmbly.GetTypes(); // foreach (var ty in types) { // var typename = ty.FullName; // } //} var entities = GetEntities(AddAnyFilePackage._dte.Solution).ToArray(); object item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var selectedItem = item as ProjectItem; var selectedProject = item as Project; Project project = selectedItem?.ContainingProject ?? selectedProject ?? ProjectHelpers.GetActiveProject(); if (project == null) { return; } var dir = new DirectoryInfo(folder); this.rootNamespace = project.GetRootNamespace(); var viewmodel = new AppServiceDialogViewModel() { Entities = new System.Windows.Data.CollectionView(entities), SelectFolder = dir.Name + "/", RootNamespace = this.rootNamespace }; string input = PromptForFileName(folder, viewmodel).TrimStart('/', '\\').Replace("/", "\\"); if (string.IsNullOrEmpty(input)) { return; } //string[] parsedInputs = GetParsedInput(input); string[] parsedInputs = new string[] { viewmodel.DtoClass + ".cs", viewmodel.CudtoClass + ".cs", viewmodel.ServiceClass + ".cs", viewmodel.IServiceClass + ".cs" }; foreach (string inputItem in parsedInputs) { input = inputItem; if (input.EndsWith("\\", StringComparison.Ordinal)) { input = input + "__dummy__"; } var file = new FileInfo(Path.Combine(folder, viewmodel.SubFolder, input)); string path = file.DirectoryName; PackageUtilities.EnsureOutputPath(path); if (!file.Exists) { int position = await WriteFileAsync(project, file.FullName); try { ProjectItem projectItem = null; if (item is ProjectItem projItem) { if ("{6BB5F8F0-4483-11D3-8BCF-00C04F8EC28C}" == projItem.Kind) // Constants.vsProjectItemKindVirtualFolder { projectItem = projItem.ProjectItems.AddFromFile(file.FullName); } } if (projectItem == null) { projectItem = project.AddFileToProject(file); } if (file.FullName.EndsWith("__dummy__")) { projectItem?.Delete(); continue; } VsShellUtilities.OpenDocument(this, file.FullName); // Move cursor into position if (position > 0) { Microsoft.VisualStudio.Text.Editor.IWpfTextView view = ProjectHelpers.GetCurentTextView(); if (view != null) { view.Caret.MoveTo(new SnapshotPoint(view.TextBuffer.CurrentSnapshot, position)); } } _dte.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); _dte.ActiveDocument.Activate(); } catch (Exception ex) { Logger.Log(ex); } } else { System.Windows.Forms.MessageBox.Show("The file '" + file + "' already exist."); } } }
public MouseNavigationProcessor(IWpfTextView wpfTextView, IServiceProvider serviceProvider) { TextView = wpfTextView; ServiceProvider = serviceProvider; }