I am a keyboard guy. I like to use keyboard shortcuts, I don’t like to waste time with the mouse. Especially when I am writing code. Today, for some stupid reason, I found myself making the mistake of hitting CTRL+HOME and jumping to the top of my source file when in fact I was trying to get to the top of a particular function. I’m not exactly sure why my brain started doing this, but rather than retrain myself, I decided to retrain Visual Studio.
Of course one of the things I love best about VS.NET is it’s incredible extensiblity mechanism. I’m not very skilled with it, but fortunately there are a bunch of sample macros already included. One of which did almost exactly what I wanted — BeginningOfFunction. I wanted to map this macro to CTRL+HOME.
But I also use CTRL+HOME an awful lot when I do want to get to the beginning of the document and I didn’t want to retrain myself there either. So I came up with what I think is a great compromise.
I made some minor modifications to the BeginningOfFunction macro that jumps to the beginning of the current function when you press CTRL+HOME, but if you press it again, it takes you to the beginning of the document. Pretty cool huh? Mapping it was pretty easy too. Below is the new source code of the BeginningOfFunction macro.
Sorry for the code formatting, it was a bitch to even get it this close.
'''
''' BeginningOfFunction moves the caret to the beginning of the containing
''' definition. If it is run twice in succession without any cursor movement,
''' then the cursor will move to the beginning of the document.
'''
Sub BeginningOfFunction()
Dim textSelection As EnvDTE.TextSelection
Dim codeElement As EnvDTE.CodeElement
Dim gotoBeginning As Boolean = True
textSelection = DTE.ActiveWindow.Selection
Try
' See if we are in a function
codeElement = textSelection.ActivePoint.CodeElement(vsCMElement.vsCMElementFunction)
If Not (codeElement Is Nothing) Then
' Get the starting point of the function
Dim functionPoint As TextPoint = codeElement.GetStartPoint(vsCMPart.vsCMPartHeader)
' Only do this if we're not already at the start of the function
' (for example if this is the second CTRL+HOME press)
If Not textSelection.ActivePoint.EqualTo(functionPoint) Then
' Goto start of function
textSelection.MoveToPoint(functionPoint)
gotoBeginning = False
End If
End If
If gotoBeginning Then
' Goto beginning
textSelection.MoveToLineAndOffset(1, 1)
End If
Catch
End Try
End Sub