22 January 2008

Visual studio macro to remove double spaced lines

If you paste code into the MSDN forums straight from Visual Studio 2005, and then copy it back out and paste it in then you get double spaced lines. This is tedious as you often have to remove them to get the code to work.
To fix it, posters can use a Macro to format the code as HTML: Coding Horror Copying Visual Studio Code Snippets to the Clipboard as HTML.
If you want to strip the spaces from code you have pasted in then you can use a macro. I'll copy his ^^ instructions:

Here's how to get started with this macro

  1. go to Tools - Macros - IDE
  2. create a new Module named "DeDoubleSpace" under "MyMacros"
  3. Paste code into the module
  4. save and close the macro IDE window
  5. go to Tools - Macros - Macro Explorer
  6. The new macros will be under "DeDoubleSpace"; select the messy text and double click the macro.
Imports EnvDTE Imports System Imports System.Collections.Generic Imports System.IO Imports System.Text Public Module DeDoubleSpace ' Remove double spaced lines from the selected text. Public Sub SelectedText() Dim textSelection1 As TextSelection = DirectCast(DTE.ActiveDocument.Selection, TextSelection) Dim rawText As String = textSelection1.Text Dim lines As New List(Of String) Using sr As New StringReader(rawText) lines = New List(Of String) Do While sr.Peek > -1 lines.Add(sr.ReadLine()) Loop End Using If lines.Count < 3 Then Exit Sub ' Find the first bit of text. Dim indexOfFirstLineWithText As Integer = 0 Dim done As Boolean = False Do If lines(indexOfFirstLineWithText) <> "" Then done = True Else indexOfFirstLineWithText += 1 End If Loop Until done Or indexOfFirstLineWithText = lines.Count ' Is the first line with text an odd or even line? Dim even As Boolean = (indexOfFirstLineWithText Mod 2 = 0) ' If it is an even line, then check if all odd lines are blank ' and vice versa. Dim allBlank As Boolean = True ' prove wrong Dim index As Integer = IIf(even, 1, 0) Do If lines(index) <> "" Then allBlank = False Else index += 2 End If Loop Until Not allBlank OrElse index > lines.Count - 1 If allBlank = False Then Exit Sub ' Create new text Dim sb As New StringBuilder Dim i As Integer For i = IIf(even, 0, 1) To lines.Count - 3 Step 2 sb.AppendLine(lines(i)) Next sb.Append(lines(i)) ' Alter the selection. textSelection1.Delete() textSelection1.Insert(sb.ToString) End Sub End Module

No comments:

Post a comment