2009-04-14 16:48

改寫 dp.SyntaxHighlighter 中 CSS 的 Highlighter 方式

最近掙扎了很久,考慮要不要用 dp.SyntaxHighlighter 來處理 Blog 中程式碼的 Highlighter,因為之前用的 Iris Syntax Highlighter 已經收起來了,而且在文章撰寫上十分不方便也不直覺,所以花了一點心思改成 dp.SyntaxHighlighter 的模式,但 1.5.1 版還蠻陽春的,花了一點時間做語法增強及檔案瘦身,希望這個套件可以用久一點。

原本 dp.SyntaxHighlighter 中 CSS 的 Highlighter 是用 keyword 的方式去處理的,未定義的 keyword 將不會有 Highlighter,為了得到更好的效果,又必須增加更多的 keyword,實在是很不划算。

所以我改用解析 Syntax 結構的方式去處理 Highlighter 的動作,雖然還不是很完整,但整體的效果比原生好多了。


/**=[ CSS ]===========================================*/
dp.sh.Brushes.CSS = function(){
// 樣式定義
this.CssClass = 'dp-css';
this.Style = '.dp-css .value{color:blue;}' +
'.dp-css .important{color:red;font-weight:bold;}'+
'.dp-css .keyword{color:#7F0055;font-weight:bold;}'+
'.dp-css .func{color:#F55;font-weight:normal;}';
};

dp.sh.Brushes.CSS.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.CSS.Aliases = ['css'];

dp.sh.Brushes.CSS.prototype.ProcessRegexList = function(){
function push(array, value){
array[array.length] = value;
}
var match1,match2,regex1,regex2;

/* 加入註解解析 */
this.GetMatches(dp.sh.RegexLib.MultiLineCComments, 'comments');
/* 加入 !important 解析 */
this.GetMatches(new RegExp('!important', 'g'),'important');

/* 解析屬性區塊 */
// 匹配 '{' 至 '}' 之間的文字
regex1 = new RegExp('\{[^}]+\}', 'gm');
// 匹配 'xxx:xxx[;\n\(!]' 格式的文字
regex2 = new RegExp('([:\\w-\.]+)\\s*:\\s*([^;\n\(!]+)[;\n\(!]', 'gm');
while((match1 = regex1.exec(this.code))){
while((match2 = regex2.exec(match1[0]))){
if(!match2[1]){continue;}
// 匹配屬性名稱
push(this.matches, new dp.sh.Match(
match2[1],
match1.index+match2.index,
'func'
));

// 匹配屬性值
if(match2[2]){
push(this.matches,new dp.sh.Match(
match2[2],
match1.index+match2.index+match2[0].indexOf(match2[2]),
'value'
));
}
}
}

/* 解析選擇器區塊 */
// 匹配 'xxx[,\{\n]' 格式的文字
regex1 = new RegExp('^([\\s\\w\.#*:+-]+)[,\{\n]', 'gm');
while((match1 = regex1.exec(this.code))){
if(!match1[1]){continue;}
push(this.matches, new dp.sh.Match(
match1[1],
match1.index,
'keyword'
));
}
};


效果可察看之前的文章:
IE6 對 visibility 負荷過大的問題[CSS]
IE6 中的最大最小寬度和高度
CSS fixed 定位( FF / IE6 )
利用 !important 修正 IE 與 Firefox 的差異

0 回應: