Programing

Visual Studio 2008에서 후행 공백을 자동으로 제거하는 방법은 무엇입니까?

crosscheck 2020. 7. 14. 08:24
반응형

Visual Studio 2008에서 후행 공백을 자동으로 제거하는 방법은 무엇입니까?


파일을 저장할 때 각 줄의 끝에 공백 문자를 자동으로 제거하도록 Visual Studio 2008을 구성 할 수 있습니까? 내장 옵션이없는 것 같으므로이를 수행 할 수있는 확장이 있습니까?


CodeMaid는 매우 인기있는 Visual Studio 확장이며 다른 유용한 정리와 함께 자동으로 수행됩니다.

저장시 파일을 정리하도록 설정했는데 이것이 기본값이라고 생각합니다.


정규식을 사용하여 찾기 / 바꾸기

찾기 및 대화 교체, 확장 옵션을 찾아 확인 사용을 선택, 정규 표현식을

무엇을 찾기 : " :Zs#$"

다음으로 대체 : ""

모두 바꾸기를 클릭 하십시오.

다른 편집기 ( 일반 정규식 구문 분석기)에서 " :Zs#$"는 " \s*$"입니다.


저장 후이를 실행하기 위해 실행되는 매크로를 작성할 수 있습니다.

매크로의 EnvironmentEvents 모듈에 다음을 추가하십시오.

Private saved As Boolean = False
Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
                                         Handles DocumentEvents.DocumentSaved
    If Not saved Then
        Try
            DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                                 "\t", _
                                 vsFindOptions.vsFindOptionsRegularExpression, _
                                 "  ", _
                                 vsFindTarget.vsFindTargetCurrentDocument, , , _
                                 vsFindResultsLocation.vsFindResultsNone)

            ' Remove all the trailing whitespaces.
            DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                                 ":Zs+$", _
                                 vsFindOptions.vsFindOptionsRegularExpression, _
                                 String.Empty, _
                                 vsFindTarget.vsFindTargetCurrentDocument, , , _
                                 vsFindResultsLocation.vsFindResultsNone)

            saved = True
            document.Save()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
        End Try
    Else
        saved = False
    End If
End Sub

나는 지금 아무런 문제없이 이것을 오랫동안 사용 해왔다. 매크로를 만들지 않았지만 빠른 Google 검색으로 찾을 수있는 ace_guidelines.vsmacros의 매크로에서 수정했습니다.


저장하기 전에 자동 서식 바로 가기 CTRL+ K+ 를 사용할 수 있습니다 D.


다음 세 가지 동작으로 쉽게 수행 할 수 있습니다.

  • Ctrl+ A(모든 텍스트를 선택하십시오)

  • 편집-> 고급-> 수평 공백 삭제

  • 편집-> 고급-> 형식 선택

몇 초 기다렸다가 완료하십시오.

그것은의 Ctrl+ Z의 경우 뭔가 수는 '잘못했다.


이미 주어진 모든 답변에서 요소를 취하면 다음과 같은 코드가 있습니다. (주로 C ++ 코드를 작성하지만 필요에 따라 다른 파일 확장자를 쉽게 확인할 수 있습니다.)

기여한 모든 분들께 감사드립니다!

Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
    Handles DocumentEvents.DocumentSaved
    Dim fileName As String
    Dim result As vsFindResult

    Try
        fileName = document.Name.ToLower()

        If fileName.EndsWith(".cs") _
        Or fileName.EndsWith(".cpp") _
        Or fileName.EndsWith(".c") _
        Or fileName.EndsWith(".h") Then
            ' Remove trailing whitespace
            result = DTE.Find.FindReplace( _
                vsFindAction.vsFindActionReplaceAll, _
                "{:b}+$", _
                vsFindOptions.vsFindOptionsRegularExpression, _
                String.Empty, _
                vsFindTarget.vsFindTargetFiles, _
                document.FullName, _
                "", _
                vsFindResultsLocation.vsFindResultsNone)

            If result = vsFindResult.vsFindResultReplaced Then
                ' Triggers DocumentEvents_DocumentSaved event again
                document.Save()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
    End Try
End Sub

정규식 검색을 사용하여 공백 제거 및 주석 다시 작성에 설명 된대로 매크로를 사용할 수 있습니다.


I am using VWD 2010 Express where macros are not supported, unfortunately. So I just do copy/paste into Notepad++ top left menu Edit > Blank Operations > Trim Trailing Space there are other related operations available too. Then copy/paste back into Visual Studio.

One can also use NetBeans instead of Notepad++, which has "Remove trailing spaces" under the "Source" menu.


Unless this is a one-person project, don't do it. It's got to be trivial to diff your local files against your source code repository, and clearing whitespace would change lines you don't need to change. I totally understand; I love to get my whitespace all uniform – but this is something you should give up for the sake of cleaner collaboration.


I think that the Jeff Muir version could be a little improved if it only trims source code files (in my case C#, but is easy to add more extensions). Also I added a check to ensure that the document window is visible because some situations without that check show me strange errors (LINQ to SQL files '*.dbml', for example).

Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) Handles DocumentEvents.DocumentSaved
    Dim result As vsFindResult
    Try
        If (document.ActiveWindow Is Nothing) Then
            Return
        End If
        If (document.Name.ToLower().EndsWith(".cs")) Then
            document.Activate()
            result = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, ":Zs+$", vsFindOptions.vsFindOptionsRegularExpression, String.Empty, vsFindTarget.vsFindTargetCurrentDocument, , , vsFindResultsLocation.vsFindResultsNone)
            If result = vsFindResult.vsFindResultReplaced Then
                document.Save()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message & Chr(13) & "Document: " & document.FullName, MsgBoxStyle.OkOnly, "Trim White Space exception")
    End Try
End Sub

I personally love the Trailing Whitespace Visualizer Visual Studio extension which has support back through Visual Studio 2012.


I think I have a version of this macro that won't crash VS2010 on refactor, and also won't hang the IDE when saving non-text files. Try this:

Private Sub DocumentEvents_DocumentSaved( _
    ByVal document As EnvDTE.Document) _
    Handles DocumentEvents.DocumentSaved
    ' See if we're saving a text file
    Dim textDocument As EnvDTE.TextDocument = _
        TryCast(document.Object(), EnvDTE.TextDocument)

    If textDocument IsNot Nothing Then
        ' Perform search/replace on the text document directly
        ' Convert tabs to spaces
        Dim convertedTabs = textDocument.ReplacePattern("\t", "    ", _
            vsFindOptions.vsFindOptionsRegularExpression)

        ' Remove trailing whitespace from each line
        Dim removedTrailingWS = textDocument.ReplacePattern(":Zs+$", "", _
            vsFindOptions.vsFindOptionsRegularExpression)

        ' Re-save the document if either replace was successful
        ' (NOTE: Should recurse only once; the searches will fail next time)
        If convertedTabs Or removedTrailingWS Then
            document.Save()
        End If
    End If
End Sub

I use ArtisticStyle (C++) to do this and also reformat my code. However, I had to add this as an external tool and you need to trigger it yourself so you might not like it.

However, I find it excellent that I can reformat code in more custom way (for example, multiline function parameters) that I can pay the price of running it manually. The tool is free.


Building on Dyaus's answer and a regular expression from a connect report, here's a macro that handles save all, doesn't replace tabs with spaces, and doesn't require a static variable. Its possible downside? It seems a little slow, perhaps due to multiple calls to FindReplace.

Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
                                         Handles DocumentEvents.DocumentSaved
    Try
        ' Remove all the trailing whitespaces.
        If vsFindResult.vsFindResultReplaced = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                             "{:b}+$", _
                             vsFindOptions.vsFindOptionsRegularExpression, _
                             String.Empty, _
                             vsFindTarget.vsFindTargetFiles, _
                             document.FullName, , _
                             vsFindResultsLocation.vsFindResultsNone) Then
            document.Save()
        End If
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
    End Try
End Sub

For anyone else trying to use this in a Visual Studio 2012 add-in, the regular expression I ended up using is [ \t]+(?=\r?$) (don't forget to escape the backslashes if necessary). I arrived here after several futile attempts to fix the problems with a raw conversion of {:b}+$ failing to match the carriage return.


This is a really good example of how to remove trailing whitespace. There are a few things that I would change based on what I discovered using this macro. First of all, the macro automatically converts tabs to spaces. This is not always desirable and could lead to making things worse for people that love tabs (typically Linux-based). The tab problem is not really the same as the extra whitespace problem anyways. Secondly, the macro assumes only one file is being saved at once. If you save multiple files at once, it will not correctly remove the whitespace. The reason is simple. The current document is considered the document you can see. Third, it does no error checking on the find results. These results can give better intelligence about what to do next. For example, if no whitespace is found and replaced, there is no need to save the file again. In general, I did not like the need for the global flag for being saved or not. It tends to ask for trouble based on unknown states. I suspect the flag had been added solely to prevent an infinite loop.

    Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
                                         Handles DocumentEvents.DocumentSaved
    Dim result As vsFindResult
    'Dim nameresult As String

    Try
        document.Activate()

        ' Remove all the trailing whitespaces.
        result = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                             ":Zs+$", _
                             vsFindOptions.vsFindOptionsRegularExpression, _
                             String.Empty, _
                             vsFindTarget.vsFindTargetCurrentDocument, , , _
                             vsFindResultsLocation.vsFindResultsNone)

        'nameresult = document.Name & " " & Str$(result)

        'MsgBox(nameresult, , "Filename and result")

        If result = vsFindResult.vsFindResultReplaced Then
            'MsgBox("Document Saved", MsgBoxStyle.OkOnly, "Saved Macro")
            document.Save()
        Else
            'MsgBox("Document Not Saved", MsgBoxStyle.OkOnly, "Saved Macro")
        End If

    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
    End Try

End Sub

I added debug message boxes to help see what was going on. It made it very clear that multiple file save was not working. If you want to play with them, uncomment those lines.

The key difference is using document.Activate() to force the document into the foreground active current document. If the result is 4, that means that the text was replaced. Zero means nothing happened. You will see two saves for every file. The first will replace and the second will do nothing. Potentially there could be trouble if the save cannot write the file but hopefully this event will not get called if that happens.

Before the original script, I was unaware of how the scripting worked in Visual Studio. It is slightly surprising that it uses Visual Basic as the main interface but it works just fine for what it needs to do.


A simple addition is to remove carriage returns during the save.

' Remove all the carriage returns.
result = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
                             "\x000d\x000a", _
                             vsFindOptions.vsFindOptionsRegularExpression, _
                             "\x000a", _
                             vsFindTarget.vsFindTargetCurrentDocument, , , _
                             vsFindResultsLocation.vsFindResultsNone)

The key to this working is changing \x000d\x000a to \x000a. The \x prefix indicates a Unicode pattern. This will automate the process of getting source files ready for Linux systems.

참고URL : https://stackoverflow.com/questions/82971/how-to-automatically-remove-trailing-whitespace-in-visual-studio-2008

반응형