C#源代码高亮着色类(C/S框架网开源)


  C#源代码高亮着色类(C/S框架网开源)


C#源代码高亮着色类(C/S框架网开源)


C#代码高亮着色

有些功能尚未实现,比如代码中的/*注释*/无法高亮,将就使用足够啦!


using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
/*
* 版权:C/S框架网 www.csframework.com
*
* C#源代码高亮着色类
*/
namespace CSFramework.BLL
{
   /// <summary>
   /// C#源代码高亮着色类
   /// </summary>
   public class CSourceRenderer
   {
      /// <summary>
      /// 源代码着色构造器
      /// </summary>
      public string RenderSource(string src)
      {
         string html = src;
         html = ColorComment(html); //转换注释
         html = ColorKeyword(html); //转换关键字
         html = IndentCode(html); //空格缩进
         html = ReplaceCSSTag(html); //替换CSS
         html = "<div class=\"codearea\">" html "</div>";
         return html;
      }
      
      private string ReplaceCSSTag(string src)
      {
         src = src.Replace(" class='codecomment' ", " class='codecomment' ");//注释
         src = src.Replace(" class='codecomment1' ", " class='codecomment1' ");//注释
         src = src.Replace(" class='codekeyword' ", " class='codekeyword' ");//关键字
         src = src.Replace("\r</span>", "</span>\r");
         src = src.Replace("\n", "</br>");
         return src;
      }
      
      /// <summary>
      /// 为//和/**/类型的注释着色
      /// </summary>
      /// <param name="src">输入源码</param>
      /// <returns>格式化后的源码</returns>
      private string ColorBasicComment(string src)
      {
         string retCode = src;
         Regex r1 = new Regex(@"(^|;)([ \t]*)(//.*$)", RegexOptions.Multiline);
         retCode = r1.Replace(retCode, "$1$2<span class='codecomment' >$3</span>");
         Regex r2 = new Regex(@"(^|[ \t] )(/\*[^\*/]*\*/[ \t\r]*$)", RegexOptions.Multiline);
         retCode = r2.Replace(retCode, new MatchEvaluator(this.ColorBasicComment2Evaluator));
         return retCode;
      }
      
      /// <summary>
      /// 为///类型的注释着色
      /// </summary>
      /// <param name="src">输入源码</param>
      /// <returns>格式化后的源码</returns>
      private string ColorXmlComment(string src)
      {
         string retCode = src;
         Regex r1 = new Regex(@"(/// *)&lt;(.*)&gt;)(.*)(&&nbsp;&nbsp;&gt;", RegexOptions.Multiline);
         retCode = r1.Replace(retCode, new MatchEvaluator(this.ColorXmlCommentEvaluator));
         Regex r2 = new Regex(@"(/// *)(.*$)", RegexOptions.Multiline);
         retCode = r2.Replace(retCode, "<span class='codecomment1' >$1</span>$2");
         return retCode;
      }
      
      /// <summary>
      /// 为折叠显示代码构建HtmlTable框架
      /// </summary>
      /// <param name="src">输入源码</param>
      /// <returns>格式化后的源码</returns>
      private string DrawCollapseFrameTable(string src)
      {
         System.Text.StringBuilder retCode = new System.Text.StringBuilder();
         string frameHeader = "";
         string frameTailer = "<br/>";
         retCode.Append(frameHeader);
         string[] lines = src.Split('\n');
         foreach (string line in lines)
         {
            string formatedLine = line.Trim();
            string lineHeader = "";
            string lineTailer = "<br/>";
            formatedLine = lineHeader formatedLine lineTailer;
            retCode.Append(formatedLine);
         }
         retCode.Append(frameTailer);
         return retCode.ToString();
      }
      
      /// <summary>
      /// 为一行源码中的关键字着色
      /// </summary>
      /// <param name="codeLine">某一行源码</param>
      /// <param name="keywordList">关键字列表</param>
      /// <returns>格式化后的源码</returns>
      /// <summary>
      private string ColorKeyword(string codeLine, string[] keywordList)
      {
         string retCode = codeLine;
         if (!retCode.StartsWith("//"))
         {
            foreach (string keyword in KEYWORD_LIST)
            {
               Regex r = new Regex(@"(^|\s |,|\)|\(|\{|\}|\[|\]|\.|=|;)(" keyword @")(\s |,|\)|\(|\{|\}|\[|\]|\.|=|;|$)");
               retCode = r.Replace(retCode, "$1<span class='codekeyword' >$2</span>$3");
            }
         }
         retCode = ClearColoredKeyworsInString(retCode);
         return retCode.Trim();
      }
      
      /// <summary>
      /// 清除字符串中的被着色的关键字
      /// </summary>
      /// <param name="codeLine">某一行源码</param>
      /// <returns>格式化后的源码</returns>
      private string ClearColoredKeyworsInString(string codeLine)
      {
         System.Text.StringBuilder retCode = new System.Text.StringBuilder();
         string str = codeLine.Trim();
         int indexOfQuot = str.IndexOf("&quot;");
         int lengthOfQuot = "&quot;".Length;
         if (indexOfQuot >= 0)
         {
            while (indexOfQuot >= 0)
            {
               retCode.Append(str.Substring(0, indexOfQuot lengthOfQuot));
               str = str.Substring(indexOfQuot lengthOfQuot);
               indexOfQuot = str.IndexOf("&quot;");
               if (indexOfQuot >= 0)
               {
                  string inStr = str.Substring(0, indexOfQuot lengthOfQuot);
                  inStr = inStr.Replace("\"color: blue\"", "\"\"");
                  retCode.Append(inStr);
                  str = str.Substring(indexOfQuot lengthOfQuot);
               }
               indexOfQuot = str.IndexOf("&quot;");
            }
         }
         retCode.Append(str);
         return retCode.ToString();
      }
      
      /// <summary>
      /// 关键字列表
      /// </summary>
      public static string[] KEYWORD_LIST = {
         "abstract", "event", "new", "struct", "as", "explicit", "null", "switch",
         "base", "extern", "object", "this", "bool", "false", "operator", "throw",
         "break", "finally", "out", "true", "byte", "fixed", "override", "try",
         "case", "float", "params", "typeof", "catch", "for", "private", "uint",
         "char", "foreach", "protected", "ulong", "checked", "goto", "public",
         "unchecked", "class", "if", "readonly", "unsafe", "const", "implicit",
         "ref", "ushort", "continue", "in", "return", "using", "decimal", "int",
         "sbyte", "virtual", "default", "interface", "sealed", "volatile",
         "delegate", "internal", "short", "void", "do", "is", "sizeof", "while",
         "double", "lock", "stackalloc", "else", "long", "static", "enum",
         "namespace", "string", "get", "set", "#region", "#endregion", "true",
         "false"
         };
         
         private string ColorXmlCommentEvaluator(Match m)
         {
            Regex r = new Regex("(^.*&lt;/.*$)");
            if (r.Match(m.Value).Success)
            {
               return r.Replace(m.Value, "<span class='codecomment1' >$1</span>$2<span class='codecomment1' >$3</span>");
            }
            else
            {
               return "<span class='codecomment1' >" m.Value "</span>";
            }
         }
         
         private string ColorBasicComment2Evaluator(Match m)
         {
            System.Text.StringBuilder retCode = new System.Text.StringBuilder();
            string[] lines = m.Value.Split('\n');
            foreach (string line in lines)
            {
               retCode.Append("<span class='codecomment' >" line "</span>" "\n");
            }
            return retCode.ToString();
         }
         
         /// <summary>
         /// 为注释着色,例如:对C#,包括///型、//型和/**/的注释
         /// </summary>
         /// <param name="src">输入源码</param>
         /// <returns>格式化后的源码</returns>
         private string ColorComment(string src)
         {
            string retCode = src;
            retCode = ColorBasicComment(retCode);
            retCode = ColorXmlComment(retCode);
            return retCode;
         }
         
         /// <summary>
         /// 为关键字着色
         /// </summary>
         /// <param name="src">输入源码</param>
         /// <returns>格式化后的源码</returns>
         private string ColorKeyword(string src)
         {
            System.Text.StringBuilder retCode = new System.Text.StringBuilder();
            string[] lines = src.Split('\n');
            if (lines != null & lines.Length > 0)
            {
               bool isInComment = false;
               foreach (string line in lines)
               {
                  string formatedLine = line.Trim();
                  if (new Regex(@"(^|[ \t] )(/\*)").Match(line).Success)
                  {
                     isInComment = true;
                  }
                  if (!isInComment)
                  {
                     formatedLine = ColorKeyword(line, KEYWORD_LIST);
                  }
                  if (new Regex(@"\*/[ \t\r]*$").Match(line).Success)
                  {
                     isInComment = false;
                  }
                  retCode.Append(formatedLine "\n");
               }
            }
            return retCode.ToString();
         }
         
         /// <summary>
         /// 代码缩进
         /// </summary>
         /// <param name="src">输入源码</param>
         /// <returns>格式化后的源码</returns>
         private string IndentCode(string src)
         {
            System.Text.StringBuilder retCode = new System.Text.StringBuilder();
            int indent = 0;
            string[] lines = src.Split('\n');
            foreach (string line in lines)
            {
               string formatedLine = line.Trim();
               if (line.Trim() == "}")
               {
                  indent--;
               }
               for (int i = 0; i < indent; i )
               {
                  formatedLine = "&nbsp;" formatedLine;
               }
               retCode.Append(formatedLine "\n");
               
               if (line.Trim() == "{" || line.EndsWith("{"))
               {
                  indent ;
               }
            }
            return retCode.ToString();
         }
      }
   }
   
   
   // 来源:www.CSFramework.com, C/S结构框架学习网
   


 

C/S框架网|原创精神.创造价值.打造精品


扫一扫加作者微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
上一篇:Asp.Net使用SmtpClient发送邮件(C/S框架网开源)
下一篇:Asp.Net生成图片验证码(C/S框架网开源)
评论列表

发表评论

评论内容
昵称:
关联文章

C#源代码(C/S框架开源)
原创:CodeHighlighter源代码格式化,代码缩进,关键词(C#源码)
C# CodeHighlighter生成的HTML源码格式化
C# 格式化CodeHighlighter生成的SQL脚本源码(CSFramework.com原创)
C#开源框架 | .NET开源快速开发平台 | C/S框架
图像处理业务逻辑CImageLibrary(C/S框架开源)
C/S框架开源框架优势
C#.NET最好用的主流开发框架 - 开源框架平台 - C/S框架
Asp.Net FileUpload实现上传文件(C/S框架开源)
C/S框架提供原创开源.NET开发架构.NET管理系统框架
模拟百度搜索渲染HTML页面关键词分组排序算法(C#)
原创MES系统框架及MES开源框架 | C/S框架
原创Winform布局开源框架,Winform控件框架,插件化框架|C/S框架
原创C#开发框架|C#开源框架|C/S框架
CMS代码 - Prism下载
MES系统快速开发平台|MES开源框架|C/S框架
开源ERP软件平台ERP系统快速开发框架 - C/S框架原创作品
C# 自动调整颜色(加深、变
Asp.Net使用SmtpClient发送邮件(C/S框架开源)
Asp.Net生成图片验证码(C/S框架开源)

热门标签
.NET5 .NET6 .NET7 .NET8 APP Auth-软件授权注册系统 Axios B/S B/S开发框架 Bug Bug记录 C#加密解密 C#源码 C/S CHATGPT CMS系统 CodeGenerator CSFramework.DB CSFramework.EF CSFrameworkV1学习版 CSFrameworkV2标准版 CSFrameworkV3高级版 CSFrameworkV4企业版 CSFrameworkV5旗舰版 CSFrameworkV6.0 CSFrameworkV6.1 DAL数据访问层 Database datalock DbFramework Demo教学 Demo实例 Demo下载 DevExpress教程 DOM EFCore EF框架 Element-UI EntityFramework ERP ES6 Excel FastReport GIT HR IDatabase IIS JavaScript LINQ MES MiniFramework MIS NavBarControl Node.JS NPM OMS Oracle资料 ORM PaaS POS Promise API Redis SAP SEO SQL SQLConnector TMS系统 Token令牌 VS2022 VSCode VUE WCF WebApi WebApi NETCore WebApi框架 WEB开发框架 Windows服务 Winform 开发框架 Winform 开发平台 WinFramework Workflow工作流 Workflow流程引擎 版本区别 报表 踩坑日记 操作手册 代码生成器 迭代开发记录 功能介绍 基础资料窗体 架构设计 角色权限 开发sce 开发技巧 开发教程 开发框架 开发平台 开发指南 客户案例 快速搭站系统 快速开发平台 框架升级 毛衫行业ERP 秘钥 密钥 权限设计 软件报价 软件测试报告 软件简介 软件开发框架 软件开发平台 软件开发文档 软件体系架构 软件下载 软著证书 三层架构 设计模式 生成代码 实用小技巧 收钱音箱 数据锁 数据同步 微信小程序 未解决问题 文档下载 喜鹊ERP 喜鹊软件 系统对接 详细设计说明书 新功能 行政区域数据库 需求分析 疑难杂症 蝇量级框架 蝇量框架 用户管理 用户开发手册 用户控件 在线支付 纸箱ERP 智能语音收款机 自定义窗体 自定义组件 自动升级程序