Saturday, August 27, 2011

How to prevent seeing “\ No newline at end of file” when using Git with Visual Studio

 

1. In Visual Studio menu, select Tools > Macros > Macros IDE

2. Select the Class View tab. Under My Macros, double click the EnvironmentEvents node.

3. select DocumentEvents from the dropdown list on the left, then select DocumentSaved from the dropdown list on the right. This will generate a blank event handler.

4. Paste the following code into the blank  event handler.

Private Sub DocumentEvents_DocumentSaved(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
        '
        ' This handler will add a newline to end of file if it doesn't already have one.
        '
        Dim textSelection As EnvDTE.TextSelection

        textSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)

        Dim originalLine As Integer
        originalLine = textSelection.AnchorPoint.Line
        Dim originalOffset As Integer
        originalOffset = textSelection.AnchorPoint.LineCharOffset
        Dim viewTop As EnvDTE.TextPoint
        viewTop = textSelection.TextPane.StartPoint

        textSelection.EndOfDocument(False)
        Dim pt As VirtualPoint
        pt = textSelection.BottomPoint()

        textSelection.GotoLine(pt.Line, True)
        If textSelection.Text.Length <> 0 Then
            textSelection.Text = textSelection.Text & vbCrLf
            DTE.ActiveDocument.Save()
        End If
        textSelection.MoveToLineAndOffset(originalLine, originalOffset, False)
        textSelection.TextPane.TryToShow(viewTop, vsPaneShowHow.vsPaneShowTop)
    End Sub

5. Save the macro

From now on all the files saved through Visual Studio will be appended with a new line to avoid the error message in the Git source control.

No comments: