private IVsTextLines GetTextBuffer(System.IntPtr docDataExisting, string filename) { IVsTextLines textLines; if (docDataExisting == IntPtr.Zero) { // Create a new IVsTextLines buffer. Type textLinesType = typeof(IVsTextLines); Guid riid = textLinesType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines; // set the buffer's site ((IObjectWithSite)textLines).SetSite(_serviceProvider.GetService(typeof(IOleServiceProvider))); } else { // Use the existing text buffer Object dataObject = Marshal.GetObjectForIUnknown(docDataExisting); textLines = dataObject as IVsTextLines; if (textLines == null) { // Try get the text buffer from textbuffer provider IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider; if (textBufferProvider != null) { textBufferProvider.GetTextBuffer(out textLines); } } if (textLines == null) { // Unknown docData type then, so we have to force VS to close the other editor. ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA); } } return textLines; }
private static string GetBufferContents(object docDataObj) { string text = null; IVsTextLines buffer = null; if (docDataObj is IVsTextLines) { buffer = (IVsTextLines)docDataObj; } else if (docDataObj is IVsTextBufferProvider) { IVsTextBufferProvider tp = (IVsTextBufferProvider)docDataObj; if (tp.GetTextBuffer(out buffer) != NativeMethods.S_OK) { buffer = null; } } if (buffer != null) { int endLine, endIndex; NativeMethods.ThrowOnFailure(buffer.GetLastLineIndex(out endLine, out endIndex)); NativeMethods.ThrowOnFailure(buffer.GetLineText(0, 0, endLine, endIndex, out text)); buffer = null; } return(text); }
private void OpenDocumentAndNavigateTo(string path, int startLine, int startColumn, int?endLine = null, int?endColumn = null) { IVsUIShellOpenDocument openDoc = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } Guid logicalView = VSConstants.LOGVIEWID_Code; IVsWindowFrame frame; try { Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp; IVsUIHierarchy hier; uint itemid; openDoc.OpenDocumentViaProject(path, ref logicalView, out sp, out hier, out itemid, out frame); } catch (Exception) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; try { bufferProvider.GetTextBuffer(out lines); } catch (Exception) { return; } buffer = lines as VsTextBuffer; Debug.Assert(buffer != null, "IVsTextLines does not implement IVsTextBuffer"); } } IVsTextManager mgr = Package.GetGlobalService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return; } mgr.NavigateToLineAndColumn(buffer, ref logicalView, startLine - 1, startColumn - 1, (endLine ?? startLine) - 1, (endColumn ?? startColumn) - 1); }
IVsEditorAdaptersFactoryService editorFactoryService = null; // null is not really necessary, but to keep the compiler happy... void ApplyToProvider(Func <IntPtr> docGetter, Action <NodeProvider> action) { var docData = docGetter(); try { IVsTextLines textLines = Marshal.GetObjectForIUnknown(docData) as IVsTextLines; if (textLines == null) { IVsTextBufferProvider vsTextBufferProvider = Marshal.GetObjectForIUnknown(docData) as IVsTextBufferProvider; if (vsTextBufferProvider != null) { ErrorHandler.ThrowOnFailure(vsTextBufferProvider.GetTextBuffer(out textLines)); } } if (textLines != null) { var textBuffer = editorFactoryService.GetDocumentBuffer((IVsTextBuffer)textLines); NodeProvider provider; if (textBuffer.Properties.TryGetProperty <NodeProvider>(typeof(NodeProvider), out provider)) { action(provider); } } } finally { Marshal.Release(docData); } }
/// <summary> /// Open the file and jump to a line (and optional column) /// </summary> public static void OpenAndNavigateTo(string fileName, int line, int column = 0) { IVsUIShellOpenDocument uishellOpenDocument = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (uishellOpenDocument != null) { Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider; IVsWindowFrame frame; IVsUIHierarchy hierarchy; uint itemId; Guid logicalView = VSConstants.LOGVIEWID_Code; if (ErrorHandler.Succeeded(uishellOpenDocument.OpenDocumentViaProject(fileName, ref logicalView, out serviceProvider, out hierarchy, out itemId, out frame))) { object document; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out document); VsTextBuffer buffer = document as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = document as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; } } if (buffer != null) { IVsTextManager textManager = Package.GetGlobalService(typeof(VsTextManagerClass)) as IVsTextManager; textManager.NavigateToLineAndColumn(buffer, ref logicalView, line, column, line, column); } } } }
public static void OpenDocumentAndNavigateTo(string path, int line, int column) { IVsUIShellOpenDocument openDoc = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (ErrorHandler.Failed( openDoc.OpenDocumentViaProject(path, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; Debug.Assert(buffer != null, "IVsTextLines does not implement IVsTextBuffer"); if (buffer == null) { return; } } } // Finally, perform the navigation. IVsTextManager mgr = Package.GetGlobalService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return; } mgr.NavigateToLineAndColumn(buffer, ref logicalView, line, column, line, column); }
private void NavigateTo(object sender, EventArgs arguments) { Microsoft.VisualStudio.Shell.Task task = sender as Microsoft.VisualStudio.Shell.Task; if (task == null) throw new ArgumentException("sender"); // Get the doc data for the task's document if (String.IsNullOrEmpty(task.Document)) return; IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) return; IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) return; object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; Debug.Assert(buffer != null, "IVsTextLines does not implement IVsTextBuffer"); if (buffer == null) return; } } // Finally, perform the navigation. IVsTextManager mgr = serviceProvider.GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) return; mgr.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column); }
protected override object CreateDocView(System.IServiceProvider serviceProvider, IVsHierarchy hierarchy, uint itemid, string fileName, object docData, out Guid cmdUIGuid) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); // Instead of creating a WindowPane based object, we'll create an instance of the VS Code Editor, to serve // as our source editor view. ILocalRegistry localRegistry = serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry; Assumes.Present(localRegistry); cmdUIGuid = typeof(SourceEditorFactory).GUID; Guid guidCodeWindow = typeof(IVsCodeWindow).GUID; IntPtr pUnkPtr; IVsCodeWindow vsCodeWindow; int hr = localRegistry.CreateInstance(typeof(VsCodeWindowClass).GUID, null, ref guidCodeWindow, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out pUnkPtr); ErrorHandler.ThrowOnFailure(hr); try { vsCodeWindow = (IVsCodeWindow)Marshal.GetObjectForIUnknown(pUnkPtr); } finally { Marshal.Release(pUnkPtr); } IVsTextLines vsTextLines = docData as IVsTextLines; if (vsTextLines == null) { IVsTextBufferProvider provider = docData as IVsTextBufferProvider; if (provider != null) { ErrorHandler.ThrowOnFailure(provider.GetTextBuffer(out vsTextLines)); } } if (vsTextLines != null) { ErrorHandler.ThrowOnFailure(vsCodeWindow.SetBuffer(vsTextLines)); } return(vsCodeWindow); }
private IVsTextLines GetTextBuffer(IntPtr docDataExisting, string documentMoniker) { IVsTextLines textLines; if (docDataExisting == IntPtr.Zero) { //// Create a new IVsTextLines buffer textLines = this.CreateInstance <IVsTextLines, VsTextBufferClass>(); //textLines = new TextBuffer(); // set the buffer's site ((IObjectWithSite)textLines).SetSite(serviceProvider.GetService(typeof(IOleServiceProvider))); //// Fcuk COM //Guid GUID_VsBufferMoniker = typeof(IVsUserData).GUID; // Explicitly load the data through IVsPersistDocData ((IVsPersistDocData)textLines).LoadDocData(documentMoniker); } else { // Use the existing text buffer object dataObject = Marshal.GetObjectForIUnknown(docDataExisting); textLines = dataObject as IVsTextLines; if (textLines == null) { // Try get the text buffer from textbuffer provider IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider; if (textBufferProvider != null) { textBufferProvider.GetTextBuffer(out textLines); } } if (textLines == null) { // Unknown docData type then, so we have to force VS to close the other editor. ErrorHandler.ThrowOnFailure(VSConstants.VS_E_INCOMPATIBLEDOCDATA); } } return(textLines); }
public override void NavigateToFileAndPosition(string file, int line, int col, int lineEnd = 0, int columnEnd = 0) { IVsUIShellOpenDocument openDoc = AspectPackage.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { return; } } } IVsTextManager mgr = AspectPackage.GetGlobalService(typeof(VsTextManagerClass)) as IVsTextManager; if (lineEnd == 0) { lineEnd = line; columnEnd = col; } mgr.NavigateToLineAndColumn(buffer, ref logicalView, line - 1, col, lineEnd - 1, columnEnd); }
///------------------------------------------------------------------------------------------------------------- /// <summary> /// If the document is open, it returns the IVsTextLines. /// </summary> ///------------------------------------------------------------------------------------------------------------- public IVsTextLines GetRunningDocumentTextBuffer() { IVsTextLines buffer = null; IVsPersistDocData docData = GetRunningDocumentData(); if (docData != null) { buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider provider = docData as IVsTextBufferProvider; if (provider != null) { provider.GetTextBuffer(out buffer); } } } return buffer; }
private IVsTextLines GetTextBuffer(IntPtr docDataExisting, Guid languageServiceId) { IVsTextLines textLines = null; if (docDataExisting == IntPtr.Zero) { // Create a new IVsTextLines buffer. Type textLinesType = typeof(IVsTextLines); Guid clsid = typeof(VsTextBufferClass).GUID; textLines = CreateInstance <IVsTextLines>(ref clsid); // set the buffer's site ((IObjectWithSite)textLines).SetSite(VsServiceProvider); textLines.SetLanguageServiceID(ref languageServiceId); } else { // Use the existing text buffer object dataObject = Marshal.GetObjectForIUnknown(docDataExisting); textLines = dataObject as IVsTextLines; if (textLines == null) { // Try get the text buffer from textbuffer provider IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider; if (textBufferProvider != null) { textBufferProvider.GetTextBuffer(out textLines); } } } if (textLines == null) { // Unknown docData type then, so we have to force VS to close the other editor. ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA); } return(textLines); }
private IVsTextLines GetTextBuffer(IntPtr docDataExisting) { IVsTextLines textLines; if (docDataExisting == IntPtr.Zero) { // Create buffer if data doesn't exist Type textLinesType = typeof(IVsTextLines); Guid riid = textLinesType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; textLines = (IVsTextLines)m_EditorPackage.CreateInstance(ref clsid, ref riid, textLinesType); // Set the buffer's site ((IObjectWithSite)textLines).SetSite(m_VSServiceProvider.GetService(typeof(IOleServiceProvider))); } else { // Use the existing text buffer Object dataObject = Marshal.GetObjectForIUnknown(docDataExisting); textLines = dataObject as IVsTextLines; if (textLines == null) { // Try get the text buffer from textbuffer provider IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider; if (textBufferProvider != null) { textBufferProvider.GetTextBuffer(out textLines); } } if (textLines == null) { ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA); } } return(textLines); }
protected virtual IVsTextLines GetTextLines() { CCITracing.TraceCall(); FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager; Debug.Assert(manager != null, "Could not get the FileDocumentManager"); Guid logicalView = Guid.Empty; IVsWindowFrame windowFrame = null; object docData; VsTextBuffer lBuffer; IVsTextLines lLines; manager.Open(false, false, logicalView, out windowFrame, WindowFrameShowAction.DontShow); Debug.Assert(windowFrame != null, "Could not get the IVsWindowFrame"); windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer lBuffer = docData as VsTextBuffer; if (lBuffer == null) { IVsTextBufferProvider lBufferProvider = docData as IVsTextBufferProvider; if (lBufferProvider != null) { NativeMethods.ThrowOnFailure(lBufferProvider.GetTextBuffer(out lLines)); } else { throw new Exception("Could get TextLines object."); } } else { lLines = lBuffer as IVsTextLines; } return(lLines); }
/// <summary> /// Returns the buffer contents for a moniker. /// </summary> /// <returns>Buffer contents</returns> private string GetBufferContents(string fileName, out IVsTextStream srpStream) { Guid CLSID_VsTextBuffer = new Guid("{8E7B96A8-E33D-11d0-A6D5-00C04FB67F6A}"); string bufferContents = ""; srpStream = null; IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { IVsHierarchy hier; IVsPersistDocData persistDocData; uint itemid, cookie; bool docInRdt = true; IntPtr docData = IntPtr.Zero; int hr = NativeMethods.E_FAIL; try { //Getting a read lock on the document. Must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, fileName, out hier, out itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { Guid iid = VSConstants.IID_IUnknown; cookie = 0; docInRdt = false; ILocalRegistry localReg = this.projectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry; ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData)); } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } //Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if (srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if (ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if (srpStream != null) { // QI for IVsBatchUpdate and call FlushPendingUpdates if they support it IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate; if (srpBatchUpdate != null) { ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); } int lBufferSize = 0; hr = srpStream.GetSize(out lBufferSize); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // Note that GetStream returns Unicode to us so we don't need to do any conversions dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); //Get the contents bufferContents = Marshal.PtrToStringUni(dest); } finally { if (dest != IntPtr.Zero) { Marshal.FreeCoTaskMem(dest); } } } } } // Unlock the document in the RDT if necessary if (docInRdt && rdt != null) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie)); } if (ErrorHandler.Failed(hr)) { // If this failed then it's probably not a text file. In that case, // we just read the file as a binary bufferContents = File.ReadAllText(fileName); } } return(bufferContents); }
private void NavigateTo(object sender, EventArgs arguments) { try { Microsoft.VisualStudio.Shell.Task task = sender as Microsoft.VisualStudio.Shell.Task; if (task == null) { throw new ArgumentException("sender"); } // Get the doc data for the task's document if (String.IsNullOrEmpty(task.Document)) { return; } IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; Debug.Assert(buffer != null, "IVsTextLines does not implement IVsTextBuffer"); if (buffer == null) { return; } } } // Finally, perform the navigation. IVsTextManager mgr = serviceProvider.GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return; } // We should use the full span information if we've been given a DocumentTask bool isDocumentTask = task is DocumentTask; int endLine = isDocumentTask ? ((DocumentTask)task).Span.iEndLine : task.Line; int endColumn = isDocumentTask ? ((DocumentTask)task).Span.iEndIndex : task.Column; mgr.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, endLine, endColumn); } catch (Exception e) { System.Diagnostics.Debug.Assert(false, "Error thrown from NavigateTo. " + e.ToString()); } }
/// <summary> /// Add the error/warning to the error list and potentially to the output window. /// </summary> private void AddToErrorList( BuildEventArgs errorEvent, string subcategory, string errorCode, string file, int startLine, int startColumn, int endLine, int endColumn) { if (file == null) { file = String.Empty; } bool isWarning = errorEvent is BuildWarningEventArgs; TaskPriority priority = isWarning ? TaskPriority.Normal : TaskPriority.High; TextSpan span; span.iStartLine = startLine; span.iStartIndex = startColumn; span.iEndLine = endLine < startLine ? span.iStartLine : endLine; span.iEndIndex = (endColumn < startColumn) && (span.iStartLine == span.iEndLine) ? span.iStartIndex : endColumn; if (OutputWindowPane != null && (this.Verbosity != LoggerVerbosity.Quiet || errorEvent is BuildErrorEventArgs)) { // Format error and output it to the output window string message = this.FormatMessage(errorEvent.Message); DefaultCompilerError e = new DefaultCompilerError(file, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, errorCode, message); e.IsWarning = isWarning; Output(GetFormattedErrorMessage(e)); } UIThread.Run(delegate() { IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; IVsTextLines buffer = null; // JAF // Notes about acquiring the buffer: // If the file physically exists then this will open the document in the current project. It doesn't matter if the file is a member of the project. // Also, it doesn't matter if this is an F# file. For example, an error in Microsoft.Common.targets will cause a file to be opened here. // However, opening the document does not mean it will be shown in VS. if (!Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) && frame != null) { object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the text lines buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { bufferProvider.GetTextBuffer(out buffer); } } } // Need to adjust line and column indexing for the task window, which assumes zero-based values if (span.iStartLine > 0 && span.iStartIndex > 0) { span.iStartLine -= 1; span.iEndLine -= 1; span.iStartIndex -= 1; span.iEndIndex -= 1; } // Add new document task to task list DocumentTask task = new DocumentTask(serviceProvider, buffer, // May be null // This seems weird. Why would warning status make this a 'compile error'? // The “code sense” errors produce red squiggles, whereas the “compile” errors produce blue squiggles. (This is in line with C#’s pre-VS2008-SP1 behavior.) Swapping these two gives us a look consistent with that of the language service. isWarning ? MARKERTYPE.MARKER_COMPILE_ERROR : MARKERTYPE.MARKER_CODESENSE_ERROR, span, file, subcategory); // Add error to task list task.Text = Microsoft.FSharp.Compiler.ErrorLogger.NewlineifyErrorString(errorEvent.Message); task.Priority = priority; task.ErrorCategory = isWarning ? TaskErrorCategory.Warning : TaskErrorCategory.Error; task.Category = TaskCategory.BuildCompile; task.HierarchyItem = hierarchy; task.Navigate += new EventHandler(NavigateTo); if (null != this.TaskReporter) { this.taskReporter.AddTask(task); } else { this.taskProvider.Tasks.Add(task); } }); }
private void GetCurrentSource() { try { IVsMonitorSelection selection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection)); object pvar = null; if (!ErrorHandler.Succeeded(selection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out pvar))) { this.currentDocument = null; return; } IVsWindowFrame frame = pvar as IVsWindowFrame; if (frame == null) { this.currentDocument = null; return; } object docData = null; if (!ErrorHandler.Succeeded(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData))) { this.currentDocument = null; return; } object docViewServiceObject; if (!ErrorHandler.Succeeded(frame.GetProperty((int)Microsoft.VisualStudio.Shell.Interop.__VSFPROPID.VSFPROPID_SPFrame, out docViewServiceObject))) { this.currentDocument = null; return; } IVsTextLines buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider tb = docData as IVsTextBufferProvider; if (tb != null) { tb.GetTextBuffer(out buffer); } } if (buffer == null) { this.currentDocument = null; return; } IOleServiceProvider docViewService = (IOleServiceProvider)docViewServiceObject; if (this.currentDocument == null || buffer != this.currentDocument.TextEditorBuffer) { this.currentDocument = new VisualStudioDocument(frame, buffer, docViewService); this.changeCount = this.currentDocument.Source.ChangeCount; } else { if (this.changeCount != this.currentDocument.Source.ChangeCount) { this.currentDocument.Reload(); this.changeCount = this.currentDocument.Source.ChangeCount; } } return; } catch (Exception e) { ReportError(e); } }
/// <include file='doc\EditorFactory.uex' path='docs/doc[@for="EditorFactory.CreateEditorInstance"]/*' /> /// <summary> /// This method checks to see if the specified file is one that your editor supports /// and if so, creates the core text editor and associated your language service /// with it. To figure out if the file is one that your editor supports it performs /// the following check: /// <list> /// <item> /// Call IsRegisteredExtension to see if the file extension is explicitly /// registered to your editor. /// </item> /// <item> /// Call GetUserDefinedEditor to see if the user has explicitly mapped the /// extension to your editor. /// </item> /// <item> /// If your editor registered the "*" extension, then it also calls /// IsFileExtensionWeShouldEditAnyway and IsOurFileFormat to let you sniff /// the file and see if you think it contains stuff that your editor recognizes /// </item> /// </list> /// If all this is true then it goes ahead with the next step which is to /// get an IVsTextLines buffer and set it up as follows: /// <list> /// <item> /// If existingDocData is non-null then it checks to see if it can get an /// IVsTextLines buffer from this docData, and if not, returns VS_E_INCOMPATIBLEDOCDATA. /// Otherwise it creates a new VsTextBufferClass. /// </item> /// Calls IVsUserData.SetData on the IVsTextLines buffer with any code page prompt /// flags you have provided via the CodePagePrompt property. /// </list> /// <list> /// Calls SetLanguageServiceID to pass in your language service Guid and /// sets the GuidVSBufferDetectLangSid IVsUserData to false to stop the core /// text editor from looking up a different language service. /// </list> /// Lastly it calls CreateEditorView to create the docView. /// </summary> public virtual int CreateEditorInstance(uint createDocFlags, string moniker, string physicalView, IVsHierarchy pHier, uint itemid, IntPtr existingDocData, out IntPtr docView, out IntPtr docData, out string editorCaption, out Guid cmdUI, out int cancelled) { docView = IntPtr.Zero; docData = IntPtr.Zero; editorCaption = null; cmdUI = Guid.Empty; cancelled = 0; int hr = VSErr.S_OK; if (this.promptFlags == __PROMPTONLOADFLAGS.codepagePrompt && existingDocData != IntPtr.Zero) { //since we are trying to open with encoding just return hr = (int)VSConstants.VS_E_INCOMPATIBLEDOCDATA; goto cleanup; } bool takeover = false; if (!string.IsNullOrEmpty(moniker)) { string ext = Path.GetExtension(moniker); docData = IntPtr.Zero; docView = IntPtr.Zero; editorCaption = null; bool openSpecific = (createDocFlags & (uint)__VSCREATEEDITORFLAGS2.CEF_OPENSPECIFIC) != 0; bool isOurs = IsRegisteredExtension(ext); bool isUserDefined = (GetUserDefinedEditor(ext) == this.GetType().GUID); // If this file extension belongs to a different language service, then we should not open it, // unless the user specifically requested our editor in the Open With... dialog. if (!isOurs && !isUserDefined && !this.IsFileExtensionWeShouldEditAnyway(ext) && !openSpecific) { return(VSConstants.VS_E_UNSUPPORTEDFORMAT); } takeover = (CheckAllFileTypes() && !isOurs); if (takeover && !isOurs && !isUserDefined && !openSpecific) { if (!IsOurFileFormat(moniker)) { return(VSConstants.VS_E_UNSUPPORTEDFORMAT); } } } IVsTextLines buffer = null; if (existingDocData != IntPtr.Zero) { object dataObject = Marshal.GetObjectForIUnknown(existingDocData); buffer = dataObject as IVsTextLines; if (buffer == null) { IVsTextBufferProvider bp = dataObject as IVsTextBufferProvider; if (bp != null) { Marshal.ThrowExceptionForHR(bp.GetTextBuffer(out buffer)); } } if (buffer == null) { // unknown docData type then, so we have to force VS to close the other editor. hr = VSConstants.VS_E_INCOMPATIBLEDOCDATA; goto cleanup; } } else { // Create a new IVsTextLines buffer. Type textLinesType = typeof(IVsTextLines); Guid riid = textLinesType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; buffer = (IVsTextLines)package.CreateInstance(ref clsid, ref riid, textLinesType); if (!string.IsNullOrEmpty(moniker)) { IVsUserData iud = buffer as IVsUserData; if (iud != null) { Guid GUID_VsBufferMoniker = typeof(IVsUserData).GUID; // Must be set in time for language service GetColorizer call in case the colorizer // is file name dependent. Marshal.ThrowExceptionForHR(iud.SetData(ref GUID_VsBufferMoniker, moniker)); } } IObjectWithSite ows = buffer as IObjectWithSite; if (ows != null) { ows.SetSite(this.site.GetService(typeof(IOleServiceProvider))); } } if (this.promptFlags == __PROMPTONLOADFLAGS.codepagePrompt && buffer is IVsUserData) { IVsUserData iud = (IVsUserData)buffer; Guid GUID_VsBufferEncodingPromptOnLoad = new Guid(0x99ec03f0, 0xc843, 0x4c09, 0xbe, 0x74, 0xcd, 0xca, 0x51, 0x58, 0xd3, 0x6c); Marshal.ThrowExceptionForHR(iud.SetData(ref GUID_VsBufferEncodingPromptOnLoad, (uint)this.CodePagePrompt)); } Guid langSid = GetLanguageServiceGuid(); if (langSid != Guid.Empty) { Guid vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}"); Guid currentSid; Marshal.ThrowExceptionForHR(buffer.GetLanguageServiceID(out currentSid)); // If the language service is set to the default SID, then // set it to our language if (currentSid == vsCoreSid) { Marshal.ThrowExceptionForHR(buffer.SetLanguageServiceID(ref langSid)); } else if (currentSid != langSid) { // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA hr = VSConstants.VS_E_INCOMPATIBLEDOCDATA; goto cleanup; } takeover = true; } if (takeover) { IVsUserData vud = (IVsUserData)buffer; Guid bufferDetectLang = GuidVSBufferDetectLangSid; Marshal.ThrowExceptionForHR(vud.SetData(ref bufferDetectLang, false)); } if (existingDocData != IntPtr.Zero) { docData = existingDocData; Marshal.AddRef(docData); } else { docData = Marshal.GetIUnknownForObject(buffer); } docView = CreateEditorView(moniker, buffer, physicalView, out editorCaption, out cmdUI); if (docView == IntPtr.Zero) { // We couldn't create the view, so return this special error code so // VS can try another editor factory. hr = VSConstants.VS_E_UNSUPPORTEDFORMAT; } cleanup: if (docView == IntPtr.Zero) { if (existingDocData != docData && docData != IntPtr.Zero) { Marshal.Release(docData); docData = IntPtr.Zero; } } return(hr); }
void NavigateHandler(object sender, EventArgs arguments) { var task = sender as ErrorTask; if (task == null || task.Document == null) { return; } // This would have been the simple way of doing things: // _errorProvider.Navigate(error, new Guid(EnvDTE.Constants.vsViewKindCode)); // Unfortunately, it doesn't work--it seems to ignore the column position. (Moreover, it wants 1-based // line/column numbers, whereas the Error Task pane wants 0-based line/column numbers.) // So, instead we do all the things that follow: var openDoc = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) { return; } object docData; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData)); // Get the VsTextBuffer VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { return; } } } VsTextManager textManager = Package.GetGlobalService(typeof(VsTextManagerClass)) as VsTextManager; if (textManager == null) { return; } // Finally, move the cursor Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(textManager.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column)); }
protected void QueueTaskEvent(BuildEventArgs errorEvent) { // This enqueues a function that will later be run on the main (UI) thread this.taskQueue.Enqueue(() => { TextSpan span; string file; MARKERTYPE marker; TaskErrorCategory category; if (errorEvent is BuildErrorEventArgs) { BuildErrorEventArgs errorArgs = (BuildErrorEventArgs)errorEvent; span = new TextSpan(); // spans require zero-based indices span.iStartLine = errorArgs.LineNumber - 1; span.iEndLine = errorArgs.EndLineNumber - 1; span.iStartIndex = errorArgs.ColumnNumber - 1; span.iEndIndex = errorArgs.EndColumnNumber - 1; file = Path.Combine(Path.GetDirectoryName(errorArgs.ProjectFile), errorArgs.File); marker = MARKERTYPE.MARKER_CODESENSE_ERROR; // red squiggles category = TaskErrorCategory.Error; } else if (errorEvent is BuildWarningEventArgs) { BuildWarningEventArgs warningArgs = (BuildWarningEventArgs)errorEvent; span = new TextSpan(); // spans require zero-based indices span.iStartLine = warningArgs.LineNumber - 1; span.iEndLine = warningArgs.EndLineNumber - 1; span.iStartIndex = warningArgs.ColumnNumber - 1; span.iEndIndex = warningArgs.EndColumnNumber - 1; file = Path.Combine(Path.GetDirectoryName(warningArgs.ProjectFile), warningArgs.File); marker = MARKERTYPE.MARKER_COMPILE_ERROR; // red squiggles category = TaskErrorCategory.Warning; } else { throw new NotImplementedException(); } if (span.iEndLine == -1) { span.iEndLine = span.iStartLine; } if (span.iEndIndex == -1) { span.iEndIndex = span.iStartIndex; } IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { throw new NotImplementedException(); // TODO } IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; IVsTextLines buffer = null; // Notes about acquiring the buffer: // If the file physically exists then this will open the document in the current project. It doesn't matter if the file is a member of the project. // Also, it doesn't matter if this is a Rust file. For example, an error in Microsoft.Common.targets will cause a file to be opened here. // However, opening the document does not mean it will be shown in VS. if (!Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) && frame != null) { object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the text lines buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { bufferProvider.GetTextBuffer(out buffer); } } } DocumentTask task = new DocumentTask(serviceProvider, buffer, marker, span, file); task.ErrorCategory = category; task.Document = file; task.Line = span.iStartLine; task.Column = span.iStartIndex; task.Priority = category == TaskErrorCategory.Error ? TaskPriority.High : TaskPriority.Normal; task.Text = errorEvent.Message; task.Category = TaskCategory.BuildCompile; task.HierarchyItem = hierarchy; return(task); }); // NOTE: Unlike output we dont want to interactively report the tasks. So we never queue // call ReportQueuedTasks here. We do this when the build finishes. }
public static bool Navigate(this IServiceProvider serviceProvider, string path, int line, int column) { Guid logicalView = VSConstants.LOGVIEWID_TextView; if (VsShellUtilities.ShellIsShuttingDown) { return(false); } var vsUIShellOpenDocument = (IVsUIShellOpenDocument)serviceProvider.GetService(typeof(IVsUIShellOpenDocument)); if (vsUIShellOpenDocument == null) { return(false); } Guid guid = logicalView; Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProviderRet; IVsUIHierarchy vsUIHierarchy; uint pItemId; IVsWindowFrame vsWindowFrame; if (ErrorHelper.Failed(vsUIShellOpenDocument.OpenDocumentViaProject(path, ref guid, out serviceProviderRet, out vsUIHierarchy, out pItemId, out vsWindowFrame)) || vsWindowFrame == null) { return(false); } object obj; vsWindowFrame.GetProperty(-4004, out obj); var vsTextBuffer = obj as VsTextBuffer; if (vsTextBuffer == null) { IVsTextBufferProvider vsTextBufferProvider = obj as IVsTextBufferProvider; if (vsTextBufferProvider != null) { IVsTextLines vsTextLines; ErrorHelper.ThrowOnFailure(vsTextBufferProvider.GetTextBuffer(out vsTextLines)); vsTextBuffer = vsTextLines as VsTextBuffer; if (vsTextBuffer == null) { return(false); } } } var vsTextManager = (IVsTextManager)serviceProvider.GetService(typeof(VsTextManagerClass)); if (vsTextManager == null) { return(false); } if (column > 0) { column--; } if (line > 0) { line--; } return(ErrorHelper.Succeeded(vsTextManager.NavigateToLineAndColumn(vsTextBuffer, ref logicalView, line, column, line, column))); }
private ITextBuffer GetTextBufferOnUIThread(bool create) { IVsTextManager textMgr = (IVsTextManager)GetService(typeof(SVsTextManager)); var model = GetService(typeof(SComponentModel)) as IComponentModel; var adapter = model.GetService <IVsEditorAdaptersFactoryService>(); uint itemid; IVsRunningDocumentTable rdt = ProjectMgr.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { IVsHierarchy hier; IVsPersistDocData persistDocData; uint cookie; bool docInRdt = true; IntPtr docData = IntPtr.Zero; int hr = NativeMethods.E_FAIL; try { //Getting a read lock on the document. Must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, GetMkDocument(), out hier, out itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { if (!create) { return(null); } Guid iid = VSConstants.IID_IUnknown; cookie = 0; docInRdt = false; ILocalRegistry localReg = this.ProjectMgr.GetService(typeof(SLocalRegistry)) as ILocalRegistry; ErrorHandler.ThrowOnFailure(localReg.CreateInstance(CLSID_VsTextBuffer, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out docData)); } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } //Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if (srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } // Unlock the document in the RDT if necessary if (docInRdt && rdt != null) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)(_VSRDTFLAGS.RDT_ReadLock | _VSRDTFLAGS.RDT_Unlock_NoSave), cookie)); } if (srpTextLines != null) { return(adapter.GetDocumentBuffer(srpTextLines)); } } IWpfTextView view = GetTextView(); return(view.TextBuffer); }
public static void errorTaskNavigateHandler(object sender, EventArgs arguments) { Microsoft.VisualStudio.Shell.Task task = sender as Microsoft.VisualStudio.Shell.Task; if (task == null) { throw new ArgumentException("sender parm cannot be null"); } if (String.IsNullOrEmpty(task.Document)) { Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: task.Document is empty"); return; } IVsUIShellOpenDocument openDoc = Package.GetGlobalService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: openDoc is null"); return; } IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider; IVsUIHierarchy hierarchy; uint itemId; Guid logicalView = VSConstants.LOGVIEWID_Code; int hr = openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out serviceProvider, out hierarchy, out itemId, out frame); if (ErrorHandler.Failed(hr) || (frame == null)) { Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: OpenDocumentViaProject failed"); return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: buffer is null"); return; } } } IVsTextManager mgr = Package.GetGlobalService(typeof(SVsTextManager)) as IVsTextManager; if (mgr == null) { Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: IVsTextManager is null"); return; } //Output("INFO: AsmDudeToolsStatic:errorTaskNavigateHandler: navigating to row="+task.Line); int iStartIndex = task.Column & 0xFFFF; int iEndIndex = (task.Column >> 16) & 0xFFFF; mgr.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, iStartIndex, task.Line, iEndIndex); }
/// <include file='doc\TaskProvider.uex' path='docs/doc[@for="Navigate"]/*' /> /// <devdoc> /// Navigates the document in the given task to the given logical view. /// </devdoc> public bool Navigate(Task task, Guid logicalView) { if (task == null) { throw new ArgumentNullException("task"); } // Get the doc data for the task's document if (task.Document == null || task.Document.Length == 0) { return(false); } IVsUIShellOpenDocument openDoc = GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return(false); } IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logView = logicalView; if (NativeMethods.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logView, out sp, out hier, out itemid, out frame)) || frame == null) { return(false); } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; NativeMethods.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; Debug.Assert(buffer != null, "IVsTextLines does not implement IVsTextBuffer"); if (buffer == null) { return(false); } } } // Finally, perform the navigation. IVsTextManager mgr = GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return(false); } int line = task.Line; // Buffer is zero based if (line > 0) { line--; } mgr.NavigateToLineAndColumn(buffer, ref logicalView, line, 0, line, 0); return(true); }
private void NavigateHandler(object sender, EventArgs arguments) { Microsoft.VisualStudio.Shell.Task task = sender as Microsoft.VisualStudio.Shell.Task; if (task == null) { throw new ArgumentException("sender parm cannot be null"); } if (String.IsNullOrEmpty(task.Document)) { return; } IVsUIShellOpenDocument openDoc = GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider; IVsUIHierarchy hierarchy; uint itemId; Guid logicalView = VSConstants.LOGVIEWID_Code; if (ErrorHandler.Failed(openDoc.OpenDocumentViaProject( task.Document, ref logicalView, out serviceProvider, out hierarchy, out itemId, out frame)) || frame == null) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { return; } } } IVsTextManager mgr = GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return; } mgr.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column); }
// // Plumbing - an event handler for when a Task is double-clicked, i.e. // to navigate to the code causing a parser error. // internal async void NavigationHandler(object sender, EventArgs args) { var task = sender as Microsoft.VisualStudio.Shell.Task; if (string.IsNullOrEmpty(task.Document)) { return; } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var serviceProvider = new ParseSession.ErrorListHelper(); var openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; if (ErrorHandler.Failed(openDoc.OpenDocumentViaProject(task.Document, ref logicalView, out sp, out hier, out itemid, out frame)) || frame == null) { return; } object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ErrorHandler.ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { return; } } } IVsTextManager mgr = serviceProvider.GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (mgr == null) { return; } // This whole mess could arguably be a lot simpler as a call to ErrorProvider.Navigate(). // Unfortunately that API assumes 1-based column/line indices, whereas our task (in order // to display correctly in the task list) assumes 0-based. This can be worked around with // a trivial addition/substraction, but the kicker is that the column is not used by that // particular API. Therefore to preserve the column we do all this crazy stuff instead. mgr.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column); }
private void NavigateToHandler(object sender, System.EventArgs args) { Microsoft.VisualStudio.Shell.Task task = sender as Microsoft.VisualStudio.Shell.Task; if (task == null) { throw new System.ArgumentException("sender"); } // Open the document. if (string.IsNullOrEmpty(task.Document)) { return; } IVsUIShellOpenDocument openDocument = m_serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDocument == null) { return; } IVsWindowFrame frame; IOleServiceProvider serviceProvider; IVsUIHierarchy hierarchy; uint itemId; System.Guid logicalView = VSConstants.LOGVIEWID_Code; if (Failed(openDocument.OpenDocumentViaProject(task.Document, ref logicalView, out serviceProvider, out hierarchy, out itemId, out frame)) || frame == null) { return; } // Get the text buffer. object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); VsTextBuffer buffer = docData as VsTextBuffer; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { IVsTextLines lines; ThrowOnFailure(bufferProvider.GetTextBuffer(out lines)); buffer = lines as VsTextBuffer; if (buffer == null) { return; } } } // Perform the navigation. IVsTextManager manager = m_serviceProvider.GetService(typeof(VsTextManagerClass)) as IVsTextManager; if (manager == null) { return; } manager.NavigateToLineAndColumn(buffer, ref logicalView, task.Line, task.Column, task.Line, task.Column); }
/// <summary> /// Add the error/warning to the error list and potentially to the output window. /// </summary> private void AddToErrorList( BuildEventArgs errorEvent, string subcategory, string errorCode, string file, int startLine, int startColumn, int endLine, int endColumn) { if (file == null) { file = String.Empty; } bool isWarning = errorEvent is BuildWarningEventArgs; Shell.TaskPriority priority = isWarning ? Shell.TaskPriority.Normal : Shell.TaskPriority.High; TextSpan span; span.iStartLine = startLine; span.iStartIndex = startColumn; span.iEndLine = endLine < startLine ? span.iStartLine : endLine; span.iEndIndex = (endColumn < startColumn) && (span.iStartLine == span.iEndLine) ? span.iStartIndex : endColumn; if (OutputWindowPane != null && (this.Verbosity != LoggerVerbosity.Quiet || errorEvent is BuildErrorEventArgs)) { // Format error and output it to the output window string message = this.FormatMessage(errorEvent.Message); DefaultCompilerError e = new DefaultCompilerError(file, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, errorCode, message); e.IsWarning = isWarning; Output(GetFormattedErrorMessage(e)); } UIThread.Run(delegate() { IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) { return; } IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; IVsTextLines buffer = null; // JAF // Notes about acquiring the buffer: // If the file physically exists then this will open the document in the current project. It doesn't matter if the file is a member of the project. // Also, it doesn't matter if this is an F# file. For example, an error in Microsoft.Common.targets will cause a file to be opened here. // However, opening the document does not mean it will be shown in VS. if (!Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) && frame != null) { object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the text lines buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { bufferProvider.GetTextBuffer(out buffer); } } } // Need to adjust line and column indexing for the task window, which assumes zero-based values if (span.iStartLine > 0 && span.iStartIndex > 0) { span.iStartLine -= 1; span.iEndLine -= 1; span.iStartIndex -= 1; span.iEndIndex -= 1; } // Add error to task list var taskText = global::FSharp.Compiler.ErrorLogger.NewlineifyErrorString(errorEvent.Message); if (errorReporter != null) { errorReporter.ReportError2(taskText, errorCode, (VSTASKPRIORITY)priority, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, file); } }); }
/// <summary> /// This is used to get the content of a specific topic file if it is open in an editor so that the /// current content is displayed for it in the topic previewer control. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void ucTopicPreviewer_TopicContentNeeded(object sender, TopicContentNeededEventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); IVsHierarchy hier; IVsPersistDocData persistDocData; IVsTextStream srpStream; IntPtr docData = IntPtr.Zero; uint itemid, cookie = 0; int hr = VSConstants.E_FAIL; IVsRunningDocumentTable rdt = Utility.GetServiceFromPackage <IVsRunningDocumentTable, SVsRunningDocumentTable>(true); if (rdt == null) { return; } try { // Getting a read lock on the document. This must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, e.TopicFilename, out hier, out itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { return; } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; // Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first IVsTextBufferProvider srpTextBufferProvider = persistDocData as IVsTextBufferProvider; if (srpTextBufferProvider != null) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if (ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if (srpStream != null) { IVsBatchUpdate srpBatchUpdate = srpStream as IVsBatchUpdate; if (srpBatchUpdate != null) { ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); } int lBufferSize = 0; hr = srpStream.GetSize(out lBufferSize); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // GetStream() returns Unicode data so we need to double the buffer size dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); // Get the contents e.TopicContent = Marshal.PtrToStringUni(dest); } finally { if (dest != IntPtr.Zero) { Marshal.FreeCoTaskMem(dest); } } } } } } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } if (cookie != 0) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, cookie)); } } }