예제 #1
0
        private void GetSnippets()
        {
            if (null == _expansionsList)
            {
                _expansionsList = new List <VsExpansion>();
            }
            else
            {
                _expansionsList.Clear();
            }

            IVsTextManager2 textManager =
                Microsoft.VisualStudio.Shell.Package.GetGlobalService(
                    typeof(SVsTextManager)) as IVsTextManager2;

            if (textManager == null)
            {
                return;
            }

            SnippetsEnumerator enumerator = new SnippetsEnumerator(
                textManager, GetLanguageServiceGuid());

            foreach (VsExpansion expansion in enumerator)
            {
                if (!string.IsNullOrEmpty(expansion.shortcut))
                {
                    _expansionsList.Add(expansion);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Gets the snippets.
        /// </summary>
        private void GetSnippets()
        {
            if (null == this.expansionsList)
            {
                this.expansionsList = new List <VsExpansion>();
            }
            else
            {
                this.expansionsList.Clear();
            }
            IVsTextManager2 textManager = Package.GetGlobalService(typeof(SVsTextManager)) as IVsTextManager2;

            if (textManager == null)
            {
                return;
            }
            SnippetsEnumerator enumerator = new SnippetsEnumerator(textManager, new Guid(ComposeStarConstants.languageServiceGuidString));

            foreach (VsExpansion expansion in enumerator)
            {
                if (!string.IsNullOrEmpty(expansion.shortcut))
                {
                    this.expansionsList.Add(expansion);
                }
            }
        }
예제 #3
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="args">Event args.</param>
        private void Execute(object sender, EventArgs args)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            object          service         = ServiceProvider.GetService(typeof(SVsTextManager));
            IVsTextManager2 textManager     = service as IVsTextManager2;
            string          highlightedText = EditorUtilities.GetHighlightedText(textManager);

            GenerateTypeWindow generateTypeWindow = new GenerateTypeWindow();
            DialogResult       result             = generateTypeWindow.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            ButlerCode bCode = ButlerCodeFactory.Create();

            bCode.Namespace  = generateTypeWindow.TypeNamespace;
            bCode.ClassName  = generateTypeWindow.TypeName;
            bCode.SourceJson = highlightedText;

            string generated = bCode.Generate();

            Clipboard.SetText(generated);

            _package.DoAlert("Generated code contents copied to clipboard.");
        }
예제 #4
0
        public static async Task <IWpfTextView> GetWpfTextViewAsync(this Microsoft.VisualStudio.Shell.IAsyncServiceProvider serviceProvider)
        {
            IVsTextManager2 textManager = (IVsTextManager2)await serviceProvider.GetServiceAsync(typeof(SVsTextManager));

            if (textManager == null)
            {
                return(null);
            }

            int result = textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out IVsTextView view);

            if (result != VSConstants.S_OK)
            {
                return(null);
            }

            IComponentModel componentModel = (IComponentModel)await serviceProvider.GetServiceAsync(typeof(SComponentModel));

            IVsEditorAdaptersFactoryService adapterService = componentModel?.GetService <IVsEditorAdaptersFactoryService>();

            if (adapterService == null)
            {
                return(null);
            }

            return(adapterService.GetWpfTextView(view));
        }
예제 #5
0
 public SnippetsEnumerator(IVsTextManager2 textManager, Guid languageGuid)
 {
     if (null == textManager)
     {
         throw new ArgumentNullException("textManager");
     }
     _textManager  = textManager;
     _languageGuid = languageGuid;
 }
예제 #6
0
        public void SetTextView(IVsTextView textViewAdapter)
        {
            m_vsTextView = textViewAdapter;
            //get the text manager from the service provider
            IVsTextManager2 textManager = (IVsTextManager2)languageService.GetService(typeof(SVsTextManager));

            textManager.GetExpansionManager(out m_exManager);
            // m_exSession = null;
        }
예제 #7
0
        private void GetSnippets(Guid languageGuid,
                                 ref ArrayList expansionsList)
        {
            IVsTextManager textManager = (IVsTextManager)Package.GetGlobalService(typeof(SVsTextManager));

            if (textManager != null)
            {
                IVsTextManager2 textManager2 = (IVsTextManager2)textManager;
                if (textManager2 != null)
                {
                    IVsExpansionManager expansionManager = null;
                    textManager2.GetExpansionManager(out expansionManager);
                    if (expansionManager != null)
                    {
                        // Tell the environment to fetch all of our snippets.
                        IVsExpansionEnumeration expansionEnumerator = null;
                        expansionManager.EnumerateExpansions(languageGuid,
                                                             0,    // return all info
                                                             null, // return all types
                                                             0,    // return all types
                                                             1,    // include snippets without types
                                                             0,    // do not include duplicates
                                                             out expansionEnumerator);
                        if (expansionEnumerator != null)
                        {
                            // Cache our expansions in a VsExpansion array
                            uint        count          = 0;
                            uint        fetched        = 0;
                            VsExpansion expansionInfo  = new VsExpansion();
                            IntPtr[]    pExpansionInfo = new IntPtr[1];

                            // Allocate enough memory for one VSExpansion structure. This memory is filled in by the Next method.
                            pExpansionInfo[0] = Marshal.AllocCoTaskMem(Marshal.SizeOf(expansionInfo));

                            expansionEnumerator.GetCount(out count);
                            for (uint i = 0; i < count; i++)
                            {
                                expansionEnumerator.Next(1, pExpansionInfo, out fetched);
                                if (fetched > 0)
                                {
                                    // Convert the returned blob of data into a structure that can be read in managed code.
                                    expansionInfo = (VsExpansion)Marshal.PtrToStructure(pExpansionInfo[0], typeof(VsExpansion));

                                    if (!String.IsNullOrEmpty(expansionInfo.shortcut))
                                    {
                                        expansionsList.Add(expansionInfo);
                                    }
                                }
                            }
                            Marshal.FreeCoTaskMem(pExpansionInfo[0]);
                        }
                    }
                }
            }
        }
예제 #8
0
 public PythonSnippetManager(
     [Import(typeof(SVsServiceProvider))] IServiceProvider site,
     [Import] IVsEditorAdaptersFactoryService editorAdaptersFactoryService
     )
 {
     _site = site ?? throw new ArgumentNullException(nameof(site));
     _editorAdaptersFactoryService = editorAdaptersFactoryService ?? throw new ArgumentNullException(nameof(editorAdaptersFactoryService));
     _textManager = site.GetService <SVsTextManager, IVsTextManager2>();
     _textManager.GetExpansionManager(out _vsExpansionMgr);
     _expansionMgr = _vsExpansionMgr as IExpansionManager;
 }
예제 #9
0
 private void Connect()
 {
     if (this.connection == null && this.site != null)
     {
         IVsTextManager2 textMgr2 = this.site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
         if (textMgr2 != null)
         {
             this.connection = new NativeMethods.ConnectionPointCookie(textMgr2, (IVsTextManagerEvents2)this, typeof(IVsTextManagerEvents2));
         }
     }
 }
예제 #10
0
        private void Connect()
        {
            IVsTextManager2 textMgr = GetService <IVsTextManager2>(typeof(SVsTextManager));
            uint            cookie;

            if (textMgr != null &&
                TryHookConnectionPoint <IVsTextManagerEvents2>(textMgr, this, out cookie))
            {
                _connection = cookie;
            }
        }
        private IEnumerable <SpringCompletion> GetSnippetsCompletions()
        {
            List <SpringCompletion> completions = new List <SpringCompletion>();

            IVsTextManager2    expansionManager   = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
            SnippetsEnumerable snippetsEnumerator = new SnippetsEnumerable(expansionManager, GuidList.guidSpringLanguage);

            completions.AddRange(snippetsEnumerator.Select(vsExpansion => new SpringCompletion(this.glyphService, vsExpansion)));

            completions.Sort();
            return(completions);
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="args">Event args.</param>
        private void Execute(object sender, EventArgs args)
        {
            object          service         = ServiceProvider.GetService(typeof(SVsTextManager));
            IVsTextManager2 textManager     = service as IVsTextManager2;
            string          highlightedText = EditorUtilities.GetHighlightedText(textManager);

            string convertedText = highlightedText.ToUnderscoreCamelCase();

            Clipboard.SetText(convertedText);

            _package.DoAlert("Converted text copied to clipboard.");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TrackActiveItemsCommandHandler"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private TrackActiveItemsCommandHandler(Package package)
        {
            this.package = package ?? throw new ArgumentNullException("package");

            ShellSettingsManager settingsManager = new ShellSettingsManager(package);

            SettingsStore = settingsManager.GetReadOnlySettingsStore(SettingsScope.UserSettings);

            OptionsService = ServicesUtil.GetMefService <IEditorOptionsFactoryService>(this.ServiceProvider);
            TextManager    = (IVsTextManager2)ServiceProvider.GetService(typeof(SVsTextManager));

            RegisterGlobalCommands();
        }
예제 #14
0
        private void Disconnect()
        {
            if (_connection.HasValue)
            {
                IVsTextManager2 textMgr = GetService <IVsTextManager2>(typeof(SVsTextManager));

                if (textMgr != null)
                {
                    ReleaseHook <IVsTextManagerEvents2>(textMgr, _connection.Value);
                }
                _connection = null;
            }
        }
예제 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DocumentCodeSpanCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private DocumentCodeSpanCommand(AsyncPackage package, OleMenuCommandService commandService, DTE2 appObj, IVsTextManager2 txtMngr)
        {
            this.package            = package ?? throw new ArgumentNullException(nameof(package));
            commandService          = commandService ?? throw new ArgumentNullException(nameof(commandService));
            this._applicationObject = appObj ?? throw new ArgumentNullException(nameof(_applicationObject));
            this._textManager       = txtMngr ?? throw new ArgumentNullException(nameof(_textManager));


            var menuCommandID = new CommandID(CommandSet, CommandId);
            var menuItem      = new MenuCommand(this.Execute, menuCommandID);

            commandService.AddCommand(menuItem);
        }
예제 #16
0
        public static string GetHighlightedText(IVsTextManager2 textManager)
        {
            if (textManager == null)
            {
                throw new Exception("Could not locate the TextManager service.");
            }

            textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out IVsTextView view);

            view.GetSelectedText(out string selectedText);

            return(selectedText);
        }
예제 #17
0
        //</Snippet29>

        //<Snippet30>
        internal TestCompletionCommandHandler(IVsTextView textViewAdapter, ITextView textView, TestCompletionHandlerProvider provider)
        {
            this.m_textView = textView;
            m_vsTextView    = textViewAdapter;
            m_provider      = provider;
            //get the text manager from the service provider
            IVsTextManager2 textManager = (IVsTextManager2)m_provider.ServiceProvider.GetService(typeof(SVsTextManager));

            textManager.GetExpansionManager(out m_exManager);
            m_exSession = null;

            //add the command to the command chain
            textViewAdapter.AddCommandFilter(this, out m_nextCommandHandler);
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="args">Event args.</param>
        private void Execute(object sender, EventArgs args)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            object          service         = ServiceProvider.GetService(typeof(SVsTextManager));
            IVsTextManager2 textManager     = service as IVsTextManager2;
            string          highlightedText = EditorUtilities.GetHighlightedText(textManager);

            string convertedText = highlightedText.ToLowerSnakeCase();

            Clipboard.SetText(convertedText);

            _package.DoAlert("Converted text copied to clipboard.");
        }
예제 #19
0
        /// <include file='doc\ExpansionProvider.uex' path='docs/doc[@for="ExpansionProvider.DisplayExpansionBrowser"]/*' />
        public virtual bool DisplayExpansionBrowser(IVsTextView view, string prompt, string[] types, bool includeNullType, string[] kinds, bool includeNullKind)
        {
            if (this.expansionActive)
            {
                this.EndTemplateEditing(true);
            }

            if (this.source.IsCompletorActive)
            {
                this.source.DismissCompletor();
            }

            this.view = view;
            IServiceProvider site    = this.source.LanguageService.Site;
            IVsTextManager2  textmgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;

            if (textmgr == null)
            {
                return(false);
            }

            IVsExpansionManager exmgr;

            textmgr.GetExpansionManager(out exmgr);
            Guid languageSID = this.source.LanguageService.GetLanguageServiceGuid();
            int  hr          = 0;

            if (exmgr != null)
            {
                hr = exmgr.InvokeInsertionUI(view,                               // pView
                                             this,                               // pClient
                                             languageSID,                        // guidLang
                                             types,                              // bstrTypes
                                             (types == null) ? 0 : types.Length, // iCountTypes
                                             includeNullType ? 1 : 0,            // fIncludeNULLType
                                             kinds,                              // bstrKinds
                                             (kinds == null) ? 0 : kinds.Length, // iCountKinds
                                             includeNullKind ? 1 : 0,            // fIncludeNULLKind
                                             prompt,                             // bstrPrefixText
                                             ">"                                 //bstrCompletionChar
                                             );
                if (NativeMethods.Succeeded(hr))
                {
                    return(true);
                }
            }

            return(false);
        }
예제 #20
0
        /// <include file='doc\PropertySheet.uex' path='docs/doc[@for="LanguagePreferences.Apply"]/*' />
        public virtual void Apply()
        {
            IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;

            if (textMgr2 != null)
            {
                this.prefs.guidLang = langSvc;
                LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1];
                langPrefs2[0] = this.prefs;
                if (!NativeMethods.Succeeded(textMgr2.SetUserPreferences2(null, null, langPrefs2, null)))
                {
                    Debug.Assert(false, "textMgr2.SetUserPreferences2");
                }
            }
        }
        public CommandFilter(IVsTextView textViewAdapter, ITextView textView, VsTextViewCreationListener provider)
        {
            _vsTextView = textViewAdapter;
            _textView   = textView;
            _provider   = provider;

            // Get the text manager from the service provider
            IVsTextManager2 textManager = (IVsTextManager2)_provider._serviceProvider.GetService(typeof(SVsTextManager));

            textManager.GetExpansionManager(out _exManager);
            _exSession = null;

            // Add the command to the command chain
            textViewAdapter.AddCommandFilter(this, out _nextCommandHandler);
        }
예제 #22
0
        public LanguageInfo(SVsServiceProvider serviceProvider, Guid languageGuid)
        {
            Contract.Requires <ArgumentNullException>(serviceProvider != null, "serviceProvider");

            _serviceProvider = serviceProvider;
            _languageGuid    = languageGuid;

            IVsTextManager2 textManager = serviceProvider.GetTextManager2();

            LANGPREFERENCES2[] preferences = new LANGPREFERENCES2[1];
            preferences[0].guidLang = languageGuid;
            ErrorHandler.ThrowOnFailure(textManager.GetUserPreferences2(null, null, preferences, null));
            _languagePreferences       = CreateLanguagePreferences(preferences[0]);
            _languagePreferencesCookie = ((IConnectionPointContainer)textManager).Advise <LanguagePreferences, IVsTextManagerEvents2>(_languagePreferences);
        }
예제 #23
0
        private async void Execute(object sender, EventArgs e)
        {
            object service = await ServiceProvider.GetServiceAsync(typeof(SVsTextManager));

            IVsTextManager2 textManager = service as IVsTextManager2;

            _ = textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out IVsTextView view);

            view.GetSelection(out _, out _, out _, out _); //end could be before beginning
            view.GetSelectedText(out string selectedText);

            StatementSyntax syntax = SyntaxFactory.ParseStatement(selectedText);

            SyntaxNode formattedResult = Formatter.Format(syntax, new AdhocWorkspace());

            SyntaxSenderService.Send(formattedResult, Language);
        }
예제 #24
0
        public static IEnumerable <string> GetSelection(EmptyLineAction Action, out int[] EmptyLinePositions, out bool WasNewLine)
        {
            IVsTextManager2 textManager = ServiceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager2;

            Assumes.Present(textManager);
            textManager.GetActiveView2(1, null, (uint)_VIEWFRAMETYPE.vftCodeWindow, out IVsTextView view);
            view.GetSelectedText(out string selectedText);
            WasNewLine = selectedText.EndsWith("\n");
            IEnumerable <string> result = selectedText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            int lastIndex = ((string[])result).Length - 1;

            EmptyLinePositions = result.Select((x, i) => new { Line = x, Index = i }).Where(x => string.IsNullOrWhiteSpace(x.Line)).Select(x => x.Index).ToArray();
            if (Action == EmptyLineAction.DependsOnSettings)
            {
                Action = VSPackage.Loader.Settings.EmptyLineAction;
            }
            result = Action == EmptyLineAction.AsLine ? result.Where((x, i) => !(string.IsNullOrEmpty(x) && i == lastIndex)) : result.Where(x => !string.IsNullOrWhiteSpace(x));
            return(result);
        }
        public async System.Threading.Tasks.Task GetItemsAsync(string searchString, IOmniBoxSearchSession searchSession)
        {
            await this.joinableTaskContext.Factory.SwitchToMainThreadAsync();

            if (this.dte == null)
            {
                this.dte = (DTE)this.serviceProvider.GetService(typeof(DTE));
            }

            if (this.textManager == null)
            {
                this.textManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
            }

            ITextView textView;
            if (!ErrorHandler.Succeeded(this.textManager.GetActiveView2(fMustHaveFocus: 1, pBuffer: null, grfIncludeViewFrameType: 0, out var ppView)) ||
                (textView = this.adaptersFactory.GetWpfTextView(ppView)) == null)
            {
                this.ConsiderShellCommands(searchSession);
            }
        internal void Initialize()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsTextManager2 textManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));

            VIEWPREFERENCES2[] viewPreferences     = new VIEWPREFERENCES2[] { new VIEWPREFERENCES2() };
            LANGPREFERENCES2[] languagePreferences = new LANGPREFERENCES2[] { new LANGPREFERENCES2()
                                                                              {
                                                                                  guidLang = Guids.Service
                                                                              } };

            int hresult = textManager.GetUserPreferences2(viewPreferences, pFramePrefs: null, pLangPrefs: languagePreferences, pColorPrefs: null);

            //ErrorHandler.ThrowOnFailure(hresult);

            this.UpdatePreferences(viewPreferences, languagePreferences);

            this.connectionPoint = new AxHost.ConnectionPointCookie(textManager, this, typeof(IVsTextManagerEvents2));
        }
예제 #27
0
        public async System.Threading.Tasks.Task GetItemsAsync(string searchString, IOmniBoxSearchSession searchSession)
        {
            await this.joinableTaskContext.Factory.SwitchToMainThreadAsync();

            if (this.textManager == null)
            {
                this.textManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
            }

            if (!ErrorHandler.Succeeded(this.textManager.GetActiveView2(fMustHaveFocus: 1, pBuffer: null, grfIncludeViewFrameType: 0, out var ppView)))
            {
                return;
            }

            var textView = this.adaptersFactory.GetWpfTextView(ppView);

            if (textView != null)
            {
                if (await this.lightBulbBroker.HasSuggestedActionsAsync(this.categoryRegistryService.Any, textView, searchSession.CancellationToken))
                {
                    // TODO: too lazy...
#pragma warning disable CS0618 // Type or member is obsolete
                    var session = this.lightBulbBroker.CreateSession(this.categoryRegistryService.Any, textView);
#pragma warning restore CS0618 // Type or member is obsolete

                    if (session != null &&
                        session.TryGetSuggestedActionSets(out var actionSets) != QuerySuggestedActionCompletionStatus.Canceled)
                    {
                        foreach (var actionSet in actionSets)
                        {
                            foreach (var action in actionSet.Actions)
                            {
                                searchSession.AddItem(new LightBulbItem(action));
                            }
                        }
                    }
                }
            }
        }
예제 #28
0
        /// <include file='doc\Preferences.uex' path='docs/doc[@for="LanguagePreferences.GetLanguagePrefs"]/*' />
        public virtual void GetLanguagePreferences()
        {
            IVsTextManager textMgr = GetService <IVsTextManager>(typeof(SVsTextManager));

            if (textMgr != null)
            {
                this.prefs.guidLang = langSvc;
                IVsTextManager2 textMgr2 = textMgr as IVsTextManager2;
                if (textMgr != null)
                {
                    LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1];
                    langPrefs2[0] = this.prefs;
                    if (VSErr.Succeeded(textMgr2.GetUserPreferences2(null, null, langPrefs2, null)))
                    {
                        this.prefs = langPrefs2[0];
                    }
                    else
                    {
                        Debug.Assert(false, "textMgr2.GetUserPreferences2");
                    }
                }
            }
        }
예제 #29
0
        /// <include file='doc\Preferences.uex' path='docs/doc[@for="LanguagePreferences.GetLanguagePrefs"]/*' />
        public virtual void GetLanguagePreferences()
        {
            IVsTextManager textMgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager;

            if (textMgr != null)
            {
                this.prefs.guidLang = langSvc;
                IVsTextManager2 textMgr2 = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
                if (textMgr != null)
                {
                    LANGPREFERENCES2[] langPrefs2 = new LANGPREFERENCES2[1];
                    langPrefs2[0] = this.prefs;
                    if (NativeMethods.Succeeded(textMgr2.GetUserPreferences2(null, null, langPrefs2, null)))
                    {
                        this.prefs = langPrefs2[0];
                    }
                    else
                    {
                        Debug.Assert(false, "textMgr2.GetUserPreferences2");
                    }
                }
                Marshal.ReleaseComObject(textMgr);
            }
        }
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (pguidCmdGroup == VSConstants.VSStd2K)
            {
                if (nCmdID == (uint)VSConstants.VSStd2KCmdID.INSERTSNIPPET || nCmdID == (uint)VSConstants.VSStd2KCmdID.SURROUNDWITH)
                {
                    IVsTextManager2     textManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
                    IVsExpansionManager expansionManager;
                    if (VSConstants.S_OK == textManager.GetExpansionManager(out expansionManager))
                    {
                        expansionManager.InvokeInsertionUI(
                            vsTextView,
                            this,
                            GuidList.guidSpringLanguage,
                            new string[] { "Expansion" },
                            1,
                            0,
                            null,
                            0,
                            1,
                            "Insert Snippet",
                            string.Empty);
                    }

                    return(VSConstants.S_OK);
                }

                if (this.expansionSession != null)
                {
                    // Handle VS Expansion (Code Snippets) keys
                    if ((nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB))
                    {
                        if (expansionSession.GoToNextExpansionField(0) == VSConstants.S_OK)
                        {
                            return(VSConstants.S_OK);
                        }
                    }
                    else if ((nCmdID == (uint)VSConstants.VSStd2KCmdID.BACKTAB))
                    {
                        if (expansionSession.GoToPreviousExpansionField() == VSConstants.S_OK)
                        {
                            return(VSConstants.S_OK);
                        }
                    }
                    else if ((nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.CANCEL))
                    {
                        if (expansionSession.EndCurrentExpansion(0) == VSConstants.S_OK)
                        {
                            expansionSession = null;

                            return(VSConstants.S_OK);
                        }
                    }
                }

                // Handle Edit.ListMembers or Edit.CompleteWord commands
                if ((nCmdID == (uint)VSConstants.VSStd2KCmdID.SHOWMEMBERLIST ||
                     nCmdID == (uint)VSConstants.VSStd2KCmdID.COMPLETEWORD))
                {
                    if (completionSession != null)
                    {
                        completionSession.Dismiss();
                    }

                    ShowCompletion();

                    return(VSConstants.S_OK);
                }

                // Handle Enter/Tab commit keys
                if (completionSession != null && (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB))
                {
                    if (completionSession.SelectedCompletionSet.SelectionStatus.IsSelected)
                    {
                        completionSession.Commit();
                    }
                    else
                    {
                        completionSession.Dismiss();
                    }

                    return(VSConstants.S_OK);
                }

                // Handle Code Snippets after pressing the Tab key without completion
                if (completionSession == null && (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB))
                {
                    IVsTextManager2    expansionManager   = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
                    SnippetsEnumerable snippetsEnumerator = new SnippetsEnumerable(expansionManager, GuidList.guidSpringLanguage);

                    SnapshotPoint           currentPoint = (this.textView.Caret.Position.BufferPosition) - 1;
                    ITextStructureNavigator navigator    = this.textStructureNavigatorSelectorService.GetTextStructureNavigator(this.textView.TextBuffer);
                    TextExtent extent   = navigator.GetExtentOfWord(currentPoint);
                    string     shortcut = this.textView.TextSnapshot.GetText(extent.Span);

                    // Search a snippet that matched the token text
                    VsExpansion expansion = snippetsEnumerator.FirstOrDefault(e => e.title == shortcut);
                    if (expansion.title != null)
                    {
                        // Set the location where the snippet will be inserted
                        int startLine, startColumn, endLine, endColumn;

                        this.vsTextView.GetCaretPos(out startLine, out endColumn);
                        startColumn = endColumn - expansion.title.Length;
                        endLine     = startLine;

                        // Insert the snippet
                        InsertCodeExpansion(expansion, startLine, startColumn, endLine, endColumn);

                        return(VSConstants.S_OK);
                    }
                }

                // Hanlde other keys
                if ((nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR))
                {
                    char typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);

                    if (completionSession == null)
                    {
                        // Handle trigger keys
                        // Check if the typed char is a trigger
                        if (IsTriggerKey(typedChar))
                        {
                            var result = this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                            ShowCompletion();

                            return(result);
                        }
                    }
                    else
                    {
                        // Handle commit keys
                        // Check if the typed char is a commit key
                        if (IsCommitKey(typedChar))
                        {
                            SpringCompletion selectedCompletion = completionSession.SelectedCompletionSet.SelectionStatus.Completion as SpringCompletion;
                            if (completionSession.SelectedCompletionSet.SelectionStatus.IsSelected &&
                                selectedCompletion != null && selectedCompletion.Type != null &&
                                selectedCompletion.Type.Value == SpringCompletionType.Namespace)
                            {
                                completionSession.Commit();
                            }
                            else
                            {
                                completionSession.Dismiss();
                            }

                            var result = this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                            // Check we should trigger completion after comitting the previous session (for example, after typing dot '.')
                            if (IsTriggerKey(typedChar))
                            {
                                ShowCompletion();
                            }

                            return(result);
                        }
                        else
                        {
                            var result = this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                            completionSession.Filter();
                            return(result);
                        }
                    }
                }

                // redo the filter if there is a deletion
                if (nCmdID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE ||
                    nCmdID == (uint)VSConstants.VSStd2KCmdID.DELETE)
                {
                    var result = this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);

                    if (completionSession != null && !completionSession.IsDismissed)
                    {
                        completionSession.Filter();
                    }

                    return(result);
                }
            }

            // we haven't handled this command so pass it onto the next target
            return(this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
        }