protected override void OnBeforeQueryStatus(object sender, EventArgs e) { base.OnBeforeQueryStatus(sender, e); ITextView view = TextEditor.GetCurrentView(); if (view == null) { return; } ITextCaret caret = view.Caret; if (caret == null) { return; } var point = TextEditor.MapCaretToPrimaryBuffer(view); //SnapshotPoint? point = caret.Position.BufferPosition; if (point != null) { IUserOutlining outlining = OutliningManager.Get(point.Value.Snapshot.TextBuffer); Command.Enabled = outlining.IsInOutliningRegion(point.Value); } }
protected override void OnInvoke(object sender, EventArgs e) { base.OnInvoke(sender, e); ITextView view = TextEditor.GetCurrentView(); if (view == null) { return; } ITextCaret caret = view.Caret; if (caret == null) { return; } var point = TextEditor.MapCaretToPrimaryBuffer(view); //SnapshotPoint? point = caret.Position.BufferPosition; if (point != null) { IUserOutlining outlining = OutliningManager.Get(point.Value.Snapshot.TextBuffer); outlining.RemoveAt(point.Value); } }
// This method should only be called once (it is normally called from the ctor unless we're using // ITextEditorFactoryService2.CreateTextViewWithoutInitialization on the factory to delay initialization). internal void Initialize() { if (_hasInitializeBeenCalled) { throw new InvalidOperationException("Attempted to Initialize a WpfTextView twice"); } _bufferGraph = _factoryService.BufferGraphFactoryService.CreateBufferGraph(this.TextViewModel.VisualBuffer); //_editorFormatMap = _factoryService.EditorFormatMapService.GetEditorFormatMap(this); _selection = new TextSelection(_textEditor, this); // Create caret _caret = new TextCaret(_textEditor, this); // this.Loaded += OnLoaded; _connectionManager = new ConnectionManager(this, _factoryService.TextViewConnectionListeners, _factoryService.GuardedOperations); SubscribeToEvents(); // Binding content type specific assets includes calling out to content-type // specific view creation listeners. We need to do this as late as possible. this.BindContentTypeSpecificAssets(null, TextViewModel.DataModel.ContentType); //Subscribe now so that there is no chance that a layout could be forced by a text change. //_visualBuffer.ChangedLowPriority += OnVisualBufferChanged; //_visualBuffer.ContentTypeChanged += OnVisualBufferContentTypeChanged; _hasInitializeBeenCalled = true; }
private int SyncedOperation(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { ITextCaret caret = m_textView.Caret; var tempTrackList = m_trackList; m_trackList = new List <ITrackingPoint>(); SnapshotPoint snapPoint = tempTrackList[0].GetPoint(m_textView.TextSnapshot); int result = 0; m_dte.UndoContext.Open("Multi-point edit"); for (int i = 0; i < tempTrackList.Count; i++) { snapPoint = tempTrackList[i].GetPoint(m_textView.TextSnapshot); caret.MoveTo(snapPoint); Debug.Print("Caret #" + i + " pos : " + caret.Position); result = NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); AddSyncPoint(m_textView.Caret.Position); } m_dte.UndoContext.Close(); RedrawScreen(); return(result); }
public static Mock <ITextView> CreateTextView( ITextBuffer textBuffer = null, ITextCaret caret = null, ITextSelection selection = null, ITextViewRoleSet textViewRoleSet = null, ITextViewModel textViewModel = null, IEditorOptions editorOptions = null, IBufferGraph bufferGraph = null, PropertyCollection propertyCollection = null, MockRepository factory = null) { factory = factory ?? new MockRepository(MockBehavior.Strict); textBuffer = textBuffer ?? CreateTextBuffer(100, factory: factory).Object; caret = caret ?? CreateCaret(factory: factory).Object; selection = selection ?? CreateSelection(factory: factory).Object; propertyCollection = propertyCollection ?? new PropertyCollection(); textViewRoleSet = textViewRoleSet ?? CreateTextViewRoleSet(factory: factory).Object; editorOptions = editorOptions ?? CreateEditorOptions(factory: factory).Object; bufferGraph = bufferGraph ?? CreateBufferGraph(factory: factory).Object; textViewModel = textViewModel ?? CreateTextViewModel(textBuffer: textBuffer, factory: factory).Object; var view = factory.Create <ITextView>(); view.SetupGet(x => x.Caret).Returns(caret); view.SetupGet(x => x.Selection).Returns(selection); view.SetupGet(x => x.TextBuffer).Returns(textBuffer); view.SetupGet(x => x.TextSnapshot).Returns(() => textBuffer.CurrentSnapshot); view.SetupGet(x => x.Properties).Returns(propertyCollection); view.SetupGet(x => x.Roles).Returns(textViewRoleSet); view.SetupGet(x => x.Options).Returns(editorOptions); view.SetupGet(x => x.BufferGraph).Returns(bufferGraph); view.SetupGet(x => x.TextViewModel).Returns(textViewModel); return(view); }
public bool SearchImplement() { #if NOTIMPLEMENTED // Try to retrieve an already parsed list of Tags XSharpClassifier xsClassifier = null; if (m_textBuffer.Properties.ContainsProperty(typeof(XSharpClassifier))) { xsClassifier = m_textBuffer.Properties[typeof(XSharpClassifier)] as XSharpClassifier; } ITextCaret caret = m_textView.Caret; if (xsClassifier != null && xsClassifier.Snapshot.Version == caret.Position.BufferPosition.Snapshot.Version) { // ITextSnapshot snapshot = xsClassifier.Snapshot; // Note we should use the same snapshot everywhere in this code. // the snapshot in the classifier may be older than the current snapshot if (snapshot.Length == 0) { return(false); // Should not happen : This means that the buffer is empty !!! } // ITextViewLine iLine = caret.ContainingTextViewLine; SnapshotSpan Span = new SnapshotSpan(snapshot, iLine.Start.Position, iLine.Length); // IList <ClassificationSpan> classifications = xsClassifier.GetClassificationSpans(Span); // foreach (var classification in classifications) { if (!classification.Span.Contains(caret.Position.BufferPosition)) { continue; } var name = classification.ClassificationType.Classification.ToLower(); // if (name.Contains("keyword")) { SnapshotSpan cspan = classification.Span; string Keyword = snapshot.GetText(cspan); Keyword = Keyword.ToLower(); // Search for Implements if (Keyword.Equals("implements")) { // Disable LightBulb return(false); //return true; } } } } #endif return(false); }
internal override void Execute(EmacsCommandContext context) { // we can't use the repeating support because of the special behavior of UniversalArgument=0 if (!context.UniversalArgument.HasValue || context.Manager.UniversalArgument == 0) { ITextCaret caret = context.TextView.Caret; int caretPosition = caret.Position.BufferPosition.Position; ITextViewLine caretViewLine = caret.ContainingTextViewLine; int endOfLine = caretViewLine.End.Position; int startOfNextLine = caretViewLine.EndIncludingLineBreak.Position; if (caretPosition == endOfLine) { context.EditorOperations.Delete(caretPosition, startOfNextLine - caretPosition); } else { // does the line contain whitespaces from caret till the end? for (int whitespaceChecker = caretPosition; ; ++whitespaceChecker) { if (whitespaceChecker <= endOfLine) { if (char.IsWhiteSpace(context.TextView.TextSnapshot[whitespaceChecker])) { continue; } else { context.EditorOperations.DeleteToEndOfPhysicalLine(); break; } } else { // reached end of line and every character was a whitespace context.EditorOperations.Delete(caretPosition, startOfNextLine - caretPosition); break; } } } } else // (context.UniversalArgument > 0) { for (int count = context.Manager.GetUniversalArgumentOrDefault(1); count > 0; count--) { int caretPosition = context.TextView.Caret.Position.BufferPosition.Position; int nextLineStart = context.TextView.Caret.ContainingTextViewLine.EndIncludingLineBreak.Position; context.EditorOperations.Delete(caretPosition, nextLineStart - caretPosition); } } }
private bool tryGetWordUnderCaret(out TextExtent o_WordExtent) { ITextCaret caret = m_textView.Caret; SnapshotPoint point = caret.Position.BufferPosition; if (caret.Position.BufferPosition <= 0) { o_WordExtent = default(TextExtent); return(false); } ITextStructureNavigator navigator = m_factory.NavigatorService.GetTextStructureNavigator(m_textBuffer); o_WordExtent = navigator.GetExtentOfWord(point); return(true); }
public static TextSelectionState Save(ITextSelection selection, ITextCaret caret) { TextSelectionState ret = new TextSelectionState(); ret.m_mode = selection.Mode; ret.m_isReversed = selection.IsReversed; ret.m_caretPosition = caret.Position; ret.m_trackedSpans = new List <ITrackingSpan>(); foreach (var span in selection.SelectedSpans) { ret.m_trackedSpans.Add(selection.TextView.TextBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive)); } return(ret); }
public static Mock <ITextView> CreateTextView( ITextBuffer textBuffer = null, ITextCaret caret = null, ITextSelection selection = null, MockRepository factory = null) { factory = factory ?? new MockRepository(MockBehavior.Strict); textBuffer = textBuffer ?? CreateTextBuffer(100, factory: factory).Object; caret = caret ?? CreateCaret(factory: factory).Object; selection = selection ?? CreateSelection(factory: factory).Object; var view = factory.Create <ITextView>(); view.SetupGet(x => x.Caret).Returns(caret); view.SetupGet(x => x.Selection).Returns(selection); view.SetupGet(x => x.TextBuffer).Returns(textBuffer); view.SetupGet(x => x.TextSnapshot).Returns(() => textBuffer.CurrentSnapshot); return(view); }
public bool IsEnabled(ITextView view, ref String commandText) { ITextCaret caret = view.Caret; if (caret == null) { return(false); } var point = TextEditor.MapCaretToPrimaryBuffer(view); if (point != null) { IUserOutlining outlining = UserOutliningManager.Get(point.Value.Snapshot.TextBuffer); return(outlining.IsInOutliningRegion(point.Value)); } return(false); }
private bool TryGetWordUnderCaret(out TextExtent wordExtent) { ITextCaret caret = TextView.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition - 1; ITextStructureNavigator navigator = this.codeFixedSourceProvider.NavigatorService.GetTextStructureNavigator(TextBuffer); wordExtent = navigator.GetExtentOfWord(point); return(true); } else { wordExtent = default(TextExtent); return(false); } }
private bool TryGetWordUnderCaret(out TextExtent wordExtent) { ITextCaret caret = _textView.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition - 1; } else { wordExtent = default(TextExtent); return(false); } ITextStructureNavigator navigator = _factory.NavigatorService.GetTextStructureNavigator(_textBuffer); wordExtent = navigator.GetExtentOfWord(point); return(true); }
private IEnumerable <ITagSpan <JiraIssueActionsSmartTag> > getTagsFromCacheFor(IEnumerable <SnapshotSpan> spans) { if (!GlobalSettings.shouldShowIssueLinks(view.TextSnapshot.LineCount)) { yield break; } JiraServer selectedServer = AtlassianPanel.Instance.Jira.CurrentlySelectedServerOrDefault; if (selectedServer == null) { yield break; } ITextCaret caret = view.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition; } else { yield break; } foreach (SnapshotSpan span in spans) { foreach (TagCache.TagEntry tagEntry in tagCache.Entries) { if (tagEntry.Start >= span.Start && tagEntry.End <= span.End) { SnapshotSpan result = new SnapshotSpan(tagEntry.Start, tagEntry.End); if (result.Start.Position <= point.Position && result.End.Position >= point.Position) { yield return(new TagSpan <JiraIssueActionsSmartTag>(result, new JiraIssueActionsSmartTag(getSmartTagActions(result)))); } } } } }
public bool Handle(ITextView view) { ITextCaret caret = view.Caret; if (caret == null) { return(false); } var point = TextEditor.MapCaretToPrimaryBuffer(view); //SnapshotPoint? point = caret.Position.BufferPosition; if (point != null) { IUserOutlining outlining = UserOutliningManager.Get(point.Value.Snapshot.TextBuffer); outlining.RemoveAt(point.Value); Telemetry.WriteEvent("Remove Outlining"); } return(true); }
private int Paste(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (Clipboard.ContainsText() && points.Any()) { var text = Clipboard.GetText(); var lines = text.Replace("\r", "").Split('\n'); if (lines.Length == points.Count) { ITextCaret caret = textView.Caret; var tmpPoints = points; points = new List <Tracking>(); dte.UndoContext.Open("Multiedit"); var i = 0; foreach (var tracking in tmpPoints) { Clipboard.SetText(lines[i]); tracking.Apply(textView); NextTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); AddSyncPoint(caret.Position); i++; } Clipboard.SetText(text); dte.UndoContext.Close(); RedrawScreen(); return(VSConstants.S_OK); } else { return(SyncedOperation(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } } else { return(SyncedOperation(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } }
private int SyncedOperation(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { Debug.WriteLine("SyncedOperation"); ITextCaret caret = textView.Caret; var tmpPoints = points; points = new List <Tracking>(); dte.UndoContext.Open("Multiedit"); try { foreach (var track in tmpPoints) { track.Apply(textView); NextTarget.Exec(pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); if (!textView.Selection.IsEmpty) { AddSyncPoint(textView.Selection.Start.Position, textView.Selection.End.Position, textView.Selection.IsReversed); textView.Selection.Clear(); } else { AddSyncPoint(caret.Position); } } } finally { dte.UndoContext.Close(); RedrawScreen(); } return(VSConstants.S_OK); }
//</Snippet6> //<Snippet7> public IEnumerable <ITagSpan <TestSmartTag> > GetTags(NormalizedSnapshotSpanCollection spans) { ITextSnapshot snapshot = m_buffer.CurrentSnapshot; if (snapshot.Length == 0) { yield break; //don't do anything if the buffer is empty } //set up the navigator ITextStructureNavigator navigator = m_provider.NavigatorService.GetTextStructureNavigator(m_buffer); foreach (var span in spans) { ITextCaret caret = m_view.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition - 1; } else { yield break; } TextExtent extent = navigator.GetExtentOfWord(point); //don't display the tag if the extent has whitespace if (extent.IsSignificant) { yield return(new TagSpan <TestSmartTag>(extent.Span, new TestSmartTag(GetSmartTagActions(extent.Span)))); } else { yield break; } } }
private object GetConfigAfterCaret(SnapshotSpan range) { ITextCaret caret = m_textView.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition - 1; } else { return(null); } if (point.GetChar() != '{') { return(null); } var ss = point.Snapshot; for (int lineNumber = point.GetContainingLine().LineNumber; lineNumber < ss.LineCount; ++lineNumber) { var line = ss.GetLineFromLineNumber(lineNumber); var lineText = line.GetText(); for (int i = 0; i < lineText.Length; ++i) { if (lineText[i] == '}') { var resultSpan = new SnapshotSpan(point, line.Start + i + 1); var str = resultSpan.GetText(); try { var document = (ITextDocument)m_textBuffer.Properties[typeof(ITextDocument)]; var folder = Path.GetDirectoryName(document.FilePath); var obj = JObject.Parse(str); if (obj.Contains("kbId") && obj.Contains("endpointKey")) { var result = new ConfigBase <QnAMakerService>(obj); result.FilePath = $@"{folder}\Deployment\Resources\QnA\en\{obj["id"].ToString()}.lu"; return(result); } else if (obj.Contains("appid")) { if (obj.Contains("type") && obj["type"].ToString() == "dispatch") { var result = new ConfigBase <DispatchService>(obj); if (string.IsNullOrEmpty(result.Config.Version)) { result.Config.Version = "Dispatch"; } return(result); } else if (obj.Contains("id")) { var result = new ConfigBase <LuisService>(obj); result.FilePath = $@"{folder}\Deployment\Resources\LU\en\{obj["id"].ToString()}.lu"; return(result); } else { return(null); } } else { return(null); } } catch (Exception e) { return(null); } } } } return(null); }
protected static ITextView CreateFocusedTextView(Func <ITextBuffer> textBufferAccessor = null, ITextCaret caret = null) { var focusedTextView = new Mock <ITextView>(); focusedTextView.Setup(textView => textView.HasAggregateFocus) .Returns(true); if (textBufferAccessor != null) { focusedTextView.Setup(textView => textView.TextBuffer) .Returns(textBufferAccessor); } if (caret != null) { focusedTextView.Setup(textView => textView.Caret) .Returns(caret); } return(focusedTextView.Object); }
internal int SyncedOperation(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int result = 0; if (_trackPointList.Count > 0) { // Se tem algo selecionado if (Selecting) { switch (nCmdID) { case ((uint)VSConstants.VSStd2KCmdID.TYPECHAR): case ((uint)VSConstants.VSStd2KCmdID.BACKSPACE): case ((uint)VSConstants.VSStd2KCmdID.TAB): case ((uint)VSConstants.VSStd97CmdID.Delete): case ((uint)VSConstants.VSStd2KCmdID.RETURN): case ((uint)VSConstants.VSStd2KCmdID.BACKTAB): case ((uint)VSConstants.VSStd97CmdID.Paste): /* Ctrl+V */ DeleteSelection(); break; default: break; } } //char typedChar = char.MinValue; //typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); _view.Selection.Clear(); ITextCaret caret = _view.Caret; List <ITrackingPoint> tempTrackList = _trackPointList; _trackPointList = new List <ITrackingPoint>(); SnapshotPoint snapshotPoint = tempTrackList[0].GetPoint(_view.TextSnapshot); //m_dte.UndoContext.Open("Multi-point edit"); for (int i = 0; i < tempTrackList.Count; i++) { snapshotPoint = tempTrackList[i].GetPoint(_view.TextSnapshot); caret.MoveTo(snapshotPoint); // Propaga o evento para os demais locais result = _nextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); AddTrackingPoint(_view.Caret.Position); } //m_dte.UndoContext.Close(); RedrawScreen(); } return(result); }
bool CompleteCompletionSession(char ch) { if (_completionSession == null) { return(false); } bool commit = false; bool moveBack = false; Completion completion = null; XSCompletion xscompletion = null; ITextCaret caret = null; WriteOutputMessage("CompleteCompletionSession()"); if (_completionSession.SelectedCompletionSet != null) { bool addDelim = false; if (_completionSession.SelectedCompletionSet.SelectionStatus.Completion != null) { completion = _completionSession.SelectedCompletionSet.SelectionStatus.Completion; } xscompletion = completion as XSCompletion; Kind kind = Kind.Unknown; if (xscompletion != null) { kind = xscompletion.Kind; } bool ctor = false; // some tokens need to be added to the insertion text. switch (kind) { case Kind.Keyword: formatKeyword(completion); break; case Kind.Class: case Kind.Structure: case Kind.Constructor: ctor = true; goto default; default: switch (ch) { case '{' when ctor: case '}' when ctor: if (!completion.InsertionText.EndsWith("{")) { completion.InsertionText += "{"; } break; case '\t': // Tab case '\r': // CR case '\n': // CR case '.': // DOT case ':': // COLON case '\0': break; default: var s = ch.ToString(); if (!completion.InsertionText.EndsWith(s)) { completion.InsertionText += s; } break; } break; } if ((_completionSession.SelectedCompletionSet.Completions.Count > 0) && (_completionSession.SelectedCompletionSet.SelectionStatus.IsSelected)) { if (XSettings.EditorCompletionAutoPairs) { caret = _completionSession.TextView.Caret; addDelim = true; WriteOutputMessage(" --> select " + completion.InsertionText); if (kind == Kind.Constructor) { completion.InsertionText += "{"; } else if (kind.HasParameters() && !completion.InsertionText.EndsWith("(")) { completion.InsertionText += "("; } } commit = true; } else { if (completion != null) { // Push the completion char into the InsertionText if needed if (!completion.InsertionText.EndsWith(ch.ToString())) { completion.InsertionText += ch; } if (XSettings.EditorCompletionAutoPairs) { caret = _completionSession.TextView.Caret; addDelim = true; } } commit = true; } if (addDelim) { if (completion.InsertionText.EndsWith("(")) { moveBack = true; completion.InsertionText += ")"; } else if (completion.InsertionText.EndsWith("{")) { moveBack = true; completion.InsertionText += "}"; } else if (completion.InsertionText.EndsWith("[")) { moveBack = true; completion.InsertionText += "]"; } } } if (commit) { WriteOutputMessage(" --> Commit"); var session = _completionSession; session.Properties.TryGetProperty(XsCompletionProperties.Type, out IXTypeSymbol type); string insertionText = completion.InsertionText; session.Properties.TryGetProperty(XsCompletionProperties.Char, out char triggerChar); if (ch == '.' || ch == ':') { if (insertionText.IndexOfAny("({".ToCharArray()) == -1) { completion.InsertionText += ch; } } _completionSession.Commit(); if (moveBack && (caret != null)) { caret.MoveToPreviousCaretPosition(); } // if a method or constructor was chosen, then trigger the signature help if (insertionText.Contains('(') || insertionText.Contains('{')) { TriggerSignatureHelp(type, insertionText, triggerChar); } return(true); } WriteOutputMessage(" --> Dismiss"); _completionSession.Dismiss(); return(false); }
public static Mock<ITextView> CreateTextView( ITextBuffer buffer = null, ITextCaret caret = null, ITextSelection selection = null, MockRepository factory = null) { factory = factory ?? new MockRepository(MockBehavior.Strict); buffer = buffer ?? CreateTextBuffer(100, factory: factory).Object; caret = caret ?? CreateCaret(factory: factory).Object; selection = selection ?? CreateSelection(factory: factory).Object; var view = factory.Create<ITextView>(); view.SetupGet(x => x.Caret).Returns(caret); view.SetupGet(x => x.Selection).Returns(selection); view.SetupGet(x => x.TextBuffer).Returns(buffer); view.SetupGet(x => x.TextSnapshot).Returns(() => buffer.CurrentSnapshot); return view; }
public static void Restore(TextSelectionState state, ITextSelection selection, ITextCaret caret) { caret.MoveTo( state.m_caretPosition.BufferPosition.TranslateTo(selection.TextView.TextSnapshot, PointTrackingMode.Positive), state.m_caretPosition.Affinity); selection.Mode = state.m_mode; SnapshotSpan newSpan; if (state.m_mode == TextSelectionMode.Box) { newSpan = new SnapshotSpan( state.m_trackedSpans[0].GetStartPoint(selection.TextView.TextBuffer.CurrentSnapshot), state.m_trackedSpans[state.m_trackedSpans.Count - 1].GetEndPoint(selection.TextView.TextBuffer.CurrentSnapshot)); } else { newSpan = state.m_trackedSpans[0].GetSpan(selection.TextView.TextBuffer.CurrentSnapshot); } selection.Select(newSpan, state.m_isReversed); }
private void MenuItemCallback(object sender, EventArgs e, bool visitor) { try { // Return if I can't determine what application this is. DTE application = Workspaces.Help.GetApplication(); if (application == null) { return; } // Get active view and determine if it's a grammar file. var grammar_view = AntlrLanguagePackage.Instance.GetActiveView(); if (grammar_view == null) { return; } ITextCaret car = grammar_view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; int pos = bp.Position; ITextBuffer buffer = grammar_view.TextBuffer; var g4_file_path = buffer.GetFFN().Result; if (g4_file_path == null) { return; } IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(g4_file_path); if (!grammar_description.IsFileType(g4_file_path)) { return; } // Get name of base class for listener and visitor. These are generated by Antlr, // constructed from the name of the file. var grammar_name = Path.GetFileName(g4_file_path); grammar_name = Path.GetFileNameWithoutExtension(grammar_name); var listener_baseclass_name = visitor ? (grammar_name + "BaseVisitor") : (grammar_name + "BaseListener"); var listener_class_name = visitor ? ("My" + grammar_name + "Visitor") : ("My" + grammar_name + "Listener"); // In the current view, find the details of the Antlr symbol at the cursor. TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[grammar_view] .GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; // Now, check for valid classification type. var cla = -1; bool can_gotovisitor = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[grammar_view].GetClassificationSpans(span).Where( classification => { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int c)) { return(false); } cla = c; return(grammar_description.CanGotovisitor[cla]); }).Any(); if (!can_gotovisitor) { return; } // Find defining occurrence. List <Antlr4.Runtime.Tree.TerminalNodeImpl> where = new List <Antlr4.Runtime.Tree.TerminalNodeImpl>(); List <ParserDetails> where_details = new List <ParserDetails>(); Antlr4.Runtime.Tree.TerminalNodeImpl token = null; foreach (var kvp in ParserDetailsFactory.AllParserDetails) { string file_name = kvp.Key; ParserDetails details = kvp.Value; { var it = details.Defs.Where( (t) => t.Value == cla && t.Key.Symbol.Text == span.GetText()).Select(t => t.Key); where.AddRange(it); foreach (var i in it) { where_details.Add(details); } } } if (where.Any()) { token = where.First(); } else { System.Windows.Forms.MessageBox.Show( "Symbol '" + span.GetText() + "' definer not found."); return; } // Get the symbol name as a string. var symbol_name = token.Symbol.Text; var capitalized_symbol_name = Capitalized(symbol_name); // Parse all the C# files in the solution. Dictionary <string, SyntaxTree> trees = new Dictionary <string, SyntaxTree>(); foreach (var item in DteExtensions.SolutionFiles(application)) { string file_name = item.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = item.Properties.Item("FullPath").Value; string ffn = (string)prop; StreamReader sr = new StreamReader(ffn); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[ffn] = tree; } catch (Exception) { } } } // Find all occurrences of visitor class. List <ClassDeclarationSyntax> found_class = new List <ClassDeclarationSyntax>(); string class_file_path = null; try { foreach (var kvp in trees) { var file_name = kvp.Key; var tree = kvp.Value; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); if (root == null) { continue; } foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } } catch { } if (found_class.Count == 0) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Look in grammar directory for any C# files. string name_space = null; string ffn = Path.GetFullPath(g4_file_path); ffn = Path.GetDirectoryName(ffn); foreach (var i in DteExtensions.SolutionFiles(application)) { string file_name = i.Name; if (file_name != null) { string prefix = file_name.TrimSuffix(".cs"); if (prefix == file_name) { continue; } try { object prop = i.Properties.Item("FullPath").Value; string ffncs = (string)prop; // Look for namespace. var t = trees[ffncs]; if (t == null) { continue; } var root = t.GetCompilationUnitRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } name_space = namespace_member.Name.ToString(); break; } } catch (Exception) { } } } if (name_space == null) { name_space = "Generated"; } // Create class. string clazz = visitor ? $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name}<Result> : {listener_baseclass_name}<Result> {{ //public override Result VisitA([NotNull] A3Parser.AContext context) //{{ // return VisitChildren(context); //}} }} }} " : $@" using System; using System.Collections.Generic; using System.Text; namespace {name_space} {{ class {listener_class_name} : {listener_baseclass_name} {{ //public override void EnterA(A3Parser.AContext context) //{{ // base.EnterA(context); //}} //public override void ExitA(A3Parser.AContext context) //{{ // base.ExitA(context); //}} }} }} "; class_file_path = ffn + Path.DirectorySeparatorChar + listener_class_name + ".cs"; System.IO.File.WriteAllText(class_file_path, clazz); var item = ProjectHelpers.GetSelectedItem(); string folder = FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } var file = new FileInfo(class_file_path); var selectedItem = Workspaces.Workspace.Instance.FindDocument(class_file_path); if (selectedItem == null) { //var selectedProject = item as Project; //Project project = selectedItem?.ContainingProject ?? selectedProject ?? null; //var projectItem = project.AddFileToProject(file); } // Redo parse. try { StreamReader sr = new StreamReader(class_file_path); string code = sr.ReadToEnd(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); throw new Exception(); } } } } } catch { } } // Look for enter or exit method for symbol. MethodDeclarationSyntax found_member = null; var ctl = CtrlKeyState.GetStateForView(grammar_view).Enabled; var capitalized_member_name = ""; if (visitor) { capitalized_member_name = "Visit" + capitalized_symbol_name; } else if (ctl) { capitalized_member_name = "Exit" + capitalized_symbol_name; } else { capitalized_member_name = "Enter" + capitalized_symbol_name; } var capitalized_grammar_name = Capitalized(grammar_name); try { foreach (var fc in found_class) { foreach (var me in fc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } if (found_member == null) { if (!global::Options.POptions.GetBoolean("GenerateVisitorListener")) { return; } // Find point for edit. var fc = found_class.First(); var here = fc.OpenBraceToken; var spn = here.FullSpan; var end = spn.End; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; var res = vstv.GetBuffer(out IVsTextLines ppBuffer); var nss = new SnapshotSpan(cc, spn.End + 1, 0); var txt_span = nss.Span; int line_number; int colum_number; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); res = ppBuffer.CreateEditPoint(line_number, colum_number, out object ppEditPoint); EditPoint editPoint = ppEditPoint as EditPoint; // Create class. string member = visitor ? $@" public override Result {capitalized_member_name}([NotNull] {capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ return VisitChildren(context); }} " : $@" public override void {capitalized_member_name}({capitalized_grammar_name}Parser.{capitalized_symbol_name}Context context) {{ base.{capitalized_member_name}(context); }} "; editPoint.Insert(member); // Redo parse. try { vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); if (vstv == null) { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } var text_buffer = vstv.GetITextBuffer(); var code = text_buffer.GetBufferText(); SyntaxTree tree = CSharpSyntaxTree.ParseText(code); trees[class_file_path] = tree; } catch (Exception) { } // Redo find class. try { var tree = trees[class_file_path]; var save = class_file_path; class_file_path = null; // Look for IParseTreeListener or IParseTreeVisitor classes. var root = (CompilationUnitSyntax)tree.GetRoot(); foreach (var nm in root.Members) { var namespace_member = nm as NamespaceDeclarationSyntax; if (namespace_member == null) { continue; } foreach (var cm in namespace_member.Members) { var class_member = cm as ClassDeclarationSyntax; if (class_member == null) { continue; } var bls = class_member.BaseList; if (bls == null) { continue; } var types = bls.Types; Regex reg = new Regex("[<].+[>]"); foreach (var type in types) { var s = type.ToString(); s = reg.Replace(s, ""); if (s.ToString() == listener_baseclass_name) { // Found the right class. found_class.Add(class_member); class_file_path = save; throw new Exception(); } } } } } catch { } try { foreach (var fcc in found_class) { foreach (var me in fcc.Members) { var method_member = me as MethodDeclarationSyntax; if (method_member == null) { continue; } if (method_member.Identifier.ValueText.ToLower() == capitalized_member_name.ToLower()) { found_member = method_member; throw new Exception(); } } } } catch { } } { // Open to this line in editor. IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); { IVsTextViewExtensions.ShowFrame(class_file_path); vstv = IVsTextViewExtensions.FindTextViewFor(class_file_path); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } int line_number; int colum_number; var txt_span = found_member.Identifier.Span; vstv.GetLineAndColumn(txt_span.Start, out line_number, out colum_number); // Create new span in the appropriate view. ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, txt_span.Start, txt_span.Length); SnapshotPoint sp = ss.Start; // Put cursor on symbol. wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center. // Center on cursor. //wpftv.Caret.EnsureVisible(); // This works, sort of. It moves the scroll bar, but it does not CENTER! Does not really work! if (line_number > 0) { vstv.CenterLines(line_number - 1, 2); } else { vstv.CenterLines(line_number, 1); } return; } } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }
public IEnumerable <ITagSpan <EasyVSSmartTag> > GetTags(NormalizedSnapshotSpanCollection spans) { ITextSnapshot snapshot = textBuffer.CurrentSnapshot; if (snapshot.Length == 0) { yield break; //don't do anything if the buffer is empty } VSTextView tv = new VSTextView(VSTextView.ActiveTextView); int line, col; tv.GetCursorPositon(out line, out col); if (VSDocument.ActiveDocument != null) { //EditPoint p = tv.GetEditPoint(line, col); //CodeElement c = VSDocument.ActiveDocument.ProjectItem.FileCodeModel.CodeElementFromPoint(p, vsCMElement.vsCMElementProperty); //if (c != null) //{ //} //CodeElements elements = VSDocument.ActiveDocument.ProjectItem.FileCodeModel .CodeElements; //foreach (CodeElement element in elements) //{ // if (element.Kind == vsCMElement.vsCMElementNamespace) // { // CodeNamespace ns = (CodeNamespace)element; // foreach (CodeElement elem in ns.Members) // { // if (elem is CodeClass) // { // CodeClass cls = elem as CodeClass; // foreach (CodeElement member in cls.Members) // if (member is CodeProperty) // { // CodeType memberType = ((member as CodeProperty)).Type.CodeType; // } // } // } // } //} //set up the navigator ITextStructureNavigator navigator = smartTaggerProvider.NavigatorService.GetTextStructureNavigator(textBuffer); foreach (var span in spans) { ITextCaret caret = textView.Caret; SnapshotPoint point; if (caret.Position.BufferPosition > 0) { point = caret.Position.BufferPosition - 1; } else { yield break; } TextExtent extent = navigator.GetExtentOfWord(point); //don't display the tag if the extent has whitespace if (extent.IsSignificant) { yield return(new TagSpan <EasyVSSmartTag>(extent.Span, new EasyVSSmartTag(GetSmartTagActions(extent.Span)))); } else { yield break; } } } }
internal static Mock<IWpfTextView> CreateWpfTextView( ITextBuffer buffer, ITextCaret caret = null, ITextSelection selection = null) { caret = caret ?? CreateCaret().Object; selection = selection ?? CreateSelection().Object; var view = new Mock<IWpfTextView>(MockBehavior.Strict); view.SetupGet(x => x.Caret).Returns(caret); view.SetupGet(x => x.Selection).Returns(selection); view.SetupGet(x => x.TextBuffer).Returns(buffer); view.SetupGet(x => x.TextSnapshot).Returns(() => buffer.CurrentSnapshot); return view; }
public static void ResetMenus() { if (GoToDefinitionCommand.Instance == null || FindAllReferencesCommand.Instance == null || RenameCommand.Instance == null || Reformat.ReformatCommand.Instance == null) { return; } IWpfTextView view = AntlrLanguagePackage.Instance.GetActiveView(); if (view == null) { return; } // First, find out what this view is, and what the file is. ITextBuffer buffer = view.TextBuffer; string path = buffer.GetFFN().Result; IGrammarDescription grammar_description = LanguageServer.GrammarDescriptionFactory.Create(path); // Whack any old values that cursor points to. GoToDefinitionCommand.Instance.Enabled = false; FindAllReferencesCommand.Instance.Enabled = false; NextSymCommand.Instance.Enabled = true; RenameCommand.Instance.Enabled = false; ReformatCommand.Instance.Enabled = false; GoToVisitorCommand.Instance.Enabled = false; AntlrLanguagePackage.Instance.Span = default(SnapshotSpan); AntlrLanguagePackage.Instance.Classification = default(string); AntlrLanguagePackage.Instance.View = view; if (grammar_description == null) { return; } var fp = view.GetFilePath().Result; if (fp != null) { var gd = LanguageServer.GrammarDescriptionFactory.Create(fp); if (gd != null && gd.CanNextRule) { NextSymCommand.Instance.Enabled = true; } if (gd != null && gd.CanReformat) { Reformat.ReformatCommand.Instance.Enabled = true; } } else { return; } // Find details of the Antlr symbol pointed to. ITextCaret car = view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; TextExtent extent = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Navigator[view].GetExtentOfWord(bp); SnapshotSpan span = extent.Span; AntlrLanguagePackage.Instance.Span = span; HighlightTagger.Update(view, bp); // Now, check for valid classification type. ClassificationSpan[] c1 = AntlrVSIX.Package.AntlrLanguagePackage.Instance.Aggregator[view].GetClassificationSpans(span).ToArray(); foreach (ClassificationSpan classification in c1) { var name = classification.ClassificationType.Classification; if (!grammar_description.InverseMap.TryGetValue(name, out int type)) { continue; } if (grammar_description.CanFindAllRefs[type]) { FindAllReferencesCommand.Instance.Enabled = true; } if (grammar_description.CanRename[type]) { RenameCommand.Instance.Enabled = true; } if (grammar_description.CanGotodef[type]) { GoToDefinitionCommand.Instance.Enabled = true; } if (grammar_description.CanGotovisitor[type]) { GoToVisitorCommand.Instance.Enabled = true; } if (grammar_description.CanReformat) { ReformatCommand.Instance.Enabled = true; } } }
public static Mock<ITextView> CreateTextView( ITextBuffer textBuffer = null, ITextCaret caret = null, ITextSelection selection = null, ITextViewRoleSet textViewRoleSet = null, ITextViewModel textViewModel = null, IEditorOptions editorOptions = null, IBufferGraph bufferGraph = null, PropertyCollection propertyCollection = null, MockRepository factory = null) { factory = factory ?? new MockRepository(MockBehavior.Strict); textBuffer = textBuffer ?? CreateTextBuffer(100, factory: factory).Object; caret = caret ?? CreateCaret(factory: factory).Object; selection = selection ?? CreateSelection(factory: factory).Object; propertyCollection = propertyCollection ?? new PropertyCollection(); textViewRoleSet = textViewRoleSet ?? CreateTextViewRoleSet(factory: factory).Object; editorOptions = editorOptions ?? CreateEditorOptions(factory: factory).Object; bufferGraph = bufferGraph ?? CreateBufferGraph(factory: factory).Object; textViewModel = textViewModel ?? CreateTextViewModel(textBuffer: textBuffer, factory: factory).Object; var view = factory.Create<ITextView>(); view.SetupGet(x => x.Caret).Returns(caret); view.SetupGet(x => x.Selection).Returns(selection); view.SetupGet(x => x.TextBuffer).Returns(textBuffer); view.SetupGet(x => x.TextSnapshot).Returns(() => textBuffer.CurrentSnapshot); view.SetupGet(x => x.Properties).Returns(propertyCollection); view.SetupGet(x => x.Roles).Returns(textViewRoleSet); view.SetupGet(x => x.Options).Returns(editorOptions); view.SetupGet(x => x.BufferGraph).Returns(bufferGraph); view.SetupGet(x => x.TextViewModel).Returns(textViewModel); return view; }
private void MenuItemCallback(object sender, EventArgs e, bool forward) { try { //////////////////////// /// Next rule. //////////////////////// string classification = AntlrLanguagePackage.Instance.Classification; SnapshotSpan span = AntlrLanguagePackage.Instance.Span; ITextView view = AntlrLanguagePackage.Instance.View; view = AntlrLanguagePackage.Instance.GetActiveView(); if (view == null) { return; } ITextCaret car = view.Caret; CaretPosition cp = car.Position; SnapshotPoint bp = cp.BufferPosition; int pos = bp.Position; // First, find out what this view is, and what the file is. ITextBuffer buffer = view.TextBuffer; string path = buffer.GetFFN().Result; if (path == null) { return; } List <IToken> where = new List <IToken>(); List <ParserDetails> where_details = new List <ParserDetails>(); int next_sym = forward ? Int32.MaxValue : -1; foreach (var kvp in ParserDetailsFactory.AllParserDetails) { string file_name = kvp.Key; if (file_name != path) { continue; } ParserDetails details = kvp.Value; foreach (var p in details.Defs) { if (p.Value != 0) { continue; } var t = p.Key; if (forward) { if (t.Symbol.StartIndex > pos && t.Symbol.StartIndex < next_sym) { next_sym = t.Symbol.StartIndex; } } else { if (t.Symbol.StartIndex < pos && t.Symbol.StartIndex > next_sym) { next_sym = t.Symbol.StartIndex; } } } foreach (var p in details.Defs) { if (p.Value != 1) { continue; } var t = p.Key; if (forward) { if (t.Symbol.StartIndex > pos && t.Symbol.StartIndex < next_sym) { next_sym = t.Symbol.StartIndex; } } else { if (t.Symbol.StartIndex < pos && t.Symbol.StartIndex > next_sym) { next_sym = t.Symbol.StartIndex; } } } break; } if (next_sym == Int32.MaxValue || next_sym < 0) { return; } string full_file_name = path; IVsTextView vstv = IVsTextViewExtensions.FindTextViewFor(full_file_name); if (vstv == null) { IVsTextViewExtensions.ShowFrame(full_file_name); vstv = IVsTextViewExtensions.FindTextViewFor(full_file_name); } IWpfTextView wpftv = vstv.GetIWpfTextView(); if (wpftv == null) { return; } int line_number; int colum_number; vstv.GetLineAndColumn(next_sym, out line_number, out colum_number); // Create new span in the appropriate view. ITextSnapshot cc = wpftv.TextBuffer.CurrentSnapshot; SnapshotSpan ss = new SnapshotSpan(cc, next_sym, 1); SnapshotPoint sp = ss.Start; // Put cursor on symbol. wpftv.Caret.MoveTo(sp); // This sets cursor, bot does not center. // Center on cursor. if (line_number > 0) { vstv.CenterLines(line_number - 1, 2); } else { vstv.CenterLines(line_number, 1); } AntlrVSIX.Package.Menus.ResetMenus(); } catch (Exception exception) { Logger.Log.Notify(exception.StackTrace); } }
private int SyncedOperation(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int result = 0; ITextCaret caret = m_textView.Caret; if (!addedCurrentCaret) { AddSyncPoint(caret.Position); addedCurrentCaret = true; } var tempTrackList = m_trackList; m_trackList = new List <ITrackingPoint>(); m_dte.UndoContext.Open("Select Next edit"); bool deleteSelection = !m_textView.Selection.IsEmpty; string currentSelection = m_textView.Selection.SelectedSpans[m_textView.Selection.SelectedSpans.Count - 1].GetText(); for (int i = 0; i < tempTrackList.Count; i++) { var trackingMode = tempTrackList[i].TrackingMode; var snapPoint = tempTrackList[i].GetPoint(m_textView.TextSnapshot); caret.MoveTo(snapPoint); using (var edit = m_textView.TextSnapshot.TextBuffer.CreateEdit()) { bool applyEdit = false; if (deleteSelection) { if (trackingMode == PointTrackingMode.Negative) { edit.Delete(caret.Position.BufferPosition.Position, currentSelection.Length); } else { edit.Delete(caret.Position.BufferPosition.Position - currentSelection.Length, currentSelection.Length); } applyEdit = true; } switch (nCmdID) { case (uint)VSConstants.VSStd2KCmdID.TYPECHAR: var typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); edit.Insert(tempTrackList[i].GetPosition(m_textView.TextSnapshot), typedChar.ToString()); applyEdit = true; break; case ((uint)VSConstants.VSStd97CmdID.Delete): if (i < tempTrackList.Count - 1 && deleteSelection) { edit.Insert(tempTrackList[i].GetPosition(m_textView.TextSnapshot), ""); } break; case ((uint)VSConstants.VSStd97CmdID.Paste): if (i < tempTrackList.Count - 1) { var pasteString = Clipboard.GetText(); edit.Insert(tempTrackList[i].GetPosition(m_textView.TextSnapshot), pasteString); applyEdit = true; } break; } if (applyEdit) { edit.Apply(); } } switch (nCmdID) { case ((uint)VSConstants.VSStd2KCmdID.TYPECHAR): break; case ((uint)VSConstants.VSStd97CmdID.Delete): if (!deleteSelection) { result = NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } break; case ((uint)VSConstants.VSStd97CmdID.Paste): if (i == tempTrackList.Count - 1) { result = NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } break; default: result = NextTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); break; } AddSyncPoint(m_textView.Caret.Position); } m_dte.UndoContext.Close(); RedrawScreen(); return(result); }
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (VsShellUtilities.IsInAutomationFunction(_provider.ServiceProvider)) { return(_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut)); } //make a copy of this so we can look at it after forwarding some commands uint commandID = nCmdID; char typedChar = char.MinValue; //make sure the input is a char before getting it if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) { typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } //check for a commit character if (nCmdID == (uint)VSConstants.VSStd2KCmdID.RETURN || nCmdID == (uint)VSConstants.VSStd2KCmdID.TAB || char.IsWhiteSpace(typedChar) || char.IsPunctuation(typedChar)) { //check for a a selection if (_session != null && !_session.IsDismissed) { //if the selection is fully selected, commit the current session if (_session.SelectedCompletionSet.SelectionStatus.IsSelected) { _session.Commit(); //also, don't add the character to the buffer return(VSConstants.S_OK); } else { //if there is no selection, dismiss the session _session.Dismiss(); } } } //pass along the command so the char is added to the buffer int retVal = _nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); bool handled = false; // Test for '-' is to catch ELUP (--^) if (!typedChar.Equals(char.MinValue) && ((char.IsLetterOrDigit(typedChar)) || ((typedChar == '\'') || (typedChar == '"') || (typedChar == '-')))) { if (_session == null || _session.IsDismissed) // If there is no active session, bring up completion { TriggerCompletion(); // No need to filter for single and double-quotes, the choice IS the characted, just doubled, and already populated in a single completionset if we're here... if ((typedChar == '\'') || (typedChar == '"')) { // We need to save the currect caret position because we'll position it in between the single/double quotes after the commit... ITextCaret caretBeforeCommit = _session.TextView.Caret; _session.Commit(); _textView.Caret.MoveTo(caretBeforeCommit.Position.BufferPosition - 1); } else if (!_session.IsDismissed) { _session.Filter(); } } else //the completion session is already active, so just filter { _session.Filter(); } handled = true; } else if (commandID == (uint)VSConstants.VSStd2KCmdID.BACKSPACE || //redo the filter if there is a deletion commandID == (uint)VSConstants.VSStd2KCmdID.DELETE) { if (_session != null && !_session.IsDismissed) { _session.Filter(); } handled = true; } if (handled) { return(VSConstants.S_OK); } return(retVal); }