Open a file in Visual Studio with a specific line number

I have a utility (grep) that gives me a list of file names and line numbers. After I determined that devenv is the right program to open the file, I would like to make sure that it is open with the specified line number. In emacs, this will be:

emacs +140 filename.c 

I did not find anything like this for Visual Studio (devenv). The closest I found:

 devenv /Command "Edit.Goto 140" filename.c 

However, this makes a separate instance of devenv for each such file. I would prefer something that uses an existing instance.

These options are to reuse an existing devenv, but do not go to the specified line:

 devenv /Command "Edit.Goto 140" /Edit filename.c devenv /Command /Edit filename.c "Edit.Goto 140" 

I thought using multiple "/ Command" arguments could do this, but I probably don't have the right one, because I either get errors or don’t answer at all (except opening empty devenv).

I can write a special macro for devenv, but I would like this utility to be used by others who do not have this macro. And I don’t understand how to call this macro with the "/ Command" parameter.

Any ideas?




Well, there seems to be a way to do this as I wanted. Since it seems to me that I need to have dedicated code to run Visual Studio, I decided to use EnvDTE, as shown below. Hope this helps someone else.

 #include "stdafx.h" //----------------------------------------------------------------------- // This code is blatently stolen from http://benbuck.com/archives/13 // // This is from the blog of somebody called "BenBuck" for which there // seems to be no information. //----------------------------------------------------------------------- // import EnvDTE #pragma warning(disable : 4278) #pragma warning(disable : 4146) #import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids #pragma warning(default : 4146) #pragma warning(default : 4278) bool visual_studio_open_file(char const *filename, unsigned int line) { HRESULT result; CLSID clsid; result = ::CLSIDFromProgID(L"VisualStudio.DTE", &clsid); if (FAILED(result)) return false; CComPtr<IUnknown> punk; result = ::GetActiveObject(clsid, NULL, &punk); if (FAILED(result)) return false; CComPtr<EnvDTE::_DTE> DTE; DTE = punk; CComPtr<EnvDTE::ItemOperations> item_ops; result = DTE->get_ItemOperations(&item_ops); if (FAILED(result)) return false; CComBSTR bstrFileName(filename); CComBSTR bstrKind(EnvDTE::vsViewKindTextView); CComPtr<EnvDTE::Window> window; result = item_ops->OpenFile(bstrFileName, bstrKind, &window); if (FAILED(result)) return false; CComPtr<EnvDTE::Document> doc; result = DTE->get_ActiveDocument(&doc); if (FAILED(result)) return false; CComPtr<IDispatch> selection_dispatch; result = doc->get_Selection(&selection_dispatch); if (FAILED(result)) return false; CComPtr<EnvDTE::TextSelection> selection; result = selection_dispatch->QueryInterface(&selection); if (FAILED(result)) return false; result = selection->GotoLine(line, TRUE); if (FAILED(result)) return false; return true; } 
+55
command-line visual-studio
Dec 08 '08 at 18:04
source share
11 answers

I cannot find a way to do this using direct command line options. It looks like you have to write a macro for it. Presumably, you can call them like this.

 devenv /command "Macros.MyMacros.Module1.OpenFavoriteFiles" 

So, you can create a macro that takes the file name and line number, then opens the file and goes to the right place. But I do not know that you can specify the flag of the same instance or not.

0
Dec 08 '08 at 18:31
source share

With VS2008 SP1, you can use the following command line to open a file on a specific line in an existing instance:

 devenv /edit FILE_PATH /command "edit.goto FILE_LINE" 

Source

+29
Sep 09 '10 at 15:31
source share

In developing Harold's question and answer, I adapted the C ++ solution (which I first adopted) to C #. This is much simpler (this is my first C # program!). You just need to create a project, add links to "envDTE" and "envDTE80" and leave the following code:

 using System; using System.Collections.Generic; using System.Text; namespace openStudioFileLine { class Program { [STAThread] static void Main(string[] args) { try { String filename = args[0]; int fileline; int.TryParse(args[1], out fileline); EnvDTE80.DTE2 dte2; dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE"); dte2.MainWindow.Activate(); EnvDTE.Window w = dte2.ItemOperations.OpenFile(filename, EnvDTE.Constants.vsViewKindTextView); ((EnvDTE.TextSelection)dte2.ActiveDocument.Selection).GotoLine(fileline, true); } catch (Exception e) { Console.Write(e.Message); } } } } 

Then only openStudioFileLine path_to_file numberOfLine .

Hope this helps!

+28
May 23 '12 at 16:20
source share

Based on the reder answer , I published a repository with the source , here is binary (.net2.0)

I also add support for multiple VS versions

 usage: <version> <file path> <line number> Visual Studio version value VisualStudio 2002 2 VisualStudio 2003 3 VisualStudio 2005 5 VisualStudio 2008 8 VisualStudio 2010 10 VisualStudio 2012 12 VisualStudio 2013 13 

GrepWin example:

 VisualStudioFileOpenTool.exe 12 %path% %line% 
+13
Jul 05 '13 at 12:26
source share

Pretty old thread, but it made me start, here is another example. This AutoHotkey function opens a file and places the cursor in a specific rowand column.

 ; http://msdn.microsoft.com/en-us/library/envdte.textselection.aspx ; http://msdn.microsoft.com/en-us/library/envdte.textselection.movetodisplaycolumn.aspx VST_Goto(Filename, Row:=1, Col:=1) { DTE := ComObjActive("VisualStudio.DTE.12.0") DTE.ExecuteCommand("File.OpenFile", Filename) DTE.ActiveDocument.Selection.MoveToDisplayColumn(Row, Col) } 

Call using:

 VST_Goto("C:\Palabra\.NET\Addin\EscDoc\EscDoc.cs", 328, 40) 

You could translate quite a few lines by line into VBScript or JScript.

+3
Nov 21 '14 at 21:16
source share

The following is a variant of Harold's VBS solution: a link to a .vbs script .

 open-in-msvs.vbs full-path-to-file line column 

Windows supports VBScript natively - there is no need for compilation or any additional interpreters.

+3
Sep 26 '16 at 6:33
source share

Here's a Python variation of Harold's solution:

 import sys import win32com.client filename = sys.argv[1] line = int(sys.argv[2]) column = int(sys.argv[3]) dte = win32com.client.GetActiveObject("VisualStudio.DTE") dte.MainWindow.Activate dte.ItemOperations.OpenFile(filename) dte.ActiveDocument.Selection.MoveToLineAndOffset(line, column+1) 

Shows how to go to the specified line of line +.

+2
Oct 20 '15 at 18:42
source share

For reference: ENVDE written in C # (using the O2 Platform in VisualStudio to get a link to a live DTE object)

 var visualStudio = new API_VisualStudio_2010(); var vsDTE = visualStudio.VsAddIn.VS_Dte; //var document = (Document)vsDTE.ActiveDocument; //var window = (Window)document.Windows.first(); var textSelection = (TextSelection)vsDTE.ActiveDocument.Selection; var selectedLine = 1; 20.loop(100,()=>{ textSelection.GotoLine(selectedLine++); textSelection.SelectLine(); }); return textSelection; 

This code is a bit of animation where 20 lines are selected (with an interval of 100 ms)

+1
May 15 '12 at 17:28
source share

The correct wingrep syntax command line is to force the new instance and go to the line number:

 "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" $F /command "edit.goto $L" 

Replace studio version number with the correct version for your installation.

+1
Jan 28 '16 at 19:20
source share

I was going to ask this question, because when you get the "yellow screen of death" when debugging a web application, you want to quickly go to the file and the line that it gives you on the stack, for example:

 [ContractException: Precondition failed: session != null] System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String msg, String userMessage, String conditionTxt, Exception inner) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String msg, String conditionTxt, Exception inner) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String msg, String conditionTxt) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 IAS_UI.Web.IAS_Session..ctor(HttpSessionStateBase session) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Web\IAS_Session.cs:15 IAS_UI.Controllers.ServiceUserController..ctor() in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\ServiceUserController.cs:41 

Let's say I want to go to ServiceUserController.cs on line 41. I usually open Visual Studio and do it manually, but then I wrote a little Autohotkey script that does this.

To open it, you highlight the file name and line number, for example. ServiceUserController.cs:41 , and then press Alt + v . Here is the code for it:

 $!v:: if (NOT ProcessExists("devenv.exe")) { MsgBox, % "Visual Studio is not loaded" } else { IfWinExist, Microsoft Visual Studio { ToolTip, Opening Visual Studio... c := GetClip() if (NOT c) { MsgBox, % "No text selected" } else { WinActivate ; now activate visual studio Sleep, 50 ; for now assume that there is only one instance of visual studio - handling of multiple instances comes in later arr := StringSplitF(c, ":") if (arr.MaxIndex() <> 2) { MsgBox, % "Text: '" . c . "' is invalid." } else { fileName := arr[1] lineNumber := arr[2] ; give focus to the "Find" box SendInput, ^d ; delete the contents of the "Find" box SendInput, {Home} SendInput, +{End} SendInput, {Delete} ; input *** >of FILENAME *** into the "Find" box SendInput, >of{Space} SendInput, % fileName ; select the first entry in the drop down list SendInput, {Down} SendInput, {Enter} ; lineNumber := 12 remove later ; open the go to line dialog SendInput, ^g Sleep, 20 ; send the file number and press enter SendInput, % lineNumber SendInput {Enter} } } ToolTip } } return 

Before that, you need to insert the following "utility functions":

 GetClip() { ClipSaved := ClipboardAll Clipboard= Sleep, 30 Send ^c ClipWait, 2 Sleep, 30 Gc := Clipboard Clipboard := ClipSaved ClipSaved= return Gc } ProcessExists(procName) { Process, Exist, %procName% return (ErrorLevel != 0) } StringSplitF(str, delimeters) { Arr := Object() Loop, parse, str, %delimeters%, { Arr.Insert(A_LoopField) } return Arr } 
0
Feb 24 '14 at 13:23
source share

Using this command works for me if Visual Studio is no longer open. "C: \ Program Files (x86) \ Microsoft Visual Studio 14.0 \ Common7 \ IDE \ devenv.exe" / edit "ABSOLUTEFILEPATH_FILENAME.CPP" / command "Edit.GoTo 164"

If it is already open, then sometimes it works and goes to the right line, but then it just stops working, and I never understood why. Microsoft seems to be aware of this issue, but said they will not “fix it” if more people don't complain. Therefore, if this is still a problem, I suggest commenting here: https://connect.microsoft.com/VisualStudio/Feedback/Details/1128717

0
Jul 24 '17 at 10:58
source share



All Articles