标题: 用VBS写的VBS代码格式化工具VbsBeautifier
作者: Demon
链接: https://demon.tw/my-work/vbs-beautifier.html
版权: 本博客的所有文章,都遵守“署名-非商业性使用-相同方式共享 2.5 中国大陆”协议条款。
昨天在VBS吧看到一个精华帖《VBS代码格式化工具》,是用C++写的,区区VBS代码格式化,就不要劳C++大驾了吧,用VBS实现VBS代码格式化工具不是更自然么?
网上的VBS代码大部分都没有缩进,新手不知道要缩进,高手缩进了被某些个垃圾网站采集以后也就没有了缩进,还有以一些博客贴吧也会把缩进给吃掉。除了缩进之外,由于学VBS的大部分都是学批处理出身,代码风格还是跟写批处理一样难看。其实一般情况下用VbsEdit 5.2.4.0自带的代码格式化功能就行了,没有必要重复造轮子。只不过VbsEdit 5.2.4.0在格式化带有冒号的代码时不是很理想,加上我已经很久没有写过像样的VBS脚本了,所以还是决定造一下轮子。
2011年12月27日更新:在线VBScript代码格式化工具VbsBeautifier
因为代码比较长,所以贴在文章的最后,下面是VBS代码格式化工具的效果演示:
格式化前的VBS代码:
ON ERROR RESUME NEXT:Set fso = CreateObject("Scripting.FileSystemObject"):X=0:T=true:WhiLe T Input=Inputbox("Filename Lowercase Batch Convertor"&vbcrlf&vbcrlf& _ "Please input the destination folder name. e.g. C:\Webmaster"&vbcrlf&vbcrlf& _ "Note: Do NOT add '\' in the end of folder name!","FLowercase Convertor","C:\") iF Input="" then:Msgbox"Folder name is empty!",48,"Error!":T=true:else T=false:end If:wend Msgbox"All files names of "&Input&" will be converted to lowercase now...",64,"Note" fold(Input):Msgbox"Done! Total "&X&" file(s) were converted to lowercase.",64,"Done" sub fold(Path):SET f=fso.GetFolder(Path):Set rf = fso.GetFolder(Path).files:Set fc = f.SubFolders foR EACh fff in rf:lcf1=LCase(fso.GetAbsolutePathName(fff)) fso.MoveFile fff, lcf1:X=X + 1:next:for EacH f1 in fc:fold(f1) Set file=fso.GetFolder(f1).files:fOR EACh ff iN file:lcf=LCase(fso.GetAbsolutePathName(ff)) fso.MoveFile ff,lcf:NEXT:NEXT:END sub
格式化后的VBS代码:
On Error Resume Next Set fso = CreateObject("Scripting.FileSystemObject") X = 0 T = True While T Input = InputBox("Filename Lowercase Batch Convertor" & vbCrLf & vbCrLf & _ "Please input the destination folder name. e.g. C:\Webmaster" & vbCrLf & vbCrLf & _ "Note: Do NOT add '\' in the end of folder name!","FLowercase Convertor","C:\") If Input = "" Then MsgBox"Folder name is empty!",48,"Error!" T = True Else T = False End If WEnd MsgBox"All files names of " & Input & " will be converted to lowercase now...",64,"Note" fold(Input) MsgBox"Done! Total " & X & " file(s) were converted to lowercase.",64,"Done" Sub fold(Path) Set f = fso.GetFolder(Path) Set rf = fso.GetFolder(Path).files Set fc = f.SubFolders For Each fff In rf lcf1 = LCase(fso.GetAbsolutePathName(fff)) fso.MoveFile fff, lcf1 X = X + 1 Next For Each f1 In fc fold(f1) Set file = fso.GetFolder(f1).files For Each ff In file lcf = LCase(fso.GetAbsolutePathName(ff)) fso.MoveFile ff,lcf Next Next End Sub
VBS代码格式化工具的源码:
赞赏Option Explicit If WScript.Arguments.Count = 0 Then MsgBox "请将要格式化的代码文件拖动到这个文件上", vbInformation, "使用方法" WScript.Quit End If '作者: Demon '时间: 2011/12/24 '链接: https://demon.tw/my-work/vbs-beautifier.html '描述: VBScript 代码格式化工具 '注意: '1. 错误的 VBScript 代码不能被正确地格式化 '2. 代码中不能含有%[comment]% %[quoted]%等模板标签, 有待改进 '3. 由2可知, 该工具不能格式化自身 Dim Beautifier, i Set Beautifier = New VbsBeautifier For Each i In WScript.Arguments Beautifier.BeautifyFile i Next MsgBox "代码格式化完成", vbInformation, "提示" Class VbsBeautifier 'VbsBeautifier类 Private quoted, comments, code, indents Private ReservedWord, BuiltInFunction, BuiltInConstants, VersionInfo '公共方法 '格式化字符串 Public Function Beautify(ByVal input) code = input code = Replace(code, vbCrLf, vbLf) Call GetQuoted() Call GetComments() Call GetErrorHandling() Call ColonToNewLine() Call FixSpaces() Call ReplaceReservedWord() Call InsertIndent() Call FixIndent() Call PutErrorHandling() Call PutComments() Call PutQuoted() code = Replace(code, vbLf, vbCrLf) code = VersionInfo & code Beautify = code End Function '公共方法 '格式化文件 Public Function BeautifyFile(ByVal path) Dim fso Set fso = CreateObject("scripting.filesystemobject") BeautifyFile = Beautify(fso.OpenTextFile(path).ReadAll) '备份文件以免出错 fso.GetFile(path).Copy path & ".bak", True fso.OpenTextFile(path, 2, True).Write(BeautifyFile) End Function Private Sub Class_Initialize() '保留字 ReservedWord = "And As Boolean ByRef Byte ByVal Call Case Class Const Currency Debug Dim Do Double Each Else ElseIf Empty End EndIf Enum Eqv Event Exit Explicit False For Function Get Goto If Imp Implements In Integer Is Let Like Long Loop LSet Me Mod New Next Not Nothing Null On Option Optional Or ParamArray Preserve Private Property Public RaiseEvent ReDim Rem Resume RSet Select Set Shared Single Static Stop Sub Then To True Type TypeOf Until Variant WEnd While With Xor" '内置函数 BuiltInFunction = "Abs Array Asc Atn CBool CByte CCur CDate CDbl CInt CLng CSng CStr Chr Cos CreateObject Date DateAdd DateDiff DatePart DateSerial DateValue Day Escape Eval Exp Filter Fix FormatCurrency FormatDateTime FormatNumber FormatPercent GetLocale GetObject GetRef Hex Hour InStr InStrRev InputBox Int IsArray IsDate IsEmpty IsNull IsNumeric IsObject Join LBound LCase LTrim Left Len LoadPicture Log Mid Minute Month MonthName MsgBox Now Oct Randomize RGB RTrim Replace Right Rnd Round ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion Second SetLocale Sgn Sin Space Split Sqr StrComp StrReverse String Tan Time TimeSerial TimeValue Timer Trim TypeName UBound UCase Unescape VarType Weekday WeekdayName Year" '内置常量 BuiltInConstants = "vbBlack vbRed vbGreen vbYellow vbBlue vbMagenta vbCyan vbWhite vbBinaryCompare vbTextCompare vbSunday vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday vbUseSystemDayOfWeek vbFirstJan1 vbFirstFourDays vbFirstFullWeek vbGeneralDate vbLongDate vbShortDate vbLongTime vbShortTime vbObjectError vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel vbCritical vbQuestion vbExclamation vbInformation vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 vbDefaultButton4 vbApplicationModal vbSystemModal vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo vbCr vbCrLf vbFormFeed vbLf vbNewLine vbNullChar vbNullString vbTab vbVerticalTab vbUseDefault vbTrue vbFalse vbEmpty vbNull vbInteger vbLong vbSingle vbDouble vbCurrency vbDate vbString vbObject vbError vbBoolean vbVariant vbDataObject vbDecimal vbByte vbArray WScript" '版本信息 VersionInfo = Chr(39) & Chr(86) & Chr(98) & Chr(115) & Chr(66) & Chr(101) & Chr(97) & Chr(117) & Chr(116) & Chr(105) & Chr(102) & Chr(105) & Chr(101) & Chr(114) & Chr(32) & Chr(49) & Chr(46) & Chr(48) & Chr(32) & Chr(98) & Chr(121) & Chr(32) & Chr(68) & Chr(101) & Chr(109) & Chr(111) & Chr(110) & Chr(13) & Chr(10) & Chr(39) & Chr(104) & Chr(116) & Chr(116) & Chr(112) & Chr(58) & Chr(47) & Chr(47) & Chr(100) & Chr(101) & Chr(109) & Chr(111) & Chr(110) & Chr(46) & Chr(116) & Chr(119) & Chr(13) & Chr(10) '缩进大小 Set indents = CreateObject("scripting.dictionary") indents("if") = 1 indents("sub") = 1 indents("function") = 1 indents("property") = 1 indents("for") = 1 indents("while") = 1 indents("do") = 1 indents("for") = 1 indents("select") = 1 indents("with") = 1 indents("class") = 1 indents("end") = -1 indents("next") = -1 indents("loop") = -1 indents("wend") = -1 End Sub Private Sub Class_Terminate() '什么也不做 End Sub '将字符串替换成%[quoted]% Private Sub GetQuoted() Dim re Set re = New RegExp re.Global = True re.Pattern = """.*?""" Set quoted = re.Execute(code) code = re.Replace(code, "%[quoted]%") End Sub '将%[quoted]%替换回字符串 Private Sub PutQuoted() Dim i For Each i In quoted code = Replace(code, "%[quoted]%", i, 1, 1) Next End Sub '将注释替换成%[comment]% Private Sub GetComments() Dim re Set re = New RegExp re.Global = True re.Pattern = "'.*" Set comments = re.Execute(code) code = re.Replace(code, "%[comment]%") End Sub '将%[comment]%替换回注释 Private Sub PutComments() Dim i For Each i In comments code = Replace(code, "%[comment]%", i, 1, 1) Next End Sub '将冒号替换成换行 Private Sub ColonToNewLine code = Replace(code, ":", vbLf) End Sub '将错误处理语句替换成模板标签 Private Sub GetErrorHandling() Dim re Set re = New RegExp re.Global = True re.IgnoreCase = True re.Pattern = "on\s+error\s+resume\s+next" code = re.Replace(code, "%[resumenext]%") re.Pattern = "on\s+error\s+goto\s+0" code = re.Replace(code, "%[gotozero]%") End Sub '将模板标签替换回错误处理语句 Private Sub PutErrorHandling() code = Replace(code, "%[resumenext]%", "On Error Resume Next") code = Replace(code, "%[gotozero]%", "On Error GoTo 0") End Sub '格式化空格 Private Sub FixSpaces() Dim re Set re = New RegExp re.Global = True re.IgnoreCase = True re.MultiLine = True '去掉每行前后的空格 re.Pattern = "^[ \t]*(.*?)[ \t]*$" code = re.Replace(code, "$1") '在操作符前后添加空格 re.Pattern = "[ \t]*(=|<|>|-|\+|&|\*|/|\^|\\)[ \t]*" code = re.Replace(code, " $1 ") '去掉<>中间的空格 re.Pattern = "[ \t]*<\s*>[ \t]*" code = re.Replace(code, " <> ") '去掉<=中间的空格 re.Pattern = "[ \t]*<\s*=[ \t]*" code = re.Replace(code, " <= ") '去掉>=中间的空格 re.Pattern = "[ \t]*>\s*=[ \t]*" code = re.Replace(code, " >= ") '在行尾的 _ 前面加上空格 re.Pattern = "[ \t]*_[ \t]*$" code = re.Replace(code, " _") '去掉Do While中间多余的空格 re.Pattern = "[ \t]*Do\s*While[ \t]*" code = re.Replace(code, "Do While") '去掉Do Until中间多余的空格 re.Pattern = "[ \t]*Do\s*Until[ \t]*" code = re.Replace(code, "Do Until") '去掉End Sub中间多余的空格 re.Pattern = "[ \t]*End\s*Sub[ \t]*" code = re.Replace(code, "End Sub") '去掉End Function中间多余的空格 re.Pattern = "[ \t]*End\s*Function[ \t]*" code = re.Replace(code, "End Function") '去掉End If中间多余的空格 re.Pattern = "[ \t]*End\s*If[ \t]*" code = re.Replace(code, "End If") '去掉End With中间多余的空格 re.Pattern = "[ \t]*End\s*With[ \t]*" code = re.Replace(code, "End With") '去掉End Select中间多余的空格 re.Pattern = "[ \t]*End\s*Select[ \t]*" code = re.Replace(code, "End Select") '去掉Select Case中间多余的空格 re.Pattern = "[ \t]*Select\s*Case[ \t]*" code = re.Replace(code, "Select Case ") End Sub '将保留字 内置函数 内置常量 替换成首字母大写 Private Sub ReplaceReservedWord() Dim re, words, word Set re = New RegExp re.Global = True re.IgnoreCase = True re.MultiLine = True words = Split(ReservedWord, " ") For Each word In words re.Pattern = "(\b)" & word & "(\b)" code = re.Replace(code, "$1" & word & "$2") Next words = Split(BuiltInFunction, " ") For Each word In words re.Pattern = "(\b)" & word & "(\b)" code = re.Replace(code, "$1" & word & "$2") Next words = Split(BuiltInConstants, " ") For Each word In words re.Pattern = "(\b)" & word & "(\b)" code = re.Replace(code, "$1" & word & "$2") Next End Sub '插入缩进 Private Sub InsertIndent() Dim lines, line, i, n, t, delta lines = Split(code, vbLf) n = UBound(lines) For i = 0 To n line = lines(i) SingleLineIfThen line t = delta delta = delta + CountDelta(line) If t <= delta Then lines(i) = String(t, vbTab) & lines(i) Else lines(i) = String(delta, vbTab) & lines(i) End If Next code = Join(lines, vbLf) End Sub '调整错误的缩进 Private Sub FixIndent() Dim lines, i, n, re Set re = New RegExp re.IgnoreCase = True lines = Split(code, vbLf) n = UBound(lines) For i = 0 To n re.Pattern = "^\t*else" If re.Test(lines(i)) Then lines(i) = Replace(lines(i), vbTab, "", 1, 1) End If Next code = Join(lines, vbLf) End Sub '计算缩进大小 Private Function CountDelta(ByRef line) Dim i, re, delta Set re = New RegExp re.Global = True re.IgnoreCase = True For Each i In indents.Keys re.Pattern = "^\s*\b" & i & "\b" If re.Test(line) Then '方便调试 'WScript.Echo line line = re.Replace(line, "") delta = delta + indents(i) End If Next CountDelta = delta End Function '处理单行的If Then Private Sub SingleLineIfThen(ByRef line) Dim re Set re = New RegExp re.IgnoreCase = True re.Pattern = "if.*?then.+" line = re.Replace(line, "") '去掉Private Public前缀 re.Pattern = "(private|public).+?(sub|function|property)" line = re.Replace(line, "$2") End Sub End Class 'Demon, 于2011年平安夜
微信赞赏支付宝赞赏
随机文章:
做个网页版的,类似于:http://www.yongfa365.com/Tools/CodeColor/js-format-compress.html
做好能着色:http://www.yongfa365.com/Tools/CodeColor/JavaScript-Version-CodeColor.html
网页版有时间再写吧,或者你帮忙写一个?
代码高亮用EditPlus的Copy as HTML功能就行了,没有必要再写,虽然不是很难实现。
话说《VBS字符串的内部实现》你看到了吗,也不留个言,专门为你写的呢。
《VBS字符串的内部实现》已经拜读过了,写的很好,呵呵,你研究的很深入。你的博客写的很棒,以后要多向你学习。
呵呵,欢迎常来。
支持下,正则是个好东西
提点改进意见哈:
最好能支持unicode文件.
你之前也写过通过BOM判断文件编码和判断无BOM文件的编码,如果能融合进来,似乎会完美一些
《在线VBScript代码格式化工具VbsBeautifier》支持Unicode。
[…] 根据雨中风铃在《用VBS写的VBS代码格式化工具VbsBeautifier》中的建议,写了一个在线版的VBScript代码格式化工具。 […]
这个很好,可以作为EmEditor的外置式VBS代码格式化工具了!
博主新年好!!
我不是程序员, 不过有时候需要写一些批处理.
希望博主能考虑写一个格式化批处理的脚本, 方便一下广大群众.
先谢过了!
你好,也祝你新年快乐。
我不喜欢批处理,批处理没有任何语法可言,想写一个格式化工具非常的困难。
博主辛苦了。博主写的东西学习了。超级赞。
发现有点小问题博主可否完善下:
一是if语句后有注释当作单行if语句处理了。
二是博主把冒号直接替换为回车,这于逻辑有时候是不对的。
谢谢~~~~~~~~~~
博主,我在使用中发现一个小bug:
对于包含16进制常数“&HXXXXXX”的代码中间依然添加了空格,导致vbsedit编译通不过。
稍微修改这句代码可以排除这种情况:
‘在操作符前后添加空格
re.Pattern = “[ \t]*(=||-|\+|&(?!H)|\*|/|\^|\\)[ \t]*”
是楼主的这个代码让我接触并了解了正则表达式,感谢!
还有O开头的八进制呢。
我也写了个,不过冒号:没考虑哈。直接readline哈哈,简单直接,正好偷懒。。。
代码如下:
add()
dim text,fso,regex,dic,dic2,sn,n
sn=8
Set fso = CreateObject(“scripting.filesystemobject”)
Set dic = CreateObject(“Scripting.Dictionary”)
Set dic2 = CreateObject(“Scripting.Dictionary”)
Set regex = New RegExp
regex.IgnoreCase =True
Set file = fso.OpenTextFile(WScript.Arguments.Item(0),1,true)
Do While file.AtEndOfStream True
strtxt=trim(replace(file.readline,vbtab,” “))
regex.pattern=”^(\bif[\s\S]+then [^’]{2,}[\s\S]+)”
if not regex.test(strtxt) Then
regex.pattern=”^(f\bfunction\b|\bsub\b|\bclass\b|\bprivate function\b|\bpublic function\b|\bprivate sub\b|\bpublic sub\b)”
if regex.test(strtxt) then
fun=fun+1
strTabNumber=””
end If
regex.pattern=”^(\bend function\b|\bend sub\b|\bend class\b)”
if regex.test(strtxt) then
fun=fun-1
strTabNumber=””
end If
regex.Pattern=”^(\bif\b|\bdo\b|\bfor\b|\bselect\b)”
if regex.test(strtxt) then
if fun=0 then
n=dic.Count+1
dic.add n,strtxt
strTabNumber=space(dic.count*sn)
else
m=dic2.Count+1
dic2.add m,strtxt
strTabNumber=space(dic2.count*sn)
end If
Else
regex.Pattern=”^(\belse\b|\belseif\b|\bcase\b)”
If regex.test(strtxt) then
if fun=0 then
If dic.Count>=1 Then strTabNumber=space((dic.Count)*sn)
Else
If dic2.Count>=1 Then strTabNumber=space((dic2.Count)*sn)
End If
Else
if fun=0 then
If dic.Count>=1 Then strTabNumber=space((dic.Count+1)*sn)
Else
If dic2.Count>=1 Then strTabNumber=space((dic2.Count+1)*sn)
End If
End If
regex.pattern=”^(end if|next|end select|loop|wend)”
if regex.test(strtxt) then
if fun=0 Then
dic.Remove(dic.Count)
n=dic.Count
strTabNumber=space((dic.Count+1)*sn)
Else
dic2.remove(dic2.Count)
m=dic2.Count
strTabNumber=space((dic2.Count+1)*sn)
End If
Else
if fun0 Then
If dic2.Count=0 Then strTabNumber=””
Else
If dic.Count=0 Then strTabNumber=””
End if
end If
End If
Else
if fun0
add()
dim text,fso,regex,dic,dic2,sn,n
sn=8
Set fso = CreateObject(“scripting.filesystemobject”)
Set dic = CreateObject(“Scripting.Dictionary”)
Set dic2 = CreateObject(“Scripting.Dictionary”)
Set regex = New RegExp
regex.IgnoreCase =True
Set file = fso.OpenTextFile(WScript.Arguments.Item(0),1,true)
Do While file.AtEndOfStream True
strtxt=trim(replace(file.readline,vbtab,” “))
regex.pattern=”^(\bif[\s\S]+then [^’]{2,}[\s\S]+)”
if not regex.test(strtxt) Then
regex.pattern=”^(f\bfunction\b|\bsub\b|\bclass\b|\bprivate function\b|\bpublic function\b|\bprivate sub\b|\bpublic sub\b)”
if regex.test(strtxt) then
fun=fun+1
strTabNumber=””
end If
regex.pattern=”^(\bend function\b|\bend sub\b|\bend class\b)”
if regex.test(strtxt) then
fun=fun-1
strTabNumber=””
end If
regex.Pattern=”^(\bif\b|\bdo\b|\bfor\b|\bselect\b)”
if regex.test(strtxt) then
if fun=0 then
n=dic.Count+1
dic.add n,strtxt
strTabNumber=space(dic.count*sn)
else
m=dic2.Count+1
dic2.add m,strtxt
strTabNumber=space(dic2.count*sn)
end If
Else
regex.Pattern=”^(\belse\b|\belseif\b|\bcase\b)”
If regex.test(strtxt) then
if fun=0 then
If dic.Count>=1 Then strTabNumber=space((dic.Count)*sn)
Else
If dic2.Count>=1 Then strTabNumber=space((dic2.Count)*sn)
End If
Else
if fun=0 then
If dic.Count>=1 Then strTabNumber=space((dic.Count+1)*sn)
Else
If dic2.Count>=1 Then strTabNumber=space((dic2.Count+1)*sn)
End If
End If
regex.pattern=”^(end if|next|end select|loop|wend)”
if regex.test(strtxt) then
if fun=0 Then
dic.Remove(dic.Count)
n=dic.Count
strTabNumber=space((dic.Count+1)*sn)
Else
dic2.remove(dic2.Count)
m=dic2.Count
strTabNumber=space((dic2.Count+1)*sn)
End If
Else
if fun0 Then
If dic2.Count=0 Then strTabNumber=””
Else
If dic.Count=0 Then strTabNumber=””
End if
end If
End If
Else
if fun0 Then
If dic2.Count0 Then strTabNumber=space((dic2.Count+1)*sn)
Else
If dic.Count0 Then strTabNumber=space((dic.Count+1)*sn)
End if
end if
If strtxt”” Then text=text&strTabNumber&strtxt&vbCrLf
loop
file.close
set file=nothing
Set file = fso.OpenTextFile(WScript.Arguments.Item(0),2,true)
file.write text
file.close
set file=Nothing
Sub add()
Dim wsh
Set wsh = CreateObject(“wscript.shell”)
‘ 直接运行脚本则提醒*******************************************
If WScript.Arguments.Count=0 Then
Wsh.RegWrite “HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\shell\VbsFormatTool\”, “VBS代码格式化工具”, “REG_SZ”
Wsh.RegWrite “HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\\shell\VbsFormatTool\command\”, “wscript.exe “&Chr(34)&WScript.ScriptFullName&Chr(34)&Chr(32)&chr(34)&”%1″&chr(34), “REG_SZ”
wsh.Popup “VBS代码格式化工具”,9,”请不要直接运行脚本”,64
WScript.Quit
End If
End Sub
Dim tt
Set tt=createobject(“sapi.spvoice”)
tt.speak(“OK”)
MsgBox “完成”