Tuesday, July 18, 2006

SmartFormat the entire solution

At work, we recently decided to all use the same c# formatting options in Visual Studio 2005. (Yes, it would be nice to have hooks in the version control package so we each could see the source with our own formatting, but svn doesn't have that.) So, I've been looking for an easy way reformat thousands of files without opening each file manually. I finally gave up looking and cobbled together a quick macro. Here it is.

Let me know if you improve it, ok?

Option Strict Off
Option Explicit Off

Imports EnvDTE
Imports System
Imports System.IO
Imports System.text

Public Module Tools

Sub SmartFormatSolution()
Dim project As Project
Dim projects As Projects = DTE.Solution.Projects()

For Each project In projects
Dim pi As ProjectItems = project.ProjectItems()
If Not (pi Is Nothing) Then
SmartFormatProjectItems(pi, Level + 1)
End If
Next
MsgBox("Reformat Done", MsgBoxStyle.Information)
End Sub

Sub SmartFormatProject()
Dim projects As System.Array = DTE.ActiveSolutionProjects()
If projects.Length > 0 Then
Dim proj As Project = CType(projects.GetValue(0), EnvDTE.Project)
Dim pi As ProjectItems = proj.ProjectItems()
If Not (pi Is Nothing) Then
SmartFormatProjectItems(pi, Level + 1)
End If
Else
MsgBox("No project selected", MsgBoxStyle.Critical)
End If
MsgBox("Reformat Done", MsgBoxStyle.Information)
End Sub

Sub SmartFormatProjectItems(ByVal ProjItems As ProjectItems, ByVal Level As Integer)
Dim ProjItem As ProjectItem
For Each ProjItem In ProjItems
If InStrRev(ProjItem.Name, ".cs") <> 0 Then
Dim ActiveWin As Window = ProjItem.Open(Constants.vsViewKindCode)
ActiveWin.Activate()
Dim txtDoc As TextDocument = DTE.ActiveDocument.Object("TextDocument")
Dim StartPoint As EditPoint = txtDoc.StartPoint.CreateEditPoint
Dim EndPoint As EditPoint = txtDoc.EndPoint.CreateEditPoint
EndPoint.SmartFormat(StartPoint)
ActiveWin.Close(vsSaveChanges.vsSaveChangesYes)
End If
' Recurse if the project item has sub-items...
Dim projitems2 As ProjectItems = ProjItem.ProjectItems()
Dim notsubcoll As Boolean = projitems2 Is Nothing
If Not notsubcoll Then
SmartFormatProjectItems(projitems2, Level + 1)
End If
Next
End Sub

End Module

0 Comments:

Post a Comment

<< Home