public void OpenFile(string projectName, string relativeFilePath) { var filePath = GetAbsolutePathForProjectRelativeFilePath(projectName, relativeFilePath); VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, filePath, VSConstants.LOGVIEWID.Code_guid, out _, out _, out _, out var view); // Reliably set focus using NavigateToLineAndColumn var textManager = GetGlobalService <SVsTextManager, IVsTextManager>(); ErrorHandler.ThrowOnFailure(view.GetBuffer(out var textLines)); ErrorHandler.ThrowOnFailure(view.GetCaretPos(out var line, out var column)); ErrorHandler.ThrowOnFailure(textManager.NavigateToLineAndColumn(textLines, VSConstants.LOGVIEWID.Code_guid, line, column, line, column)); }
/// <summary> /// Open up a new document window with the specified file /// </summary> public override bool LoadFileIntoNewWindow(string filePath) { try { VsShellUtilities.OpenDocument(_vsAdapter.ServiceProvider, filePath); return(true); } catch (Exception e) { _vim.ActiveStatusUtil.OnError(e.Message); return(false); } }
void Task_Navigate(object sender, EventArgs e) { Task task = sender as Task; VsShellUtilities.OpenDocument(SourceFileCompiler.Instance.ServiceProvider, task.Document); SourceFileData data = SourceFileCompiler.Instance.FindSourceFileData(task.Document); if (data != null && data.TextView != null) { SnapshotSpan span = data.TextView.TextSnapshot.CreateSpan(task.Line, task.Column, task.Column + 1); data.TextView.Caret.MoveTo(span.Start, PositionAffinity.Successor); data.TextView.ViewScroller.EnsureSpanVisible(span, EnsureSpanVisibleOptions.ShowStart); } }
public async override Task ApplyTextEditsAsync( Uri uri, ITextSnapshot snapshot, IEnumerable <TextEdit> textEdits) { if (uri is null) { throw new ArgumentNullException(nameof(uri)); } if (snapshot is null) { throw new ArgumentNullException(nameof(snapshot)); } if (textEdits is null) { throw new ArgumentNullException(nameof(textEdits)); } await _joinableTaskFactory.SwitchToMainThreadAsync(); var undoManager = _undoManagerProvider.GetTextBufferUndoManager(snapshot.TextBuffer); var undoHistory = undoManager.TextBufferUndoHistory; using var transaction = undoHistory.CreateTransaction("Apply Razor LSP text edits"); try { ApplyTextEdits(textEdits, snapshot, snapshot.TextBuffer); var cursorPosition = ExtractCursorPlaceholder(snapshot.TextBuffer.CurrentSnapshot, textEdits); if (cursorPosition != null) { var fullPath = GetLocalFilePath(uri); VsShellUtilities.OpenDocument(_serviceProvider, fullPath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out var windowFrame); if (windowFrame != null) { var textView = GetActiveVsTextView(windowFrame); MoveCaretToPosition(textView, cursorPosition); } } } finally { transaction.Complete(); } }
private void OpenGeneratedCode(string filePath, string extension, string generatedCode) { var tempFileName = GetTempFileName(filePath, extension); // Ignore any I/O errors try { File.WriteAllText(tempFileName, generatedCode); VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, tempFileName); } catch { } }
internal static IVsWindowFrame OpenDocumentInNewWindow(string filePath, IServiceProvider provider, int lineid = -1, int columnid = -1, int length = -1) { if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { return(null); } IVsUIHierarchy hierarchy; uint itemId; IVsWindowFrame frame = null; if (!VsShellUtilities.IsDocumentOpen(provider, filePath, VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame)) { VsShellUtilities.OpenDocument(provider, filePath, VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame); } if (frame != null && frame.Show() == VSConstants.S_OK && lineid != -1) { var vsTextView = VsShellUtilities.GetTextView(frame); var componentModel = (IComponentModel)ProjectPackage.GetGlobalService(typeof(SComponentModel)); var editorAdapterFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>(); var wpfTextView = editorAdapterFactoryService.GetWpfTextView(vsTextView); var p = wpfTextView.TextSnapshot.GetLineFromLineNumber(lineid).Start; if (columnid > -1) { p += columnid; } wpfTextView.Caret.MoveTo(p); SnapshotSpan span; if (length > 0) { span = new SnapshotSpan(p, length); } else if (columnid != -1) { var linespan = wpfTextView.TextSnapshot.GetLineFromLineNumber(lineid).End; span = new SnapshotSpan(p, linespan); } else { span = wpfTextView.TextSnapshot.GetLineFromLineNumber(lineid).Extent; } wpfTextView.Selection.Select(span, false); wpfTextView.Caret.EnsureVisible(); //System.Windows.Forms.SendKeys.Send("{RIGHT}"); } return(frame); }
internal static IVsTextView OpenStupidFile(IServiceProvider isp, string full_file_name) { ThreadHelper.ThrowIfNotOnUIThread(); if (isp == null) { return(null); } ServiceProvider sp = new ServiceProvider(isp); if (!VsShellUtilities.IsDocumentOpen(sp, full_file_name, Guid.Empty, out _, out _, out _)) { VsShellUtilities.OpenDocument(sp, full_file_name); } return(FindTextViewFor(full_file_name)); }
private IWpfTextView OpenLastEdittedFile(string lastEditFilePath) { try { VsShellUtilities.OpenDocument(this.ServiceProvider, lastEditFilePath, VSConstants.LOGVIEWID_TextView, out IVsUIHierarchy hierarchy, out uint itemId, out IVsWindowFrame windowFrame, out IVsTextView vsTextView); return(GetEditorAdaptorsFactoryService().GetWpfTextView(vsTextView)); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception occurred trying to navigate set open file last editted.", e); return(null); } }
public async Task OpenFileAsync(string projectName, string relativeFilePath, CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var filePath = await GetAbsolutePathForProjectRelativeFilePathAsync(projectName, relativeFilePath, cancellationToken); VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, filePath, VSConstants.LOGVIEWID.Code_guid, out _, out _, out _, out var view); // Reliably set focus using NavigateToLineAndColumn var textManager = await GetRequiredGlobalServiceAsync <SVsTextManager, IVsTextManager>(cancellationToken); ErrorHandler.ThrowOnFailure(view.GetBuffer(out var textLines)); ErrorHandler.ThrowOnFailure(view.GetCaretPos(out var line, out var column)); ErrorHandler.ThrowOnFailure(textManager.NavigateToLineAndColumn(textLines, VSConstants.LOGVIEWID.Code_guid, line, column, line, column)); }
IVsTextView OpenDocument(string fullPath, bool readOnly, out IWpfTextView wpfTextView) { var logicalView = VSConstants.LOGVIEWID.TextView_guid; IVsUIHierarchy hierarchy; uint itemID; IVsWindowFrame windowFrame; IVsTextView view; VsShellUtilities.OpenDocument(serviceProvider, fullPath, logicalView, out hierarchy, out itemID, out windowFrame, out view); wpfTextView = vsEditorAdaptersFactory.GetWpfTextView(view); wpfTextView?.Options?.SetOptionValue(DefaultTextViewOptions.ViewProhibitUserInputId, readOnly); return(view); }
public static void ViewFile(string fileName, string caption) { IVsUIHierarchy hier; UInt32 itemid; IVsWindowFrame frame; IVsTextView view; VsShellUtilities.OpenDocument(RPackage.Current, fileName.FromRPath(), VSConstants.LOGVIEWID.Code_guid, out hier, out itemid, out frame, out view); IVsTextLines textBuffer = null; frame?.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption); view?.GetBuffer(out textBuffer); textBuffer?.SetStateFlags((uint)BUFFERSTATEFLAGS.BSF_USER_READONLY); }
// ------------------------------------------------------------------------ // open selected files in the editor // ------------------------------------------------------------------------ void OpenSelectedFiles() { foreach (int index in _pendingItemsListView.SelectedIndices) { HGLib.HGFileStatusInfo info = _pendingItemsListView._list[index]; try { VsShellUtilities.OpenDocument(SccProvider.Provider, info.fullPath); } catch (Exception e) { MessageBox.Show(e.Message, "Open File failed"); } } }
// From https://github.com/rsdn/nemerle/blob/master/snippets/VS2010/Nemerle.VisualStudio/LanguageService/NemerleLanguageService.cs#L565 private void GoToLocation(string filename, HlslTools.Text.TextSpan textSpan, string caption, bool asReadonly) { uint itemID; IVsUIHierarchy hierarchy; IVsWindowFrame docFrame; IVsTextView textView; VsShellUtilities.OpenDocument(_serviceProvider, filename, VSConstants.LOGVIEWID_Code, out hierarchy, out itemID, out docFrame, out textView); if (asReadonly) { IVsTextLines buffer; ErrorHandler.ThrowOnFailure(textView.GetBuffer(out buffer)); IVsTextStream stream = (IVsTextStream)buffer; stream.SetStateFlags((uint)BUFFERSTATEFLAGS.BSF_USER_READONLY); } if (caption != null) { ErrorHandler.ThrowOnFailure(docFrame.SetProperty((int)__VSFPROPID.VSFPROPID_OwnerCaption, caption)); } ErrorHandler.ThrowOnFailure(docFrame.Show()); if (textView != null) { var wpfTextView = docFrame.GetWpfTextView(); var line = wpfTextView.TextBuffer.CurrentSnapshot.GetLineFromPosition(textSpan.Start); var span = new TextSpan { iStartLine = line.LineNumber, iStartIndex = textSpan.Start - line.Start.Position, iEndLine = line.LineNumber, iEndIndex = textSpan.Start - line.Start.Position }; try { ErrorHandler.ThrowOnFailure(textView.SetCaretPos(span.iStartLine, span.iStartIndex)); ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(span)); } catch (Exception ex) { Trace.WriteLine(ex.Message); } } }
internal static IVsTextView OpenStupidFile(string full_file_name) { var dte2 = (EnvDTE80.DTE2)Package.GetGlobalService(typeof(SDTE)); IServiceProvider isp = (IServiceProvider)dte2; ServiceProvider sp = new ServiceProvider(isp); IVsUIHierarchy ivsuih; uint item_id; IVsWindowFrame ivswf; if (!VsShellUtilities.IsDocumentOpen(sp, full_file_name, Guid.Empty, out ivsuih, out item_id, out ivswf)) { VsShellUtilities.OpenDocument(sp, full_file_name); } return(FindTextViewFor(full_file_name)); }
internal static void OpenDocument(IServiceProvider serviceProvider, string filename, out IVsTextView viewAdapter, out IVsWindowFrame pWindowFrame) { IVsTextManager textMgr = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager)); IVsUIHierarchy hierarchy; uint itemid; VsShellUtilities.OpenDocument( serviceProvider, filename, Guid.Empty, out hierarchy, out itemid, out pWindowFrame, out viewAdapter); }
/// <summary> /// In a perfect world this would replace the contents of the existing ITextView /// with those of the specified file. Unfortunately this causes problems in /// Visual Studio when the file is of a different content type. Instead we /// mimic the behavior by opening the document in a new window and closing the /// existing one /// </summary> public override HostResult LoadFileIntoExistingWindow(string filePath, ITextView textView) { try { // Open the document before closing the other. That way any error which occurs // during an open will cause the method to abandon and produce a user error // message VsShellUtilities.OpenDocument(_vsAdapter.ServiceProvider, filePath); _textManager.CloseView(textView); return(HostResult.Success); } catch (Exception e) { return(HostResult.NewError(e.Message)); } }
private void Task_Navigate(object sender, EventArgs e) { if ((sender is ErrorTask task) && (!string.IsNullOrEmpty(task.Document) && File.Exists(task.Document))) { VsShellUtilities.OpenDocument(package, task.Document, Guid.Empty, out IVsUIHierarchy hierarchy, out _, out IVsWindowFrame frame); if (frame != null) { task.HierarchyItem = hierarchy; errorListProvider.Refresh(); IVsTextView textView = VsShellUtilities.GetTextView(frame); if (textView != null) { textView.SetSelection(task.Line, task.Column, task.Line, task.Column); } } } }
private static void OpenDocument(string filename, out IVsTextView viewAdapter, out IVsWindowFrame pWindowFrame) { IVsTextManager textMgr = (IVsTextManager)Current.GetService(typeof(SVsTextManager)); IVsUIShellOpenDocument uiShellOpenDocument = Current.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsUIHierarchy hierarchy; uint itemid; VsShellUtilities.OpenDocument( Current, filename, Guid.Empty, out hierarchy, out itemid, out pWindowFrame, out viewAdapter); }
/// <summary> /// Called when navigating to an error task. /// </summary> private void OnTaskNavigate(Object sender, EventArgs e) { var task = (ErrorTask)sender; var fullPath = task.Document; var logicalView = new Guid(LogicalViewID.TextView); var hierarchy = default(IVsUIHierarchy); var itemID = default(uint); var windowFrame = default(IVsWindowFrame); var isClosed = !VsShellUtilities.IsDocumentOpen(serviceProvider, fullPath, logicalView, out hierarchy, out itemID, out windowFrame); if (isClosed) { try { VsShellUtilities.OpenDocument(serviceProvider, fullPath, logicalView, out hierarchy, out itemID, out windowFrame); } catch { return; } } ThreadHelper.ThrowIfNotOnUIThread(); ErrorHandler.ThrowOnFailure(windowFrame.Show()); var vsTextView = VsShellUtilities.GetTextView(windowFrame); var vsTextBuffer = default(IVsTextLines); ErrorHandler.ThrowOnFailure(vsTextView.GetBuffer(out vsTextBuffer)); var startLine = task.Line; var startCol = task.Column; var endLine = task.Line; var endCol = task.Column; var vsTextManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager)); if (vsTextManager != null) { vsTextManager.NavigateToLineAndColumn(vsTextBuffer, ref logicalView, startLine, startCol, endLine, endCol); } }
//--------------------------------------------------------------------- IVsTextView OpenTextView(string path) { var serviceProvider = VsIdeTestHostContext.ServiceProvider; uint itemID; IVsUIHierarchy uiHierarchy; IVsWindowFrame windowFrame; IVsTextView textView; VsShellUtilities.OpenDocument(serviceProvider, path, Guid.Empty, out uiHierarchy, out itemID, out windowFrame, out textView); if (textView == null) { throw new InvalidOperationException("Cannot open document " + path); } return(textView); }
/// <summary> /// In a perfect world this would replace the contents of the existing ITextView /// with those of the specified file. Unfortunately this causes problems in /// Visual Studio when the file is of a different content type. Instead we /// mimic the behavior by opening the document in a new window and closing the /// existing one /// </summary> public override bool LoadFileIntoExistingWindow(string filePath, ITextView textView) { try { // Open the document before closing the other. That way any error which occurs // during an open will cause the method to abandon and produce a user error // message VsShellUtilities.OpenDocument(_vsAdapter.ServiceProvider, filePath); _textManager.CloseView(textView); return(true); } catch (Exception e) { _vim.ActiveStatusUtil.OnError(e.Message); return(false); } }
private static void OpenDocument(string fileName, out IVsTextView view, out IVsWindowFrame windowFrame) { ThreadHelper.ThrowIfNotOnUIThread(); try { IVsUIHierarchy uiHierarchy; uint itemId; VsShellUtilities.OpenDocument(ProbeToolsPackage.Instance, fileName, Guid.Empty, out uiHierarchy, out itemId, out windowFrame, out view); } catch (Exception ex) { ShowError(ex); view = null; windowFrame = null; } }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); object item = ProjectUtils.GetSelectedItem(); string folder = ProjectUtils.FindFolder(item); if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { return; } ProjectItem selectedItem = item as ProjectItem; Project selectedProject = item as Project; Project project = selectedItem?.ContainingProject ?? selectedProject ?? ProjectUtils.GetActiveProject(); if (project == null) { throw new Exception("Could not find project!"); // TODO remove exception after testing } // Get files if (PromptForFileName(folder)) { var cppInfo = new FileInfo(m_CppFilePath); var hppInfo = new FileInfo(m_HppFilePath); ProjectItem projectItemCpp = project.AddFileToProject(cppInfo); ProjectItem projectItemHpp = project.AddFileToProject(hppInfo); if (projectItemCpp == null || projectItemHpp == null) { // We have a problem here! MessageBox.Show("Could not create project files!"); return; } project.Save(); VsShellUtilities.OpenDocument(this.package, cppInfo.FullName); VsShellUtilities.OpenDocument(this.package, hppInfo.FullName); CppSourceManagerPackage.ms_DTE.ExecuteCommand("SolutionExplorer.SyncWithActiveDocument"); CppSourceManagerPackage.ms_DTE.ActiveDocument.Activate(); } }
public override void OpenDocument(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.Value.IsForeground()) { throw new InvalidOperationException("This workspace only supports opening documents on the UI thread."); } var document = CurrentDocuments.GetDocument(documentId); if (document == null) { return; } uint itemID; IVsUIHierarchy hierarchy; IVsWindowFrame docFrame; IVsTextView textView; try { VsShellUtilities.OpenDocument( _serviceProvider, document.FilePath, VSConstants.LOGVIEWID_Code, out hierarchy, out itemID, out docFrame, out textView); } catch { // File might not exist, etc. return; } if (activate) { docFrame.Show(); } else { docFrame.ShowNoActivate(); } }
public void HandleLocalLink(string link) { var url = this.ExtractLinkUrl(link); var path = this.PreprocessPath(url); var lcinfo = this.ExtractLineColumnInfo(link); VsShellUtilities.OpenDocument(TermWindowPackage.Instance, path, Guid.Empty, out _, out _, out _, out var textView); if (textView != null) { // Indexing in an IVsTextView is zero-based, whereas values returned from a build should be one-based. textView.SetCaretPos(lcinfo.Item1 - 1, lcinfo.Item2 - 1); textView.CenterLines(lcinfo.Item1 - 1, 1); textView.SendExplicitFocus(); } }
public IWpfTextView GetTextView() { var model = GetService(typeof(SComponentModel)) as IComponentModel; var adapter = model.GetService <IVsEditorAdaptersFactoryService>(); var uiShellOpenDocument = GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; VsShellUtilities.OpenDocument( this.ProjectMgr.Site, this.GetMkDocument(), Guid.Empty, out var hierarchy, out var itemid, out var pWindowFrame, out var viewAdapter); ErrorHandler.ThrowOnFailure(pWindowFrame.Show()); return(adapter.GetWpfTextView(viewAdapter)); }
public static void HandleLocalLink(string uri) { var url = ExtractLinkUrl(uri); var path = PreprocessPath(url); var lcinfo = ExtractLineColumnInfo(uri); VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, path, Guid.Empty, out _, out _, out _, out var textView); if (textView != null) { // Indexing in an IVsTextView is zero-based, whereas values returned from a build should be one-based. textView.SetCaretPos(lcinfo.Item1 - 1, lcinfo.Item2 - 1); textView.CenterLines(lcinfo.Item1 - 1, 1); textView.SendExplicitFocus(); } }
public void OpenFile(string filePath, bool isReadOnly) { ThreadHelper.ThrowIfNotOnUIThread(); var rdt = new RunningDocumentTable(_serviceProvider); IVsWindowFrame?windowFrame = null; try { // Open the document. VsShellUtilities.OpenDocument( _serviceProvider, filePath, VSConstants.LOGVIEWID_Primary, out _, out _, out windowFrame); // Set it as read only if necessary. if (isReadOnly) { RunningDocumentInfo rdtInfo = rdt.GetDocumentInfo(filePath); // Set it as read only if necessary. if (rdtInfo.DocData is IVsTextBuffer textBuffer) { textBuffer.GetStateFlags(out uint flags); textBuffer.SetStateFlags(flags | (uint)BUFFERSTATEFLAGS.BSF_USER_READONLY); } } // Show the document window if (windowFrame != null) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } } catch (Exception ex) when(!ex.IsCritical()) { windowFrame?.CloseFrame(0); } }
// Attempt navigation to historical file bool TryNavigateFromHistoryFile(IVsTextView sourceView) { if (teamExplorerContext.Value.ActiveRepository?.LocalPath is string repositoryDir && FindObjectishForTFSTempFile(sourceView) is string objectish) { var(_, blobPath) = gitHubContextService.Value.ResolveBlobFromHistory(repositoryDir, objectish); if (blobPath is string) { var workingFile = Path.Combine(repositoryDir, blobPath); VsShellUtilities.OpenDocument(serviceProvider, workingFile, VSConstants.LOGVIEWID.TextView_guid, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame, out IVsTextView targetView); pullRequestEditorService.Value.NavigateToEquivalentPosition(sourceView, targetView); return(true); } } return(false); }
private void OpenSelectedFiles() { foreach (var fileName in GetSelectedFiles()) { try { var serviceProvider = Package.GetGlobalService(typeof(IServiceProvider)) as IServiceProvider; VsShellUtilities.OpenDocument(serviceProvider, fileName); } catch (Exception e) { if (SingleItemSelected) { MessageBox.Show(e.Message, VisualHg.Resources.MessageBoxCaption, MessageBoxButton.OK, MessageBoxImage.Error); } } } }