Notes on software development (Windows) and computer system administration.

2005-08-29

Visual Studio Macros - Header/Source switcher

This code grabs the active file's name, lops off the extension (e.g. '.cpp'), replaces it with the corresponding extension (e.g. '.h'), and attempts to load the new filename.

This should work with .c, .cpp, .cc, .h, .hh, and .hpp files.

Option Strict Off
Option Explicit Off

Public Module HeaderSourceSwitcher
'--------------------------------------------------------------------------
' Jeff Fitzsimons -- Minimal header/source switcher.
'--------------------------------------------------------------------------
Sub DoSwitch()
Try
' Make sure there's an active document...
If (DTE.ActiveDocument Is Nothing) Then
MsgBox("No active document.", MsgBoxStyle.Exclamation, "HeaderSourceSwitcher")
Return
End If

' Get the name of the active document...
Dim name As String
name = DTE.ActiveDocument.FullName()

' Substitute file extensions...
If name.EndsWith(".cpp") Then
name = name.Replace(".cpp", ".h")
' No matching .h file, try with .hpp...
If Not System.IO.File.Exists(name) Then
name = name.Replace(".h", ".hpp")
End If
ElseIf name.EndsWith(".c") Then
name = name.Replace(".c", ".h")
ElseIf name.EndsWith(".hpp") Then
name = name.Replace(".hpp", ".cpp")
ElseIf name.EndsWith(".h") Then
name = name.Replace(".h", ".cpp")
' No matching .cpp file, try with .c...
If Not System.IO.File.Exists(name) Then
name = name.Replace(".cpp", ".c")
End If
ElseIf name.EndsWith(".cc") Then
name = name.Replace(".cc", ".hh")
ElseIf name.EndsWith(".hh") Then
name = name.Replace(".hh", ".cc")
End If

' If the file exists, open it. Otherwise show an error.
If (System.IO.File.Exists(name)) Then
DTE.ItemOperations.OpenFile(name)
Else
MsgBox("Unable to find a matching file.", MsgBoxStyle.Exclamation, "HeaderSourceSwitcher")
End If
Catch
MsgBox("Unknown exception thrown!")
End Try

End Sub

End Module