Align Leftmost Macros, Easy Column-Aligned Formatting for (Almost) Everything

Environment: MSVC 6.x Macro

The following code is a set of Microsoft Visual Studio (MSVC6) macros for formatting code. These macros allow things to be aligned to the same column. It's very useful for aligning equals signs, and so forth. These allow your code to be quickly formatted from this:

int number = 0; // zero
float foo = 0.001; // almost zero
bool state; // not initialized

SetFooBar1
(float f) { FooBar = f; }
SetK1(int Kermite) { K1 = Kermite; }
SetAllowDown(bool b) { AllowDown = b; }

to this:

int number = 0;     // zero
float foo = 0.001; // almost zero
bool state; // not initialized


SetFooBar1(float f) { FooBar = f; }
SetK1(int Kermite) { K1 = Kermite; }
SetAllowDown(bool b) { AllowDown = b; }

Just select the lines of text to modify, and press a key binding, such as ALT-LEFTBRACKET. Don't forget to use ALT-MouseDrag for column editing mode selections—this can prune any unwanted white space. And who could forget ALT-F8 for Auto formatting?

This revised version correctly handles a work environment with TABS. Any existing tabs to the left of the string to align are preserved. Correct spacing for anything to the right is preserved by converting those tabs to spaces.

Source Code

'________________________________________________________________
'FILE DESCRIPTION: Custom Macros for MSVC
'AUTHOR: Vincent Scheib, www.scheib.net (c) 2001
'
' AlignByStr, and associated helper functions:
'    These macros allow all characters of a certain type to be
'    aligned in the current selection of lines.
'
'    E.G. align all left most equal signs to be at the same column:
'       int a = 3;                         int a     = 3;
'       float bee = 34.0;     becomes:     float bee = 34.0;
'       char *str;                         char *str;
'       int cc = d = 5;                    int cc    = d = 5;
'
'    The general macro AlignStr prompts for what to align
'      (I bound this to ALT ?)
'
'    The numerous helper functions can be bound to directly to 
'    the keys they align, such as ALT [  ALT /  and  ALT = 
'
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'_________________________________________________________________

'_________________________________________________________________
Sub AlignStr
'DESCRIPTION: Select lines, run macro to enter a string, and all
'leftmost instances will be aligned.
  str = InputBox("Enter string to align")
  if (str<>"") then AlignByStr str
End Sub

'_________________________________________________________________
Sub AlignBackSlash ()
'DESCRIPTION: Aligns leftmost  '\' to a common column.
  AlignByStr("\")
End Sub

'_________________________________________________________________
Sub AlignColon ()
'DESCRIPTION: Aligns leftmost  ':' to a common column.
  AlignByStr(":")
End Sub

'_________________________________________________________________
Sub AlignComments ()
'DESCRIPTION: Aligns leftmost  '//' to a common column.
  AlignByStr("//")
End Sub

'_________________________________________________________________
Sub AlignComma ()
'DESCRIPTION: Aligns leftmost  ',' to a common column.
  AlignByStr(",")
End Sub

'_________________________________________________________________
Sub AlignEquals ()
'DESCRIPTION: Aligns leftmost '=' signs to a common column.
  AlignByStr("=")
End Sub

'_________________________________________________________________
Sub AlignLeftBracket ()
'DESCRIPTION: Aligns leftmost '[' to a common column.
  AlignByStr("[")
End Sub

'_________________________________________________________________
Sub AlignLeftCurly ()
'DESCRIPTION: Aligns leftmost '{' to a common column.
  AlignByStr("{")
End Sub

'_________________________________________________________________
Sub AlignLeftParenthesis ()
'DESCRIPTION: Aligns leftmost '(' to a common column.
  AlignByStr("(")
End Sub

'_________________________________________________________________
Sub AlignMinus ()
'DESCRIPTION: Aligns leftmost '-' to a common column.
  AlignByStr("-")
End Sub

'_________________________________________________________________
Sub AlignPeriod ()
'DESCRIPTION: Aligns leftmost '.' to a common column.
  AlignByStr(".")
End Sub

'_________________________________________________________________
Sub AlignPlus ()
'DESCRIPTION: Aligns leftmost '+' to a common column.
  AlignByStr("+")
End Sub

'_________________________________________________________________
Sub AlignQuote ()
'DESCRIPTION: Aligns leftmost " to a common column.
  AlignByStr("""")
End Sub

'_________________________________________________________________
Sub AlignRightBracket ()
'DESCRIPTION: Aligns leftmost ']' to a common column.
  AlignByStr("]")
End Sub

'_________________________________________________________________
Sub AlignRightCurly ()
'DESCRIPTION: Aligns leftmost '}' to a common column.
  AlignByStr("}")
End Sub

'_________________________________________________________________
Sub AlignRightParenthesis ()
'DESCRIPTION: Aligns leftmost ')' to a common column.
  AlignByStr(")")
End Sub

'_________________________________________________________________
Sub AlignSemiColon ()
'DESCRIPTION: Aligns leftmost ';' to a common column.
  AlignByStr(";")
End Sub

'_________________________________________________________________
Sub AlignUnderscore ()
'DESCRIPTION: Aligns leftmost '_' signs to a common column.
  AlignByStr("_")
End Sub






'_________________________________________________________________
Sub AlignByStr (AlignStr)
'DESCRIPTION: Aligns leftmost (AlignStr) to a common column.
'AlignStr is most likely a character, such as / or = or {
'By Vince Scheib

  'Adjust the number of spaces a tab equals here!
  Tab = " "              'a Tab character
  TabSpaces = "    "     'The spaces to replace it

  Dim win
  set win = ActiveWindow
  if win.type <> "Text" Then
    MsgBox "This macro can only be run when a text editor window _
            is active."
  else
    StartLine = ActiveDocument.Selection.TopLine
    EndLine = ActiveDocument.Selection.BottomLine
    If EndLine < StartLine Then
      Temp = StartLine
      StartLine = EndLine
      EndLine = Temp
    End If

    If EndLine = StartLine Then
      MsgBox "This macro is to be used on a selection of _
              several lines."

    Else

      RightMostColumn = 1

      'Provide a recognizable undo point
      FlashForUndo = ActiveDocument.Selection
      ActiveDocument.Selection = ""
      ActiveDocument.Selection = FlashForUndo
 
      'Find the maximum column used
      For i = StartLine To EndLine
        ActiveDocument.Selection.GoToLine i
        ActiveDocument.Selection.SelectLine

        'Get a line with spaces, temporarily save the version
        'with tabs (untabify only works on
        'ActiveDocument.Selection)
        Line_Tabs = ActiveDocument.Selection
        ActiveDocument.Selection.Untabify
        Line_Spaces = ActiveDocument.Selection
        ActiveDocument.Selection = Line_Tabs

        if Instr(LineWithSpaces, AlignStr) > RightMostColumn Then
          RightMostColumn = Instr(LineWithSpaces, AlignStr)
        end if
      Next

      'Push everything out to maximum column
      For i = StartLine To EndLine

        ActiveDocument.Selection.GoToLine i
        ActiveDocument.Selection.SelectLine

        if Instr(ActiveDocument.Selection, AlignStr) <> 0 Then
          'Get a line with spaces and one with tabs
          Line_Tabs = ActiveDocument.Selection
          ActiveDocument.Selection.Untabify
          Line_Spaces = ActiveDocument.Selection
          
          'Divide Line into two
          NewLineBegin_Tabs = Left(Line_Tabs, Instr(Line_Tabs, _
                                   AlignStr)-1) 
          NewLineEnd_Tabs = Right(Line_Tabs, Len(Line_Tabs) _
                          - Instr(Line_Tabs, AlignStr) + 1)
          
          NewLineBegin_Spaces = Left(Line_Spaces, _
                                     Instr(Line_Spaces, _
                                           AlignStr)-1)
          NewLineEnd_Spaces = Right(Line_Spaces, Len(Line_Spaces) _
                            - Instr(Line_Spaces, AlignStr) + 1)

          NewLineFillSpaces = ""

          Do While Len(NewLineFillSpaces) < (RightMostColumn-_
                       Len(NewLineBegin_Spaces)-1)
            NewLineFillSpaces = NewLineFillSpaces + " "
          Loop

          'Preserve Tabs on left, everything else is spaces
          NewLine = NewLineBegin_Tabs + NewLineFillSpaces _
                                      + NewLineEnd_Spaces
          ActiveDocument.Selection = NewLine
        End If
      Next

    End If
  End If
End Sub


Comments

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds