原创:CodeHighlighter源代码格式化,代码缩进,关键词高亮着色(C#源码)
作者:C/S框架网|www.cscode.ne  发布日期:2020-02-21 01:57:31
  原创: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源代码格式化关键词高亮着色



扫一扫加微信:
 


上一篇 下一篇