Bite my bytes

What I learn by day I blog at night.

  Home :: Contact :: Syndication  
  776 Posts :: 3633 Comments :: 235 Trackbacks

Search

Recent Comments.

Recent Posts

Most popular posts
in last 180 days

Categories

My Projects

Archives

Stuff


Copyright © by David Vidmar
 
Contact me!
 
LinkedIn Profile
 
 

Let's say you are writing a Visual Studio add-in that does some stuff with selected text, for example string literals in the code.

It would be very user friendly if the user could just click inside that string literal and add-in would figure it out and select a complete string.

before & after

Well, that's just what I had in mind the other day, but I had a hard time finding a code that would do that. It's rare these days that you don't find a code snippet that can speed up your development.

I wrote it myself and this is what I did. I hope I save someone some time with it...

 

Document document = _applicationObject.ActiveDocument;
TextSelection selection = (TextSelection)document.Selection;
TextPoint cursorTextPoint = selection.ActivePoint;                   
 
EditPoint startPoint;
EditPoint endPoint;
 
if (selection.Text.Length > 0)
{
    // some text is selected
    startPoint = selection.TopPoint.CreateEditPoint();
    endPoint = selection.BottomPoint.CreateEditPoint();
    // lets move one char left so we can inspect last character
    endPoint.CharLeft(1);
}
else
{
    // nothing is selected
    startPoint = cursorTextPoint.CreateEditPoint();
    endPoint = cursorTextPoint.CreateEditPoint();
}
 
string stopChar = "\"";
// move left selection margin to stopChar or start of line
while (startPoint.GetText(1) != stopChar && !startPoint.AtStartOfLine)
{
    startPoint.CharLeft(1);                       
}
 
// move right selection margin to stopChar or end of line
while (endPoint.GetText(1) != stopChar && !endPoint.AtEndOfLine)
{
    endPoint.CharRight(1);
}
// compensate for last character
if (!endPoint.AtEndOfLine) endPoint.CharRight(1);
 
// do we have a valid selection?
if (!startPoint.AtStartOfLine && !endPoint.AtEndOfLine)
{
    string selectedText = startPoint.GetText(endPoint);
 
    // do stuff with selected text
    // you can replace selected text like this
    // startPoint.ReplaceText(endPoint, "fresh text");
    }
}
else
{
    MessageBox.Show("Invalid selection!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Technorati tags: , , ,
Posted on Wednesday, March 05, 2008 12:03 AM | Filed under: Developement |

 

Feedback

# re: Extending Visual Studio - How to select complete string around the caret 4/3/2008 3:38 PM Igor
Excellent snippet. But ctrl+w still rocks.

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 3 and 7 and type the answer here: