`
hcmfys
  • 浏览: 356318 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

代码格式化 JAVA c# CodeFormat

    博客分类:
  • c#
阅读更多

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace jsCodeFormater
{
    /// <summary>
    /// 代码格式化工具 V 0.1
    /// Author:hcmfys@163.com 小光棍
    /// 2008-11-11 光棍节
    /// 还有错误
    /// </summary>
    public class CodeFormater
    {
        private Hashtable _choiceElement;
        private Hashtable _singleEyeElement;
        private Hashtable _quotation;
        private Hashtable _function;
        private Hashtable _blockElement;

        private int _tabNum = 0;
        private string _wordDelimiters = "  ,.?!;:\\/<>(){}[]\"'\r\n\t=+-|*%@#$^&";
        private bool _deleteComment = false;
        //是否大小写敏感
        private bool _caseSensitive = true;
        //本行括号内分号不做换行
        private string _isFor = "for";
        private string _beginBlock = "{";
        private string _endBlock = "}";
        //得到分割字符
        //引用字符
        //行注释字符
        private string _lineComment = "//";
        //转义字符
        private string _escape = "\\";
        //多行引用开始
        private string _commentOn = "/*";
        //多行引用结束
        private string _commentOff = "*/";
        //行结束词
        private string _rowEnd = ";";
        private string _in = "in";
        private bool isCompress = false;
        private int style = 0;


        private bool quote_opened = false;    //引用标记
        private bool slash_slash_comment_opened = false;    //单行注释标记
        private int line_num = 1;        //行号
        private string quote_char = "";       //引用标记类型

 

        private bool slash_star_comment_opened = false;
        private string _ignore = "";


        public string CodeFormat(string code)
        {

            bool bracket_open = false;
            bool for_open = false;
            bool function_opened = false;

            //可以后面加块语句的关键字
            this._blockElement = this.str2hashtable("switch,if,while,try,finally");
            //是函数申明
            this._function = this.str2hashtable("function");
            this._choiceElement = this.str2hashtable("else,catch");
            this._singleEyeElement = this.str2hashtable("var,new,return,else,delete,in,case");
            this._quotation = this.str2hashtable("\",'");

            ArrayList codeArr = new ArrayList();

            int word_index = 0;
            StringBuilder htmlTxt = new StringBuilder();

            if (this.isCompress)
            {
                this._deleteComment = true;
            }

            // codeArr.Capacity = code.Length;
            //得到分割字符数组(分词)
            for (int i = 0; i < code.Length; i++)
            {

                if (this._wordDelimiters.ToString().IndexOf(code.Substring(i, 1)) == -1)
                {        //找不到关键字
                    if (word_index == 0 || codeArr[word_index] == null)
                    {
                        // codeArr[word_index] = "";
                        codeArr.Add("");
                    }
                    codeArr.Add("");
                    codeArr[word_index] += code.Substring(i, 1);

                }
                else
                {
                    if (!string.IsNullOrEmpty(codeArr[word_index] + "") && codeArr[word_index].ToString().Length > 0)
                    {
                        word_index++;
                        codeArr.Add("");
                    }
                    codeArr[word_index++] = code.Substring(i, 1);
                    // codeArr.Add(code.Substring(i, 1));
                }
            }


            //按分割字,分块显示
            for (int i = 0; i < word_index; i++)
            {
                //处理空行(由于转义带来)
                if (string.IsNullOrEmpty(codeArr[i] + "") || codeArr[i].ToString().Length == 0)
                {
                    continue;
                }
                else if (codeArr[i].ToString() == " " || codeArr[i].ToString() == "\t")
                {
                    if (slash_slash_comment_opened || slash_star_comment_opened)
                    {
                        if (!this._deleteComment)
                        {
                            htmlTxt.Append(codeArr[i]);
                        }
                    }
                    if (quote_opened)
                    {
                        htmlTxt.Append(codeArr[i]);
                    }
                }
                else if (codeArr[i].ToString() == "\n")
                {
                    //处理换行
                }
                else if (codeArr[i].ToString() == "\r")
                {
                    slash_slash_comment_opened = false;
                    quote_opened = false;
                    line_num++;
                    if (!this.isCompress)
                    {
                        htmlTxt.Append("\r\n" + this.getIdent());
                    }
                    //处理function里的参数标记
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && isFunction(codeArr[i].ToString()))
                {
                    htmlTxt.Append(codeArr[i]);
                    function_opened = true;
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == this._isFor)
                {
                    htmlTxt.Append(codeArr[i]);
                    for_open = true;
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == "(")
                {
                    bracket_open = true;
                    htmlTxt.Append(codeArr[i]);
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == ")")
                {
                    bracket_open = false;
                    htmlTxt.Append(codeArr[i]);
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == this._rowEnd)
                {
                    if (!this.isCompress)
                    {
                        if (!for_open)
                        {
                            if (i < word_index && (codeArr[i + 1].ToString() != "\r" && codeArr[i + 1].ToString() != "\n"))
                            {
                                htmlTxt.Append(codeArr[i] + "\n" + this.getIdent());
                            }
                            else
                            {
                                htmlTxt.Append(codeArr[i] + this.getIdent());
                            }
                        }
                        else
                        {
                            htmlTxt.Append(codeArr[i]);
                        }
                    }
                    else
                    {
                        htmlTxt.Append(codeArr[i]);
                    }
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == this._beginBlock)
                {
                    for_open = false;
                    if (!this.isCompress)
                    {
                        switch (this.style)
                        {
                            case 0:
                                this._tabNum++;
                                htmlTxt.Append(codeArr[i] + "\n" + this.getIdent());
                                break;
                            case 1:
                                htmlTxt.Append("\n" + this.getIdent());
                                this._tabNum++;
                                htmlTxt.Append(codeArr[i] + "\n" + this.getIdent());
                                break;
                            default:
                                this._tabNum++;
                                htmlTxt.Append(codeArr[i]);
                                break;

                        }
                    }
                    else
                    {
                        htmlTxt.Append(codeArr[i]);
                    }

                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && codeArr[i].ToString() == this._endBlock)
                {
                    if (!this.isCompress)
                    {
                        this._tabNum--;
                        if (i < word_index && codeArr[i + 1].ToString() != this._rowEnd)
                        {
                            htmlTxt.Append("\n" + this.getIdent() + codeArr[i]);
                        }
                        else
                        {
                            htmlTxt.Append("\n" + this.getIdent() + codeArr[i]);
                        }
                    }
                    else
                    {
                        if (i < word_index && codeArr[i + 1].ToString() != this._rowEnd)
                        {
                            htmlTxt.Append(codeArr[i] + this._rowEnd);
                        }
                        else
                        {
                            htmlTxt.Append(codeArr[i]);
                        }
                    }
                    //处理关键字
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && isBlockElement(codeArr[i].ToString()))
                {
                    htmlTxt.Append(codeArr[i]);
                    //处理内置对象(后面加一个空格)
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && isSingleEyeElement(codeArr[i].ToString()))
                {
                    if (codeArr[i].ToString() == this._in)
                    {
                        htmlTxt.Append(" ");
                    }
                    htmlTxt.Append(codeArr[i] + " ");
                    //处理双引号(引号前不能为转义字符)   
                }
                else if (!slash_star_comment_opened && !slash_slash_comment_opened && _quotation.Contains(codeArr[i]))
                {
                    if (quote_opened)
                    {
                        //是相应的引号
                        if (quote_char == codeArr[i].ToString())
                        {
                            htmlTxt.Append(codeArr[i]);
                            quote_opened = false;
                            quote_char = "";
                        }
                        else
                        {
                            htmlTxt.Append(codeArr[i]);
                        }
                    }
                    else
                    {
                        htmlTxt.Append(codeArr[i]);
                        quote_opened = true;
                        quote_char = codeArr[i] + "";
                    }
                    //处理转义字符
                }
                else if (codeArr[i].ToString() == this._escape)
                {
                    htmlTxt.Append(codeArr[i]);
                    if (i < word_index - 1)
                    {
                        if (char.Parse(codeArr[i + 1].ToString().Trim()) >= 32 && char.Parse(codeArr[i + 1].ToString().Trim()) <= 127)
                        {
                            htmlTxt.Append(codeArr[i + 1].ToString().Substring(0, 1));
                            htmlTxt.Append(codeArr[i + 1].ToString().Substring(0, 1));
                            i = i + 1;
                        }
                    }
                    //处理多行注释的开始
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened &&
                    isStartWith(_commentOn, codeArr, i))
                {
                    slash_star_comment_opened = true;
                    if (!this._deleteComment)
                    {
                        htmlTxt.Append(this._commentOn);
                    }
                    i = i + this.getSkipLength(this._commentOn);
                    //处理单行注释
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !
                    quote_opened && isStartWith(_lineComment, codeArr, i))
                {
                    slash_slash_comment_opened = true;
                    if (!this._deleteComment)
                    {
                        htmlTxt.Append(this._lineComment);
                    }
                    i = i + this.getSkipLength(this._lineComment);
                    //处理忽略词
                }
                else if (!slash_slash_comment_opened && !slash_star_comment_opened && !quote_opened && isStartWith(this._ignore, codeArr, i))
                {
                    slash_slash_comment_opened = true;
                    htmlTxt.Append(this._ignore);
                    i = i + this.getSkipLength(this._ignore);
                    //处理多行注释结束   
                }
                else if (!quote_opened && !slash_slash_comment_opened && isStartWith(_commentOff, codeArr, i))
                {
                    if (slash_star_comment_opened)
                    {
                        slash_star_comment_opened = false;
                        if (!this._deleteComment)
                        {
                            htmlTxt.Append(this._commentOff);
                        }
                        i = i + this.getSkipLength(this._commentOff);
                    }
                }
                else
                {
                    //不是在字符串中
                    if (!quote_opened)
                    {
                        //如果不是在注释重
                        if (!slash_slash_comment_opened && !slash_star_comment_opened)
                        {
                            htmlTxt.Append(codeArr[i]);
                            //注释中                           
                        }
                        else
                        {
                            if (!this._deleteComment)
                            {
                                htmlTxt.Append(codeArr[i]);
                            }
                        }
                    }
                    else
                    {
                        htmlTxt.Append(codeArr[i]);
                    }

                }

            }

            return htmlTxt.ToString();
        }


        private Hashtable str2hashtable(string str)
        {
            Hashtable ht = new Hashtable();
            string[] strArray = str.Split(',');
            foreach (string _str in strArray)
            {
                ht.Add(_str, _str);
            }
            return ht;

        }


        private bool isStartWith(string str, ArrayList code, int index)
        {

            if (!string.IsNullOrEmpty(str) && str.Length > 0)
            {
                StringBuilder cc = new StringBuilder();
                for (int i = index; i < index + str.Length; i++)
                {
                    cc.Append(code[i]);
                }

                string c = cc.ToString();
                if (this._caseSensitive)
                {
                    if (str.Length >= cc.Length && c.IndexOf(str) == 0)
                    {
                        return true;
                    }
                }
                else
                {
                    if (str.Length >= cc.Length && c.ToLower().IndexOf(str.ToLower()) == 0)
                    {
                        return true;
                    }
                }
                return false;

            }
            else
            {
                return false;
            }
        }


        private bool isFunction(string val)
        {
            return this._function.Contains((this._caseSensitive ? val : val.ToLower()));
        }

        private bool isBlockElement(string val)
        {
            return this._blockElement.Contains(this._caseSensitive ? val : val.ToLower());
        }

        private bool isChoiceElement(string val)
        {
            return this._choiceElement.Contains(this._caseSensitive ? val : val.ToLower());
        }

        private bool isSingleEyeElement(string val)
        {
            return this._singleEyeElement.Contains(this._caseSensitive ? val : val.ToLower());
        }

        private bool isNextElement(int from, string word)
        {
            for (int i = from; i < word.Length; i++)
            {
                if (word[i] != ' ' && word[i] != '\t' && word[i] != '\r' && word[i] != '\n')
                {
                    return this.isChoiceElement(word[i] + "");
                }
            }
            return false;
        }


        private int getSkipLength(string val)
        {
            int count = 0;
            for (int i = 0; i < val.Length; i++)
            {
                if (this._wordDelimiters.IndexOf(val.Substring(i, 1)) >= 0)
                {
                    count++;
                }
            }
            if (count > 0)
            {
                count = count - 1;
            }
            return count;
        }


        private string getIdent()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this._tabNum; i++)
            {
                sb.Append("\t");
            }
            return sb.ToString();
        }
    }

}

 
分享到:
评论

相关推荐

    CodeFormat

    标题“CodeFormat”暗示我们关注的是代码格式化相关的工具或技术。在编程世界中,代码格式化是指将源代码按照特定的编码规范自动调整布局、缩进和空格,以提高代码可读性和团队协作效率。这篇博客文章的链接虽然没有...

    NotePad++ AStyle 代码格式化工具

    "Format code"(或者按快捷键Alt+f),欣赏格式化后的代码风格。 Notepad++ 中代码格式化插件NppAStyle Notepad++ 中代码格式化插件NppAStyle 7、体验不同的代码风格并选择自己中意的某种代码风格。 重复第4步骤...

    AStyle代码格式化插件

    AStyle(Artistic Style)是一款强大的源代码格式化工具,专为C、C++、C++/CLI、Objective-C、C#和Java等编程语言设计。它旨在帮助程序员统一代码风格,提高代码可读性和维护性,尤其对于大型项目或团队合作来说,...

    clang-Format格式化-中文注解

    C++不像Java、C#、TypeScript这些语言,他们都有较为通用的代码风格标准,比较通用的IDE,基本是自带代码格式化,因此整体上来说比较容易统一。但C++就没有,比如我在公司是用Visual Studio,在家有时候用的VS Code...

    NppAStyle-NotePad++代码格式化插件

    NppAStyle-NotePad++代码格式化插件 An Artistic Style plugin for Notepad++ to Format C, C++, C++/CLI, Objective-C, C#, and Java Source Code.

    astyle格式化source insight

    Artistic Style(简称AStyle)是一款开源的源代码格式化、美化工具,支持多种编程语言,包括C, C++, C++/CLI, Objective-C, C# 和 Java。AStyle的强大之处在于它能够自动调整代码格式,遵循不同的编码规范,比如K&R...

    dxf文件转化成G代码

    ### 基于DXF文件格式的二维复杂图形数控代码自动生成法 #### 摘要 本文介绍了一种从二维图形DXF格式文件直接生成数控加工代码(G代码)的方法,这种方法为从计算机辅助设计(CAD)到计算机辅助制造(CAM)提供了一...

    MyEclipse plugins,修改编码格式

    3. 将`CodeFormat`中的.NET编码规则导入到MyEclipse的代码格式化设置中,以便在编辑时自动应用这些规则。 4. 配置`MyRuleSet`,确保所有代码遵循自定义的.NET编码规则。 5. 结合`checkstyle_ruleset_minimal.xml`,...

    Notepad++&Astyle.zip

    在Notepad++中打开需要格式化的文件,然后通过“Plugins” &gt; “Astyle” &gt; “Format Code”进行格式化操作。Astyle会根据预设的风格立即对代码进行整理,包括缩进、空格、括号对齐等方面。 Astyle还有一些高级功能...

    NppAstyle 插件

    "Format code"(或者按快捷键Alt+f),欣赏格式化后的代码风格。 步骤阅读.步骤阅读.7体验不同的代码风格并选择自己中意的某种代码风格。 重复第4步骤,例如将代码风格选中ANSI,按下快捷键Alt+f,欣赏格式化后的...

    利用ZXing .Net库二维码操作的C#例程

    该库最初由Java编写,但已经发展出多个语言的端口,包括C#版本,使得.NET开发者也能方便地进行条码和二维码的读取与生成。 首先,我们需要在项目中引入ZXing.Net库。这可以通过NuGet包管理器来完成,搜索"ZXing.Net...

    Zxing C#生成条码和二维码

    Format = BarcodeFormat.CODE_128, // 例如,选择CODE_128条码格式 Options = new EncodingOptions { Width = 400, Height = 200 } // 设置图像尺寸 }; ``` 这里,`BarcodeFormat`枚举包含了多种条码和二维码...

    Notepad++插件 NppAStyle.dll 64Bit

    Notepad++代码格式化插件 64Bit NppAStyle.dll An Artistic Style plugin for Notepad++ to Format C, C++, C++/CLI, Objective-C, C#, and Java Source Code.

    C# Winform 二维码生成工具

    在上述代码中,我们首先获取用户在文本框`txtData`中输入的数据,然后实例化`BarcodeWriter`,设置二维码格式为QR_CODE,并调整尺寸和边距。最后,调用`Write`方法生成二维码图像,并将其显示在pictureBox中。 为了...

    eclipse学习笔记

    - **代码格式化**:选中代码右键 -&gt; Source -&gt; Format进行格式化,可以在Windows -&gt; preferences -&gt; Code Style -&gt; Formatter中定制格式化规则。 - **生成GET/SET方法**:选中属性,右键 -&gt; Source -&gt; Generate ...

    NppAStyle.dll(64bit)

    notepad++b4位NppAstyle.dll插件, 亲测可用,支持 C, C++, C++/CLI, Objective-C, C#...等语言格式化代码 An Artistic Style plugin for Notepad++ to Format C, C++, C++/CLI, Objective-C, C#, and Java Source Code.

    NppAStyle 64位DLL

    notepad++插件 格式化代码工具插件 An Artistic Style plugin for Notepad++ to Format C, C++, C++/CLI, Objective-C, C#, and Java Source Code.

    NppAStyle_unicode.7z

    An Artistic Style plugin for Notepad++ to Format C, C++, C#, and Java Source Code.一款可以格式化C, C++, C#, and Java的notepad++插件。

    生成和读取条形码二维码(C#)

    在提供的压缩包文件中,可能包含了一些示例代码或教程文档,如`与.txt`和`ZXingCode`。通过研究这些文件,你可以更好地理解和应用ZXing.Net库,实现自己的条形码和二维码功能。记住,实践是检验真理的唯一标准,动手...

    ADS-B-demodulated-code.rar_ADS-B DF17_ADS-B DF17_ADS_b_df17_民航

    DF17是ADS-B Out标准中的一个数据格式(Data Format),它提供了比基础的DF11和DF16格式更丰富的信息。DF17框架可以携带更多的数据,包括飞机的身份、精确的位置、高度、速度、航向、爬升率、航班号、时间戳等,这...

Global site tag (gtag.js) - Google Analytics