标题: [原创] VBS实现代码关键词格式化书写以及颜色高亮排版功能 [打印本页]
作者: batman 时间: 2013-1-25 23:30 标题: VBS实现代码关键词格式化书写以及颜色高亮排版功能
本帖最后由 batman 于 2013-1-29 08:04 编辑
没有什么技术含量,只是一时无聊之作,请将要排版的VBS拖放在本VBS上(因为暂时定义的是VBS语法关键词,想要排版批处理的请自行修改关键词),本来是想为论坛发帖时美化代码所写,可惜论坛现在的设置不支持HTML代码:- Dim File
- On Error Resume Next
- File = WScript.Arguments.Item(0)
- If File = vbNullString Then WScript.Quit
- Dim Codes, FCTs, VBstrs, Values, objArray, ColorArray
- Codes = "and,or,for,each,to,step,next,if,then,else,end,set,dim,ReDim,do,while,wend,until,loop,exit,with,function,in,select,case,true,false"
- FCTs = "abs,array,asc,atn,cbool,cbyte,ccur,cdate,cdbl,chr,cint,class,clear,clng,const,cos,createobject,csng,cstr,date,dateadd,datediff,datepart,dateserial,datevalue,day,description,dictionary,empty,eqv,erase,err,eval,execute,execute,exp,filesystemobject,filter,firstindex,fix,formatcurrency,formatdatetime,formatnumber,formatpercent,function,getobject,getref,global,hex,helpcontext,helpfile,hour,ignorecase,imp,inputbox,instr,instrrev,int,isarray,isdate,isempty,isnull,isnumeric,isobject,join,lbound,lcase,left,len,length,loadpicture,log,ltrim,match,matches,mid,minute,mod,month,monthname,msgbox,msgbox,now,number,oct,option,pattern,private,propertyget,propertylet,propertyset,public,raise,randomize,redim,regexp,rem,replace,replace,rgb,right,rnd,round,rtrim,scriptengine,scriptenginebuildversion,scriptenginemajorversion,scriptengineminorversion,second,sgn,sin,source,space,split,sqr,strcomp,string,strreverse,sub,tan,test,time,timer,timeserial,timevalue,trim,typename,ubound,ucase,value,vartype,vartype,vbscript,weekday,weekdayname,wscript,xor,year"
- VBstrs = "vbcrlf,vbcr,vblf,vbtab,vbyesno,vbtrue,vbfalse,vbnullstring,vbformfeed,vbnewline,vbnullchar,vbnull,vbyes,vbno,vbok,vbcancle,vbokcancle,nothing"
- objArray = Array(Codes, FCTs, VBstrs)
- ColorArray = Array("darkorchid","blue","green")
- Dim objFSO, objStr, HeadStr, EndStr, Temp
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- Temp = objFSO.GetSpecialFolder(2) & "\"
- HeadStr = "<html>" & vbCrLf _
- & "<body bgcolor=""black"">" & vbCrLf _
- & "<pre>" & vbCrLf _
- & "<font color=""white"" size=4>"
- EndStr = "</font>" & vbCrLf _
- & "</pre>" & vbCrLf _
- & "</body>" & vbCrLf _
- & "</html>"
- Dim Arr, subArr, Arr1, subArr1, Arr2, subArr2, Str, WriteStr, Var
- objStr = objFSO.OpenTextFile(File).ReadAll()
- Arr = Split(objStr, vbCrLf)
- For Each subArr In Arr
- Arr1 = Split(subArr, " ")
- For Each subArr1 In Arr1
- Str = subArr1
- For i = 0 To UBound(objArray)
- Arr2 = Split(objArray(i), ",")
- For Each subArr2 In Arr2
- If i = 1 Then
- If InStr(LCase(subArr1), subArr2 & "(") Or _
- InStr(LCase(subArr1), subArr2 & " ") Or _
- InStr(LCase(subArr1), subArr2 & ".") Then
- Var = UCase(Left(subArr2, 1)) & LCase(Mid(subArr2, 2, Len(subArr2)))
- Var = "<font color=""" & ColorArray(i) & """>" & Var & "</font>"
- Str = Replace(LCase(subArr1), subArr2, Var)
- End If
- Else
- If LCase(subArr1) = subArr2 Then
- Str = UCase(Left(subArr1, 1)) & LCase(Mid(subArr1, 2, Len(subArr1)))
- Str = "<font color=""" & ColorArray(i) & """>" & Str & "</font>"
- End If
- End If
- Next
- Next
- WriteStr = WriteStr & Str & " "
- Next
- WriteStr = WriteStr & vbCrLf
- Next
- '本可以用IE对象直接写的,但考虑IE浏览器不一定靠谱,所以还是用临时文件来输出
- objFSO.OpenTextFile(Temp & "temp.html", 2, True).Write HeadStr & WriteStr & EndStr
- Set objFSO = Nothing
- CreateObject("Wscript.Shell").Run Temp & "temp.html", True, False
复制代码
作者: Demon 时间: 2013-1-26 00:12
本帖最后由 Demon 于 2013-1-26 00:16 编辑
粗略看了一下,挑点骨头:
1、没有包括所有VBS关键字、常量、函数(见《VBS关键字和保留字》、《VBS内置常量大全》、《VBS内置函数大全》、
2、没有考虑字符串中的高亮问题
3、没有考虑制表符\t
4、论坛可以使用discuz code
5、EditPlus自带Copy as HTML功能
6、暂时没想到
可以参考我写的VBS代码格式化工具,当然,我写的也并不完美,想要完美的话需要对脚本进行词法分析和语法分析,一直想写,但是一直没有时间,楼主有时间的话不妨研究一下。
作者: batman 时间: 2013-1-26 21:32
感谢Demon的帮助,先修改如下:
1、补充了大量关键词
2、对字符串中的关键词进行了筛选判断(同时效率降低不少)
3、关键词大小写定位
4、语法分析暂无时间和能力去做
5、欢迎大家测试和批评指正- Dim File
- On Error Resume Next
- File = WScript.Arguments.Item(0)
- If File = vbNullString Then WScript.Quit
- Dim Codes, FCTs, VBstrs, Values, objArray, ColorArray, HeadArray, EndArray
- Codes = "Xor,Mod,Private,And,Or,For,Each,To,Step,Next,If,Then,Else,End,Set,Dim,ReDim,Do,While,Wend,Until,Loop,Exit,With,Function,Sub,In,Select,Case,Class"
- FCTs = "Year,Wsh,Wscript,WeekdayName,Weekday,VarType,Unescape,UCase,UBound,TypeName,Trim,TimeValue,TimeSerial,Timer,Time,Tan,StrReverse,string,StrComp,Sqr,Split,Space,Sin,Sgn,Second,ScriptEngineMinorVersion,ScriptEngineMajorVersion,ScriptEngineBuildVersion,ScriptEngine,RTrim,Round,Rnd,RightB,Right,RGB,Replace,Randomize,Oct,Now,MsgBox,MonthName,Month,Minute,MidB,Mid,LTrim,Log,LoadPicture,LenB,Len,LeftB,Left,LCase,LBound,Join,IsObject,IsNumeric,IsNull,IsEmpty,IsDate,IsArray,Int,InStrRev,InStrB,InStr,InputBox,Hour,Hex,GetRef,GetObject,FormatPercent,FormatNumber,FormatDateTime,FormatCurrency,Fix,Filter,Exp,ExecuteGlobal,Execute,Eval,Escape,Erase,Day,DateValue,DateSerial,DatePart,DateDiff,DateAdd,Date,CStr,CSng,CreateObject,Cos,CLng,CInt,ChrW,ChrB,Chr,CDbl,CDate,CCur,CByte,CBool,Atn,AscW,AscB,Asc,Array,Abs"
- VBstrs = "vbYesNoCancel,vbYesNo,vbYes,vbYellow,vbWhite,vbWednesday,vbVerticalTab,vbVariant,vbUseSystemDayOfWeek,vbUseSystem,vbUseDefault,vbTuesday,vbTrue,vbThursday,vbTextCompare,vbTab,vbSystemModal,vbSunday,vbString,vbSingle,vbShortTime,vbShortDate,vbSaturday,vbRetryCancel,vbRetry,vbRed,vbQuestion,vbOKOnly,vbOKCancel,vbOK,vbObjectError,vbObject,vbNullString,vbNullChar,vbNull,vbNo,vbNewLine,VbMsgBoxSetForeground,vbMsgBoxRtlReading,vbMsgBoxRight,vbMsgBoxHelpButton,vbMonday,vbMagenta,vbLongTime,vbLongDate,vbLong,vbLf,vbInteger,vbInformation,vbIgnore,vbGreen,vbGeneralDate,vbFriday,vbFormFeed,vbFirstJan1,vbFirstFullWeek,vbFirstFourDays,vbFalse,vbExclamation,vbError,vbEmpty,vbDouble,vbDefaultButton4,vbDefaultButton3,vbDefaultButton2,vbDefaultButton1,vbDecimal,vbDate,vbDataObject,vbDatabaseCompare,vbCyan,vbCurrency,vbCrLf,vbCritical,vbCr,vbCancel,vbByte,vbBoolean,vbBlue,vbBlack,vbBinaryCompare,vbArray,vbApplicationModal,vbAbortRetryIgnore,vbAbort,True,Nothing,False"
- objArray = Array(Codes, FCTs, VBstrs)
- ColorArray = Array("darkorchid","blue","green")
- HeadArray = Array("&", "(", ".", ",", "")
- EndArray = Array(".", "(", "")
- Dim objFSO, objStr, HeadStr, EndStr, Temp
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- Temp = objFSO.GetSpecialFolder(2) & "\"
- HeadStr = "<html>" & vbCrLf _
- & "<body bgcolor=""black"">" & vbCrLf _
- & "<pre>" & vbCrLf _
- & "<font color=""white"" size=4>"
- EndStr = "</font>" & vbCrLf _
- & "</pre>" & vbCrLf _
- & "</body>" & vbCrLf _
- & "</html>"
- Dim Arr, subArr, Arr1, subArr1, Arr2, subArr2, Str, WriteStr, Var, Hstr, Estr, OK
- objStr = objFSO.OpenTextFile(File).ReadAll()
- Arr = Split(objStr, vbCrLf)
- For Each subArr In Arr
- Arr1 = Split(subArr, " ")
- For Each subArr1 In Arr1
- Str = subArr1
- For i = 0 To UBound(objArray)
- Arr2 = Split(objArray(i), ",")
- For Each subArr2 In Arr2
- OK = "b"
- If i = 1 Then
- For Each Hstr In HeadArray
- For Each Estr In EndArray
- If Hstr = "" And Estr <> "" Then
- If InStr(1, Str, Hstr & subArr2 & Estr, 1) = 1 Then OK = "a"
- Else
- If Estr = "" Then
- If InStr(1, Str, Hstr & subArr2 & Estr, 1) And _
- LCase(Right(Str, Len(subArr2))) = LCase(subArr2) And _
- Hstr <>"" Then OK = "a"
- Else
- If InStr(1, Str, Hstr & subArr2 & Estr, 1) Or _
- LCase(Str) = LCase(subArr2) Then OK = "a"
- End If
- End If
- Next
- Next
- Else
- If i = 2 Then
- If LCase(Str) = LCase(subArr2) Or _
- InStr(1, Str, "&" & subArr2, 1) Or _
- InStr(1, Str, subArr2 & "&", 1) Or _
- InStr(1, Str, "&" & subArr2 & "&", 1) Then OK = "a"
- Else
- If LCase(Str) = LCase(subArr2) Then OK = "a"
- End If
- End If
- If OK = "a" Then
- Var = subArr2
- Var = "<font color=""" & ColorArray(i) & """>" & Var & "</font>"
- Str = Replace(Str, subArr2, Var, 1, -1, 1)
- End If
- Next
- Next
- WriteStr = WriteStr & Str & " "
- Next
- WriteStr = WriteStr & vbCrLf
- Next
- '本可以用IE对象直接写的,但考虑IE浏览器不一定靠谱,所以还是用临时文件来输出
- objFSO.OpenTextFile(Temp & "temp.html", 2, True).Write HeadStr & WriteStr & EndStr
- Set objFSO = Nothing
- CreateObject("Wscript.Shell").Run Temp & "temp.html", True, False
复制代码
附本人测试的实际可能出现的一些代码组合情况:
作者: batman 时间: 2013-1-27 00:28
稍做修改后的实际应用:
http://user.qzone.qq.com/8416151 ... &pos=1359215037
ps:qq空间太水了,连HTML的PRE标签都不识别,搞得代码都没了格式
作者: batman 时间: 2013-1-29 00:27
本帖最后由 batman 于 2013-1-29 08:05 编辑
利用VBS正则解决关键词准确判断以及效率双问题,同时简化代码:- Dim File
- On Error Resume Next
- File = WScript.Arguments.Item(0)
- If File = vbNullString Then WScript.Quit
- Dim Codes, FCTs, VBstrs, Values, objArray, ColorArray, HeadArray, EndArray
- Codes = "Xor,Mod,Private,And,Or,For,Each,To,Step,Next,If,Then,Else,End,Set,Dim,ReDim,Do,While,Wend,Until,Loop,Exit,With,Function,Sub,In,Select,Case"
- FCTs = "Year,Wsh,Wscript,WeekdayName,Weekday,VarType,Unescape,UCase,UBound,TypeName,Trim,TimeValue,TimeSerial,Timer,Time,Tan,StrReverse,string,StrComp,Sqr,Split,Space,Sin,Sgn,Second,ScriptEngineMinorVersion,ScriptEngineMajorVersion,ScriptEngineBuildVersion,ScriptEngine,RTrim,Round,Rnd,RightB,Right,RGB,Replace,Randomize,Oct,Now,MsgBox,MonthName,Month,Minute,MidB,Mid,LTrim,Log,LoadPicture,LenB,Len,LeftB,Left,LCase,LBound,Join,IsObject,IsNumeric,IsNull,IsEmpty,IsDate,IsArray,Int,InStrRev,InStrB,InStr,InputBox,Hour,Hex,GetRef,GetObject,FormatPercent,FormatNumber,FormatDateTime,FormatCurrency,Fix,Filter,Exp,ExecuteGlobal,Execute,Eval,Escape,Erase,Day,DateValue,DateSerial,DatePart,DateDiff,DateAdd,Date,CStr,CSng,CreateObject,Cos,CLng,CInt,ChrW,ChrB,Chr,CDbl,CDate,CCur,CByte,CBool,Atn,AscW,AscB,Asc,Array,Abs"
- VBstrs = "vbYesNoCancel,vbYesNo,vbYes,vbYellow,vbWhite,vbWednesday,vbVerticalTab,vbVariant,vbUseSystemDayOfWeek,vbUseSystem,vbUseDefault,vbTuesday,vbTrue,vbThursday,vbTextCompare,vbTab,vbSystemModal,vbSunday,vbString,vbSingle,vbShortTime,vbShortDate,vbSaturday,vbRetryCancel,vbRetry,vbRed,vbQuestion,vbOKOnly,vbOKCancel,vbOK,vbObjectError,vbObject,vbNullString,vbNullChar,vbNull,vbNo,vbNewLine,VbMsgBoxSetForeground,vbMsgBoxRtlReading,vbMsgBoxRight,vbMsgBoxHelpButton,vbMonday,vbMagenta,vbLongTime,vbLongDate,vbLong,vbLf,vbInteger,vbInformation,vbIgnore,vbGreen,vbGeneralDate,vbFriday,vbFormFeed,vbFirstJan1,vbFirstFullWeek,vbFirstFourDays,vbFalse,vbExclamation,vbError,vbEmpty,vbDouble,vbDefaultButton4,vbDefaultButton3,vbDefaultButton2,vbDefaultButton1,vbDecimal,vbDate,vbDataObject,vbDatabaseCompare,vbCyan,vbCurrency,vbCrLf,vbCritical,vbCr,vbCancel,vbByte,vbBoolean,vbBlue,vbBlack,vbBinaryCompare,vbArray,vbApplicationModal,vbAbortRetryIgnore,vbAbort,True,Nothing,False"
- objArray = Array(Codes, FCTs, VBstrs)
- ColorArray = Array("darkorchid","blue","green")
- Dim objFSO, ReadStr, HeadStr, EndStr, Temp
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- Temp = objFSO.GetSpecialFolder(2) & "\"
- HeadStr = "<html>" & vbCrLf _
- & "<body bgcolor=""black"">" & vbCrLf _
- & "<pre>" & vbCrLf _
- & "<font color=""white"" size=4>"
- EndStr = "</font>" & vbCrLf _
- & "</pre>" & vbCrLf _
- & "</body>" & vbCrLf _
- & "</html>"
- ReadStr = vbCrLf & objFSO.OpenTextFile(File).ReadAll()
- Dim WriteStr
- GetHtmlCode ReadStr
- objFSO.OpenTextFile(Temp & "temp.html", 2, True).Write HeadStr & WriteStr & EndStr
- Set objFSO = Nothing
- CreateObject("Wscript.Shell").Run Temp & "temp.html", True, False
-
- Function GetHtmlCode(Str)
- Dim objReg, objMaches, objMache
- Set objReg = New RegExp
- objReg.Global = True
- objReg.IgnoreCase = True
- objReg.Pattern = "([\s\S]+?)([^\s&,\(\.\):]*)"
- Set objMaches = objReg.Execute(Str)
- Dim Arr, SubStr, OK, objStr
- For Each objMache In objMaches
- OK = vbNullString
- For i = 0 To UBound(objArray)
- Arr = Split(objArray(i), ",")
- For Each SubStr In Arr
- If LCase(objMache.Submatches(1)) = LCase(SubStr) Then
- OK = "a"
- WriteStr = WriteStr & objMache.Submatches(0) & "<font color=" & ColorArray(i) & ">" & SubStr & "</font>"
- End If
- Next
- Next
- If OK = vbNullString Then WriteStr = WriteStr & objMache.Submatches(0) & objMache.Submatches(1)
- Next
- Set objReg = Nothing
- End Function
复制代码
作者: yu2n 时间: 2013-7-7 17:06
嘿嘿,挑骨头就是舒服。
我也提一个,没有考虑读取VBS文件时,编码的问题。
还有 代码看得我头晕啊。
作者: PowerShell 时间: 2013-7-7 18:23
谁会把代码格式化程序写成逻辑原理,即文字说明
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |