原创:CodeHighlighter源代码格式化,代码缩进,关键词高亮着色(C#源码)

  原创:CodeHighlighter源代码格式化,代码缩进,关键词高亮着色(C#源码)

原创:CodeHighlighter源代码格式化,代码缩进,关键词高亮着色(C#源码)

最近对C/S框架网管理员后台工具升级,特别升级了代码高亮工具,对网上收集的源码重新整理和测试。

花了整整1天时间!!!

以下代码调用CodeHighlighterEngine类直接渲染代码,转换为HTML格式的源码,但是没有格式化代码缩进,在HTML页面显示极度不友好!

C# Code (Generated By Code Highlighter) :

/// <summary>
/// 调用CodeHighlighterEngine类渲染代码,无代码格式!!HTML页面显示不友好
/// </summary>
/// <param name="code">原始源码</param>
/// <param name="languageKey">语言</param>
/// <param name="isShowLineNum">显示代码行数</param>
/// <returns></returns>
public static string GeneralCodeHighlight(string code, string languageKey, bool isShowLineNum)
{
    ActiproSoftware.SyntaxEditor.SyntaxLanguage lang
= null; //尝试从缓存获取配置节
    
CodeHighlighterConfiguration config = HttpContext.Current.Cache["CodeHighlighterConfig"] as CodeHighlighterConfiguration;
    
    
//缓存不存在,重新从 web.config 获取并保存缓存
    
if (config == null)
    {
        config
= (CodeHighlighterConfiguration)ConfigurationManager.GetSection("codeHighlighter");
        HttpContext.Current.Cache.Insert(
"CodeHighlighterConfig", config);
    }
    
    
//获取语言
    
foreach (string key in config.LanguageConfigs.Keys)
    {
        
if (key.ToLower() == languageKey.ToLower())
        {
            lang
= CodeHighlighter.GetLanguage(config, key);
            
break;
        }
    }
    
    
//不明语言,不理会返回
    
if (lang == null) return code;
    
    CodeHighlighterEngine engine
= new CodeHighlighterEngine();
    engine.OutliningEnabled
= false;
    engine.LineNumberMarginVisible
= isShowLineNum;
    engine.SpacesInTabs
= (byte)char.Parse("|");
    
return engine.GenerateHtmlInline(string.Empty, code, lang);
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



将原始源码转化为HTML格式,美化着色,代码高亮,代码缩进,并替换掉ActiproSoftware公司的代码注释。


C# Code:

/// <summary>
/// 将原始源码转化为HTML格式,美化着色,代码高亮
/// </summary>
/// <param name="originalCode">原始源码</param>
/// <param name="languageKey">语言</param>
/// <param name="isShowLineNum">显示代码行数</param>
/// <returns></returns>
public static string RenderSource(string originalCode, string languageKey, bool isShowLineNum)
{
  
string renderedCode = GeneralCodeHighlight(originalCode, languageKey, isShowLineNum);
  
  
//替换掉ActiproSoftware公司的代码注释
  
renderedCode = ReplaceMatchText(renderedCode, "<!--", "-->", "");
  
  
//C#代码缩进
  
if (languageKey.ToLower() == "c#") renderedCode = IndentCodeCsharp(renderedCode);
  
  
//SQL代码缩进
  
if (languageKey.ToLower() == "sql") renderedCode = IndentCodeSql(renderedCode);
  
  
//C#断行符转化为HTML的断行符
  
renderedCode = renderedCode.Replace("\r\n", "<br/>");
  renderedCode
= renderedCode.Replace("\n", "<br/>");
  
  
string source_Header = "<STRONG><FONT color=#0000ff>" + languageKey + " Code:</FONT></STRONG></br></br>"; //显示粗体标题
  
string result = "<div class=\"codearea\">" + source_Header + renderedCode + "</div>";
  
return result;
}


/// <summary>
/// C#代码缩进
/// </summary>
/// <param name="src">输入源码</param>
/// <returns>格式化后的源码</returns>
private static string IndentCodeCsharp(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 = "    " + formatedLine;
      
formatedLine = "  " + formatedLine;//指表符
      
}
      
      retCode.Append(formatedLine +
"\n");
      
      
if (line.Trim() == "{" || line.EndsWith("{"))
      {
        indent++;
      }
    }
    
return retCode.ToString();
  }
  
  
  
/// <summary>
  
/// SQL脚本代码缩进
  
/// </summary>
  
/// <param name="SQL"></param>
  
/// <returns></returns>
  
private static string IndentCodeSql(string SQL)
  {
    
bool firstAs = false;
    
bool firstBegin = false;
    
bool firstAsBegin = false;
    
    System.Text.StringBuilder retCode
= new System.Text.StringBuilder();
    
int indent = 0;
    
string NoHtml;
    
string[] lines = SQL.Split('\n');
    
foreach (string line in lines)
    {
      NoHtml
= RemoveHTML(line.Trim());
      
      
if (NoHtml == "AS" && firstAs == false) firstAs = true;
      
if (NoHtml == "BEGIN" && firstBegin == false) firstBegin = true;
      
if (NoHtml.Replace(" ", "").ToUpper() == "ASBEGIN" && firstAsBegin == false) firstAsBegin = true;
      
      
//代码段结束,减少缩进
      
if (line.Trim() == ")" || line.Trim().ToUpper() == "END")
      {
        
if (indent > 0) indent--;
      }
      
      
string formatedLine = line.Trim();
      
      
for (int i = 0; i < indent; i++)
      {
        formatedLine
= "  " + formatedLine;//指表符
        
}
        
        
//定义符合
        
if (NoHtml.StartsWith("@")) formatedLine = "  " + formatedLine;//指表符
        

        retCode.Append(formatedLine +
"\n");
        
        
//代码段开始,增加缩进
        
if (line.Trim() == "(" || line.Trim().StartsWith("(") || line.Trim().EndsWith("(") || line.Trim().ToUpper() == "BEGIN" || line.Trim().ToUpper().EndsWith("BEGIN"))
        {
          indent++;
        }
        
        
// AS BEGIN, AS, BEGIN
        
if ((firstAs && firstBegin) || firstAsBegin)
        {
          indent++;
          firstAs
= false; firstAsBegin = false; firstAsBegin = false;
        }
      }
      
return retCode.ToString();
    }
    
    
//来源:C/S框架网(www.csframework.com) QQ:23404761





C# Code:


/// <summary>
/// C#正则表达式获取指定字符串(标识)范围的内容
/// </summary>
/// <param name="source">字符串</param>
/// <param name="startStr">开始字符串标识</param>
/// <param name="endStr">结束字符串标识</param>
/// <returns></returns>
public static string GetMatchText(string source, string startStr, string endStr)
{
    Regex rg
= new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
    
return rg.Match(source).Value;
}

/// <summary>
/// C#正则表达式替换指定字符串(标识)范围的内容
/// </summary>
/// <param name="source">字符串</param>
/// <param name="startStr">开始字符串标识</param>
/// <param name="endStr">结束字符串标识</param>
/// <param name="replaceStr">替换的内容</param>
/// <returns></returns>
public static string ReplaceMatchText(string source, string startStr, string endStr, string replaceStr)
{
    Regex rg
= new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
    
string value = rg.Match(source).Value;
    
return source.Replace(startStr + value + endStr, replaceStr);
}

//来源:C/S框架网(www.csframework.com) QQ:23404761



网上下载CodeHighlighter组件,然后在自己的项目中添加引用下面的dll文件。


贴图图片-CodeHighlighter源代码格式化关键词高亮着色



扫一扫加微信:
 


版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
发表评论

评论内容
昵称:
关联文章

CodeHighlighter源代码格式化代码关键词(C#)
C# 格式化CodeHighlighter生成的SQL脚本(CSFramework.com
C# CodeHighlighter生成的HTML格式化
C#源代码类(C/S框架网开源)
模拟百度搜索渲染HTML页面关键词分组排序算法(C#)
C# Winform销存系统快速开发框架
销存软件开发模板基于C/S架构快速开发框架C#+Winform+DevExpress
C#微信支付完成前端回调通知notify_url完整版|CSframework.com文章
C/S架构的Winform 代码生成器软件|C/S框架网作品
[]C# UDP穿越NAT,UDP打洞,UDP Hole Punching源代码(2)
[]C# UDP穿越NAT,UDP打洞,UDP Hole Punching源代码(1)
[]C#键盘勾子(Hook),屏蔽键盘活动.(源代码下载)
C# 数据窗体实现增删改查(CRUD)下载()
C# GridMovetor按回车自动跳到下一列或自动新增记录(www.csframework.com)
C/S快速开发框架能提供销存参考吗?
C#初学者请:分享一些C#.Net培训
[] Asp.Net三层体系结构应用实例(2)源代码
CSFramework C#代码生成器生成窗体界面UI,BLL,DAL,Model,WCF接口层源代码
软件开发与设计 - MRP-物料需求计划-仓底货-销存
C/S架构开源软件 - C#.NET+Winform+Dev+SQL快速开发框架