Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Extensibility: Move to line in a TextDocument

I am in the focus of a ToolWindow. By doing dobleclick on a TreeView node, the cursor has to move to a particular line within the opened source code document. I solved this issue by calling the Edit.GoTo Line command like this:

var commandName = "Edit.GoTo " + lineNumber;
_dte.ExecuteCommand(commandName);

However I am not quite convinient with that as I lose the focus of the toolwindow. Is there another way to move to a line by using the Automation API?

like image 708
Oliver Vogel Avatar asked May 31 '11 11:05

Oliver Vogel


1 Answers

Use the IViewScroller.EnsureSpanVisible(SnapshotSpan span, EnsureSpanVisibleOptions options)

To create a span, use:

var lines = view.VisualSnapshot.Lines;

var startLine = lines.FirstOrDefault(a => a.LineNumber == fromLine - 1);
var endLine = lines.FirstOrDefault(a => a.LineNumber == toLine - 1);

if (startLine == null || endLine == null)
    return;

var startPosition = startLine.Start;
var endPosition = endLine.Start;

var span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(startPosition, endPosition));

And to scroll to the span:

layer.TextView.ViewScroller.EnsureSpanVisible(span,
    EnsureSpanVisibleOptions.AlwaysCenter);

Where view is the IWpfTextView provided by your adorner (IWpfTextViewCreationListener)

like image 96
Claus Jørgensen Avatar answered Oct 14 '22 11:10

Claus Jørgensen