在cnblogs和許多其他論壇、Blog上都有插入程序代碼高亮顯示的功能。現參考cnblogs的為例,以discuz!NT 2.0 rc2為例,說明如何增加插入代碼高亮功能。
cnblogs的代碼高亮功能是通過一個共享軟件實現的,可以到以下網址下載使用
http://www.actiprosoftware.com/Download/Freeware.ASPx
此軟件的Api很簡單,就是一個ASP.Net的控件。可以在網頁上輸出高亮顯示的代碼。但我們不想讓高亮代碼在網頁上輸出,而是插入到文章中。可以對discuz自帶的Editor進行改造,以達到響應的功能。
首先將 ActiproSoftware.CodeHighlighter.Net20.dll、ActiproSoftware.Shared.Net20.dll、CodeHighlighterTest.dll Copy到discuz的bin目錄。然後在discuz的頁面文件價(ASPx/1)下添加InsertCode.ASPx文件,內容如下
<%@ Page Language="C#" %>
<%@ Import Namespace="ActiproSoftware.CodeHighlighter" %>
<%@ Import Namespace="System.Reflection" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<script runat="server">
protected string ReturnCode;
protected override void OnLoad(EventArgs e)
...{
if (!IsPostBack)
...{
//從配置文件中獲取支持的語言列表
CodeHighlighterConfiguration config = (CodeHighlighterConfiguration)ConfigurationManager.GetSection("codeHighlighter");
string[] keys = new string[config.LanguageConfigs.Keys.Count];
config.LanguageConfigs.Keys.CopyTo(keys, 0);
Array.Sort(keys);
foreach (string key in keys)
...{
LanguageDropDownList.Items.Add(key);
}
//將默認語言設置為C#
LanguageDropDownList.SelectedIndex = LanguageDropDownList.Items.IndexOf(LanguageDropDownList.Items.FindByText("C#"));
}
base.OnLoad(e);
}
protected void Insert_Click(object sender, EventArgs e)
...{
//初始化控件
ActiproSoftware.CodeHighlighter.CodeHighlighter ch = new ActiproSoftware.CodeHighlighter.CodeHighlighter();
ch.LanguageKey = LanguageDropDownList.SelectedValue;
ch.Text = Code.Text;
ch.Page = this;
Type t = ch.GetType();
//利用反射獲取高亮顯示的代碼
MethodInfo method = t.GetMethod("a", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
method.Invoke(ch, null);
FieldInfo field = t.GetFIEld("i", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
ReturnCode = (string)fIEld.GetValue(ch);
//將代碼放入 pre 標簽中以保持格式,並輸出到頁面顯示
ReturnCode = JStringEncode("<pre style='background-color:#eeeeee;font-size:13px;BORDER:1px solid #CCCCCC;PADDING-RIGHT: 5px;PADDING-BOTTOM: 4px;PADDING-left: 4px;PADDING-TOP: 4px;WIDTH: 98%;Word-break:break-all'>" + ReturnCode + "</pre>");
ReturnPanel.Visible = true;
}

/**//// <summary>
/// 替換掉字符串中的特殊字符,如把 " 替換成 "
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string JStringEncode( string str )
...{
if( str == null )
...{
return string.Empty;
}
//替換反斜槓
str = str.Replace( @"", @"\" );
//替換回車
str = str.Replace( " ", @" " );
str = str.Replace( " ", @" " );
//替換 " 號
str = str.Replace( """, "\"" );
return str;
}
</script>
<html XMLns="http://www.w3.org/1999/xHtml">
<head runat="server">
<title>插入源代碼</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="Table1" class="tb" cellspacing="0" cellpadding="3" border="0">
<tr>
<th align="right" >
編程語言:</th>
<td>
<ASP:DropDownList ID="LanguageDropDownList" runat="server" Width="100px">
</ASP:DropDownList></td>
</tr>
<tr>
<th valign="top" align="right">
代碼:</th>
<td>
<asp:TextBox ID="Code" runat="server" Height="200px" TextMode="MultiLine" Width="500px"></ASP:TextBox></td>
</tr>
<tr>
<td>
</td>
<td>
<ASP:Button ID="Insert" runat="server" OnClick="Insert_Click" Text="確定" /> <input
onclick="return window.close()" type="button" value="關閉"></td>
</tr>
</table>
</div>
<ASP:Panel ID="ReturnPanel" runat="server" Visible="false">
<script language="Javascript">
window.opener.insertText("<% = ReturnCode %>");
window.close();
</script>
</ASP:Panel>
</form>
</body>
</Html>
然後修改discuz的webconfig,如下所示
<?XML version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="codeHighlighter" requirePermission="false" type="ActiproSoftware.CodeHighlighter.CodeHighlighterConfigurationSectionHandler, ActiproSoftware.CodeHighlighter.Net20"/>
</configSections>
<system.web>
<compilation
defaultLanguage="c#"
debug="false"
/>
<authorization>
<allow users="*" /> <!-- 允許所有用戶 -->
</authorization>
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
<!-- 以下為Discuz!NT相關的一些系統設置, 如果有疑問, 請訪問 http://nt.discuz.Net/config 獲得更詳細的說明
-->


<!-- 注意:此節設置錯誤信息的顯示
"On" 始終顯示自定義(友好的)信息。
"Off" 始終顯示詳細的 ASP.Net 錯誤信息。
"RemoteOnly" 只對不在本地 Web 服務器上運行的
-->
<customErrors
mode="RemoteOnly"
/> 
<!-- 注意:此節設置全球化,Discuz!NT由此支持多語言。
-->
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
fileEncoding="utf-8"
/>
<!-- 注意:此節設置是否使用ASP.Net表單安全驗證,Discuz!NT使用自己的驗證。
-->
<pages
validateRequest="false"
enableEventValidation="false"
enableVIEwStateMac="false"
vIEwStateEncryptionMode ="Never"
/> 
<!-- 注意:此節設置由Discuz!NT接管http請求。不會干涉對非Discuz!NT論壇路徑下的請求。
-->
<httpModules>
<add type="Discuz.Forum.HttpModule, Discuz.Forum" name="HttpModule" />
</httpModules>
<xHtmlConformance mode="Legacy"/>
<httpRuntime maxRequestLength="2097151" executionTimeout="3600"/>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost"/>
</protocols>
</webServices>

</system.web>
<codeHighlighter>
<cache languageTimeout="3"/>
<keywordLinking enabled="true" target="_blank" defaultKeywordCollectionKey="ActiproKeyWords">
<keywordCollection key="ActiproKeyWords">
<explicitKeyWord tokenKey="IdentifIErToken" patternValue="Actipro" url="http://www.actiprosoftware.com" caseSensitive="false"/>
<explicitKeyWord tokenKey="IdentifIErToken" patternValue="CodeHighlighter" url="http://www.codehighlighter.com" caseSensitive="false"/>
</keyWordCollection>
</keyWordLinking>
<languages>
<language key="Assembly" definitionPath="~/Languages/Lexers/ActiproSoftware.Assembly.XML"/>
<language key="BatchFile" definitionPath="~/Languages/Lexers/ActiproSoftware.BatchFile.XML"/>
<language key="C#" definitionPath="~/Languages/Lexers/ActiproSoftware.CSharp.XML"/>
<language key="CSS" definitionPath="~/Languages/Lexers/ActiproSoftware.CSS.XML"/>
<language key="HTML" definitionPath="~/Languages/Lexers/ActiproSoftware.Html.XML"/>
<language key="INIFile" definitionPath="~/Languages/Lexers/ActiproSoftware.INIFile.XML"/>
<language key="Java" definitionPath="~/Languages/Lexers/ActiproSoftware.Java.XML"/>
<language key="JScript" definitionPath="~/Languages/Lexers/ActiproSoftware.JScript.XML"/>
<language key="Lua" definitionPath="~/Languages/Lexers/ActiproSoftware.Lua.XML"/>
<language key="MSIL" definitionPath="~/Languages/Lexers/ActiproSoftware.MSIL.XML"/>
<language key="Pascal" definitionPath="~/Languages/Lexers/ActiproSoftware.Pascal.XML"/>
<language key="Perl" definitionPath="~/Languages/Lexers/ActiproSoftware.Perl.XML"/>
<language key="PHP" definitionPath="~/Languages/Lexers/ActiproSoftware.PHP.XML"/>
<language key="PowerShell" definitionPath="~/Languages/Lexers/ActiproSoftware.PowerShell.XML"/>
<language key="Python" definitionPath="~/Languages/Lexers/ActiproSoftware.Python.XML"/>
<language key="SQL" definitionPath="~/Languages/Lexers/ActiproSoftware.SQL.XML"/>
<language key="VB.Net" definitionPath="~/Languages/Lexers/ActiproSoftware.VBDotNet.XML"/>
<language key="VBScript" definitionPath="~/Languages/Lexers/ActiproSoftware.VBScript.XML"/>
<language key="XAML" definitionPath="~/Languages/Lexers/ActiproSoftware.XAML.XML"/>
<language key="XML" definitionPath="~/Languages/Lexers/ActiproSoftware.XML.XML"/>
</languages>
<lineNumberMargin foreColor="Teal" paddingCharacter=" " visible="true"/>
<outlining enabled="true" imagesPath="~/Images/OutliningIndicators/"/>
<spacesInTabs count="4"/>
</codeHighlighter>
</configuration>
<a id="posteditor_cmd_insertcode">插入代碼</a>