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
- Public Sub formatDocWithAStyle()
- Dim fileName As String
- Dim textDocument As TextDocument
- Dim startPoint As EnvDTE.EditPoint
- Dim endPoint As EnvDTE.EditPoint
- Dim text As String
- Dim shellCmd As String
- Dim procId As Integer
- If DTE.ActiveDocument Is Nothing Then
- Return
- End If
- fileName = Environ$(“TEMP”) & “\formattedCode”
- shellCmd = “”"” & Environ$(“HOMEPATH”) & “\Downloads\AStyle\bin\AStyle” & “”"” & ” -A4Uxpfn “ & “”"” & fileName & “”"”
- textDocument = DTE.ActiveDocument.Object
- startPoint = textDocument.StartPoint.CreateEditPoint
- endPoint = textDocument.EndPoint.CreateEditPoint
- text = startPoint.GetText(endPoint)
- My.Computer.FileSystem.WriteAllText(fileName, text, False)
- procId = Shell(shellCmd, AppWinStyle.Hide, True, 30000)
- If procId = 0 Then
- text = My.Computer.FileSystem.ReadAllText(fileName)
- startPoint.ReplaceText(endPoint, text, vsEPReplaceTextOptions.vsEPReplaceTextTabsSpaces)
- End If
- End Sub