Devstudio Macros
by Mark Henri


sub AddAllTopStuff
'DESCRIPTION: Add the program name and the revision log to the top of the program
   PushCursor()
	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection = "// " + ActiveDocument.Name
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine
	writeln( "// " )
	ActiveDocument.Selection.StartOfLine dsFirstText

   RevisionLog()
   PopCursor()
end sub

sub HTMLReadyCPPa
'DESCRIPTION: Make the CPP work in an HTML file.
	ActiveDocument.ReplaceText "<", "<"
	ActiveDocument.ReplaceText ">", ">"
	ActiveDocument.ReplaceText "#define new", "#define new", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "#undef", "#undef", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "static", "static", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "#endif", "#endif", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "if", "if", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "else", "else", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "long", "long", dsMatchWord + dsMatchCase

	ActiveDocument.ReplaceText "#ifdef", "#ifdef", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "int", "int", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "class", "class", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "private:", "private:"
	ActiveDocument.ReplaceText "public:", "public:"

	ActiveDocument.ReplaceText "char", "char", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "return", "return", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "for", "for", dsMatchWord + dsMatchCase

	ActiveDocument.ReplaceText "void", "void", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "const", "const", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "bool", "bool", dsMatchWord + dsMatchCase
	ActiveDocument.ReplaceText "using namespace", "using namespace", dsMatchCase
	ActiveDocument.ReplaceText "#include", "#include", dsMatchCase

   ActiveDocument.ReplaceText "const char", "const char", dsMatchCase
end sub


'------------------------------------------------------------------------------
'FILE DESCRIPTION: SAMPLE.DSM is a collection of sample editor macros.
'------------------------------------------------------------------------------

'This routine has many uses if you are trying to determine the type of source 
'	file.
'Return value:  0 Unknown file type
'               1 C-related file, this includes .c, .cpp, .cxx, .h, .hpp, .hxx
'               2 Java-related file, this includes .jav, .java
'               3 ODL-style file, .odl, .idl
'               4 Resource file, .rc, .rc2
'               5 HTML-style file, this includes .html, and .htm
'               6 VBS-style file, .dsm
'               7 Def-style file, .def
'               8 Text, .txt, .asc, .bak
'USE: Pass this function the document that you wish to get information for.
Function FileType (ByVal doc)
	ext = doc.Name
	FileType = 0
	pos = Instr(ext, ".")
	if pos > 0 then
		Do While pos <> 1
			ext = Mid(ext, pos, Len(ext) - pos + 1)
			pos = Instr(ext, ".")
		Loop
		ext = LCase(ext)
	end if
	If ext = ".rc" Or ext = ".rc2" Then
		FileType = 4
   elseif ext = ".txt" or ext = ".asc" or ext = ".bak" then
      FileType = 8
	ElseIf doc.Language = dsCPP Then
		FileType = 1
	ElseIf doc.Language = dsJava Then
		FileType = 2
	ElseIf doc.Language = dsIDL Then
		FileType = 3
	ElseIf doc.Language = dsHTML_IE3 Or doc.Language = dsHTML_RFC1866 Then
		FileType = 5  
	ElseIf doc.Language = dsVBSMacro Then ' 
		FileType = 6  
	ElseIf ext = ".def" Then
		FileType = 7
	Else 
		FileType = 0
	End If 
End Function


'This routine has many uses if you are trying to determine if an identifier
'  is a valid C identifier.
'  These identifiers do not include qualification syntax, for example:
'  foo.bar is not valid
'  foo is valid
'Parameters:    String to test for a valid C identifier.
'Return value:  True: passed parameter is a valid C identifier.
'               False: passed parameter is not a valid C identifier.
Function ValidId(Id)
	ValidId = True

	'Don't permit an empty string
	' (how can you identify nothing with something?)
	if Id = "" then 
	  ValidID = False
	  Exit Function
	End If

	For i = 1 To Len(Id)
	  if Mid(Id, i, 1) < "a" Or Mid(Id, i, 1) > "z" Then
		if Mid(Id, i, 1) < "A" Or Mid(Id, i, 1) > "Z" Then
			if Mid(Id, i, 1) < "0" Or Mid(Id, i, 1) > "9" Then
				if Mid(Id, i, 1) <> "_" Then
					ValidId = False
				End if
			End If
		End If	
	  End If
	Next
	If IsNumeric(Left(Id, 1)) = True Then
		ValidId = False
	End If
End Function


Dim ParamArr ()  ' Dynamic array to store function arguments.

'Strips the leading tab spaces. 
Function StripTabs (ByVal MyStr)
	Do While InStr(MyStr, vbTab) <> 0
		MyStr = Right(MyStr, Len(MyStr) - InStr(MyStr, vbTab)) 
	Loop 
	StripTabs = Trim(MyStr)
End Function

Sub ToggleCommentStyle ( )
'DESCRIPTION: Toggles between comment styles /* and //.

	TmpBlock = ""
	CmtBlock = ActiveDocument.Selection
	TypeOfFile = FileType(ActiveDocument)
	If TypeOfFile > 0 And TypeOfFile < 5 Then   'C/C++ style comment.
		'Get the first two characters of the comment block.
		Trim(CmtBlock)
		If Instr(CmtBlock,"//") <> 0 Then 
			Do While Instr (CmtBlock,"//") <> 0
				TmpBlock = TmpBlock + Left (CmtBlock, Instr (CmtBlock,"//") - 1)
				CmtBlock = Right(CmtBlock, (Len(CmtBlock) - (Instr(CmtBlock,_
						"//") + 1)))
			Loop
			CmtBlock = "/*" + TmpBlock + CmtBlock + "*/"
		ElseIf Instr(CmtBlock, "/*") <> 0 Then 
			CmtBlock = Right(CmtBlock, Len(CmtBlock) - (Instr(CmtBlock,"/*")_
					+ 1))
			Do While Instr (CmtBlock, vbLf) <> 0
				TmpBlock = TmpBlock + Left (CmtBlock, Instr(CmtBlock, vbLf))_
						+ "//"
				CmtBlock = Right(CmtBlock, (Len(CmtBlock) - (Instr(CmtBlock,_
						vbLf))))
			Loop
			CmtBlock = "//" + TmpBlock + Trim(CmtBlock)
			CmtBlock = Left(CmtBlock, Instr(CmtBlock,"*/")-1)
		End If
		ActiveDocument.Selection.Delete
		ActiveDocument.Selection = CmtBlock
	Else
		MsgBox "This macro does not work on this type of file."
	End If
	
End Sub


Sub CloseExceptActive () 
'DESCRIPTION: Closes all editor windows except the current one.

	'Windows.Item(1) is always the currently active window. So to close all
	' the windows except the active one, keep looping until there is no 
	' longer a Windows.Item(2).
	do while Windows.Count > 1
		Windows.Item(2).Close(dsSaveChangesPrompt)
	Loop
End Sub

Sub MultiplePaste () 
'DESCRIPTION: Performs a paste of what is on the clipboard a multiple number of times.

	NumPastes = InputBox("Number of pastes to make", "Multiple Paste Macro", "1")
	For i = 1 To CInt(NumPastes)
		ActiveDocument.Selection.Paste
		'Because the selection remains active, the following two lines
		'clear the selection, while keeping the cursor in the same place.
		ActiveDocument.Selection.LineUp
		ActiveDocument.Selection.LineDown
		ActiveDocument.Selection = vbLf    
	Next
End Sub

Sub PrintAllOpenDocuments ()
'DESCRIPTION: Prints all open, active documents.

	'Small, quick macro, but it can be usefull.
	for each doc in Application.Documents
		Doc.PrintOut
	next
End Sub

Sub PoundDefOut (ifndef)
	If ifndef = true Then
		PoundType = "#ifndef "
	Else
		PoundType = "#ifdef "
	End If
	
	If FileType(ActiveDocument) <> 1 Then
		MsgBox ("This macro only works on" + vbLf + _
				".c, .cpp, .cxx, .h, .hpp, or .hxx files")
	Else
		ControlVarName = InputBox("What should the control variable be?" + _
			vbLf + vbLf + "Example: #ifdef ControlVariable", PoundType + _
			" out a section of code")
		OK = True
		If ValidId (ControlVarName) = False Then
			Ok = False
			MsgBox("""" + ControlVarName + """" + _ 
				" is not a valid C identifier." + _
				vbLf + "please re-run the macro with a valid C identifier")
		End If
		
		
		Sel = ActiveDocument.Selection
		For i = 1 To Len(Sel) - 1
			If Mid(Sel, i, 1) = vbLf Then
				Sel = Left(Sel,i) + vbTab + Right(Sel, Len(Sel)-i)
			End If
		Next
		If ControlVarName <> "" And Ok = True Then
			Sel = vbLf + PoundType + ControlVarName + vbLf + vbTab + Sel + _
				vbLf+ "#endif //" + ControlVarName
			If Right(Sel,1) <> vbLf Then
				Sel = Sel + vbLf
			End If
			ActiveDocument.Selection = Sel
		End If
	End If
End Sub

'The next two macros are exactly the same, except one uses ifndef and the
'  other ifdef. We recycle the same code and just use a different 
'  preprocessor directive.
Sub ifdefOut ()
'DESCRIPTION: #ifdef / #endif out a section of code.

	PoundDefOut (False)
End Sub

Sub ifndefOut ()
'DESCRIPTION: #ifndef / #endif out a section of code.

	PoundDefOut (True)
End Sub

'Allows the user to make sure the current header file is included only once. 
' There are two ways to do this, using the #pragma once directive or 
' surrounding the entire file in a #ifndef/#endif structure. The first way
' is much cleaner, but it is VC++ specific, and therefore not portable. If 
' you plan on compiling your code with other compilers, use the 
' #ifndef/#endif method, otherwise, the #pragma once option is preferrable.
Sub OneTimeInclude ()
'DESCRIPTION: Adds code to the current header file so it is included only once per c/cpp file.
	
	ext = ActiveDocument.Name
	If ext = "" Then
		If MsgBox("The file you are working with does not have a file extension." + _
				vbLF + "Are you sure this is a C/C++ header file?", 4) = vbCancel Then
			Exit Sub
		End If
		ext = "nofilenamegiven.h"
	End If
	DocName = UCase(ext)
	pos = Instr(ext, ".")
	Do While pos <> 1
		ext = Mid(ext, pos, (Len(ext) - pos + 1))
		pos = Instr(ext, ".")
	Loop

	ext = LCase(ext)
	pos = Instr(DocName, ".")
	If ext <> ".h" and ext <> ".hpp" Then
		MsgBox("This macro can only be run on .h or .hpp files")
      Exit Sub
   end if

	Examp = Left(DocName, pos - 1) + "_" + _
		UCase(Right(ext, len(ext) - 1)) + "__"
	ControlVarName = InputBox("What should the control variable be?" _
		+ vbLf + vbLf + "Example: #ifdef " + _
		Examp, "One time header include protection", Examp)
	If ValidId (ControlVarName) <> True Then
		MsgBox(ControlVarName + " is not a valid c identifier." + _
		vbLf + "please re-run the macro with a valid C identifier")
      exit sub
	End If

	ActiveDocument.Selection.StartOfDocument (False)
	ActiveDocument.Selection.FindText "^[^/]", dsMatchRegExp
	ActiveDocument.Selection.FindText "^//", dsMatchBackward + dsMatchRegExp
   ActiveDocument.Selection.endofline
   ActiveDocument.Selection.newline
   ActiveDocument.Selection.startofline

	ActiveDocument.Selection = "#ifndef " + ControlVarName + _
		vbLf + "#define " + ControlVarName + vbLf
	ActiveDocument.Selection.EndOfDocument(False)
   ActiveDocument.Selection.newline
   ActiveDocument.Selection.newline
   ActiveDocument.Selection.lineup
	ActiveDocument.Selection = vbLf + "#endif // " + ControlVarName
   ActiveDocument.Selection.endofline
End Sub


'Auto completion macro
Dim previousSelection
Dim completionWords
Dim completionWordsIndex

Sub AddToCompletionWords (word)
	' If the word is already there, abort
	if InStr(1, completionWords, " " & word & " ", 1) <> 0 Then
		Exit Sub
	End If

	completionWords = completionWords & word & " "
End Sub

Function ExtractNextCompletionWord()
	ExtractNextCompletionWord = ""

	' If no words yet, go away
	if Len(completionWords) <= 1 Then
		Exit Function
	End If
	
	' Wrap to beginning if necessary
	if completionWordsIndex > Len(completionWords) Then
		completionWordsIndex = 2
	End If

	' Find next 
	Dim newIndex
	newIndex = InStr (completionWordsIndex, completionWords, " ", 0)
	if newIndex = 0 Then
		Exit Function
	End If

	ExtractNextCompletionWord = Mid(completionWords, completionWordsIndex, _ 
		newIndex-completionWordsIndex)
	completionWordsIndex = newIndex+1		'Skip over 
End Function

Sub FillCompletionWords (word)
	' Find all words in this file which match word, and
	'  add them, space separated, into completionWords
	previousSelection = word
	completionWords = " "
	completionWordsIndex = 2
	dim sel
	set sel = ActiveDocument.Selection

	Dim searchString
	searchString = "\{^\![^a-zA-Z0-9]\}" & word
	Dim firstTime
	firstTime = True
	Dim firstLine, firstCol
	Do while sel.FindText (searchString, dsMatchBackward + dsMatchRegExp)
		if firstTime Then
			firstLine = sel.TopLine
			firstCol = sel.CurrentColumn
			firstTime = False
		ElseIf firstLine = sel.TopLine And firstCol = sel.CurrentColumn Then
			Exit Do		' Jump out of loop before repeat
		End If
		sel.WordRight
		sel.WordLeft dsExtend
		AddToCompletionWords Trim(sel.text)
		sel.Cancel
	Loop
End Sub

Function SuggestNextCompletionWord()
	SuggestNextCompletionWord = True
	Dim word
	word = ExtractNextCompletionWord()
	if word <> "" then
		ActiveDocument.Selection = word
		previousSelection = word
	end if
End Function
 
Sub AutoCompleteFromFile()
'DESCRIPTION: Looks through the active file, searching for the rest of the word that you began to type.
	Dim doc
	set doc = ActiveDocument

	' Be sure active document is a text document
	if doc Is Nothing Then
		Exit Sub
	elseif doc.Type <> "Text" Then
		Exit Sub
	End If

	' Get word to be completed
	Dim sel
	set sel = doc.Selection
	sel.Cancel
	dim origLine, origCol
	origLine = sel.TopLine
	origCol = sel.CurrentColumn
	sel.WordLeft dsExtend

	'If the cursor is sitting just to the right of a space, an infinite loop
	'results. This bit of code protects from that:
	if Right(sel, 1) = " " then
		sel.CharRight
		Exit Sub
	end If

	if sel <> previousSelection Or completionWords = "" Then
		FillCompletionWords sel
		sel.MoveTo origLine, origCol
		sel.WordLeft dsExtend
	End If

	SuggestNextCompletionWord

End Sub

Sub ODBCTestOutputFormatting()
'DESCRIPTION: Get rid of the double quotes around the output of the ODBC Test program.
'Begin Recording
	ActiveDocument.ReplaceText "^""", "", dsMatchRegExp
	ActiveDocument.ReplaceText """$", "", dsMatchRegExp
'End Recording
End Sub

Sub AddDlgToolTips()
'DESCRIPTION: Insert tool tips before the current line. (Use this in the WM_INITIALIZE section)

	writelni( "DlgCtrlToolTip m_tt( GetSafeHwnd(), ::AfxGetInstanceHandle() );" )
	writelni( "//m_tt.SetToolTipText( controlId, stringId );" )

	ActiveDocument.Selection.EndOfDocument
	ActiveDocument.Selection.FindText "#include", dsMatchBackward
   ActiveDocument.Selection.StartOfLine
   ActiveDocument.Selection.Linedown
	writelni( "#include ""DlgCtrlToolTip.h""" )

	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection.FindText "//m_tt.SetToolTipText", dsMatchBackward
   ActiveDocument.Selection.StartOfLine dsfirstText

'End Recording
End Sub

Sub AddANSIStuff()
'DESCRIPTION: Add the ansi includes and namespace std to a console application

'Begin Recording
	ActiveDocument.Selection.FindText "#include"
	ActiveDocument.Selection.LineDown
	writeln( "#include " )
	writeln( "#include " )
	writeln( "using namespace std;" )

   ' move down and block out the 'hello world' line
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.LineDown dsMove, 3
	ActiveDocument.Selection.LineDown dsExtend
'End Recording
End Sub

Sub ParenthesisSpacing()
'DESCRIPTION: make code look like func( arg, arg2 )

'Begin Recording
	ActiveDocument.ReplaceText "(", "( "
	ActiveDocument.ReplaceText ")", " )"
	ActiveDocument.ReplaceText "(  ", "( "
	ActiveDocument.ReplaceText "  )", " )"
	ActiveDocument.ReplaceText "( )", "()"
	ActiveDocument.ReplaceText " (", "("
	ActiveDocument.ReplaceText "if(", "if ("
	ActiveDocument.ReplaceText "return(", "return ("
	ActiveDocument.ReplaceText "for(", "for ("
	ActiveDocument.ReplaceText "while(", "while ("
	ActiveDocument.ReplaceText "switch(", "switch ("
	ActiveDocument.ReplaceText "catch(", "catch ("
	ActiveDocument.ReplaceText "((", "( ("
	ActiveDocument.ReplaceText "( c )", " (c)"
	ActiveDocument.ReplaceText "=(", "= ("
	ActiveDocument.ReplaceText "( char* )", "(char*)"
	ActiveDocument.ReplaceText "( int )", "(int)"
	ActiveDocument.ReplaceText "( double )", "(double)"
	ActiveDocument.ReplaceText "( void* )", "(void*)"
	ActiveDocument.ReplaceText "( void )", "(void)"

	ActiveDocument.ReplaceText "( LPARAM )", "(LPARAM)", dsMatchCase
	ActiveDocument.ReplaceText "( WPARAM )", "(WPARAM)", dsMatchCase
	ActiveDocument.ReplaceText "( BOOL )", "(( BOOL ))", dsMatchCase
	ActiveDocument.ReplaceText "( bool )", "(( bool ))", dsMatchCase
	ActiveDocument.ReplaceText "( RECT * )", "(RECT*)"
	ActiveDocument.ReplaceText "( RECT* )", "(RECT*)"
	ActiveDocument.ReplaceText ",)", ", ("
	ActiveDocument.ReplaceText "{(", "{ ("
	ActiveDocument.ReplaceText "(  ", "( "
'End Recording
End Sub

Sub FixODBCTestOutput()
'DESCRIPTION: remove the quotes and stuff...

'Begin Recording
	ActiveDocument.ReplaceText "^""", "", dsMatchRegExp
	ActiveDocument.ReplaceText """$", "", dsMatchRegExp
	ActiveDocument.Selection.StartOfDocument
'End Recording
End Sub

Sub SQLFormatSelectString()
'DESCRIPTION: Prepare the string literal, this must only be run on an empty temp file with only the statement in it.

	ActiveDocument.ReplaceText "^", "         """, dsMatchRegExp
	ActiveDocument.ReplaceText "$", """", dsMatchRegExp
	ActiveDocument.ReplaceText " """, """", dsMatchRegExp
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.SelectAll
	ActiveDocument.Selection.Unindent
	ActiveDocument.Selection.Unindent
	ActiveDocument.Selection.Unindent
	ActiveDocument.Selection.Unindent
	ActiveDocument.Selection.Unindent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.EndOfDocument dsExtend
	ActiveDocument.Selection.ReplaceText "   """, "   ""  "
	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.EndOfDocument dsExtend
	ActiveDocument.Selection.ReplaceText """  ", """ "
	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection.EndOfDocument
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown dsExtend
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.CharLeft
	ActiveDocument.Selection = ";"
	ActiveDocument.Selection.StartOfDocument
'End Recording
End Sub

Sub SQLUpdate1()
'DESCRIPTION: Just do the CSQLUpdate s; s.settable("?"); part


'Begin Recording
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection.WordRight dsExtend
	ActiveDocument.Selection.Copy
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection = "   {"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "CSQLUpdate s;"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "s.SetTable"
	ActiveDocument.Selection.Backspace 8
	ActiveDocument.Selection = "SetTable( """
	ActiveDocument.Selection.Paste
	ActiveDocument.Selection = """ );"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Delete
'End Recording
End Sub

Sub SQLInsert1()
'DESCRIPTION: Just do the CSQLInsert s; s.settable("?"); part


'Begin Recording
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection.WordRight dsExtend
	ActiveDocument.Selection.Copy
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection = "   {"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "CSQLInsert s;"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "s.SetTable"
	ActiveDocument.Selection.Backspace 8
	ActiveDocument.Selection = "SetTable( """
	ActiveDocument.Selection.Paste
	ActiveDocument.Selection = """ );"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Delete
'End Recording
End Sub

Sub SQLUpdate2SetColumn()
'DESCRIPTION: do the setcolumn call


'Begin Recording
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection.WordRight dsExtend, 2
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.WordRight dsExtend
	ActiveDocument.Selection.Copy
	ActiveDocument.Selection.WordLeft
	ActiveDocument.Selection = "s.SetColumn( """
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection = """, "
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown
'End Recording
End Sub
Sub SQLUpdate3SetWhere()
'DESCRIPTION: do the setWhere call


'Begin Recording
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection.WordRight dsExtend, 2
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.WordRight dsExtend
	ActiveDocument.Selection.Copy
	ActiveDocument.Selection.WordLeft
	ActiveDocument.Selection = "s.SetWhere( """
	ActiveDocument.Selection.WordRight
	ActiveDocument.Selection = """, "
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown
'End Recording
End Sub

Sub SQLUpdate4ESQL()
'DESCRIPTION: Last step, add the ESQL call and '}'
'Begin Recording
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "ESQL( s );"
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Indent
	ActiveDocument.Selection = "}"
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.LineDown dsExtend
	ActiveDocument.Selection.Delete
	ActiveDocument.Save
'End Recording
End Sub


Sub RecordsetLoop()
'DESCRIPTION: put up the stock loop
'Begin Recording
   sel = GetIndent()
	writeln( sel + "try" )
	writeln( sel + "{" )
	writeln( sel + "   CSQLRecordset rs( g_db.m_hdbc );" )
	writeln( sel + "   rs << """";" )
	writeln( sel + "   rs.SetWhere( """" );" )
	writeln( sel + "   rs.SQLExecDirect();" )
	writeln( sel + "   while ( rs.SQLFetch() )" )
	writeln( sel + "   {" )
	writeln( sel + "      int n = 1;" )
	writeln( sel + "      string csPatient = rs.SQLGetData( n++ );" )
	writeln( sel + "   }" )
	writeln( sel + "}" )
	writeln( sel + "catch ( CSQLException* e )" )
	writeln( sel + "{" )
	writeln( sel + "}" )

'End Recording
End Sub

Sub COleStringFormatODBC()
'DESCRIPTION: "{d'%Y-%m-%d'}"

'Begin Recording
	ActiveDocument.Selection = """{d'%Y-%m-%d'}"""
'End Recording
End Sub

Sub SQLGetString()
'DESCRIPTION: CSQLBase s; s.SetStmt( "" ); CString xxx = BR.csGetSQLValue( s.GetStatement() );


'Begin Recording
	ActiveDocument.Selection = "   "
	ActiveDocument.Selection.EndOfLine dsExtend
'End Recording
End Sub

Sub CSQLRecordset2()
'DESCRIPTION: take the fnf def from initial copy and convert it to csqlrecordset block. must be in ITs OWN TEXT FILE.
'Begin Recording
	ActiveDocument.Selection.EndOfDocument
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.SetBookmark
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.StartOfDocument dsExtend
	ActiveDocument.Selection.Copy
	ActiveDocument.Selection.EndOfDocument
	ActiveDocument.Selection.Paste
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.NextBookmark
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.StartOfDocument dsExtend
	ActiveDocument.Selection.ReplaceText "^", "   CString cs", dsMatchRegExp
	ActiveDocument.ReplaceText "$", ";", dsMatchRegExp
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.EndOfLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.LineDown dsExtend
	ActiveDocument.Selection.Delete 2
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.EndOfDocument dsExtend
	ActiveDocument.Selection.ReplaceText ";", "", dsMatchRegExp
	ActiveDocument.Selection.ReplaceText "^", "         cs", dsMatchRegExp
	ActiveDocument.Selection.ReplaceText "$", "         = rs.SQLGetData( n++ );", dsMatchRegExp
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.EndOfDocument
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown dsExtend
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.NextBookmark
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineDown
	ActiveDocument.Selection.EndOfDocument dsExtend
	ActiveDocument.Selection.Cut

	ExecuteCommand "RecordsetLoop"

	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.NextBookmark
	ActiveDocument.Selection.FindText "string ", dsMatchRegExp
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection = "//"
	ActiveDocument.Selection.EndOfLine
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.Paste
'End Recording

End Sub

Sub CommentOutBlock()
'DESCRIPTION: Comment out a selected block changing  '^' to '// '

	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
		TypeOfFile = FileType(ActiveDocument)  
		If TypeOfFile > 0 And TypeOfFile < 5 Then    'C & Java use the same 
         if ActiveDocument.Selection <> "" then
      	   ActiveDocument.Selection.ReplaceText "^", "// ", dsMatchRegExp
         else
            msgbox "must select a block first"
         end if
      else
         msgbox "must be a C++ source file"
      end if
   end if


'End Recording
End Sub

Sub SQLBatchHeader ()
'DESCRIPTION: Adds the header to an sql batch file used by ByteRite
	
	ext = ActiveDocument.Name
	If ext = "" Then
		MsgBox "Save document as nnnn_mysqlbatch.sql first."
		exit Sub
	End If

	ActiveDocument.Selection.StartOfDocument(False)
	writeln( "-- " + ext )
	writeln( "" )
	writeln( "-- codes" )
	writeln( "-- #=put answer in buffer" )
	writeln( "-- ?=if buffer == literal jump to next section or end of code" )
	writeln( "-- :=if buffer != literal jump to next section or end of code" )
	writeln( "-- ~=don't display an error messagebox" )
	writeln( "-- $=skip to this line after compare jump" )
	writeln( "-- !=load and run another batch" )
	writeln( "-- @=inform the user about the result of the compare and ask to proceed (toggle)" )
	writeln( "" )
	writeln( "#select count(*) from DMLLog where ScriptFN = '" + ext + "'" )
	writeln( "?1" )
	writeln( "~insert into DMLLog (ScriptFN, AppliedOn) values ('" + ext + "', now())" )
	writeln( "" )
End Sub

sub InsertDate()
   dim theDate
   'theDate = formatDatetime( date, vbGeneralDate )
   write( year(date) + month(date) + day(date) )
   'write( theDate )
end sub

function YYYYMMDD()
   theDate = formatdatetime( date, vbGeneralDate )
   theDate = mid( theDate, 7, 4 ) + "-" + mid( theDate, 1, 2 ) + "-" + mid( theDate, 4, 2 )
   YYYYMMDD = theDate
end function

sub InsertYYYYMMDD()
   write( YYYYMMDD() )
end sub

Sub RevisionLog()
'DESCRIPTION: ' insert a C++ revision log before the current line
'Begin Recording
	writeln( "// Revision Log" )
	writeln( "//" )
	writeln( "// Date       Who SAR     Notes" )
	writeln( "// ========== === ======= =====================================" )
	writeln( "// " + YYYYMMDD() + " mph         Initial coding by Mark Henri of" )
	writeln( "//                        MPH Software - markhenri@home.net" )
	writeln( "// " )
	writeln( "//" )
	ActiveDocument.Selection.LineUp dsMove, 2
	ActiveDocument.Selection.EndOfLine
'End Recording
End Sub

sub RevisionEntry()
	ActiveDocument.Selection.StartOfDocument
	if ActiveDocument.Selection.FindText( "// Revision Log" ) then
	   if ActiveDocument.Selection.FindText( "// =======" ) then
      	ActiveDocument.Selection.LineDown dsMove, 1
      	writeln( "// " + YYYYMMDD() + " mph         " )
      	ActiveDocument.Selection.LineUp dsMove, 1
      	ActiveDocument.Selection.EndOfLine
      end if 
   end if 
end sub

Sub SwapCase()
	' DESCRIPTION: Macro to swap the case of selected words.
	'
	' David Little
	' COADE, Inc.
	' Houston, TX
	' dlittle@coade.com
	' 5OCT98
	'
	str = ActiveDocument.Selection.Text
	str1 = ""
	i = 1
	Do While (i < Len(str)+1)
		If (Mid(str, i, 1) = LCase(Mid(str, i, 1))) Then
			str1 = str1 + UCase(Mid(str, i, 1))
		Else
		str1 = str1 + LCase(Mid(str, i, 1))
		End If
		i = i + 1
	Loop
	ActiveDocument.Selection.Text = str1
End Sub

Sub SortLinesBubble()
   'DESCRIPTION: bubble sort lines of text; size of file can be unlimited; does it on screen; file must not be read only.
   ' Note: Has a bug with read only files and will hang.
   'http://www.codeguru.com/devstudio_macros/SortOfMacro1.shtml

    Dim win
    set win = ActiveWindow  
    If win.type <> "Text" Then
        MsgBox "This macro can only be run when a text editor window is active."
        Exit Sub
    End If

    StartLine = ActiveDocument.Selection.TopLine
    EndLine = ActiveDocument.Selection.BottomLine       
    If EndLine < StartLine Then
        Temp = StartLine            
        StartLine = EndLine         
        EndLine = Temp      
    End If

    EndLine = EndLine - 1         

    If StartLine > EndLine Then
        Exit Sub
    End If

    bStop = false

    Do While Not bStop
        bStop = true
        For i = StartLine  To EndLine            
            ActiveDocument.Selection.GoToLine i         
            ActiveDocument.Selection.SelectLine
            FirstLine = ActiveDocument.Selection         

            ActiveDocument.Selection.GoToLine i + 1        
            ActiveDocument.Selection.SelectLine
            SecondLine = ActiveDocument.Selection         

            If FirstLine > SecondLine Then 
                bStop = false
                ActiveDocument.Selection.GoToLine i
	            ActiveDocument.Selection.StartOfLine
	            ActiveDocument.Selection.MoveTo i + 1, dsEndOfLine, dsExtend
                ActiveDocument.Selection = SecondLine +  FirstLine    
	            ActiveDocument.Selection.EndOfLine
	            ActiveDocument.Selection.Delete
            End If
        Next
    Loop
    ActiveDocument.Selection.GoToLine StartLine
    ActiveDocument.Selection.StartOfLine
    ActiveDocument.Selection.MoveTo EndLine + 1, dsEndOfLine, dsExtend
End Sub

Function CollectLines(Selection)
 '-- make sure the top of the selection is really the top
 StartLine = Selection.TopLine
 EndLine = Selection.BottomLine
 If EndLine < StartLine Then
    Temp="StartLine" 
    StartLine="EndLine" 
    EndLine="Temp" 
 End If 
 Dim lines() '-- don't try to collect an empty selection 
 If StartLine > EndLine Then
   Redim lines(0)
   CollectLines = lines
   Exit Function
 End If

 '-- collect all the lines of the selection into an array
 '-- this could be prohibitive on large selections ( > 2M ? )
 Redim lines(EndLine - StartLine)
 For i = StartLine To EndLine 
  Selection.GoToLine i
  Selection.SelectLine
  lines(endLine - i) = Selection.Text
 Next

 CollectLines = lines
End Function

'-- An internal routine To sort an array
'-- Specify ignoreWhiteSpace = True To ignore leading and trailing whitespace
'-- Specify ignoreCase = True To compare strings ignoring case

Sub QuickSort(vec,loBound,hiBound,ignoreWhiteSpace,ignoreCase)
 Dim pivot,loSwap,hiSwap,temp

 '-- This procedure is adapted from the algorithm given in:
 '--    Data Abstractions & Structures using C++ by
 '--    Mark Headington and David Riley, pg. 586

 '-- two items To sort
 If hiBound - loBound = 1 Then
    If vec(loBound) > vec(hiBound) Then
       temp=vec(loBound)
       vec(loBound) = vec(hiBound)
       vec(hiBound) = temp
    End If
 End If

 '-- three or more items To sort
 pivot = vec(int((loBound + hiBound) / 2))
 vec(int((loBound + hiBound) / 2)) = vec(loBound)
 vec(loBound) = pivot
 loSwap = loBound + 1
 hiSwap = hiBound

 do
 '-- find the correct loSwap
 vecLoSwap = vec(loSwap)
 If (ignoreCase = 1 And ignoreWhitespace = 1) Then
    While loSwap < hiSwap and ucase(trim(vec(loSwap))) <= ucase(trim(pivot))
        loSwap = loSwap + 1
    wend
 Elseif (ignoreCase = 1) Then
    While loSwap < hiSwap and ucase(vec(loSwap)) <= ucase(pivot)
        loSwap = loSwap + 1
    wend
 Elseif (ignoreWhiteSpace = 1) Then
    While loSwap < hiSwap and trim(vec(loSwap)) <= trim(pivot)
         loSwap = loSwap + 1
    wend
 Else
    While loSwap < hiSwap and vec(loSwap) <= pivot
         loSwap = loSwap + 1
    wend
 End If

 '-- find the correct hiSwap
 If (ignoreCase = 1 And ignoreWhitespace = 1) Then
 While ucase(trim(vec(hiSwap))) > ucase(trim(pivot))
     hiSwap = hiSwap - 1
 wend
 Elseif (ignoreCase = 1) Then
 While ucase(vec(hiSwap)) > ucase(pivot)
    hiSwap = hiSwap - 1
 wend
 Elseif (ignoreWhiteSpace = 1) Then
 While trim(vec(hiSwap)) > trim(pivot)
    hiSwap = hiSwap - 1
 wend
 Else
 While vec(hiSwap) > pivot
    hiSwap = hiSwap - 1
 wend
 End If

 '-- swap values if out of order
 If loSwap < hiSwap Then
 temp = vec(loSwap)
 vec(loSwap) = vec(hiSwap)
 vec(hiSwap) = temp
 End If
 loop While loSwap < hiSwap

 vec(loBound) = vec(hiSwap)
 vec(hiSwap) = pivot

 '-- Recursively sort the partitions

 '-- if there are 2 or more items in first partitions
 If loBound < (hiSwap - 1) Then
 Call QuickSort(vec,loBound,hiSwap-1,ignoreWhiteSpace, ignoreCase)
 End If

 '-- 2 or more items in second section
 If hiSwap + 1 < hibound Then
 Call QuickSort(vec,hiSwap+1,hiBound, ignoreWhiteSpace, ignoreCase)
 End If

End Sub

Sub SortLinesQuickSort
'DESCRIPTION: Sorts the selected lines
 If ActiveDocument.Type <> "Text" Then
    MsgBox "This macro can only be run when a text editor window is active."
 Exit Sub
 End If

 '-- make sure the top of the selection is really the top
 StartLine = ActiveDocument.Selection.TopLine
 EndLine = ActiveDocument.Selection.BottomLine
 If EndLine < StartLine Then
 Temp = StartLine
 StartLine = EndLine
 EndLine = Temp
 End If

 '-- collect the lines of the selection into an array
 lines = CollectLines(ActiveDocument.Selection)


 If isnull(lines) Then
 Exit Sub
 End If

 If (ubound(lines) <= 0) Then
    '-- don't try to sort an empty selection
    Exit Sub
 End If

 '-- sort the array
 Call QuickSort (lines, lbound(lines), ubound(lines), 0, 0)

 '-- select the entire original selection, then delete it
 ActiveDocument.Selection.GoToLine StartLine

 ActiveDocument.Selection.LineDown dsExtend, (EndLine - StartLine) + 1
 ActiveDocument.Selection.Delete

 '-- write the sorted lines out to the file
 For i = 0 To EndLine - StartLine
 ActiveDocument.Selection = lines(i)
 Next
End Sub

'///////////////////////////////////////////////////////////////

Sub MakeHFileifdef()
'DESCRIPTION: Generates #ifdef THISHFILE_H ... #endif definitions

      'if name = "ARNE.H" then s = "_ARNE_H"
	  s = Ucase(Application.ActiveDocument.Name)
	  p = Len(s)
	  for i = 1 to Len(s)	
	    if Mid(s,i,1)="." then p = i-1
	  next
	  s = Left(s,p) + "_H__"

	  Application.ActiveDocument.Selection.StartOfDocument
 	  Application.ActiveDocument.Selection = "#ifndef " + s + vbLf + "#define " + s +vbLf

	  Application.ActiveDocument.Selection.EndOfDocument
 	  Application.ActiveDocument.Selection = vbLf + "#endif // " + s + vbLf
End Sub

Sub IncludeMyH()
'DESCRIPTION: Inserts an #include "thisFile.h"

      'if name = "ARNE.CPP" then s = "ARNE"
	  s = Application.ActiveDocument.Name
	  p = Len(s)
	  for i = 1 to Len(s)	
	    if Mid(s,i,1)="." then p = i-1
	  next
	  s = Left(s,p)
	  Application.ActiveDocument.Selection = "#include "+Chr(34)+s+".h"+Chr(34)+vbLf
End Sub

Sub GetFriendFile()
'DESCRIPTION: Opens the corresponding .h / .cpp file

	currentFileName = Application.ActiveDocument.FullName
	newFileName = ""
	'MsgBox currentFileName  
	if (Ucase(Right(currentFileName,2))=".H") then
	  newFileName = Left(currentFileName,Len(currentFileName)-2)+".CPP"
	elseif	(Ucase(Right(currentFileName,4))=".CPP") then
	  newFileName = Left(currentFileName,Len(currentFileName)-4)+".H"
	end if

	'MsgBox newFileName  
	if newFileName<>"" then	Application.Documents.Open newFileName
End Sub

Sub MakeFilePair()
'DESCRIPTION: Generates a .h / .cpp file pair

   dim newDoc 
   s = InputBox("This macro generates a .h / .cpp file pair."+vbLf+vbLf+"Enter filename (not including extension)","Generate filepair")
   if s = "" then
      exit sub
   end if

   newName = s+".h"
   sTxt = "/*-----------------------------------------------" + vbCrLf
   sTxt = sTxt+"     File name    : " + newName + vbCrLf
   sTxt = sTxt+"     Author       : "+ vbCrLf
   sTxt = sTxt+"  "+ vbCrLf
   sTxt = sTxt+"     Description  : "+ vbCrLf
   sTxt = sTxt+"  -----------------------------------------------*/" + vbCrLf
   set newDoc = Application.Documents.Add("Text")
   newDoc.Save (newName)
   newDoc.Selection = vbCrLf+ "#include "+Chr(34)+"stdafx.h" +Chr(34) + vbCfLf+ vbCrLf
   MakeHFileIfDef()
   newDoc.Selection.StartOfDocument

   newDoc.Selection = sTxt

   newName = s +".cpp"
   set newDoc = Application.Documents.Add("Text")
   newDoc.Save (newName)
   IncludeMyH()
  
End Sub

function GetIndent()
   Activedocument.selection.lineup
   Activedocument.selection.endofline
   Activedocument.selection.newline
   Activedocument.selection = "x"
   Activedocument.selection.charleft
	ActiveDocument.Selection.StartOfLine dsFirstColumn, dsExtend
	sel = ActiveDocument.Selection
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.EndOfLine dsExtend
	ActiveDocument.Selection.Cut
	ActiveDocument.Selection.Delete
   GetIndent = sel
end function

sub TestIndent
   sel = getindent()
   activedocument.selection.startofline
   activedocument.selection = sel + "x"
end sub

sub writeln( line )
   'DESCRIPTION: inserts a line of text before the current line; defeats auto indent
    ActiveDocument.Selection.lineup
    ActiveDocument.Selection.EndofLine
    ActiveDocument.Selection.NewLine
    ActiveDocument.Selection.StartofLine
    ActiveDocument.Selection = line
    ActiveDocument.Selection.linedown
end sub

sub writelni( line )
   'DESCRIPTION: inserts a line of text before the current line promoting current indenting
    ActiveDocument.Selection.lineup
    ActiveDocument.Selection.EndofLine
    ActiveDocument.Selection.NewLine
    ActiveDocument.Selection = line
    ActiveDocument.Selection.linedown
end sub

sub write( line )
   'DESCRIPTION: inserts a line of text before the current line
    ActiveDocument.Selection = line
end sub

Sub zzzAddRevisionMarks ( )
'DESCRIPTION: Adds comments to a file that describe the changes made.

	'This routine adds a new comment block to the top of a file, where the 
	' programmer can place revision marks to describe the changes made to the file.
	'The rules this routine uses are as follows:
	' 1) Start at the top of the file.
	' 2) Scan through each line; if the current line starts with a comment,
	'      advance to the next line..
	' 3) If we are currently in a group comment block, keep advancing until
	'     the end of the block is found.
	' 4) If we are in a line item comment (e.g.: //, ', rem, etc), keep advancing
	'     until a line that does not start with a comment is found.
	'     By 'start with a comment', it is meant a line, where after
	'     stripping off spaces and tabs from the beginning, the first set of
	'     characters is not a comment delimiter.
	' 5) Insert a blank line; this allows the next invocation of this macro
	'     to place the newer revision mark before all others.
	' 6) Insert the revision block.

	'Change this to the programmer's name for a default.
	DefaultUserName = "..."

	'Because the user may not have closed a comment (e.g. a /* without a */),
	' try to protect ourselves from an infinite loop...
	BreakAfter = 10 'Max number of lines to look at scan before aborting
	CurrentCount = 1

	BeginComment = "" 'The token for the specified language for the beginning
						' of a comment.
	EndComment = ""   'Same, except for the end of a comment.
	EveryLine = ""    'Does the comment mark need to be placed on every line
						' (VBS, DEF types)?

	'First, make sure the active document is a text window
	' (Not really necessary, but good practice).
	If ActiveDocument.Type = "Text" Then
		TypeOfFile = FileType(ActiveDocument)
    
		'Set ourselves at the very top of the document.
		'This also clears any selection made.
		ActiveDocument.Selection.StartOfDocument
		ActiveDocument.Selection.SelectLine
		CurrText = ActiveDocument.Selection
		CurrText = LTrim(CurrText)
    
		'All of the following do relatively the same thing, 
		' except they look for different comment types.
		If TypeOfFile > 0 And TypeOfFile < 5 Then       'C/C++ family of code
			ContSearch = True
			BeginComment = "/*"
			EndComment = "*/"
			EveryLine = " "

			'In C/C++ style code, we need to look for a //;
			'  if not found, then look for a /*.
			Do
				ActiveDocument.Selection = CurrText
				If InStr(CurrText, "//") = 1 Then   'is a "//" available?
					ActiveDocument.Selection.SelectLine
					CurrText = LTrim(ActiveDocument.Selection) 'Remove whitespace.
					ContSearch = False   ' Looking at // style comments, 
											'don't look for a /* style.
				Else
					Exit Do
				End If
			Loop

			If ContSearch = False Then
				ActiveDocument.Selection.LineUp
			End If

			'When the method ActiveDocument.Selection.SelectLine is called,
			'  it is the same as when you click the mouse in the margin; it
			'  selects the whole line, including the carriage return.
			'  Because of this, the cursor comes down to the next line, which
			'  can really confuse this algorithm. So in a number of places, 
			'  you will see a grouping of LineUp/LineDown commands. By executing
			'  these commands, the cursor is moved down, which clears the current
			'  selection (including getting us past the carriage return),
			'  then moves us back up, thus putting us on the same line. This
			'  removesthe danger of skipping a line (which is what will
			'  happen without the LineUp/LineDown combination).
			If ContSearch = True Then
				ActiveDocument.Selection.StartOfDocument
				'Prime the loop with the first line.
				ActiveDocument.Selection.SelectLine
				CurrText = ActiveDocument.Selection           
				ActiveDocument.Selection.LineDown
				ActiveDocument.Selection.LineUp
				'Remove leading whitespace.
				CurrText = LTrim(CurrText)      
				'Does line start with a /*?              
				If InStr(CurrText,"/*") = 1 Then
					while (InStr(CurrText, "*/") = 0) And _
					      (BreakAfter > CurrentCount)
						ActiveDocument.Selection.SelectLine
						CurrText = ActiveDocument.Selection
						CurrText = LTrim(CurrText)                              
						ActiveDocument.Selection.LineDown
						ActiveDocument.Selection.LineUp    
						CurrentCount = CurrentCount + 1
					wend
					If (BreakAfter > CurrentCount) Then
						'Exit the loop because the search has gone on for an 
						'  unreasonable number of lines.
						MsgBox "Could not find a closing comment mark"
					End If
				End If
			End If

		'The code for these is really just a copy of that from the 
		'  C/C++ section...
		  
		ElseIf TypeOfFile = 5 Then                      'HTML code
			BeginComment = ""
			EveryLine = "    "
			If InStr(CurrText,"") <> 0 Then
					ActiveDocument.Selection.LineDown
				Else
					Do
						ActiveDocument.Selection.SelectLine
						CurrText = ActiveDocument.Selection
						CurrText = Left(CurrText, Len(CurrText) - 2)
						ActiveDocument.Selection = CurrText + vbLf
						If InStr(CurrText, "-->") Then
							Exit Do
						End If
					Loop
				End If
			End If 

		ElseIf TypeOfFile = 6 Then                      'VBS code
			BeginComment = "'"
			EndComment = "'"
			EveryLine = "'"
			Do
				ActiveDocument.Selection = CurrText
				If InStr(CurrText, "'") = 1 Or _
				   InStr(LCase(CurrText), "Rem") = 1 Then
					ActiveDocument.Selection.SelectLine
					CurrText = LTrim(ActiveDocument.Selection)
					ContSearch = False
				Else
					Exit Do
				End If
			Loop
			If ContSearch = False Then
				ActiveDocument.Selection.LineUp
			End If

		ElseIf TypeOfFile = 7 Then                      'DEF code
			BeginComment = ";"
			EndComment = ""
			EveryLine = ";"
			Do
				ActiveDocument.Selection = CurrText
				If InStr(CurrText, ";") = 1 Then
					ActiveDocument.Selection.SelectLine
					CurrText = LTrim(ActiveDocument.Selection)
					ContSearch = False
				Else
					Exit Do
				End If
			Loop
			If ContSearch = False Then
				ActiveDocument.Selection.LineUp
			End If      
		End If

		If TypeOfFile = 0 Then                          'Unknown type of code.
			MsgBox("Unable to add revision marks. Unrecgonized file type")
		ElseIf (CurrentCount < BreakAfter) Then
			'The BeginComment, EveryLine, and EndComment were set as
			' avoid duplicating this section...
			' just insert the generalized block, with the comment markers.
			ActiveDocument.Selection.StartOfLine(True)
			'This is added with one assignment statement, which enables the user
			' to hit undo once, and remove the entire change.
			ActiveDocument.Selection = vbLf + _
			BeginComment + "***********************************" + vbLf + _
			EveryLine    + " REVISION LOG ENTRY" + vbLf + _
			EveryLine    + " Revision By: " + DefaultUserName + vbLf + _
			EveryLine    + " Revised on " + CStr(Now) + vbLf + _
			EveryLine    + " Comments: ..." + vbLf + _
			EveryLine    + "***********************************" + _
			EndComment + vbLf + vbLf
		End If
	End If
End Sub

Sub zzzCommentOut ()
'DESCRIPTION: Comments out a selected block of text.
	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
		TypeOfFile = FileType(ActiveDocument)  
		If TypeOfFile > 0 And TypeOfFile < 5 Then    'C & Java use the same 
														'style of comments.
			ActiveDocument.Selection = "/*" + ActiveDocument.Selection + "*/"
		ElseIf TypeOfFile = 5 Then
			ActiveDocument.Selection = ""
		ElseIf TypeOfFile = 6 Or TypeOfFile = 7 Then
			'There is no group comment like there is in the other file types, 
			'so we need to iterate through each line, and prepend a ' to the line.
			'Also, because VBS/DEF does not have a 'end the comment at this 
			'particular column' delimiter, entire lines of code must be 
			'commented out, not sections.
			If TypeOfFile = 6 Then 
				CommentType = " ' "
			Else
				CommentType = " ; "
			End If
     
			StartLine = ActiveDocument.Selection.TopLine
			EndLine = ActiveDocument.Selection.BottomLine
			If EndLine < StartLine Then
				Temp = StartLine
				StartLine = EndLine
				EndLine = Temp
			End If

			If EndLine = StartLine Then
				ActiveDocument.Selection = CommentType + ActiveDocument.Selection

			Else 
				For i = StartLine To EndLine
					ActiveDocument.Selection.GoToLine i
					ActiveDocument.Selection.SelectLine
					ActiveDocument.Selection = CommentType + _
						ActiveDocument.Selection
				Next
			End If
		Else
			MsgBox("Unable to comment out the highlighted text" + vbLf + _
					"because the file type was unrecognized." + vbLf + _
					"If the file has not yet been saved, " + vbLf + _
					"please save it and try again.")
		End If
	End If
End Sub

Sub zzzAddFunctionDescription ( )
'DESCRIPTION: Creates a comment block for the currently selected C/C++ function prototype

	'Throughout this file, ActiveDocument.Selection is used in place 
	'of ActiveDocument.Selection.Text.  The two are equivalent, and can 
	'be used interchangeably. The reason for the equivalence is that
	'Text is regarded as the default property to use. All uses of
	'ActiveDocument.Selection without any other property default to the Text
	'property.
	if ActiveDocument.Language = dsCPP Then
		Header = StripTabs(Trim(ActiveDocument.Selection))

		'Get the function return type.
		if Header <> "" then
			Reti = InStr(Header, " ")
			Loc = InStr(Header, "(")
			if Reti < Loc Then
			  RetTp = Left(Header, Reti)
			  Header = Right(Header, Len(Header) - Reti)
			End If

			'Get the function name.
			Loc = InStr(Header, "(") - 1
			Loc2 = InStr(Header, ")")
			if Loc > 0 And Loc2 > 0 then 'make sure there is a '(' and a ')'
				fcName = Left(Header, Loc)
				Header = Right(Header, Len(Header) - Len(fcName))

				'Do we have storage type on the return type?
				Trim (fcName)
				If InStr(fcName," ") <> 0 Then
					retTp = retTp + Left(fcName,InStr (fcName," "))
					fcName = Right(fcName, Len(fcName) - InStr(fcName," "))
				End If

				'Get the function parameters.
				iPrm = 0
				iPrmA = 0
				prms = Header 

				'Count the number of parameters. 
				Do While InStr(prms, ",") <> 0
					iPrm = iPrm + 1
					prms = Right(prms, Len(prms) - InStr(prms, ",")) 
				Loop 
				
				'Store the parameter list in the array.
				If iPrm > 0 Then  ' If multiple params.
					iPrm = iPrm + 1
					iPrmA = iPrm
					Redim ParamArr(iPrm)
					Do While InStr(header, ",") <> 0
						ParamArr(iPrm) = Left(Header, InStr (Header, ",") - 1)
						'Remove brace from first parameter.
						If InStr(ParamArr(iPrm), " (") <> 0 Then
							ParamArr(iPrm) = Right(ParamArr(iPrm), _
									Len(ParamArr(iPrm))-InStr(ParamArr(iPrm)," ("))
							Trim(ParamArr(iPrm))
						End If
						Header = Right(Header, Len(Header) - InStr(Header,","))
						iPrm = iPrm - 1 
						Loop 
					ParamArr(iPrm) = Header 
					'Remove trailing brace from last parameter.
					If InStr(ParamArr(iPrm), ")") <> 0 Then
						ParamArr(iPrm) = Left(ParamArr(iPrm), _
								InStr(ParamArr(iPrm), ")") - 1)
						Trim(ParamArr(iPrm))
					End If
				Else 'Possibly one param.
					Redim ParamArr(1)
					Header = Right(Header, Len(Header) - 1) ' Strip the first brace.
					Trim(Header)
					ParamArr(1) = StripTabs(Header)
					If InStr(ParamArr(1), ")") <> 1 Then
						ParamArr(1) = Left(ParamArr(1), InStr(ParamArr(1), ")") - 1)
						Trim(ParamArr(1))
						iPrmA = 1
					End If
				End If

				'Position the cursor one line above the selected text.
				ActiveDocument.Selection.LineUp
				ActiveDocument.Selection.LineDown
				ActiveDocument.Selection.StartOfLine
				ActiveDocument.Selection = vbLf

				Descr = "// Function name	: " + fcName + _
						vbLf + "// Description	    : " + _ 
						vbLf +  "// Return type		: " + RetTp + vbLf
				
				'Print the parameter list. 
				Last = iPrmA
				Do While iPrmA <> 0
					'Remove a line feed from any of the arguments.
					If InStr(ParamArr(iPrmA), vbLf) <> 0 Then
						ParamArr(iPrmA) = Right(ParamArr(iPrmA), _
								(Len(ParamArr(iPrmA)) - _
								InStr(ParamArr(iPrmA), vbLf)))
						Trim(ParamArr(iPrmA))
					End If
					ParamArr(iPrmA) = StripTabs(ParamArr(iPrmA))
					'If there are 2+ parameters, the first parameter will 
					'have a '(' prepended to it, remove it here:
					if iPrmA = Last AND Last <> 1 then
					  ParamArr(iPrmA) = Right(ParamArr(iPrmA), _
							Len(ParamArr(iPrmA)) - 1)
					End If
					Descr = Descr + "// Argument         : " + _
							ParamArr(iPrmA) + vbLf
					iPrmA = iPrmA - 1
				Loop
				ActiveDocument.Selection = Descr
			Else
				MsgBox("It is possible that the function you are trying to"+_
						" work with has a syntax error.")
			End if
		End If
	Else
		MsgBox("You need to have an active C/C++ document open"+ _
				vbLF+"with the function prototype selected.")
	End If
End Sub

'sub a1
'    ActiveDocument.Selection.StartOfLine
'end sub
'sub a2
    'ActiveDocument.Selection.StartOfLine dsFirstText
'end sub
'sub a3
    'ActiveDocument.Selection = "test line"
'end sub
'sub a4
    'ActiveDocument.Selection.EndofLine
'end sub
'sub a5
    'ActiveDocument.Selection.lineup
'end sub

dim SaveCursorLine
dim SaveCursorColumn

sub PushCursor()
	SaveCursorColumn = ActiveDocument.Selection.CurrentColumn
   SaveCursorLine = ActiveDocument.Selection.CurrentLine
end sub

sub PopCursor()
   ActiveDocument.Selection.MoveTo SaveCursorLine, SaveCursorColumn
end sub

sub test1
	col = ActiveDocument.Selection.CurrentColumn
   row = ActiveDocument.Selection.CurrentLine
   ActiveDocument.Selection.MoveTo row+1, col+1
end sub

Sub TestInputBox()
'DESCRIPTION: 
'Begin Recording
   PushCursor

	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.StartOfLine
	ActiveDocument.Selection.LineUp dsExtend, 10
	CmtBlock = ActiveDocument.Selection
   PopCursor
   CmtBlock = replace(cmtblock, "  ", "" )
   CmtBlock = replace(cmtblock, "  ", "" )
   CmtBlock = replace(cmtblock, "  ", "" )
   CmtBlock = replace(cmtblock, vbCrLf, " " )
   CmtBlock = ltrim(cmtblock)
   cmtblock = rtrim(cmtblock)
	Result = InputBox( "Number of pastes to make", "Choose a Variable", CmtBlock)
	'InputBox( "Number of pastes to make", "Choose a Variable", Result)

   PopCursor
   if Result <> "" then
      ActiveDocument.Selection = Result
   end if

'End Recording
End Sub

Sub RevisionConvert2YYYYMMDD()
'DESCRIPTION: Change 10/02/1999 to 1999-10-02 in the revision log

'Begin Recording
	ActiveDocument.Selection.CharRight dsMove, 3
	ActiveDocument.Selection.CharRight dsExtend, 5
	ActiveDocument.Selection.Cut
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.CharRight dsMove, 4
	ActiveDocument.Selection = "-"
	ActiveDocument.Selection.Paste
	ActiveDocument.Selection.CharLeft dsMove, 3
	ActiveDocument.Selection = "-"
	ActiveDocument.Selection.Delete
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.LineDown
'End Recording
End Sub

Sub NoSTLStringWarnings()
'DESCRIPTION: Get rid of all the STL string warnings with this pragma
'Begin Recording
   PushCursor()

	ActiveDocument.Selection.StartOfDocument
	ActiveDocument.Selection.FindText "#include"
	ActiveDocument.Selection.StartOfLine dsFirstText
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.LineUp
	ActiveDocument.Selection.NewLine
	ActiveDocument.Selection.LineUp
   ActiveDocument.Selection = "#pragma warning( disable: 4786 )"

   PopCursor()
'End Recording
End Sub

'------------------------------------------------------
'FILE DESCRIPTION: Open Current Resource Script As Text
'------------------------------------------------------
sub OpenRCAsText()
'DESCRIPTION: Open Current Resource Script As Text
'AUTHOR: Roman A. Surma 
   if Windows.Count > 0 then
      rc_name = ActiveDocument.FullName
      if InStrRev( rc_name, ".rc" ) > 0 then
         'if we have .rc file - let's open it as text
         rc_wnd_name = ActiveWindow.Caption
         Documents.Open rc_name, "Text"
         'performing primitive search for resource in .rc file
         'TODO: enhance algorithm to search resource in proper
         'language section
         rc_part         = ".rc - "
         res_name_start  = InStr( rc_wnd_name, rc_part ) + Len( rc_part )
         res_name_end    = InStr( res_name_start, rc_wnd_name, " " )
         if res_name_end > res_name_start then
            res_name = Mid( rc_wnd_name, res_name_start, res_name_end - res_name_start )
            'searching for regexp like "^ *IDD_DIALOG1"
            ActiveDocument.Selection.FindText "^ *" & res_name, dsMatchFromStart + dsMatchRegExp
            'ActiveDocument.Selection.Cancel
            ActiveDocument.Selection.StartOfLine
         end if
      end if
   elseif Documents.Count >= 1 then
      rc_name = ActiveProject.FullName
      dot_pos = InStrRev( rc_name, "." )
      rc_name = Left( rc_name, dot_pos ) & "rc"
      on error resume next
      Documents.Open rc_name, "Text"
      if Err.Number < 0 then
         MsgBox( "Can not open resource file " & rc_name & " for this project: " & ActiveProject.Name )
      end if
      on error goto 0
   end if
end sub

Sub NoTabs()
'DESCRIPTION: Elimate all tabs

   ActiveDocument.ReplaceText chr(9), "   "
	'ActiveDocument.Save
	'ActiveWindow.Close dsSaveChangesPrompt

End Sub