Related
Suppose I have the following input as shown below. What I would like to do is to visually select lines 2 through 4 (shift + v) and then delete the word dog.
How can I do that? I know I can use something like :s/dog// on my selection, but I was wondering if there's a more straightforward way.
1 The quick brown dog
2 dog jumps
3 over the
4 lazy dog,
5 but it should be just a fox.
The final output should be (affected only by the visual selection on lines 2 through 4):
1 The quick brown dog
2 jumps
3 over the
4 lazy ,
5 but it should be just a fox.
That's impossible.
Why?
tl;dr
I think, you are envisioning something like a normal mode within visual mode (so that you can "move and delete like in Vim" while you are in visual mode). Such a thing doesn't exist.
Think about it: if you visual select some lines, then those lines, and nothing else, are the object of whatever action you do next (d, s, c, or whatever).
But you want to take an action not on those visually selected lines, but on words within them. But how can you tell Vim to take action on the words dog and not on other words? You can do that with movements, but as long as you are in visual mode, that's not possible, because any movement will just change the visual selection, and not allow you to somehow move within it.
This means that you need to abandon the visual selection so that you can move to those words and use them as the textual object for the action.
If you really want to start from the visual selection, then the only way to give the info that you want to take action on the words dog, is to type them out while you are in visual mode. And that's precisely what the :s approach does.
You can take advantage of the marks '< and '>: they store the start/end position of the visual selection and they keep their value after you exit the visual mode.
In command line mode, Ctrl-RCtrl-W inserts the word under the cursor.
By combining this, you can create a mapping like that:
noremap <c-d> :'<,'>s/<c-r><c-w>//<cr>
Then to use it:
first select the wanted zone with V;
hit Esc to exit visual mode;
move your cursor under the word you want to delete;
then trigger the mapping, in this example Ctrl-D.
I think there is no way in way to just replace a specific word in specific lines with visual selection. You can also use sed for that (look at #5).
Anyways:
Here are 4 way to delete the word dog in a file and one way to do it with sed:
1 (with visual mode):
Type v to enter visual character mode
Highlight dog
Press d for deleting
2 (with substitute and confirmation):
:%s/dog//gc
g stands for global
c stand for confirmation
You will be ask for every entry, what to do with.
3 (with substitute):
:2,4s/dog//
4 (with search mode):
/dog
Type: n for next match
Type: d for deleting the match
For further information: Search and Replace
5 (with sed):
sed 2,4\s/dog// filename
When you are in visual mode, pressing : automatically inserts the visual range in the command-line so whatever Ex command you use after that is going to work on the visually selected lines:
: becomes :'<,'>, in which '<,'> is a range beginning on the first line of the visual selection and ending on the last line of the visual selection.
After that, you can do s/dog<CR> (no need for the //) to substitute the first dog with nothing on every selected line. This is effectively equivalent to doing :2,4s/dog<CR>.
From a semantic point of view, :s/dog<CR> is as close as you can get with the built-in features to "remove dog in the current visual selection" so, barring making an hypothetical custom mapping that would only save a couple of keystrokes, you are unlikely to find a more "straightforward" way.
I need to find TFS work items related to a certain topic in our project.
For that purpose, I tried querying the work items using the query builder in Visual Studio.
Since there are multiple terms I wish to search for, I imagined a query like this:
WHERE (
Priority > 300 AND
(Title.Contains('Dog') OR Title.Contains('Cat') OR Title.Contains('Hamster')))
Now, according to http://msdn.microsoft.com/en-us/library/dd286638.aspx (Section And/Or) one should be able to do that like so:
| Priority| > | 300
And | Title | Contains | Dog
Or | Title | Contains | Cat
Or | Title | Contains | Hamster
But... that does not work as described: as far as I can see, this is treated like
(Priority > 300 AND Title.Contains('Dog')) OR Title.Contains('Cat') OR Title.Contains('Hamster')))
Now that is a bit of a problem for me, because apart from a 'Priority' criterion I also have 8 additional criteria that need to apply to all the matches (Date, State, etc.). And I have not only three possible title matches, but around ten. So that multiplies and I would end up with a query that is terribly long and mostly redundant.
.. or, am I missing something here? Is there another way to express those statements? Or is there even another way to query TFS work items, like another tool?
Thanks!
You need to "Group" your Title clauses together to get the query you expect. Select the three "Title" clauses, Right Click and select "Group Clauses".
Here's a snip of a query I created in VS2012 to do this, but it's the same in 2010.
It will only find work items with a Priority >4 and a Title containing either Crash, Error or Working.
Is there some way to save array/list/collection data to a file while debugging in VS2010?
For example, in this code:
var addressGraphs = from a in context.Addresses
where a.CountryRegion == "Canada"
select new { a, a.Contact };
foreach(var ag in addressGraphs) {
Console.WriteLine("LastName: {0}, Addresses: {1}", ag.Contact.LastName.Trim(),
ag.Contact.Addresses.Count());
foreach(var Address in ag.Contact.Addresses) {
Console.WriteLine("...{0} {1}", Address.Street1, Address.City);
}
}
I'd like to set a breakpoint on the first 'foreach' line and then save the data in 'addressGraph' to a file.
where 'a' contains fields such as:
int addressID
string Street1
string City
<Ect.>
and 'Contact' contains fields such as:
string FirstName
string LastName
int contactID
<Ect.>
I'd like the file to contain the values of each of the fields for each item in the collection.
I don't see an obvious way to do this. Is it possible?
When your breakpoint is hit, open up the Immediate window and use Tools.LogCommandWindowOutput to dump the output to a file:
>Tools.LogCommandWindowOutput c:\temp\temp.log
?addressGraphs
>Tools.LogCommandWindowOutput /off
Note: You can use Log which is an alias for Tools.LogCommandWindowOutput
Update:
The > character is important. Also, the log alias is case sensitive.
See screenshot:
I also encoutered such a question, but in VS2013. I have to save a content of array while debugging.
For example, I need to save a content of double array named "trimmedInput". I do so:
Open QuickWatch Window from Debug menu (Ctrl+D, Q).
Put your variable in Expression and push Recalculate Button
You'll see all the values. Now you could select them all (Ctrl+A) and copy (Ctrl+C).
Paste (Ctrl+V) them in your favorite editor. Notepad, for example. And use them.
That's the simples way that I know. Without additional efforts. Hope that my description helps you!
P.S. Sorry for non English interface on screenshots. All necessary information are written in the text.
Something similar is possible with this method:
I built an extension method that I use in all of my projects that is a general and more powerful ToString() method that shows the content of any object.
I included the source code in this link:
https://rapidshare.com/files/1791655092/FormatExtensions.cs
UPDATE:
You just have to put FormatExtensions.cs in your project and change the Namespace of FormatExtensions to coincide to the base Namespace of your project. So when you are in your breakpoint you can type in your watch window:
myCustomCollection.ToStringExtended()
And copy the output wherever you want
On Visual studio Gallery search for: Object Exporter Extension.
be aware: as far as I worked with, it has a bug that block you from exporting object once in a while.
You can also call methods in the Immediate Window, and so I think your best bet would be to use an ObjectDumper object, like the one in the LINQ samples or this one, and then write something like this in the Immediate Window:
File.WriteAllText("myFileName.txt", ObjectDumper.Dump(addressGraph));
Depending on which ObjectDumper you decide to use, you may be able to customize it to suit your needs, and to be able to tell it how many levels deep you want it to dig into your object when it's dumping it.
Here's a solution that takes care of collections. It's a VS visualizer that will display the collection values in a grid while debugging as well as save to the clipboard and csv, xml and text files. I'm using it in VS2010 Ultimate. While I haven't tested it extensively, I have tried it on List and Dictionary.
http://tinyurl.com/87sf6l7
It handles the following collections:
•System.Collections classes
◦System.Collections.ArrayList
◦System.Collections.BitArray
◦System.Collections.HashTable
◦System.Collections.Queue
◦System.Collections.SortedList
◦System.Collections.Stack
◦All classes derived from System.Collections.CollectionBase
•System.Collections.Specialized classes
◦System.Collections.Specialized.HybridDictionary
◦System.Collections.Specialized.ListDictionary
◦System.Collections.Specialized.NameValueCollection
◦System.Collections.Specialized.OrderedDictionary
◦System.Collections.Specialized.StringCollection
◦System.Collections.Specialized.StringDictionary
◦All classes derived from System.Collections.Specialized.NameObjectCollectionBase
•System.Collections.Generic classes
◦System.Collections.Generic.Dictionary
◦System.Collections.Generic.List
◦System.Collections.Generic.LinkedList
◦System.Collections.Generic.Queue
◦System.Collections.Generic.SortedDictionary
◦System.Collections.Generic.SortedList
◦System.Collections.Generic.Stack
•IIS classes, as used by
◦System.Web.HttpRequest.Cookies
◦System.Web.HttpRequest.Files
◦System.Web.HttpRequest.Form
◦System.Web.HttpRequest.Headers
◦System.Web.HttpRequest.Params
◦System.Web.HttpRequest.QueryString
◦System.Web.HttpRequest.ServerVariables
◦System.Web.HttpResponse.Cookies
As well as a couple of VB6-compatible collections
In "Immediate Window" print following to get the binary dump:
byte[] myArray = { 02,01,81,00,05,F6,05,02,01,01,00,BA };
myArray
.Select(b => string.Format("{0:X2}", b))
.Aggregate((s1, s2) => s1 + s2)
This will print something like:
0201810005F60502010100BA
Change the '.Aggregate(...)' call to add blanks between bytes, or what ever you like.
Is it possible to find the number of lines of code in an entire solution? I've heard of MZ-Tools, but is there an open source equivalent?
I've found powershell useful for this. I consider LoC to be a pretty bogus metric anyway, so I don't believe anything more formal should be required.
From a smallish solution's directory:
PS C:\Path> (gci -include *.cs,*.xaml -recurse | select-string .).Count
8396
PS C:\Path>
That will count the non-blank lines in all the solution's .cs and .xaml files. For a larger project, I just used a different extension list:
PS C:\Other> (gci -include *.cs,*.cpp,*.h,*.idl,*.asmx -recurse | select-string .).Count
909402
PS C:\Other>
Why use an entire app when a single command-line will do it? :)
Visual Studio has built-in code metrics, including lines of code:
Analyze → Calculate Code Metrics
I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).
An open source line counter for VS2005, 2003 and 2002 is available here:
http://www.wndtabs.com/
There is also discussion of creating a line counting VS addin, complete with code on Codeproject, here
http://www.codeproject.com/KB/macros/LineCounterAddin.aspx
Also Slick Edit Gadgets have a nice line-counter, here:
http://www.slickedit.com/products/slickedit
and Microsoft Visual Studio Team System 2008 includes a good line counter.
Just remember though:
Measuring programming progress by lines of code is like measuring aircraft building progress by weight.
Bill Gates
Here's an update for Visual Studio 2012/2013/2015 for those who want to do the "Find" option (which I find to be the easiest): This RegEx will find all non-blank lines with several exclusions to give the most accurate results.
Enter the following RegEx into the "Find" box. Please make sure to select the "Use Regular Expressions" option. Change the search option to either "Current Project" or "Entire Solution" depending on your needs. Now select "Find All". At the bottom of the Find Results window, you will see "Matching Lines" which is the lines of code count.
^(?!(\s*\*))(?!(\s*\-\-\>))(?!(\s*\<\!\-\-))(?!(\s*\n))(?!(\s*\*\/))(?!(\s*\/\*))(?!(\s*\/\/\/))(?!(\s*\/\/))(?!(\s*\}))(?!(\s*\{))(?!(\s(using))).*$
This RegEx excludes the following items:
Comments
// This is a comment
Multi-Line comments (assuming the lines are correctly commented with a * in front of each line)
/* I am a
* multi-line
* comment */
XML for Intellisense
/// <summary>
/// I'm a class description for Intellisense
/// </summary>
HTML Comments:
<!-- I am a HTML Comment -->
Using statements:
using System;
using System.Web;
Opening curly braces:
{
Closing curly braces:
}
Note: anything between the braces would be included in the search, but in this example only 4 lines of code would count, instead of 18 actual non-blank lines:
public class Test
{
/// <summary>
/// Do Stuff
/// </summary>
public Test()
{
TestMe();
}
public void TestMe()
{
//Do Stuff Here
/* And
* Do
* Stuff
* Here */
}
}
I created this to give me a much more accurate LOC count than some previous options, and figured I would share. The bosses love LOC counts, so I'm stuck with it for a while. I hope someone else can find this helpful, let me know if you have any questions or need help getting it to work.
Found this tip:
LOC with VS Find and replace
Not a plugin though if thats what you are looking for.
cloc is an excellent commandline, Perl-based, Windows-executable which will break down the blank lines, commented lines, and source lines of code, grouped by file-formats.
Now it won't specifically run on a VS solution file, but it can recurse through directories, and you can set up filename filters as you see fit.
Here's the sample output from their web page:
prompt> cloc perl-5.10.0.tar.gz
4076 text files.
3883 unique files.
1521 files ignored.
http://cloc.sourceforge.net v 1.07 T=10.0 s (251.0 files/s, 84566.5 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code scale 3rd gen. equiv
-------------------------------------------------------------------------------
Perl 2052 110356 112521 309778 x 4.00 = 1239112.00
C 135 18718 22862 140483 x 0.77 = 108171.91
C/C++ Header 147 7650 12093 44042 x 1.00 = 44042.00
Bourne Shell 116 3402 5789 36882 x 3.81 = 140520.42
Lisp 1 684 2242 7515 x 1.25 = 9393.75
make 7 498 473 2044 x 2.50 = 5110.00
C++ 10 312 277 2000 x 1.51 = 3020.00
XML 26 231 0 1972 x 1.90 = 3746.80
yacc 2 128 97 1549 x 1.51 = 2338.99
YAML 2 2 0 489 x 0.90 = 440.10
DOS Batch 11 85 50 322 x 0.63 = 202.86
HTML 1 19 2 98 x 1.90 = 186.20
-------------------------------------------------------------------------------
SUM: 2510 142085 156406 547174 x 2.84 = 1556285.03
-------------------------------------------------------------------------------
The third generation equivalent scale is a rough estimate of how much code it would take in a third generation language. Not terribly useful, but interesting anyway.
Answers here are a little bit out of date, may be from vs 2008 time. Because in newer Visual Studio versions 2010/2012, this feature is already built-in. Thus there are no reason to use any extension or tools for it.
Feature to count lines of code - Calculate Metrics. With it you can calculate your metrics (LOC, Maintaince index, Cyclomatic index, Depth of inheritence) for each project or solution.
Just right click on solution or project in Solution Explorer,
and select "Calculate metrics"
Later data for analysis and aggregation could be imported to Excel. Also in Excel you can filter out generated classes, or other noise from your metrics. These metrics including Lines of code LOC could be gathered also during build process, and included in build report
Regular expressions have changed between VS2010 and 2012, so most of the regular expression solutions here no longer work
(^(?!(\s*//.+)))+(^(?!(#.+)))+(^(?!(\s*\{.+)))+(^(?!(\s*\}.+)))+(^(?!(\s*\r?$)))+
Will find all lines that are not blank, are not just a single bracket ( '{' or '}' ) and not just a #include or other preprocessor.
Use Ctrl-shift-f and make sure regular expressions are enabled.
The corresponding regular expression for VS 2010 and older is
^~(:Wh#//.+)~(:Wh#\{:Wh#)~(:Wh#\}:Wh#)~(:Wh#/#).+
In Visual Studio Team System 2008 you can do from the menu Analyze--> 'Calculate Code Metrics for Solution' and it will give you a line count of your entire solution (among other things g)
For future readers I'd like to advise the DPack extension for Visual Studio 2010.
It's got a load of utilities built in including a line counter which says how many lines are blank, code, and etc.
A simple solution is to search in all files. Type in "*" while using wildcards. Which would match all lines. At the end of the find results window you should see a line of the sort:
Matching lines: 563 Matching files: 17 Total files searched: 17
Of course this is not very good for large projects, since all lines are mached and loaded into memory to be dispayed at the find results window.
Reference:
Advanced Example
In Visual Studio 2019, from the top menu you need to select:
'Analyze' -> 'Calculate Code Metrics' -> 'For Solution'
This works in both Visual Studio 2019 Professional and Enterprise.
You could use:
SCLOCCount http://www.dwheeler.com/sloccount/- Open source
loc metrics, http://www.locmetrics.com/ - not open source, but easy to use
I prefer OxyProject Metrics VS Addin.
Obviously tools are easier, but I feel cool doing this in powershell:)
This script finds all the .csproj references in the .sln file, and then within each csproj file it locates files included for compilation. For each file that is included for compilation it creates an object with properties: Solution, Project, File, Lines. It stores all these objects in a list, and then groups and projects the data as needed.
#path to the solution file e.g. "D:\Code\Test.sln"
$slnFile = "D:\Code\Test.sln"
#results
$results = #()
#iterate through .csproj references in solution file
foreach($projLines in get-item $slnFile | Get-Content | Select-String '".*csproj')
{
$projFile = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($slnFile), [regex]::Match($projLines,'[^"]*csproj').Value)
$projFolder = [System.IO.Path]::GetDirectoryName($projFile)
#from csproj file: get lines for files to compile <Compile Include="..."/>
$includeLines = get-item $projFile | Get-Content | Select-String '<Compile Include'
#count of all files lines in project
$linesInProject = 0;
foreach($fileLine in $includeLines)
{
$includedFilePath = [System.IO.Path]::Combine($projFolder, [Regex]::Match($fileLine, '"(?<file>.*)"').Groups["file"].Value)
$lineCountInFile = (Get-Content $includedFilePath).Count
$results+=New-Object PSObject -Property #{ Solution=$slnFile ;Project=$projFile; File=$includedFilePath; Lines=$lineCountInFile }
}
}
#filter out any files we dont need
$results = $results | ?{!($_.File -match "Designer")}
#print out:
"---------------lines per solution--------------"
$results | group Solution | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
"---------------lines per peoject--------------"
$results | group Project | %{$_.Name + ": " + ($_.Group | Measure-Object Lines -Sum).Sum}
Other simple tool For VS2008 (open source): http://www.accendo.sk/Download/SourceStat.zip
Use Menu-> Analyse - > Calculate Code Metrics option in Visual Studio 2010 Ultimate.
You can use the Visual Studio Code Metrics PowerTool 10.0. It's a command-line utility that calculates a few metrics on managed code for you (including lines of code). You can get a VS 2010 plugin that brings the tool into Visual Studio, and makes it as quick as selecting the menu item and clicking "Analyze Solution."
Agree with Ali Parr. The WndTab Line Counter addin is a such tool.
http://www.codeproject.com/KB/macros/linecount.aspx
It's also a good idea to search from download site to find some related tool.
http://www.cnet.com/1770-5_1-0.html?query=code+counter&tag=srch
Here is the Trick.. It counts the Js file also.
http://www.spoiledtechie.com/post/2011/11/22/How-To-Count-Lines-of-Code-in-Visual-Studio.aspx
You can use free tool SourceMonitor
Gives a lot of measures: Lines of Code, Statement Count, Complexity, Block Depth
Has graphical outputs via charts
You can use the Project Line Counter add-in in Visual Studio 2010. Normally it doesn't work with Visual Studio 2010, but it does with a helpful .reg file from here: http://www.onemanmmo.com/index.php?cmd=newsitem&comment=news.1.41.0
I came up with a quick and dirty powershell script for counting lines in a folder structure. It's not nearly as full featured as some of the other tools referenced in other answers, but I think it's good enough to provide a rough comparison of the size of code files relative to one another in a project or solution.
The script can be found here:
https://gist.github.com/1674457
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".
Try neptuner. It also gives you stuff like spaces, tabs, Lines of comments in addition to LoC.
http://neptuner.googlecode.com/files/neptuner_0_30_windows.zip
This question already has answers here:
How can I reverse code around an equal sign in Visual Studio?
(6 answers)
Closed 4 years ago.
I have a bunch of assignment operations in Visual Studio, and I want to reverse them:
i.e
i = j;
would become
j = i;
i.e. replacing everything before the equals with what's after the equals, and vice versa
Is there any easy way to do this, say something in the regular expression engine?
Select the lines you want to swap, Ctrl+H, then replace:
{:i}:b*=:b*{:i};
with:
\2 = \1;
with "Look in:" set to "Selection"
That only handles C/C++ style identifiers, though (via the ":i"). Replace that with:
{.*}:b*=:b*{.*};
to replace anything on either side of the "=".
Also, since you mentioned in a comment you use ReSharper, you can just highlight the "=", Alt+Enter, and "Reverse assignment".
Just a slight improvement on Chris's answer...
Ctrl+H, then replace:
{:b*}{[^:b]*}:b*=:b*{[^:b]*}:b*;
with:
\1\3 = \2;
(better handling of whitespace, esp. at beginning of line)
EDIT:
For Visual Studio 2012 and higher (I tried it on 2015):
Replace
(\s*)([^\s]+)\s*=\s*([^\s]+)\s*;
with:
$1$3 = $2;
In Visual Studio 2015+ after selecting code block press Ctrl + H (Find & Replace window) and check "Use Regular Expression" option, then:
Find: (\w+.\w+) = (\w+);
Replace: $2 = $1;
For example:
entity.CreateDate = CreateDate;
changes to:
CreateDate = entity.CreateDate;
Thank you #Nagesh and Revious, mentioned details added.
The robust way to do this is to use a refactoring tool. They know the syntax of the language, so they understand the concept of "assignment statement" and can correctly select the entire expression on either side of the assignment operator rather than be limited to a single identifier, which is what I think all the regular expressions so far have covered. Refactoring tools treat your code as structured code instead of just text. I found mention two Visual Studio add-ins that can do it:
ReSharper
MZ-Tools
(Inverting assignment isn't technically refactoring since it changes the behavior of the program, but most refactoring tools extend the meaning to include other generic code modifications like that.)
Please see this question: Is there a method to swap the left and right hand sides of a set of expressions in Visual Studio?
My answer to that question has a macro that you can use to swap the assignments for a block of code.
I've improved the expression a little.
Replace
(\t+)(\s*)(\S*) = (\S*);
with
$1$2$4 = $3;
The reason is, it will look for lines starting with tab (\t). It will skip the lines starting with definition. E.g.:
TestClass tc = new TestClass();
int a = 75;
int b = 76;
int c = 77;
a = tc.a;
b = tc.b;
a = tc.c;
Would ignore the int a, int b and int c and swap only the assignments.
what about replace all (CTRL-H)
you can replace for example "i = j;" by "j = i;"
you can use regular expressions in that dialog. I'm not so sure about how you should pop-up help about them however. In that dialog, press F1, then search that page for more information on regular expressions.
I like this dialog because it allows you to go through each replacement. Because the chance of breaking something is high, I think this is a more secure solution
You can do search and replace with regular expressions in Visual Studio, but it would be safer to just do a normal search and replace for each assignment you want to change rather than a bulk change.
Unfortunatly I don't have Visual Studio, so I can't try in the target environment, but if it uses standard regexps, you could probably do it like this:
Search for "(:Al) = (:Al);", and replace with "\2 = \1". (\1 and \2 are references to the first and second capture groups, in this case the parenthesises around the \w:s)
EDIT
Ok, not \w... But according to MSDN, we can instead use :Al. Edited above to use that instead.
Also, from the MSDN page I gather that it should work, as the references seem to work as usual.