在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,如下所示
1<?XML version="1.0" encoding="utf-8" ?>
2<configuration>
3 <configSections>
4 <section name="codeHighlighter" requirePermission="false" type="ActiproSoftware.CodeHighlighter.CodeHighlighterConfigurationSectionHandler, ActiproSoftware.CodeHighlighter.Net20"/>
5 </configSections>
6
7 <system.web>
8
9 <compilation
10 defaultLanguage="c#"
11 debug="false"
12 />
13
14 <authorization>
15 <allow users="*" /> <!-- 允許所有用戶 -->
16 </authorization>
17
18 <trace
19 enabled="false"
20 requestLimit="10"
21 pageOutput="false"
22 traceMode="SortByTime"
23 localOnly="true"
24 />
25
26 <!-- 以下為Discuz!NT相關的一些系統設置, 如果有疑問, 請訪問 http://nt.discuz.Net/config 獲得更詳細的說明
27 -->
28
29
30
31 <!-- 注意:此節設置錯誤信息的顯示
32
33 "On" 始終顯示自定義(友好的)信息。
34 "Off" 始終顯示詳細的 ASP.Net 錯誤信息。
35 "RemoteOnly" 只對不在本地 Web 服務器上運行的
36 -->
37 <customErrors
38mode="RemoteOnly"
39 />
40
41 <!-- 注意:此節設置全球化,Discuz!NT由此支持多語言。
42 -->
43 <globalization
44 requestEncoding="utf-8"
45 responseEncoding="utf-8"
46 fileEncoding="utf-8"
47 />
48
49 <!-- 注意:此節設置是否使用ASP.Net表單安全驗證,Discuz!NT使用自己的驗證。
50 -->
51 <pages
52 validateRequest="false"
53 enableEventValidation="false"
54 enableVIEwStateMac="false"
55 vIEwStateEncryptionMode ="Never"
56 />
57
58 <!-- 注意:此節設置由Discuz!NT接管http請求。不會干涉對非Discuz!NT論壇路徑下的請求。
59 -->
60 <httpModules>
61 <add type="Discuz.Forum.HttpModule, Discuz.Forum" name="HttpModule" />
62 </httpModules>
63
64 <xHtmlConformance mode="Legacy"/>
65
66 <httpRuntime maxRequestLength="2097151" executionTimeout="3600"/>
67
68 <webServices>
69 <protocols>
70 <add name="HttpGet" />
71 <add name="HttpPost"/>
72 </protocols>
73 </webServices>
74
75
76 </system.web>
77
78 <codeHighlighter>
79 <cache languageTimeout="3"/>
80 <keywordLinking enabled="true" target="_blank" defaultKeywordCollectionKey="ActiproKeyWords">
81 <keywordCollection key="ActiproKeyWords">
82 <explicitKeyWord tokenKey="IdentifIErToken" patternValue="Actipro" url="http://www.actiprosoftware.com" caseSensitive="false"/>
83 <explicitKeyWord tokenKey="IdentifIErToken" patternValue="CodeHighlighter" url="http://www.codehighlighter.com" caseSensitive="false"/>
84 </keyWordCollection>
85 </keyWordLinking>
86 <languages>
87 <language key="Assembly" definitionPath="~/Languages/Lexers/ActiproSoftware.Assembly.XML"/>
88 <language key="BatchFile" definitionPath="~/Languages/Lexers/ActiproSoftware.BatchFile.XML"/>
89 <language key="C#" definitionPath="~/Languages/Lexers/ActiproSoftware.CSharp.XML"/>
90 <language key="CSS" definitionPath="~/Languages/Lexers/ActiproSoftware.CSS.XML"/>
91 <language key="HTML" definitionPath="~/Languages/Lexers/ActiproSoftware.Html.XML"/>
92 <language key="INIFile" definitionPath="~/Languages/Lexers/ActiproSoftware.INIFile.XML"/>
93 <language key="Java" definitionPath="~/Languages/Lexers/ActiproSoftware.Java.XML"/>
94 <language key="JScript" definitionPath="~/Languages/Lexers/ActiproSoftware.JScript.XML"/>
95 <language key="Lua" definitionPath="~/Languages/Lexers/ActiproSoftware.Lua.XML"/>
96 <language key="MSIL" definitionPath="~/Languages/Lexers/ActiproSoftware.MSIL.XML"/>
97 <language key="Pascal" definitionPath="~/Languages/Lexers/ActiproSoftware.Pascal.XML"/>
98 <language key="Perl" definitionPath="~/Languages/Lexers/ActiproSoftware.Perl.XML"/>
99 <language key="PHP" definitionPath="~/Languages/Lexers/ActiproSoftware.PHP.XML"/>
100 <language key="PowerShell" definitionPath="~/Languages/Lexers/ActiproSoftware.PowerShell.XML"/>
101 <language key="Python" definitionPath="~/Languages/Lexers/ActiproSoftware.Python.XML"/>
102 <language key="SQL" definitionPath="~/Languages/Lexers/ActiproSoftware.SQL.XML"/>
103 <language key="VB.Net" definitionPath="~/Languages/Lexers/ActiproSoftware.VBDotNet.XML"/>
104 <language key="VBScript" definitionPath="~/Languages/Lexers/ActiproSoftware.VBScript.XML"/>
105 <language key="XAML" definitionPath="~/Languages/Lexers/ActiproSoftware.XAML.XML"/>
106 <language key="XML" definitionPath="~/Languages/Lexers/ActiproSoftware.XML.XML"/>
107 </languages>
108 <lineNumberMargin foreColor="Teal" paddingCharacter=" " visible="true"/>
109 <outlining enabled="true" imagesPath="~/Images/OutliningIndicators/"/>
110 <spacesInTabs count="4"/>
111 </codeHighlighter>
112
113</configuration>
Copy高亮組件的 Languages\Lexers、Images\OutliningIndicators 目錄到discuz的指定目錄
在discuz的編輯器文件 editor\editor.JS,在function discuzcode(cmd, arg)函數中if else組裡添加處理insertcode的代碼
if (cmd == "insertcode")
{
window.open('../InsertCode.ASPx', null, 'height=500, width=600, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
}修改discuz編輯器文件 editor\
cp_editor.htm 在插入圖片後變添加插入代碼的命令
<a id="posteditor_cmd_insertcode">插入代碼</a>
現在,discuz的blog裡就有插入高亮代碼的功能了。