Search code examples
visual-studio-extensionsvsix

How to get the top/bottom line numbers of MSVC pane


In MSVC, the shortcut Ctrl+Up places the cursor on the top line of the text-editor pane. Likewise, Ctrl+Down places the cursor at the bottom of the pane.

For the purpose of creating a C# VSIX extension, what is the code to get those top and bottom line numbers?

My purpose for this is that I want to create a shortcut that jumps to the vertical center of the pane. My code is currently at a point like so:

        private void JumpVCenter()
        {
            // Clear our current selection when we jump.
            View.Selection.Clear();

            CaretPosition caretPos = View.Caret.Position;
            ITextBuffer buffer     = View.TextBuffer;
            ITextSnapshot snapshot = buffer.CurrentSnapshot;
            SnapshotPoint start    = caretPos.BufferPosition;

            // Code here to get the top/bottom line number of the pane.
            // ...
        }

Solution

  • I didn't find documentation about this. After trying to get it working for a while, I came to a solution that I find satisfactory. This solution seems to generate correct line numbers, even when changing the size of the editor's text at runtime.

    private void JumpVCenter()
    {
        var lineTop = View.TextViewLines.GetTextViewLineContainingYCoordinate(View.ViewportTop);
        var topNum  = lineTop.Start.GetContainingLineNumber() + 1;
    
        var lineBot = View.TextViewLines.GetTextViewLineContainingYCoordinate(View.ViewportBottom);
        var botNum  = lineBot.Start.GetContainingLineNumber();
    }