Пример #1
0
            private static CodeModel.CodeSource GetCodeSourceForActiveView(out string fileName)
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                var view = Shell.ActiveView;

                if (view != null)
                {
                    fileName = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);
                    var content = view.TextBuffer.CurrentSnapshot.GetText();

                    try
                    {
                        var merger = new CodeModel.FileMerger();
                        merger.MergeFile(ProbeEnvironment.CurrentAppSettings, fileName, content, true, true);
                        return(merger.MergedContent);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteEx(ex);

                        var codeSource = new CodeModel.CodeSource();
                        codeSource.Append(content, new CodeModel.CodeAttributes(fileName, 0, content.Length, true, true, false));
                        codeSource.Flush();

                        return(codeSource);
                    }
                }

                fileName = null;
                return(null);
            }
Пример #2
0
            public static void ShowCodeModelDump()
            {
                ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    var appSettings = ProbeEnvironment.CurrentAppSettings;

                    var view = Shell.ActiveView;
                    if (view == null)
                    {
                        return;
                    }

                    var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(view.TextBuffer);
                    if (fileStore == null)
                    {
                        return;
                    }

                    var fileName = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);
                    var model    = fileStore.GetCurrentModel(appSettings, fileName, view.TextSnapshot, "Debug:ShowCodeModelDump");

                    Shell.OpenTempContent(model.DumpTree(), Path.GetFileName(model.FileName), ".model.xml");
                });
            }
Пример #3
0
		private void Reparse()
		{
			ThreadHelper.ThrowIfNotOnUIThread();

			_modelRegions.Clear();
			_snapshot = _buffer.CurrentSnapshot;
			var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_buffer);
			if (fileStore != null)
			{
				var appSettings = ProbeEnvironment.CurrentAppSettings;
				var fileName = VsTextUtil.TryGetDocumentFileName(_buffer);
				var model = fileStore.GetCurrentModel(appSettings, fileName, _snapshot, "OutliningTagger.Reparse()");

				foreach (var region in model.OutliningRegions.OrderBy(r => r.Span.Start))
				{
					_modelRegions.Add(new ModelRegion
					{
						span = new SnapshotSpan(model.Snapshot, new Span(region.Span.Start, region.Span.End - region.Span.Start)),
						isFunction = region.CollapseToDefinition,
						text = region.Text,
						tooltipText = region.TooltipText
					});
				}
			}
		}
Пример #4
0
        private IEnumerable <ISignature> HandleComma(VsText.ITextSnapshot snapshot, ProbeAppSettings appSettings)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_textBuffer);

            if (fileStore != null)
            {
                var fileName = VsTextUtil.TryGetDocumentFileName(_textBuffer);
                var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after ','");
                var modelPos = (new VsText.SnapshotPoint(snapshot, _triggerPos)).TranslateTo(model.Snapshot, VsText.PointTrackingMode.Negative).Position;

                var argsToken = model.File.FindDownward <ArgsToken>().Where(t => t.Span.Start < modelPos && (t.Span.End > modelPos || !t.IsTerminated)).LastOrDefault();
                if (argsToken != null && argsToken.Signature != null)
                {
                    var modelSpan        = new VsText.SnapshotSpan(model.Snapshot, argsToken.Span.ToVsTextSpan());
                    var snapshotSpan     = modelSpan.TranslateTo(snapshot, VsText.SpanTrackingMode.EdgeInclusive);
                    var applicableToSpan = snapshot.CreateTrackingSpan(snapshotSpan.Span, VsText.SpanTrackingMode.EdgeInclusive, 0);
                    yield return(CreateSignature(_textBuffer, argsToken.Signature, applicableToSpan));

                    foreach (var sig in argsToken.SignatureAlternatives)
                    {
                        yield return(CreateSignature(_textBuffer, sig, applicableToSpan));
                    }
                }
            }
        }
Пример #5
0
        public override bool OnSynchronizeDropdowns(LanguageService languageService, IVsTextView textView, int line, int col,
                                                    ArrayList dropDownTypes, ArrayList dropDownMembers, ref int selectedType, ref int selectedMember)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (languageService.GetType() != typeof(ProbeLanguageService))
            {
                return(false);
            }

            if (textView == null)
            {
                return(false);
            }
            var wpfTextView = Shell.VsTextViewToWpfTextView(textView);

            if (wpfTextView == null)
            {
                return(false);
            }
            var buf = wpfTextView.TextBuffer;

            dropDownMembers.Clear();
            selectedMember = -1;

            int caretPos, virtualSpaces;

            textView.GetNearestPosition(line, col, out caretPos, out virtualSpaces);
            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(buf);

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

            var index = 0;

            var appSettings = ProbeEnvironment.CurrentAppSettings;
            var fileName    = VsTextUtil.TryGetDocumentFileName(buf);

            foreach (var func in (from f in fileStore.GetFunctionDropDownList(appSettings, fileName, buf.CurrentSnapshot)
                                  orderby f.Name.ToLower()
                                  select f))
            {
                var span = func.EntireFunctionSpan;
                dropDownMembers.Add(new DropDownMember(func.Name, span.ToVsTextInteropSpan(textView), k_methodImageIndex, DROPDOWNFONTATTR.FONTATTR_PLAIN));
                if (span.Contains(caretPos))
                {
                    selectedMember = index;
                }
                index++;
            }

            return(true);
        }
Пример #6
0
        public IEnumerable <ITagSpan <ErrorTag> > GetTags(NormalizedSnapshotSpanCollection spans)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var appSettings = ProbeEnvironment.CurrentAppSettings;

            var fileName = VsTextUtil.TryGetDocumentFileName(_view.TextBuffer);

            _model = _store.GetMostRecentModel(appSettings, fileName, _view.TextSnapshot, "ErrorTagger.GetTags()");

            return(ErrorTaskProvider.Instance.GetErrorTagsForFile(_model.FileName, spans));
        }
Пример #7
0
        private void _backgroundFecDeferrer_Idle(object sender, BackgroundDeferrer.IdleEventArgs e)
        {
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                try
                {
                    if (_model != null &&
                        _model.FileContext != FileContext.Include &&
                        ProbeEnvironment.CurrentAppSettings.FileExistsInApp(_model.FileName))
                    {
                        if (ProbeToolsPackage.Instance.EditorOptions.RunBackgroundFecOnSave)
                        {
                            Compiler.BackgroundFec.Run(_model.FileName, _model.Snapshot.TextBuffer.CurrentSnapshot);
                        }
                        else
                        {
                            ErrorTaskProvider.Instance.RemoveAllForSource(ErrorTaskSource.BackgroundFec, _model.FileName);
                        }

                        if (ProbeToolsPackage.Instance.EditorOptions.RunCodeAnalysisOnSave)
                        {
                            var textBuffer = _model.Snapshot.TextBuffer;
                            var fileStore  = CodeModel.FileStore.GetOrCreateForTextBuffer(textBuffer);
                            if (fileStore == null)
                            {
                                return;
                            }

                            var fileName          = VsTextUtil.TryGetDocumentFileName(textBuffer);
                            var preprocessedModel = fileStore.CreatePreprocessedModel(_model.AppSettings, fileName, textBuffer.CurrentSnapshot, false, "Background Code Analysis");

                            var ca = new CodeAnalysis.CodeAnalyzer(null, preprocessedModel);
                            ca.Run();
                        }
                        else
                        {
                            ErrorTaskProvider.Instance.RemoveAllForSource(ErrorTaskSource.CodeAnalysis, _model.FileName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteEx(ex);
                }
            });
        }
Пример #8
0
        public void OnDocumentClosed(ITextView textView)
        {
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(textView.TextBuffer);
                if (fileStore != null)
                {
                    var appSettings = ProbeEnvironment.CurrentAppSettings;
                    var fileName    = VsTextUtil.TryGetDocumentFileName(textView.TextBuffer);
                    var model       = fileStore.GetMostRecentModel(appSettings, fileName, textView.TextSnapshot, "ErrorTaskProvider.OnDocumentClosed()");
                    RemoveAllForSource(ErrorTaskSource.BackgroundFec, model.FileName);
                }
            });
        }
Пример #9
0
        private void WordSelectDeferrer_Idle(object sender, BackgroundDeferrer.IdleEventArgs e)
        {
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var snapPt = (SnapshotPoint)e.Value;
                if (_sourceBuffer.CurrentSnapshot != snapPt.Snapshot)
                {
                    Update(snapPt, null);
                    return;
                }

                var snapshot = snapPt.Snapshot;

                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_sourceBuffer);
                if (fileStore != null)
                {
                    var appSettings = ProbeEnvironment.CurrentAppSettings;
                    var fileName    = VsTextUtil.TryGetDocumentFileName(_sourceBuffer);
                    var model       = fileStore.GetCurrentModel(appSettings, fileName, _sourceBuffer.CurrentSnapshot, "Word select idle");
                    var modelPos    = model.AdjustPosition(snapPt);
                    var caretToken  = model.File.FindDownwardTouching(modelPos).LastOrDefault(t => t.SourceDefinition != null);
                    if (caretToken == null)
                    {
                        Update(snapPt, null);
                        return;
                    }

                    var sourceDef      = caretToken.SourceDefinition;
                    var file           = model.File;
                    var matchingTokens = file.FindDownward(t => t.SourceDefinition == sourceDef);

                    var wordSpans = new NormalizedSnapshotSpanCollection(from t in matchingTokens select new SnapshotSpan(snapshot, VsTextUtil.ModelSpanToVsSnapshotSpan(model.Snapshot, t.Span, snapshot)));
                    if (!wordSpans.Any())
                    {
                        wordSpans = null;
                    }

                    Update(snapPt, wordSpans);
                }
            });
        }
        int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                char typedChar = char.MinValue;

                if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                {
                    typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                }

                var retVal = _nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                if (ErrorHandler.Failed(retVal))
                {
                    return(retVal);
                }

                if (typedChar == '}' || typedChar == '#' || typedChar == ':')
                {
                    var fileName    = VsTextUtil.TryGetDocumentFileName(_textView.TextBuffer);
                    var appSettings = ProbeEnvironment.CurrentAppSettings;
                    var tracker     = Classifier.TextBufferStateTracker.GetTrackerForTextBuffer(_textView.TextBuffer);
                    var state       = tracker.GetStateForPosition(_textView.Caret.Position.BufferPosition, fileName, appSettings);
                    if (Classifier.State.IsInLiveCode(state))
                    {
                        TriggerIndentReformat();
                        retVal = VSConstants.S_OK;
                    }
                }

                return(retVal);
            }
            catch (Exception ex)
            {
                Log.WriteEx(ex);
                return(VSConstants.E_FAIL);
            }
        }
Пример #11
0
            private static CodeModel.CodeModel GetModelForActiveDoc(ProbeAppSettings appSettings)
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                var view = Shell.ActiveView;

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

                var store = CodeModel.FileStore.GetOrCreateForTextBuffer(view.TextBuffer);

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

                var fileName = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);

                return(store.GetMostRecentModel(appSettings, fileName, view.TextSnapshot, "Debug Commands"));
            }
Пример #12
0
        private void RefreshFunctionList(VsTextEditor.IWpfTextView view)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!c_functionTab.IsSelected)
            {
                return;
            }

            if (view != null)
            {
                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(view.TextBuffer);
                if (fileStore != null)
                {
                    var snapshot = view.TextSnapshot;
                    if (_activeView != view || _activeSnapshot != snapshot)
                    {
                        _activeView     = view;
                        _activeSnapshot = snapshot;

                        var appSettings = ProbeEnvironment.CurrentAppSettings;
                        var fileName    = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);
                        _activeFunctions = (from f in fileStore.GetFunctionDropDownList(appSettings, fileName, snapshot)
                                            orderby f.Name.ToLower()
                                            select new FunctionListItem(f)).ToArray();
                        ApplyFunctionFilter();
                        c_functionList.ItemsSource = _activeFunctions;
                    }
                    return;
                }
            }

            _activeView                = null;
            _activeSnapshot            = null;
            _activeFunctions           = null;
            c_functionList.ItemsSource = null;
        }
Пример #13
0
        private static void RunCodeAnalysis(object sender, EventArgs e)
        {
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                try
                {
                    var view = Shell.ActiveView;
                    if (view == null)
                    {
                        return;
                    }

                    var appSettings = ProbeEnvironment.CurrentAppSettings;

                    var fileName = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);

                    var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(view.TextBuffer);
                    if (fileStore == null)
                    {
                        return;
                    }
                    var model = fileStore.CreatePreprocessedModel(appSettings, fileName, view.TextSnapshot, false, "Code Analysis");

                    var pane = Shell.CreateOutputPane(GuidList.guidCodeAnalysisPane, "DK Code Analysis");
                    pane.Clear();
                    pane.Show();

                    var ca = new CodeAnalysis.CodeAnalyzer(pane, model);
                    ca.Run();
                }
                catch (Exception ex)
                {
                    Shell.ShowError(ex);
                }
            });
        }
Пример #14
0
        public static int?GetDesiredIndentation(ITextBuffer buffer, ITextSnapshotLine line, int tabSize, bool keepTabs, ProbeAppSettings appSettings)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (line.LineNumber == 0)
            {
                return(0);
            }

            var lineText     = line.GetText();
            var lineTextTrim = lineText.Trim();

            if (lineTextTrim == "}")
            {
                // User is ending a set of braces.

                var bracePos    = line.Start.Position + GetNumWhiteSpacePrefixChars(lineText);
                var braceParser = new BraceHighlighting.BraceHighlightParser();

                foreach (var span in braceParser.FindMatchingBraces(line.Snapshot, bracePos))
                {
                    if (span.End < bracePos)
                    {
                        return(span.Start.GetContainingLine().GetText().GetIndentCount(tabSize));
                    }
                }
            }
            else if (lineTextTrim == "#")
            {
                // Preprocessor statements always at the very beginning of the line.
                return(0);
            }
            else if (_rxCaseLine.IsMatch(lineTextTrim))
            {
                // User is typing a 'case' inside a switch.

                // Try to find the braces that contain the 'case'.
                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(buffer);
                if (fileStore != null)
                {
                    var fileName    = VsTextUtil.TryGetDocumentFileName(buffer);
                    var model       = fileStore.GetCurrentModel(appSettings, fileName, buffer.CurrentSnapshot, "Smart indenting - case inside switch");
                    var offset      = line.Snapshot.TranslateOffsetToSnapshot(line.Start.Position, model.Snapshot);
                    var bracesToken = model.File.FindDownward(offset, t => t is CodeModel.Tokens.BracesToken).LastOrDefault() as CodeModel.Tokens.BracesToken;
                    if (bracesToken != null)
                    {
                        // Get the indent of the line where the opening brace resides.
                        var openOffset = bracesToken.OpenToken.Span.Start;
                        openOffset = model.Snapshot.TranslateOffsetToSnapshot(openOffset, line.Snapshot);
                        var openLine = line.Snapshot.GetLineFromPosition(openOffset);
                        return(openLine.GetText().GetIndentCount(tabSize));
                    }
                }
            }

            // If we got to this point, then the default smart indenting is to be used.
            {
                var prevLine = GetPreviousCodeLine(line);
                if (prevLine != null)
                {
                    var tracker = Classifier.TextBufferStateTracker.GetTrackerForTextBuffer(buffer);
                    if (tracker != null)
                    {
                        var lineNumber = prevLine.LineNumber;
                        var fileName   = VsTextUtil.TryGetDocumentFileName(buffer);
                        var prevState  = tracker.GetStateForLineStart(lineNumber, tracker.Snapshot, fileName, appSettings);
                        while (State.IsInsideMultiLineComment(prevState))
                        {
                            if (lineNumber == 0)
                            {
                                break;                                                  // At start of file. In theory, this should never happen as the state for the start of the file is always zero.
                            }
                            prevState = tracker.GetStateForLineStart(--lineNumber, tracker.Snapshot, fileName, appSettings);
                        }

                        if (prevLine.LineNumber != lineNumber)
                        {
                            prevLine = prevLine.Snapshot.GetLineFromLineNumber(lineNumber);
                        }
                    }

                    var prevLineText = prevLine.Snapshot.GetText(prevLine.Start.Position, line.Start.Position - prevLine.Start.Position);

                    //var tracker = ;
                    //var state = tracker != null ? tracker.GetStateForLine(prevLine.LineNumber, _view.TextSnapshot) : 0;

                    //if (prevLineText.EndsWith("{") || _rxCaseLine.IsMatch(prevLineText))
                    if (PrevLineTextWarrantsIndent(prevLineText))
                    {
                        return(prevLineText.GetIndentCount(tabSize).AddIndentTab(tabSize));
                    }
                    else
                    {
                        return(prevLineText.GetIndentCount(tabSize));
                    }
                }
                return(0);
            }
        }
Пример #15
0
        private IEnumerable <ISignature> HandleOpenBracket(VsText.ITextSnapshot snapshot, ProbeAppSettings appSettings)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var lineText = snapshot.GetLineTextUpToPosition(_triggerPos);

            var match = _rxFuncBeforeBracket.Match(lineText);

            if (match.Success)
            {
                var line          = snapshot.GetLineFromPosition(_triggerPos);
                var word1         = match.Groups[2].Value;
                var word1Start    = line.Start.Position + match.Groups[2].Index;
                var funcName      = match.Groups[3].Value;
                var funcNameStart = line.Start.Position + match.Groups[3].Index;

                var fileStore = FileStore.GetOrCreateForTextBuffer(_textBuffer);
                if (fileStore != null)
                {
                    if (!string.IsNullOrEmpty(word1))
                    {
                        VsText.ITrackingSpan applicableToSpan = null;

                        var fileName = VsTextUtil.TryGetDocumentFileName(snapshot.TextBuffer);
                        var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after '(' - dot separated words");
                        var modelPos = model.AdjustPosition(word1Start, snapshot);

                        foreach (var word1Def in model.DefinitionProvider.GetAny(modelPos, word1))
                        {
                            if (!word1Def.AllowsChild)
                            {
                                continue;
                            }
                            foreach (var word2Def in word1Def.GetChildDefinitions(funcName))
                            {
                                if (!word2Def.ArgumentsRequired)
                                {
                                    continue;
                                }
                                if (applicableToSpan == null)
                                {
                                    applicableToSpan = snapshot.CreateTrackingSpan(new VsText.Span(_triggerPos, 0), VsText.SpanTrackingMode.EdgeInclusive);
                                }
                                yield return(CreateSignature(_textBuffer, word2Def.ArgumentsSignature, applicableToSpan));
                            }
                        }
                    }
                    else
                    {
                        VsText.ITrackingSpan applicableToSpan = null;

                        var fileName = VsTextUtil.TryGetDocumentFileName(snapshot.TextBuffer);
                        var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after '('");
                        var modelPos = model.AdjustPosition(funcNameStart, snapshot);
                        foreach (var def in model.DefinitionProvider.GetAny(modelPos, funcName))
                        {
                            if (!def.ArgumentsRequired)
                            {
                                continue;
                            }

                            if (applicableToSpan == null)
                            {
                                applicableToSpan = snapshot.CreateTrackingSpan(new VsText.Span(_triggerPos, 0), VsText.SpanTrackingMode.EdgeInclusive);
                            }
                            yield return(CreateSignature(_textBuffer, def.ArgumentsSignature, applicableToSpan));
                        }
                    }
                }
            }
        }
Пример #16
0
        public static void TriggerGoToDefinition(ITextView textView)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                // Get caret point
                var caretPtTest = textView.Caret.Position.Point.GetPoint(textBuffer => (!textBuffer.ContentType.IsOfType("projection")), PositionAffinity.Predecessor);
                if (!caretPtTest.HasValue)
                {
                    return;
                }
                var caretPt = caretPtTest.Value;

                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(textView.TextBuffer);
                if (fileStore == null)
                {
                    return;
                }

                var appSettings = ProbeEnvironment.CurrentAppSettings;
                var fileName    = VsTextUtil.TryGetDocumentFileName(textView.TextBuffer);
                var model       = fileStore.GetCurrentModel(appSettings, fileName, caretPt.Snapshot, "Go to definition");
                var modelPos    = model.AdjustPosition(caretPt.Position, caretPt.Snapshot);
                var selTokens   = model.File.FindDownwardTouching(modelPos).ToArray();
                if (selTokens.Length == 0)
                {
                    Log.Debug("Nothing selected.");
                    return;
                }

                var defToken = selTokens.LastOrDefault(t => t.SourceDefinition != null);
                if (defToken != null && defToken.SourceDefinition != null)
                {
                    Log.Debug("Got token with SourceDefinition.");
                    BrowseToDefinition(defToken.SourceDefinition);
                    return;
                }

                var includeToken = selTokens.LastOrDefault(t => t is CodeModel.Tokens.IncludeToken) as CodeModel.Tokens.IncludeToken;
                if (includeToken != null)
                {
                    Log.Debug("Found include token.");

                    var pathName = includeToken.FullPathName;
                    if (!string.IsNullOrEmpty(pathName))
                    {
                        Shell.OpenDocument(pathName);
                        return;
                    }
                    else
                    {
                        ProbeToolsPackage.Instance.SetStatusText("Include file not found.");
                        return;
                    }
                }

                Log.Debug("Found no definitions.");
                ProbeToolsPackage.Instance.SetStatusText("Definition not found.");
            }
            catch (Exception ex)
            {
                Shell.ShowError(ex);
            }
        }
Пример #17
0
        public static void TriggerFindReferences(ITextView textView)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                var snapPt = textView.Caret.Position.BufferPosition;

                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(snapPt.Snapshot.TextBuffer);
                if (fileStore == null)
                {
                    return;
                }

                var appSettings  = ProbeEnvironment.CurrentAppSettings;
                var fileName     = VsTextUtil.TryGetDocumentFileName(textView.TextBuffer);
                var fullModel    = fileStore.CreatePreprocessedModel(appSettings, fileName, snapPt.Snapshot, false, "Find Local References");
                var fullModelPos = fullModel.PreprocessorModel.Source.PrimaryFilePositionToSource(fullModel.AdjustPosition(snapPt));

                var fullToken = fullModel.File.FindDownward(fullModelPos, t => t.SourceDefinition != null).FirstOrDefault();
                if (fullToken == null)
                {
                    var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapPt.Snapshot, "Find Local References (fallback)");
                    var modelPos = model.AdjustPosition(snapPt);
                    var token    = model.File.FindDownward(modelPos, t => t.SourceDefinition != null).FirstOrDefault();
                    if (token == null)
                    {
                        ProbeToolsPackage.Instance.SetStatusText("No reference found at cursor.");
                        return;
                    }
                    else
                    {
                        fullToken = token;
                    }
                }

                var def = fullToken.SourceDefinition;

                var pane = StartFindReferences(def.Name);

                var refList = new List <Reference>();

                foreach (var token in fullModel.File.FindDownward(t => t.SourceDefinition == fullToken.SourceDefinition))
                {
                    var localFilePos = fullModel.PreprocessorModel.Source.GetFilePosition(token.Span.Start);

                    refList.Add(new Reference(localFilePos.FileName, localFilePos.Position, false));
                }

                if (!string.IsNullOrEmpty(def.ExternalRefId))
                {
                    refList.AddRange(FindGlobalReferences(def.ExternalRefId));
                }

                EndFindReferences(pane, refList);
            }
            catch (Exception ex)
            {
                Shell.ShowError(ex);
            }
        }
Пример #18
0
        public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            try
            {
                ThreadHelper.ThrowIfNotOnUIThread();

                if (VsShellUtilities.IsInAutomationFunction(_provider.ServiceProvider))
                {
                    return(_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
                }

                var commandId = nCmdID;
                var typedChar = char.MinValue;

                if (pguidCmdGroup == typeof(VSConstants.VSStd97CmdID).GUID)
                {
                    if (nCmdID == (uint)VSConstants.VSStd97CmdID.GotoDefn)
                    {
                        Navigation.GoToDefinitionHelper.TriggerGoToDefinition(_textView);
                        return(VSConstants.S_OK);
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd97CmdID.FindReferences)
                    {
                        Navigation.GoToDefinitionHelper.TriggerFindReferences(_textView);
                        return(VSConstants.S_OK);
                    }
                }

                if (pguidCmdGroup == VSConstants.VSStd2K)
                {
                    if (nCmdID == (uint)VSConstants.VSStd2KCmdID.TYPECHAR)
                    {
                        typedChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn);
                        if (typedChar == '(')
                        {
                            var appSettings = ProbeEnvironment.CurrentAppSettings;
                            var fileName    = VsTextUtil.TryGetDocumentFileName(_textView.TextBuffer);
                            if (_textView.Caret.Position.BufferPosition.IsInLiveCode(fileName, appSettings))
                            {
                                SnapshotPoint point    = _textView.Caret.Position.BufferPosition;
                                var           pos      = point.Position;
                                var           lineText = point.Snapshot.GetLineTextUpToPosition(pos).TrimEnd();

                                if (lineText.Length > 0 && lineText[lineText.Length - 1].IsWordChar(false))
                                {
                                    if (_session != null && !_session.IsDismissed)
                                    {
                                        _session.Dismiss();
                                    }
                                    s_typedChar = typedChar;
                                    _session    = _broker.TriggerSignatureHelp(_textView);
                                }
                            }
                        }
                        else if (typedChar == ')' && _session != null)
                        {
                            if (!_session.IsDismissed)
                            {
                                _session.Dismiss();
                            }
                            _session = null;
                        }
                        else if (typedChar == ',' && (_session == null || _session.IsDismissed))
                        {
                            var appSettings = ProbeEnvironment.CurrentAppSettings;
                            var fileName    = VsTextUtil.TryGetDocumentFileName(_textView.TextBuffer);
                            if (_textView.Caret.Position.BufferPosition.IsInLiveCode(fileName, appSettings))
                            {
                                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_textView.TextBuffer);
                                if (fileStore != null)
                                {
                                    var model    = fileStore.GetMostRecentModel(appSettings, fileName, _textView.TextSnapshot, "Signature help command handler - after ','");
                                    var modelPos = _textView.Caret.Position.BufferPosition.TranslateTo(model.Snapshot, PointTrackingMode.Negative).Position;

                                    var argsToken = model.File.FindDownward <CodeModel.Tokens.ArgsToken>(modelPos).Where(t => t.Span.Start < modelPos && (t.Span.End > modelPos || !t.IsTerminated)).LastOrDefault();
                                    if (argsToken != null)
                                    {
                                        s_typedChar = typedChar;
                                        _session    = _broker.TriggerSignatureHelp(_textView);
                                    }
                                }
                            }
                        }
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.GOTOBRACE)
                    {
                        Navigation.GoToBraceHelper.Trigger(_textView, false);
                        return(VSConstants.S_OK);
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.GOTOBRACE_EXT)
                    {
                        Navigation.GoToBraceHelper.Trigger(_textView, true);
                        return(VSConstants.S_OK);
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.COMMENT_BLOCK)
                    {
                        Tagging.Tagger.CommentBlock();
                        return(VSConstants.S_OK);
                    }
                    else if (nCmdID == (uint)VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK)
                    {
                        Tagging.Tagger.UncommentBlock();
                        return(VSConstants.S_OK);
                    }
                }

                return(_nextCommandHandler.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
            }
            catch (Exception ex)
            {
                Log.WriteEx(ex);
                return(VSConstants.E_FAIL);
            }
        }
Пример #19
0
        public static void Trigger(ITextView view, bool extend)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var caretPtTest = view.Caret.Position.Point.GetPoint(buf => (!buf.ContentType.IsOfType("projection")), Microsoft.VisualStudio.Text.PositionAffinity.Predecessor);

            if (!caretPtTest.HasValue)
            {
                Log.Debug("Couldn't get caret point.");
                return;
            }
            var caretPt = caretPtTest.Value;

            var store = FileStore.GetOrCreateForTextBuffer(view.TextBuffer);

            if (store == null)
            {
                return;
            }

            var appSettings = ProbeEnvironment.CurrentAppSettings;
            var fileName    = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);
            var model       = store.GetMostRecentModel(appSettings, fileName, view.TextSnapshot, "GoToBraceHelper.Trigger()");

            var modelPos  = model.AdjustPosition(caretPt.Position, caretPt.Snapshot);
            var selTokens = model.File.FindDownwardTouching(modelPos).ToArray();

            if (selTokens.Length == 0)
            {
                Log.Debug("Touching no tokens.");
                return;
            }

            if (!extend)
            {
                Token selToken = null;
                var   token    = selTokens.LastOrDefault(t => t is BraceToken || t is BracesToken);
                if (token is BracesToken)
                {
                    selToken = (token as BracesToken).OpenToken;
                }
                else if (token is BraceToken)
                {
                    var bracesToken = ((token as BraceToken).Parent as BracesToken);
                    if (bracesToken != null)
                    {
                        selToken = token == bracesToken.OpenToken ? bracesToken.CloseToken : bracesToken.OpenToken;
                    }
                }

                if (selToken != null)
                {
                    var snapPos = model.Snapshot.TranslateOffsetToSnapshot(selToken.Span.Start, caretPt.Snapshot);

                    var snapPt = new SnapshotPoint(caretPt.Snapshot, snapPos);
                    view.Caret.MoveTo(snapPt);
                    view.Selection.Select(new SnapshotSpan(snapPt, 0), false);
                    view.ViewScroller.EnsureSpanVisible(new SnapshotSpan(snapPt, 0));
                }
            }
            else
            {
                var token = selTokens.LastOrDefault(t => t is BracesToken) as BracesToken;
                if (token != null)
                {
                    var startPos = model.Snapshot.TranslateOffsetToSnapshot(token.OpenToken.Span.Start, caretPt.Snapshot);
                    var endPos   = model.Snapshot.TranslateOffsetToSnapshot(token.CloseToken.Span.End, caretPt.Snapshot);

                    var snapPt = new SnapshotPoint(caretPt.Snapshot, startPos);
                    view.Caret.MoveTo(snapPt);

                    var snapSpan = new SnapshotSpan(caretPt.Snapshot, startPos, endPos - startPos);
                    view.Selection.Select(snapSpan, false);
                    view.ViewScroller.EnsureSpanVisible(snapSpan);
                }
            }
        }
Пример #20
0
        public bool TryGetApplicableToSpan(char typedChar, SnapshotPoint triggerPt, out SnapshotSpan applicableToSpan, CancellationToken token)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            _mode = CompletionMode.None;

            _fileName    = VsTextUtil.TryGetDocumentFileName(_textView.TextBuffer);
            _appSettings = ProbeEnvironment.CurrentAppSettings;
            var tracker = Classifier.TextBufferStateTracker.GetTrackerForTextBuffer(triggerPt.Snapshot.TextBuffer);
            var state   = tracker.GetStateForPosition(triggerPt, _fileName, _appSettings);

            if (Classifier.State.IsInLiveCode(state))
            {
                Match match;
                var   line   = triggerPt.Snapshot.GetLineFromPosition(triggerPt.Position);
                var   prefix = line.GetTextUpToPosition(triggerPt);

                if (typedChar == ' ')
                {
                    #region Assignment or Comparison
                    if ((match = _rxAfterAssignOrCompare.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterAssignOrCompare;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        _params.str      = match.Groups[1].Value;
                        _params.pt       = new SnapshotPoint(line.Snapshot, match.Groups[1].Index + line.Start.Position);
                        return(true);
                    }
                    #endregion
                    #region #ifdef
                    else if ((match = _rxAfterIfDef.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterIfDef;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                    #region Comma
                    else if (prefix.EndsWith(", "))
                    {
                        _mode            = CompletionMode.AfterComma;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                    #region order by
                    else if ((match = _rxOrderBy.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterOrderBy;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                    #region After Word
                    else if ((match = _rxAfterWord.Match(prefix)).Success)
                    {
                        switch (match.Groups[1].Value)
                        {
                        case "case":
                            _mode            = CompletionMode.AfterCase;
                            applicableToSpan = triggerPt.ToSnapshotSpan();
                            return(true);

                        case "extract":
                            _mode            = CompletionMode.AfterExtract;
                            applicableToSpan = triggerPt.ToSnapshotSpan();
                            _params.str      = match.Groups[1].Value;
                            return(true);

                        case "return":
                            _mode            = CompletionMode.AfterReturn;
                            applicableToSpan = triggerPt.ToSnapshotSpan();
                            return(true);

                        case "tag":
                            _mode            = CompletionMode.AfterTag;
                            applicableToSpan = triggerPt.ToSnapshotSpan();
                            return(true);

                        default:
                            _mode            = CompletionMode.AfterWord;
                            applicableToSpan = triggerPt.ToSnapshotSpan();
                            _params.str      = match.Groups[1].Value;
                            _params.snapshot = triggerPt.Snapshot;
                            return(true);
                        }
                    }
                    #endregion
                    #region After Symbol
                    else if ((match = _rxAfterSymbol.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterSymbol;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                    #region After Number
                    else if ((match = _rxAfterNumber.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterNumber;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                    #region After String Literal
                    else if ((match = _rxAfterStringLiteral.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.AfterStringLiteral;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        return(true);
                    }
                    #endregion
                }
                #region Table.Field
                else if ((match = _rxTypingTable.Match(prefix)).Success)
                {
                    _mode            = CompletionMode.DotSeparatedWords;
                    applicableToSpan = new SnapshotSpan(triggerPt.Snapshot, match.Groups[2].Index + line.Start.Position, match.Groups[2].Length);
                    _params.str      = match.Groups[1].Value;
                    _params.str2     = match.Groups[2].Value;
                    return(true);
                }
                #endregion
                #region Word
                else if ((match = _rxTypingWord.Match(prefix)).Success)
                {
                    // Typing a regular word.
                    _mode            = CompletionMode.Word;
                    _params.pt       = new SnapshotPoint(triggerPt.Snapshot, line.Start.Position + match.Index);
                    applicableToSpan = new SnapshotSpan(_params.pt, match.Length);
                    return(true);
                }
                #endregion
                #region Class function bracket
                else if ((match = _rxClassFunctionStartBracket.Match(prefix)).Success)
                {
                    _mode            = CompletionMode.ClassFunction;
                    applicableToSpan = triggerPt.ToSnapshotSpan();
                    _params.str      = match.Groups[1].Value;
                    _params.str2     = match.Groups[2].Value;
                    return(true);
                }
                #endregion
                #region Function bracket
                else if ((match = _rxFunctionStartBracket.Match(prefix)).Success)
                {
                    _mode            = CompletionMode.Function;
                    applicableToSpan = triggerPt.ToSnapshotSpan();
                    _params.str      = match.Groups[1].Value;
                    return(true);
                }
                #endregion
                #region #include
                else if ((match = _rxAfterInclude.Match(prefix)).Success)
                {
                    _mode            = CompletionMode.Include;
                    applicableToSpan = triggerPt.ToSnapshotSpan();
                    _params.str      = match.Groups[1].Value;
                    return(true);
                }
                #endregion
            }
            else
            {
                if ((state & State.StringLiteral_Mask) != 0)
                {
                    Match match;
                    var   line   = triggerPt.Snapshot.GetLineFromPosition(triggerPt.Position);
                    var   prefix = line.GetTextUpToPosition(triggerPt);

                    #region #include (for string literal)
                    if ((match = _rxAfterInclude.Match(prefix)).Success)
                    {
                        _mode            = CompletionMode.Include;
                        applicableToSpan = triggerPt.ToSnapshotSpan();
                        _params.str      = match.Groups[1].Value;
                        return(true);
                    }
                    #endregion
                }
            }

            applicableToSpan = new SnapshotSpan(triggerPt.Snapshot, new Span(0, 0));
            return(false);
        }
Пример #21
0
        public void GoToNextOrPrevReference(bool next)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_view.TextBuffer);

            if (fileStore == null)
            {
                Log.Debug("No file store available.");
                return;
            }

            var appSettings = ProbeEnvironment.CurrentAppSettings;
            var fileName    = VsTextUtil.TryGetDocumentFileName(_view.TextBuffer);
            var model       = fileStore.GetMostRecentModel(appSettings, fileName, _view.TextSnapshot, "ReferenceScroller.GoToNextReference()");

            // Get the caret position
            var caretPtTest = _view.Caret.Position.Point.GetPoint(buf => (!buf.ContentType.IsOfType("projection")), Microsoft.VisualStudio.Text.PositionAffinity.Predecessor);

            if (!caretPtTest.HasValue)
            {
                Log.Debug("Couldn't get caret point.");
                return;
            }
            var caretPt  = caretPtTest.Value;
            var modelPos = caretPt.Snapshot.TranslateOffsetToSnapshot(caretPt.Position, model.Snapshot);

            // Get the token the cursor is currently on
            var token = model.File.FindDownward(modelPos).LastOrDefault(x => x.SourceDefinition != null);

            if (token == null)
            {
                ProbeToolsPackage.Instance.SetStatusText("No reference found at this position.");
                return;
            }
            var def = token.SourceDefinition;

            // Find all references
            var refs = model.File.FindDownward(t => t.SourceDefinition == def).ToArray();

            if (refs.Length == 0)
            {
                Log.Debug("List of references is empty.");
                return;
            }

            // Find the current reference in the index
            var refIndex = -1;

            for (int i = 0; i < refs.Length; i++)
            {
                if (refs[i] == token)
                {
                    refIndex = i;
                    break;
                }
            }
            if (refIndex == -1)
            {
                Log.Debug("The current token couldn't be found in the reference list.");
                return;
            }

            var nextIndex = -1;

            if (next)
            {
                if (refIndex + 1 < refs.Length)
                {
                    nextIndex = refIndex + 1;
                }
                else
                {
                    nextIndex = 0;
                }
            }
            else
            {
                if (refIndex > 0)
                {
                    nextIndex = refIndex - 1;
                }
                else
                {
                    nextIndex = refs.Length - 1;
                }
            }
            var nextToken = refs[nextIndex];

            var snapStart = model.Snapshot.TranslateOffsetToSnapshot(nextToken.Span.Start, caretPt.Snapshot);
            var snapEnd   = model.Snapshot.TranslateOffsetToSnapshot(nextToken.Span.End, caretPt.Snapshot);
            var snapSpan  = new SnapshotSpan(caretPt.Snapshot, snapStart, snapEnd - snapStart);

            MoveTo(snapSpan);

            ProbeToolsPackage.Instance.SetStatusText(string.Format("Reference {0} of {1}.", nextIndex + 1, refs.Length));
        }
Пример #22
0
        public static void InsertDiag()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dte       = Shell.DTE;
            var activeDoc = dte.ActiveDocument;

            if (activeDoc != null)
            {
                var options = ProbeToolsPackage.Instance.TaggingOptions;

                var sel     = activeDoc.Selection as TextSelection;
                var selText = sel.Text.Trim();
                if (selText.IndexOf('\n') >= 0)
                {
                    selText = string.Empty;
                }

                var sb = new StringBuilder();
                sb.Append("diag(\"");
                if (options.InitialsInDiags && !string.IsNullOrWhiteSpace(options.Initials))
                {
                    sb.Append(options.Initials);
                    sb.Append(": ");
                }

                if (options.FileNameInDiags)
                {
                    sb.Append(Path.GetFileName(activeDoc.FullName));
                    sb.Append(": ");
                }

                if (options.FunctionNameInDiags)
                {
                    var funcName = string.Empty;
                    var buf      = Shell.ActiveBuffer;
                    if (buf != null)
                    {
                        var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(buf);
                        if (fileStore != null)
                        {
                            var appSettings = ProbeEnvironment.CurrentAppSettings;
                            var fileName    = VsTextUtil.TryGetDocumentFileName(buf);
                            var funcs       = fileStore.GetFunctionDropDownList(appSettings, fileName, buf.CurrentSnapshot);
                            var model       = fileStore.GetMostRecentModel(appSettings, fileName, buf.CurrentSnapshot, "Insert diag");
                            var modelPos    = model.AdjustPosition(Shell.ActiveView.Caret.Position.BufferPosition.Position, model.Snapshot);
                            foreach (var func in funcs)
                            {
                                if (func.EntireFunctionSpan.Contains(modelPos))
                                {
                                    funcName = func.Name;
                                    break;
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(funcName))
                    {
                        sb.Append(funcName);
                        sb.Append("(): ");
                    }
                }

                if (!string.IsNullOrWhiteSpace(selText))
                {
                    sb.Append(ProbeEnvironment.StringEscape(selText));
                    sb.Append(" [\", ");
                    sb.Append(selText);
                    sb.Append(", \"]");
                }

                int lengthBefore = sb.Length;

                sb.Append("\\n\");");
                if (options.TodoAfterDiags)
                {
                    sb.Append("\t// TODO");
                }

                sel.Insert(sb.ToString());

                if (string.IsNullOrWhiteSpace(selText))
                {
                    sel.CharLeft(false, sb.Length - lengthBefore);
                }
            }
        }
Пример #23
0
        public IList <ClassificationSpan> GetClassificationSpans(SnapshotSpan span)         // from IClassifier
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            _snapshot = span.Snapshot;

            var appSettings = ProbeEnvironment.CurrentAppSettings;
            var fileName    = VsTextUtil.TryGetDocumentFileName(span.Snapshot.TextBuffer);

            var tracker   = TextBufferStateTracker.GetTrackerForTextBuffer(span.Snapshot.TextBuffer);
            var spans     = new List <ClassificationSpan>();
            var state     = tracker.GetStateForPosition(span.Start.Position, span.Snapshot, fileName, appSettings);
            var tokenInfo = new ProbeClassifierScanner.TokenInfo();

            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(span.Snapshot.TextBuffer);

            if (fileStore == null)
            {
                return(new List <ClassificationSpan>());
            }

            var model = fileStore.GetMostRecentModel(appSettings, fileName, span.Snapshot, "GetClassificationSpans");

            _scanner.SetSource(span.GetText(), span.Start.Position, span.Snapshot, model);

            var disableDeadCode = ProbeToolsPackage.Instance.EditorOptions.DisableDeadCode;

            DisabledSectionTracker disabledSectionTracker = null;

            if (disableDeadCode)
            {
                disabledSectionTracker = new DisabledSectionTracker(model.DisabledSections);
                if (disabledSectionTracker.SetOffset(_scanner.PositionOffset))
                {
                    state |= State.Disabled;
                }
                else
                {
                    state &= ~State.Disabled;
                }
            }
            else
            {
                state &= ~State.Disabled;
            }

            while (_scanner.ScanTokenAndProvideInfoAboutIt(tokenInfo, ref state))
            {
                var classificationType = GetClassificationType(tokenInfo.Type);
                if (classificationType != null)
                {
                    spans.Add(new ClassificationSpan(new SnapshotSpan(_snapshot, new Span(span.Start.Position + tokenInfo.StartIndex, tokenInfo.Length)), classificationType));
                }

                if (disableDeadCode)
                {
                    if (disabledSectionTracker.Advance(_scanner.PositionOffset + _scanner.Position))
                    {
                        state |= State.Disabled;
                    }
                    else
                    {
                        state &= ~State.Disabled;
                    }
                }
                else
                {
                    state &= ~State.Disabled;
                }
            }

            return(spans);
        }