Wired2Code

Just another WordPress.com site

Visual C++ Code Formatting with AStyle

Visual Studio VBA macro to format the current C++/h document using the open source code formatter AStyle. Simply copy the macro to the “Macros->Module1” is Visual Studio, then hookup a hot key to it.

Download AStyle from http://astyle.sourceforge.net/ and extract to a directory (code will look in the download directory off the user’s home directory). Update the shellCmd string variable with any formatting options AStyle should apply (http://astyle.sourceforge.net/astyle.html).

Format string “-A4Uxpfn”
-A4 = stroustrup style
-U  = unpad paren
-x  = delete empty lines
-p  = pad operators
-f  = break blocks
-n  = do not retain backup

Code Snippet
  1. Public Sub formatDocWithAStyle()
  2. Dim fileName As String
  3. Dim textDocument As TextDocument
  4. Dim startPoint As EnvDTE.EditPoint
  5. Dim endPoint As EnvDTE.EditPoint
  6. Dim text As String
  7. Dim shellCmd As String
  8. Dim procId As Integer
  9. If DTE.ActiveDocument Is Nothing Then
  10. Return
  11. End If
  12. fileName = Environ$(“TEMP”) & “\formattedCode”
  13. shellCmd = “””” & Environ$(“HOMEPATH”) & “\Downloads\AStyle\bin\AStyle” & “””” & ” -A4Uxpfn “ & “””” & fileName & “”””
  14. textDocument = DTE.ActiveDocument.Object
  15. startPoint = textDocument.StartPoint.CreateEditPoint
  16. endPoint = textDocument.EndPoint.CreateEditPoint
  17. text = startPoint.GetText(endPoint)
  18. My.Computer.FileSystem.WriteAllText(fileName, text, False)
  19. procId = Shell(shellCmd, AppWinStyle.Hide, True, 30000)
  20. If procId = 0 Then
  21. text = My.Computer.FileSystem.ReadAllText(fileName)
  22. startPoint.ReplaceText(endPoint, text, vsEPReplaceTextOptions.vsEPReplaceTextTabsSpaces)
  23. End If
  24. End Sub

January 23, 2011 Posted by | Code Formatting | , , , , | 1 Comment