Visual studio CTRL+SHIFT+T transpose - what does it do? - visual-studio

I wrote some code and tried the Ctrl + T to check transpose feature in visual studio.
Just to check if CTRL + Shift + T does the reverse for this Transpose... I tried pressing Ctrl + Shift + T.
and it just messed up everything...
Can anyone tell me what exactly this Ctrl + Shift + T does (especially with a block) ?
For instance:
public string returnDateTimeToMyformat(DateTime dt)
{
dt = dt.AddYears(-1);
return dt.ToString("yyyy MM dd HH mm ss");
}
To:
string returnDateTimeToMyformat publicdtDateTime (dt
{
dt = )1AddYears(-.return;
dt ).ToString("yyyy MM dd HH mm ss");
}
(I started with my cursor right after 'public')

Since CTRL-T swaps the two characters on either side of the cursor, the opposite of it is ...
wait for it ...
CTRL-T
:-)
CTRLSHIFTT transposes the two words after the cursor.
What it's doing to your block seems rather bizarre. It appears to doing it to multiple parts of each line. My only advice would be (as the doctor said to the patient who complained it hurts when banging their head against a wall): Don't do that.

As others have pointed out, the two words following the cursor are transposed, and the cursor is placed after the words that have been transposed. However, Visual Studio 2010 at least appears to ignore commas and other punctuation when considering "words." One utility of this, then, is that you can reorder something like an enum. For instance,
typedef enum myEnum
{
ThingOne,
ThingThree,
ThingTwo
};
Put the cursor somewhere near ThingThree and press CtrlShiftT to get:
typedef enum myEnum
{
ThingOne,
ThingTwo,
ThingThree
};
This could be a good thing if you decide that a different order for your enums is better. You can also use this to help idiot-proof comparisons and/or quickly and easily format them to a better coding standard.
if ( ptr == NULL ) { /* stuff */ }
is considered bad (never mind that having an "if" on its own line is also bad) since you could easily write (or read) "ptr = NULL" by accident. You're better off with
if ( NULL == ptr ) { /* stuff */ }
So, if you did it wrong the first time, just select the offending expression and...CtrlShiftT to the rescue!
...Yeah, okay, so this thing isn't that useful.
Edit: Hmm, I should add that the behavior is a little weirder when your cursor is placed immediately before a punctuation symbol (such as a left-parenthesis), hence the weird result you got when you repeatedly hit CtrlShiftT on your code snippet. It seems to just swap any whitespace-terminated string after the cursor with the next alphanumeric "word," skipping over any punctuation symbols in between. The result is often difficult to read, though, so I'm not going to claim that's the exact pattern.

According to this website:
Transposes the two words that follow
the cursor. (For example, |End Sub
would be changed to read Sub End|.)
The only question that remains is probably: WHY??
Well it might become handy when you have a block of code lines where variables are assigned values. (For example Load/Save) In the opposite function, you want to do the opposite assignment, maybe this shortcut can be used in such a situation...

With this Visual Studio Document Reopen cool extension CTRL+SHIFT+T you can reopen the last closed document(s). It works like in Web browsers.

Related

How to program faster, (generate code from a pattern?)

I frequently run into problems that could be solved with automating code writing, but aren't long enough to justify it as tediously entering each piece is faster.
Here is an example:
Putting lists into dictionaries and things like this. Converting A into B.
A
hotdog HD
hamburger HB
hat H
B
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Sure I could come up with something to do this automatically, but it would only make sense if the list was 100+ items long. For a list of 10-20 items, is there a better solution than tediously typing? This is a Ruby example, but I typically run into cases like this all the time. Instead of a case statement, maybe it's a dictionary, maybe it's a list, etc.
My current solution is a python template with the streaming input and output already in place, and I just have to write the parsing and output code. This is pretty good, but is there better? I feel like this would be something VIM macro would excel at, but I'm that experienced with VIM. Can VIM do this easily?
For vim, it'd be a macro running over a list of space separated pairs of words, inserting the first 'when "' bit, the long form word 'hotdog', the ending quote, a newline and 'return "', and then the abbreviation and then final quote, then going back to the list and repeating.
Starting with a register w of:
when "
register r of:
return "
an initial list of:
hotdog HD
hamburger HB
hat H
and a starting file of:
def symbolizeType
case self.type
"newline here"
you can use the following macro at the start of the initial list:
^"ayeeeb"byeo"wp"apa"^Mrb"j
where ^M is a newline.
I do this frequently, and I use a single register and a macro, so I'll share.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
This is a long explanation, but the process is extremely simple and intuitive.
Here are the steps that I would take:
A. The starting text
hotdog HD
hamburger HB
hat H
B. Insert the initial, non-repetitive lines preceding the text to transform
def symbolizeType
case self.type
hotdog HD
hamburger HB
hat H
C. Transform the first line, while recording your keystrokes in a macro
This step I'll write out in detailed sub-steps.
Place the cursor on the first line to transform ("hotdog") and type qa to begin recording your keystrokes as a macro into register a.
Type ^ to move the cursor to the start of the line
Type like you normally would to transform the line to what you want, which for me comes out looking like the following macro
^i^Iwhen "^[ea"^[ldwi^M^Ireturn "^[ea"^[j
Where ^I is Tab, ^[ is Esc, and ^M is Enter.
After the line is transformed to your liking, move your cursor to the next line that you want to transform. You can see this in the macro above with the final j at the end.
This will allow you to automatically repeat the macro while it cycles through each repetitive line.
Stop recording the macro by typing q again.
You can then replay the macro from register a as many times as you like using a standard vim count prefix, in this case two consecutive times starting from the next line to transform.
2#a
This gives the following text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
D. Finally, insert the ending non-repetitive text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Final Comments
This works very quick for any random, repetitive text, and I find it very fluent.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
For things like this I have a few ways of making it easier. One is to use an editor like Sublime Text that allows you to multi-edit a number of things at once, so you can throw in markup with a few keystrokes and convert that into a Hash like:
NAME_TO_CODE = {
hotdog: 'HD',
hamburger: 'HB',
hat: 'H'
}
Not really a whole lot changed there. Your function looks like:
def symbolize_type(type)
NAME_TO_CODE[type.to_sym]
end
Defining this as a data structure has the bonus of being able to manipulate it:
CODE_TO_NAME = NAME_TO_CODE.invert
Now you can do this:
def unsymbolize_type(symbol)
CODE_TO_NAME[symbol.to_s]
end
You can also get super lazy and just parse it on the fly:
NAME_TO_CODE = Hash[%w[
hotdog HD
hamburger HB
hat H
].each_slice(2).to_a]
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.

Import Subtitles in Processing

I am working on this sketch on Processing which gets the videofeed from my webcam/smartphone and shows it when running. I want to import an .srt converted to txt subtitles file from a film to it. I can see that the text file has all these numbers that stand for the start and end subtitle frame before the actual text.
Here's an example:
{9232}{9331}Those swings are dangerous.|Stay off there. I haven't fixed them yet.
{9333}{9374}I think you're gonna live.
What I would like to do is to figure outa code that will
use the numbers and set them as start/end frames to run at the right time as in the film
display the subtitles
figure out how the '|'sign can be used as a symbol to trigger in the script the change of line.
I guess that might already be quite complicated but I just wanted to check whether someone has done anything similar in the past..
I guess what I want to do is save me from doing the whole
if ((current_frame > 9232) && ((current_frame < 9331)) {
text("Those swings are dangerous.", 200, 500/2);
text("Stay off there. I haven't fixed them yet..", 200, (500/2 + 35));
}
thing for each subtitle...
I am quite new to processing so not that familiar with many commands apart from 'for' and 'if', a newbie at importing .txt files and an ignoramus in working with arrays. But I really want to find a nice way in the last two bits..
Any help in any form will be greatly appreciated :)
Cheers,
George
For displaying the appropriate subtitle, you could do something like the following (explanation below, sorry in advance for the wall of text):
String[] subtitles = loadStrings("subtitles.txt");
int currentFrame = 0;
int subtitleIndex = -1;
int startFrame = -1, endFrame = -1;
int fontSize = 10; //change to suit your taste
String[] currentSubtitle;
...
//draw loop start:
//video drawing code goes here
if(currentFrame > endFrame){ //update which subtitle is now/next
subtitleIndex++;
startFrame = int(subtitles[subtitleIndex].split("\\}\\{")[0].substring(1));
endFrame = int(subtitles[subtitleIndex].split("\\}\\{")[1].split("\\}")[0]);
currentSubtitle = subtitles[subtitleIndex].split("\\}")[2].split("\\|");
}
if(currentFrame >= startFrame && currentFrame <= endFrame){
for(int i = 0; i < currentSubtitle.length; i++){
text(currentSubtitle[i], width/2, height - fontSize * (currentSubtitle.length - i));
}
}
currentFrame++;
//draw loop end
Probably that looks pretty intimidating to you, so here's some walk-through commentary. Your program will be a type of state machine. It will either be in the state of displaying a subtitle, or not. We'll keep this in mind later when we're designing the code. First, you need to declare and initialize your variables.
The first line uses the loadStrings() function, which reads through a text file and returns a String array where each element in the array is a line in the file. Of course, you'll need to change the filename to fit your file.
Your code uses a variable called current_frame, which is a very good idea, but I've renamed it to currentFrame to fit the java coding convention. We'll start at zero, and later on our code will increment it on every frame display. This variable will tell us where we are in the subtitle sequence and which message should be displayed (if any).
Because the information for what frame each subtitle starts and ends on is encoded in a string, it's a bit tricky to incorporate it into the code. For now, let's just create some variables that represent when the "current" subtitle-- the subtitle that we're either currently displaying or will be displaying next-- starts and ends. We'll also create an index to keep track of which element in the subtitles array is the "current" subtitle. These variables all start at -1, which may seem a bit odd. Whereas we initialized currentFrame to 0, these don't really have a real "initial" value, at least not for now. If we chose 0, then that's not really true, because the first subtitle may not (probably doesn't) begin and end at frame 0, and any other positive number doesn't make much sense. -1 is often used as a dummy index that will be replaced before the variable actually gets used, so we'll do that here, too.
Now for the final variable: currentSubtitle. The immediate thought would be to have this be a plain String, not a String array. However, because each subtitle may need to be split on the pipe (|) symbols, each subtitle may actually represent several lines of text, so we'll create an array just to be safe. It's possible that some subtitles may be a single-element array, but that's fine.
Now for the hard part!
Presumably, your code will have some sort of loop in it, where on each iteration the pertinent video frame is drawn to the screen and (if the conditions are met), the subtitle is drawn over top of it. I've left out the video portion, as that's not part of your question.
Before we do anything else, we need to remember that some of our variables don't have real values yet-- all those -1s from before need to be set to something. The basic logic of the drawing loop is 1) figure out if a subtitle needs to be drawn, and if so, draw it, and 2) figure out if the "current" subtitle needs to be moved to the next one in the array. Let's do #2 first, because on the first time through the loop, we don't know anything about it yet! The criterion (in general) for moving to the next subtitle is if we're past the end of the current one : currentFrame > endFrame. If that is true, then we need to shift all of our variables to the next subtitle. subtitleIndex is easy, we just add one and done. The rest are... not as easy. I know it looks disgusting, but I'll talk about that at the end so as to not break the flow. Skip ahead to the bottom if you just can't wait :)
After (if necessary) changing all of the variables so that they're relevant to the current subtitle, we need to do some actual displaying. The second if statement checks to see if we're "inside" the frame-boundaries of the current subtitle. Because the currentSubtitle variable can either refer to the subtitle that needs to be displayed RIGHT NOW, or merely just the next one in the sequence, we need to do some checking to determine which one it is for this frame. That's the second if statement-- if we're past the start and before the end, then we should be displaying the subtitle! Recall that our currentSubtitle variable is an array, so we can't just display it directly. We'll need to loop through it and display each element on a separate line. You mentioned the text() command, so I won't go too in depth here. The tricky bit is the y-coordinate of the text, since it's supposed to be on multiple lines. We want the first element to be above the second, which is above the third, etc. To do that, we'll have the y-coordinate depend on which element we're on, marked by i. We can scale the difference between lines by changing the value of fontSize; that'll just be up to your taste. Know that the number you set it to will be equal to the height of a line in pixels.
Now for the messy bit that I didn't want to explain above. This code depends on String's split() method, which is performed on the string that you want split and takes a string as a parameter that instructs it how to split the string-- a regex. To get the startFrame out of a subtitle line in the file, we need to split it along the curly braces, because those are the dividers between the numbers. First, we'll split the string everywhere that "}{" occurs-- right after the first number (and right before the second). Because split() returns an array, we can reference a single string from it using an index between square braces. We know that the first number will be in the first string return by splitting on "}{", so we'll use index 0. This will return (for example) "{1234", because split() removes the thing you're splitting on. Now we need to just take the substring that occurs after the first character, convert it to an int using int(), and we're done!
For the second number, we can take a similar approach. Let's split on "}{" again, only we'll take the second (index 1) element in the returned array this time. Now, we have something like "9331}Those swings are dang...", which we can split again on "}", choose the first string of that array, convert to int, and we're done! In both of these cases, we're using subtitles[subtitleIndex] as the original String, which represents the raw input of the file that we loaded using loadStrings() at the beginning. Note that during all this splitting, the original string in subtitles is never changed-- split(), substring(), etc only return new sequences and don't modify the string you called it on.
I'll leave it to you to figure out how the last line in that sequence works :)
Finally, you'll see that there are a bunch of backslashes cluttering up the split() calls. This is because split() takes in a regex, not a simple string. Regexs use a lot of special notation which I won't get into here, but if you just passed split() something like "}{", it would try to interpret it and it would not behave as expected. You need to escape the characters, telling split() that you don't want them to be interpreted as special and you just want the characters themselves. To do that, you use a backlash before any character that needs to be escaped. However, the backslash itself is yet another special character, so you need to escape it, too! This results in stuff like "\\{" -- the first backslash escapes the second one, which escapes whatever the third character is. Note that the | character also needs to be escaped.
Sorry for the wall of text! It's nice to see questions asked intelligently and politely, so I thought I'd give a good answer in return.

Does Sublime Text 2 have the ability to region code similar to Visual Studio?

In Visual Studio you can minimize huge chunks of code using regions; they essentially just surround the code and minimize it in the window.
Does Sublime have a feature similar to this?
By default, you can select some code the go to Edit > Code Folding > Fold. There are tons of plugins that leverage the code-folding api for more options.
There's a request on the official site to "ask for features" here.
But apparently:
FYI, Jon has stated that this is not possible in the current
implementation of the editor control. Looks like we're waiting till V3
guys.
Jon being the programmer behind Sublime Text 2.
There might be a way to fake it by creating a plugin that looks for markers and removes the code region in between the markers, but it probably wouldn't look good. With the current API, it's probably your best bet!
By the way, there is some code folding in Sublime Text, if you hover your mouse next to the line number, you will see some arrows appearing when you can fold / unfold.
I ended up using custom comment tags, indented one level less than the code I want to fold. It doesn't look best, though it serves its purpose.
class Foobar {
// ...some code
// <fold
function foo() {
}
function bar() {
}
// </fold
// more code...
}
This (at the moment) folds to:
class Foobar {
// ...some code
// <fold[...]
// </fold
// more code...
}
Having a native ST2 support for this would be nice.
This looks what you are looking for. You can define tags for #region and #endregion for each language, or a generic tag for all of them.
If you are obsessed with intendation, this solution may make you uncomfortable but here it is, once upon a time while I had been writing a semi-complex jQuery plugin I've had constants, variables, private and public functions sections and foldings like so;
;(function($, undefined, window) {...
/* Consts */
var FOO = "BAR";
/* Variables */
var m_Foo = "bar";
/* Functions */
/* Public Functions */
function foo() {...}
function bar() {...}
/* Private Functions */
function _foo() {...}
function _bar() {...}
})(jQuery, window);
As you can see it is all about intendation. Sections can be folded; Consts, Variables, Functions. And also inside Functions section, Public Functions and Private Functions are both can be folded.
You can also use one line comment (//) to name your fold. So the idea underneath that is simple; ST2 thinks that the more intended lines belongs to first less-intended comment above them, like C/C++ compilers how handle brackets as own unique code blocks.
To fold the code select the code and press
ctrl + shift + [
To unfold the code put the cursor there and press
ctrl + shift + ]
I think that like myself, the OP has come to appreciate a little-known feature in VS called regions that many equate to code-folding, but is FAR more powerful and above, Dio Phung provided the answer that I wanted, and I suspect the OP wanted, but he didn't share as an answer so here it is.
The difference between "code-folding" as it's provided in Sublime Text is that it's based on code/compiler syntax while "regions" and what this plugin does, allow you infinitely more freedom, though it's a freedom that's more or less dependant on the code you're working with to begin with (deeply nested, or properly modularized).
If you are on Sublime Text 3, here is a plugin that can do it :
github.com/jamalsenouci/sublimetext-syntaxfold – Dio Phung
In languages which support 3 types of comments (e.g. PHP) I use the hashtag comment for regions, as shown in the other answers. It's also good for keeping track of what's being done
# default options
$a = 3;
$b = 'bob';
$old_code = 1;
# bugfix #130
$result = magic_function($data);
fix_stuff($result);
$old_code = $result;
Otherwise use triple slash ///, or //# etc.
In sublime text, it works like this, it shades the lines you want to collapse and presses (Control + Shift +?)
I have the most recent version of sublimetext.

Is there a shortcut to swap/reorder parameters in visual studio IDE?

I have a common issue when working with code in the IDE:
string.Concat("foo", "bar");
and I need to change it to:
string.Concat("bar", "foo");
Often I have several of these that need to be swapped at once. I would like to avoid all the typing. Is there a way to automate this? Either a shortcut or some sort of macro would be great if I knew where to start.
Edit: changed to string.Concat to show that you can't always modify the method signature. I am only looking to change the order of the params in the method call, and nothing else.
<Ctrl> + <Shift> + <t> will transpose two words, so it would work in your case. Unfortunately I don't see this working (without multiple presses) for functions with larger parameter lists...
I had a lot of code with this function:
SetInt(comboBox1.Value + 1, "paramName", ...
SetInt(comboBoxOther.Value, "paramName", ...
And I needed to swap only the first two parameters;
I ended up using some text editor with regular expression management (like Scite), and using this one saved me hours:
Find: SetInt(\([.a-z0-9]+[ + 1]*\), \("[a-z0-9]+"\)
Replace: SetInt(\2, \1

Invert assignment direction in Visual Studio [duplicate]

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.

Resources