protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return(false); } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return(true); } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } }
public int OnItemChosen(string pszTitle, string pszPath) { var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextViewModel.DataBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return(hr); }
public virtual int OnBeforeInsertion(IVsExpansionSession session) { if (session == null) { return(NativeMethods.E_UNEXPECTED); } this.expansionPrepared = false; this.expansionActive = true; // stash the expansion session pointer while the expansion is active if (this.expansionSession == null) { this.expansionSession = session; } else { // these better be the same! Debug.Assert(this.expansionSession == session); } // now set any field defaults that we have. foreach (DefaultFieldValue dv in this.fieldDefaults) { this.expansionSession.SetFieldDefault(dv.Field, dv.Value); } this.fieldDefaults.Clear(); return(NativeMethods.S_OK); }
public int EndExpansion() { _session = null; _sessionEnded = true; _selectionStart = _selectionEnd = null; return(VSConstants.S_OK); }
public int OnItemChosen(string pszTitle, string pszPath) { int hr = VSConstants.E_FAIL; if (!TextView.Caret.InVirtualSpace) { SnapshotPoint caretPoint = TextView.Caret.Position.BufferPosition; IVsExpansion expansion = TextBuffer.GetBufferAdapter <IVsExpansion>(); _earlyEndExpansionHappened = false; _title = pszTitle; var ts = TextSpanFromPoint(caretPoint); hr = expansion.InsertNamedExpansion(pszTitle, pszPath, ts, this, RGuidList.RLanguageServiceGuid, 0, out _expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set _expansionSession // to null to indicate that there is no active expansion session. This can occur when // the snippet inserted doesn't have any expansion fields. _expansionSession = null; _earlyEndExpansionHappened = false; _title = null; _shortcut = null; } } return(hr); }
public int OnItemChosen(string pszTitle, string pszPath) { int hr = VSConstants.E_FAIL; if (!TextView.Caret.InVirtualSpace) { var span = new Span(TextView.Caret.Position.BufferPosition, 0); var ts = TextSpanFromViewSpan(span); if (ts.HasValue) { var expansion = GetTargetBuffer().GetBufferAdapter <IVsExpansion>(); _earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, ts.Value, this, RGuidList.RLanguageServiceGuid, 0, out _expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set _expansionSession // to null to indicate that there is no active expansion session. This can occur when // the snippet inserted doesn't have any expansion fields. _expansionSession = null; _earlyEndExpansionHappened = false; } } } return(hr); }
public static bool TryGetHeaderNode( this IVsExpansionSession expansionSession, string name, [NotNullWhen(true)] out IXMLDOMNode?node ) { var query = name is null ? null : $@"node()[local-name()=""{name}""]"; IXMLDOMNode?localNode = null; if ( !ErrorHandler.Succeeded( ErrorHandler.CallWithCOMConvention( () => expansionSession.GetHeaderNode(query, out localNode) ) ) ) { node = null; return(false); } node = localNode; return(node is not null); }
public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return(VSConstants.S_OK); }
private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); }
private void EndSession() { if (_session != null) { _session.EndCurrentExpansion(0); _session = null; } }
public override int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { //the snippet picker code starts here if (nCmdID == (uint)VSConstants.VSStd2KCmdID.INSERTSNIPPET) { _manager.InvokeInsertionUI( _vsTextView, this, //the expansion client new Guid(_guid), null, //use all snippet types 0, //number of types (0 for all) 0, //ignored if iCountTypes == 0 null, //use all snippet kinds 0, //use all snippet kinds 0, //ignored if iCountTypes == 0 Constants.LanguageName, //the text to show in the prompt string.Empty); //only the ENTER key causes insert return(VSConstants.S_OK); } if (_session != null) { if (nCmdID == (uint)VSConstants.VSStd2KCmdID.BACKTAB) { _session.GoToPreviousExpansionField(); return(VSConstants.S_OK); } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB) { _session.GoToNextExpansionField(0); //false to support cycling through all the fields return(VSConstants.S_OK); } else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.CANCEL) { if (_session.EndCurrentExpansion(0) == VSConstants.S_OK) { _session = null; return(VSConstants.S_OK); } } } if (_session == null && nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB) { CaretPosition pos = _view.Caret.Position; TextExtent word = _navigator.GetTextStructureNavigator(_view.TextBuffer).GetExtentOfWord(pos.BufferPosition - 1); string textString = word.Span.GetText(); if (InsertAnyExpansion(textString, null, null)) { EndSession(); return(VSConstants.S_OK); } } return(Next.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); }
public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return(true); } return(false); }
public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return(VSConstants.S_OK); }
public int EndExpansion() { if (_expansionSession == null) { _earlyEndExpansionHappened = true; } else { _expansionSession = null; } return(VSConstants.S_OK); }
internal EnableSnippetsCommand(IVsTextView vsTextView, ITextView textView, ITextStructureNavigatorSelectorService navigator) { _vsTextView = vsTextView; _view = textView; _navigator = navigator; var textManager = (IVsTextManager2)Package.GetGlobalService(typeof(SVsTextManager)); ErrorHandler.ThrowOnFailure(textManager.GetExpansionManager(out _manager)); _session = null; }
internal virtual void EndTemplateEditing(bool leaveCaret) { if (!this.expansionActive || this.expansionSession == null) { this.expansionActive = false; return; } this.expansionSession.EndCurrentExpansion(leaveCaret ? 1 : 0); // fLeaveCaret=true this.expansionSession = null; this.expansionActive = false; }
public virtual bool TryHandleReturn() { // TODO(davip): Only move the caret if the enter was hit within the editable spans if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0); ExpansionSession = null; return(true); } return(false); }
/// <summary> /// Inserts a snippet based on a shortcut string. /// </summary> public int StartSnippetInsertion(out bool snippetInserted) { int hr = VSConstants.E_FAIL; snippetInserted = false; // Get the text at the current caret position and // determine if it is a snippet shortcut. if (!TextView.Caret.InVirtualSpace) { SnapshotPoint caretPoint = TextView.Caret.Position.BufferPosition; var document = REditorDocument.FindInProjectedBuffers(TextView.TextBuffer); // Document may be null in tests var textBuffer = document != null ? document.TextBuffer : TextView.TextBuffer; var expansion = textBuffer.GetBufferAdapter <IVsExpansion>(); _earlyEndExpansionHappened = false; Span span; _shortcut = TextView.GetItemBeforeCaret(out span, x => true); VsExpansion?exp = _cache.GetExpansion(_shortcut); // Get view span var ts = span.Length > 0 ? TextSpanFromSpan(TextView, span) : TextSpanFromPoint(caretPoint); // Map it down to R buffer var start = TextView.MapDownToR(span.Start); var end = TextView.MapDownToR(span.End); if (exp.HasValue && start.HasValue && end.HasValue) { // Insert into R buffer ts = TextSpanFromSpan(textBuffer, Span.FromBounds(start.Value, end.Value)); hr = expansion.InsertNamedExpansion(exp.Value.title, exp.Value.path, ts, this, RGuidList.RLanguageServiceGuid, 0, out _expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertExpansion returned, so set _expansionSession // to null to indicate that there is no active expansion session. This can occur when // the snippet inserted doesn't have any expansion fields. _expansionSession = null; _earlyEndExpansionHappened = false; _shortcut = null; _title = null; } ErrorHandler.ThrowOnFailure(hr); snippetInserted = true; return(hr); } } return(hr); }
//</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); }
public virtual bool TryHandleReturn() { if (ExpansionSession != null) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); ExpansionSession.EndCurrentExpansion(fLeaveCaret: hitWithinField ? 0 : 1); ExpansionSession = null; return(hitWithinField); } return(false); }
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); }
/// <summary> /// Constructor. /// </summary> /// <param name="textViewAdapter">IVsTextView</param> /// <param name="textView">ITextView</param> /// <param name="provider">Provider</param> internal CompletionCommandHandler(IVsTextView textViewAdapter, ITextView textView, CompletionHandlerProvider provider) { this.TextView = textView; this.VsTextView = textViewAdapter; this.Provider = provider; // Get the text manager from the service provider var textManager = (IVsTextManager2)this.Provider.ServiceProvider.GetService(typeof(SVsTextManager)); textManager.GetExpansionManager(out this.ExpansionManager); this.ExpansionSession = null; // Add the command to the command chain textViewAdapter.AddCommandFilter(this, out this.NextCommandHandler); }
internal CakeScriptSnippetsHandler(IVsTextView textViewAdapter, ITextView textView, CakeScriptSnippetsProvider provider) { this.textView = textView; this.provider = provider; vsTextView = textViewAdapter; //get the text manager from the service provider var textManager = (IVsTextManager2)provider.ServiceProvider.GetService(typeof(SVsTextManager)) ?? throw new ArgumentOutOfRangeException(nameof(provider), "Could not create a SVsTextManager!"); textManager.GetExpansionManager(out expansionManager); session = null; //add the command to the command chain textViewAdapter.AddCommandFilter(this, out nextCommandHandler); }
internal SnippetHandler(IVsTextView textViewAdapter, SnippetHandlerProvider provider, IVsEditorAdaptersFactoryService adaptersFactory, ITextView textView) { _adapterFactory = adaptersFactory; _textView = textView; _view = textViewAdapter; _mProvider = provider; //get the text manager from the service provider var textManager = (IVsTextManager2)_mProvider.ServiceProvider.GetService(typeof(SVsTextManager)); textManager.GetExpansionManager(out _mExManager); _session = null; //add the command to the command chain textViewAdapter.AddCommandFilter(this, out _mNextCommandHandler); _lines = (IVsTextLines)_adapterFactory.GetBufferAdapter(_textView.TextBuffer); }
public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return(tabbedInsideSnippetField); } return(false); }
/// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return(false); } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return(false); } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return(false); } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return(false); } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return(true); }
public int InsertNamedExpansion(string pszTitle, string pszPath, TextSpan textSpan) { if (_session != null) { // if the user starts an expansion session while one is in progress // then abort the current expansion session _session.EndCurrentExpansion(1); _session = null; } var expansion = _lines as IVsExpansion; if (expansion == null) { return(VSConstants.S_OK); } var selection = _textView.Selection; var snapshot = selection.Start.Position.Snapshot; _selectionStart = snapshot.CreateTrackingPoint(selection.Start.Position, PointTrackingMode.Positive); _selectionEnd = snapshot.CreateTrackingPoint(selection.End.Position, PointTrackingMode.Negative); _selectEndSpan = _sessionEnded = false; var hr = expansion.InsertNamedExpansion( pszTitle, pszPath, textSpan, this, new Guid(GuidList.PowerShellLanguage), 0, out _session ); if (ErrorHandler.Succeeded(hr)) { if (_sessionEnded) { _session = null; } } return(VSConstants.S_OK); }
public int OnAfterInsertion(IVsExpansionSession pSession) { //TextSpan[] pts = new TextSpan[1]; //if (pSession.GetSnippetSpan(pts) == VSConstants.S_OK) //{ // var span = pts[0]; // SmartIndenting.ProbeSmartIndent smartIndent; // if (_view.Properties.TryGetProperty(typeof(SmartIndenting.ProbeSmartIndent), out smartIndent) && smartIndent != null) // { // smartIndent.FixIndentingBetweenLines(span.iStartLine, span.iEndLine); // } // else // { // Log.WriteDebug("Failed to get smart indent object for view."); // } //} return(VSConstants.S_OK); }
/// <summary> /// Inserts a snippet based on a shortcut string. /// </summary> public int StartSnippetInsertion(out bool snippetInserted) { int hr = VSConstants.E_FAIL; snippetInserted = false; // Get the text at the current caret position and // determine if it is a snippet shortcut. if (!TextView.Caret.InVirtualSpace) { SnapshotPoint caretPoint = TextView.Caret.Position.BufferPosition; var textBuffer = GetTargetBuffer(); var expansion = textBuffer.GetBufferAdapter <IVsExpansion>(); _earlyEndExpansionHappened = false; Span span; var shortcut = TextView.GetItemBeforeCaret(out span, x => true); VsExpansion?exp = _cache.GetExpansion(shortcut); var ts = TextSpanFromViewSpan(span); if (exp.HasValue && ts.HasValue) { // Insert into R buffer hr = expansion.InsertNamedExpansion(exp.Value.title, exp.Value.path, ts.Value, this, RGuidList.RLanguageServiceGuid, 0, out _expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertExpansion returned, so set _expansionSession // to null to indicate that there is no active expansion session. This can occur when // the snippet inserted doesn't have any expansion fields. _expansionSession = null; _earlyEndExpansionHappened = false; } PositionCaretInField(0); ErrorHandler.ThrowOnFailure(hr); snippetInserted = true; return(hr); } } return(hr); }
/// <include file='doc\ExpansionProvider.uex' path='docs/doc[@for="ExpansionProvider.InsertSpecificExpansion"]/*' /> public virtual bool InsertSpecificExpansion(IVsTextView view, XmlElement snippet, TextSpan pos, string relativePath) { if (this.expansionActive) { this.EndTemplateEditing(true); } if (this.source.IsCompletorActive) { this.source.DismissCompletor(); } this.view = view; MSXML.IXMLDOMDocument doc = new MSXML.DOMDocumentClass(); if (!doc.loadXML(snippet.OuterXml)) { throw new ArgumentException(doc.parseError.reason); } Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid(); int hr = this.vsExpansion.InsertSpecificExpansion(doc, pos, this, guidLanguage, relativePath, out this.expansionSession); if (hr != NativeMethods.S_OK) { this.EndTemplateEditing(true); } else { // When inserting a snippet it is possible that the edit session is ended inside the insert // function (e.g. if the template has no editable fields). In this case we should not stay // in template edit mode because otherwise our filter will stole messages to the editor. if (!this.expansionActive) { this.expansionSession = null; } return(true); } return(false); }
public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return VSConstants.S_OK; }
public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return true; } return false; }
public virtual bool TryHandleReturn() { // TODO(davip): Only move the caret if the enter was hit within the editable spans if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0); ExpansionSession = null; return true; } return false; }
public int EndExpansion() { _expansionSession = null; return VSConstants.S_OK; }
public virtual int OnAfterInsertion(IVsExpansionSession session) { return NativeMethods.S_OK; }
public int OnItemChosen(string pszTitle, string pszPath) { var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; }
public int EndExpansion() { if (_expansionSession == null) { _earlyEndExpansionHappened = true; } else { _expansionSession = null; } _title = null; _shortcut = null; return VSConstants.S_OK; }
public int InsertSpecificExpansion(MSXML.IXMLDOMNode pSnippet, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, string pszRelativePath, out IVsExpansionSession pSession) { throw new NotImplementedException(); }
public int InsertNamedExpansion(string bstrTitle, string bstrPath, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, int fShowDisambiguationUI, out IVsExpansionSession pSession) { throw new NotImplementedException(); }
public int InsertSpecificExpansion(IXMLDOMNode pSnippet, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, string pszRelativePath, out IVsExpansionSession pSession) { TextBuffer.Insert(0, "specific-expansion"); pSession = new VsExpansionSessionMock(); return VSConstants.S_OK; }
public int InsertNamedExpansion(string bstrTitle, string bstrPath, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, int fShowDisambiguationUI, out IVsExpansionSession pSession) { TextBuffer.Insert(0, bstrTitle); pSession = new VsExpansionSessionMock(); return VSConstants.S_OK; }
public int InsertExpansion(TextSpan tsContext, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, out IVsExpansionSession pSession) { TextBuffer.Insert(0, "expansion"); pSession = new VsExpansionSessionMock(); return VSConstants.S_OK; }
public virtual int OnBeforeInsertion(IVsExpansionSession session) { if (session == null) return NativeMethods.E_UNEXPECTED; this.expansionPrepared = false; this.expansionActive = true; // stash the expansion session pointer while the expansion is active if (this.expansionSession == null) { this.expansionSession = session; } else { // these better be the same! Debug.Assert(this.expansionSession == session); } // now set any field defaults that we have. foreach (DefaultFieldValue dv in this.fieldDefaults) { this.expansionSession.SetFieldDefault(dv.Field, dv.Value); } this.fieldDefaults.Clear(); return NativeMethods.S_OK; }
public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; }
public int EndExpansion() { _session = null; _sessionEnded = true; _selectionStart = _selectionEnd = null; return VSConstants.S_OK; }
public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return VSConstants.S_OK; }
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); }
private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>(); var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); }
public int InsertExpansion(TextSpan tsContext, TextSpan tsInsertPos, IVsExpansionClient pExpansionClient, Guid guidLang, out IVsExpansionSession pSession) { throw new NotImplementedException(); }
public virtual bool TryHandleReturn() { if (ExpansionSession != null) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); ExpansionSession.EndCurrentExpansion(fLeaveCaret: hitWithinField ? 0 : 1); ExpansionSession = null; return hitWithinField; } return false; }
public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; }
public int OnItemChosen(string pszTitle, string pszPath) { int hr = VSConstants.E_FAIL; if (!TextView.Caret.InVirtualSpace) { SnapshotPoint caretPoint = TextView.Caret.Position.BufferPosition; IVsExpansion expansion = TextBuffer.GetBufferAdapter<IVsExpansion>(); _earlyEndExpansionHappened = false; _title = pszTitle; var ts = TextSpanFromPoint(caretPoint); hr = expansion.InsertNamedExpansion(pszTitle, pszPath, ts, this, RGuidList.RLanguageServiceGuid, 0, out _expansionSession); if (_earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set _expansionSession // to null to indicate that there is no active expansion session. This can occur when // the snippet inserted doesn't have any expansion fields. _expansionSession = null; _earlyEndExpansionHappened = false; _title = null; _shortcut = null; } } return hr; }
private void AddReferencesAndImports( IVsExpansionSession pSession, int position, CancellationToken cancellationToken) { if (!TryGetSnippetNode(pSession, out var snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); }
public int InsertNamedExpansion(string pszTitle, string pszPath, TextSpan textSpan) { if (_session != null) { // if the user starts an expansion session while one is in progress // then abort the current expansion session _session.EndCurrentExpansion(1); _session = null; } var selection = _textView.Selection; var snapshot = selection.Start.Position.Snapshot; _selectionStart = snapshot.CreateTrackingPoint(selection.Start.Position, VisualStudio.Text.PointTrackingMode.Positive); _selectionEnd = snapshot.CreateTrackingPoint(selection.End.Position, VisualStudio.Text.PointTrackingMode.Negative); _selectEndSpan = _sessionEnded = false; int hr = _expansion.InsertNamedExpansion( pszTitle, pszPath, textSpan, this, GuidList.guidPythonLanguageServiceGuid, 0, out _session ); if (ErrorHandler.Succeeded(hr)) { if (_sessionEnded) { _session = null; } } return hr; }
/// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; }
public int OnBeforeInsertion(IVsExpansionSession pSession) { return VSConstants.S_OK; }
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } }
public int EndExpansion() { this.expansionActive = false; this.expansionSession = null; return NativeMethods.S_OK; }
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { // Handle VS commands to support code snippets 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, Constants.IronPythonLanguageServiceGuid, null, 0, 1, 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 (activeSession != null) { activeSession.Dismiss(); } ShowCompletion(); return VSConstants.S_OK; } // Handle Enter/Tab commit keys if (activeSession != null && (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)) { if (activeSession.SelectedCompletionSet.SelectionStatus.IsSelected) activeSession.Commit(); else activeSession.Dismiss(); return VSConstants.S_OK; } // Handle Code Snippets after pressing the Tab key without completion if (activeSession == null && (nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB)) { using (var systemState = new SystemState()) { // Get the current line text until the cursor var line = this.textView.GetTextViewLineContainingBufferPosition(this.textView.Caret.Position.BufferPosition); var text = this.textView.TextSnapshot.GetText(line.Start.Position, this.textView.Caret.Position.BufferPosition - line.Start.Position); // Create a tokenizer for the text var tokenizer = new Tokenizer(text.ToCharArray(), true, systemState, new CompilerContext(string.Empty, new QuietCompilerSink())); // Get the last token in the text Token currentToken, lastToken = null; while ((currentToken = tokenizer.Next()).Kind != TokenKind.NewLine) { lastToken = currentToken; } if (lastToken != null && lastToken.Kind != TokenKind.Constant) { var expansionManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager)); var snippetsEnumerator = new SnippetsEnumerator(expansionManager, Constants.IronPythonLanguageServiceGuid); // Search a snippet that matched the token text var expansion = snippetsEnumerator.FirstOrDefault(e => e.title == lastToken.Value.ToString()); 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 (activeSession == 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)) { if (activeSession.SelectedCompletionSet.SelectionStatus.IsSelected) activeSession.Commit(); else activeSession.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; } } } } // we haven't handled this command so pass it onto the next target return this.nextCommandTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); }