Example #1
0
        internal Result <ITextBuffer> GetTextBufferForDocCookie(uint cookie)
        {
            var info                 = _table.GetDocumentInfo(cookie);
            var obj                  = info.DocData;
            var vsTextLines          = obj as IVsTextLines;
            var vsTextBufferProvider = obj as IVsTextBufferProvider;

            ITextBuffer textBuffer;

            if (vsTextLines != null)
            {
                textBuffer = _editorAdaptersFactoryService.GetDataBuffer(vsTextLines);
            }
            else if (vsTextBufferProvider != null &&
                     ErrorHandler.Succeeded(vsTextBufferProvider.GetTextBuffer(out vsTextLines)) &&
                     vsTextLines != null)
            {
                textBuffer = _editorAdaptersFactoryService.GetDataBuffer(vsTextLines);
            }
            else
            {
                textBuffer = null;
            }

            return(Result.CreateSuccessNonNull(textBuffer));
        }
        public XFile getFile(IVsTextBuffer pBuffer)
        {
            var   buffer = _editorAdaptersFactoryService.GetDataBuffer(pBuffer);
            XFile file;

            if (buffer.Properties.TryGetProperty(typeof(XSharpModel.XFile), out file))
            {
                return(file);
            }
            return(null);
        }
        public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR ppEnum)
        {
            var textBuffer = _editorAdaptersFactory.GetDataBuffer(pBuffer);

            if (textBuffer == null)
            {
                // Can't resolve the text buffer, let someone else deal with this breakpoint.
                ppEnum = null;
                return(VSConstants.E_NOTIMPL);
            }

            var snapshot = textBuffer.CurrentSnapshot;

            if (!ValidateLocation(snapshot, iLine, iCol))
            {
                // The point disappeared between sessions. Do not evaluate proximity expressions here.
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            var dialogResult = _waitDialogFactory.TryCreateWaitDialog(
                title: "Determining proximity expressions...",
                message: "Razor Debugger",
                async(context) =>
            {
                var proximityExpressions = await _proximityExpressionResolver.TryResolveProximityExpressionsAsync(textBuffer, iLine, iCol, context.CancellationToken).ConfigureAwait(false);
                return(proximityExpressions);
            });

            if (dialogResult == null)
            {
                // Failed to create the dialog at all.
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            if (dialogResult.Cancelled)
            {
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            if (dialogResult.Result == null)
            {
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            ppEnum = new VsEnumBSTR(dialogResult.Result);
            return(VSConstants.S_OK);
        }
Example #4
0
        ITextBuffer GetBufferAt(string filePath)
        {
            IVsUIHierarchy uiHierarchy;
            uint           itemID;
            IVsWindowFrame windowFrame;

            if (VsShellUtilities.IsDocumentOpen(
                    serviceProvider,
                    filePath,
                    Guid.Empty,
                    out uiHierarchy,
                    out itemID,
                    out windowFrame))
            {
                IVsTextView  view = VsShellUtilities.GetTextView(windowFrame);
                IVsTextLines lines;
                if (view.GetBuffer(out lines) == 0)
                {
                    var buffer = lines as IVsTextBuffer;
                    if (buffer != null)
                    {
                        return(vsEditorAdaptersFactory.GetDataBuffer(buffer));
                    }
                }
            }

            return(null);
        }
Example #5
0
        public void DocumentOpened(uint cookie)
        {
            JoinableTaskContext.AssertUIThread();

            lock (Lock)
            {
                // Casts avoid dynamic
                if ((object)_runningDocumentTable.GetDocumentData(cookie) is IVsTextBuffer vsTextBuffer)
                {
                    var filePath = _runningDocumentTable.GetDocumentMoniker(cookie);
                    if (!TryGetMatchingDocuments(filePath, out var documents))
                    {
                        // This isn't a document that we're interesting in.
                        return;
                    }

                    var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);
                    if (textBuffer == null)
                    {
                        // The text buffer has not been created yet, register to be notified when it is.
                        VsTextBufferDataEventsSink.Subscribe(vsTextBuffer, () => BufferLoaded(vsTextBuffer, filePath));

                        return;
                    }

                    // It's possible that events could be fired out of order and that this is a rename.
                    if (_documentsByCookie.ContainsKey(cookie))
                    {
                        DocumentClosed(cookie, exceptFilePath: filePath);
                    }

                    BufferLoaded(textBuffer, filePath, documents);
                }
            }
        }
        public IWpfTextViewHost CreateEditor(string filePath, int start = 0, int end = 0, bool createProjectedEditor = false)
        {
            //IVsInvisibleEditors are in-memory represenations of typical Visual Studio editors.
            //Language services, highlighting and error squiggles are hooked up to these editors
            //for us once we convert them to WpfTextViews.
            var invisibleEditor = GetInvisibleEditor(filePath);

            var  docDataPointer   = IntPtr.Zero;
            Guid guidIVsTextLines = typeof(IVsTextLines).GUID;

            ErrorHandler.ThrowOnFailure(invisibleEditor.GetDocData(
                                            fEnsureWritable: 1
                                            , riid: ref guidIVsTextLines
                                            , ppDocData: out docDataPointer));

            IVsTextLines docData = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);

            // This will actually be defined as _codewindowbehaviorflags2.CWB_DISABLEDIFF once the latest version of
            // Microsoft.VisualStudio.TextManager.Interop.16.0.DesignTime is published. Setting the flag will have no effect
            // on releases prior to d16.0.
            const _codewindowbehaviorflags CWB_DISABLEDIFF = (_codewindowbehaviorflags)0x04;

            //Create a code window adapter
            var codeWindow = _editorAdapter.CreateVsCodeWindowAdapter(VisualStudioServices.OLEServiceProvider);

            // You need to disable the dropdown, splitter and -- for d16.0 -- diff since you are extracting the code window's TextViewHost and using it.
            ((IVsCodeWindowEx)codeWindow).Initialize((uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER | (uint)_codewindowbehaviorflags.CWB_DISABLEDROPDOWNBAR | (uint)CWB_DISABLEDIFF,
                                                     VSUSERCONTEXTATTRIBUTEUSAGE.VSUC_Usage_Filter,
                                                     string.Empty,
                                                     string.Empty,
                                                     0,
                                                     new INITVIEW[1]);

            ErrorHandler.ThrowOnFailure(codeWindow.SetBuffer(docData));

            //Get a text view for our editor which we will then use to get the WPF control for that editor.
            IVsTextView textView;

            ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView));

            if (createProjectedEditor)
            {
                //We add our own role to this text view. Later this will allow us to selectively modify
                //this editor without getting in the way of Visual Studio's normal editors.
                var roles = _editorFactoryService.DefaultRoles.Concat(new string[] { "CustomProjectionRole" });

                var vsTextBuffer = docData as IVsTextBuffer;
                var textBuffer   = _editorAdapter.GetDataBuffer(vsTextBuffer);

                textBuffer.Properties.AddProperty("StartPosition", start);
                textBuffer.Properties.AddProperty("EndPosition", end);
                var guid = VSConstants.VsTextBufferUserDataGuid.VsTextViewRoles_guid;
                ((IVsUserData)codeWindow).SetData(ref guid, _editorFactoryService.CreateTextViewRoleSet(roles).ToString());
            }

            _currentlyFocusedTextView = textView;
            var textViewHost = _editorAdapter.GetWpfTextViewHost(textView);

            return(textViewHost);
        }
Example #7
0
        protected override void Initialize()
        {
            base.Initialize();

            IComponentModel                 compMod         = GetService(typeof(SComponentModel)) as IComponentModel;
            ITextBufferFactoryService       bufferFactory   = compMod.GetService <ITextBufferFactoryService>();
            ITextEditorFactoryService       editorFactory   = compMod.GetService <ITextEditorFactoryService>();
            IVsEditorAdaptersFactoryService adapterFactory  = compMod.GetService <IVsEditorAdaptersFactoryService>();
            IContentTypeRegistryService     registryService = compMod.GetService <IContentTypeRegistryService>();

            //completionBroker = compMod.GetService<ICompletionBroker>();

            textView = adapterFactory.CreateVsTextViewAdapter(GetService(typeof(IOleServiceProvider)) as IOleServiceProvider);
            IVsTextBuffer textBuffer        = adapterFactory.CreateVsTextBufferAdapter(GetService(typeof(IOleServiceProvider)) as IOleServiceProvider);
            uint          textViewInitFlags = (uint)TextViewInitFlags.VIF_DEFAULT |
                                              (uint)TextViewInitFlags.VIF_HSCROLL |
                                              (uint)TextViewInitFlags.VIF_VSCROLL;

            textBuffer.InitializeContent("", 0);
            textView.Initialize(textBuffer as IVsTextLines, IntPtr.Zero, textViewInitFlags, null);

            // Create Dev10 objects
            _textView     = adapterFactory.GetWpfTextView(textView);
            mefTextBuffer = adapterFactory.GetDataBuffer(textBuffer);

            IVsUserData userData = textView as IVsUserData;

            if (userData != null)
            {
                Guid   g = Microsoft.VisualStudio.Editor.DefGuidList.guidIWpfTextViewHost;
                object obj;
                int    hr = userData.GetData(ref g, out obj);
                if (hr == VSConstants.S_OK)
                {
                    _textViewHost = obj as IWpfTextViewHost;
                }
            }

            // disable zoom view
            _textView.Options.SetOptionValue(DefaultTextViewHostOptions.ZoomControlId, false);

            //Initialize the history
            if (null == history)
            {
                history = new HistoryBuffer();
            }

            adapterFactory.GetWpfTextView(textView).Caret.MoveTo(new SnapshotPoint(mefTextBuffer.CurrentSnapshot, mefTextBuffer.CurrentSnapshot.Length));


            IContentType ivsdContentType = registryService.GetContentType(VSDContentTypeDefinition.ContentType);

            mefTextBuffer.ChangeContentType(ivsdContentType, null);

            // init console input
            WriteConsoleInputSymbol();

            return;
        }
        private ITextBuffer GetTextBufferFromCookie(uint docCookie)
        {
            var documentInfo = RunningDocumentTable.GetDocumentInfo(docCookie);

            var textLines          = documentInfo.DocData as IVsTextLines;
            var textBufferProvider = documentInfo.DocData as IVsTextBufferProvider;

            ITextBuffer textBuffer = null;

            if (textLines != null)
            {
                textBuffer = _editorAdaptersFactory.GetDataBuffer(textLines);
            }
            else if (textBufferProvider != null && textBufferProvider.GetTextBuffer(out textLines) == 0)
            {
                textBuffer = _editorAdaptersFactory.GetDataBuffer(textLines);
            }

            return(textBuffer);
        }
Example #9
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            VisualStudioProjectTracker projectTrackerOpt,
            ProjectId projectId,
            TLanguageService languageService,
            AbstractFormattingRule vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = projectTrackerOpt?.Workspace ?? componentModel.GetService <VisualStudioWorkspace>();

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService    = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer);

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines);

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath))
                {
                    FatalError.Report(new System.Exception("Failed to get document moniker for a contained document"));
                }
            }

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(), filePath,
                    sourceCodeKind: SourceCodeKind.Regular, folders: default,
        private async Task <INavigableLocation?> GetNavigableLocationForMetadataAsync(
            Project project, ISymbol symbol, CancellationToken cancellationToken)
        {
            var masOptions = _globalOptions.GetMetadataAsSourceOptions();

            var result = await _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, signaturesOnly : false, masOptions, cancellationToken).ConfigureAwait(false);

            return(new NavigableLocation(async(options, cancellationToken) =>
            {
                await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                var vsRunningDocumentTable4 = _serviceProvider.GetServiceOnMainThread <SVsRunningDocumentTable, IVsRunningDocumentTable4>();
                var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

                var openDocumentService = _serviceProvider.GetServiceOnMainThread <SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
                openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out _, out var windowFrame);

                var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

                var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);

                // Set the buffer to read only, just in case the file isn't
                ErrorHandler.ThrowOnFailure(vsTextBuffer.GetStateFlags(out var flags));
                flags |= (int)BUFFERSTATEFLAGS.BSF_USER_READONLY;
                ErrorHandler.ThrowOnFailure(vsTextBuffer.SetStateFlags(flags));

                var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

                if (!fileAlreadyOpen)
                {
                    ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                    ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                    ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
                }

                windowFrame.Show();

                var openedDocument = textBuffer?.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
                if (openedDocument != null)
                {
                    var editorWorkspace = openedDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();

                    await navigationService.TryNavigateToSpanAsync(
                        this.ThreadingContext,
                        editorWorkspace,
                        openedDocument.Id,
                        result.IdentifierLocation.SourceSpan,
                        options with {
                        PreferProvisionalTab = true
                    },
                        cancellationToken).ConfigureAwait(false);
                }
        public int ValidateBreakpointLocation(IVsTextBuffer pBuffer, int iLine, int iCol, TextSpan[] pCodeSpan)
        {
            var textBuffer = _editorAdaptersFactory.GetDataBuffer(pBuffer);

            if (textBuffer == null)
            {
                // Can't resolve the text buffer, let someone else deal with this breakpoint.
                return(VSConstants.E_NOTIMPL);
            }

            var snapshot = textBuffer.CurrentSnapshot;

            if (!ValidBreakpointLocation(snapshot, iLine, iCol))
            {
                // The point disappeared between sessions. Do not allow a breakpoint here.
                return(VSConstants.E_FAIL);
            }

            var dialogResult = _waitDialogFactory.TryCreateWaitDialog(
                title: "Determining breakpoint location...",
                message: "Razor Debugger",
                async(context) =>
            {
                var breakpointRange = await _breakpointResolver.TryResolveBreakpointRangeAsync(textBuffer, iLine, iCol, context.CancellationToken);
                if (breakpointRange == null)
                {
                    // No applicable breakpoint location.
                    return(VSConstants.E_FAIL);
                }

                pCodeSpan[0] = new TextSpan()
                {
                    iStartIndex = breakpointRange.Start.Character,
                    iStartLine  = breakpointRange.Start.Line,
                    iEndIndex   = breakpointRange.End.Character,
                    iEndLine    = breakpointRange.End.Line,
                };
                return(VSConstants.S_OK);
            });

            if (dialogResult == null)
            {
                // Failed to create the dialog at all.
                return(VSConstants.E_FAIL);
            }

            if (dialogResult.Cancelled)
            {
                return(VSConstants.E_FAIL);
            }

            return(dialogResult.Result);
        }
Example #12
0
        internal static Ast GetScript(IVsEditorAdaptersFactoryService adaptersFactory, IVsTextBuffer buffer)
        {
            ITextBuffer textBuffer = adaptersFactory.GetDataBuffer(buffer);
            Ast         scriptAst;

            if (!textBuffer.Properties.TryGetProperty <Ast>(BufferProperties.Ast, out scriptAst))
            {
                return(null);
            }

            return(scriptAst);
        }
Example #13
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            Workspace workspace,
            ProjectId projectId,
            VisualStudioProject?project,
            string filePath,
            Guid languageServiceGuid,
            AbstractFormattingRule?vbHelperFormattingRule = null
            )
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageServiceGuid   = languageServiceGuid;

            this.Workspace = workspace;

            _editorAdaptersFactoryService =
                componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(
                bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines)
                );
            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryTextLines) !;

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(
                bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines)
                );
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer(primaryTextLines) !;

            // Create our tagger
            var bufferTagAggregatorFactory =
                ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(
                SubjectBuffer
                );

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(),
                    filePath,
                    sourceCodeKind: SourceCodeKind.Regular,
                    folders: default,
        public int GetProximityExpressions(IVsTextBuffer pBuffer, int iLine, int iCol, int cLines, out IVsEnumBSTR?ppEnum)
        {
            var textBuffer = _editorAdaptersFactory.GetDataBuffer(pBuffer);

            if (textBuffer is null)
            {
                // Can't resolve the text buffer, let someone else deal with this breakpoint.
                ppEnum = null;
                return(VSConstants.E_NOTIMPL);
            }

            var snapshot = textBuffer.CurrentSnapshot;

            if (!ValidateLocation(snapshot, iLine, iCol))
            {
                // The point disappeared between sessions. Do not evaluate proximity expressions here.
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            var proximityExpressions = _uiThreadOperationExecutor.Execute(
                title: Resources.ProximityExpression_Dialog_Title,
                description: Resources.ProximityExpression_Dialog_Description,
                allowCancellation: true,
                showProgress: true,
                (cancellationToken) => _proximityExpressionResolver.TryResolveProximityExpressionsAsync(textBuffer, iLine, iCol, cancellationToken), _joinableTaskFactory);

            if (proximityExpressions is null)
            {
                ppEnum = null;
                return(VSConstants.E_FAIL);
            }

            ppEnum = new VsEnumBSTR(proximityExpressions);
            return(VSConstants.S_OK);
        }
Example #15
0
        public bool TryGetTextBufferForDocCookie(uint cookie, out ITextBuffer buffer)
        {
            var info                 = _table.GetDocumentInfo(cookie);
            var obj                  = info.DocData;
            var vsTextLines          = obj as IVsTextLines;
            var vsTextBufferProvider = obj as IVsTextBufferProvider;

            if (vsTextLines != null)
            {
                buffer = _editorAdaptersFactoryService.GetDataBuffer(vsTextLines);
            }
            else if (vsTextBufferProvider != null &&
                     ErrorHandler.Succeeded(vsTextBufferProvider.GetTextBuffer(out vsTextLines)) &&
                     vsTextLines != null)
            {
                buffer = _editorAdaptersFactoryService.GetDataBuffer(vsTextLines);
            }
            else
            {
                buffer = null;
            }

            return(buffer != null);
        }
Example #16
0
        public static Language GetLanguage(VS.Document doc)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Language result = Language.Unknown;

            if (doc != null)
            {
                result = GetLanguage(doc.Language, doc.FullName);

                // I'd like to get the "current" (based on the caret position) ITextBuffer's ContentType.
                // That would allow for better Language decisions in multi-language files like .razor,
                // which allows C#, HTML, and CSS. But I can't figure out a way to get the current
                // caret position's ITextBuffer. This started from https://stackoverflow.com/a/7373385/1882616.
                if ((result == Language.Unknown || result == Language.PlainText) &&
                    doc.DTE is Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider &&
                    !string.IsNullOrEmpty(doc.FullName))
                {
                    using (var serviceProvider = new ServiceProvider(oleServiceProvider))
                    {
                        if (VsShellUtilities.IsDocumentOpen(
                                serviceProvider,
                                doc.FullName,
                                Guid.Empty,
                                out _,
                                out _,
                                out IVsWindowFrame windowFrame))
                        {
                            IVsTextView view = VsShellUtilities.GetTextView(windowFrame);
                            if (view.GetBuffer(out IVsTextLines lines) == VSConstants.S_OK && lines is IVsTextBuffer vsBuffer)
                            {
                                IComponentModel componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
                                IVsEditorAdaptersFactoryService adapterFactory = componentModel.GetService <IVsEditorAdaptersFactoryService>();
                                ITextBuffer buffer          = adapterFactory.GetDataBuffer(vsBuffer);
                                string      contentType     = buffer?.ContentType?.TypeName;
                                Language    contentLanguage = GetLanguage(contentType, doc.FullName);
                                if (contentLanguage != Language.Unknown)
                                {
                                    result = contentLanguage;
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        public IWpfTextViewHost CreateEditor(string filePath, int start = 0, int end = 0, bool createProjectedEditor = false)
        {
            //IVsInvisibleEditors are in-memory represenations of typical Visual Studio editors.
            //Language services, highlighting and error squiggles are hooked up to these editors
            //for us once we convert them to WpfTextViews.
            var invisibleEditor = GetInvisibleEditor(filePath);

            var  docDataPointer   = IntPtr.Zero;
            Guid guidIVsTextLines = typeof(IVsTextLines).GUID;

            ErrorHandler.ThrowOnFailure(invisibleEditor.GetDocData(
                                            fEnsureWritable: 1
                                            , riid: ref guidIVsTextLines
                                            , ppDocData: out docDataPointer));

            IVsTextLines docData = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);

            //Create a code window adapter
            var codeWindow = _editorAdapter.CreateVsCodeWindowAdapter(VisualStudioServices.OLEServiceProvider);

            ErrorHandler.ThrowOnFailure(codeWindow.SetBuffer(docData));

            //Get a text view for our editor which we will then use to get the WPF control for that editor.
            IVsTextView textView;

            ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView));

            if (createProjectedEditor)
            {
                //We add our own role to this text view. Later this will allow us to selectively modify
                //this editor without getting in the way of Visual Studio's normal editors.
                var roles = _editorFactoryService.DefaultRoles.Concat(new string[] { "CustomProjectionRole" });

                var vsTextBuffer = docData as IVsTextBuffer;
                var textBuffer   = _editorAdapter.GetDataBuffer(vsTextBuffer);

                textBuffer.Properties.AddProperty("StartPosition", start);
                textBuffer.Properties.AddProperty("EndPosition", end);
                var guid = VSConstants.VsTextBufferUserDataGuid.VsTextViewRoles_guid;
                ((IVsUserData)codeWindow).SetData(ref guid, _editorFactoryService.CreateTextViewRoleSet(roles).ToString());
            }


            _currentlyFocusedTextView = textView;
            var textViewHost = _editorAdapter.GetWpfTextViewHost(textView);

            return(textViewHost);
        }
Example #18
0
        public ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            TProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            TLanguageService languageService,
            SourceCodeKind sourceCodeKind,
            IFormattingRule vbHelperFormattingRule = null)
            : base(project)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = componentModel.GetService <VisualStudioWorkspace>();
            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            // Get the ITextBuffer for the secondary buffer
            IVsTextLines secondaryTextLines;

            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SetSubjectBuffer(_editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer));

            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            IVsTextLines primaryTextLines;

            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out primaryTextLines));
            var primaryVsTextBuffer = (IVsTextBuffer)primaryTextLines;
            var dataBuffer          = (IProjectionBuffer)_editorAdaptersFactoryService.GetDataBuffer(primaryVsTextBuffer);

            SetDataBuffer(dataBuffer);

            this.ContainedDocument = new ContainedDocument(
                this, sourceCodeKind, this.Workspace, hierarchy, itemid, componentModel, vbHelperFormattingRule);

            // TODO: Can contained documents be linked or shared?
            this.Project.AddDocument(this.ContainedDocument, isCurrentContext: true);
        }
Example #19
0
        int IVsLanguageInfo.GetCodeWindowManager(IVsCodeWindow pCodeWin, out IVsCodeWindowManager ppCodeWinMgr)
        {
            IVsEditorAdaptersFactoryService adaptersFactory = ComponentModel.GetService <IVsEditorAdaptersFactoryService>();

            IVsTextLines textLines;

            ErrorHandler.ThrowOnFailure(pCodeWin.GetBuffer(out textLines));
            ITextBuffer textBuffer = adaptersFactory.GetDataBuffer(textLines);

            if (textBuffer == null)
            {
                ppCodeWinMgr = null;
                return(VSConstants.E_FAIL);
            }

            ppCodeWinMgr = GetCodeWindowManager(pCodeWin, textBuffer);
            return(VSConstants.S_OK);
        }
Example #20
0
        public static ITextDocument GetTextDocument(
            IVsWindowFrame frame,
            IVsEditorAdaptersFactoryService adapterFactory,
            ITextDocumentFactoryService documentFactory)
        {
            ITextDocument result = null;

            // http://stackoverflow.com/a/7373385/1882616
            IVsTextView view = VsShellUtilities.GetTextView(frame);

            if (view != null && view.GetBuffer(out IVsTextLines lines) == 0 && lines is IVsTextBuffer oldVsBuffer)
            {
                ITextBuffer buffer = adapterFactory.GetDataBuffer(oldVsBuffer);
                result = GetTextDocument(buffer, documentFactory);
            }

            return(result);
        }
Example #21
0
        public static ITextBuffer GetTextBuffer(IServiceProvider serviceProvider, IVsTextView textView)
        {
            IComponentModel componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();

            IVsTextLines textLines;

            if (textView.GetBuffer(out textLines) == VSConstants.S_OK)
            {
                IVsTextBuffer buffer = textLines as IVsTextBuffer;
                if (buffer != null)
                {
                    ITextBuffer textBuffer = editorAdaptersFactoryService.GetDataBuffer(buffer);
                    return(textBuffer);
                }
            }

            return(null);
        }
        public static ParamBlockAst GetScriptParameters(IVsEditorAdaptersFactoryService adaptersFactory, IVsTextManager textManager)
        {
            IVsTextView   vsTextView;
            ParamBlockAst paramBlock = null;

            //Returns the active or previously active view.
            //
            // Parameters:
            //   fMustHaveFocus:
            //     [in] If true, then the current UI active view is returned. If false, then
            //     the last active view is returned, regardless of whether this view is currently
            //     UI active.
            //
            //   pBuffer:
            //     [in] Pass null for pBuffer to get the previously active code view, regardless
            //     of the text buffer that it was associated with. If you pass in a valid pointer
            //     to a buffer, then you are returned the last active view for that particular
            //     buffer.
            //
            //   ppView:
            //     [out] Pointer to the Microsoft.VisualStudio.TextManager.Interop.IVsTextView
            //     interface.
            textManager.GetActiveView(1, null, out vsTextView);
            if (vsTextView == null)
            {
                return(null);
            }

            IVsTextLines textLines;

            vsTextView.GetBuffer(out textLines);
            ITextBuffer textBuffer = adaptersFactory.GetDataBuffer(textLines as IVsTextBuffer);
            Ast         scriptAst;

            if (!textBuffer.Properties.TryGetProperty <Ast>(BufferProperties.Ast, out scriptAst))
            {
                return(null);
            }

            PowerShellParseUtilities.HasParamBlock(scriptAst, out paramBlock);
            return(paramBlock);
        }
Example #23
0
            private void Show()
            {
                IVsTextView    view;
                IVsWindowFrame vsWindowFrame;

                try {
                    IVsUIHierarchy hier;
                    uint           itemid;
                    VsShellUtilities.OpenDocument(RPackage.Current, _fileName, VSConstants.LOGVIEWID.Code_guid, out hier, out itemid, out vsWindowFrame, out view);
                } catch (Exception ex) {
                    _services.ShowErrorMessage(Resources.Error_ExceptionAccessingPath.FormatInvariant(_fileName, ex.Message));
                    _tcs.TrySetResult(string.Empty);
                    return;
                }

                _editorFrame = vsWindowFrame;
                if (view == null || _editorFrame == null)
                {
                    _tcs.TrySetResult(string.Empty);
                    return;
                }

                if (_tcs.Task.IsCompleted)
                {
                    Close();
                    return;
                }

                IVsTextLines vsTextLines;

                view.GetBuffer(out vsTextLines);
                _textBuffer = _adapterService.GetDataBuffer(vsTextLines);

                _uiShell = _services.GetService <IVsUIShell7>(typeof(SVsUIShell));
                _cookie  = _uiShell.AdviseWindowFrameEvents(this);
            }
        private bool GetBufferAndSelection(out ITextBuffer textBuffer, out int selectionStart, out int selectionEnd, out string selectedCode, out bool emptySelection)
        {
            emptySelection = SelectLines();

            textBuffer = null;

            IVsTextView textView;

            if (_textManager.GetActiveView(1, null, out textView) == 0)
            {
                TextSpan[] span = new TextSpan[1];

                int temp;

                textView.GetSelectionSpan(span);
                textView.GetNearestPosition(span[0].iStartLine, span[0].iStartIndex, out selectionStart, out temp);
                textView.GetNearestPosition(span[0].iEndLine, span[0].iEndIndex, out selectionEnd, out temp);

                IVsTextLines lines;
                if (textView.GetBuffer(out lines) == 0)
                {
                    var linesTextBuffer = lines as IVsTextBuffer;

                    textBuffer   = _adapters.GetDataBuffer(linesTextBuffer);
                    selectedCode = textBuffer.CurrentSnapshot.GetText(selectionStart, selectionEnd - selectionStart);

                    return(true);
                }
            }

            selectionStart = 0;
            selectionEnd   = 0;
            selectedCode   = "";

            return(false);
        }
Example #25
0
        public ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            TLanguageService languageService,
            IFormattingRule vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = componentModel.GetService <VisualStudioWorkspace>();

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService    = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer);

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines);

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath))
                {
                    FatalError.Report(new System.Exception("Failed to get document moniker for a contained document"));
                }
            }

            var documentId = this.Project.AddSourceTextContainer(SubjectBuffer.AsTextContainer(), filePath);

            this.ContainedDocument = new ContainedDocument(
                componentModel.GetService <IThreadingContext>(),
                documentId,
                subjectBuffer: SubjectBuffer,
                dataBuffer: DataBuffer,
                bufferCoordinator,
                this.Workspace,
                project,
                hierarchy,
                itemid,
                componentModel,
                vbHelperFormattingRule);

            // TODO: Can contained documents be linked or shared?
            this.DataBuffer.Changed += OnDataBufferChanged;
        }
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, bool usePreviewTab = false)
        {
            if (project == null || symbol == null)
            {
                return(false);
            }

            symbol = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations        = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation         = visibleSourceLocations.Any() ? visibleSourceLocations.First() : sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace   = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetService <IDocumentNavigationService>();
                    return(navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, usePreviewTab));
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();

            if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return(false);
            }

            // Generate new source or retrieve existing source for the symbol in question
            var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol).WaitAndGetResult(CancellationToken.None);

            var vsRunningDocumentTable4 = GetService <SVsRunningDocumentTable, IVsRunningDocumentTable4>();
            var fileAlreadyOpen         = vsRunningDocumentTable4.IsMonikerValid((string)result.FilePath);

            var openDocumentService = GetService <SVsUIShellOpenDocument, IVsUIShellOpenDocument>();

            IVsUIHierarchy      hierarchy;
            uint                itemId;
            IOleServiceProvider localServiceProvider;
            IVsWindowFrame      windowFrame;

            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
            var textBuffer   = _editorAdaptersFactory.GetDataBuffer((IVsTextBuffer)vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();

            if (openedDocument != null)
            {
                var editorWorkspace   = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetService <IDocumentNavigationService>();
                return(navigationService.TryNavigateToSpan(editorWorkspace, openedDocument.Id, result.IdentifierLocation.SourceSpan, usePreviewTab: true));
            }

            return(true);
        }
Example #27
0
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet?options, CancellationToken cancellationToken)
        {
            if (project == null || symbol == null)
            {
                return(false);
            }

            options ??= project.Solution.Options;
            symbol = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations        = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation         = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace   = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();
                    return(navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options, cancellationToken));
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();

            if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return(false);
            }

            // Should we prefer navigating to the Object Browser over metadata-as-source?
            if (_globalOptions.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
            {
                var libraryService = project.LanguageServices.GetService <ILibraryService>();
                if (libraryService == null)
                {
                    return(false);
                }

                var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var navInfo     = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
                if (navInfo == null)
                {
                    navInfo = libraryService.NavInfoFactory.CreateForProject(project);
                }

                if (navInfo != null)
                {
                    var navigationTool = IServiceProviderExtensions.GetService <SVsObjBrowser, IVsNavigationTool>(_serviceProvider);
                    return(navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK);
                }

                // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
            }

            // Generate new source or retrieve existing source for the symbol in question
            var allowDecompilation = false;

            // Check whether decompilation is supported for the project. We currently only support this for C# projects.
            if (project.LanguageServices.GetService <IDecompiledSourceService>() != null)
            {
                allowDecompilation = project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.NavigateToDecompiledSources) && !symbol.IsFromSource();
            }

            var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, allowDecompilation, cancellationToken).WaitAndGetResult(cancellationToken);

            var vsRunningDocumentTable4 = IServiceProviderExtensions.GetService <SVsRunningDocumentTable, IVsRunningDocumentTable4>(_serviceProvider);
            var fileAlreadyOpen         = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

            var openDocumentService = IServiceProviderExtensions.GetService <SVsUIShellOpenDocument, IVsUIShellOpenDocument>(_serviceProvider);

            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out var localServiceProvider, out var hierarchy, out var itemId, out var windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            // The cast from dynamic to object doesn't change semantics, but avoids loading the dynamic binder
            // which saves us JIT time in this method.
            var vsTextBuffer = (IVsTextBuffer)(object)vsRunningDocumentTable4.GetDocumentData(documentCookie);
            var textBuffer   = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer?.AsTextContainer().GetRelatedDocuments().FirstOrDefault();

            if (openedDocument != null)
            {
                var editorWorkspace   = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetRequiredService <IDocumentNavigationService>();

                return(navigationService.TryNavigateToSpan(
                           editorWorkspace,
                           openedDocument.Id,
                           result.IdentifierLocation.SourceSpan,
                           options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true),
                           cancellationToken));
            }

            return(true);
        }
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken)
        {
            if (project == null || symbol == null)
            {
                return(false);
            }

            options = options ?? project.Solution.Workspace.Options;
            symbol  = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations        = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation         = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace   = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetService <IDocumentNavigationService>();
                    return(navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options));
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();

            if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return(false);
            }

            // Should we prefer navigating to the Object Browser over metadata-as-source?
            if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
            {
                var libraryService = project.LanguageServices.GetService <ILibraryService>();
                if (libraryService == null)
                {
                    return(false);
                }

                var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var navInfo     = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
                if (navInfo == null)
                {
                    navInfo = libraryService.NavInfoFactory.CreateForProject(project);
                }

                if (navInfo != null)
                {
                    var navigationTool = _serviceProvider.GetService <SVsObjBrowser, IVsNavigationTool>();
                    return(navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK);
                }

                // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
            }

            // Generate new source or retrieve existing source for the symbol in question
            var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken);

            var vsRunningDocumentTable4 = _serviceProvider.GetService <SVsRunningDocumentTable, IVsRunningDocumentTable4>();
            var fileAlreadyOpen         = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

            var openDocumentService = _serviceProvider.GetService <SVsUIShellOpenDocument, IVsUIShellOpenDocument>();

            IVsUIHierarchy      hierarchy;
            uint                itemId;
            IOleServiceProvider localServiceProvider;
            IVsWindowFrame      windowFrame;

            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
            var textBuffer   = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();

            if (openedDocument != null)
            {
                var editorWorkspace   = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetService <IDocumentNavigationService>();

                return(navigationService.TryNavigateToSpan(
                           workspace: editorWorkspace,
                           documentId: openedDocument.Id,
                           textSpan: result.IdentifierLocation.SourceSpan,
                           options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true)));
            }

            return(true);
        }
        protected override void Initialize()
        {
            base.Initialize();

            IComponentModel                 compMod         = GetService(typeof(SComponentModel)) as IComponentModel;
            ITextBufferFactoryService       bufferFactory   = compMod.GetService <ITextBufferFactoryService>();
            ITextEditorFactoryService       editorFactory   = compMod.GetService <ITextEditorFactoryService>();
            IVsEditorAdaptersFactoryService adapterFactory  = compMod.GetService <IVsEditorAdaptersFactoryService>();
            IContentTypeRegistryService     registryService = compMod.GetService <IContentTypeRegistryService>();

            completionBroker = compMod.GetService <ICompletionBroker>();

            textView = adapterFactory.CreateVsTextViewAdapter(GetService(typeof(IOleServiceProvider)) as IOleServiceProvider);
            IVsTextBuffer textBuffer        = adapterFactory.CreateVsTextBufferAdapter(GetService(typeof(IOleServiceProvider)) as IOleServiceProvider);
            uint          textViewInitFlags = (uint)TextViewInitFlags.VIF_DEFAULT
                                              | (uint)TextViewInitFlags.VIF_HSCROLL
                                              | (uint)TextViewInitFlags.VIF_VSCROLL;

            textBuffer.InitializeContent("", 0);
            textView.Initialize(textBuffer as IVsTextLines, IntPtr.Zero, textViewInitFlags, null);

            // Create Dev10 objects
            _textView     = adapterFactory.GetWpfTextView(textView);
            mefTextBuffer = adapterFactory.GetDataBuffer(textBuffer);

            IVsUserData userData = textView as IVsUserData;

            if (userData != null)
            {
                Guid   g = Microsoft.VisualStudio.Editor.DefGuidList.guidIWpfTextViewHost;
                object obj;
                int    hr = userData.GetData(ref g, out obj);
                if (hr == VSConstants.S_OK)
                {
                    _textViewHost = obj as IWpfTextViewHost;
                }
            }


            //Initialize the history
            history = new HistoryBuffer();

            // Create the stream on top of the text buffer.
            textStream = new TextBufferStream(mefTextBuffer);

            // Initialize the engine.
            InitializeEngine();

            IContentType ipContentType = registryService.GetContentType(PyContentTypeDefinition.ConsoleContentType);

            mefTextBuffer.ChangeContentType(ipContentType, null);

            adapterFactory.GetWpfTextView(textView).Caret.MoveTo(new SnapshotPoint(mefTextBuffer.CurrentSnapshot, mefTextBuffer.CurrentSnapshot.Length));

            // Set the title of the window.
            this.Caption = Resources.ToolWindowTitle;

            // Set the icon of the toolwindow.
            this.BitmapResourceID = 301;
            this.BitmapIndex      = 0;

            return;
        }