使用IDE宏遍历代码中的非ASCII字符

    在产品开发的时候,虽然大家知道需要做I18N的支持。不过在开发代码的过程中,由于需要首先关注逻辑实现,所以文件中也难免会hardcode中文文字什么的。在代码的UI描述和业务逻辑都很稳定后,最后还需要清理一下代码中是否还有中文资源,因为那些类似错误提示一类的描述,在程序未出错时Tester几乎是无法发现的。

    不过这个检查如果靠眼睛看,也是非常之郁闷的事情,那么除了编写额外的工具分析文档,还有没有其它简单又自动的方法帮我们解决问题呢?由于VS.NET 2003给我提供了非常强大的宏功能(可以在宏中使用.NET Framework类库!),所以对于这种小case使用宏来解决就太合适不过了。下面这个宏的功能就是在当前文档中找出非ASCII字符,并把出现的行号和内容输出到Output工具窗口中。代码如下:
Imports EnvDTE
Imports System.Windows.Forms
Imports System.Text
Imports System.Globalization
Imports System.Text.RegularExpressions
Imports System.Diagnostics
Imports MyMacros.Util

Public Module Birdshome
    
Sub FindChineseWords()
        
Dim doc As Document = DTE.ActiveDocument
        
Dim docText As TextDocument = doc.Object
        
Dim lineCount = docText.EndPoint.Line
        
Dim ep As EditPoint = docText.StartPoint.CreateEditPoint()
        
Dim strLine As String
        
Dim i As Integer
        
Dim regex As Regex = New Regex("[^\u0000-\u00ff]+")
        
Dim strbResult As StringBuilder = New StringBuilder
        
For i = 1 To lineCount - 1
            strLine 
= ep.GetLines(i, i + 1)
            
Dim m As MatchCollection = regex.Matches(strLine)
            
If m.Count > 0 Then
                strbResult.Append(i.ToString())
                strbResult.Append(
"")
                
Dim j As Integer
                
For j = 0 To m.Count - 1
                    strbResult.Append(m(j).Value)
                    strbResult.Append(
"")
                
Next
                strbResult.Length 
= strbResult.Length - 2
                strbResult.Append(
";")
                strbResult.Append(System.Environment.NewLine)
            
End If
        
Next
        
'MessageBox.Show(strbResult.ToString)
        Dim win As Window = DTE.Windows.Item(Constants.vsWindowKindCommandWindow)
        
Dim target As Object
        
If (DTE.ActiveWindow Is win) Then
            target 
= win.Object
        
Else
            target 
= GetOutputWindowPane("Chinese Words")
            target.clear()
        
End If
        target.OutputString(strbResult.ToString())
    End Sub

End Module

    方法GetOutputWindowPane在如下公用模块中:
Imports EnvDTE
Imports System.Diagnostics

Public Module Util
    
Function GetOutputWindowPane(ByVal Name As StringOptional ByVal show As Boolean = TrueAs OutputWindowPane
        
Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
        
If show Then win.Visible = True
        
Dim ow As OutputWindow = win.Object
        
Dim owpane As OutputWindowPane
        
Try
            owpane 
= ow.OutputWindowPanes.Item(Name)
        
Catch e As System.Exception
            owpane 
= ow.OutputWindowPanes.Add(Name)
        
End Try
        owpane.Activate()
        
Return owpane
    
End Function

End Module
// 多写写VB,觉得它的语法还是挺自然的:)

    以中文google首页的html代码(Formatted by IDE)为示例,运行本脚本代码的结果如下图:
    ChineseWords.png

posted on 2005-12-25 14:53  birdshome  阅读(1350)  评论(4编辑  收藏  举报

导航